@cortexkit/opencode-magic-context 0.49.90 → 0.49.92

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 (188) hide show
  1. package/dist/auto-search-worker.js +4 -4
  2. package/dist/chunk-embedding-write-worker.js +6 -6
  3. package/dist/{compartment-chunk-embedding-fey2bsyf.js → compartment-chunk-embedding-rp4asvk0.js} +3 -3
  4. package/dist/config/index.d.ts.map +1 -1
  5. package/dist/config/migrate-dreamer-v2.d.ts +1 -0
  6. package/dist/config/migrate-dreamer-v2.d.ts.map +1 -1
  7. package/dist/{conflict-warning-hook-kbq6ppjf.js → conflict-warning-hook-exf96bpt.js} +3 -3
  8. package/dist/{context-cdds0gjj.js → context-e8qd2v00.js} +579 -245
  9. package/dist/{embedding-backfill-qjkaee9s.js → embedding-backfill-w0yq71q2.js} +6 -6
  10. package/dist/embedding-worker.js +3 -3
  11. package/dist/features/magic-context/dreamer/refresh-primers.d.ts.map +1 -1
  12. package/dist/features/magic-context/dreamer/task-scheduler.d.ts +2 -2
  13. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  14. package/dist/features/magic-context/memory/single-store-embedding-drain.d.ts.map +1 -1
  15. package/dist/features/magic-context/overflow-detection.d.ts +7 -1
  16. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  17. package/dist/features/magic-context/project-embedding-registry.d.ts +2 -1
  18. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  19. package/dist/features/magic-context/storage-meta-persisted.d.ts +13 -3
  20. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/compartment-parser.d.ts +2 -0
  22. package/dist/hooks/magic-context/compartment-parser.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner-types.d.ts +7 -7
  25. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/compartment-runner-validation.d.ts +3 -0
  27. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/compartment-trigger.d.ts +2 -1
  29. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/event-handler.d.ts +4 -0
  31. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/event-resolvers.d.ts +5 -0
  33. package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/historian-drain-gate.d.ts +15 -0
  35. package/dist/hooks/magic-context/historian-drain-gate.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/historian-host-runner.d.ts +1 -1
  37. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/historian-prompt.generated.d.ts +1 -1
  39. package/dist/hooks/magic-context/historian-prompt.generated.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/historian-publish-stage-logger.d.ts +5 -0
  41. package/dist/hooks/magic-context/historian-publish-stage-logger.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  43. package/dist/hooks/magic-context/provider-overflow-notice.d.ts +8 -0
  44. package/dist/hooks/magic-context/provider-overflow-notice.d.ts.map +1 -0
  45. package/dist/hooks/magic-context/read-session-db.d.ts +2 -0
  46. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  47. package/dist/hooks/magic-context/read-session-formatting.d.ts +2 -0
  48. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +5 -0
  50. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  51. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  52. package/dist/{index-1y4y98r1.js → index-01h7tqe3.js} +25 -2
  53. package/dist/{index-3pdknr07.js → index-0twg41mh.js} +2 -2
  54. package/dist/{index-q7msfgwz.js → index-3f3d548g.js} +1503 -1371
  55. package/dist/{index-2pdgy88n.js → index-3n376ann.js} +19 -7
  56. package/dist/{index-78t37mcq.js → index-41bma6qs.js} +3 -3
  57. package/dist/{index-qfcjrnpe.js → index-5a9kwapd.js} +4 -4
  58. package/dist/{index-dk3hy2a2.js → index-5pmf4jpj.js} +10 -10
  59. package/dist/{index-2qsca7h7.js → index-5y9w2ax7.js} +4 -4
  60. package/dist/{index-pxnzyvjc.js → index-6r99v53h.js} +1 -1
  61. package/dist/{index-mrjat4eq.js → index-6rk44cer.js} +3 -3
  62. package/dist/{index-60wnwcwz.js → index-901exj0f.js} +91 -26
  63. package/dist/{index-6zewd2n5.js → index-9ffntwyr.js} +1 -1
  64. package/dist/{index-h9hybzr5.js → index-anwy2mfb.js} +6 -6
  65. package/dist/{index-83qd3n7s.js → index-et39x9k3.js} +1 -1
  66. package/dist/{index-w51n3576.js → index-f25ha337.js} +1 -1
  67. package/dist/{index-kknjvmpx.js → index-fqth7850.js} +51 -60
  68. package/dist/{index-zxhev8ze.js → index-hbn5g7rt.js} +1 -1
  69. package/dist/{index-chpzb6xy.js → index-hre29c1a.js} +2 -2
  70. package/dist/{index-08jfpny9.js → index-j2w79s9r.js} +76 -6
  71. package/dist/{index-tt0vs4x5.js → index-jba6ny4m.js} +28 -4
  72. package/dist/{index-m6dnydf8.js → index-mg9s2rc3.js} +1 -1
  73. package/dist/{index-61knrt52.js → index-mjy2k9jr.js} +1 -1
  74. package/dist/{index-wmb2mcdw.js → index-n71006wq.js} +6 -6
  75. package/dist/{index-n1ty0vd3.js → index-r3tdqqtq.js} +127 -101
  76. package/dist/{index-5vsk2cpp.js → index-s7460efs.js} +12 -1
  77. package/dist/{index-x40zr813.js → index-sp5pvs95.js} +9 -1
  78. package/dist/{index-9d3qgwq0.js → index-wvbg9m0h.js} +4 -4
  79. package/dist/index-x3rdza40.js +63 -0
  80. package/dist/{index-jzfsnbmm.js → index-xg1zjht5.js} +5 -5
  81. package/dist/{index-60x5d68t.js → index-xn9efn18.js} +1 -1
  82. package/dist/{index-39rzef89.js → index-ydhymf0b.js} +3 -3
  83. package/dist/{index-g0mb2kb4.js → index-zzhcshdk.js} +75 -67
  84. package/dist/index.js +97 -60
  85. package/dist/{message-index-bounded-r1qys471.js → message-index-bounded-f6fc00ze.js} +6 -6
  86. package/dist/migration-worker.js +4 -4
  87. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  88. package/dist/{project-embedding-registry-m3fp1pa4.js → project-embedding-registry-8je0xg18.js} +7 -5
  89. package/dist/raw-ordinal-warmup-worker.js +4 -4
  90. package/dist/{read-session-chunk-xv9f0wgb.js → read-session-chunk-y2ew3630.js} +5 -5
  91. package/dist/{recomp-orchestrator-dgyb394j.js → recomp-orchestrator-ggtcvb9g.js} +21 -20
  92. package/dist/{render-d014e603.js → render-q8c6wrq9.js} +14 -14
  93. package/dist/{search-archive-gybn6q7s.js → search-archive-pz1jf655.js} +7 -7
  94. package/dist/{search-9gceftb9.js → search-gjyrwapc.js} +16 -16
  95. package/dist/{send-session-notification-gzxz88vq.js → send-session-notification-0779tyd9.js} +2 -2
  96. package/dist/shared/model-suggestion-retry.d.ts +18 -0
  97. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  98. package/dist/{storage-tags-f1ftvjpw.js → storage-tags-7raphcw6.js} +3 -3
  99. package/dist/{store-reader-nf8z86n9.js → store-reader-qbq6q4v0.js} +1 -1
  100. package/dist/{store-n4yz3n66.js → store-yr443ye8.js} +2 -2
  101. package/dist/{task-config-qt6n4bxm.js → task-config-vrebjxyy.js} +2 -1
  102. package/dist/{transform-postprocess-phase-34k1zwsy.js → transform-postprocess-phase-pmzdd3s2.js} +22 -21
  103. package/dist/v2/auto-search-worker.js +4 -4
  104. package/dist/v2/chunk-embedding-write-worker.js +6 -6
  105. package/dist/v2/{compartment-chunk-embedding-knt2468v.js → compartment-chunk-embedding-w7ht0t9v.js} +3 -3
  106. package/dist/v2/{context-satgm752.js → context-qqbpzk1q.js} +686 -323
  107. package/dist/v2/{embedding-backfill-0ar1bm97.js → embedding-backfill-95m72gxa.js} +6 -6
  108. package/dist/v2/embedding-worker.js +3 -3
  109. package/dist/v2/fold/host-media.d.ts.map +1 -1
  110. package/dist/v2/fold/native-replay-v3.d.ts.map +1 -1
  111. package/dist/v2/fold/native-replay.d.ts +1 -0
  112. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  113. package/dist/v2/fold/restore.d.ts +15 -0
  114. package/dist/v2/fold/restore.d.ts.map +1 -1
  115. package/dist/v2/hidden-child-native.d.ts +1 -1
  116. package/dist/v2/hidden-child-native.d.ts.map +1 -1
  117. package/dist/v2/hidden-child-record.d.ts +11 -2
  118. package/dist/v2/hidden-child-record.d.ts.map +1 -1
  119. package/dist/v2/hidden-child-sweep.d.ts +3 -0
  120. package/dist/v2/hidden-child-sweep.d.ts.map +1 -1
  121. package/dist/v2/hidden-completion.d.ts +4 -0
  122. package/dist/v2/hidden-completion.d.ts.map +1 -1
  123. package/dist/v2/hidden-run-holder.d.ts +6 -6
  124. package/dist/v2/hidden-run-holder.d.ts.map +1 -1
  125. package/dist/v2/hooks/context.d.ts +2 -2
  126. package/dist/v2/hooks/context.d.ts.map +1 -1
  127. package/dist/v2/hooks/hidden-child.d.ts +2 -0
  128. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  129. package/dist/v2/hooks/overflow-recovery.d.ts +6 -0
  130. package/dist/v2/hooks/overflow-recovery.d.ts.map +1 -1
  131. package/dist/v2/{message-index-bounded-b07r9cjv.js → message-index-bounded-70g28hyg.js} +6 -6
  132. package/dist/v2/migration-worker.js +4 -4
  133. package/dist/v2/{project-embedding-registry-gx2waee8.js → project-embedding-registry-fcxf4qht.js} +7 -5
  134. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  135. package/dist/v2/{read-session-chunk-38wdy8nd.js → read-session-chunk-9rf0n9e6.js} +5 -5
  136. package/dist/v2/{recomp-orchestrator-wq7gbkqa.js → recomp-orchestrator-cwghhjc9.js} +21 -20
  137. package/dist/v2/{render-2dan17xc.js → render-e852zmxz.js} +14 -14
  138. package/dist/v2/{search-archive-89hdy0a2.js → search-archive-tmn6b5w8.js} +7 -7
  139. package/dist/v2/{search-nyqykx7q.js → search-jd3vczhn.js} +15 -15
  140. package/dist/v2/{send-session-notification-zazaxxpf.js → send-session-notification-v69y04f5.js} +2 -2
  141. package/dist/v2/server-3gz9k20t.js +63 -0
  142. package/dist/v2/{server-09h2vyvs.js → server-6t3asmx8.js} +6 -6
  143. package/dist/v2/{server-dgjqvpgd.js → server-72k2r3kt.js} +19 -7
  144. package/dist/v2/{server-pjk9spbf.js → server-7e89a2kf.js} +1 -1
  145. package/dist/v2/{server-dtcwkdqj.js → server-7x5a46hf.js} +1427 -1322
  146. package/dist/v2/{server-add0j5n3.js → server-8ps3717t.js} +3 -3
  147. package/dist/v2/{server-c7awk5s2.js → server-9011eteb.js} +4 -4
  148. package/dist/v2/{server-f7tzvmzs.js → server-b4efn08m.js} +1 -1
  149. package/dist/v2/{server-y17r5ryz.js → server-barj0mjz.js} +2 -2
  150. package/dist/v2/{server-b0a9h3ds.js → server-bvr9xs8h.js} +5 -5
  151. package/dist/v2/{server-pmws7we9.js → server-d4trxrj3.js} +91 -26
  152. package/dist/v2/{server-fb5hvvfc.js → server-fj3pekz2.js} +3 -3
  153. package/dist/v2/{server-6250cxzs.js → server-gs2251jr.js} +1 -1
  154. package/dist/v2/{server-a85j3kam.js → server-jkj1dq6j.js} +28 -4
  155. package/dist/v2/{server-ta4h0fch.js → server-js2v309w.js} +9 -9
  156. package/dist/v2/{server-9n2qgk29.js → server-mgxqfprb.js} +2 -2
  157. package/dist/v2/{server-2kswss3d.js → server-n5wn7d9b.js} +48 -60
  158. package/dist/v2/{server-vy0beygw.js → server-p4g021y5.js} +4 -4
  159. package/dist/v2/{server-x6fn9x8q.js → server-ps6zrzwj.js} +1 -1
  160. package/dist/v2/{server-y8xjr8rx.js → server-qb3s0mnc.js} +12 -1
  161. package/dist/v2/{server-stjy5dxv.js → server-qntmqaca.js} +1 -1
  162. package/dist/v2/{server-ytqps2xa.js → server-rkj44mez.js} +76 -6
  163. package/dist/v2/{server-tj65pgvg.js → server-vsqmkvxc.js} +32 -5
  164. package/dist/v2/{server-qyazxy92.js → server-vtgeyhq6.js} +25 -2
  165. package/dist/v2/{server-fn4ky6mn.js → server-x69fqsvz.js} +1 -1
  166. package/dist/v2/{server-yx0nyj1q.js → server-ysjjcatk.js} +3 -3
  167. package/dist/v2/server.js +4 -3
  168. package/dist/v2/{storage-tags-pmw33chf.js → storage-tags-wgsemtw1.js} +3 -3
  169. package/dist/v2/{store-y56y034s.js → store-enef5jcn.js} +2 -2
  170. package/dist/v2/{store-reader-2vhx33n6.js → store-reader-jbaqv1yp.js} +1 -1
  171. package/dist/v2/store-reader.d.ts +18 -0
  172. package/dist/v2/store-reader.d.ts.map +1 -1
  173. package/dist/v2/{task-config-ex2vajr2.js → task-config-4nqq2s0w.js} +2 -1
  174. package/dist/v2/{v2-archive-reader-gh1jghf7.js → v2-archive-reader-dm1aeqk2.js} +1 -1
  175. package/dist/v2/{wrapup-orchestrator-2h7ayss9.js → wrapup-orchestrator-cke368np.js} +21 -20
  176. package/dist/{v2-archive-reader-8158kyfd.js → v2-archive-reader-39ye0d3b.js} +1 -1
  177. package/dist/{wrapup-orchestrator-ct59br0c.js → wrapup-orchestrator-ggnk0r4r.js} +22 -21
  178. package/package.json +1 -1
  179. package/src/config/index.test.ts +58 -0
  180. package/src/config/index.ts +4 -1
  181. package/src/config/migrate-dreamer-v2.ts +42 -0
  182. package/src/shared/model-suggestion-retry.test.ts +37 -0
  183. package/src/shared/model-suggestion-retry.ts +38 -4
  184. package/src/shared/models-dev-cache.test.ts +15 -0
  185. package/src/shared/startup-maintenance-policy.test.ts +11 -6
  186. package/dist/index-ksdyrrav.js +0 -52
  187. package/dist/v2/server-0s95v3en.js +0 -49
  188. /package/dist/v2/{server-3ap5dmhc.js → server-5hwf5c7r.js} +0 -0
@@ -35,7 +35,7 @@ import {
35
35
  getRawSessionTagKeysThrough2,
36
36
  getLegacyProtectedTailStartOrdinal2,
37
37
  readSessionChunk2
38
- } from "./index-2qsca7h7.js";
38
+ } from "./index-5y9w2ax7.js";
39
39
  import {
40
40
  getHarness2,
41
41
  harnessOwnsOpenCodeStore2
@@ -75,6 +75,12 @@ import {
75
75
  resolveHistorianProducerLimits2,
76
76
  producerSourceLocalBudget2
77
77
  } from "./index-xsqw8kbd.js";
78
+ import {
79
+ isCompactionEnabled,
80
+ migrateLegacyAgentEnabledInMemory,
81
+ CANONICAL_DREAM_TASKS,
82
+ isCanonicalDreamTask
83
+ } from "./index-fqth7850.js";
78
84
  import {
79
85
  withContentLanguageDirective,
80
86
  buildPrimaryLanguageDirective,
@@ -97,7 +103,7 @@ import {
97
103
  hasMeaningfulUserText2,
98
104
  estimateTokens,
99
105
  estimateFixedPromptTokens
100
- } from "./index-5vsk2cpp.js";
106
+ } from "./index-s7460efs.js";
101
107
  import {
102
108
  FAIL_CLOSED_DOCTOR_COMMAND
103
109
  } from "./index-wh9fxds5.js";
@@ -117,7 +123,7 @@ import {
117
123
  LATEST_SUPPORTED_VERSION,
118
124
  getPersistedSchemaVersion,
119
125
  openDatabase
120
- } from "./index-mrjat4eq.js";
126
+ } from "./index-6rk44cer.js";
121
127
  import {
122
128
  areRustHistorianSyntheticParts2,
123
129
  isStrictGapHealingMessage2,
@@ -134,10 +140,10 @@ import {
134
140
  resolveStoredPathWorkspaceIdentity,
135
141
  sourceNameForMemory,
136
142
  computeWorkspaceEpochFingerprint
137
- } from "./index-tt0vs4x5.js";
143
+ } from "./index-jba6ny4m.js";
138
144
  import {
139
145
  BoundedSessionMap
140
- } from "./index-m6dnydf8.js";
146
+ } from "./index-mg9s2rc3.js";
141
147
  import {
142
148
  V2_MEMORY_CATEGORIES,
143
149
  CATEGORY_PRIORITY,
@@ -161,7 +167,7 @@ import {
161
167
  replaceCompartmentChunkEmbeddings2,
162
168
  deleteChunkEmbedBackoffForSession2,
163
169
  chunkWindowSourceKey2
164
- } from "./index-3pdknr07.js";
170
+ } from "./index-0twg41mh.js";
165
171
  import {
166
172
  COMPARTMENT_LEASE_RENEWAL_MS,
167
173
  getCompartmentLeaseBlocker,
@@ -206,14 +212,14 @@ import {
206
212
  getProjectState,
207
213
  recordSubagentInvocation,
208
214
  getLatestHistorianInvocationId
209
- } from "./index-h9hybzr5.js";
215
+ } from "./index-anwy2mfb.js";
210
216
  import {
211
217
  clearCompressionDepth,
212
218
  clearCompressionDepthRange,
213
219
  toMessageIndexSource,
214
220
  clearIndexedMessagesInTransaction,
215
221
  indexSourcesAfterOrdinal
216
- } from "./index-chpzb6xy.js";
222
+ } from "./index-hre29c1a.js";
217
223
  import {
218
224
  stripWellFormedLeadingTagPrefix,
219
225
  peelLeadingMcTagNotation,
@@ -231,6 +237,7 @@ import {
231
237
  recordProtectedTailPublicationFloor,
232
238
  recordProtectedTailNoEligibleHead,
233
239
  isWrapupInProgress,
240
+ getProtectedTailDrainBudgetSkip,
234
241
  reserveProtectedTailDrainTokens,
235
242
  clearEmergencyDrainLatch,
236
243
  recordHistorianDrainFailure,
@@ -263,17 +270,17 @@ import {
263
270
  foldShrunkPartTags2,
264
271
  getTagNumberByMessageId2,
265
272
  getActiveTagsBySession2
266
- } from "./index-60wnwcwz.js";
273
+ } from "./index-901exj0f.js";
267
274
  import {
268
275
  openCodeDbExists,
269
276
  withReadOnlySessionDb,
270
277
  getMessageTimesFromOpenCodeDb
271
- } from "./index-x40zr813.js";
278
+ } from "./index-sp5pvs95.js";
272
279
  import {
273
280
  getSessionNotes,
274
281
  getReadySmartNotes,
275
282
  insertPrimerCandidates
276
- } from "./index-61knrt52.js";
283
+ } from "./index-mjy2k9jr.js";
277
284
  import {
278
285
  pushNotification2
279
286
  } from "./index-y14pawe1.js";
