@cortexkit/opencode-magic-context 0.49.81 → 0.49.83

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 (173) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +4 -4
  3. package/dist/{conflict-warning-hook-8s8r0c0v.js → conflict-warning-hook-a0wrnzch.js} +2 -2
  4. package/dist/{context-359s1ncq.js → context-xmyke353.js} +258 -31
  5. package/dist/{embedding-backfill-0tvprmrn.js → embedding-backfill-k994xdas.js} +4 -4
  6. package/dist/features/magic-context/dreamer/map-memories-retry.d.ts +18 -0
  7. package/dist/features/magic-context/dreamer/map-memories-retry.d.ts.map +1 -0
  8. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  9. package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts +2 -0
  10. package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts.map +1 -1
  11. package/dist/features/magic-context/dreamer/task-gates.d.ts +1 -1
  12. package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
  13. package/dist/features/magic-context/dreamer/task-registry.d.ts +7 -0
  14. package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
  15. package/dist/features/magic-context/dreamer/task-scheduler.d.ts +9 -0
  16. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  17. package/dist/features/magic-context/memory/identity-merge-command.d.ts +4 -0
  18. package/dist/features/magic-context/memory/identity-merge-command.d.ts.map +1 -0
  19. package/dist/features/magic-context/memory/project-binding-notice.d.ts +5 -0
  20. package/dist/features/magic-context/memory/project-binding-notice.d.ts.map +1 -0
  21. package/dist/features/magic-context/memory/project-identity.d.ts +1 -0
  22. package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
  23. package/dist/features/magic-context/storage-clone.d.ts +17 -0
  24. package/dist/features/magic-context/storage-clone.d.ts.map +1 -1
  25. package/dist/features/magic-context/store-generation-rebase.d.ts +13 -0
  26. package/dist/features/magic-context/store-generation-rebase.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts +1 -7
  28. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/stored-compartment-gaps.d.ts +16 -0
  32. package/dist/hooks/magic-context/stored-compartment-gaps.d.ts.map +1 -0
  33. package/dist/hooks/magic-context/transform.d.ts +1 -0
  34. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  35. package/dist/{index-m4q6ptgz.js → index-2xhzmwf6.js} +4 -4
  36. package/dist/{index-jhhkb4jv.js → index-2ygw6q5s.js} +1 -1
  37. package/dist/{index-v0epndb8.js → index-93rezfvc.js} +22 -2
  38. package/dist/{index-1rx9bfrk.js → index-b2787fk6.js} +111 -40
  39. package/dist/{index-tebcx987.js → index-bd34njzg.js} +1 -1
  40. package/dist/{index-zpd4pxnp.js → index-dg5jvh9r.js} +6 -6
  41. package/dist/{index-6athgjba.js → index-e21n48yd.js} +34 -2
  42. package/dist/{index-726b5jh5.js → index-eptthgkw.js} +5 -5
  43. package/dist/{index-6sckwxjj.js → index-eyk7msgw.js} +344 -159
  44. package/dist/{index-9554nr2q.js → index-fgy6hnr3.js} +6 -1
  45. package/dist/{index-tzy5h4x6.js → index-fpqdbb67.js} +1 -1
  46. package/dist/{index-x8a7jmkh.js → index-fzgyvsb1.js} +15 -4
  47. package/dist/{index-1sq1krqw.js → index-g6hfh4h4.js} +4 -4
  48. package/dist/{index-wwzamy3j.js → index-hz1xdb15.js} +3 -3
  49. package/dist/{index-nda0zgna.js → index-kknjvmpx.js} +2 -1
  50. package/dist/{index-m6rkq3t4.js → index-rnyaa7cj.js} +1 -1
  51. package/dist/{index-yfn52pb6.js → index-shpyv8gq.js} +2 -2
  52. package/dist/{index-7jefmy0g.js → index-stx8zd81.js} +2 -2
  53. package/dist/{index-jg7sbt3v.js → index-vpw46557.js} +1 -1
  54. package/dist/{index-xx05vta0.js → index-w2wpx7t5.js} +1 -1
  55. package/dist/{index-177yv84k.js → index-w8dcjt7f.js} +1 -1
  56. package/dist/{index-ma258g0g.js → index-wxxcfpxh.js} +5 -5
  57. package/dist/{index-xsdaz3mq.js → index-x8qgqnym.js} +30 -11
  58. package/dist/{index-aawwdt26.js → index-zvane1rq.js} +2 -2
  59. package/dist/index.js +32 -32
  60. package/dist/migration-worker.js +3 -3
  61. package/dist/plugin/rpc-handlers.d.ts +2 -0
  62. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  63. package/dist/{project-embedding-registry-sw4z2ptg.js → project-embedding-registry-y3z36mjy.js} +3 -3
  64. package/dist/raw-ordinal-warmup-worker.js +2 -2
  65. package/dist/{recomp-orchestrator-ar3xw3f4.js → recomp-orchestrator-fjdp3t1d.js} +14 -14
  66. package/dist/{render-bjxgkrk6.js → render-c9fjwrad.js} +6 -6
  67. package/dist/{rpc-notifications-3hed126v.js → rpc-notifications-t9q0ynq7.js} +3 -1
  68. package/dist/{search-z56487n8.js → search-1jejx5cx.js} +9 -9
  69. package/dist/{search-archive-p3jhx9wc.js → search-archive-s2jas2jb.js} +2 -2
  70. package/dist/{send-session-notification-ykvt5k2s.js → send-session-notification-7x518gew.js} +1 -1
  71. package/dist/shared/prompt-surface-runtime.d.ts +1 -1
  72. package/dist/shared/rpc-notifications.d.ts +8 -3
  73. package/dist/shared/rpc-notifications.d.ts.map +1 -1
  74. package/dist/shared/rpc-types.d.ts +4 -0
  75. package/dist/shared/rpc-types.d.ts.map +1 -1
  76. package/dist/shared/status-summary.d.ts +2 -0
  77. package/dist/shared/status-summary.d.ts.map +1 -1
  78. package/dist/shared/status-view-check.d.ts.map +1 -1
  79. package/dist/shared/status-view.d.ts +1 -0
  80. package/dist/shared/status-view.d.ts.map +1 -1
  81. package/dist/shared/user-facing-codes.d.ts +5 -0
  82. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  83. package/dist/{store-8trkpmtx.js → store-ggrq9e14.js} +6 -2
  84. package/dist/{store-reader-3eh1s1m8.js → store-reader-tr64nxyy.js} +1 -1
  85. package/dist/{task-config-t6bpyka7.js → task-config-qt6n4bxm.js} +1 -1
  86. package/dist/tools/ctx-memory/constants.d.ts +1 -1
  87. package/dist/tools/ctx-memory/constants.d.ts.map +1 -1
  88. package/dist/tools/light-descriptions.d.ts +1 -1
  89. package/dist/tools/light-descriptions.d.ts.map +1 -1
  90. package/dist/tools/parameter-descriptions.d.ts +6 -6
  91. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  92. package/dist/{transform-postprocess-phase-6kyqctnq.js → transform-postprocess-phase-p2egg02g.js} +15 -15
  93. package/dist/v2/auto-search-worker.js +3 -3
  94. package/dist/v2/chunk-embedding-write-worker.js +4 -4
  95. package/dist/v2/{context-dpe94zcx.js → context-zn18k0yk.js} +648 -245
  96. package/dist/v2/{embedding-backfill-qnaswpmb.js → embedding-backfill-hjvjxp7d.js} +4 -4
  97. package/dist/v2/fork-inheritance.d.ts +25 -17
  98. package/dist/v2/fork-inheritance.d.ts.map +1 -1
  99. package/dist/v2/hidden-child-native.d.ts +6 -6
  100. package/dist/v2/hidden-child-native.d.ts.map +1 -1
  101. package/dist/v2/hidden-child-record.d.ts +21 -3
  102. package/dist/v2/hidden-child-record.d.ts.map +1 -1
  103. package/dist/v2/hidden-child-sweep.d.ts +1 -1
  104. package/dist/v2/hidden-child-sweep.d.ts.map +1 -1
  105. package/dist/v2/hidden-completion.d.ts +1 -0
  106. package/dist/v2/hidden-completion.d.ts.map +1 -1
  107. package/dist/v2/hidden-run-holder.d.ts +16 -0
  108. package/dist/v2/hidden-run-holder.d.ts.map +1 -0
  109. package/dist/v2/hooks/context.d.ts.map +1 -1
  110. package/dist/v2/hooks/dream-timer.d.ts +5 -7
  111. package/dist/v2/hooks/dream-timer.d.ts.map +1 -1
  112. package/dist/v2/hooks/fork-history-status.d.ts +10 -0
  113. package/dist/v2/hooks/fork-history-status.d.ts.map +1 -0
  114. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  115. package/dist/v2/hooks/store.d.ts +4 -0
  116. package/dist/v2/hooks/store.d.ts.map +1 -1
  117. package/dist/v2/hooks/types.d.ts +5 -26
  118. package/dist/v2/hooks/types.d.ts.map +1 -1
  119. package/dist/v2/migration-worker.js +3 -3
  120. package/dist/v2/{project-embedding-registry-52f2jept.js → project-embedding-registry-mzsvyads.js} +3 -3
  121. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  122. package/dist/v2/{recomp-orchestrator-7t6fkpbb.js → recomp-orchestrator-jn39mxh0.js} +13 -13
  123. package/dist/v2/{render-hwqk0d8t.js → render-q2aj9bgy.js} +6 -6
  124. package/dist/v2/retrospective-raw-provider.d.ts.map +1 -1
  125. package/dist/v2/{rpc-notifications-3hed126v.js → rpc-notifications-t9q0ynq7.js} +3 -1
  126. package/dist/v2/{search-eftsvbg7.js → search-9xn6ds9x.js} +8 -8
  127. package/dist/v2/{search-archive-mdxzvgpm.js → search-archive-fj59gjv1.js} +2 -2
  128. package/dist/v2/{send-session-notification-8g4r97bp.js → send-session-notification-p52rhjzy.js} +1 -1
  129. package/dist/v2/{server-ma9jwnas.js → server-1cn3kryt.js} +4 -4
  130. package/dist/v2/{server-34pvhvxt.js → server-1efjj215.js} +22 -2
  131. package/dist/v2/{server-92g7d776.js → server-2kswss3d.js} +2 -1
  132. package/dist/v2/{server-jn4pktdk.js → server-2ktxmtbd.js} +1 -1
  133. package/dist/v2/{server-zw1e3wq5.js → server-2w1rdttn.js} +1 -1
  134. package/dist/v2/{server-jtq03rkb.js → server-4z964n1c.js} +1 -1
  135. package/dist/v2/{server-pxdpwycq.js → server-53n8hv5q.js} +6 -6
  136. package/dist/v2/{server-rbtx6q5v.js → server-569he5mh.js} +1 -1
  137. package/dist/v2/{server-rthnpmbp.js → server-5yfq912a.js} +34 -2
  138. package/dist/v2/{server-mhrgymcs.js → server-68q80y27.js} +2 -2
  139. package/dist/v2/{server-afsz3cmx.js → server-bt546axy.js} +1 -1
  140. package/dist/v2/{server-dhdn8mwq.js → server-c8mqs0v5.js} +30 -11
  141. package/dist/v2/{server-x8a7jmkh.js → server-fzgyvsb1.js} +15 -4
  142. package/dist/v2/{server-76v5y7zm.js → server-g1a0nhtk.js} +2 -2
  143. package/dist/v2/{server-25qtxt4d.js → server-gx1s06dx.js} +6 -1
  144. package/dist/v2/{server-x8ksqcw7.js → server-pejjj0nv.js} +1 -1
  145. package/dist/v2/{server-a1zp7exh.js → server-vt6nj2hn.js} +106 -35
  146. package/dist/v2/{server-qjff96a6.js → server-wdq85mxj.js} +4 -4
  147. package/dist/v2/server.js +3 -3
  148. package/dist/v2/{store-m3zny7q2.js → store-qdgzd38f.js} +6 -2
  149. package/dist/v2/{store-reader-yaxtdy6f.js → store-reader-83tka051.js} +1 -1
  150. package/dist/v2/store-reader.d.ts +15 -8
  151. package/dist/v2/store-reader.d.ts.map +1 -1
  152. package/dist/v2/{task-config-7md27rx8.js → task-config-ex2vajr2.js} +1 -1
  153. package/dist/v2/tui/index.d.ts +1 -1
  154. package/dist/v2/tui/index.d.ts.map +1 -1
  155. package/dist/v2/{v2-archive-reader-p89x05hj.js → v2-archive-reader-9z8z97db.js} +1 -1
  156. package/dist/v2/{wrapup-orchestrator-c0bwb0wa.js → wrapup-orchestrator-vd5zfp3v.js} +13 -13
  157. package/dist/{v2-archive-reader-vzmzb245.js → v2-archive-reader-r0xpxsb1.js} +1 -1
  158. package/dist/{wrapup-orchestrator-548q5y55.js → wrapup-orchestrator-k29zqfp9.js} +15 -15
  159. package/package.json +1 -1
  160. package/src/agents/smart-notes-dreamer-gate.golden.json +169 -169
  161. package/src/features/magic-context/dreamer/task-registry.ts +8 -0
  162. package/src/shared/prompt-surface-a1-golden.md +8 -7
  163. package/src/shared/rpc-notifications.test.ts +29 -0
  164. package/src/shared/rpc-notifications.ts +24 -5
  165. package/src/shared/rpc-types.ts +4 -0
  166. package/src/shared/status-summary.ts +9 -1
  167. package/src/shared/status-view-check.ts +2 -0
  168. package/src/shared/status-view.test.ts +9 -0
  169. package/src/shared/status-view.ts +4 -0
  170. package/src/shared/user-facing-codes.ts +5 -0
  171. package/src/tui/slots/sidebar-content.tsx +11 -5
  172. package/src/tui-compiled/slots/sidebar-content.tsx +191 -176
  173. package/src/v2/tui/index.ts +7 -2
@@ -63,6 +63,7 @@ import {
63
63
  } from "./server-rz6g5xne.js";
