@cortexkit/opencode-magic-context 0.49.51 → 0.49.53

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.
Files changed (136) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-r77d4fdy.js → context-p6r0bk7a.js} +90 -51
  4. package/dist/{embedding-backfill-3wdjzrvs.js → embedding-backfill-qes2kf1c.js} +2 -2
  5. package/dist/features/magic-context/compartment-embedding.d.ts.map +1 -1
  6. package/dist/features/magic-context/message-fts-session-filter.d.ts +1 -1
  7. package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
  8. package/dist/features/magic-context/project-embedding-registry.d.ts +8 -0
  9. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  10. package/dist/features/magic-context/search.d.ts.map +1 -1
  11. package/dist/features/magic-context/storage-host-instruction-retention.d.ts +10 -3
  12. package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -1
  13. package/dist/features/magic-context/storage-meta-persisted.d.ts +20 -1
  14. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  15. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  16. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  17. package/dist/features/magic-context/storage.d.ts +1 -1
  18. package/dist/features/magic-context/storage.d.ts.map +1 -1
  19. package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
  20. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/active-anthropic-turn.d.ts +6 -0
  22. package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +2 -1
  24. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/history-boundary-recovery.d.ts +15 -0
  27. package/dist/hooks/magic-context/history-boundary-recovery.d.ts.map +1 -0
  28. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/host-served-rows.d.ts +12 -2
  30. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
  32. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/latest-assistant-turn.d.ts +43 -0
  34. package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +102 -26
  36. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
  37. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +18 -2
  38. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
  39. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  41. package/dist/hooks/magic-context/pending-marker-rearm.d.ts +20 -0
  42. package/dist/hooks/magic-context/pending-marker-rearm.d.ts.map +1 -0
  43. package/dist/hooks/magic-context/persist-filtered-noise.d.ts +1 -1
  44. package/dist/hooks/magic-context/persist-filtered-noise.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/priced-pass-sizing.d.ts +7 -0
  46. package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -1
  47. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +11 -1
  48. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -1
  50. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  51. package/dist/hooks/magic-context/served-check.d.ts +127 -0
  52. package/dist/hooks/magic-context/served-check.d.ts.map +1 -0
  53. package/dist/hooks/magic-context/signed-thinking-hold.d.ts +32 -4
  54. package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
  55. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +37 -2
  56. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  58. package/dist/hooks/magic-context/unresolved-history-boundary.d.ts +21 -2
  59. package/dist/hooks/magic-context/unresolved-history-boundary.d.ts.map +1 -1
  60. package/dist/{index-n0twfvah.js → index-2ctn7q09.js} +531 -17
  61. package/dist/{index-bamnjp2t.js → index-2m54t4g1.js} +9 -5
  62. package/dist/{index-30sf7e5k.js → index-3b5k5vma.js} +27 -16
  63. package/dist/{index-ct3ettqt.js → index-3h0wyv22.js} +3 -3
  64. package/dist/{index-hkveze74.js → index-3hhq18q0.js} +1 -1
  65. package/dist/{index-kaqs6h31.js → index-52x68mj4.js} +1 -1
  66. package/dist/{index-wr2t8zb0.js → index-5684dzbv.js} +648 -69
  67. package/dist/{index-s131svmx.js → index-7wasafnb.js} +1 -1
  68. package/dist/{index-8d7gkgjs.js → index-85chg6fw.js} +1 -1
  69. package/dist/{index-z4832qfe.js → index-a6bxwv4a.js} +1 -1
  70. package/dist/{index-h8g08nxs.js → index-chjsdqg6.js} +104 -62
  71. package/dist/{index-5dptmnvd.js → index-esm4farg.js} +8 -7
  72. package/dist/{index-97bjd14c.js → index-fbs0f5ch.js} +4 -4
  73. package/dist/{index-cwj6qhmf.js → index-kwpweqzs.js} +8 -3
  74. package/dist/{index-07rp6xcn.js → index-n3rxwtwt.js} +48 -15
  75. package/dist/{index-gv7dwx5b.js → index-p7ssfv6p.js} +503 -395
  76. package/dist/{index-v4a1pnny.js → index-pgbmbtdq.js} +4 -4
  77. package/dist/{index-mjh63zvw.js → index-wpab17w4.js} +1 -1
  78. package/dist/index.js +53 -32
  79. package/dist/{message-index-bounded-k0ebpy3y.js → message-index-bounded-7p3064st.js} +2 -2
  80. package/dist/migration-worker.js +1 -1
  81. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  82. package/dist/plugin/messages-transform.d.ts +6 -0
  83. package/dist/plugin/messages-transform.d.ts.map +1 -1
  84. package/dist/{project-embedding-registry-5dwh5zfn.js → project-embedding-registry-m8t547fb.js} +3 -1
  85. package/dist/raw-ordinal-warmup-worker.js +3 -3
  86. package/dist/{read-session-chunk-6712p893.js → read-session-chunk-cyks9yx4.js} +1 -1
  87. package/dist/{recomp-orchestrator-8ebydg5j.js → recomp-orchestrator-d4nks9da.js} +9 -9
  88. package/dist/{render-dtc4qkq4.js → render-gc1fn4nz.js} +5 -5
  89. package/dist/{search-75bj2430.js → search-1bjy7yhc.js} +8 -8
  90. package/dist/{search-archive-f6hjbnsa.js → search-archive-hdrfjgv8.js} +4 -4
  91. package/dist/shared/test-open-files.d.ts +17 -0
  92. package/dist/shared/test-open-files.d.ts.map +1 -0
  93. package/dist/shared/user-facing-codes.d.ts +7 -2
  94. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  95. package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
  96. package/dist/{transform-postprocess-phase-1bg25094.js → transform-postprocess-phase-9e53b1dr.js} +10 -10
  97. package/dist/v2/auto-search-worker.js +3 -3
  98. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  99. package/dist/v2/{context-cpbhpxks.js → context-1p22880w.js} +1084 -370
  100. package/dist/v2/{embedding-backfill-x1zpc04f.js → embedding-backfill-bwcmw1te.js} +2 -2
  101. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  102. package/dist/v2/hooks/context.d.ts.map +1 -1
  103. package/dist/v2/{message-index-bounded-a36rw93p.js → message-index-bounded-mjpxz7wp.js} +2 -2
  104. package/dist/v2/migration-worker.js +1 -1
  105. package/dist/v2/{project-embedding-registry-v2fxrs8b.js → project-embedding-registry-7qcs8c61.js} +3 -1
  106. package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
  107. package/dist/v2/{read-session-chunk-hzhxvhyv.js → read-session-chunk-cxk2kssy.js} +1 -1
  108. package/dist/v2/{recomp-orchestrator-yzr49pd0.js → recomp-orchestrator-e560ryjm.js} +8 -8
  109. package/dist/v2/{render-rhaevxv1.js → render-rk17pvy0.js} +5 -5
  110. package/dist/v2/{search-archive-9924fyk8.js → search-archive-a51g9sp7.js} +4 -4
  111. package/dist/v2/{search-3yrdpr38.js → search-kvzyj2mf.js} +7 -7
  112. package/dist/v2/{server-scp3y4dh.js → server-28g1b00j.js} +1 -1
  113. package/dist/v2/{server-kaqs6h31.js → server-52x68mj4.js} +1 -1
  114. package/dist/v2/{server-0k586y7d.js → server-71bg2psk.js} +3 -3
  115. package/dist/v2/{server-3bfc26r7.js → server-77rvx3wn.js} +34 -15
  116. package/dist/v2/{server-jxrqsn84.js → server-ah1j996f.js} +1 -1
  117. package/dist/v2/{server-sgn61hht.js → server-bjsmb6zs.js} +8 -3
  118. package/dist/v2/{server-16kfxcxj.js → server-bzh1fkvd.js} +1 -1
  119. package/dist/v2/{server-vjadwb3j.js → server-d5zgah57.js} +1 -1
  120. package/dist/v2/{server-q93jdtz8.js → server-e37d2zt4.js} +8 -7
  121. package/dist/v2/{server-016a1whm.js → server-fh6dhx8c.js} +104 -62
  122. package/dist/v2/{server-eznem83k.js → server-jmrd7vwc.js} +26 -15
  123. package/dist/v2/{server-4h4acntc.js → server-k3vtc89v.js} +9 -5
  124. package/dist/v2/{server-88yvx6r9.js → server-zq704789.js} +531 -17
  125. package/dist/v2/server.js +2 -2
  126. package/dist/v2/{v2-archive-reader-5ggewg8q.js → v2-archive-reader-hsvddme0.js} +1 -1
  127. package/dist/v2/{wrapup-orchestrator-36c5wyvq.js → wrapup-orchestrator-ckpj1yvj.js} +8 -8
  128. package/dist/{v2-archive-reader-gx5ke1d7.js → v2-archive-reader-qgqrxgrq.js} +1 -1
  129. package/dist/{wrapup-orchestrator-ya31knav.js → wrapup-orchestrator-6189f37j.js} +10 -10
  130. package/package.json +1 -1
  131. package/src/shared/escalation-bands.test.ts +16 -1
  132. package/src/shared/sqlite-placeholders.test.ts +103 -0
  133. package/src/shared/storage-file-mutex-review.test.ts +5 -7
  134. package/src/shared/test-open-files.test.ts +194 -0
  135. package/src/shared/test-open-files.ts +71 -0
  136. package/src/shared/user-facing-codes.ts +8 -2