@@ -291,13 +298,13 @@ import {
291
298
  getProjectChunkEmbeddingModelId2,
292
299
  getProjectEmbeddingMaxInputTokens2,
293
300
  embedItemsWindowBounded2
294
- } from "./index-2pdgy88n.js";
301
+ } from "./index-3n376ann.js";
295
302
  import {
296
303
  renderUserFacingFailure,
297
304
  userFacingFailureCode,
298
305
  promoteSessionFactsDurable,
299
306
  embedPromotedFacts
300
- } from "./index-39rzef89.js";
307
+ } from "./index-ydhymf0b.js";
301
308
  import {
302
309
  isMarkerCandidateBasisCurrent2,
303
310
  invalidateMarkerCandidateBasis2,
@@ -311,11 +318,7 @@ import {
311
318
  } from "./index-832w615x.js";
312
319
  import {
313
320
  sendStatusNotification2
314
- } from "./index-6zewd2n5.js";
315
- import {
316
- isCompactionEnabled,
317
- migrateLegacyAgentEnabledInMemory
318
- } from "./index-ksdyrrav.js";
321
+ } from "./index-9ffntwyr.js";
319
322
  import {
320
323
  retreatPastHostUnservedRows,
321
324
  snapTerminalCompartmentToServedRow,
@@ -1170,6 +1173,30 @@ function windowToCron(schedule) {
1170
1173
  function asObject(value) {
1171
1174
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
1172
1175
  }
1176
+ function unknownDreamTaskWarnings(config, authoredText) {
1177
+ const tasks = asObject(asObject(config.dreamer)?.tasks);
1178
+ if (!tasks)
1179
+ return [];
1180
+ const unknown = Object.keys(tasks).filter((key) => !isCanonicalDreamTask(key) && key !== "key-files" && !RETIRED_OBJECT_MEMORY_TASKS.includes(key));
1181
+ if (unknown.length === 0)
1182
+ return [];
1183
+ const authored = asObject(parseJsoncRecovering(authoredText).value);
1184
+ const authoredTasks = asObject(asObject(authored?.dreamer)?.tasks);
1185
+ const valid = `Valid task names: ${CANONICAL_DREAM_TASKS.join(", ")}.`;
1186
+ const warnings = [];
1187
+ let expandedUnknown = false;
1188
+ for (const name of unknown) {
1189
+ if (authoredTasks && Object.hasOwn(authoredTasks, name)) {
1190
+ warnings.push(`${JSON.stringify(`dreamer.tasks.${name}`)}: unknown task name, ignoring. ${valid}`);
1191
+ } else {
1192
+ expandedUnknown = true;
1193
+ }
1194
+ }
1195
+ if (expandedUnknown) {
1196
+ warnings.push(`a nightly task name from variable expansion is unknown, ignoring. ${valid}`);
1197
+ }
1198
+ return warnings;
1199
+ }
1173
1200
  function cronIntervalScore(schedule) {
1174
1201
  const parts = schedule.trim().split(/\s+/);
1175
1202
  if (parts.length !== 5)
@@ -2727,7 +2754,8 @@ function loadConfigFileDetailed(configPath, source) {
2727
2754
  ...parseFailures.map((failure) => failure.warning),
2728
2755
  ...rawWarnings.map((warning) => `${configPath}: ${warning}`),
2729
2756
  ...substituted.warnings.map((warning) => `${configPath}: ${warning}`),
2730
- ...unsafeKeyWarnings.map((warning) => `${configPath}: ${warning}`)
2757
+ ...unsafeKeyWarnings.map((warning) => `${configPath}: ${warning}`),
2758
+ ...unknownDreamTaskWarnings(config, rawText).map((warning) => `${configPath}: ${warning}`)
2731
2759
  ],
2732
2760
  parseFailures,
2733
2761
  warningDetails: parseFailures,
@@ -3861,6 +3889,10 @@ Facts capture stable properties of the project that survive past any single comp
3861
3889
  - One fact bullet = exactly one rule/default/constraint/decision/name.
3862
3890
  - If a new fact contradicts a \`<project_memory>\` entry, emit the new fact as you observe it. **Do not write "X was Y but now Z" framing — the dreamer handles contradiction resolution.** Your job is to report what is true in this chunk; the dreamer reconciles.
3863
3891
 
3892
+ Prefix every <facts> bullet with the compartment it came from: \`* [at_compartment=N] Fact text\`.
3893
+ - N is the 1-based index of the compartment above that the fact came from (the same convention as events).
3894
+ - When you can't tell which compartment, write \`* [at_compartment=unknown] Fact text\`. Never guess.
3895
+
3864
3896
  ### The 5 categories
3865
3897
 
3866
3898
  Each statement maps to exactly one category. If a statement seems to fit two categories, you have not understood it sharply enough — re-read it and pick the category that captures the durable signal.
@@ -4176,19 +4208,19 @@ Closing tags must match their opening tier tag (e.g. \`<p1>...</p1>\`, never \`<
4176
4208
  </compartments>
4177
4209
  <facts>
4178
4210
  <PROJECT_RULES>
4179
- * Fact text
4211
+ * [at_compartment=N] Fact text
4180
4212
  </PROJECT_RULES>
4181
4213
  <ARCHITECTURE>
4182
- * Fact text
4214
+ * [at_compartment=N] Fact text
4183
4215
  </ARCHITECTURE>
4184
4216
  <CONSTRAINTS>
4185
- * Fact text
4217
+ * [at_compartment=N] Fact text
4186
4218
  </CONSTRAINTS>
4187
4219
  <CONFIG_VALUES>
4188
- * Fact text
4220
+ * [at_compartment=N] Fact text
4189
4221
  </CONFIG_VALUES>
4190
4222
  <NAMING>
4191
- * Fact text
4223
+ * [at_compartment=N] Fact text
4192
4224
  </NAMING>
4193
4225
  </facts>
4194
4226
  <events>
@@ -4720,24 +4752,27 @@ function isHiddenRunHolder(id) {
4720
4752
  return id.startsWith(HOLDER_PREFIX);
4721
4753
  }
4722
4754
  function supportsQuietHiddenChildren(version) {
4723
- return typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version) && version !== "2.3.0";
4755
+ return version !== "2.3.0";
4724
4756
  }
4725
4757
  function matchesHiddenRunLocation(wanted, returned) {
4726
4758
  return sameProjectDirectory(wanted, returned ?? "");
4727
4759
  }
4728
- async function hiddenRunPlacement(createHolder, directory) {
4729
- if (!(await stat(directory)).isDirectory())
4760
+ async function hiddenRunPlacement(createHolder, directory, budget) {
4761
+ const work = budget?.work ?? ((start) => start());
4762
+ budget?.setStage("checking the holder directory");
4763
+ if (!(await work(() => stat(directory))).isDirectory())
4730
4764
  throw new Error(`Not a run directory: ${directory}`);
4731
4765
  const base = HOLDER_PREFIX + createHash3("sha256").update(directory).digest("hex").slice(0, 32);
4732
4766
  const displaced = [];
4733
4767
  for (let index = 0;index < HOLDER_CANDIDATES; index++) {
4734
4768
  const id = index === 0 ? base : `${base}_${index + 1}`;
4735
- const holder = await createHolder({
4769
+ budget?.setStage("creating the background holder");
4770
+ const holder = await work(() => createHolder({
4736
4771
  id,
4737
4772
  title: "Magic Context background runs",
4738
4773
  location: { directory },
4739
4774
  metadata: { magic_context: "background-holder" }
4740
- });
4775
+ }));
4741
4776
  if (holder.id !== id || holder.parentID)
4742
4777
  throw new Error(`OpenCode did not return the expected background holder ${id}`);
4743
4778
  if (holder.metadata?.magic_context === "background-holder" && matchesHiddenRunLocation(directory, holder.location?.directory)) {
@@ -4794,14 +4829,25 @@ function hiddenAgentAllowedTools(agent) {
4794
4829
  }
4795
4830
  var HIDDEN_RUN_DISPOSED_REASON = "the Magic Context plugin instance that started this hidden run was disposed (OpenCode reloaded the plugin), so the run was cancelled; the work is retried on a later run";
4796
4831
  var DISPOSED_CHILDREN_KEY = Symbol.for("@cortexkit/magic-context/v2/disposed-hidden-children");
4832
+ var TIMED_OUT_CHILDREN_KEY = Symbol.for("@cortexkit/magic-context/v2/timed-out-hidden-children");
4797
4833
  var DISPOSED_CHILDREN_LIMIT = 512;
4834
+ var HIDDEN_RUN_RETIRED_REASON = "the Magic Context hidden run was cancelled or timed out and is being retired";
4798
4835
  function disposedChildren() {
4799
4836
  const store = globalThis;
4800
4837
  store[DISPOSED_CHILDREN_KEY] ??= new Set;
4801
4838
  return store[DISPOSED_CHILDREN_KEY];
4802
4839
  }
4803
4840
  function noteChildOfDisposedInstance(sessionID) {
4804
- const children = disposedChildren();
4841
+ rememberStoppedChild(disposedChildren(), sessionID);
4842
+ }
4843
+ function timedOutChildren() {
4844
+ const store = globalThis;
4845
+ return store[TIMED_OUT_CHILDREN_KEY] ??= new Set;
4846
+ }
4847
+ function noteTimedOutHiddenChild(sessionID) {
4848
+ rememberStoppedChild(timedOutChildren(), sessionID);
4849
+ }
4850
+ function rememberStoppedChild(children, sessionID) {
4805
4851
  children.delete(sessionID);
4806
4852
  children.add(sessionID);
4807
4853
  while (children.size > DISPOSED_CHILDREN_LIMIT) {
@@ -4844,6 +4890,8 @@ async function registerHiddenChildAgents(agent) {
4844
4890
  });
4845
4891
  }
4846
4892
  function hiddenToolCallRefusal(call, hook) {
4893
+ if (timedOutChildren().has(call.sessionID))
4894
+ return `Magic Context hidden child ${call.sessionID} refused: ${HIDDEN_RUN_RETIRED_REASON}; ${call.tool} refused`;
4847
4895
  const owned = hook.owns(call.sessionID);
4848
4896
  if (!owned && isChildOfDisposedInstance(call.sessionID))
4849
4897
  return `Magic Context hidden child ${call.sessionID} refused: ${HIDDEN_RUN_DISPOSED_REASON}; ${call.tool} refused`;
@@ -5025,6 +5073,8 @@ class HiddenChildHook {
5025
5073
  }
5026
5074
  }
5027
5075
  compactionSummary(sessionID, agent) {
5076
+ if (timedOutChildren().has(sessionID))
5077
+ this.refuse(HIDDEN_RUN_RETIRED_REASON, { sessionID, messages: [] }, undefined);
5028
5078
  if (!this.owns(sessionID)) {
5029
5079
  if (isChildOfDisposedInstance(sessionID)) {
5030
5080
  this.refuse(`Refusing to compact a Magic Context hidden child of a disposed plugin instance: ${HIDDEN_RUN_DISPOSED_REASON}`, { sessionID, messages: [] }, undefined, undefined, "hidden_instance_disposed");
@@ -5080,6 +5130,8 @@ class HiddenChildHook {
5080
5130
  return [{ type: "text", text: claudeAgentInstructionsText(system) }, ...parts];
5081
5131
  }
5082
5132
  apply(draft) {
5133
+ if (timedOutChildren().has(draft.sessionID))
5134
+ this.refuse(HIDDEN_RUN_RETIRED_REASON, draft, undefined);
5083
5135
  if (!this.owns(draft.sessionID)) {
5084
5136
  if (isChildOfDisposedInstance(draft.sessionID)) {
5085
5137
  this.refuse(`Refusing a turn of a Magic Context hidden child of a disposed plugin instance: ${HIDDEN_RUN_DISPOSED_REASON}`, draft, userTexts(draft.messages.at(-1)), undefined, "hidden_instance_disposed");
@@ -5400,6 +5452,14 @@ class ModelProducedNoOutputError extends Error {
5400
5452
  }
5401
5453
  }
5402
5454
  var modelActivityBySignal = new WeakMap;
5455
+ function promptTransportBudget(signal) {
5456
+ return signal ? modelActivityBySignal.get(signal) : undefined;
5457
+ }
5458
+ function notePromptSetupTimeout(signal, read) {
5459
+ const activity = signal ? modelActivityBySignal.get(signal) : undefined;
5460
+ if (activity)
5461
+ activity.setupTimeout = read;
5462
+ }
5403
5463
  function noteModelActivityMonitored(signal) {
5404
5464
  const activity = signal ? modelActivityBySignal.get(signal) : undefined;
5405
5465
  if (activity)
@@ -5499,9 +5559,20 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport, fir
5499
5559
  throw new Error(externalAbortMessage(signal));
5500
5560
  }
5501
5561
  const controller = new AbortController;
5502
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
5503
- const activity = { monitored: false, received: false };
5562
+ const activity = {
5563
+ monitored: false,
5564
+ received: false,
5565
+ timeoutMs,
5566
+ deadline: Date.now() + timeoutMs
5567
+ };
5504
5568
  modelActivityBySignal.set(controller.signal, activity);
5569
+ let setupTimeout;
5570
+ const timeout = setTimeout(() => {
5571
+ try {
5572
+ setupTimeout = activity.setupTimeout?.();
5573
+ } catch {}
5574
+ controller.abort();
5575
+ }, timeoutMs);
5505
5576
  let silent = false;
5506
5577
  const firstOutputTimer = firstOutputTimeoutMs !== undefined && firstOutputTimeoutMs < timeoutMs ? setTimeout(() => {
5507
5578
  if (!activity.monitored || activity.received)
@@ -5509,7 +5580,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport, fir
5509
5580
  silent = true;
5510
5581
  controller.abort(new ModelProducedNoOutputError(firstOutputTimeoutMs));
5511
5582
  }, firstOutputTimeoutMs) : undefined;
5512
- const timeoutError = () => silent && firstOutputTimeoutMs !== undefined ? new ModelProducedNoOutputError(firstOutputTimeoutMs) : new Error(`prompt timed out after ${timeoutMs}ms`);
5583
+ const timeoutError = () => setupTimeout ?? (silent && firstOutputTimeoutMs !== undefined ? new ModelProducedNoOutputError(firstOutputTimeoutMs) : new Error(`prompt timed out after ${timeoutMs}ms`));
5513
5584
  const onExternalAbort = () => controller.abort();
5514
5585
  signal?.addEventListener("abort", onExternalAbort);
5515
5586
  try {
@@ -5541,6 +5612,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport, fir
5541
5612
  }
5542
5613
  throw error;
5543
5614
  } finally {
5615
+ activity.setupTimeout = undefined;
5544
5616
  clearTimeout(timeout);
5545
5617
  if (firstOutputTimer)
5546
5618
  clearTimeout(firstOutputTimer);
@@ -6866,6 +6938,9 @@ function mapParsedCompartmentsToChunk(compartments, chunk, sequenceOffset) {
6866
6938
  }
6867
6939
 
6868
6940
  // src/hooks/magic-context/historian-publish-stage-logger.ts
6941
+ function logWeakTailFactPromotion(sessionId, promotion) {
6942
+ sessionLog2(sessionId, `historian weak-tail fact promotion: reason=${promotion.reason} facts_stored=${promotion.stored} facts_not_stored=${promotion.emitted - promotion.stored}`);
6943
+ }
6869
6944
  function startHistorianPublishStage(sessionId, stage, extra) {
6870
6945
  const suffix = extra ? ` ${extra}` : "";
6871
6946
  sessionLog2(sessionId, `historian publish stage: stage=${stage} status=started elapsed=0.0ms${suffix}`);
@@ -6925,6 +7000,9 @@ function shouldDiscardLastHistorianCompartment(compartments, chunk) {
6925
7000
  const lookaheadMargin = chunk.endIndex - last.endMessage;
6926
7001
  return lookaheadMargin <= HISTORIAN_BOUNDARY_HEALING_SLACK && !boundarySplitsCompletedToolArc(previous.endMessage + 1, chunk.completedToolArcs);
6927
7002
  }
7003
+ function retainAnchoredHistorianFacts(facts, trustedCount) {
7004
+ return facts.filter(({ originCompartmentIndex }) => originCompartmentIndex !== undefined && originCompartmentIndex >= 1 && originCompartmentIndex <= trustedCount);
7005
+ }
6928
7006
  function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, sequenceOffset) {
6929
7007
  const parseStarted = startHistorianPublishStage(sessionId, "parse", `response_chars=${text.length}`);
6930
7008
  const parsed = parseCompartmentOutput(text);
@@ -12773,21 +12851,21 @@ Acorn Suite made JWT tenant_id the single tenant authority across REST, GraphQL,
12773
12851
  </compartment>
12774
12852
  <facts>
12775
12853
  <PROJECT_RULES>
12776
- * All tenant-scoped Acorn Suite handlers must call requireTenantContext(req) and fail closed; do not recover missing tenant_id from orgSlug or X-Org-Slug.
12777
- * Acorn Suite auth changes must include both REST and GraphQL tenant-boundary tests before merge.
12854
+ * [at_compartment=1] All tenant-scoped Acorn Suite handlers must call requireTenantContext(req) and fail closed; do not recover missing tenant_id from orgSlug or X-Org-Slug.
12855
+ * [at_compartment=1] Acorn Suite auth changes must include both REST and GraphQL tenant-boundary tests before merge.
12778
12856
  </PROJECT_RULES>
12779
12857
  <ARCHITECTURE>
12780
- * Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
12781
- * Platform support bypass is modeled as a service actor, not as a tenant wildcard.
12858
+ * [at_compartment=1] Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
12859
+ * [at_compartment=1] Platform support bypass is modeled as a service actor, not as a tenant wildcard.
12782
12860
  </ARCHITECTURE>
12783
12861
  <CONSTRAINTS>
12784
- * X-Org-Slug and route orgSlug are presentation hints only; using them as tenant authority can produce cross-tenant reads when cached dashboard URLs are stale.
12862
+ * [at_compartment=1] X-Org-Slug and route orgSlug are presentation hints only; using them as tenant authority can produce cross-tenant reads when cached dashboard URLs are stale.
12785
12863
  </CONSTRAINTS>
12786
12864
  <CONFIG_VALUES>
12787
- * Acorn Suite tenant-boundary fixtures live under apps/api/test/tenant-boundary/ and use seed tenants acme_lab and beta_works.
12865
+ * [at_compartment=1] Acorn Suite tenant-boundary fixtures live under apps/api/test/tenant-boundary/ and use seed tenants acme_lab and beta_works.
12788
12866
  </CONFIG_VALUES>
12789
12867
  <NAMING>
12790
- * The shared auth helper is named requireTenantContext; "resolveTenantMaybe" was rejected because it implied fallback behavior.
12868
+ * [at_compartment=1] The shared auth helper is named requireTenantContext; "resolveTenantMaybe" was rejected because it implied fallback behavior.
12791
12869
  </NAMING>
12792
12870
  </facts>
12793
12871
  <events>
@@ -12834,19 +12912,19 @@ OpLog; SnapshotCache; vector_clock; max_ops_before_compact=10000; crates/chorus-
12834
12912
  </compartment>
12835
12913
  <facts>
12836
12914
  <ARCHITECTURE>
12837
- * Chorus document state is defined by the op log in causal order (vector clocks); materialized snapshots are derived-on-read cache entries, not the source of truth.
12915
+ * [at_compartment=7] Chorus document state is defined by the op log in causal order (vector clocks); materialized snapshots are derived-on-read cache entries, not the source of truth.
12838
12916
  </ARCHITECTURE>
12839
12917
  <CONSTRAINTS>
12840
- * Chorus SnapshotCache invalidation must be synchronous on new op arrival; async invalidation causes stale reads visible to concurrent editing clients (observed: up to 200 ms staleness in async prototype).
12918
+ * [at_compartment=7] Chorus SnapshotCache invalidation must be synchronous on new op arrival; async invalidation causes stale reads visible to concurrent editing clients (observed: up to 200 ms staleness in async prototype).
12841
12919
  </CONSTRAINTS>
12842
12920
  <PROJECT_RULES>
12843
- * Never mutate a Chorus materialized snapshot directly; always append an op to the log and re-derive the snapshot.
12921
+ * [at_compartment=7] Never mutate a Chorus materialized snapshot directly; always append an op to the log and re-derive the snapshot.
12844
12922
  </PROJECT_RULES>
12845
12923
  <NAMING>
12846
- * Chorus core types: OpLog (crates/chorus-core/src/log.rs), SnapshotCache (crates/chorus-core/src/snapshot.rs).
12924
+ * [at_compartment=7] Chorus core types: OpLog (crates/chorus-core/src/log.rs), SnapshotCache (crates/chorus-core/src/snapshot.rs).
12847
12925
  </NAMING>
12848
12926
  <CONFIG_VALUES>
12849
- * Chorus compaction threshold: max_ops_before_compact=10000 per document.
12927
+ * [at_compartment=7] Chorus compaction threshold: max_ops_before_compact=10000 per document.
12850
12928
  </CONFIG_VALUES>
12851
12929
  </facts>
12852
12930
  <events>
@@ -12889,28 +12967,28 @@ The durable decision was to allow standby replicas to do read-heavy reconcile wo
12889
12967
  </compartment>
12890
12968
  <facts>
12891
12969
  <PROJECT_RULES>
12892
- * Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
12893
- * Any new cleanup step must be idempotent across repeated reconcile loops before it is attached to finalizer removal.
12970
+ * [at_compartment=1] Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
12971
+ * [at_compartment=1] Any new cleanup step must be idempotent across repeated reconcile loops before it is attached to finalizer removal.
12894
12972
  </PROJECT_RULES>
12895
12973
  <ARCHITECTURE>
12896
- * The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
12897
- * Status carries an observedPlan hash so downstream tools can detect desired-versus-applied drift without diffing child resources.
12974
+ * [at_compartment=1] The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
12975
+ * [at_compartment=1] Status carries an observedPlan hash so downstream tools can detect desired-versus-applied drift without diffing child resources.
12898
12976
  </ARCHITECTURE>
12899
12977
  <CONSTRAINTS>
12900
- * In a multi-control-plane cluster, standby reconciles can race with the active leader; unrestricted status writes make object health lie even when spec is unchanged.
12978
+ * [at_compartment=1] In a multi-control-plane cluster, standby reconciles can race with the active leader; unrestricted status writes make object health lie even when spec is unchanged.
12901
12979
  </CONSTRAINTS>
12902
12980
  <CONFIG_VALUES>
12903
- * Leader election lease name: workspacemesh-controller-lock.
12904
- * Drift hash status field: status.observedPlan.
12981
+ * [at_compartment=1] Leader election lease name: workspacemesh-controller-lock.
12982
+ * [at_compartment=1] Drift hash status field: status.observedPlan.
12905
12983
  </CONFIG_VALUES>
12906
12984
  <NAMING>
12907
- * The controller write gate wrapper is named LeaseGuard.
12985
+ * [at_compartment=1] The controller write gate wrapper is named LeaseGuard.
12908
12986
  </NAMING>
12909
12987
  </facts>`
12910
12988
  },
12911
12989
  {
12912
12990
  importance: 94,
12913
- block: '<compartment start="415" end="612" title="Tenant isolation: chose Postgres RLS over schema-per-tenant" episode_type="design" importance="94">\n<p1>\nWorked through the tenant isolation model for the new control plane. Three candidates on the table: (a) schema-per-tenant with `search_path` switching, (b) database-per-tenant, (c) shared schema with Postgres Row-Level Security policies keyed on `tenant_id`. Spent the morning sketching how each interacts with our migration tooling, connection pooling (pgbouncer in transaction mode), and the analytics replica.\n\nU: I keep getting pulled toward schema-per-tenant because it feels "more isolated" but I want to be talked out of it if RLS holds up\n\nSchema-per-tenant blows up under pgbouncer transaction-pooling — `SET search_path` is session-state and gets lost between transactions; the per-tenant search_path either has to be set on every transaction (expensive, race-prone) or we drop pgbouncer (kills our connection economy). Database-per-tenant solves isolation cleanly but our migration tooling (sqlx) doesn\'t have a clean fan-out story and we\'d need to build one. Also onboarding latency goes from ~50ms to ~30s because we\'d need to provision a DB.\n\nLanded on RLS. Every tenant-scoped table gets `tenant_id uuid not null`, an `ENABLE ROW LEVEL SECURITY` declaration, and a policy `USING (tenant_id = current_setting(\'app.current_tenant\')::uuid)`. The current tenant is set via `SET LOCAL app.current_tenant = \'...\'` at the start of every request transaction — `SET LOCAL` is transaction-scoped so it survives pgbouncer transaction mode cleanly. Wrote a middleware in `internal/db/tenant.go` that wraps every request in a transaction and sets the value.\n\nU: what about the analytics replica, does RLS work the same there\n\nYes — RLS policies replicate via logical replication; the analytics service connects with a separate role that also has RLS enforced. The escape hatch for cross-tenant analytics is a dedicated `analytics_admin` role with `BYPASSRLS`, used only by the scheduled aggregation job, never by interactive code paths.\n\nU: ok and write down that if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind\n\nDocumented. Added a lint rule in `tools/sqllint/` that flags `SET ROLE`, `BYPASSRLS`, and unqualified table access in `internal/handlers/`.\n</p1>\n<p2>\nTenant isolation decision: Postgres RLS keyed on `tenant_id`, set per-transaction via `SET LOCAL app.current_tenant`. Rejected schema-per-tenant (breaks pgbouncer transaction mode) and database-per-tenant (sqlx migration fan-out cost + 30s onboarding latency). Analytics uses a separate role with BYPASSRLS for the scheduled aggregator only. U: "if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind." Lint rule added in `tools/sqllint/`.\n</p2>\n<p3>\nChose RLS with `tenant_id` and `SET LOCAL app.current_tenant` per request. BYPASSRLS reserved for the scheduled analytics aggregator role only; app code is lint-enforced to never bypass.\n</p3>\n<p4>\nRLS on tenant_id; SET LOCAL app.current_tenant; BYPASSRLS = analytics_admin only\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* Tenant isolation is enforced at the database layer via Postgres RLS keyed on `tenant_id`, not via schema separation. Chosen because `SET LOCAL` is transaction-scoped and survives pgbouncer transaction-mode pooling, where session-scoped `search_path` switching does not.\n</ARCHITECTURE>\n<PROJECT_RULES>\n* Every tenant-scoped table must declare `tenant_id uuid not null` and `ENABLE ROW LEVEL SECURITY` with a policy referencing `current_setting(\'app.current_tenant\')`.\n* Application code must never call `SET ROLE` or use `BYPASSRLS` roles. `tools/sqllint/` enforces this in CI.\n</PROJECT_RULES>\n<CONSTRAINTS>\n* `SET search_path` is session-scoped and is silently lost between transactions when running behind pgbouncer in transaction pooling mode — making schema-per-tenant impractical for our deployment.\n</CONSTRAINTS>\n<CONFIG_VALUES>\n* Per-request tenant context is set via `SET LOCAL app.current_tenant = \'<uuid>\'` inside the request transaction opened by `internal/db/tenant.go`.\n</CONFIG_VALUES>\n<NAMING>\n* The privileged analytics role is `analytics_admin` (the only role with `BYPASSRLS`); used exclusively by the scheduled aggregation job.\n</NAMING>\n</facts>\n<events>\n<trajectory_correction at_compartment="3">\n <summary>Considered and rejected schema-per-tenant in favor of RLS after realizing it was incompatible with the existing pgbouncer setup.</summary>\n <before_strategy>Lean toward schema-per-tenant for "stronger" isolation feel.</before_strategy>\n <correction_source>self_review</correction_source>\n <correction_signal>Realized `SET search_path` is session-scoped and doesn\'t survive pgbouncer transaction-mode pooling.</correction_signal>\n <after_strategy>Adopt RLS with `SET LOCAL app.current_tenant` per transaction.</after_strategy>\n <evidence>"I keep getting pulled toward schema-per-tenant... I want to be talked out of it if RLS holds up"</evidence>\n</trajectory_correction>\n</events>\n<user_observations>\n* User asks to be argued out of intuitive-but-weakly-supported design preferences rather than rubber-stamped on them.\n* User pre-emptively codifies "rules to avoid future temptation" — translating decisions into lint rules and written prohibitions in the same session.\n</user_observations>'
12991
+ block: '<compartment start="415" end="612" title="Tenant isolation: chose Postgres RLS over schema-per-tenant" episode_type="design" importance="94">\n<p1>\nWorked through the tenant isolation model for the new control plane. Three candidates on the table: (a) schema-per-tenant with `search_path` switching, (b) database-per-tenant, (c) shared schema with Postgres Row-Level Security policies keyed on `tenant_id`. Spent the morning sketching how each interacts with our migration tooling, connection pooling (pgbouncer in transaction mode), and the analytics replica.\n\nU: I keep getting pulled toward schema-per-tenant because it feels "more isolated" but I want to be talked out of it if RLS holds up\n\nSchema-per-tenant blows up under pgbouncer transaction-pooling — `SET search_path` is session-state and gets lost between transactions; the per-tenant search_path either has to be set on every transaction (expensive, race-prone) or we drop pgbouncer (kills our connection economy). Database-per-tenant solves isolation cleanly but our migration tooling (sqlx) doesn\'t have a clean fan-out story and we\'d need to build one. Also onboarding latency goes from ~50ms to ~30s because we\'d need to provision a DB.\n\nLanded on RLS. Every tenant-scoped table gets `tenant_id uuid not null`, an `ENABLE ROW LEVEL SECURITY` declaration, and a policy `USING (tenant_id = current_setting(\'app.current_tenant\')::uuid)`. The current tenant is set via `SET LOCAL app.current_tenant = \'...\'` at the start of every request transaction — `SET LOCAL` is transaction-scoped so it survives pgbouncer transaction mode cleanly. Wrote a middleware in `internal/db/tenant.go` that wraps every request in a transaction and sets the value.\n\nU: what about the analytics replica, does RLS work the same there\n\nYes — RLS policies replicate via logical replication; the analytics service connects with a separate role that also has RLS enforced. The escape hatch for cross-tenant analytics is a dedicated `analytics_admin` role with `BYPASSRLS`, used only by the scheduled aggregation job, never by interactive code paths.\n\nU: ok and write down that if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind\n\nDocumented. Added a lint rule in `tools/sqllint/` that flags `SET ROLE`, `BYPASSRLS`, and unqualified table access in `internal/handlers/`.\n</p1>\n<p2>\nTenant isolation decision: Postgres RLS keyed on `tenant_id`, set per-transaction via `SET LOCAL app.current_tenant`. Rejected schema-per-tenant (breaks pgbouncer transaction mode) and database-per-tenant (sqlx migration fan-out cost + 30s onboarding latency). Analytics uses a separate role with BYPASSRLS for the scheduled aggregator only. U: "if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind." Lint rule added in `tools/sqllint/`.\n</p2>\n<p3>\nChose RLS with `tenant_id` and `SET LOCAL app.current_tenant` per request. BYPASSRLS reserved for the scheduled analytics aggregator role only; app code is lint-enforced to never bypass.\n</p3>\n<p4>\nRLS on tenant_id; SET LOCAL app.current_tenant; BYPASSRLS = analytics_admin only\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* [at_compartment=3] Tenant isolation is enforced at the database layer via Postgres RLS keyed on `tenant_id`, not via schema separation. Chosen because `SET LOCAL` is transaction-scoped and survives pgbouncer transaction-mode pooling, where session-scoped `search_path` switching does not.\n</ARCHITECTURE>\n<PROJECT_RULES>\n* [at_compartment=3] Every tenant-scoped table must declare `tenant_id uuid not null` and `ENABLE ROW LEVEL SECURITY` with a policy referencing `current_setting(\'app.current_tenant\')`.\n* [at_compartment=3] Application code must never call `SET ROLE` or use `BYPASSRLS` roles. `tools/sqllint/` enforces this in CI.\n</PROJECT_RULES>\n<CONSTRAINTS>\n* [at_compartment=3] `SET search_path` is session-scoped and is silently lost between transactions when running behind pgbouncer in transaction pooling mode — making schema-per-tenant impractical for our deployment.\n</CONSTRAINTS>\n<CONFIG_VALUES>\n* [at_compartment=3] Per-request tenant context is set via `SET LOCAL app.current_tenant = \'<uuid>\'` inside the request transaction opened by `internal/db/tenant.go`.\n</CONFIG_VALUES>\n<NAMING>\n* [at_compartment=3] The privileged analytics role is `analytics_admin` (the only role with `BYPASSRLS`); used exclusively by the scheduled aggregation job.\n</NAMING>\n</facts>\n<events>\n<trajectory_correction at_compartment="3">\n <summary>Considered and rejected schema-per-tenant in favor of RLS after realizing it was incompatible with the existing pgbouncer setup.</summary>\n <before_strategy>Lean toward schema-per-tenant for "stronger" isolation feel.</before_strategy>\n <correction_source>self_review</correction_source>\n <correction_signal>Realized `SET search_path` is session-scoped and doesn\'t survive pgbouncer transaction-mode pooling.</correction_signal>\n <after_strategy>Adopt RLS with `SET LOCAL app.current_tenant` per transaction.</after_strategy>\n <evidence>"I keep getting pulled toward schema-per-tenant... I want to be talked out of it if RLS holds up"</evidence>\n</trajectory_correction>\n</events>\n<user_observations>\n* User asks to be argued out of intuitive-but-weakly-supported design preferences rather than rubber-stamped on them.\n* User pre-emptively codifies "rules to avoid future temptation" — translating decisions into lint rules and written prohibitions in the same session.\n</user_observations>'
12914
12992
  },
12915
12993
  {
12916
12994
  importance: 92,
@@ -12938,22 +13016,22 @@ Tenant authorization now flows from membership state rather than browser-selecte
12938
13016
  </compartment>
12939
13017
  <facts>
12940
13018
  <PROJECT_RULES>
12941
- * New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
12942
- * Any endpoint bypassing TenantGuard needs an explicit integration test covering membership revocation.
13019
+ * [at_compartment=1] New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
13020
+ * [at_compartment=1] Any endpoint bypassing TenantGuard needs an explicit integration test covering membership revocation.
12943
13021
  </PROJECT_RULES>
12944
13022
  <ARCHITECTURE>
12945
- * Session tokens carry user_id and active_membership_id; tenant and role are rehydrated server-side so revocation and membership changes apply without waiting for session expiry.
12946
- * Billing, files, and audit services consume a middleware-built TenantContext instead of parsing auth material independently.
13023
+ * [at_compartment=1] Session tokens carry user_id and active_membership_id; tenant and role are rehydrated server-side so revocation and membership changes apply without waiting for session expiry.
13024
+ * [at_compartment=1] Billing, files, and audit services consume a middleware-built TenantContext instead of parsing auth material independently.
12947
13025
  </ARCHITECTURE>
12948
13026
  <CONSTRAINTS>
12949
- * Browser-supplied orgId values are unsafe for tenant authorization because users can belong to multiple tenants and stale tabs can replay old selections.
13027
+ * [at_compartment=1] Browser-supplied orgId values are unsafe for tenant authorization because users can belong to multiple tenants and stale tabs can replay old selections.
12950
13028
  </CONSTRAINTS>
12951
13029
  <CONFIG_VALUES>
12952
- * Internal tenant hop header: x-ledgerleaf-tenant-id.
12953
- * Auth claim name: active_membership_id.
13030
+ * [at_compartment=1] Internal tenant hop header: x-ledgerleaf-tenant-id.
13031
+ * [at_compartment=1] Auth claim name: active_membership_id.
12954
13032
  </CONFIG_VALUES>
12955
13033
  <NAMING>
12956
- * The auth boundary middleware is named TenantGuard and the resolver behind it is TenantContextResolver.
13034
+ * [at_compartment=1] The auth boundary middleware is named TenantGuard and the resolver behind it is TenantContextResolver.
12957
13035
  </NAMING>
12958
13036
  </facts>
12959
13037
  <user_observations>
@@ -12988,16 +13066,16 @@ internal/leaderelection/release.go shim removed; PreStop hook; lease 30s / retry
12988
13066
  </compartment>
12989
13067
  <facts>
12990
13068
  <PROJECT_RULES>
12991
- * Do not wrap or shim controller-runtime leader-election internals — extend via its config surface only. Package \`internal/leaderelection/\` is CODEOWNERS-locked for this reason.
13069
+ * [at_compartment=1] Do not wrap or shim controller-runtime leader-election internals — extend via its config surface only. Package \`internal/leaderelection/\` is CODEOWNERS-locked for this reason.
12992
13070
  </PROJECT_RULES>
12993
13071
  <ARCHITECTURE>
12994
- * Leader-election release path must run unobstructed during SIGTERM so the kube-apiserver can transfer the lease before the pod's Node disappears.
13072
+ * [at_compartment=1] Leader-election release path must run unobstructed during SIGTERM so the kube-apiserver can transfer the lease before the pod's Node disappears.
12995
13073
  </ARCHITECTURE>
12996
13074
  <CONSTRAINTS>
12997
- * Suppressing errors during graceful shutdown can mask actual API calls in flight; the suppression boundary must be drawn around logging, not around the network call itself.
13075
+ * [at_compartment=1] Suppressing errors during graceful shutdown can mask actual API calls in flight; the suppression boundary must be drawn around logging, not around the network call itself.
12998
13076
  </CONSTRAINTS>
12999
13077
  <CONFIG_VALUES>
13000
- * Operator leader-election: lease duration 30s, retry period 5s, PreStop hook 5s.
13078
+ * [at_compartment=1] Operator leader-election: lease duration 30s, retry period 5s, PreStop hook 5s.
13001
13079
  </CONFIG_VALUES>
13002
13080
  </facts>
13003
13081
  <events>
@@ -13039,19 +13117,19 @@ run_id; pipeline_run; IntegrityError; idempotent retry; {pipeline_name}_{YYYYMMD
13039
13117
  </compartment>
13040
13118
  <facts>
13041
13119
  <ARCHITECTURE>
13042
- * All Luminary ETL pipeline loads are idempotent via run_id deduplication; any run can be safely retried without risk of double-counting or partial loads.
13120
+ * [at_compartment=1] All Luminary ETL pipeline loads are idempotent via run_id deduplication; any run can be safely retried without risk of double-counting or partial loads.
13043
13121
  </ARCHITECTURE>
13044
13122
  <PROJECT_RULES>
13045
- * Every Luminary pipeline run must generate and log a run_id to the pipeline_run table before any target writes begin.
13123
+ * [at_compartment=1] Every Luminary pipeline run must generate and log a run_id to the pipeline_run table before any target writes begin.
13046
13124
  </PROJECT_RULES>
13047
13125
  <CONSTRAINTS>
13048
- * Luminary run_id uniqueness is enforced by a DB unique constraint on (target_table, run_id); a duplicate run_id raises IntegrityError, not a silent skip — retry logic must catch IntegrityError explicitly.
13126
+ * [at_compartment=1] Luminary run_id uniqueness is enforced by a DB unique constraint on (target_table, run_id); a duplicate run_id raises IntegrityError, not a silent skip — retry logic must catch IntegrityError explicitly.
13049
13127
  </CONSTRAINTS>
13050
13128
  <NAMING>
13051
- * Luminary idempotency primitives: run_id (string dedup key), pipeline_run (dedup table), orchestrator/runner.py (retry logic with IntegrityError handling).
13129
+ * [at_compartment=1] Luminary idempotency primitives: run_id (string dedup key), pipeline_run (dedup table), orchestrator/runner.py (retry logic with IntegrityError handling).
13052
13130
  </NAMING>
13053
13131
  <CONFIG_VALUES>
13054
- * Luminary run_id format: {pipeline_name}_{YYYYMMDD}_{uuid4_prefix8} (e.g., orders_daily_20250523_a3f92c11).
13132
+ * [at_compartment=1] Luminary run_id format: {pipeline_name}_{YYYYMMDD}_{uuid4_prefix8} (e.g., orders_daily_20250523_a3f92c11).
13055
13133
  </CONFIG_VALUES>
13056
13134
  </facts>`
13057
13135
  },
@@ -13075,20 +13153,20 @@ Harborlight sharding is namespace-scoped: one operator binary can run cluster-wi
13075
13153
  </compartment>
13076
13154
  <facts>
13077
13155
  <PROJECT_RULES>
13078
- * Harborlight CRD changes must regenerate manifests, deepcopy code, RBAC, and envtest fixtures before merge.
13156
+ * [at_compartment=5] Harborlight CRD changes must regenerate manifests, deepcopy code, RBAC, and envtest fixtures before merge.
13079
13157
  </PROJECT_RULES>
13080
13158
  <ARCHITECTURE>
13081
- * Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
13082
- * QueueShard.status.observedLeaseUID records reconciler-observed lease identity; QueueShard.spec remains user intent only.
13159
+ * [at_compartment=5] Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
13160
+ * [at_compartment=5] QueueShard.status.observedLeaseUID records reconciler-observed lease identity; QueueShard.spec remains user intent only.
13083
13161
  </ARCHITECTURE>
13084
13162
  <CONSTRAINTS>
13085
- * Kubernetes Lease renewTime is unreliable for Harborlight ownership decisions under node clock skew.
13163
+ * [at_compartment=5] Kubernetes Lease renewTime is unreliable for Harborlight ownership decisions under node clock skew.
13086
13164
  </CONSTRAINTS>
13087
13165
  <CONFIG_VALUES>
13088
- * Harborlight QueueShard lease timing is duration 18s, renew deadline 12s, retry period 3s.
13166
+ * [at_compartment=5] Harborlight QueueShard lease timing is duration 18s, renew deadline 12s, retry period 3s.
13089
13167
  </CONFIG_VALUES>
13090
13168
  <NAMING>
13091
- * The Harborlight CRD kind is QueueShard; "WorkPartition" was rejected as too generic.
13169
+ * [at_compartment=5] The Harborlight CRD kind is QueueShard; "WorkPartition" was rejected as too generic.
13092
13170
  </NAMING>
13093
13171
  </facts>
13094
13172
  <events>
@@ -13123,13 +13201,13 @@ CAN RX no longer allocates or sends BLE notifications inside the ISR; frames are
13123
13201
  </compartment>
13124
13202
  <facts>
13125
13203
  <PROJECT_RULES>
13126
- * Pawprint firmware ISR paths must not allocate; enqueue to can_rx_ring and wake deferred work instead.
13204
+ * [at_compartment=3] Pawprint firmware ISR paths must not allocate; enqueue to can_rx_ring and wake deferred work instead.
13127
13205
  </PROJECT_RULES>
13128
13206
  <CONSTRAINTS>
13129
- * nRF52840 BLE notification from IRQ context can trigger supervisor reset when SoftDevice holds the radio lock.
13207
+ * [at_compartment=3] nRF52840 BLE notification from IRQ context can trigger supervisor reset when SoftDevice holds the radio lock.
13130
13208
  </CONSTRAINTS>
13131
13209
  <CONFIG_VALUES>
13132
- * Pawprint can_rx_ring depth is 32 frames, with overflow counted by can_rx_ring_overrun.
13210
+ * [at_compartment=3] Pawprint can_rx_ring depth is 32 frames, with overflow counted by can_rx_ring_overrun.
13133
13211
  </CONFIG_VALUES>
13134
13212
  </facts>
13135
13213
  <events>
@@ -13166,10 +13244,10 @@ unscale_ → clip_grad_norm_ → step
13166
13244
  </compartment>
13167
13245
  <facts>
13168
13246
  <CONSTRAINTS>
13169
- * \`torch.nn.utils.clip_grad_norm_\` called on still-scaled fp16 gradients overflows silently, returns inf, drives the clip ratio to 0, and zeros parameters on the next optimizer step.
13247
+ * [at_compartment=2] \`torch.nn.utils.clip_grad_norm_\` called on still-scaled fp16 gradients overflows silently, returns inf, drives the clip ratio to 0, and zeros parameters on the next optimizer step.
13170
13248
  </CONSTRAINTS>
13171
13249
  <ARCHITECTURE>
13172
- * In mixed-precision training, gradient clipping is computed against TRUE gradient magnitudes — \`scaler.unscale_(optimizer)\` must run before any norm-based clipping.
13250
+ * [at_compartment=2] In mixed-precision training, gradient clipping is computed against TRUE gradient magnitudes — \`scaler.unscale_(optimizer)\` must run before any norm-based clipping.
13173
13251
  </ARCHITECTURE>
13174
13252
  </facts>
13175
13253
  <events>
@@ -13208,13 +13286,13 @@ LoomDoc wraps Y.Doc; HLC (physical_ms, logical, node_id); skew cap 300s
13208
13286
  </compartment>
13209
13287
  <facts>
13210
13288
  <ARCHITECTURE>
13211
- * Document conflict resolution uses a two-layer model: Yjs handles concurrent per-character positioning, while a hybrid logical clock on top orders structural operations across regions. The split exists because Yjs's intrinsic ordering doesn't carry cross-region semantics for whole-node operations.
13289
+ * [at_compartment=1] Document conflict resolution uses a two-layer model: Yjs handles concurrent per-character positioning, while a hybrid logical clock on top orders structural operations across regions. The split exists because Yjs's intrinsic ordering doesn't carry cross-region semantics for whole-node operations.
13212
13290
  </ARCHITECTURE>
13213
13291
  <CONSTRAINTS>
13214
- * Incoming HLC values whose physical component is more than 300 seconds ahead of local are rejected — clients with worse skew can't participate in collaboration until they correct.
13292
+ * [at_compartment=1] Incoming HLC values whose physical component is more than 300 seconds ahead of local are rejected — clients with worse skew can't participate in collaboration until they correct.
13215
13293
  </CONSTRAINTS>
13216
13294
  <NAMING>
13217
- * CRDT library: Yjs (rejected Automerge for merge-cost scaling on ~50k-char documents). Our wrapper type is \`LoomDoc\`.
13295
+ * [at_compartment=1] CRDT library: Yjs (rejected Automerge for merge-cost scaling on ~50k-char documents). Our wrapper type is \`LoomDoc\`.
13218
13296
  </NAMING>
13219
13297
  </facts>`
13220
13298
  },
@@ -13238,21 +13316,21 @@ Billetto made proration credits auditable by storing them in its own ledger tabl
13238
13316
  </compartment>
13239
13317
  <facts>
13240
13318
  <PROJECT_RULES>
13241
- * Billetto billing migrations must include a rollback dry-run against test/fixtures/billing-ledger/.
13319
+ * [at_compartment=1] Billetto billing migrations must include a rollback dry-run against test/fixtures/billing-ledger/.
13242
13320
  </PROJECT_RULES>
13243
13321
  <ARCHITECTURE>
13244
- * Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
13245
- * Billetto proration calculation is idempotent around subscription_version and reuses existing ledger entries on retry.
13322
+ * [at_compartment=1] Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
13323
+ * [at_compartment=1] Billetto proration calculation is idempotent around subscription_version and reuses existing ledger entries on retry.
13246
13324
  </ARCHITECTURE>
13247
13325
  <CONSTRAINTS>
13248
- * Stripe invoice metadata is not a durable Billetto credit ledger because dashboard edits can mutate it outside the app.
13326
+ * [at_compartment=1] Stripe invoice metadata is not a durable Billetto credit ledger because dashboard edits can mutate it outside the app.
13249
13327
  </CONSTRAINTS>
13250
13328
  <CONFIG_VALUES>
13251
- * Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
13252
- * Billetto Stripe idempotency key format for proration is proration:{account_id}:{subscription_version}:{invoice_id}.
13329
+ * [at_compartment=1] Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
13330
+ * [at_compartment=1] Billetto Stripe idempotency key format for proration is proration:{account_id}:{subscription_version}:{invoice_id}.
13253
13331
  </CONFIG_VALUES>
13254
13332
  <NAMING>
13255
- * The Billetto credit ledger table is named account_credit_entries; "negative_invoice_lines" was rejected.
13333
+ * [at_compartment=1] The Billetto credit ledger table is named account_credit_entries; "negative_invoice_lines" was rejected.
13256
13334
  </NAMING>
13257
13335
  </facts>`
13258
13336
  },
@@ -13274,10 +13352,10 @@ Nereid contrastive training stabilized after restoring per-worker augmentation s
13274
13352
  </compartment>
13275
13353
  <facts>
13276
13354
  <CONSTRAINTS>
13277
- * Nereid's contrastive trainer can diverge if augmentation_seed is shared across dataloader workers.
13355
+ * [at_compartment=2] Nereid's contrastive trainer can diverge if augmentation_seed is shared across dataloader workers.
13278
13356
  </CONSTRAINTS>
13279
13357
  <CONFIG_VALUES>
13280
- * Nereid worker augmentation seed formula is base_seed + worker_id + epoch * 1009.
13358
+ * [at_compartment=2] Nereid worker augmentation seed formula is base_seed + worker_id + epoch * 1009.
13281
13359
  </CONFIG_VALUES>
13282
13360
  </facts>
13283
13361
  <events>
@@ -13316,19 +13394,19 @@ billing.stripe_event_idempotency; key = event.id; TTL 90d
13316
13394
  </compartment>
13317
13395
  <facts>
13318
13396
  <PROJECT_RULES>
13319
- * Idempotency for any external webhook source must key on the provider's event identifier (e.g. Stripe \`event.id\`), never on delivery-level signatures or timestamps. Stored response body+status is returned on duplicate.
13397
+ * [at_compartment=8] Idempotency for any external webhook source must key on the provider's event identifier (e.g. Stripe \`event.id\`), never on delivery-level signatures or timestamps. Stored response body+status is returned on duplicate.
13320
13398
  </PROJECT_RULES>
13321
13399
  <CONSTRAINTS>
13322
- * Stripe webhook signatures and timestamps are regenerated per delivery attempt — they CANNOT be used as idempotency keys because retries of the same event produce different signatures.
13400
+ * [at_compartment=8] Stripe webhook signatures and timestamps are regenerated per delivery attempt — they CANNOT be used as idempotency keys because retries of the same event produce different signatures.
13323
13401
  </CONSTRAINTS>
13324
13402
  <ARCHITECTURE>
13325
- * Webhook idempotency uses a write-through pattern: the handler's full response is captured inside the same transaction that records the event_id, so replays return byte-identical responses without re-executing side effects.
13403
+ * [at_compartment=8] Webhook idempotency uses a write-through pattern: the handler's full response is captured inside the same transaction that records the event_id, so replays return byte-identical responses without re-executing side effects.
13326
13404
  </ARCHITECTURE>
13327
13405
  <CONFIG_VALUES>
13328
- * \`billing.stripe_event_idempotency\` table; primary key on \`event_id\`; row TTL 90 days; wrapper in \`internal/billing/webhooks/idempotent.go\`.
13406
+ * [at_compartment=8] \`billing.stripe_event_idempotency\` table; primary key on \`event_id\`; row TTL 90 days; wrapper in \`internal/billing/webhooks/idempotent.go\`.
13329
13407
  </CONFIG_VALUES>
13330
13408
  <NAMING>
13331
- * Webhook idempotency table is \`billing.stripe_event_idempotency\`. Future provider-specific tables follow the pattern \`<provider>_event_idempotency\`.
13409
+ * [at_compartment=8] Webhook idempotency table is \`billing.stripe_event_idempotency\`. Future provider-specific tables follow the pattern \`<provider>_event_idempotency\`.
13332
13410
  </NAMING>
13333
13411
  </facts>
13334
13412
  <events>
@@ -13371,13 +13449,13 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
13371
13449
  </compartment>
13372
13450
  <facts>
13373
13451
  <CONSTRAINTS>
13374
- * Tethys JWT access tokens carry tenant_roles at issue time; role changes do not invalidate existing tokens — a revoked role remains usable until token expiry (up to access_token_ttl=900 s for clients that don't refresh).
13452
+ * [at_compartment=15] Tethys JWT access tokens carry tenant_roles at issue time; role changes do not invalidate existing tokens — a revoked role remains usable until token expiry (up to access_token_ttl=900 s for clients that don't refresh).
13375
13453
  </CONSTRAINTS>
13376
13454
  <PROJECT_RULES>
13377
- * Tethys token refresh must always re-fetch tenant_roles from the DB; never carry role claims forward from the incoming token.
13455
+ * [at_compartment=15] Tethys token refresh must always re-fetch tenant_roles from the DB; never carry role claims forward from the incoming token.
13378
13456
  </PROJECT_RULES>
13379
13457
  <CONFIG_VALUES>
13380
- * Tethys token TTLs: access_token_ttl=900 s, refresh_token_ttl=86400 s.
13458
+ * [at_compartment=15] Tethys token TTLs: access_token_ttl=900 s, refresh_token_ttl=86400 s.
13381
13459
  </CONFIG_VALUES>
13382
13460
  </facts>
13383
13461
  <events>
@@ -13397,7 +13475,7 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
13397
13475
  },
13398
13476
  {
13399
13477
  importance: 74,
13400
- block: '<compartment start="760" end="848" title="HLS segment numbering migration from 5-digit to 9-digit indices" episode_type="refactor,infra" importance="74">\n<p1>\nThe transcoder\'s HLS output was using `segment_%05d.ts` — five digits, max 99,999 segments. For a 24/7 live channel at 6s segments that\'s ~7 days before wraparound, and we just hit a wraparound on `channel-news-east` Friday night that broke the playlist sliding window for ~40 minutes before paging on-call noticed.\n\nMigrated to `segment_%09d.ts` everywhere. Touched `transcoder/hls/segmenter.go` for the writer, `transcoder/hls/playlist.go` for the manifest builder, and the CDN purge job\'s glob in `ops/purge-stale-segments.sh`. The CDN cache config didn\'t need changes — the glob was already `segment_*.ts`. Backfill is a no-op because old playlists naturally roll off the sliding window within an hour.\n\nCodified in the writer: any future segment-index format change must keep monotonic ordering AND must always be lexicographically sortable. The 5-digit choice was actually fine lexicographically until wraparound — the failure mode was running out of namespace, not ordering.\n</p1>\n<p2>\nHLS segment naming widened from `%05d` to `%09d` after a live-channel wraparound broke playlist sliding-window on `channel-news-east`. Changes in `transcoder/hls/segmenter.go` and `transcoder/hls/playlist.go`. Naming rule documented: segment indices must always be zero-padded to remain lexicographically sortable, with enough digits for a year of continuous segments at our minimum segment duration.\n</p2>\n<p3>\nHLS segment indices widened after a live-channel index wraparound.\n</p3>\n<p4>\nsegment_%09d.ts; transcoder/hls/\n</p4>\n</compartment>\n<facts>\n<CONFIG_VALUES>\n* HLS segment filename format: `segment_%09d.ts` (writer in `transcoder/hls/segmenter.go`, manifest builder in `transcoder/hls/playlist.go`).\n</CONFIG_VALUES>\n<PROJECT_RULES>\n* HLS segment indices must be zero-padded to a width sufficient for at least one year of continuous output at the minimum supported segment duration. Lexicographic sortability is required for CDN purge globbing.\n</PROJECT_RULES>\n</facts>\n<events>\n<causal_incident at_compartment="5">\n <summary>Live channel playback window broke for ~40 minutes after HLS segment index wrapped from 99,999 back to 0.</summary>\n <affected_surface>edit_pipeline</affected_surface>\n <symptom>Playlist sliding window on `channel-news-east` stopped advancing; viewers saw frozen live feed for ~40 minutes.</symptom>\n <cause_summary>5-digit segment index namespace exhausted on a continuously-running channel; new segments lexicographically sorted before old ones, breaking the manifest builder\'s ordering assumption.</cause_summary>\n <disposition>fixed</disposition>\n <evidence>On-call paged on viewer drop in channel-news-east; logs showed segment files alternating between `segment_99998.ts` and `segment_00000.ts` in the same directory.</evidence>\n <fix_summary>Widened format to `segment_%09d.ts` across writer, manifest builder, and CDN purge glob.</fix_summary>\n</causal_incident>\n</events>'
13478
+ block: '<compartment start="760" end="848" title="HLS segment numbering migration from 5-digit to 9-digit indices" episode_type="refactor,infra" importance="74">\n<p1>\nThe transcoder\'s HLS output was using `segment_%05d.ts` — five digits, max 99,999 segments. For a 24/7 live channel at 6s segments that\'s ~7 days before wraparound, and we just hit a wraparound on `channel-news-east` Friday night that broke the playlist sliding window for ~40 minutes before paging on-call noticed.\n\nMigrated to `segment_%09d.ts` everywhere. Touched `transcoder/hls/segmenter.go` for the writer, `transcoder/hls/playlist.go` for the manifest builder, and the CDN purge job\'s glob in `ops/purge-stale-segments.sh`. The CDN cache config didn\'t need changes — the glob was already `segment_*.ts`. Backfill is a no-op because old playlists naturally roll off the sliding window within an hour.\n\nCodified in the writer: any future segment-index format change must keep monotonic ordering AND must always be lexicographically sortable. The 5-digit choice was actually fine lexicographically until wraparound — the failure mode was running out of namespace, not ordering.\n</p1>\n<p2>\nHLS segment naming widened from `%05d` to `%09d` after a live-channel wraparound broke playlist sliding-window on `channel-news-east`. Changes in `transcoder/hls/segmenter.go` and `transcoder/hls/playlist.go`. Naming rule documented: segment indices must always be zero-padded to remain lexicographically sortable, with enough digits for a year of continuous segments at our minimum segment duration.\n</p2>\n<p3>\nHLS segment indices widened after a live-channel index wraparound.\n</p3>\n<p4>\nsegment_%09d.ts; transcoder/hls/\n</p4>\n</compartment>\n<facts>\n<CONFIG_VALUES>\n* [at_compartment=5] HLS segment filename format: `segment_%09d.ts` (writer in `transcoder/hls/segmenter.go`, manifest builder in `transcoder/hls/playlist.go`).\n</CONFIG_VALUES>\n<PROJECT_RULES>\n* [at_compartment=5] HLS segment indices must be zero-padded to a width sufficient for at least one year of continuous output at the minimum supported segment duration. Lexicographic sortability is required for CDN purge globbing.\n</PROJECT_RULES>\n</facts>\n<events>\n<causal_incident at_compartment="5">\n <summary>Live channel playback window broke for ~40 minutes after HLS segment index wrapped from 99,999 back to 0.</summary>\n <affected_surface>edit_pipeline</affected_surface>\n <symptom>Playlist sliding window on `channel-news-east` stopped advancing; viewers saw frozen live feed for ~40 minutes.</symptom>\n <cause_summary>5-digit segment index namespace exhausted on a continuously-running channel; new segments lexicographically sorted before old ones, breaking the manifest builder\'s ordering assumption.</cause_summary>\n <disposition>fixed</disposition>\n <evidence>On-call paged on viewer drop in channel-news-east; logs showed segment files alternating between `segment_99998.ts` and `segment_00000.ts` in the same directory.</evidence>\n <fix_summary>Widened format to `segment_%09d.ts` across writer, manifest builder, and CDN purge glob.</fix_summary>\n</causal_incident>\n</events>'
13401
13479
  },
13402
13480
  {
13403
13481
  importance: 74,
@@ -13417,16 +13495,16 @@ Partition membership changes now fence planner statistics through partition_epoc
13417
13495
  </compartment>
13418
13496
  <facts>
13419
13497
  <PROJECT_RULES>
13420
- * Any catalog change affecting partition membership needs a planner regression under tests/sql/partition_pruning_regress.slt.
13498
+ * [at_compartment=13] Any catalog change affecting partition membership needs a planner regression under tests/sql/partition_pruning_regress.slt.
13421
13499
  </PROJECT_RULES>
13422
13500
  <ARCHITECTURE>
13423
- * Planner stats cache keys include partition_epoch so partition topology changes invalidate selectivity estimates without clearing the whole cache.
13501
+ * [at_compartment=13] Planner stats cache keys include partition_epoch so partition topology changes invalidate selectivity estimates without clearing the whole cache.
13424
13502
  </ARCHITECTURE>
13425
13503
  <CONSTRAINTS>
13426
- * Child partition attach and detach can make NDV and selectivity data unsafe even when the parent table schema is unchanged.
13504
+ * [at_compartment=13] Child partition attach and detach can make NDV and selectivity data unsafe even when the parent table schema is unchanged.
13427
13505
  </CONSTRAINTS>
13428
13506
  <CONFIG_VALUES>
13429
- * New planner cache key field: partition_epoch.
13507
+ * [at_compartment=13] New planner cache key field: partition_epoch.
13430
13508
  </CONFIG_VALUES>
13431
13509
  </facts>
13432
13510
  <events>
@@ -13461,13 +13539,13 @@ CollabPad CRDT ordering now follows document clocks rather than server receive t
13461
13539
  </compartment>
13462
13540
  <facts>
13463
13541
  <ARCHITECTURE>
13464
- * CollabPad orders CRDT operations by (lamport, site_id); server receivedAt is telemetry only.
13542
+ * [at_compartment=10] CollabPad orders CRDT operations by (lamport, site_id); server receivedAt is telemetry only.
13465
13543
  </ARCHITECTURE>
13466
13544
  <CONSTRAINTS>
13467
- * WebRTC reconnect can deliver buffered CollabPad ops older than a websocket ack, so receivedAt cannot be used as causal order.
13545
+ * [at_compartment=10] WebRTC reconnect can deliver buffered CollabPad ops older than a websocket ack, so receivedAt cannot be used as causal order.
13468
13546
  </CONSTRAINTS>
13469
13547
  <NAMING>
13470
- * CollabPad's editing-site field is named site_id rather than clientId because multiple browser contexts can share one account.
13548
+ * [at_compartment=10] CollabPad's editing-site field is named site_id rather than clientId because multiple browser contexts can share one account.
13471
13549
  </NAMING>
13472
13550
  </facts>
13473
13551
  <events>
@@ -13504,10 +13582,10 @@ bond_table partition 0x7E000–0x7FFFF; pm_static.yml
13504
13582
  </compartment>
13505
13583
  <facts>
13506
13584
  <CONSTRAINTS>
13507
- * nRF SDK 2.6.0 bond manager (with \`NRF_FSTORAGE_API_FDS\`) writes its bond table to the top 8KB of flash regardless of the partition manifest — the SDK does not consult \`pm_static.yml\`.
13585
+ * [at_compartment=6] nRF SDK 2.6.0 bond manager (with \`NRF_FSTORAGE_API_FDS\`) writes its bond table to the top 8KB of flash regardless of the partition manifest — the SDK does not consult \`pm_static.yml\`.
13508
13586
  </CONSTRAINTS>
13509
13587
  <CONFIG_VALUES>
13510
- * \`bond_table\` partition reserved at 0x7E000–0x7FFFF in \`pm_static.yml\`. OTA pre-swap erase range narrowed to 0x70000–0x7DFFF.
13588
+ * [at_compartment=6] \`bond_table\` partition reserved at 0x7E000–0x7FFFF in \`pm_static.yml\`. OTA pre-swap erase range narrowed to 0x70000–0x7DFFF.
13511
13589
  </CONFIG_VALUES>
13512
13590
  </facts>
13513
13591
  <events>
@@ -13544,10 +13622,10 @@ leader election; Lease resource; VESPER_LEASE_DURATION_S; VESPER_RENEW_INTERVAL_
13544
13622
  </compartment>
13545
13623
  <facts>
13546
13624
  <ARCHITECTURE>
13547
- * Vesper controller uses Kubernetes Lease-based leader election; non-holder replicas skip the reconcile loop entirely and only run health probes.
13625
+ * [at_compartment=1] Vesper controller uses Kubernetes Lease-based leader election; non-holder replicas skip the reconcile loop entirely and only run health probes.
13548
13626
  </ARCHITECTURE>
13549
13627
  <CONFIG_VALUES>
13550
- * Vesper leader election defaults: VESPER_LEASE_DURATION_S=30, VESPER_RENEW_INTERVAL_S=10, VESPER_ACQUIRE_DEADLINE_S=8 (all overridable via env).
13628
+ * [at_compartment=1] Vesper leader election defaults: VESPER_LEASE_DURATION_S=30, VESPER_RENEW_INTERVAL_S=10, VESPER_ACQUIRE_DEADLINE_S=8 (all overridable via env).
13551
13629
  </CONFIG_VALUES>
13552
13630
  </facts>`
13553
13631
  },
