@remnic/core 9.3.719 → 9.3.721
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-boundary.d.ts +10 -7
- package/dist/access-boundary.js +37 -34
- package/dist/access-cli.js +71 -66
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +11 -8
- package/dist/access-http.js +44 -41
- package/dist/access-mcp.d.ts +11 -8
- package/dist/access-mcp.js +40 -37
- package/dist/access-operations-batch.js +38 -35
- package/dist/access-operations.d.ts +11 -8
- package/dist/access-operations.js +39 -36
- package/dist/access-schema.d.ts +19 -19
- package/dist/access-schema.js +3 -3
- package/dist/{access-service-CZbnt0t2.d.ts → access-service-Dj3I-VBS.d.ts} +3 -3
- package/dist/access-service.d.ts +11 -8
- package/dist/access-service.js +36 -33
- package/dist/access-surface-catalog.d.ts +10 -7
- package/dist/action-confidence.d.ts +1 -1
- package/dist/active-memory-bridge.d.ts +1 -1
- package/dist/active-recall.d.ts +1 -1
- package/dist/active-recall.js +4 -2
- 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-24NNS3GU.js → auto-sync-F3KCSQFJ.js} +5 -5
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +11 -8
- package/dist/briefing.d.ts +1 -1
- package/dist/briefing.js +12 -10
- package/dist/buffer-surprise-report.d.ts +1 -1
- package/dist/buffer.d.ts +1 -1
- package/dist/calibration.d.ts +1 -1
- package/dist/calibration.js +2 -2
- package/dist/capabilities.d.ts +30 -2
- package/dist/capabilities.js +3 -1
- package/dist/{catalog-CEYlMs9X.d.ts → catalog-F-OEVbRQ.d.ts} +1 -1
- package/dist/causal-behavior.d.ts +1 -1
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.d.ts +1 -1
- package/dist/causal-consolidation.js +15 -13
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.d.ts +4 -0
- package/dist/causal-trajectory-graph.js +2 -2
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-TH7WMHVK.js → chunk-3NN73CM7.js} +2 -2
- package/dist/{chunk-A5TUPZ3N.js → chunk-4SF232E6.js} +60 -30
- package/dist/chunk-4SF232E6.js.map +1 -0
- package/dist/{chunk-DGTDRIUO.js → chunk-4T3BMHKD.js} +2 -2
- package/dist/{chunk-EH27LHML.js → chunk-5O42UKXI.js} +2 -2
- package/dist/{chunk-KRGC4EDX.js → chunk-6FAMMBQ3.js} +2 -2
- package/dist/{chunk-FEB7W5JG.js → chunk-6OIDDKAA.js} +27 -6
- package/dist/chunk-6OIDDKAA.js.map +1 -0
- package/dist/{chunk-67HG7KFE.js → chunk-6YKIYQU7.js} +2 -2
- package/dist/{chunk-LXSG4L55.js → chunk-7CTNUVHZ.js} +2 -2
- package/dist/{chunk-UCJ5CDTK.js → chunk-A5XNBK2D.js} +22 -14
- package/dist/chunk-A5XNBK2D.js.map +1 -0
- package/dist/{chunk-7EEVXW7X.js → chunk-A7TJZLPK.js} +2 -2
- package/dist/{chunk-P5IPFZVH.js → chunk-B7WISIAJ.js} +5 -5
- package/dist/chunk-BCDKBDSY.js +173 -0
- package/dist/chunk-BCDKBDSY.js.map +1 -0
- package/dist/{chunk-JAKYZGV4.js → chunk-BXEOHV7K.js} +3 -3
- package/dist/chunk-C4X4QGIO.js +60 -0
- package/dist/chunk-C4X4QGIO.js.map +1 -0
- package/dist/{chunk-S3OPGGZB.js → chunk-D7EBTQ24.js} +2 -2
- package/dist/{chunk-IO5NQEGZ.js → chunk-DKT3X5C3.js} +2 -2
- package/dist/{chunk-PBH4JUAB.js → chunk-DVRHLN2O.js} +18 -3
- package/dist/chunk-DVRHLN2O.js.map +1 -0
- package/dist/{chunk-S35FX6MU.js → chunk-EBDA5TYA.js} +2 -2
- package/dist/{chunk-2PTBLS2S.js → chunk-EDOQM4E4.js} +2 -2
- package/dist/{chunk-YTZLBBEB.js → chunk-EEJMD2L2.js} +3 -3
- package/dist/{chunk-YGKUAX2B.js → chunk-EHQ5HO5T.js} +11 -11
- package/dist/chunk-EHQ5HO5T.js.map +1 -0
- package/dist/{chunk-JIZGYQYH.js → chunk-EM2LDXJ2.js} +4 -4
- package/dist/{chunk-YYOK4GVF.js → chunk-EVPNWN7Z.js} +10 -10
- package/dist/{chunk-HLIR3RJ7.js → chunk-EXUCUPV2.js} +2 -2
- package/dist/{chunk-F3PVXKHP.js → chunk-GDUOCHCD.js} +27 -21
- package/dist/chunk-GDUOCHCD.js.map +1 -0
- package/dist/{chunk-L5ASZA2F.js → chunk-GJSL4WG2.js} +17 -2
- package/dist/chunk-GJSL4WG2.js.map +1 -0
- package/dist/{chunk-2SXMCQEQ.js → chunk-GZQXOQQ2.js} +3 -3
- package/dist/{chunk-2KAYTPPT.js → chunk-HCVWF657.js} +12 -12
- package/dist/{chunk-N3DUH6OO.js → chunk-ILFSEIRT.js} +1 -1
- package/dist/chunk-ILFSEIRT.js.map +1 -0
- package/dist/{chunk-4KZGLDJJ.js → chunk-J3JPB7ZI.js} +2 -2
- package/dist/{chunk-3JJWNZTT.js → chunk-L2B3EE7B.js} +102 -42
- package/dist/chunk-L2B3EE7B.js.map +1 -0
- package/dist/{chunk-NFRBADNR.js → chunk-LA3HZKES.js} +610 -369
- package/dist/chunk-LA3HZKES.js.map +1 -0
- package/dist/{chunk-LQ6JI4VH.js → chunk-LD53WPMU.js} +4 -4
- package/dist/{chunk-URM3HW2R.js → chunk-LLUGAZ3B.js} +2 -2
- package/dist/{chunk-RVLB4E6N.js → chunk-MDBZTH7N.js} +5 -32
- package/dist/chunk-MDBZTH7N.js.map +1 -0
- package/dist/{chunk-U5H7WHTS.js → chunk-N77ELJ2D.js} +4 -4
- package/dist/{chunk-2VHMVWPU.js → chunk-NXRUUDUF.js} +2 -2
- package/dist/{chunk-DIFU33GU.js → chunk-OHTOPFRF.js} +2 -2
- package/dist/{chunk-74MYJSKB.js → chunk-ORAK3LNZ.js} +2 -2
- package/dist/{chunk-REWQAFSA.js → chunk-PD42EYQN.js} +2 -2
- package/dist/chunk-PHK3HARR.js +32 -0
- package/dist/chunk-PHK3HARR.js.map +1 -0
- package/dist/{chunk-773DPI6T.js → chunk-PKMQK2WY.js} +4 -4
- package/dist/{chunk-72VDBALG.js → chunk-QD6QP5P6.js} +63 -54
- package/dist/chunk-QD6QP5P6.js.map +1 -0
- package/dist/{chunk-CTOQEZSN.js → chunk-QR67FU5G.js} +2 -2
- package/dist/{chunk-AU7Q3LSC.js → chunk-RKNJBZ55.js} +7 -7
- package/dist/{chunk-YI7RZO7Y.js → chunk-SQNED75R.js} +1 -1
- package/dist/{chunk-5CEJH5ZN.js → chunk-TAPSNIMA.js} +4 -4
- package/dist/{chunk-IF362TF6.js → chunk-TQT3USCG.js} +2 -2
- package/dist/chunk-TQT3USCG.js.map +1 -0
- package/dist/{chunk-5RHM43BJ.js → chunk-TXQCG6SE.js} +3 -3
- package/dist/{chunk-ANI5DUAE.js → chunk-UIXXE6NI.js} +7 -7
- package/dist/{chunk-2COL35PK.js → chunk-UO5ZHIIH.js} +2 -2
- package/dist/{chunk-OJU73BUX.js → chunk-VCLGUIFM.js} +2 -2
- package/dist/{chunk-5J4OL7TJ.js → chunk-VUA4S7P6.js} +4 -4
- package/dist/{chunk-A66YRSOS.js → chunk-WQYSDPMA.js} +2 -2
- package/dist/chunk-XGTBNVIU.js +79 -0
- package/dist/chunk-XGTBNVIU.js.map +1 -0
- package/dist/{chunk-OZ2KQ7HF.js → chunk-YEE5KJQQ.js} +2 -2
- package/dist/chunk-YN2UN7N3.js +217 -0
- package/dist/chunk-YN2UN7N3.js.map +1 -0
- package/dist/{chunk-WRFKZEO6.js → chunk-YQGHW5ML.js} +4 -4
- package/dist/{chunk-APUJIMDM.js → chunk-Z4RU5VPM.js} +2 -2
- package/dist/{chunk-DCWIQFNA.js → chunk-ZUDM75KG.js} +4 -4
- package/dist/{cli-1orcdXOY.d.ts → cli-P_GaYcCY.d.ts} +3 -3
- package/dist/cli.d.ts +9 -6
- package/dist/cli.js +67 -63
- package/dist/compounding/engine.d.ts +1 -1
- package/dist/compounding/engine.js +12 -10
- package/dist/compounding/preference-consolidator.d.ts +1 -1
- package/dist/compression-optimizer.d.ts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/config.js +4 -2
- package/dist/connectors/codex-materialize-runner.d.ts +1 -1
- package/dist/connectors/codex-materialize-runner.js +12 -10
- package/dist/connectors/codex-materialize.d.ts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/connectors/index.js +13 -11
- package/dist/consolidation-provenance-check.d.ts +1 -1
- package/dist/consolidation-undo.d.ts +1 -1
- package/dist/contradiction/index.d.ts +1 -1
- package/dist/conversation-index/backend.d.ts +1 -1
- package/dist/conversation-index/backend.js +2 -2
- package/dist/conversation-index/chunker.d.ts +1 -1
- package/dist/conversation-index/faiss-adapter.d.ts +1 -1
- package/dist/conversation-index/indexer.d.ts +1 -1
- package/dist/conversation-index/search.d.ts +1 -1
- package/dist/day-summary.d.ts +1 -1
- package/dist/delinearize.d.ts +1 -1
- package/dist/direct-answer-wiring.d.ts +1 -1
- package/dist/direct-answer.d.ts +1 -1
- package/dist/embedding-fallback.d.ts +1 -1
- package/dist/enrichment/index.d.ts +1 -1
- package/dist/entity-retrieval.d.ts +1 -1
- package/dist/entity-retrieval.js +12 -10
- package/dist/entity-schema.d.ts +1 -1
- package/dist/explicit-capture.d.ts +11 -8
- package/dist/extraction-faithfulness.d.ts +8 -2
- package/dist/extraction-faithfulness.js +4 -3
- package/dist/extraction-judge-telemetry.d.ts +1 -1
- package/dist/extraction-judge-training.d.ts +1 -1
- package/dist/extraction-judge.d.ts +1 -1
- package/dist/extraction-judge.js +3 -3
- package/dist/extraction.d.ts +1 -1
- package/dist/extraction.js +5 -4
- package/dist/faithfulness-config.d.ts +55 -0
- package/dist/faithfulness-config.js +11 -0
- package/dist/faithfulness-config.js.map +1 -0
- package/dist/fallback-llm.d.ts +1 -1
- package/dist/fallback-llm.js +2 -2
- package/dist/{forget-U66KPDPY.js → forget-OEE5OELK.js} +2 -2
- package/dist/graph-dashboard-diff.d.ts +4 -0
- package/dist/graph-dashboard-key.d.ts +4 -0
- package/dist/graph-dashboard-parser.d.ts +4 -0
- package/dist/{graph-edge-decay-JLOF3YW4.js → graph-edge-decay-QPRJQ7DL.js} +3 -3
- package/dist/graph-edge-reinforcement.d.ts +4 -0
- package/dist/graph-snapshot.d.ts +7 -3
- package/dist/graph-snapshot.js +3 -3
- package/dist/graph.d.ts +7 -1
- package/dist/graph.js +2 -2
- package/dist/identity-continuity.d.ts +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/index.d.ts +571 -570
- package/dist/index.js +104 -99
- package/dist/index.js.map +1 -1
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/engine.js +2 -2
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/index.js +4 -4
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/local-model-endpoint.d.ts +96 -0
- package/dist/local-model-endpoint.js +12 -0
- package/dist/local-model-endpoint.js.map +1 -0
- package/dist/maintenance/memory-governance.d.ts +1 -1
- package/dist/maintenance/memory-governance.js +12 -10
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +12 -10
- package/dist/maintenance/rebuild-memory-projection.js +13 -11
- package/dist/mcp-memory-inspector-app.d.ts +11 -8
- package/dist/memory-action-policy.d.ts +1 -1
- package/dist/memory-cache.d.ts +1 -1
- package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-provenance.d.ts +1 -1
- package/dist/memory-worth-outcomes.d.ts +1 -1
- package/dist/models-json.d.ts +1 -1
- package/dist/namespaces/migrate.d.ts +2 -2
- package/dist/namespaces/migrate.js +22 -20
- package/dist/namespaces/principal.d.ts +1 -1
- package/dist/namespaces/search.d.ts +1 -1
- package/dist/namespaces/search.js +9 -9
- package/dist/namespaces/storage.d.ts +2 -2
- package/dist/namespaces/storage.js +12 -10
- package/dist/native-knowledge.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +3 -2
- package/dist/operator-toolkit.js +32 -28
- package/dist/orchestration/maintenance.d.ts +2 -2
- package/dist/orchestration/maintenance.js +14 -12
- package/dist/{orchestrator-kOxredSr.d.ts → orchestrator-f5xv19kp.d.ts} +178 -81
- package/dist/orchestrator.d.ts +8 -5
- package/dist/orchestrator.js +56 -52
- package/dist/patterns-cli.d.ts +1 -1
- package/dist/policy-runtime.d.ts +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/provenance.js +2 -1
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +1 -1
- package/dist/recall-disclosure-escalation.d.ts +1 -1
- package/dist/recall-explain-renderer.d.ts +1 -1
- package/dist/recall-explain-renderer.js +3 -3
- package/dist/recall-planner-llm.d.ts +1 -1
- package/dist/recall-planner-llm.js +2 -2
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-cli.js +4 -4
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray-renderer.js +3 -3
- package/dist/recall-xray.d.ts +18 -1
- package/dist/recall-xray.js +2 -2
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/resume-bundles.js +5 -3
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/search/embed-helper.d.ts +1 -1
- package/dist/search/factory.d.ts +1 -1
- package/dist/search/factory.js +8 -8
- package/dist/search/index.d.ts +1 -1
- package/dist/search/index.js +14 -14
- package/dist/search/lancedb-backend.d.ts +1 -1
- package/dist/search/lancedb-backend.js +2 -2
- package/dist/search/meilisearch-backend.d.ts +1 -1
- package/dist/search/meilisearch-backend.js +2 -2
- package/dist/search/noop-backend.d.ts +1 -1
- package/dist/search/orama-backend.d.ts +1 -1
- package/dist/search/orama-backend.js +2 -2
- package/dist/search/port.d.ts +1 -1
- package/dist/search/remote-backend.d.ts +1 -1
- package/dist/{semantic-consolidation-B58v3S-a.d.ts → semantic-consolidation-BQm1e1Pn.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +2 -2
- package/dist/semantic-consolidation.js +13 -11
- package/dist/semantic-rule-promotion.js +12 -10
- package/dist/semantic-rule-verifier.d.ts +1 -1
- package/dist/semantic-rule-verifier.js +12 -10
- package/dist/session-observer-bands.d.ts +1 -1
- package/dist/session-observer-state.d.ts +1 -1
- package/dist/shared-context/manager.d.ts +1 -1
- package/dist/signal.d.ts +1 -1
- package/dist/storage.d.ts +45 -1
- package/dist/storage.js +11 -9
- package/dist/summarizer.d.ts +1 -1
- package/dist/summarizer.js +3 -3
- package/dist/summary-snapshot.d.ts +1 -1
- package/dist/temporal-supersession.d.ts +1 -1
- package/dist/temporal-validity.d.ts +1 -1
- package/dist/threading.d.ts +1 -1
- package/dist/tier-migration.d.ts +1 -1
- package/dist/tier-routing.d.ts +1 -1
- package/dist/topics.d.ts +1 -1
- package/dist/transcript.d.ts +1 -1
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/capsule-import.js +1 -1
- package/dist/trust-score-stage.d.ts +178 -0
- package/dist/trust-score-stage.js +18 -0
- package/dist/trust-score-stage.js.map +1 -0
- package/dist/trust-score.d.ts +164 -0
- package/dist/trust-score.js +22 -0
- package/dist/trust-score.js.map +1 -0
- package/dist/{types-ACmDOScJ.d.ts → types-DwO1Ot4n.d.ts} +56 -2
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/dist/verified-recall.js +12 -10
- package/package.json +2 -2
- package/src/access-service.ts +8 -5
- package/src/capabilities-cluster-b.test.ts +78 -0
- package/src/capabilities.test.ts +11 -1
- package/src/capabilities.ts +58 -0
- package/src/cli/research-status-commands.ts +7 -3
- package/src/cli.ts +11 -6
- package/src/config.ts +60 -30
- package/src/extraction-faithfulness.test.ts +175 -0
- package/src/extraction-faithfulness.ts +53 -1
- package/src/faithfulness-config.test.ts +96 -0
- package/src/faithfulness-config.ts +138 -0
- package/src/graph-snapshot.ts +3 -3
- package/src/graph.ts +8 -7
- package/src/lifecycle/tombstones.test.ts +242 -1
- package/src/lifecycle/tombstones.ts +157 -70
- package/src/local-model-endpoint.test.ts +155 -0
- package/src/local-model-endpoint.ts +189 -0
- package/src/operator-toolkit.ts +24 -7
- package/src/orchestration/tier-migration-coordinator.ts +286 -0
- package/src/orchestrator.ts +331 -222
- package/src/recall-xray.test.ts +62 -0
- package/src/recall-xray.ts +34 -0
- package/src/trust-score-recall-paths.test.ts +157 -0
- package/src/trust-score-stage.test.ts +350 -0
- package/src/trust-score-stage.ts +398 -0
- package/src/trust-score.test.ts +282 -0
- package/src/trust-score.ts +449 -0
- package/src/types.ts +61 -1
- package/dist/chunk-3JJWNZTT.js.map +0 -1
- package/dist/chunk-72VDBALG.js.map +0 -1
- package/dist/chunk-A5TUPZ3N.js.map +0 -1
- package/dist/chunk-F3PVXKHP.js.map +0 -1
- package/dist/chunk-FEB7W5JG.js.map +0 -1
- package/dist/chunk-IF362TF6.js.map +0 -1
- package/dist/chunk-L5ASZA2F.js.map +0 -1
- package/dist/chunk-N3DUH6OO.js.map +0 -1
- package/dist/chunk-NFRBADNR.js.map +0 -1
- package/dist/chunk-PBH4JUAB.js.map +0 -1
- package/dist/chunk-RVLB4E6N.js.map +0 -1
- package/dist/chunk-UCJ5CDTK.js.map +0 -1
- package/dist/chunk-YGKUAX2B.js.map +0 -1
- /package/dist/{auto-sync-24NNS3GU.js.map → auto-sync-F3KCSQFJ.js.map} +0 -0
- /package/dist/{chunk-TH7WMHVK.js.map → chunk-3NN73CM7.js.map} +0 -0
- /package/dist/{chunk-DGTDRIUO.js.map → chunk-4T3BMHKD.js.map} +0 -0
- /package/dist/{chunk-EH27LHML.js.map → chunk-5O42UKXI.js.map} +0 -0
- /package/dist/{chunk-KRGC4EDX.js.map → chunk-6FAMMBQ3.js.map} +0 -0
- /package/dist/{chunk-67HG7KFE.js.map → chunk-6YKIYQU7.js.map} +0 -0
- /package/dist/{chunk-LXSG4L55.js.map → chunk-7CTNUVHZ.js.map} +0 -0
- /package/dist/{chunk-7EEVXW7X.js.map → chunk-A7TJZLPK.js.map} +0 -0
- /package/dist/{chunk-P5IPFZVH.js.map → chunk-B7WISIAJ.js.map} +0 -0
- /package/dist/{chunk-JAKYZGV4.js.map → chunk-BXEOHV7K.js.map} +0 -0
- /package/dist/{chunk-S3OPGGZB.js.map → chunk-D7EBTQ24.js.map} +0 -0
- /package/dist/{chunk-IO5NQEGZ.js.map → chunk-DKT3X5C3.js.map} +0 -0
- /package/dist/{chunk-S35FX6MU.js.map → chunk-EBDA5TYA.js.map} +0 -0
- /package/dist/{chunk-2PTBLS2S.js.map → chunk-EDOQM4E4.js.map} +0 -0
- /package/dist/{chunk-YTZLBBEB.js.map → chunk-EEJMD2L2.js.map} +0 -0
- /package/dist/{chunk-JIZGYQYH.js.map → chunk-EM2LDXJ2.js.map} +0 -0
- /package/dist/{chunk-YYOK4GVF.js.map → chunk-EVPNWN7Z.js.map} +0 -0
- /package/dist/{chunk-HLIR3RJ7.js.map → chunk-EXUCUPV2.js.map} +0 -0
- /package/dist/{chunk-2SXMCQEQ.js.map → chunk-GZQXOQQ2.js.map} +0 -0
- /package/dist/{chunk-2KAYTPPT.js.map → chunk-HCVWF657.js.map} +0 -0
- /package/dist/{chunk-4KZGLDJJ.js.map → chunk-J3JPB7ZI.js.map} +0 -0
- /package/dist/{chunk-LQ6JI4VH.js.map → chunk-LD53WPMU.js.map} +0 -0
- /package/dist/{chunk-URM3HW2R.js.map → chunk-LLUGAZ3B.js.map} +0 -0
- /package/dist/{chunk-U5H7WHTS.js.map → chunk-N77ELJ2D.js.map} +0 -0
- /package/dist/{chunk-2VHMVWPU.js.map → chunk-NXRUUDUF.js.map} +0 -0
- /package/dist/{chunk-DIFU33GU.js.map → chunk-OHTOPFRF.js.map} +0 -0
- /package/dist/{chunk-74MYJSKB.js.map → chunk-ORAK3LNZ.js.map} +0 -0
- /package/dist/{chunk-REWQAFSA.js.map → chunk-PD42EYQN.js.map} +0 -0
- /package/dist/{chunk-773DPI6T.js.map → chunk-PKMQK2WY.js.map} +0 -0
- /package/dist/{chunk-CTOQEZSN.js.map → chunk-QR67FU5G.js.map} +0 -0
- /package/dist/{chunk-AU7Q3LSC.js.map → chunk-RKNJBZ55.js.map} +0 -0
- /package/dist/{chunk-YI7RZO7Y.js.map → chunk-SQNED75R.js.map} +0 -0
- /package/dist/{chunk-5CEJH5ZN.js.map → chunk-TAPSNIMA.js.map} +0 -0
- /package/dist/{chunk-5RHM43BJ.js.map → chunk-TXQCG6SE.js.map} +0 -0
- /package/dist/{chunk-ANI5DUAE.js.map → chunk-UIXXE6NI.js.map} +0 -0
- /package/dist/{chunk-2COL35PK.js.map → chunk-UO5ZHIIH.js.map} +0 -0
- /package/dist/{chunk-OJU73BUX.js.map → chunk-VCLGUIFM.js.map} +0 -0
- /package/dist/{chunk-5J4OL7TJ.js.map → chunk-VUA4S7P6.js.map} +0 -0
- /package/dist/{chunk-A66YRSOS.js.map → chunk-WQYSDPMA.js.map} +0 -0
- /package/dist/{chunk-OZ2KQ7HF.js.map → chunk-YEE5KJQQ.js.map} +0 -0
- /package/dist/{chunk-WRFKZEO6.js.map → chunk-YQGHW5ML.js.map} +0 -0
- /package/dist/{chunk-APUJIMDM.js.map → chunk-Z4RU5VPM.js.map} +0 -0
- /package/dist/{chunk-DCWIQFNA.js.map → chunk-ZUDM75KG.js.map} +0 -0
- /package/dist/{forget-U66KPDPY.js.map → forget-OEE5OELK.js.map} +0 -0
- /package/dist/{graph-edge-decay-JLOF3YW4.js.map → graph-edge-decay-QPRJQ7DL.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/capabilities.ts"],"sourcesContent":["/**\n * CapabilitySet — recall-operation feature gates resolved once, then threaded.\n *\n * Issue #1523 (Phase 1 of epic #1520). Root cause this addresses: 161+\n * scattered `config.<flag>Enabled` reads mean each gate is re-derived at every\n * call site, and reviews keep finding parallel code paths where one branch\n * checks a gate the other forgot (CLAUDE.md rule 39 — the \"gate divergence\"\n * defect class). The fix is to resolve a frozen capability projection ONCE at\n * the top of the recall operation and pass it down explicitly.\n *\n * Scope of THIS module (first migration PR): only the recall-operation-scoped\n * flags below. Flags that are also read in graph construction, writes, CLI, or\n * the summarizer are deliberately deferred to a follow-up so we never leave a\n * single flag half-migrated (some sites on `caps.`, some on `config.`).\n *\n * Field naming: each field is the config flag name with the trailing `Enabled`\n * removed (`recallMmrEnabled` → `recallMmr`).\n *\n * This is plumbing, not a feature — there is deliberately NO `enabled` gate for\n * the CapabilitySet itself (rule 30 governs behavior changes; resolving and\n * threading a capability projection must stay behavior-preserving).\n */\n\nimport type { PluginConfig } from \"./types.js\";\n\n/**\n * Frozen projection of recall-operation feature gates.\n *\n * Every field is `readonly boolean`. The composition that maps a config flag to\n * a capability (including default-when-undefined semantics for optional flags)\n * lives ONLY in {@link resolveCapabilities} — call sites must read the\n * capability, never re-derive it from raw config.\n */\nexport interface CapabilitySet {\n /** `rerankCacheEnabled` — cache reranker scores across recall passes. */\n readonly rerankCache: boolean;\n /** `recallDirectAnswerEnabled` — observation-mode direct-answer tier. */\n readonly recallDirectAnswer: boolean;\n /** `recallMemoryWorthFilterEnabled` — Memory-Worth score reweighting. */\n readonly recallMemoryWorthFilter: boolean;\n /** `recallMmrEnabled` — maximal-marginal-relevance diversification. */\n readonly recallMmr: boolean;\n /** `recallReasoningTraceBoostEnabled` — boost reasoning-trace memories. */\n readonly recallReasoningTraceBoost: boolean;\n /** `recallPlannerLlmEnabled` — LLM-backed recall-mode planner. */\n readonly recallPlannerLlm: boolean;\n /** `recallPlannerEnabled` — recall-mode planner (heuristic + optional LLM). */\n readonly recallPlanner: boolean;\n /** `recallConfidenceGateEnabled` — Synapse-style confidence gate. */\n readonly recallConfidenceGate: boolean;\n /** `graphRecallEnabled` — graph-mode recall tier (gates planner graph mode). */\n readonly graphRecall: boolean;\n /** `graphAssistInFullModeEnabled` — graph-assist overlay in full mode. */\n readonly graphAssistInFullMode: boolean;\n /** `graphExpandedIntentEnabled` — promote broad-intent asks to graph mode. */\n readonly graphExpandedIntent: boolean;\n}\n\n/**\n * Resolve the recall-operation {@link CapabilitySet} from parsed config.\n *\n * Call this ONCE per recall operation (at the `recall()` / `recallInternal`\n * entry) and thread the result down. Composition lives here and only here.\n *\n * Session toggles are intentionally not a parameter yet: `session-toggles.ts`\n * is agent-scoped (per session/agent enable-disable of the whole plugin), not\n * flag-scoped — none of the flags projected here have a per-session override,\n * so there is nothing for a toggle argument to compose at this layer.\n */\nexport function resolveCapabilities(config: PluginConfig): CapabilitySet {\n return Object.freeze({\n rerankCache: config.rerankCacheEnabled,\n recallDirectAnswer: config.recallDirectAnswerEnabled,\n recallMemoryWorthFilter: config.recallMemoryWorthFilterEnabled,\n recallMmr: config.recallMmrEnabled,\n recallReasoningTraceBoost: config.recallReasoningTraceBoostEnabled,\n recallPlannerLlm: config.recallPlannerLlmEnabled,\n recallPlanner: config.recallPlannerEnabled,\n recallConfidenceGate: config.recallConfidenceGateEnabled,\n graphRecall: config.graphRecallEnabled,\n // Optional flags: preserve the exact default-when-undefined semantics the\n // migrated call sites used (`!== false` = default-on, `=== true` = default-off).\n graphAssistInFullMode: config.graphAssistInFullModeEnabled !== false,\n graphExpandedIntent: config.graphExpandedIntentEnabled === true,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Graph-construction capability set (issue #1566 Cluster A).\n//\n// The recall CapabilitySet above covers flags whose EVERY read site lives on\n// the recall call chain. The five flags below are read on graph-construction,\n// write/extraction, AND recall paths — so they cannot join the recall set\n// without leaving some sites on `caps.` and others on `config.` (the exact\n// divergence #1523 forbade). They get their own projection, resolved at graph\n// build/write entry (and alongside `caps` when recall reads them).\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of graph-construction feature gates.\n *\n * Every field is `readonly boolean`. Composition (including default-when-\n * undefined semantics for the optional `graphWriteSessionAdjacencyEnabled`)\n * lives ONLY in {@link resolveGraphConstructionCapabilities}.\n */\nexport interface GraphConstructionCapabilitySet {\n /** `entityGraphEnabled` — maintain entity co-reference graph edges. */\n readonly entityGraph: boolean;\n /** `timeGraphEnabled` — maintain thread-adjacency graph edges. */\n readonly timeGraph: boolean;\n /** `causalGraphEnabled` — maintain causal-language graph edges. */\n readonly causalGraph: boolean;\n /** `multiGraphMemoryEnabled` — master switch for multi-graph writes/traversal. */\n readonly multiGraphMemory: boolean;\n /** `graphWriteSessionAdjacencyEnabled` — session-adjacency fallback for time edges (default-on). */\n readonly graphWriteSessionAdjacency: boolean;\n}\n\n/**\n * Resolve the {@link GraphConstructionCapabilitySet} from parsed config.\n *\n * Call this ONCE at graph build/write entry (extraction, recall graph\n * expansion, graph-health/repair) and thread the result down — exactly the\n * pattern {@link resolveCapabilities} established for recall.\n */\nexport type GraphConstructionConfigProjection = Pick<\n PluginConfig,\n | \"entityGraphEnabled\"\n | \"timeGraphEnabled\"\n | \"causalGraphEnabled\"\n | \"multiGraphMemoryEnabled\"\n | \"graphWriteSessionAdjacencyEnabled\"\n>;\n\nexport function resolveGraphConstructionCapabilities(\n config: GraphConstructionConfigProjection,\n): GraphConstructionCapabilitySet {\n return Object.freeze({\n entityGraph: config.entityGraphEnabled,\n timeGraph: config.timeGraphEnabled,\n causalGraph: config.causalGraphEnabled,\n multiGraphMemory: config.multiGraphMemoryEnabled,\n // Optional flag: preserve the exact default-when-undefined semantics the\n // migrated call site used (`!== false` = default-on).\n graphWriteSessionAdjacency: config.graphWriteSessionAdjacencyEnabled !== false,\n });\n}\n"],"mappings":";AAqEO,SAAS,oBAAoB,QAAqC;AACvE,SAAO,OAAO,OAAO;AAAA,IACnB,aAAa,OAAO;AAAA,IACpB,oBAAoB,OAAO;AAAA,IAC3B,yBAAyB,OAAO;AAAA,IAChC,WAAW,OAAO;AAAA,IAClB,2BAA2B,OAAO;AAAA,IAClC,kBAAkB,OAAO;AAAA,IACzB,eAAe,OAAO;AAAA,IACtB,sBAAsB,OAAO;AAAA,IAC7B,aAAa,OAAO;AAAA;AAAA;AAAA,IAGpB,uBAAuB,OAAO,iCAAiC;AAAA,IAC/D,qBAAqB,OAAO,+BAA+B;AAAA,EAC7D,CAAC;AACH;AAiDO,SAAS,qCACd,QACgC;AAChC,SAAO,OAAO,OAAO;AAAA,IACnB,aAAa,OAAO;AAAA,IACpB,WAAW,OAAO;AAAA,IAClB,aAAa,OAAO;AAAA,IACpB,kBAAkB,OAAO;AAAA;AAAA;AAAA,IAGzB,4BAA4B,OAAO,sCAAsC;AAAA,EAC3E,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provenance.ts","../src/connectors/coerce.ts"],"sourcesContent":["/**\n * Claim-level provenance spans (issue #1575 PR 1).\n *\n * Centralizes the parse/serialize logic for the `sources` array and the\n * coarse `provenance` strength tag, plus the `provenance` config-block\n * parser. Extracted from `storage.ts` and `config.ts` so those files keep\n * only thin delegation call-sites — the frontmatter round-trip and config\n * parsing growth lives here (issue #1520 ratchet discipline).\n *\n * Contract:\n * - When no provenance fields are present, output is byte-identical to\n * pre-feature behavior (rule 39).\n * - Corrupt `sources` lines / unknown `provenance` tags drop to\n * `undefined` on read so a malformed frontmatter never poisons\n * downstream readers (rule 34 spirit — drop corrupt rather than poison).\n * - Validation lives on the write path; this module only parses.\n * - Invariant (review round 5, cursor thread KQN): a `verified` or\n * `unverified` tag is NEVER persisted/read without surviving sources —\n * without excerpts the tag is indistinguishable from a grounded fact to\n * downstream faithfulness/correction/TrustScore surfaces. The invariant\n * is enforced symmetrically: `serializeProvenanceFields` (write) and\n * `reconcileProvenanceRead` (read) both downgrade the tag to `none`\n * when no source survives.\n */\n\nimport { z } from \"zod\";\n\nimport { coerceBool, coerceNumber } from \"./connectors/coerce.js\";\nimport { readEnvVar } from \"./runtime/env.js\";\nimport { collapseWhitespace } from \"./whitespace.js\";\nimport type { MemoryFrontmatter, ProvenanceConfig, ProvenanceSource } from \"./types.js\";\nimport { isSafeMemoryContent } from \"./sanitize.js\";\n\n/**\n * Canonical key order for a serialized `ProvenanceSource` (issue #1575).\n * Deterministic emission (rule 38) — readers and the byte-identical-when-off\n * contract (rule 39) depend on this order never drifting.\n */\nconst PROVENANCE_SOURCE_KEY_ORDER = [\n \"sessionKey\",\n \"turnId\",\n \"observedAt\",\n \"quote\",\n \"charStart\",\n \"charEnd\",\n] as const;\n\n/**\n * Build a single `ProvenanceSource` object whose keys appear in the canonical\n * order, omitting absent optional fields. The result is what gets fed to\n * `JSON.stringify` so the on-disk line is deterministic.\n */\nfunction canonicalProvenanceSource(src: ProvenanceSource): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of PROVENANCE_SOURCE_KEY_ORDER) {\n const value = src[key];\n if (value !== undefined) out[key] = value;\n }\n return out;\n}\n\n/**\n * Serialize the `sources` array (issue #1575) as a single JSON line, matching\n * the `structuredAttributes` precedent. Each entry is rebuilt in canonical key\n * order (rule 38) so the output is byte-stable. The `provenance` enum is\n * emitted bare (same style as `status`) — only the three documented values\n * are ever written.\n *\n * Verified-requires-evidence invariant (review round 5, cursor thread KQN):\n * a `verified`/`unverified` tag is downgraded to `none` whenever no source\n * survives write validation — whether sources were absent, an empty array,\n * or all entries failed the schema. This covers all three failure shapes the\n * earlier 3-branch logic left open (`{provenance:\"verified\"}`,\n * `{sources:[],provenance:\"verified\"}`, `{sources:[invalid…],provenance:\"verified\"}`).\n */\nexport function serializeProvenanceFields(fm: MemoryFrontmatter, lines: string[]): void {\n let hasValidSources = false;\n if (fm.sources && fm.sources.length > 0) {\n // Validate each entry against the same schema used on read so invalid\n // in-memory sources are dropped at write time, not silently lost on the\n // next read (review thread 4 — write-path validation parity).\n const canonical: Record<string, unknown>[] = [];\n for (const src of fm.sources) {\n const result = ProvenanceSourceSchema.safeParse(src);\n if (result.success) canonical.push(canonicalProvenanceSource(result.data));\n }\n if (canonical.length > 0) {\n lines.push(`sources: ${JSON.stringify(canonical)}`);\n hasValidSources = true;\n }\n }\n // A verified/unverified tag requires surviving evidence; without it the\n // tag is meaningless downstream (faithfulness/TrustScore cannot distinguish\n // it from a grounded fact). Downgrade to \"none\" regardless of WHY no source\n // survived (absent / empty / all-invalid) — single invariant, all cases.\n const tag =\n (fm.provenance === \"verified\" || fm.provenance === \"unverified\") && !hasValidSources\n ? \"none\"\n : fm.provenance;\n if (tag) {\n lines.push(`provenance: ${tag}`);\n }\n}\n\n/**\n * Parse the coarse `provenance` strength tag (issue #1575). Returns\n * `undefined` for missing/blank/unknown values so a corrupt or hand-edited\n * field fails safely to the legacy-equivalent `\"none\"` semantics on read\n * (rule 34 spirit — drop corrupt rather than poison).\n */\nexport function parseProvenanceTag(\n raw: string | undefined,\n): \"verified\" | \"unverified\" | \"none\" | undefined {\n if (raw === undefined) return undefined;\n const trimmed = raw.trim();\n if (trimmed.length === 0) return undefined;\n if (trimmed === \"verified\" || trimmed === \"unverified\" || trimmed === \"none\") {\n return trimmed;\n }\n return undefined;\n}\n\n/**\n * Enforce the verified-requires-evidence invariant on the READ path.\n * `parseProvenanceTag` and `parseProvenanceSources` are independent (they\n * parse separate frontmatter lines), so a hand-edited or imported memory may\n * carry `provenance: verified` with no surviving `sources` — a corrupt line,\n * an empty array, or all-invalid entries. Downgrade such a tag to `none` so\n * the in-memory object never exposes an ungrounded \"verified\" fact\n * (review round 5, cursor thread KQN — read-path parity with the write-path\n * downgrade in `serializeProvenanceFields`). `none`/`undefined` tags pass\n * through unchanged.\n */\nexport function reconcileProvenanceRead(\n tag: \"verified\" | \"unverified\" | \"none\" | undefined,\n sources: ProvenanceSource[] | undefined,\n): \"verified\" | \"unverified\" | \"none\" | undefined {\n if ((tag === \"verified\" || tag === \"unverified\") && (!sources || sources.length === 0)) {\n return \"none\";\n }\n return tag;\n}\n\n/**\n * Strict ISO-8601 timestamp check (review round 6, codex thread OXPAp).\n * `Date.parse` accepts non-ISO strings (bare years like `\"123\"`) and\n * silently normalizes calendar overflow (`2026-02-30` -> March 2, hour 25\n * -> next day), so malformed provenance survives as if valid. Require the\n * full `YYYY-MM-DDTHH:MM:SS[.fff](Z|±HH:MM)` shape and reject overflow via a\n * `Date.UTC` round-trip component check — the offset does not affect whether\n * a wall-clock field overflows, so this is correct for any timezone suffix.\n */\nfunction isStrictIsoTimestamp(s: string): boolean {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(s);\n if (!m) return false;\n const y = Number(m[1]), mo = Number(m[2]), da = Number(m[3]);\n const h = Number(m[4]), mi = Number(m[5]), se = Number(m[6]);\n // Date.UTC normalizes overflow (Feb 30 -> Mar 2); a component round-trip\n // catches what Date.parse silently accepts.\n const d = new Date(Date.UTC(y, mo - 1, da, h, mi, se));\n // The component round-trip validates wall-clock overflow (Feb 30 -> Mar 2);\n // Date.parse additionally rejects impossible timezone offsets such as\n // +99:99, which the regex accepts but the runtime treats as NaN\n // (codex thread OXQ0e).\n return (\n !Number.isNaN(Date.parse(s)) &&\n d.getUTCFullYear() === y &&\n d.getUTCMonth() === mo - 1 &&\n d.getUTCDate() === da &&\n d.getUTCHours() === h &&\n d.getUTCMinutes() === mi &&\n d.getUTCSeconds() === se\n );\n}\n\n/**\n * Coerce a turn timestamp to a strict ISO-8601 string (cursor thread Ocveu —\n * \"Non-ISO turn timestamps drop sources\"). The write-path `ProvenanceSourceSchema`\n * rejects anything `isStrictIsoTimestamp` fails, so a turn whose `timestamp`\n * parses via `new Date(...)` but isn't already strict ISO (e.g.\n * `\"2026/01/15 12:00:00\"` or `\"Jan 15 2026\"`) would be silently dropped at\n * serialization — clearing the whole `sources` array and downgrading the tag\n * to `\"none\"`. Normalizing at extraction time preserves the source.\n *\n * Returns the strict ISO string when the timestamp already passes or\n * `Date.parse` can round-trip it; `undefined` for empty / unparseable input\n * so callers can decide whether to skip the source or fall back.\n */\nfunction toStrictIsoTimestamp(ts: string | undefined | null): string | undefined {\n if (typeof ts !== \"string\" || ts.length === 0) return undefined;\n if (isStrictIsoTimestamp(ts)) return ts;\n const parsed = Date.parse(ts);\n if (Number.isNaN(parsed)) return undefined;\n // Reject bare-year / numeric-only strings that Date.parse accepts (e.g.\n // \"123\") — isStrictIsoTimestamp already rejected them, and the round-trip\n // below would otherwise resurrect them. Require at least one date/time\n // separator so a plain number never round-trips into a fake epoch.\n if (!/[-:T]/.test(ts)) return undefined;\n // Reject calendar-overflow dates (chatgpt-codex-connector thread dANc):\n // Date.parse silently rolls over invalid components — \"2026-02-30\" becomes\n // 2026-03-02 — fabricating the observation date. For strings that carry an\n // explicit numeric Y/M/D prefix (the common import/provider shape), validate\n // the calendar components are in range before accepting the shifted result.\n // isStrictIsoTimestamp already does this for full ISO strings; this closes\n // the gap for the non-ISO normalization path.\n const ymd = /^(\\d{4})\\D(\\d{1,2})\\D(\\d{1,2})/.exec(ts);\n if (ymd) {\n const [_, ys, ms, ds] = ymd;\n const y = Number(ys), mo = Number(ms), da = Number(ds);\n if (!isValidCalendarDate(y, mo, da)) return undefined;\n }\n // Also validate M/D/Y or D/M/Y formats (provider/import common shapes:\n // 02/30/2026, 30-02-2026, etc.). Date.parse silently shifts overflow in\n // these too. Try both month-first and day-first interpretations; if\n // neither is a valid calendar date, reject (chatgpt-codex-connector thread\n // dH47 — non-YMD overflow timestamps).\n const mdy = /^(\\d{1,2})\\D(\\d{1,2})\\D(\\d{4})/.exec(ts);\n if (mdy) {\n const a = Number(mdy[1]), b = Number(mdy[2]), yr = Number(mdy[3]);\n if (!isValidCalendarDate(yr, a, b) && !isValidCalendarDate(yr, b, a)) {\n return undefined;\n }\n }\n const iso = new Date(parsed).toISOString();\n return isStrictIsoTimestamp(iso) ? iso : undefined;\n}\n\n/**\n * Validate numeric calendar components without Date overflow (review thread\n * dANc). Date.UTC silently normalizes Feb 30 -> Mar 2; a component round-trip\n * catches what Date.parse accepts. Mirrors the same technique isStrictIsoTimestamp\n * uses for full ISO strings, applied here to the non-ISO normalization path.\n */\nfunction isValidCalendarDate(y: number, mo: number, da: number): boolean {\n if (mo < 1 || mo > 12 || da < 1) return false;\n const leap = (y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0)) ? 29 : 28;\n const daysInMonth = [31, leap, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n return da <= daysInMonth[mo - 1]!;\n}\n\n/**\n * Zod schema for a single `ProvenanceSource` entry (issue #1575). Parsed\n * JSON from frontmatter is external data, so each entry is validated here\n * rather than trusted via a cast (rule: no inline-cast-access on parsed\n * blobs). `safeParse` lets us drop corrupt entries individually instead of\n * failing the whole field.\n */\nconst ProvenanceSourceSchema = z\n .object({\n sessionKey: z.string().min(1),\n observedAt: z\n .string()\n .min(1)\n .refine(isStrictIsoTimestamp, \"must be a valid ISO 8601 timestamp (YYYY-MM-DDTHH:MM:SS[Z|±HH:MM], no calendar overflow)\"),\n quote: z.string().min(1),\n turnId: z.string().min(1).optional(),\n charStart: z.number().finite().nonnegative().int().optional(),\n charEnd: z.number().finite().nonnegative().int().optional(),\n })\n .refine(\n (src) => src.charStart === undefined || src.charEnd === undefined || src.charEnd >= src.charStart,\n { message: \"charEnd must be >= charStart (half-open interval, rule 35)\" },\n );\n\n/**\n * Parse the `sources` array (issue #1575) from its single-line JSON form.\n * Mirrors `parseStructuredAttributes` (JSON.parse) but validates each entry\n * against `ProvenanceSourceSchema` and DROPS corrupt ones rather than\n * poisoning downstream readers — the same \"drop corrupt rather than poison\"\n * contract as `parseMemoryWorthCounterField`. If no entry survives, the\n * whole field is `undefined` (legacy-equivalent).\n */\nexport function parseProvenanceSources(raw: string | undefined): ProvenanceSource[] | undefined {\n if (raw === undefined) return undefined;\n const trimmed = raw.trim();\n if (trimmed.length === 0) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return undefined;\n }\n if (!Array.isArray(parsed)) return undefined;\n const sources: ProvenanceSource[] = [];\n for (const entry of parsed) {\n const result = ProvenanceSourceSchema.safeParse(entry);\n if (result.success) sources.push(result.data);\n }\n return sources.length > 0 ? sources : undefined;\n}\n\n/**\n * Parse the `provenance` config block (issue #1575 PR 1). Validates the\n * shape before applying defaults — a shorthand like `provenance: false` must\n * reject loudly rather than normalize to `{}` and silently enable the feature\n * (rule 51). Booleans coerce via `coerceBool` (rule 36); numeric cap clamps\n * at 1 (rule 28). `REMNIC_PROVENANCE_ENABLED` / `ENGRAM_PROVENANCE_ENABLED`\n * are honored only when the `enabled` key is omitted (explicit config wins).\n *\n * Schema-default note (review rounds 1–3, settled): `provenance.enabled` has\n * NO `\"default\"` in any plugin.json schema. OpenClaw's loader runs\n * `applyDefaults: true` before exposing `api.pluginConfig` (src/index.ts:1345,\n * PR #1593 round 8), so a schema default would be materialized into the\n * merged config and mask the `REMNIC_`/`ENGRAM_` env override. The code-level\n * default-on here (`return true` when `enabled` is omitted) supplies the\n * default-on behavior without that materialization. This matches the\n * emitLegacyTools/namespaceCatalogEnabled precedent, which omits the env\n * override only after a raw-vs-effective split — overkill for a single\n * boolean, so this field uses the simpler omit-the-default approach.\n */\nexport function parseProvenanceConfig(raw: unknown): ProvenanceConfig {\n if (\n raw !== undefined &&\n (raw === null || typeof raw !== \"object\" || Array.isArray(raw))\n ) {\n throw new Error(\n `provenance must be an object (got ${JSON.stringify(raw)}). Use provenance: { enabled: false } to opt out; omit the key to use the default-on behavior (issue #1575).`,\n );\n }\n const rawProvenance =\n raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n return {\n enabled: (() => {\n if (rawProvenance.enabled === undefined) {\n const envEnabled =\n readEnvVar(\"REMNIC_PROVENANCE_ENABLED\") ?? readEnvVar(\"ENGRAM_PROVENANCE_ENABLED\");\n if (envEnabled !== undefined) {\n const coerced = coerceBool(envEnabled);\n if (coerced === undefined) {\n throw new Error(\n `REMNIC_PROVENANCE_ENABLED must be a boolean-like value (true/false/1/0/yes/no/on/off); got ${JSON.stringify(envEnabled)}`,\n );\n }\n return coerced;\n }\n return true;\n }\n const coerced = coerceBool(rawProvenance.enabled);\n if (coerced === undefined) {\n throw new Error(\n `provenance.enabled must be a boolean or one of \"true\"/\"false\"/\"1\"/\"0\"/\"yes\"/\"no\"/\"on\"/\"off\" (got ${JSON.stringify(rawProvenance.enabled)}). Omit the key to use the default-on behavior (issue #1575).`,\n );\n }\n return coerced;\n })(),\n maxQuoteChars: (() => {\n if (rawProvenance.maxQuoteChars === undefined) return 300;\n const rawCap = coerceNumber(rawProvenance.maxQuoteChars);\n // Reject present-but-invalid rather than silently widening the cap\n // (AGENTS.md input-validation rule — a typo should not persist more\n // text than the operator configured).\n if (rawCap === undefined || !Number.isFinite(rawCap) || rawCap < 1 || !Number.isInteger(rawCap)) {\n throw new Error(\n `provenance.maxQuoteChars must be a positive integer >= 1 (got ${JSON.stringify(rawProvenance.maxQuoteChars)}).`,\n );\n }\n return rawCap;\n })(),\n requireSpans: (() => {\n if (rawProvenance.requireSpans === undefined) return false;\n const coerced = coerceBool(rawProvenance.requireSpans);\n if (coerced === undefined) {\n throw new Error(\n `provenance.requireSpans must be a boolean or one of \"true\"/\"false\"/\"1\"/\"0\"/\"yes\"/\"no\"/\"on\"/\"off\" (got ${JSON.stringify(rawProvenance.requireSpans)}).`,\n );\n }\n return coerced;\n })(),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Issue #1575 PR 2 — extraction-side post-parse validator.\n// ---------------------------------------------------------------------------\n//\n// This runs once at write time (inside `ExtractionEngine.extract`, after the\n// LLM output is parsed and sanitized, before the result is returned for\n// persistence). Its job: locate each fact's LLM-provided `quote` in the\n// buffered turn texts and build a `ProvenanceSource[]` with verified\n// offsets. Never throws, never drops a fact (rule 34 spirit — an\n// unverifiable span is a tagged state, not a silent failure).\n//\n// Reuses `collapseWhitespace` from `whitespace.ts` for normalization so there\n// is exactly one normalizer in the codebase (issue #1575 pitfall: \"do not\n// write a second normalizer\").\n// ---------------------------------------------------------------------------\n\n/**\n * A turn in the buffered conversation, reduced to the fields the provenance\n * validator needs. `ExtractionEngine.extract` maps its `BufferTurn[]` to this\n * shape so the validator is pure and testable without the full BufferTurn type.\n */\nexport interface ProvenanceTurnInput {\n content: string;\n sessionKey?: string;\n logicalSessionKey?: string;\n timestamp: string;\n turnId?: string;\n}\n\n/**\n * Result of building provenance for a single extracted fact.\n */\nexport interface ProvenanceBuildResult {\n /** Verified sources (one per matching turn). Absent when no quote survives. */\n sources?: ProvenanceSource[];\n /** Coarse strength tag persisted to frontmatter. */\n provenance: \"verified\" | \"unverified\" | \"none\";\n /**\n * Transient signal (never persisted): `true` when `config.requireSpans`\n * is enabled and the LLM-provided quote could not be located in ANY source\n * turn (the strict case `ProvenanceConfig.requireSpans` documents: \"facts\n * whose quote cannot be located are routed to `pending_review`\"). The\n * extraction consumer carries this onto the in-memory `ExtractedFact` so\n * the persist path can route the fact to the review queue. A quote that\n * WAS located but whose source was dropped (e.g. un-coercible timestamp)\n * does NOT set this flag — the span was found, so requireSpans is\n * satisfied (chatgpt-codex-connector thread 4xB).\n */\n requireSpansPending?: boolean;\n}\n\n/**\n * Cap a quote string at `maxChars`, truncating at the last word boundary that\n * fits and appending an ellipsis marker. Quotes at or under the cap pass\n * through unchanged. Operates on Unicode code points (not UTF-16 units) so\n * emoji and astral-plane characters are not split mid-glyph.\n */\nfunction capQuote(quote: string, maxChars: number): string {\n const glyphs = Array.from(quote);\n if (glyphs.length <= maxChars) return quote;\n // Walk backward from the cap to find a word boundary (space). If the entire\n // span is one long token (no spaces), cut at the cap — a hard cut is better\n // than no quote at all.\n let cut = maxChars;\n while (cut > 0 && !/\\s/.test(glyphs[cut - 1]!)) cut--;\n if (cut === 0) cut = maxChars; // no word boundary found\n return glyphs.slice(0, cut).join(\"\").trimEnd() + \"\\u2026\";\n}\n\n/**\n * Casefold a string for normalized matching. Uses `toLowerCase` (not\n * `toLocaleLowerCase`) for determinism across runtime locales — the existing\n * `normalizeFactKey` helper in extraction.ts follows the same convention.\n */\nfunction casefold(s: string): string {\n return s.toLowerCase();\n}\n\n/**\n * Locate `quote` within `text`, returning whether a match was found and, when\n * recoverable, the half-open `[start, end)` offsets. Tries exact substring\n * first, then whitespace/case-normalized match.\n *\n * For the normalized path, the mapping from the normalized string back to\n * original offsets is recovered by walking both strings in lockstep: we know\n * `collapseWhitespace(text)` is a subsequence of `text` with whitespace runs\n * collapsed, so we can track the original offset as we scan.\n *\n * Returns `{ matched: false }` when neither match succeeds. Returns\n * `{ matched: true, offsets }` when offsets are recoverable. Returns\n * `{ matched: true }` (offsets omitted) when the normalized substring was\n * found but original offsets could not be recovered — callers still treat\n * this as a verified match and record a source without offsets (cursor\n * thread Ocver — \"Normalized match drops verified provenance\").\n */\ntype LocateQuoteResult =\n | { matched: false }\n | { matched: true; offsets?: { charStart: number; charEnd: number } };\n\nfunction locateQuoteOffsets(quote: string, text: string): LocateQuoteResult {\n // 1. Exact substring match (handles unicode, curly quotes, emoji verbatim).\n const exactIdx = text.indexOf(quote);\n if (exactIdx >= 0) {\n return { matched: true, offsets: { charStart: exactIdx, charEnd: exactIdx + quote.length } };\n }\n\n // 2. Whitespace/case-normalized match. Collapse runs of whitespace and\n // casefold both sides, then find the normalized quote in the normalized\n // text. Recover original offsets by scanning forward from the normalized\n // match start through the original text, accumulating non-whitespace\n // glyphs until we've consumed the normalized quote length.\n const normQuote = collapseWhitespace(casefold(quote));\n if (normQuote.length === 0) return { matched: false };\n const normText = collapseWhitespace(casefold(text));\n const normIdx = normText.indexOf(normQuote);\n if (normIdx < 0) return { matched: false };\n\n // Recover original offsets: walk the original text, skipping leading\n // whitespace to align with the collapsed form, then track how many\n // normalized chars we've consumed.\n const normQuoteLen = normQuote.length;\n let origIdx = 0;\n // Skip leading whitespace in original text (collapseWhitespace trims both ends).\n while (origIdx < text.length && /\\s/.test(text[origIdx]!)) origIdx++;\n // Walk through original text, counting normalized chars consumed.\n // Each non-whitespace char in original = 1 normalized char.\n // Whitespace runs in original = 1 space in normalized (but only between non-ws).\n let normPos = 0;\n let origStart = -1;\n let origEnd = -1;\n let prevWasWs = true; // suppress the leading space in collapsed form\n while (origIdx < text.length && origEnd < 0) {\n const ch = text[origIdx]!;\n if (/\\s/.test(ch)) {\n if (!prevWasWs) {\n // This whitespace run collapses to a single space in normalized text.\n if (normPos === normIdx) origStart = origIdx; // normalized space aligns\n normPos++;\n prevWasWs = true;\n }\n origIdx++;\n continue;\n }\n // Non-whitespace char.\n if (normPos === normIdx && origStart < 0) {\n origStart = origIdx;\n }\n normPos++;\n prevWasWs = false;\n origIdx++;\n if (normPos >= normIdx + normQuoteLen) {\n origEnd = origIdx;\n }\n }\n if (origStart >= 0 && origEnd >= 0) {\n return { matched: true, offsets: { charStart: origStart, charEnd: origEnd } };\n }\n // Normalized substring was found, but original offsets are not recoverable\n // (edge case in the normalized mapping). The match still counts as verified\n // — record a source without offsets rather than dropping the turn entirely\n // (cursor thread Ocver). charStart/charEnd are best-effort debugging aids,\n // not a precondition for a verified source.\n return { matched: true };\n}\n\n/**\n * Build provenance sources for a single extracted fact by locating its\n * LLM-provided `quote` in the buffered turns (issue #1575 PR 2).\n *\n * Matching strategy (per issue design):\n * 1. Exact substring match in a turn → `provenance: \"verified\"` with\n * `charStart`/`charEnd` offsets.\n * 2. Whitespace/case-normalized match → `\"verified\"`, offsets recovered\n * when possible, else omitted.\n * 3. No match in any turn → `\"unverified\"` — the quote survives as a\n * source (the LLM vouched for it) but without located offsets.\n * 4. No quote provided by the LLM → `\"none\"` — no evidence to record.\n *\n * A quote appearing in multiple turns produces multiple sources (one per\n * matching turn) so a repeated utterance backs the fact from each occurrence.\n *\n * The quote is capped at `config.maxQuoteChars` (truncated at a word boundary\n * with an ellipsis marker) BEFORE storage. Locating uses the original\n * (untruncated) quote for maximum match fidelity; the capped excerpt is what\n * gets persisted.\n *\n * When `config.enabled === false`, returns `{ provenance: \"none\" }`\n * immediately — byte-identical to pre-feature extraction (rule 39).\n *\n * Never throws. An unexpected error degrades to `{ provenance: \"none\" }` so\n * extraction never crashes on a provenance hiccup (rule 13/18).\n */\n/**\n * Strip a leading extraction-prompt role label from a quote (cursor thread Oc3Z2\n * — \"Quote prompt mismatches validator\"). The extraction prompt renders each\n * buffered turn as `[role] content` (or `[context role] content`), so a\n * faithful LLM may include that prefix in its verbatim quote. buildFactProvenance\n * searches the raw `turn.content` (no prefix), so a quote carrying the label\n * would never match. Stripping the leading label lets the actual utterance\n * verify against the turn text. Only a SINGLE leading label is stripped — a\n * multi-turn quote (with embedded labels) is left untouched and will simply\n * fail to match a single turn, as before.\n *\n * The regex is constrained to the labels the prompt actually emits — `user`,\n * `assistant`, optionally prefixed with `context ` (extraction.ts renders\n * `[user]`, `[assistant]`, `[context user]`, `[context assistant]`). A\n * real utterance that happens to start with other bracketed text (e.g.\n * `[do not] deploy before approval`, `[P1] fix the cache`) is preserved\n * verbatim so the quote can match the turn and the persisted span retains its\n * original meaning (chatgpt-codex-connector thread 4xA — limiting role-prefix\n * stripping to actual prompt labels).\n */\nfunction stripLeadingRolePrefix(quote: string): string {\n return quote.replace(/^\\s*\\[(?:context\\s+)?(?:user|assistant)\\]\\s+/i, \"\");\n}\n\nexport function buildFactProvenance(\n factQuote: string | null | undefined,\n turns: ReadonlyArray<ProvenanceTurnInput>,\n config: ProvenanceConfig,\n): ProvenanceBuildResult {\n if (!config.enabled) return { provenance: \"none\" };\n const rawQuote = typeof factQuote === \"string\" ? factQuote.trim() : \"\";\n // requireSpans (chatgpt-codex-connector thread dEsu + cursor thread dGKJ):\n // every early exit that drops a fact's span (no quote, empty after label\n // strip, or unsafe quote) must flag requireSpansPending when the operator\n // opted into requireSpans, so the persist path routes the fact to\n // pending_review instead of active. Only the disabled-feature exit (above)\n // and the unexpected-error catch (below) omit the flag — those are\n // policy-neutral degradations, not a missing-span decision.\n const noneResult = (): ProvenanceBuildResult =>\n config.requireSpans === true\n ? { provenance: \"none\", requireSpansPending: true }\n : { provenance: \"none\" };\n if (rawQuote.length === 0) return noneResult();\n // Strip a leading prompt role label so a faithful quote verifies against\n // the raw turn content (cursor thread Oc3Z2). Prefer the RAW quote when it\n // matches at least one turn — an utterance that literally begins with\n // [user]/[assistant] must verify as-is, not be truncated to the post-label\n // text (cursor/codex thread dEsw). The strip handles the common case where\n // the LLM includes the prompt label; this preserves the rare case where the\n // utterance itself starts with that text.\n const strippedQuote = stripLeadingRolePrefix(rawQuote);\n const useRawQuote =\n rawQuote === strippedQuote ||\n turns.some(\n (t) =>\n typeof t?.content === \"string\" &&\n t.content.length > 0 &&\n locateQuoteOffsets(rawQuote, t.content).matched,\n );\n const quote = useRawQuote ? rawQuote : strippedQuote;\n if (quote.length === 0) return noneResult();\n // Sanitize the quote before persisting it as a provenance span\n // (chatgpt-codex-connector thread dANZ): the fact body is sanitized via\n // sanitizeMemoryContent, but sources[].quote was persisted verbatim,\n // reintroducing unsafe memory text (e.g. \"ignore previous instructions\")\n // through the provenance field exposed to memory_get/x-ray/faithfulness.\n // An unsafe quote cannot serve as evidence — drop the source entirely\n // (consistent with how the body is sanitized: unsafe text is redacted,\n // and a redacted quote is useless as a verbatim span).\n if (!isSafeMemoryContent(quote)) return noneResult();\n\n try {\n // Search every turn for the quote. Collect verified sources.\n const sources: ProvenanceSource[] = [];\n // Track the first turn where the quote was located even when its\n // timestamp can't be coerced (cursor thread 4Pj — \"Bad timestamp drops\n // matched source\"). Without this, a located-but-unverifiable quote falls\n // through to the unverified branch and is attributed to the *last* turn's\n // session, mislabeling the source's origin session. Also drives the\n // requireSpans signal: only a quote that was NOT located in any turn\n // qualifies for pending_review routing under requireSpans (thread 4xB).\n let locatedTurn: ProvenanceTurnInput | undefined;\n for (const turn of turns) {\n if (!turn || typeof turn.content !== \"string\" || turn.content.length === 0) continue;\n const located = locateQuoteOffsets(quote, turn.content);\n // cursor thread Ocver: a normalized match counts as verified even when\n // original offsets are unrecoverable — record the source without\n // charStart/charEnd instead of skipping the turn.\n if (!located.matched) continue;\n if (!locatedTurn) locatedTurn = turn;\n // cursor thread Ocveu: normalize the turn timestamp to strict ISO so\n // the write-path ProvenanceSourceSchema keeps the source. Skip the turn\n // when the timestamp can't be coerced — pushing it would guarantee a\n // serialization drop (and the tag downgrade) for this source.\n const observedAt = toStrictIsoTimestamp(turn.timestamp);\n if (!observedAt) continue;\n sources.push({\n sessionKey: turn.sessionKey ?? turn.logicalSessionKey ?? \"unknown\",\n ...(turn.turnId ? { turnId: turn.turnId } : {}),\n observedAt,\n quote: capQuote(quote, config.maxQuoteChars),\n ...(located.offsets\n ? { charStart: located.offsets.charStart, charEnd: located.offsets.charEnd }\n : {}),\n });\n }\n\n if (sources.length > 0) {\n return { sources, provenance: \"verified\" };\n }\n\n // Quote provided but could not be turned into a verified source.\n // Determine the session to attribute: prefer the turn where the quote was\n // LOCATED even if its timestamp couldn't be coerced (cursor thread 4Pj — a\n // located quote must not be tied to the *last* turn's session). If the\n // quote was not located in any turn at all, fall back to the last turn's\n // session (the documented unverified behavior: the LLM vouched for the\n // excerpt but we couldn't pin it to a character offset). Normalize the\n // timestamp (thread Ocveu); fall back to epoch when no turn supplies a\n // coercible timestamp so the unverified source still survives the\n // write-path schema.\n const fallbackTurn = locatedTurn ?? turns[turns.length - 1];\n const fallbackSessionKey = fallbackTurn\n ? (fallbackTurn.sessionKey ?? fallbackTurn.logicalSessionKey ?? \"unknown\")\n : \"unknown\";\n const fallbackObservedAt = fallbackTurn\n ? (toStrictIsoTimestamp(fallbackTurn.timestamp) ?? new Date(0).toISOString())\n : new Date(0).toISOString();\n // requireSpans signal (chatgpt-codex-connector thread 4xB): when an\n // operator opts into provenance.requireSpans, a fact whose quote could\n // not be located in ANY turn (locatedTurn undefined) is flagged so the\n // persist path routes it to pending_review instead of active. A quote\n // that WAS located (locatedTurn set) satisfies requireSpans even when\n // its source was dropped for an un-coercible timestamp — the span was\n // found, so the fact has the grounding requireSpans demands.\n const requireSpansPending =\n config.requireSpans === true && locatedTurn === undefined;\n return {\n sources: [\n {\n sessionKey: fallbackSessionKey,\n observedAt: fallbackObservedAt,\n quote: capQuote(quote, config.maxQuoteChars),\n },\n ],\n provenance: \"unverified\",\n ...(requireSpansPending ? { requireSpansPending: true } : {}),\n };\n } catch {\n // Never crash extraction on a provenance error (rule 13/18).\n return { provenance: \"none\" };\n }\n}\n","/**\n * Shared boolean coercion helpers.\n *\n * Extracted from connectors/index.ts so that both config.ts and\n * connectors/index.ts can import them without creating a circular dependency.\n */\n\n/**\n * Generic boolean coercion: converts string representations of booleans\n * (e.g. from CLI `--config someFlag=false`) to proper boolean values.\n * Accepts the same truthy/falsy strings that common shells and env vars use.\n *\n * Returns `undefined` when the value is neither a boolean nor a recognised\n * string, so callers can fall back to a default.\n *\n * CLAUDE.md gotcha #36: String \"false\" is truthy in JavaScript.\n * CLAUDE.md gotcha #28: Coerce CLI values to expected types at input boundaries.\n */\nexport function coerceBool(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n const v = value.trim().toLowerCase();\n if ([\"false\", \"0\", \"no\", \"off\"].includes(v)) return false;\n if ([\"true\", \"1\", \"yes\", \"on\"].includes(v)) return true;\n }\n return undefined;\n}\n\n/**\n * Coerce the `installExtension` config value from a string (e.g. from CLI\n * `--config installExtension=false`) to a proper boolean.\n *\n * Delegates to the generic `coerceBool` helper. Kept for backward compatibility.\n */\nexport function coerceInstallExtension(value: unknown): boolean | undefined {\n return coerceBool(value);\n}\n\n/**\n * Generic numeric coercion: accepts a finite number or a string that\n * parses cleanly to one. Returns `undefined` otherwise so callers can\n * fall back to a default.\n *\n * Rules:\n * - number: returned as-is only if finite (NaN / ±Infinity → undefined).\n * - string: trimmed, parsed with `Number()`. Returns `undefined` on\n * empty, NaN, or Infinity.\n *\n * CLAUDE.md gotcha #28: Coerce CLI values to expected types at input boundaries.\n */\nexport function coerceNumber(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n const n = Number(trimmed);\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;AAyBA,SAAS,SAAS;;;ACPX,SAAS,WAAW,OAAqC;AAC9D,MAAI,OAAO,UAAU,UAAW,QAAO;AACvC,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,QAAI,CAAC,SAAS,KAAK,MAAM,KAAK,EAAE,SAAS,CAAC,EAAG,QAAO;AACpD,QAAI,CAAC,QAAQ,KAAK,OAAO,IAAI,EAAE,SAAS,CAAC,EAAG,QAAO;AAAA,EACrD;AACA,SAAO;AACT;AAQO,SAAS,uBAAuB,OAAqC;AAC1E,SAAO,WAAW,KAAK;AACzB;AAcO,SAAS,aAAa,OAAoC;AAC/D,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAAA,EAC1C;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,MAAM,KAAK;AAC3B,QAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,UAAM,IAAI,OAAO,OAAO;AACxB,WAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAAA,EAClC;AACA,SAAO;AACT;;;ADvBA,IAAM,8BAA8B;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOA,SAAS,0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A,MACZ,GAAI,sBAAsB,EAAE,qBAAqB,KAAK,IAAI,CAAC;AAAA,IAC7D;AAAA,EACF,QAAQ;AAEN,WAAO,EAAE,YAAY,OAAO;AAAA,EAC9B;AACF;","names":["coerced"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/operator-toolkit.ts"],"sourcesContent":["import path from \"node:path\";\nimport { constants as fsConstants } from \"node:fs\";\nimport { access, mkdir, readFile, readdir, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { lintWorkspaceFiles } from \"./hygiene.js\";\nimport { parseConfig } from \"./config.js\";\nimport { readEnvVar, resolveHomeDir } from \"./runtime/env.js\";\nimport { resolvePluginEntry } from \"./plugin-entry-resolver.js\";\nimport {\n resolveCuratedIncludeFilesStatePath,\n resolveNativeKnowledgeStatePath,\n resolveOpenClawWorkspaceStatePath,\n} from \"./native-knowledge.js\";\nimport { StorageManager } from \"./storage.js\";\nimport { listNamespaces } from \"./namespaces/migrate.js\";\nimport { summarizeNamespaceMaintenanceHealth } from \"./maintenance/namespace-maintenance-fanout.js\";\nimport {\n createEvalBaselineSnapshot,\n getEvalHarnessStatus,\n runEvalBaselineDeltaReport,\n runEvalBenchmarkCiGate,\n validateEvalBenchmarkPack,\n type EvalBaselineDeltaReport,\n type EvalCiGateReport,\n type EvalHarnessStatus,\n} from \"./evals.js\";\nimport { analyzeGraphHealth, type GraphHealthReport } from \"./graph.js\";\nimport {\n analyzeSessionIntegrity,\n applySessionRepair,\n planSessionRepair,\n type SessionIntegrityReport,\n type SessionRepairApplyResult,\n type SessionRepairPlan,\n} from \"./session-integrity.js\";\nimport {\n listMemoryGovernanceRuns,\n readMemoryGovernanceRunArtifact,\n} from \"./maintenance/memory-governance.js\";\nimport {\n runConsolidationProvenanceCheck,\n type ConsolidationProvenanceReport,\n} from \"./consolidation-provenance-check.js\";\nimport type {\n BufferSurpriseEvent,\n DreamsPhasesConfig,\n FileHygieneConfig,\n MemoryFile,\n PluginConfig,\n} from \"./types.js\";\nimport { reportBufferSurpriseDistribution } from \"./buffer-surprise-report.js\";\nimport { readJudgeVerdictStats } from \"./extraction-judge-telemetry.js\";\n\nconst OPENCLAW_REMNIC_PLUGIN_IDS = [\"openclaw-remnic\", \"openclaw-engram\"] as const;\n\nfunction getOpenClawPluginEntries(raw: Record<string, unknown>): Record<string, unknown> | undefined {\n const plugins =\n raw[\"plugins\"] && typeof raw[\"plugins\"] === \"object\" && !Array.isArray(raw[\"plugins\"])\n ? (raw[\"plugins\"] as Record<string, unknown>)\n : undefined;\n const entries =\n plugins && plugins[\"entries\"] && typeof plugins[\"entries\"] === \"object\" && !Array.isArray(plugins[\"entries\"])\n ? (plugins[\"entries\"] as Record<string, unknown>)\n : undefined;\n return entries;\n}\n\nfunction getOpenClawMemorySlotId(raw: Record<string, unknown>): string | undefined {\n const plugins =\n raw[\"plugins\"] && typeof raw[\"plugins\"] === \"object\" && !Array.isArray(raw[\"plugins\"])\n ? (raw[\"plugins\"] as Record<string, unknown>)\n : undefined;\n const slots =\n plugins && plugins[\"slots\"] && typeof plugins[\"slots\"] === \"object\" && !Array.isArray(plugins[\"slots\"])\n ? (plugins[\"slots\"] as Record<string, unknown>)\n : undefined;\n const slotId = slots?.[\"memory\"];\n return typeof slotId === \"string\" ? slotId : undefined;\n}\n\nfunction resolveOpenClawRemnicPluginEntry(raw: unknown): Record<string, unknown> | undefined {\n return resolvePluginEntry(raw, {\n candidateIds: OPENCLAW_REMNIC_PLUGIN_IDS,\n getEntries: getOpenClawPluginEntries,\n getSlotId: getOpenClawMemorySlotId,\n });\n}\n\ninterface QmdRuntimeLike {\n probe(): Promise<boolean>;\n isAvailable(): boolean;\n ensureCollection(\n memoryDir: string,\n collectionOrExecution?: string | { signal?: AbortSignal },\n execution?: { signal?: AbortSignal },\n ): Promise<\"present\" | \"missing\" | \"unknown\" | \"skipped\">;\n debugStatus(): string;\n}\n\nfunction isMissingPathError(error: unknown): boolean {\n return typeof error === \"object\"\n && error !== null\n && \"code\" in error\n && (error as { code?: unknown }).code === \"ENOENT\";\n}\n\nfunction formatUnknownError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ninterface ConversationIndexLike {\n getConversationIndexHealth(): Promise<{\n enabled: boolean;\n backend: \"qmd\" | \"faiss\";\n status: \"ok\" | \"degraded\" | \"disabled\";\n chunkDocCount: number;\n lastUpdateAt: string | null;\n qmdAvailable?: boolean;\n faiss?: {\n ok: boolean;\n status: \"ok\" | \"degraded\" | \"error\";\n indexPath: string;\n message?: string;\n manifest?: {\n version: number;\n modelId: string;\n normalizedModelId: string;\n dimension: number;\n chunkCount: number;\n updatedAt: string;\n lastSuccessfulRebuildAt: string;\n };\n };\n }>;\n rebuildConversationIndex(\n sessionKey?: string,\n hours?: number,\n opts?: { embed?: boolean },\n ): Promise<{\n chunks: number;\n skipped: boolean;\n reason?: string;\n embedded?: boolean;\n rebuilt?: boolean;\n }>;\n}\n\nexport interface OperatorToolkitOrchestrator extends ConversationIndexLike {\n config: PluginConfig;\n storage: StorageManager;\n qmd: QmdRuntimeLike;\n}\n\nexport interface OperatorConfigLoadResult {\n found: boolean;\n path: string;\n parsed: boolean;\n memoryDir?: string;\n workspaceDir?: string;\n error?: string;\n}\n\nexport interface OperatorSetupReport {\n schemaVersion: 1;\n generatedAt: string;\n config: OperatorConfigLoadResult;\n memoryDir: string;\n workspaceDir: string;\n directories: Array<{ path: string; exists: boolean; writable: boolean }>;\n qmd: {\n enabled: boolean;\n available: boolean;\n collectionState: \"present\" | \"missing\" | \"unknown\" | \"skipped\";\n debugStatus: string;\n };\n nativeKnowledge: {\n enabled: boolean;\n includeFiles: string[];\n curatedIncludeSync: {\n statePath: string;\n exists: boolean;\n updatedAt: string | null;\n fileCount: number;\n activeChunkCount: number;\n deletedFileCount: number;\n };\n openclawWorkspaceAdapterEnabled: boolean;\n obsidianVaultAdapterEnabled: boolean;\n obsidianSync: {\n statePath: string;\n exists: boolean;\n updatedAt: string | null;\n vaultCount: number;\n activeChunkCount: number;\n deletedNoteCount: number;\n };\n openclawWorkspaceSync: {\n statePath: string;\n exists: boolean;\n updatedAt: string | null;\n fileCount: number;\n activeChunkCount: number;\n deletedFileCount: number;\n };\n };\n explicitCapture: {\n captureMode: string;\n enabled: boolean;\n memoryDocPath: string;\n memoryDocExists: boolean;\n memoryDocInstalled: boolean;\n memoryDocUpdated: boolean;\n memoryDocRemoved: boolean;\n preview: string | null;\n };\n nextSteps: string[];\n verificationCommands: string[];\n}\n\nexport interface OperatorDoctorCheck {\n key: string;\n status: \"ok\" | \"warn\" | \"error\";\n summary: string;\n remediation?: string;\n details?: unknown;\n}\n\nexport interface OperatorConfigReviewFinding {\n key: string;\n status: \"recommend\" | \"problem\";\n setting: string;\n currentValue: string;\n defaultValue: string;\n recommendedValue: string;\n summary: string;\n rationale: string;\n}\n\nexport interface OperatorConfigReviewReport {\n schemaVersion: 1;\n generatedAt: string;\n ok: boolean;\n config: OperatorConfigLoadResult;\n profile: {\n memoryOsPreset?: string;\n searchBackend: string;\n qmdEnabled: boolean;\n qmdDaemonEnabled: boolean;\n nativeKnowledgeEnabled: boolean;\n fileHygieneEnabled: boolean;\n conversationIndexEnabled: boolean;\n };\n summary: {\n recommend: number;\n problem: number;\n };\n findings: OperatorConfigReviewFinding[];\n}\n\nexport interface OperatorDoctorReport {\n schemaVersion: 1;\n generatedAt: string;\n ok: boolean;\n summary: {\n ok: number;\n warn: number;\n error: number;\n };\n config: OperatorConfigLoadResult;\n checks: OperatorDoctorCheck[];\n}\n\nexport interface OperatorInventoryNamespaceSummary {\n namespace: string;\n memoryCount: number;\n entityCount: number;\n}\n\nexport interface OperatorInventoryReport {\n schemaVersion: 1;\n generatedAt: string;\n memoryDir: string;\n totals: {\n memories: number;\n entities: number;\n namespaces: number;\n reviewQueue: number;\n storageBytes: number;\n };\n categories: Record<string, number>;\n statuses: Record<string, number>;\n namespaces: OperatorInventoryNamespaceSummary[];\n ageBands: Record<string, number>;\n profile: {\n exists: boolean;\n chars: number;\n lines: number;\n };\n storageFootprint: {\n bytes: number;\n byTopLevel: Record<string, number>;\n };\n archivePressure: {\n archived: number;\n pendingReview: number;\n quarantined: number;\n rejected: number;\n };\n conversationIndex: {\n enabled: boolean;\n backend: \"qmd\" | \"faiss\";\n status: \"ok\" | \"degraded\" | \"disabled\";\n chunkDocCount: number;\n lastUpdateAt: string | null;\n };\n nativeKnowledge: {\n enabled: boolean;\n curatedIncludeSync: {\n exists: boolean;\n updatedAt: string | null;\n fileCount: number;\n activeChunkCount: number;\n deletedFileCount: number;\n };\n obsidianSync: {\n exists: boolean;\n updatedAt: string | null;\n vaultCount: number;\n activeChunkCount: number;\n deletedNoteCount: number;\n };\n openclawWorkspaceSync: {\n exists: boolean;\n updatedAt: string | null;\n fileCount: number;\n activeChunkCount: number;\n deletedFileCount: number;\n };\n };\n}\n\nexport interface BenchmarkRecallReport {\n schemaVersion: 1;\n generatedAt: string;\n mode: \"status\" | \"validate\" | \"baseline-report\" | \"ci-gate\" | \"snapshot\";\n status: EvalHarnessStatus;\n validate?: Awaited<ReturnType<typeof validateEvalBenchmarkPack>>;\n baselineReport?: EvalBaselineDeltaReport;\n ciGate?: EvalCiGateReport;\n snapshot?: {\n targetPath: string;\n snapshotId: string;\n };\n}\n\nexport interface OperatorRepairReport {\n schemaVersion: 1;\n generatedAt: string;\n dryRun: boolean;\n sessionCheck: SessionIntegrityReport;\n sessionRepairPlan: SessionRepairPlan;\n sessionRepairApply: SessionRepairApplyResult;\n graphHealth: GraphHealthReport;\n}\n\nexport interface OperatorSetupOptions {\n orchestrator: OperatorToolkitOrchestrator;\n installCaptureInstructions?: boolean;\n captureInstructionsMode?: \"preview\" | \"install\" | \"remove\";\n configPath?: string;\n now?: Date;\n}\n\nexport interface OperatorDoctorOptions {\n orchestrator: OperatorToolkitOrchestrator;\n configPath?: string;\n now?: Date;\n}\n\nexport interface OperatorConfigReviewOptions {\n orchestrator: OperatorToolkitOrchestrator;\n configPath?: string;\n now?: Date;\n}\n\nexport interface OperatorInventoryOptions {\n orchestrator: OperatorToolkitOrchestrator;\n now?: Date;\n}\n\nexport interface BenchmarkRecallOptions {\n config: Pick<\n PluginConfig,\n | \"memoryDir\"\n | \"evalStoreDir\"\n | \"evalHarnessEnabled\"\n | \"evalShadowModeEnabled\"\n | \"benchmarkBaselineSnapshotsEnabled\"\n | \"benchmarkDeltaReporterEnabled\"\n | \"memoryRedTeamBenchEnabled\"\n >;\n validatePath?: string;\n baseEvalStoreDir?: string;\n candidateEvalStoreDir?: string;\n snapshotId?: string;\n createSnapshot?: boolean;\n snapshotNotes?: string;\n gitRef?: string;\n createdAt?: string;\n now?: Date;\n}\n\nexport interface OperatorRepairOptions {\n config: Pick<\n PluginConfig,\n \"memoryDir\" | \"entityGraphEnabled\" | \"timeGraphEnabled\" | \"causalGraphEnabled\"\n >;\n apply?: boolean;\n dryRun?: boolean;\n allowSessionFileRepair?: boolean;\n sessionFilesDir?: string;\n now?: Date;\n}\n\nfunction resolveConfigPath(explicitPath?: string): string {\n if (explicitPath && explicitPath.trim().length > 0) return explicitPath.trim();\n const configured =\n readEnvVar(\"OPENCLAW_CONFIG_PATH\") ||\n readEnvVar(\"OPENCLAW_ENGRAM_CONFIG_PATH\");\n if (configured && configured.trim().length > 0) return configured.trim();\n return path.join(resolveHomeDir(), \".openclaw\", \"openclaw.json\");\n}\n\nasync function loadCliPluginConfig(configPath?: string): Promise<OperatorConfigLoadResult> {\n const resolvedPath = resolveConfigPath(configPath);\n try {\n const raw = JSON.parse(await readFile(resolvedPath, \"utf-8\")) as Record<string, unknown>;\n // Delegate slot → canonical → legacy resolution to the generic helper so\n // all config loaders stay in sync (#403).\n const entry = resolveOpenClawRemnicPluginEntry(raw);\n const parsedConfig = parseConfig(\n entry && typeof entry === \"object\"\n ? ((entry[\"config\"] as Record<string, unknown> | undefined) ?? {})\n : {},\n );\n return {\n found: true,\n path: resolvedPath,\n parsed: true,\n memoryDir: parsedConfig.memoryDir,\n workspaceDir: parsedConfig.workspaceDir,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n found: !/ENOENT/i.test(message),\n path: resolvedPath,\n parsed: false,\n error: message,\n };\n }\n}\n\nasync function isWritable(targetPath: string): Promise<boolean> {\n try {\n await access(targetPath, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function pathExists(targetPath: string): Promise<boolean> {\n try {\n await access(targetPath, fsConstants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction formatConfigValue(value: unknown): string {\n if (value === undefined || value === null) return \"(unset)\";\n if (typeof value === \"string\") return value.length > 0 ? value : \"(unset)\";\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n\nasync function gatherDirectoryStatus(\n paths: string[],\n): Promise<Array<{ path: string; exists: boolean; writable: boolean }>> {\n return Promise.all(paths.map(async (targetPath) => {\n try {\n await access(targetPath, fsConstants.F_OK);\n return {\n path: targetPath,\n exists: true,\n writable: await isWritable(targetPath),\n };\n } catch {\n return {\n path: targetPath,\n exists: false,\n writable: false,\n };\n }\n }));\n}\n\nfunction getSetupPaths(config: PluginConfig): string[] {\n return [\n config.memoryDir,\n config.workspaceDir,\n path.join(config.memoryDir, \"facts\"),\n path.join(config.memoryDir, \"entities\"),\n path.join(config.memoryDir, \"state\"),\n path.join(config.memoryDir, \"questions\"),\n path.join(config.memoryDir, \"artifacts\"),\n path.join(config.memoryDir, \"config\"),\n ];\n}\n\nasync function readJsonIfExists(filePath: string): Promise<unknown | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf-8\")) as unknown;\n } catch {\n return null;\n }\n}\n\nasync function summarizeNativeKnowledgeStatus(config: PluginConfig): Promise<{\n enabled: boolean;\n includeFiles: string[];\n curatedIncludeSync: {\n statePath: string;\n exists: boolean;\n updatedAt: string | null;\n fileCount: number;\n activeChunkCount: number;\n deletedFileCount: number;\n };\n openclawWorkspaceAdapterEnabled: boolean;\n obsidianVaultAdapterEnabled: boolean;\n obsidianSync: {\n statePath: string;\n exists: boolean;\n updatedAt: string | null;\n vaultCount: number;\n activeChunkCount: number;\n deletedNoteCount: number;\n };\n openclawWorkspaceSync: {\n statePath: string;\n exists: boolean;\n updatedAt: string | null;\n fileCount: number;\n activeChunkCount: number;\n deletedFileCount: number;\n };\n}> {\n const nativeKnowledge = config.nativeKnowledge;\n const nativeKnowledgeStateDir = nativeKnowledge?.stateDir ?? \"state/native-knowledge\";\n const curatedStatePath = nativeKnowledge\n ? resolveCuratedIncludeFilesStatePath(config.memoryDir, nativeKnowledge)\n : path.join(config.memoryDir, nativeKnowledgeStateDir, \"curated-include-sync.json\");\n const obsidianStatePath = nativeKnowledge\n ? resolveNativeKnowledgeStatePath(config.memoryDir, nativeKnowledge)\n : path.join(config.memoryDir, nativeKnowledgeStateDir, \"obsidian-sync.json\");\n const openclawStatePath = nativeKnowledge\n ? resolveOpenClawWorkspaceStatePath(config.memoryDir, nativeKnowledge)\n : path.join(config.memoryDir, nativeKnowledgeStateDir, \"openclaw-workspace-sync.json\");\n const [curatedRaw, obsidianRaw, openclawRaw] = await Promise.all([\n readJsonIfExists(curatedStatePath),\n readJsonIfExists(obsidianStatePath),\n readJsonIfExists(openclawStatePath),\n ]);\n\n const curatedFiles = curatedRaw && typeof curatedRaw === \"object\" && curatedRaw !== null\n && \"files\" in curatedRaw && typeof (curatedRaw as { files?: unknown }).files === \"object\"\n && (curatedRaw as { files?: unknown }).files !== null\n ? (curatedRaw as {\n updatedAt?: unknown;\n files: Record<string, { deleted?: boolean; chunks?: unknown[] }>;\n })\n : null;\n\n let curatedActiveChunkCount = 0;\n let curatedDeletedFileCount = 0;\n for (const file of Object.values(curatedFiles?.files ?? {})) {\n if (file.deleted) {\n curatedDeletedFileCount += 1;\n continue;\n }\n curatedActiveChunkCount += Array.isArray(file.chunks) ? file.chunks.length : 0;\n }\n\n const obsidianVaults = obsidianRaw && typeof obsidianRaw === \"object\" && obsidianRaw !== null\n && \"vaults\" in obsidianRaw && typeof (obsidianRaw as { vaults?: unknown }).vaults === \"object\"\n && (obsidianRaw as { vaults?: unknown }).vaults !== null\n ? (obsidianRaw as {\n updatedAt?: unknown;\n vaults: Record<string, { notes?: Record<string, { deleted?: boolean; chunks?: unknown[] }> }>;\n })\n : null;\n\n let obsidianActiveChunkCount = 0;\n let obsidianDeletedNoteCount = 0;\n for (const vault of Object.values(obsidianVaults?.vaults ?? {})) {\n for (const note of Object.values(vault.notes ?? {})) {\n if (note.deleted) {\n obsidianDeletedNoteCount += 1;\n continue;\n }\n obsidianActiveChunkCount += Array.isArray(note.chunks) ? note.chunks.length : 0;\n }\n }\n\n const openclawFiles = openclawRaw && typeof openclawRaw === \"object\" && openclawRaw !== null\n && \"files\" in openclawRaw && typeof (openclawRaw as { files?: unknown }).files === \"object\"\n && (openclawRaw as { files?: unknown }).files !== null\n ? (openclawRaw as {\n updatedAt?: unknown;\n files: Record<string, { deleted?: boolean; chunks?: unknown[] }>;\n })\n : null;\n\n let openclawActiveChunkCount = 0;\n let openclawDeletedFileCount = 0;\n for (const file of Object.values(openclawFiles?.files ?? {})) {\n if (file.deleted) {\n openclawDeletedFileCount += 1;\n continue;\n }\n openclawActiveChunkCount += Array.isArray(file.chunks) ? file.chunks.length : 0;\n }\n\n return {\n enabled: nativeKnowledge?.enabled === true,\n includeFiles: nativeKnowledge?.includeFiles ?? [],\n curatedIncludeSync: {\n statePath: curatedStatePath,\n exists: curatedFiles !== null,\n updatedAt: typeof curatedFiles?.updatedAt === \"string\" ? curatedFiles.updatedAt : null,\n fileCount: Object.keys(curatedFiles?.files ?? {}).length,\n activeChunkCount: curatedActiveChunkCount,\n deletedFileCount: curatedDeletedFileCount,\n },\n openclawWorkspaceAdapterEnabled: nativeKnowledge?.openclawWorkspace?.enabled === true,\n obsidianVaultAdapterEnabled: (nativeKnowledge?.obsidianVaults?.length ?? 0) > 0,\n obsidianSync: {\n statePath: obsidianStatePath,\n exists: obsidianVaults !== null,\n updatedAt: typeof obsidianVaults?.updatedAt === \"string\" ? obsidianVaults.updatedAt : null,\n vaultCount: Object.keys(obsidianVaults?.vaults ?? {}).length,\n activeChunkCount: obsidianActiveChunkCount,\n deletedNoteCount: obsidianDeletedNoteCount,\n },\n openclawWorkspaceSync: {\n statePath: openclawStatePath,\n exists: openclawFiles !== null,\n updatedAt: typeof openclawFiles?.updatedAt === \"string\" ? openclawFiles.updatedAt : null,\n fileCount: Object.keys(openclawFiles?.files ?? {}).length,\n activeChunkCount: openclawActiveChunkCount,\n deletedFileCount: openclawDeletedFileCount,\n },\n };\n}\n\nconst CAPTURE_INSTRUCTIONS_START = \"<!-- BEGIN ENGRAM EXPLICIT CAPTURE INSTRUCTIONS -->\";\nconst CAPTURE_INSTRUCTIONS_END = \"<!-- END ENGRAM EXPLICIT CAPTURE INSTRUCTIONS -->\";\n\nfunction buildCaptureInstructions(): string {\n return [\n CAPTURE_INSTRUCTIONS_START,\n \"# Memory\",\n \"\",\n \"Use this file for explicit memory capture notes when Engram runs in explicit or hybrid mode.\",\n \"\",\n \"## Suggested format\",\n \"\",\n \"- Write durable facts, decisions, commitments, or corrections.\",\n \"- Keep entries concise and specific.\",\n \"- Avoid secrets, tokens, and private credentials.\",\n \"\",\n \"## Example\",\n \"\",\n \"- Decision: recall benchmark packs live under `state/evals/benchmarks/`.\",\n \"- Commitment: rerun `openclaw engram doctor --json` after changing retrieval settings.\",\n \"\",\n CAPTURE_INSTRUCTIONS_END,\n ].join(\"\\n\");\n}\n\nfunction upsertManagedCaptureInstructions(existing: string | null, snippet: string): { content: string; updated: boolean; installed: boolean } {\n if (!existing || existing.trim().length === 0) {\n return { content: `${snippet}\\n`, updated: false, installed: true };\n }\n if (existing.includes(CAPTURE_INSTRUCTIONS_START) && existing.includes(CAPTURE_INSTRUCTIONS_END)) {\n const next = existing.replace(\n new RegExp(`${CAPTURE_INSTRUCTIONS_START}[\\\\s\\\\S]*?${CAPTURE_INSTRUCTIONS_END}`),\n snippet,\n );\n return { content: next.endsWith(\"\\n\") ? next : `${next}\\n`, updated: next !== existing, installed: false };\n }\n const trimmed = existing.trimEnd();\n return {\n content: `${trimmed}\\n\\n${snippet}\\n`,\n updated: false,\n installed: true,\n };\n}\n\nfunction removeManagedCaptureInstructions(existing: string): { content: string; removed: boolean } {\n if (!existing.includes(CAPTURE_INSTRUCTIONS_START) || !existing.includes(CAPTURE_INSTRUCTIONS_END)) {\n return { content: existing, removed: false };\n }\n const stripped = existing\n .replace(new RegExp(`\\\\n*${CAPTURE_INSTRUCTIONS_START}[\\\\s\\\\S]*?${CAPTURE_INSTRUCTIONS_END}\\\\n*`), \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n return {\n content: stripped.length > 0 ? `${stripped}\\n` : \"\",\n removed: true,\n };\n}\n\nexport async function runOperatorSetup(options: OperatorSetupOptions): Promise<OperatorSetupReport> {\n const now = options.now ?? new Date();\n const configStatus = await loadCliPluginConfig(options.configPath);\n const storage = options.orchestrator.storage;\n await storage.ensureDirectories();\n await mkdir(options.orchestrator.config.workspaceDir, { recursive: true });\n\n const qmdAvailable = await options.orchestrator.qmd.probe();\n const collectionState = options.orchestrator.config.qmdEnabled\n ? await options.orchestrator.qmd.ensureCollection(\n options.orchestrator.config.memoryDir,\n options.orchestrator.config.qmdCollection,\n )\n : \"skipped\";\n const nativeKnowledgeStatus = await summarizeNativeKnowledgeStatus(options.orchestrator.config);\n\n const memoryDocPath = path.join(options.orchestrator.config.workspaceDir, \"MEMORY.md\");\n const captureInstructionsMode =\n options.captureInstructionsMode\n ?? (options.installCaptureInstructions ? \"install\" : undefined);\n let memoryDocExists = false;\n try {\n await access(memoryDocPath, fsConstants.F_OK);\n memoryDocExists = true;\n } catch {\n memoryDocExists = false;\n }\n let memoryDocInstalled = false;\n let memoryDocUpdated = false;\n let memoryDocRemoved = false;\n const explicitCaptureEnabled = options.orchestrator.config.captureMode === \"explicit\"\n || options.orchestrator.config.captureMode === \"hybrid\";\n const captureInstructionsPreview = captureInstructionsMode ? buildCaptureInstructions() : null;\n if (captureInstructionsMode) {\n if (captureInstructionsMode === \"preview\") {\n // no-op, preview only\n } else if (captureInstructionsMode === \"install\") {\n const existing = memoryDocExists ? await readFile(memoryDocPath, \"utf-8\") : null;\n const next = upsertManagedCaptureInstructions(existing, captureInstructionsPreview ?? \"\");\n if (!existing || next.content !== existing) {\n await writeFile(memoryDocPath, next.content, \"utf-8\");\n }\n memoryDocExists = true;\n memoryDocInstalled = next.installed;\n memoryDocUpdated = next.updated;\n } else if (captureInstructionsMode === \"remove\" && memoryDocExists) {\n const existing = await readFile(memoryDocPath, \"utf-8\");\n const next = removeManagedCaptureInstructions(existing);\n if (next.removed) {\n if (next.content.length === 0) {\n await unlink(memoryDocPath);\n memoryDocExists = false;\n } else {\n await writeFile(memoryDocPath, next.content, \"utf-8\");\n memoryDocExists = true;\n }\n memoryDocRemoved = true;\n }\n }\n }\n\n const directories = await gatherDirectoryStatus(getSetupPaths(options.orchestrator.config));\n const nextSteps = [\n `Run \\`openclaw engram doctor${options.installCaptureInstructions ? \"\" : \" --json\"}\\` to verify runtime health.`,\n \"Run `openclaw engram inventory --json` to capture a baseline footprint.\",\n \"If QMD is enabled and the collection is missing, add the collection to `~/.config/qmd/index.yml` and run `qmd update && qmd embed`.\",\n ];\n if (explicitCaptureEnabled && !memoryDocExists) {\n nextSteps.push(\"Run `openclaw engram setup --preview-capture-instructions` to review the managed explicit-capture snippet, then `--install-capture-instructions` to write it.\");\n }\n\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n config: configStatus,\n memoryDir: options.orchestrator.config.memoryDir,\n workspaceDir: options.orchestrator.config.workspaceDir,\n directories,\n qmd: {\n enabled: options.orchestrator.config.qmdEnabled,\n available: qmdAvailable,\n collectionState,\n debugStatus: options.orchestrator.qmd.debugStatus(),\n },\n nativeKnowledge: nativeKnowledgeStatus,\n explicitCapture: {\n captureMode: options.orchestrator.config.captureMode,\n enabled: explicitCaptureEnabled,\n memoryDocPath,\n memoryDocExists,\n memoryDocInstalled,\n memoryDocUpdated,\n memoryDocRemoved,\n preview: captureInstructionsMode === \"preview\" ? captureInstructionsPreview : null,\n },\n nextSteps,\n verificationCommands: [\n \"openclaw engram doctor --json\",\n \"openclaw engram inventory --json\",\n \"openclaw engram benchmark recall --json\",\n ],\n };\n}\n\nfunction summarizeHygieneWarnings(\n warnings: Awaited<ReturnType<typeof lintWorkspaceFiles>>,\n hygiene: FileHygieneConfig | undefined,\n): OperatorDoctorCheck {\n if (!hygiene?.enabled || hygiene.lintEnabled !== true) {\n return {\n key: \"file_hygiene\",\n status: \"warn\",\n summary: \"File hygiene linting is disabled; bootstrap file truncation warnings are not active.\",\n remediation: \"Enable `fileHygiene.enabled` and `fileHygiene.lintEnabled` if large workspace bootstrap files are common.\",\n details: {\n enabled: hygiene?.enabled === true,\n lintEnabled: hygiene?.lintEnabled === true,\n },\n };\n }\n if (warnings.length > 0) {\n return {\n key: \"file_hygiene\",\n status: \"warn\",\n summary: `${warnings.length} bootstrap file(s) are near or above the configured budget.`,\n remediation: \"Archive/split the listed files or adjust `fileHygiene` budgets.\",\n details: { warnings },\n };\n }\n return {\n key: \"file_hygiene\",\n status: \"ok\",\n summary: \"Bootstrap file hygiene is within budget.\",\n details: {\n enabled: true,\n lintPaths: hygiene.lintPaths,\n budgetBytes: hygiene.lintBudgetBytes,\n },\n };\n}\n\nfunction buildConfigReviewFinding(input: {\n key: string;\n status: \"recommend\" | \"problem\";\n setting: string;\n currentValue: unknown;\n defaultValue: unknown;\n recommendedValue: unknown;\n summary: string;\n rationale: string;\n}): OperatorConfigReviewFinding {\n return {\n key: input.key,\n status: input.status,\n setting: input.setting,\n currentValue: formatConfigValue(input.currentValue),\n defaultValue: formatConfigValue(input.defaultValue),\n recommendedValue: formatConfigValue(input.recommendedValue),\n summary: input.summary,\n rationale: input.rationale,\n };\n}\n\nexport async function runOperatorConfigReview(\n options: OperatorConfigReviewOptions,\n): Promise<OperatorConfigReviewReport> {\n const now = options.now ?? new Date();\n const configStatus = await loadCliPluginConfig(options.configPath);\n return buildOperatorConfigReviewReport({\n now,\n configStatus,\n config: options.orchestrator.config,\n });\n}\n\nasync function buildOperatorConfigReviewReport(input: {\n now: Date;\n configStatus: OperatorConfigLoadResult;\n config: PluginConfig;\n}): Promise<OperatorConfigReviewReport> {\n const { now, configStatus, config } = input;\n const findings: OperatorConfigReviewFinding[] = [];\n const searchBackend = config.searchBackend ?? \"qmd\";\n const workspaceBootstrapFiles = [\n path.join(config.workspaceDir, \"IDENTITY.md\"),\n path.join(config.workspaceDir, \"MEMORY.md\"),\n path.join(config.workspaceDir, \"USER.md\"),\n ];\n const workspaceBootstrapExists = (await Promise.all(workspaceBootstrapFiles.map(pathExists))).some(Boolean);\n\n if (\n config.memoryOsPreset !== \"conservative\" &&\n config.memoryOsPreset !== \"balanced\" &&\n config.memoryOsPreset !== \"research-max\" &&\n config.memoryOsPreset !== \"local-llm-heavy\" &&\n config.queryAwareIndexingEnabled === false &&\n config.verbatimArtifactsEnabled === false &&\n config.rerankEnabled === false\n ) {\n findings.push(buildConfigReviewFinding({\n key: \"balanced_preset\",\n status: \"recommend\",\n setting: \"memoryOsPreset\",\n currentValue: config.memoryOsPreset,\n defaultValue: \"(unset)\",\n recommendedValue: \"balanced\",\n summary: \"Adopt the balanced preset as the baseline configuration profile.\",\n rationale:\n \"The balanced preset enables the recommended indexing, reranking, and artifact defaults without turning on the higher-churn graph and learning loops.\",\n }));\n }\n\n if (config.qmdEnabled && config.qmdDaemonEnabled === false) {\n findings.push(buildConfigReviewFinding({\n key: \"qmd_daemon\",\n status: \"recommend\",\n setting: \"qmdDaemonEnabled\",\n currentValue: config.qmdDaemonEnabled,\n defaultValue: true,\n recommendedValue: true,\n summary: \"Enable the QMD daemon path when QMD powers recall.\",\n rationale:\n \"The daemon path reduces recall/search contention by preferring the MCP transport instead of repeated subprocess calls when QMD is available.\",\n }));\n }\n\n if (workspaceBootstrapExists && config.nativeKnowledge?.enabled !== true) {\n findings.push(buildConfigReviewFinding({\n key: \"native_knowledge_enabled\",\n status: \"recommend\",\n setting: \"nativeKnowledge.enabled\",\n currentValue: config.nativeKnowledge?.enabled,\n defaultValue: false,\n recommendedValue: true,\n summary: \"Enable native knowledge recall for workspace bootstrap documents.\",\n rationale:\n \"When files like IDENTITY.md or MEMORY.md already exist, native knowledge recall can chunk and inject them directly instead of relying only on extracted memories.\",\n }));\n }\n\n if (workspaceBootstrapExists && config.fileHygiene?.enabled !== true) {\n findings.push(buildConfigReviewFinding({\n key: \"file_hygiene_enabled\",\n status: \"recommend\",\n setting: \"fileHygiene.enabled\",\n currentValue: config.fileHygiene?.enabled,\n defaultValue: false,\n recommendedValue: true,\n summary: \"Enable file hygiene to avoid silent workspace-file truncation.\",\n rationale:\n \"OpenClaw bootstrap files can grow quietly; file hygiene warns before oversized files are truncated during prompt bootstrap.\",\n }));\n }\n\n if (searchBackend === \"qmd\" && config.qmdEnabled === false) {\n findings.push(buildConfigReviewFinding({\n key: \"qmd_search_backend_disabled\",\n status: \"problem\",\n setting: \"qmdEnabled\",\n currentValue: config.qmdEnabled,\n defaultValue: true,\n recommendedValue: true,\n summary: \"QMD search is selected but QMD is disabled.\",\n rationale:\n \"When searchBackend resolves to qmd while qmdEnabled is false, Engram falls back to the noop backend and disables the primary search path.\",\n }));\n }\n\n if (config.qmdColdTierEnabled === true && config.qmdEnabled === false) {\n findings.push(buildConfigReviewFinding({\n key: \"qmd_cold_tier_requires_qmd\",\n status: \"problem\",\n setting: \"qmdEnabled\",\n currentValue: config.qmdEnabled,\n defaultValue: true,\n recommendedValue: true,\n summary: \"Cold-tier QMD recall is enabled while QMD itself is disabled.\",\n rationale:\n \"The cold tier depends on the same QMD runtime as the hot tier, so turning QMD off leaves the extra tiering path unusable.\",\n }));\n }\n\n if (config.qmdTierMigrationEnabled && config.qmdColdTierEnabled !== true) {\n findings.push(buildConfigReviewFinding({\n key: \"qmd_tier_migration_requires_cold_tier\",\n status: \"problem\",\n setting: \"qmdColdTierEnabled\",\n currentValue: config.qmdColdTierEnabled,\n defaultValue: false,\n recommendedValue: true,\n summary: \"Hot/cold tier migration is enabled without the cold tier itself.\",\n rationale:\n \"Tier migration depends on the cold-tier collection and recall path, so enabling migration while the cold tier is off leaves the feature in a contradictory state.\",\n }));\n }\n\n if (config.conversationIndexEnabled && config.conversationIndexBackend === \"qmd\" && config.qmdEnabled === false) {\n findings.push(buildConfigReviewFinding({\n key: \"conversation_index_qmd_requires_qmd\",\n status: \"problem\",\n setting: \"qmdEnabled\",\n currentValue: config.qmdEnabled,\n defaultValue: true,\n recommendedValue: true,\n summary: \"The conversation index is configured for QMD while QMD is disabled.\",\n rationale:\n \"A QMD-backed conversation index cannot rebuild or serve queries when the underlying QMD runtime is disabled.\",\n }));\n }\n\n const summary = findings.reduce(\n (acc, finding) => {\n acc[finding.status] += 1;\n return acc;\n },\n { recommend: 0, problem: 0 },\n );\n\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n ok: configStatus.parsed && summary.problem === 0,\n config: configStatus,\n profile: {\n memoryOsPreset: config.memoryOsPreset,\n searchBackend,\n qmdEnabled: config.qmdEnabled,\n qmdDaemonEnabled: config.qmdDaemonEnabled,\n nativeKnowledgeEnabled: config.nativeKnowledge?.enabled === true,\n fileHygieneEnabled: config.fileHygiene?.enabled === true,\n conversationIndexEnabled: config.conversationIndexEnabled,\n },\n summary,\n findings,\n };\n}\n\n/**\n * Summarize the provenance coverage of a set of memories (issue #1575 PR 3).\n * Pure function — counts the verified/unverified/none distribution so the\n * doctor check and any future surface can consume it without coupling to the\n * orchestrator. Legacy memories (no `provenance` field) count as `\"none\"`.\n */\nexport function summarizeProvenanceCoverage(\n memories: ReadonlyArray<{ frontmatter: { provenance?: string } }>,\n): { counts: { verified: number; unverified: number; none: number }; total: number } {\n const counts = { verified: 0, unverified: 0, none: 0 };\n for (const mem of memories) {\n const tag = mem.frontmatter.provenance ?? \"none\";\n if (tag === \"verified\") counts.verified += 1;\n else if (tag === \"unverified\") counts.unverified += 1;\n else counts.none += 1;\n }\n return { counts, total: memories.length };\n}\n\nexport async function runOperatorDoctor(options: OperatorDoctorOptions): Promise<OperatorDoctorReport> {\n const now = options.now ?? new Date();\n const configStatus = await loadCliPluginConfig(options.configPath);\n const checks: OperatorDoctorCheck[] = [];\n const config = options.orchestrator.config;\n const storage = options.orchestrator.storage;\n const configReview = await buildOperatorConfigReviewReport({\n now,\n configStatus,\n config,\n });\n const nativeKnowledgeStatus = await summarizeNativeKnowledgeStatus(config);\n const setupPaths = await gatherDirectoryStatus(getSetupPaths(config));\n const missingPaths = setupPaths.filter((entry) => !entry.exists).map((entry) => entry.path);\n\n checks.push({\n key: \"config\",\n status: configStatus.parsed\n ? \"ok\"\n : options.configPath\n ? \"error\"\n : \"warn\",\n summary: configStatus.parsed ? \"OpenClaw config loaded and Engram config parsed successfully.\" : \"Config file could not be parsed.\",\n remediation: configStatus.parsed ? undefined : \"Fix the config file or set OPENCLAW_ENGRAM_CONFIG_PATH/OPENCLAW_CONFIG_PATH.\",\n details: configStatus,\n });\n\n checks.push({\n key: \"memory_dir\",\n status: missingPaths.length === 0 ? \"ok\" : \"warn\",\n summary: missingPaths.length === 0\n ? \"Expected Engram directories exist.\"\n : `${missingPaths.length} expected directory path(s) are missing.`,\n remediation: missingPaths.length === 0 ? undefined : \"Run `openclaw engram setup` to create missing directories.\",\n details: { directories: setupPaths },\n });\n\n checks.push({\n key: \"config_review\",\n status: configReview.summary.problem > 0 ? \"error\" : configReview.summary.recommend > 0 ? \"warn\" : \"ok\",\n summary: configReview.summary.problem > 0\n ? `${configReview.summary.problem} configuration problem(s) detected.`\n : configReview.summary.recommend > 0\n ? `No configuration problems detected; ${configReview.summary.recommend} optional recommendation(s) are available.`\n : \"No configuration problems detected.\",\n remediation: configReview.summary.problem > 0 || configReview.summary.recommend > 0\n ? \"Run `openclaw engram config-review` to inspect and fix the flagged configuration combinations.\"\n : undefined,\n details: configReview,\n });\n\n const qmdAvailable = await options.orchestrator.qmd.probe();\n const collectionState = config.qmdEnabled\n ? await options.orchestrator.qmd.ensureCollection(config.memoryDir, config.qmdCollection)\n : \"skipped\";\n checks.push({\n key: \"qmd\",\n status: !config.qmdEnabled\n ? \"warn\"\n : !qmdAvailable\n ? \"error\"\n : collectionState === \"present\"\n ? \"ok\"\n : collectionState === \"missing\"\n ? \"error\"\n : \"warn\",\n summary: !config.qmdEnabled\n ? \"QMD is disabled in config.\"\n : qmdAvailable\n ? `QMD is reachable (${collectionState}).`\n : \"QMD is not currently reachable.\",\n remediation: !config.qmdEnabled\n ? \"Enable `qmdEnabled` if you expect hybrid search.\"\n : !qmdAvailable\n ? \"Ensure the `qmd` binary is installed and on PATH, or set `qmdPath`.\"\n : collectionState === \"missing\"\n ? \"Add the configured collection to `~/.config/qmd/index.yml`.\"\n : collectionState === \"present\"\n ? undefined\n : \"Re-run `openclaw engram setup` after restoring QMD access.\",\n details: {\n available: qmdAvailable,\n collectionState,\n debugStatus: options.orchestrator.qmd.debugStatus(),\n },\n });\n\n const conversationIndex = await options.orchestrator.getConversationIndexHealth();\n checks.push({\n key: \"conversation_index\",\n status: conversationIndex.status === \"ok\"\n ? \"ok\"\n : conversationIndex.enabled\n ? \"error\"\n : \"warn\",\n summary: conversationIndex.enabled\n ? `Conversation index backend is ${conversationIndex.status}.`\n : \"Conversation index is disabled.\",\n remediation: conversationIndex.enabled && conversationIndex.status !== \"ok\"\n ? \"Run `openclaw engram rebuild-index` to refresh the conversation index artifacts.\"\n : undefined,\n details: conversationIndex,\n });\n\n const meta = await storage.loadMeta();\n checks.push({\n key: \"maintenance\",\n status: meta.lastExtractionAt || meta.lastConsolidationAt ? \"ok\" : \"warn\",\n summary: meta.lastExtractionAt || meta.lastConsolidationAt\n ? \"Extraction/consolidation metadata is present.\"\n : \"No extraction or consolidation metadata found yet.\",\n remediation: meta.lastExtractionAt || meta.lastConsolidationAt\n ? undefined\n : \"Run a normal agent turn or `openclaw engram consolidate` after seeding memory.\",\n details: meta,\n });\n\n // Provenance coverage (issue #1575 PR 3). Operators need to see the\n // verified/unverified/none distribution grow as extraction backfills.\n // Best-effort: a read failure surfaces as a warn, not an error.\n let provenanceCoverage: ReturnType<typeof summarizeProvenanceCoverage> = {\n counts: { verified: 0, unverified: 0, none: 0 },\n total: 0,\n };\n let provenanceReadOk = true;\n let provenancePartialTiers: string[] = [];\n try {\n // Include all tiers so cold-migrated and archived memories are counted\n // (codex thread PRRT_kwDORJXyws6Ojqz8 — readAllMemories is hot-only).\n // Use allSettled so a real read failure (e.g. locked encrypted store)\n // is surfaced as a partial-read warning, not silently swallowed\n // (codex thread PRRT_kwDORJXyws6OjygQ).\n const [hot, archived, cold] = await Promise.allSettled([\n storage.readAllMemories(),\n storage.readArchivedMemories(),\n storage.readAllColdMemories(),\n ]);\n const all: { frontmatter: { provenance?: string } }[] = [];\n if (hot.status === \"fulfilled\") all.push(...hot.value);\n else provenancePartialTiers.push(\"hot\");\n if (archived.status === \"fulfilled\") all.push(...archived.value);\n else provenancePartialTiers.push(\"archived\");\n if (cold.status === \"fulfilled\") all.push(...cold.value);\n else provenancePartialTiers.push(\"cold\");\n provenanceCoverage = summarizeProvenanceCoverage(all);\n } catch {\n provenanceReadOk = false;\n }\n const pc = provenanceCoverage.counts;\n const totalProvenance = provenanceCoverage.total;\n const provenanceCovered = pc.verified + pc.unverified;\n const partialSuffix = provenancePartialTiers.length > 0\n ? ` (partial: ${provenancePartialTiers.join(\"/\")} tier unreadable)`\n : \"\";\n checks.push({\n key: \"provenance_coverage\",\n status: !provenanceReadOk || provenancePartialTiers.length > 0\n ? \"warn\"\n : totalProvenance === 0\n ? \"warn\"\n : provenanceCovered === 0\n ? \"warn\"\n : \"ok\",\n summary: !provenanceReadOk\n ? \"Could not read memories for provenance coverage.\"\n : totalProvenance === 0\n ? \"No memories found yet — provenance coverage is empty.\"\n : `Provenance coverage: ${pc.verified} verified, ${pc.unverified} unverified, ${pc.none} none (${totalProvenance} total).${partialSuffix}`,\n remediation: !provenanceReadOk\n ? undefined\n : provenancePartialTiers.length > 0\n ? `Some tiers could not be read (${provenancePartialTiers.join(\", \")}). Check storage health and re-run.`\n : provenanceCovered === 0 && totalProvenance > 0\n ? \"New extractions will carry source spans. Existing legacy memories remain `none` until re-extracted.\"\n : undefined,\n details: { provenanceCounts: pc, total: totalProvenance, partialTiers: provenancePartialTiers.length > 0 ? provenancePartialTiers : undefined },\n });\n\n const syncedChunkCount =\n nativeKnowledgeStatus.curatedIncludeSync.activeChunkCount +\n nativeKnowledgeStatus.obsidianSync.activeChunkCount +\n nativeKnowledgeStatus.openclawWorkspaceSync.activeChunkCount;\n const hasSyncState =\n nativeKnowledgeStatus.curatedIncludeSync.exists ||\n nativeKnowledgeStatus.obsidianSync.exists ||\n nativeKnowledgeStatus.openclawWorkspaceSync.exists;\n checks.push({\n key: \"native_knowledge\",\n status: !nativeKnowledgeStatus.enabled\n ? \"warn\"\n : hasSyncState\n ? \"ok\"\n : \"warn\",\n summary: !nativeKnowledgeStatus.enabled\n ? \"Native knowledge sync is disabled.\"\n : hasSyncState\n ? `Native knowledge sync state is present (${syncedChunkCount} active chunks).`\n : \"Native knowledge sync is enabled but no sync state has been written yet.\",\n remediation: !nativeKnowledgeStatus.enabled\n ? \"Enable `nativeKnowledge.enabled` if curated workspace recall should participate in retrieval.\"\n : hasSyncState\n ? undefined\n : \"Run a recall, sync, or setup flow that touches native knowledge sources, then rerun `openclaw engram doctor --json`.\",\n details: nativeKnowledgeStatus,\n });\n\n const agentAccessEnabled = config.agentAccessHttp?.enabled === true;\n // A SecretRef object counts as \"configured\" (issue #757) — resolution\n // happens at service-start time, not at doctor-time. We only check that\n // *something* is set; we never log the resolved value.\n const rawAuthToken = config.agentAccessHttp?.authToken;\n const authTokenConfigured =\n (typeof rawAuthToken === \"string\" && rawAuthToken.length > 0) ||\n (rawAuthToken !== null &&\n typeof rawAuthToken === \"object\" &&\n typeof (rawAuthToken as { source?: unknown }).source === \"string\");\n checks.push({\n key: \"access_http_auth\",\n status: !agentAccessEnabled\n ? \"warn\"\n : authTokenConfigured\n ? \"ok\"\n : \"error\",\n summary: !agentAccessEnabled\n ? \"Agent access HTTP bridge is disabled.\"\n : authTokenConfigured\n ? \"Agent access HTTP bridge has an auth token configured.\"\n : \"Agent access HTTP bridge is enabled without an auth token.\",\n remediation: !agentAccessEnabled\n ? \"Ignore unless you plan to enable the HTTP bridge.\"\n : authTokenConfigured\n ? undefined\n : \"Set `agentAccessHttp.authToken` before exposing the bridge.\",\n });\n\n const warnings = config.fileHygiene?.lintEnabled\n ? await lintWorkspaceFiles({\n workspaceDir: config.workspaceDir,\n paths: config.fileHygiene.lintPaths,\n budgetBytes: config.fileHygiene.lintBudgetBytes,\n warnRatio: config.fileHygiene.lintWarnRatio,\n })\n : [];\n checks.push(summarizeHygieneWarnings(warnings, config.fileHygiene));\n\n // Memory Worth legacy counter audit (issue #560 PR 1).\n // Memories written before #560 have no `mw_success` / `mw_fail` frontmatter\n // fields. That is fully supported — readers treat the absence as a uniform\n // Beta(1,1) prior — but surfacing the count helps operators understand how\n // much history will bootstrap the scoring pipeline landed in later PRs.\n // This is an informational check, never an error.\n checks.push(await summarizeMemoryWorthLegacyCounters(storage));\n\n // Buffer surprise telemetry distribution (issue #563 PR 3).\n // Surfaces recent surprise scores so operators can calibrate the\n // `bufferSurpriseThreshold` from real traffic. Never an error — an empty\n // ledger is the expected state until the flag is turned on.\n checks.push(\n await summarizeBufferSurpriseDistribution(storage, config),\n );\n\n // Consolidation provenance integrity (issue #561 PR 4).\n // Validates that every `derived_from` entry resolves to an on-disk\n // page-version snapshot and every `derived_via` is a known operator.\n // Broken provenance emits warnings with the offending file path — the\n // check is informational (never an error) because a missing snapshot\n // can legitimately occur after log pruning or versioning being disabled\n // retroactively; operators need visibility, not a hard fail. Review\n // feedback (PR #634): the summarizer threads the configured\n // `versioningSidecarDir` into the scan so deployments that override\n // the default `.versions` directory get accurate results instead of\n // false-missing warnings.\n checks.push(await summarizeConsolidationProvenance(storage, config));\n\n // Graph-edge decay maintenance status (issue #681 PR 2/3).\n // Reports whether the periodic decay job has run and surfaces last-run\n // counts. Disabled is \"ok\" with a note; enabled-but-never-run is \"warn\".\n checks.push(await summarizeGraphEdgeDecayStatus(config));\n\n // Tier distribution (issue #686 retention-completion).\n // Shows hot/cold counts, per-status breakdown, and forgotten-memory count.\n // Informational only — never errors, never blocks doctor from returning ok.\n checks.push(await summarizeTierDistribution(options.orchestrator.storage));\n\n // Dreams phases thresholds and last-run timestamps (issue #678 PR 2/4).\n // Surfaces per-phase: enabled status, cadence, threshold values, and the\n // best-available last-run timestamp for each of the three pipeline phases.\n checks.push(await summarizeDreamsPhases(config, storage));\n\n // Security mitigation status (issue #565).\n // Reports whether the cross-namespace budget and anomaly detection\n // mitigations are enabled and surfaces config values for operator review.\n checks.push(summarizeSecurityMitigations(config));\n\n // Observation throughput + judge acceptance rate (issue #685).\n // Surfaces the total verdict count, accept/reject/defer breakdown, and the\n // most recent `observedAt` timestamp from the extraction-judge telemetry\n // ledger. This closes the *(future)* item deferred in\n // `docs/trace-to-primitive.md`. The check is purely informational — it\n // always resolves to `ok`; an empty ledger is the expected cold-install\n // state and is never an error.\n checks.push(await summarizeObservationThroughput(config.memoryDir));\n\n // Namespace maintenance fanout status (issue #1500).\n // Reports per-job+namespace maintenance outcomes (ran/skipped/failed) so\n // operators can verify that dynamic project/team namespaces are being\n // maintained. Informational: never errors on its own — a namespace that has\n // never been maintained is the expected cold-install state.\n const namespaceMaintenanceHealth = await summarizeNamespaceMaintenanceHealth(config);\n checks.push({\n key: \"namespace_maintenance\",\n status: namespaceMaintenanceHealth.totalFailed > 0 ? \"warn\" : \"ok\",\n summary:\n namespaceMaintenanceHealth.totalRan === 0 && namespaceMaintenanceHealth.totalFailed === 0\n ? \"No namespace maintenance recorded yet (expected for a fresh install).\"\n : `${namespaceMaintenanceHealth.totalRan} namespace maintenance run(s)` +\n (namespaceMaintenanceHealth.totalFailed > 0\n ? `, ${namespaceMaintenanceHealth.totalFailed} failure(s) across ${namespaceMaintenanceHealth.jobs.filter((j) => j.failed > 0).length} job(s)`\n : \"\") +\n \".\",\n remediation:\n namespaceMaintenanceHealth.totalFailed > 0\n ? \"Run `remnic namespaces maintenance` for per-namespace details.\"\n : undefined,\n details: namespaceMaintenanceHealth,\n });\n\n // Tombstone non-resurrection invariant (issue #1579). Reports active\n // tombstone count, last append, corrupted-line count, and rebuild\n // staleness so operators can verify the invariant is enforced and know\n // when a rebuild is warranted. Informational: never errors on its own.\n checks.push(await summarizeTombstoneStatus(options.orchestrator.storage));\n\n const summary = checks.reduce(\n (acc, check) => {\n acc[check.status] += 1;\n return acc;\n },\n { ok: 0, warn: 0, error: 0 },\n );\n\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n ok: summary.error === 0,\n summary,\n config: configStatus,\n checks,\n };\n}\n\n/**\n * Categories whose memories are eligible for Memory Worth instrumentation.\n *\n * Memory Worth is a per-fact utility signal: the counters ride on extracted\n * facts whose retrieval outcome can be judged (success/fail) by the feedback\n * pipeline landing in issue #560 PR 3. Procedures, corrections, and other\n * non-fact memory kinds are out of scope — they are not expected to be\n * instrumented, and counting them as \"legacy\" would permanently inflate the\n * legacy bucket and make rollout progress misleading even when every fact\n * memory is instrumented.\n *\n * If a later PR widens Memory Worth to additional categories, extend this set\n * alongside the scoring/increment logic so the doctor audit stays in sync.\n */\nconst MEMORY_WORTH_ELIGIBLE_CATEGORIES: ReadonlySet<MemoryFile[\"frontmatter\"][\"category\"]> =\n new Set([\"fact\"]);\n\n/**\n * Count memories that pre-date the Memory Worth counters introduced in issue\n * #560 — i.e., neither `mw_success` nor `mw_fail` is set on the frontmatter.\n *\n * Only memories whose category is eligible for Memory Worth (see\n * `MEMORY_WORTH_ELIGIBLE_CATEGORIES`) are considered. Procedures, corrections,\n * and other kinds that are not instrumented are excluded entirely — they're\n * neither \"legacy\" nor \"instrumented\" for the purposes of this audit. The\n * total in the returned details reflects only eligible memories.\n *\n * Returned as an `ok` check regardless of count, since legacy memories are\n * fully functional (readers treat missing counters as zero observations). The\n * numbers are informational for operators following the #560 rollout.\n *\n * Exported so unit tests can exercise the classification logic without\n * booting a full orchestrator.\n */\nexport async function summarizeMemoryWorthLegacyCounters(\n storage: StorageManager,\n): Promise<OperatorDoctorCheck> {\n let legacy = 0;\n let instrumented = 0;\n let ineligible = 0;\n try {\n const memories = await storage.readAllMemories();\n for (const memory of memories) {\n if (!MEMORY_WORTH_ELIGIBLE_CATEGORIES.has(memory.frontmatter.category)) {\n ineligible += 1;\n continue;\n }\n const { mw_success, mw_fail } = memory.frontmatter;\n if (mw_success === undefined && mw_fail === undefined) {\n legacy += 1;\n } else {\n instrumented += 1;\n }\n }\n } catch (err) {\n return {\n key: \"memory_worth_legacy\",\n status: \"warn\",\n summary: \"Could not enumerate memories to count Memory Worth instrumentation.\",\n remediation: \"Retry `remnic doctor` after ensuring the memory directory is readable.\",\n details: { error: String(err) },\n };\n }\n\n const total = legacy + instrumented;\n return {\n key: \"memory_worth_legacy\",\n status: \"ok\",\n summary:\n total === 0\n ? \"No Memory Worth–eligible memories on disk yet — counters will populate as facts are extracted.\"\n : `${legacy} of ${total} eligible memories have no Memory Worth counters yet (${instrumented} instrumented).`,\n details: { legacy, instrumented, total, ineligible },\n };\n}\n\n/**\n * Summarize the recent buffer-surprise telemetry distribution for the\n * Doctor report (issue #563 PR 3).\n *\n * Reports mean/median/p90 surprise scores and the triggered-flush rate\n * over the most recent window of ledger rows. An empty ledger is the\n * expected state until `bufferSurpriseTriggerEnabled` is turned on — the\n * check never escalates beyond `ok` / `warn` (ledger unreadable).\n *\n * Exported so tests can exercise the formatting without booting a real\n * orchestrator.\n */\nexport async function summarizeBufferSurpriseDistribution(\n storage: StorageManager,\n config: PluginConfig,\n): Promise<OperatorDoctorCheck> {\n const storageWithLedger = storage as StorageManager & {\n readBufferSurpriseEvents?: (\n opts: { limit?: number },\n ) => Promise<BufferSurpriseEvent[]>;\n };\n\n // Defensive: older StorageManager builds (not yet rebuilt) may lack the\n // reader. Do not fail the entire Doctor run in that case.\n if (typeof storageWithLedger.readBufferSurpriseEvents !== \"function\") {\n return {\n key: \"buffer_surprise_distribution\",\n status: \"ok\",\n summary: \"Buffer-surprise telemetry reader unavailable in this build.\",\n details: { available: false },\n };\n }\n\n try {\n const dist = await reportBufferSurpriseDistribution(\n async (opts) =>\n storageWithLedger.readBufferSurpriseEvents!({ limit: opts.limit }),\n { limit: 200 },\n );\n\n if (dist.count === 0) {\n return {\n key: \"buffer_surprise_distribution\",\n status: \"ok\",\n summary: config.bufferSurpriseTriggerEnabled\n ? \"Surprise trigger is enabled but no telemetry has been recorded yet.\"\n : \"Surprise trigger is disabled; no telemetry expected.\",\n details: {\n enabled: config.bufferSurpriseTriggerEnabled,\n distribution: dist,\n },\n };\n }\n\n const pct = (value: number) => (value * 100).toFixed(1);\n return {\n key: \"buffer_surprise_distribution\",\n status: \"ok\",\n summary: `Recent surprise: mean=${dist.mean.toFixed(3)}, median=${dist.median.toFixed(3)}, p90=${dist.p90.toFixed(3)}, triggered=${pct(dist.triggeredRate)}% over ${dist.count} turns (threshold=${dist.currentThreshold ?? config.bufferSurpriseThreshold}).`,\n details: {\n enabled: config.bufferSurpriseTriggerEnabled,\n distribution: dist,\n },\n };\n } catch (err) {\n return {\n key: \"buffer_surprise_distribution\",\n status: \"warn\",\n summary: \"Could not read buffer-surprise telemetry ledger.\",\n remediation:\n \"Retry `remnic doctor` after ensuring the memory state directory is readable.\",\n details: { error: String(err) },\n };\n }\n}\n\n/**\n * Summarize the consolidation-provenance integrity scan for the doctor\n * report (issue #561 PR 4). Returns an `ok` check when no issues are\n * found, `warn` otherwise. Never returns `error` — a broken provenance\n * pointer is informational because it can legitimately result from log\n * pruning, versioning being disabled retroactively, or operator-driven\n * archive operations.\n *\n * Exported so unit tests can exercise the summarization without booting a\n * full orchestrator.\n */\n\nasync function summarizeGraphEdgeDecayStatus(\n config: Pick<\n PluginConfig,\n \"memoryDir\" | \"graphEdgeDecayEnabled\" | \"graphEdgeDecayCadenceMs\"\n >,\n): Promise<OperatorDoctorCheck> {\n // Lazy import to keep the doctor fast when the feature is disabled.\n const { readGraphEdgeDecayStatus } = await import(\"./maintenance/graph-edge-decay.js\");\n const enabled = config.graphEdgeDecayEnabled === true;\n if (!enabled) {\n return {\n key: \"graph_edge_decay\",\n status: \"ok\",\n summary: \"Graph-edge decay maintenance is disabled (graphEdgeDecayEnabled = false).\",\n remediation: \"Set graphEdgeDecayEnabled = true to opt into the periodic decay job (issue #681).\",\n details: { enabled: false },\n };\n }\n\n const status = await readGraphEdgeDecayStatus(config.memoryDir);\n if (!status) {\n return {\n key: \"graph_edge_decay\",\n status: \"warn\",\n summary: \"Graph-edge decay is enabled but has not run yet (no status file present).\",\n remediation:\n \"Trigger the cron, run `engram.graph_edge_decay_run` via MCP, or wait for the scheduled cadence to fire.\",\n details: { enabled: true, lastRun: null, cadenceMs: config.graphEdgeDecayCadenceMs },\n };\n }\n\n return {\n key: \"graph_edge_decay\",\n status: \"ok\",\n summary:\n `Graph-edge decay last ran at ${status.ranAt} ` +\n `(${status.edgesDecayed}/${status.edgesTotal} edges decayed, ` +\n `${status.edgesBelowVisibilityThreshold} below visibility threshold).`,\n details: {\n enabled: true,\n lastRun: status.ranAt,\n durationMs: status.durationMs,\n edgesTotal: status.edgesTotal,\n edgesDecayed: status.edgesDecayed,\n edgesBelowVisibilityThreshold: status.edgesBelowVisibilityThreshold,\n topDecayedEntities: status.topDecayedEntities,\n cadenceMs: config.graphEdgeDecayCadenceMs,\n },\n };\n}\n\n/**\n * Summarize hot/cold tier distribution for the Doctor report\n * (issue #686 retention-completion).\n *\n * Shows:\n * - hot vs cold memory counts\n * - forgotten-memory count\n * - top per-status breakdown\n * - recent migrations in the last 7 days (from the tier-migration journal)\n * - top demotion reasons from the journal\n *\n * Always returns an `ok` check — this section is informational, never\n * a gate. A missing journal or unreadable corpus is surfaced as a note,\n * not an error.\n *\n * Exported so tests can exercise the summarizer without a full orchestrator.\n */\nexport async function summarizeTierDistribution(\n storage: StorageManager,\n): Promise<OperatorDoctorCheck> {\n try {\n const { summarizeTiers } = await import(\"./maintenance/tier-stats.js\");\n const summary = await summarizeTiers(storage);\n\n // Read recent migration journal entries (last 7 days)\n const storageDir = (storage as unknown as { dir?: string }).dir ?? \"\";\n const journalPath = storageDir.length > 0\n ? path.join(storageDir, \"state\", \"tier-migration-journal.jsonl\")\n : null;\n let recentMigrations = 0;\n const demotionReasons: Record<string, number> = {};\n const sevenDaysAgoMs = Date.now() - 7 * 86_400_000;\n\n if (journalPath) {\n try {\n const { readFile } = await import(\"node:fs/promises\");\n const raw = await readFile(journalPath, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n try {\n const entry = JSON.parse(trimmed) as {\n ts?: string;\n changed?: boolean;\n fromTier?: string;\n toTier?: string;\n reason?: string;\n };\n const tsMs = entry.ts ? Date.parse(entry.ts) : NaN;\n if (Number.isFinite(tsMs) && tsMs >= sevenDaysAgoMs && entry.changed === true) {\n recentMigrations += 1;\n if (entry.fromTier === \"hot\" && entry.toTier === \"cold\" && typeof entry.reason === \"string\") {\n const reason = entry.reason;\n demotionReasons[reason] = (demotionReasons[reason] ?? 0) + 1;\n }\n }\n } catch {\n // Malformed line — skip\n }\n }\n } catch {\n // Journal not present yet — expected on fresh installs\n }\n }\n\n const topDemotionReasons = Object.entries(demotionReasons)\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 5)\n .map(([reason, count]) => ({ reason, count }));\n\n const statusParts = Object.entries(summary.byStatus)\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 6)\n .map(([s, n]) => `${s}: ${n}`)\n .join(\", \");\n\n return {\n key: \"tier_distribution\",\n status: \"ok\",\n summary:\n `Tier distribution: hot=${summary.byTier.hot}, cold=${summary.byTier.cold}` +\n (summary.forgottenCount > 0 ? `, forgotten=${summary.forgottenCount}` : \"\") +\n `. Total: ${summary.total}.` +\n (recentMigrations > 0 ? ` Recent migrations (7d): ${recentMigrations}.` : \"\"),\n details: {\n total: summary.total,\n byTier: summary.byTier,\n byStatus: summary.byStatus,\n forgottenCount: summary.forgottenCount,\n statusSummary: statusParts,\n recentMigrations,\n topDemotionReasons,\n },\n };\n } catch (err) {\n return {\n key: \"tier_distribution\",\n status: \"ok\",\n summary: \"Tier distribution unavailable — could not enumerate memories.\",\n details: { error: String(err) },\n };\n }\n}\n\n/**\n * Dreams phases doctor check (issue #678 PR 2/4).\n *\n * Reports per-phase: enabled status, cadence, threshold values, and last-run\n * timestamp sourced from `meta.json` (the existing maintenance ledger).\n *\n * Last-run mapping (best available in PR 2; PR 3/4 will emit per-phase events):\n * light sleep → `meta.lastExtractionAt` (lifecycle pass runs with extraction)\n * REM → `meta.lastConsolidationAt` (semantic consolidation)\n * deep sleep → latest governance run manifest when present, otherwise null\n */\nexport async function summarizeDreamsPhases(\n config: Pick<PluginConfig, \"memoryDir\" | \"dreamsPhases\">,\n storage: StorageManager = new StorageManager(config.memoryDir),\n): Promise<OperatorDoctorCheck> {\n const phases: DreamsPhasesConfig = config.dreamsPhases;\n\n // Load meta.json for best-available last-run timestamps.\n const meta = await storage.loadMeta();\n\n let deepSleepLastRun: string | null = null;\n let deepSleepLastRunWarning: string | null = null;\n try {\n // Read the latest governance run's manifest from the real on-disk format\n // rather than treating every failure as \"no runs yet\".\n const runsDir = path.join(config.memoryDir, \"state\", \"memory-governance\", \"runs\");\n const runIds = (await readdir(runsDir)).sort().reverse();\n if (runIds.length > 0) {\n const latestRunId = runIds[0];\n const manifestPath = path.join(\n runsDir,\n latestRunId,\n \"manifest.json\",\n );\n const raw = await readFile(manifestPath, \"utf-8\");\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (typeof parsed.createdAt === \"string\" && parsed.createdAt.length > 0) {\n deepSleepLastRun = parsed.createdAt;\n }\n }\n } catch (error) {\n if (!isMissingPathError(error)) {\n deepSleepLastRunWarning = `Could not read latest governance run manifest: ${formatUnknownError(error)}`;\n }\n }\n\n // Build per-phase summary lines for the human-readable `summary` field.\n const phaseLines: string[] = [\n `lightSleep: enabled=${phases.lightSleep.enabled}, cadenceMs=${phases.lightSleep.cadenceMs}, promoteHeat=${phases.lightSleep.promoteHeatThreshold}, staleDecay=${phases.lightSleep.staleDecayThreshold}, archiveDecay=${phases.lightSleep.archiveDecayThreshold}, filterStale=${phases.lightSleep.filterStaleEnabled}, lastRun=${meta.lastExtractionAt ?? \"never\"}`,\n `rem: enabled=${phases.rem.enabled}, cadenceMs=${phases.rem.cadenceMs}, similarity=${phases.rem.similarityThreshold}, minCluster=${phases.rem.minClusterSize}, maxPerRun=${phases.rem.maxPerRun}, minIntervalMs=${phases.rem.minIntervalMs}, lastRun=${meta.lastConsolidationAt ?? \"never\"}`,\n `deepSleep: enabled=${phases.deepSleep.enabled}, cadenceMs=${phases.deepSleep.cadenceMs}, versioning=${phases.deepSleep.versioningEnabled}, versioningMaxPerPage=${phases.deepSleep.versioningMaxPerPage}, lastRun=${deepSleepLastRun ?? \"never\"}`,\n ];\n\n return {\n key: \"dreams_phases\",\n status: deepSleepLastRunWarning ? \"warn\" : \"ok\",\n summary: `Dreams pipeline phases: ${phaseLines.join(\"; \")}${deepSleepLastRunWarning ? `; ${deepSleepLastRunWarning}` : \"\"}`,\n remediation: deepSleepLastRunWarning\n ? \"Inspect state/memory-governance/runs and repair or remove unreadable governance run artifacts.\"\n : undefined,\n details: {\n lightSleep: {\n enabled: phases.lightSleep.enabled,\n cadenceMs: phases.lightSleep.cadenceMs,\n promoteHeatThreshold: phases.lightSleep.promoteHeatThreshold,\n staleDecayThreshold: phases.lightSleep.staleDecayThreshold,\n archiveDecayThreshold: phases.lightSleep.archiveDecayThreshold,\n filterStaleEnabled: phases.lightSleep.filterStaleEnabled,\n lastRun: meta.lastExtractionAt ?? null,\n },\n rem: {\n enabled: phases.rem.enabled,\n cadenceMs: phases.rem.cadenceMs,\n similarityThreshold: phases.rem.similarityThreshold,\n minClusterSize: phases.rem.minClusterSize,\n maxPerRun: phases.rem.maxPerRun,\n minIntervalMs: phases.rem.minIntervalMs,\n lastRun: meta.lastConsolidationAt ?? null,\n },\n deepSleep: {\n enabled: phases.deepSleep.enabled,\n cadenceMs: phases.deepSleep.cadenceMs,\n versioningEnabled: phases.deepSleep.versioningEnabled,\n versioningMaxPerPage: phases.deepSleep.versioningMaxPerPage,\n lastRun: deepSleepLastRun,\n warning: deepSleepLastRunWarning,\n },\n },\n };\n}\n\nfunction summarizeSecurityMitigations(\n config: Pick<\n PluginConfig,\n | \"recallCrossNamespaceBudgetEnabled\"\n | \"recallCrossNamespaceBudgetWindowMs\"\n | \"recallCrossNamespaceBudgetSoftLimit\"\n | \"recallCrossNamespaceBudgetHardLimit\"\n | \"recallAuditAnomalyDetectionEnabled\"\n | \"recallAuditAnomalyWindowMs\"\n | \"recallAuditAnomalyRepeatQueryLimit\"\n | \"recallAuditAnomalyNamespaceWalkLimit\"\n | \"recallAuditAnomalyHighCardinalityLimit\"\n | \"recallAuditAnomalyRapidFireLimit\"\n >,\n): OperatorDoctorCheck {\n const budgetEnabled = config.recallCrossNamespaceBudgetEnabled === true;\n const anomalyEnabled = config.recallAuditAnomalyDetectionEnabled === true;\n\n if (!budgetEnabled && !anomalyEnabled) {\n return {\n key: \"security_mitigations\",\n status: \"warn\",\n summary: \"Memory-extraction mitigations are disabled (cross-namespace budget and anomaly detection off).\",\n remediation: \"Enable recallCrossNamespaceBudgetEnabled and/or recallAuditAnomalyDetectionEnabled for production deployments. See docs/security/memory-extraction-threat-model.md.\",\n details: {\n budgetEnabled: false,\n anomalyDetectionEnabled: false,\n },\n };\n }\n\n const details: Record<string, unknown> = {\n budgetEnabled,\n anomalyDetectionEnabled: anomalyEnabled,\n };\n\n if (budgetEnabled) {\n details.budgetConfig = {\n windowMs: config.recallCrossNamespaceBudgetWindowMs,\n softLimit: config.recallCrossNamespaceBudgetSoftLimit,\n hardLimit: config.recallCrossNamespaceBudgetHardLimit,\n };\n }\n\n if (anomalyEnabled) {\n details.anomalyConfig = {\n windowMs: config.recallAuditAnomalyWindowMs,\n repeatQueryLimit: config.recallAuditAnomalyRepeatQueryLimit,\n namespaceWalkLimit: config.recallAuditAnomalyNamespaceWalkLimit,\n highCardinalityLimit: config.recallAuditAnomalyHighCardinalityLimit,\n rapidFireLimit: config.recallAuditAnomalyRapidFireLimit,\n };\n }\n\n return {\n key: \"security_mitigations\",\n status: \"ok\",\n summary: `Memory-extraction mitigation config enabled: ${budgetEnabled ? \"budget\" : \"\"}${budgetEnabled && anomalyEnabled ? \", \" : \"\"}${anomalyEnabled ? \"anomaly detection\" : \"\"}.`,\n details: { ...details, configOnly: true },\n };\n}\n\n/**\n * Observation throughput check for `remnic doctor` (issue #685).\n *\n * Reads the extraction-judge verdict ledger to surface:\n * - total observations (verdicts) recorded\n * - accept / reject / defer breakdown\n * - most-recent `observedAt` timestamp\n *\n * The check is purely informational (always `ok`): a missing or empty\n * ledger is the expected state on a fresh install and is never an error.\n * This closes the `*(future)*` item deferred in `docs/trace-to-primitive.md`.\n */\nexport async function summarizeObservationThroughput(\n memoryDir: string,\n): Promise<OperatorDoctorCheck> {\n try {\n const stats = await readJudgeVerdictStats(memoryDir);\n if (stats.total === 0) {\n return {\n key: \"observations\",\n status: \"ok\",\n summary: \"No observations recorded yet (extraction-judge telemetry ledger is empty or missing).\",\n details: { total: 0, accept: 0, reject: 0, defer: 0, lastObservedAt: null },\n };\n }\n const acceptPct = ((stats.accept / stats.total) * 100).toFixed(1);\n const rejectPct = ((stats.reject / stats.total) * 100).toFixed(1);\n const deferPct = ((stats.defer / stats.total) * 100).toFixed(1);\n return {\n key: \"observations\",\n status: \"ok\",\n summary: `${stats.total} observations recorded: accept=${acceptPct}%, reject=${rejectPct}%, defer=${deferPct}%. Last observed: ${stats.lastTs ?? \"unknown\"}.`,\n details: {\n total: stats.total,\n accept: stats.accept,\n reject: stats.reject,\n defer: stats.defer,\n deferCapTriggered: stats.deferCapTriggered,\n deferRate: stats.deferRate,\n meanElapsedMs: stats.meanElapsedMs,\n firstObservedAt: stats.firstTs ?? null,\n lastObservedAt: stats.lastTs ?? null,\n },\n };\n } catch (err) {\n return {\n key: \"observations\",\n status: \"warn\",\n summary: \"Could not read observation telemetry ledger.\",\n remediation: \"Retry `remnic doctor` after ensuring the memory state directory is readable.\",\n details: { error: String(err) },\n };\n }\n}\n\n/**\n * Tombstone non-resurrection invariant status for `remnic doctor`\n * (issue #1579).\n *\n * Reports:\n * - active tombstone count (excluding revoked)\n * - revoked count (re-allowed via the review queue)\n * - last append timestamp\n * - corrupted-line count (skipped, not crashed — rule 34/18)\n * - rebuild staleness (whether the in-memory index loaded cleanly)\n *\n * Always informational: a disabled or empty tombstone store is the expected\n * cold-install state and is never an error. A non-zero corrupted-line count\n * surfaces as `warn` so operators know a rebuild (`remnic doctor\n * --rebuild-tombstones`) will repair the log.\n */\nexport async function summarizeTombstoneStatus(\n storage: StorageManager,\n): Promise<OperatorDoctorCheck> {\n try {\n const stats = await storage.getTombstoneStats();\n if (stats === null) {\n return {\n key: \"tombstones\",\n status: \"ok\",\n summary: \"Tombstone non-resurrection invariant is disabled (tombstonesEnabled=false).\",\n details: { enabled: false },\n };\n }\n const corrupted = stats.corruptedLines > 0;\n const parts = [\n `${stats.count} active tombstone(s)`,\n ...(stats.revoked > 0 ? [`${stats.revoked} revoked`] : []),\n ];\n if (stats.lastAppendAt) {\n parts.push(`last append ${stats.lastAppendAt}`);\n }\n if (corrupted) {\n parts.push(`${stats.corruptedLines} corrupted line(s) skipped`);\n }\n return {\n key: \"tombstones\",\n status: corrupted ? \"warn\" : \"ok\",\n summary:\n `Tombstone invariant enabled. ${parts.join(\", \")}. ` +\n (corrupted\n ? \"Run `remnic doctor --rebuild-tombstones` to repair the log.\"\n : \"Re-observation of retired facts is blocked at the storage chokepoint.\"),\n remediation: corrupted\n ? \"Rebuild the tombstone log from retired memories on disk.\"\n : undefined,\n details: {\n enabled: true,\n count: stats.count,\n revoked: stats.revoked,\n lastAppendAt: stats.lastAppendAt,\n corruptedLines: stats.corruptedLines,\n loaded: stats.loaded,\n },\n };\n } catch (err) {\n return {\n key: \"tombstones\",\n status: \"warn\",\n summary: \"Could not read tombstone store stats.\",\n remediation: \"Ensure the memory state directory is readable and rerun `remnic doctor`.\",\n details: { error: String(err) },\n };\n }\n}\n\nexport async function summarizeConsolidationProvenance(\n storage: StorageManager,\n config: Pick<PluginConfig, \"memoryDir\"> & { versioningSidecarDir?: string },\n): Promise<OperatorDoctorCheck> {\n let report: ConsolidationProvenanceReport;\n try {\n report = await runConsolidationProvenanceCheck({\n storage,\n memoryDir: config.memoryDir,\n // Honor the configured sidecar directory (PR #634 review): when an\n // operator overrides `versioningSidecarDir`, the default `.versions`\n // would point at the wrong location and every entry would report as\n // missing. Undefined falls back to the helper's default.\n sidecarDir: config.versioningSidecarDir,\n });\n } catch (err) {\n return {\n key: \"consolidation_provenance\",\n status: \"warn\",\n summary: \"Could not run consolidation-provenance integrity check.\",\n remediation: \"Ensure the memory directory is readable and rerun `remnic doctor`.\",\n details: { error: String(err) },\n };\n }\n\n if (report.issues.length === 0) {\n return {\n key: \"consolidation_provenance\",\n status: \"ok\",\n summary:\n report.withProvenance === 0\n ? \"No consolidation-provenance memories on disk yet.\"\n : `${report.withProvenance} consolidation-provenance memories verified (no broken references).`,\n details: report,\n };\n }\n\n return {\n key: \"consolidation_provenance\",\n status: \"warn\",\n summary: `${report.issues.length} consolidation-provenance integrity issue(s) detected across ${report.withProvenance} memories with provenance frontmatter.`,\n remediation:\n \"Broken pointers are informational. Inspect flagged memories, and if they should resolve, re-snapshot via a consolidation pass or accept pruning.\",\n details: report,\n };\n}\n\nfunction getMemoryAgeBand(memory: MemoryFile, now: Date): string {\n const created = Date.parse(memory.frontmatter.created ?? \"\");\n if (!Number.isFinite(created)) return \"unknown\";\n const ageDays = Math.max(0, Math.floor((now.getTime() - created) / 86_400_000));\n if (ageDays < 7) return \"0_6d\";\n if (ageDays < 30) return \"7_29d\";\n if (ageDays < 90) return \"30_89d\";\n return \"90d_plus\";\n}\n\nasync function dirSize(targetPath: string): Promise<number> {\n try {\n const info = await stat(targetPath);\n if (info.isFile()) return info.size;\n if (!info.isDirectory()) return 0;\n } catch {\n return 0;\n }\n\n let total = 0;\n let entries;\n try {\n entries = await readdir(targetPath, { withFileTypes: true });\n } catch {\n return 0;\n }\n for (const entry of entries) {\n total += await dirSize(path.join(targetPath, entry.name));\n }\n return total;\n}\n\nasync function summarizeStorageFootprint(memoryDir: string): Promise<{ bytes: number; byTopLevel: Record<string, number> }> {\n const topLevel = [\n \"facts\",\n \"entities\",\n \"questions\",\n \"corrections\",\n \"artifacts\",\n \"state\",\n \"identity\",\n \"namespaces\",\n \"summaries\",\n \"profile.md\",\n ];\n const byTopLevel: Record<string, number> = {};\n let bytes = 0;\n for (const name of topLevel) {\n const size = await dirSize(path.join(memoryDir, name));\n if (size > 0) {\n byTopLevel[name] = size;\n bytes += size;\n }\n }\n return { bytes, byTopLevel };\n}\n\nexport async function runOperatorInventory(options: OperatorInventoryOptions): Promise<OperatorInventoryReport> {\n const now = options.now ?? new Date();\n const config = options.orchestrator.config;\n const namespaceEntries = await listNamespaces({ config });\n const uniqueRootEntries = new Map<string, { namespace: string; rootDir: string }>();\n for (const entry of namespaceEntries) {\n if (!uniqueRootEntries.has(entry.rootDir)) {\n uniqueRootEntries.set(entry.rootDir, { namespace: entry.namespace, rootDir: entry.rootDir });\n }\n }\n const categories: Record<string, number> = {};\n const statuses: Record<string, number> = {};\n const ageBands: Record<string, number> = {\n \"0_6d\": 0,\n \"7_29d\": 0,\n \"30_89d\": 0,\n \"90d_plus\": 0,\n unknown: 0,\n };\n const namespaces: OperatorInventoryNamespaceSummary[] = [];\n let totalMemories = 0;\n let totalEntities = 0;\n let archived = 0;\n let pendingReview = 0;\n let quarantined = 0;\n let rejected = 0;\n\n for (const entry of uniqueRootEntries.values()) {\n const storage = new StorageManager(entry.rootDir);\n const memories = await storage.readAllMemories();\n const entities = await storage.readAllEntityFiles();\n namespaces.push({\n namespace: entry.namespace,\n memoryCount: memories.length,\n entityCount: entities.length,\n });\n totalMemories += memories.length;\n totalEntities += entities.length;\n for (const memory of memories) {\n const category = memory.frontmatter.category;\n categories[category] = (categories[category] ?? 0) + 1;\n const status = memory.frontmatter.status ?? \"active\";\n statuses[status] = (statuses[status] ?? 0) + 1;\n ageBands[getMemoryAgeBand(memory, now)] += 1;\n if (status === \"archived\") archived += 1;\n if (status === \"pending_review\") pendingReview += 1;\n if (status === \"quarantined\") quarantined += 1;\n if (status === \"rejected\") rejected += 1;\n }\n }\n\n const defaultStorage = new StorageManager(config.memoryDir);\n const profile = await defaultStorage.readProfile();\n const footprint = await summarizeStorageFootprint(config.memoryDir);\n const reviewRunId = (await listMemoryGovernanceRuns(config.memoryDir))[0];\n let reviewQueue = 0;\n if (reviewRunId) {\n try {\n reviewQueue = (await readMemoryGovernanceRunArtifact(config.memoryDir, reviewRunId)).reviewQueue.length;\n } catch {\n reviewQueue = 0;\n }\n }\n const conversationIndex = await options.orchestrator.getConversationIndexHealth();\n const nativeKnowledgeStatus = await summarizeNativeKnowledgeStatus(config);\n\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n memoryDir: config.memoryDir,\n totals: {\n memories: totalMemories,\n entities: totalEntities,\n namespaces: namespaceEntries.length,\n reviewQueue,\n storageBytes: footprint.bytes,\n },\n categories,\n statuses,\n namespaces,\n ageBands,\n profile: {\n exists: profile.length > 0,\n chars: profile.length,\n lines: profile.length > 0 ? profile.split(\"\\n\").length : 0,\n },\n storageFootprint: footprint,\n archivePressure: {\n archived,\n pendingReview,\n quarantined,\n rejected,\n },\n conversationIndex: {\n enabled: conversationIndex.enabled,\n backend: conversationIndex.backend,\n status: conversationIndex.status,\n chunkDocCount: conversationIndex.chunkDocCount,\n lastUpdateAt: conversationIndex.lastUpdateAt,\n },\n nativeKnowledge: {\n enabled: nativeKnowledgeStatus.enabled,\n curatedIncludeSync: nativeKnowledgeStatus.curatedIncludeSync,\n obsidianSync: nativeKnowledgeStatus.obsidianSync,\n openclawWorkspaceSync: nativeKnowledgeStatus.openclawWorkspaceSync,\n },\n };\n}\n\nexport async function runBenchmarkRecall(options: BenchmarkRecallOptions): Promise<BenchmarkRecallReport> {\n const now = options.now ?? new Date();\n const status = await getEvalHarnessStatus({\n memoryDir: options.config.memoryDir,\n evalStoreDir: options.config.evalStoreDir,\n enabled: options.config.evalHarnessEnabled,\n shadowModeEnabled: options.config.evalShadowModeEnabled,\n baselineSnapshotsEnabled: options.config.benchmarkBaselineSnapshotsEnabled,\n memoryRedTeamBenchEnabled: options.config.memoryRedTeamBenchEnabled,\n });\n\n if (options.createSnapshot && options.snapshotId) {\n const snapshot = await createEvalBaselineSnapshot({\n memoryDir: options.config.memoryDir,\n evalStoreDir: options.config.evalStoreDir,\n baselineSnapshotsEnabled: options.config.benchmarkBaselineSnapshotsEnabled,\n snapshotId: options.snapshotId,\n notes: options.snapshotNotes,\n gitRef: options.gitRef,\n createdAt: options.createdAt,\n });\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n mode: \"snapshot\",\n status,\n snapshot: {\n targetPath: snapshot.targetPath,\n snapshotId: snapshot.snapshot.snapshotId,\n },\n };\n }\n\n if (options.baseEvalStoreDir && options.candidateEvalStoreDir) {\n const ciGate = await runEvalBenchmarkCiGate({\n baseEvalStoreDir: options.baseEvalStoreDir,\n candidateEvalStoreDir: options.candidateEvalStoreDir,\n });\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n mode: \"ci-gate\",\n status,\n ciGate,\n };\n }\n\n if (options.snapshotId) {\n const baselineReport = await runEvalBaselineDeltaReport({\n memoryDir: options.config.memoryDir,\n evalStoreDir: options.config.evalStoreDir,\n benchmarkDeltaReporterEnabled: options.config.benchmarkDeltaReporterEnabled,\n snapshotId: options.snapshotId,\n });\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n mode: \"baseline-report\",\n status,\n baselineReport,\n };\n }\n\n if (options.validatePath) {\n const validate = await validateEvalBenchmarkPack(options.validatePath, {\n memoryRedTeamBenchEnabled: options.config.memoryRedTeamBenchEnabled,\n });\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n mode: \"validate\",\n status,\n validate,\n };\n }\n\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n mode: \"status\",\n status,\n };\n}\n\nexport async function runOperatorRepair(options: OperatorRepairOptions): Promise<OperatorRepairReport> {\n const now = options.now ?? new Date();\n const dryRun = options.dryRun === true || options.apply !== true;\n const sessionCheck = await analyzeSessionIntegrity({ memoryDir: options.config.memoryDir });\n const sessionRepairPlan = planSessionRepair({\n report: sessionCheck,\n dryRun,\n allowSessionFileRepair: options.allowSessionFileRepair,\n sessionFilesDir: options.sessionFilesDir,\n });\n const sessionRepairApply = await applySessionRepair({\n plan: sessionRepairPlan,\n });\n const graphHealth = await analyzeGraphHealth(options.config.memoryDir, {\n entityGraphEnabled: options.config.entityGraphEnabled,\n timeGraphEnabled: options.config.timeGraphEnabled,\n causalGraphEnabled: options.config.causalGraphEnabled,\n includeRepairGuidance: true,\n });\n return {\n schemaVersion: 1,\n generatedAt: now.toISOString(),\n dryRun,\n sessionCheck,\n sessionRepairPlan,\n sessionRepairApply,\n graphHealth,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,aAAa,mBAAmB;AACzC,SAAS,QAAQ,OAAO,UAAU,SAAS,MAAM,QAAQ,iBAAiB;AAkD1E,IAAM,6BAA6B,CAAC,mBAAmB,iBAAiB;AAExE,SAAS,yBAAyB,KAAmE;AACnG,QAAM,UACJ,IAAI,SAAS,KAAK,OAAO,IAAI,SAAS,MAAM,YAAY,CAAC,MAAM,QAAQ,IAAI,SAAS,CAAC,IAChF,IAAI,SAAS,IACd;AACN,QAAM,UACJ,WAAW,QAAQ,SAAS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R,CAAC;AACD,QAAM,cAAc,MAAM,mBAAmB,QAAQ,OAAO,WAAW;AAAA,IACrE,oBAAoB,QAAQ,OAAO;AAAA,IACnC,kBAAkB,QAAQ,OAAO;AAAA,IACjC,oBAAoB,QAAQ,OAAO;AAAA,IACnC,uBAAuB;AAAA,EACzB,CAAC;AACD,SAAO;AAAA,IACL,eAAe;AAAA,IACf,aAAa,IAAI,YAAY;AAAA,IAC7B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["readFile"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph.ts"],"sourcesContent":["/**\n * Multi-Graph Memory (MAGMA/SYNAPSE-inspired, v8.2)\n *\n * Maintains three typed edge graphs:\n * entity.jsonl — memories sharing a named entity (entityRef)\n * time.jsonl — consecutive memories in the same thread/session\n * causal.jsonl — memories linked by causal language heuristics\n *\n * Stored under `<memoryDir>/state/graphs/`.\n * All writes are fail-open: errors are caught/logged, never thrown.\n */\n\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { readEdgeConfidence } from \"./graph-edge-reinforcement.js\";\nimport { emitGraphEvent } from \"./graph-events.js\";\n\nexport type GraphType = \"entity\" | \"time\" | \"causal\";\n\nexport interface GraphEdge {\n from: string; // relative memory path (e.g. \"facts/2026-02-22/abc.md\")\n to: string; // relative memory path\n type: GraphType;\n weight: number; // 1.0 default, decay applied during traversal\n label: string; // entity name, threadId, or matched causal phrase\n ts: string; // ISO timestamp of edge creation\n\n // Issue #681 — edge confidence + reinforcement (PR 1/3: schema + primitive only).\n // Both fields are optional so existing edges without confidence still validate.\n // Treat a missing `confidence` as 1.0 (legacy behavior) at read sites.\n // PR 2/3 wires the maintenance decay job; PR 3/3 weights PageRank traversal by confidence.\n confidence?: number; // [0, 1]; missing = 1.0\n lastReinforcedAt?: string; // ISO timestamp of most recent reinforcement\n}\n\nexport interface GraphConfig {\n multiGraphMemoryEnabled: boolean;\n entityGraphEnabled: boolean;\n timeGraphEnabled: boolean;\n causalGraphEnabled: boolean;\n maxGraphTraversalSteps: number;\n graphActivationDecay: number;\n maxEntityGraphEdgesPerMemory: number;\n graphLateralInhibitionEnabled: boolean;\n graphLateralInhibitionBeta: number;\n graphLateralInhibitionTopM: number;\n /**\n * Issue #681 PR 3/3 — minimum edge confidence required for traversal.\n * Edges with confidence below this floor are pruned. Legacy edges\n * (no `confidence` field) are treated as 1.0 and always pass.\n * Range `[0, 1]`. Default 0.2.\n */\n graphTraversalConfidenceFloor: number;\n /**\n * Issue #681 PR 3/3 — number of PageRank-style refinement iterations\n * applied on top of BFS activation. Set to 0 to disable refinement\n * and return raw BFS scores. Default 8.\n */\n graphTraversalPageRankIterations: number;\n}\n\n/** Default minimum edge confidence required for traversal (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR = 0.2;\n/** Default PageRank-style refinement iteration count (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_PAGERANK_ITERATIONS = 8;\n\n// Causal signal phrases — order matters (most specific first)\nexport const CAUSAL_PHRASES = [\"as a result\", \"led to\", \"because of\", \"therefore\", \"caused\", \"because\"];\n\nexport function graphsDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"graphs\");\n}\n\nexport function graphFilePath(memoryDir: string, type: GraphType): string {\n return path.join(graphsDir(memoryDir), `${type}.jsonl`);\n}\n\nexport async function ensureGraphsDir(memoryDir: string): Promise<void> {\n await mkdir(graphsDir(memoryDir), { recursive: true });\n}\n\n// ---------------------------------------------------------------------------\n// Per-graph-file write lock (gotcha #40 promise-chain pattern).\n//\n// Both the append path (`appendEdge`) and the rewrite path used by the\n// decay maintenance job must serialize on the same lock keyed by the\n// JSONL file path. Without this, an extraction can append a new edge\n// between the decay job's read-snapshot and rewrite, silently dropping\n// the appended edge during active traffic (issue #729 / Codex P1).\n// ---------------------------------------------------------------------------\nconst graphWriteLocks = new Map<string, Promise<void>>();\n\n/**\n * Run `fn` while holding the write lock for the given graph JSONL file.\n *\n * The lock is keyed by absolute file path so concurrent writes to\n * different graph types proceed independently. The chain recovers from\n * rejection (gotcha #40) so a single I/O failure does not poison all\n * future writers, but the original error is still surfaced to the\n * caller of `withGraphWriteLock`.\n */\nexport function withGraphWriteLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n const prev = graphWriteLocks.get(filePath) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n graphWriteLocks.set(\n filePath,\n next.then(\n () => undefined,\n () => undefined\n )\n );\n return next;\n}\n\nexport async function appendEdge(memoryDir: string, edge: GraphEdge): Promise<void> {\n await ensureGraphsDir(memoryDir);\n const filePath = graphFilePath(memoryDir, edge.type);\n const line = `${JSON.stringify(edge)}\\n`;\n await withGraphWriteLock(filePath, async () => {\n await appendFile(filePath, line, \"utf8\");\n });\n // Emit edge-added event for SSE subscribers (issue #691 PR 5/5).\n // Fail-open: emitGraphEvent catches listener errors so a bad SSE client\n // can never surface into the extraction pipeline.\n emitGraphEvent(memoryDir, \"edge-added\", {\n source: edge.from,\n target: edge.to,\n kind: edge.type,\n weight: edge.weight,\n label: edge.label,\n confidence: typeof edge.confidence === \"number\" ? edge.confidence : 1.0,\n });\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return typeof err === \"object\" && err !== null && \"code\" in err;\n}\n\nfunction parseEdgesJsonl(raw: string, expectedType: GraphType): GraphEdge[] {\n const edges: GraphEdge[] = [];\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (isValidGraphEdge(parsed, expectedType)) {\n edges.push(parsed);\n }\n } catch {\n // skip corrupt lines — fail-open for partial JSONL recovery\n }\n }\n return edges;\n}\n\n/**\n * Read all edges of a given type from the JSONL file.\n * Returns [] if the file doesn't exist or any read error occurs (fail-open).\n *\n * Production traversal callers (recall/PageRank) depend on this fail-open\n * posture so a temporarily missing or unreadable graph file never blocks\n * a recall. Maintenance jobs that need to distinguish ENOENT from real\n * I/O failures must use {@link readEdgesStrict} instead.\n */\nexport async function readEdges(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch {\n return [];\n }\n}\n\n/**\n * Same as {@link readEdges} but only swallows `ENOENT`; all other read\n * errors (`EACCES`, `EIO`, …) are propagated. Used by the graph-edge\n * decay maintenance job so I/O outages surface as a failed run instead\n * of being silently reported as \"no edges to decay\" (issue #729 /\n * Codex P1, line 120).\n */\nexport async function readEdgesStrict(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n\n/**\n * Read edges from all enabled graph types.\n */\nexport async function readAllEdges(\n memoryDir: string,\n config: Pick<GraphConfig, \"entityGraphEnabled\" | \"timeGraphEnabled\" | \"causalGraphEnabled\">\n): Promise<GraphEdge[]> {\n const parts: GraphEdge[][] = await Promise.all([\n config.entityGraphEnabled ? readEdges(memoryDir, \"entity\") : Promise.resolve([]),\n config.timeGraphEnabled ? readEdges(memoryDir, \"time\") : Promise.resolve([]),\n config.causalGraphEnabled ? readEdges(memoryDir, \"causal\") : Promise.resolve([]),\n ]);\n return parts.flat();\n}\n\nexport interface GraphHealthFileStats {\n type: GraphType;\n filePath: string;\n exists: boolean;\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n}\n\nexport interface GraphHealthReport {\n generatedAt: string;\n enabledTypes: GraphType[];\n totals: {\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n };\n files: GraphHealthFileStats[];\n repairGuidance?: string[];\n}\n\nfunction isValidGraphEdge(raw: unknown, expectedType: GraphType): raw is GraphEdge {\n if (!raw || typeof raw !== \"object\") return false;\n const edge = raw as Record<string, unknown>;\n return (\n edge.type === expectedType &&\n typeof edge.from === \"string\" &&\n edge.from.length > 0 &&\n typeof edge.to === \"string\" &&\n edge.to.length > 0 &&\n typeof edge.weight === \"number\" &&\n Number.isFinite(edge.weight) &&\n typeof edge.label === \"string\" &&\n typeof edge.ts === \"string\"\n );\n}\n\nexport async function analyzeGraphHealth(\n memoryDir: string,\n options?: {\n entityGraphEnabled?: boolean;\n timeGraphEnabled?: boolean;\n causalGraphEnabled?: boolean;\n includeRepairGuidance?: boolean;\n }\n): Promise<GraphHealthReport> {\n const enabledTypes: GraphType[] = [];\n if (options?.entityGraphEnabled !== false) enabledTypes.push(\"entity\");\n if (options?.timeGraphEnabled !== false) enabledTypes.push(\"time\");\n if (options?.causalGraphEnabled !== false) enabledTypes.push(\"causal\");\n\n const files: GraphHealthFileStats[] = [];\n const globalNodes = new Set<string>();\n\n for (const type of enabledTypes) {\n const filePath = graphFilePath(memoryDir, type);\n let exists = true;\n let totalLines = 0;\n let validEdges = 0;\n let corruptLines = 0;\n const nodes = new Set<string>();\n\n try {\n const raw = await readFile(filePath, \"utf8\");\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n totalLines += 1;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (!isValidGraphEdge(parsed, type)) {\n corruptLines += 1;\n continue;\n }\n validEdges += 1;\n nodes.add(parsed.from);\n nodes.add(parsed.to);\n globalNodes.add(parsed.from);\n globalNodes.add(parsed.to);\n } catch {\n corruptLines += 1;\n }\n }\n } catch {\n exists = false;\n }\n\n files.push({\n type,\n filePath,\n exists,\n totalLines,\n validEdges,\n corruptLines,\n uniqueNodes: nodes.size,\n });\n }\n\n const totals = files.reduce(\n (acc, item) => {\n acc.totalLines += item.totalLines;\n acc.validEdges += item.validEdges;\n acc.corruptLines += item.corruptLines;\n return acc;\n },\n {\n totalLines: 0,\n validEdges: 0,\n corruptLines: 0,\n uniqueNodes: globalNodes.size,\n }\n );\n totals.uniqueNodes = globalNodes.size;\n\n const report: GraphHealthReport = {\n generatedAt: new Date().toISOString(),\n enabledTypes,\n totals,\n files,\n };\n\n if (options?.includeRepairGuidance === true) {\n const guidance: string[] = [];\n if (totals.corruptLines > 0) {\n guidance.push(\n \"Corrupt graph lines detected: back up memory/state/graphs, then rebuild graphs from clean memory replay/extraction runs.\"\n );\n }\n if (totals.validEdges === 0) {\n guidance.push(\n \"No valid edges detected yet: run normal extraction traffic (or replay ingestion) to seed graph files.\"\n );\n }\n if (guidance.length > 0) report.repairGuidance = guidance;\n }\n\n return report;\n}\n\n/**\n * Detect causal signal phrases in text. Returns the first matched phrase, or null.\n */\nexport function detectCausalPhrase(text: string): string | null {\n const lower = text.toLowerCase();\n for (const phrase of CAUSAL_PHRASES) {\n if (lower.includes(phrase)) return phrase;\n }\n return null;\n}\n\n/**\n * GraphIndex — builds and updates the three memory graphs.\n *\n * Usage (orchestrator):\n * this.graphIndex = new GraphIndex(config.memoryDir, config);\n *\n * // After each memory write:\n * await this.graphIndex.onMemoryWritten(memoryPath, frontmatter, threadId, recentInThread);\n */\nexport class GraphIndex {\n private readonly memoryDir: string;\n private readonly cfg: GraphConfig;\n\n // Cache for readAllEdges() result. With 30k+ entity edges (6 MB JSONL) the\n // file read + JSON parse takes 2-4 s per call. This instance-level cache\n // eliminates that overhead on every spreadingActivation() call; it is\n // invalidated (set to null) in onMemoryWritten() so new edges appear promptly.\n private edgeCache: { allEdges: GraphEdge[]; loadedAt: number } | null = null;\n private static readonly EDGE_CACHE_TTL_MS = 300_000; // 5 minutes\n\n constructor(memoryDir: string, cfg: GraphConfig) {\n this.memoryDir = memoryDir;\n this.cfg = cfg;\n }\n\n /** Clear the edge cache so the next spreadingActivation() re-reads from disk.\n * Call after any code path that appends edges outside of onMemoryWritten(). */\n invalidateEdgeCache(): void {\n this.edgeCache = null;\n }\n\n private async loadEdgesCached(): Promise<GraphEdge[]> {\n if (this.edgeCache && Date.now() - this.edgeCache.loadedAt < GraphIndex.EDGE_CACHE_TTL_MS) {\n return this.edgeCache.allEdges;\n }\n const allEdges = await readAllEdges(this.memoryDir, {\n entityGraphEnabled: this.cfg.entityGraphEnabled,\n timeGraphEnabled: this.cfg.timeGraphEnabled,\n causalGraphEnabled: this.cfg.causalGraphEnabled,\n });\n this.edgeCache = { allEdges, loadedAt: Date.now() };\n return allEdges;\n }\n\n /**\n * Called after a memory is written to disk.\n *\n * @param memoryPath - relative path from memoryDir (e.g. \"facts/2026-02-22/abc.md\")\n * @param entityRef - entityRef frontmatter field (if any)\n * @param content - full memory text (for causal detection)\n * @param created - ISO timestamp of this memory\n * @param threadId - current thread ID (for time graph)\n * @param recentInThread - paths of the N most-recent memories in this thread (for time graph)\n * @param entitySiblings - paths of other memories that share the same entityRef (for entity graph)\n */\n async onMemoryWritten(opts: {\n memoryPath: string;\n entityRef?: string;\n content: string;\n created: string;\n threadId?: string;\n recentInThread?: string[];\n entitySiblings?: string[];\n causalPredecessor?: string;\n /**\n * Optional frozen gate overrides (from GraphConstructionCapabilitySet).\n * When provided, these take precedence over `this.cfg` so the caller's\n * operation-scoped snapshot is the single source of truth (#1566).\n */\n graphCapsOverride?: {\n entityGraph: boolean;\n timeGraph: boolean;\n causalGraph: boolean;\n multiGraphMemory: boolean;\n };\n }): Promise<void> {\n const g = opts.graphCapsOverride;\n const multiGraphOn = g ? g.multiGraphMemory : this.cfg.multiGraphMemoryEnabled;\n if (!multiGraphOn) return;\n const entityOn = g ? g.entityGraph : this.cfg.entityGraphEnabled;\n const timeOn = g ? g.timeGraph : this.cfg.timeGraphEnabled;\n const causalOn = g ? g.causalGraph : this.cfg.causalGraphEnabled;\n const ts = new Date().toISOString();\n\n try {\n // Entity graph\n if (entityOn && opts.entityRef && opts.entitySiblings?.length) {\n const siblings = opts.entitySiblings.slice(0, this.cfg.maxEntityGraphEdgesPerMemory);\n for (const sibling of siblings) {\n await appendEdge(this.memoryDir, {\n from: opts.memoryPath,\n to: sibling,\n type: \"entity\",\n weight: 1.0,\n label: opts.entityRef,\n ts,\n });\n }\n }\n\n // Time graph — link to most recent memory in same thread\n if (timeOn && opts.threadId && opts.recentInThread?.length) {\n const predecessor = opts.recentInThread[opts.recentInThread.length - 1];\n if (predecessor && predecessor !== opts.memoryPath) {\n await appendEdge(this.memoryDir, {\n from: predecessor,\n to: opts.memoryPath,\n type: \"time\",\n weight: 1.0,\n label: opts.threadId,\n ts,\n });\n }\n }\n\n // Causal graph\n if (causalOn && opts.causalPredecessor) {\n const phrase = detectCausalPhrase(opts.content);\n if (phrase) {\n await appendEdge(this.memoryDir, {\n from: opts.causalPredecessor,\n to: opts.memoryPath,\n type: \"causal\",\n weight: 1.0,\n label: phrase,\n ts,\n });\n }\n }\n } catch (err) {\n // Fail-open: graph write errors must never surface to caller\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] onMemoryWritten error: ${err}`);\n } finally {\n // Invalidate edge cache so spreadingActivation() picks up new edges.\n // In `finally` so the cache is cleared even on partial write failure.\n this.edgeCache = null;\n }\n }\n\n /**\n * Spreading activation BFS (SYNAPSE-inspired).\n *\n * Starting from `seeds`, traverse the combined graph for up to `maxSteps` hops.\n * Each candidate gets an activation score = edge.weight × edgeConfidence × decay^hop.\n *\n * Issue #681 PR 3/3 — confidence-aware traversal:\n * - Each edge's `weight` is multiplied by its `confidence` (legacy edges\n * missing `confidence` are treated as 1.0, preserving prior behavior).\n * - Edges with `confidence < graphTraversalConfidenceFloor` are pruned and\n * contribute neither activation nor downstream neighbors.\n * - When `graphTraversalPageRankIterations > 0`, an additional PageRank-\n * style refinement pass redistributes activation along confidence-weighted\n * edges, sharpening the ranking among multi-hop candidates.\n * - Per-result provenance includes the highest-confidence edge that landed\n * on each candidate, so the X-ray surface can attribute pruning and\n * ranking decisions back to specific edges.\n *\n * @param seeds - initial memory paths to expand from (e.g. QMD top results)\n * @param maxSteps - max BFS hops (from config: maxGraphTraversalSteps)\n * @returns Array of {path, score, edgeConfidence, ...} sorted descending, not including seed paths\n */\n async spreadingActivation(\n seeds: string[],\n maxSteps?: number,\n opts?: {\n /**\n * Issue #681 — when `true`, bypasses the configured\n * `graphTraversalConfidenceFloor` and includes low-confidence\n * edges in traversal. Equivalent to forcing the floor to `0`.\n * Default `false` (floor from config is applied).\n */\n includeLowConfidence?: boolean;\n /** Absolute deadline in ms-since-epoch for post-retrieval assembly. */\n deadlineAtMs?: number;\n }\n ): Promise<\n Array<{\n path: string;\n score: number;\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n /**\n * Confidence of the edge that produced this candidate's recorded\n * provenance (the strongest edge along the chosen entry path).\n * In `[0, 1]`. Legacy edges without `confidence` surface as 1.0.\n */\n edgeConfidence: number;\n }>\n > {\n if (!this.cfg.multiGraphMemoryEnabled) return [];\n const steps = maxSteps ?? this.cfg.maxGraphTraversalSteps;\n const decay = this.cfg.graphActivationDecay;\n // When `includeLowConfidence` is set, use floor=0 so all edges\n // participate in traversal regardless of their decay state.\n // Otherwise clamp the configured floor into [0, 1] so misconfiguration\n // cannot (a) admit edges with negative confidence or (b) reject every\n // edge.\n const floor =\n opts?.includeLowConfidence === true ? 0 : clampConfidenceFloor(this.cfg.graphTraversalConfidenceFloor);\n const iterations = clampPageRankIterations(this.cfg.graphTraversalPageRankIterations);\n const deadlineAtMs = opts?.deadlineAtMs;\n const deadlineExpired = (): boolean =>\n typeof deadlineAtMs === \"number\" && Date.now() >= deadlineAtMs;\n\n try {\n if (deadlineExpired()) return [];\n const allEdges = await this.loadEdgesCached();\n if (deadlineExpired()) return [];\n\n // Build adjacency index: from → edges, to → edges (bidirectional for entity/time, directional for causal).\n // Edges below the confidence floor are pruned at index time so neither\n // direct activation nor downstream BFS expansion can re-introduce them.\n const adj = new Map<string, GraphEdge[]>();\n for (let i = 0; i < allEdges.length; i += 1) {\n if ((i & 1023) === 0 && deadlineExpired()) return [];\n const edge = allEdges[i];\n const conf = readEdgeConfidence(edge);\n if (conf < floor) continue;\n if (!adj.has(edge.from)) adj.set(edge.from, []);\n adj.get(edge.from)!.push(edge);\n // Entity and time edges are bidirectional\n if (edge.type !== \"causal\") {\n if (!adj.has(edge.to)) adj.set(edge.to, []);\n adj.get(edge.to)!.push({ ...edge, from: edge.to, to: edge.from });\n }\n }\n\n const seedSet = new Set(seeds);\n const scores = new Map<string, number>(); // candidate path → accumulated activation score\n const provenance = new Map<\n string,\n {\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n edgeConfidence: number;\n }\n >();\n let frontier = new Map<string, { node: string; seed: string; activation: number }>();\n const reachedBySeed = new Map<string, Set<string>>();\n for (const seed of seeds) {\n frontier.set(`${seed}\\0${seed}`, { node: seed, seed, activation: 1 });\n reachedBySeed.set(seed, new Set([seed]));\n }\n const finalizeScores = () =>\n Array.from(scores.entries())\n .map(([p, score]) => ({\n path: p,\n score,\n seed: provenance.get(p)?.seed ?? \"\",\n hopDepth: provenance.get(p)?.hopDepth ?? 0,\n decayedWeight: provenance.get(p)?.decayedWeight ?? 0,\n graphType: provenance.get(p)?.graphType ?? \"entity\",\n edgeConfidence: provenance.get(p)?.edgeConfidence ?? 1,\n }))\n .sort((a, b) => b.score - a.score);\n\n for (let hop = 0; hop < steps && frontier.size > 0; hop++) {\n if (deadlineExpired()) return finalizeScores();\n const nextFrontier = new Map<string, { node: string; seed: string; activation: number }>();\n\n for (const { node, seed: sourceSeed, activation } of frontier.values()) {\n const edges = adj.get(node) ?? [];\n for (let i = 0; i < edges.length; i += 1) {\n if ((i & 1023) === 0 && deadlineExpired()) return finalizeScores();\n const edge = edges[i];\n const neighbor = edge.to === node ? edge.from : edge.to;\n const conf = readEdgeConfidence(edge);\n // Defense in depth: the adjacency build already drops sub-floor\n // edges, but if a synthesized reverse edge ever bypassed that\n // path, this guard keeps spreading activation honest.\n if (conf < floor) continue;\n const score = activation * edge.weight * conf * decay;\n const reachedForSeed = reachedBySeed.get(sourceSeed);\n if (reachedForSeed?.has(neighbor)) {\n continue;\n }\n\n if (!seedSet.has(neighbor)) {\n const existing = scores.get(neighbor) ?? 0;\n scores.set(neighbor, existing + score);\n\n const prev = provenance.get(neighbor);\n if (!prev || hop + 1 < prev.hopDepth || (hop + 1 === prev.hopDepth && score > prev.decayedWeight)) {\n provenance.set(neighbor, {\n seed: sourceSeed,\n hopDepth: hop + 1,\n decayedWeight: score,\n graphType: edge.type,\n edgeConfidence: conf,\n });\n }\n\n if (hop + 1 < steps) {\n const frontierKey = `${sourceSeed}\\0${neighbor}`;\n const existingFrontier = nextFrontier.get(frontierKey);\n if (existingFrontier) {\n existingFrontier.activation += score;\n } else {\n nextFrontier.set(frontierKey, {\n node: neighbor,\n seed: sourceSeed,\n activation: score,\n });\n }\n }\n }\n }\n }\n\n for (const { node, seed } of nextFrontier.values()) {\n reachedBySeed.get(seed)?.add(node);\n }\n frontier = nextFrontier;\n }\n\n // Issue #681 PR 3/3 — optional PageRank-style refinement.\n // Redistributes a node's accumulated activation along its outgoing\n // edges, weighted by edge confidence. Damping is fixed at the\n // canonical 0.85 so the ranking stays comparable across queries;\n // the `iterations` knob bounds compute, not behavior shape.\n if (!deadlineExpired() && iterations > 0 && scores.size > 1) {\n applyPageRankRefinement(scores, adj, {\n iterations,\n floor,\n damping: 0.85,\n deadlineAtMs,\n });\n }\n\n // Apply lateral inhibition if enabled (Synapse-inspired competitive suppression)\n if (deadlineExpired()) return finalizeScores();\n if (this.cfg.graphLateralInhibitionEnabled && scores.size > 1) {\n const inhibited = applyLateralInhibition(scores, {\n beta: this.cfg.graphLateralInhibitionBeta,\n topM: this.cfg.graphLateralInhibitionTopM,\n });\n for (const [k, v] of inhibited) {\n scores.set(k, v);\n }\n }\n\n return finalizeScores();\n } catch (err) {\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] spreadingActivation error: ${err}`);\n return [];\n }\n }\n}\n\n/**\n * Clamp `graphTraversalConfidenceFloor` into the legal range `[0, 1]`.\n * Non-finite or non-numeric values fall back to the documented default\n * so misconfiguration cannot silently disable the floor or reject every edge.\n *\n * Exported for tests; call sites in `spreadingActivation` use it to make\n * the contract explicit at every boundary.\n */\nexport function clampConfidenceFloor(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n return DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR;\n }\n if (raw < 0) return 0;\n if (raw > 1) return 1;\n return raw;\n}\n\n/**\n * Clamp `graphTraversalPageRankIterations` into a non-negative integer.\n * Negative or non-finite values fall back to 0 (disable refinement) so\n * misconfiguration cannot stall recall in an unbounded loop.\n */\nexport function clampPageRankIterations(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) return 0;\n if (raw <= 0) return 0;\n return Math.floor(raw);\n}\n\n/**\n * PageRank-style refinement on top of the BFS activation map.\n *\n * Each iteration redistributes a fraction of every node's score along\n * its outgoing edges, scaled by edge confidence. Confidence below\n * `floor` is filtered out before redistribution, mirroring the BFS\n * pruning rule. Mutates `scores` in place.\n *\n * Exported for tests; in production, call sites pass the same adjacency\n * map already used by BFS so behavior stays consistent.\n */\nexport function applyPageRankRefinement(\n scores: Map<string, number>,\n adj: Map<string, GraphEdge[]>,\n opts: { iterations: number; floor: number; damping: number; deadlineAtMs?: number }\n): void {\n const { iterations, floor, damping, deadlineAtMs } = opts;\n if (iterations <= 0 || scores.size === 0) return;\n const safeDamping = Math.min(1, Math.max(0, damping));\n const deadlineExpired = (): boolean =>\n typeof deadlineAtMs === \"number\" && Date.now() >= deadlineAtMs;\n\n // Pre-compute confidence-weighted out-edge totals for normalization.\n // Done once per refinement, not per iteration, since adjacency is\n // immutable inside the loop.\n //\n // Codex P1 (#735): the denominator MUST be computed over the same\n // eligible-neighbor set the iteration redistributes into — i.e.\n // edges whose neighbor is in `scores`. Counting edges-to-seeds (or\n // edges-to-unseen-nodes) in the denominator while dropping their\n // flow during iteration leaks `safeDamping × score` every pass and\n // collapses leaf candidates' scores instead of just re-ranking them.\n const eligible = (edge: GraphEdge, fromNode: string): boolean => {\n if (readEdgeConfidence(edge) < floor) return false;\n const neighbor = edge.to === fromNode ? edge.from : edge.to;\n return scores.has(neighbor);\n };\n const outboundTotal = new Map<string, number>();\n for (const [node, edges] of adj.entries()) {\n if (deadlineExpired()) return;\n if (!scores.has(node)) continue; // only candidate nodes redistribute\n let sum = 0;\n for (const edge of edges) {\n if (!eligible(edge, node)) continue;\n sum += readEdgeConfidence(edge) * edge.weight;\n }\n if (sum > 0) outboundTotal.set(node, sum);\n }\n\n for (let i = 0; i < iterations; i += 1) {\n if (deadlineExpired()) return;\n const next = new Map<string, number>();\n // Teleport / damping floor: every node retains `(1 - damping) * score`\n // of its current activation so dangling nodes do not bleed to zero.\n for (const [node, score] of scores) {\n next.set(node, (1 - safeDamping) * score);\n }\n for (const [node, score] of scores) {\n const outEdges = adj.get(node);\n const total = outboundTotal.get(node);\n // Dangling-node fallback: when a candidate has zero eligible\n // outflow (no in-scores neighbors above the floor), the\n // `safeDamping × score` portion would otherwise evaporate. Keep\n // it on `node` so total mass is conserved and the score reflects\n // the candidate's standing rather than its in-degree topology.\n if (!outEdges || outEdges.length === 0 || !total || total <= 0) {\n next.set(node, (next.get(node) ?? 0) + safeDamping * score);\n continue;\n }\n for (let edgeIndex = 0; edgeIndex < outEdges.length; edgeIndex += 1) {\n if ((edgeIndex & 1023) === 0 && deadlineExpired()) return;\n const edge = outEdges[edgeIndex];\n if (!eligible(edge, node)) continue;\n const conf = readEdgeConfidence(edge);\n const neighbor = edge.to === node ? edge.from : edge.to;\n const flow = safeDamping * score * ((conf * edge.weight) / total);\n next.set(neighbor, (next.get(neighbor) ?? 0) + flow);\n }\n }\n for (const [node, score] of next) {\n scores.set(node, score);\n }\n }\n}\n\n/**\n * Lateral inhibition (Synapse-inspired).\n *\n * For each node, the top-M higher-activation competitors exert inhibition\n * proportional to their activation difference. Output is clamped to [0, ∞).\n *\n * No sigmoid is applied here — downstream `normalizeGraphActivationScore`\n * already applies x/(1+x) soft squash, so adding a sigmoid would double-\n * normalize and cap graph influence at ~50%.\n *\n * Formula: u_hat_i = max(0, u_i - beta * sum_{k in top-M where u_k > u_i}(u_k - u_i))\n *\n * When beta=0 or topM=0, returns original scores unchanged (no-op).\n */\nexport function applyLateralInhibition(\n scores: Map<string, number>,\n opts: { beta: number; topM: number }\n): Map<string, number> {\n const { beta, topM } = opts;\n if (beta === 0 || topM === 0) return new Map(scores);\n\n const sorted = Array.from(scores.entries()).sort((a, b) => b[1] - a[1]);\n const topCompetitors = sorted.slice(0, topM);\n\n const result = new Map<string, number>();\n for (const [node, u] of scores) {\n let inhibition = 0;\n for (const [, uK] of topCompetitors) {\n if (uK > u) {\n inhibition += uK - u;\n }\n }\n result.set(node, Math.max(0, u - beta * inhibition));\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;AAYA,SAAS,YAAY,OAAO,gBAAgB;AAC5C,YAAY,UAAU;AAkDf,IAAM,2CAA2C;AAEjD,IAAM,8CAA8C;AAGpD,IAAM,iBAAiB,CAAC,eAAe,UAAU,cAAc,aAAa,UAAU,SAAS;AAE/F,SAAS,UAAU,WAA2B;AACnD,SAAY,UAAK,WAAW,SAAS,QAAQ;AAC/C;AAEO,SAAS,cAAc,WAAmB,MAAyB;AACxE,SAAY,UAAK,UAAU,SAAS,GAAG,GAAG,IAAI,QAAQ;AACxD;AAEA,eAAsB,gBAAgB,WAAkC;AACtE,QAAM,MAAM,UAAU,SAAS,GAAG,EAAE,WAAW,KAAK,CAAC;AACvD;AAWA,IAAM,kBAAkB,oBAAI,IAA2B;AAWhD,SAAS,mBAAsB,UAAkB,IAAkC;AACxF,QAAM,OAAO,gBAAgB,IAAI,QAAQ,KAAK,QAAQ,QAAQ;AAC9D,QAAM,OAAO,KAAK,KAAK,IAAI,EAAE;AAC7B,kBAAgB;AAAA,IACd;AAAA,IACA,KAAK;AAAA,MACH,MAAM;A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AAK;AACrD,cAAM,OAAO,cAAc,SAAU,OAAO,KAAK,SAAU;AAC3D,aAAK,IAAI,WAAW,KAAK,IAAI,QAAQ,KAAK,KAAK,IAAI;AAAA,MACrD;AAAA,IACF;AACA,eAAW,CAAC,MAAM,KAAK,KAAK,MAAM;AAChC,aAAO,IAAI,MAAM,KAAK;AAAA,IACxB;AAAA,EACF;AACF;AAgBO,SAAS,uBACd,QACA,MACqB;AACrB,QAAM,EAAE,MAAM,KAAK,IAAI;AACvB,MAAI,SAAS,KAAK,SAAS,EAAG,QAAO,IAAI,IAAI,MAAM;AAEnD,QAAM,SAAS,MAAM,KAAK,OAAO,QAAQ,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AACtE,QAAM,iBAAiB,OAAO,MAAM,GAAG,IAAI;AAE3C,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,CAAC,MAAM,CAAC,KAAK,QAAQ;AAC9B,QAAI,aAAa;AACjB,eAAW,CAAC,EAAE,EAAE,KAAK,gBAAgB;AACnC,UAAI,KAAK,GAAG;AACV,sBAAc,KAAK;AAAA,MACrB;AAAA,IACF;AACA,WAAO,IAAI,MAAM,KAAK,IAAI,GAAG,IAAI,OAAO,UAAU,CAAC;AAAA,EACrD;AAEA,SAAO;AACT;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|