@@ -194,7 +194,7 @@ import {
194
194
  snapRangeToCompartments,
195
195
  getActiveCompartmentRun,
196
196
  startCompartmentAgent
197
- } from "./index-h8g08nxs.js";
197
+ } from "./index-chjsdqg6.js";
198
198
  import {
199
199
  hasTrustedAbsoluteWall,
200
200
  applyProvenInputFloor,
@@ -307,7 +307,6 @@ import {
307
307
  DreamTokenBudgetExceeded,
308
308
  isEditTool,
309
309
  createFinalWireIncompleteLogger,
310
- decodeMergedReasoningParts,
311
310
  MAX_EXECUTE_THRESHOLD,
312
311
  escalationBands,
313
312
  sessionDecisionCalibration,
@@ -365,8 +364,9 @@ import {
365
364
  getStrippedPlaceholderIds,
366
365
  THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
367
366
  thinkingBindingRecoveryFrozenId,
368
- getThinkingBindingRecoveryTarget,
369
- armThinkingBindingRecovery,
367
+ noteBindingRecoveryAwaitingClear,
368
+ bindingRecoveryAwaitingClear,
369
+ retryBindingRecoveryClear,
370
370
  clearThinkingBindingRecoveryIf,
371
371
  getMergedReasoningStrippedIds,
372
372
  addMergedReasoningStrippedIds,
@@ -378,8 +378,6 @@ import {
378
378
  getObservedEpochFloor,
379
379
  resolveEpochFloorForPass,
380
380
  getReasoningRemovalState,
381
- detectThinkingBindingMismatch,
382
- detectLatestTurnThinkingMismatch,
383
381
  isPrefixBoundThinkingModel,
384
382
  detectOverflow,
385
383
  modelAcceptsEmptyContent,
@@ -426,7 +424,7 @@ import {
426
424
  readRawSessionMessageById2,
427
425
  readSessionChunk2,
428
426
  readRawSessionSeedTail2
429
- } from "./index-07rp6xcn.js";
427
+ } from "./index-n3rxwtwt.js";
430
428
  import {
431
429
  BoundedSessionMap,
432
430
  getMeasuredToolDefinitionTokens
@@ -456,7 +454,7 @@ import {
456
454
  runSqliteOptimize,
457
455
  openDatabase,
458
456
  openCurrentDatabase
459
- } from "./index-z4832qfe.js";
457
+ } from "./index-a6bxwv4a.js";
460
458
  import {
461
459
  unescapeXml,
462
460
  resolveWorkspaceShareCategories,
@@ -541,6 +539,13 @@ import {
541
539
  noteLkgHealthyPrefix,
542
540
  lkgRecoveryReplayUnproven,
543
541
  lkgRecoveryEntryUnproven,
542
+ beginServedRequest,
543
+ noteServedModel,
544
+ noteServedReplay,
545
+ noteServedHostInput,
546
+ countServedRefusal,
547
+ forgetServedRecord,
548
+ commitServedRequest,
544
549
  lkgInputIdentity,
545
550
  beginLkgPass,
546
551
  visitMessageContentFields,
@@ -549,6 +554,7 @@ import {
549
554
  signatureForFields,
550
555
  exactReusablePrefix,
551
556
  incrementalLkgContentDigests,
557
+ lkgContentDigest,
552
558
  lkgSlotRejection,
553
559
  captureSlot,
554
560
  getInMemorySlot,
@@ -557,7 +563,6 @@ import {
557
563
  dropSlot,
558
564
  noteEntry,
559
565
  getLkgSlotHeapStats,
560
- TOOL_SWEEP_SCOPED_MARKER,
561
566
  useScopedToolSweep,
562
567
  createPreAdoptionToolSweepResolver,
563
568
  queueMemoryMutation,
@@ -565,10 +570,10 @@ import {
565
570
  GLOBAL_USER_PROFILE_PROJECT_PATH,
566
571
  getProjectState,
567
572
  bumpProjectUserProfileVersion
568
- } from "./index-n0twfvah.js";
573
+ } from "./index-2ctn7q09.js";
569
574
  import {
570
575
  getLastIndexedOrdinal
571
- } from "./index-hkveze74.js";
576
+ } from "./index-3hhq18q0.js";
572
577
  import {
573
578
  SESSION_NOTE_CONDITION_ERROR,
574
579
  getNoteByIdInScope,
@@ -627,7 +632,7 @@ import {
627
632
  embedSessionCompartmentChunks2,
628
633
  getEmbeddingCoverageStatus2,
629
634
  getAutoEmbeddingSessionCoverage2
630
- } from "./index-bamnjp2t.js";
635
+ } from "./index-2m54t4g1.js";
631
636
  import {
632
637
  saveEmbeddingIfHashMatches,
633
638
  invalidateProject2,
@@ -635,7 +640,7 @@ import {
635
640
  } from "./index-4dhv7mqz.js";
636
641
  import {
637
642
  cosineSimilarity
638
- } from "./index-8d7gkgjs.js";
643
+ } from "./index-85chg6fw.js";
639
644
  import {
640
645
  computeCueContentHash,
641
646
  hasMuralCueColumns,
@@ -681,7 +686,7 @@ import {
681
686
  readGitFileChangeTimesSince,
682
687
  verificationFileExists,
683
688
  normalizeVerificationFiles
684
- } from "./index-cwj6qhmf.js";
689
+ } from "./index-kwpweqzs.js";
685
690
  import {
686
691
  renderSingleStoreMigrationRequiredRefusal,
687
692
  SingleStoreMigrationRequiredError,
@@ -702,13 +707,13 @@ import {
702
707
  resolveMemoriesByIdsForSearch2,
703
708
  unifiedSearch2,
704
709
  formatSearchResults2
705
- } from "./index-30sf7e5k.js";
710
+ } from "./index-3b5k5vma.js";
706
711
  import {
707
712
  scheduleReconciliation,
708
713
  scheduleIncrementalIndex,
709
714
  getMessageIndexQueueHeapStats,
710
715
  clearSessionTracking
711
- } from "./index-s131svmx.js";
716
+ } from "./index-7wasafnb.js";
712
717
  import {
713
718
  flushIgnoredMessages2,
714
719
  clearIgnoredMessages2,
@@ -718,7 +723,7 @@ import {
718
723
  import {
719
724
  setRecompStarting2,
720
725
  setRecompTerminal2
721
- } from "./index-97bjd14c.js";
726
+ } from "./index-fbs0f5ch.js";
722
727
  import {
723
728
  makeToolCompositeKey,
724
729
  searchMessageHistoryOffThread,
@@ -761,13 +766,20 @@ import {
761
766
  latestAssistantTurnMessages,
762
767
  hasActiveAnthropicThinkingTurn,
763
768
  retainedActiveThinkingParts,
769
+ LATEST_TURN_THINKING_REMOVED_REASON,
770
+ prepareLatestThinkingRecovery,
771
+ endLatestThinkingRecoveryAfterReset,
772
+ restoredTurnMessages,
773
+ captureLatestTurnOriginals,
774
+ hostInstructionRetentionEnabled,
775
+ isHostInstructionRetentionOn,
776
+ recordHostInstructionDecisions,
764
777
  replayCavemanCompression,
765
778
  DegradedPassRefusalError,
766
779
  degradedPassError,
767
780
  revertHostCheckpointPass,
768
781
  forgetHostCheckpointPass,
769
- hostInstructionRetentionEnabled,
770
- isHostInstructionRetentionOn,
782
+ forceBandConfirmed,
771
783
  pressureBands,
772
784
  forceRide,
773
785
  heuristicsRunOnPass,
@@ -796,7 +808,7 @@ import {
796
808
  abortSessionFailClosed2,
797
809
  evaluateEmergencyFailClosed2,
798
810
  runPostTransformPhase2
799
- } from "./index-wr2t8zb0.js";
811
+ } from "./index-5684dzbv.js";
800
812
  import {
801
813
  ANNOUNCEMENT_VERSION2,
802
814
  ANNOUNCEMENT_FEATURES2,
@@ -811,13 +823,13 @@ import {
811
823
  renderMessageByOrdinal2,
812
824
  renderVerboseRangeForTool2,
813
825
  renderItemByTag2
814
- } from "./index-mjh63zvw.js";
826
+ } from "./index-wpab17w4.js";
815
827
  import {
816
828
  readV2ArchiveOffThread2
817
- } from "./index-ct3ettqt.js";
829
+ } from "./index-3h0wyv22.js";
818
830
  import {
819
831
  renderSearchArchiveOffThread2
820
- } from "./index-5dptmnvd.js";
832
+ } from "./index-esm4farg.js";
821
833
  import {
822
834
  COMPACTION_ENABLED_PATH,
823
835
  isDreamerRunnable,
@@ -16436,7 +16448,7 @@ function registerRpcHandlers(rpcServer, args) {
16436
16448
  const db = readDatabase();
16437
16449
  if (!db)
16438
16450
  return { ok: false, error: "db unavailable" };
16439
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-8ebydg5j.js"));
16451
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-d4nks9da.js"));
16440
16452
  const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-gamjee2f.js"));
16441
16453
  log2(`[rpc] recomp requested for session ${sessionId}`);
16442
16454
  if (!args.client && !args.hiddenCompletionExecutor) {
@@ -16521,7 +16533,7 @@ function registerRpcHandlers(rpcServer, args) {
16521
16533
  const db = readDatabase();
16522
16534
  if (!db)
16523
16535
  return { ok: false, error: "db unavailable" };
16524
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-ya31knav.js"));
16536
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-6189f37j.js"));
16525
16537
  const model = liveSessionState.liveModelBySession.get(sessionId);
16526
16538
  const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
16527
16539
  const ctx = {
@@ -16719,7 +16731,8 @@ var canonicalReasons = new Set([
16719
16731
  "coverage_fold",
16720
16732
  "profile_transition",
16721
16733
  "host_compaction",
16722
- "tag_identity_repair"
16734
+ "tag_identity_repair",
16735
+ "latest_turn_thinking_removed"
16723
16736
  ]);
16724
16737
  var piReasonAliases = {
16725
16738
  project_memory_change: "project_memory_epoch",
@@ -16759,11 +16772,12 @@ function normalizeMaterializeReason(harness, reason, rematerialized) {
16759
16772
  function writeRustTransformDecision(args) {
16760
16773
  const rawDecision = args.decision.trim();
16761
16774
  const decisionUpper = rawDecision.toUpperCase();
16762
- const mapped = decisionUpper === "HARD" || decisionUpper === "MIGRATE_HARD" ? { decision: "execute", materialized: true, bustedThisPass: true } : decisionUpper === "SOFT" || decisionUpper === "EXECUTE" || args.materializeReason === "ttl_idle" ? { decision: "execute", materialized: false, bustedThisPass: true } : decisionUpper === "SOFT+" ? { decision: "defer", materialized: false, bustedThisPass: false } : {
16775
+ const scheduled = decisionUpper === "HARD" || decisionUpper === "MIGRATE_HARD" ? { decision: "execute", materialized: true, bustedThisPass: true } : decisionUpper === "SOFT" || decisionUpper === "EXECUTE" || args.materializeReason === "ttl_idle" ? { decision: "execute", materialized: false, bustedThisPass: true } : decisionUpper === "SOFT+" ? { decision: "defer", materialized: false, bustedThisPass: false } : {
16763
16776
  decision: rawDecision.toLowerCase() || "unknown",
16764
16777
  materialized: false,
16765
16778
  bustedThisPass: false
16766
16779
  };
16780
+ const mapped = args.materializeReason === "latest_turn_thinking_removed" ? { ...scheduled, bustedThisPass: true } : scheduled;
16767
16781
  pendingDecisionBySession.set(args.sessionId, {
16768
16782
  tsMs: args.tsMs ?? Date.now(),
16769
16783
  decision: mapped.decision,
@@ -17151,146 +17165,6 @@ async function maybeDeliverChannel2(sessionId, deps) {
17151
17165
  }
17152
17166
  }
17153
17167
 
17154
- // src/hooks/magic-context/latest-thinking-recovery.ts
17155
- var LATEST_THINKING_RESTORE = "latest_thinking_original";
17156
- var knownRejectedSessions = new Set;
17157
- var lastPassTurnAnchor = new Map;
17158
- var ACTIVE = `${LATEST_THINKING_RESTORE}:`;
17159
- var ARMED = `${LATEST_THINKING_RESTORE}_armed:`;
17160
- var UNRECOVERABLE = `${LATEST_THINKING_RESTORE}_unavailable`;
17161
- var LATEST_THINKING_UNSAFE = "ANTHROPIC_LATEST_TURN_EDIT_UNSAFE: The provider rejected edits to this thinking turn and its original context cannot be safely replayed. Send a new user message or /clear to continue.";
17162
- function armLatestThinkingRecovery(db, sessionId) {
17163
- knownRejectedSessions.add(sessionId);
17164
- ensureSessionMetaRow(db, sessionId);
17165
- const current = getThinkingBindingRecoveryTarget(db, sessionId);
17166
- const anchor = lastPassTurnAnchor.get(sessionId);
17167
- const next = current?.startsWith(ACTIVE) ? UNRECOVERABLE + ":" + current.slice(ACTIVE.length) : current?.startsWith(UNRECOVERABLE) || current?.startsWith(ARMED) ? current : anchor !== undefined ? ARMED + anchor : LATEST_THINKING_RESTORE;
17168
- db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
17169
- }
17170
- function clone(value) {
17171
- if (Array.isArray(value))
17172
- return value.map(clone);
17173
- if (!isRecord(value))
17174
- return value;
17175
- const proto = Object.getPrototypeOf(value);
17176
- if (proto !== Object.prototype && proto !== null)
17177
- return value;
17178
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
17179
- }
17180
- function isThinkingPart2(part) {
17181
- return isRecord(part) && ["thinking", "reasoning", "redacted_thinking"].includes(String(part.type));
17182
- }
17183
- function replayableOriginal(part) {
17184
- if (!isThinkingPart2(part) || !isRecord(part))
17185
- return false;
17186
- const metadata = isRecord(part.metadata) && isRecord(part.metadata.anthropic) ? part.metadata.anthropic : {};
17187
- const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
17188
- return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
17189
- }
17190
- function prepareLatestThinkingRecovery(args) {
17191
- const start = latestAssistantTurnStart(args.messages);
17192
- const anchor = start > 0 ? args.id(args.messages[start - 1], start - 1) : undefined;
17193
- if (anchor === undefined)
17194
- lastPassTurnAnchor.delete(args.sessionId);
17195
- else
17196
- lastPassTurnAnchor.set(args.sessionId, anchor);
17197
- let target;
17198
- try {
17199
- target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
17200
- } catch (error) {
17201
- if (knownRejectedSessions.has(args.sessionId))
17202
- throw contextRefusalError(LATEST_THINKING_UNSAFE);
17203
- return { restore: false, ended: false };
17204
- }
17205
- if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
17206
- knownRejectedSessions.delete(args.sessionId);
17207
- return { restore: false, ended: false };
17208
- }
17209
- const armedAnchor = target.startsWith(ARMED) ? target.slice(ARMED.length) : undefined;
17210
- if (target === LATEST_THINKING_RESTORE || armedAnchor !== undefined && armedAnchor !== anchor) {
17211
- args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
17212
- knownRejectedSessions.delete(args.sessionId);
17213
- return { restore: false, ended: false };
17214
- }
17215
- knownRejectedSessions.add(args.sessionId);
17216
- const savedAnchor = target.startsWith(ACTIVE) ? target.slice(ACTIVE.length) : target.startsWith(UNRECOVERABLE + ":") ? target.slice(UNRECOVERABLE.length + 1) : undefined;
17217
- if (savedAnchor !== undefined && savedAnchor !== anchor) {
17218
- args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
17219
- knownRejectedSessions.delete(args.sessionId);
17220
- return { restore: false, ended: true };
17221
- }
17222
- if (target.startsWith(UNRECOVERABLE) || !anchor)
17223
- throw contextRefusalError(LATEST_THINKING_UNSAFE);
17224
- if (armedAnchor !== undefined) {
17225
- args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(ACTIVE + anchor, args.sessionId, target);
17226
- }
17227
- const active = args.messages.slice(start);
17228
- if (!active.some((message) => args.parts(message).some(replayableOriginal)))
17229
- throw contextRefusalError(LATEST_THINKING_UNSAFE + " [missing-thinking-original]");
17230
- const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
17231
- for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
17232
- if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
17233
- continue;
17234
- const id = decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith("binding_mismatch:") ? decision.slice("binding_mismatch:".length) : decision);
17235
- const index = ids.get(id);
17236
- if (index === undefined || index >= start && !args.parts(args.messages[index]).some(replayableOriginal))
17237
- throw contextRefusalError(LATEST_THINKING_UNSAFE + ` [missing-original:${id}]`);
17238
- }
17239
- return { restore: true, ended: false };
17240
- }
17241
- function endLatestThinkingRecoveryAfterReset(db, sessionId) {
17242
- const target = getThinkingBindingRecoveryTarget(db, sessionId);
17243
- if (target?.startsWith(LATEST_THINKING_RESTORE)) {
17244
- db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, target);
17245
- }
17246
- knownRejectedSessions.delete(sessionId);
17247
- }
17248
- function captureOriginalTurn(messages, parts, setParts) {
17249
- const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
17250
- const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
17251
- const before = messages.slice(0, start);
17252
- return (target = messages) => {
17253
- const first = target.findIndex((message) => originals.some((original) => original.message === message || isRecord(message) && isRecord(original.message) && (isRecord(message.info) && isRecord(original.message.info) && message.info.id === original.message.info.id || message.role === original.message.role && message.timestamp !== undefined && message.timestamp === original.message.timestamp)));
17254
- const prefix = first >= 0 ? target.slice(0, first) : target === messages ? before : target.slice();
17255
- for (const original of originals) {
17256
- setParts(original.message, clone(original.parts));
17257
- }
17258
- target.length = 0;
17259
- target.push(...prefix, ...originals.map((original) => original.message));
17260
- };
17261
- }
17262
- function captureLatestTurnOriginals(messages) {
17263
- return captureOriginalTurn(messages, (message) => message.parts, (message, parts) => {
17264
- message.parts = parts;
17265
- });
17266
- }
17267
- function armBindingRecoverySafely(db, sessionId) {
17268
- if (getThinkingBindingRecoveryTarget(db, sessionId)?.startsWith(LATEST_THINKING_RESTORE))
17269
- armLatestThinkingRecovery(db, sessionId);
17270
- else
17271
- armThinkingBindingRecovery(db, sessionId);
17272
- }
17273
- function armLatestThinkingRecoveryFromError(args) {
17274
- if (!detectLatestTurnThinkingMismatch(args.error))
17275
- return false;
17276
- if (!isAnthropicFamilyRoute(args.providerID, args.modelID))
17277
- return true;
17278
- armLatestThinkingRecovery(args.db, args.sessionId);
17279
- dropSlot(args.sessionId, "latest-thinking-recovery-arm");
17280
- return true;
17281
- }
17282
- function armThinkingBindingRecoveryFromError(args) {
17283
- const mismatch = detectThinkingBindingMismatch(args.error);
17284
- if (!mismatch.isBindingMismatch)
17285
- return false;
17286
- if (!isPrefixBoundThinkingModel(args.providerID, args.modelID))
17287
- return true;
17288
- armBindingRecoverySafely(args.db, args.sessionId);
17289
- sessionLog2(args.sessionId, `thinking binding recovery armed from ${args.source} (provider paths: failing=${mismatch.failingBlockPath ?? "?"} firstChanged=${mismatch.firstChangedPath ?? "?"})`);
17290
- dropSlot(args.sessionId, "thinking-binding-recovery-arm");
17291
- return true;
17292
- }
17293
-
17294
17168
  // src/hooks/magic-context/compaction-off-transition.ts
17295
17169
  import { existsSync as existsSync7 } from "node:fs";
17296
17170
  var loggedUnverifiedMarkerCleanupRetry = false;
@@ -17447,6 +17321,47 @@ function recordCompartmentTriggerError(passOutcome, sessionId, error, log = sess
17447
17321
  log(sessionId, "compartment trigger failed (non-fatal):", error);
17448
17322
  }
17449
17323
 
17324
+ // src/hooks/magic-context/history-boundary-recovery.ts
17325
+ var exhaustedStateBySession = new BoundedSessionMap(512);
17326
+ function inputMessagesKey(messages) {
17327
+ let count = 0;
17328
+ let first = "";
17329
+ let last = "";
17330
+ for (const message of messages) {
17331
+ const id = message.info.id;
17332
+ if (typeof id !== "string" || id.length === 0)
17333
+ continue;
17334
+ if (count === 0)
17335
+ first = id;
17336
+ last = id;
17337
+ count += 1;
17338
+ }
17339
+ return `${count}:${first}:${last}`;
17340
+ }
17341
+ function historyBoundaryRecoveryStateKey(db, sessionId, inputKey) {
17342
+ try {
17343
+ const row = db.prepare(`SELECT
17344
+ (SELECT COUNT(*) FROM compartments WHERE session_id = ?) AS compartments,
17345
+ (SELECT COALESCE(MAX(sequence), -1) FROM compartments WHERE session_id = ?) AS newest,
17346
+ (SELECT COUNT(*) FROM tags WHERE session_id = ? AND status = 'dropped') AS dropped,
17347
+ (SELECT COALESCE(cached_m0_last_baseline_end_message_id, '') FROM session_meta WHERE session_id = ?) AS boundary`).get(sessionId, sessionId, sessionId, sessionId);
17348
+ if (!row)
17349
+ return null;
17350
+ return `${inputKey}|${row.compartments}:${row.newest}|${row.dropped}|${row.boundary ?? ""}`;
17351
+ } catch {
17352
+ return null;
17353
+ }
17354
+ }
17355
+ function markHistoryBoundaryRecoveryExhausted(sessionId, stateKey) {
17356
+ exhaustedStateBySession.set(sessionId, stateKey);
17357
+ }
17358
+ function isHistoryBoundaryRecoveryExhausted(sessionId, stateKey) {
17359
+ return stateKey !== null && exhaustedStateBySession.get(sessionId) === stateKey;
17360
+ }
17361
+ function forgetHistoryBoundaryRecovery(sessionId) {
17362
+ exhaustedStateBySession.delete(sessionId);
17363
+ }
17364
+
17450
17365
  // src/hooks/magic-context/local-wire-reading.ts
17451
17366
  function createLocalWireReadings() {
17452
17367
  const readings = new Map;
@@ -17548,6 +17463,111 @@ function createPassOutcome() {
17548
17463
  };
17549
17464
  }
17550
17465
 
17466
+ // src/hooks/magic-context/signed-thinking-hold.ts
17467
+ var HEAVY_REASONING_TOKENS = 1500;
17468
+ var HEAVY_REASONING_WINDOW_STEPS = 15;
17469
+ var HOLD_CAP_POINTS = 10;
17470
+ var REASONING_TYPES = new Set(["reasoning", "thinking"]);
17471
+ function role(message) {
17472
+ if (!isRecord(message))
17473
+ return;
17474
+ return isRecord(message.info) ? message.info.role : message.role;
17475
+ }
17476
+ function parts(message) {
17477
+ if (!isRecord(message))
17478
+ return [];
17479
+ if (Array.isArray(message.parts))
17480
+ return message.parts;
17481
+ return Array.isArray(message.content) ? message.content : [];
17482
+ }
17483
+ function recordedReasoningTokens(message) {
17484
+ if (!isRecord(message))
17485
+ return;
17486
+ const info = isRecord(message.info) ? message.info : undefined;
17487
+ const candidates = [];
17488
+ if (info && isRecord(info.tokens))
17489
+ candidates.push(info.tokens.reasoning);
17490
+ if (isRecord(message.usage)) {
17491
+ candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
17492
+ }
17493
+ for (const value of candidates) {
17494
+ if (typeof value === "number" && Number.isFinite(value) && value > 0)
17495
+ return value;
17496
+ }
17497
+ return;
17498
+ }
17499
+ function stepReasoningTokens(message, estimateTextTokens) {
17500
+ let text = "";
17501
+ let opaque = false;
17502
+ for (const part of parts(message)) {
17503
+ if (!isRecord(part))
17504
+ continue;
17505
+ const type = String(part.type ?? part.kind);
17506
+ if (type === "redacted_thinking" || part.redacted === true) {
17507
+ opaque = true;
17508
+ continue;
17509
+ }
17510
+ if (!REASONING_TYPES.has(type))
17511
+ continue;
17512
+ const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
17513
+ if (body.length > 0)
17514
+ text += body;
17515
+ else
17516
+ opaque = true;
17517
+ }
17518
+ if (!text && !opaque)
17519
+ return 0;
17520
+ return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
17521
+ }
17522
+ function decideSignedThinkingHold(args) {
17523
+ const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
17524
+ let heavyStepsBack = null;
17525
+ let heavyStepTokens = 0;
17526
+ const start = latestAssistantTurnStart(args.messages);
17527
+ let stepsBack = 0;
17528
+ for (let index = args.messages.length - 1;index >= start; index--) {
17529
+ const message = args.messages[index];
17530
+ if (role(message) !== "assistant" || parts(message).length === 0)
17531
+ continue;
17532
+ stepsBack++;
17533
+ if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
17534
+ break;
17535
+ const tokens = stepReasoningTokens(message, args.estimateTextTokens);
17536
+ if (tokens > HEAVY_REASONING_TOKENS) {
17537
+ heavyStepsBack = stepsBack;
17538
+ heavyStepTokens = tokens;
17539
+ break;
17540
+ }
17541
+ }
17542
+ if (heavyStepsBack === null)
17543
+ return {
17544
+ held: false,
17545
+ reason: "no_recent_heavy_reasoning",
17546
+ heavyStepsBack,
17547
+ heavyStepTokens,
17548
+ capPercentage
17549
+ };
17550
+ const ended = readingEndsHold({
17551
+ usagePercentage: args.usagePercentage,
17552
+ capPercentage,
17553
+ forceBandPressure: args.forceBandPressure
17554
+ });
17555
+ if (ended !== null)
17556
+ return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
17557
+ return {
17558
+ held: true,
17559
+ reason: "heavy_reasoning",
17560
+ heavyStepsBack,
17561
+ heavyStepTokens,
17562
+ capPercentage
17563
+ };
17564
+ }
17565
+ function readingEndsHold(args) {
17566
+ if (!(args.usagePercentage < args.capPercentage))
17567
+ return "above_cap";
17568
+ return args.forceBandPressure ? "force_band" : null;
17569
+ }
17570
+
17551
17571
  // src/hooks/magic-context/priced-pass-sizing.ts
17552
17572
  var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
17553
17573
  var WIDEST_PRICED_PASS_PLAN = {
@@ -17564,6 +17584,11 @@ function planPricedPass(input, usage) {
17564
17584
  schedulerDecision: input.schedulerDecision
17565
17585
  });
17566
17586
  const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
17587
+ const signedThinkingHold = input.signedThinkingHold && (input.signedThinkingHoldCapPercentage === undefined ? !bands.forceBandConfirmed : readingEndsHold({
17588
+ usagePercentage: usage.percentage,
17589
+ capPercentage: input.signedThinkingHoldCapPercentage,
17590
+ forceBandPressure: bands.forceBandConfirmed
17591
+ }) === null);
17567
17592
  const rides = {
17568
17593
  hardFold: input.folds || input.firstRender,
17569
17594
  force: forceRide({
@@ -17579,11 +17604,11 @@ function planPricedPass(input, usage) {
17579
17604
  servedShapeRepair: false
17580
17605
  };
17581
17606
  const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
17582
- signedThinkingHold: input.signedThinkingHold,
17607
+ signedThinkingHold,
17583
17608
  firstRender: input.firstRender,
17584
17609
  emergency: bands.forceBandConfirmed
17585
17610
  });
17586
- const materializationRequested = !input.signedThinkingHold && input.materializationRequested;
17611
+ const materializationRequested = !signedThinkingHold && input.materializationRequested;
17587
17612
  const heuristics = heuristicsRunOnPass({
17588
17613
  compactionOff: input.compactionOff,
17589
17614
  drainAllowed,
@@ -17610,8 +17635,8 @@ function planPricedPass(input, usage) {
17610
17635
  rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
17611
17636
  });
17612
17637
  return {
17613
- editsWholePrefix: drainAllowed && !input.signedThinkingHold,
17614
- clearsReasoning: routine && !input.signedThinkingHold
17638
+ editsWholePrefix: drainAllowed && !signedThinkingHold,
17639
+ clearsReasoning: routine && !signedThinkingHold
17615
17640
  };
17616
17641
  }
17617
17642
  function sameSizingPlan(input, a, b) {
@@ -22381,12 +22406,15 @@ function createRustModeTransform(deps, options) {
22381
22406
  }
22382
22407
  const inputCount = messages.length;
22383
22408
  const inputHasActiveThinking = hasActiveAnthropicThinkingTurn(messages, "anthropic");
22409
+ const rustRecoveryModel = modelFromMessages(messages) ?? deps.liveModelBySession?.get(sessionId);
22384
22410
  const thinkingRecovery = prepareLatestThinkingRecovery({
22385
22411
  db: deps.db,
22386
22412
  sessionId,
22387
22413
  messages,
22388
22414
  id: (message) => message?.info.id,
22389
- parts: (message) => message?.parts ?? []
22415
+ parts: (message) => message?.parts ?? [],
22416
+ modelID: rustRecoveryModel?.modelID,
22417
+ providerID: rustRecoveryModel?.providerID
22390
22418
  });
22391
22419
  const restoreLatestTurnOriginals = thinkingRecovery.restore ? captureLatestTurnOriginals(messages) : undefined;
22392
22420
  let requestInputTokens = 0;
@@ -22633,7 +22661,7 @@ function createRustModeTransform(deps, options) {
22633
22661
  writeRustTransformDecision({
22634
22662
  sessionId,
22635
22663
  decision,
22636
- materializeReason: materializeReason === "none" ? null : materializeReason,
22664
+ materializeReason: thinkingRecovery.removedThisPass && (materializeReason === "none" || materializeReason === "ttl_idle") ? LATEST_TURN_THINKING_REMOVED_REASON : materializeReason !== "none" ? materializeReason : null,
22637
22665
  inputTokens: requestInputTokens,
22638
22666
  tsMs: passObservedAtMs,
22639
22667
  lkgFrozenReleaseReason: applied && served && frozenReleaseReason ? `${frozenReleaseReason};first_changed=${frozenReleaseFirstChanged}` : undefined
@@ -23537,7 +23565,7 @@ function createRustModeTransform(deps, options) {
23537
23565
  const activeThinkingTurn = inputHasActiveThinking && isAnthropicFamilyRoute(model?.providerID, model?.modelID);
23538
23566
  const postprocess = runRustModePostprocess2({
23539
23567
  activeThinkingTurn,
23540
- protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
23568
+ protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(appliedMessages, protectedThinkingMessages) : undefined,
23541
23569
  restoreLatestTurnOriginals: () => restoreLatestTurnOriginals?.(appliedMessages),
23542
23570
  db: deps.db,
23543
23571
  sessionId,
@@ -23697,7 +23725,7 @@ function createRustModeTransform(deps, options) {
23697
23725
  }
23698
23726
  }
23699
23727
  const endRecoveryAfterResetCapture = () => {
23700
- if (signedThinkingReset && thinkingRecovery.restore) {
23728
+ if (signedThinkingReset) {
23701
23729
  endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
23702
23730
  }
23703
23731
  };
@@ -24146,101 +24174,6 @@ function takeSignedThinkingFitSnapshot(args) {
24146
24174
  }
24147
24175
  var snapshotObserver;
24148
24176
 
24149
- // src/hooks/magic-context/signed-thinking-hold.ts
24150
- var HEAVY_REASONING_TOKENS = 1500;
24151
- var HEAVY_REASONING_WINDOW_STEPS = 15;
24152
- var HOLD_CAP_POINTS = 10;
24153
- var REASONING_TYPES = new Set(["reasoning", "thinking"]);
24154
- function role(message) {
24155
- if (!isRecord(message))
24156
- return;
24157
- return isRecord(message.info) ? message.info.role : message.role;
24158
- }
24159
- function parts(message) {
24160
- if (!isRecord(message))
24161
- return [];
24162
- if (Array.isArray(message.parts))
24163
- return message.parts;
24164
- return Array.isArray(message.content) ? message.content : [];
24165
- }
24166
- function recordedReasoningTokens(message) {
24167
- if (!isRecord(message))
24168
- return;
24169
- const info = isRecord(message.info) ? message.info : undefined;
24170
- const candidates = [];
24171
- if (info && isRecord(info.tokens))
24172
- candidates.push(info.tokens.reasoning);
24173
- if (isRecord(message.usage)) {
24174
- candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
24175
- }
24176
- for (const value of candidates) {
24177
- if (typeof value === "number" && Number.isFinite(value) && value > 0)
24178
- return value;
24179
- }
24180
- return;
24181
- }
24182
- function stepReasoningTokens(message, estimateTextTokens) {
24183
- let text = "";
24184
- let opaque = false;
24185
- for (const part of parts(message)) {
24186
- if (!isRecord(part))
24187
- continue;
24188
- const type = String(part.type ?? part.kind);
24189
- if (type === "redacted_thinking" || part.redacted === true) {
24190
- opaque = true;
24191
- continue;
24192
- }
24193
- if (!REASONING_TYPES.has(type))
24194
- continue;
24195
- const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
24196
- if (body.length > 0)
24197
- text += body;
24198
- else
24199
- opaque = true;
24200
- }
24201
- if (!text && !opaque)
24202
- return 0;
24203
- return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
24204
- }
24205
- function decideSignedThinkingHold(args) {
24206
- const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
24207
- let heavyStepsBack = null;
24208
- let heavyStepTokens = 0;
24209
- const start = latestAssistantTurnStart(args.messages);
24210
- let stepsBack = 0;
24211
- for (let index = args.messages.length - 1;index >= start; index--) {
24212
- const message = args.messages[index];
24213
- if (role(message) !== "assistant" || parts(message).length === 0)
24214
- continue;
24215
- stepsBack++;
24216
- if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
24217
- break;
24218
- const tokens = stepReasoningTokens(message, args.estimateTextTokens);
24219
- if (tokens > HEAVY_REASONING_TOKENS) {
24220
- heavyStepsBack = stepsBack;
24221
- heavyStepTokens = tokens;
24222
- break;
24223
- }
24224
- }
24225
- if (heavyStepsBack === null)
24226
- return {
24227
- held: false,
24228
- reason: "no_recent_heavy_reasoning",
24229
- heavyStepsBack,
24230
- heavyStepTokens,
24231
- capPercentage
24232
- };
24233
- if (!(args.usagePercentage < capPercentage))
24234
- return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
24235
- return {
24236
- held: true,
24237
- reason: "heavy_reasoning",
24238
- heavyStepsBack,
24239
- heavyStepTokens,
24240
- capPercentage
24241
- };
24242
- }
24243
-
24244
24177
  // src/hooks/magic-context/temporal-served-projection.ts
24245
24178
  function readLkgTemporalDecisions(db, sessionId, runtime) {
24246
24179
  const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
@@ -24736,23 +24669,46 @@ function storedHistoryBoundaryPresence(db, sessionId) {
24736
24669
  return;
24737
24670
  }
24738
24671
  }
24672
+ var CAUSE_SENTENCES = {
24673
+ "boundary-not-in-request": "The message the history summary ends on is in the host's store but not in the loaded conversation, so Magic Context could not tell which loaded messages the summary already covers.",
24674
+ "boundary-unordered": "Magic Context could not place the message the history summary ends on in the loaded conversation: either it is not there and the host's store could not order it against the messages that are, or the conversation holds it more than once.",
24675
+ "boundary-missing-from-store": "The message the history summary ends on is no longer in the host's store."
24676
+ };
24677
+ function historyBoundaryRefusalText(cause, remedy) {
24678
+ const failure = renderUserFacingFailure(remedy === "send-again" ? "history_boundary_recovering" : "history_boundary_unresolved", "plain");
24679
+ return cause ? `${CAUSE_SENTENCES[cause]} ${failure}` : failure;
24680
+ }
24739
24681
 
24740
24682
  class UnresolvedHistoryBoundaryError extends Error {
24741
24683
  estimatedTokens;
24742
24684
  contextLimitTokens;
24743
- boundaryPresent;
24685
+ refusalCause;
24686
+ remedy;
24744
24687
  code = "UNRESOLVED_HISTORY_BOUNDARY";
24745
24688
  recoverable = true;
24746
- constructor(estimatedTokens, contextLimitTokens, boundaryPresent) {
24747
- const reason = boundaryPresent === true ? "The boundary row is present in the host store but out of order relative to the loaded history. " : boundaryPresent === false ? "The boundary row is missing from the host store. " : "";
24748
- super(reason + renderUserFacingFailure("history_boundary_unresolved", "plain"));
24689
+ constructor(estimatedTokens, contextLimitTokens, refusalCause, remedy = "flush") {
24690
+ super(historyBoundaryRefusalText(refusalCause, remedy));
24749
24691
  this.estimatedTokens = estimatedTokens;
24750
24692
  this.contextLimitTokens = contextLimitTokens;
24751
- this.boundaryPresent = boundaryPresent;
24693
+ this.refusalCause = refusalCause;
24694
+ this.remedy = remedy;
24752
24695
  this.name = "UnresolvedHistoryBoundaryError";
24753
24696
  }
24754
24697
  }
24698
+ function historyBoundaryRefusalCause(trimRefusal, boundaryInStore) {
24699
+ if (boundaryInStore === false)
24700
+ return "boundary-missing-from-store";
24701
+ return trimRefusal ?? undefined;
24702
+ }
24755
24703
  // src/hooks/magic-context/transform.ts
24704
+ function afterCapture(sessionId, statement, run) {
24705
+ try {
24706
+ return run();
24707
+ } catch (error) {
24708
+ sessionLog2(sessionId, `${statement} failed after the request was decided; serving the pass:`, error);
24709
+ return;
24710
+ }
24711
+ }
24756
24712
  var MESSAGE_TOKENS_CACHE_MAX = 100;
24757
24713
  var messageTokensBySession = new BoundedSessionMap(MESSAGE_TOKENS_CACHE_MAX);
24758
24714
  function getMessageTokensCache(sessionId) {
@@ -24852,6 +24808,7 @@ function createTransform(deps) {
24852
24808
  const clearSessionLogState = (sessionId) => {
24853
24809
  prefixHoldLogTurnIds.delete(sessionId);
24854
24810
  clearDiagnosticLogState(sessionId);
24811
+ forgetHistoryBoundaryRecovery(sessionId);
24855
24812
  };
24856
24813
  const unmanagedOverWindowSessions = new Set;
24857
24814
  const localWireReadings = createLocalWireReadings();
@@ -25086,12 +25043,21 @@ function createTransform(deps) {
25086
25043
  }
25087
25044
  }
25088
25045
  const activeThinkingModel = findLastAssistantModel(messages) ?? deps.liveModelBySession?.get(sessionId);
25046
+ const thinkingRecoveryModel = findNewestUserModel(messages) ?? deps.liveModelBySession?.get(sessionId);
25047
+ try {
25048
+ retryBindingRecoveryClear(db, sessionId);
25049
+ } catch (error) {
25050
+ sessionLog2(sessionId, "thinking binding recovery: retried clear failed:", error);
25051
+ }
25052
+ const appliedBindingRecoveryTarget = bindingRecoveryAwaitingClear(sessionId);
25089
25053
  const thinkingRecovery = prepareLatestThinkingRecovery({
25090
25054
  db,
25091
25055
  sessionId,
25092
25056
  messages,
25093
25057
  id: (message) => message?.info.id,
25094
- parts: (message) => message?.parts ?? []
25058
+ parts: (message) => message?.parts ?? [],
25059
+ modelID: thinkingRecoveryModel?.modelID,
25060
+ providerID: thinkingRecoveryModel?.providerID
25095
25061
  });
25096
25062
  if (thinkingRecovery.ended)
25097
25063
  deps.pendingMaterializationSessions?.add(sessionId);
@@ -25144,6 +25110,7 @@ function createTransform(deps) {
25144
25110
  } else {
25145
25111
  clearDetectedContextLimit(db, sessionId);
25146
25112
  clearEmergencyRecovery(db, sessionId);
25113
+ forgetHistoryBoundaryRecovery(sessionId);
25147
25114
  }
25148
25115
  deps.contextUsageMap.delete(sessionId);
25149
25116
  sessionMeta = {
@@ -25187,6 +25154,8 @@ function createTransform(deps) {
25187
25154
  let recoveryNoEligibleHeadCount = earlyStateSnapshot.protectedTail.recoveryNoEligibleHeadCount;
25188
25155
  let emergencyRecoveryOrigin = null;
25189
25156
  let usagePercentageSynthetic = false;
25157
+ const passInputKey = inputMessagesKey(messages);
25158
+ let recoveryStateKeyAtPassStart = null;
25190
25159
  if (fullFeatureMode && !compactionOff) {
25191
25160
  try {
25192
25161
  const armModel = deps.liveModelBySession?.get(sessionId);
@@ -25204,22 +25173,29 @@ function createTransform(deps) {
25204
25173
  overflowStateMutatedThisPass = true;
25205
25174
  }
25206
25175
  const overflowState = overflowStateMutatedThisPass ? getOverflowState(db, sessionId) : earlyStateSnapshot.overflow;
25207
- emergencyRecoveryArmed = overflowState.needsEmergencyRecovery;
25208
- emergencyRecoveryOrigin = overflowState.emergencyRecoveryOrigin;
25176
+ if (overflowState.needsEmergencyRecovery) {
25177
+ recoveryStateKeyAtPassStart = historyBoundaryRecoveryStateKey(db, sessionId, passInputKey);
25178
+ }
25179
+ const recoveryIdle = overflowState.needsEmergencyRecovery && overflowState.emergencyRecoveryOrigin === "history_boundary_over_window" && isHistoryBoundaryRecoveryExhausted(sessionId, recoveryStateKeyAtPassStart);
25180
+ if (recoveryIdle) {
25181
+ sessionLog2(sessionId, "transform: recovery for an uncut history already ran on this exact state and made no room; idle until the conversation, its summaries or its dropped tool output change");
25182
+ }
25183
+ emergencyRecoveryArmed = overflowState.needsEmergencyRecovery && !recoveryIdle;
25184
+ emergencyRecoveryOrigin = recoveryIdle ? null : overflowState.emergencyRecoveryOrigin;
25209
25185
  if (contextUsageEarly.percentage < 80 && !overflowState.needsEmergencyRecovery) {
25210
25186
  resetProtectedTailNoEligibleHead(db, sessionId);
25211
25187
  recoveryNoEligibleHeadCount = 0;
25212
25188
  }
25213
25189
  const noHeadEscape = overflowState.needsEmergencyRecovery && recoveryNoEligibleHeadCount >= RECOVERY_NO_HEAD_LIMIT;
25214
25190
  recoveryNoHeadEscapeActive = noHeadEscape;
25215
- if (overflowState.needsEmergencyRecovery && contextUsageEarly.percentage < 95 && !noHeadEscape) {
25191
+ if (overflowState.needsEmergencyRecovery && !recoveryIdle && contextUsageEarly.percentage < 95 && !noHeadEscape) {
25216
25192
  sessionLog2(sessionId, `transform: bumping percentage to 95% due to overflow recovery flag (was ${contextUsageEarly.percentage.toFixed(1)}%, detectedLimit=${overflowState.detectedContextLimit || "unknown"})`);
25217
25193
  contextUsageEarly = {
25218
25194
  ...contextUsageEarly,
25219
25195
  percentage: 95
25220
25196
  };
25221
25197
  usagePercentageSynthetic = true;
25222
- } else if (recoveryNoHeadEscapeActive && deps.client) {
25198
+ } else if (recoveryNoHeadEscapeActive && !recoveryIdle && deps.client) {
25223
25199
  withoutSqliteTransformPass2(() => sendStatusNotification2(deps.client, sessionId, "Magic Context can't compact yet — the recent history is a single in-progress block. Continuing; it will compact once the block completes. Run `/ctx-recomp` if this persists.", runNotificationParams(sessionId) ?? {}));
25224
25200
  }
25225
25201
  } catch (error) {
@@ -25235,6 +25211,7 @@ function createTransform(deps) {
25235
25211
  deps.liveModelBySession?.set(sessionId, recovered);
25236
25212
  }
25237
25213
  }
25214
+ noteServedModel(sessionId, modelForBudget);
25238
25215
  const resolvedProviderID = modelForBudget?.providerID;
25239
25216
  activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
25240
25217
  const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
@@ -25307,6 +25284,12 @@ function createTransform(deps) {
25307
25284
  messages,
25308
25285
  usagePercentage: contextUsageEarly.percentage,
25309
25286
  executeThresholdPercentage: effectiveExecuteThresholdPercentage,
25287
+ forceBandPressure: forceBandConfirmed({
25288
+ percentage: contextUsageEarly.percentage,
25289
+ fromEstimate: hostOverWindow,
25290
+ forceMaterializationPercentage,
25291
+ compactionOff
25292
+ }),
25310
25293
  estimateTextTokens: (text) => {
25311
25294
  holdProseRatio ??= sessionDecisionCalibration(db, sessionId).proseRatio;
25312
25295
  return estimateTokens(text) * holdProseRatio;
@@ -25959,6 +25942,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25959
25942
  schedulerDecision,
25960
25943
  forceMaterializationPercentage,
25961
25944
  signedThinkingHold: activeThinkingPrefixHold,
25945
+ signedThinkingHoldCapPercentage: !compactionOff && signedThinkingHold?.held === true ? signedThinkingHold.capPercentage : undefined,
25962
25946
  firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
25963
25947
  folds: protectionFoldWillBust,
25964
25948
  explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
@@ -26073,6 +26057,20 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26073
26057
  sessionLog2(sessionId, `transform: unknown provider usage; using ${reading.usedProviderInput ? "provider-proven input" : "wire estimate"} for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} trusted=${pressureEstimate.trusted} wireTokens=${pressureEstimate.tokens} pressureTokens=${pressureEstimate.pressureTokens}${reading.grewPastSavedReading ? ` grewPastSavedReading=${savedProviderReading?.percentage.toFixed(1)}` : ""} ${sizedPlan}`);
26074
26058
  }
26075
26059
  }
26060
+ const sizedHoldEnd = activeThinkingPrefixHold && !compactionOff && signedThinkingHold?.held === true ? readingEndsHold({
26061
+ usagePercentage: contextUsage.percentage,
26062
+ capPercentage: signedThinkingHold.capPercentage,
26063
+ forceBandPressure: forceBandConfirmed({
26064
+ percentage: contextUsage.percentage,
26065
+ fromEstimate: contextUsageFromEstimate,
26066
+ forceMaterializationPercentage,
26067
+ compactionOff
26068
+ })
26069
+ }) : null;
26070
+ if (sizedHoldEnd !== null && signedThinkingHold) {
26071
+ activeThinkingPrefixHold = false;
26072
+ sessionLog2(sessionId, `signed thinking hold: held=false reason=${sizedHoldEnd} heavyStepsBack=${signedThinkingHold.heavyStepsBack ?? "none"} heavyStepTokens=${signedThinkingHold.heavyStepTokens} usage=${contextUsage.percentage.toFixed(1)}% cap=${signedThinkingHold.capPercentage}% (sized reading${contextUsageFromEstimate ? ", local count" : ""})`);
26073
+ }
26076
26074
  const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
26077
26075
  const protectionFloor = resolveEpochFloorForPass(db, sessionId, {
26078
26076
  configuredOverride: deps.protectedTokens,
@@ -26097,6 +26095,22 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26097
26095
  opencode2: deps.storeGeneration === "v2",
26098
26096
  structuralSentinelUpgradeFailed,
26099
26097
  releaseRecoveryPrefix: releaseRecoveryReplay,
26098
+ frozenRecoveryRequest: recovery.prefix ? () => {
26099
+ try {
26100
+ const frozen = JSON.parse(recovery.prefix?.json ?? "null");
26101
+ return Array.isArray(frozen) ? frozen : null;
26102
+ } catch {
26103
+ return null;
26104
+ }
26105
+ } : undefined,
26106
+ restartedLastServedRequest: recovery.restartedSlotJson !== undefined ? () => {
26107
+ try {
26108
+ const saved = JSON.parse(recovery.restartedSlotJson ?? "");
26109
+ return Array.isArray(saved) ? saved : null;
26110
+ } catch {
26111
+ return null;
26112
+ }
26113
+ } : undefined,
26100
26114
  normalizeRecoveryTail,
26101
26115
  compactionMarkerStrategy: deps.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy2,
26102
26116
  sessionId,
@@ -26178,10 +26192,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26178
26192
  protectedTools: deps.protectedTools,
26179
26193
  resolvedProviderID,
26180
26194
  activeThinkingTurn,
26181
- protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
26182
- restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...protectedThinkingMessages].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
26195
+ protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(messages, protectedThinkingMessages) : undefined,
26196
+ restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...restoredTurnMessages(messages, protectedThinkingMessages)].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
26183
26197
  restoreLatestTurnOriginals,
26184
26198
  resolvedModelID: modelForBudget?.modelID,
26199
+ appliedBindingRecoveryTarget,
26185
26200
  thinkingBindingRecoveryEnabledForModel: isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID),
26186
26201
  trailingBlankSourceDecisions,
26187
26202
  passOutcome,
@@ -26216,7 +26231,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26216
26231
  const suffix = recoveryTailSources.flatMap(({ identity, pristineSystem }) => pristineSystem ? [pristineSystem] : renderedById.get(identity) ?? []);
26217
26232
  messages.splice(0, messages.length, ...JSON.parse(recovery.prefix.json), ...suffix);
26218
26233
  }
26219
- const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : undefined);
26234
+ const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : postTransformResult.restartHeadChanged ? "lkg_restart_head_changed" : undefined);
26220
26235
  if (recoveryReleaseReason)
26221
26236
  postTransformResult.bustedThisPass = true;
26222
26237
  passOutcome.markFinalized();
@@ -26303,6 +26318,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26303
26318
  throw contextRefusalError("The request remains over the model window after stripping signed thinking and reclaiming context");
26304
26319
  }
26305
26320
  }
26321
+ const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
26322
+ const keepRecoveryArmed = () => {
26323
+ if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
26324
+ return;
26325
+ try {
26326
+ if (getOverflowState(db, sessionId).needsEmergencyRecovery)
26327
+ return;
26328
+ recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
26329
+ } catch (error) {
26330
+ throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
26331
+ cause: error
26332
+ });
26333
+ }
26334
+ sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
26335
+ };
26306
26336
  if (postTransformResult.prefixTrimStatus === "refused") {
26307
26337
  const untrimmed = finalWireEstimate ?? estimateFinalWireInputTokens({
26308
26338
  messages,
@@ -26313,8 +26343,35 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26313
26343
  sessionId
26314
26344
  });
26315
26345
  if (untrimmed.tokens > boundaryContextLimit) {
26316
- sessionLog2(sessionId, `history boundary unresolved: prefix trim refused and the untrimmed request estimate ${untrimmed.tokens} (trusted=${untrimmed.trusted}) exceeds the context limit ${boundaryContextLimit}; not sending it`);
26317
- throw new UnresolvedHistoryBoundaryError(untrimmed.tokens, boundaryContextLimit, storedHistoryBoundaryPresence(db, sessionId));
26346
+ const stateKey = historyBoundaryRecoveryStateKey(db, sessionId, passInputKey);
26347
+ let remedy = "flush";
26348
+ let recovery;
26349
+ if (emergencyRecoveryArmed && emergencyRecoveryOrigin !== null) {
26350
+ const madeRoom = compartmentPhase.published || postTransformResult.droppedCount > 0 || postTransformResult.emergencyReclaimedTokens > 0 || stateKey !== null && recoveryStateKeyAtPassStart !== null && stateKey !== recoveryStateKeyAtPassStart;
26351
+ if (madeRoom) {
26352
+ keepRecoveryArmed();
26353
+ remedy = "send-again";
26354
+ recovery = `${emergencyRecoveryOrigin} recovery made room this pass but not enough; it stays armed for the next turn`;
26355
+ } else {
26356
+ if (stateKey !== null)
26357
+ markHistoryBoundaryRecoveryExhausted(sessionId, stateKey);
26358
+ recovery = `${emergencyRecoveryOrigin} recovery ran this pass and made no room; it stays idle on this state`;
26359
+ }
26360
+ } else if (!untrimmed.trusted) {
26361
+ recovery = "the estimate is not calibrated, so recovery is not armed";
26362
+ } else if (isHistoryBoundaryRecoveryExhausted(sessionId, stateKey)) {
26363
+ recovery = "recovery already ran on this exact state and made no room";
26364
+ } else {
26365
+ try {
26366
+ recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, "history_boundary_over_window");
26367
+ remedy = "send-again";
26368
+ recovery = "overflow recovery armed (history_boundary_over_window) for the next pass";
26369
+ } catch (error) {
26370
+ recovery = `arming overflow recovery failed: ${getErrorMessage(error)}`;
26371
+ }
26372
+ }
26373
+ sessionLog2(sessionId, `history boundary unresolved: prefix trim refused (${postTransformResult.prefixTrimRefusal ?? "no reason recorded"}) and the untrimmed request estimate ${untrimmed.tokens} (trusted=${untrimmed.trusted}) exceeds the context limit ${boundaryContextLimit}; not sending it; ${recovery}`);
26374
+ throw new UnresolvedHistoryBoundaryError(untrimmed.tokens, boundaryContextLimit, historyBoundaryRefusalCause(postTransformResult.prefixTrimRefusal, storedHistoryBoundaryPresence(db, sessionId)), remedy);
26318
26375
  }
26319
26376
  }
26320
26377
  if (unmanagedOverWindowPass) {
@@ -26334,21 +26391,6 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26334
26391
  unmanagedOverWindowSessions.delete(sessionId);
26335
26392
  sessionLog2(sessionId, `over-window first pass reduced: the request is about ${servedTokens} tokens (history started at ${unmanagedOverWindowPass.tokens}), under the ${unmanagedOverWindowPass.limit}-token window`);
26336
26393
  }
26337
- const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
26338
- const keepRecoveryArmed = () => {
26339
- if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
26340
- return;
26341
- try {
26342
- if (getOverflowState(db, sessionId).needsEmergencyRecovery)
26343
- return;
26344
- recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
26345
- } catch (error) {
26346
- throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
26347
- cause: error
26348
- });
26349
- }
26350
- sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
26351
- };
26352
26394
  const timedOutHistorianFailure = compartmentPhase.historianJoinTimedOut ? historianJoinFailClosedMessage({
26353
26395
  timedOut: true,
26354
26396
  budgetMs: compartmentPhase.historianJoinBudgetMs,
@@ -26386,9 +26428,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26386
26428
  });
26387
26429
  if (emergencyFailClosed.disarm) {
26388
26430
  clearEmergencyRecovery(db, sessionId);
26431
+ forgetHistoryBoundaryRecovery(sessionId);
26389
26432
  sessionLog2(sessionId, `emergency disarm: trusted final-wire ${emergencyFailClosed.disarm.finalWireTokens} under limit ${emergencyFailClosed.disarm.provenLimitTokens}`);
26390
26433
  } else if (recoveryAdmissionPass && !emergencyFailClosed.shouldAbort && recoveryServedRequest !== undefined) {
26391
26434
  clearEmergencyRecovery(db, sessionId);
26435
+ forgetHistoryBoundaryRecovery(sessionId);
26392
26436
  sessionLog2(sessionId, `transform: recovery request admitted: about ${recoveryServedRequest.tokens} tokens, within ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; ${emergencyRecoveryOrigin} recovery ends`);
26393
26437
  }
26394
26438
  if (emergencyFailClosed.shouldAbort) {
@@ -26453,11 +26497,25 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26453
26497
  if (!finalWireEstimate) {
26454
26498
  sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
26455
26499
  }
26500
+ const instructionDecisions = postTransformResult.pendingHostInstructionDecisions;
26501
+ const reclaim = instructionDecisions?.reclaim;
26502
+ const decisionsDue = instructionDecisions !== undefined && (instructionDecisions.retention || reclaim?.hasDecisions === true);
26456
26503
  if (!compactionOff) {
26457
26504
  const stillUntagged = untaggedReplayTailServed && !recoveryNormalized ? [...untaggedReplayIds] : [];
26458
- if (JSON.stringify([...new Set(stillUntagged)].sort()) !== JSON.stringify([...new Set(persistedUntaggedInputIds)].sort()) && !persistLkgUntaggedInputIds(db, sessionId, stillUntagged))
26505
+ const untaggedChanged = JSON.stringify([...new Set(stillUntagged)].sort()) !== JSON.stringify([...new Set(persistedUntaggedInputIds)].sort());
26506
+ if ((untaggedChanged || decisionsDue) && !persistLkgUntaggedInputIds(db, sessionId, untaggedChanged ? stillUntagged : undefined, decisionsDue ? (doc) => recordHostInstructionDecisions(doc, {
26507
+ retention: instructionDecisions?.retention === true,
26508
+ record: reclaim ? (target) => reclaim.record(target) : undefined
26509
+ }) : undefined)) {
26510
+ if (decisionsDue) {
26511
+ const failure = new Error("Cannot persist the last-good records with this pass's instruction-row decisions");
26512
+ sessionLog2(sessionId, "transform refused degraded pass site=host-instruction-retention-persistence-failure:", failure);
26513
+ failPass("host-instruction-retention-persistence-failure", failure);
26514
+ }
26459
26515
  throw new Error("Cannot persist the last-good untagged-message record");
26516
+ }
26460
26517
  }
26518
+ reclaim?.markRetired();
26461
26519
  const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock2(messages, modelForBudget?.providerID, modelForBudget?.modelID);
26462
26520
  finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
26463
26521
  if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
@@ -26478,8 +26536,10 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26478
26536
  agentName: notificationParams?.agent
26479
26537
  });
26480
26538
  if (captured) {
26481
- const capturedSlot = getInMemorySlot(sessionId);
26482
- if (capturedSlot) {
26539
+ afterCapture(sessionId, "deferred last-good save", () => {
26540
+ const capturedSlot = getInMemorySlot(sessionId);
26541
+ if (!capturedSlot)
26542
+ return;
26483
26543
  const revision = lkgDirtyRevision(sessionId) ?? dirtyLkgRecoveryRevision(sessionId, capturedSlot);
26484
26544
  const fence = {
26485
26545
  ownDirtyRevision: revision,
@@ -26499,7 +26559,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26499
26559
  sessionLog2(sessionId, "Last-good deferred publication remains uncertified:", error);
26500
26560
  }
26501
26561
  }));
26502
- }
26562
+ });
26503
26563
  noteLkgHealthyPrefix(sessionId, lkgInput, messages, !!recoveryReleaseReason);
26504
26564
  }
26505
26565
  if (!captured) {
@@ -26513,94 +26573,98 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26513
26573
  }
26514
26574
  sessionLog2(sessionId, `lkg_capture_declined degradations=${passOutcome.degradations.map((item) => item.site).join(",")}`);
26515
26575
  }
26516
- if (postTransformResult.bustedThisPass || hardCacheExpired) {
26517
- recordPendingTransformDecision(sessionId, {
26518
- tsMs: Date.now(),
26519
- decision: schedulerDecision,
26520
- materialized: postTransformResult.materialized,
26521
- materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason ?? (hardCacheExpired ? "ttl_idle" : null), postTransformResult.materialized),
26522
- systemHashPrev: postTransformResult.systemHashPrev,
26523
- systemHashNew: postTransformResult.systemHashNew,
26524
- m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
26525
- m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
26526
- m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
26527
- m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
26528
- emergency: postTransformResult.emergency,
26529
- droppedTokens: postTransformResult.droppedTokens,
26530
- droppedCount: postTransformResult.droppedCount,
26531
- inputTokens: contextUsage.inputTokens,
26532
- bustedThisPass: true,
26533
- lkgFrozenReleaseReason: recoveryReleaseReason
26534
- });
26535
- } else {
26536
- noteOpenCodeUnbustedPass(sessionId, {
26537
- tsMs: Date.now(),
26538
- decision: schedulerDecision,
26539
- materialized: postTransformResult.materialized,
26540
- materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
26541
- systemHashPrev: postTransformResult.systemHashPrev,
26542
- systemHashNew: postTransformResult.systemHashNew,
26543
- m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
26544
- m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
26545
- m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
26546
- m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
26547
- emergency: postTransformResult.emergency,
26548
- droppedTokens: postTransformResult.droppedTokens,
26549
- droppedCount: postTransformResult.droppedCount,
26550
- inputTokens: contextUsage.inputTokens,
26551
- bustedThisPass: false
26552
- });
26553
- }
26554
- logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
26555
- const msgTokens = getMessageTokensCache(sessionId);
26556
- let storedByMessage = new Map;
26557
- const uncachedMessageIds = messages.flatMap((message) => {
26558
- const messageId = message.info.id;
26559
- return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
26576
+ afterCapture(sessionId, "transform decision record", () => {
26577
+ if (postTransformResult.bustedThisPass || hardCacheExpired || thinkingRecovery.removedThisPass) {
26578
+ recordPendingTransformDecision(sessionId, {
26579
+ tsMs: Date.now(),
26580
+ decision: schedulerDecision,
26581
+ materialized: postTransformResult.materialized,
26582
+ materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason ?? (thinkingRecovery.removedThisPass ? LATEST_TURN_THINKING_REMOVED_REASON : hardCacheExpired ? "ttl_idle" : null), postTransformResult.materialized),
26583
+ systemHashPrev: postTransformResult.systemHashPrev,
26584
+ systemHashNew: postTransformResult.systemHashNew,
26585
+ m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
26586
+ m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
26587
+ m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
26588
+ m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
26589
+ emergency: postTransformResult.emergency,
26590
+ droppedTokens: postTransformResult.droppedTokens,
26591
+ droppedCount: postTransformResult.droppedCount,
26592
+ inputTokens: contextUsage.inputTokens,
26593
+ bustedThisPass: true,
26594
+ lkgFrozenReleaseReason: recoveryReleaseReason
26595
+ });
26596
+ } else {
26597
+ noteOpenCodeUnbustedPass(sessionId, {
26598
+ tsMs: Date.now(),
26599
+ decision: schedulerDecision,
26600
+ materialized: postTransformResult.materialized,
26601
+ materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
26602
+ systemHashPrev: postTransformResult.systemHashPrev,
26603
+ systemHashNew: postTransformResult.systemHashNew,
26604
+ m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
26605
+ m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
26606
+ m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
26607
+ m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
26608
+ emergency: postTransformResult.emergency,
26609
+ droppedTokens: postTransformResult.droppedTokens,
26610
+ droppedCount: postTransformResult.droppedCount,
26611
+ inputTokens: contextUsage.inputTokens,
26612
+ bustedThisPass: false
26613
+ });
26614
+ }
26560
26615
  });
26561
- if (uncachedMessageIds.length > 0) {
26562
- try {
26563
- storedByMessage = omitIncompleteFileTokenTotals(db, sessionId, messages.flatMap((message) => message.info.id ? [{ id: message.info.id, parts: message.parts }] : []), getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds));
26564
- } catch {
26565
- storedByMessage = new Map;
26566
- }
26567
- }
26568
- let conversationTokens = 0;
26569
- let toolCallTokens = 0;
26570
- for (const message of messages) {
26571
- const mid = message.info.id;
26572
- if (mid) {
26573
- const cached = msgTokens.get(mid);
26574
- if (cached) {
26575
- conversationTokens += cached.conversation;
26576
- toolCallTokens += cached.toolCall;
26577
- continue;
26616
+ logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
26617
+ afterCapture(sessionId, "conversation token estimate", () => {
26618
+ const msgTokens = getMessageTokensCache(sessionId);
26619
+ let storedByMessage = new Map;
26620
+ const uncachedMessageIds = messages.flatMap((message) => {
26621
+ const messageId = message.info.id;
26622
+ return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
26623
+ });
26624
+ if (uncachedMessageIds.length > 0) {
26625
+ try {
26626
+ storedByMessage = omitIncompleteFileTokenTotals(db, sessionId, messages.flatMap((message) => message.info.id ? [{ id: message.info.id, parts: message.parts }] : []), getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds));
26627
+ } catch {
26628
+ storedByMessage = new Map;
26578
26629
  }
26579
- const stored = storedByMessage.get(mid);
26580
- if (stored && !stored.hasNull) {
26581
- conversationTokens += stored.conversation;
26582
- toolCallTokens += stored.toolCall;
26583
- msgTokens.set(mid, {
26584
- conversation: stored.conversation,
26585
- toolCall: stored.toolCall
26586
- });
26587
- continue;
26630
+ }
26631
+ let conversationTokens = 0;
26632
+ let toolCallTokens = 0;
26633
+ for (const message of messages) {
26634
+ const mid = message.info.id;
26635
+ if (mid) {
26636
+ const cached = msgTokens.get(mid);
26637
+ if (cached) {
26638
+ conversationTokens += cached.conversation;
26639
+ toolCallTokens += cached.toolCall;
26640
+ continue;
26641
+ }
26642
+ const stored = storedByMessage.get(mid);
26643
+ if (stored && !stored.hasNull) {
26644
+ conversationTokens += stored.conversation;
26645
+ toolCallTokens += stored.toolCall;
26646
+ msgTokens.set(mid, {
26647
+ conversation: stored.conversation,
26648
+ toolCall: stored.toolCall
26649
+ });
26650
+ continue;
26651
+ }
26588
26652
  }
26653
+ const estimated = estimateMessageTokens(message);
26654
+ if (mid)
26655
+ msgTokens.set(mid, estimated);
26656
+ conversationTokens += estimated.conversation;
26657
+ toolCallTokens += estimated.toolCall;
26589
26658
  }
26590
- const estimated = estimateMessageTokens(message);
26591
- if (mid)
26592
- msgTokens.set(mid, estimated);
26593
- conversationTokens += estimated.conversation;
26594
- toolCallTokens += estimated.toolCall;
26595
- }
26596
- try {
26597
- updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
26598
- } catch (error) {
26599
- const code = error?.code;
26600
- if (code !== "SQLITE_BUSY") {
26601
- sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
26659
+ try {
26660
+ updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
26661
+ } catch (error) {
26662
+ const code = error?.code;
26663
+ if (code !== "SQLITE_BUSY") {
26664
+ sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
26665
+ }
26602
26666
  }
26603
- }
26667
+ });
26604
26668
  const channelBaseline = deps.channel1StateBySession?.get(sessionId);
26605
26669
  if (ctxReduceCallable && !compactionOff && channelBaseline) {
26606
26670
  try {
@@ -26639,14 +26703,16 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26639
26703
  }
26640
26704
  const elapsed = (performance.now() - startTime).toFixed(1);
26641
26705
  sessionLog2(sessionId, `transform completed in ${elapsed}ms (${messages.length} messages, ${targets.size} targets, watermark: ${watermark})`);
26642
- withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId));
26706
+ afterCapture(sessionId, "auto-embed scheduling", () => withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId)));
26643
26707
  const bindingRecovery = postTransformResult.thinkingBindingRecovery;
26644
26708
  if (bindingRecovery) {
26645
- const cleared = clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget);
26646
- sessionLog2(sessionId, `thinking binding recovery: stripped bound reasoning from ${bindingRecovery.messageIds.length} assistant(s) [${bindingRecovery.messageIds.join(",")}]; flag=${cleared ? "cleared" : "rearmed"}`);
26709
+ const cleared = afterCapture(sessionId, "thinking binding recovery clear", () => clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget));
26710
+ if (cleared === undefined)
26711
+ noteBindingRecoveryAwaitingClear(sessionId, bindingRecovery.flagTarget);
26712
+ sessionLog2(sessionId, `thinking binding recovery: stripped bound reasoning from ${bindingRecovery.messageIds.length} assistant(s) [${bindingRecovery.messageIds.join(",")}]; flag=${cleared === undefined ? "kept" : cleared ? "cleared" : "rearmed"}`);
26647
26713
  }
26648
26714
  if (passOutcome.captureEligible)
26649
- finalWireUsage.capture(sessionId, {
26715
+ afterCapture(sessionId, "final wire usage capture", () => finalWireUsage.capture(sessionId, {
26650
26716
  messages,
26651
26717
  systemPromptTokens: sessionMeta.systemPromptTokens,
26652
26718
  providerID: modelForBudget?.providerID,
@@ -26654,8 +26720,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
26654
26720
  agentName: notificationParams.agent,
26655
26721
  sessionId,
26656
26722
  systemPromptHash: sessionMeta.systemPromptHash
26657
- });
26658
- deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted);
26723
+ }));
26724
+ afterCapture(sessionId, "pass permission report", () => deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted));
26659
26725
  };
26660
26726
  const timedTransform = (input, output) => withTransformTimingSummary(async () => {
26661
26727
  const sessionId = findSessionId(output.messages);
@@ -27448,6 +27514,7 @@ function tryMessagesTransformLkgReplay(args) {
27448
27514
  } else {
27449
27515
  const inputMessages = output.messages;
27450
27516
  const keys = resolveLkgModelKeys(inputMessages);
27517
+ const hostTailDigests = rust ? [] : entry.pristineTail.map(lkgContentDigest);
27451
27518
  const replay = replayLkg({
27452
27519
  sessionId,
27453
27520
  messages: inputMessages,
@@ -27514,6 +27581,7 @@ function tryMessagesTransformLkgReplay(args) {
27514
27581
  entry,
27515
27582
  messages: replay.messages,
27516
27583
  ...keys,
27584
+ hostTailDigests,
27517
27585
  db
27518
27586
  }))
27519
27587
  return false;
@@ -27521,6 +27589,7 @@ function tryMessagesTransformLkgReplay(args) {
27521
27589
  args.onLkgReplay?.();
27522
27590
  noteExternalLkgReplay(rust, sessionId, inputMessages, replay.messages);
27523
27591
  replaceMessagesInPlace2(output, replay.messages);
27592
+ noteServedReplay(sessionId);
27524
27593
  sessionLog2(sessionId, "lkg_replay_served");
27525
27594
  return true;
27526
27595
  } else {
@@ -27547,6 +27616,8 @@ function createMessagesTransformHandler(args) {
27547
27616
  const isInternalChild = typeof sessionId === "string" && sessionId.length > 0 && args.internalChildSessions?.has(sessionId) === true;
27548
27617
  const compactionOffInputSnapshot = args.compactionOff ? [...output.messages] : null;
27549
27618
  const restoreCompactionOffInput = () => {
27619
+ if (compactionOffInputSnapshot && sessionId)
27620
+ noteServedHostInput(sessionId);
27550
27621
  if (compactionOffInputSnapshot && output.messages !== compactionOffInputSnapshot) {
27551
27622
  output.messages.splice(0, output.messages.length, ...compactionOffInputSnapshot);
27552
27623
  }
@@ -27627,6 +27698,8 @@ function createMessagesTransformHandler(args) {
27627
27698
  tryReopen: args.tryReopenStorage
27628
27699
  });
27629
27700
  }
27701
+ if (sessionId)
27702
+ noteServedHostInput(sessionId);
27630
27703
  return output.messages;
27631
27704
  }
27632
27705
  }
@@ -27713,7 +27786,42 @@ function createMessagesTransformHandler(args) {
27713
27786
  restoreCompactionOffInput();
27714
27787
  return output.messages;
27715
27788
  };
27789
+ const finishServedRequest = (sessionId, output, returned) => {
27790
+ try {
27791
+ if (!returned)
27792
+ countServedRefusal(sessionId);
27793
+ else if (resolveRust(sessionId))
27794
+ forgetServedRecord(sessionId);
27795
+ else {
27796
+ const keys = resolveLkgModelKeys(output.messages);
27797
+ commitServedRequest({
27798
+ sessionId,
27799
+ host: "opencode",
27800
+ messages: output.messages,
27801
+ providerID: keys.providerKey,
27802
+ modelID: keys.modelKey && keys.providerKey ? keys.modelKey.slice(keys.providerKey.length + 1) : keys.modelKey,
27803
+ compactionOff: args.compactionOff === true
27804
+ });
27805
+ }
27806
+ } catch (error) {
27807
+ sessionLog2(sessionId, "served check skipped:", error);
27808
+ }
27809
+ };
27716
27810
  return (input, output) => withSqliteTransformPass2(async () => {
27811
+ const servedSessionId = args.recordServed === false ? null : resolveSessionId2(output);
27812
+ if (servedSessionId)
27813
+ beginServedRequest(servedSessionId);
27814
+ let returned = false;
27815
+ try {
27816
+ const served = await servePass(input, output);
27817
+ returned = true;
27818
+ return served;
27819
+ } finally {
27820
+ if (servedSessionId)
27821
+ finishServedRequest(servedSessionId, output, returned);
27822
+ }
27823
+ });
27824
+ async function servePass(input, output) {
27717
27825
  const tail = output.messages.at(-1);
27718
27826
  if (tail?.info.role === "user" && tail.info.id && !tail.info.summary && tail.parts.length === 0) {
27719
27827
  throw new IncompleteUserMessageError;
@@ -27727,7 +27835,7 @@ function createMessagesTransformHandler(args) {
27727
27835
  preserveUserTerminatedTail(output.messages, inputMessages);
27728
27836
  reportAssistantTerminatedTail(output.messages, inputTailRole, resolveSessionId2(output));
27729
27837
  }
27730
- });
27838
+ }
27731
27839
  }
27732
27840
  function resolveSessionId2(output) {
27733
27841
  for (const message of output.messages) {
@@ -30428,4 +30536,4 @@ function applyHiddenSubagentTemperature(input, output, log) {
30428
30536
  output.temperature = temperature;
30429
30537
  }
30430
30538
 
30431
- export { logConfigDependencyNotesOnce, openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, startDreamScheduleTimer, createDreamTimerModuleClient, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, parseCacheTtl, createScheduler, computeHardCacheExpired, describeStorageUnavailability, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, maybeAutoEmbedSessionBackfill, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, stageOpenCodeV2TransformDecision, bindOpenCodeV2TransformDecision, maybeDeliverChannel2, armLatestThinkingRecovery, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, armThinkingBindingRecoveryFromError, createM0RenderOptions, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, bindSystemDateRequestIdentity, bindSystemDateOutput, registerSystemDateRefresh, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, removePrimaryOnlyTools, storedSubagentMode, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };
30539
+ export { logConfigDependencyNotesOnce, openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, startDreamScheduleTimer, createDreamTimerModuleClient, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, parseCacheTtl, createScheduler, computeHardCacheExpired, describeStorageUnavailability, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, maybeAutoEmbedSessionBackfill, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, stageOpenCodeV2TransformDecision, bindOpenCodeV2TransformDecision, maybeDeliverChannel2, createM0RenderOptions, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, bindSystemDateRequestIdentity, bindSystemDateOutput, registerSystemDateRefresh, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, removePrimaryOnlyTools, storedSubagentMode, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };