@remnic/core 9.63.6 → 9.63.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-admin-ops-surface.d.ts +1 -1
- package/dist/access-admin-ops-surface.js +27 -25
- package/dist/access-authorization-probe.d.ts +1 -1
- package/dist/access-authorization-probe.js +28 -26
- package/dist/access-boundary.d.ts +1 -1
- package/dist/access-boundary.js +27 -25
- package/dist/access-cli.js +83 -81
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.d.ts +1 -1
- package/dist/access-extraction-force-flush.js +27 -25
- package/dist/access-http-lcm-compaction.d.ts +1 -1
- package/dist/access-http-lifecycle-flush.d.ts +1 -1
- package/dist/access-http-offline-stream.d.ts +1 -1
- package/dist/access-http-query.js +29 -27
- package/dist/access-http.d.ts +2 -2
- package/dist/access-http.js +43 -41
- package/dist/access-identity-continuity-surface.js +27 -25
- package/dist/access-lcm-surface.d.ts +1 -1
- package/dist/access-lcm-surface.js +27 -25
- package/dist/access-mcp.d.ts +1 -1
- package/dist/access-mcp.js +34 -32
- package/dist/access-namespace-preflight.js +27 -25
- package/dist/access-observe-write-surface.d.ts +1 -1
- package/dist/access-observe-write-surface.js +27 -25
- package/dist/access-offline-manifest.js +6 -5
- package/dist/access-operations-batch.js +29 -27
- package/dist/access-operations.d.ts +4 -4
- package/dist/access-operations.js +33 -31
- package/dist/access-recall-concurrency.d.ts +1 -1
- package/dist/access-recall-concurrency.js +27 -25
- package/dist/access-recall-response.d.ts +1 -1
- package/dist/access-recall-response.js +27 -25
- package/dist/access-recall-surface.d.ts +1 -1
- package/dist/access-recall-surface.js +27 -25
- package/dist/access-schema.d.ts +88 -88
- package/dist/access-schema.js +6 -5
- package/dist/access-service-helpers.d.ts +1 -1
- package/dist/access-service.d.ts +1 -1
- package/dist/access-service.js +27 -25
- package/dist/access-surface-catalog.d.ts +1 -1
- package/dist/access-surface-catalog.js +29 -27
- package/dist/access-surface-catalog.js.map +1 -1
- package/dist/active-recall.js +5 -3
- package/dist/active-recall.js.map +1 -1
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/{auto-sync-BKRJDMKX.js → auto-sync-3SHMZVQS.js} +5 -3
- package/dist/{auto-sync-BKRJDMKX.js.map → auto-sync-3SHMZVQS.js.map} +1 -1
- package/dist/briefing.js +10 -10
- package/dist/calibration.d.ts +2 -1
- package/dist/calibration.js +7 -0
- package/dist/calibration.js.map +1 -1
- package/dist/causal-consolidation.js +11 -11
- package/dist/census-validation.d.ts +19 -0
- package/dist/census-validation.js +14 -0
- package/dist/census-validation.js.map +1 -0
- package/dist/{chunk-LEPOP46W.js → chunk-227UFSEQ.js} +4 -4
- package/dist/{chunk-Z4N7SVVF.js → chunk-2L7DKNVE.js} +12 -7
- package/dist/chunk-2L7DKNVE.js.map +1 -0
- package/dist/{chunk-3Z5TGRFA.js → chunk-3NZAVWU5.js} +9 -9
- package/dist/{chunk-I5FLIB2J.js → chunk-3S3PNR5H.js} +2 -2
- package/dist/{chunk-R6UMNP5C.js → chunk-3T6HIIKA.js} +2 -2
- package/dist/{chunk-77QZW2D6.js → chunk-3TDAA7VA.js} +2 -2
- package/dist/{chunk-TWTUGCTY.js → chunk-3YTTAGPB.js} +6 -1
- package/dist/chunk-3YTTAGPB.js.map +1 -0
- package/dist/{chunk-DXDAQZ2K.js → chunk-42TIIO2M.js} +2 -2
- package/dist/{chunk-Y7COCXY2.js → chunk-4F67JJPG.js} +2 -2
- package/dist/{chunk-PB4WVYGC.js → chunk-5S5DUJFJ.js} +2 -2
- package/dist/{chunk-KYTRF64R.js → chunk-5SCFDQEJ.js} +2 -2
- package/dist/{chunk-GG4DN63W.js → chunk-62Y5AGCM.js} +2 -2
- package/dist/{chunk-KHCUVYCY.js → chunk-6UKSOXAO.js} +3 -3
- package/dist/{chunk-F6JYBVL6.js → chunk-7ZAC2C2U.js} +24 -24
- package/dist/{chunk-GF7RQWXC.js → chunk-AJRJDXYR.js} +2 -2
- package/dist/{chunk-YEQCMA5L.js → chunk-BOSIHHOH.js} +2 -2
- package/dist/{chunk-7LF2OHIJ.js → chunk-BRHKW7GY.js} +2 -2
- package/dist/{chunk-LX4TNSAE.js → chunk-CBY54QYW.js} +4 -4
- package/dist/chunk-FEHIOYML.js +168 -0
- package/dist/chunk-FEHIOYML.js.map +1 -0
- package/dist/{chunk-6YMEU6OQ.js → chunk-G72IPMR7.js} +2 -2
- package/dist/{chunk-7AF243WZ.js → chunk-GBVRVYF4.js} +1 -1
- package/dist/{chunk-GTD4Q62X.js → chunk-H4GQ2Y24.js} +3 -3
- package/dist/{chunk-QI5RDDEL.js → chunk-HXZNTZ3Y.js} +6 -6
- package/dist/{chunk-CIAI24TQ.js → chunk-IBZQQOM5.js} +3 -3
- package/dist/{chunk-RYST72N5.js → chunk-IINVXO3U.js} +4 -154
- package/dist/chunk-IINVXO3U.js.map +1 -0
- package/dist/{chunk-R7TZ2HCS.js → chunk-JG22O53B.js} +58 -3
- package/dist/chunk-JG22O53B.js.map +1 -0
- package/dist/{chunk-VPHSMJ2E.js → chunk-JPWSYHLB.js} +2 -2
- package/dist/{chunk-X7LEDA74.js → chunk-KFB4YNXM.js} +2 -2
- package/dist/{chunk-IPLYGWQF.js → chunk-KQAFEZQX.js} +5 -5
- package/dist/chunk-LQWOFU6L.js +17 -0
- package/dist/chunk-LQWOFU6L.js.map +1 -0
- package/dist/{chunk-ZUPKNWRZ.js → chunk-MIUL6AUZ.js} +3 -3
- package/dist/{chunk-EJY3HJMT.js → chunk-MYI3RKI6.js} +2 -2
- package/dist/{chunk-NA56NSKL.js → chunk-OOJCXJBN.js} +2 -2
- package/dist/{chunk-7KQB4EBS.js → chunk-OPPBTPUU.js} +4 -4
- package/dist/{chunk-ERPBRXVZ.js → chunk-PZKWPXRF.js} +2 -2
- package/dist/{chunk-FHKXVTM5.js → chunk-Q5XKKDFQ.js} +16 -16
- package/dist/{chunk-QRWMS6SI.js → chunk-Q6OL23WM.js} +2 -2
- package/dist/{chunk-OW7NVMGQ.js → chunk-QIZOU3FN.js} +2 -2
- package/dist/{chunk-V3KIRICY.js → chunk-QQYHYW2N.js} +3 -3
- package/dist/{chunk-YFCEBB5P.js → chunk-QTXNS3HB.js} +2 -2
- package/dist/{chunk-2QSZNTDO.js → chunk-RKNJBZ55.js} +4 -4
- package/dist/{chunk-E4KMY4KR.js → chunk-SNEUAZ6B.js} +2 -2
- package/dist/{chunk-TSTI6A3A.js → chunk-SYJW273H.js} +11 -11
- package/dist/{chunk-EFKZT6AY.js → chunk-T42L3S6A.js} +6 -11
- package/dist/chunk-T42L3S6A.js.map +1 -0
- package/dist/{chunk-YXMHUBN2.js → chunk-TOP3FSDW.js} +25 -102
- package/dist/chunk-TOP3FSDW.js.map +1 -0
- package/dist/{chunk-PBRCYYO7.js → chunk-ULZFZL7K.js} +2 -2
- package/dist/{chunk-UGHCZS6K.js → chunk-VFZQXYN5.js} +2 -2
- package/dist/{chunk-IVXVLDNT.js → chunk-WKJTMXME.js} +37 -54
- package/dist/chunk-WKJTMXME.js.map +1 -0
- package/dist/{chunk-NKB43PGI.js → chunk-WZDTSBGQ.js} +2 -2
- package/dist/{chunk-2UM6WHME.js → chunk-XE2QCCT2.js} +2 -2
- package/dist/{chunk-FPEZ74F7.js → chunk-XNJQZLAP.js} +3 -3
- package/dist/{chunk-SYVGVK4S.js → chunk-XTMYB2HY.js} +2 -2
- package/dist/{chunk-OETHJBAL.js → chunk-XV6PUXJ5.js} +71 -71
- package/dist/{chunk-UCLMKNHA.js → chunk-YIMV2KYM.js} +2 -2
- package/dist/{chunk-DYZR3Z6D.js → chunk-YMQKPSB2.js} +4 -4
- package/dist/{chunk-AYVCKGA6.js → chunk-YTXNDEUS.js} +2 -2
- package/dist/{chunk-L3CHRBHE.js → chunk-ZRUEP4IK.js} +17 -11
- package/dist/chunk-ZRUEP4IK.js.map +1 -0
- package/dist/{cli-BFBDYV0D.d.ts → cli-BTNj5DzK.d.ts} +1 -1
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +59 -57
- package/dist/compounding/engine.js +10 -10
- package/dist/config.js +5 -3
- package/dist/connectors/codex-materialize-runner.js +10 -10
- package/dist/connectors/index.js +10 -10
- package/dist/consolidation-provenance-check.js +2 -2
- package/dist/convergence-refresh.js +12 -12
- package/dist/conversation-index/backend.js +2 -2
- package/dist/corpus-watermark.js +12 -12
- package/dist/entity-retrieval.js +10 -10
- package/dist/external-wiki-access.d.ts +1 -1
- package/dist/external-wiki-access.js +28 -26
- package/dist/external-wiki-mcp-tools.d.ts +1 -1
- package/dist/extraction-judge.d.ts +2 -1
- package/dist/extraction-judge.js +6 -1
- package/dist/extraction-normalization.js +2 -2
- package/dist/extraction-prompt.d.ts +20 -1
- package/dist/extraction-prompt.js +11 -1
- package/dist/extraction.js +13 -13
- package/dist/{first-start-migration-4NETATFF.js → first-start-migration-Q2VB2E2D.js} +4 -4
- package/dist/harmonic-retrieval.js +1 -1
- package/dist/index.d.ts +680 -680
- package/dist/index.js +92 -90
- package/dist/maintenance/memory-governance.js +10 -10
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
- package/dist/maintenance/rebuild-memory-projection.js +11 -11
- package/dist/mcp-memory-inspector-app.d.ts +1 -1
- package/dist/namespaces/migrate.js +11 -11
- package/dist/namespaces/search.js +4 -4
- package/dist/namespaces/storage.js +10 -10
- package/dist/offline-sync.js +3 -2
- package/dist/operator-doctor-corpus.js +13 -13
- package/dist/operator-toolkit.js +24 -22
- package/dist/orchestration/maintenance.js +16 -16
- package/dist/orchestrator.js +85 -83
- package/dist/{public-http-8PcrDIYi.d.ts → public-http-BmPktTe3.d.ts} +1 -1
- package/dist/reconcile/cursor.js +7 -3
- package/dist/reconcile/cursor.js.map +1 -1
- package/dist/reconcile/manifest.js +3 -7
- package/dist/reconcile/plan.d.ts +15 -1
- package/dist/reconcile/plan.js +6 -10
- package/dist/resume-bundles.js +6 -4
- package/dist/schemas.d.ts +108 -108
- package/dist/search/factory.js +3 -3
- package/dist/search/index.js +3 -3
- package/dist/semantic-consolidation.js +16 -16
- package/dist/semantic-rule-promotion.js +10 -10
- package/dist/semantic-rule-verifier.js +10 -10
- package/dist/shared-context/manager.d.ts +8 -8
- package/dist/source-agent-qualifier.js +10 -10
- package/dist/storage.js +9 -9
- package/dist/support-passport/index.d.ts +4 -4
- package/dist/support-passport/index.js +30 -28
- package/dist/transfer/autodetect.js +1 -1
- package/dist/transfer/backup.js +1 -1
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/types.d.ts +66 -66
- package/dist/verified-recall.js +10 -10
- package/package.json +2 -2
- package/src/calibration.ts +3 -1
- package/src/census-validation.ts +25 -0
- package/src/coding/architecture-surfaces.test.ts +9 -10
- package/src/coding/architecture-surfaces.ts +2 -35
- package/src/coding/codegraph-runtime-loader.test.ts +228 -0
- package/src/coding/codegraph-runtime.ts +30 -50
- package/src/coding/codegraph-surfaces.ts +2 -2
- package/src/coding/coding-knowledge-config.ts +35 -1
- package/src/coding/decision-surfaces.test.ts +9 -10
- package/src/coding/decision-surfaces.ts +2 -40
- package/src/coding/session-delta-surfaces.test.ts +9 -10
- package/src/coding/session-delta-surfaces.ts +2 -33
- package/src/extraction-judge.ts +3 -1
- package/src/extraction-output-language.test.ts +116 -0
- package/src/extraction-prompt.ts +70 -1
- package/src/extraction.ts +23 -95
- package/src/offline-sync.ts +4 -4
- package/src/reconcile/census-parity.test.ts +152 -0
- package/src/reconcile/cursor.ts +5 -5
- package/src/reconcile/manifest.ts +4 -11
- package/src/reconcile/plan.ts +18 -15
- package/dist/chunk-EFKZT6AY.js.map +0 -1
- package/dist/chunk-IVXVLDNT.js.map +0 -1
- package/dist/chunk-L3CHRBHE.js.map +0 -1
- package/dist/chunk-R7TZ2HCS.js.map +0 -1
- package/dist/chunk-RYST72N5.js.map +0 -1
- package/dist/chunk-TWTUGCTY.js.map +0 -1
- package/dist/chunk-YXMHUBN2.js.map +0 -1
- package/dist/chunk-Z4N7SVVF.js.map +0 -1
- package/dist/{access-service-cKQrte9Z.d.ts → access-service-CocW74uA.d.ts} +64 -64
- /package/dist/{chunk-LEPOP46W.js.map → chunk-227UFSEQ.js.map} +0 -0
- /package/dist/{chunk-3Z5TGRFA.js.map → chunk-3NZAVWU5.js.map} +0 -0
- /package/dist/{chunk-I5FLIB2J.js.map → chunk-3S3PNR5H.js.map} +0 -0
- /package/dist/{chunk-R6UMNP5C.js.map → chunk-3T6HIIKA.js.map} +0 -0
- /package/dist/{chunk-77QZW2D6.js.map → chunk-3TDAA7VA.js.map} +0 -0
- /package/dist/{chunk-DXDAQZ2K.js.map → chunk-42TIIO2M.js.map} +0 -0
- /package/dist/{chunk-Y7COCXY2.js.map → chunk-4F67JJPG.js.map} +0 -0
- /package/dist/{chunk-PB4WVYGC.js.map → chunk-5S5DUJFJ.js.map} +0 -0
- /package/dist/{chunk-KYTRF64R.js.map → chunk-5SCFDQEJ.js.map} +0 -0
- /package/dist/{chunk-GG4DN63W.js.map → chunk-62Y5AGCM.js.map} +0 -0
- /package/dist/{chunk-KHCUVYCY.js.map → chunk-6UKSOXAO.js.map} +0 -0
- /package/dist/{chunk-F6JYBVL6.js.map → chunk-7ZAC2C2U.js.map} +0 -0
- /package/dist/{chunk-GF7RQWXC.js.map → chunk-AJRJDXYR.js.map} +0 -0
- /package/dist/{chunk-YEQCMA5L.js.map → chunk-BOSIHHOH.js.map} +0 -0
- /package/dist/{chunk-7LF2OHIJ.js.map → chunk-BRHKW7GY.js.map} +0 -0
- /package/dist/{chunk-LX4TNSAE.js.map → chunk-CBY54QYW.js.map} +0 -0
- /package/dist/{chunk-6YMEU6OQ.js.map → chunk-G72IPMR7.js.map} +0 -0
- /package/dist/{chunk-7AF243WZ.js.map → chunk-GBVRVYF4.js.map} +0 -0
- /package/dist/{chunk-GTD4Q62X.js.map → chunk-H4GQ2Y24.js.map} +0 -0
- /package/dist/{chunk-QI5RDDEL.js.map → chunk-HXZNTZ3Y.js.map} +0 -0
- /package/dist/{chunk-CIAI24TQ.js.map → chunk-IBZQQOM5.js.map} +0 -0
- /package/dist/{chunk-VPHSMJ2E.js.map → chunk-JPWSYHLB.js.map} +0 -0
- /package/dist/{chunk-X7LEDA74.js.map → chunk-KFB4YNXM.js.map} +0 -0
- /package/dist/{chunk-IPLYGWQF.js.map → chunk-KQAFEZQX.js.map} +0 -0
- /package/dist/{chunk-ZUPKNWRZ.js.map → chunk-MIUL6AUZ.js.map} +0 -0
- /package/dist/{chunk-EJY3HJMT.js.map → chunk-MYI3RKI6.js.map} +0 -0
- /package/dist/{chunk-NA56NSKL.js.map → chunk-OOJCXJBN.js.map} +0 -0
- /package/dist/{chunk-7KQB4EBS.js.map → chunk-OPPBTPUU.js.map} +0 -0
- /package/dist/{chunk-ERPBRXVZ.js.map → chunk-PZKWPXRF.js.map} +0 -0
- /package/dist/{chunk-FHKXVTM5.js.map → chunk-Q5XKKDFQ.js.map} +0 -0
- /package/dist/{chunk-QRWMS6SI.js.map → chunk-Q6OL23WM.js.map} +0 -0
- /package/dist/{chunk-OW7NVMGQ.js.map → chunk-QIZOU3FN.js.map} +0 -0
- /package/dist/{chunk-V3KIRICY.js.map → chunk-QQYHYW2N.js.map} +0 -0
- /package/dist/{chunk-YFCEBB5P.js.map → chunk-QTXNS3HB.js.map} +0 -0
- /package/dist/{chunk-2QSZNTDO.js.map → chunk-RKNJBZ55.js.map} +0 -0
- /package/dist/{chunk-E4KMY4KR.js.map → chunk-SNEUAZ6B.js.map} +0 -0
- /package/dist/{chunk-TSTI6A3A.js.map → chunk-SYJW273H.js.map} +0 -0
- /package/dist/{chunk-PBRCYYO7.js.map → chunk-ULZFZL7K.js.map} +0 -0
- /package/dist/{chunk-UGHCZS6K.js.map → chunk-VFZQXYN5.js.map} +0 -0
- /package/dist/{chunk-NKB43PGI.js.map → chunk-WZDTSBGQ.js.map} +0 -0
- /package/dist/{chunk-2UM6WHME.js.map → chunk-XE2QCCT2.js.map} +0 -0
- /package/dist/{chunk-FPEZ74F7.js.map → chunk-XNJQZLAP.js.map} +0 -0
- /package/dist/{chunk-SYVGVK4S.js.map → chunk-XTMYB2HY.js.map} +0 -0
- /package/dist/{chunk-OETHJBAL.js.map → chunk-XV6PUXJ5.js.map} +0 -0
- /package/dist/{chunk-UCLMKNHA.js.map → chunk-YIMV2KYM.js.map} +0 -0
- /package/dist/{chunk-DYZR3Z6D.js.map → chunk-YMQKPSB2.js.map} +0 -0
- /package/dist/{chunk-AYVCKGA6.js.map → chunk-YTXNDEUS.js.map} +0 -0
- /package/dist/{first-start-migration-4NETATFF.js.map → first-start-migration-Q2VB2E2D.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extraction-judge.ts"],"sourcesContent":["/**\n * Extraction Judge — LLM-as-judge fact-worthiness gate (issue #376).\n *\n * Evaluates extracted facts against a durability rubric before they are\n * persisted. Facts that are unlikely to be useful 30+ days from now or\n * across sessions are rejected (or shadow-logged depending on config).\n *\n * Design constraints:\n * - Corrections and principles are auto-approved (safety bypass).\n * - Critical-importance facts are auto-approved.\n * - Batches respect extractionJudgeBatchSize.\n * - Content-hash caching avoids redundant LLM calls.\n * - Performance budget: <= 1.5s per batch.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { log } from \"./logger.js\";\nimport type { PluginConfig, ImportanceLevel } from \"./types.js\";\nimport type { LocalLlmClient } from \"./local-llm.js\";\nimport { type FallbackLlmClient, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport { normalizeProcedureSteps } from \"./procedural/procedure-types.js\";\n\n// ---------------------------------------------------------------------------\n// Public interfaces\n// ---------------------------------------------------------------------------\n\nexport interface JudgeCandidate {\n text: string;\n category: string;\n confidence: number;\n tags?: string[];\n /** Local importance level, set by caller before judging. */\n importanceLevel?: ImportanceLevel;\n}\n\n/**\n * Verdict kinds (issue #562, PR 1).\n *\n * - `\"accept\"`: fact is durable, persist it.\n * - `\"reject\"`: fact is not durable, drop it.\n * - `\"defer\"`: fact is ambiguous; push it back into the buffer for another\n * pass with fresh context. Inspired by MemReader (arxiv 2604.07877).\n *\n * PR 1 only introduces the type. No emit path produces `\"defer\"` yet — the\n * defer-capable prompt, buffer re-routing, telemetry, and GRPO data\n * collection are landing in PRs 2, 3, and 4 respectively.\n */\nexport type JudgeVerdictKind = \"accept\" | \"reject\" | \"defer\";\n\n/**\n * Judge verdict shape.\n *\n * Back-compat note: `kind` is optional. Verdicts serialized before PR 1\n * (both in-memory cache entries and any persisted caches) only carry\n * `{ durable, reason }`. Downstream consumers must either read `durable`\n * directly, or use {@link getVerdictKind} / {@link isDurableVerdict} which\n * gracefully fall back to the boolean when `kind` is missing, and ignore\n * unknown future `kind` values rather than crashing.\n */\nexport interface JudgeVerdict {\n /**\n * True iff the fact should be persisted. For `\"defer\"` verdicts this is\n * `false` — a deferred fact is not (yet) persisted, so callers that only\n * look at `durable` will treat defer as \"skip this turn\", which matches\n * the pre-PR-1 fail-closed behavior for non-accepted verdicts.\n */\n durable: boolean;\n reason: string;\n /**\n * Optional explicit verdict kind. Added in PR 1 of issue #562. Legacy\n * verdicts (including cache entries produced before this field existed)\n * do not set `kind`; use {@link getVerdictKind} to read this safely.\n */\n kind?: JudgeVerdictKind;\n}\n\n/**\n * Resolve a verdict's effective kind.\n *\n * - If `kind` is explicitly set to one of the known values, return it.\n * - If `kind` is absent, infer from `durable` (back-compat with pre-PR-1\n * cache entries and emit paths that have not been updated yet).\n * - If `kind` is set to an unrecognised value (forward-compat, e.g. a\n * future cache entry loaded by an older build), fall back to `durable`\n * so we never crash on unknown strings.\n */\nexport function getVerdictKind(verdict: JudgeVerdict): JudgeVerdictKind {\n const raw = verdict.kind;\n if (raw === \"accept\" || raw === \"reject\" || raw === \"defer\") {\n return raw;\n }\n return verdict.durable ? \"accept\" : \"reject\";\n}\n\n/**\n * Type guard: returns `true` only for verdicts that should be persisted.\n * Treats both `\"reject\"` and `\"defer\"` as \"not durable\" — defer means the\n * caller should re-evaluate later, not write now.\n */\nexport function isDurableVerdict(verdict: JudgeVerdict): boolean {\n return getVerdictKind(verdict) === \"accept\";\n}\n\n/**\n * Validate a cache entry loaded from persistence / another process.\n *\n * Strict: accepts legacy `{ durable, reason }` entries and new entries\n * whose `kind` is one of the three known `JudgeVerdictKind` values.\n * Rejects structurally wrong types and unknown `kind` strings so the\n * type-guard narrowing is sound — callers that receive\n * `value is JudgeVerdict` can safely treat `kind` as the declared\n * union.\n *\n * Forward-compat is handled by {@link normalizeCachedVerdict}, which\n * drops unknown `kind` strings before validation so a newer build's\n * cache entry still loads instead of being rejected.\n */\nexport function isValidCachedVerdict(value: unknown): value is JudgeVerdict {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n if (typeof v.durable !== \"boolean\") return false;\n if (typeof v.reason !== \"string\") return false;\n if (v.kind !== undefined) {\n if (v.kind !== \"accept\" && v.kind !== \"reject\" && v.kind !== \"defer\") {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Forward-compatible cache-entry loader.\n *\n * Drops unknown `kind` strings to `undefined` (so `getVerdictKind` can\n * fall back to `durable`), then validates structurally. Non-string\n * `kind` values are still treated as structural violations and rejected.\n * Returns the sanitised verdict, or `null` when the entry is structurally\n * unusable.\n */\nexport function normalizeCachedVerdict(value: unknown): JudgeVerdict | null {\n if (typeof value !== \"object\" || value === null) return null;\n const v = value as Record<string, unknown>;\n if (typeof v.durable !== \"boolean\") return null;\n if (typeof v.reason !== \"string\") return null;\n let kind: JudgeVerdictKind | undefined;\n if (v.kind !== undefined) {\n if (typeof v.kind !== \"string\") return null;\n if (v.kind === \"accept\" || v.kind === \"reject\" || v.kind === \"defer\") {\n kind = v.kind;\n }\n // Unknown string `kind`: dropped to undefined for forward-compat.\n }\n const out: JudgeVerdict = { durable: v.durable, reason: v.reason };\n if (kind !== undefined) out.kind = kind;\n return out;\n}\n\nexport interface JudgeBatchResult {\n verdicts: Map<number, JudgeVerdict>;\n /** Number of verdicts served from cache. */\n cached: number;\n /** Number of verdicts produced by an LLM call. */\n judged: number;\n /** Total wall-clock time in milliseconds. */\n elapsed: number;\n /**\n * Number of verdicts in this batch that resolved to `\"defer\"` (issue #562,\n * PR 2). Callers can use this to decide whether to retain buffer turns for\n * the next extraction pass.\n */\n deferred: number;\n /**\n * Number of defers that were forcibly converted to `\"reject\"` because the\n * same candidate text had already been deferred at least\n * `extractionJudgeMaxDeferrals` times. Rolled out of `deferred` — a\n * candidate counted here is *not* also in `deferred`.\n */\n deferredCappedToReject: number;\n}\n\n/**\n * Per-verdict observation emitted by `judgeFactDurability` when an\n * `onVerdict` callback is supplied (issue #562, PR 3). Used to wire the\n * observation ledger / telemetry stream without coupling the judge module\n * directly to filesystem I/O. One event is emitted for every resolved\n * verdict, including auto-approved and cache-hit paths.\n */\nexport interface JudgeVerdictObservation {\n verdict: JudgeVerdict;\n /** The original `JudgeCandidate` passed in (same reference). */\n candidate: JudgeCandidate;\n /** SHA-256 of `text\\0category`, same key the cache/deferCounter use. */\n contentHash: string;\n /** Verdict resolution path. Useful for debugging + dashboards. */\n source: \"auto-approve\" | \"cache\" | \"llm\" | \"llm-cap-rejected\" | \"fail-open\";\n /**\n * How many times this candidate had already been deferred before this\n * verdict resolved. 0 when the candidate had never been deferred.\n */\n priorDeferrals: number;\n /**\n * Milliseconds from batch start to now. Shared across verdicts emitted in\n * the same batch.\n */\n elapsedMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Prompt (embedded; mirrors prompts/extraction_judge.prompt.md)\n// ---------------------------------------------------------------------------\n\nconst JUDGE_SYSTEM_PROMPT = `You are a memory curator evaluating whether extracted facts are **durable** — worth storing for long-term recall across sessions.\n\nA fact is **durable** if it will still be useful 30+ days from now and is relevant across multiple sessions, not just the current task.\n\nReturn one of three verdicts per candidate:\n\nACCEPT — the fact is durable, persist it:\n- Personal preferences, identities, or relationships\n- Decisions with rationale that affect future work\n- Corrections to previously held beliefs\n- Principles, rules, or constraints the user wants respected\n- Stable facts about projects, tools, or workflows\n- Commitments, deadlines, or obligations\n\nREJECT — the fact is not durable, drop it:\n- Transient task details (\"currently debugging line 42\")\n- Ephemeral state (\"the build is running now\")\n- Routine operations (\"ran npm install\")\n- Conversational filler or acknowledgements\n- Information that will be stale within hours\n- Step-by-step instructions for a one-time task\n\nDEFER — the fact MIGHT be durable but needs more context to decide. The candidate will be re-evaluated on a later extraction pass with fresh context; if it cannot be resolved within a small number of re-evaluations it will be rejected.\n- Ambiguous referents (\"he said they'd follow up on it\")\n- Partial or in-progress statements that might become durable once completed\n- Future-tense commitments whose subject or timeline is unclear\n- Facts whose durability hinges on context not present in the candidate text\n\nDo NOT use defer as a soft reject. Reject facts you are confident are transient. Only defer when another turn of context would genuinely change the verdict.\n\nReturn a JSON array of objects with these fields:\n- index: number (the candidate index)\n- kind: string — one of \"accept\", \"reject\", \"defer\"\n- reason: string (brief explanation, under 80 characters)\n\nYou may also include durable (boolean) for backwards compatibility: true for accept, false for reject or defer. If kind is omitted, durable determines the verdict.\n\nRules:\n1. Return exactly one verdict per input candidate, matched by index.\n2. When in doubt between accept and reject, lean toward accept — false negatives (losing a useful fact) are worse than false positives (keeping a marginal one).\n3. Use defer only when another turn of context would genuinely change the verdict.\n4. Output valid JSON only. No markdown fences, no commentary.\n\nExample output:\n[{\"index\": 0, \"kind\": \"accept\", \"durable\": true, \"reason\": \"Stable personal preference\"}, {\"index\": 1, \"kind\": \"reject\", \"durable\": false, \"reason\": \"Ephemeral build status\"}, {\"index\": 2, \"kind\": \"defer\", \"durable\": false, \"reason\": \"Ambiguous pronoun\"}]`;\n\n// ---------------------------------------------------------------------------\n// Content-hash cache (in-memory, per-process fallback)\n// ---------------------------------------------------------------------------\n\n/** Maximum entries before evicting the oldest half. */\nconst VERDICT_CACHE_MAX_SIZE = 10_000;\n\n/** Module-level fallback cache, used when callers do not pass their own. */\nconst defaultVerdictCache = new Map<string, JudgeVerdict>();\n\n/**\n * Per-content-hash deferral counter (issue #562, PR 2).\n *\n * When the judge emits a `\"defer\"` verdict for a candidate whose content\n * has already been deferred `extractionJudgeMaxDeferrals` times, the verdict\n * is forcibly converted to `\"reject\"` so a pathological LLM response cannot\n * produce an infinite defer loop.\n *\n * Module-level with a size cap so stale test state cannot leak between runs\n * in the unlikely case a caller does not clear it between processes.\n */\nconst defaultDeferCounts = new Map<string, number>();\nconst DEFER_COUNT_MAX_SIZE = 20_000;\n\nfunction cacheKey(text: string, category: string): string {\n return createHash(\"sha256\").update(`${text}\\0${category}`).digest(\"hex\");\n}\n\n/**\n * Resolve the effective defer cap from config, defaulting to 2 when the\n * config value is missing or non-positive. Matches the PR 2 spec.\n */\nfunction resolveDeferCap(config: PluginConfig): number {\n const raw = (config as { extractionJudgeMaxDeferrals?: number })\n .extractionJudgeMaxDeferrals;\n if (typeof raw === \"number\" && Number.isFinite(raw) && raw >= 1) {\n return Math.floor(raw);\n }\n return 2;\n}\n\n/**\n * Enforce the max-size invariant on a verdict cache. When the cache exceeds\n * VERDICT_CACHE_MAX_SIZE, the oldest half of entries are deleted (Map\n * iteration order is insertion order).\n */\nfunction enforceMaxCacheSize(cache: Map<string, JudgeVerdict>): void {\n if (cache.size <= VERDICT_CACHE_MAX_SIZE) return;\n const deleteCount = Math.floor(cache.size / 2);\n let deleted = 0;\n for (const key of cache.keys()) {\n if (deleted >= deleteCount) break;\n cache.delete(key);\n deleted++;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Categories that bypass the judge (safety / correctness)\n// ---------------------------------------------------------------------------\n\nconst AUTO_APPROVE_CATEGORIES = new Set([\"correction\", \"principle\"]);\n\n/** Explicit trigger phrasing — procedures must match to persist (issue #519). */\nconst PROCEDURE_TRIGGER_RE =\n /(when you|whenever|before you|before running|always\\s|first\\b.*\\bthen|to deploy|to ship|run these steps|follow these steps|how (i|we)\\s|recipe for|workflow|each time you)/i;\n\n/**\n * Deterministic gate for extracted `procedure` memories: ≥2 steps with non-empty\n * intents and explicit trigger wording in title and/or steps.\n */\nexport function validateProcedureExtraction(input: {\n content: string;\n procedureSteps?: unknown;\n}): JudgeVerdict {\n const steps = normalizeProcedureSteps(input.procedureSteps);\n if (steps.length < 2) {\n return { durable: false, reason: \"Procedure requires at least two steps with intents\" };\n }\n const combined = [input.content, ...steps.map((s) => s.intent)].join(\" \").toLowerCase();\n if (!PROCEDURE_TRIGGER_RE.test(combined)) {\n return { durable: false, reason: \"Procedure missing explicit trigger phrasing\" };\n }\n return { durable: true, reason: \"Procedure structure validated\" };\n}\n\n// ---------------------------------------------------------------------------\n// Core judge function\n// ---------------------------------------------------------------------------\n\n/**\n * Evaluate a batch of candidate facts for durability.\n *\n * Auto-approves corrections, principles, and critical-importance facts.\n * Remaining candidates are batched (up to extractionJudgeBatchSize),\n * checked against an in-memory content-hash cache, and sent to the LLM\n * for verdict.\n */\nexport async function judgeFactDurability(\n candidates: JudgeCandidate[],\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n cache?: Map<string, JudgeVerdict>,\n deferCounts?: Map<string, number>,\n onVerdict?: (observation: JudgeVerdictObservation) => void,\n): Promise<JudgeBatchResult> {\n const startMs = Date.now();\n const verdicts = new Map<number, JudgeVerdict>();\n let cached = 0;\n let judged = 0;\n let deferred = 0;\n let deferredCappedToReject = 0;\n\n // Use caller-provided cache for per-orchestrator scoping, or fall back\n // to the module-level default cache.\n const verdictCache = cache ?? defaultVerdictCache;\n const deferCountMap = deferCounts ?? defaultDeferCounts;\n const deferCap = resolveDeferCap(config);\n\n // Lazy emit (Codex P2): when `onVerdict` is undefined (default path —\n // telemetry off), payload construction is skipped entirely. Callers\n // pass a factory instead of a pre-built observation so the `sha256`\n // `contentHash` and surrounding object allocation only run when a\n // subscriber is present. For large batches with telemetry off this\n // removes per-verdict overhead that would otherwise fire on every\n // auto-approved / cache / fail-open path.\n const emit = (build: () => JudgeVerdictObservation): void => {\n if (!onVerdict) return;\n let observation: JudgeVerdictObservation;\n try {\n observation = build();\n } catch (err) {\n log.debug(\n `extraction-judge: onVerdict builder threw (non-fatal): ${err instanceof Error ? err.message : String(err)}`,\n );\n return;\n }\n try {\n onVerdict(observation);\n } catch (err) {\n // Fail-open: telemetry errors must never block extraction.\n log.debug(\n `extraction-judge: onVerdict callback threw (non-fatal): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n };\n\n if (candidates.length === 0) {\n return {\n verdicts,\n cached,\n judged,\n elapsed: 0,\n deferred,\n deferredCappedToReject,\n };\n }\n\n // Indices that need LLM judgment\n const pendingIndices: number[] = [];\n\n for (let i = 0; i < candidates.length; i++) {\n const c = candidates[i];\n\n // Auto-approve safety categories\n if (AUTO_APPROVE_CATEGORIES.has(c.category)) {\n const v: JudgeVerdict = {\n durable: true,\n reason: `Auto-approved: ${c.category} category bypasses judge`,\n };\n verdicts.set(i, v);\n emit(() => ({\n verdict: v,\n candidate: c,\n contentHash: cacheKey(c.text, c.category),\n source: \"auto-approve\",\n priorDeferrals: 0,\n elapsedMs: Date.now() - startMs,\n }));\n continue;\n }\n\n // Auto-approve critical importance\n if (c.importanceLevel === \"critical\") {\n const v: JudgeVerdict = {\n durable: true,\n reason: \"Auto-approved: critical importance\",\n };\n verdicts.set(i, v);\n emit(() => ({\n verdict: v,\n candidate: c,\n contentHash: cacheKey(c.text, c.category),\n source: \"auto-approve\",\n priorDeferrals: 0,\n elapsedMs: Date.now() - startMs,\n }));\n continue;\n }\n\n // Check cache\n const key = cacheKey(c.text, c.category);\n const cachedVerdict = verdictCache.get(key);\n if (cachedVerdict) {\n verdicts.set(i, cachedVerdict);\n cached++;\n emit(() => ({\n verdict: cachedVerdict,\n candidate: c,\n contentHash: key,\n source: \"cache\",\n priorDeferrals: deferCountMap.get(key) ?? 0,\n elapsedMs: Date.now() - startMs,\n }));\n continue;\n }\n\n pendingIndices.push(i);\n }\n\n // If all resolved without LLM, return early\n if (pendingIndices.length === 0) {\n return {\n verdicts,\n cached,\n judged,\n elapsed: Date.now() - startMs,\n deferred,\n deferredCappedToReject,\n };\n }\n\n // Batch the pending candidates up to batchSize\n const batchSize = config.extractionJudgeBatchSize;\n for (let batchStart = 0; batchStart < pendingIndices.length; batchStart += batchSize) {\n const batchIndices = pendingIndices.slice(batchStart, batchStart + batchSize);\n const batchPayload = batchIndices.map((idx) => ({\n index: idx,\n text: candidates[idx].text,\n category: candidates[idx].category,\n confidence: candidates[idx].confidence,\n }));\n\n const userPrompt = JSON.stringify(batchPayload);\n\n try {\n const llmResponse = await callJudgeLlm(\n userPrompt,\n config,\n localLlm,\n fallbackLlm,\n );\n\n if (llmResponse) {\n const parsed = parseJudgeResponse(llmResponse, batchIndices);\n // Per-batch defer-increment dedupe (codex P2): a single extraction\n // pass must not advance the cap more than once for identical\n // candidate content, even if the same text appears multiple times\n // in the same LLM response. Duplicate hits share the first\n // increment's `priorDeferrals` snapshot.\n const deferredThisBatch = new Set<string>();\n for (const [idx, rawVerdict] of parsed.entries()) {\n const c = candidates[idx];\n const key = cacheKey(c.text, c.category);\n let verdict = rawVerdict;\n let source: JudgeVerdictObservation[\"source\"] = \"llm\";\n const priorDefers = deferCountMap.get(key) ?? 0;\n\n // Defer cap (issue #562, PR 2). A candidate that has already been\n // deferred `deferCap` times is forcibly rejected so a pathological\n // LLM response cannot produce an infinite defer loop.\n if (getVerdictKind(verdict) === \"defer\") {\n if (priorDefers >= deferCap) {\n verdict = {\n durable: false,\n reason: `Defer cap reached (${deferCap} prior defers); rejecting`,\n kind: \"reject\",\n };\n source = \"llm-cap-rejected\";\n // Only clear + count the cap conversion once per batch for\n // this key — duplicates in the same response all resolve to\n // reject but should not inflate the cap-rejection counter.\n if (!deferredThisBatch.has(key)) {\n deferCountMap.delete(key);\n deferredCappedToReject++;\n deferredThisBatch.add(key);\n }\n } else if (!deferredThisBatch.has(key)) {\n deferCountMap.set(key, priorDefers + 1);\n deferred++;\n deferredThisBatch.add(key);\n // Bound the per-process defer-counter map.\n if (deferCountMap.size > DEFER_COUNT_MAX_SIZE) {\n const drop = Math.floor(deferCountMap.size / 2);\n let dropped = 0;\n for (const k of deferCountMap.keys()) {\n if (dropped >= drop) break;\n deferCountMap.delete(k);\n dropped++;\n }\n }\n }\n // else: duplicate defer for a key already counted this batch —\n // no additional counter increment, verdict still marked defer.\n } else {\n // On accept/reject, clear any outstanding defer counter so a\n // future reappearance of the same text starts fresh.\n deferCountMap.delete(key);\n }\n\n verdicts.set(idx, verdict);\n judged++;\n // Cache non-defer verdicts. Defer is intentionally NOT cached:\n // caching it would short-circuit the re-evaluation pass that is\n // the entire point of the defer verdict.\n if (getVerdictKind(verdict) !== \"defer\") {\n verdictCache.set(key, verdict);\n }\n emit(() => ({\n verdict,\n candidate: c,\n contentHash: key,\n source,\n priorDeferrals: priorDefers,\n elapsedMs: Date.now() - startMs,\n }));\n }\n // Evict oldest entries if cache exceeds max size\n enforceMaxCacheSize(verdictCache);\n }\n } catch (err) {\n // Fail-open: if the LLM call fails, approve all candidates in this batch\n log.warn(\n `extraction-judge: LLM call failed, approving batch (fail-open): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Fill in any missing verdicts from this batch (fail-open: approve).\n // Clear defer counts so a transient outage doesn't leave stale state\n // that causes later defers to hit the cap early.\n for (const idx of batchIndices) {\n if (!verdicts.has(idx)) {\n const c = candidates[idx];\n const hash = cacheKey(c.text, c.category);\n // Capture the prior deferral count BEFORE clearing so the\n // telemetry event reflects the true state rather than always 0.\n const priorDefers = deferCountMap.get(hash) ?? 0;\n deferCountMap.delete(hash);\n const v: JudgeVerdict = {\n durable: true,\n reason: \"Approved by default (judge unavailable or parse error)\",\n };\n verdicts.set(idx, v);\n emit(() => {\n return {\n verdict: v,\n candidate: c,\n contentHash: hash,\n source: \"fail-open\",\n priorDeferrals: priorDefers,\n elapsedMs: Date.now() - startMs,\n };\n });\n }\n }\n }\n\n return {\n verdicts,\n cached,\n judged,\n elapsed: Date.now() - startMs,\n deferred,\n deferredCappedToReject,\n };\n}\n\n// ---------------------------------------------------------------------------\n// LLM call helpers\n// ---------------------------------------------------------------------------\n\nasync function callJudgeLlm(\n userPrompt: string,\n config: PluginConfig,\n localLlm: LocalLlmClient | null,\n fallbackLlm: FallbackLlmClient | null,\n): Promise<string | null> {\n const messages: Array<{ role: \"system\" | \"user\"; content: string }> = [\n { role: \"system\", content: JUDGE_SYSTEM_PROMPT },\n { role: \"user\", content: userPrompt },\n ];\n\n const modelOverride = config.extractionJudgeModel || undefined;\n\n // When modelSource is \"gateway\", skip localLlm and go directly to fallback\n // (the gateway-routed backend). This respects the operator's explicit\n // routing preference.\n const skipLocal = config.modelSource === \"gateway\";\n\n // Route judge-gated extractions through the SAME shared resolution as every\n // other background task (taskModelChain > gatewayAgentId in gateway mode), so\n // the judge never silently falls back to the persona/default chain when a\n // task chain is configured (gotcha #22, #39). Issue #1365 / PR #1425.\n const gatewayChain = gatewayTaskChainOptions(config);\n\n // Try local LLM first (unless modelSource says gateway)\n if (localLlm && !skipLocal) {\n try {\n const result = await (localLlm as any).chatCompletion(messages, {\n temperature: 0.1,\n maxTokens: 2048,\n responseFormat: { type: \"json_object\" },\n timeoutMs: 1500,\n operation: \"extraction-judge\",\n ...(modelOverride ? { model: modelOverride } : {}),\n });\n if (result?.content) {\n return result.content;\n }\n } catch (err) {\n log.debug(\n `extraction-judge: local LLM failed, trying fallback: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // Try fallback LLM\n if (fallbackLlm) {\n try {\n const result = await fallbackLlm.chatCompletion(\n messages as Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n {\n temperature: 0.1,\n maxTokens: 2048,\n timeoutMs: 1500,\n ...(modelOverride ? { model: modelOverride } : {}),\n ...gatewayChain,\n },\n );\n if (result?.content) {\n return result.content;\n }\n } catch (err) {\n log.debug(\n `extraction-judge: fallback LLM failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Response parsing\n// ---------------------------------------------------------------------------\n\nfunction parseJudgeResponse(\n raw: string,\n expectedIndices: number[],\n): Map<number, JudgeVerdict> {\n const result = new Map<number, JudgeVerdict>();\n const expectedSet = new Set(expectedIndices);\n\n try {\n // Try direct parse first, then fall back to JSON extraction\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n const candidates = extractJsonCandidates(raw);\n if (candidates.length > 0) {\n parsed = JSON.parse(candidates[0]);\n }\n }\n\n if (!Array.isArray(parsed)) {\n // Might be wrapped in an object with a key\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const values = Object.values(parsed as Record<string, unknown>);\n for (const v of values) {\n if (Array.isArray(v)) {\n parsed = v;\n break;\n }\n }\n }\n if (!Array.isArray(parsed)) {\n log.debug(\"extraction-judge: response is not an array, cannot parse\");\n return result;\n }\n }\n\n for (const item of parsed) {\n if (\n typeof item !== \"object\" ||\n item === null ||\n typeof (item as any).index !== \"number\"\n ) {\n continue;\n }\n const idx = (item as any).index as number;\n if (!expectedSet.has(idx)) continue;\n\n // Parse kind first — it's the primary signal in PR 2 and above.\n // Fall back to durable for pre-PR-2 model responses that only return\n // the boolean.\n let kind: JudgeVerdictKind | undefined;\n const rawKind = (item as any).kind;\n const rawAction = (item as any).action;\n if (rawKind === \"accept\" || rawKind === \"reject\" || rawKind === \"defer\") {\n kind = rawKind;\n } else if (\n rawAction === \"accept\" ||\n rawAction === \"reject\" ||\n rawAction === \"defer\"\n ) {\n // Tolerate `action` as an alias — MemReader uses that word in the\n // paper and models may echo it.\n kind = rawAction;\n }\n\n const hasDurable = typeof (item as any).durable === \"boolean\";\n const durableFromModel = hasDurable\n ? ((item as any).durable as boolean)\n : undefined;\n\n // Resolve the durable flag from kind when present; otherwise trust\n // the model's boolean; otherwise fail-open to durable=true.\n let durable: boolean;\n if (kind === \"accept\") {\n durable = true;\n } else if (kind === \"reject\" || kind === \"defer\") {\n durable = false;\n } else if (durableFromModel !== undefined) {\n durable = durableFromModel;\n } else {\n durable = true; // fail-open\n }\n\n const reason =\n typeof (item as any).reason === \"string\"\n ? ((item as any).reason as string).slice(0, 120)\n : \"No reason provided\";\n\n const verdict: JudgeVerdict = { durable, reason };\n if (kind !== undefined) verdict.kind = kind;\n result.set(idx, verdict);\n }\n } catch (err) {\n log.debug(\n `extraction-judge: failed to parse response: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Cache management (exposed for testing)\n// ---------------------------------------------------------------------------\n\n/** Clear the in-memory default verdict cache. Primarily for tests. */\nexport function clearVerdictCache(): void {\n defaultVerdictCache.clear();\n defaultDeferCounts.clear();\n}\n\n/** Return the current default verdict cache size. Primarily for tests. */\nexport function verdictCacheSize(): number {\n return defaultVerdictCache.size;\n}\n\n/** Create a new per-instance verdict cache. Orchestrators should hold one. */\nexport function createVerdictCache(): Map<string, JudgeVerdict> {\n return new Map();\n}\n\n/**\n * Create a new per-instance defer-counter map. Orchestrators should hold one\n * alongside their verdict cache so defer counts survive across extraction\n * passes within a single orchestrator but do not leak across orchestrators.\n */\nexport function createDeferCountMap(): Map<string, number> {\n return new Map();\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,SAAS,kBAAkB;AAwEpB,SAAS,eAAe,SAAyC;AACtE,QAAM,MAAM,QAAQ;AACpB,MAAI,QAAQ,YAAY,QAAQ,YAAY,QAAQ,SAAS;AAC3D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,UAAU,WAAW;AACtC;AAOO,SAAS,iBAAiB,SAAgC;AAC/D,SAAO,eAAe,OAAO,MAAM;AACrC;AAgBO,SAAS,qBAAqB,OAAuC;AAC1E,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,IAAI;AACV,MAAI,OAAO,EAAE,YAAY,UAAW,QAAO;AAC3C,MAAI,OAAO,EAAE,WAAW,SAAU,QAAO;AACzC,MAAI,EAAE,SAAS,QAAW;AACxB,QAAI,EAAE,SAAS,YAAY,EAAE,SAAS,YAAY,EAAE,SAAS,SAAS;AACpE,a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UAAI,CAAC,YAAY,IAAI,GAAG,EAAG;AAK3B,UAAI;AACJ,YAAM,UAAW,KAAa;AAC9B,YAAM,YAAa,KAAa;AAChC,UAAI,YAAY,YAAY,YAAY,YAAY,YAAY,SAAS;AACvE,eAAO;AAAA,MACT,WACE,cAAc,YACd,cAAc,YACd,cAAc,SACd;AAGA,eAAO;AAAA,MACT;AAEA,YAAM,aAAa,OAAQ,KAAa,YAAY;AACpD,YAAM,mBAAmB,aACnB,KAAa,UACf;AAIJ,UAAI;AACJ,UAAI,SAAS,UAAU;AACrB,kBAAU;AAAA,MACZ,WAAW,SAAS,YAAY,SAAS,SAAS;AAChD,kBAAU;AAAA,MACZ,WAAW,qBAAqB,QAAW;AACzC,kBAAU;AAAA,MACZ,OAAO;AACL,kBAAU;AAAA,MACZ;AAEA,YAAM,SACJ,OAAQ,KAAa,WAAW,WAC1B,KAAa,OAAkB,MAAM,GAAG,GAAG,IAC7C;AAEN,YAAM,UAAwB,EAAE,SAAS,OAAO;AAChD,UAAI,SAAS,OAAW,SAAQ,OAAO;AACvC,aAAO,IAAI,KAAK,OAAO;AAAA,IACzB;AAAA,EACF,SAAS,KAAK;AACZ,QAAI;AAAA,MACF,+CAA+C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IACjG;AAAA,EACF;AAEA,SAAO;AACT;AAOO,SAAS,oBAA0B;AACxC,sBAAoB,MAAM;AAC1B,qBAAmB,MAAM;AAC3B;AAGO,SAAS,mBAA2B;AACzC,SAAO,oBAAoB;AAC7B;AAGO,SAAS,qBAAgD;AAC9D,SAAO,oBAAI,IAAI;AACjB;AAOO,SAAS,sBAA2C;AACzD,SAAO,oBAAI,IAAI;AACjB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extraction.ts","../src/orchestration/dependency-revalidation.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport { isAbortError } from \"./abort-error.js\";\nimport { log } from \"./logger.js\";\nimport { delinearize } from \"./delinearize.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { shouldRunProactivePass } from \"./proactive-contention.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { revalidateDependentsViaLlm, type RevalidationFastChatCompletion } from \"./orchestration/dependency-revalidation.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 ExtractionFailureClass,\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, buildExtensionsFooterForSummary } from \"./day-summary.js\";\nimport { ProfilingCollector } from \"./profiling.js\";\nimport { normalizeProcedureSteps } from \"./procedural/procedure-types.js\";\nimport { normalizeReasoningTrace } from \"./reasoning-trace-types.js\";\nimport { looksLikeMechanicalTelemetryTranscript } from \"./telemetry-transcript.js\";\nimport {\n attachExtractionProvenance,\n type ExtractionGroundingRoleSources,\n} from \"./extraction-source-grounding.js\";\nimport { applyGroundingWithConnector, headerConnector, renderExtractionConversation, resolveSourceConnector, type ExtractionGroundingContext } from \"./source-agent-qualifier.js\";\nimport { isMemoryCategory } from \"./write-envelope.js\";\nimport { classifyExtractionThrownError, classifyFallbackParseFailure } from \"./extraction-error-classification.js\";\nimport { AMBIENT_CAPTURE_PROMPT_SECTION_COMPACT, clampAmbientCaptureConfidence } from \"./ambient-provenance.js\";\nimport { CUE_ANCHOR_PROMPT_INSTRUCTION, EXTRACTION_RESPONSE_SHAPE, buildExtractionInstructions, eventTimePromptInstruction } from \"./extraction-prompt.js\";\nimport {\n containsExtractionPlaceholder,\n extractionAttributes,\n extractionCueAnchors,\n extractionText,\n isPlainRecord,\n} from \"./extraction-normalization.js\";\nexport { classifyExtractionThrownError, classifyFallbackParseFailure } from \"./extraction-error-classification.js\";\nimport { resolveLocalLlmCapabilities, resolveMemoryLifecycleCapabilities, resolvePipelineProcessingCapabilities, resolveRecallAuxiliaryCapabilities } from \"./capabilities.js\";\n\ntype ExtractionQuestion = ExtractionResult[\"questions\"][number];\ntype ExtractedFactResult = ExtractionResult[\"facts\"][number];\ntype ExtractedEntityResult = ExtractionResult[\"entities\"][number];\ntype ExtractedRelationshipResult = NonNullable<ExtractionResult[\"relationships\"]>[number];\n\nconst PROACTIVE_MIN_CONFIDENCE = 0.8;\nconst CONSOLIDATION_RESPONSE_SCHEMA = `{\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\nfunction extractionEntityType(value: unknown): ExtractedEntityResult[\"type\"] | undefined {\n const type = extractionText(value);\n if (\n type === \"person\" ||\n type === \"project\" ||\n type === \"tool\" ||\n type === \"company\" ||\n type === \"place\" ||\n type === \"other\"\n ) {\n return type;\n }\n return undefined;\n}\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 function shouldEnableLocalExtractionThinking(\n config: Pick<PluginConfig, \"localLlmDisableThinking\" | \"localLlmThinkingThresholdChars\">,\n conversationChars: number,\n): boolean {\n return config.localLlmDisableThinking &&\n config.localLlmThinkingThresholdChars > 0 &&\n conversationChars < config.localLlmThinkingThresholdChars;\n}\n\nfunction throwIfExtractionAborted(signal?: AbortSignal): void {\n if (!signal?.aborted) return;\n const reason = signal.reason;\n throw reason instanceof Error ? reason : new Error(\"extraction aborted\");\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 private readonly fastChatCompletion?: RevalidationFastChatCompletion,\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(\n gatewayConfig,\n fallbackLlmRuntimeContextFromConfig(config),\n );\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.taskModelChain ? \" (taskModelChain)\" :\n config.gatewayAgentId ? ` (agent: ${config.gatewayAgentId})` : \" (defaults)\"),\n );\n } else if (config.taskModelChain) {\n // taskModelChain resolves through gateway providers, so it only applies\n // under modelSource: \"gateway\". Warn rather than silently ignore it so a\n // misconfigured plugin-mode setup is visible. Issue #1365 / PR #1370.\n log.warn(\n `taskModelChain is set but modelSource is \"${config.modelSource}\"; the chain is ignored. ` +\n `Set modelSource: \"gateway\" to use it for extraction/consolidation/summarization.`,\n );\n }\n }\n\n private get useGatewayModelSource(): boolean {\n return this.config.modelSource === \"gateway\";\n }\n\n private get shouldUseLocalLlm(): boolean {\n return resolveLocalLlmCapabilities(this.config).localLlm && !this.useGatewayModelSource;\n }\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 // Shared resolution (taskModelChain > gatewayAgentId) so every background\n // task routes identically (gotcha #22). Issue #1365.\n return { ...options, ...gatewayTaskChainOptions(this.config) };\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 proceduralOn = this.config.procedural?.enabled === true;\n const ts = messageTimestamp ?? new Date();\n const facts = result.facts\n .filter((fact) => proceduralOn || fact.category !== \"procedure\")\n .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 (resolvePipelineProcessingCapabilities(this.config).delinearize) {\n content = delinearize(content, result.entities, ts);\n }\n return {\n ...fact,\n content,\n cueAnchors: extractionCueAnchors(fact.cueAnchors),\n };\n });\n return { ...result, facts, episodeTitle: extractionText(result.episodeTitle) };\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 looksLikeExtractionResultPayload(parsed: any): boolean {\n return !!parsed &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed) &&\n (\n \"facts\" in parsed ||\n \"entities\" in parsed ||\n \"profileUpdates\" in parsed ||\n \"questions\" in parsed ||\n \"relationships\" in parsed ||\n \"identityReflection\" in parsed\n );\n }\n\n private normalizeExtractionResultPayload(parsed: any): ExtractionResult {\n const entities: ExtractedEntityResult[] = Array.isArray(parsed?.entities)\n ? parsed.entities\n .map((candidate: unknown): ExtractedEntityResult | undefined => this.normalizeEntityUpdate(candidate))\n .filter((entity: ExtractedEntityResult | undefined): entity is ExtractedEntityResult => (\n entity !== undefined && entity.name.length > 0\n ))\n : [];\n\n const facts = Array.isArray(parsed?.facts)\n ? parsed.facts\n .map((candidate: unknown) => {\n const f = isPlainRecord(candidate) ? candidate : {};\n const category = typeof f.category === \"string\" ? f.category.trim() : \"fact\";\n const reasoningTraceInput = isPlainRecord(f.reasoningTrace)\n ? f.reasoningTrace\n : isPlainRecord(f?.reasoning_trace)\n ? f.reasoning_trace\n : undefined;\n if (!isMemoryCategory(category)) return undefined;\n const procedureSteps = Array.isArray(f.procedureSteps)\n ? normalizeProcedureSteps(f.procedureSteps)\n : undefined;\n const reasoningTrace = reasoningTraceInput\n ? normalizeReasoningTrace(reasoningTraceInput) ?? undefined\n : undefined;\n if (\n containsExtractionPlaceholder(procedureSteps) ||\n containsExtractionPlaceholder(reasoningTrace)\n ) {\n return undefined;\n }\n return {\n category,\n content: extractionText(f.content) ?? extractionText(f.text) ?? \"\",\n confidence: typeof f.confidence === \"number\" ? f.confidence : 0.7,\n tags: Array.isArray(f.tags)\n ? f.tags.flatMap((tag: unknown) => {\n const text = extractionText(tag);\n return text === undefined ? [] : [text];\n })\n : [],\n entityRef: extractionText(f.entityRef),\n cueAnchors: extractionCueAnchors(f.cueAnchors),\n promptedByQuestion: extractionText(f.promptedByQuestion),\n scope:\n f.scope === \"global\" || f.scope === \"project\" ? f.scope : undefined,\n structuredAttributes: extractionAttributes(f.structuredAttributes),\n procedureSteps,\n reasoningTrace,\n quote: extractionText(f.quote),\n eventTime: extractionText(f.eventTime) ?? extractionText(f.event_time),\n };\n })\n .filter((fact: ExtractedFactResult | undefined): fact is ExtractedFactResult => (\n fact !== undefined && fact.content.length > 0\n ))\n : [];\n\n const questions: ExtractionQuestion[] = Array.isArray(parsed?.questions)\n ? parsed.questions.flatMap((candidate: unknown) => {\n const record = isPlainRecord(candidate) ? candidate : undefined;\n const question =\n extractionText(record?.question) ??\n extractionText(record?.text) ??\n extractionText(candidate);\n if (question === undefined) return [];\n return [{\n question,\n context: extractionText(record?.context) ?? \"\",\n priority: typeof record?.priority === \"number\" ? record.priority : 0.5,\n }];\n })\n : [];\n\n const profileUpdates = Array.isArray(parsed?.profileUpdates)\n ? parsed.profileUpdates.flatMap((candidate: unknown) => {\n const update = extractionText(candidate);\n return update === undefined ? [] : [update];\n })\n : [];\n\n const relationships: ExtractedRelationshipResult[] | undefined = Array.isArray(parsed?.relationships)\n ? parsed.relationships.flatMap((candidate: unknown) => {\n const relationship = isPlainRecord(candidate) ? candidate : undefined;\n const source = extractionText(relationship?.source);\n const target = extractionText(relationship?.target);\n const label = extractionText(relationship?.label);\n if (source === undefined || target === undefined || label === undefined) return [];\n return [{\n source,\n target,\n label,\n promptedByQuestion: extractionText(relationship?.promptedByQuestion),\n }];\n })\n : undefined;\n\n return {\n facts,\n entities,\n profileUpdates,\n questions,\n identityReflection: extractionText(parsed?.identityReflection),\n episodeTitle: extractionText(parsed?.episodeTitle),\n relationships,\n };\n }\n\n private normalizeEntityUpdate(entity: unknown): ExtractedEntityResult | undefined {\n const record = isPlainRecord(entity) ? entity : {};\n const rawUpdates = isPlainRecord(record.updates) ? record.updates : undefined;\n const normalizedTexts = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.flatMap((candidate: unknown) => {\n const text = extractionText(candidate);\n return text === undefined ? [] : [text];\n })\n : [];\n const directFacts = normalizedTexts(record.facts);\n const updateFacts = normalizedTexts(rawUpdates?.facts);\n const scalarUpdateFacts = rawUpdates\n ? Object.entries(rawUpdates)\n .sort(([left], [right]) => left.localeCompare(right))\n .flatMap(([key, value]) => {\n if ([\"facts\", \"name\", \"promptedByQuestion\", \"structuredSections\", \"type\"].includes(key)) {\n return [];\n }\n const normalizedKey = extractionText(key);\n if (normalizedKey === undefined) return [];\n const normalizedValue = extractionText(value);\n if (normalizedValue !== undefined) return [`${normalizedKey}: ${normalizedValue}`];\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return [`${normalizedKey}: ${String(value)}`];\n }\n return [];\n })\n : [];\n const structuredSectionsSource = Array.isArray(record.structuredSections)\n ? record.structuredSections\n : Array.isArray(rawUpdates?.structuredSections)\n ? rawUpdates.structuredSections\n : [];\n const structuredSections = structuredSectionsSource.flatMap((candidate: unknown) => {\n const section = isPlainRecord(candidate) ? candidate : {};\n const key = extractionText(section.key);\n const title = extractionText(section.title);\n const facts = normalizedTexts(section.facts);\n if (key === undefined || title === undefined || facts.length === 0) return [];\n return [{ key, title, facts }];\n });\n\n const rawType = record.type ?? rawUpdates?.type;\n const type = rawType === undefined ? \"other\" : extractionEntityType(rawType);\n if (type === undefined) return undefined;\n return {\n name:\n extractionText(record.name) ??\n extractionText(record.entityId) ??\n extractionText(rawUpdates?.name) ??\n \"\",\n type,\n facts: [...directFacts, ...updateFacts, ...scalarUpdateFacts],\n structuredSections: structuredSections.length > 0 ? structuredSections : undefined,\n promptedByQuestion: extractionText(record.promptedByQuestion) ?? extractionText(rawUpdates?.promptedByQuestion),\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: {\n items?: unknown[];\n profileUpdates?: unknown[];\n entityUpdates?: unknown[];\n }): ConsolidationResult {\n const items: ConsolidationResult[\"items\"] = [];\n for (const item of Array.isArray(result.items) ? result.items : []) {\n const rawAction = typeof (item as any)?.action === \"string\" ? (item as any).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 const existingId =\n typeof (item as any)?.existingId === \"string\"\n ? (item as any).existingId.trim()\n : typeof (item as any)?.newMemoryId === \"string\"\n ? (item as any).newMemoryId.trim()\n : typeof (item as any)?.memoryId === \"string\"\n ? (item as any).memoryId.trim()\n : \"\";\n if (!existingId) continue;\n const mergeWith = typeof (item as any)?.mergeWith === \"string\" ? (item as any).mergeWith : undefined;\n const reason = typeof (item as any)?.reason === \"string\" ? (item as any).reason : \"\";\n const rawUpdatedContent = typeof (item as any)?.updatedContent === \"string\" ? (item as any).updatedContent : undefined;\n if (!rawUpdatedContent) {\n items.push({ existingId, action, mergeWith, updatedContent: undefined, reason });\n continue;\n }\n const sanitized = sanitizeMemoryContent(rawUpdatedContent);\n if (!sanitized.clean) {\n log.warn(`consolidation item sanitized (${existingId}); violations=${sanitized.violations.join(\", \")}`);\n }\n items.push({\n existingId,\n action,\n mergeWith,\n updatedContent: sanitized.text,\n reason,\n });\n }\n const profileUpdates = (Array.isArray(result.profileUpdates) ? result.profileUpdates : [])\n .map((update: any) =>\n typeof update === \"string\"\n ? update.trim()\n : typeof update?.content === \"string\"\n ? update.content.trim()\n : \"\",\n )\n .filter((update) => update.length > 0);\n const entityUpdates = (Array.isArray(result.entityUpdates) ? result.entityUpdates : [])\n .map((entity: unknown): ExtractedEntityResult | undefined => this.normalizeEntityUpdate(entity))\n .filter((entity: ExtractedEntityResult | undefined): entity is ExtractedEntityResult => (\n entity !== undefined && entity.name.length > 0\n ));\n return { items, profileUpdates, entityUpdates };\n }\n\n private async applyProactiveQuestionPass(\n conversation: string,\n base: ExtractionResult,\n ctx: ExtractionGroundingContext,\n signal?: AbortSignal,\n ): Promise<ExtractionResult> {\n if (!resolvePipelineProcessingCapabilities(this.config).proactiveExtraction) return base;\n const maxAdditional = Math.max(0, Math.floor(this.config.maxProactiveQuestionsPerExtraction));\n if (!shouldRunProactivePass(this.config, maxAdditional, this.shouldUseLocalLlm, this.localLlm)) return base;\n\n try {\n const proactive = await this.generateProactiveQuestions(conversation, base, maxAdditional, ctx.ambientCapture === true, signal);\n if (proactive.length === 0) return base;\n const ambient = ctx.ambientCapture === true;\n const proactiveAdditions = await this.answerProactiveQuestions(\n conversation, base, proactive, maxAdditional, ctx.sourceConnector, ambient, signal);\n const sanitizedAdditions = this.sanitizeExtractionResult(proactiveAdditions, ctx.messageTimestamp);\n const groundedAdditions = applyGroundingWithConnector(this.config, sanitizedAdditions, ctx);\n if (!this.hasExtractionOutputs(groundedAdditions)) return base;\n return this.mergeProactiveExtractionPass(base, groundedAdditions, maxAdditional);\n } catch (err) {\n if (signal?.aborted) throw 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 ambientCapture: boolean,\n signal?: AbortSignal,\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.${ambientCapture ? AMBIENT_CAPTURE_PROMPT_SECTION_COMPACT : \"\"}`,\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 signal,\n },\n );\n throwIfExtractionAborted(signal);\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 (signal?.aborted || !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 signal,\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 sourceConnector: string | undefined,\n ambientCapture: boolean,\n signal?: AbortSignal,\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.${ambientCapture ? AMBIENT_CAPTURE_PROMPT_SECTION_COMPACT : \"\"}`,\n \"Return only valid JSON with this shape:\",\n '{\"facts\":[{\"category\":\"fact\",\"content\":\"...\",\"confidence\":0.0,\"tags\":[\"...\"],\"entityRef\":\"optional\",\"promptedByQuestion\":\"optional\",\"quote\":\"optional verbatim span from a single turn\"}],\"profileUpdates\":[\"...\"],\"entities\":[{\"name\":\"...\",\"type\":\"person\",\"facts\":[\"...\"],\"structuredSections\":[{\"key\":\"beliefs\",\"title\":\"Beliefs\",\"facts\":[\"...\"]}],\"promptedByQuestion\":\"optional\"}],\"relationships\":[{\"source\":\"...\",\"target\":\"...\",\"label\":\"...\",\"promptedByQuestion\":\"optional\"}]}',\n this.config.provenance?.enabled\n ? '- Source quotes: For each fact, include a \"quote\" field with the EXACT verbatim words from the conversation that support the fact (a contiguous span from a single turn, not a paraphrase). Cap at ~300 chars.'\n : \"\",\n // #1578: emit the same event-time guidance as the primary extraction\n // paths so proactive-recovered facts also carry an optional eventTime\n // (chatgpt-codex thread on extraction.ts:1607). Returns \"\" when the\n // bi-temporal gate is off, keeping the prompt unchanged by default.\n eventTimePromptInstruction(this.config),\n headerConnector(sourceConnector) !== undefined && resolveMemoryLifecycleCapabilities(this.config).extractionScopeClassification\n ? `Tool, command, or CLI-flag instructions tied to the ${sourceConnector} agent are \"project\" scope; when you recover one, begin the fact with a leading \"In ${sourceConnector}, \" clause naming that agent (e.g. \"In ${sourceConnector}, use the search tool with a repository path.\").`\n : \"\",\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 signal,\n },\n );\n throwIfExtractionAborted(signal);\n if (localResponse?.content) {\n const parsed = this.parseProactiveExtractionResultFromText(localResponse.content.trim());\n if (parsed) {\n return parsed;\n }\n }\n if (!this.config.localLlmFallback) {\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n } catch (err) {\n if (signal?.aborted || !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 signal,\n }),\n );\n if (!fallbackResult) {\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n return this.normalizeExtractionResultPayload({\n ...fallbackResult,\n questions: [],\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 structuredSections: entity.structuredSections\n ? entity.structuredSections.map((section) => ({\n ...section,\n facts: [...section.facts],\n }))\n : undefined,\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 const nextSections = new Map(\n (existing.structuredSections ?? []).map((section) => [section.key, {\n ...section,\n facts: [...section.facts],\n }]),\n );\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 for (const section of entity.structuredSections ?? []) {\n const existingSection = nextSections.get(section.key);\n if (!existingSection) {\n nextSections.set(section.key, {\n key: section.key,\n title: section.title,\n facts: [...section.facts],\n });\n changed = true;\n continue;\n }\n const nextSectionFacts = new Set(existingSection.facts.map((fact) => fact.trim()));\n for (const fact of section.facts) {\n const trimmed = fact.trim();\n if (!trimmed || nextSectionFacts.has(trimmed)) continue;\n nextSectionFacts.add(trimmed);\n changed = true;\n }\n existingSection.facts = Array.from(nextSectionFacts);\n }\n if (changed) {\n mergedEntities[existingIndex] = {\n ...existing,\n facts: Array.from(nextFacts),\n structuredSections: Array.from(nextSections.values()),\n source: \"proactive\",\n promptedByQuestion: existing.promptedByQuestion ?? entity.promptedByQuestion,\n };\n remainingBudget -= 1;\n }\n continue;\n }\n mergedEntities.push({\n ...entity,\n source: \"proactive\",\n structuredSections: entity.structuredSections\n ? entity.structuredSections.map((section) => ({\n ...section,\n facts: [...section.facts],\n }))\n : undefined,\n });\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 (\"modelUsed\" in detailed) {\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 /**\n * The one funnel every successful extraction path returns through — local\n * LLM, direct client, and gateway fallback alike. The ambient clamp lives\n * here so a new path cannot bypass it (issue #2294).\n */\n private finalizeExtractionResult(\n result: ExtractionResult,\n turns: ReadonlyArray<{\n content: string;\n sessionKey?: string;\n logicalSessionKey?: string;\n timestamp: string;\n turnFingerprint?: string;\n }>,\n sourceConnector?: string,\n ambientCapture = false,\n ): ExtractionResult {\n const clamped = ambientCapture ? clampAmbientCaptureConfidence(result) : result;\n const provenanced = attachExtractionProvenance(clamped, turns, this.config.provenance);\n return sourceConnector === undefined ? provenanced : { ...provenanced, sourceConnector };\n }\n\n async extract(\n turns: BufferTurn[],\n existingEntities?: string[],\n signal?: AbortSignal,\n ): Promise<ExtractionResult> {\n const lifecycleCaps = resolveMemoryLifecycleCapabilities(this.config);\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 // One derivation, over the turns the model actually sees (boundedTurns) —\n // the same set the qualifier, grounding source, and telemetry filter\n // operate on. result.sourceConnector carries it to persistence so the\n // orchestrator does not recompute over a different turn set (#2183).\n const resolvedConnector = resolveSourceConnector(boundedTurns);\n // Ambient-capture provenance (issue #2294): true when any contributing turn\n // came from an always-on recorder, so the prompt warns about media audio\n // and the finalize chokepoint clamps high-impact personal facts.\n const ambientCapture = boundedTurns.some(\n (turn) => turn.ambientCapture === true && turn.extractionContextOnly !== true,\n );\n // The header and qualifier strip/restore are gated on the scope-classification\n // capability; persistence records resolvedConnector regardless (trusted metadata).\n const sourceConnector = lifecycleCaps.extractionScopeClassification\n ? resolvedConnector\n : undefined;\n const { conversation, renderedConversation } = renderExtractionConversation(boundedTurns, headerConnector(sourceConnector));\n\n const groundingSource = boundedTurns\n .map((turn) => turn.content)\n .join(\"\\n\\n\");\n const assertionSource = boundedTurns\n .filter((turn) => turn.extractionContextOnly !== true)\n .map((turn) => turn.content)\n .join(\"\\n\\n\");\n const roleAssertionSources: ExtractionGroundingRoleSources = {\n profile: boundedTurns\n .filter((turn) => turn.role === \"user\" && turn.extractionContextOnly !== true)\n .map((turn) => turn.content)\n .join(\"\\n\\n\"),\n identity: boundedTurns\n .filter((turn) => turn.role === \"assistant\" && turn.extractionContextOnly !== true)\n .map((turn) => turn.content)\n .join(\"\\n\\n\"),\n };\n if (renderedConversation.trim().length === 0) {\n log.debug(\"extraction skipped — conversation only contained non-memory work-layer context\");\n return {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionSkippedReason: \"conversation_only_non_memory\",\n };\n }\n if (\n lifecycleCaps.extractionTelemetryPrefilter &&\n looksLikeMechanicalTelemetryTranscript(renderedConversation)\n ) {\n log.debug(\"extraction skipped — mechanical action/state telemetry without durable-memory cues\");\n return {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionSkippedReason: \"mechanical_telemetry\",\n };\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 const groundingContext: ExtractionGroundingContext = {\n groundingSource,\n assertionSource,\n roleAssertionSources,\n messageTimestamp,\n sourceConnector,\n ambientCapture,\n scopeClassificationEnabled: lifecycleCaps.extractionScopeClassification,\n };\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: resolveLocalLlmCapabilities(this.config).localLlm,\n });\n this.profiler.startSpan(\"total\", extractionTraceId);\n // True when a local or direct extractor was attempted before the gateway\n // fallback, so a gateway \"no models\" result doesn't re-classify a real\n // primary failure as auth_config (codex review: preserve direct/local failures).\n let primaryExtractorAttempted = false;\n\n try {\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n this.profiler.startSpan(\"local-llm\", extractionTraceId);\n primaryExtractorAttempted = true;\n try {\n const localResult = await this.extractWithLocalLlm(conversation, existingEntities, signal, ambientCapture);\n throwIfExtractionAborted(signal);\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 const grounded = applyGroundingWithConnector(this.config, sanitized, groundingContext);\n const finalResult = await this.applyProactiveQuestionPass(conversation, grounded, groundingContext, signal);\n return this.finalizeExtractionResult(finalResult, boundedTurns, resolvedConnector, ambientCapture);\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 {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionFailure: \"local_llm_unavailable\",\n extractionFailureClass: \"provider_retryable\",\n };\n }\n log.info(\"extraction: local LLM unavailable, falling back to gateway default AI\");\n } catch (err) {\n if (signal?.aborted) throw err;\n if (!this.config.localLlmFallback) {\n log.warn(\"extraction: local LLM error and fallback disabled:\", err);\n return {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionFailure: \"local_llm_error\",\n extractionFailureClass: \"provider_retryable\",\n };\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 primaryExtractorAttempted = true;\n try {\n const directResult = await this.extractWithDirectClient(conversation, existingEntities, signal, ambientCapture);\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 const grounded = applyGroundingWithConnector(this.config, sanitized, groundingContext);\n const finalResult = await this.applyProactiveQuestionPass(conversation, grounded, groundingContext, signal);\n return this.finalizeExtractionResult(finalResult, boundedTurns, resolvedConnector, ambientCapture);\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 if (signal?.aborted) throw 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.taskModelChain ? \" (taskModelChain)\" :\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: buildExtractionInstructions(this.config, existingEntities, ambientCapture) },\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({\n temperature: 0.3,\n maxTokens: this.config.extractionMaxOutputTokens,\n timeoutMs: this.config.localLlmTimeoutMs,\n signal,\n }),\n );\n\n const fallbackDurationMs = Date.now() - fallbackStartTime;\n\n if (\"modelUsed\" in detailed && 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 normalized = this.normalizeExtractionResultPayload(result);\n const sanitized = this.sanitizeExtractionResult(normalized, messageTimestamp);\n const grounded = applyGroundingWithConnector(this.config, sanitized, groundingContext);\n const finalResult = await this.applyProactiveQuestionPass(conversation, grounded, groundingContext, signal);\n return this.finalizeExtractionResult(finalResult, boundedTurns, resolvedConnector, ambientCapture);\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 const fallbackParseFailureClass: ExtractionFailureClass =\n detailed.result === null\n ? detailed.failureReason === \"no_models\" && primaryExtractorAttempted\n ? // Gateway had no models, but a local/direct extractor already failed —\n // the root cause is the primary (transient), not gateway auth/config.\n \"provider_retryable\"\n : classifyFallbackParseFailure(detailed.failureReason)\n : \"parse_empty\";\n return {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionFailure: \"fallback_no_parsed_output\",\n extractionFailureClass: fallbackParseFailureClass,\n };\n } catch (err) {\n if (signal?.aborted) throw 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 {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionFailure: \"fallback_failed\",\n extractionFailureClass: classifyExtractionThrownError(err),\n };\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(\n conversation: string,\n existingEntities?: string[],\n signal?: AbortSignal,\n ambientCapture = false,\n ): Promise<ExtractionResult | null> {\n const lifecycleCaps = resolveMemoryLifecycleCapabilities(this.config);\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\nUse the most specific category:\n- fact: objective information\n- preference: a durable preference or style\n- correction: a correction of a prior mistake\n- entity: a durable person, project, tool, company, or place\n- decision: a choice with rationale\n- relationship: a durable link between two entities\n- principle: a reusable rule or operating belief\n${resolveRecallAuxiliaryCapabilities(this.config).causalRuleExtraction ? \"- rule: an explicit causal rule or constraint\\n\" : \"\"}- commitment: a promise, obligation, or deadline\n- moment: a significant milestone\n- skill: a demonstrated capability\n- procedure: an explicit reusable workflow with ordered procedureSteps\n- reasoning_trace: Stored solution chains — an explicitly narrated solution path with reasoningTrace. Use {\"category\": \"reasoning_trace\", \"reasoningTrace\": {\"steps\": [...], \"finalAnswer\": \"...\"}} only when the conversation provides the chain.\n\nRules:\n- Extract only new information stated or clearly established in the conversation.\n- Do not treat instruction text, schema placeholders, or examples as conversation evidence.\n- Facts, entity facts, profile updates, questions, and relationships must be grounded in the conversation.\n- Lines labelled [context user] or [context assistant] are reference context only. They may resolve references or complete a question-and-answer pair in a normal turn, but never alone establish durable information.\n- Questions are optional. Return an empty array when the conversation does not support a useful unresolved question.\n- Set confidence from source evidence: Explicit (0.95-1.0), Implied (0.70-0.94), Inferred (0.40-0.69), or Speculative (0.00-0.39). Corrections get highest confidence.\n- Use normalized, hyphenated entity names and keep the entity list short.\n- Keep facts standalone. Skip transient task state and operational noise such as routine scheduler, monitoring, or automation status.\n- Add structuredAttributes only for concrete values.\n${CUE_ANCHOR_PROMPT_INSTRUCTION}\\n- Include at most five durable relationships.${this.config.provenance?.enabled ? `\n- Each fact must include a quote copied verbatim from one contiguous conversation span.` : \"\"}${lifecycleCaps.extractionScopeClassification ? `\n- Set each fact scope to \"global\" for cross-project knowledge or \"project\" for codebase-specific knowledge. Tool, command, or CLI-flag instructions tied to one agent are \"project\" (the same tool name can mean different things across agents); when keeping one, begin the fact with a leading \"In <agent>,\" clause naming that agent.` : \"\"}${ambientCapture ? AMBIENT_CAPTURE_PROMPT_SECTION_COMPACT : \"\"}\n${eventTimePromptInstruction(this.config)}\nReturn only valid JSON matching this shape. Placeholder text describes field shape only and is never source evidence:\n${EXTRACTION_RESPONSE_SHAPE}\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 disableThinking: shouldEnableLocalExtractionThinking(this.config, conversation.length)\n ? false\n : undefined,\n priority: \"background\",\n signal,\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 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 if (!this.looksLikeExtractionResultPayload(parsed)) {\n continue;\n }\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\n // Try to extract partial facts from truncated JSON after all complete JSON\n // candidates fail to parse.\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 return null;\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 signal?: AbortSignal,\n ambientCapture = false,\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 {\n model: this.config.model,\n messages: [\n {\n role: \"system\",\n content:\n buildExtractionInstructions(this.config, existingEntities, ambientCapture) +\n `\\n\\nReturn only valid JSON matching this shape. Placeholder text describes field shape only and is never source evidence:\\n${EXTRACTION_RESPONSE_SHAPE}`,\n },\n { role: \"user\", content: conversation },\n ],\n ...tokenParams,\n },\n signal ? { signal } : undefined,\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\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 category = match[1]?.trim() ?? \"\";\n if (!isMemoryCategory(category)) continue;\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 type = extractionEntityType(match[2]);\n if (type === undefined) continue;\n entities.push({\n name: match[1],\n type,\n facts: [],\n });\n }\n } catch {\n // Ignore regex errors\n }\n\n return this.normalizeExtractionResultPayload({ facts, entities, profileUpdates: [], questions: [] });\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${resolveRecallAuxiliaryCapabilities(this.config).causalRuleExtraction ? `\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 return this.sanitizeConsolidationResult({\n items: fallbackResult.items,\n profileUpdates: fallbackResult.profileUpdates,\n entityUpdates: fallbackResult.entityUpdates,\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 instructionText = `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${resolveRecallAuxiliaryCapabilities(this.config).causalRuleExtraction ? `\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${CONSOLIDATION_RESPONSE_SCHEMA}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\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 log.debug(\n `consolidation: ${parsed.items.length} decisions`,\n );\n return this.sanitizeConsolidationResult({\n items: parsed.items,\n profileUpdates: Array.isArray(parsed.profileUpdates) ? parsed.profileUpdates : [],\n entityUpdates: Array.isArray(parsed.entityUpdates) ? parsed.entityUpdates : [],\n });\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${resolveRecallAuxiliaryCapabilities(this.config).causalRuleExtraction ? `\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${CONSOLIDATION_RESPONSE_SCHEMA}`;\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 instructionText = `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: instructionText },\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 instructionText = `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: instructionText },\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 instructionText = `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: instructionText },\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: instructionText },\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: instructionText },\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 async revalidateDependents(\n superseded: { id: string; content: string },\n replacement: { id: string; content: string } | null,\n dependents: Array<{ id: string; category: string; content: string }>,\n signal?: AbortSignal,\n ): Promise<{\n verdicts: Array<{\n memoryId: string;\n verdict: \"still_valid\" | \"invalidated\" | \"uncertain\";\n reason?: string;\n }>;\n }> {\n const complete: RevalidationFastChatCompletion = async (messages, options) => {\n try {\n const fast = await this.fastChatCompletion?.(messages, options);\n if (fast) return fast;\n } catch (error) {\n if (isAbortError(error) || options.signal?.aborted) throw error;\n log.warn(`dependency revalidation fast route failed: ${error}`);\n }\n if (this.shouldUseLocalLlm) {\n try {\n const local = await this.localLlm.chatCompletion(messages, options);\n if (local || !this.config.localLlmFallback) return local;\n } catch (error) {\n if (!this.config.localLlmFallback) throw error;\n }\n }\n if (!this.shouldUseDirectClient) {\n return this.fallbackLlm.chatCompletion(messages, this.withGatewayAgent(options));\n }\n const client = this.client;\n if (!client) return null;\n if (!shouldAssumeOpenAiChatCompletions(client.baseURL ?? this.config.openaiBaseUrl)) {\n const response = await client.chat.completions.create(\n {\n model: this.config.model,\n messages,\n max_tokens: options.maxTokens,\n },\n { signal: options.signal },\n );\n const content = response.choices[0]?.message?.content;\n return typeof content === \"string\" ? { content } : null;\n }\n const response = await client.responses.create({\n model: this.config.model,\n instructions: messages.find((message) => message.role === \"system\")?.content,\n input: messages.filter((message) => message.role !== \"system\").map((message) => message.content).join(\"\\n\\n\"),\n max_output_tokens: options.maxTokens,\n }, { signal: options.signal });\n return typeof response.output_text === \"string\" ? { content: response.output_text } : null;\n };\n return revalidateDependentsViaLlm(\n { fastChatCompletion: complete, parseJsonObject: this.parseJsonObject },\n superseded,\n replacement,\n dependents,\n { signal, timeoutMs: this.config.dependencyPropagation.timeoutMs },\n );\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 instructionText = `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: instructionText },\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: instructionText },\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: instructionText },\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 (!resolveRecallAuxiliaryCapabilities(this.config).daySummary) {\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 instructionText = await loadDaySummaryPrompt();\n\n // Append extension footer when extensions are active (#382)\n let extensionsFooter = \"\";\n try {\n extensionsFooter = await buildExtensionsFooterForSummary(this.config);\n } catch {\n // Non-fatal: skip extension footer if discovery fails\n }\n\n const userPrompt = `Generate an end-of-day summary from this Remnic memory context:\n\n${memoryContext}${extensionsFooter.length > 0 ? `\\n\\n${extensionsFooter}` : \"\"}`;\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: `${instructionText}\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: `${instructionText}\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: `${instructionText}\\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 instructionText = `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: instructionText },\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: instructionText },\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: instructionText },\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","/**\n * LLM revalidation of dependent memories after a support link breaks.\n *\n * Extracted from ExtractionEngine to keep extraction.ts under its ratchet\n * ceiling. The ExtractionEngine.revalidateDependents method delegates here.\n */\n\nexport interface RevalidationVerdict {\n memoryId: string;\n verdict: \"still_valid\" | \"invalidated\" | \"uncertain\";\n reason?: string;\n}\n\nexport type RevalidationFastChatCompletion = (\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: {\n temperature?: number;\n maxTokens?: number;\n timeoutMs?: number;\n operation?: string;\n priority?: \"background\" | \"recall-critical\";\n signal?: AbortSignal;\n },\n) => Promise<{ content: string } | null>;\n\nexport interface RevalidationDeps {\n fastChatCompletion: RevalidationFastChatCompletion;\n parseJsonObject: (raw: string | null) => unknown;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction buildPrompt(\n superseded: { id: string; content: string },\n replacement: { id: string; content: string } | null,\n dependents: Array<{ id: string; category: string; content: string }>,\n): { input: string; instructionText: string } {\n const dependentPrompt = dependents\n .map(\n (memory, index) =>\n `[${index + 1}] id: ${memory.id} | category: ${memory.category}\\n${memory.content}`,\n )\n .join(\"\\n\\n\");\n const input = `SUPERSEDED MEMORY (id: ${superseded.id}):\n${superseded.content}\n\nREPLACEMENT (id: ${replacement?.id ?? \"none\"}):\n${replacement?.content ?? \"none — the memory was removed without replacement\"}\n\nDEPENDENTS TO REVALIDATE (return exactly one verdict per id):\n${dependentPrompt}`;\n const instructionText = `You revalidate dependent memory claims after a supporting memory changes.\nFor each requested memory, decide whether its claim still holds.\nReturn valid JSON only:\n{\"verdicts\":[{\"memoryId\":\"id\",\"verdict\":\"still_valid|invalidated|uncertain\",\"reason\":\"brief reason\"}]}\nNever invent memory IDs. Use \"uncertain\" when the evidence is insufficient.`;\n return { input, instructionText };\n}\n\nfunction normalizeVerdicts(\n parsed: unknown,\n dependents: Array<{ id: string }>,\n): RevalidationVerdict[] {\n const raw: unknown[] = isPlainRecord(parsed) && Array.isArray(parsed.verdicts) ? parsed.verdicts : [];\n const requested = new Set(dependents.map((memory) => memory.id));\n const seen = new Set<string>();\n const normalized: RevalidationVerdict[] = [];\n for (const candidate of raw) {\n if (!isPlainRecord(candidate)) continue;\n const memoryId = typeof candidate.memoryId === \"string\" ? candidate.memoryId.trim() : \"\";\n if (!requested.has(memoryId) || seen.has(memoryId)) continue;\n seen.add(memoryId);\n const verdict =\n candidate.verdict === \"still_valid\" ||\n candidate.verdict === \"invalidated\" ||\n candidate.verdict === \"uncertain\"\n ? candidate.verdict\n : \"uncertain\";\n normalized.push({\n memoryId,\n verdict,\n ...(typeof candidate.reason === \"string\" ? { reason: candidate.reason } : {}),\n });\n }\n return dependents.map((memory) => {\n const verdict = normalized.find((candidate) => candidate.memoryId === memory.id);\n return verdict ?? { memoryId: memory.id, verdict: \"uncertain\" as const };\n });\n}\n\nexport async function revalidateDependentsViaLlm(\n deps: RevalidationDeps,\n superseded: { id: string; content: string },\n replacement: { id: string; content: string } | null,\n dependents: Array<{ id: string; category: string; content: string }>,\n options: { signal?: AbortSignal; timeoutMs?: number } = {},\n): Promise<{ verdicts: RevalidationVerdict[] }> {\n const { input, instructionText } = buildPrompt(superseded, replacement, dependents);\n const maxTokens = Math.max(1024, dependents.length * 256);\n const response = await deps.fastChatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n {\n temperature: 0.2,\n maxTokens,\n operation: \"dependency_revalidation\",\n priority: \"background\",\n timeoutMs: options.timeoutMs,\n signal: options.signal,\n },\n );\n const rawContent = response?.content ?? null;\n if (!rawContent?.trim()) {\n throw new Error(\"fast completion returned no dependency revalidation output\");\n }\n\n return { verdicts: normalizeVerdicts(deps.parseJsonObject(rawContent), dependents) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,YAAY;;;AC8BnB,SAASA,eAAc,OAAkD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,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