@@ -13579,13 +13657,13 @@ onPreInstall; onPostInstall; onRemove; schema_version; dependency-declaration or
13579
13657
  </compartment>
13580
13658
  <facts>
13581
13659
  <ARCHITECTURE>
13582
- * boltpkg plugin hooks execute in plugin dependency-declaration order, not registration order; deterministic and matches user expectations about dependency sequencing.
13660
+ * [at_compartment=17] boltpkg plugin hooks execute in plugin dependency-declaration order, not registration order; deterministic and matches user expectations about dependency sequencing.
13583
13661
  </ARCHITECTURE>
13584
13662
  <NAMING>
13585
- * boltpkg plugin lifecycle hooks: onPreInstall, onPostInstall, onRemove (src/plugin/types.ts).
13663
+ * [at_compartment=17] boltpkg plugin lifecycle hooks: onPreInstall, onPostInstall, onRemove (src/plugin/types.ts).
13586
13664
  </NAMING>
13587
13665
  <PROJECT_RULES>
13588
- * boltpkg plugin manifests must include schema_version; the loader rejects manifests with unrecognized schema versions to prevent silently running mismatched plugins.
13666
+ * [at_compartment=17] boltpkg plugin manifests must include schema_version; the loader rejects manifests with unrecognized schema versions to prevent silently running mismatched plugins.
13589
13667
  </PROJECT_RULES>