64
64
  import {
65
65
  CANONICAL_DREAM_TASKS,
66
+ MIN_POOL_TO_CLASSIFY,
66
67
  DREAM_TASK_CAPABILITIES,
67
68
  toolLoopDreamTasks,
68
69
  formatUnsupportedDreamTasks,
@@ -78,7 +79,7 @@ import {
78
79
  userMemoryCollectionEnabled2,
79
80
  userObservationCollectionEnabled2,
80
81
  userObservationsRequested2
81
- } from "./server-92g7d776.js";
82
+ } from "./server-2kswss3d.js";
82
83
  import {
83
84
  historianRunConfig,
84
85
  dreamerRunConfig,
@@ -114,6 +115,9 @@ import {
114
115
  DREAMER_CLASSIFIER_AGENT,
115
116
  DREAMER_DOCS_AGENT,
116
117
  DREAMER_REVIEWER_AGENT,
118
+ supportsQuietHiddenChildren,
119
+ matchesHiddenRunLocation,
120
+ hiddenRunPlacement,
117
121
  HIDDEN_HISTORIAN_AGENT,
118
122
  HIDDEN_DREAMER_AGENT,
119
123
  HIDDEN_CURATE_AGENT,
@@ -158,6 +162,7 @@ import {
158
162
  runTokenLog,
159
163
  formatRunTokenLog,
160
164
  createChildSessionWithFence,
165
+ validateStoredCompartments,
161
166
  buildMagicContextSection,
162
167
  getMuralIdentity,
163
168
  getMural,
@@ -217,11 +222,12 @@ import {
217
222
  hasRunnableCompartmentWindow,
218
223
  recordHighPressureNoEligibleHead,
219
224
  noteTransformPassForExactOrdinalReads,
225
+ nonNarrativeStoredGapRanges,
220
226
  getActiveCompartmentRun,
221
227
  startCompartmentAgent,
222
228
  setRecompStarting2,
223
229
  setRecompTerminal2
224
- } from "./server-a1zp7exh.js";
230
+ } from "./server-vt6nj2hn.js";
225
231
  import {
226
232
  resolveHistorianModel2
227
233
  } from "./server-5kym00ag.js";
@@ -239,6 +245,7 @@ import {
239
245
  setHomeProjectPermission,
240
246
  shouldSkipHomeProjectMemory,
241
247
  ProjectIdentityError,
248
+ directoryFallback,
242
249
  takeDubiousOwnershipProjectIdentityWarning,
243
250
  isUserHomeDirectory,
244
251
  resolveProjectIdentity,
@@ -250,7 +257,7 @@ import {
250
257
  storedPathBelongsToIdentity,
251
258
  beginBootQuietPeriod,
252
259
  scheduleAfterBootQuiet
253
- } from "./server-afsz3cmx.js";
260
+ } from "./server-bt546axy.js";
254
261
  import"./server-v0p37hm2.js";
255
262
  import {
256
263
  inRootAsyncContext2,
@@ -650,7 +657,7 @@ import {
650
657
  resolveMemoriesByIdsForSearch2,
651
658
  unifiedSearch2,
652
659
  formatSearchResults2
653
- } from "./server-pxdpwycq.js";
660
+ } from "./server-53n8hv5q.js";
654
661
  import {
655
662
  embedPauseBySession,
656
663
  embedRunStateBySession,
@@ -798,7 +805,7 @@ import {
798
805
  saveSourceContent,
799
806
  replaceSourceContent,
800
807
  getSourceContents
801
- } from "./server-dhdn8mwq.js";
808
+ } from "./server-c8mqs0v5.js";
802
809
  import {
803
810
  startBootDeadline,
804
811
  getUnconfirmedMigrationHolders,
@@ -814,7 +821,7 @@ import {
814
821
  openDatabaseAsync,
815
822
  isDatabasePersisted,
816
823
  getDatabasePersistenceError
817
- } from "./server-76v5y7zm.js";
824
+ } from "./server-g1a0nhtk.js";
818
825
  import {
819
826
  V2_MEMORY_CATEGORIES,
820
827
  CATEGORY_PRIORITY
@@ -827,13 +834,13 @@ import {
827
834
  resolveStoredPathWorkspaceIdentity,
828
835
  storedPathBelongsToWorkspace,
829
836
  computeWorkspaceEpochFingerprint
830
- } from "./server-jn4pktdk.js";
837
+ } from "./server-2ktxmtbd.js";
831
838
  import {
832
839
  gaDatabasePath2,
833
840
  RAW_MESSAGE_TYPES2,
834
841
  V2StoreReaderPool2,
835
842
  V2StoreReader2
836
- } from "./server-rthnpmbp.js";
843
+ } from "./server-5yfq912a.js";
837
844
  import {
838
845
  configureContextDatabasePragmas2
839
846
  } from "./server-fb3zxn06.js";
@@ -862,7 +869,7 @@ import {
862
869
  createPrimer,
863
870
  updatePrimerSupport,
864
871
  updatePrimerAnswer
865
- } from "./server-rbtx6q5v.js";
872
+ } from "./server-569he5mh.js";
866
873
  import {
867
874
  deriveTriggerBudget2,
868
875
  deriveHistorianChunkTokens2,
@@ -895,7 +902,7 @@ import {
895
902
  embedSessionCompartmentChunks2,
896
903
  getEmbeddingCoverageStatus2,
897
904
  getAutoEmbeddingSessionCoverage2
898
- } from "./server-mhrgymcs.js";
905
+ } from "./server-68q80y27.js";
899
906
  import {
900
907
  GIT_SWEEP_LEASE_RENEWAL_MS,
901
908
  acquireGitSweepLease,
@@ -905,7 +912,7 @@ import {
905
912
  releaseGitSweepLease,
906
913
  recordSessionProjectIdentity,
907
914
  hasRecordedSessionProjectIdentity
908
- } from "./server-jtq03rkb.js";
915
+ } from "./server-4z964n1c.js";
909
916
  import {
910
917
  saveEmbeddingIfHashMatches,
911
918
  invalidateProject2,
@@ -935,8 +942,8 @@ import {
935
942
  readGitFileChangeTimesSince,
936
943
  verificationFileExists,
937
944
  normalizeVerificationFiles
938
- } from "./server-25qtxt4d.js";
939
- import"./server-x8ksqcw7.js";
945
+ } from "./server-gx1s06dx.js";
946
+ import"./server-pejjj0nv.js";
940
947
  import {
941
948
  computeCueContentHash,
942
949
  hasMuralCueColumns,
@@ -961,20 +968,22 @@ import {
961
968
  supersededMemory2,
962
969
  mergeMemoryStats2,
963
970
  archiveMemory2,
971
+ getMemoryCount2,
964
972
  getMemoryCountsByStatus2
965
973
  } from "./server-jjvbk92s.js";
966
974
  import {
967
975
  registerNotificationSink2,
976
+ pushLiveNotification2,
968
977
  pushNotification2,
969
978
  acknowledgeNotifications2,
970
979
  drainNotifications2,
971
980
  isTuiConnected2
972
- } from "./server-x8a7jmkh.js";
981
+ } from "./server-fzgyvsb1.js";
973
982
  import"./server-npdey91q.js";
974
983
  import {
975
984
  flushIgnoredMessages2,
976
985
  sendStatusNotification2
977
- } from "./server-qjff96a6.js";
986
+ } from "./server-wdq85mxj.js";
978
987
  import {
979
988
  rememberHostMedia,
980
989
  hostMediaAsset,
@@ -990,13 +999,15 @@ import {
990
999
  HOST_RESTORE_MEDIA,
991
1000
  restoreRow,
992
1001
  rawMessagePage2,
1002
+ readV2MessageRange2,
1003
+ iterateV2MessageRange2,
993
1004
  servedBoundaryRow2,
994
1005
  resolveV2BoundaryUserMessage2,
995
1006
  readAllV2RawMessagesForConversion2,
996
1007
  readV2RawMessagePagesForConversion2,
997
1008
  createV2RawMessageReader2,
998
1009
  createV2RawMessageProvider2
999
- } from "./server-34pvhvxt.js";
1010
+ } from "./server-1efjj215.js";
1000
1011
  import {
1001
1012
  resolvePromptContext2
1002
1013
  } from "./server-fmsr7v69.js";
