@remnic/core 10.0.186 → 10.0.188
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.js +105 -104
- package/dist/access-audit.js +2 -2
- package/dist/access-cli.js +105 -104
- package/dist/access-cli.js.map +1 -1
- package/dist/access-coding-context-resolution.js +6 -6
- package/dist/access-extraction-force-flush-preempt.js +105 -104
- package/dist/access-extraction-force-flush.js +105 -104
- package/dist/access-http-briefing.js +105 -104
- package/dist/access-http-query.js +105 -104
- package/dist/access-http.js +105 -104
- package/dist/access-identity-continuity-surface.js +105 -104
- package/dist/access-lcm-surface.js +105 -104
- package/dist/access-mcp.js +105 -104
- package/dist/access-observe-write-category.js +6 -6
- package/dist/access-observe-write-surface.js +105 -104
- package/dist/access-offline-manifest.js +5 -5
- package/dist/access-operations-batch.js +105 -104
- package/dist/access-operations.js +105 -104
- package/dist/access-recall-concurrency.js +105 -104
- package/dist/access-recall-response.js +105 -104
- package/dist/access-recall-surface.js +105 -104
- package/dist/access-schema.js +5 -5
- package/dist/access-service.js +105 -104
- package/dist/active-recall.js +10 -10
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/{auto-sync-OOEY2FSA.js → auto-sync-BJUAGKI5.js} +4 -4
- package/dist/briefing.js +7 -7
- package/dist/buffer-add-turns-bounded.js +2 -2
- package/dist/buffer-admission-idempotency.d.ts.map +1 -1
- package/dist/buffer-admission-idempotency.js +1 -1
- package/dist/buffer-persistence.d.ts +14 -0
- package/dist/buffer-persistence.d.ts.map +1 -1
- package/dist/buffer-persistence.js +3 -1
- package/dist/buffer.js +9 -8
- package/dist/calibration.js +4 -4
- package/dist/causal-consolidation.js +8 -8
- package/dist/{chunk-XYZR3NBU.js → chunk-2I3ETW3G.js} +2 -2
- package/dist/{chunk-5RWIZISF.js → chunk-2VNMSEZR.js} +3 -3
- package/dist/{chunk-4TPU36X4.js → chunk-4N33L4HY.js} +2 -2
- package/dist/{chunk-BFPF5N3H.js → chunk-4RASUAN3.js} +4 -4
- package/dist/{chunk-N2PXVLV3.js → chunk-56BNHKZM.js} +7 -7
- package/dist/{chunk-R3UQIS3F.js → chunk-5AFBFAFX.js} +4 -4
- package/dist/{chunk-3FEQNKMB.js → chunk-5WDUY2ZZ.js} +2 -2
- package/dist/{chunk-5ITPOAKW.js → chunk-65DWWJKI.js} +2 -2
- package/dist/{chunk-O5ZCDK32.js → chunk-6AMFGXG2.js} +39 -11
- package/dist/chunk-6AMFGXG2.js.map +1 -0
- package/dist/{chunk-L4TYD52M.js → chunk-6MDHK6NO.js} +2 -2
- package/dist/{chunk-FYHFM64A.js → chunk-6OHCNTKU.js} +2 -2
- package/dist/{chunk-PY5XP7GR.js → chunk-6TIQLG7I.js} +2 -2
- package/dist/{chunk-A3HLZMHD.js → chunk-7KTORRIK.js} +2 -2
- package/dist/{chunk-ENKXMLE3.js → chunk-A32EBVCZ.js} +2 -2
- package/dist/{chunk-H4HBQRGI.js → chunk-ATPY63F5.js} +2 -2
- package/dist/{chunk-2LXROA34.js → chunk-AXSQGJSG.js} +2 -2
- package/dist/chunk-B256MMS7.js +205 -0
- package/dist/chunk-B256MMS7.js.map +1 -0
- package/dist/{chunk-VUC3DLQ5.js → chunk-C6Y2YHJL.js} +2 -2
- package/dist/{chunk-FBNR3JI5.js → chunk-CIAQK2OU.js} +7 -2
- package/dist/{chunk-FBNR3JI5.js.map → chunk-CIAQK2OU.js.map} +1 -1
- package/dist/{chunk-FDXLO6CX.js → chunk-CRS2NY44.js} +2 -2
- package/dist/{chunk-AJVCM2E3.js → chunk-CYX7JI4O.js} +2 -2
- package/dist/{chunk-JK5YFQQT.js → chunk-D3FP4JQI.js} +2 -2
- package/dist/{chunk-ZNHLUYIT.js → chunk-D7HOJFDS.js} +4 -4
- package/dist/{chunk-ZX5N5D6M.js → chunk-DAOMWGO2.js} +4 -4
- package/dist/{chunk-VN3RYYMS.js → chunk-DR4TYD56.js} +2 -2
- package/dist/{chunk-7DFJ4JX2.js → chunk-DTTDMK7Q.js} +7 -7
- package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
- package/dist/{chunk-QJBULLKG.js → chunk-F2MVWUNF.js} +2 -2
- package/dist/{chunk-TQXKUQFX.js → chunk-FZU62GIV.js} +7 -6
- package/dist/chunk-FZU62GIV.js.map +1 -0
- package/dist/{chunk-BAMF6J4W.js → chunk-GCHM5BYL.js} +4 -4
- package/dist/{chunk-6SROXED4.js → chunk-GRX5BE73.js} +2 -2
- package/dist/{chunk-TKWIUL3D.js → chunk-H442UKDV.js} +8 -8
- package/dist/{chunk-VFJ3PBZI.js → chunk-HL53XYHC.js} +4 -4
- package/dist/{chunk-CKTKATXL.js → chunk-IMSLPQJB.js} +20 -16
- package/dist/chunk-IMSLPQJB.js.map +1 -0
- package/dist/{chunk-63FIQIER.js → chunk-JJ42IDJU.js} +2 -2
- package/dist/{chunk-N33M4NWM.js → chunk-K3JGILZC.js} +3 -3
- package/dist/{chunk-CJERJ724.js → chunk-K6BS5RB4.js} +2 -2
- package/dist/{chunk-VAQIBC2L.js → chunk-KQIOW3TG.js} +2 -2
- package/dist/{chunk-UMGO4LEZ.js → chunk-KVTUUU7H.js} +2 -2
- package/dist/{chunk-TRFSTCQK.js → chunk-LL6WEMTC.js} +34 -6
- package/dist/chunk-LL6WEMTC.js.map +1 -0
- package/dist/{chunk-LALPM2DN.js → chunk-MTKSH7HY.js} +143 -139
- package/dist/chunk-MTKSH7HY.js.map +1 -0
- package/dist/{chunk-IK7NPYYU.js → chunk-NFQKIZK3.js} +2 -2
- package/dist/{chunk-2WITFW6F.js → chunk-NKHRIDYP.js} +2 -2
- package/dist/{chunk-KYZMCH4I.js → chunk-NN3LMWKA.js} +12 -4
- package/dist/chunk-NN3LMWKA.js.map +1 -0
- package/dist/{chunk-RXAWE76Y.js → chunk-O6QSBI3U.js} +2 -2
- package/dist/{chunk-5RBHL5TF.js → chunk-OA7YDB6A.js} +2 -2
- package/dist/{chunk-SSKIXUR5.js → chunk-PCGBESAN.js} +2 -2
- package/dist/{chunk-DYZDFOBX.js → chunk-Q6S67LHR.js} +2 -2
- package/dist/{chunk-WCXWCAUC.js → chunk-QGT5KNQT.js} +2 -2
- package/dist/{chunk-KYPFQO43.js → chunk-QPD7EYGI.js} +2 -2
- package/dist/{chunk-4KUK3KGI.js → chunk-QXHWOUS6.js} +3 -3
- package/dist/{chunk-FE43YKNJ.js → chunk-RBPC4XGU.js} +31 -8
- package/dist/chunk-RBPC4XGU.js.map +1 -0
- package/dist/{chunk-CXGD3N2Y.js → chunk-RPOG6HLI.js} +2 -2
- package/dist/{chunk-3N7I53KR.js → chunk-RVODERA5.js} +2 -2
- package/dist/{chunk-G6V32Q4F.js → chunk-SFWQZBPN.js} +2 -2
- package/dist/{chunk-DNXQVCIC.js → chunk-SUI75NTN.js} +8 -8
- package/dist/{chunk-3GD5SFDT.js → chunk-T3XOP7TA.js} +5 -5
- package/dist/{chunk-FDLPNFKE.js → chunk-T7R42MWB.js} +2 -2
- package/dist/{chunk-5BESLEU7.js → chunk-TAPF7T26.js} +2 -2
- package/dist/chunk-TK6EBBKG.js +13 -0
- package/dist/chunk-TK6EBBKG.js.map +1 -0
- package/dist/{chunk-PZ4OA7CP.js → chunk-TQODBIMW.js} +2 -2
- package/dist/{chunk-PDXO4LIH.js → chunk-UWKHLWUE.js} +13 -9
- package/dist/chunk-UWKHLWUE.js.map +1 -0
- package/dist/{chunk-QJG6PEAM.js → chunk-VQQZJ6KJ.js} +3 -3
- package/dist/{chunk-CIC3WZVO.js → chunk-X3ERYOLO.js} +2 -2
- package/dist/{chunk-T4MKFTJF.js → chunk-XHDS6HIX.js} +5 -5
- package/dist/{chunk-J7BAJ6BF.js → chunk-XQF2KLV5.js} +2 -2
- package/dist/{chunk-U7VEZ2XS.js → chunk-XWPYK5T4.js} +2 -2
- package/dist/{chunk-L7MVHAMS.js → chunk-YVXR7CPS.js} +2 -2
- package/dist/{chunk-NU5JRN3A.js → chunk-ZDLVHGIC.js} +2 -2
- package/dist/{chunk-OJXK5C6Z.js → chunk-ZG4GNPRE.js} +7 -7
- package/dist/{chunk-IJKO5RVJ.js → chunk-ZNYDDZVW.js} +3 -3
- package/dist/cli.js +105 -104
- package/dist/coding/export-okf-codegraph.js +13 -13
- package/dist/compounding/engine.js +8 -8
- package/dist/config.js +10 -10
- package/dist/connectors/codex-materialize-runner.js +7 -7
- package/dist/connectors/index.js +7 -7
- package/dist/convergence-refresh.js +9 -9
- package/dist/corpus-watermark.js +9 -9
- package/dist/dashboard-runtime.js +2 -2
- package/dist/deep-recall-http-glue.js +6 -6
- package/dist/deep-recall.js +2 -2
- package/dist/entity-retrieval.js +7 -7
- package/dist/explicit-capture.js +105 -104
- package/dist/extraction-entities-source.d.ts +11 -0
- package/dist/extraction-entities-source.d.ts.map +1 -0
- package/dist/extraction-entities-source.js +8 -0
- package/dist/extraction-entities-source.js.map +1 -0
- package/dist/extraction-judge.js +2 -2
- package/dist/extraction-normalization.js +2 -2
- package/dist/extraction-prompt.d.ts +19 -2
- package/dist/extraction-prompt.d.ts.map +1 -1
- package/dist/extraction-prompt.js +5 -1
- package/dist/extraction.d.ts +2 -1
- package/dist/extraction.d.ts.map +1 -1
- package/dist/extraction.js +18 -17
- package/dist/{first-start-migration-TCPK2I7J.js → first-start-migration-CCZ5SM3V.js} +4 -4
- package/dist/harmonic-retrieval.js +7 -7
- package/dist/index.js +125 -124
- package/dist/lcm/engine.js +3 -3
- package/dist/lcm/index.js +8 -8
- package/dist/local-llm-helpers.d.ts.map +1 -1
- package/dist/local-llm-helpers.js +2 -2
- package/dist/local-llm-transport.d.ts +82 -9
- package/dist/local-llm-transport.d.ts.map +1 -1
- package/dist/local-llm-transport.js +11 -3
- package/dist/local-llm.d.ts.map +1 -1
- package/dist/local-llm.js +3 -3
- package/dist/location/index.js +8 -8
- package/dist/maintenance/memory-governance.js +7 -7
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -7
- package/dist/maintenance/rebuild-memory-projection-runner.js +9 -9
- package/dist/maintenance/rebuild-memory-projection.js +8 -8
- package/dist/memory-browse.js +5 -5
- package/dist/namespaces/migrate.js +8 -8
- package/dist/namespaces/search.js +4 -4
- package/dist/namespaces/storage.js +7 -7
- package/dist/offline-sync-changeset-generations.js +3 -3
- package/dist/offline-sync-embedding-generation.js +2 -2
- package/dist/offline-sync-snapshot-stream.js +5 -5
- package/dist/offline-sync.js +6 -6
- package/dist/operator-doctor-corpus.js +10 -10
- package/dist/operator-toolkit.js +17 -17
- package/dist/orchestration/backlog-scheduler.js +106 -105
- package/dist/orchestration/backlog-scheduler.js.map +1 -1
- package/dist/orchestration/buffer-drain-runner.js +106 -105
- package/dist/orchestration/extraction-queue-coordinator.d.ts.map +1 -1
- package/dist/orchestration/extraction-run-helpers.d.ts +2 -1
- package/dist/orchestration/extraction-run-helpers.d.ts.map +1 -1
- package/dist/orchestration/extraction-run.d.ts.map +1 -1
- package/dist/orchestration/maintenance.js +18 -18
- package/dist/orchestrator.js +107 -106
- package/dist/qmd.js +2 -2
- package/dist/recall-navigation.js +105 -104
- package/dist/recall-state-view-admission.js +5 -5
- package/dist/recall-why-service.js +5 -5
- package/dist/resume-bundles.js +13 -13
- package/dist/search/factory.js +3 -3
- package/dist/search/index.js +3 -3
- package/dist/semantic-consolidation.js +8 -8
- package/dist/semantic-rule-promotion.js +7 -7
- package/dist/semantic-rule-verifier.js +7 -7
- package/dist/source-agent-qualifier.js +11 -10
- package/dist/standup/build.js +7 -7
- package/dist/storage/entity-canonical-id-migration-runner.d.ts.map +1 -1
- package/dist/storage.js +6 -6
- package/dist/summarizer.js +4 -4
- package/dist/support-passport/index.js +4 -4
- package/dist/transcript.js +2 -2
- package/dist/transfer/export-okf.js +7 -7
- package/dist/verified-recall.js +7 -7
- package/dist/who-knows-cli.js +8 -8
- package/dist/who-knows.js +7 -7
- package/package.json +2 -2
- package/src/buffer-admission-idempotency.test.ts +115 -0
- package/src/buffer-admission-idempotency.ts +67 -11
- package/src/buffer-persistence.ts +46 -5
- package/src/extraction-carry-forward.test.ts +147 -0
- package/src/extraction-entities-source.ts +19 -0
- package/src/extraction-prompt.ts +60 -9
- package/src/extraction.ts +11 -8
- package/src/local-llm-headers-timeout.test.ts +246 -16
- package/src/local-llm-helpers.ts +14 -4
- package/src/local-llm-transport.ts +253 -16
- package/src/local-llm.ts +7 -8
- package/src/orchestration/extraction-queue-coordinator.ts +7 -1
- package/src/orchestration/extraction-queue-lane-bias.test.ts +35 -0
- package/src/orchestration/extraction-run-helpers.ts +11 -4
- package/src/orchestration/extraction-run.test.ts +23 -12
- package/src/orchestration/extraction-run.ts +6 -5
- package/src/storage/entity-canonical-id-migration-runner.test.ts +90 -0
- package/src/storage/entity-canonical-id-migration-runner.ts +10 -0
- package/dist/chunk-5YQXWVCP.js +0 -74
- package/dist/chunk-5YQXWVCP.js.map +0 -1
- package/dist/chunk-CKTKATXL.js.map +0 -1
- package/dist/chunk-FE43YKNJ.js.map +0 -1
- package/dist/chunk-KYZMCH4I.js.map +0 -1
- package/dist/chunk-LALPM2DN.js.map +0 -1
- package/dist/chunk-O5ZCDK32.js.map +0 -1
- package/dist/chunk-PDXO4LIH.js.map +0 -1
- package/dist/chunk-TQXKUQFX.js.map +0 -1
- package/dist/chunk-TRFSTCQK.js.map +0 -1
- /package/dist/{auto-sync-OOEY2FSA.js.map → auto-sync-BJUAGKI5.js.map} +0 -0
- /package/dist/{chunk-XYZR3NBU.js.map → chunk-2I3ETW3G.js.map} +0 -0
- /package/dist/{chunk-5RWIZISF.js.map → chunk-2VNMSEZR.js.map} +0 -0
- /package/dist/{chunk-4TPU36X4.js.map → chunk-4N33L4HY.js.map} +0 -0
- /package/dist/{chunk-BFPF5N3H.js.map → chunk-4RASUAN3.js.map} +0 -0
- /package/dist/{chunk-N2PXVLV3.js.map → chunk-56BNHKZM.js.map} +0 -0
- /package/dist/{chunk-R3UQIS3F.js.map → chunk-5AFBFAFX.js.map} +0 -0
- /package/dist/{chunk-3FEQNKMB.js.map → chunk-5WDUY2ZZ.js.map} +0 -0
- /package/dist/{chunk-5ITPOAKW.js.map → chunk-65DWWJKI.js.map} +0 -0
- /package/dist/{chunk-L4TYD52M.js.map → chunk-6MDHK6NO.js.map} +0 -0
- /package/dist/{chunk-FYHFM64A.js.map → chunk-6OHCNTKU.js.map} +0 -0
- /package/dist/{chunk-PY5XP7GR.js.map → chunk-6TIQLG7I.js.map} +0 -0
- /package/dist/{chunk-A3HLZMHD.js.map → chunk-7KTORRIK.js.map} +0 -0
- /package/dist/{chunk-ENKXMLE3.js.map → chunk-A32EBVCZ.js.map} +0 -0
- /package/dist/{chunk-H4HBQRGI.js.map → chunk-ATPY63F5.js.map} +0 -0
- /package/dist/{chunk-2LXROA34.js.map → chunk-AXSQGJSG.js.map} +0 -0
- /package/dist/{chunk-VUC3DLQ5.js.map → chunk-C6Y2YHJL.js.map} +0 -0
- /package/dist/{chunk-FDXLO6CX.js.map → chunk-CRS2NY44.js.map} +0 -0
- /package/dist/{chunk-AJVCM2E3.js.map → chunk-CYX7JI4O.js.map} +0 -0
- /package/dist/{chunk-JK5YFQQT.js.map → chunk-D3FP4JQI.js.map} +0 -0
- /package/dist/{chunk-ZNHLUYIT.js.map → chunk-D7HOJFDS.js.map} +0 -0
- /package/dist/{chunk-ZX5N5D6M.js.map → chunk-DAOMWGO2.js.map} +0 -0
- /package/dist/{chunk-VN3RYYMS.js.map → chunk-DR4TYD56.js.map} +0 -0
- /package/dist/{chunk-7DFJ4JX2.js.map → chunk-DTTDMK7Q.js.map} +0 -0
- /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
- /package/dist/{chunk-QJBULLKG.js.map → chunk-F2MVWUNF.js.map} +0 -0
- /package/dist/{chunk-BAMF6J4W.js.map → chunk-GCHM5BYL.js.map} +0 -0
- /package/dist/{chunk-6SROXED4.js.map → chunk-GRX5BE73.js.map} +0 -0
- /package/dist/{chunk-TKWIUL3D.js.map → chunk-H442UKDV.js.map} +0 -0
- /package/dist/{chunk-VFJ3PBZI.js.map → chunk-HL53XYHC.js.map} +0 -0
- /package/dist/{chunk-63FIQIER.js.map → chunk-JJ42IDJU.js.map} +0 -0
- /package/dist/{chunk-N33M4NWM.js.map → chunk-K3JGILZC.js.map} +0 -0
- /package/dist/{chunk-CJERJ724.js.map → chunk-K6BS5RB4.js.map} +0 -0
- /package/dist/{chunk-VAQIBC2L.js.map → chunk-KQIOW3TG.js.map} +0 -0
- /package/dist/{chunk-UMGO4LEZ.js.map → chunk-KVTUUU7H.js.map} +0 -0
- /package/dist/{chunk-IK7NPYYU.js.map → chunk-NFQKIZK3.js.map} +0 -0
- /package/dist/{chunk-2WITFW6F.js.map → chunk-NKHRIDYP.js.map} +0 -0
- /package/dist/{chunk-RXAWE76Y.js.map → chunk-O6QSBI3U.js.map} +0 -0
- /package/dist/{chunk-5RBHL5TF.js.map → chunk-OA7YDB6A.js.map} +0 -0
- /package/dist/{chunk-SSKIXUR5.js.map → chunk-PCGBESAN.js.map} +0 -0
- /package/dist/{chunk-DYZDFOBX.js.map → chunk-Q6S67LHR.js.map} +0 -0
- /package/dist/{chunk-WCXWCAUC.js.map → chunk-QGT5KNQT.js.map} +0 -0
- /package/dist/{chunk-KYPFQO43.js.map → chunk-QPD7EYGI.js.map} +0 -0
- /package/dist/{chunk-4KUK3KGI.js.map → chunk-QXHWOUS6.js.map} +0 -0
- /package/dist/{chunk-CXGD3N2Y.js.map → chunk-RPOG6HLI.js.map} +0 -0
- /package/dist/{chunk-3N7I53KR.js.map → chunk-RVODERA5.js.map} +0 -0
- /package/dist/{chunk-G6V32Q4F.js.map → chunk-SFWQZBPN.js.map} +0 -0
- /package/dist/{chunk-DNXQVCIC.js.map → chunk-SUI75NTN.js.map} +0 -0
- /package/dist/{chunk-3GD5SFDT.js.map → chunk-T3XOP7TA.js.map} +0 -0
- /package/dist/{chunk-FDLPNFKE.js.map → chunk-T7R42MWB.js.map} +0 -0
- /package/dist/{chunk-5BESLEU7.js.map → chunk-TAPF7T26.js.map} +0 -0
- /package/dist/{chunk-PZ4OA7CP.js.map → chunk-TQODBIMW.js.map} +0 -0
- /package/dist/{chunk-QJG6PEAM.js.map → chunk-VQQZJ6KJ.js.map} +0 -0
- /package/dist/{chunk-CIC3WZVO.js.map → chunk-X3ERYOLO.js.map} +0 -0
- /package/dist/{chunk-T4MKFTJF.js.map → chunk-XHDS6HIX.js.map} +0 -0
- /package/dist/{chunk-J7BAJ6BF.js.map → chunk-XQF2KLV5.js.map} +0 -0
- /package/dist/{chunk-U7VEZ2XS.js.map → chunk-XWPYK5T4.js.map} +0 -0
- /package/dist/{chunk-L7MVHAMS.js.map → chunk-YVXR7CPS.js.map} +0 -0
- /package/dist/{chunk-NU5JRN3A.js.map → chunk-ZDLVHGIC.js.map} +0 -0
- /package/dist/{chunk-OJXK5C6Z.js.map → chunk-ZG4GNPRE.js.map} +0 -0
- /package/dist/{chunk-IJKO5RVJ.js.map → chunk-ZNYDDZVW.js.map} +0 -0
- /package/dist/{first-start-migration-TCPK2I7J.js.map → first-start-migration-CCZ5SM3V.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/buffer-admission-idempotency.ts"],"sourcesContent":["/** Fields on {@link BufferState} used by observe-buffer idempotency (#3368). */\nexport interface BufferAdmissionIdempotencyState {\n admissionIdempotency?: Record<string, number>;\n admissionIdempotencyOrder?: string[];\n}\n\n/**\n * FIFO bound on recorded observe-buffer admission keys per session buffer.\n * 4096 retains the most recent keys per session — roughly two\n * hours at typical capture load. A replay of more than 4096 keys for one\n * session still evicts its oldest keys, so a complete 5000-entry outbox\n * replay for a single hot session is not guaranteed; the previous\n * 512-entry ring only covered about fifteen minutes, so any drain outage\n * longer than that made duplicate captures likely once replay caught up.\n */\nexport const BUFFER_ADMISSION_IDEMPOTENCY_CAP = 4096;\n\n/** Client observe idempotency keys are namespaced by durable capture scope. */\nexport function scopeObserveBufferAdmissionIdempotencyKey(input: {\n sessionKey: string;\n writeNamespace: string;\n principal?: string;\n clientKey: string;\n}): string {\n const principal = input.principal?.trim() ?? \"\";\n const client = input.clientKey.trim();\n return `obs\\u001f${input.writeNamespace}\\u001f${principal}\\u001f${input.sessionKey}\\u001e${client}`;\n}\n\nexport function ensureAdmissionIdempotencyMap(state: BufferAdmissionIdempotencyState): Record<string, number> {\n const existing = state.admissionIdempotency;\n if (existing && Object.getPrototypeOf(existing) === null) return existing;\n // SAFETY: prototype-free map contract for observe idempotency keys (#3368).\n const map = Object.create(null) as Record<string, number>;\n if (existing) {\n for (const key of Object.keys(existing)) {\n if (Object.hasOwn(existing, key)) map[key] = existing[key]!;\n }\n }\n state.admissionIdempotency = map;\n return map;\n}\n\nexport function ensureAdmissionIdempotencyOrder(state: BufferAdmissionIdempotencyState): string[] {\n if (!state.admissionIdempotencyOrder) {\n state.admissionIdempotencyOrder = [];\n }\n const order = state.admissionIdempotencyOrder;\n const map = state.admissionIdempotency;\n if (map) {\n for (const key of Object.keys(map)) {\n if (Object.hasOwn(map, key) && !order.includes(key)) order.push(key);\n }\n }\n return order;\n}\n\nexport function hasBufferedAdmissionIdempotencyKey(state: BufferAdmissionIdempotencyState, key: string): boolean {\n const trimmed = key.trim();\n if (!trimmed) return false;\n const map = state.admissionIdempotency;\n return map !== undefined && Object.hasOwn(map, trimmed);\n}\n\nexport function recordBufferedAdmissionIdempotencyKey(state: BufferAdmissionIdempotencyState, key: string, turnCount: number): void {\n const trimmed = key.trim();\n if (!trimmed || turnCount <= 0) return;\n const map = ensureAdmissionIdempotencyMap(state);\n const order = ensureAdmissionIdempotencyOrder(state);\n map[trimmed] = turnCount;\n if (!order.includes(trimmed)) order.push(trimmed);\n while (order.length > BUFFER_ADMISSION_IDEMPOTENCY_CAP) {\n const evicted = order.shift();\n if (evicted !== undefined) delete map[evicted];\n }\n}\n"],"mappings":";AAeO,IAAM,mCAAmC;AAGzC,SAAS,0CAA0C,OAK/C;AACT,Q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AAO,EAAG,OAAM,KAAK,OAAO;AAChD,SAAO,MAAM,SAAS,kCAAkC;AACtD,UAAM,UAAU,MAAM,MAAM;AAC5B,QAAI,YAAY,OAAW,QAAO,IAAI,OAAO;AAAA,EAC/C;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/orchestration/extraction-run-helpers.ts","../src/orchestration/provider-breaker.ts","../src/orchestration/extraction-run.ts","../src/orchestration/extraction-origin-context.ts","../src/orchestration/probe-deadline.ts"],"sourcesContent":["import type { BufferTurn, ExtractionFailureClass, ExtractionResult, MetaState, PluginConfig } from \"../types.js\";\nimport type { StorageManager } from \"../index.js\";\nimport { resolveMemoryLifecycleCapabilities, resolveRecallEnhancementCapabilities } from \"../capabilities.js\";\nimport { log } from \"../logger.js\";\nimport type { ExtractionRunResult } from \"./extraction-run.js\";\nimport type { ExtractionEngine } from \"../extraction.js\";\n\n/**\n * Count of durable outputs an extraction result asks persistence to write\n * (#3227). Besides the four core arrays, it includes complete relationships\n * while `entityRelationships` is on and a nonblank identity reflection while\n * `identity` is on. It counts requested output, not items that passed the\n * writer's policy gates. Episode titles and provenance metadata never count.\n */\nexport function countRequestedDurableOutputs(result: ExtractionResult, config: PluginConfig): number {\n const capabilities = resolveRecallEnhancementCapabilities(config);\n const relationships =\n capabilities.entityRelationships && Array.isArray(result.relationships)\n ? result.relationships.filter((rel) => Boolean(rel?.source && rel.target && rel.label)).length\n : 0;\n const reflection = capabilities.identity && (result.identityReflection ?? \"\").trim().length > 0 ? 1 : 0;\n return (\n result.facts.length + result.entities.length + result.questions.length + result.profileUpdates.length +\n relationships + reflection\n );\n}\n\nexport function combineExtractionAbortSignals(\n primary: AbortSignal | undefined,\n deadlineController: AbortController | undefined,\n): AbortSignal | undefined {\n if (!deadlineController) return primary;\n return primary ? AbortSignal.any([primary, deadlineController.signal]) : deadlineController.signal;\n}\n\n\n/** Result of a run whose extraction found nothing durable; `retained` marks a recorded failure that left the window in the buffer. */\nexport function emptyExtractionResult(retained: boolean, failureClass?: ExtractionFailureClass): ExtractionRunResult {\n const result: ExtractionRunResult = { status: \"skipped\", reason: \"empty_extraction_result\", persistedCount: 0, durableOutputCount: 0 };\n if (retained) Object.assign(result, { retainedBuffer: true, failureClass: failureClass ?? \"provider_retryable\" }); // same default as the retry bookkeeping\n return result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nexport function deriveTopicsFromExtraction(result: ExtractionResult): string[] {\n if (!isRecord(result)) return [];\n const topics = new Set<string>();\n const facts = Array.isArray(result.facts) ? result.facts : [];\n for (const rawFact of facts) {\n if (!isRecord(rawFact)) continue;\n const tags = Array.isArray(rawFact.tags) ? rawFact.tags : [];\n for (const tag of tags) {\n if (typeof tag === \"string\" && tag.length >= 2) topics.add(tag.toLowerCase());\n }\n if (typeof rawFact.entityRef === \"string\" && rawFact.entityRef.length >= 2) {\n topics.add(rawFact.entityRef.toLowerCase());\n }\n if (typeof rawFact.category === \"string\" && rawFact.category.length > 0) {\n topics.add(rawFact.category);\n }\n }\n const entities = Array.isArray(result.entities) ? result.entities : [];\n for (const rawEntity of entities) {\n if (!isRecord(rawEntity)) continue;\n if (typeof rawEntity.name === \"string\" && rawEntity.name.length >= 2) {\n topics.add(rawEntity.name.toLowerCase());\n }\n }\n return [...topics].slice(0, 16);\n}\n\n/** Bounded cap on persisted per-fingerprint retry-state entries (per namespace meta). */\nexport const EXTRACTION_RETRY_STATE_MAX_ENTRIES = 500;\n\nexport interface ExtractionRetryStateEntry {\n attempts: number;\n nextEligibleAtMs: number;\n firstFailedAtMs: number;\n lastFailureClass: ExtractionFailureClass;\n}\n\nexport interface ExtractionResilienceStatus {\n breaker: {\n state: \"closed\" | \"open\" | \"half_open\";\n openUntilMs: number;\n consecutiveFailures: number;\n lastReason: string;\n };\n backoffFingerprintCount: number;\n}\n\n/**\n * Pure backoff scheduler. Returns the absolute ms timestamp at which a\n * fingerprint that has failed `attempts` times becomes eligible again:\n * exponential via the configured schedule, clamped to `maxBackoffMs`, with\n * ±`jitterRatio` multiplicative jitter. `rng` is injectable for deterministic\n * tests. Never returns a timestamp before `now`.\n */\nexport function computeExtractionRetryNextEligibleMs(\n attempts: number,\n scheduleMs: readonly number[],\n maxBackoffMs: number,\n jitterRatio: number,\n now: number,\n rng: () => number = Math.random,\n): number {\n if (!Number.isFinite(attempts) || !Number.isInteger(attempts) || attempts < 1) {\n throw new RangeError(\"attempts must be a finite integer >= 1\");\n }\n if (!Number.isFinite(maxBackoffMs) || maxBackoffMs < 0) {\n throw new RangeError(\"maxBackoffMs must be a finite number >= 0\");\n }\n if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) {\n throw new RangeError(\"jitterRatio must be a finite number in [0, 1]\");\n }\n const safeNow = Number.isFinite(now) ? now : 0;\n const cap = maxBackoffMs;\n if (!Array.isArray(scheduleMs) || scheduleMs.length === 0) {\n return safeNow + cap;\n }\n const idx = Math.min(attempts - 1, scheduleMs.length - 1);\n const step = scheduleMs[idx];\n const base = Math.min(typeof step === \"number\" && Number.isFinite(step) && step > 0 ? step : cap, cap);\n const randomValue = rng();\n if (!Number.isFinite(randomValue) || randomValue < 0 || randomValue > 1) {\n throw new RangeError(\"rng() must return a finite number in [0, 1]\");\n }\n const jitter = 1 + (randomValue * 2 - 1) * jitterRatio;\n return safeNow + Math.max(0, Math.round(base * jitter));\n}\n\n/**\n * Whether a recorded failure long-parks the fingerprint: `output_truncated`\n * can never succeed at the same output ceiling, and `parse_empty` past its\n * attempt cap has shown this window unparseable — both park to max backoff.\n * The retained window still drains under a raised ceiling (#3521).\n */\nexport function extractionFailureLongParks(\n cls: ExtractionFailureClass,\n attempts: number,\n parseEmptyMaxAttempts: number,\n): boolean {\n return cls === \"output_truncated\" || (cls === \"parse_empty\" && attempts > parseEmptyMaxAttempts);\n}\n\n/**\n * Cap the persisted retry-state array to the newest `maxEntries` by\n * firstFailedAt. Guards invalid caps so they cannot turn `slice(-maxEntries)`\n * into an unbounded copy (AGENTS.md rule 17).\n */\nexport function capExtractionRetryStateEntries<T extends { firstFailedAt: string }>(\n entries: readonly T[],\n maxEntries: number,\n): T[] {\n if (!Number.isFinite(maxEntries) || !Number.isInteger(maxEntries) || maxEntries <= 0) return [];\n const sorted = [...entries].sort((a, b) => a.firstFailedAt.localeCompare(b.firstFailedAt));\n return sorted.slice(-maxEntries);\n}\n\n/**\n * Derive a single `sourceConnector` from a batch of turns.\n * Returns the connector ONLY when ALL turns carry the same connector.\n * Mixed tagged/untagged batches return undefined — extraction facts are\n * persisted at batch level, so attributing them to the single tagged\n * connector would falsely label facts from untagged turns.\n * Conflicting connectors (different values) also return undefined.\n */\nexport function deriveSourceConnector(turns: readonly BufferTurn[]): string | undefined {\n if (turns.length === 0) return undefined;\n const connectors = new Set<string>();\n let untaggedCount = 0;\n for (const turn of turns) {\n if (typeof turn.sourceConnector === \"string\" && turn.sourceConnector.length > 0) {\n connectors.add(turn.sourceConnector);\n } else {\n untaggedCount += 1;\n }\n }\n // All turns must agree on the same connector — no untagged turns mixed in.\n if (untaggedCount > 0) return undefined;\n return connectors.size === 1 ? [...connectors][0] : undefined;\n}\n\nexport async function runExtractionPostPersistBestEffort(\n runDeadlineAware: (\n operation: () => Promise<unknown>,\n phase: string,\n clearTimerOnError?: boolean,\n options?: { ignoreAbort?: boolean; ignoreDeadline?: boolean },\n ) => Promise<unknown>,\n stage: string,\n operation: () => Promise<unknown>,\n options?: { ignoreAbort?: boolean; ignoreDeadline?: boolean; propagateErrors?: boolean },\n): Promise<void> {\n try {\n await runDeadlineAware(operation, stage, false, {\n ignoreAbort: options?.ignoreAbort,\n ignoreDeadline: options?.ignoreDeadline,\n });\n } catch (error) {\n if (options?.propagateErrors) throw error;\n log.warn(`runExtraction: ${stage} failed after persistence (non-fatal)`, error);\n }\n}\n\n/**\n * Applies deferred-judge retention only to live, non-shadow extraction runs.\n * Replay/import paths must not synthesize live-buffer entries after persistence.\n */\nexport interface ExtractionDeferRetentionOptions {\n clearBufferAfterExtraction: boolean;\n extractionJudgeShadow: boolean;\n deferredCount: number;\n normalizedTurns: BufferTurn[];\n bufferKey: string;\n retainDeferredTurns: (bufferKey: string, turns: BufferTurn[], max: number) => Promise<void>;\n}\n\nexport async function runExtractionDeferRetention(\n runPostPersistBestEffort: (\n stage: string,\n operation: () => Promise<unknown>,\n options?: { ignoreAbort?: boolean },\n ) => Promise<void>,\n options: ExtractionDeferRetentionOptions,\n): Promise<void> {\n await runPostPersistBestEffort(\"during_defer_retention\", async () => {\n if (options.clearBufferAfterExtraction && !options.extractionJudgeShadow) {\n const deferredCount = options.deferredCount;\n if (deferredCount > 0 && options.normalizedTurns.length > 0) {\n await options.retainDeferredTurns(options.bufferKey, options.normalizedTurns, 10);\n } else {\n await options.retainDeferredTurns(options.bufferKey, [], 0);\n }\n }\n });\n}\n\nexport interface ExtractionPostPersistOptions {\n result: ExtractionResult;\n storage: StorageManager;\n extractionFingerprint?: string;\n shouldPersistProcessedFingerprint: boolean;\n recordProcessedExtractionFingerprint: (\n storage: StorageManager,\n fingerprint: string,\n meta: MetaState,\n ) => Promise<void>;\n runDeadlineAware: (\n operation: () => Promise<unknown>,\n phase: string,\n clearTimerOnError?: boolean,\n options?: { ignoreAbort?: boolean; ignoreDeadline?: boolean },\n ) => Promise<unknown>;\n isDeadlineError: (error: unknown) => boolean;\n createDeadlineError: (stage: string) => Error;\n deadlineMs?: number;\n clearBufferAfterExtraction: boolean;\n runPostPersistBestEffort: (\n stage: string,\n operation: () => Promise<unknown>,\n options?: { ignoreAbort?: boolean; ignoreDeadline?: boolean; propagateErrors?: boolean },\n ) => Promise<void>;\n extractionJudgeShadow: boolean;\n /** Facts this run's persist deferred to the judge — drives retention (#1523). */\n deferredCount: number;\n normalizedTurns: BufferTurn[];\n bufferKey: string;\n retainDeferredTurns: (bufferKey: string, turns: BufferTurn[], max: number) => Promise<void>;\n clearBuffer: (options?: { ignoreAbort?: boolean }) => Promise<void>;\n failOnExtractionFailure: boolean;\n}\n\nexport interface ExtractionPostPersistResult {\n metadataFailed: boolean;\n}\n\nexport async function runExtractionPostPersist(\n options: ExtractionPostPersistOptions,\n): Promise<ExtractionPostPersistResult> {\n let metadataFailed = false;\n let deadlineError: Error | undefined;\n const recordFailure = (stage: string, error: unknown): void => {\n metadataFailed = true;\n if (options.isDeadlineError(error) && deadlineError === undefined) {\n deadlineError = error as Error;\n }\n log.warn(`runExtraction: ${stage} failed after durable persistence; continuing with buffer clear`, error);\n };\n // Applied under the storage's per-dir meta lock (storage.updateMeta): the\n // fingerprint record and the counters land on a FRESHLY loaded meta, so a\n // concurrent extraction's updates are not reverted by this save.\n const applyPostPersistMetadata = async (fresh: MetaState): Promise<void> => {\n if (options.extractionFingerprint && options.shouldPersistProcessedFingerprint) {\n try {\n await options.recordProcessedExtractionFingerprint(options.storage, options.extractionFingerprint, fresh);\n } catch (error) {\n metadataFailed = true;\n log.warn(\"runExtraction: processed fingerprint failed after durable persistence; continuing with buffer clear\", error);\n }\n }\n fresh.extractionCount += 1;\n fresh.lastExtractionAt = new Date().toISOString();\n fresh.totalMemories += Array.isArray(options.result.facts) ? options.result.facts.length : 0;\n fresh.totalEntities += Array.isArray(options.result.entities) ? options.result.entities.length : 0;\n };\n try {\n await options.runDeadlineAware(\n () => options.storage.updateMeta(applyPostPersistMetadata),\n \"during_post_persist_meta_save\",\n false,\n );\n } catch (error) {\n recordFailure(\"metadata save\", error);\n }\n const runBestEffort = options.runPostPersistBestEffort;\n await runExtractionDeferRetention(runBestEffort, {\n clearBufferAfterExtraction: options.clearBufferAfterExtraction,\n extractionJudgeShadow: options.extractionJudgeShadow,\n deferredCount: options.deferredCount,\n normalizedTurns: options.normalizedTurns,\n bufferKey: options.bufferKey,\n retainDeferredTurns: options.retainDeferredTurns,\n });\n await runBestEffort(\n \"during_buffer_clear\",\n () => options.clearBuffer({ ignoreAbort: true }),\n {\n ignoreAbort: true,\n ignoreDeadline: options.failOnExtractionFailure,\n propagateErrors: options.failOnExtractionFailure,\n },\n );\n if (options.failOnExtractionFailure && typeof options.deadlineMs === \"number\" && Date.now() >= options.deadlineMs) {\n throw options.createDeadlineError(\"during_buffer_clear\");\n }\n if (deadlineError) throw deadlineError;\n return { metadataFailed };\n}\n\n/**\n * Record a processed fingerprint when applicable and advance the extraction\n * liveness watermark only for a provider-backed empty success. Fingerprinted\n * imports treat the metadata save as load-bearing dedupe state; normal live\n * runs treat the stamp as diagnostic and fail open. Deadline errors always\n * propagate.\n */\nexport async function commitEmptySuccessExtraction(args: {\n storage: StorageManager;\n extractionFingerprint: string | null;\n shouldPersistProcessedFingerprint: boolean;\n hasExtractionFailure: boolean;\n extractionSkippedReason: ExtractionResult[\"extractionSkippedReason\"];\n recordProcessedExtractionFingerprint: (storage: StorageManager, fingerprint: string, meta: MetaState) => Promise<unknown>;\n runDeadlineAware: <T>(operation: () => Promise<T>, phase: string, clearTimerOnError?: boolean) => Promise<T>;\n isDeadlineError: (error: unknown) => boolean;\n}): Promise<void> {\n const {\n storage,\n extractionFingerprint,\n shouldPersistProcessedFingerprint,\n hasExtractionFailure,\n extractionSkippedReason,\n recordProcessedExtractionFingerprint,\n runDeadlineAware,\n isDeadlineError,\n } = args;\n const shouldRecordFingerprint =\n extractionFingerprint !== null &&\n shouldPersistProcessedFingerprint &&\n !hasExtractionFailure;\n const shouldStampLiveness =\n !hasExtractionFailure && extractionSkippedReason === undefined;\n if (!shouldRecordFingerprint && !shouldStampLiveness) return;\n\n const metadataFailureIsFatal = shouldRecordFingerprint;\n try {\n await runDeadlineAware(\n () =>\n storage.updateMeta(async (meta) => {\n if (shouldRecordFingerprint) {\n await recordProcessedExtractionFingerprint(storage, extractionFingerprint!, meta);\n }\n if (shouldStampLiveness) {\n meta.extractionCount += 1;\n meta.lastExtractionAt = new Date().toISOString();\n }\n }),\n \"during_empty_success_liveness_save\",\n false,\n );\n } catch (err) {\n if (isDeadlineError(err)) throw err;\n if (metadataFailureIsFatal) throw err;\n log.warn(\"runExtraction: failed to stamp empty-success liveness watermark (non-fatal)\", err);\n }\n}\n\n/**\n * Split a claim's turn list across sequential extract() calls capped at\n * extractionPromptMaxChars of turn content per call. Every turn goes to\n * exactly one call — chunking never drops or samples turns; it keeps each\n * call's prompt small enough to finish inside the caller's LLM time budget\n * (giant prompts abort at the caller's timeout and burn the whole attempt).\n * Budget 0 disables chunking.\n */\nexport async function extractChunkedExtraction(\n engine: Pick<ExtractionEngine, \"extract\">,\n config: PluginConfig,\n turns: BufferTurn[],\n existingEntities: string[],\n signal?: AbortSignal,\n): Promise<ExtractionResult> {\n const budget = config.extractionPromptMaxChars;\n if (!(budget > 0)) {\n return engine.extract(turns, existingEntities, signal);\n }\n const chunks: BufferTurn[][] = [[]];\n let chars = 0;\n for (const turn of turns) {\n const size = turn.content.length;\n if (chars > 0 && chars + size > budget) {\n chunks.push([]);\n chars = 0;\n }\n chunks[chunks.length - 1]!.push(turn);\n chars += size;\n }\n if (chunks.length === 1) {\n return engine.extract(turns, existingEntities, signal);\n }\n const merged: ExtractionResult = {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n };\n const entityNames = [...existingEntities];\n let skippedReason: ExtractionResult[\"extractionSkippedReason\"];\n let providerCalls = 0;\n for (const chunk of chunks) {\n const part = await engine.extract(chunk, entityNames, signal);\n // A provider failure keeps the single-call surface so the run stays\n // retryable under the no-drop contract; a per-chunk prefilter skip is\n // not a failure — later chunks can still carry real facts.\n if (part.extractionFailure) return part;\n if (part.extractionSkippedReason) {\n skippedReason ??= part.extractionSkippedReason;\n continue;\n }\n providerCalls += 1;\n merged.facts.push(...part.facts);\n merged.profileUpdates.push(...part.profileUpdates);\n merged.entities.push(...part.entities);\n merged.questions.push(...part.questions);\n if (part.relationships) {\n merged.relationships = [...(merged.relationships ?? []), ...part.relationships];\n }\n merged.identityReflection ??= part.identityReflection;\n merged.episodeTitle ??= part.episodeTitle;\n // Entity names found in earlier chunks flow into later calls so the\n // LLM reuses them instead of inventing variants.\n entityNames.push(...part.entities.map((entity) => entity.name));\n }\n // The connector must derive from the whole claim, not the first chunk —\n // a mixed claim resolves to no connector, same as one call over the set.\n if (resolveMemoryLifecycleCapabilities(config).extractionScopeClassification) {\n merged.sourceConnector = deriveSourceConnector(turns);\n }\n // Every chunk prefiltered: no provider call happened — keep the skip\n // reason so the caller does not record provider success on a silent batch.\n if (providerCalls === 0 && skippedReason) {\n merged.extractionSkippedReason = skippedReason;\n }\n log.debug(\n `extraction chunked: ${turns.length} turns across ${chunks.length} calls (budget ${budget} chars)`,\n );\n return merged;\n}\n","import { log } from \"../logger.js\";\nimport type { ExtractionFailureClass } from \"../types.js\";\n\nexport interface ProviderBreakerConfig {\n readonly failureThreshold: number;\n readonly cooldownMs: number;\n readonly authCooldownMs: number;\n}\n\n/**\n * How long the single half-open probe may run before it counts as a provider\n * failure and re-opens the breaker. Before this bound, a probe waiting in the\n * local LLM queue and then timing out twice held every drain for up to 55 min.\n * 15 min covers the slowest probe that did succeed in a 24 h production log\n * (10 min) and caps a failed one at 15 min plus the cooldown.\n * shortcut: a constant, not config; make it a config key if hosts need to tune it.\n */\nexport const HALF_OPEN_PROBE_TIMEOUT_MS = 900_000;\n\nexport interface ProbeOwnerToken {\n readonly __probeOwner: true;\n}\n\nexport interface ProviderBreakerSnapshot {\n readonly state: \"closed\" | \"open\" | \"half_open\";\n readonly openUntilMs: number;\n readonly consecutiveFailures: number;\n readonly lastReason: string;\n}\n\nexport interface ProbeAcquisition {\n /** True when the attempt is suppressed (breaker open, or the half-open\n * probe is owned by another attempt). */\n readonly suppressed: boolean;\n /** True when THIS attempt owns the single half-open probe and must\n * terminate it via {@link failure}/{@link success} (with its token), or\n * release it via {@link releaseProbe} on any early exit (deadline, abort,\n * throw). */\n readonly probe: boolean;\n /** Opaque ownership token; only the matching token settles or releases the\n * probe, so attempts that bypass the gate (forced extractions) can never\n * release another attempt's in-flight probe. */\n readonly token?: ProbeOwnerToken;\n}\n\n/**\n * Provider circuit breaker with single-flight half-open probe OWNERSHIP\n * (codex P2 on #3311): under extractionQueueConcurrency > 1 several sessions\n * can pass an expired `open` breaker in the same window, and a wall-clock\n * reservation either expires under a live long provider attempt (600s\n * timeouts) or pins the breaker when an attempt dies without settling. So the\n * probe is OWNED, not timed: exactly one attempt holds it from the\n * open→half_open flip until its terminal `failure()`/`success()`, and any\n * early exit releases it explicitly. A released-but-unfinished probe lets the\n * next attempt re-probe; a retry backoff still throttles that namespace.\n */\nexport class ProviderCircuitBreaker {\n private consecutiveFailures = 0;\n private openUntilMs = 0;\n private state: ProviderBreakerSnapshot[\"state\"] = \"closed\";\n private lastReason = \"\";\n private probeHeld = false;\n private probeToken: ProbeOwnerToken | null = null;\n\n acquire(now: number): ProbeAcquisition {\n if (now < this.openUntilMs) return { suppressed: true, probe: false };\n if (this.state === \"open\") {\n this.state = \"half_open\";\n this.probeHeld = true;\n const token: ProbeOwnerToken = { __probeOwner: true };\n this.probeToken = token;\n this.logTransition();\n return { suppressed: false, probe: true, token }; // THIS attempt is the probe.\n }\n if (this.state === \"half_open\") {\n if (this.probeHeld) return { suppressed: true, probe: false };\n this.probeHeld = true; // previous owner released without settling; re-probe.\n const token: ProbeOwnerToken = { __probeOwner: true };\n this.probeToken = token;\n return { suppressed: false, probe: true, token };\n }\n return { suppressed: false, probe: false };\n }\n\n /** Release an owned probe on an attempt that exits without a terminal\n * outcome (deadline, abort, throw). Only the matching owner releases;\n * idempotent; state stays half_open so the next attempt re-probes. */\n releaseProbe(token?: ProbeOwnerToken): void {\n if (token === undefined || this.probeToken !== token) return;\n this.probeToken = null;\n this.probeHeld = false;\n }\n\n failure(cls: ExtractionFailureClass, now: number, config: ProviderBreakerConfig, probeToken?: ProbeOwnerToken): void {\n // Only the probe OWNER's failure settles the half-open probe: a failure\n // from an attempt that bypassed acquire (forced extraction) must not\n // release another attempt's in-flight probe or masquerade as its result.\n const owned = probeToken !== undefined && this.probeToken === probeToken;\n if (owned) {\n this.probeToken = null;\n this.probeHeld = false;\n }\n this.consecutiveFailures += 1;\n const trip =\n // An unowned auth_config failure (forced extraction) must not reopen\n // over a held half-open probe — same ownership rule as the threshold\n // term; the auth cooldown still applies once the probe settles.\n (cls === \"auth_config\" && (this.state !== \"half_open\" || owned)) ||\n // A failed half-open probe re-opens immediately (standard breaker\n // semantics). Without this, an auth_config-opened breaker (which trips\n // below the threshold) would get stuck half_open after a transient\n // probe failure and stop suppressing (cursor review).\n (owned && this.state === \"half_open\") ||\n // PRRT_kwDORJXyws6zxG6V: an unowned (forced-extraction) failure must\n // not cross the threshold while another attempt owns the half-open\n // probe — reopening here would strand the owner's token and let the\n // next cooldown mint a second concurrent probe. The failure count and\n // retry bookkeeping still accumulate for when the state leaves\n // half_open.\n (this.state !== \"half_open\" && this.consecutiveFailures >= config.failureThreshold);\n if (!trip) return;\n const cooldown = cls === \"auth_config\" ? config.authCooldownMs : config.cooldownMs;\n this.openUntilMs = now + Math.max(0, cooldown);\n this.lastReason = cls;\n if (this.state !== \"open\") {\n this.state = \"open\";\n this.logTransition();\n }\n }\n\n success(probeToken?: ProbeOwnerToken): void {\n const wasDisturbed =\n this.state !== \"closed\" || this.consecutiveFailures > 0 || this.openUntilMs > 0;\n if (!wasDisturbed) return;\n // PRRT_kwDORJXyws6zxG6u: while a half-open probe is held, only its OWNER\n // may settle it. An unowned (forced-extraction) success must not clear\n // another run's probe or close the breaker mid-probe — the next ordinary\n // acquisition could then start a second concurrent probe.\n if (this.probeHeld && !(probeToken !== undefined && this.probeToken === probeToken)) return;\n const wasOpen = this.state !== \"closed\";\n this.probeToken = null;\n this.probeHeld = false;\n this.consecutiveFailures = 0;\n this.openUntilMs = 0;\n this.lastReason = \"\";\n this.state = \"closed\";\n if (wasOpen) this.logTransition();\n }\n\n snapshot(): ProviderBreakerSnapshot {\n return {\n state: this.state,\n openUntilMs: this.openUntilMs,\n consecutiveFailures: this.consecutiveFailures,\n lastReason: this.lastReason,\n };\n }\n\n private logTransition(): void {\n // Once per state change (not per attempt) — AGENTS.md observability rule.\n log.warn(\"extraction: provider circuit breaker transition\", {\n state: this.state,\n consecutiveFailures: this.consecutiveFailures,\n lastReason: this.lastReason,\n openUntilMs: this.openUntilMs,\n });\n }\n}\n","/**\n * Buffer → extract → persist coordinator (issue #1526, seam 15).\n * Owns runExtraction, shouldQueueExtraction, buildExtractionFingerprint,\n * normalizeExtractionFingerprintTurns and recordProcessedExtractionFingerprint.\n * The orchestrator delegates here and retains cross-subsystem routing,\n * persistence and post-write side effects via injected dependencies.\n * Extracted from orchestrator.ts without behavior changes.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { StorageManager } from \"../index.js\";\nimport { NamespaceStorageRouter } from \"../namespaces/storage.js\";\nimport type { ExtractionEngine } from \"../extraction.js\";\nimport type { SmartBuffer } from \"../buffer.js\";\nimport type { ThreadingManager } from \"../threading.js\";\nimport type { BoxBuilder } from \"../boxes.js\";\nimport { resolvePrincipal, defaultNamespaceForPrincipal } from \"../namespaces/principal.js\";\nimport { resolveScopeProfilePlan, type ResolvedScopeProfilePlan } from \"../namespaces/scope-profiles.js\";\nimport { resolveCodingNamespaceOverlay } from \"../coding/coding-namespace.js\";\nimport type { CodingContext } from \"../types.js\";\nimport { deriveExtractionOriginContext, type ExtractionSourceContext } from \"./extraction-origin-context.js\";\nimport {\n resolvePresentationCapabilities,\n resolveMemoryLifecycleCapabilities,\n type GraphConstructionCapabilitySet,\n type MemoryLifecycleCapabilitySet,\n} from \"../capabilities.js\";\nimport { parseFlexibleIsoTimestamp } from \"../utils/iso-timestamp.js\";\nimport { tagPersistedMemories } from \"../location/tagging.js\";\nimport { log } from \"../logger.js\";\nimport { emitExtractionLlmFailureError, recordExtractionLlmFailure, recordExtractionLlmSuccess } from \"../extraction-llm-health.js\";\nimport type { PluginConfig, BufferTurn, ExtractionResult, MetaState, ExtractionFailureClass } from \"../types.js\";\nimport type { TierMigrationCycleSummary } from \"../recall-state.js\";\n\nexport interface ExtractionRunResult {\n status: \"completed\" | \"skipped\";\n reason?: string;\n persistedCount: number;\n durableOutputCount: number;\n postPersistMetadataFailed?: boolean;\n retainedBuffer?: boolean; failureClass?: ExtractionFailureClass; // retained: the run left the window in the buffer for a retry (a recorded failure) of this class\n}\n\nexport class ExtractionDeadlineError extends Error {\n readonly stage: string;\n\n constructor(stage: string) {\n super(`replay extraction deadline exceeded (${stage})`);\n this.name = \"ExtractionDeadlineError\";\n this.stage = stage;\n }\n}\n\n/** Dependencies injected by the orchestrator. All stable references or\n * live accessors — lazy getters for anything tests reassign\n * post-construction (buffer, extraction, storageRouter, threading). */\nexport interface ExtractionRunCoordinatorDeps {\n config: PluginConfig;\n getBuffer: () => SmartBuffer;\n getExtraction: () => Pick<ExtractionEngine, \"extract\">;\n getStorageRouter: () => Pick<NamespaceStorageRouter, \"storageFor\">;\n getThreading: () => Pick<ThreadingManager, \"processTurn\" | \"updateThreadTitle\">;\n\n persistExtraction: (\n result: ExtractionResult,\n storage: StorageManager,\n threadIdForExtraction?: string | null,\n sourceContext?: ExtractionSourceContext,\n baseNamespace?: string,\n scopeProfileWritePlan?: ResolvedScopeProfilePlan | null,\n sourceText?: string,\n graphCaps?: GraphConstructionCapabilitySet,\n lifecycleCaps?: MemoryLifecycleCapabilitySet\n ) => Promise<ExtractionPersistResult>;\n\n maybeCapturePassiveCorrections: (\n turns: readonly BufferTurn[],\n opts: {\n sessionKey: string;\n principal?: string;\n namespace: string;\n bufferKey: string;\n isLiveSession: boolean;\n abortSignal?: AbortSignal;\n }\n ) => Promise<void>;\n\n resolveSelfNamespace: (sessionKey?: string) => string;\n getCodingContextForSession: (sessionKey: string) => CodingContext | null;\n applyCodingNamespaceOverlay: (sessionKey: string, namespace: string) => string;\n boxBuilderFor: (storage: StorageManager) => Pick<BoxBuilder, \"onExtraction\">;\n appendPersistedThreadEpisodes: (threadId: string, ids: string[], pendingReviewIds: string[]) => Promise<void>;\n maybeScheduleConsolidation: (nonZero: boolean) => void;\n requestQmdMaintenance: () => void;\n runTierMigrationCycle: (\n storage: StorageManager,\n trigger: \"extraction\" | \"maintenance\" | \"manual\",\n options?: {\n dryRun?: boolean;\n limitOverride?: number;\n force?: boolean;\n }\n ) => Promise<TierMigrationCycleSummary>;\n recordProcessedExtractionFingerprint: (\n storage: StorageManager,\n fingerprint: string,\n preloadedMeta?: Awaited<ReturnType<StorageManager[\"loadMeta\"]>>\n ) => Promise<void>;\n /**\n * Orchestrator-wide provider resilience state. Absent for a standalone\n * coordinator (own breaker); the orchestrator passes ITS breaker so every\n * isolated claim-backed drain accumulates failures toward the same\n * threshold and honors a foreground-opened breaker (review round).\n */\n providerBreaker?: ProviderCircuitBreaker;\n /** Orchestrator-owned stop signal, combined into every extraction run's\n * abort signal: queued tasks never start and in-flight runs abort the\n * moment destroy() begins. Absent for standalone coordinators (tests). */\n shutdownSignal?: AbortSignal;\n /** Test seam: how long a half-open probe may run before it counts as a\n * provider failure. Defaults to HALF_OPEN_PROBE_TIMEOUT_MS (provider-breaker.ts). */\n halfOpenProbeTimeoutMs?: number;\n}\n\n// Recall/extraction abort helpers live in orchestrator-helpers.ts since\n// #1526 seam 25; this file previously carried duplicate copies\n// (AGENTS.md rule 8 — no duplicated helpers).\nimport { raceRecallAbort, throwIfRecallAborted } from \"./orchestrator-helpers.js\";\nimport {\n capExtractionRetryStateEntries,\n combineExtractionAbortSignals,\n commitEmptySuccessExtraction,\n computeExtractionRetryNextEligibleMs,\n countRequestedDurableOutputs,\n deriveSourceConnector,\n deriveTopicsFromExtraction, emptyExtractionResult, extractChunkedExtraction,\n extractionFailureLongParks,\n runExtractionPostPersist,\n runExtractionPostPersistBestEffort,\n EXTRACTION_RETRY_STATE_MAX_ENTRIES,\n} from \"./extraction-run-helpers.js\";\nimport type { ExtractionResilienceStatus, ExtractionRetryStateEntry } from \"./extraction-run-helpers.js\";\nimport type { ExtractionPersistResult } from \"./extraction-persist.js\";\nimport { ProviderCircuitBreaker, type ProbeOwnerToken } from \"./provider-breaker.js\";\nimport { probeTimedOutResult, startProbeDeadline } from \"./probe-deadline.js\";\n\nexport {\n capExtractionRetryStateEntries,\n computeExtractionRetryNextEligibleMs,\n deriveSourceConnector,\n deriveTopicsFromExtraction,\n};\nexport type { ExtractionResilienceStatus };\n\n/**\n * Coordinates the extraction run pipeline. Holds the dedupe fingerprint\n * cache (`recentExtractionFingerprints`) and delegates all side effects\n * to injected orchestrator methods.\n */\nexport class ExtractionRunCoordinator {\n private readonly recentExtractionFingerprints = new Map<string, number>();\n // Per-fingerprint extraction retry/backoff state (extraction hot-loop\n // hardening). Outer key = namespace, inner key = fingerprint. Hydrated lazily\n // from namespace-scoped meta so the hot path is a Map lookup; persisted back\n // to meta on change (restart-safe, cross-process coherent via the shared\n // meta.json). The breaker below is intentionally per-process in-memory\n // (mirrors local-llm.cooldownUntilMs); a restart clears it but the persisted\n // backoff still throttles, so a restart can't resurrect the hot loop.\n private readonly extractionRetryState = new Map<string, Map<string, ExtractionRetryStateEntry>>();\n private readonly hydratedRetryNamespaces = new Set<string>();\n private readonly providerBreaker: ProviderCircuitBreaker;\n\n constructor(private readonly deps: ExtractionRunCoordinatorDeps) {\n this.providerBreaker = deps.providerBreaker ?? new ProviderCircuitBreaker();\n }\n\n private get config(): PluginConfig {\n return this.deps.config;\n }\n\n // -------------------------------------------------------------------------\n // Source-valid-at helpers (moved from orchestrator.ts module scope)\n // -------------------------------------------------------------------------\n\n private latestSourceValidAtFromTurns(turns: readonly BufferTurn[]): string | undefined {\n let latestMs: number | null = null;\n for (const turn of turns) {\n if (turn.extractionContextOnly === true) continue;\n if (typeof turn.sourceValidAt !== \"string\") continue;\n const parsed = parseFlexibleIsoTimestamp(turn.sourceValidAt.trim());\n if (parsed === null) continue;\n if (latestMs === null || parsed > latestMs) {\n latestMs = parsed;\n }\n }\n return latestMs === null ? undefined : new Date(latestMs).toISOString();\n }\n\n // -------------------------------------------------------------------------\n // Extraction dedupe fingerprint helpers\n // -------------------------------------------------------------------------\n\n normalizeExtractionFingerprintTurns(turns: BufferTurn[]): string[] {\n if (!Array.isArray(turns) || turns.length === 0) return [];\n return turns\n .filter((turn) => turn.role === \"user\" || turn.role === \"assistant\")\n .map((turn) => {\n if (typeof turn.turnFingerprint === \"string\" && turn.turnFingerprint.length > 0) {\n return `fp:${turn.turnFingerprint}`;\n }\n return `${turn.role}:${(turn.content ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, this.config.extractionMaxTurnChars)}`;\n })\n .filter((value) => value.length > 0);\n }\n\n buildExtractionFingerprint(turns: BufferTurn[], bufferKey: string): string | null {\n const normalized = this.normalizeExtractionFingerprintTurns(turns).join(\"\\n\");\n if (!normalized) return null;\n return createHash(\"sha256\").update(`${bufferKey}\\n${normalized}`).digest(\"hex\");\n }\n\n shouldQueueExtraction(turns: BufferTurn[], options: { commit?: boolean; bufferKey?: string } = {}): boolean {\n const lifecycleCaps = resolveMemoryLifecycleCapabilities(this.config);\n if (!lifecycleCaps.extractionDedupe) return true;\n if (!Array.isArray(turns) || turns.length === 0) return false;\n\n const bufferKey = options.bufferKey ?? turns[0]?.sessionKey ?? \"default\";\n const fingerprint = this.buildExtractionFingerprint(turns, bufferKey);\n if (!fingerprint) return false;\n const now = Date.now();\n const seenAt = this.recentExtractionFingerprints.get(fingerprint);\n if (seenAt && now - seenAt < this.config.extractionDedupeWindowMs) {\n log.debug(\"extraction dedupe: skipped duplicate buffered turn set\");\n return false;\n }\n\n if (options.commit !== false) {\n this.recentExtractionFingerprints.set(fingerprint, now);\n }\n // Keep this cache bounded to avoid unbounded growth.\n if (options.commit !== false && this.recentExtractionFingerprints.size > 200) {\n const entries = Array.from(this.recentExtractionFingerprints.entries()).sort((a, b) => a[1] - b[1]);\n for (const [key] of entries.slice(0, entries.length - 200)) {\n this.recentExtractionFingerprints.delete(key);\n }\n }\n\n return true;\n }\n\n // -------------------------------------------------------------------------\n // Processed-fingerprint recording\n // -------------------------------------------------------------------------\n\n async recordProcessedExtractionFingerprint(\n storage: StorageManager,\n fingerprint: string,\n preloadedMeta?: Awaited<ReturnType<StorageManager[\"loadMeta\"]>>\n ): Promise<void> {\n const meta = preloadedMeta ?? (await storage.loadMeta());\n const observedAt = new Date().toISOString();\n const seen = new Map(\n (meta.processedExtractionFingerprints ?? []).map((entry) => [entry.fingerprint, entry.observedAt])\n );\n seen.set(fingerprint, observedAt);\n meta.processedExtractionFingerprints = Array.from(seen.entries())\n .map(([value, at]) => ({ fingerprint: value, observedAt: at }))\n .sort((left, right) => left.observedAt.localeCompare(right.observedAt))\n .slice(-500);\n if (!preloadedMeta) {\n await storage.saveMeta(meta);\n }\n }\n\n // -------------------------------------------------------------------------\n // Extraction retry/backoff + circuit breaker (extraction hot-loop hardening)\n // -------------------------------------------------------------------------\n\n /** Lazily hydrate the in-memory retry-state mirror for a namespace from meta.\n * One-time per namespace per coordinator; the hot path is then a Map lookup.\n * Cross-process coherence: a fresh coordinator hydrates from the shared\n * meta.json, so a failure persisted by another process is honored here. */\n private hydrateRetryStateFromMeta(namespace: string, meta: MetaState): void {\n if (this.hydratedRetryNamespaces.has(namespace)) return;\n this.hydratedRetryNamespaces.add(namespace);\n const nsMap = this.extractionRetryState.get(namespace) ?? new Map<string, ExtractionRetryStateEntry>();\n for (const entry of meta.extractionRetryState ?? []) {\n const nextEligibleAtMs = Date.parse(entry.nextEligibleAt);\n const firstFailedAtMs = Date.parse(entry.firstFailedAt);\n nsMap.set(entry.fingerprint, {\n attempts: entry.attempts,\n nextEligibleAtMs: Number.isFinite(nextEligibleAtMs) ? nextEligibleAtMs : 0,\n firstFailedAtMs: Number.isFinite(firstFailedAtMs) ? firstFailedAtMs : Date.now(),\n lastFailureClass: entry.lastFailureClass,\n });\n }\n this.extractionRetryState.set(namespace, nsMap);\n }\n\n /** Rebuild `meta.extractionRetryState` from the in-memory namespace mirror,\n * bounded to the newest entries, and prune the mirror to match. */\n private persistRetryStateToMeta(namespace: string, meta: MetaState): void {\n const nsMap = this.extractionRetryState.get(namespace);\n const entries = nsMap\n ? Array.from(nsMap.entries()).map(([fingerprint, st]) => ({\n fingerprint,\n attempts: st.attempts,\n nextEligibleAt: new Date(st.nextEligibleAtMs).toISOString(),\n firstFailedAt: new Date(st.firstFailedAtMs).toISOString(),\n lastFailureClass: st.lastFailureClass,\n }))\n : [];\n const capped = capExtractionRetryStateEntries(entries, EXTRACTION_RETRY_STATE_MAX_ENTRIES);\n meta.extractionRetryState = capped;\n if (nsMap && capped.length < nsMap.size) {\n const kept = new Set(capped.map((e) => e.fingerprint));\n for (const key of Array.from(nsMap.keys())) {\n if (!kept.has(key)) nsMap.delete(key);\n }\n }\n }\n /** Record an extraction failure into per-fingerprint backoff state + breaker, persisting to namespace meta. Fail-open. */\n private async recordExtractionFailure(\n namespace: string,\n fingerprint: string,\n cls: ExtractionFailureClass,\n meta: MetaState,\n now: number,\n probeToken?: ProbeOwnerToken,\n ): Promise<void> {\n try {\n this.hydrateRetryStateFromMeta(namespace, meta);\n this.applyExtractionFailureToMemory(namespace, fingerprint, cls, now, probeToken);\n this.persistRetryStateToMeta(namespace, meta);\n // The caller's storage.updateMeta persists this — saving here would write the same file twice.\n } catch (err) {\n // Fail-open: recording failure state must never crash observe/recall.\n log.warn(\"runExtraction: failed to record extraction retry state (non-fatal)\", err);\n }\n }\n\n /** Failure backoff into the in-memory mirror + breaker WITHOUT touching meta — the fallback\n * when the locked meta write cannot run: the retry gate reads this mirror, so it stays shut. */\n private applyExtractionFailureToMemory(\n namespace: string,\n fingerprint: string,\n cls: ExtractionFailureClass,\n now: number,\n probeToken?: ProbeOwnerToken,\n ): void {\n const nsMap = this.extractionRetryState.get(namespace) ?? new Map<string, ExtractionRetryStateEntry>();\n const prev = nsMap.get(fingerprint);\n const attempts = (prev?.attempts ?? 0) + 1;\n const firstFailedAtMs = prev?.firstFailedAtMs ?? now;\n // output_truncated or parse_empty past its cap → long-park; the window survives a raised ceiling (#3521).\n const nextEligibleAtMs = extractionFailureLongParks(cls, attempts, this.config.extractionParseEmptyMaxAttempts)\n ? now + Math.max(0, this.config.extractionRetryMaxBackoffMs)\n : computeExtractionRetryNextEligibleMs(\n attempts,\n this.config.extractionRetryScheduleMs,\n this.config.extractionRetryMaxBackoffMs,\n this.config.extractionRetryJitterRatio,\n now,\n );\n nsMap.set(fingerprint, { attempts, nextEligibleAtMs, firstFailedAtMs, lastFailureClass: cls });\n this.extractionRetryState.set(namespace, nsMap);\n this.providerBreaker.failure(cls, now, {\n failureThreshold: this.config.extractionBreakerFailureThreshold,\n cooldownMs: this.config.extractionBreakerCooldownMs,\n authCooldownMs: this.config.extractionBreakerAuthCooldownMs,\n }, probeToken);\n }\n\n /** Delete a fingerprint's retry entry from the mirror + meta. Returns whether\n * meta changed (so the caller can decide to persist). Does not touch the\n * breaker — callers pair this with `resetProviderBreakerOnSuccess`. */\n private clearExtractionRetryEntry(namespace: string, fingerprint: string, meta: MetaState): boolean {\n const nsMap = this.extractionRetryState.get(namespace);\n if (!nsMap?.has(fingerprint)) return false;\n nsMap.delete(fingerprint);\n this.persistRetryStateToMeta(namespace, meta);\n return true;\n }\n\n /** Live in-process resilience snapshot (breaker + backoff population). */\n getExtractionResilienceStatus(): ExtractionResilienceStatus {\n let backoffFingerprintCount = 0;\n for (const nsMap of this.extractionRetryState.values()) {\n backoffFingerprintCount += nsMap.size;\n }\n return {\n breaker: this.providerBreaker.snapshot(),\n backoffFingerprintCount,\n };\n }\n\n // -------------------------------------------------------------------------\n // Main extraction pipeline\n // -------------------------------------------------------------------------\n\n async runExtraction(\n turns: BufferTurn[],\n options: {\n clearBufferAfterExtraction?: boolean;\n clearMatchingTurns?: boolean; retentionWindow?: readonly BufferTurn[];\n skipCharThreshold?: boolean;\n skipUserTurnThreshold?: boolean;\n deadlineMs?: number;\n bufferKey?: string;\n abortSignal?: AbortSignal;\n failOnExtractionFailure?: boolean;\n /** Write-rate commit boundary, after persistence returns. */\n onDurableCommit?: () => void;\n /** Disarm preemption once persistence can no longer be aborted. */\n onBeforePersist?: () => void;\n /**\n * Explicit namespace override for the write path (#460). When set, this\n * is the namespace where extraction writes go instead of the one derived\n * from `defaultNamespaceForPrincipal(resolvePrincipal(sessionKey))`.\n * The resolved `principal` is still threaded into memory metadata for\n * provenance; only the storage target is overridden.\n */\n writeNamespaceOverride?: string;\n /**\n * Pin the provenance principal instead of deriving it from\n * `resolvePrincipal(sessionKey)`. When set, this is the identity an\n * access surface already authenticated; used so observed-turn provenance\n * is correct even though `turn.sessionKey` is the original key.\n */\n principalOverride?: string;\n /**\n * Access scope resolution may already have selected a profile while the\n * session context remains intentionally unbound. Reuse that plan for\n * persistence instead of deriving it from shared session state.\n */\n scopeProfileWritePlan?: ResolvedScopeProfilePlan | null;\n /**\n * Force the extractor call, bypassing the retry-backoff / circuit-breaker\n * gate (extraction hot-loop hardening). Set by explicit flush paths.\n */\n forceExtractionAttempt?: boolean;\n } = {}\n ): Promise<ExtractionRunResult> {\n log.debug(`running extraction on ${turns.length} turns`);\n const clearBufferAfterExtraction = options.clearBufferAfterExtraction ?? true;\n const clearMatchingTurns = options.clearMatchingTurns === true;\n const skipCharThreshold = options.skipCharThreshold ?? false;\n const skipUserTurnThreshold = options.skipUserTurnThreshold ?? false;\n const deadlineMs =\n typeof options.deadlineMs === \"number\" && Number.isFinite(options.deadlineMs) ? options.deadlineMs : undefined;\n const bufferKey = options.bufferKey ?? turns[0]?.sessionKey ?? \"default\";\n const throwIfDeadlineExceeded = (stage: string): void => {\n if (typeof deadlineMs === \"number\" && Date.now() >= deadlineMs) {\n throw new ExtractionDeadlineError(stage);\n }\n };\n const throwIfAborted = (stage: string): void => {\n throwIfRecallAborted(options.abortSignal, `extraction aborted (${stage})`);\n };\n const runPassiveCapture = async (\n captureTurns: readonly BufferTurn[],\n captureOptions: {\n sessionKey: string;\n principal?: string;\n namespace: string;\n bufferKey: string;\n isLiveSession: boolean;\n abortSignal?: AbortSignal;\n },\n ): Promise<void> => {\n const deadlineController =\n typeof deadlineMs === \"number\" && Number.isFinite(deadlineMs) ? new AbortController() : undefined;\n const captureSignal = combineExtractionAbortSignals(captureOptions.abortSignal ?? options.abortSignal,\n deadlineController);\n let deadlineTimer: NodeJS.Timeout | undefined;\n if (deadlineController && typeof deadlineMs === \"number\") {\n const scheduleDeadlineAbort = (): void => {\n const remainingMs = deadlineMs - Date.now();\n if (remainingMs <= 0) {\n deadlineController.abort();\n return;\n }\n deadlineTimer = setTimeout(\n () => {\n if (Date.now() >= deadlineMs) {\n deadlineController.abort();\n } else {\n scheduleDeadlineAbort();\n }\n },\n Math.min(remainingMs, 2_147_483_647),\n );\n };\n scheduleDeadlineAbort();\n }\n try {\n await raceRecallAbort(\n this.deps.maybeCapturePassiveCorrections(captureTurns, {\n ...captureOptions,\n ...(captureSignal ? { abortSignal: captureSignal } : {}),\n }),\n captureSignal,\n \"extraction aborted (during_passive_capture)\",\n );\n } catch (error) {\n if (typeof deadlineMs === \"number\" && Date.now() >= deadlineMs) {\n throw new ExtractionDeadlineError(\"during_passive_capture\");\n }\n throw error;\n } finally {\n if (deadlineTimer) clearTimeout(deadlineTimer);\n }\n };\n const clearBuffer = async (clearOptions?: { ignoreAbort?: boolean }) => {\n options.onBeforePersist?.();\n if (clearOptions?.ignoreAbort !== true) {\n throwIfDeadlineExceeded(\"before_clear_buffer\");\n throwIfAborted(\"before_clear_buffer\");\n }\n if (clearBufferAfterExtraction) {\n await this.deps\n .getBuffer()\n .clearAfterExtraction(bufferKey, turns, clearMatchingTurns ? { allowNonPrefix: true } : undefined);\n }\n };\n\n // Skip extraction for cron job sessions - these are system operations, not user conversations\n const sessionKey = turns[0]?.sessionKey ?? \"\";\n if (sessionKey.includes(\":cron:\")) {\n log.debug(`skipping extraction for cron session: ${sessionKey}`);\n await clearBuffer();\n return {\n status: \"skipped\",\n reason: \"cron_session\",\n persistedCount: 0,\n durableOutputCount: 0,\n };\n }\n\n const normalizedTurns = turns\n // #3443: marked duplicate copies ride along for clearing/drop identity only; the representative is already here.\n .filter((t) => t.extractionDuplicateOf !== true)\n .filter((t) => (t.role === \"user\" || t.role === \"assistant\") && typeof t.content === \"string\")\n .map((t) => ({\n ...t,\n content: t.content.trim().slice(0, this.config.extractionMaxTurnChars),\n }))\n .filter((t) => t.content.length > 0);\n const targetTurns = normalizedTurns.filter((turn) => turn.extractionContextOnly !== true);\n if (targetTurns.length === 0) {\n log.debug(\"skipping extraction: no non-context turns after normalization\");\n // Context-only turns may still contain corrections (review: \"context-only\n // turns skip capture\"). Scan normalizedTurns before clearing the buffer.\n if (normalizedTurns.length > 0) {\n throwIfDeadlineExceeded(\"before_context_only_capture\");\n const capturePrincipal =\n typeof options.principalOverride === \"string\" && options.principalOverride.length > 0\n ? options.principalOverride\n : resolvePrincipal(sessionKey, this.config);\n const captureNamespace =\n typeof options.writeNamespaceOverride === \"string\" && options.writeNamespaceOverride.length > 0\n ? options.writeNamespaceOverride\n : this.deps.resolveSelfNamespace(sessionKey);\n await runPassiveCapture(normalizedTurns as BufferTurn[], {\n sessionKey,\n principal: capturePrincipal,\n namespace: captureNamespace,\n bufferKey,\n isLiveSession: clearBufferAfterExtraction,\n });\n throwIfDeadlineExceeded(\"before_context_only_clear\");\n }\n await clearBuffer();\n return { status: \"skipped\", reason: \"empty_normalized_turns\", persistedCount: 0, durableOutputCount: 0 };\n }\n const sourceValidAt = this.latestSourceValidAtFromTurns(targetTurns);\n throwIfDeadlineExceeded(\"before_extract\");\n throwIfAborted(\"before_extract\");\n\n const userTurns = targetTurns.filter((t) => t.role === \"user\");\n const totalChars = targetTurns.reduce((sum, t) => sum + t.content.length, 0);\n const belowCharThreshold = totalChars < this.config.extractionMinChars;\n const belowUserTurnThreshold = !skipUserTurnThreshold && userTurns.length < this.config.extractionMinUserTurns;\n if ((!skipCharThreshold && belowCharThreshold) || belowUserTurnThreshold) {\n log.debug(`skipping extraction: below threshold (totalChars=${totalChars}, userTurns=${userTurns.length})`);\n // Passive correction capture runs even when extraction is skipped for\n // being below the char/user-turn threshold (review: \"skipped extraction\n // skips capture\"). A short correction like \"stop using Vim\" is under\n // extractionMinChars but is exactly the high-value case this feature\n // exists for. The write namespace resolves through the SAME scope-profile\n // plan as the full extraction path so corrections target the active\n // profile's write layer, not just resolveSelfNamespace (review:\n // \"below-threshold wrong namespace\"). The ACL in passiveCorrectionService\n // authorizes the actual plan/apply.\n {\n const capturePrincipal =\n typeof options.principalOverride === \"string\" && options.principalOverride.length > 0\n ? options.principalOverride\n : resolvePrincipal(sessionKey, this.config);\n const captureWO =\n typeof options.writeNamespaceOverride === \"string\" && options.writeNamespaceOverride.length > 0\n ? options.writeNamespaceOverride\n : undefined;\n const captureCodingCtx = sessionKey ? this.deps.getCodingContextForSession(sessionKey) : null;\n const captureCodingOv = resolveCodingNamespaceOverlay(\n captureCodingCtx,\n this.config.codingMode,\n this.config.defaultNamespace\n );\n const captureScopePlan = resolveScopeProfilePlan({\n config: this.config,\n principal: capturePrincipal,\n codingContext: captureCodingCtx,\n codingOverlay: captureCodingOv,\n });\n const captureNamespace =\n captureWO ?? captureScopePlan?.writeNamespace ?? this.deps.resolveSelfNamespace(sessionKey);\n await runPassiveCapture(normalizedTurns as BufferTurn[], {\n sessionKey,\n principal: capturePrincipal,\n namespace: captureNamespace,\n bufferKey,\n isLiveSession: clearBufferAfterExtraction,\n });\n }\n await clearBuffer();\n return {\n status: \"skipped\",\n reason: \"below_threshold\",\n persistedCount: 0,\n durableOutputCount: 0,\n };\n }\n\n // Provenance principal honours the access-surface override (#1495 thread 1,\n // mirroring the recall path's `principalOverride`, issue #570 PR 4). Access\n // surfaces that authenticated the caller at the transport layer pass their\n // resolved principal so provenance uses the SAME identity the surface\n // authorized, instead of `resolvePrincipal(sessionKey)` — which on a\n // namespace-prefixed key would collapse to `default`. The ORIGINAL,\n // un-prefixed session key still drives threading.\n const principal =\n typeof options.principalOverride === \"string\" && options.principalOverride.length > 0\n ? options.principalOverride\n : resolvePrincipal(sessionKey, this.config);\n // Write path — explicit callers still win. Otherwise, an active hosted\n // scope profile owns the extraction write target so hook-captured turns land\n // in the same layer that profile recall searches. Without a profile, preserve\n // the existing coding-agent overlay behavior (issue #569).\n const explicitWriteNamespace =\n typeof options.writeNamespaceOverride === \"string\" && options.writeNamespaceOverride.length > 0\n ? options.writeNamespaceOverride\n : undefined;\n const codingContextForWrite = sessionKey ? this.deps.getCodingContextForSession(sessionKey) : null;\n const codingOverlayForWrite = resolveCodingNamespaceOverlay(\n codingContextForWrite,\n this.config.codingMode,\n this.config.defaultNamespace\n );\n const scopeProfileGatePlan =\n options.scopeProfileWritePlan !== undefined\n ? options.scopeProfileWritePlan\n : resolveScopeProfilePlan({\n config: this.config,\n principal,\n codingContext: codingContextForWrite,\n codingOverlay: codingOverlayForWrite,\n });\n const scopeProfileWritePlan =\n explicitWriteNamespace && options.scopeProfileWritePlan === undefined\n ? null\n : scopeProfileGatePlan;\n if (scopeProfileWritePlan) {\n const selectedLayer = scopeProfileWritePlan.layers.find((layer) => layer.id === scopeProfileWritePlan.writeLayer);\n const writeNamespaceReadable = scopeProfileWritePlan.readNamespaces.includes(\n scopeProfileWritePlan.writeNamespace\n );\n if (!selectedLayer?.writable || !writeNamespaceReadable) {\n log.warn(\n `runExtraction: skipping scope profile ${scopeProfileWritePlan.profileId} because write layer ${scopeProfileWritePlan.writeLayer} is not writable inside the profile read stack`\n );\n // Policy refusal (same family as namespace_write_revoked): the window\n // stays in the buffer/claim pending a later attempt. Clearing here\n // would destroy content policy never wrote — the claim drain would\n // erase denied backlog and ack it as drained.\n return {\n status: \"skipped\",\n reason: \"scope_profile_no_writable_layer\",\n retainedBuffer: true,\n persistedCount: 0,\n durableOutputCount: 0,\n };\n }\n }\n const selfNamespace =\n explicitWriteNamespace ??\n scopeProfileWritePlan?.writeNamespace ??\n this.deps.applyCodingNamespaceOverlay(sessionKey, defaultNamespaceForPrincipal(principal, this.config));\n const extractionDeadlineController =\n typeof deadlineMs === \"number\" && Number.isFinite(deadlineMs)\n ? new AbortController()\n : undefined;\n const shutdownSignal = this.deps.shutdownSignal;\n const callerAbortSignal =\n options.abortSignal && shutdownSignal\n ? AbortSignal.any([options.abortSignal, shutdownSignal])\n : (options.abortSignal ?? shutdownSignal);\n const extractionAbortSignal = extractionDeadlineController\n ? callerAbortSignal\n ? AbortSignal.any([callerAbortSignal, extractionDeadlineController.signal])\n : extractionDeadlineController.signal\n : callerAbortSignal;\n let extractionDeadlineTimer: NodeJS.Timeout | undefined;\n const clearExtractionDeadlineTimer = (): void => {\n if (extractionDeadlineTimer) {\n clearTimeout(extractionDeadlineTimer);\n extractionDeadlineTimer = undefined;\n }\n };\n const runDeadlineAware = async <T>(\n operation: () => Promise<T>,\n phase: string,\n clearTimerOnError = true,\n options: { ignoreAbort?: boolean; ignoreDeadline?: boolean } = {},\n ): Promise<T> => {\n const operationSignal = options.ignoreAbort ? undefined : extractionAbortSignal;\n try {\n if (!options.ignoreDeadline && typeof deadlineMs === \"number\" && Date.now() >= deadlineMs) {\n throwIfDeadlineExceeded(phase);\n }\n if (operationSignal?.aborted) {\n throwIfAborted(phase);\n }\n return await raceRecallAbort(\n operation(),\n operationSignal,\n `extraction aborted (${phase})`,\n );\n } catch (error) {\n if (clearTimerOnError) clearExtractionDeadlineTimer();\n if (!options.ignoreDeadline && typeof deadlineMs === \"number\" && Date.now() >= deadlineMs) {\n throw new ExtractionDeadlineError(phase);\n }\n throw error;\n }\n };\n if (extractionDeadlineController && typeof deadlineMs === \"number\") {\n const deadline = deadlineMs;\n const maxTimerDelayMs = 2_147_483_647;\n const scheduleDeadlineAbort = (): void => {\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) {\n extractionDeadlineController.abort();\n return;\n }\n extractionDeadlineTimer = setTimeout(() => {\n if (Date.now() >= deadline) {\n extractionDeadlineController.abort();\n } else {\n scheduleDeadlineAbort();\n }\n }, Math.min(remainingMs, maxTimerDelayMs));\n };\n scheduleDeadlineAbort();\n }\n const storage = await runDeadlineAware(\n () => this.deps.getStorageRouter().storageFor(selfNamespace),\n \"during_storage\",\n );\n const shouldPersistProcessedFingerprint = targetTurns.some((turn) => turn.persistProcessedFingerprint === true);\n const extractionFingerprint = this.buildExtractionFingerprint(targetTurns, bufferKey);\n let meta = extractionFingerprint && shouldPersistProcessedFingerprint\n ? await runDeadlineAware(() => storage.loadMeta(), \"during_load_meta\")\n : null;\n if (\n extractionFingerprint &&\n shouldPersistProcessedFingerprint &&\n (meta?.processedExtractionFingerprints ?? []).some((entry) => entry.fingerprint === extractionFingerprint)\n ) {\n await runDeadlineAware(() => clearBuffer(), \"during_clear_buffer\");\n clearExtractionDeadlineTimer();\n return {\n status: \"skipped\",\n reason: \"processed_fingerprint\",\n persistedCount: 0,\n durableOutputCount: 0,\n };\n }\n\n // Extraction retry/backoff + circuit-breaker gate (extraction hot-loop\n // hardening). Suppresses re-attempts of a recently-failed fingerprint and\n // short-circuits every fingerprint while the provider breaker is open, so a\n // failing LLM endpoint is not hammered once per observe. Forced flushes and\n // fail-closed callers bypass the gate (rule 18) but still record failures.\n // On a suppressed attempt the buffer is deliberately NOT cleared, so no\n // extractable turn is dropped — it is retried after cooldown/nextEligibleAt.\n const forcedExtractionAttempt =\n options.failOnExtractionFailure === true || options.forceExtractionAttempt === true;\n // Resolve the gate through the shared lifecycle capability plan (issue\n // #1523) rather than reading the raw config flag at each call site.\n const extractionRetryEnabled = resolveMemoryLifecycleCapabilities(this.config).extractionRetry;\n let extractionProbeOwned = false;\n let extractionProbeToken: ProbeOwnerToken | undefined;\n if (extractionFingerprint && !forcedExtractionAttempt && extractionRetryEnabled) {\n try {\n meta ??= await runDeadlineAware(() => storage.loadMeta(), \"during_retry_gate\");\n this.hydrateRetryStateFromMeta(selfNamespace, meta);\n const nowMs = Date.now();\n const probeAttempt = this.providerBreaker.acquire(nowMs);\n extractionProbeOwned = probeAttempt.probe;\n extractionProbeToken = probeAttempt.token;\n let suppressReason: \"provider_circuit_open\" | \"extraction_backoff\" | null = null;\n if (probeAttempt.suppressed) {\n suppressReason = \"provider_circuit_open\";\n } else {\n const st = this.extractionRetryState.get(selfNamespace)?.get(extractionFingerprint);\n if (st && nowMs < st.nextEligibleAtMs) suppressReason = \"extraction_backoff\";\n }\n if (suppressReason) {\n // Passive correction capture is local and must not be delayed by a\n // provider cooldown. It remains fail-open.\n try {\n await runDeadlineAware(\n () => runPassiveCapture(normalizedTurns as BufferTurn[], {\n sessionKey,\n principal,\n namespace: selfNamespace,\n bufferKey,\n isLiveSession: clearBufferAfterExtraction,\n }),\n \"during_passive_capture\",\n );\n } catch (captureErr) {\n if (captureErr instanceof ExtractionDeadlineError) throw captureErr;\n log.warn(\"runExtraction: passive correction capture failed on suppressed attempt (non-fatal)\", captureErr);\n }\n clearExtractionDeadlineTimer();\n // Backoff suppression exits inside the gate, before the wrapper\n // finally: release an acquired probe here (codex follow-up) so a\n // cooldown-expired fingerprint cannot pin the breaker half_open.\n if (extractionProbeOwned) this.providerBreaker.releaseProbe(extractionProbeToken);\n return { status: \"skipped\", reason: suppressReason, persistedCount: 0, durableOutputCount: 0 };\n }\n } catch (err) {\n if (err instanceof ExtractionDeadlineError) throw err;\n // Fail-open: a gate error must never block extraction.\n log.warn(\"runExtraction: extraction retry gate check failed; proceeding (fail-open)\", err);\n }\n }\n // Pass existing entity names so the LLM can reuse them instead of inventing variants.\n // The probe owner must release on ANY pre-persistence exit too (codex P1):\n // the big try below only covers from the extract call onward.\n try {\n const existingEntities = await runDeadlineAware(\n () => storage.listEntityNames(),\n \"during_list_entity_names\",\n );\n let result: ExtractionResult;\n // The half-open probe is bounded: one that gets no answer in time counts as\n // a provider failure (re-opens the breaker) instead of holding every other\n // attempt until the provider answers or times out.\n const probe = startProbeDeadline(extractionProbeOwned, extractionAbortSignal, this.deps.halfOpenProbeTimeoutMs);\n const engine = this.deps.getExtraction();\n try {\n result = await raceRecallAbort(\n extractChunkedExtraction(engine, this.config, normalizedTurns, existingEntities, probe.signal),\n probe.signal,\n \"extraction aborted (during_extract)\",\n );\n } catch (error) {\n const pastDeadline = deadlineMs !== undefined && Date.now() >= deadlineMs;\n // Keep the caller deadline timer running while a probe timeout is turned into a failure result.\n if (pastDeadline || !probe.timedOut()) clearExtractionDeadlineTimer();\n if (pastDeadline) throw new ExtractionDeadlineError(\"during_extract\");\n if (!probe.timedOut()) throw error;\n log.warn(\"runExtraction: half-open probe got no answer in time; treating it as a provider failure\");\n result = probeTimedOutResult();\n } finally {\n probe.stop();\n }\n try {\n throwIfDeadlineExceeded(\"before_persist\");\n throwIfAborted(\"before_persist\");\n\n // Defensive: validate extraction result before processing. Explicit\n // fail-closed callers, such as flush-plan import, must not observe\n // malformed extractor output as a successful skip.\n if (!result) {\n log.warn(\"runExtraction: extraction returned null/undefined\");\n if (options.failOnExtractionFailure) {\n throw new Error(\"extraction failed: invalid_extraction_result\");\n }\n // Actual extraction failure: the window is retained for a retry (same\n // no-drop contract as a recorded provider failure), never destroyed.\n return {\n status: \"skipped\",\n reason: \"invalid_extraction_result\",\n retainedBuffer: true,\n failureClass: \"parse_empty\",\n persistedCount: 0,\n durableOutputCount: 0,\n };\n }\n const invalidExtractionResultFields = [\n [\"facts\", result.facts],\n [\"entities\", result.entities],\n [\"questions\", result.questions],\n [\"profileUpdates\", result.profileUpdates],\n ]\n .filter(([, value]) => !Array.isArray(value))\n .map(([field]) => field);\n if (invalidExtractionResultFields.length > 0) {\n log.warn(\"runExtraction: extraction returned invalid collection fields\", {\n invalidFields: invalidExtractionResultFields,\n resultKeys: typeof result === \"object\" && result !== null ? Object.keys(result) : [],\n });\n if (options.failOnExtractionFailure) {\n throw new Error(\"extraction failed: invalid_extraction_result\");\n }\n // Actual extraction failure: the window is retained for a retry (same\n // no-drop contract as a recorded provider failure), never destroyed.\n return {\n status: \"skipped\",\n reason: \"invalid_extraction_result\",\n retainedBuffer: true,\n failureClass: \"parse_empty\",\n persistedCount: 0,\n durableOutputCount: 0,\n };\n }\n const extractionFailure =\n typeof result.extractionFailure === \"string\" && result.extractionFailure.trim().length > 0\n ? result.extractionFailure\n : undefined;\n // Issue #3140: surface extraction-LLM outages on /health and as an\n // ERROR-level deduplicated event instead of debug-only lines. Records on\n // every completed attempt so a later success clears the failure.\n if (extractionFailure) {\n recordExtractionLlmFailure(extractionFailure);\n emitExtractionLlmFailureError(extractionFailure, result.extractionFailureClass);\n } else if (result.extractionSkippedReason !== undefined) {\n // Prefiltered batch: no LLM was contacted, so we cannot confirm or deny\n // reachability. Do not clear the outage state.\n } else {\n recordExtractionLlmSuccess();\n }\n let recordedRetryFailure = false;\n // Record failure into backoff/breaker state, or heal on success. Runs for\n // every result path (empty and durable), before the fail-closed throw, so a\n // forced flush still records its failure (rule 18). Gated by\n // extractionRetryEnabled so a disabled feature restores prior behavior.\n if (extractionFingerprint && extractionRetryEnabled) {\n if (extractionFailure) {\n const failureClass = result.extractionFailureClass ?? \"provider_retryable\";\n try {\n await runDeadlineAware(\n () =>\n storage.updateMeta((freshMeta) =>\n this.recordExtractionFailure(selfNamespace, extractionFingerprint, failureClass, freshMeta, Date.now(), extractionProbeToken),\n ),\n \"during_retry_bookkeeping_save\",\n false,\n );\n recordedRetryFailure = true;\n } catch (err) {\n if (err instanceof ExtractionDeadlineError) throw err;\n // Fail-open, but retain the turns (a cleared buffer with no retry state drops them). Only a\n // LOCK skip reaches here without the mutator having run — a later save must not double-count.\n if (err instanceof Error && err.message.includes(\"meta.json.lock not acquired\"))\n this.applyExtractionFailureToMemory(selfNamespace, extractionFingerprint, failureClass, Date.now(), extractionProbeToken);\n recordedRetryFailure = true;\n log.warn(\"runExtraction: retry state kept in memory; meta persist will catch up\", err);\n }\n } else if (result.extractionSkippedReason === undefined) {\n // Provider responded without failure → breaker heals; clear any\n // parked backoff for this fingerprint so it proceeds normally.\n // PRRT_kwDORJXyws6zxG6u: pass the run's probe token so the settlement\n // only applies to a probe this run owns.\n this.providerBreaker.success(extractionProbeToken);\n try {\n await runDeadlineAware(\n () =>\n storage.updateMeta((freshMeta) => {\n // Hydrate the mirror from persisted meta before clearing: a forced flush\n // bypassed the retry gate, and a stale persisted entry would keep blocking.\n this.hydrateRetryStateFromMeta(selfNamespace, freshMeta);\n // `false` skips the save when nothing was parked for this fingerprint.\n return this.clearExtractionRetryEntry(selfNamespace, extractionFingerprint, freshMeta);\n }),\n \"during_retry_bookkeeping_save\",\n false,\n );\n } catch (err) {\n if (err instanceof ExtractionDeadlineError) throw err;\n log.warn(\"runExtraction: failed to persist cleared retry state (non-fatal)\", err);\n }\n }\n }\n if (options.failOnExtractionFailure && extractionFailure) {\n throw new Error(`extraction failed: ${extractionFailure}`);\n }\n // #3227: one count covers every enabled durable output kind, so a\n // reflection-only or relationship-only result reaches persistence.\n const durableOutputCount = countRequestedDurableOutputs(result, this.config);\n if (durableOutputCount === 0) {\n log.debug(\"runExtraction: extraction produced no durable outputs; skipping persistence\");\n if (extractionFailure) {\n log.warn(\n \"runExtraction: extraction reported failure with no durable outputs; not marking fingerprint processed\",\n { extractionFailure }\n );\n }\n const emptySuccessCommit = {\n storage,\n extractionFingerprint,\n shouldPersistProcessedFingerprint,\n hasExtractionFailure: Boolean(extractionFailure),\n extractionSkippedReason: result.extractionSkippedReason,\n recordProcessedExtractionFingerprint: this.deps.recordProcessedExtractionFingerprint,\n runDeadlineAware,\n isDeadlineError: (error: unknown) => error instanceof ExtractionDeadlineError,\n };\n if (shouldPersistProcessedFingerprint) {\n await commitEmptySuccessExtraction(emptySuccessCommit);\n }\n await runPassiveCapture(normalizedTurns as BufferTurn[], {\n sessionKey,\n principal,\n namespace: selfNamespace,\n bufferKey,\n isLiveSession: clearBufferAfterExtraction,\n });\n // Issue #3415: retention follows the actual extraction failure, not the\n // retry bookkeeping. With retry disabled no backoff state is recorded,\n // but the failed turns are still kept for the next attempt — clearing\n // them is silent loss. A successful empty result still clears below.\n if (extractionFailure) {\n log.debug(\"runExtraction: retaining buffer after failed extraction\", { extractionFailure });\n } else {\n await clearBuffer();\n }\n if (!shouldPersistProcessedFingerprint) {\n await commitEmptySuccessExtraction(emptySuccessCommit);\n }\n return emptyExtractionResult(Boolean(extractionFailure), result.extractionFailureClass);\n }\n\n let threadIdForExtraction: string | null = null;\n if (resolvePresentationCapabilities(this.config).threading && turns.length > 0) {\n const lastTurn = turns[turns.length - 1];\n try {\n threadIdForExtraction = await runDeadlineAware(\n () => this.deps.getThreading().processTurn(lastTurn, []),\n \"during_threading\",\n );\n } catch (err) {\n if (err instanceof ExtractionDeadlineError) throw err;\n // Fail-open: threading errors must not block memory persistence.\n log.warn(\"[threading] processTurn failed before persistence (non-fatal)\", err);\n }\n }\n const originContext = deriveExtractionOriginContext(targetTurns, result.sourceConnector);\n options.onBeforePersist?.();\n throwIfDeadlineExceeded(\"before_persist\");\n throwIfAborted(\"before_persist\");\n\n const { persistedIds, deferredCount, pendingReviewIds } = await this.deps.persistExtraction(\n result,\n storage,\n threadIdForExtraction,\n { sessionKey, principal, validAt: sourceValidAt, ...originContext },\n // Pass the KNOWN base namespace (NHIdx) so the catalog write touch records the\n // real namespace rather than a guess decoded from the storage dir.\n selfNamespace,\n scopeProfileWritePlan,\n // Verbatim source turns for the faithfulness gate (#1576) so it can\n // locate a quote per fact when #1575 spans are absent.\n normalizedTurns\n .map((t) => t.content)\n .join(\"\\n\\n\")\n );\n try {\n options.onDurableCommit?.();\n } catch (error) {\n log.warn(\"runExtraction: durable-commit callback failed\", error);\n }\n const runPostPersistBestEffort = runExtractionPostPersistBestEffort.bind(null, runDeadlineAware);\n await tagPersistedMemories(storage, persistedIds, this.config);\n const postPersist = await runExtractionPostPersist({\n result,\n storage,\n extractionFingerprint: extractionFingerprint ?? undefined,\n shouldPersistProcessedFingerprint,\n recordProcessedExtractionFingerprint: this.deps.recordProcessedExtractionFingerprint,\n runDeadlineAware,\n isDeadlineError: (error) => error instanceof ExtractionDeadlineError,\n createDeadlineError: (stage) => new ExtractionDeadlineError(stage),\n deadlineMs,\n clearBufferAfterExtraction,\n runPostPersistBestEffort,\n extractionJudgeShadow: this.config.extractionJudgeShadow,\n deferredCount,\n normalizedTurns: normalizedTurns as BufferTurn[],\n bufferKey,\n retainDeferredTurns: (key, retainedTurns, max) =>\n this.deps.getBuffer().retainDeferredTurns(key, retainedTurns, max, options.retentionWindow ?? turns),\n clearBuffer,\n failOnExtractionFailure: options.failOnExtractionFailure === true,\n });\n const postPersistMetadataFailed = postPersist.metadataFailed;\n\n // Passive correction capture (issue #1581) — detect corrections expressed\n // passively in the extracted turns and route to the Correction Contract.\n // Runs AFTER persistence + buffer clear so a capture failure never blocks\n // the extraction return. `clearBufferAfterExtraction` gates live-session\n // auto-apply (replay/import → queue-only).\n await runPostPersistBestEffort(\"during_post_persist_passive_capture\", () =>\n runPassiveCapture(normalizedTurns as BufferTurn[], {\n sessionKey,\n principal,\n namespace: selfNamespace,\n bufferKey,\n isLiveSession: clearBufferAfterExtraction,\n abortSignal: extractionAbortSignal,\n }),\n );\n\n // Build memory box from this extraction (v8.0 Phase 2A)\n // Topics are derived from the current extraction's facts and entities only —\n // not from readAllMemories() — so box topics accurately reflect the current\n // session window and the call is free of expensive full-corpus I/O.\n if (resolvePresentationCapabilities(this.config).memoryBoxes && persistedIds.length > 0) {\n const extractionTopics = deriveTopicsFromExtraction(result);\n // Derive episodic metadata from buffer turns (REMem-inspired)\n const firstUserTurn = turns.find((t) => t.role === \"user\");\n const boxGoal = firstUserTurn?.content?.slice(0, 100)?.trim() || undefined;\n await runPostPersistBestEffort(\"during_memory_box\", () =>\n this.deps.boxBuilderFor(storage).onExtraction({\n topics: extractionTopics,\n memoryIds: persistedIds,\n timestamp: new Date().toISOString(),\n goal: boxGoal,\n }),\n );\n }\n\n // Batch-append persisted IDs so non-fact memories (entities/questions) are\n // always attached to the thread. The helper excludes pending_review ids (#1635).\n if (resolvePresentationCapabilities(this.config).threading && threadIdForExtraction && persistedIds.length > 0) {\n await runPostPersistBestEffort(\"during_thread_episode_append\", () =>\n this.deps.appendPersistedThreadEpisodes(threadIdForExtraction, persistedIds, pendingReviewIds),\n );\n }\n\n // Thread title update for the already-established thread context.\n if (resolvePresentationCapabilities(this.config).threading && threadIdForExtraction) {\n const conversationContent = turns.map((t) => t.content).join(\" \");\n await runPostPersistBestEffort(\"during_thread_title_update\", () =>\n this.deps.getThreading().updateThreadTitle(threadIdForExtraction, conversationContent),\n );\n }\n\n // Check if consolidation is needed (debounced + non-zero gated).\n const nonZeroExtraction = durableOutputCount > 0;\n try {\n // The increment of nonZeroExtractionsSinceConsolidation moved into\n // the scheduler with the rest of the cadence state (issue #1526 PR1).\n this.deps.maybeScheduleConsolidation(nonZeroExtraction);\n } catch (err) {\n log.warn(\"runExtraction: consolidation scheduling failed after persistence (non-fatal)\", err);\n }\n\n try {\n this.deps.requestQmdMaintenance();\n } catch (err) {\n log.warn(\"runExtraction: QMD maintenance scheduling failed after persistence (non-fatal)\", err);\n }\n\n await runPostPersistBestEffort(\"during_tier_migration\", () =>\n this.deps.runTierMigrationCycle(storage, \"extraction\"),\n );\n\n return {\n status: \"completed\",\n persistedCount: persistedIds.length,\n durableOutputCount,\n postPersistMetadataFailed,\n };\n } finally {\n clearExtractionDeadlineTimer();\n }\n } finally {\n // The half-open probe is OWNED, not timed: the WRAPPER finally releases\n // it on every exit path, including pre-persistence ones (codex P1) that\n // never reach the inner try above.\n if (extractionProbeOwned) this.providerBreaker.releaseProbe(extractionProbeToken);\n }\n }\n}\n","/**\n * Derive issue #1955 origin metadata at the extraction boundary.\n */\n\nimport { classifyOrigin, type OriginClass } from \"../security/origin-authority.js\";\nimport type { BufferTurn } from \"../types.js\";\n\nexport interface ExtractionSourceContext {\n sessionKey?: string;\n principal?: string;\n validAt?: string;\n sourceConnector?: string;\n turnRole?: \"user\" | \"assistant\" | \"tool\" | string;\n importAdapter?: string;\n originConflict?: boolean;\n}\n\n/** Derive one origin context from the turns that supplied an extraction. */\nexport function deriveExtractionOriginContext(\n targetTurns: readonly BufferTurn[],\n fallbackConnector?: string,\n): Pick<ExtractionSourceContext, \"turnRole\" | \"importAdapter\" | \"sourceConnector\" | \"originConflict\"> {\n const originRoles = new Set(targetTurns.map((turn) => turn.originRole ?? turn.role));\n const turnRole = originRoles.size === 1 ? [...originRoles][0] : undefined;\n const originConnectors = new Set(\n targetTurns\n .map((turn) => turn.sourceConnector)\n .filter((connector): connector is string => typeof connector === \"string\" && connector.length > 0),\n );\n // Mirror the pre-#1955 provenance rule: a batch only carries a connector\n // when EVERY turn is tagged with the same one — a mixed tagged+untagged\n // batch must stay connector-less (connector-provenance-lifecycle tests).\n const connector =\n targetTurns.length > 0 &&\n targetTurns.every(\n (turn) => typeof turn.sourceConnector === \"string\" && turn.sourceConnector.length > 0,\n ) &&\n originConnectors.size === 1\n ? [...originConnectors][0]\n : undefined;\n const originAdapters = new Set(\n targetTurns\n .map((turn) => turn.importProvenance?.sourceLabel)\n .filter((adapter): adapter is string => typeof adapter === \"string\" && adapter.length > 0),\n );\n // Conflict when identities disagree OR are only partially present: a batch\n // where some turns carry an import label (or connector) and others do not\n // must classify as unknown, never fall back to the uniform turn role\n // (#1955 review: mixed import labels previously became `user`).\n const everyTurnHasConnector =\n targetTurns.length > 0 &&\n targetTurns.every((turn) => typeof turn.sourceConnector === \"string\" && turn.sourceConnector.length > 0);\n const everyTurnHasAdapter =\n targetTurns.length > 0 &&\n targetTurns.every(\n (turn) => typeof turn.importProvenance?.sourceLabel === \"string\" && turn.importProvenance.sourceLabel.length > 0,\n );\n const originConflict =\n originConnectors.size > 1 ||\n originAdapters.size > 1 ||\n (originConnectors.size > 0 && originAdapters.size > 0) ||\n (originConnectors.size > 0 && !everyTurnHasConnector) ||\n (originAdapters.size > 0 && !everyTurnHasAdapter);\n const importAdapter =\n targetTurns.length > 0 &&\n targetTurns.every(\n (turn) =>\n typeof turn.importProvenance?.sourceLabel === \"string\" &&\n turn.importProvenance.sourceLabel.length > 0,\n ) &&\n originAdapters.size === 1\n ? [...originAdapters][0]\n : undefined;\n return {\n ...(turnRole ? { turnRole } : {}),\n ...(importAdapter ? { importAdapter } : {}),\n ...(originConflict ? { originConflict: true } : {}),\n sourceConnector: fallbackConnector ?? connector,\n };\n}\n\n/** Classify the persisted origin without reading config flags. */\nexport function classifyExtractionOrigin(sourceContext?: ExtractionSourceContext): OriginClass {\n if (sourceContext?.originConflict === true) return \"unknown\";\n return classifyOrigin({\n turnRole: sourceContext?.turnRole,\n connectorId: sourceContext?.sourceConnector,\n importAdapter: sourceContext?.importAdapter,\n });\n}\n","import type { ExtractionResult } from \"../types.js\";\nimport { HALF_OPEN_PROBE_TIMEOUT_MS } from \"./provider-breaker.js\";\n\nexport interface ProbeDeadline {\n /** The caller's signal, plus the probe timer's when this attempt owns the probe. */\n readonly signal: AbortSignal | undefined;\n /** True only when the probe timer fired (not when the caller aborted). */\n timedOut(): boolean;\n stop(): void;\n}\n\n/** Bounds the single half-open probe; any other attempt keeps the caller's signal and no timer. */\nexport function startProbeDeadline(\n probeOwned: boolean,\n callerSignal: AbortSignal | undefined,\n timeoutMs: number = HALF_OPEN_PROBE_TIMEOUT_MS,\n): ProbeDeadline {\n if (!probeOwned) return { signal: callerSignal, timedOut: () => false, stop: () => undefined };\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), timeoutMs);\n return {\n signal: callerSignal ? AbortSignal.any([callerSignal, timeout.signal]) : timeout.signal,\n timedOut: () => timeout.signal.aborted,\n stop: () => clearTimeout(timer),\n };\n}\n\n/** What a probe that got no answer in time reports: the ordinary retryable provider failure. */\nexport function probeTimedOutResult(): ExtractionResult {\n return {\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n extractionFailure: \"local_llm_unavailable\",\n extractionFailureClass: \"provider_retryable\",\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcO,SAAS,6BAA6B,QAA0B,QAA8B;AACnG,QAAM,eAAe,qCAAqC,MAAM;AAChE,QAAM,gBACJ,aAAa,uBAAuB,MAAM,QAAQ,OAAO,aAAa,IAClE,OAAO,cAAc,OAAO,CAAC,QAAQ,QAAQ,KAAK,UAAU,IAAI,UAAU,IAAI,KAAK,CAAC,EAAE,SACtF;AACN,QAAM,aAAa,aAAa,aAAa,OAAO,sBAAsB,IAA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AK,GAAG;AAChE,gBAAM;AAAA,YAAyB;AAAA,YAA8B,MAC3D,KAAK,KAAK,aAAa,EAAE,kBAAkB,uBAAuB,mBAAmB;AAAA,UACvF;AAAA,QACF;AAGA,cAAM,oBAAoB,qBAAqB;AAC/C,YAAI;AAGF,eAAK,KAAK,2BAA2B,iBAAiB;AAAA,QACxD,SAAS,KAAK;AACZ,cAAI,KAAK,gFAAgF,GAAG;AAAA,QAC9F;AAEA,YAAI;AACF,eAAK,KAAK,sBAAsB;AAAA,QAClC,SAAS,KAAK;AACZ,cAAI,KAAK,kFAAkF,GAAG;AAAA,QAChG;AAEA,cAAM;AAAA,UAAyB;AAAA,UAAyB,MACtD,KAAK,KAAK,sBAAsB,SAAS,YAAY;AAAA,QACvD;AAEA,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,gBAAgB,aAAa;AAAA,UAC7B;AAAA,UACA;AAAA,QACF;AAAA,MACA,UAAE;AACA,qCAA6B;AAAA,MAC/B;AAAA,IACA,UAAE;AAIA,UAAI,qBAAsB,MAAK,gBAAgB,aAAa,oBAAoB;AAAA,IAClF;AAAA,EACF;AACF;","names":["connector","options"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/local-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport { isUnsupportedJsonSchemaError } from \"./fallback-llm-codex-subscription.js\";\nimport { estimateTokenCount } from \"./token-estimate.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport { launchProcessSync } from \"./runtime/child-process.js\";\nimport { mergeEnv, readEnvVar } from \"./runtime/env.js\";\nimport { resolveLocalLlmCapabilities, resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\nimport { ChatTransport } from \"./local-llm-transport.js\";\nimport { LocalLlmRateLimitSession, resolveRateLimitSettings, isTerminalLocalLlmProxyPoolError } from \"./local-llm-rate-limit.js\";\nimport {\n extractNonRecoverableBackendReason,\n extractNonRecoverableBackendReasonFromErrorText,\n isAbortError,\n probeFetch,\n resolveUnavailableVerdict,\n type ProbeFetchResult,\n normalizeBackendTripReason,\n waitForRetryBackoff,\n combineClientAbortSignals,\n SingleFlightProbe,\n buildLocalLlmRoutingHeaders,\n formatLocalLlmPoolKey,\n localLlmBackendPoolExpiredAtMs,\n getLocalLlmTrippedBackendPoolState,\n markLocalLlmBackendPoolUnavailable,\n type LocalLlmChatCompletionOptions,\n type LocalLlmChatCompletionResult,\n} from \"./local-llm-helpers.js\";\nimport { NativeSchemaGate, type LocalLlmChatRequestBody } from \"./local-llm-native-schema.js\";\nimport {\n isObjectRecord,\n orderedLocalServers,\n type LocalLlmType,\n} from \"./local-llm-servers.js\";\n\nexport type { LocalLlmType } from \"./local-llm-servers.js\";\n\n/** Trim trailing slash characters without backtracking regex. */\nfunction trimTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s[end - 1] === \"/\") end--;\n return s.substring(0, end);\n}\n\nfunction stripTrailingV1Path(s: string): string {\n return s.endsWith(\"/v1\") ? s.slice(0, -3) : s;\n}\n\nfunction isLlamaCppPropsResponse(value: unknown): boolean {\n return (\n isObjectRecord(value) &&\n isObjectRecord(value.default_generation_settings) &&\n typeof value.total_slots === \"number\" &&\n (\n typeof value.model_path === \"string\" ||\n typeof value.chat_template === \"string\" ||\n typeof value.build_info === \"string\"\n )\n );\n}\n\nfunction isLlamaCppModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.data)) {\n return false;\n }\n return value.data.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n if (entry.owned_by === \"llamacpp\") return true;\n if (typeof entry.id === \"string\" && entry.id.endsWith(\".gguf\")) return true;\n const meta = entry.meta;\n return (\n isObjectRecord(meta) &&\n (\"n_ctx_train\" in meta || \"n_params\" in meta || \"vocab_type\" in meta)\n );\n });\n}\n\nfunction isLmStudioApiV1ModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.models)) {\n return false;\n }\n return value.models.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n return (\n typeof entry.key === \"string\" &&\n typeof entry.display_name === \"string\" &&\n (\n typeof entry.format === \"string\" ||\n typeof entry.max_context_length === \"number\" ||\n Array.isArray(entry.loaded_instances)\n )\n );\n });\n}\n\nfunction isLmStudioApiV0ModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.data)) {\n return false;\n }\n return value.data.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n return (\n typeof entry.id === \"string\" &&\n typeof entry.publisher === \"string\" &&\n (\n typeof entry.compatibility_type === \"string\" ||\n typeof entry.max_context_length === \"number\" ||\n typeof entry.state === \"string\"\n )\n );\n });\n}\n\nfunction isLmStudioNativeModelsResponse(value: unknown): boolean {\n return isLmStudioApiV1ModelsResponse(value) || isLmStudioApiV0ModelsResponse(value);\n}\n\n/**\n * Backends known to honor `chat_template_kwargs: { enable_thinking: false }`\n * on OpenAI-compatible `/v1/chat/completions`. LM Studio, vLLM, and\n * llama.cpp forward this field to the jinja chat template, where thinking-capable\n * models (Qwen 3.5, Gemma 4, DeepSeek) suppress reasoning tokens.\n *\n * Strict OpenAI-compatible backends (standard OpenAI, Azure OpenAI, some\n * proxies) reject unknown request fields with 400 — which trips the\n * `localLlm400*` cooldown path. `LocalLlmClient` therefore only injects\n * the kwarg when the detected backend is in this set; unknown / `generic`\n * / `ollama` / `mlx` fail open (no injection, no 400 risk). Issue #548.\n */\nconst THINKING_COMPATIBLE_BACKENDS: ReadonlySet<LocalLlmType> = new Set([\n \"lmstudio\",\n \"vllm\",\n \"llamacpp\",\n]);\n\nconst THINKING_SUPPRESSED_OPERATIONS: ReadonlySet<string> = new Set([\n \"extraction\",\n \"extraction-judge\",\n \"extraction-faithfulness\",\n \"contradiction-judge\",\n \"contradiction_verification\",\n \"link_suggestion\",\n \"memory_summarization\",\n \"proactive_extraction\",\n \"lcm-summarize\",\n \"day_summary\",\n \"hourly_summary\",\n \"hourly_summary_extended\",\n \"correction-classify\",\n]);\n\nexport interface LocalModelInfo {\n id: string;\n contextWindow?: number;\n maxTokens?: number;\n}\n\nexport type LocalLlmRequestPriority = \"recall-critical\" | \"background\";\n\n// LocalLlmChatCompletionOptions and LocalLlmChatCompletionResult live in\n// local-llm-helpers.ts so this file stays under its size ceiling (#1995).\ninterface LocalLlmQueuedRequest {\n messages: Array<{ role: string; content: string }>;\n options: LocalLlmChatCompletionOptions;\n priority: LocalLlmRequestPriority;\n enqueuedAtMs: number;\n resolve: (value: LocalLlmChatCompletionResult | null) => void;\n}\n\n/**\n * Local LLM client for OpenAI-compatible endpoints (LM Studio, Ollama, MLX, etc.)\n *\n * Based on openclaw-tactician's provider detection patterns for consistency.\n * Provides privacy-preserving, cost-effective LLM operations with\n * graceful fallback to cloud providers when local LLM is unavailable.\n */\nexport class LocalLlmClient {\n private config: PluginConfig;\n private isAvailable: boolean | null = null;\n private lastHealthCheck: number = 0;\n private poolExpirySeenMs = new Map<string, number>(); // pool key → lapsed-circuit instant already invalidated\n private readonly availabilityProbe = new SingleFlightProbe();\n private detectedType: LocalLlmType | null = null;\n private cachedModelInfo: LocalModelInfo | null = null;\n private cachedLmsContext: number | null = null;\n private lastLmsCheck: number = 0;\n private consecutive400s: number = 0;\n private cooldownUntilMs: number = 0;\n private modelRegistry?: ModelRegistry;\n private readonly nativeSchemaGate = new NativeSchemaGate(() => this.modelRegistry);\n private _disableThinking: boolean = false;\n private readonly requestQueues: Record<LocalLlmRequestPriority, LocalLlmQueuedRequest[]> = {\n \"recall-critical\": [],\n background: [],\n };\n private readonly queueProcessing = new Set<LocalLlmRequestPriority>();\n private queueDrainScheduled: boolean = false;\n private static readonly HEALTH_CHECK_INTERVAL_MS = 60000; // 1 minute\n private static readonly LMS_CACHE_INTERVAL_MS = 30000; // 30 seconds\n private readonly chatTransport = new ChatTransport();\n /** Orchestrator-owned stop signal: aborts every in-flight and queued\n * request (and their retry backoffs) the moment teardown begins. */\n private readonly shutdownSignal: AbortSignal | undefined;\n\n constructor(config: PluginConfig, modelRegistry?: ModelRegistry, shutdownSignal?: AbortSignal) {\n this.config = config;\n this.modelRegistry = modelRegistry;\n this.shutdownSignal = shutdownSignal;\n }\n\n /**\n * Request thinking/reasoning suppression on the next chat completion.\n *\n * When `true`, the client will inject\n * `chat_template_kwargs: { enable_thinking: false }` into the request\n * body — **but only when the detected backend is known to support it**\n * (LM Studio, vLLM; see `THINKING_COMPATIBLE_BACKENDS`). Strict\n * OpenAI-compat backends reject unknown fields with 400; on those the\n * client fails open (thinking runs normally). This is the safe\n * default for Remnic extraction-style operations: measurable latency\n * win on thinking-capable backends, zero risk on others. Consolidation\n * operations keep thinking enabled unless explicitly added to\n * `THINKING_SUPPRESSED_OPERATIONS`. Issues #548 and #979.\n */\n set disableThinking(value: boolean) {\n this._disableThinking = value;\n }\n\n private resolveHomeDir(): string {\n return this.config.localLlmHomeDir || readEnvVar(\"HOME\") || os.homedir();\n }\n\n private buildRequestHeaders(base: Record<string, string> = {}): Record<string, string> {\n const headers = { ...base } satisfies Record<string, string>;\n const configured = this.config.localLlmHeaders ?? {};\n for (const [key, value] of Object.entries(configured)) {\n const existing = Object.keys(headers).find((name) => name.toLowerCase() === key.toLowerCase());\n if (existing !== undefined) delete headers[existing];\n headers[key] = value;\n }\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n const existing = Object.keys(headers).find((name) => name.toLowerCase() === \"authorization\");\n if (existing !== undefined) delete headers[existing];\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return headers;\n }\n\n\n /**\n * Set the ModelRegistry for caching detected capabilities\n */\n setModelRegistry(registry: ModelRegistry): void {\n this.modelRegistry = registry;\n }\n\n /**\n * Get the detected server type (null if not detected)\n */\n getDetectedType(): LocalLlmType | null {\n return this.detectedType;\n }\n\n private markBackendUnavailable(\n reason: string,\n durationMs: number,\n chatUrl: string,\n operation: string,\n ): void {\n markLocalLlmBackendPoolUnavailable(reason, durationMs, chatUrl, operation);\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.warn(\n `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizeBackendTripReason(reason)} op=${operation}`,\n );\n }\n\n\n /**\n * Fetch with timeout for health checks. Body lives in the sibling helper so\n * this file stays under its size ceiling (issue #1995).\n */\n private async fetchWithTimeout(\n url: string,\n timeoutMs: number = 2000,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ): Promise<ProbeFetchResult> {\n return await probeFetch(url, {\n timeoutMs,\n headers: this.buildRequestHeaders({ Accept: \"application/json\", ...(headers ?? {}) }),\n signal,\n });\n }\n\n private async probeLmStudioNativeModels(\n probeBaseUrl: string,\n signal?: AbortSignal,\n ): Promise<{ matched: boolean; unauthorized: boolean }> {\n let unauthorized = false;\n for (const endpoint of [\"/api/v1/models\", \"/api/v0/models\"]) {\n if (signal?.aborted) return { matched: false, unauthorized };\n const probe = await this.fetchWithTimeout(`${probeBaseUrl}${endpoint}`, 2000, undefined, signal);\n if (signal?.aborted) return { matched: false, unauthorized };\n if (probe.ok && isLmStudioNativeModelsResponse(probe.data)) {\n return { matched: true, unauthorized };\n }\n if (probe.status === 401 || probe.status === 403) {\n unauthorized = true;\n }\n }\n return { matched: false, unauthorized };\n }\n\n /**\n * Check if local LLM is available\n * Uses 127.0.0.1 instead of localhost to avoid DNS issues (consistent with tactician)\n */\n async checkAvailability(\n signal?: AbortSignal,\n chatUrl?: string,\n operation?: string,\n ): Promise<boolean> {\n if (signal?.aborted) return false;\n const now = Date.now(); // cache health check results for 1 minute\n if (chatUrl) {\n // An empty label is a real pool key: a \"\" caller still sees a recorded circuit (wAN on #3474).\n const poolOperation = operation ?? \"unspecified\";\n const poolKey = formatLocalLlmPoolKey(chatUrl, poolOperation);\n // A lapsed circuit stays visible as a tombstone; each client clears its cached verdict once.\n const expiredAtMs = localLlmBackendPoolExpiredAtMs(now, chatUrl, poolOperation);\n if (expiredAtMs !== null && expiredAtMs > (this.poolExpirySeenMs.get(poolKey) ?? 0)) {\n this.poolExpirySeenMs.set(poolKey, expiredAtMs);\n this.isAvailable = null;\n this.lastHealthCheck = 0;\n }\n const trippedState = getLocalLlmTrippedBackendPoolState(now, chatUrl, poolOperation);\n if (trippedState) {\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.info(\n `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason}) op=${poolOperation}`,\n );\n return false;\n }\n }\n if (this.isAvailable !== null && now - this.lastHealthCheck < LocalLlmClient.HEALTH_CHECK_INTERVAL_MS) {\n return this.isAvailable;\n }\n return await this.availabilityProbe.run((probeSignal) => this.probeAvailability(probeSignal), signal);\n }\n\n private async probeAvailability(signal?: AbortSignal): Promise<boolean> {\n const now = Date.now();\n // Probe server-native endpoints from the server root even when users configure\n // the OpenAI-compatible `/v1` base URL for chat completions.\n const configuredBaseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const probeBaseUrl = stripTrailingV1Path(configuredBaseUrl);\n let sawUnauthorizedProbe = false;\n // A probe that TIMED OUT says the event loop was busy, not that the backend\n // is down (issue #2210). Tracked separately so a loaded daemon cannot cache\n // itself into a blackout.\n let sawAbortedProbe = false;\n // Several server shapes share a probe URL (LiteLLM and Ollama both use\n // `/`); fetch each URL once per pass.\n const probed = new Map<string, ProbeFetchResult>();\n const probeOnce = async (url: string): Promise<ProbeFetchResult> => {\n const cached = probed.get(url);\n if (cached) return cached;\n const result = await this.fetchWithTimeout(url, 2000, undefined, signal);\n probed.set(url, result);\n return result;\n };\n\n // Try to detect which server type is running\n if (signal?.aborted) return false;\n for (const serverConfig of orderedLocalServers(configuredBaseUrl)) {\n const healthUrl = `${probeBaseUrl}${serverConfig.healthEndpoint}`;\n log.debug(`checking ${serverConfig.type} at ${healthUrl}`);\n\n const result = await probeOnce(healthUrl);\n if (result.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\n if (result.ok && serverConfig.detectFn(result.data)) {\n if (serverConfig.type === \"mlx\") {\n const lmStudioProbe = await this.probeLmStudioNativeModels(probeBaseUrl, signal);\n if (signal?.aborted) return false;\n if (lmStudioProbe.unauthorized) {\n sawUnauthorizedProbe = true;\n }\n if (lmStudioProbe.matched) {\n this.isAvailable = true;\n this.detectedType = \"lmstudio\";\n this.lastHealthCheck = now;\n log.info(`detected lmstudio at ${configuredBaseUrl}`);\n return true;\n }\n }\n if (serverConfig.type === \"llamacpp\") {\n let sawLlamaCppSignal = false;\n const propsProbe = await this.fetchWithTimeout(`${probeBaseUrl}/props`, 2000, undefined, signal);\n if (propsProbe.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\n if (propsProbe.ok && isLlamaCppPropsResponse(propsProbe.data)) {\n sawLlamaCppSignal = true;\n }\n if (propsProbe.status === 401 || propsProbe.status === 403) {\n sawUnauthorizedProbe = true;\n }\n\n const modelsUrl = `${probeBaseUrl}${serverConfig.modelsEndpoint}`;\n const modelsProbe = await this.fetchWithTimeout(modelsUrl, 2000, undefined, signal);\n if (modelsProbe.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\n if (modelsProbe.ok && isLlamaCppModelsResponse(modelsProbe.data)) {\n sawLlamaCppSignal = true;\n }\n if (modelsProbe.status === 401 || modelsProbe.status === 403) {\n sawUnauthorizedProbe = true;\n continue;\n }\n\n const authConfigured = Boolean(this.config.localLlmApiKey) && this.config.localLlmAuthHeader !== false;\n if (!sawLlamaCppSignal || (authConfigured && !modelsProbe.ok)) {\n continue;\n }\n }\n this.isAvailable = true;\n this.detectedType = serverConfig.type;\n this.lastHealthCheck = now;\n log.info(`detected ${serverConfig.type} at ${configuredBaseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n }\n if (signal?.aborted) return false;\n\n // Generic check if specific detection failed\n try {\n const modelsUrl = `${probeBaseUrl}/v1/models`;\n const result = await this.fetchWithTimeout(modelsUrl, 2000, undefined, signal);\n if (result.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\n if (result.ok) {\n this.isAvailable = true;\n this.detectedType = \"generic\";\n this.lastHealthCheck = now;\n log.info(`detected generic OpenAI-compatible server at ${configuredBaseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n } catch {\n // Fall through to unavailable\n }\n\n const wasAvailable = this.isAvailable;\n this.detectedType = null;\n if (sawUnauthorizedProbe) {\n log.warn(\n `local LLM availability probe was unauthorized at ${configuredBaseUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n const verdict = resolveUnavailableVerdict({\n baseUrl: configuredBaseUrl,\n sawAbortedProbe,\n wasAvailable,\n });\n this.isAvailable = verdict.cacheVerdict ? false : null;\n this.lastHealthCheck = verdict.cacheVerdict ? now : 0;\n if (verdict.warning) log.warn(verdict.warning);\n log.debug(\"local LLM not available at\", configuredBaseUrl);\n return false;\n }\n\n /**\n * Try to get context window from LM Studio settings.json as fallback.\n * This reads the defaultContextLength setting which is what LM Studio uses\n * when loading models without explicit context configuration.\n */\n private getContextFromLmStudioSettings(): number | null {\n try {\n const homeDir = this.resolveHomeDir();\n const settingsPath = `${homeDir}/.cache/lm-studio/settings.json`;\n\n if (!fs.existsSync(settingsPath)) {\n log.debug(`LM Studio settings: file not found at ${settingsPath}`);\n return null;\n }\n\n const content = fs.readFileSync(settingsPath, \"utf-8\");\n const settings = JSON.parse(content) as {\n defaultContextLength?: {\n type?: string;\n value?: number;\n };\n };\n\n if (settings.defaultContextLength?.value) {\n const contextWindow = settings.defaultContextLength.value;\n log.debug(`LM Studio settings: found default context length: ${contextWindow}`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LM Studio settings: failed to read - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Try to get context window from LMS CLI (LM Studio specific).\n * Uses --json flag for reliable parsing.\n * Returns null if LMS CLI is not available or model not found.\n */\n private getContextFromLmsCli(modelId: string): number | null {\n try {\n // Check if lms CLI exists in common locations.\n // HOME may be absent in launchd environments, so prefer the resolved helper.\n const homeDir = this.resolveHomeDir();\n const lmsPaths = [\n this.config.localLmsCliPath || \"\",\n `${homeDir}/.cache/lm-studio/bin/lms`,\n \"/usr/local/bin/lms\",\n \"/opt/homebrew/bin/lms\",\n ];\n\n const lmsPath = lmsPaths.find((p) => p.length > 0 && fs.existsSync(p));\n if (!lmsPath) {\n log.debug(`LMS CLI: not found in standard locations (checked: ${lmsPaths.join(\", \")})`);\n return null;\n }\n\n // Run lms ps --json to get loaded models with context\n // Use spawnSync with shell and explicit PATH to ensure lms can find its dependencies\n log.debug(`LMS CLI: running: ${lmsPath} ps --json`);\n const existingPath = readEnvVar(\"PATH\") || \"\";\n const result = launchProcessSync(lmsPath, [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false, // Don't use shell for JSON output - more reliable\n env: mergeEnv({\n PATH: `${this.config.localLmsBinDir || `${homeDir}/.cache/lm-studio/bin`}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:${existingPath}`,\n HOME: homeDir,\n }),\n });\n\n if (result.error) {\n log.debug(`LMS CLI: spawn error - ${result.error.message}`);\n return null;\n }\n\n if (result.stderr && result.stderr.trim()) {\n log.debug(`LMS CLI: stderr - ${result.stderr.slice(0, 200)}`);\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n log.debug(\"LMS CLI: empty output - LM Studio may not be running or no models loaded\");\n return null;\n }\n\n // Parse JSON output\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch (parseErr) {\n log.debug(`LMS CLI: JSON parse error - ${parseErr}`);\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n log.debug(\"LMS CLI: no models loaded\");\n return null;\n }\n\n // Find the model matching our configured model ID\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model) {\n log.debug(`LMS CLI: model \"${modelId}\" not found in loaded models: ${models.map(m => m.identifier).join(\", \")}`);\n return null;\n }\n\n // Use contextLength (actual configured) or fall back to maxContextLength (model max)\n const contextWindow = model.contextLength || model.maxContextLength;\n\n if (contextWindow) {\n log.info(`LMS CLI detected context window: ${contextWindow} for ${modelId} (max: ${model.maxContextLength})`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n // LMS CLI not available or failed\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LMS CLI: failed - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Get full model info from LMS CLI including context length and max context length.\n * Returns null if LMS CLI is unavailable or model not found.\n */\n private getLmsModelInfo(modelId: string): { contextLength: number; maxContextLength: number; identifier: string } | null {\n try {\n const result = launchProcessSync(\"lms\", [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false,\n });\n\n if (result.error) {\n return null;\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n return null;\n }\n\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch {\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n return null;\n }\n\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model || !model.contextLength) {\n return null;\n }\n\n return {\n contextLength: model.contextLength,\n maxContextLength: model.maxContextLength || model.contextLength,\n identifier: model.identifier || modelId,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Get context window for the configured model, using cache if available.\n * This method caches the result to avoid repeated LMS CLI calls.\n * Order: ModelRegistry (persistent) -> memory cache -> LMS CLI -> settings.json\n */\n getCachedContextWindow(modelId: string): number | null {\n const now = Date.now();\n\n // 1. Check ModelRegistry for persisted context window\n if (this.modelRegistry) {\n const caps = this.modelRegistry.getCapabilities(modelId);\n if (caps.source === \"lmstudio\" && caps.contextWindow) {\n log.debug(`ModelRegistry: using persisted LM Studio context: ${caps.contextWindow}`);\n // Also update memory cache\n this.cachedLmsContext = caps.contextWindow;\n this.lastLmsCheck = now;\n return caps.contextWindow;\n }\n }\n\n // 2. Return in-memory cached value if still valid\n if (this.cachedLmsContext && now - this.lastLmsCheck < LocalLlmClient.LMS_CACHE_INTERVAL_MS) {\n log.debug(`LMS CLI: returning in-memory cached context: ${this.cachedLmsContext}`);\n return this.cachedLmsContext;\n }\n\n // 3. Try LMS CLI (authoritative source)\n const lmsInfo = this.getLmsModelInfo(modelId);\n if (lmsInfo?.contextLength) {\n this.cachedLmsContext = lmsInfo.contextLength;\n this.lastLmsCheck = now;\n // Calculate appropriate output tokens based on context size\n // Use 12.5% of context window, capped at 16K (generous but safe)\n const calculatedOutputTokens = Math.min(Math.floor(lmsInfo.contextLength / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096); // Minimum 4K\n // Persist to ModelRegistry with detected capabilities\n if (this.modelRegistry) {\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: lmsInfo.maxContextLength || lmsInfo.contextLength,\n contextWindow: lmsInfo.contextLength,\n supportsExtendedContext: (lmsInfo.maxContextLength || lmsInfo.contextLength) > 65536,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n log.info(`LMS CLI: Stored capabilities for ${modelId}: ${lmsInfo.contextLength} context, ${outputTokens} output tokens`);\n }\n return lmsInfo.contextLength;\n }\n\n // Legacy: Try LMS CLI context only (fallback)\n const legacyContext = this.getContextFromLmsCli(modelId);\n if (legacyContext) {\n this.cachedLmsContext = legacyContext;\n this.lastLmsCheck = now;\n // Persist to ModelRegistry with calculated output tokens\n if (this.modelRegistry) {\n const calculatedOutputTokens = Math.min(Math.floor(legacyContext / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096);\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: legacyContext,\n contextWindow: legacyContext,\n supportsExtendedContext: false,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n }\n return legacyContext;\n }\n\n // 4. Fall back to LM Studio settings.json\n const settingsContext = this.getContextFromLmStudioSettings();\n if (settingsContext) {\n log.info(`LM Studio settings: using default context: ${settingsContext}`);\n this.cachedLmsContext = settingsContext;\n this.lastLmsCheck = now;\n return settingsContext;\n }\n\n return null;\n }\n\n /**\n * Clear the LMS context cache. Call this when the model changes.\n */\n clearContextCache(): void {\n this.cachedLmsContext = null;\n this.lastLmsCheck = 0;\n log.debug(\"LMS CLI: context cache cleared\");\n }\n\n private remainingCooldownMs(now: number = Date.now()): number {\n return Math.max(0, this.cooldownUntilMs - now);\n }\n\n private scheduleQueueDrain(): void {\n if (this.queueDrainScheduled) return;\n this.queueDrainScheduled = true;\n\n queueMicrotask(() => {\n this.queueDrainScheduled = false;\n this.startAvailableQueuedRequests();\n });\n }\n\n /** True when a background-priority request occupies or awaits this client's local lane (issue #2011). */\n isBackgroundLaneContended(): boolean {\n return this.queueProcessing.has(\"background\") || this.requestQueues.background.length > 0;\n }\n\n private dequeueQueuedRequest(priority: LocalLlmRequestPriority): LocalLlmQueuedRequest | null {\n const next = this.requestQueues[priority].shift();\n return next ?? null;\n }\n\n private failOpenQueuedRequestsForCooldown(): number {\n let dropped = 0;\n for (const priority of [\"recall-critical\", \"background\"] as const) {\n while (this.requestQueues[priority].length > 0) {\n const queued = this.requestQueues[priority].shift();\n queued?.resolve(null);\n dropped += 1;\n }\n }\n return dropped;\n }\n\n private startAvailableQueuedRequests(): void {\n if (!this.queueProcessing.has(\"recall-critical\")) {\n const nextCritical = this.dequeueQueuedRequest(\"recall-critical\");\n if (nextCritical) {\n this.queueProcessing.add(\"recall-critical\");\n void this.runQueuedRequest(nextCritical);\n }\n }\n\n if (!this.queueProcessing.has(\"background\")) {\n const nextBackground = this.dequeueQueuedRequest(\"background\");\n if (nextBackground) {\n this.queueProcessing.add(\"background\");\n void this.runQueuedRequest(nextBackground);\n }\n }\n }\n\n private async runQueuedRequest(next: LocalLlmQueuedRequest): Promise<void> {\n try {\n if (combineClientAbortSignals(next.options.signal, this.shutdownSignal)?.aborted) {\n next.resolve(null);\n return;\n }\n const remainingCooldownMs = this.remainingCooldownMs();\n if (remainingCooldownMs > 0) {\n const additionalDropped = this.failOpenQueuedRequestsForCooldown();\n log.warn(\n `local LLM: cooldown active (${remainingCooldownMs}ms remaining), dropping ${additionalDropped + 1} queued request(s) fail-open`,\n );\n next.resolve(null);\n return;\n }\n\n let result: LocalLlmChatCompletionResult | null = null;\n try {\n result = await this.runChatCompletionRequest(next.messages, next.options, {\n priority: next.priority,\n enqueuedAtMs: next.enqueuedAtMs,\n });\n } catch (err) {\n log.warn(`local LLM queue drain failed open: ${next.options.redactProviderErrors ? \"provider error details redacted\" : err instanceof Error ? err.message : String(err)}`);\n }\n next.resolve(result);\n } finally {\n this.queueProcessing.delete(next.priority);\n if (this.requestQueues[\"recall-critical\"].length > 0 || this.requestQueues.background.length > 0) {\n this.scheduleQueueDrain();\n }\n }\n }\n\n private async runChatCompletionRequest(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions,\n queueMeta?: { priority: LocalLlmRequestPriority; enqueuedAtMs: number },\n ): Promise<LocalLlmChatCompletionResult | null> {\n log.debug(\n `local LLM chatCompletion: localLlmEnabled=${resolveLocalLlmCapabilities(this.config).localLlm}, model=${this.config.localLlmModel}`,\n );\n\n const operation = options.operation ?? \"unspecified\";\n const startedAtMs = Date.now();\n if (queueMeta) {\n log.debug(\n `local LLM queue start: priority=${queueMeta.priority} waitMs=${startedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n\n let chatUrl = \"\";\n try {\n const signal = combineClientAbortSignals(options.signal, this.shutdownSignal);\n if (signal?.aborted) return null;\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n chatUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/chat/completions`\n : `${baseUrl}/v1/chat/completions`;\n const isAvailable = await this.checkAvailability(signal, chatUrl, operation);\n if (!isAvailable) {\n log.debug(\n `local LLM: checkAvailability returned false for ${this.config.localLlmUrl} op=${operation}`,\n );\n return null;\n }\n\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const requestModel = options.model ?? this.config.localLlmModel;\n const requestBody: LocalLlmChatRequestBody = {\n model: requestModel,\n messages,\n temperature: options.temperature ?? 0.7,\n // Use max_tokens consistent with cloud models\n max_tokens: options.maxTokens ?? 4096,\n stream: false,\n };\n this.nativeSchemaGate.attach(requestBody, options, requestModel);\n\n // Suppress thinking/reasoning for operations that benefit from terse,\n // structured output. Thinking-capable models (Qwen 3.5, Gemma 4,\n // DeepSeek) default to thinking-on via their chat template; sending\n // `chat_template_kwargs: { enable_thinking: false }` tells the template\n // to skip reasoning tokens. Consolidation operations on the main client\n // intentionally keep thinking enabled so entity resolution and\n // deduplication can use the model's reasoning path. Fast-tier callers can\n // still force suppression per request to preserve their low-latency\n // contract.\n //\n // Gate the injection on detected backend support (issue #548,\n // Codex P1 on PR #550): `chat_template_kwargs` is an LM Studio /\n // vLLM / llama.cpp extension, not part of standard OpenAI chat\n // completions. Strict OpenAI-compatible backends reject\n // unknown fields with 400, which trips the 400-cooldown path and\n // can effectively disable local extraction. Fail open when the\n // backend hasn't been positively identified as thinking-capable.\n const shouldSuppressThinking =\n options.forceDisableThinking === true ||\n ((options.disableThinking ?? this._disableThinking) &&\n THINKING_SUPPRESSED_OPERATIONS.has(operation));\n if (\n shouldSuppressThinking &&\n this.detectedType !== null &&\n THINKING_COMPATIBLE_BACKENDS.has(this.detectedType)\n ) {\n requestBody.chat_template_kwargs = { enable_thinking: false };\n } else if (shouldSuppressThinking && this.detectedType === \"ollama\") {\n // Ollama's /v1 endpoint silently drops `chat_template_kwargs` AND\n // `enable_thinking` — the ONLY field it maps to think-off is\n // `reasoning_effort` (\"none\" → ThinkValue{false} in openai.go;\n // verified against Ollama 0.32.0 source and live probes,\n // issue #1996). Without this, thinking-capable models (Gemma 4,\n // Qwen 3.5+) burn 1,700-2,000 reasoning tokens per extraction on\n // Ollama, exceed the client timeout, and retry forever. The effort\n // is configurable via `localLlmReasoningEffort` (default \"none\");\n // an empty value disables injection (pre-#1996 behavior).\n const effort = this.config.localLlmReasoningEffort;\n if (effort) {\n requestBody.reasoning_effort = effort;\n }\n }\n\n let requestBodyJson = JSON.stringify(requestBody);\n log.debug(\n `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,\n );\n // Avoid logging request bodies by default (can contain sensitive user content).\n log.debug(`local LLM: request body length=${requestBodyJson.length}`);\n\n const effectiveTimeoutMs =\n typeof options.timeoutMs === \"number\"\n ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)\n : this.config.localLlmTimeoutMs;\n const maxAttempts = 1 + Math.max(0, this.config.localLlmRetry5xxCount);\n // COS-447: rate-limit responses (429/503/408, LiteLLM cooldown) get\n // their own retry budget with exponential full-jitter backoff, and a\n // process-wide semaphore caps concurrent HTTP attempts across clients.\n // Waits are bounded by the request timeout so a short caller budget\n // (e.g. rerankTimeoutMs) is never stretched by a long cooldown.\n const rateLimit = new LocalLlmRateLimitSession(\n formatLocalLlmPoolKey(chatUrl, operation),\n resolveRateLimitSettings(this.config),\n (queueMeta?.priority ?? options.priority) === \"recall-critical\",\n effectiveTimeoutMs,\n );\n let lastRateLimitDelayMs: number | null = null;\n let response: Response | null = null, responseBody = \"\";\n let lastAbortError: Error | null = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n response = null;\n responseBody = \"\";\n // Wait out the shared endpoint backoff, then take a concurrency slot.\n const gate = await rateLimit.beforeAttempt(signal);\n if (gate.kind === \"skip\") {\n log.warn(gate.reason === \"queue\"\n ? `local LLM concurrency queue exceeded the ${effectiveTimeoutMs}ms request budget; skipping request (op=${operation})`\n : `local LLM rate-limit backoff active (${gate.remainingMs}ms remaining); skipping request (op=${operation})`);\n if (options.failureDiag)\n options.failureDiag.lastError = Object.assign(new Error(\"local LLM rate limited\"), { status: 429 });\n return null;\n }\n if (gate.kind === \"aborted\") return null;\n const attemptAbort = new AbortController();\n const onCallerAbort = (): void => {\n attemptAbort.abort(signal?.reason);\n };\n if (signal) {\n if (signal.aborted) {\n onCallerAbort();\n } else {\n signal.addEventListener(\"abort\", onCallerAbort, { once: true });\n }\n }\n const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);\n const routingHeaders = buildLocalLlmRoutingHeaders(operation, options.priority);\n const postAttempt = (bodyJson: string): Promise<Response> => this.chatTransport.post({\n url: chatUrl,\n headers: this.buildRequestHeaders(routingHeaders),\n body: bodyJson,\n signal: attemptAbort.signal,\n budgetMs: this.config.localLlmTimeoutMs,\n });\n try {\n response = await postAttempt(requestBodyJson);\n responseBody = await response.text();\n if (\n response.status === 400 &&\n requestBody.response_format &&\n isUnsupportedJsonSchemaError(`400 ${responseBody}`)\n ) {\n this.nativeSchemaGate.rememberRejection(requestModel);\n // Match gateway degradation without extending this attempt's deadline.\n delete requestBody.response_format;\n requestBodyJson = JSON.stringify(requestBody);\n log.debug(\"local LLM rejected native JSON schema; retrying without it\");\n response = null;\n response = await postAttempt(requestBodyJson);\n responseBody = await response.text();\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n if (signal?.aborted) {\n response = null;\n lastAbortError = error;\n break;\n }\n if (response && !response.ok) {\n log.debug(`local LLM failed to read ${response.status} response body: ${options.redactProviderErrors ? \"details redacted\" : error.message}`);\n } else {\n response = null;\n if (!isAbortError(err)) throw err;\n lastAbortError = error;\n if (attempt >= maxAttempts) break;\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request aborted: op=${operation} attempt=${attempt}/${maxAttempts} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel}; retrying after ${backoffMs}ms`,\n );\n if (!(await waitForRetryBackoff(backoffMs, signal))) return null;\n continue;\n }\n } finally {\n clearTimeout(attemptTimeout);\n signal?.removeEventListener(\"abort\", onCallerAbort);\n gate.release();\n }\n\n if (response.ok) {\n rateLimit.onSuccess();\n break;\n }\n if (response.status >= 500 && attempt < maxAttempts) {\n const nonRecoverableReason = extractNonRecoverableBackendReasonFromErrorText(responseBody);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n chatUrl,\n operation,\n );\n this.consecutive400s = 0;\n return null;\n }\n }\n const decision = rateLimit.onResponse(response.status, response.headers?.get(\"retry-after\"), responseBody);\n lastRateLimitDelayMs = decision.kind === \"not-rate-limited\" ? null : decision.delayMs;\n if (decision.kind === \"give-up\") break;\n if (decision.kind === \"retry\") {\n log.warn(`local LLM rate limited: ${response.status}; backing off ${decision.delayMs}ms before retry ${decision.retry}/${rateLimit.settings.retryCount} (op=${operation}, serverHintMs=${decision.hintMs ?? \"none\"}, consecutive=${decision.consecutive})`);\n attempt -= 1; // own retry budget; the loop top waits out the backoff\n continue;\n }\n // A terminal pool-unavailable 503 must not reach the generic 5xx retry.\n if (isTerminalLocalLlmProxyPoolError(response.status, responseBody)) break;\n if (response.status < 500 || attempt >= maxAttempts) break;\n\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request got ${response.status}; retrying (attempt ${attempt + 1}/${maxAttempts}) after ${backoffMs}ms`,\n );\n if (!(await waitForRetryBackoff(backoffMs, signal))) return null;\n }\n log.debug(\n `local LLM: received response, status=${response?.status}, ok=${response?.ok}`,\n );\n if (!response) {\n if (lastAbortError) {\n log.warn(\n `local LLM request aborted after ${maxAttempts} attempt(s): op=${operation} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel} promptChars=${promptChars} durationMs=${Date.now() - startedAtMs}${queueMeta ? ` waitMs=${startedAtMs - queueMeta.enqueuedAtMs}` : \"\"}`,\n );\n } else {\n log.warn(\n `local LLM request failed: no response object (op=${operation} model=${this.config.localLlmModel} durationMs=${Date.now() - startedAtMs})`,\n );\n }\n return null;\n }\n\n if (!response.ok) {\n if (lastRateLimitDelayMs !== null)\n log.warn(`local LLM rate-limit retries exhausted: op=${operation} retries=${rateLimit.retryCount} nextBackoffMs=${lastRateLimitDelayMs}`);\n let reason = \"\";\n try {\n const parsed = JSON.parse(responseBody) as { error?: { message?: string } };\n reason = parsed?.error?.message ? ` — ${parsed.error.message}` : \"\";\n } catch {\n if (!options.redactProviderErrors) log.debug(`local LLM error body: ${responseBody.slice(0, 500)}`);\n }\n log.warn(\n `local LLM request failed: ${response.status}${options.redactProviderErrors ? \"\" : ` ${response.statusText}${reason}`} ` +\n `(op=${operation}, model=${this.config.localLlmModel}, url=${chatUrl}, promptChars=${promptChars}, maxTokens=${requestBody.max_tokens as number})`,\n );\n const nonRecoverableReason =\n extractNonRecoverableBackendReason(reason) ??\n extractNonRecoverableBackendReasonFromErrorText(responseBody);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n chatUrl,\n operation,\n );\n this.consecutive400s = 0;\n return null;\n }\n if (response.status === 400) {\n this.consecutive400s += 1;\n if (this.consecutive400s >= this.config.localLlm400TripThreshold) {\n this.cooldownUntilMs = Date.now() + this.config.localLlm400CooldownMs;\n log.warn(\n `local LLM: entering cooldown for ${this.config.localLlm400CooldownMs}ms ` +\n `after ${this.consecutive400s} consecutive 400 responses`,\n );\n this.consecutive400s = 0;\n }\n } else {\n this.consecutive400s = 0;\n }\n if (options.failureDiag)\n options.failureDiag.lastError = Object.assign(new Error(\"local LLM http failure\"), {\n status: response.status,\n });\n return null;\n }\n this.consecutive400s = 0;\n this.nativeSchemaGate.recordSuccess(requestBody, requestModel);\n\n // SAFETY: OpenAI-compatible wire format; every field is optional and read defensively below.\n const data = JSON.parse(responseBody) as {\n choices?: Array<{ message?: { content?: string; reasoning_content?: string }; finish_reason?: string }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n log.debug(\n `local LLM response: choices=${data.choices?.length}, usage=${JSON.stringify(data.usage)}`,\n );\n\n // Thinking models (e.g. Qwen 3.5) may put their response in\n // `reasoning_content` and leave `content` empty. Fall back to\n // reasoning_content so engram still gets a usable result.\n const msg = data.choices?.[0]?.message;\n if (options.failureDiag) options.failureDiag.finishReason = data.choices?.[0]?.finish_reason;\n const content = msg?.content || msg?.reasoning_content || \"\";\n if (!content) {\n log.warn(`local LLM returned empty content.${options.redactProviderErrors ? \"\" : ` choices=${JSON.stringify(data.choices)?.slice(0, 200)}`}`);\n return null;\n }\n\n // Estimate tokens if not provided by local LLM\n const usage = data.usage\n ? {\n promptTokens: data.usage.prompt_tokens ?? 0,\n completionTokens: data.usage.completion_tokens ?? 0,\n totalTokens: data.usage.total_tokens ?? 0,\n }\n : this.estimateTokens(messages, content);\n\n const durationMs = Date.now() - startedAtMs;\n if (resolvePipelineProcessingCapabilities(this.config).slowLog && durationMs >= this.config.slowLogThresholdMs) {\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const op = options.operation ? ` op=${options.operation}` : \"\";\n log.warn(\n `SLOW local LLM:${op} durationMs=${durationMs} model=${this.config.localLlmModel} url=${chatUrl} promptChars=${promptChars} outputTokens=${usage.completionTokens} totalTokens=${usage.totalTokens}`,\n );\n }\n\n log.debug(\"local LLM: request succeeded, tokens:\", usage.totalTokens);\n return { content, usage };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const durationMs = Date.now() - startedAtMs;\n if (isAbortError(err)) {\n log.warn(\n `local LLM request aborted: op=${operation} timeoutMs=${options.timeoutMs ?? this.config.localLlmTimeoutMs} model=${this.config.localLlmModel} durationMs=${durationMs} error=${options.redactProviderErrors ? \"provider error details redacted\" : errMsg}`,\n );\n return null;\n }\n log.warn(`local LLM request error: op=${operation} error=${options.redactProviderErrors ? \"provider error details redacted\" : errMsg}`);\n this.isAvailable = false; // Mark as unavailable on non-abort errors\n const nonRecoverableReason = extractNonRecoverableBackendReason(errMsg);\n if (nonRecoverableReason && chatUrl.length > 0) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n chatUrl,\n operation,\n );\n }\n return null;\n } finally {\n if (queueMeta) {\n const finishedAtMs = Date.now();\n const waitMs = startedAtMs - queueMeta.enqueuedAtMs;\n log.debug(\n `local LLM queue finish: priority=${queueMeta.priority} waitMs=${waitMs} runMs=${finishedAtMs - startedAtMs} totalMs=${finishedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n }\n }\n\n /**\n * Query the local LLM server for loaded model information.\n * Returns null if unavailable or if the model is not found.\n */\n async getLoadedModelInfo(): Promise<LocalModelInfo | null> {\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n\n // Handle URL construction - localLlmUrl may already include /v1\n const modelsUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/models`\n : `${baseUrl}/v1/models`;\n log.debug(`Fetching model info from ${modelsUrl}`);\n\n try {\n const result = await this.fetchWithTimeout(modelsUrl, 3000);\n if (!result.ok) {\n if (result.status === 401 || result.status === 403) {\n log.warn(\n `Local LLM: unauthorized while fetching models from ${modelsUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.warn(`Local LLM: Failed to fetch models from ${modelsUrl} - server returned error`);\n return null;\n }\n if (!result.data) {\n log.warn(`Local LLM: No data returned from ${modelsUrl}`);\n return null;\n }\n\n const data = result.data as {\n data?: Array<{\n id?: string;\n object?: string;\n owned_by?: string;\n // LM Studio specific fields\n max_context_length?: number;\n max_tokens?: number;\n // Ollama specific\n name?: string;\n details?: {\n parameter_size?: string;\n family?: string;\n };\n }>;\n };\n\n if (!Array.isArray(data.data) || data.data.length === 0) {\n log.warn(\"Local LLM returned no models\");\n return null;\n }\n\n // Verbose model listings are noisy on every gateway restart. Keep it debug-only.\n const modelIds = data.data.map((m) => m.id).filter(Boolean);\n log.debug(\n `Local LLM: Found ${modelIds.length} model(s). First 10: ${modelIds.slice(0, 10).join(\", \")}`,\n );\n\n // Find the model matching our configured model ID\n const configuredModel = this.config.localLlmModel;\n let model = data.data.find((m) => m.id === configuredModel);\n\n // If not found by exact match, try partial match (handle suffixes like @4bit)\n if (!model) {\n model = data.data.find((m) =>\n configuredModel.includes(m.id || \"\") ||\n (m.id || \"\").includes(configuredModel.replace(/@\\d+bit$/, \"\"))\n );\n }\n\n // If still not found, use the first loaded model and warn\n if (!model) {\n model = data.data[0];\n const availablePreview = data.data\n .map((m) => m.id)\n .filter(Boolean)\n .slice(0, 10)\n .join(\", \");\n log.warn(\n `Configured model \"${configuredModel}\" not found in local LLM. ` +\n `Using \"${model.id}\" instead. Available (first 10): ${availablePreview}`\n );\n }\n\n // Extract context window - try multiple field names\n let contextWindow = model.max_context_length || model.max_tokens;\n\n // If API doesn't report context window, try LMS CLI (LM Studio specific)\n if (!contextWindow) {\n log.info(\"Local LLM: API did not report context window, trying LMS CLI...\");\n const lmsContext = this.getCachedContextWindow(model.id || \"\");\n if (lmsContext) {\n contextWindow = lmsContext;\n }\n }\n\n this.cachedModelInfo = {\n id: model.id || \"unknown\",\n contextWindow: contextWindow,\n maxTokens: model.max_tokens,\n };\n\n log.info(\n `Local LLM model detected: ${this.cachedModelInfo.id}, ` +\n `context window: ${contextWindow?.toLocaleString() || \"unknown (may use default)\"}`\n );\n\n return this.cachedModelInfo;\n } catch (err) {\n log.warn(`Failed to fetch model info: ${err}`);\n return null;\n }\n }\n\n /**\n * Check if the configured model is available and get its actual context window.\n * Warns if there's a mismatch between expected and actual context.\n */\n async validateModelConfig(expectedContextWindow?: number): Promise<{\n available: boolean;\n actualContextWindow?: number;\n warnings: string[];\n }> {\n const warnings: string[] = [];\n\n const modelInfo = await this.getLoadedModelInfo();\n if (!modelInfo) {\n return { available: false, warnings: [\"Could not query local LLM for model info\"] };\n }\n\n // If we have expected context and the server reports one, check for mismatch\n if (expectedContextWindow && modelInfo.contextWindow) {\n if (modelInfo.contextWindow < expectedContextWindow) {\n warnings.push(\n `Context window mismatch: Model ${modelInfo.id} supports ${modelInfo.contextWindow.toLocaleString()} tokens, ` +\n `but engram is configured for ${expectedContextWindow.toLocaleString()}. ` +\n `Set localLlmMaxContext: ${modelInfo.contextWindow} in config to avoid errors.`\n );\n }\n }\n\n // Warn if server doesn't report context window (common with some local LLM setups)\n if (!modelInfo.contextWindow) {\n warnings.push(\n `Local LLM server did not report context window for ${modelInfo.id}. ` +\n `If you get \"context length exceeded\" errors, set localLlmMaxContext in config.`\n );\n }\n\n return {\n available: true,\n actualContextWindow: modelInfo.contextWindow,\n warnings,\n };\n }\n\n /**\n * Make a chat completion request to local LLM\n */\n async chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions = {},\n ): Promise<LocalLlmChatCompletionResult | null> {\n if (!resolveLocalLlmCapabilities(this.config).localLlm) {\n log.debug(\"local LLM: disabled, returning null\");\n return null;\n }\n\n const remainingMs = this.remainingCooldownMs();\n if (remainingMs > 0) {\n log.debug(`local LLM: cooldown active (${remainingMs}ms remaining), skipping request`);\n return null;\n }\n if (options.priority) {\n const priority = options.priority;\n const signal = combineClientAbortSignals(options.signal, this.shutdownSignal);\n return await new Promise<LocalLlmChatCompletionResult | null>((resolve) => {\n let settled = false;\n let onAbort: (() => void) | undefined;\n const finish = (value: LocalLlmChatCompletionResult | null): void => {\n if (settled) return;\n settled = true;\n if (onAbort) signal?.removeEventListener(\"abort\", onAbort);\n resolve(value);\n };\n const queued: LocalLlmQueuedRequest = {\n messages,\n options,\n priority,\n enqueuedAtMs: Date.now(),\n resolve: finish,\n };\n onAbort = () => {\n const queue = this.requestQueues[priority];\n const index = queue.indexOf(queued);\n if (index >= 0) queue.splice(index, 1);\n finish(null);\n };\n this.requestQueues[priority].push(queued);\n if (signal?.aborted) onAbort();\n else if (signal) signal.addEventListener(\"abort\", onAbort, { once: true });\n this.scheduleQueueDrain();\n });\n }\n\n return await this.runChatCompletionRequest(messages, options);\n }\n /**\n * Estimate tokens when local LLM does not return usage stats.\n */\n private estimateTokens(\n messages: Array<{ role: string; content: string }>,\n response: string\n ): { promptTokens: number; completionTokens: number; totalTokens: number } {\n const promptTokens = messages.reduce((sum, message) => sum + estimateTokenCount(message.content), 0);\n const completionTokens = estimateTokenCount(response);\n\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n }\n\n /**\n * Try local LLM first, fallback to cloud provider if configured\n */\n async withFallback<T>(\n localOperation: () => Promise<T | null>,\n fallbackOperation: () => Promise<T>,\n operationName: string\n ): Promise<T> {\n // Try local LLM first if enabled\n if (resolveLocalLlmCapabilities(this.config).localLlm) {\n const localResult = await localOperation();\n if (localResult !== null) {\n log.debug(`${operationName}: used local LLM`);\n return localResult;\n }\n\n // Local failed or unavailable\n if (this.config.localLlmFallback) {\n log.info(`${operationName}: local LLM unavailable, falling back to cloud`);\n } else {\n throw new Error(`${operationName}: local LLM unavailable and fallback disabled`);\n }\n }\n\n // Use fallback (cloud provider)\n return fallbackOperation();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,OAAO,QAAQ;AACf,OAAO,QAAQ;AAoCf,SAAS,oBAAoB,GAAmB;AAC9C,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,MAAM,CAAC,MAAM,IAAK;AACtC,SAAO,EAAE,UAAU,GAAG,GAAG;AAC3B;AAEA,SAAS,oBAAoB,GAAmB;AAC9C,SAAO,EAAE,SAAS,KAAK,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI;AAC9C;AAEA,SAAS,wBAAwB,OAAyB;AACxD,SACE,eAAe,KAAK,KACpB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AQ,OAAO,GAAG,CAAC;AACnG,UAAM,mBAAmB,mBAAmB,QAAQ;AAEpD,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,aAAa,eAAe;AAAA,IAC9B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aACJ,gBACA,mBACA,eACY;AAEZ,QAAI,4BAA4B,KAAK,MAAM,EAAE,UAAU;AACrD,YAAM,cAAc,MAAM,eAAe;AACzC,UAAI,gBAAgB,MAAM;AACxB,YAAI,MAAM,GAAG,aAAa,kBAAkB;AAC5C,eAAO;AAAA,MACT;AAGA,UAAI,KAAK,OAAO,kBAAkB;AAChC,YAAI,KAAK,GAAG,aAAa,gDAAgD;AAAA,MAC3E,OAAO;AACL,cAAM,IAAI,MAAM,GAAG,aAAa,+CAA+C;AAAA,MACjF;AAAA,IACF;AAGA,WAAO,kBAAkB;AAAA,EAC3B;AACF;","names":["backoffMs","promptChars"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/buffer-persistence.ts"],"sourcesContent":["import type { DrainedTurnSets } from \"./buffer-turn-helpers.js\";\nimport type { BufferEntryState, BufferState, BufferSurpriseEvent } from \"./types.js\";\nimport type { BufferSessionSaveOutcome } from \"./storage/buffer-drain-claims.js\";\n\n/**\n * The buffer persistence surface SmartBuffer depends on.\n *\n * `saveBufferSession` / `deleteBufferSession` are the per-session incremental\n * writes (one file per session); when a storage backend does not provide\n * them, the buffer falls back to the whole-state `saveBuffer`. Both are\n * optional in the type so a storage double only has to implement what it\n * actually supports.\n */\nexport interface BufferStorage {\n loadBuffer(): Promise<BufferState>;\n saveBuffer(state: BufferState): Promise<void>;\n /** Reports \"handed_over\" when the session is claimed by `remnic buffer drain` and the entry moved into the claim instead of a session file. Legacy doubles may return void (treated as \"saved\"). */\n saveBufferSession?(key: string, entry: BufferEntryState): Promise<BufferSessionSaveOutcome | void>;\n deleteBufferSession?(key: string): Promise<void>;\n /** Sync claim check for the extraction gate; omitted when the backend has no drain-claim store. */\n isBufferSessionClaimed?(key: string): boolean;\n /** Optional surprise-telemetry sink; older storage and test doubles omit it. */\n appendBufferSurpriseEvents?(events: BufferSurpriseEvent[]): Promise<number>;\n /** Persist observe-buffer idempotency metadata (#3368 production path). */\n saveBufferAdmissionIdempotency?(state: BufferState): Promise<void>;\n}\n\n/** What one persist pass changed beyond plain writes. */\nexport interface BufferPersistOutcome {\n /** Sessions whose in-memory entry moved into a drain claim: the caller must evict them (a claimed session no longer lives in this process). */\n handedOver: string[];\n /** Per session, the turns a drain extracted, kept in their original lists. */\n drainedTurns: Map<string, DrainedTurnSets>;\n /** Sessions whose rewrite this pass deferred (#3389); they stay dirty. */\n deferred: string[];\n /**\n * Milliseconds until the earliest deferred session becomes rewrite-eligible\n * (set only when `deferred` is non-empty). The caller arms a retry for this\n * delay so a deferred tail of a burst lands without needing another turn.\n */\n deferredRetryDelayMs?: number;\n}\n\n/**\n * Session files at or above this estimated serialized size get rate-limited\n * rewrites on steady-state passes (issue #3389). A single hot session grew to\n * ~44 MB and its whole-file rewrite dominated `durable-bufferMs` (~99% of\n * observe latency, worst ~10 min) while real disk utilization sat at ~2%.\n */\nexport const BUFFER_SESSION_DEFER_MIN_BYTES = 8 * 1024 * 1024;\n\n/** A session past the size floor is rewritten at most once per this interval. */\nexport const BUFFER_SESSION_DEFER_INTERVAL_MS = 60_000;\n\nexport interface BufferPersistOptions {\n /** Injectable clock (monotonic ms) for tests. */\n now?: () => number;\n /**\n * Steady-state passes may defer rewriting a dirty session whose estimated\n * size is at or above BUFFER_SESSION_DEFER_MIN_BYTES and whose last persist\n * was within BUFFER_SESSION_DEFER_INTERVAL_MS. Durability barriers\n * (extraction-trigger saves, explicit buffer.save / flushPendingSave,\n * shutdown flushes) omit this: they always write. Deferral never applies to\n * a session's first persist or to a drain-claimed session. Bounds match the\n * sanctioned bufferSaveDebounceMs crash-loss window: deferred turns stay in\n * memory until the next pass or a forced flush.\n */\n allowDeferral?: boolean;\n}\n\n/** Approximate serialized size of one session file without stringifying it. */\nfunction estimateEntryBytes(entry: BufferEntryState): number {\n // ~15% over content for JSON structure + string escaping (quotes, braces,\n // key names, escape growth); the fixed per-turn overhead covers field names\n // and metadata. Under-counting here biases against deferral — the exact\n // case the floor exists for — so the estimate errs high.\n let bytes = 256;\n for (const turn of entry.turns) bytes += Math.ceil(turn.content.length * 1.15) + 128;\n for (const turn of entry.retainedTurns ?? [])\n bytes += Math.ceil(turn.content.length * 1.15) + 128;\n return bytes;\n}\n\n/**\n * Tracks which sessions' persisted files are stale and writes only those.\n *\n * Marks are cleared only after a durable write of that session. All calls\n * happen under SmartBuffer's serialized mutation chain: one writer.\n */\nexport interface BufferSessionPersistenceOptions {\n /** Injectable clock (monotonic ms) for tests; defaults to performance.now(). */\n now?: () => number;\n /** Test seam: override BUFFER_SESSION_DEFER_INTERVAL_MS. */\n deferIntervalMs?: number;\n}\n\nexport class BufferSessionPersistence {\n private readonly dirty = new Set<string>();\n private readonly deleted = new Set<string>();\n private admissionIdempotencyDirty = false;\n /** Last successful session-file write per key (deferral bookkeeping, #3389). */\n private readonly lastPersistedAt = new Map<string, number>();\n private readonly clock: () => number;\n private readonly deferIntervalMs: number;\n\n constructor(options: BufferSessionPersistenceOptions = {}) {\n this.clock = options.now ?? (() => performance.now());\n this.deferIntervalMs = options.deferIntervalMs ?? BUFFER_SESSION_DEFER_INTERVAL_MS;\n }\n\n markDirty(key: string): void {\n this.dirty.add(key);\n this.deleted.delete(key);\n }\n\n markDeleted(key: string): void {\n this.deleted.add(key);\n this.dirty.delete(key);\n this.lastPersistedAt.delete(key);\n }\n\n /** Eviction removed `key` from memory: its session file must go, any pending write is moot. */\n markEvicted(keys: readonly string[]): void {\n for (const key of keys) this.markDeleted(key);\n }\n\n markAdmissionIdempotencyDirty(): void {\n this.admissionIdempotencyDirty = true;\n }\n\n hasPending(): boolean {\n return this.dirty.size > 0 || this.deleted.size > 0 || this.admissionIdempotencyDirty;\n }\n\n /**\n * Persist buffer state. On session-capable storage this writes ONLY the\n * sessions whose state changed since the last successful persist and\n * deletes files for evicted/reset sessions, so the observe path never\n * re-serializes other sessions' turns. On legacy storage it falls back to\n * the whole-state saveBuffer. Files are deleted before dirty writes: a\n * crash mid-persist can then only resurrect already-evicted data (the same\n * exposure as a whole-file rewrite), never drop sessions the state says\n * exist.\n */\n async persist(\n storage: BufferStorage,\n state: BufferState,\n peekEntry: (key: string) => BufferEntryState | undefined,\n reconcile?: { key: string; drained: DrainedTurnSets },\n opts?: BufferPersistOptions,\n ): Promise<BufferPersistOutcome> {\n const drainedTurns = new Map<string, DrainedTurnSets>(\n reconcile ? [[reconcile.key, reconcile.drained]] : [],\n );\n const saveSession = storage.saveBufferSession?.bind(storage);\n const deleteSession = storage.deleteBufferSession?.bind(storage);\n if (!saveSession || !deleteSession) {\n await storage.saveBuffer(state);\n if (this.admissionIdempotencyDirty && storage.saveBufferAdmissionIdempotency) {\n await storage.saveBufferAdmissionIdempotency(state);\n }\n this.dirty.clear();\n this.deleted.clear();\n this.admissionIdempotencyDirty = false;\n return { handedOver: [], drainedTurns, deferred: [] };\n }\n const now = opts?.now ?? this.clock;\n const handedOver: string[] = [];\n const deferred: string[] = [];\n let nextEligibleAt: number | undefined;\n for (const key of [...this.deleted]) {\n await deleteSession(key);\n this.deleted.delete(key);\n }\n for (const key of [...this.dirty]) {\n const entry = peekEntry(key);\n if (!entry) {\n // A dirty key without state must not be written from a fabricated\n // empty entry: treat it as a deletion instead.\n this.markDeleted(key);\n continue;\n }\n if (opts?.allowDeferral === true && key !== reconcile?.key) {\n const last = this.lastPersistedAt.get(key);\n if (\n last !== undefined &&\n now() - last < this.deferIntervalMs &&\n estimateEntryBytes(entry) >= BUFFER_SESSION_DEFER_MIN_BYTES &&\n // Fail closed: a backend that omits isBufferSessionClaimed cannot\n // prove the session is unclaimed, so it never defers (PR 3481 review).\n storage.isBufferSessionClaimed?.(key) === false\n ) {\n deferred.push(key);\n const eligibleAt = last + this.deferIntervalMs;\n if (nextEligibleAt === undefined || eligibleAt < nextEligibleAt) {\n nextEligibleAt = eligibleAt;\n }\n continue;\n }\n }\n const saveOutcome = await saveSession(key, entry);\n this.dirty.delete(key);\n this.lastPersistedAt.set(key, now());\n // \"handed_over\": the entry moved into a drain claim. Content is durable\n // in the claim, so this key's pending state is settled — the caller\n // evicts the in-memory entry on its side.\n if (saveOutcome?.status === \"handed_over\") handedOver.push(key);\n // A drain tombstone: the turns it extracted must leave this process's\n // copy too, or the owner would extract them a second time.\n if (\n saveOutcome?.drainedTurns &&\n (saveOutcome.drainedTurns.turns.length > 0 || saveOutcome.drainedTurns.retainedTurns.length > 0)\n ) {\n drainedTurns.set(key, saveOutcome.drainedTurns);\n }\n if (saveOutcome?.status === \"handed_over\") this.lastPersistedAt.delete(key);\n }\n // #3368: never persist admission keys while session bodies are still deferred —\n // a crash after the key lands but before the deferred rewrite would make a\n // same-key retry swallow the unwritten turns.\n if (this.admissionIdempotencyDirty && deferred.length === 0 && storage.saveBufferAdmissionIdempotency) {\n await storage.saveBufferAdmissionIdempotency(state);\n this.admissionIdempotencyDirty = false;\n }\n const outcome: BufferPersistOutcome = { handedOver, drainedTurns, deferred };\n if (deferred.length > 0 && nextEligibleAt !== undefined) {\n outcome.deferredRetryDelayMs = Math.max(0, nextEligibleAt - now());\n }\n return outcome;\n }\n}\n"],"mappings":";AAiDO,IAAM,iCAAiC,IAAI,OAAO;AAGlD,IAAM,mCAAmC;AAmBhD,SAAS,mBAAmB,OAAiC;AAK3D,MAAI,QAAQ;AACZ,aAAW,QAAQ,MAAM,MAAO,UAAS,KAAK,KAAK,KAAK,QAAQ,SAAS,IAAI,IAAI;AACjF,aAAW,QAAQ,MAAM,iBAAiB,CAAC;AACzC,aAAS,KAAK,KAAK,KAAK,QAAQ,SAAS,IAAI,IAAI;AACnD,SAAO;AACT;AAeO,IAAM,2BAAN,MAA+B;AAAA,EACnB,QAAQ,oBAAI,IAAY;AAAA,EACxB,UAAU,oBAAI,IAAY;AAAA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AAgC;AACrG,YAAM,QAAQ,+BAA+B,KAAK;AAClD,WAAK,4BAA4B;AAAA,IACnC;AACA,UAAM,UAAgC,EAAE,YAAY,cAAc,SAAS;AAC3E,QAAI,SAAS,SAAS,KAAK,mBAAmB,QAAW;AACvD,cAAQ,uBAAuB,KAAK,IAAI,GAAG,iBAAiB,IAAI,CAAC;AAAA,IACnE;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|