13590
13668
  </facts>
13591
13669
  <events>
@@ -13617,16 +13695,16 @@ Subscription MRR history moved into a daily fact table instead of being reconstr
13617
13695
  </compartment>
13618
13696
  <facts>
13619
13697
  <PROJECT_RULES>
13620
- * Northstar DW subscription backfills should use the backfill_subscription_day dbt macro instead of ad hoc DELETE and INSERT queries.
13698
+ * [at_compartment=1] Northstar DW subscription backfills should use the backfill_subscription_day dbt macro instead of ad hoc DELETE and INSERT queries.
13621
13699
  </PROJECT_RULES>
13622
13700
  <ARCHITECTURE>
13623
- * Northstar DW answers historical MRR from fct_subscription_day daily snapshots rather than replaying raw billing events at query time.
13701
+ * [at_compartment=1] Northstar DW answers historical MRR from fct_subscription_day daily snapshots rather than replaying raw billing events at query time.
13624
13702
  </ARCHITECTURE>
13625
13703
  <CONFIG_VALUES>
13626
- * fct_subscription_day is materialized incrementally with unique key account_id, subscription_id, and date_day.
13704
+ * [at_compartment=1] fct_subscription_day is materialized incrementally with unique key account_id, subscription_id, and date_day.
13627
13705
  </CONFIG_VALUES>
13628
13706
  <NAMING>
13629
- * The subscription daily snapshot model is named fct_subscription_day.
13707
+ * [at_compartment=1] The subscription daily snapshot model is named fct_subscription_day.
13630
13708
  </NAMING>
13631
13709
  </facts>`
13632
13710
  },
@@ -13654,10 +13732,10 @@ bucket width 50; K=24; asymmetric expansion down-only first 60s
13654
13732
  </compartment>
13655
13733
  <facts>
13656
13734
  <CONFIG_VALUES>
13657
- * Matchmaking: bucket width 50 MMR, K-factor 24, native-bucket wait 60s, down-only expansion phase 60s, symmetric expansion after 120s.
13735
+ * [at_compartment=1] Matchmaking: bucket width 50 MMR, K-factor 24, native-bucket wait 60s, down-only expansion phase 60s, symmetric expansion after 120s.
13658
13736
  </CONFIG_VALUES>
13659
13737
  <ARCHITECTURE>
13660
- * Matchmaking expands the candidate bucket asymmetrically (down-only first) for high-rank players because the skill distribution is right-truncated — there are no buckets above them to expand into, and expanding symmetrically produces visible mismatches.
13738
+ * [at_compartment=1] Matchmaking expands the candidate bucket asymmetrically (down-only first) for high-rank players because the skill distribution is right-truncated — there are no buckets above them to expand into, and expanding symmetrically produces visible mismatches.
13661
13739
  </ARCHITECTURE>
13662
13740
  </facts>
13663
13741
  <user_observations>
@@ -13680,7 +13758,7 @@ PDF page rotation is captured before OCR rasterization so Tesseract sees the cor
13680
13758
  </compartment>
13681
13759
  <facts>
13682
13760
  <CONSTRAINTS>
13683
- * QuillOCR cannot rely on pdfimages output for page rotation when Poppler emits JBIG2 masks; rotation must be read from pdfinfo before rasterization.
13761
+ * [at_compartment=8] QuillOCR cannot rely on pdfimages output for page rotation when Poppler emits JBIG2 masks; rotation must be read from pdfinfo before rasterization.
13684
13762
  </CONSTRAINTS>
13685
13763
  </facts>
13686
13764
  <events>
@@ -13711,13 +13789,13 @@ Synonym edits are now shipped by building and promoting a shadow index, not by r
13711
13789
  </compartment>
13712
13790
  <facts>
13713
13791
  <PROJECT_RULES>
13714
- * Search schema changes and synonym changes ship through the same shadow-index promotion workflow.
13792
+ * [at_compartment=1] Search schema changes and synonym changes ship through the same shadow-index promotion workflow.
13715
13793
  </PROJECT_RULES>
13716
13794
  <ARCHITECTURE>
13717
- * Synonym changes are applied by building a shadow index and swapping aliases, not by reloading the hot index in place.
13795
+ * [at_compartment=1] Synonym changes are applied by building a shadow index and swapping aliases, not by reloading the hot index in place.
13718
13796
  </ARCHITECTURE>
13719
13797
  <NAMING>
13720
- * The paired search aliases are products_live and products_next.
13798
+ * [at_compartment=1] The paired search aliases are products_live and products_next.
13721
13799
  </NAMING>
13722
13800
  </facts>`
13723
13801
  },
@@ -13739,16 +13817,16 @@ Ranked duo matchmaking now preserves parties even when it increases queue time.
13739
13817
  </compartment>
13740
13818
  <facts>
13741
13819
  <PROJECT_RULES>
13742
- * Arcade Relay matchmaker must not split a party_id across ranked lobbies; widen match criteria before breaking party constraints.
13820
+ * [at_compartment=1] Arcade Relay matchmaker must not split a party_id across ranked lobbies; widen match criteria before breaking party constraints.
13743
13821
  </PROJECT_RULES>
13744
13822
  <CONFIG_VALUES>
13745
- * Arcade Relay ranked_duo MMR window widens by 75 every 15s up to 450.
13823
+ * [at_compartment=1] Arcade Relay ranked_duo MMR window widens by 75 every 15s up to 450.
13746
13824
  </CONFIG_VALUES>
13747
13825
  </facts>`
13748
13826
  },
13749
13827
  {
13750
13828
  importance: 52,
13751
- block: '<compartment start="1201" end="1264" title="Slowly-changing-dim fix in dim_customer dbt model" episode_type="refactor,bug" importance="52">\n<p1>\n`dim_customer` was implementing a hand-rolled Type-2 SCD with `valid_from`/`valid_to` columns and a `is_current` flag, updated by a UDF that fired on row change. The UDF had a race window where two concurrent upstream loads could both stamp `is_current=true` on overlapping rows for the same customer_id.\n\nMigrated to dbt snapshots (`snapshots/dim_customer.sql`) with `strategy=\'timestamp\'` on `updated_at`. Snapshot runs single-threaded by design; no race window. Backfilled the snapshot from the existing dim — diffed against the old table, 14 customers had overlapping `is_current` windows, all resolved by taking the latest by `updated_at`. Old UDF and trigger removed.\n</p1>\n<p2>\n`dim_customer` SCD reimplemented as a dbt snapshot (timestamp strategy on `updated_at`) replacing a hand-rolled trigger+UDF that had a concurrent-update race. Backfill resolved 14 customers with overlapping is_current windows.\n</p2>\n<p3>\nCustomer SCD moved from custom triggers to dbt snapshots.\n</p3>\n<p4>\nsnapshots/dim_customer.sql; strategy=timestamp on updated_at\n</p4>\n</compartment>\n<facts>\n<PROJECT_RULES>\n* Type-2 SCD modeling uses dbt snapshots with the `timestamp` strategy. Hand-rolled SCD via triggers/UDFs is not permitted because it has no race-free coordination across concurrent upstream loads.\n</PROJECT_RULES>\n</facts>'
13829
+ block: '<compartment start="1201" end="1264" title="Slowly-changing-dim fix in dim_customer dbt model" episode_type="refactor,bug" importance="52">\n<p1>\n`dim_customer` was implementing a hand-rolled Type-2 SCD with `valid_from`/`valid_to` columns and a `is_current` flag, updated by a UDF that fired on row change. The UDF had a race window where two concurrent upstream loads could both stamp `is_current=true` on overlapping rows for the same customer_id.\n\nMigrated to dbt snapshots (`snapshots/dim_customer.sql`) with `strategy=\'timestamp\'` on `updated_at`. Snapshot runs single-threaded by design; no race window. Backfilled the snapshot from the existing dim — diffed against the old table, 14 customers had overlapping `is_current` windows, all resolved by taking the latest by `updated_at`. Old UDF and trigger removed.\n</p1>\n<p2>\n`dim_customer` SCD reimplemented as a dbt snapshot (timestamp strategy on `updated_at`) replacing a hand-rolled trigger+UDF that had a concurrent-update race. Backfill resolved 14 customers with overlapping is_current windows.\n</p2>\n<p3>\nCustomer SCD moved from custom triggers to dbt snapshots.\n</p3>\n<p4>\nsnapshots/dim_customer.sql; strategy=timestamp on updated_at\n</p4>\n</compartment>\n<facts>\n<PROJECT_RULES>\n* [at_compartment=1] Type-2 SCD modeling uses dbt snapshots with the `timestamp` strategy. Hand-rolled SCD via triggers/UDFs is not permitted because it has no race-free coordination across concurrent upstream loads.\n</PROJECT_RULES>\n</facts>'
13752
13830
  },
13753
13831
  {
13754
13832
  importance: 48,
@@ -13787,10 +13865,10 @@ tesseract=5.3.3; docker/ocr/Dockerfile; upstream #4117
13787
13865
  </compartment>
13788
13866
  <facts>
13789
13867
  <CONFIG_VALUES>
13790
- * \`docker/ocr/Dockerfile\` pins \`tesseract-ocr=5.3.3\` with apt version + SHA pin. Unpin only after upstream #4117 resolves.
13868
+ * [at_compartment=10] \`docker/ocr/Dockerfile\` pins \`tesseract-ocr=5.3.3\` with apt version + SHA pin. Unpin only after upstream #4117 resolves.
13791
13869
  </CONFIG_VALUES>
13792
13870
  <CONSTRAINTS>
13793
- * Tesseract 5.3.4 regresses multi-column layout detection (column-detection heuristic in LSTM postprocessing changed). Single-column accuracy is unaffected.
13871
+ * [at_compartment=10] Tesseract 5.3.4 regresses multi-column layout detection (column-detection heuristic in LSTM postprocessing changed). Single-column accuracy is unaffected.
13794
13872
  </CONSTRAINTS>
13795
13873
  </facts>
13796
13874
  <events>
@@ -13823,10 +13901,10 @@ Snapbench recording examples became runnable instead of descriptive only.
13823
13901
  </compartment>
13824
13902
  <facts>
13825
13903
  <CONFIG_VALUES>
13826
- * Snapbench's default snapshot directory is .snapbench/.
13904
+ * [at_compartment=1] Snapbench's default snapshot directory is .snapbench/.
13827
13905
  </CONFIG_VALUES>
13828
13906
  <NAMING>
13829
- * The Snapbench capture subcommand is named snapbench record.
13907
+ * [at_compartment=1] The Snapbench capture subcommand is named snapbench record.
13830
13908
  </NAMING>
13831
13909
  </facts>
13832
13910
  <user_observations>
@@ -13859,7 +13937,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
13859
13937
  </compartment>
13860
13938
  <facts>
13861
13939
  <CONSTRAINTS>
13862
- * Meridian's ffmpeg HLS mux requires the -copyts flag when chaining segments; without it pts is rescaled per-segment and playback gaps appear at boundaries under some codec configurations.
13940
+ * [at_compartment=8] Meridian's ffmpeg HLS mux requires the -copyts flag when chaining segments; without it pts is rescaled per-segment and playback gaps appear at boundaries under some codec configurations.
13863
13941
  </CONSTRAINTS>
13864
13942
  </facts>
13865
13943
  <events>
@@ -13876,7 +13954,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
13876
13954
  },
13877
13955
  {
13878
13956
  importance: 36,
13879
- block: '<compartment start="1533" end="1617" title="Statistics-refresh hook on bulk-load completion in query planner integration" episode_type="feature,refactor" importance="36">\n<p1>\nThe embedded analytics DB\'s query planner uses table statistics that get stale after large bulk loads (>1M rows), causing the next query against the loaded table to pick a sequential scan even when a covering index would crush it. Added a `post_bulk_load` hook in `internal/storage/loader.go` that triggers an asynchronous `ANALYZE` against the affected tables. The hook is opt-in per loader because some flows already know they\'ll be followed by a manual ANALYZE; default is on.\n\nVerified the planner picks the index on the post-load query in the affected analytics benchmark — query went from 18s to 240ms.\n</p1>\n<p2>\nBulk loader (`internal/storage/loader.go`) now fires an async `ANALYZE` via a `post_bulk_load` hook after >1M-row loads to keep planner stats fresh. Affected benchmark: 18s → 240ms.\n</p2>\n<p3>\nBulk loader triggers asynchronous statistics refresh on large loads to keep the planner from picking sequential scans.\n</p3>\n<p4>\npost_bulk_load hook; internal/storage/loader.go\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* Bulk-load paths are responsible for refreshing planner statistics on the tables they touch — the planner does not auto-trigger ANALYZE on bulk-loaded tables, and stale stats cause it to choose sequential scans over covering indexes.\n</ARCHITECTURE>\n</facts>'
13957
+ block: '<compartment start="1533" end="1617" title="Statistics-refresh hook on bulk-load completion in query planner integration" episode_type="feature,refactor" importance="36">\n<p1>\nThe embedded analytics DB\'s query planner uses table statistics that get stale after large bulk loads (>1M rows), causing the next query against the loaded table to pick a sequential scan even when a covering index would crush it. Added a `post_bulk_load` hook in `internal/storage/loader.go` that triggers an asynchronous `ANALYZE` against the affected tables. The hook is opt-in per loader because some flows already know they\'ll be followed by a manual ANALYZE; default is on.\n\nVerified the planner picks the index on the post-load query in the affected analytics benchmark — query went from 18s to 240ms.\n</p1>\n<p2>\nBulk loader (`internal/storage/loader.go`) now fires an async `ANALYZE` via a `post_bulk_load` hook after >1M-row loads to keep planner stats fresh. Affected benchmark: 18s → 240ms.\n</p2>\n<p3>\nBulk loader triggers asynchronous statistics refresh on large loads to keep the planner from picking sequential scans.\n</p3>\n<p4>\npost_bulk_load hook; internal/storage/loader.go\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* [at_compartment=1] Bulk-load paths are responsible for refreshing planner statistics on the tables they touch — the planner does not auto-trigger ANALYZE on bulk-loaded tables, and stale stats cause it to choose sequential scans over covering indexes.\n</ARCHITECTURE>\n</facts>'
13880
13958
  },
13881
13959
  {
13882
13960
  importance: 36,
@@ -13911,7 +13989,7 @@ Polaris; data/preprocessed/; preprocessor.py; polaris.preprocess; preprocess.yam
13911
13989
  </compartment>
13912
13990
  <facts>
13913
13991
  <CONFIG_VALUES>
13914
- * Polaris preprocessed dataset cache dir: data/preprocessed/; triggered via python -m polaris.preprocess --config configs/preprocess.yaml; cache key: dataset name + SHA256 of preprocessing config.
13992
+ * [at_compartment=1] Polaris preprocessed dataset cache dir: data/preprocessed/; triggered via python -m polaris.preprocess --config configs/preprocess.yaml; cache key: dataset name + SHA256 of preprocessing config.
13915
13993
  </CONFIG_VALUES>
13916
13994
  </facts>`
13917
13995
  },
@@ -13934,10 +14012,10 @@ The SKU importer now defaults to a safe preview workflow instead of assuming liv
13934
14012
  </compartment>
13935
14013
  <facts>
13936
14014
  <PROJECT_RULES>
13937
- * New operational import commands should default to preview mode unless an explicit apply flag is present.
14015
+ * [at_compartment=15] New operational import commands should default to preview mode unless an explicit apply flag is present.
13938
14016
  </PROJECT_RULES>
13939
14017
  <CONFIG_VALUES>
13940
- * Destructive execution flag: --apply; preview mode is the default when it is absent.
14018
+ * [at_compartment=15] Destructive execution flag: --apply; preview mode is the default when it is absent.
13941
14019
  </CONFIG_VALUES>
13942
14020
  </facts>
13943
14021
  <events>
@@ -13970,7 +14048,7 @@ Invalid IoT telemetry is retained in a DLQ instead of silently disappearing.
13970
14048
  </compartment>
13971
14049
  <facts>
13972
14050
  <CONFIG_VALUES>
13973
- * BeaconMesh malformed raw telemetry is routed to Kafka topic telemetry.raw.dlq.v2.
14051
+ * [at_compartment=1] BeaconMesh malformed raw telemetry is routed to Kafka topic telemetry.raw.dlq.v2.
13974
14052
  </CONFIG_VALUES>
13975
14053
  </facts>`
13976
14054
  },
@@ -13992,7 +14070,7 @@ Mobile offline sync shipped with a narrow notes-only scope.
13992
14070
  </compartment>
13993
14071
  <facts>
13994
14072
  <CONFIG_VALUES>
13995
- * Harbor Notes offline sync MVP includes note title and body only; attachments and comment threads remain online-only.
14073
+ * [at_compartment=1] Harbor Notes offline sync MVP includes note title and body only; attachments and comment threads remain online-only.
13996
14074
  </CONFIG_VALUES>
13997
14075
  </facts>`
13998
14076
  },
@@ -14018,10 +14096,10 @@ Low-confidence scan rotation is now handled through a manual override path, with
14018
14096
  </compartment>
14019
14097
  <facts>
14020
14098
  <CONSTRAINTS>
14021
- * OCR angle predictions below a high confidence threshold are not reliable enough for unattended page rotation on messy multi-scan uploads.
14099
+ * [at_compartment=19] OCR angle predictions below a high confidence threshold are not reliable enough for unattended page rotation on messy multi-scan uploads.
14022
14100
  </CONSTRAINTS>
14023
14101
  <CONFIG_VALUES>
14024
- * Automatic rotation threshold: angle_confidence 0.98 or higher.
14102
+ * [at_compartment=19] Automatic rotation threshold: angle_confidence 0.98 or higher.
14025
14103
  </CONFIG_VALUES>
14026
14104
  </facts>
14027
14105
  <events>
@@ -14095,7 +14173,7 @@ This was a scoped replay, not a lasting data-model change: the useful outcome wa
14095
14173
  </compartment>
14096
14174
  <facts>
14097
14175
  <CONFIG_VALUES>
14098
- * The orders repair workflow is keyed off landed_at partitions rather than invoice_date.
14176
+ * [at_compartment=5] The orders repair workflow is keyed off landed_at partitions rather than invoice_date.
14099
14177
  </CONFIG_VALUES>
14100
14178
  </facts>
14101
14179
  <events>
@@ -14140,13 +14218,13 @@ README install path fixed for Apple Silicon.
14140
14218
  </compartment>
14141
14219
  <facts>
14142
14220
  <NAMING>
14143
- * On darwin-arm64 (Apple Silicon), the installed binary path is \`/opt/homebrew/bin/loomctl\`. On darwin-x86_64 and Linux, it remains \`/usr/local/bin/loomctl\`.
14221
+ * [at_compartment=1] On darwin-arm64 (Apple Silicon), the installed binary path is \`/opt/homebrew/bin/loomctl\`. On darwin-x86_64 and Linux, it remains \`/usr/local/bin/loomctl\`.
14144
14222
  </NAMING>
14145
14223
  </facts>`
14146
14224
  },
14147
14225
  {
14148
14226
  importance: 17,
14149
- block: '<compartment start="1734" end="1768" title="Rename internal `bilUtil` helper to `invoiceMath`" episode_type="refactor" importance="17">\n<p1>\nThe `bilUtil` package in the billing service was a holdover name from a partial rename — `bil` was the original short prefix before we standardized on `invoice`. Renamed to `invoiceMath` since that\'s what the package actually does (rounding, proration, tax-base math). No behavior change. Updated callers, ran tests, done.\n</p1>\n<p2>\nRenamed `bilUtil` package to `invoiceMath` to match its actual responsibility.\n</p2>\n<p3>\nNaming cleanup in the billing service.\n</p3>\n<p4/>\n</compartment>\n<facts>\n<NAMING>\n* Billing math helpers live in package `invoiceMath` (rounding, proration, tax-base computation). The prior name `bilUtil` is deprecated.\n</NAMING>\n</facts>'
14227
+ block: '<compartment start="1734" end="1768" title="Rename internal `bilUtil` helper to `invoiceMath`" episode_type="refactor" importance="17">\n<p1>\nThe `bilUtil` package in the billing service was a holdover name from a partial rename — `bil` was the original short prefix before we standardized on `invoice`. Renamed to `invoiceMath` since that\'s what the package actually does (rounding, proration, tax-base math). No behavior change. Updated callers, ran tests, done.\n</p1>\n<p2>\nRenamed `bilUtil` package to `invoiceMath` to match its actual responsibility.\n</p2>\n<p3>\nNaming cleanup in the billing service.\n</p3>\n<p4/>\n</compartment>\n<facts>\n<NAMING>\n* [at_compartment=1] Billing math helpers live in package `invoiceMath` (rounding, proration, tax-base computation). The prior name `bilUtil` is deprecated.\n</NAMING>\n</facts>'
14150
14228
  },
14151
14229
  {
14152
14230
  importance: 14,
@@ -14188,7 +14266,7 @@ kind; ci/kind-config.yaml; kindest/node:v1.29.2; integration.yml
14188
14266
  </compartment>
14189
14267
  <facts>
14190
14268
  <CONFIG_VALUES>
14191
- * Vesper CI kind cluster: config ci/kind-config.yaml, node image kindest/node:v1.29.2.
14269
+ * [at_compartment=1] Vesper CI kind cluster: config ci/kind-config.yaml, node image kindest/node:v1.29.2.
14192
14270
  </CONFIG_VALUES>
14193
14271
  </facts>`
14194
14272
  },
@@ -14245,7 +14323,7 @@ False start: attempted-and-reverted controller-runtime cache bypass.
14245
14323
  </compartment>
14246
14324
  <facts>
14247
14325
  <CONSTRAINTS>
14248
- * controller-runtime's cache is itself informer-backed; "going direct to informers" doesn't remove any indirection and gives no latency benefit.
14326
+ * [at_compartment=18] controller-runtime's cache is itself informer-backed; "going direct to informers" doesn't remove any indirection and gives no latency benefit.
14249
14327
  </CONSTRAINTS>
14250
14328
  </facts>
14251
14329
  <events>
@@ -14370,7 +14448,7 @@ Captured high-load CAN bus limitation in firmware docs.
14370
14448
  </compartment>
14371
14449
  <facts>
14372
14450
  <CONSTRAINTS>
14373
- * CAN bus arbitration on the current MCU fails under >80% bus load; requires priority inversion mitigation in the driver.
14451
+ * [at_compartment=1] CAN bus arbitration on the current MCU fails under >80% bus load; requires priority inversion mitigation in the driver.
14374
14452
  </CONSTRAINTS>
14375
14453
  </facts>`
14376
14454
  },
@@ -14420,7 +14498,7 @@ Docs examples section was renamed.
14420
14498
  </compartment>
14421
14499
  <facts>
14422
14500
  <NAMING>
14423
- * AstraKit's docs navigation label for examples is "Cookbook", not "Recipes".
14501
+ * [at_compartment=1] AstraKit's docs navigation label for examples is "Cookbook", not "Recipes".
14424
14502
  </NAMING>