@@ -1008,10 +1019,10 @@ import {
1008
1019
  import"./server-52x68mj4.js";
1009
1020
  import {
1010
1021
  readV2ArchiveOffThread2
1011
- } from "./server-ma9jwnas.js";
1022
+ } from "./server-1cn3kryt.js";
1012
1023
  import {
1013
1024
  renderSearchArchiveOffThread2
1014
- } from "./server-zw1e3wq5.js";
1025
+ } from "./server-2w1rdttn.js";
1015
1026
  import {
1016
1027
  markHostInstructionRow,
1017
1028
  hostInstructionRow,
@@ -5526,6 +5537,91 @@ function getCurateCategoryScopeRefusal(args) {
5526
5537
  return null;
5527
5538
  }
5528
5539
 
5540
+ // src/features/magic-context/dreamer/map-memories-retry.ts
5541
+ import { createHash } from "node:crypto";
5542
+
5543
+ // src/features/magic-context/dreamer/storage-dream-state.ts
5544
+ var getDreamStateStatements = new WeakMap;
5545
+ var setDreamStateStatements = new WeakMap;
5546
+ var deleteDreamStateStatements = new WeakMap;
5547
+ function getGetDreamStateStatement(db) {
5548
+ let stmt = getDreamStateStatements.get(db);
5549
+ if (!stmt) {
5550
+ stmt = db.prepare("SELECT value FROM dream_state WHERE key = ?");
5551
+ getDreamStateStatements.set(db, stmt);
5552
+ }
5553
+ return stmt;
5554
+ }
5555
+ function getSetDreamStateStatement(db) {
5556
+ let stmt = setDreamStateStatements.get(db);
5557
+ if (!stmt) {
5558
+ stmt = db.prepare("INSERT INTO dream_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
5559
+ setDreamStateStatements.set(db, stmt);
5560
+ }
5561
+ return stmt;
5562
+ }
5563
+ function getDeleteDreamStateStatement(db) {
5564
+ let stmt = deleteDreamStateStatements.get(db);
5565
+ if (!stmt) {
5566
+ stmt = db.prepare("DELETE FROM dream_state WHERE key = ?");
5567
+ deleteDreamStateStatements.set(db, stmt);
5568
+ }
5569
+ return stmt;
5570
+ }
5571
+ function getDreamState(db, key) {
5572
+ const row = getGetDreamStateStatement(db).get(key);
5573
+ return typeof row?.value === "string" ? row.value : null;
5574
+ }
5575
+ function setDreamState(db, key, value) {
5576
+ getSetDreamStateStatement(db).run(key, value);
5577
+ }
5578
+ function deleteDreamState(db, key) {
5579
+ getDeleteDreamStateStatement(db).run(key);
5580
+ }
5581
+
5582
+ // src/features/magic-context/dreamer/map-memories-retry.ts
5583
+ function mapMemoryRetryKey(project) {
5584
+ return `map-memories:retry:${project}`;
5585
+ }
5586
+ function readMapMemoryRetries(db, project) {
5587
+ try {
5588
+ const parsed = JSON.parse(getDreamState(db, mapMemoryRetryKey(project)) ?? "{}");
5589
+ if (!isRecord(parsed))
5590
+ return {};
5591
+ const retries = {};
5592
+ for (const [id, value] of Object.entries(parsed)) {
5593
+ if (isRecord(value) && typeof value.content === "string" && typeof value.failures === "number" && typeof value.deferUntil === "number") {
5594
+ retries[id] = {
5595
+ content: value.content,
5596
+ failures: value.failures,
5597
+ deferUntil: value.deferUntil
5598
+ };
5599
+ }
5600
+ }
5601
+ return retries;
5602
+ } catch {
5603
+ return {};
5604
+ }
5605
+ }
5606
+ function contentKey(memory) {
5607
+ return createHash("sha256").update(`${memory.category}
5608
+ ${memory.content}`).digest("hex");
5609
+ }
5610
+ function isMapMemoryDeferred(memory, retries, now = Date.now()) {
5611
+ const retry = retries[memory.id];
5612
+ return !!retry && retry.deferUntil > now && retry.content === contentKey(memory);
5613
+ }
5614
+ function nextMapMemoryRetry(memory, prior) {
5615
+ const content = contentKey(memory);
5616
+ const failures = (prior?.content === content ? prior.failures : 0) + 1;
5617
+ const maxWaitHours = 7 * 24;
5618
+ return {
5619
+ content,
5620
+ failures,
5621
+ deferUntil: failures < 2 ? 0 : Date.now() + Math.min(maxWaitHours, 2 ** (failures - 2)) * 3600000
5622
+ };
5623
+ }
5624
+
5529
5625
  // src/features/magic-context/dreamer/task-gates.ts
5530
5626
  function countActiveMemories(db, projectPath) {
5531
5627
  const row = db.prepare("SELECT COUNT(*) AS cnt FROM memories WHERE project_path = ? AND status IN ('active','permanent')").get(projectPath);
@@ -5542,16 +5638,24 @@ function countLiveMemories(db, projectPath, options = {}) {
5542
5638
  const row = options.category ? db.prepare(`${sql} AND category = ?`).get(projectPath, Date.now(), options.category) : db.prepare(sql).get(projectPath, Date.now());
5543
5639
  return row?.cnt ?? 0;
5544
5640
  }
5641
+ var UNMAPPED_LIVE_MEMORIES_SQL = `FROM memories m
5642
+ WHERE m.project_path = ?
5643
+ AND m.status IN ('active','permanent')
5644
+ AND (m.expires_at IS NULL OR m.expires_at > ?)
5645
+ AND NOT EXISTS (SELECT 1 FROM memory_verifications v WHERE v.memory_id = m.id)`;
5545
5646
  function countUnmappedActiveMemories(db, projectPath) {
5546
- const row = db.prepare(`SELECT COUNT(*) AS cnt
5547
- FROM memories m
5548
- WHERE m.project_path = ?
5549
- AND m.status IN ('active','permanent')
5550
- AND (m.expires_at IS NULL OR m.expires_at > ?)
5551
- AND NOT EXISTS (
5552
- SELECT 1 FROM memory_verifications v WHERE v.memory_id = m.id
5553
- )`).get(projectPath, Date.now());
5554
- return row?.cnt ?? 0;
5647
+ const now = Date.now();
5648
+ const row = db.prepare(`SELECT COUNT(*) AS cnt ${UNMAPPED_LIVE_MEMORIES_SQL}`).get(projectPath, now);
5649
+ const total = row?.cnt ?? 0;
5650
+ if (total === 0)
5651
+ return 0;
5652
+ const retries = readMapMemoryRetries(db, projectPath);
5653
+ const waitingIds = Object.entries(retries).filter(([, retry]) => retry.deferUntil > now).map(([id]) => id);
5654
+ if (waitingIds.length === 0)
5655
+ return total;
5656
+ const waiting = db.prepare(`SELECT m.id, m.category, m.content ${UNMAPPED_LIVE_MEMORIES_SQL}
5657
+ AND m.id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))`).all(projectPath, now, JSON.stringify(waitingIds));
5658
+ return total - waiting.filter((memory) => isMapMemoryDeferred(memory, retries, now)).length;
5555
5659
  }
5556
5660
  function countCompartmentsSince(db, projectPath, since) {
5557
5661
  const row = db.prepare(`SELECT COUNT(*) AS cnt
@@ -5734,7 +5838,7 @@ function getDreamTaskBacklog(db, projectPath, task, options = {}) {
5734
5838
  case "classify-memories": {
5735
5839
  const total = countLiveMemories(db, projectPath);
5736
5840
  return {
5737
- pending: countLiveMemories(db, projectPath, { unclassifiedOnly: true }),
5841
+ pending: total >= MIN_POOL_TO_CLASSIFY ? countLiveMemories(db, projectPath, { unclassifiedOnly: true }) : 0,
5738
5842
  total
5739
5843
  };
5740
5844
  }
@@ -5840,6 +5944,9 @@ function getDreamTaskBacklogs(db, projectPath, tasks = CANONICAL_DREAM_TASKS, op
5840
5944
  cache.eligibleProjects.clear();
5841
5945
  cache.eligibleProjects.set(projectPath, eligible);
5842
5946
  }
5947
+ if (eligible && tasks.includes("map-memories")) {
5948
+ eligible = !Object.values(readMapMemoryRetries(db, projectPath)).some(({ deferUntil }) => deferUntil > 0);
5949
+ }
5843
5950
  const optionKey = (value) => value === undefined ? "omitted" : value === null ? "null" : `number:${value}`;
5844
5951
  const key = JSON.stringify([
5845
5952
  getHarness2(),
@@ -5875,7 +5982,7 @@ function evaluateTaskGate(task, ctx) {
5875
5982
  case "compress-cues":
5876
5983
  return countLiveMemories(db, project) > 0;
5877
5984
  case "classify-memories":
5878
- return countLiveMemories(db, project) > 0;
5985
+ return countLiveMemories(db, project) >= MIN_POOL_TO_CLASSIFY;
5879
5986
  case "retrospective":
5880
5987
  return countProjectSessionsSince(db, project, ctx.retrospectiveWatermarkMs ?? null) > 0;
5881
5988
  case "maintain-docs":
@@ -7037,7 +7144,7 @@ function createToolExecuteAfterHook(args) {
7037
7144
  }
7038
7145
 
7039
7146
  // src/hooks/magic-context/host-checkpoint-ride.ts
7040
- import { createHash } from "node:crypto";
7147
+ import { createHash as createHash2 } from "node:crypto";
7041
7148
  var SESSIONS_MAX = 100;
7042
7149
  var servedHeads = new BoundedSessionMap(SESSIONS_MAX);
7043
7150
  var commits = new BoundedSessionMap(SESSIONS_MAX);
@@ -7047,7 +7154,7 @@ function servedHeadDigest(head) {
7047
7154
  return null;
7048
7155
  const mural = head.muralDataUrl ?? null;
7049
7156
  const m0 = mural ? head.m0Text : stripMemoryMuralBlock(head.m0Text);
7050
- return createHash("sha256").update(JSON.stringify([m0, head.m1Text, mural])).digest("hex");
7157
+ return createHash2("sha256").update(JSON.stringify([m0, head.m1Text, mural])).digest("hex");
7051
7158
  }
7052
7159
  function servedHeadChanged(before, after) {
7053
7160
  const a = servedHeadDigest(before);
@@ -13031,12 +13138,12 @@ function systemPromptDates(prompt, sticky) {
13031
13138
  }
13032
13139
 
13033
13140
  // src/hooks/magic-context/system-prompt-diagnostics.ts
13034
- import { createHash as createHash2 } from "node:crypto";
13141
+ import { createHash as createHash3 } from "node:crypto";
13035
13142
  function snapshotSystemPrompt(system, preset) {
13036
13143
  return { elements: system.map((element) => Buffer.from(element)), preset };
13037
13144
  }
13038
13145
  function describeSystemPromptChange(previous, current) {
13039
- const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${createHash2("md5").update(element).digest("hex")}`;
13146
+ const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${createHash3("md5").update(element).digest("hex")}`;
13040
13147
  const elements = [];
13041
13148
  for (let index = 0;index < Math.max(previous?.elements.length ?? 0, current.elements.length); index++) {
13042
13149
  const before = previous?.elements[index];
@@ -13471,6 +13578,79 @@ function createSystemPromptHashHandler(deps) {
13471
13578
  };
13472
13579
  }
13473
13580
 
13581
+ // src/features/magic-context/memory/identity-merge-command.ts
13582
+ var IDENTITY_MERGE_COMMAND = "npx @cortexkit/magic-context@latest doctor merge-identities";
13583
+ var IDENTITY_MERGE_PREVIEW_HINT = "It shows what would move. Add --apply to move them.";
13584
+ function shellArg(value, platform) {
13585
+ if (/^[\w.:/-]+$/.test(value))
13586
+ return value;
13587
+ return platform === "win32" ? `"${value}"` : `'${value.replaceAll("'", "'\\''")}'`;
13588
+ }
13589
+ function identityMergeCommand(from, to, platform = process.platform) {
13590
+ return `${IDENTITY_MERGE_COMMAND} --from ${shellArg(from, platform)} --to ${to ? shellArg(to, platform) : '"DESTINATION_IDENTITY"'}`;
13591
+ }
13592
+
13593
+ // src/features/magic-context/memory/project-binding-notice.ts
13594
+ var observedBindings = new WeakMap;
13595
+ function bindingLog(harness, directory, old, identity, memories) {
13596
+ return `project binding changed harness=${harness} cwd=${directory || "unknown"} old=${old ?? "none"} new=${identity} memories=${memories}`;
13597
+ }
13598
+ function observeSessionProjectBinding(db, sessionId, identity, directory, notify) {
13599
+ const change = recordSessionProjectIdentity(db, sessionId, identity);
13600
+ const harness = getHarness2();
13601
+ let observations = observedBindings.get(db);
13602
+ if (!observations) {
13603
+ observations = new BoundedSessionMap(1000);
13604
+ observedBindings.set(db, observations);
13605
+ }
13606
+ const key = `${harness}\x00${sessionId}`;
13607
+ const last = observations.get(key);
13608
+ const noticed = last?.noticed ?? new Set;
13609
+ const observation = {
13610
+ directory,
13611
+ noticed,
13612
+ warning: change ? undefined : last?.warning
13613
+ };
13614
+ observations.set(key, observation);
13615
+ const old = change?.previousProjectPath;
13616
+ if (!change || !old && harness !== "pi" && harness !== "omp")
13617
+ return;
13618
+ const memories = old ? getMemoryCount2(db, old) : 0;
13619
+ const binding = bindingLog(harness, directory, old, identity, memories);
13620
+ if (!old || !memories) {
13621
+ sessionLog2(sessionId, binding);
13622
+ return;
13623
+ }
13624
+ const oldDirectory = [last?.directory, directory].find((path) => path && directoryFallback(path) === old);
13625
+ const location = oldDirectory ? `the old folder (${oldDirectory})` : `the old project (${old})`;
13626
+ let guidance;
13627
+ if (old.startsWith("dir:") && /^(dir|git):/.test(identity)) {
13628
+ guidance = `Review the merge first:
13629
+ ${identityMergeCommand(oldDirectory ?? old, identity)}
13630
+ ${IDENTITY_MERGE_PREVIEW_HINT}`;
13631
+ } else if (old.startsWith("git:") && identity.startsWith("dir:")) {
13632
+ guidance = "A repository's memories cannot be merged into a folder project.";
13633
+ } else {
13634
+ guidance = "Run `npx @cortexkit/magic-context@latest doctor` to see how these memories can be merged.";
13635
+ }
13636
+ const count = `${memories} ${memories === 1 ? "memory" : "memories"}`;
13637
+ observation.warning = `${count} stayed under this session's previous project. Nothing was moved.
13638
+ ${guidance}`;
13639
+ if (noticed.has(old)) {
13640
+ sessionLog2(sessionId, binding);
13641
+ return;
13642
+ }
13643
+ noticed.add(old);
13644
+ const notice = `This session changed projects. ${count} stayed with ${location}; nothing moved. ${guidance}`;
13645
+ sessionLog2(sessionId, `${binding} notice=${JSON.stringify(notice)}`);
13646
+ try {
13647
+ notify?.(notice);
13648
+ } catch {}
13649
+ }
13650
+ function getProjectBindingWarning(db, sessionId) {
13651
+ return observedBindings.get(db)?.peek(`${getHarness2()}\x00${sessionId}`)?.warning;
13652
+ }
13653
+
13474
13654
  // src/hooks/magic-context/compaction-off-transition.ts
13475
13655
  import { existsSync } from "node:fs";
13476
13656
  var loggedUnverifiedMarkerCleanupRetry = false;
@@ -14187,7 +14367,7 @@ function evaluateRequestToolsRelease(args) {
14187
14367
  }
14188
14368
 
14189
14369
  // src/hooks/magic-context/rust-mode-transform.ts
14190
- import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
14370
+ import { createHash as createHash7, randomUUID as randomUUID2 } from "node:crypto";
14191
14371
 
14192
14372
  // src/features/magic-context/memory/single-store-embedding-drain.ts
14193
14373
  function isWatermarkRow(row) {
@@ -14251,7 +14431,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
14251
14431
  }
14252
14432
 
14253
14433
  // src/features/magic-context/mural/source-revision.ts
14254
- import { createHash as createHash3 } from "node:crypto";
14434
+ import { createHash as createHash4 } from "node:crypto";
14255
14435
  var statements = new WeakMap;
14256
14436
  function muralSourceRevision(db, projectPath) {
14257
14437
  let statement = statements.get(db);
@@ -14268,7 +14448,7 @@ function muralSourceRevision(db, projectPath) {
14268
14448
  statements.set(db, statement);
14269
14449
  }
14270
14450
  const row = statement.get(projectPath, Date.now());
14271
- return createHash3("sha256").update(row.revision).digest("hex");
14451
+ return createHash4("sha256").update(row.revision).digest("hex");
14272
14452
  }
14273
14453
 
14274
14454
  // src/features/magic-context/install-instance-id.ts
@@ -16643,7 +16823,7 @@ function noteExternalLkgReplay(participant, sessionId, inputMessages, servedMess
16643
16823
  }
16644
16824
 
16645
16825
  // src/hooks/magic-context/rust-served-raw.ts
16646
- import { createHash as createHash5 } from "node:crypto";
16826
+ import { createHash as createHash6 } from "node:crypto";
16647
16827
  class RustServedRawConflict extends EmergencyFailClosedError {
16648
16828
  reason;
16649
16829
  messageIds;
@@ -16657,7 +16837,7 @@ class RustServedRawConflict extends EmergencyFailClosedError {
16657
16837
  }
16658
16838
  function partDigest(part) {
16659
16839
  const serialized = JSON.stringify(part);
16660
- return createHash5("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
16840
+ return createHash6("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
16661
16841
  }
16662
16842
  function records(doc) {
16663
16843
  if (doc.rustServedRaw === undefined)
@@ -17209,10 +17389,10 @@ function messageCacheSignature(message) {
17209
17389
  const parts = Array.isArray(message.parts) ? message.parts : [];
17210
17390
  const serializedParts = JSON.stringify(parts) ?? "null";
17211
17391
  const serializedMessage = JSON.stringify(message) ?? "null";
17212
- return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash6("sha256").update(serializedMessage).digest("hex")}`;
17392
+ return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash7("sha256").update(serializedMessage).digest("hex")}`;
17213
17393
  }
17214
17394
  function advanceWireFingerprint(previous, encoded) {
17215
- return createHash6("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
17395
+ return createHash7("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
17216
17396
  }
17217
17397
  function buildWireFingerprint(encoded) {
17218
17398
  let fingerprint = "rust-wire-v1";
@@ -18779,7 +18959,11 @@ function createRustModeTransform(deps, options) {
18779
18959
  const sessionProjectIdentity = (options.sessionProjectIdentityResolverForTests ?? resolveProjectIdentityForSession)(directory, deps.allowHomeProject);
18780
18960
  if (sessionProjectIdentity) {
18781
18961
  if (state.recordedSessionProjectIdentity !== sessionProjectIdentity) {
18782
- recordSessionProjectIdentity(deps.db, sessionId, sessionProjectIdentity);
18962
+ observeSessionProjectBinding(deps.db, sessionId, sessionProjectIdentity, directory, (notice) => {
18963
+ withoutSqliteTransformPass2(() => sendStatusNotification2(deps.client, sessionId, `## Project memory warning
18964
+
18965
+ ${notice}`, {}));
18966
+ });
18783
18967
  }
18784
18968
  state.recordedSessionProjectIdentity = sessionProjectIdentity;
18785
18969
  state.recordedSessionDirectory = directory;
@@ -18997,7 +19181,7 @@ function createRustModeTransform(deps, options) {
18997
19181
  const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
18998
19182
  const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
18999
19183
  if (parts?.length) {
19000
- todoCalls.set(id, createHash6("sha256").update(JSON.stringify(parts)).digest("hex"));
19184
+ todoCalls.set(id, createHash7("sha256").update(JSON.stringify(parts)).digest("hex"));
19001
19185
  } else {
19002
19186
  todoCalls.delete(id);
19003
19187
  }
@@ -21578,7 +21762,15 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
21578
21762
  const authorityProjectPath = (deps.memoryConfig?.enabled ? projectIdentity : undefined) ?? deps.projectPath ?? sessionProjectIdentity;
21579
21763
  if (authorityProjectPath) {}
21580
21764
  if (sessionIdentityForBinding && sessionDirectoryResolvedFromHost && recordedSessionProjectIdentity.get(sessionId) !== sessionIdentityForBinding) {
21581
- recordSessionProjectIdentity(db, sessionId, sessionIdentityForBinding);
21765
+ observeSessionProjectBinding(db, sessionId, sessionIdentityForBinding, sessionDirectory, (notice) => {
21766
+ if (deps.hostProjectBindingNotice)
21767
+ deps.hostProjectBindingNotice(sessionId, notice);
21768
+ else {
21769
+ withoutSqliteTransformPass2(() => sendStatusNotification2(deps.client, sessionId, `## Project memory warning
21770
+
21771
+ ${notice}`, notificationParams));
21772
+ }
21773
+ });
21582
21774
  recordedSessionProjectIdentity.set(sessionId, sessionIdentityForBinding);
21583
21775
  }
21584
21776
  const taggerFloor = compactionOff ? 0 : deriveTaggerLoadFloor(messages, sessionId, db);
@@ -24628,7 +24820,7 @@ function setSessionWorkMetricsCarry(db, sessionId, source, carry, metrics) {
24628
24820
  import { readFileSync, statSync } from "node:fs";
24629
24821
 
24630
24822
  // src/plugin/embedding-bootstrap-helpers.ts
24631
- import { createHash as createHash7 } from "node:crypto";
24823
+ import { createHash as createHash8 } from "node:crypto";
24632
24824
  var EMBEDDING_AFFECTING_KEYS = new Set([
24633
24825
  "embedding.api_key",
24634
24826
  "embedding.endpoint",
@@ -24677,7 +24869,7 @@ var EMBEDDING_WARNING_TERMS = [
24677
24869
  ];
24678
24870
  var loggedFailureSignatures = new Map;
24679
24871
  function sha256Prefix(value, length = 16) {
24680
- return createHash7("sha256").update(value).digest("hex").slice(0, length);
24872
+ return createHash8("sha256").update(value).digest("hex").slice(0, length);
24681
24873
  }
24682
24874
  function warningLooksEmbeddingRelated(message) {
24683
24875
  const lower = message.toLowerCase();
@@ -25544,6 +25736,7 @@ function buildSidebarSnapshot(db, sessionId, directory, liveSessionState, inject
25544
25736
  readySmartNoteCount,
25545
25737
  cacheTtl,
25546
25738
  lastTransformError: meta?.last_transform_error ? String(meta.last_transform_error) : null,
25739
+ projectBindingWarning: getProjectBindingWarning(db, sessionId),
25547
25740
  lastDreamerRunAt,
25548
25741
  projectIdentity,
25549
25742
  dreamerBacklog,
@@ -26048,6 +26241,15 @@ function registerRpcHandlers(rpcServer, args) {
26048
26241
  const rawConfig = config;
26049
26242
  const getNotificationParams = (sessionId) => getLiveNotificationParams(sessionId, liveSessionState.liveModelBySession, liveSessionState.variantBySession, liveSessionState.agentBySession, currentPluginConfigReader(directory)?.poll().effective.toast_duration_ms ?? config.toast_duration_ms);
26050
26243
  const injectionBudgetTokens = config.memory?.injection_budget_tokens;
26244
+ const showForkHistoryGap = (db, sessionId) => {
26245
+ if (!compactionEnabled || config.transform_mode === "rust")
26246
+ return false;
26247
+ try {
26248
+ return args.readForkHistoryGap?.(db, sessionId) === true;
26249
+ } catch {
26250
+ return false;
26251
+ }
26252
+ };
26051
26253
  if (isDebugRpcEnabled(config)) {
26052
26254
  const readMemory = () => buildDebugMemoryUsage(args.getDebugMemoryHolders?.());
26053
26255
  rpcServer.handle("debug.memoryUsage", async () => ({ ...readMemory() }));
@@ -26068,7 +26270,10 @@ function registerRpcHandlers(rpcServer, args) {
26068
26270
  error: "Rust module status unavailable; canonical session state was not read"
26069
26271
  };
26070
26272
  }
26071
- return buildSidebarSnapshotRpcResponse(db, sessionId, dir, liveSessionState, injectionBudgetTokens, rawConfig, moduleStatus, compactionEnabled);
26273
+ const snapshot = buildSidebarSnapshotRpcResponse(db, sessionId, dir, liveSessionState, injectionBudgetTokens, rawConfig, moduleStatus, compactionEnabled);
26274
+ if (!snapshot.error && snapshot.disabled !== true && showForkHistoryGap(db, sessionId))
26275
+ snapshot.forkHistoryGap = true;
26276
+ return snapshot;
26072
26277
  });
26073
26278
  rpcServer.handle("session-owner", async (params) => {
26074
26279
  const sessionId = String(params.sessionId ?? "");
@@ -26102,6 +26307,8 @@ function registerRpcHandlers(rpcServer, args) {
26102
26307
  };
26103
26308
  }
26104
26309
  const detail = buildStatusDetail(db, sessionId, dir, modelKey, rawConfig, liveSessionState, injectionBudgetTokens, moduleStatus, compactionEnabled);
26310
+ if (showForkHistoryGap(db, sessionId))
26311
+ detail.forkHistoryGap = true;
26105
26312
  if (args.hiddenCompletionExecutor?.capabilities.tools === false) {
26106
26313
  detail.dreamerUnsupportedTasks = toolLoopDreamTasks();
26107
26314
  }
@@ -26147,7 +26354,7 @@ function registerRpcHandlers(rpcServer, args) {
26147
26354
  const buildManagedCtx = async (db) => {
26148
26355
  const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-2eam671q.js"));
26149
26356
  const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
26150
- const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-7md27rx8.js"));
26357
+ const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-ex2vajr2.js"));
26151
26358
  const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
26152
26359
  const runConfig = historianRunConfig(config, currentPluginConfigReader(directory)?.poll().effective ?? config);
26153
26360
  const historianModel = resolveHistorianModel(runConfig, "opencode");
@@ -26197,8 +26404,8 @@ function registerRpcHandlers(rpcServer, args) {
26197
26404
  const db = readDatabase();
26198
26405
  if (!db)
26199
26406
  return { ok: false, error: "db unavailable" };
26200
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-7t6fkpbb.js"));
26201
- const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-8g4r97bp.js"));
26407
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-jn39mxh0.js"));
26408
+ const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-p52rhjzy.js"));
26202
26409
  log2(`[rpc] recomp requested for session ${sessionId}`);
26203
26410
  if (!args.client && !args.hiddenCompletionExecutor) {
26204
26411
  return {
@@ -26282,7 +26489,7 @@ function registerRpcHandlers(rpcServer, args) {
26282
26489
  const db = readDatabase();
26283
26490
  if (!db)
26284
26491
  return { ok: false, error: "db unavailable" };
26285
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-c0bwb0wa.js"));
26492
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-vd5zfp3v.js"));
26286
26493
  const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
26287
26494
  const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
26288
26495
  if (!window)
@@ -27041,9 +27248,9 @@ var FULL_PARAMETER_DESCRIPTIONS = {
27041
27248
  },
27042
27249
  ctx_memory: {
27043
27250
  action: "write | update | archive | merge | get",
27044
- content: "The memory text — one standalone fact (write, update, merge). Archive and get take an empty string.",
27045
- category: "Kind of fact: the new fact's kind for write; on update/merge, the memory's current category to keep it. Archive and get ignore it.",
27046
- ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get. Write takes an empty list.",
27251
+ content: "Send on every call — the memory text for write, update and merge; pass an empty string for archive and get.",
27252
+ category: "Send on every call — the fact's kind for write; on update/merge, the memory's current category to keep it; archive and get ignore it, so pass any valid category.",
27253
+ ids: "Send on every call — one id for update, one or more for archive, two or more distinct ids of memories in the same category for merge, 1–20 for get; write takes an empty list.",
27047
27254
  reason: "Why it is being archived (optional)."
27048
27255
  },
27049
27256
  ctx_search: {
@@ -27076,9 +27283,9 @@ var LIGHT_PARAMETER_DESCRIPTIONS = {
27076
27283
  },
27077
27284
  ctx_memory: {
27078
27285
  action: "write | update | archive | merge | get",
27079
- content: "One standalone fact (write, update, merge). Archive and get: empty string.",
27080
- category: "Kind of fact (write; on update/merge pass the current category to keep it). Archive and get ignore it.",
27081
- ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get. Write: empty list.",
27286
+ content: "Send on every call: the fact (write, update, merge); empty string for archive/get.",
27287
+ category: "Send on every call: kind for write; current category for update/merge; any category for archive/get (ignored).",
27288
+ ids: "Send on every call: one id for update, 1+ for archive, 2+ distinct same-category ids for merge, 1–20 for get; write: empty list.",
27082
27289
  reason: "Why it is archived (optional)."
27083
27290
  },
27084
27291
  ctx_search: {
@@ -27611,7 +27818,7 @@ function stageManualBaseline(db, sessionID, render) {
27611
27818
  import { randomUUID as randomUUID4 } from "node:crypto";
27612
27819
 
27613
27820
  // src/v2/fold/owner.ts
27614
- import { createHash as createHash8 } from "node:crypto";
27821
+ import { createHash as createHash9 } from "node:crypto";
27615
27822
 
27616
27823
  // src/v2/fold/summary.ts
27617
27824
  var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
@@ -27641,7 +27848,7 @@ ${head}
27641
27848
  }
27642
27849
 
27643
27850
  // src/v2/fold/owner.ts
27644
- var foldDigest = (value) => createHash8("sha256").update(value).digest("hex");
27851
+ var foldDigest = (value) => createHash9("sha256").update(value).digest("hex");
27645
27852
  var boundToCheckpoint = (record) => record.cutSeq !== undefined || record.rendered !== undefined || record.answered !== undefined;
27646
27853
 
27647
27854
  class FoldOwner {
@@ -28142,7 +28349,7 @@ function instanceBytes(value, seen) {
28142
28349
  bytes += 16 + instanceBytes(entry, seen);
28143
28350
  return bytes;
28144
28351
  }
28145
- function contentKey(value) {
28352
+ function contentKey2(value) {
28146
28353
  const plain = (entry) => {
28147
28354
  if (ArrayBuffer.isView(entry)) {
28148
28355
  return {
@@ -28206,7 +28413,7 @@ function adaptPayload(draft, syntheticIDs = new Set, messageTimes = new Map, hid
28206
28413
  for (const message of source) {
28207
28414
  for (const part of message.content) {
28208
28415
  if (part.type !== "tool-call" && part.type !== "tool-result" && part.type !== "tool" && containsHostInstance(part)) {
28209
- const key = contentKey(part);
28416
+ const key = contentKey2(part);
28210
28417
  if (!hostParts.has(key))
28211
28418
  hostParts.set(key, part);
28212
28419
  hostPartTypes.add(part.type);
@@ -28411,7 +28618,7 @@ function adaptPayload(draft, syntheticIDs = new Set, messageTimes = new Map, hid
28411
28618
  continue;
28412
28619
  }
28413
28620
  const { synthetic: _synthetic, ...clean } = part;
28414
- const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(contentKey(clean)) : undefined;
28621
+ const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(contentKey2(clean)) : undefined;
28415
28622
  const projected = original ?? clean;
28416
28623
  if (projected.type === "media" && !isHostInstance(projected.media)) {
28417
28624
  content.push(repairMediaPart(message, partIndex, projected));
@@ -30048,7 +30255,123 @@ function splitMessageScopedId(id) {
30048
30255
  return { messageId: id, suffix: "" };
30049
30256
  return { messageId: id.slice(0, -match[1].length), suffix: match[1] };
30050
30257
  }
30051
- function forkCloneFilter(idMap, copiedToolCallIds) {
30258
+ function selectForkCompartments(source, map, proof) {
30259
+ const rows = new Map;
30260
+ const forkId = (id) => map.parentToFork.get(id) ?? "";
30261
+ const ordinal = (id) => map.forkOrdinals.get(forkId(id));
30262
+ let matchingPrefix;
30263
+ const provePrefix = () => {
30264
+ const matching = proof.matchingBodies();
30265
+ let length = 0;
30266
+ for (const [position, id] of map.parentOrdinals) {
30267
+ if (ordinal(id) !== position || matching.get(id) !== forkId(id))
30268
+ break;
30269
+ length = position;
30270
+ }
30271
+ return length;
30272
+ };
30273
+ let stopped = false;
30274
+ let lastEnd = 0;
30275
+ let acceptedGaps;
30276
+ const conversionGaps = [];
30277
+ const inheritedGaps = [];
30278
+ for (const [i, row] of source.entries()) {
30279
+ const { sequence, startMessage, endMessage, startMessageId, endMessageId } = row;
30280
+ const start = ordinal(startMessageId);
30281
+ const end = ordinal(endMessageId);
30282
+ let reason;
30283
+ if (stopped) {
30284
+ reason = "after first skipped compartment";
30285
+ } else {
30286
+ const startSeq = start === undefined ? proof.sequenceForId(startMessageId) : undefined;
30287
+ const endSeq = end === undefined ? proof.sequenceForId(endMessageId) : undefined;
30288
+ const previous = source[i - 1];
30289
+ const next = source[i + 1];
30290
+ if ((startSeq ?? -1) > map.throughSeq || (endSeq ?? -1) > map.throughSeq) {
30291
+ reason = "outside the fork boundary";
30292
+ } else if (startSeq !== undefined || endSeq !== undefined) {
30293
+ reason = "a live endpoint was not copied";
30294
+ } else if (row.rebaseStatus === "unresolved") {
30295
+ reason = "parent coordinates are unresolved";
30296
+ } else if (!Number.isSafeInteger(startMessage) || !Number.isSafeInteger(endMessage) || startMessage < 1 || endMessage < startMessage) {
30297
+ reason = "invalid message range";
30298
+ } else if (startMessage <= lastEnd) {
30299
+ reason = "range overlaps the inherited prefix";
30300
+ } else if (startMessage > lastEnd + 1 && validateStoredCompartments(lastEnd > 0 ? [{ startMessage: 1, endMessage: lastEnd }, row] : [row], acceptedGaps ??= proof.acceptedGaps(source, (gap) => conversionGaps.push(gap))) !== null) {
30301
+ reason = "gap before range";
30302
+ } else if (start !== undefined && start !== startMessage || end !== undefined && end !== endMessage) {
30303
+ reason = "live endpoint conflicts with the stored position";
30304
+ } else if (start === undefined && previous && ordinal(previous.endMessageId) !== lastEnd || end === undefined && (!next || next.startMessage !== endMessage + 1 || ordinal(next.startMessageId) !== endMessage + 1)) {
30305
+ reason = "live neighboring anchors do not prove the stored range";
30306
+ } else if ((end === undefined ? endMessage + 1 : endMessage) > (matchingPrefix ??= provePrefix())) {
30307
+ reason = "parent and fork raw prefixes do not match in order and body";
30308
+ } else {
30309
+ rows.set(sequence, {
30310
+ sequence,
30311
+ startMessage,
30312
+ endMessage,
30313
+ startMessageId: forkId(map.parentOrdinals.get(startMessage) ?? ""),
30314
+ endMessageId: forkId(map.parentOrdinals.get(endMessage) ?? "")
30315
+ });
30316
+ const conversionGap = conversionGaps.find(({ start, end }) => start === lastEnd + 1 && end === startMessage - 1);
30317
+ if (conversionGap)
30318
+ inheritedGaps.push(conversionGap);
30319
+ lastEnd = endMessage;
30320
+ continue;
30321
+ }
30322
+ stopped = true;
30323
+ }
30324
+ sessionLog2(proof.sessionId, `v2 fork skipped compartment ${sequence} (${startMessage}-${endMessage}): ${reason}`);
30325
+ }
30326
+ const keepRaw = new Set;
30327
+ if (stopped) {
30328
+ const count = map.parentOrdinals.size;
30329
+ const changes = new Int32Array(count + 2);
30330
+ const markCovered = (from, to) => {
30331
+ const start = Math.max(1, from);
30332
+ const end = Math.min(count, to);
30333
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end)
30334
+ return;
30335
+ changes[start] = (changes[start] ?? 0) + 1;
30336
+ changes[end + 1] = (changes[end + 1] ?? 0) - 1;
30337
+ };
30338
+ const parentPositions = new Map([...map.parentOrdinals].map(([position, id]) => [id, position]));
30339
+ const liveOrdinal = (id) => {
30340
+ const position = parentPositions.get(id);
30341
+ if (position !== undefined)
30342
+ return position;
30343
+ return (proof.sequenceForId(id) ?? -1) > map.throughSeq ? count + 1 : undefined;
30344
+ };
30345
+ const live = source.map((row) => ({
30346
+ start: liveOrdinal(row.startMessageId),
30347
+ end: liveOrdinal(row.endMessageId)
30348
+ }));
30349
+ for (const [index, row] of source.entries()) {
30350
+ if (rows.has(row.sequence))
30351
+ continue;
30352
+ markCovered(row.startMessage, row.endMessage);
30353
+ const { start, end } = live[index] ?? {};
30354
+ if (start === undefined && end === undefined)
30355
+ continue;
30356
+ const previousEnd = live[index - 1]?.end;
30357
+ const nextStart = live[index + 1]?.start;
30358
+ const from = start ?? (previousEnd !== undefined ? previousEnd + 1 : index === 0 ? 1 : undefined);
30359
+ const to = end ?? (nextStart !== undefined ? nextStart - 1 : undefined);
30360
+ if (from !== undefined && to !== undefined)
30361
+ markCovered(from, to);
30362
+ else
30363
+ markCovered(Math.min(row.startMessage, from ?? row.startMessage), Math.max(row.endMessage, to ?? row.endMessage));
30364
+ }
30365
+ let covering = 0;
30366
+ for (const [position, id] of map.parentOrdinals) {
30367
+ covering += changes[position] ?? 0;
30368
+ if (covering > 0)
30369
+ keepRaw.add(id);
30370
+ }
30371
+ }
30372
+ return { rows, keepRaw, inheritedGaps };
30373
+ }
30374
+ function forkCloneFilter(idMap, copiedToolCallIds, proof, toolOwners) {
30052
30375
  const mapMessageScoped = (id) => {
30053
30376
  const direct = idMap.parentToFork.get(id);
30054
30377
  if (direct)
@@ -30059,14 +30382,28 @@ function forkCloneFilter(idMap, copiedToolCallIds) {
30059
30382
  const mapped = idMap.parentToFork.get(messageId);
30060
30383
  return mapped ? `${mapped}${suffix}` : undefined;
30061
30384
  };
30385
+ let keepRaw;
30386
+ let inheritedGaps = [];
30387
+ const includeMessageId = (messageId) => mapMessageScoped(messageId) !== undefined || copiedToolCallIds.has(messageId);
30062
30388
  return {
30389
+ selectCompartments: proof && ((source) => {
30390
+ const plan = selectForkCompartments(source, idMap, proof);
30391
+ keepRaw = plan.keepRaw;
30392
+ inheritedGaps = plan.inheritedGaps;
30393
+ return plan.rows;
30394
+ }),
30395
+ inheritedCoordinateGaps: proof && (() => inheritedGaps),
30063
30396
  resolveBoundaryOrdinal: (messageId) => {
30064
30397
  const forkId = idMap.parentToFork.get(messageId);
30065
30398
  return forkId ? idMap.forkOrdinals.get(forkId) : undefined;
30066
30399
  },
30067
- includeMessageId: (messageId) => mapMessageScoped(messageId) !== undefined || copiedToolCallIds.has(messageId),
30400
+ includeMessageId,
30401
+ includeReplayMessageId: (messageId) => includeMessageId(messageId) && !keepRaw?.has(splitMessageScopedId(messageId).messageId) && !toolOwners?.get(messageId)?.some((owner) => keepRaw?.has(owner)),
30068
30402
  mapMessageId: (messageId) => mapMessageScoped(messageId) ?? messageId,
30069
30403
  includeTag: (tag) => {
30404
+ const owner = tag.type === "tool" ? tag.toolOwnerMessageId : splitMessageScopedId(tag.messageId).messageId;
30405
+ if (owner && keepRaw?.has(owner))
30406
+ return false;
30070
30407
  if (tag.type === "tool") {
30071
30408
  return tag.toolOwnerMessageId !== null && idMap.parentToFork.has(tag.toolOwnerMessageId);
30072
30409
  }
@@ -30110,7 +30447,20 @@ function seedV2ForkFromParent(args) {
30110
30447
  return { kind: "parent-missing", parentSessionID, reason: "no copied rows pair up" };
30111
30448
  const toolTags = db.prepare("SELECT message_id, tool_owner_message_id FROM tags WHERE session_id = ? AND type = 'tool'").all(parentSessionID);
30112
30449
  const copiedToolCallIds = new Set(toolTags.filter((row) => row.tool_owner_message_id !== null && idMap.parentToFork.has(row.tool_owner_message_id)).map((row) => row.message_id));
30113
- const result = copySessionStateForClone(db, parentSessionID, sessionId, forkCloneFilter(idMap, copiedToolCallIds));
30450
+ const toolOwners = new Map;
30451
+ for (const row of toolTags) {
30452
+ if (!row.tool_owner_message_id)
30453
+ continue;
30454
+ const owners = toolOwners.get(row.message_id) ?? [];
30455
+ owners.push(row.tool_owner_message_id);
30456
+ toolOwners.set(row.message_id, owners);
30457
+ }
30458
+ const result = copySessionStateForClone(db, parentSessionID, sessionId, forkCloneFilter(idMap, copiedToolCallIds, {
30459
+ sessionId,
30460
+ sequenceForId: (id) => store.sequenceForId(parentSessionID, id),
30461
+ matchingBodies: () => store.matchingForkBodies(parentSessionID, sessionId, throughSeq),
30462
+ acceptedGaps: (source, onConversionGap) => nonNarrativeStoredGapRanges(db, parentSessionID, source, (start, end) => readV2MessageRange2(store, parentSessionID, start, Math.min(end, idMap.parentOrdinals.size)), onConversionGap)
30463
+ }, toolOwners));
30114
30464
  if (result.kind === "destination-not-empty")
30115
30465
  return { kind: "destination-not-empty", parentSessionID };
30116
30466
  return { kind: "seeded", parentSessionID, pairedRows: idMap.parentToFork.size, result };
@@ -30281,6 +30631,7 @@ function isSessionNotFound(error) {
30281
30631
  return /not\s*found/i.test(label);
30282
30632
  }
30283
30633
  function createNativeHiddenChildren(host, removeSession, options) {
30634
+ const quiet = supportsQuietHiddenChildren(options.hostVersion);
30284
30635
  const removing = new Map;
30285
30636
  const remove = (child) => {
30286
30637
  const inFlight = removing.get(child.id);
@@ -30323,6 +30674,15 @@ function createNativeHiddenChildren(host, removeSession, options) {
30323
30674
  };
30324
30675
  const create = async (identity, role, model) => {
30325
30676
  const input = childCreateInput(identity, role, model);
30677
+ const directory = identity.directory;
30678
+ if (quiet) {
30679
+ if (!host.createHolder)
30680
+ throw new Error("OpenCode 2 background holder API is not wired");
30681
+ const placement = await hiddenRunPlacement(host.createHolder, directory);
30682
+ input.id = placement.id;
30683
+ input.parentID = placement.parentID;
30684
+ delete input.location;
30685
+ }
30326
30686
  const created = await host.create(input);
30327
30687
  if (!created.id)
30328
30688
  throw new Error("OpenCode 2 did not return a child session id");
@@ -30332,7 +30692,7 @@ function createNativeHiddenChildren(host, removeSession, options) {
30332
30692
  try {
30333
30693
  recordHiddenChild(options.db, {
30334
30694
  id: created.id,
30335
- directory: identity.directory,
30695
+ directory,
30336
30696
  created_at: createdAt,
30337
30697
  deadline_at: createdAt + identity.timeoutMs
30338
30698
  });
@@ -30358,17 +30718,22 @@ function createNativeHiddenChildren(host, removeSession, options) {
30358
30718
  throw storeError;
30359
30719
  }
30360
30720
  }
30361
- options.hook.registerChild(created.id, input.agent);
30362
- options.log(`[magic-context] hidden child ${created.id} created role=${role} keep_subagents=${options.keepSubagents}`);
30363
- return {
30721
+ const child = {
30364
30722
  id: created.id,
30365
30723
  role,
30366
30724
  generation: options.generation,
30367
30725
  title: roleTitle(role),
30368
30726
  model,
30369
30727
  created_at: createdAt,
30370
- directory: identity.directory
30728
+ directory
30371
30729
  };
30730
+ if (input.parentID && (created.id !== input.id || created.parentID !== input.parentID || !matchesHiddenRunLocation(directory, created.location?.directory))) {
30731
+ await remove(child);
30732
+ throw new Error(`OpenCode created a background run outside its holder at ${directory}`);
30733
+ }
30734
+ options.hook.registerChild(created.id, input.agent);
30735
+ options.log(`[magic-context] hidden child ${created.id} created role=${role} keep_subagents=${options.keepSubagents}`);
30736
+ return child;
30372
30737
  };
30373
30738
  const kept = (child) => keptUnderRetention(options.keepSubagents, child);
30374
30739
  return {
@@ -30867,6 +31232,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
30867
31232
  db: options.db,
30868
31233
  hook: options.hook,
30869
31234
  generation,
31235
+ hostVersion: options.hostVersion,
30870
31236
  keepSubagents: options.keepSubagents === true,
30871
31237
  log: note,
30872
31238
  removalTimeoutMs: options.removalTimeoutMs
@@ -31795,50 +32161,11 @@ class DeletedSessionTombstones {
31795
32161
  }
31796
32162
 
31797
32163
  // src/features/magic-context/dreamer/task-executor.ts
31798
- import { createHash as createHash16 } from "node:crypto";
32164
+ import { createHash as createHash17 } from "node:crypto";
31799
32165
  import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
31800
32166
 
31801
32167
  // src/features/magic-context/mural/compress-cues.ts
31802
- import { createHash as createHash9 } from "node:crypto";
31803
-
31804
- // src/features/magic-context/dreamer/storage-dream-state.ts
31805
- var getDreamStateStatements = new WeakMap;
31806
- var setDreamStateStatements = new WeakMap;
31807
- var deleteDreamStateStatements = new WeakMap;
31808
- function getGetDreamStateStatement(db) {
31809
- let stmt = getDreamStateStatements.get(db);
31810
- if (!stmt) {
31811
- stmt = db.prepare("SELECT value FROM dream_state WHERE key = ?");
31812
- getDreamStateStatements.set(db, stmt);
31813
- }
31814
- return stmt;
31815
- }
31816
- function getSetDreamStateStatement(db) {
31817
- let stmt = setDreamStateStatements.get(db);
31818
- if (!stmt) {
31819
- stmt = db.prepare("INSERT INTO dream_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
31820
- setDreamStateStatements.set(db, stmt);
31821
- }
31822
- return stmt;
31823
- }
31824
- function getDeleteDreamStateStatement(db) {
31825
- let stmt = deleteDreamStateStatements.get(db);
31826
- if (!stmt) {
31827
- stmt = db.prepare("DELETE FROM dream_state WHERE key = ?");
31828
- deleteDreamStateStatements.set(db, stmt);
31829
- }
31830
- return stmt;
31831
- }
31832
- function getDreamState(db, key) {
31833
- const row = getGetDreamStateStatement(db).get(key);
31834
- return typeof row?.value === "string" ? row.value : null;
31835
- }
31836
- function setDreamState(db, key, value) {
31837
- getSetDreamStateStatement(db).run(key, value);
31838
- }
31839
- function deleteDreamState(db, key) {
31840
- getDeleteDreamStateStatement(db).run(key);
31841
- }
32168
+ import { createHash as createHash10 } from "node:crypto";
31842
32169
 
31843
32170
  // src/features/magic-context/dreamer/lease.ts
31844
32171
  var LEASE_DURATION_MS = 2 * 60 * 1000;
@@ -32544,7 +32871,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
32544
32871
  log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
32545
32872
  }
32546
32873
  }
32547
- const commandId = `mural-cues:${route.moduleCommandId}:${createHash9("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
32874
+ const commandId = `mural-cues:${route.moduleCommandId}:${createHash10("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
32548
32875
  let response;
32549
32876
  try {
32550
32877
  response = await route.moduleClient.call({
@@ -33161,7 +33488,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
33161
33488
  }
33162
33489
 
33163
33490
  // src/features/magic-context/dreamer/classify.ts
33164
- import { createHash as createHash10 } from "node:crypto";
33491
+ import { createHash as createHash11 } from "node:crypto";
33165
33492
 
33166
33493
  // src/plugin/rust-tool-backends.ts
33167
33494
  function isRustAuthorityDrainingError(error) {
@@ -33334,7 +33661,6 @@ async function readFailedChildMessages(client, sessionId, directory) {
33334
33661
  }
33335
33662
 
33336
33663
  // src/features/magic-context/dreamer/classify.ts
33337
- var MIN_POOL_TO_CLASSIFY = 10;
33338
33664
  var FULL_POOL_CEILING = 100;
33339
33665
  var STAGE3_ANCHOR_COUNT = 30;
33340
33666
  var CLASSIFY_CHUNK_SIZE = 100;
@@ -33599,7 +33925,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
33599
33925
  if (entry.qualifier)
33600
33926
  modelVariants[entry.model] = entry.qualifier;
33601
33927
  }
33602
- const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash10("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
33928
+ const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash11("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
33603
33929
  const runTask = (hostCompletion) => args.moduleClient?.call({
33604
33930
  sessionId: args.moduleSessionId,
33605
33931
  projectRoot: args.moduleProjectRoot,
@@ -33892,7 +34218,7 @@ function takeCurateSafetyRefusalCount(sessionId) {
33892
34218
 
33893
34219
  // src/features/magic-context/dreamer/docs-proposals.ts
33894
34220
  import { execFileSync } from "node:child_process";
33895
- import { createHash as createHash11 } from "node:crypto";
34221
+ import { createHash as createHash12 } from "node:crypto";
33896
34222
  import {
33897
34223
  existsSync as existsSync4,
33898
34224
  mkdirSync,
@@ -33907,7 +34233,7 @@ import {
33907
34233
  import { tmpdir } from "node:os";
33908
34234
  import { join as join8 } from "node:path";
33909
34235
  var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
33910
- var hash = (text) => createHash11("sha256").update(text).digest("hex");
34236
+ var hash = (text) => createHash12("sha256").update(text).digest("hex");
33911
34237
  var proposalDir = (projectDir) => join8(projectDir, ".cortexkit/magic-context/docs-update-proposals");
33912
34238
  function docsBaseHashes(projectDir) {
33913
34239
  return Object.fromEntries(FILES.map((name) => [
@@ -34527,7 +34853,7 @@ function throwIfAborted2(signal) {
34527
34853
  }
34528
34854
 
34529
34855
  // src/features/magic-context/smart-notes/compiler.ts
34530
- import { createHash as createHash12 } from "node:crypto";
34856
+ import { createHash as createHash13 } from "node:crypto";
34531
34857
 
34532
34858
  // src/features/magic-context/smart-notes/compiler-prompt.ts
34533
34859
  var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
@@ -34874,7 +35200,7 @@ function manifestAdvisoryWarnings(code, manifest) {
34874
35200
  return warnings;
34875
35201
  }
34876
35202
  function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
34877
- return createHash12("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
35203
+ return createHash13("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
34878
35204
  }
34879
35205
  function extractJsonObject(output) {
34880
35206
  const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
@@ -35647,7 +35973,7 @@ function snapshotMaintainDocsFiles(docsDir) {
35647
35973
  }
35648
35974
 
35649
35975
  // src/features/magic-context/dreamer/map-memories.ts
35650
- import { createHash as createHash13 } from "node:crypto";
35976
+ import { createHash as createHash14 } from "node:crypto";
35651
35977
 
35652
35978
  // src/features/magic-context/dreamer/map-memories-prompt.ts
35653
35979
  import { execFile as execFile2 } from "node:child_process";
@@ -35857,37 +36183,6 @@ var MAP_BATCH_SIZE = 5;
35857
36183
  var MAP_BATCH_FLOOR_MS = 240000;
35858
36184
  var CONSECUTIVE_TIMEOUT_LIMIT2 = 2;
35859
36185
  var MAX_INDEPENDENT_REQUEUE_PER_RUN = MAP_BATCH_SIZE;
35860
- function retryKey(project) {
35861
- return `map-memories:retry:${project}`;
35862
- }
35863
- function readRetries(db, project) {
35864
- try {
35865
- const parsed = JSON.parse(getDreamState(db, retryKey(project)) ?? "{}");
35866
- if (!isRecord(parsed))
35867
- return {};
35868
- const retries = {};
35869
- for (const [id, value] of Object.entries(parsed)) {
35870
- if (isRecord(value) && typeof value.content === "string" && typeof value.failures === "number" && typeof value.deferUntil === "number") {
35871
- retries[id] = {
35872
- content: value.content,
35873
- failures: value.failures,
35874
- deferUntil: value.deferUntil
35875
- };
35876
- }
35877
- }
35878
- return retries;
35879
- } catch {
35880
- return {};
35881
- }
35882
- }
35883
- function contentKey2(memory) {
35884
- return createHash13("sha256").update(`${memory.category}
35885
- ${memory.content}`).digest("hex");
35886
- }
35887
- function isDeferred(memory, retries) {
35888
- const retry = retries[memory.id];
35889
- return !!retry && retry.content === contentKey2(memory) && retry.deferUntil > Date.now();
35890
- }
35891
36186
  function assistantText2(messages) {
35892
36187
  const joined = messages.filter((message) => isRecord(message) && (message.role === "assistant" || isRecord(message.info) && message.info.role === "assistant")).map((message) => extractLatestAssistantText([message]) ?? (isRecord(message) && Array.isArray(message.content) ? message.content.filter(isRecord).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
35893
36188
  `) : "")).join(`
@@ -35956,8 +36251,8 @@ function selectMapMemoryInputs(db, projectIdentity, repoDir, includeDeferred = f
35956
36251
  if (requeue.length >= MAX_INDEPENDENT_REQUEUE_PER_RUN)
35957
36252
  break;
35958
36253
  }
35959
- const retries = readRetries(db, projectIdentity);
35960
- return [...unmappedInputs, ...requeue].filter((memory) => includeDeferred || !isDeferred(memory, retries));
36254
+ const retries = readMapMemoryRetries(db, projectIdentity);
36255
+ return [...unmappedInputs, ...requeue].filter((memory) => includeDeferred || !isMapMemoryDeferred(memory, retries));
35961
36256
  }
35962
36257
  async function mapMemories(args) {
35963
36258
  const result = {
@@ -35968,12 +36263,12 @@ async function mapMemories(args) {
35968
36263
  complete: true
35969
36264
  };
35970
36265
  const allInputs = selectMapMemoryInputs(args.db, args.projectIdentity, args.sessionDirectory, true);
35971
- const retries = readRetries(args.db, args.projectIdentity);
36266
+ const retries = readMapMemoryRetries(args.db, args.projectIdentity);
35972
36267
  const activeIds = new Set(allInputs.map((memory) => String(memory.id)));
35973
36268
  for (const id of Object.keys(retries))
35974
36269
  if (!activeIds.has(id))
35975
36270
  delete retries[id];
35976
- const inputs = allInputs.filter((memory) => !isDeferred(memory, retries));
36271
+ const inputs = allInputs.filter((memory) => !isMapMemoryDeferred(memory, retries));
35977
36272
  result.remaining = allInputs.length;
35978
36273
  result.complete = result.remaining === 0;
35979
36274
  if (inputs.length === 0) {
@@ -35990,6 +36285,7 @@ async function mapMemories(args) {
35990
36285
  try {
35991
36286
  let consecutiveTimeouts = 0;
35992
36287
  let timeoutStreakElapsedMs = [];
36288
+ const countedMisses = new Set;
35993
36289
  for (let i = 0;i < batches.length; i += 1) {
35994
36290
  const remainingMs = Math.max(0, args.deadline - Date.now());
35995
36291
  if (remainingMs <= 0) {
@@ -36012,22 +36308,19 @@ async function mapMemories(args) {
36012
36308
  }
36013
36309
  const committed = outcome.mapped + outcome.independent;
36014
36310
  const committedIds = new Set(outcome.committedIds);
36311
+ const missedIds = new Set(outcome.missedIds);
36015
36312
  runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
36016
36313
  for (const memory of batch.inputs) {
36017
36314
  if (committedIds.has(memory.id)) {
36018
36315
  delete retries[memory.id];
36019
36316
  continue;
36020
36317
  }
36021
- const content = contentKey2(memory);
36022
- const prior = retries[memory.id];
36023
- const failures = (prior?.content === content ? prior.failures : 0) + 1;
36024
- retries[memory.id] = {
36025
- content,
36026
- failures,
36027
- deferUntil: failures < 2 ? 0 : Date.now() + Math.min(24, 2 ** (failures - 2)) * 3600000
36028
- };
36318
+ if (missedIds.has(memory.id) && !countedMisses.has(memory.id)) {
36319
+ countedMisses.add(memory.id);
36320
+ retries[memory.id] = nextMapMemoryRetry(memory, retries[memory.id]);
36321
+ }
36029
36322
  }
36030
- setDreamState(args.db, retryKey(args.projectIdentity), JSON.stringify(retries));
36323
+ setDreamState(args.db, mapMemoryRetryKey(args.projectIdentity), JSON.stringify(retries));
36031
36324
  });
36032
36325
  result.mapped += outcome.mapped;
36033
36326
  result.independent += outcome.independent;
@@ -36039,7 +36332,7 @@ async function mapMemories(args) {
36039
36332
  if (outcome.requeue?.length) {
36040
36333
  if (!batch.isOmissionRetry) {
36041
36334
  batches.push({
36042
- inputs: outcome.requeue.filter((memory) => !isDeferred(memory, retries)),
36335
+ inputs: outcome.requeue.filter((memory) => !isMapMemoryDeferred(memory, retries)),
36043
36336
  isOmissionRetry: true
36044
36337
  });
36045
36338
  log2(`[dreamer] map-memories: committed ${committed}/${batch.inputs.length} mapping(s); requeueing ${outcome.requeue.length} omitted id(s) in a targeted retry`);
@@ -36127,11 +36420,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
36127
36420
  stage = "apply";
36128
36421
  const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
36129
36422
  logBatchUsage(run.completion.messages ?? [], outcome.mapped + outcome.independent, startedAt);
36130
- const returnedIds = new Set(outcome.committedIds);
36131
- return {
36132
- ...outcome,
36133
- requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
36134
- };
36423
+ return completedMapBatch(outcome, batch, run.validated, budgetFinalized);
36135
36424
  }
36136
36425
  const client = args.client;
36137
36426
  if (!client)
@@ -36185,11 +36474,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
36185
36474
  stage = "apply";
36186
36475
  const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
36187
36476
  logBatchUsage(run.output, outcome.mapped + outcome.independent, startedAt);
36188
- const returnedIds = new Set(outcome.committedIds);
36189
- return {
36190
- ...outcome,
36191
- requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
36192
- };
36477
+ return completedMapBatch(outcome, batch, run.validated, budgetFinalized);
36193
36478
  } catch (error) {
36194
36479
  const desc = describeError(error);
36195
36480
  log2(`[dreamer] map-memories batch failed: ${desc.brief}`, desc.stackHead ? { stackHead: desc.stackHead } : undefined);
@@ -36231,6 +36516,17 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
36231
36516
  });
36232
36517
  }
36233
36518
  }
36519
+ function completedMapBatch(outcome, batch, parsed, budgetFinalized) {
36520
+ if (budgetFinalized)
36521
+ return outcome;
36522
+ const decided = new Set(parsed.map(({ id }) => id));
36523
+ const committed = new Set(outcome.committedIds);
36524
+ return {
36525
+ ...outcome,
36526
+ missedIds: batch.filter(({ id }) => !decided.has(id)).map(({ id }) => id),
36527
+ requeue: batch.filter(({ id }) => !committed.has(id))
36528
+ };
36529
+ }
36234
36530
  async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = false, allowPartial = false) {
36235
36531
  const batchIds = new Set(batch.map((memory) => memory.id));
36236
36532
  const valid = parsed.filter((entry) => batchIds.has(entry.id));
@@ -36322,7 +36618,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
36322
36618
  name: "memory.set_mapping",
36323
36619
  arguments: {
36324
36620
  memory_project: args.projectIdentity,
36325
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash13("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
36621
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash14("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
36326
36622
  rows
36327
36623
  }
36328
36624
  }
@@ -37258,6 +37554,33 @@ ${buildFrictionGatePrompt({ userLines })}`;
37258
37554
  function retrospectiveGatePromptTokens(messages) {
37259
37555
  return estimateTokens(retrospectiveGatePrompt(messages));
37260
37556
  }
37557
+ function admitRetrospectiveCohorts(rows, firstUnreadTs, maxMessages, promptInputLimitTokens) {
37558
+ const kept = [];
37559
+ let start = 0;
37560
+ for (let first = rows[start];first && first.ts < firstUnreadTs; first = rows[start]) {
37561
+ const ts = first.ts;
37562
+ let end = start + 1;
37563
+ while (end < rows.length && rows[end]?.ts === ts)
37564
+ end += 1;
37565
+ const cohort = rows.slice(start, end);
37566
+ const tooManyRows = end > maxMessages;
37567
+ const tooManyTokens = !tooManyRows && promptInputLimitTokens !== undefined && retrospectiveGatePromptTokens([...kept, ...cohort]) > promptInputLimitTokens;
37568
+ if (tooManyRows || tooManyTokens) {
37569
+ return {
37570
+ kept,
37571
+ budgetTruncated: tooManyTokens,
37572
+ ...kept.length === 0 ? { oversized: { ts, rows: cohort } } : {}
37573
+ };
37574
+ }
37575
+ kept.push(...cohort);
37576
+ start = end;
37577
+ }
37578
+ return { kept, budgetTruncated: false };
37579
+ }
37580
+ function logSkippedRetrospectiveCohort(sessionIds, ts, count, lowerBound) {
37581
+ const sessions = [...new Set(sessionIds)].join(",");
37582
+ log2(`[dreamer] retrospective: oversized timestamp cohort sessionIds=${sessions} timestamp=${ts} ${lowerBound ? "skippedAtLeast" : "skipped"}=${count}`);
37583
+ }
37261
37584
  async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkMs, overlapUserCount, options) {
37262
37585
  const maxMessages = options?.maxMessagesPerRun ?? RETROSPECTIVE_MAX_MESSAGES_PER_RUN;
37263
37586
  const capPerSession = options?.capPerSession ?? RETROSPECTIVE_MAX_MESSAGES_PER_SESSION;
@@ -37287,59 +37610,57 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
37287
37610
  if (sessionsToRead.length > 0) {
37288
37611
  sinceReads.push(...await Promise.all(sessionsToRead.map((session) => provider.readUserMessagesSince(session.sessionId, scanSinceMs, capPerSession))));
37289
37612
  }
37290
- let saturatedFrontier = Number.POSITIVE_INFINITY;
37291
- for (const read of sinceReads) {
37292
- const lastKept = read.truncated ? read.messages[read.messages.length - 1] : undefined;
37293
- if (lastKept)
37294
- saturatedFrontier = Math.min(saturatedFrontier, lastKept.ts - 1);
37295
- }
37296
- const allSince = sinceReads.flatMap((read) => read.messages).filter((message) => message.ts >= recencyCutoffMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
37297
- const countCandidates = allSince.slice(0, maxMessages);
37298
- const countDropped = allSince.slice(maxMessages);
37299
- const keptSince = [];
37300
- let budgetDropped = [];
37301
- if (promptInputLimitTokens === undefined) {
37302
- keptSince.push(...countCandidates);
37303
- } else {
37304
- for (let index = 0;index < countCandidates.length; index += 1) {
37305
- const row = countCandidates[index];
37306
- if (!row)
37307
- continue;
37308
- const candidate = [...keptSince, row];
37309
- if (retrospectiveGatePromptTokens(candidate) <= promptInputLimitTokens) {
37310
- keptSince.push(row);
37311
- continue;
37312
- }
37313
- budgetDropped = countCandidates.slice(index);
37314
- break;
37613
+ const allSince = sinceReads.flatMap((read) => read.messages).filter((message) => message.ts > scanSinceMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
37614
+ let unknownBoundary = !!firstExcludedSession && firstExcludedPendingTs === undefined;
37615
+ let firstUnreadTs = firstExcludedPendingTs ?? Number.POSITIVE_INFINITY;
37616
+ const oversizedSessions = new Map;
37617
+ for (const [index, read] of sinceReads.entries()) {
37618
+ if (!read.truncated)
37619
+ continue;
37620
+ const unreadTs = read.firstOmittedTs ?? read.messages.at(-1)?.ts;
37621
+ if (unreadTs === undefined) {
37622
+ unknownBoundary = true;
37623
+ continue;
37624
+ }
37625
+ firstUnreadTs = Math.min(firstUnreadTs, unreadTs);
37626
+ const sessionId = sessionsToRead[index]?.sessionId;
37627
+ if (sessionId !== undefined && read.firstOmittedTs !== undefined && read.firstOmittedTs === oldestBySession?.get(sessionId)) {
37628
+ oversizedSessions.set(sessionId, read.firstOmittedTs);
37315
37629
  }
37316
37630
  }
37317
- const droppedSince = [...budgetDropped, ...countDropped];
37631
+ const {
37632
+ kept: keptSince,
37633
+ budgetTruncated,
37634
+ oversized
37635
+ } = admitRetrospectiveCohorts(allSince, unknownBoundary ? scanSinceMs : firstUnreadTs, maxMessages, promptInputLimitTokens);
37636
+ const lastKept = keptSince.at(-1);
37318
37637
  let maxScannedTs = scanSinceMs;
37319
- if (oldestBySession && sinceReads.every((read) => read.messages.length === 0)) {
37320
- for (const { session } of eligibleSessions) {
37321
- maxScannedTs = Math.max(maxScannedTs, session.updatedAt ?? scanSinceMs);
37638
+ if (!unknownBoundary) {
37639
+ if (oversized) {
37640
+ maxScannedTs = oversized.ts;
37641
+ logSkippedRetrospectiveCohort(oversized.rows.map(({ sessionId }) => sessionId), maxScannedTs, oversized.rows.length, false);
37642
+ } else if (lastKept) {
37643
+ maxScannedTs = lastKept.ts;
37644
+ } else if (Number.isFinite(firstUnreadTs)) {
37645
+ const blockedSessions = sessions.filter(({ session }) => oldestBySession?.get(session.sessionId) === firstUnreadTs);
37646
+ const hitSessionReadCap = blockedSessions.some(({ session }) => oversizedSessions.get(session.sessionId) === firstUnreadTs);
37647
+ if (hitSessionReadCap || blockedSessions.length > sessionLimit) {
37648
+ maxScannedTs = firstUnreadTs;
37649
+ logSkippedRetrospectiveCohort(blockedSessions.map(({ session }) => session.sessionId), maxScannedTs, Math.max(blockedSessions.length, hitSessionReadCap ? capPerSession + 1 : 0), true);
37650
+ } else {
37651
+ maxScannedTs = Math.max(scanSinceMs, firstUnreadTs - 1);
37652
+ }
37653
+ } else if (oldestBySession && allSince.length === 0) {
37654
+ for (const { session } of eligibleSessions) {
37655
+ maxScannedTs = Math.max(maxScannedTs, session.updatedAt ?? scanSinceMs);
37656
+ }
37322
37657
  }
37323
37658
  }
37324
- for (const row of keptSince) {
37325
- if (row.ts > maxScannedTs)
37326
- maxScannedTs = row.ts;
37327
- }
37328
- let frontier = saturatedFrontier;
37329
- const firstDropped = droppedSince[0];
37330
- if (firstDropped)
37331
- frontier = Math.min(frontier, firstDropped.ts - 1);
37332
- if (typeof firstExcludedPendingTs === "number") {
37333
- frontier = Math.min(frontier, firstExcludedPendingTs - 1);
37334
- } else if (typeof firstExcludedSession?.updatedAt === "number") {
37335
- frontier = Math.min(frontier, firstExcludedSession.updatedAt - 1);
37336
- }
37337
- maxScannedTs = Math.max(scanSinceMs, Math.min(maxScannedTs, frontier));
37338
37659
  const keptSessionIds = new Set(keptSince.map((message) => message.sessionId));
37339
37660
  const overlapSessions = sessionsToRead.filter((session) => keptSessionIds.has(session.sessionId));
37340
37661
  const overlapBatches = overlapUserCount > 0 && watermarkMs > 0 && watermarkMs >= recencyCutoffMs ? await Promise.all(overlapSessions.map((session) => provider.readUserMessagesBefore(session.sessionId, watermarkMs, overlapUserCount))) : [];
37341
37662
  const seen = new Set;
37342
- const merged = [];
37663
+ const merged = [...keptSince];
37343
37664
  const appendUnique = (row) => {
37344
37665
  const key = `${row.sessionId}\x00${row.ts}\x00${row.role}\x00${row.toolName ?? ""}`;
37345
37666
  if (seen.has(key))
@@ -37348,9 +37669,7 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
37348
37669
  merged.push(row);
37349
37670
  return true;
37350
37671
  };
37351
- for (const row of keptSince)
37352
- appendUnique(row);
37353
- const overlapRows = overlapBatches.flat().filter((message) => message.ts >= recencyCutoffMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
37672
+ const overlapRows = overlapBatches.flat().filter((message) => message.ts >= recencyCutoffMs && message.ts <= watermarkMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
37354
37673
  for (const row of overlapRows) {
37355
37674
  const beforeLength = merged.length;
37356
37675
  if (!appendUnique(row))
@@ -37370,7 +37689,7 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
37370
37689
  maxScannedTs,
37371
37690
  promptTokens,
37372
37691
  ...promptInputLimitTokens === undefined ? {} : { promptInputLimitTokens },
37373
- budgetTruncated: budgetDropped.length > 0
37692
+ budgetTruncated
37374
37693
  };
37375
37694
  } finally {
37376
37695
  provider.dispose?.();
@@ -37403,7 +37722,12 @@ function readOpenCodeMessagesSince(db, sessionId, sinceMs, capPerSession) {
37403
37722
  LIMIT ?`).all(sessionId, sinceMs, limit + 1);
37404
37723
  const truncated = rows.length > limit;
37405
37724
  const kept = truncated ? rows.slice(0, limit) : rows;
37406
- return { messages: normalizeOpenCodeRows(db, sessionId, kept), truncated };
37725
+ const firstOmitted = rows[limit];
37726
+ return {
37727
+ messages: normalizeOpenCodeRows(db, sessionId, kept),
37728
+ truncated,
37729
+ ...firstOmitted ? { firstOmittedTs: firstOmitted.time_created } : {}
37730
+ };
37407
37731
  }
37408
37732
  function readOpenCodeOldestMessageTimesSince(db, sessionIds, sinceMs) {
37409
37733
  const result = new Map;
@@ -37631,7 +37955,7 @@ function insertDreamRun(db, run) {
37631
37955
  }
37632
37956
 
37633
37957
  // src/features/magic-context/dreamer/verify.ts
37634
- import { createHash as createHash15 } from "node:crypto";
37958
+ import { createHash as createHash16 } from "node:crypto";
37635
37959
 
37636
37960
  // src/features/magic-context/dreamer/verify-diff.ts
37637
37961
  import { execFile as execFile3 } from "node:child_process";
@@ -37755,7 +38079,7 @@ Read only these changed line ranges if they may affect the claim.`
37755
38079
  import path6 from "node:path";
37756
38080
 
37757
38081
  // src/features/magic-context/dreamer/verify-state.ts
37758
- import { createHash as createHash14 } from "node:crypto";
38082
+ import { createHash as createHash15 } from "node:crypto";
37759
38083
  import { readFile, realpath as realpath2 } from "node:fs/promises";
37760
38084
  import path5 from "node:path";
37761
38085
  function verificationMetadata(memory) {
@@ -37768,7 +38092,7 @@ function verificationMetadata(memory) {
37768
38092
  }
37769
38093
  async function verificationFilesFingerprint(directory, files) {
37770
38094
  const root = await resolveGitTopLevel(directory) ?? path5.resolve(directory);
37771
- const hash = createHash14("sha256");
38095
+ const hash = createHash15("sha256");
37772
38096
  for (const file of [...new Set(files)].sort()) {
37773
38097
  const absolute = path5.resolve(root, file);
37774
38098
  const withinRoot = (candidate) => {
@@ -37781,7 +38105,7 @@ async function verificationFilesFingerprint(directory, files) {
37781
38105
  try {
37782
38106
  if (!withinRoot(await realpath2(absolute)))
37783
38107
  return null;
37784
- hash.update(createHash14("sha256").update(await readFile(absolute)).digest("hex"));
38108
+ hash.update(createHash15("sha256").update(await readFile(absolute)).digest("hex"));
37785
38109
  } catch (error) {
37786
38110
  if (error.code !== "ENOENT")
37787
38111
  return null;
@@ -38586,7 +38910,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
38586
38910
  name: "memory.set_verification",
38587
38911
  arguments: {
38588
38912
  memory_project: args.projectIdentity,
38589
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash15("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
38913
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash16("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
38590
38914
  rows
38591
38915
  }
38592
38916
  }
@@ -39500,7 +39824,7 @@ function parseFrictionGateVerdict(verdict) {
39500
39824
  }
39501
39825
  function computeRetrospectiveWindowKey(flagged) {
39502
39826
  const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
39503
- return createHash16("sha256").update(anchors).digest("hex").slice(0, 32);
39827
+ return createHash17("sha256").update(anchors).digest("hex").slice(0, 32);
39504
39828
  }
39505
39829
  function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
39506
39830
  const flagged = new Set(flaggedOrdinals);
@@ -39619,6 +39943,13 @@ async function runRetrospectiveTask(config, ctx, helpers) {
39619
39943
  const recencyDays = Math.max(1, Math.floor(config.retrospectiveRecencyDays ?? 30));
39620
39944
  const recencyCutoffMs = helpers.invocationStartedAt - recencyDays * RETROSPECTIVE_DAY_MS;
39621
39945
  const scan = await readRetrospectiveScanWindow(provider, projectIdentity, watermarkMs, RETROSPECTIVE_OVERLAP_USER_LINES, { usableInputTokens, recencyCutoffMs });
39946
+ ctx.onRetrospectiveScan?.({
39947
+ watermarkMs,
39948
+ maxScannedTs: scan.maxScannedTs,
39949
+ usableInputTokens,
39950
+ recencyCutoffMs,
39951
+ budgetTruncated: scan.budgetTruncated
39952
+ });
39622
39953
  const clearedTaskStateJson = activeOverflow ? writeRetrospectiveOverflowState(taskState.root, null) : undefined;
39623
39954
  const completedWindow = (retrospectiveWatermarkMs, noOpReason) => ({
39624
39955
  retrospectiveWatermarkMs,
@@ -40406,6 +40737,7 @@ async function runDomainGroup(deps, group, cb) {
40406
40737
  }
40407
40738
  }
40408
40739
  let outcome;
40740
+ const diagnostics = {};
40409
40741
  const startedAt = Date.now();
40410
40742
  try {
40411
40743
  outcome = await executor(due.config, {
@@ -40413,7 +40745,12 @@ async function runDomainGroup(deps, group, cb) {
40413
40745
  projectIdentity,
40414
40746
  holderId,
40415
40747
  leaseKey,
40416
- leaseAcquisition: acquisition
40748
+ leaseAcquisition: acquisition,
40749
+ ...due.config.task === "retrospective" ? {
40750
+ onRetrospectiveScan: (scan) => {
40751
+ diagnostics.retrospectiveScan = scan;
40752
+ }
40753
+ } : {}
40417
40754
  });
40418
40755
  } catch (error) {
40419
40756
  outcome = { status: "failed", transient: true, error: String(error) };
@@ -40424,6 +40761,11 @@ async function runDomainGroup(deps, group, cb) {
40424
40761
  cb?.onSkipped?.(due.config.task, outcome.detail);
40425
40762
  } else if (outcome.status === "completed") {
40426
40763
  advanceAfterRun(db, projectIdentity, due, finishedAt, "completed", null, outcome.schedulePatch, startedAt);
40764
+ const scan = diagnostics.retrospectiveScan;
40765
+ if (scan) {
40766
+ const stored = readRetrospectiveWatermark(db, projectIdentity, due.config.task);
40767
+ log2(`[dreamer] retrospective: watermark start=${scan.watermarkMs} maxScannedTs=${scan.maxScannedTs} patch=${outcome.schedulePatch?.retrospectiveWatermarkMs ?? "none"} stored=${stored ?? "none"} usableInputTokens=${scan.usableInputTokens} recencyCutoffMs=${scan.recencyCutoffMs} budgetTruncated=${scan.budgetTruncated}`, { projectIdentity });
40768
+ }
40427
40769
  cb?.onRan?.(due.config.task, outcome.detail, outcome.backlog);
40428
40770
  } else if (outcome.transient) {
40429
40771
  recordTransientFailure(db, projectIdentity, due, finishedAt, outcome.error ?? null, outcome.schedulePatch);
@@ -40607,7 +40949,12 @@ class V2RetrospectiveRawProvider {
40607
40949
  readUserMessagesSince(sessionId, sinceMs, capPerSession) {
40608
40950
  const cap = Math.max(1, Math.min(9999, Math.floor(capPerSession)));
40609
40951
  const rows = this.read(sessionId, sinceMs, cap + 1);
40610
- return { messages: rows.slice(0, cap), truncated: rows.length > cap };
40952
+ const firstOmitted = rows[cap];
40953
+ return {
40954
+ messages: rows.slice(0, cap),
40955
+ truncated: rows.length > cap,
40956
+ ...firstOmitted ? { firstOmittedTs: firstOmitted.ts } : {}
40957
+ };
40611
40958
  }
40612
40959
  readUserMessagesBefore(sessionId, beforeMs, count) {
40613
40960
  return this.read(sessionId, beforeMs, Math.max(1, Math.min(1e4, Math.floor(count))), true).reverse().filter((row) => hasMeaningfulUserText2([{ type: "text", text: row.text }]));
@@ -41460,11 +41807,60 @@ function createV2EmbeddingScope(initialProject) {
41460
41807
  };
41461
41808
  }
41462
41809
 
41810
+ // src/v2/hooks/fork-history-status.ts
41811
+ var logged = new Set;
41812
+ var toasted = new Set;
41813
+ var isGap = (error) => error?.startsWith("gap before message ") === true;
41814
+ var diagnoses = new WeakMap;
41815
+ function readForkHistoryGap(db, openReader, sessionID) {
41816
+ const rows = db.prepare(`SELECT sequence, start_message AS startMessage, end_message AS endMessage,
41817
+ rebase_status AS rebaseStatus FROM compartments WHERE session_id = ? ORDER BY sequence`).all(sessionID);
41818
+ if (!isGap(validateStoredCompartments(rows)) || rows.some(({ rebaseStatus }) => rebaseStatus === "unresolved")) {
41819
+ diagnoses.get(db)?.delete(sessionID);
41820
+ return false;
41821
+ }
41822
+ let cache = diagnoses.get(db);
41823
+ if (!cache) {
41824
+ cache = new BoundedSessionMap(1000);
41825
+ diagnoses.set(db, cache);
41826
+ }
41827
+ const notice = db.prepare("SELECT coordinate_rebase_notice AS text FROM session_meta WHERE session_id = ?").get(sessionID);
41828
+ const reader = openReader();
41829
+ let gap;
41830
+ try {
41831
+ const key = JSON.stringify([
41832
+ rows,
41833
+ notice?.text ?? null,
41834
+ reader.messageCountAndNewestId(sessionID)
41835
+ ]);
41836
+ const cached = cache.get(sessionID);
41837
+ if (cached?.key === key) {
41838
+ gap = cached.gap;
41839
+ } else {
41840
+ gap = Boolean(reader.forkOrigin(sessionID)) && isGap(validateStoredCompartments(rows, nonNarrativeStoredGapRanges(db, sessionID, rows, (from, to) => iterateV2MessageRange2(reader, sessionID, from, to))));
41841
+ cache.set(sessionID, { key, gap });
41842
+ }
41843
+ } finally {
41844
+ reader.close();
41845
+ }
41846
+ if (!gap)
41847
+ return false;
41848
+ if (!logged.has(sessionID)) {
41849
+ logged.add(sessionID);
41850
+ sessionLog2(sessionID, "v2 fork saved history has a gap; /ctx-recomp repairs this fork");
41851
+ }
41852
+ if (!toasted.has(sessionID) && isTuiConnected2(sessionID)) {
41853
+ toasted.add(sessionID);
41854
+ pushNotification2("toast", { message: renderUserFacingFailure("fork_history_gap", "plain"), variant: "warning" }, sessionID, { liveOnly: true });
41855
+ }
41856
+ return true;
41857
+ }
41858
+
41463
41859
  // src/v2/hooks/generate.ts
41464
- import { createHash as createHash17 } from "node:crypto";
41860
+ import { createHash as createHash18 } from "node:crypto";
41465
41861
  var typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
41466
41862
  function hostPrefixDigest(messages, end) {
41467
- const hash = createHash17("sha256");
41863
+ const hash = createHash18("sha256");
41468
41864
  const chunks = [];
41469
41865
  let pendingCodeUnits = 0;
41470
41866
  const batchCodeUnits = 16 * 1024 * 1024;
@@ -41663,9 +42059,9 @@ function hiddenTerminalError(event) {
41663
42059
  }
41664
42060
 
41665
42061
  // src/v2/hooks/lkg-system.ts
41666
- import { createHash as createHash18 } from "node:crypto";
42062
+ import { createHash as createHash19 } from "node:crypto";
41667
42063
  function identity2(slot) {
41668
- return createHash18("sha256").update(JSON.stringify({
42064
+ return createHash19("sha256").update(JSON.stringify({
41669
42065
  capturedAt: slot.capturedAt,
41670
42066
  captureSequence: slot.captureSequence,
41671
42067
  rowVersion: slot.rowVersion,
@@ -54520,10 +54916,11 @@ Your active memories are already in <project-memory> as \`#id: fact\` lines. Wri
54520
54916
 
54521
54917
  Actions:
54522
54918
  - write: new memory (content + category).
54523
- - update: rewrite one memory whose fact changed (ids: [one], content; category optional to recategorize).
54919
+ - update: rewrite one memory whose fact changed (ids: [one], content; category: the current one to keep, a new one to recategorize).
54524
54920
  - archive: retire wrong or obsolete memories (ids: [one or more], optional reason).
54525
- - merge: collapse duplicates into one (ids: [two or more], content).
54921
+ - merge: collapse duplicates into one (ids: [two or more distinct ids of memories in the same category], content).
54526
54922
  - get: fetch by id (ids: 1–20), readable in every status.
54923
+ The call form that works on every host sends action, content, category and ids every time: argument-dropping providers only emit required fields. For get and archive pass content="" and any valid category; for write pass ids=[].
54527
54924
  Examples: category="CONFIG_VALUES", content="OpenCode source is at ~/Work/OSS/opencode" · category="CONSTRAINTS", content="Dashboard Tauri build needs RGBA PNGs, not grayscale"`;
54528
54925
  var DEFAULT_SEARCH_LIMIT = 10;
54529
54926
  // src/features/magic-context/memory/memory-visibility.ts
@@ -54780,13 +55177,13 @@ function updateMemoryContentInCurrentTransaction(db, memory, content, normalized
54780
55177
  }
54781
55178
  var ctxMemoryArgsShape = {
54782
55179
  action: tool.schema.enum([...CTX_MEMORY_ACTIONS]).describe("write | update | archive | merge | get"),
54783
- content: tool.schema.string().describe("The memory text — one standalone fact (write, update, merge)."),
54784
- category: tool.schema.enum([...V2_MEMORY_CATEGORIES]).describe("Kind of fact (required for write; on update/merge, pass the memory's current category to keep it)."),
54785
- ids: tool.schema.array(tool.schema.number()).describe("Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get."),
55180
+ content: tool.schema.string().describe("Send on every call — the memory text for write, update and merge; pass an empty string for archive and get."),
55181
+ category: tool.schema.enum([...V2_MEMORY_CATEGORIES]).describe("Send on every call — the fact's kind for write; on update/merge, the memory's current category to keep it; archive and get ignore it, so pass any valid category."),
55182
+ ids: tool.schema.array(tool.schema.number()).describe("Send on every call — one id for update, one or more for archive, two or more distinct ids of memories in the same category for merge, 1–20 for get; write takes an empty list."),
54786
55183
  reason: tool.schema.string().optional().describe("Why it is being archived (optional).")
54787
55184
  };
54788
55185
  var ctxMemoryListArgsShape = {
54789
- category: tool.schema.enum([...V2_MEMORY_CATEGORIES]).optional().describe("Kind of fact (required for write; on update/merge optional, omitted keeps the current category)."),
55186
+ category: tool.schema.enum([...V2_MEMORY_CATEGORIES]).optional().describe("Filter listed memories to this category (optional)."),
54790
55187
  limit: tool.schema.number().optional().describe("Max results for list (default 10).")
54791
55188
  };
54792
55189
  var ctxMemoryArgsSchema = tool.schema.object({
@@ -55951,7 +56348,7 @@ function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
55951
56348
  return parts.join(" ");
55952
56349
  }
55953
56350
  // src/tools/ctx-reduce/tools.ts
55954
- import { createHash as createHash19 } from "node:crypto";
56351
+ import { createHash as createHash20 } from "node:crypto";
55955
56352
 
55956
56353
  // src/features/magic-context/range-parser.ts
55957
56354
  function parseRangeString(input) {
@@ -56014,11 +56411,11 @@ function createCtxReduceTool(deps) {
56014
56411
  const stableId = `oc-${sessionId}-${callId}`;
56015
56412
  if (Buffer.byteLength(stableId) <= 128)
56016
56413
  return stableId;
56017
- return `oc-${createHash19("sha256").update(stableId).digest("hex")}`;
56414
+ return `oc-${createHash20("sha256").update(stableId).digest("hex")}`;
56018
56415
  }
56019
56416
  fallbackCommandSequence += 1;
56020
56417
  const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
56021
- return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash19("sha256").update(monotonicId).digest("hex")}`;
56418
+ return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash20("sha256").update(monotonicId).digest("hex")}`;
56022
56419
  };
56023
56420
  return tool({
56024
56421
  description: CTX_REDUCE_DESCRIPTION,
@@ -57268,6 +57665,7 @@ async function registerContext(context) {
57268
57665
  await cleanupLegacyOnce(database);
57269
57666
  return createV2HiddenCompletionExecutor({
57270
57667
  ...context.session,
57668
+ createHolder: (input) => context.session.create(input),
57271
57669
  watchModelActivity: (sessionID, onOutput) => hiddenModelActivity.watch(sessionID, onOutput),
57272
57670
  get: async (input) => {
57273
57671
  const session = await context.session.get(input);
@@ -57294,6 +57692,7 @@ async function registerContext(context) {
57294
57692
  projectIdentity: resolveProjectIdentityForSession(directory, config.allow_home_project) ?? "",
57295
57693
  directory,
57296
57694
  hook: hiddenChildHook,
57695
+ hostVersion: context.app?.version,
57297
57696
  keepSubagents: config.keep_subagents === true,
57298
57697
  ensureAgent: () => hiddenAgentsReady ??= context.agent.reload(),
57299
57698
  modelCatalog: () => Promise.resolve(context.model.list()),
@@ -58007,6 +58406,9 @@ async function registerContext(context) {
58007
58406
  tagger,
58008
58407
  ...createV2ThresholdDeps(config),
58009
58408
  contextUsageMap: usage,
58409
+ hostProjectBindingNotice: (sessionID, message) => {
58410
+ pushLiveNotification2("toast", { message, variant: "warning" }, sessionID);
58411
+ },
58010
58412
  hostInputEstimate: (sessionID) => checkpointInputEstimates.get(sessionID),
58011
58413
  onPassPermission: (sessionID, permission) => {
58012
58414
  checkpointPassPermissions.set(sessionID, permission);
@@ -58772,6 +59174,7 @@ async function registerContext(context) {
58772
59174
  hiddenCompletionExecutor: storageOpenedAtBoot ? hiddenCompletionExecutor : lateHiddenExecutor,
58773
59175
  compactionMarkerStrategy: v2CompactionMarkerStrategy,
58774
59176
  prepareHistorySession,
59177
+ readForkHistoryGap: (database, sessionID) => readForkHistoryGap(database, openStoreReader, sessionID),
58775
59178
  readSessionDirectory: async (sessionID) => {
58776
59179
  try {
58777
59180
  return (await context.session.get({ sessionID })).location?.directory ?? null;