@remnic/core 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1 -0
- package/dist/abort-error.d.ts +32 -0
- package/dist/abort-error.js +11 -0
- package/dist/access-cli.d.ts +13 -3
- package/dist/access-cli.js +96 -80
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +12 -4
- package/dist/access-http.js +25 -18
- package/dist/access-mcp.d.ts +32 -4
- package/dist/access-mcp.js +16 -1
- package/dist/access-schema.d.ts +28 -28
- package/dist/access-schema.js +1 -1
- package/dist/access-service-HmO1Trrx.d.ts +732 -0
- package/dist/access-service.d.ts +15 -601
- package/dist/access-service.js +21 -15
- package/dist/active-memory-bridge.d.ts +66 -0
- package/dist/active-memory-bridge.js +11 -0
- package/dist/active-memory-bridge.js.map +1 -0
- package/dist/active-recall.d.ts +96 -0
- package/dist/active-recall.js +308 -0
- package/dist/active-recall.js.map +1 -0
- package/dist/behavior-learner.js +1 -1
- package/dist/bootstrap.d.ts +6 -3
- package/dist/bootstrap.js +2 -2
- package/dist/boxes.js +2 -2
- package/dist/briefing.d.ts +169 -0
- package/dist/briefing.js +52 -0
- package/dist/briefing.js.map +1 -0
- package/dist/buffer.d.ts +19 -5
- package/dist/buffer.js +2 -2
- package/dist/calibration.js +6 -6
- package/dist/causal-behavior.js +5 -5
- package/dist/causal-chain.js +3 -3
- package/dist/causal-consolidation.d.ts +22 -2
- package/dist/causal-consolidation.js +36 -9
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/causal-retrieval.js +6 -6
- package/dist/causal-trajectory-graph.js +1 -1
- package/dist/causal-trajectory.d.ts +14 -1
- package/dist/causal-trajectory.js +5 -1
- package/dist/{chunk-KWBU5S5U.js → chunk-2ODBA7MQ.js} +9 -3
- package/dist/chunk-2ODBA7MQ.js.map +1 -0
- package/dist/{chunk-ZJLY4QSU.js → chunk-37UIFYWO.js} +130 -6
- package/dist/chunk-37UIFYWO.js.map +1 -0
- package/dist/chunk-3PG3H5TD.js +7 -0
- package/dist/chunk-3PG3H5TD.js.map +1 -0
- package/dist/{chunk-NTTLPF7F.js → chunk-3QFQGRHO.js} +5 -5
- package/dist/{chunk-QDOSNLB4.js → chunk-3QHL5ABG.js} +17 -15
- package/dist/chunk-3QHL5ABG.js.map +1 -0
- package/dist/{chunk-6UJQNRIO.js → chunk-3SV6CQHO.js} +92 -33
- package/dist/chunk-3SV6CQHO.js.map +1 -0
- package/dist/{chunk-U4PV25RD.js → chunk-3WHVNEN7.js} +1 -1
- package/dist/chunk-3WHVNEN7.js.map +1 -0
- package/dist/{chunk-XUHI52HK.js → chunk-44ICJRF3.js} +98 -10
- package/dist/chunk-44ICJRF3.js.map +1 -0
- package/dist/{chunk-HG2NKWR2.js → chunk-47UU5PU2.js} +49 -10
- package/dist/chunk-47UU5PU2.js.map +1 -0
- package/dist/chunk-4DJQYKMN.js +187 -0
- package/dist/chunk-4DJQYKMN.js.map +1 -0
- package/dist/chunk-4KAN3GZ3.js +225 -0
- package/dist/chunk-4KAN3GZ3.js.map +1 -0
- package/dist/chunk-4LACOVZX.js +813 -0
- package/dist/chunk-4LACOVZX.js.map +1 -0
- package/dist/{chunk-ORZMT74A.js → chunk-4NRAJUDS.js} +11 -1
- package/dist/chunk-4NRAJUDS.js.map +1 -0
- package/dist/{chunk-B7LOFDVE.js → chunk-4WMCPJWX.js} +8 -3
- package/dist/chunk-4WMCPJWX.js.map +1 -0
- package/dist/{chunk-G3AG3KZN.js → chunk-5IZL4DCV.js} +2 -2
- package/dist/{chunk-BRK4ODMI.js → chunk-5NPGSAVB.js} +2 -2
- package/dist/{chunk-QANCTXQF.js → chunk-6LX5ORAS.js} +3 -3
- package/dist/chunk-6MKAMLQL.js +16 -0
- package/dist/chunk-6MKAMLQL.js.map +1 -0
- package/dist/{chunk-ESSMF2FR.js → chunk-6PFRXT4K.js} +15 -6
- package/dist/chunk-6PFRXT4K.js.map +1 -0
- package/dist/{chunk-UIYZ5T3I.js → chunk-6UJ47TVX.js} +8 -8
- package/dist/chunk-6ZH4TU6I.js +245 -0
- package/dist/chunk-6ZH4TU6I.js.map +1 -0
- package/dist/{chunk-L5RPWGFK.js → chunk-7DHTMOND.js} +2 -2
- package/dist/{chunk-L7WO3MZ4.js → chunk-7ECD5ATE.js} +2 -2
- package/dist/{chunk-Q6FETXJA.js → chunk-7SEAZFFB.js} +2 -2
- package/dist/{chunk-V4YC4LUK.js → chunk-7WQ6SLIE.js} +175 -63
- package/dist/chunk-7WQ6SLIE.js.map +1 -0
- package/dist/chunk-ALXMCZEU.js +332 -0
- package/dist/chunk-ALXMCZEU.js.map +1 -0
- package/dist/{chunk-TVVVQQAK.js → chunk-BLKTA7MM.js} +58 -24
- package/dist/chunk-BLKTA7MM.js.map +1 -0
- package/dist/{chunk-SCHEKPYH.js → chunk-C2EFFULQ.js} +1 -1
- package/dist/{chunk-GJR6D6KC.js → chunk-D654IBA6.js} +2 -2
- package/dist/{chunk-OTFNI3OO.js → chunk-DEPL3635.js} +1828 -401
- package/dist/chunk-DEPL3635.js.map +1 -0
- package/dist/{chunk-UYSKNO6E.js → chunk-DHHP2Z4X.js} +15 -4
- package/dist/chunk-DHHP2Z4X.js.map +1 -0
- package/dist/{chunk-UV2FO7J4.js → chunk-E6K4NIEU.js} +2 -2
- package/dist/{chunk-T4WRIV2C.js → chunk-EABGC2TL.js} +2 -2
- package/dist/chunk-EJI5XIBB.js +232 -0
- package/dist/chunk-EJI5XIBB.js.map +1 -0
- package/dist/{chunk-ONRU4L2N.js → chunk-FEMOX5AD.js} +2 -2
- package/dist/{chunk-IFFFR3MR.js → chunk-FSFEQI74.js} +3 -3
- package/dist/chunk-G4SK7DSQ.js +121 -0
- package/dist/chunk-G4SK7DSQ.js.map +1 -0
- package/dist/{chunk-WWIQTB2Y.js → chunk-GGD5W7TB.js} +9 -2
- package/dist/chunk-GGD5W7TB.js.map +1 -0
- package/dist/{chunk-QWUUMMIK.js → chunk-GV6NLQ4X.js} +1355 -80
- package/dist/chunk-GV6NLQ4X.js.map +1 -0
- package/dist/{chunk-2PO5ZRKV.js → chunk-GZCUW5IC.js} +16 -3
- package/dist/chunk-GZCUW5IC.js.map +1 -0
- package/dist/{chunk-AAI7JARD.js → chunk-HMDCOMYU.js} +8 -11
- package/dist/chunk-HMDCOMYU.js.map +1 -0
- package/dist/chunk-IQT3XTKW.js +121 -0
- package/dist/chunk-IQT3XTKW.js.map +1 -0
- package/dist/{chunk-J3BT33K7.js → chunk-ITRLGI2T.js} +5 -5
- package/dist/{chunk-BDFZXRSO.js → chunk-J4IYOZZ5.js} +15 -2
- package/dist/chunk-J4IYOZZ5.js.map +1 -0
- package/dist/{chunk-J47FNDR7.js → chunk-JIU55F3X.js} +7 -7
- package/dist/{chunk-MDDAA2AO.js → chunk-JL2PU6AI.js} +17 -6
- package/dist/chunk-JL2PU6AI.js.map +1 -0
- package/dist/{chunk-ZKYI7UVO.js → chunk-JR4ZC3G4.js} +2 -2
- package/dist/{chunk-UCYSTFZR.js → chunk-JRNQ3RNA.js} +2 -2
- package/dist/{chunk-GPGBSNKM.js → chunk-K4FLSOR5.js} +2 -2
- package/dist/chunk-KVE7R4CG.js +320 -0
- package/dist/chunk-KVE7R4CG.js.map +1 -0
- package/dist/chunk-LAYN4LDC.js +267 -0
- package/dist/chunk-LAYN4LDC.js.map +1 -0
- package/dist/{chunk-ISY75RLM.js → chunk-MBJHSA7F.js} +344 -7
- package/dist/chunk-MBJHSA7F.js.map +1 -0
- package/dist/{chunk-PGK3VUHN.js → chunk-MTLYEMJB.js} +3 -2
- package/dist/chunk-MTLYEMJB.js.map +1 -0
- package/dist/{chunk-QY2BHY5O.js → chunk-MVTHXUBX.js} +297 -34
- package/dist/chunk-MVTHXUBX.js.map +1 -0
- package/dist/{chunk-LP47L3ZX.js → chunk-N42IWANG.js} +5 -5
- package/dist/{chunk-YNI4S5WT.js → chunk-N53K2EXC.js} +2 -2
- package/dist/{chunk-763GUIOU.js → chunk-NBNN5GOB.js} +2 -2
- package/dist/{chunk-CXWFUJR2.js → chunk-NQEVYWX6.js} +195 -5
- package/dist/chunk-NQEVYWX6.js.map +1 -0
- package/dist/{chunk-KL4CP4SB.js → chunk-O5ETUNBT.js} +17 -5
- package/dist/chunk-O5ETUNBT.js.map +1 -0
- package/dist/{chunk-OOSWAUYB.js → chunk-ODWDQNRE.js} +2 -2
- package/dist/chunk-OIT5QGG4.js +80 -0
- package/dist/chunk-OIT5QGG4.js.map +1 -0
- package/dist/{chunk-HLBYLYRD.js → chunk-PAORGQRI.js} +70 -13
- package/dist/chunk-PAORGQRI.js.map +1 -0
- package/dist/chunk-PVGDJXVK.js +21 -0
- package/dist/chunk-PVGDJXVK.js.map +1 -0
- package/dist/{chunk-OTAVQCSF.js → chunk-PYXS46O7.js} +2 -2
- package/dist/chunk-QDW3E4RD.js +108 -0
- package/dist/chunk-QDW3E4RD.js.map +1 -0
- package/dist/{chunk-YNCQ7E4M.js → chunk-QDYXG4CS.js} +4 -3
- package/dist/chunk-QDYXG4CS.js.map +1 -0
- package/dist/{chunk-HLXVTBF3.js → chunk-QNJMBKFK.js} +3 -2
- package/dist/chunk-QNJMBKFK.js.map +1 -0
- package/dist/{chunk-4A24LIM2.js → chunk-S75M5ZRK.js} +2 -2
- package/dist/chunk-SYUK3VLY.js +789 -0
- package/dist/chunk-SYUK3VLY.js.map +1 -0
- package/dist/{chunk-QCCCQT3O.js → chunk-TBBDFYXW.js} +2 -2
- package/dist/chunk-TBBDFYXW.js.map +1 -0
- package/dist/chunk-U66YHYC7.js +31 -0
- package/dist/chunk-U66YHYC7.js.map +1 -0
- package/dist/{chunk-MWGVGUIS.js → chunk-UEYA6UC7.js} +36 -4
- package/dist/chunk-UEYA6UC7.js.map +1 -0
- package/dist/{chunk-M5KEYE5E.js → chunk-URB2WSKZ.js} +2 -2
- package/dist/chunk-UVJFDP7P.js +202 -0
- package/dist/chunk-UVJFDP7P.js.map +1 -0
- package/dist/chunk-W6SL7OFG.js +180 -0
- package/dist/chunk-W6SL7OFG.js.map +1 -0
- package/dist/chunk-WBSAYXVI.js +7945 -0
- package/dist/chunk-WBSAYXVI.js.map +1 -0
- package/dist/{chunk-M5ZBBBJI.js → chunk-XZ2TIKGC.js} +39 -9
- package/dist/chunk-XZ2TIKGC.js.map +1 -0
- package/dist/chunk-Y4FHOFJ2.js +140 -0
- package/dist/chunk-Y4FHOFJ2.js.map +1 -0
- package/dist/chunk-YDBIWGNI.js +298 -0
- package/dist/chunk-YDBIWGNI.js.map +1 -0
- package/dist/chunk-YNB73F22.js +137 -0
- package/dist/chunk-YNB73F22.js.map +1 -0
- package/dist/{chunk-IZME7KW2.js → chunk-ZVBB3T7V.js} +31 -12
- package/dist/chunk-ZVBB3T7V.js.map +1 -0
- package/dist/chunking.js +1 -1
- package/dist/citations.d.ts +67 -0
- package/dist/citations.js +13 -0
- package/dist/citations.js.map +1 -0
- package/dist/cli-BneVIEvh.d.ts +1240 -0
- package/dist/cli.d.ts +32 -1147
- package/dist/cli.js +150 -7092
- package/dist/cli.js.map +1 -1
- package/dist/codex-materialize-CQlLTzke.d.ts +139 -0
- package/dist/codex-thread-key.d.ts +3 -0
- package/dist/codex-thread-key.js +7 -0
- package/dist/codex-thread-key.js.map +1 -0
- package/dist/config.js +3 -2
- package/dist/connectors/codex/instructions.md +160 -0
- package/dist/connectors/codex/resources/namespace-cheatsheet.md +48 -0
- package/dist/contradiction-review-WIUBAR52.js +21 -0
- package/dist/contradiction-review-WIUBAR52.js.map +1 -0
- package/dist/contradiction-scan-GR33PONM.js +376 -0
- package/dist/contradiction-scan-GR33PONM.js.map +1 -0
- package/dist/day-summary.d.ts +7 -2
- package/dist/day-summary.js +5 -2
- package/dist/direct-answer-wiring.d.ts +77 -0
- package/dist/direct-answer-wiring.js +75 -0
- package/dist/direct-answer-wiring.js.map +1 -0
- package/dist/direct-answer.d.ts +106 -0
- package/dist/direct-answer.js +10 -0
- package/dist/direct-answer.js.map +1 -0
- package/dist/embedding-fallback.d.ts +96 -2
- package/dist/embedding-fallback.js +6 -4
- package/dist/{engine-2A6J4XEX.js → engine-5TIQBYZR.js} +10 -7
- package/dist/engine-5TIQBYZR.js.map +1 -0
- package/dist/entity-retrieval.d.ts +3 -2
- package/dist/entity-retrieval.js +10 -7
- package/dist/entity-schema.d.ts +11 -0
- package/dist/entity-schema.js +19 -0
- package/dist/entity-schema.js.map +1 -0
- package/dist/explicit-capture.d.ts +6 -3
- package/dist/explicit-capture.js +2 -2
- package/dist/extraction-judge.d.ts +66 -0
- package/dist/extraction-judge.js +18 -0
- package/dist/extraction-judge.js.map +1 -0
- package/dist/extraction.d.ts +1 -0
- package/dist/extraction.js +12 -10
- package/dist/fallback-llm.d.ts +11 -2
- package/dist/fallback-llm.js +4 -4
- package/dist/graph.js +1 -1
- package/dist/harmonic-retrieval.js +2 -1
- package/dist/importance.d.ts +11 -1
- package/dist/importance.js +3 -1
- package/dist/index.d.ts +1027 -9
- package/dist/index.js +3303 -349
- package/dist/index.js.map +1 -1
- package/dist/intent.d.ts +2 -1
- package/dist/intent.js +3 -1
- package/dist/lifecycle.js +1 -1
- package/dist/local-llm.d.ts +10 -3
- package/dist/local-llm.js +2 -2
- package/dist/logger.d.ts +1 -1
- package/dist/logger.js +1 -1
- package/dist/memory-cache.d.ts +2 -2
- package/dist/memory-cache.js +1 -1
- package/dist/{memory-projection-store-NxMkbocT.d.ts → memory-projection-store-DeSXPh1j.d.ts} +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/model-registry.js +2 -2
- package/dist/models-json.js +2 -2
- package/dist/native-knowledge.js +2 -2
- package/dist/negative.js +2 -2
- package/dist/operator-toolkit.js +20 -15
- package/dist/{orchestrator-zTa-Qo-1.d.ts → orchestrator-DRYA6_lW.d.ts} +273 -9
- package/dist/orchestrator.d.ts +6 -3
- package/dist/orchestrator.js +76 -63
- package/dist/page-versioning.d.ts +77 -0
- package/dist/page-versioning.js +15 -0
- package/dist/page-versioning.js.map +1 -0
- package/dist/plugin-id.d.ts +37 -0
- package/dist/plugin-id.js +11 -0
- package/dist/plugin-id.js.map +1 -0
- package/dist/policy-runtime.js +2 -2
- package/dist/profiling.js +2 -2
- package/dist/qmd.d.ts +5 -2
- package/dist/qmd.js +4 -3
- package/dist/recall-audit.d.ts +20 -0
- package/dist/recall-audit.js +50 -0
- package/dist/recall-audit.js.map +1 -0
- package/dist/recall-mmr.d.ts +152 -0
- package/dist/recall-mmr.js +17 -0
- package/dist/recall-mmr.js.map +1 -0
- package/dist/recall-qos.js +2 -2
- package/dist/recall-state.d.ts +28 -1
- package/dist/recall-state.js +2 -2
- package/dist/relevance.js +2 -2
- package/dist/resolution-QBTDHTG7.js +100 -0
- package/dist/resolution-QBTDHTG7.js.map +1 -0
- package/dist/resolve-provider-secret.d.ts +24 -1
- package/dist/resolve-provider-secret.js +4 -2
- package/dist/resume-bundles.js +6 -5
- package/dist/retrieval-agents.js +2 -2
- package/dist/retrieval.js +2 -2
- package/dist/schemas.d.ts +412 -54
- package/dist/schemas.js +3 -1
- package/dist/sdk-compat.d.ts +2 -0
- package/dist/sdk-compat.js +6 -3
- package/dist/sdk-compat.js.map +1 -1
- package/dist/semantic-chunking.d.ts +87 -0
- package/dist/semantic-chunking.js +20 -0
- package/dist/semantic-chunking.js.map +1 -0
- package/dist/semantic-consolidation-DrvSYRdB.d.ts +119 -0
- package/dist/semantic-consolidation.d.ts +4 -42
- package/dist/semantic-consolidation.js +23 -2
- package/dist/semantic-rule-promotion.js +9 -6
- package/dist/semantic-rule-verifier.js +10 -7
- package/dist/session-observer-state.js +2 -2
- package/dist/session-toggles.d.ts +22 -0
- package/dist/session-toggles.js +116 -0
- package/dist/session-toggles.js.map +1 -0
- package/dist/skills-registry.d.ts +47 -0
- package/dist/skills-registry.js +48 -0
- package/dist/skills-registry.js.map +1 -0
- package/dist/source-attribution.d.ts +169 -0
- package/dist/source-attribution.js +27 -0
- package/dist/source-attribution.js.map +1 -0
- package/dist/storage.d.ts +171 -10
- package/dist/storage.js +16 -5
- package/dist/summarizer.js +7 -7
- package/dist/temporal-supersession.d.ts +127 -0
- package/dist/temporal-supersession.js +20 -0
- package/dist/temporal-supersession.js.map +1 -0
- package/dist/threading.js +2 -2
- package/dist/tier-migration.d.ts +2 -1
- package/dist/tier-routing.js +2 -2
- package/dist/tokens.d.ts +21 -1
- package/dist/tokens.js +5 -1
- package/dist/transcript.js +2 -2
- package/dist/types-DJhqDJUV.d.ts +50 -0
- package/dist/types.d.ts +529 -3
- package/dist/types.js +1 -1
- package/dist/utility-learner.js +2 -2
- package/dist/utility-runtime.js +3 -3
- package/dist/verified-recall.js +11 -8
- package/dist/whitespace.d.ts +4 -0
- package/dist/whitespace.js +9 -0
- package/dist/whitespace.js.map +1 -0
- package/package.json +14 -8
- package/dist/chunk-2CJCWDMR.js +0 -87
- package/dist/chunk-2CJCWDMR.js.map +0 -1
- package/dist/chunk-2PO5ZRKV.js.map +0 -1
- package/dist/chunk-6UJQNRIO.js.map +0 -1
- package/dist/chunk-AAI7JARD.js.map +0 -1
- package/dist/chunk-B7LOFDVE.js.map +0 -1
- package/dist/chunk-BDFZXRSO.js.map +0 -1
- package/dist/chunk-CXWFUJR2.js.map +0 -1
- package/dist/chunk-DORBM6OB.js +0 -81
- package/dist/chunk-DORBM6OB.js.map +0 -1
- package/dist/chunk-ESSMF2FR.js.map +0 -1
- package/dist/chunk-HG2NKWR2.js.map +0 -1
- package/dist/chunk-HLBYLYRD.js.map +0 -1
- package/dist/chunk-HLXVTBF3.js.map +0 -1
- package/dist/chunk-ISY75RLM.js.map +0 -1
- package/dist/chunk-IZME7KW2.js.map +0 -1
- package/dist/chunk-KL4CP4SB.js.map +0 -1
- package/dist/chunk-KWBU5S5U.js.map +0 -1
- package/dist/chunk-M5ZBBBJI.js.map +0 -1
- package/dist/chunk-MDDAA2AO.js.map +0 -1
- package/dist/chunk-MWGVGUIS.js.map +0 -1
- package/dist/chunk-ORZMT74A.js.map +0 -1
- package/dist/chunk-OTFNI3OO.js.map +0 -1
- package/dist/chunk-PGK3VUHN.js.map +0 -1
- package/dist/chunk-QCCCQT3O.js.map +0 -1
- package/dist/chunk-QDOSNLB4.js.map +0 -1
- package/dist/chunk-QPKFPHOO.js +0 -178
- package/dist/chunk-QPKFPHOO.js.map +0 -1
- package/dist/chunk-QWUUMMIK.js.map +0 -1
- package/dist/chunk-QY2BHY5O.js.map +0 -1
- package/dist/chunk-TVVVQQAK.js.map +0 -1
- package/dist/chunk-U4PV25RD.js.map +0 -1
- package/dist/chunk-UYSKNO6E.js.map +0 -1
- package/dist/chunk-V4YC4LUK.js.map +0 -1
- package/dist/chunk-WWIQTB2Y.js.map +0 -1
- package/dist/chunk-XUHI52HK.js.map +0 -1
- package/dist/chunk-YNCQ7E4M.js.map +0 -1
- package/dist/chunk-ZJLY4QSU.js.map +0 -1
- /package/dist/{engine-2A6J4XEX.js.map → abort-error.js.map} +0 -0
- /package/dist/{chunk-NTTLPF7F.js.map → chunk-3QFQGRHO.js.map} +0 -0
- /package/dist/{chunk-G3AG3KZN.js.map → chunk-5IZL4DCV.js.map} +0 -0
- /package/dist/{chunk-BRK4ODMI.js.map → chunk-5NPGSAVB.js.map} +0 -0
- /package/dist/{chunk-QANCTXQF.js.map → chunk-6LX5ORAS.js.map} +0 -0
- /package/dist/{chunk-UIYZ5T3I.js.map → chunk-6UJ47TVX.js.map} +0 -0
- /package/dist/{chunk-L5RPWGFK.js.map → chunk-7DHTMOND.js.map} +0 -0
- /package/dist/{chunk-L7WO3MZ4.js.map → chunk-7ECD5ATE.js.map} +0 -0
- /package/dist/{chunk-Q6FETXJA.js.map → chunk-7SEAZFFB.js.map} +0 -0
- /package/dist/{chunk-SCHEKPYH.js.map → chunk-C2EFFULQ.js.map} +0 -0
- /package/dist/{chunk-GJR6D6KC.js.map → chunk-D654IBA6.js.map} +0 -0
- /package/dist/{chunk-UV2FO7J4.js.map → chunk-E6K4NIEU.js.map} +0 -0
- /package/dist/{chunk-T4WRIV2C.js.map → chunk-EABGC2TL.js.map} +0 -0
- /package/dist/{chunk-ONRU4L2N.js.map → chunk-FEMOX5AD.js.map} +0 -0
- /package/dist/{chunk-IFFFR3MR.js.map → chunk-FSFEQI74.js.map} +0 -0
- /package/dist/{chunk-J3BT33K7.js.map → chunk-ITRLGI2T.js.map} +0 -0
- /package/dist/{chunk-J47FNDR7.js.map → chunk-JIU55F3X.js.map} +0 -0
- /package/dist/{chunk-ZKYI7UVO.js.map → chunk-JR4ZC3G4.js.map} +0 -0
- /package/dist/{chunk-UCYSTFZR.js.map → chunk-JRNQ3RNA.js.map} +0 -0
- /package/dist/{chunk-GPGBSNKM.js.map → chunk-K4FLSOR5.js.map} +0 -0
- /package/dist/{chunk-LP47L3ZX.js.map → chunk-N42IWANG.js.map} +0 -0
- /package/dist/{chunk-YNI4S5WT.js.map → chunk-N53K2EXC.js.map} +0 -0
- /package/dist/{chunk-763GUIOU.js.map → chunk-NBNN5GOB.js.map} +0 -0
- /package/dist/{chunk-OOSWAUYB.js.map → chunk-ODWDQNRE.js.map} +0 -0
- /package/dist/{chunk-OTAVQCSF.js.map → chunk-PYXS46O7.js.map} +0 -0
- /package/dist/{chunk-4A24LIM2.js.map → chunk-S75M5ZRK.js.map} +0 -0
- /package/dist/{chunk-M5KEYE5E.js.map → chunk-URB2WSKZ.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extraction.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport { log } from \"./logger.js\";\nimport { delinearize } from \"./delinearize.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport {\n ExtractionResultSchema,\n ConsolidationResultSchema,\n IdentityConsolidationResultSchema,\n buildProfileConsolidationResultSchema,\n ProactiveExtractionResultSchema,\n ProactiveQuestionsResultSchema,\n type ContradictionVerificationResult,\n type SuggestedLinks,\n type MemorySummaryResult,\n type ProactiveQuestionsResultParsed,\n DaySummaryResultSchema,\n} from \"./schemas.js\";\nimport type {\n BufferTurn,\n ExtractionResult,\n ConsolidationResult,\n MemoryFile,\n PluginConfig,\n LlmTraceEvent,\n GatewayConfig,\n MemoryCategory,\n DaySummaryResult as DaySummaryResultShape,\n} from \"./types.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { applyWorkExtractionBoundary } from \"./work/boundary.js\";\nimport { buildChatCompletionTokenLimit, shouldAssumeOpenAiChatCompletions } from \"./openai-chat-compat.js\";\nimport { formatDaySummaryMemories, loadDaySummaryPrompt } from \"./day-summary.js\";\nimport { ProfilingCollector } from \"./profiling.js\";\n\ntype ExtractionQuestion = ExtractionResult[\"questions\"][number];\ntype ExtractedFactResult = ExtractionResult[\"facts\"][number];\ntype ExtractedEntityResult = ExtractionResult[\"entities\"][number];\ntype ExtractedRelationshipResult = NonNullable<ExtractionResult[\"relationships\"]>[number];\nconst PROACTIVE_MIN_CONFIDENCE = 0.8;\n\nfunction normalizeQuestion(question: ExtractionQuestion): ExtractionQuestion {\n const priority = Number.isFinite(question.priority)\n ? Math.max(0, Math.min(1, question.priority))\n : 0.5;\n return {\n question: typeof question.question === \"string\" ? question.question.trim() : \"\",\n context: typeof question.context === \"string\" ? question.context.trim() : \"\",\n priority,\n };\n}\n\nfunction normalizeFactKey(fact: Pick<ExtractedFactResult, \"category\" | \"content\">): string {\n return `${fact.category}:${fact.content.trim().toLowerCase()}`;\n}\n\nfunction normalizeEntityKey(entity: Pick<ExtractedEntityResult, \"name\" | \"type\">): string {\n return `${entity.type}:${entity.name.trim().toLowerCase()}`;\n}\n\nfunction normalizeRelationshipKey(\n relationship: Pick<ExtractedRelationshipResult, \"source\" | \"target\" | \"label\">,\n): string {\n return `${relationship.source.trim().toLowerCase()}=>${relationship.target.trim().toLowerCase()}:${relationship.label.trim().toLowerCase()}`;\n}\n\nfunction normalizeProfileUpdateKey(update: string): string {\n return update.trim().toLowerCase();\n}\n\nexport class ExtractionEngine {\n private client: OpenAI | null;\n private localLlm: LocalLlmClient;\n private fallbackLlm: FallbackLlmClient;\n private modelRegistry: ModelRegistry;\n private profiler: ProfilingCollector;\n\n constructor(\n private readonly config: PluginConfig,\n profilerArg?: ProfilingCollector,\n localLlm?: LocalLlmClient,\n gatewayConfig?: GatewayConfig,\n modelRegistry?: ModelRegistry,\n ) {\n this.profiler = profilerArg ?? new ProfilingCollector({ enabled: false, storageDir: \"/tmp/engram-profiler-disabled\", maxTraces: 0 });\n if (config.openaiApiKey) {\n this.client = new OpenAI({\n apiKey: config.openaiApiKey,\n ...(config.openaiBaseUrl ? { baseURL: config.openaiBaseUrl } : {}),\n });\n } else {\n this.client = null;\n log.warn(\"no OpenAI API key — direct OpenAI client disabled; local and gateway fallback paths remain available\");\n }\n this.localLlm = localLlm ?? new LocalLlmClient(config, modelRegistry);\n this.fallbackLlm = new FallbackLlmClient(gatewayConfig);\n this.modelRegistry = modelRegistry ?? new ModelRegistry(config.memoryDir);\n if (config.modelSource === \"gateway\") {\n log.debug(\n `extraction engine: gateway model source active; extraction uses the gateway chain as its primary path` +\n (config.gatewayAgentId ? ` (agent: ${config.gatewayAgentId})` : \" (defaults)\"),\n );\n }\n }\n\n /**\n * Whether LLM calls should be routed through the gateway model chain\n * instead of the plugin's own local/OpenAI clients.\n */\n private get useGatewayModelSource(): boolean {\n return this.config.modelSource === \"gateway\";\n }\n\n /**\n * Whether the local LLM path should be attempted.\n * Disabled when gateway model source is active (gateway chain replaces local).\n */\n private get shouldUseLocalLlm(): boolean {\n return this.config.localLlmEnabled && !this.useGatewayModelSource;\n }\n\n /**\n * Whether the direct OpenAI client should be used.\n * Disabled when gateway model source is active.\n */\n private get shouldUseDirectClient(): boolean {\n return !this.useGatewayModelSource && this.client !== null;\n }\n\n /**\n * Build FallbackLlmOptions with the configured gateway agent ID injected.\n */\n private withGatewayAgent(options: import(\"./fallback-llm.js\").FallbackLlmOptions): import(\"./fallback-llm.js\").FallbackLlmOptions {\n if (!this.useGatewayModelSource) return options;\n const agentId = this.config.gatewayAgentId || undefined;\n return agentId ? { ...options, agentId } : options;\n }\n\n private emit(event: LlmTraceEvent): void {\n try {\n const cb = (globalThis as any).__openclawEngramTrace;\n if (typeof cb === \"function\") cb(event);\n } catch {\n // Never throw — broken subscriber must not crash extraction\n }\n }\n\n private directClientUsesOpenAiTokenSemantics(): boolean {\n return shouldAssumeOpenAiChatCompletions(this.config.openaiBaseUrl);\n }\n\n private sanitizeExtractionResult(result: ExtractionResult, messageTimestamp?: Date): ExtractionResult {\n const ts = messageTimestamp ?? new Date();\n const facts = result.facts.map((fact) => {\n const sanitized = sanitizeMemoryContent(fact.content);\n if (!sanitized.clean) {\n log.warn(`extraction fact sanitized; violations=${sanitized.violations.join(\", \")}`);\n }\n let content = sanitized.text;\n // De-linearize: resolve coreferences + anchor temporal expressions\n if (this.config.delinearizeEnabled) {\n content = delinearize(content, result.entities, ts);\n }\n return { ...fact, content };\n });\n return { ...result, facts };\n }\n\n private hasExtractionOutputs(result: ExtractionResult): boolean {\n return result.facts.length > 0\n || result.entities.length > 0\n || result.questions.length > 0\n || result.profileUpdates.length > 0\n || (result.relationships?.length ?? 0) > 0;\n }\n\n private normalizeExtractionResultPayload(parsed: any): ExtractionResult {\n const entities = Array.isArray(parsed?.entities)\n ? parsed.entities\n .map((e: any) => ({\n name: typeof e?.name === \"string\" ? e.name : \"\",\n type: typeof e?.type === \"string\" ? e.type : \"other\",\n facts: Array.isArray(e?.facts)\n ? e.facts.filter((f: any) => typeof f === \"string\")\n : [],\n promptedByQuestion:\n typeof e?.promptedByQuestion === \"string\" ? e.promptedByQuestion : undefined,\n }))\n .filter((e: any) => e.name.length > 0)\n : [];\n\n const facts = Array.isArray(parsed?.facts)\n ? parsed.facts\n .map((f: any) => ({\n category: typeof f?.category === \"string\" ? f.category : \"fact\",\n content: typeof f?.content === \"string\" ? f.content : typeof f?.text === \"string\" ? f.text : \"\",\n confidence: typeof f?.confidence === \"number\" ? f.confidence : 0.7,\n tags: Array.isArray(f?.tags) ? f.tags.filter((t: any) => typeof t === \"string\") : [],\n entityRef: typeof f?.entityRef === \"string\" ? f.entityRef : undefined,\n promptedByQuestion:\n typeof f?.promptedByQuestion === \"string\" ? f.promptedByQuestion : undefined,\n structuredAttributes:\n f?.structuredAttributes && typeof f.structuredAttributes === \"object\" && !Array.isArray(f.structuredAttributes)\n ? Object.fromEntries(\n Object.entries(f.structuredAttributes)\n .filter(([k, v]) => typeof k === \"string\" && typeof v === \"string\")\n ) as Record<string, string>\n : undefined,\n }))\n .filter((f: any) => f.content.length > 0)\n : [];\n\n const questions = Array.isArray(parsed?.questions)\n ? parsed.questions\n .map((q: any) => {\n if (typeof q === \"string\") return { question: q, context: \"\", priority: 0.5 };\n return {\n question: typeof q?.question === \"string\" ? q.question : typeof q?.text === \"string\" ? q.text : \"\",\n context: typeof q?.context === \"string\" ? q.context : \"\",\n priority: typeof q?.priority === \"number\" ? q.priority : 0.5,\n };\n })\n .filter((q: any) => q.question.length > 0)\n : [];\n\n return {\n facts,\n entities,\n profileUpdates: Array.isArray(parsed?.profileUpdates)\n ? parsed.profileUpdates.filter((u: any) => typeof u === \"string\" && u.trim().length > 0)\n : [],\n questions,\n identityReflection: parsed?.identityReflection ?? undefined,\n relationships: Array.isArray(parsed?.relationships)\n ? parsed.relationships.filter(\n (r: any) =>\n typeof r?.source === \"string\" &&\n typeof r?.target === \"string\" &&\n typeof r?.label === \"string\",\n )\n .map((r: any) => ({\n source: r.source,\n target: r.target,\n label: r.label,\n promptedByQuestion:\n typeof r?.promptedByQuestion === \"string\" ? r.promptedByQuestion : undefined,\n }))\n : undefined,\n };\n }\n\n private parseJsonObject(content?: string | null): any | null {\n const trimmed = content?.trim();\n if (!trimmed) return null;\n\n for (const candidate of extractJsonCandidates(trimmed)) {\n try {\n return JSON.parse(candidate);\n } catch {\n // keep trying candidates\n }\n }\n\n return null;\n }\n\n private normalizeContradictionVerificationResult(parsed: any): ContradictionVerificationResult | null {\n if (!parsed || typeof parsed.isContradiction !== \"boolean\") return null;\n\n const rawWhich = parsed.whichIsNewer ?? parsed.winner;\n const normalizedWhich =\n rawWhich === \"first\" || rawWhich === \"existing\"\n ? \"first\"\n : rawWhich === \"second\" || rawWhich === \"new\"\n ? \"second\"\n : \"unclear\";\n\n return {\n isContradiction: Boolean(parsed.isContradiction),\n confidence: typeof parsed.confidence === \"number\" ? parsed.confidence : 0.5,\n reasoning:\n typeof parsed.reasoning === \"string\"\n ? parsed.reasoning\n : typeof parsed.explanation === \"string\"\n ? parsed.explanation\n : \"\",\n whichIsNewer: normalizedWhich,\n };\n }\n\n private normalizeSuggestedLinksResult(parsed: any): SuggestedLinks | null {\n if (!parsed || !Array.isArray(parsed.links)) {\n return null;\n }\n\n const normalizedLinks = parsed.links\n .map((link: any) => {\n const rawLinkType = link?.linkType ?? link?.type;\n return {\n targetId: typeof link?.targetId === \"string\" ? link.targetId : \"\",\n linkType:\n rawLinkType === \"follows\" ||\n rawLinkType === \"references\" ||\n rawLinkType === \"contradicts\" ||\n rawLinkType === \"supports\" ||\n rawLinkType === \"related\"\n ? rawLinkType\n : \"related\",\n strength: typeof link?.strength === \"number\" ? Math.max(0, Math.min(1, link.strength)) : 0.5,\n reason: typeof link?.reason === \"string\" ? link.reason : undefined,\n };\n })\n .filter((link: any) => link.targetId.length > 0);\n\n return { links: normalizedLinks };\n }\n\n private normalizeMemorySummaryResult(parsed: any): MemorySummaryResult | null {\n if (!parsed) return null;\n\n const normalized: MemorySummaryResult = {\n summaryText:\n typeof parsed.summaryText === \"string\"\n ? parsed.summaryText\n : typeof parsed.summary === \"string\"\n ? parsed.summary\n : \"\",\n keyFacts: Array.isArray(parsed.keyFacts) ? parsed.keyFacts.filter((f: unknown) => typeof f === \"string\") : [],\n keyEntities: Array.isArray(parsed.keyEntities)\n ? parsed.keyEntities.filter((e: unknown) => typeof e === \"string\")\n : Array.isArray(parsed.entities)\n ? parsed.entities.filter((e: unknown) => typeof e === \"string\")\n : [],\n };\n\n return normalized.summaryText.length > 0 ? normalized : null;\n }\n\n private normalizeDaySummaryResult(parsed: any): DaySummaryResultShape | null {\n if (!parsed) return null;\n\n const normalized: DaySummaryResultShape = {\n summary: typeof parsed.summary === \"string\" ? parsed.summary.trim() : \"\",\n bullets: Array.isArray(parsed.bullets)\n ? parsed.bullets.filter((item: unknown) => typeof item === \"string\").map((item: string) => item.trim()).filter(Boolean)\n : [],\n next_actions: Array.isArray(parsed.next_actions)\n ? parsed.next_actions.filter((item: unknown) => typeof item === \"string\").map((item: string) => item.trim()).filter(Boolean)\n : [],\n risks_or_open_loops: Array.isArray(parsed.risks_or_open_loops)\n ? parsed.risks_or_open_loops.filter((item: unknown) => typeof item === \"string\").map((item: string) => item.trim()).filter(Boolean)\n : [],\n };\n\n return normalized.summary.length > 0 ? normalized : null;\n }\n\n private sanitizeConsolidationResult(result: ConsolidationResult): ConsolidationResult {\n const items = result.items.map((item) => {\n if (!item.updatedContent) return item;\n const sanitized = sanitizeMemoryContent(item.updatedContent);\n if (!sanitized.clean) {\n log.warn(`consolidation item sanitized (${item.existingId}); violations=${sanitized.violations.join(\", \")}`);\n }\n return { ...item, updatedContent: sanitized.text };\n });\n return { ...result, items };\n }\n\n private async applyProactiveQuestionPass(\n conversation: string,\n base: ExtractionResult,\n ): Promise<ExtractionResult> {\n if (!this.config.proactiveExtractionEnabled) return base;\n const maxAdditional = Math.max(0, Math.floor(this.config.maxProactiveQuestionsPerExtraction));\n if (maxAdditional === 0) return base;\n if (this.config.proactiveExtractionTimeoutMs === 0) return base;\n if (this.config.proactiveExtractionMaxTokens === 0) return base;\n\n try {\n const proactive = await this.generateProactiveQuestions(conversation, base, maxAdditional);\n if (proactive.length === 0) return base;\n const proactiveAdditions = await this.answerProactiveQuestions(\n conversation,\n base,\n proactive,\n maxAdditional,\n );\n if (!this.hasExtractionOutputs(proactiveAdditions)) return base;\n return this.mergeProactiveExtractionPass(base, proactiveAdditions, maxAdditional);\n } catch (err) {\n log.debug(`proactive extraction question pass failed (ignored): ${err}`);\n return base;\n }\n }\n\n private parseProactiveQuestionsFromText(\n content: string,\n existingQuestionKeys: Set<string>,\n ): ExtractionQuestion[] {\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate) as Partial<ProactiveQuestionsResultParsed>;\n if (!Array.isArray(parsed.questions)) continue;\n return parsed.questions\n .map((q) => normalizeQuestion(q as ExtractionQuestion))\n .filter((q) => q.question.length > 0)\n .filter((q) => !existingQuestionKeys.has(q.question.toLowerCase()));\n } catch {\n // Continue to next candidate.\n }\n }\n return [];\n }\n\n private parseProactiveExtractionResultFromText(content: string): ExtractionResult | null {\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = ProactiveExtractionResultSchema.parse(JSON.parse(candidate));\n return this.normalizeExtractionResultPayload({\n ...parsed,\n questions: [],\n });\n } catch {\n // Continue to next candidate.\n }\n }\n return null;\n }\n\n private async generateProactiveQuestions(\n conversation: string,\n base: ExtractionResult,\n maxAdditional: number,\n ): Promise<ExtractionQuestion[]> {\n const existingQuestionKeys = new Set(\n (base.questions ?? [])\n .map((q) => q.question.trim().toLowerCase())\n .filter((q) => q.length > 0),\n );\n const factsPreview = base.facts\n .slice(0, 8)\n .map((f) => `- (${f.category}) ${f.content}`)\n .join(\"\\n\");\n const existingQuestionsPreview = (base.questions ?? [])\n .slice(0, 8)\n .map((q) => `- ${q.question}`)\n .join(\"\\n\");\n\n const prompt = [\n \"You are doing a proactive second-pass memory extraction.\",\n `Generate up to ${maxAdditional} additional high-value follow-up questions not already covered.`,\n \"Return only valid JSON with this shape:\",\n '{\"questions\":[{\"question\":\"...\",\"context\":\"...\",\"priority\":0.0}]}',\n \"\",\n \"Current extracted facts:\",\n factsPreview || \"(none)\",\n \"\",\n \"Questions already extracted (do not repeat):\",\n existingQuestionsPreview || \"(none)\",\n \"\",\n \"Conversation:\",\n conversation,\n ].join(\"\\n\");\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n {\n role: \"system\",\n content: \"You are a proactive memory extraction assistant. Output valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n operation: \"proactive_extraction\",\n priority: \"background\",\n },\n );\n if (localResponse?.content) {\n const localParsed = this.parseProactiveQuestionsFromText(\n localResponse.content.trim(),\n existingQuestionKeys,\n );\n if (localParsed.length > 0) {\n return localParsed.slice(0, maxAdditional);\n }\n }\n if (!this.config.localLlmFallback) {\n return [];\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n throw err;\n }\n }\n }\n\n const fallbackResult = await this.fallbackLlm.parseWithSchema(\n [\n {\n role: \"system\",\n content: \"Generate additional proactive memory follow-up questions. Return valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n ProactiveQuestionsResultSchema,\n this.withGatewayAgent({\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n }),\n );\n if (!fallbackResult?.questions) return [];\n return fallbackResult.questions\n .map((q) => normalizeQuestion(q as ExtractionQuestion))\n .filter((q) => q.question.length > 0)\n .filter((q) => !existingQuestionKeys.has(q.question.toLowerCase()))\n .slice(0, maxAdditional);\n }\n\n private async answerProactiveQuestions(\n conversation: string,\n base: ExtractionResult,\n proactiveQuestions: ExtractionQuestion[],\n maxAdditional: number,\n ): Promise<ExtractionResult> {\n const factsPreview = base.facts\n .slice(0, 8)\n .map((f) => `- (${f.category}) ${f.content}`)\n .join(\"\\n\");\n const entitiesPreview = base.entities\n .slice(0, 8)\n .map((entity) => `- (${entity.type}) ${entity.name}: ${entity.facts.join(\"; \") || \"(no facts)\"}`)\n .join(\"\\n\");\n const proactivePreview = proactiveQuestions\n .slice(0, maxAdditional)\n .map((question, index) => `${index + 1}. ${question.question}${question.context ? `\\n context: ${question.context}` : \"\"}`)\n .join(\"\\n\");\n\n const prompt = [\n \"You are answering proactive memory follow-up questions using only the provided buffered conversation.\",\n `Return at most ${maxAdditional} additional high-confidence memory candidates that were omitted from the base extraction.`,\n \"Only include information directly supported by the conversation. Do not speculate. Do not repeat the base extraction.\",\n \"Return only valid JSON with this shape:\",\n '{\"facts\":[{\"category\":\"fact\",\"content\":\"...\",\"confidence\":0.0,\"tags\":[\"...\"],\"entityRef\":\"optional\",\"promptedByQuestion\":\"optional\"}],\"profileUpdates\":[\"...\"],\"entities\":[{\"name\":\"...\",\"type\":\"person\",\"facts\":[\"...\"],\"promptedByQuestion\":\"optional\"}],\"relationships\":[{\"source\":\"...\",\"target\":\"...\",\"label\":\"...\",\"promptedByQuestion\":\"optional\"}]}',\n \"\",\n \"Base extracted facts (do not repeat):\",\n factsPreview || \"(none)\",\n \"\",\n \"Base extracted entities (do not repeat):\",\n entitiesPreview || \"(none)\",\n \"\",\n \"Answer these follow-up questions from the same conversation only:\",\n proactivePreview || \"(none)\",\n \"\",\n \"Conversation:\",\n conversation,\n ].join(\"\\n\");\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n {\n role: \"system\",\n content: \"You are a proactive memory extraction assistant. Output valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n operation: \"proactive_extraction\",\n priority: \"background\",\n },\n );\n if (localResponse?.content) {\n const parsed = this.parseProactiveExtractionResultFromText(localResponse.content.trim());\n if (parsed) {\n return this.sanitizeExtractionResult(parsed);\n }\n }\n if (!this.config.localLlmFallback) {\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n throw err;\n }\n }\n }\n\n const fallbackResult = await this.fallbackLlm.parseWithSchema(\n [\n {\n role: \"system\",\n content: \"Answer proactive memory follow-up questions from the provided conversation only. Return valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n ProactiveExtractionResultSchema,\n this.withGatewayAgent({\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n }),\n );\n if (!fallbackResult) {\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n return this.sanitizeExtractionResult(\n this.normalizeExtractionResultPayload({\n ...fallbackResult,\n questions: [],\n }),\n );\n }\n\n private mergeProactiveExtractionPass(\n base: ExtractionResult,\n proactive: ExtractionResult,\n maxAdditional: number,\n ): ExtractionResult {\n const allowlist = this.config.proactiveExtractionCategoryAllowlist;\n let remainingBudget = Math.max(0, Math.floor(maxAdditional));\n const mergedFacts = [...base.facts];\n const seenFacts = new Set(base.facts.map((fact) => normalizeFactKey(fact)));\n for (const fact of proactive.facts) {\n if (remainingBudget <= 0) break;\n if (fact.confidence < PROACTIVE_MIN_CONFIDENCE) continue;\n if (allowlist && !allowlist.includes(fact.category as MemoryCategory)) continue;\n const key = normalizeFactKey(fact);\n if (seenFacts.has(key)) continue;\n seenFacts.add(key);\n mergedFacts.push({ ...fact, source: \"proactive\" });\n remainingBudget -= 1;\n }\n\n const mergedEntities = base.entities.map((entity) => ({\n ...entity,\n facts: [...entity.facts],\n }));\n const entityIndex = new Map(mergedEntities.map((entity, index) => [normalizeEntityKey(entity), index]));\n for (const entity of proactive.entities) {\n if (remainingBudget <= 0) break;\n const key = normalizeEntityKey(entity);\n const existingIndex = entityIndex.get(key);\n if (typeof existingIndex === \"number\") {\n const existing = mergedEntities[existingIndex]!;\n const nextFacts = new Set(existing.facts.map((fact) => fact.trim()));\n let changed = false;\n for (const fact of entity.facts) {\n const trimmed = fact.trim();\n if (!trimmed || nextFacts.has(trimmed)) continue;\n nextFacts.add(trimmed);\n changed = true;\n }\n if (changed) {\n mergedEntities[existingIndex] = {\n ...existing,\n facts: Array.from(nextFacts),\n source: \"proactive\",\n promptedByQuestion: existing.promptedByQuestion ?? entity.promptedByQuestion,\n };\n remainingBudget -= 1;\n }\n continue;\n }\n mergedEntities.push({ ...entity, source: \"proactive\" });\n entityIndex.set(key, mergedEntities.length - 1);\n remainingBudget -= 1;\n }\n\n const mergedProfileUpdates = [...base.profileUpdates];\n const seenProfileUpdates = new Set(base.profileUpdates.map((update) => normalizeProfileUpdateKey(update)));\n for (const update of proactive.profileUpdates) {\n if (remainingBudget <= 0) break;\n const key = normalizeProfileUpdateKey(update);\n if (!key || seenProfileUpdates.has(key)) continue;\n seenProfileUpdates.add(key);\n mergedProfileUpdates.push(update.trim());\n remainingBudget -= 1;\n }\n\n const mergedRelationships = [...(base.relationships ?? [])];\n const seenRelationships = new Set(mergedRelationships.map((relationship) => normalizeRelationshipKey(relationship)));\n for (const relationship of proactive.relationships ?? []) {\n if (remainingBudget <= 0) break;\n const key = normalizeRelationshipKey(relationship);\n if (seenRelationships.has(key)) continue;\n seenRelationships.add(key);\n mergedRelationships.push({ ...relationship, extractionSource: \"proactive\" });\n remainingBudget -= 1;\n }\n\n return {\n ...base,\n facts: mergedFacts,\n entities: mergedEntities,\n profileUpdates: mergedProfileUpdates,\n relationships: mergedRelationships,\n };\n }\n\n private async parseWithGatewayFallback<T>(\n traceId: string,\n operation: LlmTraceEvent[\"operation\"],\n startedAtMs: number,\n schema: { parse: (data: unknown) => T },\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: { temperature?: number; maxTokens?: number } = {},\n ): Promise<T | null> {\n const detailed = await this.fallbackLlm.parseWithSchemaDetailed(messages, schema, this.withGatewayAgent(options));\n if (detailed?.result) {\n const durationMs = Date.now() - startedAtMs;\n this.emit({\n kind: \"llm_end\",\n traceId,\n model: detailed.modelUsed,\n operation,\n durationMs,\n output: JSON.stringify(detailed.result).slice(0, 2000),\n });\n return detailed.result;\n }\n return null;\n }\n\n async extract(turns: BufferTurn[], existingEntities?: string[]): Promise<ExtractionResult> {\n\n // Guard: skip if buffer is empty or all turns are whitespace-only\n const substantiveTurns = turns.filter((t) => t.content.trim().length > 0);\n if (substantiveTurns.length === 0) {\n log.debug(\"extraction skipped — no substantive turns in buffer\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n\n const boundedTurns = substantiveTurns\n .map((turn) => ({\n ...turn,\n content: turn.role === \"assistant\"\n ? applyWorkExtractionBoundary(turn.content)\n : turn.content,\n }))\n .filter((turn) => turn.content.trim().length > 0);\n const conversation = boundedTurns\n .map((t) => `[${t.role}] ${t.content}`)\n .join(\"\\n\\n\");\n if (conversation.trim().length === 0) {\n log.debug(\"extraction skipped — conversation only contained non-memory work-layer context\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n\n // Use the last turn's timestamp for temporal anchoring (more accurate than wall-clock)\n const lastTurnTs = boundedTurns.length > 0 ? new Date(boundedTurns[boundedTurns.length - 1].timestamp) : undefined;\n const messageTimestamp = lastTurnTs && !isNaN(lastTurnTs.getTime()) ? lastTurnTs : undefined;\n\n const traceId = crypto.randomUUID();\n // Only emit llm_start for the direct path when a client or local LLM is configured.\n // Fallback-only deployments skip this to avoid fake spans in Opik.\n const emittedDirectStart = !!(this.shouldUseDirectClient || this.shouldUseLocalLlm);\n if (emittedDirectStart) {\n this.emit({ kind: \"llm_start\", traceId, model: this.config.model, operation: \"extraction\", input: conversation });\n }\n let closedDirectTrace = false;\n const startTime = Date.now();\n\n // --- profiling instrumentation ---\n const extractionTraceId = this.profiler.startTrace(\"extraction\", undefined, {\n model: this.config.model,\n localLlm: this.config.localLlmEnabled,\n });\n this.profiler.startSpan(\"total\", extractionTraceId);\n\n try {\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n this.profiler.startSpan(\"local-llm\", extractionTraceId);\n try {\n const localResult = await this.extractWithLocalLlm(conversation, existingEntities);\n if (localResult) {\n const durationMs = Date.now() - startTime;\n this.profiler.endSpan(\"local-llm\", extractionTraceId);\n this.emit({ kind: \"llm_end\", traceId, model: this.config.localLlmModel, operation: \"extraction\", durationMs });\n log.debug(`extraction: used local LLM — ${localResult.facts.length} facts, ${localResult.entities.length} entities`);\n const sanitized = this.sanitizeExtractionResult(localResult, messageTimestamp);\n return await this.applyProactiveQuestionPass(conversation, sanitized);\n }\n // Local failed, fall back if allowed\n if (!this.config.localLlmFallback) {\n log.warn(\"extraction: local LLM failed and fallback disabled\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n log.info(\"extraction: local LLM unavailable, falling back to gateway default AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"extraction: local LLM error and fallback disabled:\", err);\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n log.info(\"extraction: local LLM error, falling back to gateway default AI:\", err);\n } finally {\n // End local-llm span if it wasn't ended on the success path\n try { this.profiler.endSpan(\"local-llm\", extractionTraceId); } catch { /* span may already be closed */ }\n }\n }\n\n // Try direct OpenAI-compatible client (Scryr, OpenRouter, etc.)\n if (this.shouldUseDirectClient) {\n this.profiler.startSpan(\"direct-client\", extractionTraceId);\n try {\n const directResult = await this.extractWithDirectClient(conversation, existingEntities);\n if (directResult) {\n const durationMs = Date.now() - startTime;\n this.profiler.endSpan(\"direct-client\", extractionTraceId);\n this.emit({ kind: \"llm_end\", traceId, model: this.config.model, operation: \"extraction\", durationMs });\n log.debug(`extraction: used direct client (${this.config.model}) — ${directResult.facts.length} facts, ${directResult.entities.length} entities`);\n const sanitized = this.sanitizeExtractionResult(directResult, messageTimestamp);\n return await this.applyProactiveQuestionPass(conversation, sanitized);\n }\n // Emit error event so Opik sees the direct client failure before fallback.\n // Wrapped in try/catch so a subscriber error doesn't break the fallback path.\n try {\n this.emit({\n kind: \"llm_error\", traceId, model: this.config.model, operation: \"extraction\",\n durationMs: Date.now() - startTime, error: \"direct client returned no result\",\n });\n } catch { /* trace emit must not block fallback */ }\n closedDirectTrace = true;\n log.info(\"extraction: direct client returned no result, falling back to gateway AI\");\n } catch (err) {\n try {\n this.emit({\n kind: \"llm_error\", traceId, model: this.config.model, operation: \"extraction\",\n durationMs: Date.now() - startTime, error: String(err),\n });\n } catch { /* trace emit must not block fallback */ }\n closedDirectTrace = true;\n log.info(\"extraction: direct client failed, falling back to gateway AI:\", err);\n } finally {\n try { this.profiler.endSpan(\"direct-client\", extractionTraceId); } catch { /* span may already be closed */ }\n }\n }\n\n // Close any orphaned direct-path llm_start (e.g., local LLM failed, no direct client)\n if (emittedDirectStart && !closedDirectTrace) {\n try {\n this.emit({\n kind: \"llm_error\", traceId, model: this.config.model, operation: \"extraction\",\n durationMs: Date.now() - startTime, error: \"local LLM failed, handing off to gateway fallback\",\n });\n } catch { /* trace emit must not block fallback */ }\n }\n\n // In gateway mode this is the primary extraction path. In plugin mode it is the\n // final fallback after local/direct attempts fail. Emit a fresh llm_start so the\n // gateway-backed call gets its own trace rather than being orphaned under the\n // direct-client traceId.\n const fallbackTraceId = crypto.randomUUID();\n const fallbackStartTime = Date.now();\n if (this.useGatewayModelSource) {\n log.debug(\n `extraction: using gateway model chain as primary path` +\n (this.config.gatewayAgentId ? ` (agent: ${this.config.gatewayAgentId})` : \" (defaults)\"),\n );\n } else {\n log.info(\"extraction: falling back to gateway default AI\");\n }\n\n this.profiler.startSpan(\"gateway-fallback\", extractionTraceId);\n try {\n const messages = [\n { role: \"system\" as const, content: this.buildExtractionInstructions(existingEntities) },\n { role: \"user\" as const, content: conversation },\n ];\n\n this.emit({ kind: \"llm_start\", traceId: fallbackTraceId, model: \"fallback\", operation: \"extraction\", input: conversation });\n\n const detailed = await this.fallbackLlm.parseWithSchemaDetailed(\n messages,\n ExtractionResultSchema,\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 4096, timeoutMs: 30_000 }),\n );\n\n const fallbackDurationMs = Date.now() - fallbackStartTime;\n\n if (detailed?.result && Array.isArray(detailed.result.facts)) {\n const result = detailed.result;\n this.emit({\n kind: \"llm_end\", traceId: fallbackTraceId, model: detailed.modelUsed, operation: \"extraction\",\n durationMs: fallbackDurationMs, output: JSON.stringify(result).slice(0, 2000),\n });\n log.debug(\n `extracted ${result.facts.length} facts, ${result.entities.length} entities, ${(result.questions ?? []).length} questions via fallback (${detailed.modelUsed})`,\n );\n const sanitized = this.sanitizeExtractionResult({\n ...result,\n questions: result.questions ?? [],\n identityReflection: result.identityReflection ?? undefined,\n } as ExtractionResult, messageTimestamp);\n return await this.applyProactiveQuestionPass(conversation, sanitized);\n }\n\n this.emit({\n kind: \"llm_error\", traceId: fallbackTraceId, model: \"fallback\", operation: \"extraction\",\n durationMs: fallbackDurationMs, error: \"fallback returned no parsed output\",\n });\n log.warn(\"extraction fallback returned no parsed output\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: fallbackTraceId, model: \"fallback\", operation: \"extraction\",\n durationMs: Date.now() - fallbackStartTime, error: String(err),\n });\n log.error(\"extraction fallback failed\", err);\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n } finally {\n try { this.profiler.endSpan(\"gateway-fallback\", extractionTraceId); } catch { /* span may already be closed */ }\n }\n\n } finally {\n // --- profiling: close the total span and trace ---\n this.profiler.endSpan(\"total\", extractionTraceId);\n this.profiler.endTrace(extractionTraceId); // persists to JSONL file\n }\n }\n\n /**\n * Extract memories using local LLM with JSON mode.\n * Uses a minimal prompt to fit within local model context limits (typically 4k-8k).\n */\n private async extractWithLocalLlm(conversation: string, existingEntities?: string[]): Promise<ExtractionResult | null> {\n log.debug(\n `extractWithLocalLlm: starting extraction, localLlmEnabled=${this.shouldUseLocalLlm}, model=${this.config.localLlmModel}`,\n );\n\n // Get dynamic context sizes based on model capabilities (with optional user override)\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Model context: ${contextSizes.description}`);\n\n const maxConversationChars = contextSizes.maxInputChars;\n const truncatedConversation = conversation.length > maxConversationChars\n ? conversation.slice(0, maxConversationChars) + \"\\n\\n[truncated]\"\n : conversation;\n\n const localPrompt = `You are a memory extraction system. Extract durable, reusable memories from this conversation.\n\nMemory categories — use the MOST SPECIFIC category that fits:\n- fact: Objective information about the world\n- preference: User likes, dislikes, or stylistic choices\n- correction: User correcting a mistake (highest priority)\n- entity: People, projects, tools, companies (use canonical hyphenated names like \"my-project\")\n- decision: Choices made with rationale\n- relationship: How entities relate (e.g., \"Alice manages Bob\")\n- principle: Durable rules or operating beliefs (e.g., \"never use X API\")\n- commitment: Promises, obligations, deadlines\n- moment: Emotionally significant events\n- skill: Demonstrated capabilities\n\nIMPORTANT: Do NOT label everything as \"fact\". Use \"decision\" for architectural choices, \"commitment\" for deadlines/promises, \"principle\" for reusable rules, \"correction\" for when the user rejects a suggestion, etc.\n\n=== DO NOT EXTRACT (negative examples) ===\nThese are operational noise - skip them:\n- \"The user has a cron job that runs every 30 minutes\" (scheduled task descriptions)\n- \"The user encountered error XYZ at 3:45 PM\" (temporary error states)\n- \"The file is located at /path/to/project/file\" (transient file paths)\n- \"The system is using 4GB of memory\" (current resource usage)\n- \"The user ran the 'git status' command\" (individual command executions)\n- \"The conversation took place on Tuesday\" (session metadata)\n- \"The agent read the file at /path/to/file.txt\" (agent's own actions)\n- \"The user's OpenClaw automation posts to #channel on failures\" (automation behavior descriptions)\n- \"The user stores state in /path/to/state.json\" (implementation details)\n- \"The X-watch automation has been stalled for 58 hours\" (system status updates)\n- \"The user processed 5 batch files and extracted insights\" (processing summaries)\n- \"The user has a cron job that runs a Checkpoint Loop every 2 hours\" (automation schedules)\n- \"The user runs a Morning Surprise cron job daily at 7:30 AM\" (automation schedules)\n- \"The user runs an X Bookmarks → Insights pipeline hourly at :13\" (automation schedules)\n- \"The user's system mines X/Twitter mentions for ideas every 10a/2p/6p\" (automation schedules)\n- \"The user runs a Health Insights cron job weekday mornings\" (automation schedules)\n- \"The system monitors the showcase page every 12 hours\" (system monitoring configurations)\n\n=== DO EXTRACT (positive examples) ===\nThese are durable insights - capture them:\n- \"The user prefers dark mode interfaces and finds light mode uncomfortable\" (preference)\n- \"The user works primarily with TypeScript and avoids Python for frontend code\" (long-term fact)\n- \"The user's side project 'alpha-trader' uses a custom algorithm for arbitrage\" (entity + detail)\n- \"The user corrected that PostgreSQL 15 is required, not version 14\" (correction)\n- \"The user never commits code without running tests first\" (principle)\n- \"The user has a meeting with the design team every Friday at 2pm\" (commitment)\n\n=== Rules ===\n- Extract only NEW information worth remembering across sessions\n- Skip transient details (file paths, current errors, temporary states, agent actions)\n- Confidence: Explicit (0.95-1.0), Implied (0.70-0.94), Inferred (0.40-0.69), Speculative (0.00-0.39)\n- Corrections get highest confidence (0.95+)\n- Each fact should be standalone and self-contained\n- CRITICAL: Use canonical hyphenated entity names (e.g., \"jane-doe\" not \"janedoe\")\n- CRITICAL: NEVER extract the same fact twice - check for duplicates before adding to facts array\n- CRITICAL: NEVER extract cron job schedules, automation configurations, or system monitoring details (these are operational noise)\n- If uncertain about relevance, prefer NOT extracting\n\n=== Structured Attributes ===\nWhen a fact contains measurable, categorical, or precisely valued data, add a \"structuredAttributes\" object with key-value string pairs. This captures exact values for precise retrieval later.\nExamples of when to add structuredAttributes:\n- Product details: {\"price\": \"29.99\", \"brand\": \"Sony\", \"color\": \"black\", \"rating\": \"4.5\"}\n- Person details: {\"age\": \"32\", \"occupation\": \"engineer\", \"city\": \"Austin\"}\n- Events with dates: {\"date\": \"2024-03-15\", \"location\": \"San Francisco\"}\n- Decisions: {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\", \"reason\": \"ACID compliance\"}\n- Quantities/measurements: {\"budget\": \"50000\", \"team_size\": \"5\", \"deadline\": \"2024-06-01\"}\nOnly add structuredAttributes when there are concrete values. Skip for abstract or narrative facts.\n\nAlso generate:\n1. 1-3 genuine questions you're curious about from this conversation\n2. Profile updates about user patterns/behaviors (if any)\n3. Relationships between entities (max 5). Use normalized names like \"person-jane-doe\", \"company-acme-corp\".\n\nOutput JSON:\n{\n \"facts\": [{\"category\": \"decision\", \"content\": \"Chose PostgreSQL over MongoDB for the user service\", \"importance\": 8, \"confidence\": 0.9, \"structuredAttributes\": {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\"}}, {\"category\": \"commitment\", \"content\": \"Must ship v2.0 API by end of March\", \"importance\": 10, \"confidence\": 1.0, \"structuredAttributes\": {\"deadline\": \"end of March\", \"deliverable\": \"v2.0 API\"}}, {\"category\": \"fact\", \"content\": \"The store backend uses Redis for session caching\", \"importance\": 6, \"confidence\": 0.95, \"entityRef\": \"project-acme-store\"}, {\"category\": \"principle\", \"content\": \"Always run migrations in a transaction to avoid partial schema updates\", \"importance\": 8, \"confidence\": 0.9}],\n \"entities\": [{\"name\": \"person-jane-doe\", \"type\": \"person\", \"facts\": [\"Works at Acme Corp\", \"Prefers Python over JavaScript\"]}, {\"name\": \"project-acme-store\", \"type\": \"project\", \"facts\": [\"Built with Next.js\", \"Deployed on Vercel\"]}],\n \"profileUpdates\": [\"User prefers dark mode in all editors\"],\n \"questions\": [{\"question\": \"Which cloud provider hosts the staging environment?\", \"context\": \"Came up during deployment discussion\", \"priority\": 0.5}],\n \"relationships\": [{\"source\": \"person-jane-doe\", \"target\": \"company-acme-corp\", \"label\": \"works at\"}]\n}\n\nConversation:\n${truncatedConversation}`;\n\n log.debug(\n `extractWithLocalLlm: calling localLlm.chatCompletion with prompt length ${localPrompt.length}...`,\n );\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a memory extraction system. Output valid JSON only.\" },\n { role: \"user\", content: localPrompt },\n ],\n {\n temperature: 0.1,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"extraction\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n log.debug(\"extractWithLocalLlm: chatCompletion returned null or empty content\");\n return null;\n }\n\n const content = response.content.trim();\n // Avoid logging model output content by default (may contain user data).\n log.debug(`extractWithLocalLlm: got response content, length=${content.length}`);\n\n try {\n for (const candidate of extractJsonCandidates(content)) {\n try {\n log.debug(`extractWithLocalLlm: attempting JSON parse, candidate length=${candidate.length}`);\n const parsed = JSON.parse(candidate);\n\n const result: ExtractionResult = this.normalizeExtractionResultPayload(parsed);\n\n log.debug(\n `extractWithLocalLlm: successfully parsed response, facts=${result.facts.length}, entities=${result.entities.length}, profileUpdates=${result.profileUpdates.length}, questions=${result.questions.length}`,\n );\n return result;\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n // Try to extract partial facts from truncated JSON\n log.debug(\"extractWithLocalLlm: JSON parse failed, attempting partial extraction...\");\n const partial = this.extractPartialFacts(content);\n if (partial.facts.length > 0 || partial.entities.length > 0) {\n log.debug(\n `extractWithLocalLlm: extracted ${partial.facts.length} partial facts from truncated JSON`,\n );\n return partial;\n }\n\n // Could not extract anything\n const errMsg = err instanceof Error ? err.message : String(err);\n log.debug(`extractWithLocalLlm: JSON parse error: ${errMsg}`);\n return null;\n }\n }\n\n /**\n * Extract memories using direct OpenAI-compatible client (Chat Completions API).\n * Works with Scryr, OpenRouter, and other OpenAI-compatible endpoints.\n */\n private async extractWithDirectClient(\n conversation: string,\n existingEntities?: string[],\n ): Promise<ExtractionResult | null> {\n if (!this.client) return null;\n\n const tokenParams = buildChatCompletionTokenLimit(this.config.model, this.config.extractionMaxOutputTokens, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n });\n log.debug(`extractWithDirectClient: calling model=${this.config.model} tokenParams=${JSON.stringify(tokenParams)}`);\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n {\n role: \"system\",\n content:\n this.buildExtractionInstructions(existingEntities) +\n `\\n\\nRespond with valid JSON matching this schema:\n{\n \"facts\": [{\"category\": \"decision\", \"content\": \"Chose React over Vue for the dashboard rewrite\", \"importance\": 8, \"confidence\": 0.9, \"tags\": [\"frontend\"], \"structuredAttributes\": {\"chosen\": \"React\", \"rejected\": \"Vue\"}}, {\"category\": \"fact\", \"content\": \"The API gateway uses rate limiting at 1000 req/min\", \"importance\": 6, \"confidence\": 0.95, \"tags\": [\"infra\"], \"entityRef\": \"project-dashboard\", \"structuredAttributes\": {\"rate_limit\": \"1000 req/min\"}}],\n \"entities\": [{\"name\": \"person-sarah-chen\", \"type\": \"person\", \"facts\": [\"Leads the backend team\", \"Joined from Google in 2024\"]}, {\"name\": \"project-dashboard\", \"type\": \"project\", \"facts\": [\"React-based admin panel\", \"Deployed on AWS ECS\"]}],\n \"profileUpdates\": [\"User prefers TypeScript over plain JavaScript\"],\n \"questions\": [{\"question\": \"What database does the analytics service use?\", \"context\": \"Came up during discussion of migration plan\", \"priority\": 0.5}],\n \"relationships\": [{\"source\": \"person-sarah-chen\", \"target\": \"project-dashboard\", \"label\": \"leads development of\"}]\n}`,\n },\n { role: \"user\", content: conversation },\n ],\n ...tokenParams,\n });\n\n const content = response.choices?.[0]?.message?.content?.trim();\n if (!content) {\n log.info(`extractWithDirectClient: empty response — choices=${JSON.stringify(response.choices?.length ?? 0)} finishReason=${response.choices?.[0]?.finish_reason ?? \"n/a\"}`);\n return null;\n }\n\n log.info(\n `extractWithDirectClient: got response, length=${content.length}`,\n );\n\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n\n return this.normalizeExtractionResultPayload(parsed);\n } catch {\n // keep trying candidates\n }\n }\n\n log.info(`extractWithDirectClient: failed to parse JSON from response (first 200 chars: ${content.slice(0, 200)})`);\n return null;\n }\n\n /**\n * Extract partial facts from truncated JSON responses.\n * Local LLMs sometimes hit token limits mid-JSON. This tries to salvage valid facts.\n */\n private extractPartialFacts(jsonStr: string): ExtractionResult {\n const allowedCategories = new Set([\n \"fact\",\n \"preference\",\n \"correction\",\n \"entity\",\n \"decision\",\n \"relationship\",\n \"principle\",\n \"commitment\",\n \"moment\",\n \"skill\",\n ]);\n const allowedEntityTypes = new Set([\n \"person\",\n \"project\",\n \"tool\",\n \"company\",\n \"place\",\n \"other\",\n ]);\n\n const facts: ExtractionResult[\"facts\"] = [];\n const entities: ExtractionResult[\"entities\"] = [];\n\n try {\n // Find all complete fact objects (ones with all required fields)\n const factRegex = /\\{\\s*\"category\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"content\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"confidence\"\\s*:\\s*([0-9.]+)/g;\n let match;\n while ((match = factRegex.exec(jsonStr)) !== null) {\n const rawCat = match[1];\n const category = allowedCategories.has(rawCat) ? (rawCat as ExtractionResult[\"facts\"][number][\"category\"]) : \"fact\";\n facts.push({\n category,\n content: match[2].replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"'),\n confidence: parseFloat(match[3]),\n tags: [],\n });\n }\n\n // Find all complete entity objects\n const entityRegex = /\\{\\s*\"name\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"type\"\\s*:\\s*\"([^\"]+)\"/g;\n while ((match = entityRegex.exec(jsonStr)) !== null) {\n const rawType = match[2];\n const type = allowedEntityTypes.has(rawType) ? (rawType as ExtractionResult[\"entities\"][number][\"type\"]) : \"other\";\n entities.push({\n name: match[1],\n type,\n facts: [],\n });\n }\n } catch {\n // Ignore regex errors\n }\n\n return { facts, entities, profileUpdates: [], questions: [] };\n }\n\n /**\n * Build extraction instructions shared between local and cloud LLM.\n */\n private buildExtractionInstructions(existingEntities?: string[]): string {\n return `You are a memory extraction system. Analyze the following conversation and extract durable, reusable memories.\n\nMemory categories:\n- fact: Objective information about the world\n- preference: User likes, dislikes, or stylistic choices\n- correction: User correcting a mistake or misconception (highest priority)\n- entity: Information about a specific person, project, tool, or company\n- decision: A choice that was made with rationale\n- relationship: How two entities relate to each other (e.g., \"Alice is Bob's manager\", \"Acme Corp uses Shopify\")\n- principle: Durable rules, values, or operating beliefs (e.g., \"never use Chat Completions API\")\n- commitment: Promises, obligations, or deadlines (e.g., \"deploy by Friday\", \"call accountant Monday\")\n- moment: Emotionally significant events or milestones (e.g., \"first successful deployment of engram\")\n- skill: Capabilities the user or agent has demonstrated (e.g., \"user is proficient with Kubernetes\")${this.config.causalRuleExtractionEnabled ? `\n- rule: Causal rules discovered through experience (format: \"IF <condition> THEN <action/outcome>\", e.g., \"IF Shopify API returns 401 THEN the admin token is missing read_products scope\")` : \"\"}\n\nRules:\n- Only extract genuinely NEW information worth remembering across sessions\n- Skip transient task details (file paths being edited, current errors, etc.)\n- Priority: corrections > principles${this.config.causalRuleExtractionEnabled ? \" > rules\" : \"\"} > preferences > commitments > decisions > relationships > entities > moments > skills > facts\n- Corrections (user saying \"actually, don't do X\" or \"I prefer Y\") get highest confidence\n- Each fact should be a standalone, self-contained statement\n- Entity references should use normalized names (lowercase, hyphenated: \"jane-doe\", \"acme-corp\")\n- CRITICAL: Entity names must be CANONICAL. Always use the hyphenated multi-word form: \"acme-corp\" NOT \"acmecorp\" or \"acme\". \"jane-doe\" NOT \"janedoe\" or \"jane\". If unsure, prefer the most specific full name.\n- Avoid creating entities typed as \"other\" when a more specific type fits (company, project, tool, person, place)\n- Tags should be concise and reusable (e.g., \"coding-style\", \"personal\", \"tools\")\n- When a fact contains measurable, categorical, or precisely valued data, include a \"structuredAttributes\" field with key-value string pairs (e.g., {\"price\": \"29.99\", \"brand\": \"Sony\"}, {\"date\": \"2024-03-15\", \"location\": \"SF\"}, {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\"}). Only for concrete values, not narrative content.\n- Set confidence using these tiers:\n * Explicit (0.95-1.0): Direct user statements — \"I prefer X\", \"my name is Y\"\n * Implied (0.70-0.94): Strong contextual inference — user consistently does X, clear from conversation flow\n * Inferred (0.40-0.69): Pattern recognition — reasonable guess from limited evidence\n * Speculative (0.00-0.39): Tentative hypothesis — weak signal, needs future confirmation. Speculative memories auto-expire after 30 days if not confirmed.\n- For commitments: include any deadline or timeframe mentioned\n\nEntity creation rules (STRICT):\n- Only create entities for DURABLE things: real people, companies, products, tools, ongoing projects\n- NEVER create entities for transient items: individual PRs, branches, Jira tickets, meetings, agent task IDs, log files, database tables, cron job runs, sessions\n- When you learn something about a transient item (e.g., PR #58 fixed a bug), store it as a FACT with an entityRef to the parent project — do NOT create an entity for the PR itself\n- Prefer attaching facts to broad parent entities rather than creating sub-entities. E.g., \"acme-store uses Algolia for search\" is a fact on entity \"acme-store\", NOT a new entity \"acme-store-algolia-connector\"\n- The entity list should be SHORT — think \"things that would have their own Wikipedia page\" not \"things mentioned in passing\"\n\n${existingEntities && existingEntities.length > 0 ? `\nKNOWN ENTITIES (use these exact names when referencing existing things):\n${existingEntities.join(\", \")}\n\nWhen you see something that matches a known entity, use THAT name exactly. Only create a NEW entity if nothing in this list represents it.\n` : \"\"}\nAlso extract relationships between entities mentioned in the conversation.\n- Format: {source: \"entity-name\", target: \"entity-name\", label: \"relationship description\"}\n- Max 5 relationships per extraction\n- Only include clear, durable relationships (e.g., \"works at\", \"created\", \"manages\", \"uses\")\n- Use normalized entity names (e.g., \"person-jane-doe\", \"company-acme-corp\")\n\nAlso generate 1-3 genuine questions you're curious about based on this conversation. These should be things you'd actually want answers to in future sessions — not prompts, but real curiosity.\n\nFinally, write a brief identity reflection about the AGENT who had this conversation (not about you, the extraction system). Based on what the agent said and did in the conversation:\n- What communication patterns did the agent show? (e.g., proactive vs reactive, verbose vs concise)\n- Did the agent handle the user's needs well or miss something?\n- What behavioral tendencies are visible? (e.g., cautious, creative, thorough, impatient)\n- What could the agent improve next time?\nDo NOT write about the extraction process itself. Do NOT say things like \"I extracted durable facts\" — that's about YOUR job, not the agent's behavior.`;\n }\n\n async consolidate(\n newMemories: MemoryFile[],\n existingMemories: MemoryFile[],\n currentProfile: string,\n ): Promise<ConsolidationResult> {\n const newList = newMemories\n .map(\n (m) =>\n `[${m.frontmatter.id}] (${m.frontmatter.category}) ${m.content}`,\n )\n .join(\"\\n\");\n\n const existingList = existingMemories\n .slice(-50) // Only consolidate against recent memories\n .map(\n (m) =>\n `[${m.frontmatter.id}] (${m.frontmatter.category}) ${m.content}`,\n )\n .join(\"\\n\");\n\n const cTraceId = crypto.randomUUID();\n this.emit({ kind: \"llm_start\", traceId: cTraceId, model: this.config.model, operation: \"consolidation\", input: newList });\n const cStartTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.consolidateWithLocalLlm(newList, existingList, currentProfile);\n if (localResult) {\n const durationMs = Date.now() - cStartTime;\n this.emit({ kind: \"llm_end\", traceId: cTraceId, model: this.config.localLlmModel, operation: \"consolidation\", durationMs });\n log.debug(`consolidation: used local LLM — ${localResult.items.length} decisions`);\n return this.sanitizeConsolidationResult(localResult);\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"consolidation: local LLM failed and fallback disabled\");\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n log.info(\"consolidation: local LLM unavailable, falling back to gateway AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"consolidation: local LLM error and fallback disabled:\", err);\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n log.info(\"consolidation: local LLM error, falling back to gateway AI:\", err);\n }\n }\n\n const fallbackResult = await this.parseWithGatewayFallback(\n cTraceId,\n \"consolidation\",\n cStartTime,\n ConsolidationResultSchema,\n [\n {\n role: \"system\",\n content: `You are a memory consolidation system. Compare new memories against existing ones and decide what to do with each.\n\nActions:\n- ADD: Keep the new memory as-is (no duplicate exists)\n- MERGE: Combine with an existing memory (provide mergeWith ID and updated content)\n- UPDATE: Replace existing memory content (provide updated content)\n- INVALIDATE: Remove existing memory (it's been superseded or is wrong)\n- SKIP: This new memory is redundant (exact duplicate or subset of existing)\n\nAlso:\n- Suggest profile updates based on patterns across memories\n- Identify entity updates for entity tracking${this.config.causalRuleExtractionEnabled ? `\n- When merging or updating memories, look for IF→THEN causal patterns. If a memory describes \"X failed/succeeded because Y\" or \"doing X led to Y\", rewrite its content to make the causal rule explicit in the form \"IF <condition> THEN <action/outcome>\".` : \"\"}`,\n },\n {\n role: \"user\",\n content: `Current behavioral profile:\n${currentProfile || \"(empty)\"}\n\nExisting memories:\n${existingList || \"(none)\"}\n\nNew memories to consolidate:\n${newList}\n\nConsolidate the new memories against existing ones.`,\n },\n ],\n { temperature: 0.3, maxTokens: 4096 },\n );\n if (fallbackResult) {\n log.debug(`consolidation: ${fallbackResult.items.length} decisions via fallback`);\n const normalizedEntityUpdates = fallbackResult.entityUpdates.map((entity) => ({\n ...entity,\n promptedByQuestion:\n typeof entity.promptedByQuestion === \"string\" ? entity.promptedByQuestion : undefined,\n }));\n return this.sanitizeConsolidationResult({\n items: fallbackResult.items.map((item) => ({\n ...item,\n mergeWith: item.mergeWith ?? undefined,\n updatedContent: item.updatedContent ?? undefined,\n })),\n profileUpdates: fallbackResult.profileUpdates,\n entityUpdates: normalizedEntityUpdates,\n });\n }\n\n // Fall back to OpenAI API\n if (!this.client) {\n log.warn(\"consolidation skipped — no OpenAI API key and local LLM failed/disabled\");\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n\n try {\n const systemPrompt = `You are a memory consolidation system. Compare new memories against existing ones and decide what to do with each.\n\nActions:\n- ADD: Keep the new memory as-is (no duplicate exists)\n- MERGE: Combine with an existing memory (provide mergeWith ID and updated content)\n- UPDATE: Replace existing memory content (provide updated content)\n- INVALIDATE: Remove existing memory (it's been superseded or is wrong)\n- SKIP: This new memory is redundant (exact duplicate or subset of existing)\n\nAlso:\n- Suggest profile updates based on patterns across memories\n- Identify entity updates for entity tracking${this.config.causalRuleExtractionEnabled ? `\n- When merging or updating memories, look for IF→THEN causal patterns. If a memory describes \"X failed/succeeded because Y\" or \"doing X led to Y\", rewrite its content to make the causal rule explicit in the form \"IF <condition> THEN <action/outcome>\".` : \"\"}\n\nCurrent behavioral profile:\n${currentProfile || \"(empty)\"}\n\nExisting memories:\n${existingList || \"(none)\"}\n\nNew memories to consolidate:\n${newList}\n\nRespond with valid JSON only, matching this schema:\n{\n \"items\": [\n {\n \"existingId\": \"id\",\n \"action\": \"ADD\",\n \"mergeWith\": \"optional-existing-id\",\n \"updatedContent\": \"optional replacement content\",\n \"reason\": \"brief reason for this action\"\n }\n ],\n \"profileUpdates\": [\"optional profile update\"],\n \"entityUpdates\": [{\"name\": \"person-jane-doe\", \"type\": \"person\", \"facts\": [\"Now leads the backend team\", \"Recently migrated the user service to TypeScript\"]}]\n}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: \"Consolidate the new memories against existing ones.\" },\n ],\n ...(this.config.reasoningEffort !== \"none\" ? { reasoning_effort: this.config.reasoningEffort } : {}),\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const rawContent = response.choices?.[0]?.message?.content?.trim();\n const cDurationMs = Date.now() - cStartTime;\n const cUsage = (response as any).usage;\n\n let parsed: any = null;\n if (rawContent) {\n for (const candidate of extractJsonCandidates(rawContent)) {\n try {\n parsed = JSON.parse(candidate);\n break;\n } catch {\n // keep trying candidates\n }\n }\n }\n\n this.emit({\n kind: \"llm_end\", traceId: cTraceId, model: this.config.model, operation: \"consolidation\", durationMs: cDurationMs,\n output: parsed ? JSON.stringify(parsed).slice(0, 2000) : undefined,\n tokenUsage: cUsage ? { input: cUsage.prompt_tokens, output: cUsage.completion_tokens, total: cUsage.total_tokens } : undefined,\n });\n\n if (parsed && Array.isArray(parsed.items)) {\n const normalizedItems = parsed.items\n .map((item: any) => {\n const rawAction = typeof item?.action === \"string\" ? item.action.toUpperCase() : \"SKIP\";\n const action =\n rawAction === \"ADD\" ||\n rawAction === \"MERGE\" ||\n rawAction === \"UPDATE\" ||\n rawAction === \"INVALIDATE\" ||\n rawAction === \"SKIP\"\n ? rawAction\n : \"SKIP\";\n return {\n existingId:\n typeof item?.existingId === \"string\"\n ? item.existingId\n : typeof item?.newMemoryId === \"string\"\n ? item.newMemoryId\n : \"\",\n action,\n mergeWith: typeof item?.mergeWith === \"string\" ? item.mergeWith : undefined,\n updatedContent: typeof item?.updatedContent === \"string\" ? item.updatedContent : undefined,\n reason: typeof item?.reason === \"string\" ? item.reason : \"\",\n };\n })\n .filter((item: any) => item.existingId.length > 0);\n const normalizedEntityUpdates = Array.isArray(parsed.entityUpdates)\n ? parsed.entityUpdates\n .map((entity: any) => ({\n name: typeof entity?.name === \"string\" ? entity.name : \"\",\n type: typeof entity?.type === \"string\" ? entity.type : \"other\",\n facts: Array.isArray(entity?.facts)\n ? entity.facts.filter((fact: any) => typeof fact === \"string\")\n : [],\n }))\n .filter((entity: any) => entity.name.length > 0)\n : [];\n log.debug(\n `consolidation: ${normalizedItems.length} decisions`,\n );\n return this.sanitizeConsolidationResult({\n items: normalizedItems,\n profileUpdates: Array.isArray(parsed.profileUpdates)\n ? parsed.profileUpdates.filter((update: unknown) => typeof update === \"string\" && update.trim().length > 0)\n : [],\n entityUpdates: normalizedEntityUpdates,\n } as ConsolidationResult);\n }\n\n log.warn(\"consolidation returned no parsed output\");\n return { items: [], profileUpdates: [], entityUpdates: [] };\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: cTraceId, model: this.config.model, operation: \"consolidation\",\n durationMs: Date.now() - cStartTime, error: String(err),\n });\n log.error(\"consolidation failed\", err);\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n }\n\n /**\n * Consolidate memories using local LLM.\n */\n private async consolidateWithLocalLlm(\n newList: string,\n existingList: string,\n currentProfile: string,\n ): Promise<ConsolidationResult | null> {\n // Get dynamic context sizes\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Consolidation model context: ${contextSizes.description}`);\n\n const prompt = `You are a memory consolidation system. Compare new memories against existing ones and decide what to do with each.\n\nActions:\n- ADD: Keep the new memory as-is (no duplicate exists)\n- MERGE: Combine with an existing memory (provide mergeWith ID and updated content)\n- UPDATE: Replace existing memory content (provide updated content)\n- INVALIDATE: Remove existing memory (it's been superseded or is wrong)\n- SKIP: This new memory is redundant (exact duplicate or subset of existing)\n\nAlso:\n- Suggest profile updates based on patterns across memories\n- Identify entity updates for entity tracking${this.config.causalRuleExtractionEnabled ? `\n- When merging or updating memories, look for IF→THEN causal patterns. If a memory describes \"X failed/succeeded because Y\" or \"doing X led to Y\", rewrite its content to make the causal rule explicit in the form \"IF <condition> THEN <action/outcome>\".` : \"\"}\n\nCurrent behavioral profile:\n${currentProfile || \"(empty)\"}\n\nExisting memories:\n${existingList || \"(none)\"}\n\nNew memories to consolidate:\n${newList}\n\nRespond with valid JSON matching this schema:\n{\n \"items\": [\n {\"memoryId\": \"id\", \"action\": \"ADD|MERGE|UPDATE|INVALIDATE|SKIP\", \"reason\": \"why\", \"updatedContent\": \"optional new content\"}\n ],\n \"profileUpdates\": [{\"section\": \"section name\", \"content\": \"new bullet\"}],\n \"entityUpdates\": [{\"entityId\": \"id\", \"updates\": {\"field\": \"value\"}}]\n}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a memory consolidation system. Output valid JSON only.\" },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"consolidation\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return {\n items: Array.isArray((parsed as any).items) ? (parsed as any).items : [],\n profileUpdates: Array.isArray((parsed as any).profileUpdates)\n ? (parsed as any).profileUpdates\n : [],\n entityUpdates: Array.isArray((parsed as any).entityUpdates)\n ? (parsed as any).entityUpdates\n : [],\n } as ConsolidationResult;\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM consolidation: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n /**\n * Consolidate a bloated profile.md into a compact version.\n * The LLM merges duplicates, removes stale info, and preserves section structure.\n * Returns the consolidated markdown or null on failure.\n */\n async consolidateProfile(\n fullProfileContent: string,\n targetLines: number = 50,\n ): Promise<{ consolidatedProfile: string; removedCount: number; summary: string } | null> {\n const pTraceId = crypto.randomUUID();\n this.emit({ kind: \"llm_start\", traceId: pTraceId, model: this.config.model, operation: \"profile_consolidation\", input: fullProfileContent.slice(0, 2000) });\n const pStartTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.consolidateProfileWithLocalLlm(fullProfileContent, targetLines);\n if (localResult) {\n const durationMs = Date.now() - pStartTime;\n this.emit({ kind: \"llm_end\", traceId: pTraceId, model: this.config.localLlmModel, operation: \"profile_consolidation\", durationMs });\n log.debug(`profile consolidation: used local LLM — removed ${localResult.removedCount} items`);\n return localResult;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"profile consolidation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"profile consolidation: local LLM unavailable, falling back to gateway AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"profile consolidation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"profile consolidation: local LLM error, falling back to gateway AI:\", err);\n }\n }\n\n const profileFallback = await this.parseWithGatewayFallback(\n pTraceId,\n \"profile_consolidation\",\n pStartTime,\n buildProfileConsolidationResultSchema(targetLines),\n [\n {\n role: \"system\",\n content: `You are a profile consolidation system. You are given a behavioral profile (markdown) that has grown too large. Your job is to produce a CONSOLIDATED version that:\n\n1. PRESERVES all ## section headers and their structure\n2. MERGES duplicate or near-duplicate bullet points into single, clear statements\n3. REMOVES stale information that has been superseded by newer bullets\n4. REMOVES trivial or overly specific operational details that won't be useful across sessions\n5. KEEPS the most important, durable observations about the user's preferences, habits, identity, and working style\n6. Target roughly ${targetLines} lines — this is a soft target, prioritize quality over length\n7. Write in the same style as the existing profile — concise bullets, no fluff\n\nThe output should be the COMPLETE consolidated profile as valid markdown, starting with \"# Behavioral Profile\".`,\n },\n { role: \"user\", content: fullProfileContent },\n ],\n { temperature: 0.3, maxTokens: 4096 },\n );\n if (profileFallback) {\n log.debug(\n `profile consolidation: removed ${profileFallback.removedCount} items — ${profileFallback.summary} (fallback)`,\n );\n return profileFallback;\n }\n\n // Fall back to OpenAI API\n if (!this.client) {\n log.warn(\"profile consolidation skipped — no OpenAI API key and local LLM failed/disabled\");\n return null;\n }\n\n try {\n const systemPrompt = `You are a profile consolidation system. You are given a behavioral profile (markdown) that has grown too large. Your job is to produce a CONSOLIDATED version that:\n\n1. PRESERVES all ## section headers and their structure\n2. MERGES duplicate or near-duplicate bullet points into single, clear statements\n3. REMOVES stale information that has been superseded by newer bullets\n4. REMOVES trivial or overly specific operational details that won't be useful across sessions\n5. KEEPS the most important, durable observations about the user's preferences, habits, identity, and working style\n6. Target roughly ${targetLines} lines — this is a soft target, prioritize quality over length\n7. Write in the same style as the existing profile — concise bullets, no fluff\n\nThe output should be the COMPLETE consolidated profile as valid markdown, starting with \"# Behavioral Profile\".\n\nRespond with valid JSON matching this schema:\n{\n \"consolidatedProfile\": \"# Behavioral Profile\\\\n\\\\n... (complete markdown)\",\n \"removedCount\": 42,\n \"summary\": \"brief summary of what was consolidated\"\n}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: fullProfileContent },\n ],\n ...(this.config.reasoningEffort !== \"none\" ? { reasoning_effort: this.config.reasoningEffort } : {}),\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const rawContent = response.choices?.[0]?.message?.content?.trim();\n const pDurationMs = Date.now() - pStartTime;\n const pUsage = (response as any).usage;\n\n let parsed: any = null;\n if (rawContent) {\n for (const candidate of extractJsonCandidates(rawContent)) {\n try {\n parsed = JSON.parse(candidate);\n break;\n } catch {\n // keep trying candidates\n }\n }\n }\n\n this.emit({\n kind: \"llm_end\", traceId: pTraceId, model: this.config.model, operation: \"profile_consolidation\", durationMs: pDurationMs,\n output: parsed ? parsed.summary : undefined,\n tokenUsage: pUsage ? { input: pUsage.prompt_tokens, output: pUsage.completion_tokens, total: pUsage.total_tokens } : undefined,\n });\n\n if (parsed && typeof parsed.consolidatedProfile === \"string\") {\n log.debug(\n `profile consolidation: removed ${parsed.removedCount ?? 0} items — ${parsed.summary ?? \"\"}`,\n );\n return {\n consolidatedProfile: parsed.consolidatedProfile,\n removedCount: Number(parsed.removedCount || 0),\n summary: String(parsed.summary || \"\"),\n };\n }\n\n log.warn(\"profile consolidation returned no parsed output\");\n return null;\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: pTraceId, model: this.config.model, operation: \"profile_consolidation\",\n durationMs: Date.now() - pStartTime, error: String(err),\n });\n log.error(\"profile consolidation failed\", err);\n return null;\n }\n }\n\n /**\n * Consolidate profile using local LLM.\n */\n private async consolidateProfileWithLocalLlm(\n fullProfileContent: string,\n targetLines: number = 50,\n ): Promise<{ consolidatedProfile: string; removedCount: number; summary: string } | null> {\n // Get dynamic context sizes\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Profile consolidation model context: ${contextSizes.description}`);\n\n const prompt = `You are a profile consolidation system. You are given a behavioral profile (markdown) that has grown too large. Your job is to produce a CONSOLIDATED version that:\n\n1. PRESERVES all ## section headers and their structure\n2. MERGES duplicate or near-duplicate bullet points into single, clear statements\n3. REMOVES stale information that has been superseded by newer bullets\n4. REMOVES trivial or overly specific operational details that won't be useful across sessions\n5. KEEPS the most important, durable observations about the user's preferences, habits, identity, and working style\n6. Target roughly ${targetLines} lines — this is a soft target, prioritize quality over length\n7. Write in the same style as the existing profile — concise bullets, no fluff\n\nProfile to consolidate:\n${fullProfileContent}\n\nRespond with valid JSON matching this schema:\n{\n \"consolidatedProfile\": \"# Behavioral Profile\\\\n\\\\n... (complete markdown)\",\n \"removedCount\": 42,\n \"summary\": \"brief summary of what was consolidated\"\n}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a profile consolidation system. Output valid JSON only.\" },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"profile_consolidation\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return {\n consolidatedProfile: String((parsed as any).consolidatedProfile || \"\"),\n removedCount: Number((parsed as any).removedCount || 0),\n summary: String((parsed as any).summary || \"\"),\n };\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM profile consolidation: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n /**\n * Consolidate IDENTITY.md reflections into a concise \"Learned Patterns\" section.\n * Returns the new content for the IDENTITY.md file (everything below the static header).\n */\n async consolidateIdentity(\n fullIdentityContent: string,\n staticHeaderEndMarker: string,\n ): Promise<{ learnedPatterns: string[]; summary: string } | null> {\n const iTraceId = crypto.randomUUID();\n this.emit({ kind: \"llm_start\", traceId: iTraceId, model: this.config.model, operation: \"identity_consolidation\", input: fullIdentityContent.slice(0, 2000) });\n const iStartTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.consolidateIdentityWithLocalLlm(fullIdentityContent);\n if (localResult) {\n const durationMs = Date.now() - iStartTime;\n this.emit({ kind: \"llm_end\", traceId: iTraceId, model: this.config.localLlmModel, operation: \"identity_consolidation\", durationMs });\n log.debug(`identity consolidation: used local LLM — ${localResult.learnedPatterns.length} patterns`);\n return localResult;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"identity consolidation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"identity consolidation: local LLM unavailable, falling back to gateway AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"identity consolidation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"identity consolidation: local LLM error, falling back to gateway AI:\", err);\n }\n }\n\n const identityFallback = await this.parseWithGatewayFallback(\n iTraceId,\n \"identity_consolidation\",\n iStartTime,\n IdentityConsolidationResultSchema,\n [\n {\n role: \"system\",\n content: `You are an identity consolidation system. You are given the full contents of an IDENTITY.md file that contains many individual reflection entries. Your job is to:\n\n1. Read all the reflection entries (sections starting with \"## Reflection\")\n2. Extract the most important, durable behavioral patterns and lessons learned\n3. Consolidate them into concise, standalone statements (aim for 10-25 key patterns)\n4. Remove redundancy — if multiple reflections say the same thing, merge into one clear statement\n5. Prioritize patterns that are actionable and recurring over one-off observations\n6. Write a brief summary paragraph\n\nThe goal is to reduce a bloated file to a compact, high-signal set of learned patterns while preserving all genuinely useful self-knowledge.`,\n },\n { role: \"user\", content: fullIdentityContent },\n ],\n { temperature: 0.3, maxTokens: 4096 },\n );\n if (identityFallback) {\n log.debug(\n `identity consolidation: ${identityFallback.learnedPatterns.length} patterns (fallback)`,\n );\n return identityFallback;\n }\n\n // Fall back to OpenAI API\n if (!this.client) {\n log.warn(\"identity consolidation skipped — no OpenAI API key and local LLM failed/disabled\");\n return null;\n }\n\n try {\n const systemPrompt = `You are an identity consolidation system. You are given the full contents of an IDENTITY.md file that contains many individual reflection entries. Your job is to:\n\n1. Read all the reflection entries (sections starting with \"## Reflection\")\n2. Extract the most important, durable behavioral patterns and lessons learned\n3. Consolidate them into concise, standalone statements (aim for 10-25 key patterns)\n4. Remove redundancy — if multiple reflections say the same thing, merge into one clear statement\n5. Prioritize patterns that are actionable and recurring over one-off observations\n6. Write a brief summary paragraph\n\nThe goal is to reduce a bloated file to a compact, high-signal set of learned patterns while preserving all genuinely useful self-knowledge.\n\nRespond with valid JSON matching this schema:\n{\n \"learnedPatterns\": [\"pattern 1\", \"pattern 2\", \"pattern 3\"],\n \"summary\": \"brief summary of consolidation\"\n}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: fullIdentityContent },\n ],\n ...(this.config.reasoningEffort !== \"none\" ? { reasoning_effort: this.config.reasoningEffort } : {}),\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const rawContent = response.choices?.[0]?.message?.content?.trim();\n const iDurationMs = Date.now() - iStartTime;\n const iUsage = (response as any).usage;\n\n let parsed: any = null;\n if (rawContent) {\n for (const candidate of extractJsonCandidates(rawContent)) {\n try {\n parsed = JSON.parse(candidate);\n break;\n } catch {\n // keep trying candidates\n }\n }\n }\n\n this.emit({\n kind: \"llm_end\", traceId: iTraceId, model: this.config.model, operation: \"identity_consolidation\", durationMs: iDurationMs,\n output: parsed ? parsed.summary : undefined,\n tokenUsage: iUsage ? { input: iUsage.prompt_tokens, output: iUsage.completion_tokens, total: iUsage.total_tokens } : undefined,\n });\n\n if (parsed && Array.isArray(parsed.learnedPatterns)) {\n const learnedPatterns = parsed.learnedPatterns\n .filter((pattern: unknown) => typeof pattern === \"string\")\n .map((pattern: string) => pattern.trim())\n .filter((pattern: string) => pattern.length > 0);\n log.debug(\n `identity consolidation: ${learnedPatterns.length} patterns`,\n );\n return {\n learnedPatterns,\n summary: String(parsed.summary || \"\"),\n };\n }\n\n log.warn(\"identity consolidation returned no parsed output\");\n return null;\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: iTraceId, model: this.config.model, operation: \"identity_consolidation\",\n durationMs: Date.now() - iStartTime, error: String(err),\n });\n log.error(\"identity consolidation failed\", err);\n return null;\n }\n }\n\n /**\n * Consolidate identity using local LLM.\n */\n private async consolidateIdentityWithLocalLlm(\n fullIdentityContent: string,\n ): Promise<{ learnedPatterns: string[]; summary: string } | null> {\n // Get dynamic context sizes\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Identity consolidation model context: ${contextSizes.description}`);\n\n const prompt = `You are an identity consolidation system. You are given the full contents of an IDENTITY.md file that contains many individual reflection entries. Your job is to:\n\n1. Read all the reflection entries (sections starting with \"## Reflection\")\n2. Extract the most important, durable behavioral patterns and lessons learned\n3. Consolidate them into concise, standalone statements (aim for 10-25 key patterns)\n4. Remove redundancy — if multiple reflections say the same thing, merge into one clear statement\n5. Prioritize patterns that are actionable and recurring over one-off observations\n6. Write a brief summary paragraph\n\nThe goal is to reduce a bloated file to a compact, high-signal set of learned patterns while preserving all genuinely useful self-knowledge.\n\nIDENTITY.md content:\n${fullIdentityContent}\n\nRespond with valid JSON matching this schema:\n{\n \"learnedPatterns\": [\"pattern 1\", \"pattern 2\", \"pattern 3\"],\n \"summary\": \"brief summary of consolidation\"\n}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are an identity consolidation system. Output valid JSON only.\" },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"identity_consolidation\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return {\n learnedPatterns: Array.isArray((parsed as any).learnedPatterns)\n ? (parsed as any).learnedPatterns\n : [],\n summary: String((parsed as any).summary || \"\"),\n };\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM identity consolidation: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n /**\n * Verify if two memories contradict each other using LLM.\n * Called when QMD finds semantically similar memories (Phase 2B).\n */\n async verifyContradiction(\n newMemory: { content: string; category: string },\n existingMemory: { id: string; content: string; category: string; created: string },\n ): Promise<ContradictionVerificationResult | null> {\n const input = `Memory 1 (existing, created ${existingMemory.created}):\nCategory: ${existingMemory.category}\nContent: ${existingMemory.content}\n\nMemory 2 (new):\nCategory: ${newMemory.category}\nContent: ${newMemory.content}`;\n\n try {\n const systemPrompt = `You are a contradiction detection system. Analyze whether two memories contradict each other.\n\nIMPORTANT: Not all similar memories are contradictions!\n- \"User likes TypeScript\" and \"User likes Python\" are NOT contradictions (preferences can coexist)\n- \"User prefers dark mode\" and \"User prefers light mode\" ARE contradictions (mutually exclusive)\n- \"User's email is a@b.com\" and \"User's email is c@d.com\" ARE contradictions (only one email)\n- \"User works at Acme\" and \"User used to work at Acme\" might be a contradiction (temporal change)\n\nOnly mark as contradiction if the two statements CANNOT both be true at the same time.\n\nIf they ARE contradictory, determine which represents the more recent/current state based on:\n- Explicit time references (\"now\", \"currently\", \"used to\", \"no longer\")\n- The fact that newer corrections often start with \"actually\" or \"correction\"\n- Context clues about change over time\n\nRespond with valid JSON matching this schema:\n{\n \"isContradiction\": true,\n \"confidence\": 0.95,\n \"reasoning\": \"why they contradict or don't\",\n \"whichIsNewer\": \"first\"\n}`;\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: input },\n ],\n {\n temperature: 0.3,\n maxTokens: 2048,\n operation: \"contradiction_verification\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeContradictionVerificationResult(\n this.parseJsonObject(localResponse?.content),\n );\n if (normalized) {\n log.debug(\n `contradiction check via local LLM: ${normalized.isContradiction ? \"YES\" : \"NO\"} (confidence: ${normalized.confidence})`,\n );\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"contradiction verification skipped — local LLM returned invalid JSON and cloud fallback is disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(`contradiction verification skipped — local LLM failed and cloud fallback is disabled: ${err}`);\n return null;\n }\n }\n }\n\n if (!this.shouldUseDirectClient) {\n const fallbackResponse = await this.fallbackLlm.chatCompletion(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: input },\n ],\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 2048 }),\n );\n const normalized = this.normalizeContradictionVerificationResult(\n this.parseJsonObject(fallbackResponse?.content),\n );\n if (normalized) {\n log.debug(\n `contradiction check via fallback: ${normalized.isContradiction ? \"YES\" : \"NO\"} (confidence: ${normalized.confidence})`,\n );\n return normalized;\n }\n log.warn(\"contradiction verification skipped — no OpenAI API key and fallback unavailable\");\n return null;\n }\n\n const response = await this.client!.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: input },\n ],\n ...buildChatCompletionTokenLimit(this.config.model, 2048, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const normalized = this.normalizeContradictionVerificationResult(\n this.parseJsonObject(response.choices?.[0]?.message?.content),\n );\n if (normalized) {\n log.debug(\n `contradiction check: ${normalized.isContradiction ? \"YES\" : \"NO\"} (confidence: ${normalized.confidence})`,\n );\n return normalized;\n }\n\n return null;\n } catch (err) {\n log.error(\"contradiction verification failed\", err);\n return null;\n }\n }\n\n /**\n * Suggest links between a new memory and existing memories (Phase 3A).\n * Called during extraction to build the knowledge graph.\n */\n async suggestLinks(\n newMemory: { content: string; category: string },\n candidateMemories: Array<{ id: string; content: string; category: string }>,\n ): Promise<SuggestedLinks | null> {\n if (candidateMemories.length === 0) {\n return { links: [] };\n }\n\n const candidateList = candidateMemories\n .map((m, i) => `[${i + 1}] ID: ${m.id}\\nCategory: ${m.category}\\nContent: ${m.content}`)\n .join(\"\\n\\n\");\n\n const input = `New memory:\nCategory: ${newMemory.category}\nContent: ${newMemory.content}\n\nCandidate memories to link to:\n${candidateList}`;\n\n try {\n const systemPrompt = `You are a memory linking system. Analyze the new memory and suggest relationships to existing memories.\n\nLink types:\n- follows: This memory is a continuation or next step (e.g., decision follows discussion)\n- references: This memory mentions or refers to the other (e.g., fact references entity)\n- contradicts: This memory conflicts with the other (use sparingly, only for true contradictions)\n- supports: This memory provides evidence or reinforcement (e.g., example supports principle)\n- related: General topical relationship\n\nRules:\n- Only suggest links with strength > 0.5\n- Quality over quantity — 0-3 links is typical\n- Prefer specific link types over generic \"related\"\n- Consider entity references, topics, and causal relationships\n\nRespond with valid JSON matching this schema:\n{\n \"links\": [{\"targetId\": \"memory-id\", \"linkType\": \"follows|references|contradicts|supports|related\", \"strength\": 0.8, \"reason\": \"why\"}]\n}`;\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: input },\n ],\n {\n temperature: 0.3,\n maxTokens: 2048,\n operation: \"link_suggestion\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeSuggestedLinksResult(this.parseJsonObject(localResponse?.content));\n if (normalized) {\n log.debug(`suggested ${normalized.links.length} links via local LLM`);\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"link suggestion skipped — local LLM returned invalid JSON and cloud fallback is disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(`link suggestion skipped — local LLM failed and cloud fallback is disabled: ${err}`);\n return null;\n }\n }\n }\n\n if (!this.shouldUseDirectClient) {\n const fallbackResponse = await this.fallbackLlm.chatCompletion(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: input },\n ],\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 2048 }),\n );\n const normalized = this.normalizeSuggestedLinksResult(this.parseJsonObject(fallbackResponse?.content));\n if (normalized) {\n log.debug(`suggested ${normalized.links.length} links via fallback`);\n return normalized;\n }\n log.warn(\"link suggestion skipped — no OpenAI API key and fallback unavailable\");\n return null;\n }\n\n const response = await this.client!.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: input },\n ],\n ...buildChatCompletionTokenLimit(this.config.model, 2048, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const normalized = this.normalizeSuggestedLinksResult(\n this.parseJsonObject(response.choices?.[0]?.message?.content),\n );\n if (normalized) {\n log.debug(`suggested ${normalized.links.length} links`);\n return normalized;\n }\n\n return null;\n } catch (err) {\n log.error(\"link suggestion failed\", err);\n return null;\n }\n }\n\n async generateDaySummary(memories: string | MemoryFile[]): Promise<DaySummaryResultShape | null> {\n if (!this.config.daySummaryEnabled) {\n log.warn(\"day summary skipped — disabled by config\");\n return null;\n }\n\n const memoryContext = formatDaySummaryMemories(memories);\n if (memoryContext.length === 0) return null;\n\n const systemPrompt = await loadDaySummaryPrompt();\n const userPrompt = `Generate an end-of-day summary from this Remnic memory context:\n\n${memoryContext}`;\n const traceId = crypto.randomUUID();\n const startedAt = Date.now();\n this.emit({ kind: \"llm_start\", traceId, model: this.config.model, operation: \"day_summary\", input: memoryContext.slice(0, 4000) });\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: `${systemPrompt}\n\nReturn valid JSON only.` },\n { role: \"user\", content: userPrompt },\n ],\n {\n temperature: 0.2,\n maxTokens: 2048,\n operation: \"day_summary\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeDaySummaryResult(this.parseJsonObject(localResponse?.content));\n if (normalized) {\n this.emit({ kind: \"llm_end\", traceId, model: this.config.localLlmModel, operation: \"day_summary\", durationMs: Date.now() - startedAt, output: JSON.stringify(normalized).slice(0, 2000) });\n log.debug(`generated day summary via local LLM (${normalized.bullets.length} bullets)`);\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n this.emit({ kind: \"llm_error\", traceId, model: this.config.localLlmModel, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: \"local LLM returned invalid JSON and fallback disabled\" });\n log.warn(\"day summary skipped — local LLM returned invalid JSON and fallback disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n this.emit({ kind: \"llm_error\", traceId, model: this.config.localLlmModel, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: String(err) });\n log.warn(`day summary skipped — local LLM failed and fallback disabled: ${err}`);\n return null;\n }\n }\n }\n\n const fallbackResult = await this.parseWithGatewayFallback(\n traceId,\n \"day_summary\",\n startedAt,\n DaySummaryResultSchema,\n [\n { role: \"system\", content: `${systemPrompt}\n\nReturn valid JSON only.` },\n { role: \"user\", content: userPrompt },\n ],\n { temperature: 0.2, maxTokens: 2048 },\n );\n if (fallbackResult) {\n const normalized = this.normalizeDaySummaryResult(fallbackResult);\n if (normalized) {\n log.debug(`generated day summary via fallback (${normalized.bullets.length} bullets)`);\n return normalized;\n }\n }\n\n // Direct Responses API fallback (AGENTS.md-compliant: never Chat Completions)\n if (this.shouldUseDirectClient) {\n try {\n const response = await (this.client as any).responses.create({\n model: this.config.model,\n instructions: `${systemPrompt}\\n\\nReturn valid JSON only.`,\n input: userPrompt,\n max_output_tokens: 2048,\n });\n const rawText = typeof response.output_text === \"string\" ? response.output_text : JSON.stringify(response.output_text ?? \"\");\n const normalized = this.normalizeDaySummaryResult(this.parseJsonObject(rawText));\n if (normalized) {\n this.emit({ kind: \"llm_end\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, output: JSON.stringify(normalized).slice(0, 2000) });\n log.debug(`generated day summary via Responses API (${normalized.bullets.length} bullets)`);\n return normalized;\n }\n this.emit({ kind: \"llm_error\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: \"Responses API returned unparseable output\" });\n } catch (err) {\n this.emit({ kind: \"llm_error\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: `Responses API failed: ${err}` });\n }\n }\n\n this.emit({ kind: \"llm_error\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: \"all generation paths exhausted (local LLM + gateway + Responses API)\" });\n log.warn(\"day summary skipped — all generation paths exhausted\");\n return null;\n }\n\n\n /**\n * Summarize a batch of old memories into a compact summary (Phase 4A).\n */\n async summarizeMemories(\n memories: Array<{ id: string; content: string; category: string; created: string }>,\n ): Promise<MemorySummaryResult | null> {\n if (memories.length === 0) return null;\n\n const memoryList = memories\n .map((m) => `[${m.id}] (${m.category}, ${m.created.slice(0, 10)})\\n${m.content}`)\n .join(\"\\n\\n\");\n\n try {\n const systemPrompt = `You are a memory summarization system. You are given a batch of old memories that need to be compressed into a summary.\n\nYour task:\n1. Write a concise summary paragraph (2-4 sentences) capturing the essence of these memories\n2. Extract the 5-10 most important facts that should be preserved\n3. List the key entities mentioned\n\nGuidelines:\n- Preserve specific, actionable information\n- Merge redundant details into single statements\n- Focus on durable insights, not transient details\n- Maintain any preferences, decisions, or corrections as key facts\n\nRespond with valid JSON matching this schema:\n{\n \"summaryText\": \"concise summary paragraph\",\n \"keyFacts\": [\"fact 1\", \"fact 2\"],\n \"keyEntities\": [\"entity-1\", \"entity-2\"]\n}`;\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: `Summarize these ${memories.length} memories:\\n\\n${memoryList}` },\n ],\n {\n temperature: 0.3,\n maxTokens: 4096,\n operation: \"memory_summarization\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeMemorySummaryResult(this.parseJsonObject(localResponse?.content));\n if (normalized) {\n log.debug(\n `summarized ${memories.length} memories into ${normalized.keyFacts.length} key facts via local LLM`,\n );\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"summarization skipped — local LLM returned invalid JSON and cloud fallback is disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(`summarization skipped — local LLM failed and cloud fallback is disabled: ${err}`);\n return null;\n }\n }\n }\n\n if (!this.shouldUseDirectClient) {\n const fallbackResponse = await this.fallbackLlm.chatCompletion(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: `Summarize these ${memories.length} memories:\\n\\n${memoryList}` },\n ],\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 4096 }),\n );\n const normalized = this.normalizeMemorySummaryResult(this.parseJsonObject(fallbackResponse?.content));\n if (normalized) {\n log.debug(`summarized ${memories.length} memories into ${normalized.keyFacts.length} key facts via fallback`);\n return normalized;\n }\n log.warn(\"summarization skipped — no OpenAI API key and fallback unavailable\");\n return null;\n }\n\n const response = await this.client!.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: `Summarize these ${memories.length} memories:\\n\\n${memoryList}` },\n ],\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const normalized = this.normalizeMemorySummaryResult(\n this.parseJsonObject(response.choices?.[0]?.message?.content),\n );\n if (normalized) {\n log.debug(`summarized ${memories.length} memories into ${normalized.keyFacts.length} key facts`);\n return normalized;\n }\n\n return null;\n } catch (err) {\n log.error(\"memory summarization failed\", err);\n return null;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,YAAY;AAyCnB,IAAM,2BAA2B;AAEjC,SAAS,kBAAkB,UAAkD;AAC3E,QAAM,WAAW,OAAO,SAAS,SAAS,QAAQ,IAC9C,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,QAAQ,CAAC,IAC1C;AACJ,SAAO;AAAA,IACL,UAAU,OAAO,SAAS,aAAa,WAAW,SAAS,SAAS,KAAK,IAAI;AAAA,IAC7E,SAAS,OAAO,SAAS,YAAY,WAAW,SAAS,QAAQ,KAAK,IAAI;AAAA,IAC1E;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,MAAiE;AACzF,SAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,QAAQ,KAAK,EAAE,YAAY,CAAC;AAC9D;AAEA,SAAS,mBAAmB,QAA8D;AACxF,SAAO,GAAG,OAAO,IAAI,IAAI,OAAO,KAAK,KAAK,EAAE,YAAY,CAAC;AAC3D;AAEA,SAAS,yBACP,cACQ;AACR,SAAO,GAAG,aAAa,OAAO,KAAK,EAAE,YAAY,CAAC,KAAK,aAAa,OAAO,KAAK,EAAE,YAAY,CAAC,IAAI,aAAa,MAAM,KAAK,EAAE,YAAY,CAAC;AAC5I;AAEA,SAAS,0B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AY,OAAO;AAAA,QAC1D,OAAO,KAAK,OAAO;AAAA,QACnB,UAAU;AAAA,UACR,EAAE,MAAM,UAAU,SAAS,aAAa;AAAA,UACxC,EAAE,MAAM,QAAQ,SAAS,mBAAmB,SAAS,MAAM;AAAA;AAAA,EAAiB,UAAU,GAAG;AAAA,QAC3F;AAAA,QACA,GAAG,8BAA8B,KAAK,OAAO,OAAO,MAAM;AAAA,UACxD,cAAc,KAAK,qCAAqC;AAAA,QAC1D,CAAC;AAAA,MACH,CAAC;AAED,YAAM,aAAa,KAAK;AAAA,QACtB,KAAK,gBAAgB,SAAS,UAAU,CAAC,GAAG,SAAS,OAAO;AAAA,MAC9D;AACA,UAAI,YAAY;AACd,YAAI,MAAM,cAAc,SAAS,MAAM,kBAAkB,WAAW,SAAS,MAAM,YAAY;AAC/F,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,UAAI,MAAM,+BAA+B,GAAG;AAC5C,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["normalized"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/harmonic-retrieval.ts"],"sourcesContent":["import path from \"node:path\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport {\n resolveAbstractionNodeStoreDir,\n validateAbstractionNode,\n type AbstractionNode,\n} from \"./abstraction-nodes.js\";\nimport {\n resolveCueAnchorStoreDir,\n validateCueAnchor,\n type CueAnchor,\n type CueAnchorType,\n} from \"./cue-anchors.js\";\nimport { countRecallTokenOverlap, normalizeRecallTokens } from \"./recall-tokenization.js\";\n\nexport interface HarmonicMatchedAnchor {\n anchorId: string;\n anchorType: CueAnchorType;\n anchorValue: string;\n}\n\nexport interface HarmonicRetrievalResult {\n node: AbstractionNode;\n score: number;\n nodeScore: number;\n anchorScore: number;\n matchedFields: string[];\n matchedAnchors: HarmonicMatchedAnchor[];\n}\n\ninterface HarmonicCandidate {\n node: AbstractionNode;\n nodeScore: number;\n anchorScore: number;\n matchedFields: Set<string>;\n matchedAnchors: Map<string, HarmonicMatchedAnchor>;\n}\n\nfunction scoreNode(node: AbstractionNode, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const titleMatches = countRecallTokenOverlap(queryTokens, node.title);\n if (titleMatches > 0) {\n score += titleMatches * 3;\n matchedFields.push(\"title\");\n }\n\n const summaryMatches = countRecallTokenOverlap(queryTokens, node.summary);\n if (summaryMatches > 0) {\n score += summaryMatches * 3;\n matchedFields.push(\"summary\");\n }\n\n const tagMatches = countRecallTokenOverlap(queryTokens, node.tags?.join(\" \"));\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"tags\");\n }\n\n const entityMatches = countRecallTokenOverlap(queryTokens, node.entityRefs?.join(\" \"));\n if (entityMatches > 0) {\n score += entityMatches * 2;\n matchedFields.push(\"entityRefs\");\n }\n\n const kindMatches = countRecallTokenOverlap(queryTokens, `${node.kind} ${node.abstractionLevel}`);\n if (kindMatches > 0) {\n score += kindMatches;\n matchedFields.push(\"kind\");\n }\n\n return { score, matchedFields };\n}\n\nfunction scoreAnchor(anchor: CueAnchor, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const valueMatches = countRecallTokenOverlap(queryTokens, anchor.anchorValue);\n const normalizedMatches = countRecallTokenOverlap(queryTokens, anchor.normalizedCue);\n const cueMatches = Math.max(valueMatches, normalizedMatches);\n if (cueMatches > 0) {\n score += cueMatches * 4;\n if (valueMatches > 0) matchedFields.push(\"anchorValue\");\n if (normalizedMatches > 0) matchedFields.push(\"anchor\");\n }\n\n const typeMatches = countRecallTokenOverlap(queryTokens, anchor.anchorType);\n if (typeMatches > 0) {\n score += typeMatches;\n matchedFields.push(\"anchorType\");\n }\n\n const tagMatches = countRecallTokenOverlap(queryTokens, anchor.tags?.join(\" \"));\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"anchorTags\");\n }\n\n return { score, matchedFields };\n}\n\nasync function readAbstractionNodes(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<AbstractionNode[]> {\n const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const files = await listJsonFiles(path.join(rootDir, \"nodes\"));\n const nodes: AbstractionNode[] = [];\n for (const filePath of files) {\n try {\n nodes.push(validateAbstractionNode(await readJsonFile(filePath)));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n }\n }\n return nodes;\n}\n\nasync function readCueAnchors(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<CueAnchor[]> {\n const abstractionRoot = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const rootDir = resolveCueAnchorStoreDir(abstractionRoot);\n const files = await listJsonFiles(rootDir);\n const anchors: CueAnchor[] = [];\n for (const filePath of files) {\n try {\n anchors.push(validateCueAnchor(await readJsonFile(filePath)));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n }\n }\n return anchors;\n}\n\nexport async function searchHarmonicRetrieval(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n query: string;\n maxResults: number;\n sessionKey?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n}): Promise<HarmonicRetrievalResult[]> {\n throwIfAborted(options.abortSignal);\n const queryTokens = new Set(normalizeRecallTokens(options.query, [\"what\", \"which\"]));\n if (queryTokens.size === 0 || options.maxResults <= 0) return [];\n\n const nodes = await readAbstractionNodes(options);\n const candidates = new Map<string, HarmonicCandidate>();\n\n for (const node of nodes) {\n throwIfAborted(options.abortSignal);\n const { score, matchedFields } = scoreNode(node, queryTokens);\n if (score <= 0) continue;\n candidates.set(node.nodeId, {\n node,\n nodeScore: score,\n anchorScore: 0,\n matchedFields: new Set(matchedFields),\n matchedAnchors: new Map(),\n });\n }\n\n if (options.anchorsEnabled) {\n throwIfAborted(options.abortSignal);\n const anchors = await readCueAnchors(options);\n const nodeIndex = new Map(nodes.map((node) => [node.nodeId, node]));\n for (const anchor of anchors) {\n throwIfAborted(options.abortSignal);\n const { score, matchedFields } = scoreAnchor(anchor, queryTokens);\n if (score <= 0) continue;\n for (const nodeRef of anchor.nodeRefs) {\n const node = nodeIndex.get(nodeRef);\n if (!node) continue;\n const existing = candidates.get(nodeRef) ?? {\n node,\n nodeScore: 0,\n anchorScore: 0,\n matchedFields: new Set<string>(),\n matchedAnchors: new Map<string, HarmonicMatchedAnchor>(),\n };\n existing.anchorScore += score;\n existing.matchedFields.add(\"anchor\");\n for (const field of matchedFields) existing.matchedFields.add(field);\n existing.matchedAnchors.set(anchor.anchorId, {\n anchorId: anchor.anchorId,\n anchorType: anchor.anchorType,\n anchorValue: anchor.anchorValue,\n });\n candidates.set(nodeRef, existing);\n }\n }\n }\n\n return [...candidates.values()]\n .map((candidate) => {\n let score = candidate.nodeScore + candidate.anchorScore;\n if (options.sessionKey && candidate.node.sessionKey === options.sessionKey) score += 0.5;\n return {\n node: candidate.node,\n score,\n nodeScore: candidate.nodeScore,\n anchorScore: candidate.anchorScore,\n matchedFields: [...candidate.matchedFields].sort(),\n matchedAnchors: [...candidate.matchedAnchors.values()].sort((left, right) =>\n left.anchorType.localeCompare(right.anchorType) || left.anchorValue.localeCompare(right.anchorValue)\n ),\n };\n })\n .filter((result) => result.nodeScore > 0 || result.anchorScore > 0)\n .sort(\n (left, right) =>\n right.score - left.score\n || right.anchorScore - left.anchorScore\n || right.node.recordedAt.localeCompare(left.node.recordedAt),\n )\n .slice(0, options.maxResults);\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (!signal?.aborted) return;\n const err = new Error(\"harmonic retrieval aborted\");\n Object.defineProperty(err, \"name\", { value: \"AbortError\" });\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AAsCjB,SAAS,UAAU,MAAuB,aAAsE;AAC9G,QAAM,gBAA0B,CAAC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O;AAAA,MACL,MAAM,UAAU;AAAA,MAChB;AAAA,MACA,WAAW,UAAU;AAAA,MACrB,aAAa,UAAU;AAAA,MACvB,eAAe,CAAC,GAAG,UAAU,aAAa,EAAE,KAAK;AAAA,MACjD,gBAAgB,CAAC,GAAG,UAAU,eAAe,OAAO,CAAC,EAAE;AAAA,QAAK,CAAC,MAAM,UACjE,KAAK,WAAW,cAAc,MAAM,UAAU,KAAK,KAAK,YAAY,cAAc,MAAM,WAAW;AAAA,MACrG;AAAA,IACF;AAAA,EACF,CAAC,EACA,OAAO,CAAC,WAAW,OAAO,YAAY,KAAK,OAAO,cAAc,CAAC,EACjE;AAAA,IACC,CAAC,MAAM,UACL,MAAM,QAAQ,KAAK,SAChB,MAAM,cAAc,KAAK,eACzB,MAAM,KAAK,WAAW,cAAc,KAAK,KAAK,UAAU;AAAA,EAC/D,EACC,MAAM,GAAG,QAAQ,UAAU;AAChC;AAEA,SAAS,eAAe,QAA4B;AAClD,MAAI,CAAC,QAAQ,QAAS;AACtB,QAAM,MAAM,IAAI,MAAM,4BAA4B;AAClD,SAAO,eAAe,KAAK,QAAQ,EAAE,OAAO,aAAa,CAAC;AAC1D,QAAM;AACR;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chunking.ts"],"sourcesContent":["/**\n * Automatic Chunking with Overlap (Phase 2A)\n *\n * Sentence-boundary chunking for long memories.\n * Preserves coherent thoughts by never splitting mid-sentence.\n */\n\nexport interface ChunkingConfig {\n /** Target tokens per chunk (default 200) */\n targetTokens: number;\n /** Minimum tokens to trigger chunking (default 150) */\n minTokens: number;\n /** Number of sentences to overlap between chunks (default 2) */\n overlapSentences: number;\n}\n\nexport interface Chunk {\n /** Chunk content */\n content: string;\n /** 0-based index */\n index: number;\n /** Approximate token count */\n tokenCount: number;\n}\n\nexport interface ChunkResult {\n /** Whether content was chunked */\n chunked: boolean;\n /** Array of chunks (length 1 if not chunked) */\n chunks: Chunk[];\n}\n\n/** Default chunking configuration */\nexport const DEFAULT_CHUNKING_CONFIG: ChunkingConfig = {\n targetTokens: 200,\n minTokens: 150,\n overlapSentences: 2,\n};\n\n/**\n * Estimate token count for text.\n * Rough approximation: ~4 characters per token for English.\n */\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Split text into sentences.\n * Handles common abbreviations and edge cases.\n */\nfunction splitSentences(text: string): string[] {\n // Split on sentence-ending punctuation followed by whitespace or end of string\n // Preserve the punctuation with the sentence\n const sentences: string[] = [];\n\n // Regex to match sentence boundaries\n // Match: period/exclamation/question followed by space or end, but not abbreviations\n const sentenceRegex = /[^.!?]*[.!?]+(?:\\s+|$)/g;\n\n let match: RegExpExecArray | null;\n let lastIndex = 0;\n\n while ((match = sentenceRegex.exec(text)) !== null) {\n sentences.push(match[0].trim());\n lastIndex = sentenceRegex.lastIndex;\n }\n\n // Handle remaining text without sentence-ending punctuation\n if (lastIndex < text.length) {\n const remaining = text.slice(lastIndex).trim();\n if (remaining) {\n sentences.push(remaining);\n }\n }\n\n // Filter out empty sentences\n return sentences.filter((s) => s.length > 0);\n}\n\n/**\n * Chunk content into overlapping segments at sentence boundaries.\n *\n * @param content - The text content to chunk\n * @param config - Chunking configuration\n * @returns ChunkResult with chunks array\n */\nexport function chunkContent(\n content: string,\n config: ChunkingConfig = DEFAULT_CHUNKING_CONFIG,\n): ChunkResult {\n const totalTokens = estimateTokens(content);\n\n // Don't chunk if below minimum threshold\n if (totalTokens < config.minTokens) {\n return {\n chunked: false,\n chunks: [{\n content,\n index: 0,\n tokenCount: totalTokens,\n }],\n };\n }\n\n const sentences = splitSentences(content);\n\n // If we couldn't split into multiple sentences, don't chunk\n if (sentences.length <= 1) {\n return {\n chunked: false,\n chunks: [{\n content,\n index: 0,\n tokenCount: totalTokens,\n }],\n };\n }\n\n const chunks: Chunk[] = [];\n let currentChunkSentences: string[] = [];\n let currentTokens = 0;\n let chunkIndex = 0;\n\n for (let i = 0; i < sentences.length; i++) {\n const sentence = sentences[i];\n const sentenceTokens = estimateTokens(sentence);\n\n // Add sentence to current chunk\n currentChunkSentences.push(sentence);\n currentTokens += sentenceTokens;\n\n // Check if we've reached target size (with some flexibility)\n // Allow going over by up to 50% to avoid tiny final chunks\n const atTarget = currentTokens >= config.targetTokens;\n const isLastSentence = i === sentences.length - 1;\n\n if (atTarget || isLastSentence) {\n // Create chunk from accumulated sentences\n const chunkContent = currentChunkSentences.join(\" \");\n chunks.push({\n content: chunkContent,\n index: chunkIndex,\n tokenCount: estimateTokens(chunkContent),\n });\n chunkIndex++;\n\n // Start new chunk with overlap (if not at end)\n if (!isLastSentence) {\n // Keep last N sentences for overlap\n const overlapCount = Math.min(config.overlapSentences, currentChunkSentences.length);\n currentChunkSentences = currentChunkSentences.slice(-overlapCount);\n currentTokens = currentChunkSentences.reduce((sum, s) => sum + estimateTokens(s), 0);\n }\n }\n }\n\n // Only consider it \"chunked\" if we got multiple chunks\n return {\n chunked: chunks.length > 1,\n chunks,\n };\n}\n\n/**\n * Get parent content by reassembling chunks.\n * Useful for displaying full context when a chunk is retrieved.\n *\n * @param chunks - Array of chunk contents in order\n * @returns Reassembled parent content (with overlap removed)\n */\nexport function reassembleChunks(chunks: string[]): string {\n if (chunks.length === 0) return \"\";\n if (chunks.length === 1) return chunks[0];\n\n // For overlapping chunks, we need to deduplicate\n // Simple approach: use full first chunk, then non-overlapping parts of subsequent chunks\n // This is imperfect but handles most cases\n const result: string[] = [chunks[0]];\n\n for (let i = 1; i < chunks.length; i++) {\n const prevChunk = chunks[i - 1];\n const currChunk = chunks[i];\n\n // Find overlap by looking for common suffix/prefix\n // Try to find where the previous chunk ends in the current chunk\n const prevSentences = splitSentences(prevChunk);\n const currSentences = splitSentences(currChunk);\n\n // Find how many sentences from prev are at the start of curr\n let overlapCount = 0;\n for (let j = 0; j < Math.min(prevSentences.length, currSentences.length); j++) {\n // Check if last N sentences of prev match first N sentences of curr\n const prevEnd = prevSentences.slice(-(j + 1));\n const currStart = currSentences.slice(0, j + 1);\n\n if (prevEnd.join(\" \") === currStart.join(\" \")) {\n overlapCount = j + 1;\n }\n }\n\n // Add non-overlapping portion\n if (overlapCount > 0 && overlapCount < currSentences.length) {\n result.push(currSentences.slice(overlapCount).join(\" \"));\n } else if (overlapCount === 0) {\n // No detected overlap, add full chunk\n result.push(currChunk);\n }\n // If overlapCount === currSentences.length, skip (fully contained)\n }\n\n return result.join(\" \");\n}\n"],"mappings":";AAiCO,IAAM,0BAA0C;AAAA,EACrD,cAAc;AAAA,EACd,WAAW;AAAA,EACX,kBAAkB;AACpB;AAMA,SAAS,eAAe,MAAsB;AAC5C,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC;AAMA,SAAS,eAAe,MAAwB;AAG9C,QAAM,YAAsB,CAAC;AAI7B,QAAM,gBAAgB;AAEtB,MAAI;AACJ,MAAI,YAAY;AAEhB,UAAQ,QAAQ,cAAc,KAAK,IAAI,OAAO,MAAM;AAClD,cAAU,KAAK,MAAM,CAAC,EAAE,KAAK,CAAC;AAC9B,gBAAY,cAAc;AAAA,EAC5B;AAGA,MAAI,YAAY,KAAK,QAAQ;AAC3B,UAAM,YAAY,KAAK,MAAM,SAAS,EAAE,KAAK;AAC7C,QAAI,WAAW;AACb,gBAAU,KAAK,SAAS;AAAA,IAC1B;AAAA,EACF;AAGA,SAAO,UAAU,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC7C;AASO,SAAS,aACd,SACA,SAAyB,yBACZ;AACb,QAAM,cAAc,eAAe,OAAO;AAG1C,MAAI,cAAc,OAAO,WAAW;AAClC,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ,CAAC;AAAA,QACP;AAAA,QACA,OAAO;AAAA,QACP,YAAY;AAAA,MACd,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,YAAY,eAAe,OAAO;AAGxC,MAAI,UAAU,UAAU,GAAG;AACzB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ,CAA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9C,QAAI,eAAe;AACnB,aAAS,IAAI,GAAG,IAAI,KAAK,IAAI,cAAc,QAAQ,cAAc,MAAM,GAAG,KAAK;AAE7E,YAAM,UAAU,cAAc,MAAM,EAAE,IAAI,EAAE;AAC5C,YAAM,YAAY,cAAc,MAAM,GAAG,IAAI,CAAC;AAE9C,UAAI,QAAQ,KAAK,GAAG,MAAM,UAAU,KAAK,GAAG,GAAG;AAC7C,uBAAe,IAAI;AAAA,MACrB;AAAA,IACF;AAGA,QAAI,eAAe,KAAK,eAAe,cAAc,QAAQ;AAC3D,aAAO,KAAK,cAAc,MAAM,YAAY,EAAE,KAAK,GAAG,CAAC;AAAA,IACzD,WAAW,iBAAiB,GAAG;AAE7B,aAAO,KAAK,SAAS;AAAA,IACvB;AAAA,EAEF;AAEA,SAAO,OAAO,KAAK,GAAG;AACxB;","names":["chunkContent"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/importance.ts"],"sourcesContent":["/**\n * Local Importance Scoring (Phase 1B)\n *\n * Zero-LLM heuristic system that evaluates each memory's significance.\n * Analyzes content for markers like explicit importance statements,\n * personal information, instructions, emotional content, and factual density.\n */\n\nimport type { ImportanceLevel, ImportanceScore, MemoryCategory, MemoryFile } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Marker patterns for each tier\n// ---------------------------------------------------------------------------\n\n/** Critical importance markers (0.9-1.0) */\nconst CRITICAL_PATTERNS = [\n // Explicit importance\n /\\b(critical|crucial|essential|must|always|never)\\b/i,\n /\\b(important|remember this|don't forget)\\b/i,\n // Personal identity\n /\\b(my name is|i am|i'm called)\\b/i,\n /\\b(my (birthday|phone|email|address|ssn|password))\\b/i,\n // Strong preferences\n /\\b(i (hate|love|despise|adore))\\b/i,\n /\\b(absolutely|definitely|certainly) (not|must|should)\\b/i,\n // Corrections (high weight)\n /\\b(actually|no,? that's wrong|correction:?|let me correct)\\b/i,\n /\\b(i said|i meant|i was wrong)\\b/i,\n];\n\n/** High importance markers (0.7-0.9) */\nconst HIGH_PATTERNS = [\n // Decisions\n /\\b(decided|decision|chose|choosing|picked|selected)\\b/i,\n /\\b(we('ll| will) (go with|use|implement))\\b/i,\n // Instructions\n /\\b(make sure|ensure|always|don't|do not|never|avoid)\\b/i,\n /\\b(you (should|must|need to))\\b/i,\n // Temporal references (deadlines, schedules)\n /\\b(by (monday|tuesday|wednesday|thursday|friday|saturday|sunday))\\b/i,\n /\\b(deadline|due (date|by)|by (end of|next))\\b/i,\n /\\b(tomorrow|next week|this week|today)\\b/i,\n // Preferences\n /\\b(i (prefer|like|want|need|dislike))\\b/i,\n /\\b(my (preference|style|approach|way))\\b/i,\n // Commitments\n /\\b(i('ll| will)|promise|commit|guarantee)\\b/i,\n /\\b(scheduled|appointment|meeting|call)\\b/i,\n];\n\n/** Normal importance markers (0.4-0.7) */\nconst NORMAL_PATTERNS = [\n // Factual content\n /\\b(is|are|was|were|has|have|does|do)\\b/i,\n /\\b(because|since|therefore|thus|so)\\b/i,\n // Emotional content\n /\\b(happy|sad|frustrated|excited|worried|anxious)\\b/i,\n /\\b(feel|feeling|felt)\\b/i,\n // Technical details\n /\\b(version|api|endpoint|database|server|config)\\b/i,\n /\\b(function|class|method|variable|parameter)\\b/i,\n];\n\n/** Low importance markers (0.2-0.4) */\nconst LOW_PATTERNS = [\n // Uncertainty\n /\\b(maybe|perhaps|possibly|might|could be)\\b/i,\n /\\b(i think|i guess|not sure|uncertain)\\b/i,\n /\\b(probably|likely|seems like)\\b/i,\n // Hedging\n /\\b(kind of|sort of|somewhat|a bit)\\b/i,\n /\\b(in a way|to some extent)\\b/i,\n];\n\n/** Trivial content markers (0.0-0.2) */\nconst TRIVIAL_PATTERNS = [\n // Greetings and filler\n /^(hi|hello|hey|yo|sup|greetings)[.!,]?\\s*$/i,\n /^(ok|okay|k|sure|yes|no|yep|nope|yeah|nah)[.!]?\\s*$/i,\n /^(thanks|thank you|thx|ty|cheers)[.!]?\\s*$/i,\n /^(got it|understood|roger|copy|noted)[.!]?\\s*$/i,\n /^(bye|goodbye|later|see ya|ttyl)[.!]?\\s*$/i,\n /^(lol|haha|hehe|lmao|rofl)[.!]?\\s*$/i,\n /^(hmm+|uhh*|ahh*|err*|umm*)[.!]?\\s*$/i,\n // Very short content\n /^.{1,10}$/,\n];\n\n// ---------------------------------------------------------------------------\n// Category-based importance boosts\n// ---------------------------------------------------------------------------\n\nconst CATEGORY_BOOSTS: Record<MemoryCategory, number> = {\n correction: 0.15, // Corrections are always important\n principle: 0.12, // Durable rules/values\n rule: 0.11, // Causal IF→THEN rules\n preference: 0.10, // User preferences matter\n commitment: 0.10, // Promises/obligations\n decision: 0.08, // Decisions with rationale\n relationship: 0.05, // Entity relationships\n skill: 0.05, // Capabilities\n moment: 0.03, // Emotional milestones\n entity: 0.02, // Entity facts\n fact: 0.00, // Base facts, no boost\n};\n\n// ---------------------------------------------------------------------------\n// Keyword extraction\n// ---------------------------------------------------------------------------\n\n/** Common stop words to filter out */\nconst STOP_WORDS = new Set([\n \"a\", \"an\", \"the\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\", \"would\", \"could\",\n \"should\", \"may\", \"might\", \"must\", \"shall\", \"can\", \"need\", \"dare\",\n \"ought\", \"used\", \"to\", \"of\", \"in\", \"for\", \"on\", \"with\", \"at\", \"by\",\n \"from\", \"as\", \"into\", \"through\", \"during\", \"before\", \"after\", \"above\",\n \"below\", \"between\", \"under\", \"again\", \"further\", \"then\", \"once\",\n \"here\", \"there\", \"when\", \"where\", \"why\", \"how\", \"all\", \"each\", \"few\",\n \"more\", \"most\", \"other\", \"some\", \"such\", \"no\", \"nor\", \"not\", \"only\",\n \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"just\", \"and\", \"but\",\n \"or\", \"if\", \"because\", \"until\", \"while\", \"this\", \"that\", \"these\",\n \"those\", \"i\", \"me\", \"my\", \"myself\", \"we\", \"our\", \"ours\", \"ourselves\",\n \"you\", \"your\", \"yours\", \"yourself\", \"yourselves\", \"he\", \"him\", \"his\",\n \"himself\", \"she\", \"her\", \"hers\", \"herself\", \"it\", \"its\", \"itself\",\n \"they\", \"them\", \"their\", \"theirs\", \"themselves\", \"what\", \"which\",\n \"who\", \"whom\", \"whose\", \"am\", \"been\", \"being\", \"about\", \"against\",\n]);\n\n/**\n * Extract salient keywords from content.\n * Returns top N keywords sorted by relevance.\n */\nfunction extractKeywords(content: string, maxKeywords: number = 5): string[] {\n // Tokenize and normalize\n const words = content\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length >= 3 && !STOP_WORDS.has(w));\n\n // Count frequencies\n const freq = new Map<string, number>();\n for (const word of words) {\n freq.set(word, (freq.get(word) ?? 0) + 1);\n }\n\n // Sort by frequency, take top N\n return [...freq.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, maxKeywords)\n .map(([word]) => word);\n}\n\n// ---------------------------------------------------------------------------\n// Main scoring function\n// ---------------------------------------------------------------------------\n\n/**\n * Calculate importance score for a memory.\n * Pure local heuristics, zero LLM calls.\n */\nexport function scoreImportance(\n content: string,\n category: MemoryCategory,\n tags: string[] = [],\n): ImportanceScore {\n const reasons: string[] = [];\n let score = 0.5; // Start at normal baseline\n\n const lowerContent = content.toLowerCase();\n const contentLength = content.length;\n\n // Check for trivial content first (short-circuit)\n for (const pattern of TRIVIAL_PATTERNS) {\n if (pattern.test(content)) {\n return {\n score: 0.1,\n level: \"trivial\",\n reasons: [\"Trivial content (greeting, filler, or very short)\"],\n keywords: [],\n };\n }\n }\n\n // Check critical patterns\n for (const pattern of CRITICAL_PATTERNS) {\n if (pattern.test(content)) {\n score += 0.20;\n reasons.push(`Critical marker: ${pattern.source.slice(0, 30)}`);\n break; // Only count once per tier\n }\n }\n\n // Check high patterns\n for (const pattern of HIGH_PATTERNS) {\n if (pattern.test(content)) {\n score += 0.12;\n reasons.push(`High importance marker detected`);\n break;\n }\n }\n\n // Check low patterns (reduces score)\n for (const pattern of LOW_PATTERNS) {\n if (pattern.test(content)) {\n score -= 0.15;\n reasons.push(`Uncertainty/hedging detected`);\n break;\n }\n }\n\n // Category boost\n const categoryBoost = CATEGORY_BOOSTS[category] ?? 0;\n if (categoryBoost > 0) {\n score += categoryBoost;\n reasons.push(`Category boost: ${category}`);\n }\n\n // Length bonus (longer = more substance, capped)\n if (contentLength > 200) {\n const lengthBonus = Math.min((contentLength - 200) / 1000, 0.1);\n score += lengthBonus;\n if (lengthBonus > 0.05) {\n reasons.push(\"Substantial content length\");\n }\n }\n\n // Check for personal pronouns (signals personal relevance)\n if (/\\b(my|mine|i|i'm|i've|i'd|i'll)\\b/i.test(content)) {\n score += 0.05;\n reasons.push(\"Personal reference\");\n }\n\n // Check for numbers/specifics (concrete details)\n if (/\\b\\d{2,}\\b/.test(content) || /\\b(version|v\\d|api|config)\\b/i.test(content)) {\n score += 0.03;\n reasons.push(\"Contains specific details\");\n }\n\n // Tag-based boosts\n const importantTags = tags.filter((t) =>\n [\"important\", \"critical\", \"preference\", \"decision\", \"rule\", \"principle\"].includes(t.toLowerCase())\n );\n if (importantTags.length > 0) {\n score += 0.05 * importantTags.length;\n reasons.push(`Important tags: ${importantTags.join(\", \")}`);\n }\n\n // Clamp score to 0-1 range\n score = Math.max(0, Math.min(1, score));\n\n // Determine level from score\n let level: ImportanceLevel;\n if (score >= 0.9) {\n level = \"critical\";\n } else if (score >= 0.7) {\n level = \"high\";\n } else if (score >= 0.4) {\n level = \"normal\";\n } else if (score >= 0.2) {\n level = \"low\";\n } else {\n level = \"trivial\";\n }\n\n // Extract keywords\n const keywords = extractKeywords(content);\n\n return {\n score: Math.round(score * 100) / 100, // Round to 2 decimal places\n level,\n reasons: reasons.slice(0, 5), // Cap at 5 reasons\n keywords,\n };\n}\n\n/**\n * Recompute importance for an existing memory file using current local heuristics.\n */\nexport function rescoreMemoryImportance(memory: MemoryFile): ImportanceScore {\n return scoreImportance(memory.content, memory.frontmatter.category, memory.frontmatter.tags ?? []);\n}\n\n/**\n * Get importance level from numeric score.\n */\nexport function importanceLevel(score: number): ImportanceLevel {\n if (score >= 0.9) return \"critical\";\n if (score >= 0.7) return \"high\";\n if (score >= 0.4) return \"normal\";\n if (score >= 0.2) return \"low\";\n return \"trivial\";\n}\n"],"mappings":";AAeA,IAAM,oBAAoB;AAAA;AAAA,EAExB;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAGA,IAAM,gBAAgB;AAAA;AAAA,EAEpB;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAgBA,IAAM,eAAe;AAAA;AAAA,EAEnB;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAGA,IAAM,mBAAmB;AAAA;AAAA,EAEvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACF;AAMA,IAAM,kBAAkD;AAAA,EACtD,YAAY;AAAA;AAAA,EACZ,WAAW;AAAA;AAAA,EACX,MAAM;AAAA;AAAA,EACN,YAAY;AAAA;AAAA,EACZ,YAAY;AAAA;AAAA,EACZ,UAAU;AAAA;AAAA,EACV,cAAc;AAAA;AAAA,EACd,OAAO;AAAA;AAAA,EACP,QAAQ;AAAA;AAAA,EACR,QAAQ;AAAA;AAAA,EACR,MAAM;AAAA;AACR;AAOA,IAAM,aAAa,oBAAI,IAAI;AAAA,EACzB;AAAA,EAAK;AAAA,EAAM;AAAA,EAAO;AAAA,EAAM;AAAA,EAAO;AAAA,EAAO;AAAA,EAAQ;AAAA,EAAM;AAAA,EAAQ;AAAA,EAC5D;AAAA,EAAQ;AAAA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