14425
14503
  </facts>`
14426
14504
  }
@@ -15203,7 +15281,7 @@ async function runHistorianPrompt(args) {
15203
15281
  promptSettled = false;
15204
15282
  const errorMsg = getErrorMessage(error);
15205
15283
  sessionLog2(parentSessionId, `historian: prompt attempt ${retryIndex + 1} failed: ${errorMsg}`);
15206
- const shouldRetry = retryIndex < MAX_HISTORIAN_RETRIES && isTransientHistorianPromptError(errorMsg);
15284
+ const shouldRetry = retryIndex < MAX_HISTORIAN_RETRIES && !(error instanceof HiddenCompletionRefusal && error.code === "hidden_setup_timeout") && isTransientHistorianPromptError(errorMsg);
15207
15285
  if (!shouldRetry) {
15208
15286
  throw error;
15209
15287
  }
@@ -16273,1316 +16351,1357 @@ function queueDropsForCompartmentalizedMessages(db, sessionId, upToMessageIndex,
16273
16351
  queuePreparedCompartmentDrops(db, prepareCompartmentDrops(db, sessionId, upToMessageIndex, observedKeys, fromMessageIndex));
16274
16352
  }
16275
16353
 
16276
- // src/hooks/magic-context/historian-failure-report.ts
16277
- var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
16278
- var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
16279
- var ACTIONS = "What to do: run /ctx-status for detail; change the historian model or its fallback models in magic-context.jsonc (user or project config); or run /ctx-recomp to rebuild the history.";
16280
- var REFUSAL_ERROR_MAX_CHARS = 500;
16281
- var WARNING_ERROR_MAX_CHARS = 200;
16282
- function readHistorianFailureStreak(db, sessionId, options = {}) {
16283
- const state = getHistorianFailureState(db, sessionId);
16284
- const count = state.failureCount;
16285
- let since = null;
16286
- if (count > 0) {
16287
- const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
16288
- if (recorded <= 0) {
16289
- since = state.lastFailureAt;
16290
- } else {
16291
- const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
16292
- since = times.length === recorded ? times[recorded - 1] ?? null : null;
16293
- }
16354
+ // src/hooks/magic-context/file-token-coverage.ts
16355
+ function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
16356
+ const filesByMessage = new Map;
16357
+ for (const message of messages) {
16358
+ const count = message.parts.filter(isFilePart).length;
16359
+ if (count > 0 && totals.has(message.id))
16360
+ filesByMessage.set(message.id, count);
16294
16361
  }
16295
- return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
16362
+ if (filesByMessage.size === 0)
16363
+ return totals;
16364
+ const rows = db.prepare(`
16365
+ SELECT o.value AS owner, COUNT(t.id) AS count
16366
+ FROM json_each(?) o LEFT JOIN tags t
16367
+ ON t.session_id = ? AND t.type = 'file'
16368
+ AND t.message_id >= o.value || ':file'
16369
+ AND t.message_id < o.value || ':file;'
16370
+ GROUP BY o.value
16371
+ `).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
16372
+ for (const row of rows) {
16373
+ if (row.count < (filesByMessage.get(row.owner) ?? 0))
16374
+ totals.delete(row.owner);
16375
+ }
16376
+ return totals;
16296
16377
  }
16297
- function formatHistorianClockTime(at, now = Date.now()) {
16298
- const date = new Date(at);
16299
- const pad = (value) => String(value).padStart(2, "0");
16300
- const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
16301
- const today = new Date(now);
16302
- const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
16303
- return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
16378
+
16379
+ // src/hooks/magic-context/protected-tail-boundary.ts
16380
+ function describeBoundaryDiagnostics(snapshot) {
16381
+ return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
16304
16382
  }
16305
- function formatHistorianSeconds(ms) {
16306
- const seconds = Math.max(0, ms) / 1000;
16307
- return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
16383
+ function boundaryDiagnostics(args) {
16384
+ return {
16385
+ ...args,
16386
+ capTier: args.usagePercentage >= 95 ? "95" : args.usagePercentage >= 80 ? "80" : "normal",
16387
+ drainBudget: "not-reserved; does-not-size-cap"
16388
+ };
16308
16389
  }
16309
- function singleLine(text) {
16310
- return text.replace(/\s+/g, " ").trim();
16390
+ var ALPHA = 0.3;
16391
+ var FLOOR_RATIO = 0.08;
16392
+ var FLOOR_MIN = 2000;
16393
+ var FLOOR_MAX = 12000;
16394
+ var ABS_CAP = 96000;
16395
+ var MAX_USABLE_RATIO = 0.4;
16396
+ var RESERVED_HEADROOM_MIN = 1000;
16397
+ var RESERVED_HEADROOM_RATIO = 0.02;
16398
+ var NON_EMERGENCY_MAX_CAP = 250000;
16399
+ var FORCE80_MAX_CAP = 500000;
16400
+ var FORCE95_MAX_CAP = 750000;
16401
+ var NORMAL_HYSTERESIS_TOKENS = 256;
16402
+ var RECOVERY_NO_HEAD_LIMIT = 2;
16403
+ function clampPercentage(value) {
16404
+ if (!Number.isFinite(value))
16405
+ return 0;
16406
+ return Math.max(0, Math.min(100, value));
16311
16407
  }
16312
- function quoteError(error, maxChars) {
16313
- const text = sanitizeDiagnosticText(singleLine(error));
16314
- return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
16408
+ function clampOrdinal(value, rawMessageCount) {
16409
+ return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
16315
16410
  }
16316
- function endSentence(text) {
16317
- return /[.!?]$/.test(text) ? text : `${text}.`;
16411
+ function deriveProtectedTailTokenTarget(args) {
16412
+ const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
16413
+ const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
16414
+ const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
16415
+ const usage = clampPercentage(args.usagePercentage);
16416
+ const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
16417
+ const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
16418
+ const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
16419
+ const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
16420
+ const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
16421
+ const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
16422
+ const effectiveFloor = Math.min(floorN, ceilingN);
16423
+ const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
16424
+ return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
16318
16425
  }
16319
- function usageClause(usagePercentage) {
16320
- return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
16426
+ function nonEmergencyPerRunCap(usable, N) {
16427
+ return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
16321
16428
  }
16322
- function capitalize(text) {
16323
- return text.charAt(0).toUpperCase() + text.slice(1);
16429
+ function force80PerRunCap(usable, N) {
16430
+ return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
16324
16431
  }
16325
- function chunkLabel(chunk) {
16326
- return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
16432
+ function force95PerRunCap(usable, N) {
16433
+ return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
16327
16434
  }
16328
- function streakSentence(failures, now) {
16329
- if (failures.count <= 0)
16435
+ function selectPerRunCap(snapshot) {
16436
+ const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
16437
+ if (snapshot.usagePercentage >= 95)
16438
+ return force95PerRunCap(usable, snapshot.N);
16439
+ if (snapshot.usagePercentage >= 80)
16440
+ return force80PerRunCap(usable, snapshot.N);
16441
+ return nonEmergencyPerRunCap(usable, snapshot.N);
16442
+ }
16443
+ function boundaryMessageId(index, ordinal) {
16444
+ if (ordinal < 1 || ordinal > index.rawMessageCount)
16330
16445
  return null;
16331
- const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
16332
- return `Summary runs failed in a row: ${failures.count}${since}.`;
16446
+ return index.messageIdAtOrdinal(ordinal);
16333
16447
  }
16334
- function failureBelongsToRun(failures, run) {
16335
- return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
16448
+ function isSemanticBoundaryCandidate(messageParts, role) {
16449
+ if (role === "user" && hasMeaningfulUserText2(messageParts))
16450
+ return true;
16451
+ if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
16452
+ return true;
16453
+ }
16454
+ return false;
16336
16455
  }
16337
- function describeHistorianJoinRefusal(input) {
16338
- const now = input.now ?? Date.now();
16339
- const { run, failures } = input;
16340
- const sentences = [
16341
- `This turn was not sent: ${usageClause(input.usagePercentage)}, and Magic Context waited ${formatHistorianSeconds(input.waitedMs)} s for a history summary that did not finish in time.`
16342
- ];
16343
- const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
16344
- const ownFailure = failureBelongsToRun(failures, run);
16345
- const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
16346
- if (ownFailure) {
16347
- sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
16348
- } else if (run && run.endedAt === undefined) {
16349
- sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
16350
- } else if (run) {
16351
- sentences.push(`${subject} finished after the wait ended.`);
16456
+ function semanticSnapBoundary(args) {
16457
+ const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
16458
+ let snapped = candidate;
16459
+ for (const message of messages) {
16460
+ if (message.ordinal > candidate)
16461
+ break;
16462
+ if (message.ordinal < lastCompartmentEndOrdinal + 1)
16463
+ continue;
16464
+ if (!isSemanticBoundaryCandidate(message.parts, message.role))
16465
+ continue;
16466
+ snapped = message.ordinal;
16352
16467
  }
16353
- if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
16354
- sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
16468
+ if (snapped === candidate)
16469
+ return candidate;
16470
+ const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
16471
+ if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
16472
+ return candidate;
16473
+ const snappedMessage = messages.find((message) => message.ordinal === snapped);
16474
+ if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
16475
+ return candidate;
16355
16476
  }
16356
- const streak = streakSentence(failures, now);
16357
- if (streak)
16358
- sentences.push(streak);
16359
- sentences.push(ACTIONS);
16360
- return sentences.join(" ");
16361
- }
16362
- function describeRepeatedHistorianFailures(input) {
16363
- const now = input.now ?? Date.now();
16364
- const { failures } = input;
16365
- const facts = [
16366
- streakSentence(failures, now) ?? "Summary runs are failing.",
16367
- ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
16368
- ...failures.lastError ? [
16369
- endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
16370
- ] : [],
16371
- `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
16372
- ];
16373
- return [
16374
- "## Magic Context — History summaries keep failing",
16375
- "",
16376
- facts.join(" "),
16377
- "",
16378
- ACTIONS
16379
- ].join(`
16380
- `);
16477
+ return snapped;
16381
16478
  }
16382
- var repeatedFailureWarnings = new Map;
16383
- function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
16384
- const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
16385
- if (failureCount < step || failureCount % step !== 0)
16386
- return false;
16387
- const last = repeatedFailureWarnings.get(sessionId);
16388
- if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
16389
- return false;
16479
+ function snapWrapupBoundaryToUser(args) {
16480
+ const { messages, index, candidate, offset, triggerBudget } = args;
16481
+ if (candidate <= offset)
16482
+ return candidate;
16483
+ const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
16484
+ for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
16485
+ const message = messages.find((m) => m.ordinal === ordinal);
16486
+ if (!message)
16487
+ continue;
16488
+ if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
16489
+ continue;
16490
+ const extraTokens = index.rangeTokens(ordinal, candidate);
16491
+ if (extraTokens <= snapTokenLimit)
16492
+ return ordinal;
16493
+ return candidate;
16390
16494
  }
16391
- repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
16392
- return true;
16495
+ return candidate;
16393
16496
  }
16394
- function takeRepeatedHistorianFailureWarning(input) {
16395
- const now = input.now ?? Date.now();
16396
- if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
16397
- return null;
16497
+ function fenceWrapupBoundaryForToolArcs(args) {
16498
+ let boundary = args.candidate;
16499
+ const maxPasses = args.arcs.length + 1;
16500
+ for (let pass = 0;pass < maxPasses; pass += 1) {
16501
+ let next = boundary;
16502
+ for (const arc of args.arcs) {
16503
+ if (arc.resOrdinal === null) {
16504
+ continue;
16505
+ }
16506
+ if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
16507
+ next = arc.invOrdinal;
16508
+ }
16509
+ }
16510
+ if (next === boundary)
16511
+ return boundary;
16512
+ boundary = next;
16398
16513
  }
16399
- const failures = readHistorianFailureStreak(input.db, input.sessionId, {
16400
- unrecordedFailures: input.unrecordedFailures
16401
- });
16402
- return describeRepeatedHistorianFailures({
16403
- chunk: input.chunk,
16404
- failures: { ...failures, count: input.failureCount },
16405
- usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
16406
- now
16407
- });
16408
- }
16409
-
16410
- // src/hooks/magic-context/historian-history-wait.ts
16411
- var historyWaits = new Map;
16412
- function newestMessageId(snapshot) {
16413
- try {
16414
- const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
16415
- const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
16416
- const newest = ids.keys().next().value;
16417
- if (newest)
16418
- return newest;
16419
- } catch {}
16420
- return snapshot.rawLastMessageIdAtTrigger;
16421
- }
16422
- function recoveryWindow(snapshot, percentage) {
16423
- return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
16424
- }
16425
- function clearHistorianHistoryWait(sessionId) {
16426
- historyWaits.delete(sessionId);
16514
+ return boundary;
16427
16515
  }
16428
- function recordHistorianNoProgress(snapshot, emergency = false) {
16429
- const newest = newestMessageId(snapshot);
16430
- if (!newest)
16431
- return;
16432
- const previous = historyWaits.get(snapshot.sessionId);
16433
- const sameHistory = previous?.newestMessageId === newest;
16434
- historyWaits.set(snapshot.sessionId, {
16435
- newestMessageId: newest,
16436
- recoveryAttempted: sameHistory && previous.recoveryAttempted || emergency || recoveryWindow(snapshot, snapshot.usagePercentage),
16437
- floorLiftAttempted: sameHistory && previous.floorLiftAttempted || snapshot.liftLivePromptFloor === true
16516
+ function applyHeadCap(args) {
16517
+ const {
16518
+ index,
16519
+ protectedTailStart,
16520
+ offset,
16521
+ arcs,
16522
+ lastCompartmentEndOrdinal,
16523
+ capTokens,
16524
+ recentOpenArcCutoff
16525
+ } = args;
16526
+ const diagnostics = {
16527
+ offset,
16528
+ capEnd: offset,
16529
+ capTokenSum: 0,
16530
+ completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
16531
+ oversizeAdmission: { from: offset, to: offset },
16532
+ openArcClamp: { from: offset, to: offset },
16533
+ completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
16534
+ eligibleEnd: offset
16535
+ };
16536
+ if (offset >= protectedTailStart) {
16537
+ args.observeDiagnostics?.(diagnostics);
16538
+ return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
16539
+ }
16540
+ let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
16541
+ diagnostics.capEnd = end;
16542
+ diagnostics.capTokenSum = index.rangeTokens(offset, end);
16543
+ let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
16544
+ let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
16545
+ diagnostics.completedFence.arcs = component.map((arc) => ({
16546
+ assistant: arc.invocation,
16547
+ result: arc.result
16548
+ }));
16549
+ diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
16438
16550
  });
16439
- }
16440
- function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
16441
- const wait = historyWaits.get(snapshot.sessionId);
16442
- if (!wait)
16443
- return false;
16444
- const newest = newestMessageId(snapshot);
16445
- if (newest && newest !== wait.newestMessageId) {
16446
- try {
16447
- const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
16448
- if (order === null || order > 0)
16449
- return false;
16450
- } catch {}
16551
+ diagnostics.completedFence.from = end;
16552
+ diagnostics.completedFence.to = completedFence;
16553
+ diagnostics.oversizeAdmission.from = completedFence;
16554
+ if (completedFence <= offset && end > offset) {
16555
+ const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
16556
+ if (afterFirstArc <= protectedTailStart)
16557
+ completedFence = afterFirstArc;
16451
16558
  }
16452
- const recovery = options.emergency || recoveryWindow(snapshot, options.usagePercentage ?? snapshot.usagePercentage);
16453
- const floorLift = snapshot.liftLivePromptFloor === true;
16454
- if (recovery && !wait.recoveryAttempted || floorLift && !wait.floorLiftAttempted) {
16455
- if (options.claim) {
16456
- wait.recoveryAttempted ||= recovery;
16457
- wait.floorLiftAttempted ||= floorLift;
16559
+ diagnostics.oversizeAdmission.to = completedFence;
16560
+ if (completedFence > end) {
16561
+ end = Math.min(protectedTailStart, completedFence);
16562
+ if (index.rangeTokens(offset, end) > capTokens)
16563
+ oversizeAtomicUnit = true;
16564
+ } else {
16565
+ end = completedFence;
16566
+ }
16567
+ diagnostics.openArcClamp.from = end;
16568
+ for (const arc of arcs) {
16569
+ const resOrdinal = arc.resOrdinal;
16570
+ if (resOrdinal === null) {
16571
+ if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
16572
+ end = Math.min(end, arc.invOrdinal);
16573
+ }
16458
16574
  }
16459
- return false;
16460
16575
  }
16461
- return true;
16462
- }
16463
-
16464
- // src/tools/ctx-note/render.ts
16465
- var GLANCE_TITLE_MAX = 80;
16466
- var NUDGE_TITLE_MAX = 60;
16467
- var STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
16468
- var EMPTY_READ_REPLY = `## Notes
16469
-
16470
- No session notes or smart notes.`;
16471
- function noteTouchedAt(note) {
16472
- return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
16473
- }
16474
- function formatNoteAge(touchedAt, nowMs) {
16475
- const elapsed = Math.max(0, nowMs - touchedAt);
16476
- const minutes = Math.floor(elapsed / 60000);
16477
- if (minutes < 60)
16478
- return `${minutes}m`;
16479
- const hours = Math.floor(elapsed / 3600000);
16480
- if (hours < 24)
16481
- return `${hours}h`;
16482
- const days = Math.floor(elapsed / 86400000);
16483
- if (days < 7)
16484
- return `${days}d`;
16485
- return `${Math.floor(days / 7)}w`;
16486
- }
16487
- function clipNoteTitle(content, max) {
16488
- const firstLine = (content.split(`
16489
- `, 1)[0] ?? "").trim();
16490
- const characters = [...firstLine];
16491
- if (characters.length <= max)
16492
- return firstLine;
16493
- return `${characters.slice(0, max).join("")}…`;
16494
- }
16495
- function formatGlanceRow(note, nowMs) {
16496
- const touchedAt = noteTouchedAt(note);
16497
- const markers = [];
16498
- if (note.status !== "active")
16499
- markers.push(note.status);
16500
- if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
16501
- markers.push(`parked: ${note.readyReason ?? "Condition can't be checked"}`);
16576
+ diagnostics.openArcClamp.to = end;
16577
+ diagnostics.completedRefence.from = end;
16578
+ end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
16579
+ diagnostics.completedRefence.arcs = component.map((arc) => ({
16580
+ assistant: arc.invocation,
16581
+ result: arc.result
16582
+ }));
16583
+ diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
16584
+ });
16585
+ diagnostics.completedRefence.to = end;
16586
+ if (end > protectedTailStart)
16587
+ end = offset;
16588
+ diagnostics.eligibleEnd = end <= offset ? offset : end;
16589
+ args.observeDiagnostics?.(diagnostics);
16590
+ if (end <= offset && offset < protectedTailStart) {
16591
+ return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
16502
16592
  }
16503
- if (nowMs - touchedAt >= STALE_AFTER_MS)
16504
- markers.push("stale");
16505
- const suffix = markers.length > 0 ? ` · ${markers.join(" · ")}` : "";
16506
- const title = clipNoteTitle(note.content, GLANCE_TITLE_MAX);
16507
- return `#${note.id} · ${formatNoteAge(touchedAt, nowMs)} · ${title}${suffix}`;
16508
- }
16509
- function newestFirst(left, right) {
16510
- return right.updatedAt - left.updatedAt || right.id - left.id;
16511
- }
16512
- function orderGlanceNotes(notes) {
16513
- const ready = notes.filter((note) => note.status === "ready").sort(newestFirst);
16514
- const pending = notes.filter((note) => note.status === "pending").sort(newestFirst);
16515
- const rest = notes.filter((note) => note.status !== "ready" && note.status !== "pending").sort(newestFirst);
16516
- return [...ready, ...pending, ...rest];
16517
- }
16518
- function renderGlance(notes, options) {
16519
- const ordered = orderGlanceNotes(notes);
16520
- const page = ordered.slice(options.offset, options.offset + options.limit);
16521
- if (page.length === 0)
16522
- return EMPTY_READ_REPLY;
16523
- const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
16524
- `);
16525
- const remaining = ordered.length - options.offset - page.length;
16526
- const footer = remaining > 0 ? `
16527
-
16528
- Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
16529
- return `## Notes
16530
-
16531
- ${rows}${footer}`;
16532
- }
16533
- function formatNoteBody(note, nowMs) {
16534
- const touchedAt = noteTouchedAt(note);
16535
- const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
16536
- const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
16537
- if (note.type !== "smart")
16538
- return head;
16539
- const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
16540
- const label = note.status === "ready" ? "Condition met" : "Condition";
16541
- const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
16542
- ${note.readyReason}` : "";
16543
- return `${head}
16544
- ${label}: ${condition}${failure}`;
16545
- }
16546
- function renderNotesById(entries, nowMs) {
16547
- const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
16548
- return `## Notes by ID
16549
-
16550
- ${lines.join(`
16551
-
16552
- `)}`;
16553
- }
16554
- function formatTraySuffix(tray, nowMs) {
16555
- if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
16556
- return "";
16557
- return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
16558
- }
16559
- function formatWriteReply(noteId, tray, nowMs) {
16560
- return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
16593
+ return { eligibleEndOrdinal: end, oversizeAtomicUnit };
16561
16594
  }
16562
- function noteNudgePickIndex(sessionId, counter, poolSize) {
16563
- if (poolSize <= 0)
16564
- return 0;
16565
- const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
16566
- let hash = 2166136261;
16567
- for (const byte of bytes) {
16568
- hash ^= byte;
16569
- hash = Math.imul(hash, 16777619) >>> 0;
16595
+ function resolveProtectedTailBoundary(ctx) {
16596
+ const createdAt = ctx.createdAt ?? Date.now();
16597
+ const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
16598
+ const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
16599
+ const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
16600
+ const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
16601
+ const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
16602
+ const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
16603
+ const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
16604
+ providerShapeVersion: ctx.providerShapeVersion,
16605
+ cacheNamespace: ctx.cacheNamespace,
16606
+ calibration: ctx.calibration,
16607
+ absoluteMessageCount,
16608
+ storedTotalForMessage: storedTotals ? (m) => {
16609
+ const v = storedTotals.get(m.id);
16610
+ return v === undefined ? null : v;
16611
+ } : undefined
16612
+ });
16613
+ const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
16614
+ providerShapeVersion: ctx.providerShapeVersion,
16615
+ cacheNamespace: ctx.cacheNamespace,
16616
+ calibration: ctx.calibration,
16617
+ absoluteMessageCount,
16618
+ measure: "summary-removed",
16619
+ storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
16620
+ });
16621
+ const rawMessageCount = index.rawMessageCount;
16622
+ const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
16623
+ const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
16624
+ if (rawMessageCount === 0) {
16625
+ return {
16626
+ sessionId: ctx.sessionId,
16627
+ mode: ctx.mode,
16628
+ offset,
16629
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
16630
+ offsetMessageId: null,
16631
+ protectedTailStart: 1,
16632
+ protectedTailStartMessageId: null,
16633
+ eligibleEndOrdinal: 1,
16634
+ eligibleEndMessageId: null,
16635
+ rawMessageCountAtTrigger: 0,
16636
+ rawLastMessageIdAtTrigger: null,
16637
+ N: 0,
16638
+ usagePercentage,
16639
+ usageInputTokens,
16640
+ usageSource: ctx.usageSource,
16641
+ contextLimit: ctx.contextLimit,
16642
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
16643
+ triggerBudget: ctx.triggerBudget,
16644
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
16645
+ migrationFloorActive: ctx.migrationFloorActive,
16646
+ emergencyTailScale: ctx.emergencyTailScale,
16647
+ recovery: ctx.recovery,
16648
+ providerShapeVersion: ctx.providerShapeVersion,
16649
+ cacheNamespace: ctx.cacheNamespace,
16650
+ createdAt,
16651
+ rawRangeFingerprint: "",
16652
+ trueRawEligibleTokens: 0,
16653
+ summaryRemovedEligibleTokens: 0,
16654
+ oversizeAtomicUnit: false,
16655
+ boundaryReason: "empty-session"
16656
+ };
16570
16657
  }
16571
- return hash % poolSize;
16658
+ if (ctx.mode === "manual-full-recomp") {
16659
+ const arcs = buildToolArcs(messages);
16660
+ const recompTarget = deriveProtectedTailTokenTarget({
16661
+ contextLimit: ctx.contextLimit,
16662
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
16663
+ usagePercentage: 0,
16664
+ triggerBudget: ctx.triggerBudget
16665
+ });
16666
+ const recentOpenArcCutoff = index.findSuffixStartForTokens(recompTarget.N);
16667
+ const firstOpenArc = arcs.find((arc) => arc.resOrdinal === null && arc.invOrdinal >= offset && arc.invOrdinal >= recentOpenArcCutoff);
16668
+ const protectedTailStart = firstOpenArc?.invOrdinal ?? rawMessageCount + 1;
16669
+ const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, protectedTailStart);
16670
+ return {
16671
+ sessionId: ctx.sessionId,
16672
+ mode: ctx.mode,
16673
+ offset,
16674
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
16675
+ offsetMessageId: boundaryMessageId(index, offset),
16676
+ protectedTailStart,
16677
+ protectedTailStartMessageId: null,
16678
+ eligibleEndOrdinal: protectedTailStart,
16679
+ eligibleEndMessageId: boundaryMessageId(index, protectedTailStart - 1),
16680
+ rawMessageCountAtTrigger: rawMessageCount,
16681
+ rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
16682
+ N: 0,
16683
+ usagePercentage: 0,
16684
+ usageInputTokens: 0,
16685
+ usageSource: "manual-none",
16686
+ contextLimit: ctx.contextLimit,
16687
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
16688
+ triggerBudget: ctx.triggerBudget,
16689
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
16690
+ migrationFloorActive: false,
16691
+ emergencyTailScale: ctx.emergencyTailScale,
16692
+ recovery: ctx.recovery,
16693
+ providerShapeVersion: ctx.providerShapeVersion,
16694
+ cacheNamespace: ctx.cacheNamespace,
16695
+ createdAt,
16696
+ rawRangeFingerprint,
16697
+ trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
16698
+ summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
16699
+ oversizeAtomicUnit: false,
16700
+ boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
16701
+ };
16702
+ }
16703
+ const target = deriveProtectedTailTokenTarget({
16704
+ contextLimit: ctx.contextLimit,
16705
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
16706
+ usagePercentage,
16707
+ triggerBudget: ctx.triggerBudget
16708
+ });
16709
+ const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
16710
+ const arcs = buildToolArcs(messages);
16711
+ let boundary = index.findSuffixStartForTokens(scaledN);
16712
+ const recentOpenArcCutoff = boundary;
16713
+ let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
16714
+ const tokenAtBoundary = index.tokenForOrdinal(boundary);
16715
+ if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
16716
+ boundary += 1;
16717
+ boundaryReason = "huge-message-exception";
16718
+ }
16719
+ boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
16720
+ const snapped = semanticSnapBoundary({
16721
+ messages,
16722
+ index,
16723
+ candidate: boundary,
16724
+ scaledN,
16725
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
16726
+ });
16727
+ if (snapped !== boundary)
16728
+ boundaryReason = "semantic-snap";
16729
+ boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
16730
+ let runtimeFloor = offset;
16731
+ if (ctx.migrationFloorActive)
16732
+ runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
16733
+ let protectedTailStart = Math.max(boundary, runtimeFloor);
16734
+ const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
16735
+ const livePromptFloor = {
16736
+ ordinal: null,
16737
+ from: protectedTailStart,
16738
+ to: protectedTailStart
16739
+ };
16740
+ if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
16741
+ let lastMeaningfulUserOrdinal = 0;
16742
+ for (let i = messages.length - 1;i >= 0; i--) {
16743
+ const message = messages[i];
16744
+ if (message.role !== "user")
16745
+ continue;
16746
+ if (!hasMeaningfulUserText2(message.parts))
16747
+ continue;
16748
+ lastMeaningfulUserOrdinal = message.ordinal;
16749
+ break;
16750
+ }
16751
+ livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
16752
+ livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
16753
+ if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
16754
+ protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
16755
+ }
16756
+ }
16757
+ livePromptFloor.to = protectedTailStart;
16758
+ if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
16759
+ protectedTailStart = offset;
16760
+ }
16761
+ protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
16762
+ protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
16763
+ protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
16764
+ const perRunCap = selectPerRunCap({
16765
+ usagePercentage,
16766
+ N: scaledN,
16767
+ contextLimit: ctx.contextLimit,
16768
+ executeThresholdPercentage: ctx.executeThresholdPercentage
16769
+ });
16770
+ let headDiagnostics;
16771
+ const head = applyHeadCap({
16772
+ observeDiagnostics: (value) => {
16773
+ headDiagnostics = value;
16774
+ },
16775
+ index: summaryRemovedIndex,
16776
+ protectedTailStart,
16777
+ offset,
16778
+ arcs,
16779
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
16780
+ capTokens: perRunCap,
16781
+ recentOpenArcCutoff
16782
+ });
16783
+ const servedEndOrdinal = retreatPastHostUnservedRows(messages, head.eligibleEndOrdinal, offset);
16784
+ const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
16785
+ const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
16786
+ return {
16787
+ sessionId: ctx.sessionId,
16788
+ mode: ctx.mode,
16789
+ offset,
16790
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
16791
+ offsetMessageId: boundaryMessageId(index, offset),
16792
+ protectedTailStart,
16793
+ protectedTailStartMessageId: boundaryMessageId(index, protectedTailStart),
16794
+ eligibleEndOrdinal,
16795
+ eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
16796
+ rawMessageCountAtTrigger: rawMessageCount,
16797
+ rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
16798
+ N: scaledN,
16799
+ usagePercentage,
16800
+ usageInputTokens,
16801
+ usageSource: ctx.usageSource,
16802
+ contextLimit: ctx.contextLimit,
16803
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
16804
+ triggerBudget: ctx.triggerBudget,
16805
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
16806
+ migrationFloorActive: ctx.migrationFloorActive,
16807
+ emergencyTailScale: ctx.emergencyTailScale,
16808
+ recovery: ctx.recovery,
16809
+ liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
16810
+ providerShapeVersion: ctx.providerShapeVersion,
16811
+ cacheNamespace: ctx.cacheNamespace,
16812
+ createdAt,
16813
+ rawRangeFingerprint,
16814
+ trueRawEligibleTokens: index.rangeTokens(offset, eligibleEndOrdinal),
16815
+ summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
16816
+ oversizeAtomicUnit: head.oversizeAtomicUnit,
16817
+ boundaryReason,
16818
+ diagnostics: boundaryDiagnostics({
16819
+ tailTarget: target,
16820
+ usable: target.usable,
16821
+ usagePercentage,
16822
+ N: scaledN,
16823
+ triggerBudget: ctx.triggerBudget,
16824
+ capTokens: perRunCap,
16825
+ sizeWalkStart: recentOpenArcCutoff,
16826
+ protectedTailStart,
16827
+ livePromptFloor,
16828
+ head: headDiagnostics
16829
+ })
16830
+ };
16572
16831
  }
16573
- function formatNoteNudge(args) {
16574
- const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
16575
- const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
16576
- const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
16577
- return `${counts}${oldest}${shown}`;
16832
+ function readLastCompartmentBoundary(db, sessionId) {
16833
+ const row = db.prepare(`SELECT COALESCE(MAX(end_message), -1) AS max_end,
16834
+ (SELECT end_message_id FROM compartments
16835
+ WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
16836
+ FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
16837
+ const endMessageId = row?.end_message_id;
16838
+ return {
16839
+ endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
16840
+ endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
16841
+ };
16578
16842
  }
16579
-
16580
- // src/hooks/magic-context/note-nudger.ts
16581
- var observedUsers = new WeakMap;
16582
- function observeNoteNudgeServe(args) {
16583
- let sessions = observedUsers.get(args.db);
16584
- if (!sessions) {
16585
- sessions = new Map;
16586
- observedUsers.set(args.db, sessions);
16843
+ function resolveBoundaryContext(args) {
16844
+ const lastCompartmentBoundary = readLastCompartmentBoundary(args.db, args.sessionId);
16845
+ const lastCompartmentEndOrdinal = lastCompartmentBoundary.endOrdinal;
16846
+ const triggerBudget = deriveTriggerBudget2(args.contextLimit, args.executeThresholdPercentage);
16847
+ let meta = args.protectedTailMeta ?? loadProtectedTailMeta(args.db, args.sessionId);
16848
+ let migrationFloorActive = false;
16849
+ if (meta.protectedTailPolicyVersion < 3) {
16850
+ let legacyBoundary = 1;
16851
+ try {
16852
+ legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
16853
+ } catch (error) {
16854
+ sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
16855
+ }
16856
+ const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
16857
+ meta = seedResult;
16858
+ migrationFloorActive = seedResult.seeded;
16587
16859
  }
16588
- let seen = sessions.get(args.sessionId);
16589
- const warm = seen !== undefined && seen.size > 0;
16590
- if (!seen)
16591
- seen = new Set;
16592
- const firstServe = args.anchorMessageId !== null && !seen.has(args.anchorMessageId);
16593
- for (const id of args.userMessageIds)
16594
- seen.add(id);
16595
- sessions.set(args.sessionId, seen);
16860
+ const calibration = sessionDecisionCalibration(args.db, args.sessionId);
16861
+ const storedTokenTotalsForMessages = (messageIds, messages = []) => {
16862
+ try {
16863
+ const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
16864
+ return {
16865
+ totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
16866
+ summaryRemovedTotals: weights.summaryRemovedTotals
16867
+ };
16868
+ } catch (error) {
16869
+ sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
16870
+ return;
16871
+ }
16872
+ };
16873
+ return {
16874
+ sessionId: args.sessionId,
16875
+ mode: args.mode,
16876
+ contextLimit: args.contextLimit,
16877
+ executeThresholdPercentage: args.executeThresholdPercentage,
16878
+ triggerBudget,
16879
+ usage: args.usage ?? null,
16880
+ usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
16881
+ lastCompartmentEndOrdinal,
16882
+ lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
16883
+ priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
16884
+ protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
16885
+ migrationFloorActive,
16886
+ emergencyTailScale: args.emergencyTailScale,
16887
+ recovery: args.recovery,
16888
+ liftLivePromptFloor: args.liftLivePromptFloor,
16889
+ providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
16890
+ cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
16891
+ storedTokenTotalsForMessages,
16892
+ calibration
16893
+ };
16894
+ }
16895
+ function resolveOpenCodeProtectedTailBoundary(args) {
16896
+ return resolveProtectedTailBoundary(resolveBoundaryContext(args));
16897
+ }
16898
+ function resolveWrapupProtectedTailBoundary(args) {
16899
+ const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
16900
+ const createdAt = ctx.createdAt ?? Date.now();
16901
+ const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
16902
+ const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
16903
+ const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
16904
+ const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
16905
+ const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
16906
+ const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
16907
+ const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
16908
+ providerShapeVersion: ctx.providerShapeVersion,
16909
+ cacheNamespace: ctx.cacheNamespace,
16910
+ calibration: ctx.calibration,
16911
+ absoluteMessageCount,
16912
+ storedTotalForMessage: storedTotals ? (m) => {
16913
+ const value = storedTotals?.get(m.id);
16914
+ return value === undefined ? null : value;
16915
+ } : undefined
16916
+ });
16917
+ const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
16918
+ providerShapeVersion: ctx.providerShapeVersion,
16919
+ cacheNamespace: ctx.cacheNamespace,
16920
+ calibration: ctx.calibration,
16921
+ absoluteMessageCount,
16922
+ measure: "summary-removed",
16923
+ storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
16924
+ });
16925
+ const rawMessageCount = index.rawMessageCount;
16926
+ const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
16927
+ const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
16928
+ const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
16929
+ const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
16930
+ const keep = Math.max(1, Math.floor(args.messagesToKeep));
16931
+ let targetProtectedTailStart = offset;
16932
+ let boundaryReason = "manual-wrapup-empty";
16933
+ if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
16934
+ targetProtectedTailStart = offset;
16935
+ boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
16936
+ } else {
16937
+ targetProtectedTailStart = anchorRawMessageCount - keep + 1;
16938
+ boundaryReason = "manual-wrapup-keep-watermark";
16939
+ const arcs = buildToolArcs(messages);
16940
+ const fenced = fenceWrapupBoundaryForToolArcs({
16941
+ candidate: targetProtectedTailStart,
16942
+ arcs,
16943
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
16944
+ });
16945
+ if (fenced !== targetProtectedTailStart)
16946
+ boundaryReason = "manual-wrapup-tool-arc";
16947
+ targetProtectedTailStart = fenced;
16948
+ const snapped = snapWrapupBoundaryToUser({
16949
+ messages,
16950
+ index,
16951
+ candidate: targetProtectedTailStart,
16952
+ offset,
16953
+ triggerBudget: ctx.triggerBudget
16954
+ });
16955
+ if (snapped !== targetProtectedTailStart)
16956
+ boundaryReason = "manual-wrapup-user-snap";
16957
+ targetProtectedTailStart = snapped;
16958
+ const refenced = fenceWrapupBoundaryForToolArcs({
16959
+ candidate: targetProtectedTailStart,
16960
+ arcs,
16961
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
16962
+ });
16963
+ if (refenced !== targetProtectedTailStart)
16964
+ boundaryReason = "manual-wrapup-tool-arc";
16965
+ targetProtectedTailStart = refenced;
16966
+ }
16967
+ targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
16968
+ targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
16969
+ const target = deriveProtectedTailTokenTarget({
16970
+ contextLimit: ctx.contextLimit,
16971
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
16972
+ usagePercentage,
16973
+ triggerBudget: ctx.triggerBudget
16974
+ });
16975
+ const perRunCap = selectPerRunCap({
16976
+ usagePercentage,
16977
+ N: target.N,
16978
+ contextLimit: ctx.contextLimit,
16979
+ executeThresholdPercentage: ctx.executeThresholdPercentage
16980
+ });
16981
+ let headDiagnostics;
16982
+ const head = applyHeadCap({
16983
+ observeDiagnostics: (value) => {
16984
+ headDiagnostics = value;
16985
+ },
16986
+ index: summaryRemovedIndex,
16987
+ protectedTailStart: targetProtectedTailStart,
16988
+ offset,
16989
+ arcs: buildToolArcs(messages),
16990
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
16991
+ capTokens: perRunCap,
16992
+ recentOpenArcCutoff: targetProtectedTailStart
16993
+ });
16994
+ const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
16995
+ const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
16996
+ const snapshot = {
16997
+ sessionId: ctx.sessionId,
16998
+ mode: "manual-wrapup",
16999
+ offset,
17000
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
17001
+ offsetMessageId: boundaryMessageId(index, offset),
17002
+ protectedTailStart: targetProtectedTailStart,
17003
+ protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
17004
+ eligibleEndOrdinal,
17005
+ eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
17006
+ rawMessageCountAtTrigger: rawMessageCount,
17007
+ rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
17008
+ N: keep,
17009
+ usagePercentage,
17010
+ usageInputTokens,
17011
+ usageSource: ctx.usageSource,
17012
+ contextLimit: ctx.contextLimit,
17013
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
17014
+ triggerBudget: ctx.triggerBudget,
17015
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
17016
+ migrationFloorActive: ctx.migrationFloorActive,
17017
+ emergencyTailScale: ctx.emergencyTailScale,
17018
+ providerShapeVersion: ctx.providerShapeVersion,
17019
+ cacheNamespace: ctx.cacheNamespace,
17020
+ createdAt,
17021
+ rawRangeFingerprint,
17022
+ trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
17023
+ summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
17024
+ oversizeAtomicUnit: head.oversizeAtomicUnit,
17025
+ boundaryReason,
17026
+ diagnostics: boundaryDiagnostics({
17027
+ tailTarget: target,
17028
+ usable: target.usable,
17029
+ usagePercentage,
17030
+ N: target.N,
17031
+ triggerBudget: ctx.triggerBudget,
17032
+ capTokens: perRunCap,
17033
+ sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
17034
+ protectedTailStart: targetProtectedTailStart,
17035
+ livePromptFloor: {
17036
+ ordinal: null,
17037
+ from: targetProtectedTailStart,
17038
+ to: targetProtectedTailStart
17039
+ },
17040
+ head: headDiagnostics
17041
+ })
17042
+ };
16596
17043
  return {
16597
- isFirstServe: warm && args.isLiveTail && firstServe,
16598
- prefixRewriteCoversAnchor: args.anchorMessageId !== null && args.prefixRewriteCoversAnchor
17044
+ snapshot,
17045
+ rawMessagesAboveLastCompartment,
17046
+ anchorRawMessageCount,
17047
+ targetProtectedTailStart,
17048
+ targetEligibleEndOrdinal: targetProtectedTailStart
16599
17049
  };
16600
17050
  }
16601
- var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
16602
- var lastDeliveredAt = new Map;
16603
- function isCoolingDown(deliveredAt, now) {
16604
- return now - deliveredAt < NOTE_NUDGE_COOLDOWN_MS;
16605
- }
16606
- function getNoteNudgeDeliveredAt(sessionId) {
16607
- const deliveredAt = lastDeliveredAt.get(sessionId);
16608
- if (deliveredAt === undefined)
16609
- return 0;
16610
- if (!isCoolingDown(deliveredAt, Date.now())) {
16611
- lastDeliveredAt.delete(sessionId);
16612
- return 0;
16613
- }
16614
- return deliveredAt;
17051
+ function getRawHistoryEligibility(db, sessionId) {
17052
+ const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
17053
+ const offset = Math.max(1, lastCompartmentEnd + 1);
17054
+ const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
17055
+ const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
17056
+ return {
17057
+ lastCompartmentEnd,
17058
+ offset,
17059
+ rawMessageCount,
17060
+ hasRawBeyondLastCompartment: rawMessageCount >= offset
17061
+ };
16615
17062
  }
16616
- function recordNoteNudgeDeliveryTime(sessionId) {
16617
- const now = Date.now();
16618
- for (const [otherSessionId, deliveredAt] of lastDeliveredAt) {
16619
- if (!isCoolingDown(deliveredAt, now))
16620
- lastDeliveredAt.delete(otherSessionId);
17063
+ function hasRunnableCompartmentWindow(snapshot) {
17064
+ if (snapshot.offset >= snapshot.protectedTailStart)
17065
+ return false;
17066
+ if (snapshot.eligibleEndOrdinal <= snapshot.offset)
17067
+ return false;
17068
+ if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
17069
+ return true;
17070
+ const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
17071
+ if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
17072
+ return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
16621
17073
  }
16622
- lastDeliveredAt.set(sessionId, now);
16623
- }
16624
- function onNoteTrigger(db, sessionId, trigger) {
16625
- let transactionStartedAt = 0;
16626
- db.transaction(() => {
16627
- transactionStartedAt = performance.now();
16628
- setPersistedNoteNudgeTrigger(db, sessionId);
16629
- }).immediate();
16630
- logSlowWriteTransaction("note_nudge_trigger", transactionStartedAt);
16631
- sessionLog2(sessionId, `note-nudge: trigger fired (${trigger}), triggerPending=true`);
17074
+ return snapshot.eligibleEndOrdinal > snapshot.offset;
16632
17075
  }
16633
- function peekNoteNudgeText(db, sessionId, currentUserMessageId, projectIdentity, noteReadStillVisible, eligibility) {
16634
- const state = getPersistedNoteNudge(db, sessionId);
16635
- if (!state.triggerPending)
16636
- return null;
16637
- if (eligibility && !eligibility.isFirstServe && !eligibility.prefixRewriteCoversAnchor) {
16638
- sessionLog2(sessionId, "note-nudge: deferring — user already served or first serve unproven");
16639
- return null;
16640
- }
16641
- if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
16642
- setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
16643
- state.triggerMessageId = currentUserMessageId;
17076
+ function boundarySnapshotIdChecks(snapshot) {
17077
+ const checks = [
17078
+ [snapshot.offset, snapshot.offsetMessageId, "offset"],
17079
+ [snapshot.rawMessageCountAtTrigger, snapshot.rawLastMessageIdAtTrigger, "last"]
17080
+ ];
17081
+ if (snapshot.protectedTailStart <= snapshot.rawMessageCountAtTrigger) {
17082
+ checks.push([
17083
+ snapshot.protectedTailStart,
17084
+ snapshot.protectedTailStartMessageId,
17085
+ "protectedTailStart"
17086
+ ]);
16644
17087
  }
16645
- if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
16646
- sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
16647
- return null;
17088
+ if (snapshot.eligibleEndOrdinal > snapshot.offset) {
17089
+ checks.push([
17090
+ snapshot.eligibleEndOrdinal - 1,
17091
+ snapshot.eligibleEndMessageId,
17092
+ "eligibleEnd"
17093
+ ]);
16648
17094
  }
16649
- const deliveredAt = getNoteNudgeDeliveredAt(sessionId);
16650
- if (deliveredAt > 0) {
16651
- sessionLog2(sessionId, `note-nudge: suppressing — last delivered ${Math.round((Date.now() - deliveredAt) / 1000)}s ago (cooldown ${NOTE_NUDGE_COOLDOWN_MS / 60000}m)`);
16652
- clearNoteNudgeTriggerOnly(db, sessionId);
16653
- return null;
17095
+ return checks;
17096
+ }
17097
+ function validateBoundarySnapshot(args) {
17098
+ const { snapshot, exactIds } = args;
17099
+ if (args.currentContextLimit && args.currentContextLimit !== snapshot.contextLimit) {
17100
+ return {
17101
+ ok: false,
17102
+ reason: "model_or_limit_changed",
17103
+ detail: `context limit changed from ${snapshot.contextLimit} to ${args.currentContextLimit}`
17104
+ };
16654
17105
  }
16655
- const notes = getSessionNotes(db, sessionId);
16656
- const readySmartNotes = projectIdentity ? getReadySmartNotes(db, projectIdentity) : [];
16657
- const totalCount = notes.length + readySmartNotes.length;
16658
- if (totalCount === 0) {
16659
- sessionLog2(sessionId, "note-nudge: triggerPending but no notes found, skipping");
16660
- clearNoteNudgeTriggerOnly(db, sessionId);
16661
- return null;
17106
+ const currentRawMessageCount = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
17107
+ if (snapshot.rawMessageCountAtTrigger > currentRawMessageCount) {
17108
+ return { ok: false, reason: "stale_snapshot", detail: "raw message count shrank" };
16662
17109
  }
16663
- const lastReadAt = getNoteLastReadAt(db, sessionId);
16664
- if (lastReadAt > 0 && noteReadStillVisible) {
16665
- const mostRecentNoteActivity = maxNoteActivityTime([...notes, ...readySmartNotes]);
16666
- if (mostRecentNoteActivity > 0 && lastReadAt > mostRecentNoteActivity) {
16667
- sessionLog2(sessionId, `note-nudge: suppressing — agent ran ctx_note(read) at ${new Date(lastReadAt).toISOString()} and the read is still visible; no new notes since ${new Date(mostRecentNoteActivity).toISOString()}`);
16668
- clearNoteNudgeTriggerOnly(db, sessionId);
16669
- return null;
17110
+ const idAt = (ordinal) => {
17111
+ if (!exactIds)
17112
+ return readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, ordinal, ordinal).keys().next().value ?? null;
17113
+ const id = exactIds.get(ordinal);
17114
+ if (id === undefined)
17115
+ throw new Error(`boundary validation was given no exact id for ordinal ${ordinal}`);
17116
+ return id;
17117
+ };
17118
+ for (const [ordinal, expected, label] of boundarySnapshotIdChecks(snapshot)) {
17119
+ if (expected !== idAt(ordinal)) {
17120
+ return {
17121
+ ok: false,
17122
+ reason: "stale_snapshot",
17123
+ detail: `${label} ordinal ${ordinal} id changed`
17124
+ };
16670
17125
  }
16671
17126
  }
16672
- const failureNotice = notes.find((note) => /^Smart note #\d+ cannot be checked\.\nCondition: /.test(note.content));
16673
- if (failureNotice) {
16674
- const reason = failureNotice.content.split(`
16675
- Reason: `)[1]?.split(`
16676
- `)[0] ?? "check unavailable";
16677
- return `Smart note check unavailable: ${reason}. Read ctx_note #${failureNotice.id} for the condition and repair instructions; this is NOT evidence that the condition is met.`;
16678
- }
16679
- const parts = [];
16680
- if (notes.length > 0) {
16681
- parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
16682
- }
16683
- if (readySmartNotes.length > 0) {
16684
- parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
16685
- }
16686
- sessionLog2(sessionId, `note-nudge: delivering nudge for ${parts.join(" and ")}`);
16687
- return formatNoteNudge({
16688
- readyCount: readySmartNotes.length,
16689
- activeCount: notes.length,
16690
- oldestActiveTouchedAt: oldestTouchedAt(notes),
16691
- shown: pickNudgeNote({ db, sessionId, activeNotes: notes, readySmartNotes }),
16692
- nowMs: Date.now()
16693
- });
16694
- }
16695
- function oldestTouchedAt(notes) {
16696
- return notes.reduce((min, note) => {
16697
- const touchedAt = noteTouchedAt(note);
16698
- return min === null || touchedAt < min ? touchedAt : min;
16699
- }, null);
16700
- }
16701
- function pickNudgeNote(args) {
16702
- const pool = args.readySmartNotes.length > 0 ? [...args.readySmartNotes].sort((left, right) => left.id - right.id) : [...args.activeNotes].sort((left, right) => left.id - right.id);
16703
- if (pool.length === 0)
16704
- return null;
16705
- const counter = getNoteNudgeAnchors(args.db, args.sessionId).length;
16706
- return pool[noteNudgePickIndex(args.sessionId, counter, pool.length)] ?? null;
16707
- }
16708
- function maxNoteActivityTime(notes) {
16709
- let max = 0;
16710
- for (const note of notes) {
16711
- if (note.updatedAt > max)
16712
- max = note.updatedAt;
16713
- if (note.readyAt !== null && note.readyAt > max)
16714
- max = note.readyAt;
16715
- }
16716
- return max;
16717
- }
16718
- function markNoteNudgeDelivered(db, sessionId, text, messageId) {
16719
- if (!messageId) {
16720
- clearNoteNudgeTriggerAndCooldown(db, sessionId);
16721
- sessionLog2(sessionId, "note-nudge: marked delivered without anchor");
16722
- return { ok: true, kind: "already-present" };
17127
+ const expectedOffset = Math.max(1, getLastCompartmentEndMessage(args.db, snapshot.sessionId) + 1);
17128
+ if (expectedOffset !== snapshot.offset) {
17129
+ return {
17130
+ ok: false,
17131
+ reason: "stale_snapshot",
17132
+ detail: `last compartment moved: offset ${snapshot.offset} -> ${expectedOffset}`
17133
+ };
16723
17134
  }
16724
- const outcome = db.transaction(() => {
16725
- const delivered = deliverNoteNudgeAtomic(db, sessionId, messageId, text);
16726
- const nudgeText = text?.replace(/^\s*<instruction name="deferred_notes">/, "") ?? "";
16727
- const noticeId = nudgeText.match(/^Smart note check unavailable: [\s\S]*Read ctx_note #(\d+) for the condition/);
16728
- if (delivered.ok && noticeId) {
16729
- db.prepare(`UPDATE notes SET status = 'dismissed', updated_at = ?
16730
- WHERE id = ? AND type = 'session' AND session_id = ?
16731
- AND content LIKE 'Smart note #% cannot be checked.%'`).run(Date.now(), Number(noticeId[1]), sessionId);
16732
- }
16733
- return delivered;
16734
- }).immediate();
16735
- if (outcome.ok) {
16736
- recordNoteNudgeDeliveryTime(sessionId);
17135
+ const fingerprintMessages = readRawSessionMessageRange2(snapshot.sessionId, snapshot.offset, snapshot.eligibleEndOrdinal - 1);
17136
+ const fingerprint = computeRawRangeFingerprint(fingerprintMessages, snapshot.offset, snapshot.eligibleEndOrdinal);
17137
+ if (fingerprint !== snapshot.rawRangeFingerprint) {
17138
+ return { ok: false, reason: "stale_snapshot", detail: "raw range fingerprint changed" };
16737
17139
  }
16738
- sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
16739
- return outcome;
17140
+ return { ok: true };
16740
17141
  }
16741
- function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
16742
- db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
16743
- lastDeliveredAt.delete(sessionId);
17142
+ function recordHighPressureNoEligibleHead(db, snapshot) {
17143
+ const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
17144
+ if (snapshot.usagePercentage < forceMaterializationPercentage && !snapshot.emergencyTailScale) {
17145
+ return 0;
17146
+ }
17147
+ return recordProtectedTailNoEligibleHead(db, snapshot.sessionId);
16744
17148
  }
16745
- function resetNoteNudgeCooldownOnly(sessionId) {
16746
- lastDeliveredAt.delete(sessionId);
17149
+
17150
+ // src/hooks/magic-context/historian-drain-gate.ts
17151
+ var loggedWindows = new WeakMap;
17152
+ function reportProviderRecoveryDrainSkip(sessionId) {
17153
+ let logged = false;
17154
+ return (skip) => {
17155
+ if (logged)
17156
+ return;
17157
+ logged = true;
17158
+ sessionLog2(sessionId, `historian skip during provider recovery: ${skip.reason}; next eligible at ${new Date(skip.nextEligibleAt).toISOString()}`);
17159
+ };
16747
17160
  }
16748
- function clearNoteNudgeTriggerOnly(db, sessionId) {
16749
- db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
17161
+ function resolveHistorianDrainBudgetGeometry(args) {
17162
+ const target = deriveProtectedTailTokenTarget(args);
17163
+ return { usable: target.usable, perRunCap: selectPerRunCap({ ...args, N: target.N }) };
16750
17164
  }
16751
-
16752
- // src/hooks/magic-context/persist-filtered-noise.ts
16753
- function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
16754
- const rows = chunk.filteredNoiseLines ?? [];
16755
- const start = chunk.startIndex;
16756
- if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
16757
- return false;
16758
- const endId = rows[rows.length - 1].messageId;
16759
- if (!hasRawSessionMessageById2(sessionId, endId)) {
16760
- sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
17165
+ function isHistorianDrainBudgetSpent(args) {
17166
+ const usagePercentage = args.recoveryUsagePercentage ?? args.usagePercentage;
17167
+ const state = getProtectedTailDrainBudgetSkip({
17168
+ ...args,
17169
+ usagePercentage,
17170
+ providerRecovery: args.recoveryUsagePercentage !== undefined,
17171
+ ...resolveHistorianDrainBudgetGeometry({ ...args, usagePercentage })
17172
+ });
17173
+ if (!state)
16761
17174
  return false;
16762
- }
16763
- const saved = db.transaction(() => {
16764
- const prior = getCompartments(db, sessionId);
16765
- const last = prior.at(-1);
16766
- if ((last?.endMessage ?? 0) + 1 !== start)
16767
- return false;
16768
- appendCompartments(db, sessionId, [
16769
- {
16770
- sequence: (last?.sequence ?? -1) + 1,
16771
- startMessage: start,
16772
- endMessage: eligibleEnd - 1,
16773
- startMessageId: rows[0].messageId,
16774
- endMessageId: rows[rows.length - 1].messageId,
16775
- title: "",
16776
- content: "",
16777
- p1: "",
16778
- p2: "",
16779
- p3: "",
16780
- p4: "",
16781
- episodeType: "filtered-noise",
16782
- importance: 1
16783
- }
16784
- ]);
17175
+ if (args.reportSkip) {
17176
+ args.reportSkip(state);
16785
17177
  return true;
16786
- }).immediate();
16787
- if (saved)
16788
- sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
16789
- return saved;
16790
- }
16791
-
16792
- // src/hooks/magic-context/file-token-coverage.ts
16793
- function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
16794
- const filesByMessage = new Map;
16795
- for (const message of messages) {
16796
- const count = message.parts.filter(isFilePart).length;
16797
- if (count > 0 && totals.has(message.id))
16798
- filesByMessage.set(message.id, count);
16799
17178
  }
16800
- if (filesByMessage.size === 0)
16801
- return totals;
16802
- const rows = db.prepare(`
16803
- SELECT o.value AS owner, COUNT(t.id) AS count
16804
- FROM json_each(?) o LEFT JOIN tags t
16805
- ON t.session_id = ? AND t.type = 'file'
16806
- AND t.message_id >= o.value || ':file'
16807
- AND t.message_id < o.value || ':file;'
16808
- GROUP BY o.value
16809
- `).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
16810
- for (const row of rows) {
16811
- if (row.count < (filesByMessage.get(row.owner) ?? 0))
16812
- totals.delete(row.owner);
17179
+ let windows = loggedWindows.get(args.db);
17180
+ if (!windows) {
17181
+ windows = new Map;
17182
+ loggedWindows.set(args.db, windows);
16813
17183
  }
16814
- return totals;
17184
+ if (windows.get(args.sessionId) !== state.resetsAt) {
17185
+ windows.set(args.sessionId, state.resetsAt);
17186
+ sessionLog2(args.sessionId, `historian skip: internal drain budget spent (${state.spentTokens}/${state.limitTokens} tokens); next eligible at ${new Date(state.nextEligibleAt).toISOString()}`);
17187
+ }
17188
+ return true;
16815
17189
  }
16816
17190
 
16817
- // src/hooks/magic-context/protected-tail-boundary.ts
16818
- function describeBoundaryDiagnostics(snapshot) {
16819
- return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
17191
+ // src/hooks/magic-context/historian-failure-report.ts
17192
+ var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
17193
+ var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
17194
+ var ACTIONS = "What to do: run /ctx-status for detail; change the historian model or its fallback models in magic-context.jsonc (user or project config); or run /ctx-recomp to rebuild the history.";
17195
+ var REFUSAL_ERROR_MAX_CHARS = 500;
17196
+ var WARNING_ERROR_MAX_CHARS = 200;
17197
+ function readHistorianFailureStreak(db, sessionId, options = {}) {
17198
+ const state = getHistorianFailureState(db, sessionId);
17199
+ const count = state.failureCount;
17200
+ let since = null;
17201
+ if (count > 0) {
17202
+ const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
17203
+ if (recorded <= 0) {
17204
+ since = state.lastFailureAt;
17205
+ } else {
17206
+ const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
17207
+ since = times.length === recorded ? times[recorded - 1] ?? null : null;
17208
+ }
17209
+ }
17210
+ return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
16820
17211
  }
16821
- function boundaryDiagnostics(args) {
16822
- return {
16823
- ...args,
16824
- capTier: args.usagePercentage >= 95 ? "95" : args.usagePercentage >= 80 ? "80" : "normal",
16825
- drainBudget: "not-reserved; does-not-size-cap"
16826
- };
17212
+ function formatHistorianClockTime(at, now = Date.now()) {
17213
+ const date = new Date(at);
17214
+ const pad = (value) => String(value).padStart(2, "0");
17215
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
17216
+ const today = new Date(now);
17217
+ const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
17218
+ return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
16827
17219
  }
16828
- var ALPHA = 0.3;
16829
- var FLOOR_RATIO = 0.08;
16830
- var FLOOR_MIN = 2000;
16831
- var FLOOR_MAX = 12000;
16832
- var ABS_CAP = 96000;
16833
- var MAX_USABLE_RATIO = 0.4;
16834
- var RESERVED_HEADROOM_MIN = 1000;
16835
- var RESERVED_HEADROOM_RATIO = 0.02;
16836
- var NON_EMERGENCY_MAX_CAP = 250000;
16837
- var FORCE80_MAX_CAP = 500000;
16838
- var FORCE95_MAX_CAP = 750000;
16839
- var NORMAL_HYSTERESIS_TOKENS = 256;
16840
- var RECOVERY_NO_HEAD_LIMIT = 2;
16841
- function clampPercentage(value) {
16842
- if (!Number.isFinite(value))
16843
- return 0;
16844
- return Math.max(0, Math.min(100, value));
17220
+ function formatHistorianSeconds(ms) {
17221
+ const seconds = Math.max(0, ms) / 1000;
17222
+ return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
16845
17223
  }
16846
- function clampOrdinal(value, rawMessageCount) {
16847
- return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
17224
+ function singleLine(text) {
17225
+ return text.replace(/\s+/g, " ").trim();
16848
17226
  }
16849
- function deriveProtectedTailTokenTarget(args) {
16850
- const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
16851
- const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
16852
- const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
16853
- const usage = clampPercentage(args.usagePercentage);
16854
- const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
16855
- const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
16856
- const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
16857
- const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
16858
- const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
16859
- const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
16860
- const effectiveFloor = Math.min(floorN, ceilingN);
16861
- const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
16862
- return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
17227
+ function quoteError(error, maxChars) {
17228
+ const text = sanitizeDiagnosticText(singleLine(error));
17229
+ return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
16863
17230
  }
16864
- function nonEmergencyPerRunCap(usable, N) {
16865
- return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
17231
+ function endSentence(text) {
17232
+ return /[.!?]$/.test(text) ? text : `${text}.`;
16866
17233
  }
16867
- function force80PerRunCap(usable, N) {
16868
- return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
17234
+ function usageClause(usagePercentage) {
17235
+ return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
16869
17236
  }
16870
- function force95PerRunCap(usable, N) {
16871
- return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
17237
+ function capitalize(text) {
17238
+ return text.charAt(0).toUpperCase() + text.slice(1);
16872
17239
  }
16873
- function selectPerRunCap(snapshot) {
16874
- const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
16875
- if (snapshot.usagePercentage >= 95)
16876
- return force95PerRunCap(usable, snapshot.N);
16877
- if (snapshot.usagePercentage >= 80)
16878
- return force80PerRunCap(usable, snapshot.N);
16879
- return nonEmergencyPerRunCap(usable, snapshot.N);
17240
+ function chunkLabel(chunk) {
17241
+ return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
16880
17242
  }
16881
- function boundaryMessageId(index, ordinal) {
16882
- if (ordinal < 1 || ordinal > index.rawMessageCount)
17243
+ function streakSentence(failures, now) {
17244
+ if (failures.count <= 0)
16883
17245
  return null;
16884
- return index.messageIdAtOrdinal(ordinal);
17246
+ const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
17247
+ return `Summary runs failed in a row: ${failures.count}${since}.`;
16885
17248
  }
16886
- function isSemanticBoundaryCandidate(messageParts, role) {
16887
- if (role === "user" && hasMeaningfulUserText2(messageParts))
16888
- return true;
16889
- if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
16890
- return true;
16891
- }
16892
- return false;
17249
+ function failureBelongsToRun(failures, run) {
17250
+ return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
16893
17251
  }
16894
- function semanticSnapBoundary(args) {
16895
- const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
16896
- let snapped = candidate;
16897
- for (const message of messages) {
16898
- if (message.ordinal > candidate)
16899
- break;
16900
- if (message.ordinal < lastCompartmentEndOrdinal + 1)
16901
- continue;
16902
- if (!isSemanticBoundaryCandidate(message.parts, message.role))
16903
- continue;
16904
- snapped = message.ordinal;
16905
- }
16906
- if (snapped === candidate)
16907
- return candidate;
16908
- const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
16909
- if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
16910
- return candidate;
16911
- const snappedMessage = messages.find((message) => message.ordinal === snapped);
16912
- if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
16913
- return candidate;
17252
+ function describeHistorianJoinRefusal(input) {
17253
+ const now = input.now ?? Date.now();
17254
+ const { run, failures } = input;
17255
+ const sentences = [
17256
+ `This turn was not sent: ${usageClause(input.usagePercentage)}, and Magic Context waited ${formatHistorianSeconds(input.waitedMs)} s for a history summary that did not finish in time.`
17257
+ ];
17258
+ const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
17259
+ const ownFailure = failureBelongsToRun(failures, run);
17260
+ const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
17261
+ if (ownFailure) {
17262
+ sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
17263
+ } else if (run && run.endedAt === undefined) {
17264
+ sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
17265
+ } else if (run) {
17266
+ sentences.push(`${subject} finished after the wait ended.`);
16914
17267
  }
16915
- return snapped;
16916
- }
16917
- function snapWrapupBoundaryToUser(args) {
16918
- const { messages, index, candidate, offset, triggerBudget } = args;
16919
- if (candidate <= offset)
16920
- return candidate;
16921
- const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
16922
- for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
16923
- const message = messages.find((m) => m.ordinal === ordinal);
16924
- if (!message)
16925
- continue;
16926
- if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
16927
- continue;
16928
- const extraTokens = index.rangeTokens(ordinal, candidate);
16929
- if (extraTokens <= snapTokenLimit)
16930
- return ordinal;
16931
- return candidate;
17268
+ if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
17269
+ sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
16932
17270
  }
16933
- return candidate;
17271
+ const streak = streakSentence(failures, now);
17272
+ if (streak)
17273
+ sentences.push(streak);
17274
+ sentences.push(ACTIONS);
17275
+ return sentences.join(" ");
16934
17276
  }
16935
- function fenceWrapupBoundaryForToolArcs(args) {
16936
- let boundary = args.candidate;
16937
- const maxPasses = args.arcs.length + 1;
16938
- for (let pass = 0;pass < maxPasses; pass += 1) {
16939
- let next = boundary;
16940
- for (const arc of args.arcs) {
16941
- if (arc.resOrdinal === null) {
16942
- continue;
16943
- }
16944
- if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
16945
- next = arc.invOrdinal;
16946
- }
16947
- }
16948
- if (next === boundary)
16949
- return boundary;
16950
- boundary = next;
17277
+ function describeRepeatedHistorianFailures(input) {
17278
+ const now = input.now ?? Date.now();
17279
+ const { failures } = input;
17280
+ const facts = [
17281
+ streakSentence(failures, now) ?? "Summary runs are failing.",
17282
+ ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
17283
+ ...failures.lastError ? [
17284
+ endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
17285
+ ] : [],
17286
+ `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
17287
+ ];
17288
+ return [
17289
+ "## Magic Context — History summaries keep failing",
17290
+ "",
17291
+ facts.join(" "),
17292
+ "",
17293
+ ACTIONS
17294
+ ].join(`
17295
+ `);
17296
+ }
17297
+ var repeatedFailureWarnings = new Map;
17298
+ function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
17299
+ const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
17300
+ if (failureCount < step || failureCount % step !== 0)
17301
+ return false;
17302
+ const last = repeatedFailureWarnings.get(sessionId);
17303
+ if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
17304
+ return false;
16951
17305
  }
16952
- return boundary;
17306
+ repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
17307
+ return true;
16953
17308
  }
16954
- function applyHeadCap(args) {
16955
- const {
16956
- index,
16957
- protectedTailStart,
16958
- offset,
16959
- arcs,
16960
- lastCompartmentEndOrdinal,
16961
- capTokens,
16962
- recentOpenArcCutoff
16963
- } = args;
16964
- const diagnostics = {
16965
- offset,
16966
- capEnd: offset,
16967
- capTokenSum: 0,
16968
- completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
16969
- oversizeAdmission: { from: offset, to: offset },
16970
- openArcClamp: { from: offset, to: offset },
16971
- completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
16972
- eligibleEnd: offset
16973
- };
16974
- if (offset >= protectedTailStart) {
16975
- args.observeDiagnostics?.(diagnostics);
16976
- return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
17309
+ function takeRepeatedHistorianFailureWarning(input) {
17310
+ const now = input.now ?? Date.now();
17311
+ if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
17312
+ return null;
16977
17313
  }
16978
- let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
16979
- diagnostics.capEnd = end;
16980
- diagnostics.capTokenSum = index.rangeTokens(offset, end);
16981
- let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
16982
- let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
16983
- diagnostics.completedFence.arcs = component.map((arc) => ({
16984
- assistant: arc.invocation,
16985
- result: arc.result
16986
- }));
16987
- diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
17314
+ const failures = readHistorianFailureStreak(input.db, input.sessionId, {
17315
+ unrecordedFailures: input.unrecordedFailures
16988
17316
  });
16989
- diagnostics.completedFence.from = end;
16990
- diagnostics.completedFence.to = completedFence;
16991
- diagnostics.oversizeAdmission.from = completedFence;
16992
- if (completedFence <= offset && end > offset) {
16993
- const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
16994
- if (afterFirstArc <= protectedTailStart)
16995
- completedFence = afterFirstArc;
16996
- }
16997
- diagnostics.oversizeAdmission.to = completedFence;
16998
- if (completedFence > end) {
16999
- end = Math.min(protectedTailStart, completedFence);
17000
- if (index.rangeTokens(offset, end) > capTokens)
17001
- oversizeAtomicUnit = true;
17002
- } else {
17003
- end = completedFence;
17004
- }
17005
- diagnostics.openArcClamp.from = end;
17006
- for (const arc of arcs) {
17007
- const resOrdinal = arc.resOrdinal;
17008
- if (resOrdinal === null) {
17009
- if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
17010
- end = Math.min(end, arc.invOrdinal);
17011
- }
17012
- }
17013
- }
17014
- diagnostics.openArcClamp.to = end;
17015
- diagnostics.completedRefence.from = end;
17016
- end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
17017
- diagnostics.completedRefence.arcs = component.map((arc) => ({
17018
- assistant: arc.invocation,
17019
- result: arc.result
17020
- }));
17021
- diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
17317
+ return describeRepeatedHistorianFailures({
17318
+ chunk: input.chunk,
17319
+ failures: { ...failures, count: input.failureCount },
17320
+ usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
17321
+ now
17022
17322
  });
17023
- diagnostics.completedRefence.to = end;
17024
- if (end > protectedTailStart)
17025
- end = offset;
17026
- diagnostics.eligibleEnd = end <= offset ? offset : end;
17027
- args.observeDiagnostics?.(diagnostics);
17028
- if (end <= offset && offset < protectedTailStart) {
17029
- return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
17030
- }
17031
- return { eligibleEndOrdinal: end, oversizeAtomicUnit };
17032
17323
  }
17033
- function resolveProtectedTailBoundary(ctx) {
17034
- const createdAt = ctx.createdAt ?? Date.now();
17035
- const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
17036
- const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
17037
- const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
17038
- const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
17039
- const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
17040
- const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
17041
- const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
17042
- providerShapeVersion: ctx.providerShapeVersion,
17043
- cacheNamespace: ctx.cacheNamespace,
17044
- calibration: ctx.calibration,
17045
- absoluteMessageCount,
17046
- storedTotalForMessage: storedTotals ? (m) => {
17047
- const v = storedTotals.get(m.id);
17048
- return v === undefined ? null : v;
17049
- } : undefined
17050
- });
17051
- const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
17052
- providerShapeVersion: ctx.providerShapeVersion,
17053
- cacheNamespace: ctx.cacheNamespace,
17054
- calibration: ctx.calibration,
17055
- absoluteMessageCount,
17056
- measure: "summary-removed",
17057
- storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
17058
- });
17059
- const rawMessageCount = index.rawMessageCount;
17060
- const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
17061
- const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
17062
- if (rawMessageCount === 0) {
17063
- return {
17064
- sessionId: ctx.sessionId,
17065
- mode: ctx.mode,
17066
- offset,
17067
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
17068
- offsetMessageId: null,
17069
- protectedTailStart: 1,
17070
- protectedTailStartMessageId: null,
17071
- eligibleEndOrdinal: 1,
17072
- eligibleEndMessageId: null,
17073
- rawMessageCountAtTrigger: 0,
17074
- rawLastMessageIdAtTrigger: null,
17075
- N: 0,
17076
- usagePercentage,
17077
- usageInputTokens,
17078
- usageSource: ctx.usageSource,
17079
- contextLimit: ctx.contextLimit,
17080
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17081
- triggerBudget: ctx.triggerBudget,
17082
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
17083
- migrationFloorActive: ctx.migrationFloorActive,
17084
- emergencyTailScale: ctx.emergencyTailScale,
17085
- recovery: ctx.recovery,
17086
- providerShapeVersion: ctx.providerShapeVersion,
17087
- cacheNamespace: ctx.cacheNamespace,
17088
- createdAt,
17089
- rawRangeFingerprint: "",
17090
- trueRawEligibleTokens: 0,
17091
- summaryRemovedEligibleTokens: 0,
17092
- oversizeAtomicUnit: false,
17093
- boundaryReason: "empty-session"
17094
- };
17095
- }
17096
- if (ctx.mode === "manual-full-recomp") {
17097
- const arcs = buildToolArcs(messages);
17098
- const recompTarget = deriveProtectedTailTokenTarget({
17099
- contextLimit: ctx.contextLimit,
17100
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17101
- usagePercentage: 0,
17102
- triggerBudget: ctx.triggerBudget
17103
- });
17104
- const recentOpenArcCutoff = index.findSuffixStartForTokens(recompTarget.N);
17105
- const firstOpenArc = arcs.find((arc) => arc.resOrdinal === null && arc.invOrdinal >= offset && arc.invOrdinal >= recentOpenArcCutoff);
17106
- const protectedTailStart = firstOpenArc?.invOrdinal ?? rawMessageCount + 1;
17107
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, protectedTailStart);
17108
- return {
17109
- sessionId: ctx.sessionId,
17110
- mode: ctx.mode,
17111
- offset,
17112
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
17113
- offsetMessageId: boundaryMessageId(index, offset),
17114
- protectedTailStart,
17115
- protectedTailStartMessageId: null,
17116
- eligibleEndOrdinal: protectedTailStart,
17117
- eligibleEndMessageId: boundaryMessageId(index, protectedTailStart - 1),
17118
- rawMessageCountAtTrigger: rawMessageCount,
17119
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
17120
- N: 0,
17121
- usagePercentage: 0,
17122
- usageInputTokens: 0,
17123
- usageSource: "manual-none",
17124
- contextLimit: ctx.contextLimit,
17125
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17126
- triggerBudget: ctx.triggerBudget,
17127
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
17128
- migrationFloorActive: false,
17129
- emergencyTailScale: ctx.emergencyTailScale,
17130
- recovery: ctx.recovery,
17131
- providerShapeVersion: ctx.providerShapeVersion,
17132
- cacheNamespace: ctx.cacheNamespace,
17133
- createdAt,
17134
- rawRangeFingerprint,
17135
- trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
17136
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
17137
- oversizeAtomicUnit: false,
17138
- boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
17139
- };
17140
- }
17141
- const target = deriveProtectedTailTokenTarget({
17142
- contextLimit: ctx.contextLimit,
17143
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17144
- usagePercentage,
17145
- triggerBudget: ctx.triggerBudget
17324
+
17325
+ // src/hooks/magic-context/historian-history-wait.ts
17326
+ var historyWaits = new Map;
17327
+ function newestMessageId(snapshot) {
17328
+ try {
17329
+ const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
17330
+ const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
17331
+ const newest = ids.keys().next().value;
17332
+ if (newest)
17333
+ return newest;
17334
+ } catch {}
17335
+ return snapshot.rawLastMessageIdAtTrigger;
17336
+ }
17337
+ function recoveryWindow(snapshot, percentage) {
17338
+ return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
17339
+ }
17340
+ function clearHistorianHistoryWait(sessionId) {
17341
+ historyWaits.delete(sessionId);
17342
+ }
17343
+ function recordHistorianNoProgress(snapshot, emergency = false) {
17344
+ const newest = newestMessageId(snapshot);
17345
+ if (!newest)
17346
+ return;
17347
+ const previous = historyWaits.get(snapshot.sessionId);
17348
+ const sameHistory = previous?.newestMessageId === newest;
17349
+ historyWaits.set(snapshot.sessionId, {
17350
+ newestMessageId: newest,
17351
+ recoveryAttempted: sameHistory && previous.recoveryAttempted || emergency || recoveryWindow(snapshot, snapshot.usagePercentage),
17352
+ floorLiftAttempted: sameHistory && previous.floorLiftAttempted || snapshot.liftLivePromptFloor === true
17146
17353
  });
17147
- const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
17148
- const arcs = buildToolArcs(messages);
17149
- let boundary = index.findSuffixStartForTokens(scaledN);
17150
- const recentOpenArcCutoff = boundary;
17151
- let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
17152
- const tokenAtBoundary = index.tokenForOrdinal(boundary);
17153
- if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
17154
- boundary += 1;
17155
- boundaryReason = "huge-message-exception";
17354
+ }
17355
+ function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
17356
+ const wait = historyWaits.get(snapshot.sessionId);
17357
+ if (!wait)
17358
+ return false;
17359
+ const newest = newestMessageId(snapshot);
17360
+ if (newest && newest !== wait.newestMessageId) {
17361
+ try {
17362
+ const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
17363
+ if (order === null || order > 0)
17364
+ return false;
17365
+ } catch {}
17156
17366
  }
17157
- boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
17158
- const snapped = semanticSnapBoundary({
17159
- messages,
17160
- index,
17161
- candidate: boundary,
17162
- scaledN,
17163
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
17164
- });
17165
- if (snapped !== boundary)
17166
- boundaryReason = "semantic-snap";
17167
- boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
17168
- let runtimeFloor = offset;
17169
- if (ctx.migrationFloorActive)
17170
- runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
17171
- let protectedTailStart = Math.max(boundary, runtimeFloor);
17172
- const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
17173
- const livePromptFloor = {
17174
- ordinal: null,
17175
- from: protectedTailStart,
17176
- to: protectedTailStart
17177
- };
17178
- if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
17179
- let lastMeaningfulUserOrdinal = 0;
17180
- for (let i = messages.length - 1;i >= 0; i--) {
17181
- const message = messages[i];
17182
- if (message.role !== "user")
17183
- continue;
17184
- if (!hasMeaningfulUserText2(message.parts))
17185
- continue;
17186
- lastMeaningfulUserOrdinal = message.ordinal;
17187
- break;
17188
- }
17189
- livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
17190
- livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
17191
- if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
17192
- protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
17367
+ const recovery = options.emergency || recoveryWindow(snapshot, options.usagePercentage ?? snapshot.usagePercentage);
17368
+ const floorLift = snapshot.liftLivePromptFloor === true;
17369
+ if (recovery && !wait.recoveryAttempted || floorLift && !wait.floorLiftAttempted) {
17370
+ if (options.claim) {
17371
+ wait.recoveryAttempted ||= recovery;
17372
+ wait.floorLiftAttempted ||= floorLift;
17193
17373
  }
17374
+ return false;
17194
17375
  }
17195
- livePromptFloor.to = protectedTailStart;
17196
- if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
17197
- protectedTailStart = offset;
17376
+ return true;
17377
+ }
17378
+
17379
+ // src/tools/ctx-note/render.ts
17380
+ var GLANCE_TITLE_MAX = 80;
17381
+ var NUDGE_TITLE_MAX = 60;
17382
+ var STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
17383
+ var EMPTY_READ_REPLY = `## Notes
17384
+
17385
+ No session notes or smart notes.`;
17386
+ function noteTouchedAt(note) {
17387
+ return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
17388
+ }
17389
+ function formatNoteAge(touchedAt, nowMs) {
17390
+ const elapsed = Math.max(0, nowMs - touchedAt);
17391
+ const minutes = Math.floor(elapsed / 60000);
17392
+ if (minutes < 60)
17393
+ return `${minutes}m`;
17394
+ const hours = Math.floor(elapsed / 3600000);
17395
+ if (hours < 24)
17396
+ return `${hours}h`;
17397
+ const days = Math.floor(elapsed / 86400000);
17398
+ if (days < 7)
17399
+ return `${days}d`;
17400
+ return `${Math.floor(days / 7)}w`;
17401
+ }
17402
+ function clipNoteTitle(content, max) {
17403
+ const firstLine = (content.split(`
17404
+ `, 1)[0] ?? "").trim();
17405
+ const characters = [...firstLine];
17406
+ if (characters.length <= max)
17407
+ return firstLine;
17408
+ return `${characters.slice(0, max).join("")}…`;
17409
+ }
17410
+ function formatGlanceRow(note, nowMs) {
17411
+ const touchedAt = noteTouchedAt(note);
17412
+ const markers = [];
17413
+ if (note.status !== "active")
17414
+ markers.push(note.status);
17415
+ if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
17416
+ markers.push(`parked: ${note.readyReason ?? "Condition can't be checked"}`);
17198
17417
  }
17199
- protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
17200
- protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
17201
- protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
17202
- const perRunCap = selectPerRunCap({
17203
- usagePercentage,
17204
- N: scaledN,
17205
- contextLimit: ctx.contextLimit,
17206
- executeThresholdPercentage: ctx.executeThresholdPercentage
17207
- });
17208
- let headDiagnostics;
17209
- const head = applyHeadCap({
17210
- observeDiagnostics: (value) => {
17211
- headDiagnostics = value;
17212
- },
17213
- index: summaryRemovedIndex,
17214
- protectedTailStart,
17215
- offset,
17216
- arcs,
17217
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
17218
- capTokens: perRunCap,
17219
- recentOpenArcCutoff
17220
- });
17221
- const servedEndOrdinal = retreatPastHostUnservedRows(messages, head.eligibleEndOrdinal, offset);
17222
- const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
17223
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
17224
- return {
17225
- sessionId: ctx.sessionId,
17226
- mode: ctx.mode,
17227
- offset,
17228
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
17229
- offsetMessageId: boundaryMessageId(index, offset),
17230
- protectedTailStart,
17231
- protectedTailStartMessageId: boundaryMessageId(index, protectedTailStart),
17232
- eligibleEndOrdinal,
17233
- eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
17234
- rawMessageCountAtTrigger: rawMessageCount,
17235
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
17236
- N: scaledN,
17237
- usagePercentage,
17238
- usageInputTokens,
17239
- usageSource: ctx.usageSource,
17240
- contextLimit: ctx.contextLimit,
17241
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17242
- triggerBudget: ctx.triggerBudget,
17243
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
17244
- migrationFloorActive: ctx.migrationFloorActive,
17245
- emergencyTailScale: ctx.emergencyTailScale,
17246
- recovery: ctx.recovery,
17247
- liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
17248
- providerShapeVersion: ctx.providerShapeVersion,
17249
- cacheNamespace: ctx.cacheNamespace,
17250
- createdAt,
17251
- rawRangeFingerprint,
17252
- trueRawEligibleTokens: index.rangeTokens(offset, eligibleEndOrdinal),
17253
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
17254
- oversizeAtomicUnit: head.oversizeAtomicUnit,
17255
- boundaryReason,
17256
- diagnostics: boundaryDiagnostics({
17257
- tailTarget: target,
17258
- usable: target.usable,
17259
- usagePercentage,
17260
- N: scaledN,
17261
- triggerBudget: ctx.triggerBudget,
17262
- capTokens: perRunCap,
17263
- sizeWalkStart: recentOpenArcCutoff,
17264
- protectedTailStart,
17265
- livePromptFloor,
17266
- head: headDiagnostics
17267
- })
17268
- };
17418
+ if (nowMs - touchedAt >= STALE_AFTER_MS)
17419
+ markers.push("stale");
17420
+ const suffix = markers.length > 0 ? ` · ${markers.join(" · ")}` : "";
17421
+ const title = clipNoteTitle(note.content, GLANCE_TITLE_MAX);
17422
+ return `#${note.id} · ${formatNoteAge(touchedAt, nowMs)} · ${title}${suffix}`;
17423
+ }
17424
+ function newestFirst(left, right) {
17425
+ return right.updatedAt - left.updatedAt || right.id - left.id;
17426
+ }
17427
+ function orderGlanceNotes(notes) {
17428
+ const ready = notes.filter((note) => note.status === "ready").sort(newestFirst);
17429
+ const pending = notes.filter((note) => note.status === "pending").sort(newestFirst);
17430
+ const rest = notes.filter((note) => note.status !== "ready" && note.status !== "pending").sort(newestFirst);
17431
+ return [...ready, ...pending, ...rest];
17432
+ }
17433
+ function renderGlance(notes, options) {
17434
+ const ordered = orderGlanceNotes(notes);
17435
+ const page = ordered.slice(options.offset, options.offset + options.limit);
17436
+ if (page.length === 0)
17437
+ return EMPTY_READ_REPLY;
17438
+ const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
17439
+ `);
17440
+ const remaining = ordered.length - options.offset - page.length;
17441
+ const footer = remaining > 0 ? `
17442
+
17443
+ Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
17444
+ return `## Notes
17445
+
17446
+ ${rows}${footer}`;
17447
+ }
17448
+ function formatNoteBody(note, nowMs) {
17449
+ const touchedAt = noteTouchedAt(note);
17450
+ const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
17451
+ const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
17452
+ if (note.type !== "smart")
17453
+ return head;
17454
+ const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
17455
+ const label = note.status === "ready" ? "Condition met" : "Condition";
17456
+ const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
17457
+ ${note.readyReason}` : "";
17458
+ return `${head}
17459
+ ${label}: ${condition}${failure}`;
17460
+ }
17461
+ function renderNotesById(entries, nowMs) {
17462
+ const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
17463
+ return `## Notes by ID
17464
+
17465
+ ${lines.join(`
17466
+
17467
+ `)}`;
17468
+ }
17469
+ function formatTraySuffix(tray, nowMs) {
17470
+ if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
17471
+ return "";
17472
+ return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
17269
17473
  }
17270
- function readLastCompartmentBoundary(db, sessionId) {
17271
- const row = db.prepare(`SELECT COALESCE(MAX(end_message), -1) AS max_end,
17272
- (SELECT end_message_id FROM compartments
17273
- WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
17274
- FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
17275
- const endMessageId = row?.end_message_id;
17276
- return {
17277
- endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
17278
- endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
17279
- };
17474
+ function formatWriteReply(noteId, tray, nowMs) {
17475
+ return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
17280
17476
  }
17281
- function resolveBoundaryContext(args) {
17282
- const lastCompartmentBoundary = readLastCompartmentBoundary(args.db, args.sessionId);
17283
- const lastCompartmentEndOrdinal = lastCompartmentBoundary.endOrdinal;
17284
- const triggerBudget = deriveTriggerBudget2(args.contextLimit, args.executeThresholdPercentage);
17285
- let meta = args.protectedTailMeta ?? loadProtectedTailMeta(args.db, args.sessionId);
17286
- let migrationFloorActive = false;
17287
- if (meta.protectedTailPolicyVersion < 3) {
17288
- let legacyBoundary = 1;
17289
- try {
17290
- legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
17291
- } catch (error) {
17292
- sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
17293
- }
17294
- const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
17295
- meta = seedResult;
17296
- migrationFloorActive = seedResult.seeded;
17477
+ function noteNudgePickIndex(sessionId, counter, poolSize) {
17478
+ if (poolSize <= 0)
17479
+ return 0;
17480
+ const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
17481
+ let hash = 2166136261;
17482
+ for (const byte of bytes) {
17483
+ hash ^= byte;
17484
+ hash = Math.imul(hash, 16777619) >>> 0;
17297
17485
  }
17298
- const calibration = sessionDecisionCalibration(args.db, args.sessionId);
17299
- const storedTokenTotalsForMessages = (messageIds, messages = []) => {
17300
- try {
17301
- const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
17302
- return {
17303
- totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
17304
- summaryRemovedTotals: weights.summaryRemovedTotals
17305
- };
17306
- } catch (error) {
17307
- sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
17308
- return;
17309
- }
17310
- };
17311
- return {
17312
- sessionId: args.sessionId,
17313
- mode: args.mode,
17314
- contextLimit: args.contextLimit,
17315
- executeThresholdPercentage: args.executeThresholdPercentage,
17316
- triggerBudget,
17317
- usage: args.usage ?? null,
17318
- usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
17319
- lastCompartmentEndOrdinal,
17320
- lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
17321
- priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
17322
- protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
17323
- migrationFloorActive,
17324
- emergencyTailScale: args.emergencyTailScale,
17325
- recovery: args.recovery,
17326
- liftLivePromptFloor: args.liftLivePromptFloor,
17327
- providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
17328
- cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
17329
- storedTokenTotalsForMessages,
17330
- calibration
17331
- };
17486
+ return hash % poolSize;
17332
17487
  }
17333
- function resolveOpenCodeProtectedTailBoundary(args) {
17334
- return resolveProtectedTailBoundary(resolveBoundaryContext(args));
17488
+ function formatNoteNudge(args) {
17489
+ const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
17490
+ const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
17491
+ const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
17492
+ return `${counts}${oldest}${shown}`;
17335
17493
  }
17336
- function resolveWrapupProtectedTailBoundary(args) {
17337
- const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
17338
- const createdAt = ctx.createdAt ?? Date.now();
17339
- const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
17340
- const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
17341
- const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
17342
- const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
17343
- const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
17344
- const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
17345
- const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
17346
- providerShapeVersion: ctx.providerShapeVersion,
17347
- cacheNamespace: ctx.cacheNamespace,
17348
- calibration: ctx.calibration,
17349
- absoluteMessageCount,
17350
- storedTotalForMessage: storedTotals ? (m) => {
17351
- const value = storedTotals?.get(m.id);
17352
- return value === undefined ? null : value;
17353
- } : undefined
17354
- });
17355
- const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
17356
- providerShapeVersion: ctx.providerShapeVersion,
17357
- cacheNamespace: ctx.cacheNamespace,
17358
- calibration: ctx.calibration,
17359
- absoluteMessageCount,
17360
- measure: "summary-removed",
17361
- storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
17362
- });
17363
- const rawMessageCount = index.rawMessageCount;
17364
- const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
17365
- const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
17366
- const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
17367
- const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
17368
- const keep = Math.max(1, Math.floor(args.messagesToKeep));
17369
- let targetProtectedTailStart = offset;
17370
- let boundaryReason = "manual-wrapup-empty";
17371
- if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
17372
- targetProtectedTailStart = offset;
17373
- boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
17374
- } else {
17375
- targetProtectedTailStart = anchorRawMessageCount - keep + 1;
17376
- boundaryReason = "manual-wrapup-keep-watermark";
17377
- const arcs = buildToolArcs(messages);
17378
- const fenced = fenceWrapupBoundaryForToolArcs({
17379
- candidate: targetProtectedTailStart,
17380
- arcs,
17381
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
17382
- });
17383
- if (fenced !== targetProtectedTailStart)
17384
- boundaryReason = "manual-wrapup-tool-arc";
17385
- targetProtectedTailStart = fenced;
17386
- const snapped = snapWrapupBoundaryToUser({
17387
- messages,
17388
- index,
17389
- candidate: targetProtectedTailStart,
17390
- offset,
17391
- triggerBudget: ctx.triggerBudget
17392
- });
17393
- if (snapped !== targetProtectedTailStart)
17394
- boundaryReason = "manual-wrapup-user-snap";
17395
- targetProtectedTailStart = snapped;
17396
- const refenced = fenceWrapupBoundaryForToolArcs({
17397
- candidate: targetProtectedTailStart,
17398
- arcs,
17399
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
17400
- });
17401
- if (refenced !== targetProtectedTailStart)
17402
- boundaryReason = "manual-wrapup-tool-arc";
17403
- targetProtectedTailStart = refenced;
17494
+
17495
+ // src/hooks/magic-context/note-nudger.ts
17496
+ var observedUsers = new WeakMap;
17497
+ function observeNoteNudgeServe(args) {
17498
+ let sessions = observedUsers.get(args.db);
17499
+ if (!sessions) {
17500
+ sessions = new Map;
17501
+ observedUsers.set(args.db, sessions);
17404
17502
  }
17405
- targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
17406
- targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
17407
- const target = deriveProtectedTailTokenTarget({
17408
- contextLimit: ctx.contextLimit,
17409
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17410
- usagePercentage,
17411
- triggerBudget: ctx.triggerBudget
17412
- });
17413
- const perRunCap = selectPerRunCap({
17414
- usagePercentage,
17415
- N: target.N,
17416
- contextLimit: ctx.contextLimit,
17417
- executeThresholdPercentage: ctx.executeThresholdPercentage
17418
- });
17419
- let headDiagnostics;
17420
- const head = applyHeadCap({
17421
- observeDiagnostics: (value) => {
17422
- headDiagnostics = value;
17423
- },
17424
- index: summaryRemovedIndex,
17425
- protectedTailStart: targetProtectedTailStart,
17426
- offset,
17427
- arcs: buildToolArcs(messages),
17428
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
17429
- capTokens: perRunCap,
17430
- recentOpenArcCutoff: targetProtectedTailStart
17431
- });
17432
- const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
17433
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
17434
- const snapshot = {
17435
- sessionId: ctx.sessionId,
17436
- mode: "manual-wrapup",
17437
- offset,
17438
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
17439
- offsetMessageId: boundaryMessageId(index, offset),
17440
- protectedTailStart: targetProtectedTailStart,
17441
- protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
17442
- eligibleEndOrdinal,
17443
- eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
17444
- rawMessageCountAtTrigger: rawMessageCount,
17445
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
17446
- N: keep,
17447
- usagePercentage,
17448
- usageInputTokens,
17449
- usageSource: ctx.usageSource,
17450
- contextLimit: ctx.contextLimit,
17451
- executeThresholdPercentage: ctx.executeThresholdPercentage,
17452
- triggerBudget: ctx.triggerBudget,
17453
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
17454
- migrationFloorActive: ctx.migrationFloorActive,
17455
- emergencyTailScale: ctx.emergencyTailScale,
17456
- providerShapeVersion: ctx.providerShapeVersion,
17457
- cacheNamespace: ctx.cacheNamespace,
17458
- createdAt,
17459
- rawRangeFingerprint,
17460
- trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
17461
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
17462
- oversizeAtomicUnit: head.oversizeAtomicUnit,
17463
- boundaryReason,
17464
- diagnostics: boundaryDiagnostics({
17465
- tailTarget: target,
17466
- usable: target.usable,
17467
- usagePercentage,
17468
- N: target.N,
17469
- triggerBudget: ctx.triggerBudget,
17470
- capTokens: perRunCap,
17471
- sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
17472
- protectedTailStart: targetProtectedTailStart,
17473
- livePromptFloor: {
17474
- ordinal: null,
17475
- from: targetProtectedTailStart,
17476
- to: targetProtectedTailStart
17477
- },
17478
- head: headDiagnostics
17479
- })
17480
- };
17481
- return {
17482
- snapshot,
17483
- rawMessagesAboveLastCompartment,
17484
- anchorRawMessageCount,
17485
- targetProtectedTailStart,
17486
- targetEligibleEndOrdinal: targetProtectedTailStart
17487
- };
17488
- }
17489
- function getRawHistoryEligibility(db, sessionId) {
17490
- const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
17491
- const offset = Math.max(1, lastCompartmentEnd + 1);
17492
- const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
17493
- const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
17503
+ let seen = sessions.get(args.sessionId);
17504
+ const warm = seen !== undefined && seen.size > 0;
17505
+ if (!seen)
17506
+ seen = new Set;
17507
+ const firstServe = args.anchorMessageId !== null && !seen.has(args.anchorMessageId);
17508
+ for (const id of args.userMessageIds)
17509
+ seen.add(id);
17510
+ sessions.set(args.sessionId, seen);
17494
17511
  return {
17495
- lastCompartmentEnd,
17496
- offset,
17497
- rawMessageCount,
17498
- hasRawBeyondLastCompartment: rawMessageCount >= offset
17512
+ isFirstServe: warm && args.isLiveTail && firstServe,
17513
+ prefixRewriteCoversAnchor: args.anchorMessageId !== null && args.prefixRewriteCoversAnchor
17499
17514
  };
17500
17515
  }
17501
- function hasRunnableCompartmentWindow(snapshot) {
17502
- if (snapshot.offset >= snapshot.protectedTailStart)
17503
- return false;
17504
- if (snapshot.eligibleEndOrdinal <= snapshot.offset)
17505
- return false;
17506
- if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
17507
- return true;
17508
- const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
17509
- if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
17510
- return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
17511
- }
17512
- return snapshot.eligibleEndOrdinal > snapshot.offset;
17516
+ var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
17517
+ var lastDeliveredAt = new Map;
17518
+ function isCoolingDown(deliveredAt, now) {
17519
+ return now - deliveredAt < NOTE_NUDGE_COOLDOWN_MS;
17513
17520
  }
17514
- function boundarySnapshotIdChecks(snapshot) {
17515
- const checks = [
17516
- [snapshot.offset, snapshot.offsetMessageId, "offset"],
17517
- [snapshot.rawMessageCountAtTrigger, snapshot.rawLastMessageIdAtTrigger, "last"]
17518
- ];
17519
- if (snapshot.protectedTailStart <= snapshot.rawMessageCountAtTrigger) {
17520
- checks.push([
17521
- snapshot.protectedTailStart,
17522
- snapshot.protectedTailStartMessageId,
17523
- "protectedTailStart"
17524
- ]);
17521
+ function getNoteNudgeDeliveredAt(sessionId) {
17522
+ const deliveredAt = lastDeliveredAt.get(sessionId);
17523
+ if (deliveredAt === undefined)
17524
+ return 0;
17525
+ if (!isCoolingDown(deliveredAt, Date.now())) {
17526
+ lastDeliveredAt.delete(sessionId);
17527
+ return 0;
17525
17528
  }
17526
- if (snapshot.eligibleEndOrdinal > snapshot.offset) {
17527
- checks.push([
17528
- snapshot.eligibleEndOrdinal - 1,
17529
- snapshot.eligibleEndMessageId,
17530
- "eligibleEnd"
17531
- ]);
17529
+ return deliveredAt;
17530
+ }
17531
+ function recordNoteNudgeDeliveryTime(sessionId) {
17532
+ const now = Date.now();
17533
+ for (const [otherSessionId, deliveredAt] of lastDeliveredAt) {
17534
+ if (!isCoolingDown(deliveredAt, now))
17535
+ lastDeliveredAt.delete(otherSessionId);
17532
17536
  }
17533
- return checks;
17537
+ lastDeliveredAt.set(sessionId, now);
17534
17538
  }
17535
- function validateBoundarySnapshot(args) {
17536
- const { snapshot, exactIds } = args;
17537
- if (args.currentContextLimit && args.currentContextLimit !== snapshot.contextLimit) {
17538
- return {
17539
- ok: false,
17540
- reason: "model_or_limit_changed",
17541
- detail: `context limit changed from ${snapshot.contextLimit} to ${args.currentContextLimit}`
17542
- };
17539
+ function onNoteTrigger(db, sessionId, trigger) {
17540
+ let transactionStartedAt = 0;
17541
+ db.transaction(() => {
17542
+ transactionStartedAt = performance.now();
17543
+ setPersistedNoteNudgeTrigger(db, sessionId);
17544
+ }).immediate();
17545
+ logSlowWriteTransaction("note_nudge_trigger", transactionStartedAt);
17546
+ sessionLog2(sessionId, `note-nudge: trigger fired (${trigger}), triggerPending=true`);
17547
+ }
17548
+ function peekNoteNudgeText(db, sessionId, currentUserMessageId, projectIdentity, noteReadStillVisible, eligibility) {
17549
+ const state = getPersistedNoteNudge(db, sessionId);
17550
+ if (!state.triggerPending)
17551
+ return null;
17552
+ if (eligibility && !eligibility.isFirstServe && !eligibility.prefixRewriteCoversAnchor) {
17553
+ sessionLog2(sessionId, "note-nudge: deferring — user already served or first serve unproven");
17554
+ return null;
17543
17555
  }
17544
- const currentRawMessageCount = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
17545
- if (snapshot.rawMessageCountAtTrigger > currentRawMessageCount) {
17546
- return { ok: false, reason: "stale_snapshot", detail: "raw message count shrank" };
17556
+ if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
17557
+ setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
17558
+ state.triggerMessageId = currentUserMessageId;
17547
17559
  }
17548
- const idAt = (ordinal) => {
17549
- if (!exactIds)
17550
- return readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, ordinal, ordinal).keys().next().value ?? null;
17551
- const id = exactIds.get(ordinal);
17552
- if (id === undefined)
17553
- throw new Error(`boundary validation was given no exact id for ordinal ${ordinal}`);
17554
- return id;
17555
- };
17556
- for (const [ordinal, expected, label] of boundarySnapshotIdChecks(snapshot)) {
17557
- if (expected !== idAt(ordinal)) {
17558
- return {
17559
- ok: false,
17560
- reason: "stale_snapshot",
17561
- detail: `${label} ordinal ${ordinal} id changed`
17562
- };
17560
+ if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
17561
+ sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
17562
+ return null;
17563
+ }
17564
+ const deliveredAt = getNoteNudgeDeliveredAt(sessionId);
17565
+ if (deliveredAt > 0) {
17566
+ sessionLog2(sessionId, `note-nudge: suppressing — last delivered ${Math.round((Date.now() - deliveredAt) / 1000)}s ago (cooldown ${NOTE_NUDGE_COOLDOWN_MS / 60000}m)`);
17567
+ clearNoteNudgeTriggerOnly(db, sessionId);
17568
+ return null;
17569
+ }
17570
+ const notes = getSessionNotes(db, sessionId);
17571
+ const readySmartNotes = projectIdentity ? getReadySmartNotes(db, projectIdentity) : [];
17572
+ const totalCount = notes.length + readySmartNotes.length;
17573
+ if (totalCount === 0) {
17574
+ sessionLog2(sessionId, "note-nudge: triggerPending but no notes found, skipping");
17575
+ clearNoteNudgeTriggerOnly(db, sessionId);
17576
+ return null;
17577
+ }
17578
+ const lastReadAt = getNoteLastReadAt(db, sessionId);
17579
+ if (lastReadAt > 0 && noteReadStillVisible) {
17580
+ const mostRecentNoteActivity = maxNoteActivityTime([...notes, ...readySmartNotes]);
17581
+ if (mostRecentNoteActivity > 0 && lastReadAt > mostRecentNoteActivity) {
17582
+ sessionLog2(sessionId, `note-nudge: suppressing — agent ran ctx_note(read) at ${new Date(lastReadAt).toISOString()} and the read is still visible; no new notes since ${new Date(mostRecentNoteActivity).toISOString()}`);
17583
+ clearNoteNudgeTriggerOnly(db, sessionId);
17584
+ return null;
17563
17585
  }
17564
17586
  }
17565
- const expectedOffset = Math.max(1, getLastCompartmentEndMessage(args.db, snapshot.sessionId) + 1);
17566
- if (expectedOffset !== snapshot.offset) {
17567
- return {
17568
- ok: false,
17569
- reason: "stale_snapshot",
17570
- detail: `last compartment moved: offset ${snapshot.offset} -> ${expectedOffset}`
17571
- };
17587
+ const failureNotice = notes.find((note) => /^Smart note #\d+ cannot be checked\.\nCondition: /.test(note.content));
17588
+ if (failureNotice) {
17589
+ const reason = failureNotice.content.split(`
17590
+ Reason: `)[1]?.split(`
17591
+ `)[0] ?? "check unavailable";
17592
+ return `Smart note check unavailable: ${reason}. Read ctx_note #${failureNotice.id} for the condition and repair instructions; this is NOT evidence that the condition is met.`;
17572
17593
  }
17573
- const fingerprintMessages = readRawSessionMessageRange2(snapshot.sessionId, snapshot.offset, snapshot.eligibleEndOrdinal - 1);
17574
- const fingerprint = computeRawRangeFingerprint(fingerprintMessages, snapshot.offset, snapshot.eligibleEndOrdinal);
17575
- if (fingerprint !== snapshot.rawRangeFingerprint) {
17576
- return { ok: false, reason: "stale_snapshot", detail: "raw range fingerprint changed" };
17594
+ const parts = [];
17595
+ if (notes.length > 0) {
17596
+ parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
17577
17597
  }
17578
- return { ok: true };
17598
+ if (readySmartNotes.length > 0) {
17599
+ parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
17600
+ }
17601
+ sessionLog2(sessionId, `note-nudge: delivering nudge for ${parts.join(" and ")}`);
17602
+ return formatNoteNudge({
17603
+ readyCount: readySmartNotes.length,
17604
+ activeCount: notes.length,
17605
+ oldestActiveTouchedAt: oldestTouchedAt(notes),
17606
+ shown: pickNudgeNote({ db, sessionId, activeNotes: notes, readySmartNotes }),
17607
+ nowMs: Date.now()
17608
+ });
17579
17609
  }
17580
- function recordHighPressureNoEligibleHead(db, snapshot) {
17581
- const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
17582
- if (snapshot.usagePercentage < forceMaterializationPercentage && !snapshot.emergencyTailScale) {
17583
- return 0;
17610
+ function oldestTouchedAt(notes) {
17611
+ return notes.reduce((min, note) => {
17612
+ const touchedAt = noteTouchedAt(note);
17613
+ return min === null || touchedAt < min ? touchedAt : min;
17614
+ }, null);
17615
+ }
17616
+ function pickNudgeNote(args) {
17617
+ const pool = args.readySmartNotes.length > 0 ? [...args.readySmartNotes].sort((left, right) => left.id - right.id) : [...args.activeNotes].sort((left, right) => left.id - right.id);
17618
+ if (pool.length === 0)
17619
+ return null;
17620
+ const counter = getNoteNudgeAnchors(args.db, args.sessionId).length;
17621
+ return pool[noteNudgePickIndex(args.sessionId, counter, pool.length)] ?? null;
17622
+ }
17623
+ function maxNoteActivityTime(notes) {
17624
+ let max = 0;
17625
+ for (const note of notes) {
17626
+ if (note.updatedAt > max)
17627
+ max = note.updatedAt;
17628
+ if (note.readyAt !== null && note.readyAt > max)
17629
+ max = note.readyAt;
17584
17630
  }
17585
- return recordProtectedTailNoEligibleHead(db, snapshot.sessionId);
17631
+ return max;
17632
+ }
17633
+ function markNoteNudgeDelivered(db, sessionId, text, messageId) {
17634
+ if (!messageId) {
17635
+ clearNoteNudgeTriggerAndCooldown(db, sessionId);
17636
+ sessionLog2(sessionId, "note-nudge: marked delivered without anchor");
17637
+ return { ok: true, kind: "already-present" };
17638
+ }
17639
+ const outcome = db.transaction(() => {
17640
+ const delivered = deliverNoteNudgeAtomic(db, sessionId, messageId, text);
17641
+ const nudgeText = text?.replace(/^\s*<instruction name="deferred_notes">/, "") ?? "";
17642
+ const noticeId = nudgeText.match(/^Smart note check unavailable: [\s\S]*Read ctx_note #(\d+) for the condition/);
17643
+ if (delivered.ok && noticeId) {
17644
+ db.prepare(`UPDATE notes SET status = 'dismissed', updated_at = ?
17645
+ WHERE id = ? AND type = 'session' AND session_id = ?
17646
+ AND content LIKE 'Smart note #% cannot be checked.%'`).run(Date.now(), Number(noticeId[1]), sessionId);
17647
+ }
17648
+ return delivered;
17649
+ }).immediate();
17650
+ if (outcome.ok) {
17651
+ recordNoteNudgeDeliveryTime(sessionId);
17652
+ }
17653
+ sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
17654
+ return outcome;
17655
+ }
17656
+ function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
17657
+ db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
17658
+ lastDeliveredAt.delete(sessionId);
17659
+ }
17660
+ function resetNoteNudgeCooldownOnly(sessionId) {
17661
+ lastDeliveredAt.delete(sessionId);
17662
+ }
17663
+ function clearNoteNudgeTriggerOnly(db, sessionId) {
17664
+ db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
17665
+ }
17666
+
17667
+ // src/hooks/magic-context/persist-filtered-noise.ts
17668
+ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
17669
+ const rows = chunk.filteredNoiseLines ?? [];
17670
+ const start = chunk.startIndex;
17671
+ if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
17672
+ return false;
17673
+ const endId = rows[rows.length - 1].messageId;
17674
+ if (!hasRawSessionMessageById2(sessionId, endId)) {
17675
+ sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
17676
+ return false;
17677
+ }
17678
+ const saved = db.transaction(() => {
17679
+ const prior = getCompartments(db, sessionId);
17680
+ const last = prior.at(-1);
17681
+ if ((last?.endMessage ?? 0) + 1 !== start)
17682
+ return false;
17683
+ appendCompartments(db, sessionId, [
17684
+ {
17685
+ sequence: (last?.sequence ?? -1) + 1,
17686
+ startMessage: start,
17687
+ endMessage: eligibleEnd - 1,
17688
+ startMessageId: rows[0].messageId,
17689
+ endMessageId: rows[rows.length - 1].messageId,
17690
+ title: "",
17691
+ content: "",
17692
+ p1: "",
17693
+ p2: "",
17694
+ p3: "",
17695
+ p4: "",
17696
+ episodeType: "filtered-noise",
17697
+ importance: 1
17698
+ }
17699
+ ]);
17700
+ return true;
17701
+ }).immediate();
17702
+ if (saved)
17703
+ sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
17704
+ return saved;
17586
17705
  }
17587
17706
 
17588
17707
  // src/hooks/magic-context/raw-exact-ordinal-read.ts
@@ -18105,7 +18224,6 @@ async function runCompartmentAgent(deps) {
18105
18224
  if (promptFit.trimmed || chunkTokens < historianChunkTokens) {
18106
18225
  sessionLog2(sessionId, `historian prompt fit: sized to ${producerModel ?? "unknown"} (${describeHistorianPromptTrim(promptFit)}; requestedChunkTokens=${historianChunkTokens})`);
18107
18226
  }
18108
- const perRunCap = selectPerRunCap(boundarySnapshot);
18109
18227
  if (!deps.forceDrainQuota && shouldWaitForNewHistorianHistory(boundarySnapshot, {
18110
18228
  emergency: getOverflowState(db, sessionId).needsEmergencyRecovery
18111
18229
  })) {
@@ -18114,19 +18232,27 @@ async function runCompartmentAgent(deps) {
18114
18232
  sessionLog2(sessionId, "historian no-op: waiting for new history after no forward progress");
18115
18233
  return;
18116
18234
  }
18117
- const usable = Math.max(1, Math.round(boundarySnapshot.contextLimit * boundarySnapshot.executeThresholdPercentage / 100));
18235
+ const usagePercentage = deps.drainBudgetUsagePercentage ?? boundarySnapshot.usagePercentage;
18236
+ const { usable, perRunCap } = deps.drainBudgetUsagePercentage === undefined ? {
18237
+ usable: Math.max(1, Math.round(boundarySnapshot.contextLimit * boundarySnapshot.executeThresholdPercentage / 100)),
18238
+ perRunCap: selectPerRunCap(boundarySnapshot)
18239
+ } : resolveHistorianDrainBudgetGeometry({ ...boundarySnapshot, usagePercentage });
18118
18240
  const reserve = deps.forceDrainQuota ? { ok: true, reservation: null } : reserveProtectedTailDrainTokens({
18119
18241
  db,
18120
18242
  sessionId,
18121
18243
  runId: crypto.randomUUID(),
18122
18244
  trueRawTokens: boundarySnapshot.summaryRemovedEligibleTokens,
18123
- usagePercentage: boundarySnapshot.usagePercentage,
18245
+ usagePercentage,
18246
+ providerRecovery: deps.drainBudgetUsagePercentage !== undefined,
18124
18247
  usable,
18125
18248
  perRunCap,
18126
18249
  executeThresholdPercentage: boundarySnapshot.executeThresholdPercentage
18127
18250
  });
18128
18251
  if (!reserve.ok) {
18129
- sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
18252
+ if (deps.reportDrainSkip && reserve.drainSkip)
18253
+ deps.reportDrainSkip(reserve.drainSkip);
18254
+ else
18255
+ sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
18130
18256
  telemetry.status = "noop";
18131
18257
  telemetry.failureReason = "internal protected-tail drain budget spent";
18132
18258
  return;
@@ -18296,6 +18422,8 @@ ${chunkText}`,
18296
18422
  const discardedLast = persistedCompartments.length < emittedCompartments.length;
18297
18423
  const weakLookaheadFinalCompartment = forceKeepLastCompartmentForChunk;
18298
18424
  const skipUnanchoredPromotion = discardedLast || weakLookaheadFinalCompartment;
18425
+ const facts = validatedPass.facts;
18426
+ const publishableFacts = !skipUnanchoredPromotion ? facts : retainAnchoredHistorianFacts(facts, weakLookaheadFinalCompartment ? Math.min(persistedCompartments.length, emittedCompartments.length - 1) : persistedCompartments.length);
18299
18427
  const embeddingActive = !!promotionDirectory;
18300
18428
  const promotionActive = embeddingActive && deps.memoryEnabled !== false && deps.autoPromote !== false;
18301
18429
  const promotionProjectIdentity = promotionDirectory ? resolveProjectIdentity(promotionDirectory) : "";
@@ -18309,10 +18437,7 @@ ${chunkText}`,
18309
18437
  }
18310
18438
  return true;
18311
18439
  });
18312
- const unanchoredPromotionSkipReason = discardedLast ? "discarded_last" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
18313
- if (unanchoredPromotionSkipReason) {
18314
- sessionLog2(sessionId, `historian unanchored promotion skipped: reason=${unanchoredPromotionSkipReason} facts=${validatedPass.facts?.length ?? 0} user_observations=${validatedPass.userObservations?.length ?? 0} primers=${validatedPass.primerCandidates?.length ?? 0} events_publishable=${publishableEvents.length}/${validatedPass.events?.length ?? 0}`);
18315
- }
18440
+ const weakTailReason = telemetry.discardedLast ? "discarded_last" : discardedLast ? "unserved_final_compartment" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
18316
18441
  let promotedFactRefs = [];
18317
18442
  let promotedFactCount = 0;
18318
18443
  let publishedEventCount = 0;
@@ -18355,9 +18480,9 @@ ${chunkText}`,
18355
18480
  }
18356
18481
  appendCompartments(db, sessionId, persistedCompartments);
18357
18482
  persistedIds = getNewestCompartmentIds(db, sessionId, persistedCompartments.length);
18358
- if (promotionActive && !skipUnanchoredPromotion) {
18483
+ if (promotionActive && publishableFacts.length > 0) {
18359
18484
  try {
18360
- const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, validatedPass.facts ?? []);
18485
+ const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, publishableFacts);
18361
18486
  promotedFactRefs = promotion.newMemoryRefs;
18362
18487
  promotedFactCount = promotion.factsPromoted;
18363
18488
  } catch (error) {
@@ -18425,6 +18550,13 @@ ${chunkText}`,
18425
18550
  }
18426
18551
  updateSessionMeta(db, sessionId, { compartmentInProgress: false });
18427
18552
  completedSuccessfully = true;
18553
+ if (weakTailReason) {
18554
+ logWeakTailFactPromotion(sessionId, {
18555
+ reason: weakTailReason,
18556
+ emitted: facts.length,
18557
+ stored: promotedFactCount
18558
+ });
18559
+ }
18428
18560
  {
18429
18561
  const facts = validatedPass.facts ?? [];
18430
18562
  const validIds = persistedIds.filter((id) => typeof id === "number");
@@ -19706,4 +19838,4 @@ async function executeContextRecomp(deps, options = {}) {
19706
19838
  return (await executeContextRecompWithResult(deps, options)).message;
19707
19839
  }
19708
19840
 
19709
- export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, supportsQuietHiddenChildren, matchesHiddenRunLocation, hiddenRunPlacement, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, isLatestAssistantLengthCapped, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, pausedRecompReason, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
19841
+ export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, supportsQuietHiddenChildren, matchesHiddenRunLocation, hiddenRunPlacement, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, noteTimedOutHiddenChild, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, isLatestAssistantLengthCapped, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, promptTransportBudget, notePromptSetupTimeout, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, pausedRecompReason, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, reportProviderRecoveryDrainSkip, isHistorianDrainBudgetSpent, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };