@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
@@ -19,7 +19,7 @@ import {
19
19
  cortexKitProjectConfigBasePath,
20
20
  resolveLegacyConfigSourcesForHarness,
21
21
  loadPluginConfigDetailed
22
- } from "./server-tj65pgvg.js";
22
+ } from "./server-vsqmkvxc.js";
23
23
  import {
24
24
  catalogOutputReserve,
25
25
  getSdkContextLimit,
@@ -70,6 +70,7 @@ import {
70
70
  recordProtectedTailPublicationFloor,
71
71
  recordProtectedTailNoEligibleHead,
72
72
  isWrapupInProgress,
73
+ getProtectedTailDrainBudgetSkip,
73
74
  reserveProtectedTailDrainTokens,
74
75
  clearEmergencyDrainLatch,
75
76
  recordHistorianDrainFailure,
@@ -101,15 +102,15 @@ import {
101
102
  foldShrunkPartTags2,
102
103
  getTagNumberByMessageId2,
103
104
  getActiveTagsBySession2
104
- } from "./server-pmws7we9.js";
105
+ } from "./server-d4trxrj3.js";
105
106
  import {
106
107
  hasMeaningfulUserText2,
107
108
  estimateTokens,
108
109
  estimateFixedPromptTokens
109
- } from "./server-y8xjr8rx.js";
110
+ } from "./server-qb3s0mnc.js";
110
111
  import {
111
112
  BoundedSessionMap
112
- } from "./server-stjy5dxv.js";
113
+ } from "./server-qntmqaca.js";
113
114
  import {
114
115
  resolveOpenCodeDbPath,
115
116
  assertOpenCodeStoreGeneration,
@@ -120,7 +121,7 @@ import {
120
121
  openCodeDbExists,
121
122
  withReadOnlySessionDb,
122
123
  getMessageTimesFromOpenCodeDb
123
- } from "./server-3ap5dmhc.js";
124
+ } from "./server-5hwf5c7r.js";
124
125
  import {
125
126
  removeUnsupportedCommitHashes,
126
127
  completedToolArcCrossesBoundary,
@@ -156,14 +157,14 @@ import {
156
157
  getRawSessionTagKeysThrough2,
157
158
  getLegacyProtectedTailStartOrdinal2,
158
159
  readSessionChunk2
159
- } from "./server-c7awk5s2.js";
160
+ } from "./server-9011eteb.js";
160
161
  import {
161
162
  clearCompressionDepth,
162
163
  clearCompressionDepthRange,
163
164
  toMessageIndexSource,
164
165
  clearIndexedMessagesInTransaction,
165
166
  indexSourcesAfterOrdinal
166
- } from "./server-9n2qgk29.js";
167
+ } from "./server-mgxqfprb.js";
167
168
  import {
168
169
  COMPARTMENT_LEASE_RENEWAL_MS,
169
170
  getCompartmentLeaseBlocker,
@@ -210,7 +211,7 @@ import {
210
211
  getProjectState,
211
212
  recordSubagentInvocation,
212
213
  getLatestHistorianInvocationId
213
- } from "./server-09h2vyvs.js";
214
+ } from "./server-6t3asmx8.js";
214
215
  import {
215
216
  invalidateAutoEmbedSession
216
217
  } from "./server-2amn2s73.js";
@@ -223,7 +224,7 @@ import {
223
224
  replaceCompartmentChunkEmbeddings2,
224
225
  deleteChunkEmbedBackoffForSession2,
225
226
  chunkWindowSourceKey2
226
- } from "./server-y17r5ryz.js";
227
+ } from "./server-barj0mjz.js";
227
228
  import {
228
229
  isMarkerCandidateBasisCurrent2,
229
230
  invalidateMarkerCandidateBasis2,
@@ -245,7 +246,7 @@ import {
245
246
  getProjectChunkEmbeddingModelId2,
246
247
  getProjectEmbeddingMaxInputTokens2,
247
248
  embedItemsWindowBounded2
248
- } from "./server-dgjqvpgd.js";
249
+ } from "./server-72k2r3kt.js";
249
250
  import {
250
251
  V2_MEMORY_CATEGORIES,
251
252
  CATEGORY_PRIORITY,
@@ -256,7 +257,7 @@ import {
256
257
  userFacingFailureCode,
257
258
  promoteSessionFactsDurable,
258
259
  embedPromotedFacts
259
- } from "./server-add0j5n3.js";
260
+ } from "./server-8ps3717t.js";
260
261
  import {
261
262
  computeCueContentHash,
262
263
  getMuralCueState,
@@ -270,7 +271,7 @@ import {
270
271
  LATEST_SUPPORTED_VERSION,
271
272
  getPersistedSchemaVersion,
272
273
  openDatabase
273
- } from "./server-fb5hvvfc.js";
274
+ } from "./server-fj3pekz2.js";
274
275
  import {
275
276
  parseCompartmentOutput,
276
277
  resolveWorkspaceShareCategories,
@@ -279,7 +280,7 @@ import {
279
280
  resolveStoredPathWorkspaceIdentity,
280
281
  sourceNameForMemory,
281
282
  computeWorkspaceEpochFingerprint
282
- } from "./server-a85j3kam.js";
283
+ } from "./server-jkj1dq6j.js";
283
284
  import {
284
285
  FAIL_CLOSED_DOCTOR_COMMAND
285
286
  } from "./server-39bcszk4.js";
@@ -287,7 +288,7 @@ import {
287
288
  getSessionNotes,
288
289
  getReadySmartNotes,
289
290
  insertPrimerCandidates
290
- } from "./server-fn4ky6mn.js";
291
+ } from "./server-x69fqsvz.js";
291
292
  import {
292
293
  pushNotification2
293
294
  } from "./server-y14pawe1.js";
@@ -298,7 +299,7 @@ import {
298
299
  } from "./server-j4jjtdc5.js";
299
300
  import {
300
301
  sendStatusNotification2
301
- } from "./server-6250cxzs.js";
302
+ } from "./server-gs2251jr.js";
302
303
  import {
303
304
  retreatPastHostUnservedRows,
304
305
  snapTerminalCompartmentToServedRow,
@@ -2746,24 +2747,27 @@ function isHiddenRunHolder(id) {
2746
2747
  return id.startsWith(HOLDER_PREFIX);
2747
2748
  }
2748
2749
  function supportsQuietHiddenChildren(version) {
2749
- return typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version) && version !== "2.3.0";
2750
+ return version !== "2.3.0";
2750
2751
  }
2751
2752
  function matchesHiddenRunLocation(wanted, returned) {
2752
2753
  return sameProjectDirectory(wanted, returned ?? "");
2753
2754
  }
2754
- async function hiddenRunPlacement(createHolder, directory) {
2755
- if (!(await stat(directory)).isDirectory())
2755
+ async function hiddenRunPlacement(createHolder, directory, budget) {
2756
+ const work = budget?.work ?? ((start) => start());
2757
+ budget?.setStage("checking the holder directory");
2758
+ if (!(await work(() => stat(directory))).isDirectory())
2756
2759
  throw new Error(`Not a run directory: ${directory}`);
2757
2760
  const base = HOLDER_PREFIX + createHash5("sha256").update(directory).digest("hex").slice(0, 32);
2758
2761
  const displaced = [];
2759
2762
  for (let index = 0;index < HOLDER_CANDIDATES; index++) {
2760
2763
  const id = index === 0 ? base : `${base}_${index + 1}`;
2761
- const holder = await createHolder({
2764
+ budget?.setStage("creating the background holder");
2765
+ const holder = await work(() => createHolder({
2762
2766
  id,
2763
2767
  title: "Magic Context background runs",
2764
2768
  location: { directory },
2765
2769
  metadata: { magic_context: "background-holder" }
2766
- });
2770
+ }));
2767
2771
  if (holder.id !== id || holder.parentID)
2768
2772
  throw new Error(`OpenCode did not return the expected background holder ${id}`);
2769
2773
  if (holder.metadata?.magic_context === "background-holder" && matchesHiddenRunLocation(directory, holder.location?.directory)) {
@@ -2820,14 +2824,25 @@ function hiddenAgentAllowedTools(agent) {
2820
2824
  }
2821
2825
  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";
2822
2826
  var DISPOSED_CHILDREN_KEY = Symbol.for("@cortexkit/magic-context/v2/disposed-hidden-children");
2827
+ var TIMED_OUT_CHILDREN_KEY = Symbol.for("@cortexkit/magic-context/v2/timed-out-hidden-children");
2823
2828
  var DISPOSED_CHILDREN_LIMIT = 512;
2829
+ var HIDDEN_RUN_RETIRED_REASON = "the Magic Context hidden run was cancelled or timed out and is being retired";
2824
2830
  function disposedChildren() {
2825
2831
  const store = globalThis;
2826
2832
  store[DISPOSED_CHILDREN_KEY] ??= new Set;
2827
2833
  return store[DISPOSED_CHILDREN_KEY];
2828
2834
  }
2829
2835
  function noteChildOfDisposedInstance(sessionID) {
2830
- const children = disposedChildren();
2836
+ rememberStoppedChild(disposedChildren(), sessionID);
2837
+ }
2838
+ function timedOutChildren() {
2839
+ const store = globalThis;
2840
+ return store[TIMED_OUT_CHILDREN_KEY] ??= new Set;
2841
+ }
2842
+ function noteTimedOutHiddenChild(sessionID) {
2843
+ rememberStoppedChild(timedOutChildren(), sessionID);
2844
+ }
2845
+ function rememberStoppedChild(children, sessionID) {
2831
2846
  children.delete(sessionID);
2832
2847
  children.add(sessionID);
2833
2848
  while (children.size > DISPOSED_CHILDREN_LIMIT) {
@@ -2870,6 +2885,8 @@ async function registerHiddenChildAgents(agent) {
2870
2885
  });
2871
2886
  }
2872
2887
  function hiddenToolCallRefusal(call, hook) {
2888
+ if (timedOutChildren().has(call.sessionID))
2889
+ return `Magic Context hidden child ${call.sessionID} refused: ${HIDDEN_RUN_RETIRED_REASON}; ${call.tool} refused`;
2873
2890
  const owned = hook.owns(call.sessionID);
2874
2891
  if (!owned && isChildOfDisposedInstance(call.sessionID))
2875
2892
  return `Magic Context hidden child ${call.sessionID} refused: ${HIDDEN_RUN_DISPOSED_REASON}; ${call.tool} refused`;
@@ -3051,6 +3068,8 @@ class HiddenChildHook {
3051
3068
  }
3052
3069
  }
3053
3070
  compactionSummary(sessionID, agent) {
3071
+ if (timedOutChildren().has(sessionID))
3072
+ this.refuse(HIDDEN_RUN_RETIRED_REASON, { sessionID, messages: [] }, undefined);
3054
3073
  if (!this.owns(sessionID)) {
3055
3074
  if (isChildOfDisposedInstance(sessionID)) {
3056
3075
  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");
@@ -3106,6 +3125,8 @@ class HiddenChildHook {
3106
3125
  return [{ type: "text", text: claudeAgentInstructionsText(system) }, ...parts];
3107
3126
  }
3108
3127
  apply(draft) {
3128
+ if (timedOutChildren().has(draft.sessionID))
3129
+ this.refuse(HIDDEN_RUN_RETIRED_REASON, draft, undefined);
3109
3130
  if (!this.owns(draft.sessionID)) {
3110
3131
  if (isChildOfDisposedInstance(draft.sessionID)) {
3111
3132
  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");
@@ -3426,6 +3447,14 @@ class ModelProducedNoOutputError extends Error {
3426
3447
  }
3427
3448
  }
3428
3449
  var modelActivityBySignal = new WeakMap;
3450
+ function promptTransportBudget(signal) {
3451
+ return signal ? modelActivityBySignal.get(signal) : undefined;
3452
+ }
3453
+ function notePromptSetupTimeout(signal, read) {
3454
+ const activity = signal ? modelActivityBySignal.get(signal) : undefined;
3455
+ if (activity)
3456
+ activity.setupTimeout = read;
3457
+ }
3429
3458
  function noteModelActivityMonitored(signal) {
3430
3459
  const activity = signal ? modelActivityBySignal.get(signal) : undefined;
3431
3460
  if (activity)
@@ -3525,9 +3554,20 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport, fir
3525
3554
  throw new Error(externalAbortMessage(signal));
3526
3555
  }
3527
3556
  const controller = new AbortController;
3528
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
3529
- const activity = { monitored: false, received: false };
3557
+ const activity = {
3558
+ monitored: false,
3559
+ received: false,
3560
+ timeoutMs,
3561
+ deadline: Date.now() + timeoutMs
3562
+ };
3530
3563
  modelActivityBySignal.set(controller.signal, activity);
3564
+ let setupTimeout;
3565
+ const timeout = setTimeout(() => {
3566
+ try {
3567
+ setupTimeout = activity.setupTimeout?.();
3568
+ } catch {}
3569
+ controller.abort();
3570
+ }, timeoutMs);
3531
3571
  let silent = false;
3532
3572
  const firstOutputTimer = firstOutputTimeoutMs !== undefined && firstOutputTimeoutMs < timeoutMs ? setTimeout(() => {
3533
3573
  if (!activity.monitored || activity.received)
@@ -3535,7 +3575,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport, fir
3535
3575
  silent = true;
3536
3576
  controller.abort(new ModelProducedNoOutputError(firstOutputTimeoutMs));
3537
3577
  }, firstOutputTimeoutMs) : undefined;
3538
- const timeoutError = () => silent && firstOutputTimeoutMs !== undefined ? new ModelProducedNoOutputError(firstOutputTimeoutMs) : new Error(`prompt timed out after ${timeoutMs}ms`);
3578
+ const timeoutError = () => setupTimeout ?? (silent && firstOutputTimeoutMs !== undefined ? new ModelProducedNoOutputError(firstOutputTimeoutMs) : new Error(`prompt timed out after ${timeoutMs}ms`));
3539
3579
  const onExternalAbort = () => controller.abort();
3540
3580
  signal?.addEventListener("abort", onExternalAbort);
3541
3581
  try {
@@ -3567,6 +3607,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport, fir
3567
3607
  }
3568
3608
  throw error;
3569
3609
  } finally {
3610
+ activity.setupTimeout = undefined;
3570
3611
  clearTimeout(timeout);
3571
3612
  if (firstOutputTimer)
3572
3613
  clearTimeout(firstOutputTimer);
@@ -5667,6 +5708,10 @@ Facts capture stable properties of the project that survive past any single comp
5667
5708
  - One fact bullet = exactly one rule/default/constraint/decision/name.
5668
5709
  - 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.
5669
5710
 
5711
+ Prefix every <facts> bullet with the compartment it came from: \`* [at_compartment=N] Fact text\`.
5712
+ - N is the 1-based index of the compartment above that the fact came from (the same convention as events).
5713
+ - When you can't tell which compartment, write \`* [at_compartment=unknown] Fact text\`. Never guess.
5714
+
5670
5715
  ### The 5 categories
5671
5716
 
5672
5717
  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.
@@ -5982,19 +6027,19 @@ Closing tags must match their opening tier tag (e.g. \`<p1>...</p1>\`, never \`<
5982
6027
  </compartments>
5983
6028
  <facts>
5984
6029
  <PROJECT_RULES>
5985
- * Fact text
6030
+ * [at_compartment=N] Fact text
5986
6031
  </PROJECT_RULES>
5987
6032
  <ARCHITECTURE>
5988
- * Fact text
6033
+ * [at_compartment=N] Fact text
5989
6034
  </ARCHITECTURE>
5990
6035
  <CONSTRAINTS>
5991
- * Fact text
6036
+ * [at_compartment=N] Fact text
5992
6037
  </CONSTRAINTS>
5993
6038
  <CONFIG_VALUES>
5994
- * Fact text
6039
+ * [at_compartment=N] Fact text
5995
6040
  </CONFIG_VALUES>
5996
6041
  <NAMING>
5997
- * Fact text
6042
+ * [at_compartment=N] Fact text
5998
6043
  </NAMING>
5999
6044
  </facts>
6000
6045
  <events>
@@ -6390,6 +6435,9 @@ function mapParsedCompartmentsToChunk(compartments, chunk, sequenceOffset) {
6390
6435
  }
6391
6436
 
6392
6437
  // src/hooks/magic-context/historian-publish-stage-logger.ts
6438
+ function logWeakTailFactPromotion(sessionId, promotion) {
6439
+ sessionLog2(sessionId, `historian weak-tail fact promotion: reason=${promotion.reason} facts_stored=${promotion.stored} facts_not_stored=${promotion.emitted - promotion.stored}`);
6440
+ }
6393
6441
  function startHistorianPublishStage(sessionId, stage, extra) {
6394
6442
  const suffix = extra ? ` ${extra}` : "";
6395
6443
  sessionLog2(sessionId, `historian publish stage: stage=${stage} status=started elapsed=0.0ms${suffix}`);
@@ -6449,6 +6497,9 @@ function shouldDiscardLastHistorianCompartment(compartments, chunk) {
6449
6497
  const lookaheadMargin = chunk.endIndex - last.endMessage;
6450
6498
  return lookaheadMargin <= HISTORIAN_BOUNDARY_HEALING_SLACK && !boundarySplitsCompletedToolArc(previous.endMessage + 1, chunk.completedToolArcs);
6451
6499
  }
6500
+ function retainAnchoredHistorianFacts(facts, trustedCount) {
6501
+ return facts.filter(({ originCompartmentIndex }) => originCompartmentIndex !== undefined && originCompartmentIndex >= 1 && originCompartmentIndex <= trustedCount);
6502
+ }
6452
6503
  function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, sequenceOffset) {
6453
6504
  const parseStarted = startHistorianPublishStage(sessionId, "parse", `response_chars=${text.length}`);
6454
6505
  const parsed = parseCompartmentOutput(text);
@@ -10731,21 +10782,21 @@ Acorn Suite made JWT tenant_id the single tenant authority across REST, GraphQL,
10731
10782
  </compartment>
10732
10783
  <facts>
10733
10784
  <PROJECT_RULES>
10734
- * 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.
10735
- * Acorn Suite auth changes must include both REST and GraphQL tenant-boundary tests before merge.
10785
+ * [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.
10786
+ * [at_compartment=1] Acorn Suite auth changes must include both REST and GraphQL tenant-boundary tests before merge.
10736
10787
  </PROJECT_RULES>
10737
10788
  <ARCHITECTURE>
10738
- * Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
10739
- * Platform support bypass is modeled as a service actor, not as a tenant wildcard.
10789
+ * [at_compartment=1] Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
10790
+ * [at_compartment=1] Platform support bypass is modeled as a service actor, not as a tenant wildcard.
10740
10791
  </ARCHITECTURE>
10741
10792
  <CONSTRAINTS>
10742
- * 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.
10793
+ * [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.
10743
10794
  </CONSTRAINTS>
10744
10795
  <CONFIG_VALUES>
10745
- * Acorn Suite tenant-boundary fixtures live under apps/api/test/tenant-boundary/ and use seed tenants acme_lab and beta_works.
10796
+ * [at_compartment=1] Acorn Suite tenant-boundary fixtures live under apps/api/test/tenant-boundary/ and use seed tenants acme_lab and beta_works.
10746
10797
  </CONFIG_VALUES>
10747
10798
  <NAMING>
10748
- * The shared auth helper is named requireTenantContext; "resolveTenantMaybe" was rejected because it implied fallback behavior.
10799
+ * [at_compartment=1] The shared auth helper is named requireTenantContext; "resolveTenantMaybe" was rejected because it implied fallback behavior.
10749
10800
  </NAMING>
10750
10801
  </facts>
10751
10802
  <events>
@@ -10792,19 +10843,19 @@ OpLog; SnapshotCache; vector_clock; max_ops_before_compact=10000; crates/chorus-
10792
10843
  </compartment>
10793
10844
  <facts>
10794
10845
  <ARCHITECTURE>
10795
- * 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.
10846
+ * [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.
10796
10847
  </ARCHITECTURE>
10797
10848
  <CONSTRAINTS>
10798
- * 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).
10849
+ * [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).
10799
10850
  </CONSTRAINTS>
10800
10851
  <PROJECT_RULES>
10801
- * Never mutate a Chorus materialized snapshot directly; always append an op to the log and re-derive the snapshot.
10852
+ * [at_compartment=7] Never mutate a Chorus materialized snapshot directly; always append an op to the log and re-derive the snapshot.
10802
10853
  </PROJECT_RULES>
10803
10854
  <NAMING>
10804
- * Chorus core types: OpLog (crates/chorus-core/src/log.rs), SnapshotCache (crates/chorus-core/src/snapshot.rs).
10855
+ * [at_compartment=7] Chorus core types: OpLog (crates/chorus-core/src/log.rs), SnapshotCache (crates/chorus-core/src/snapshot.rs).
10805
10856
  </NAMING>
10806
10857
  <CONFIG_VALUES>
10807
- * Chorus compaction threshold: max_ops_before_compact=10000 per document.
10858
+ * [at_compartment=7] Chorus compaction threshold: max_ops_before_compact=10000 per document.
10808
10859
  </CONFIG_VALUES>
10809
10860
  </facts>
10810
10861
  <events>
@@ -10847,28 +10898,28 @@ The durable decision was to allow standby replicas to do read-heavy reconcile wo
10847
10898
  </compartment>
10848
10899
  <facts>
10849
10900
  <PROJECT_RULES>
10850
- * Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
10851
- * Any new cleanup step must be idempotent across repeated reconcile loops before it is attached to finalizer removal.
10901
+ * [at_compartment=1] Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
10902
+ * [at_compartment=1] Any new cleanup step must be idempotent across repeated reconcile loops before it is attached to finalizer removal.
10852
10903
  </PROJECT_RULES>
10853
10904
  <ARCHITECTURE>
10854
- * The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
10855
- * Status carries an observedPlan hash so downstream tools can detect desired-versus-applied drift without diffing child resources.
10905
+ * [at_compartment=1] The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
10906
+ * [at_compartment=1] Status carries an observedPlan hash so downstream tools can detect desired-versus-applied drift without diffing child resources.
10856
10907
  </ARCHITECTURE>
10857
10908
  <CONSTRAINTS>
10858
- * 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.
10909
+ * [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.
10859
10910
  </CONSTRAINTS>
10860
10911
  <CONFIG_VALUES>
10861
- * Leader election lease name: workspacemesh-controller-lock.
10862
- * Drift hash status field: status.observedPlan.
10912
+ * [at_compartment=1] Leader election lease name: workspacemesh-controller-lock.
10913
+ * [at_compartment=1] Drift hash status field: status.observedPlan.
10863
10914
  </CONFIG_VALUES>
10864
10915
  <NAMING>
10865
- * The controller write gate wrapper is named LeaseGuard.
10916
+ * [at_compartment=1] The controller write gate wrapper is named LeaseGuard.
10866
10917
  </NAMING>
10867
10918
  </facts>`
10868
10919
  },
10869
10920
  {
10870
10921
  importance: 94,
10871
- 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>'
10922
+ 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>'
10872
10923
  },
10873
10924
  {
10874
10925
  importance: 92,
@@ -10896,22 +10947,22 @@ Tenant authorization now flows from membership state rather than browser-selecte
10896
10947
  </compartment>
10897
10948
  <facts>
10898
10949
  <PROJECT_RULES>
10899
- * New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
10900
- * Any endpoint bypassing TenantGuard needs an explicit integration test covering membership revocation.
10950
+ * [at_compartment=1] New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
10951
+ * [at_compartment=1] Any endpoint bypassing TenantGuard needs an explicit integration test covering membership revocation.
10901
10952
  </PROJECT_RULES>
10902
10953
  <ARCHITECTURE>
10903
- * 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.
10904
- * Billing, files, and audit services consume a middleware-built TenantContext instead of parsing auth material independently.
10954
+ * [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.
10955
+ * [at_compartment=1] Billing, files, and audit services consume a middleware-built TenantContext instead of parsing auth material independently.
10905
10956
  </ARCHITECTURE>
10906
10957
  <CONSTRAINTS>
10907
- * Browser-supplied orgId values are unsafe for tenant authorization because users can belong to multiple tenants and stale tabs can replay old selections.
10958
+ * [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.
10908
10959
  </CONSTRAINTS>
10909
10960
  <CONFIG_VALUES>
10910
- * Internal tenant hop header: x-ledgerleaf-tenant-id.
10911
- * Auth claim name: active_membership_id.
10961
+ * [at_compartment=1] Internal tenant hop header: x-ledgerleaf-tenant-id.
10962
+ * [at_compartment=1] Auth claim name: active_membership_id.
10912
10963
  </CONFIG_VALUES>
10913
10964
  <NAMING>
10914
- * The auth boundary middleware is named TenantGuard and the resolver behind it is TenantContextResolver.
10965
+ * [at_compartment=1] The auth boundary middleware is named TenantGuard and the resolver behind it is TenantContextResolver.
10915
10966
  </NAMING>
10916
10967
  </facts>
10917
10968
  <user_observations>
@@ -10946,16 +10997,16 @@ internal/leaderelection/release.go shim removed; PreStop hook; lease 30s / retry
10946
10997
  </compartment>
10947
10998
  <facts>
10948
10999
  <PROJECT_RULES>
10949
- * 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.
11000
+ * [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.
10950
11001
  </PROJECT_RULES>
10951
11002
  <ARCHITECTURE>
10952
- * Leader-election release path must run unobstructed during SIGTERM so the kube-apiserver can transfer the lease before the pod's Node disappears.
11003
+ * [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.
10953
11004
  </ARCHITECTURE>
10954
11005
  <CONSTRAINTS>
10955
- * 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.
11006
+ * [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.
10956
11007
  </CONSTRAINTS>
10957
11008
  <CONFIG_VALUES>
10958
- * Operator leader-election: lease duration 30s, retry period 5s, PreStop hook 5s.
11009
+ * [at_compartment=1] Operator leader-election: lease duration 30s, retry period 5s, PreStop hook 5s.
10959
11010
  </CONFIG_VALUES>
10960
11011
  </facts>
10961
11012
  <events>
@@ -10997,19 +11048,19 @@ run_id; pipeline_run; IntegrityError; idempotent retry; {pipeline_name}_{YYYYMMD
10997
11048
  </compartment>
10998
11049
  <facts>
10999
11050
  <ARCHITECTURE>
11000
- * 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.
11051
+ * [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.
11001
11052
  </ARCHITECTURE>
11002
11053
  <PROJECT_RULES>
11003
- * Every Luminary pipeline run must generate and log a run_id to the pipeline_run table before any target writes begin.
11054
+ * [at_compartment=1] Every Luminary pipeline run must generate and log a run_id to the pipeline_run table before any target writes begin.
11004
11055
  </PROJECT_RULES>
11005
11056
  <CONSTRAINTS>
11006
- * 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.
11057
+ * [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.
11007
11058
  </CONSTRAINTS>
11008
11059
  <NAMING>
11009
- * Luminary idempotency primitives: run_id (string dedup key), pipeline_run (dedup table), orchestrator/runner.py (retry logic with IntegrityError handling).
11060
+ * [at_compartment=1] Luminary idempotency primitives: run_id (string dedup key), pipeline_run (dedup table), orchestrator/runner.py (retry logic with IntegrityError handling).
11010
11061
  </NAMING>
11011
11062
  <CONFIG_VALUES>
11012
- * Luminary run_id format: {pipeline_name}_{YYYYMMDD}_{uuid4_prefix8} (e.g., orders_daily_20250523_a3f92c11).
11063
+ * [at_compartment=1] Luminary run_id format: {pipeline_name}_{YYYYMMDD}_{uuid4_prefix8} (e.g., orders_daily_20250523_a3f92c11).
11013
11064
  </CONFIG_VALUES>
11014
11065
  </facts>`
11015
11066
  },
@@ -11033,20 +11084,20 @@ Harborlight sharding is namespace-scoped: one operator binary can run cluster-wi
11033
11084
  </compartment>
11034
11085
  <facts>
11035
11086
  <PROJECT_RULES>
11036
- * Harborlight CRD changes must regenerate manifests, deepcopy code, RBAC, and envtest fixtures before merge.
11087
+ * [at_compartment=5] Harborlight CRD changes must regenerate manifests, deepcopy code, RBAC, and envtest fixtures before merge.
11037
11088
  </PROJECT_RULES>
11038
11089
  <ARCHITECTURE>
11039
- * Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
11040
- * QueueShard.status.observedLeaseUID records reconciler-observed lease identity; QueueShard.spec remains user intent only.
11090
+ * [at_compartment=5] Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
11091
+ * [at_compartment=5] QueueShard.status.observedLeaseUID records reconciler-observed lease identity; QueueShard.spec remains user intent only.
11041
11092
  </ARCHITECTURE>
11042
11093
  <CONSTRAINTS>
11043
- * Kubernetes Lease renewTime is unreliable for Harborlight ownership decisions under node clock skew.
11094
+ * [at_compartment=5] Kubernetes Lease renewTime is unreliable for Harborlight ownership decisions under node clock skew.
11044
11095
  </CONSTRAINTS>
11045
11096
  <CONFIG_VALUES>
11046
- * Harborlight QueueShard lease timing is duration 18s, renew deadline 12s, retry period 3s.
11097
+ * [at_compartment=5] Harborlight QueueShard lease timing is duration 18s, renew deadline 12s, retry period 3s.
11047
11098
  </CONFIG_VALUES>
11048
11099
  <NAMING>
11049
- * The Harborlight CRD kind is QueueShard; "WorkPartition" was rejected as too generic.
11100
+ * [at_compartment=5] The Harborlight CRD kind is QueueShard; "WorkPartition" was rejected as too generic.
11050
11101
  </NAMING>
11051
11102
  </facts>
11052
11103
  <events>
@@ -11081,13 +11132,13 @@ CAN RX no longer allocates or sends BLE notifications inside the ISR; frames are
11081
11132
  </compartment>
11082
11133
  <facts>
11083
11134
  <PROJECT_RULES>
11084
- * Pawprint firmware ISR paths must not allocate; enqueue to can_rx_ring and wake deferred work instead.
11135
+ * [at_compartment=3] Pawprint firmware ISR paths must not allocate; enqueue to can_rx_ring and wake deferred work instead.
11085
11136
  </PROJECT_RULES>
11086
11137
  <CONSTRAINTS>
11087
- * nRF52840 BLE notification from IRQ context can trigger supervisor reset when SoftDevice holds the radio lock.
11138
+ * [at_compartment=3] nRF52840 BLE notification from IRQ context can trigger supervisor reset when SoftDevice holds the radio lock.
11088
11139
  </CONSTRAINTS>
11089
11140
  <CONFIG_VALUES>
11090
- * Pawprint can_rx_ring depth is 32 frames, with overflow counted by can_rx_ring_overrun.
11141
+ * [at_compartment=3] Pawprint can_rx_ring depth is 32 frames, with overflow counted by can_rx_ring_overrun.
11091
11142
  </CONFIG_VALUES>
11092
11143
  </facts>
11093
11144
  <events>
@@ -11124,10 +11175,10 @@ unscale_ → clip_grad_norm_ → step
11124
11175
  </compartment>
11125
11176
  <facts>
11126
11177
  <CONSTRAINTS>
11127
- * \`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.
11178
+ * [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.
11128
11179
  </CONSTRAINTS>
11129
11180
  <ARCHITECTURE>
11130
- * In mixed-precision training, gradient clipping is computed against TRUE gradient magnitudes — \`scaler.unscale_(optimizer)\` must run before any norm-based clipping.
11181
+ * [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.
11131
11182
  </ARCHITECTURE>
11132
11183
  </facts>
11133
11184
  <events>
@@ -11166,13 +11217,13 @@ LoomDoc wraps Y.Doc; HLC (physical_ms, logical, node_id); skew cap 300s
11166
11217
  </compartment>
11167
11218
  <facts>
11168
11219
  <ARCHITECTURE>
11169
- * 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.
11220
+ * [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.
11170
11221
  </ARCHITECTURE>
11171
11222
  <CONSTRAINTS>
11172
- * 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.
11223
+ * [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.
11173
11224
  </CONSTRAINTS>
11174
11225
  <NAMING>
11175
- * CRDT library: Yjs (rejected Automerge for merge-cost scaling on ~50k-char documents). Our wrapper type is \`LoomDoc\`.
11226
+ * [at_compartment=1] CRDT library: Yjs (rejected Automerge for merge-cost scaling on ~50k-char documents). Our wrapper type is \`LoomDoc\`.
11176
11227
  </NAMING>
11177
11228
  </facts>`
11178
11229
  },
@@ -11196,21 +11247,21 @@ Billetto made proration credits auditable by storing them in its own ledger tabl
11196
11247
  </compartment>
11197
11248
  <facts>
11198
11249
  <PROJECT_RULES>
11199
- * Billetto billing migrations must include a rollback dry-run against test/fixtures/billing-ledger/.
11250
+ * [at_compartment=1] Billetto billing migrations must include a rollback dry-run against test/fixtures/billing-ledger/.
11200
11251
  </PROJECT_RULES>
11201
11252
  <ARCHITECTURE>
11202
- * Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
11203
- * Billetto proration calculation is idempotent around subscription_version and reuses existing ledger entries on retry.
11253
+ * [at_compartment=1] Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
11254
+ * [at_compartment=1] Billetto proration calculation is idempotent around subscription_version and reuses existing ledger entries on retry.
11204
11255
  </ARCHITECTURE>
11205
11256
  <CONSTRAINTS>
11206
- * Stripe invoice metadata is not a durable Billetto credit ledger because dashboard edits can mutate it outside the app.
11257
+ * [at_compartment=1] Stripe invoice metadata is not a durable Billetto credit ledger because dashboard edits can mutate it outside the app.
11207
11258
  </CONSTRAINTS>
11208
11259
  <CONFIG_VALUES>
11209
- * Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
11210
- * Billetto Stripe idempotency key format for proration is proration:{account_id}:{subscription_version}:{invoice_id}.
11260
+ * [at_compartment=1] Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
11261
+ * [at_compartment=1] Billetto Stripe idempotency key format for proration is proration:{account_id}:{subscription_version}:{invoice_id}.
11211
11262
  </CONFIG_VALUES>
11212
11263
  <NAMING>
11213
- * The Billetto credit ledger table is named account_credit_entries; "negative_invoice_lines" was rejected.
11264
+ * [at_compartment=1] The Billetto credit ledger table is named account_credit_entries; "negative_invoice_lines" was rejected.
11214
11265
  </NAMING>
11215
11266
  </facts>`
11216
11267
  },
@@ -11232,10 +11283,10 @@ Nereid contrastive training stabilized after restoring per-worker augmentation s
11232
11283
  </compartment>
11233
11284
  <facts>
11234
11285
  <CONSTRAINTS>
11235
- * Nereid's contrastive trainer can diverge if augmentation_seed is shared across dataloader workers.
11286
+ * [at_compartment=2] Nereid's contrastive trainer can diverge if augmentation_seed is shared across dataloader workers.
11236
11287
  </CONSTRAINTS>
11237
11288
  <CONFIG_VALUES>
11238
- * Nereid worker augmentation seed formula is base_seed + worker_id + epoch * 1009.
11289
+ * [at_compartment=2] Nereid worker augmentation seed formula is base_seed + worker_id + epoch * 1009.
11239
11290
  </CONFIG_VALUES>
11240
11291
  </facts>
11241
11292
  <events>
@@ -11274,19 +11325,19 @@ billing.stripe_event_idempotency; key = event.id; TTL 90d
11274
11325
  </compartment>
11275
11326
  <facts>
11276
11327
  <PROJECT_RULES>
11277
- * 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.
11328
+ * [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.
11278
11329
  </PROJECT_RULES>
11279
11330
  <CONSTRAINTS>
11280
- * 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.
11331
+ * [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.
11281
11332
  </CONSTRAINTS>
11282
11333
  <ARCHITECTURE>
11283
- * 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.
11334
+ * [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.
11284
11335
  </ARCHITECTURE>
11285
11336
  <CONFIG_VALUES>
11286
- * \`billing.stripe_event_idempotency\` table; primary key on \`event_id\`; row TTL 90 days; wrapper in \`internal/billing/webhooks/idempotent.go\`.
11337
+ * [at_compartment=8] \`billing.stripe_event_idempotency\` table; primary key on \`event_id\`; row TTL 90 days; wrapper in \`internal/billing/webhooks/idempotent.go\`.
11287
11338
  </CONFIG_VALUES>
11288
11339
  <NAMING>
11289
- * Webhook idempotency table is \`billing.stripe_event_idempotency\`. Future provider-specific tables follow the pattern \`<provider>_event_idempotency\`.
11340
+ * [at_compartment=8] Webhook idempotency table is \`billing.stripe_event_idempotency\`. Future provider-specific tables follow the pattern \`<provider>_event_idempotency\`.
11290
11341
  </NAMING>
11291
11342
  </facts>
11292
11343
  <events>
@@ -11329,13 +11380,13 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
11329
11380
  </compartment>
11330
11381
  <facts>
11331
11382
  <CONSTRAINTS>
11332
- * 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).
11383
+ * [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).
11333
11384
  </CONSTRAINTS>
11334
11385
  <PROJECT_RULES>
11335
- * Tethys token refresh must always re-fetch tenant_roles from the DB; never carry role claims forward from the incoming token.
11386
+ * [at_compartment=15] Tethys token refresh must always re-fetch tenant_roles from the DB; never carry role claims forward from the incoming token.
11336
11387
  </PROJECT_RULES>
11337
11388
  <CONFIG_VALUES>
11338
- * Tethys token TTLs: access_token_ttl=900 s, refresh_token_ttl=86400 s.
11389
+ * [at_compartment=15] Tethys token TTLs: access_token_ttl=900 s, refresh_token_ttl=86400 s.
11339
11390
  </CONFIG_VALUES>
11340
11391
  </facts>
11341
11392
  <events>
@@ -11355,7 +11406,7 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
11355
11406
  },
11356
11407
  {
11357
11408
  importance: 74,
11358
- 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>'
11409
+ 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>'
11359
11410
  },
11360
11411
  {
11361
11412
  importance: 74,
@@ -11375,16 +11426,16 @@ Partition membership changes now fence planner statistics through partition_epoc
11375
11426
  </compartment>
11376
11427
  <facts>
11377
11428
  <PROJECT_RULES>
11378
- * Any catalog change affecting partition membership needs a planner regression under tests/sql/partition_pruning_regress.slt.
11429
+ * [at_compartment=13] Any catalog change affecting partition membership needs a planner regression under tests/sql/partition_pruning_regress.slt.
11379
11430
  </PROJECT_RULES>
11380
11431
  <ARCHITECTURE>
11381
- * Planner stats cache keys include partition_epoch so partition topology changes invalidate selectivity estimates without clearing the whole cache.
11432
+ * [at_compartment=13] Planner stats cache keys include partition_epoch so partition topology changes invalidate selectivity estimates without clearing the whole cache.
11382
11433
  </ARCHITECTURE>
11383
11434
  <CONSTRAINTS>
11384
- * Child partition attach and detach can make NDV and selectivity data unsafe even when the parent table schema is unchanged.
11435
+ * [at_compartment=13] Child partition attach and detach can make NDV and selectivity data unsafe even when the parent table schema is unchanged.
11385
11436
  </CONSTRAINTS>
11386
11437
  <CONFIG_VALUES>
11387
- * New planner cache key field: partition_epoch.
11438
+ * [at_compartment=13] New planner cache key field: partition_epoch.
11388
11439
  </CONFIG_VALUES>
11389
11440
  </facts>
11390
11441
  <events>
@@ -11419,13 +11470,13 @@ CollabPad CRDT ordering now follows document clocks rather than server receive t
11419
11470
  </compartment>
11420
11471
  <facts>
11421
11472
  <ARCHITECTURE>
11422
- * CollabPad orders CRDT operations by (lamport, site_id); server receivedAt is telemetry only.
11473
+ * [at_compartment=10] CollabPad orders CRDT operations by (lamport, site_id); server receivedAt is telemetry only.
11423
11474
  </ARCHITECTURE>
11424
11475
  <CONSTRAINTS>
11425
- * WebRTC reconnect can deliver buffered CollabPad ops older than a websocket ack, so receivedAt cannot be used as causal order.
11476
+ * [at_compartment=10] WebRTC reconnect can deliver buffered CollabPad ops older than a websocket ack, so receivedAt cannot be used as causal order.
11426
11477
  </CONSTRAINTS>
11427
11478
  <NAMING>
11428
- * CollabPad's editing-site field is named site_id rather than clientId because multiple browser contexts can share one account.
11479
+ * [at_compartment=10] CollabPad's editing-site field is named site_id rather than clientId because multiple browser contexts can share one account.
11429
11480
  </NAMING>
11430
11481
  </facts>
11431
11482
  <events>
@@ -11462,10 +11513,10 @@ bond_table partition 0x7E000–0x7FFFF; pm_static.yml
11462
11513
  </compartment>
11463
11514
  <facts>
11464
11515
  <CONSTRAINTS>
11465
- * 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\`.
11516
+ * [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\`.
11466
11517
  </CONSTRAINTS>
11467
11518
  <CONFIG_VALUES>
11468
- * \`bond_table\` partition reserved at 0x7E000–0x7FFFF in \`pm_static.yml\`. OTA pre-swap erase range narrowed to 0x70000–0x7DFFF.
11519
+ * [at_compartment=6] \`bond_table\` partition reserved at 0x7E000–0x7FFFF in \`pm_static.yml\`. OTA pre-swap erase range narrowed to 0x70000–0x7DFFF.
11469
11520
  </CONFIG_VALUES>
11470
11521
  </facts>
11471
11522
  <events>
@@ -11502,10 +11553,10 @@ leader election; Lease resource; VESPER_LEASE_DURATION_S; VESPER_RENEW_INTERVAL_
11502
11553
  </compartment>
11503
11554
  <facts>
11504
11555
  <ARCHITECTURE>
11505
- * Vesper controller uses Kubernetes Lease-based leader election; non-holder replicas skip the reconcile loop entirely and only run health probes.
11556
+ * [at_compartment=1] Vesper controller uses Kubernetes Lease-based leader election; non-holder replicas skip the reconcile loop entirely and only run health probes.
11506
11557
  </ARCHITECTURE>
11507
11558
  <CONFIG_VALUES>
11508
- * Vesper leader election defaults: VESPER_LEASE_DURATION_S=30, VESPER_RENEW_INTERVAL_S=10, VESPER_ACQUIRE_DEADLINE_S=8 (all overridable via env).
11559
+ * [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).
11509
11560
  </CONFIG_VALUES>
11510
11561
  </facts>`
11511
11562
  },
@@ -11537,13 +11588,13 @@ onPreInstall; onPostInstall; onRemove; schema_version; dependency-declaration or
11537
11588
  </compartment>
11538
11589
  <facts>
11539
11590
  <ARCHITECTURE>
11540
- * boltpkg plugin hooks execute in plugin dependency-declaration order, not registration order; deterministic and matches user expectations about dependency sequencing.
11591
+ * [at_compartment=17] boltpkg plugin hooks execute in plugin dependency-declaration order, not registration order; deterministic and matches user expectations about dependency sequencing.
11541
11592
  </ARCHITECTURE>
11542
11593
  <NAMING>
11543
- * boltpkg plugin lifecycle hooks: onPreInstall, onPostInstall, onRemove (src/plugin/types.ts).
11594
+ * [at_compartment=17] boltpkg plugin lifecycle hooks: onPreInstall, onPostInstall, onRemove (src/plugin/types.ts).
11544
11595
  </NAMING>
11545
11596
  <PROJECT_RULES>
11546
- * boltpkg plugin manifests must include schema_version; the loader rejects manifests with unrecognized schema versions to prevent silently running mismatched plugins.
11597
+ * [at_compartment=17] boltpkg plugin manifests must include schema_version; the loader rejects manifests with unrecognized schema versions to prevent silently running mismatched plugins.
11547
11598
  </PROJECT_RULES>
11548
11599
  </facts>
11549
11600
  <events>
@@ -11575,16 +11626,16 @@ Subscription MRR history moved into a daily fact table instead of being reconstr
11575
11626
  </compartment>
11576
11627
  <facts>
11577
11628
  <PROJECT_RULES>
11578
- * Northstar DW subscription backfills should use the backfill_subscription_day dbt macro instead of ad hoc DELETE and INSERT queries.
11629
+ * [at_compartment=1] Northstar DW subscription backfills should use the backfill_subscription_day dbt macro instead of ad hoc DELETE and INSERT queries.
11579
11630
  </PROJECT_RULES>
11580
11631
  <ARCHITECTURE>
11581
- * Northstar DW answers historical MRR from fct_subscription_day daily snapshots rather than replaying raw billing events at query time.
11632
+ * [at_compartment=1] Northstar DW answers historical MRR from fct_subscription_day daily snapshots rather than replaying raw billing events at query time.
11582
11633
  </ARCHITECTURE>
11583
11634
  <CONFIG_VALUES>
11584
- * fct_subscription_day is materialized incrementally with unique key account_id, subscription_id, and date_day.
11635
+ * [at_compartment=1] fct_subscription_day is materialized incrementally with unique key account_id, subscription_id, and date_day.
11585
11636
  </CONFIG_VALUES>
11586
11637
  <NAMING>
11587
- * The subscription daily snapshot model is named fct_subscription_day.
11638
+ * [at_compartment=1] The subscription daily snapshot model is named fct_subscription_day.
11588
11639
  </NAMING>
11589
11640
  </facts>`
11590
11641
  },
@@ -11612,10 +11663,10 @@ bucket width 50; K=24; asymmetric expansion down-only first 60s
11612
11663
  </compartment>
11613
11664
  <facts>
11614
11665
  <CONFIG_VALUES>
11615
- * Matchmaking: bucket width 50 MMR, K-factor 24, native-bucket wait 60s, down-only expansion phase 60s, symmetric expansion after 120s.
11666
+ * [at_compartment=1] Matchmaking: bucket width 50 MMR, K-factor 24, native-bucket wait 60s, down-only expansion phase 60s, symmetric expansion after 120s.
11616
11667
  </CONFIG_VALUES>
11617
11668
  <ARCHITECTURE>
11618
- * 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.
11669
+ * [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.
11619
11670
  </ARCHITECTURE>
11620
11671
  </facts>
11621
11672
  <user_observations>
@@ -11638,7 +11689,7 @@ PDF page rotation is captured before OCR rasterization so Tesseract sees the cor
11638
11689
  </compartment>
11639
11690
  <facts>
11640
11691
  <CONSTRAINTS>
11641
- * QuillOCR cannot rely on pdfimages output for page rotation when Poppler emits JBIG2 masks; rotation must be read from pdfinfo before rasterization.
11692
+ * [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.
11642
11693
  </CONSTRAINTS>
11643
11694
  </facts>
11644
11695
  <events>
@@ -11669,13 +11720,13 @@ Synonym edits are now shipped by building and promoting a shadow index, not by r
11669
11720
  </compartment>
11670
11721
  <facts>
11671
11722
  <PROJECT_RULES>
11672
- * Search schema changes and synonym changes ship through the same shadow-index promotion workflow.
11723
+ * [at_compartment=1] Search schema changes and synonym changes ship through the same shadow-index promotion workflow.
11673
11724
  </PROJECT_RULES>
11674
11725
  <ARCHITECTURE>
11675
- * Synonym changes are applied by building a shadow index and swapping aliases, not by reloading the hot index in place.
11726
+ * [at_compartment=1] Synonym changes are applied by building a shadow index and swapping aliases, not by reloading the hot index in place.
11676
11727
  </ARCHITECTURE>
11677
11728
  <NAMING>
11678
- * The paired search aliases are products_live and products_next.
11729
+ * [at_compartment=1] The paired search aliases are products_live and products_next.
11679
11730
  </NAMING>
11680
11731
  </facts>`
11681
11732
  },
@@ -11697,16 +11748,16 @@ Ranked duo matchmaking now preserves parties even when it increases queue time.
11697
11748
  </compartment>
11698
11749
  <facts>
11699
11750
  <PROJECT_RULES>
11700
- * Arcade Relay matchmaker must not split a party_id across ranked lobbies; widen match criteria before breaking party constraints.
11751
+ * [at_compartment=1] Arcade Relay matchmaker must not split a party_id across ranked lobbies; widen match criteria before breaking party constraints.
11701
11752
  </PROJECT_RULES>
11702
11753
  <CONFIG_VALUES>
11703
- * Arcade Relay ranked_duo MMR window widens by 75 every 15s up to 450.
11754
+ * [at_compartment=1] Arcade Relay ranked_duo MMR window widens by 75 every 15s up to 450.
11704
11755
  </CONFIG_VALUES>
11705
11756
  </facts>`
11706
11757
  },
11707
11758
  {
11708
11759
  importance: 52,
11709
- 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>'
11760
+ 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>'
11710
11761
  },
11711
11762
  {
11712
11763
  importance: 48,
@@ -11745,10 +11796,10 @@ tesseract=5.3.3; docker/ocr/Dockerfile; upstream #4117
11745
11796
  </compartment>
11746
11797
  <facts>
11747
11798
  <CONFIG_VALUES>
11748
- * \`docker/ocr/Dockerfile\` pins \`tesseract-ocr=5.3.3\` with apt version + SHA pin. Unpin only after upstream #4117 resolves.
11799
+ * [at_compartment=10] \`docker/ocr/Dockerfile\` pins \`tesseract-ocr=5.3.3\` with apt version + SHA pin. Unpin only after upstream #4117 resolves.
11749
11800
  </CONFIG_VALUES>
11750
11801
  <CONSTRAINTS>
11751
- * Tesseract 5.3.4 regresses multi-column layout detection (column-detection heuristic in LSTM postprocessing changed). Single-column accuracy is unaffected.
11802
+ * [at_compartment=10] Tesseract 5.3.4 regresses multi-column layout detection (column-detection heuristic in LSTM postprocessing changed). Single-column accuracy is unaffected.
11752
11803
  </CONSTRAINTS>
11753
11804
  </facts>
11754
11805
  <events>
@@ -11781,10 +11832,10 @@ Snapbench recording examples became runnable instead of descriptive only.
11781
11832
  </compartment>
11782
11833
  <facts>
11783
11834
  <CONFIG_VALUES>
11784
- * Snapbench's default snapshot directory is .snapbench/.
11835
+ * [at_compartment=1] Snapbench's default snapshot directory is .snapbench/.
11785
11836
  </CONFIG_VALUES>
11786
11837
  <NAMING>
11787
- * The Snapbench capture subcommand is named snapbench record.
11838
+ * [at_compartment=1] The Snapbench capture subcommand is named snapbench record.
11788
11839
  </NAMING>
11789
11840
  </facts>
11790
11841
  <user_observations>
@@ -11817,7 +11868,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
11817
11868
  </compartment>
11818
11869
  <facts>
11819
11870
  <CONSTRAINTS>
11820
- * 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.
11871
+ * [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.
11821
11872
  </CONSTRAINTS>
11822
11873
  </facts>
11823
11874
  <events>
@@ -11834,7 +11885,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
11834
11885
  },
11835
11886
  {
11836
11887
  importance: 36,
11837
- 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>'
11888
+ 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>'
11838
11889
  },
11839
11890
  {
11840
11891
  importance: 36,
@@ -11869,7 +11920,7 @@ Polaris; data/preprocessed/; preprocessor.py; polaris.preprocess; preprocess.yam
11869
11920
  </compartment>
11870
11921
  <facts>
11871
11922
  <CONFIG_VALUES>
11872
- * 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.
11923
+ * [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.
11873
11924
  </CONFIG_VALUES>
11874
11925
  </facts>`
11875
11926
  },
@@ -11892,10 +11943,10 @@ The SKU importer now defaults to a safe preview workflow instead of assuming liv
11892
11943
  </compartment>
11893
11944
  <facts>
11894
11945
  <PROJECT_RULES>
11895
- * New operational import commands should default to preview mode unless an explicit apply flag is present.
11946
+ * [at_compartment=15] New operational import commands should default to preview mode unless an explicit apply flag is present.
11896
11947
  </PROJECT_RULES>
11897
11948
  <CONFIG_VALUES>
11898
- * Destructive execution flag: --apply; preview mode is the default when it is absent.
11949
+ * [at_compartment=15] Destructive execution flag: --apply; preview mode is the default when it is absent.
11899
11950
  </CONFIG_VALUES>
11900
11951
  </facts>
11901
11952
  <events>
@@ -11928,7 +11979,7 @@ Invalid IoT telemetry is retained in a DLQ instead of silently disappearing.
11928
11979
  </compartment>
11929
11980
  <facts>
11930
11981
  <CONFIG_VALUES>
11931
- * BeaconMesh malformed raw telemetry is routed to Kafka topic telemetry.raw.dlq.v2.
11982
+ * [at_compartment=1] BeaconMesh malformed raw telemetry is routed to Kafka topic telemetry.raw.dlq.v2.
11932
11983
  </CONFIG_VALUES>
11933
11984
  </facts>`
11934
11985
  },
@@ -11950,7 +12001,7 @@ Mobile offline sync shipped with a narrow notes-only scope.
11950
12001
  </compartment>
11951
12002
  <facts>
11952
12003
  <CONFIG_VALUES>
11953
- * Harbor Notes offline sync MVP includes note title and body only; attachments and comment threads remain online-only.
12004
+ * [at_compartment=1] Harbor Notes offline sync MVP includes note title and body only; attachments and comment threads remain online-only.
11954
12005
  </CONFIG_VALUES>
11955
12006
  </facts>`
11956
12007
  },
@@ -11976,10 +12027,10 @@ Low-confidence scan rotation is now handled through a manual override path, with
11976
12027
  </compartment>
11977
12028
  <facts>
11978
12029
  <CONSTRAINTS>
11979
- * OCR angle predictions below a high confidence threshold are not reliable enough for unattended page rotation on messy multi-scan uploads.
12030
+ * [at_compartment=19] OCR angle predictions below a high confidence threshold are not reliable enough for unattended page rotation on messy multi-scan uploads.
11980
12031
  </CONSTRAINTS>
11981
12032
  <CONFIG_VALUES>
11982
- * Automatic rotation threshold: angle_confidence 0.98 or higher.
12033
+ * [at_compartment=19] Automatic rotation threshold: angle_confidence 0.98 or higher.
11983
12034
  </CONFIG_VALUES>
11984
12035
  </facts>
11985
12036
  <events>
@@ -12053,7 +12104,7 @@ This was a scoped replay, not a lasting data-model change: the useful outcome wa
12053
12104
  </compartment>
12054
12105
  <facts>
12055
12106
  <CONFIG_VALUES>
12056
- * The orders repair workflow is keyed off landed_at partitions rather than invoice_date.
12107
+ * [at_compartment=5] The orders repair workflow is keyed off landed_at partitions rather than invoice_date.
12057
12108
  </CONFIG_VALUES>
12058
12109
  </facts>
12059
12110
  <events>
@@ -12098,13 +12149,13 @@ README install path fixed for Apple Silicon.
12098
12149
  </compartment>
12099
12150
  <facts>
12100
12151
  <NAMING>
12101
- * 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\`.
12152
+ * [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\`.
12102
12153
  </NAMING>
12103
12154
  </facts>`
12104
12155
  },
12105
12156
  {
12106
12157
  importance: 17,
12107
- 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>'
12158
+ 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>'
12108
12159
  },
12109
12160
  {
12110
12161
  importance: 14,
@@ -12146,7 +12197,7 @@ kind; ci/kind-config.yaml; kindest/node:v1.29.2; integration.yml
12146
12197
  </compartment>
12147
12198
  <facts>
12148
12199
  <CONFIG_VALUES>
12149
- * Vesper CI kind cluster: config ci/kind-config.yaml, node image kindest/node:v1.29.2.
12200
+ * [at_compartment=1] Vesper CI kind cluster: config ci/kind-config.yaml, node image kindest/node:v1.29.2.
12150
12201
  </CONFIG_VALUES>
12151
12202
  </facts>`
12152
12203
  },
@@ -12203,7 +12254,7 @@ False start: attempted-and-reverted controller-runtime cache bypass.
12203
12254
  </compartment>
12204
12255
  <facts>
12205
12256
  <CONSTRAINTS>
12206
- * controller-runtime's cache is itself informer-backed; "going direct to informers" doesn't remove any indirection and gives no latency benefit.
12257
+ * [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.
12207
12258
  </CONSTRAINTS>
12208
12259
  </facts>
12209
12260
  <events>
@@ -12328,7 +12379,7 @@ Captured high-load CAN bus limitation in firmware docs.
12328
12379
  </compartment>
12329
12380
  <facts>
12330
12381
  <CONSTRAINTS>
12331
- * CAN bus arbitration on the current MCU fails under >80% bus load; requires priority inversion mitigation in the driver.
12382
+ * [at_compartment=1] CAN bus arbitration on the current MCU fails under >80% bus load; requires priority inversion mitigation in the driver.
12332
12383
  </CONSTRAINTS>
12333
12384
  </facts>`
12334
12385
  },
@@ -12378,7 +12429,7 @@ Docs examples section was renamed.
12378
12429
  </compartment>
12379
12430
  <facts>
12380
12431
  <NAMING>
12381
- * AstraKit's docs navigation label for examples is "Cookbook", not "Recipes".
12432
+ * [at_compartment=1] AstraKit's docs navigation label for examples is "Cookbook", not "Recipes".
12382
12433
  </NAMING>
12383
12434
  </facts>`
12384
12435
  }
@@ -13161,7 +13212,7 @@ async function runHistorianPrompt(args) {
13161
13212
  promptSettled = false;
13162
13213
  const errorMsg = getErrorMessage(error);
13163
13214
  sessionLog2(parentSessionId, `historian: prompt attempt ${retryIndex + 1} failed: ${errorMsg}`);
13164
- const shouldRetry = retryIndex < MAX_HISTORIAN_RETRIES && isTransientHistorianPromptError(errorMsg);
13215
+ const shouldRetry = retryIndex < MAX_HISTORIAN_RETRIES && !(error instanceof HiddenCompletionRefusal && error.code === "hidden_setup_timeout") && isTransientHistorianPromptError(errorMsg);
13165
13216
  if (!shouldRetry) {
13166
13217
  throw error;
13167
13218
  }
@@ -13383,761 +13434,552 @@ function sanitizeDumpName(value) {
13383
13434
  return value.replace(/[^a-zA-Z0-9._-]/g, "-");
13384
13435
  }
13385
13436
 
13386
- // src/hooks/magic-context/historian-failure-report.ts
13387
- var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
13388
- var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
13389
- 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.";
13390
- var REFUSAL_ERROR_MAX_CHARS = 500;
13391
- var WARNING_ERROR_MAX_CHARS = 200;
13392
- function readHistorianFailureStreak(db, sessionId, options = {}) {
13393
- const state = getHistorianFailureState(db, sessionId);
13394
- const count = state.failureCount;
13395
- let since = null;
13396
- if (count > 0) {
13397
- const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
13398
- if (recorded <= 0) {
13399
- since = state.lastFailureAt;
13400
- } else {
13401
- const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
13402
- since = times.length === recorded ? times[recorded - 1] ?? null : null;
13403
- }
13437
+ // src/hooks/magic-context/file-token-coverage.ts
13438
+ function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
13439
+ const filesByMessage = new Map;
13440
+ for (const message of messages) {
13441
+ const count = message.parts.filter(isFilePart).length;
13442
+ if (count > 0 && totals.has(message.id))
13443
+ filesByMessage.set(message.id, count);
13404
13444
  }
13405
- return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
13445
+ if (filesByMessage.size === 0)
13446
+ return totals;
13447
+ const rows = db.prepare(`
13448
+ SELECT o.value AS owner, COUNT(t.id) AS count
13449
+ FROM json_each(?) o LEFT JOIN tags t
13450
+ ON t.session_id = ? AND t.type = 'file'
13451
+ AND t.message_id >= o.value || ':file'
13452
+ AND t.message_id < o.value || ':file;'
13453
+ GROUP BY o.value
13454
+ `).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
13455
+ for (const row of rows) {
13456
+ if (row.count < (filesByMessage.get(row.owner) ?? 0))
13457
+ totals.delete(row.owner);
13458
+ }
13459
+ return totals;
13406
13460
  }
13407
- function formatHistorianClockTime(at, now = Date.now()) {
13408
- const date = new Date(at);
13409
- const pad = (value) => String(value).padStart(2, "0");
13410
- const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
13411
- const today = new Date(now);
13412
- const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
13413
- return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
13461
+
13462
+ // src/hooks/magic-context/protected-tail-boundary.ts
13463
+ function describeBoundaryDiagnostics(snapshot) {
13464
+ return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
13414
13465
  }
13415
- function formatHistorianSeconds(ms) {
13416
- const seconds = Math.max(0, ms) / 1000;
13417
- return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
13466
+ function boundaryDiagnostics(args) {
13467
+ return {
13468
+ ...args,
13469
+ capTier: args.usagePercentage >= 95 ? "95" : args.usagePercentage >= 80 ? "80" : "normal",
13470
+ drainBudget: "not-reserved; does-not-size-cap"
13471
+ };
13418
13472
  }
13419
- function singleLine(text) {
13420
- return text.replace(/\s+/g, " ").trim();
13473
+ var ALPHA = 0.3;
13474
+ var FLOOR_RATIO = 0.08;
13475
+ var FLOOR_MIN = 2000;
13476
+ var FLOOR_MAX = 12000;
13477
+ var ABS_CAP = 96000;
13478
+ var MAX_USABLE_RATIO = 0.4;
13479
+ var RESERVED_HEADROOM_MIN = 1000;
13480
+ var RESERVED_HEADROOM_RATIO = 0.02;
13481
+ var NON_EMERGENCY_MAX_CAP = 250000;
13482
+ var FORCE80_MAX_CAP = 500000;
13483
+ var FORCE95_MAX_CAP = 750000;
13484
+ var NORMAL_HYSTERESIS_TOKENS = 256;
13485
+ var RECOVERY_NO_HEAD_LIMIT = 2;
13486
+ function clampPercentage(value) {
13487
+ if (!Number.isFinite(value))
13488
+ return 0;
13489
+ return Math.max(0, Math.min(100, value));
13421
13490
  }
13422
- function quoteError(error, maxChars) {
13423
- const text = sanitizeDiagnosticText(singleLine(error));
13424
- return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
13491
+ function clampOrdinal(value, rawMessageCount) {
13492
+ return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
13425
13493
  }
13426
- function endSentence(text) {
13427
- return /[.!?]$/.test(text) ? text : `${text}.`;
13494
+ function deriveProtectedTailTokenTarget(args) {
13495
+ const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
13496
+ const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
13497
+ const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
13498
+ const usage = clampPercentage(args.usagePercentage);
13499
+ const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
13500
+ const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
13501
+ const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
13502
+ const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
13503
+ const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
13504
+ const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
13505
+ const effectiveFloor = Math.min(floorN, ceilingN);
13506
+ const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
13507
+ return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
13428
13508
  }
13429
- function usageClause(usagePercentage) {
13430
- return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
13509
+ function nonEmergencyPerRunCap(usable, N) {
13510
+ return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
13431
13511
  }
13432
- function capitalize(text) {
13433
- return text.charAt(0).toUpperCase() + text.slice(1);
13512
+ function force80PerRunCap(usable, N) {
13513
+ return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
13434
13514
  }
13435
- function chunkLabel(chunk) {
13436
- return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
13515
+ function force95PerRunCap(usable, N) {
13516
+ return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
13437
13517
  }
13438
- function streakSentence(failures, now) {
13439
- if (failures.count <= 0)
13518
+ function selectPerRunCap(snapshot) {
13519
+ const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
13520
+ if (snapshot.usagePercentage >= 95)
13521
+ return force95PerRunCap(usable, snapshot.N);
13522
+ if (snapshot.usagePercentage >= 80)
13523
+ return force80PerRunCap(usable, snapshot.N);
13524
+ return nonEmergencyPerRunCap(usable, snapshot.N);
13525
+ }
13526
+ function boundaryMessageId(index, ordinal) {
13527
+ if (ordinal < 1 || ordinal > index.rawMessageCount)
13440
13528
  return null;
13441
- const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
13442
- return `Summary runs failed in a row: ${failures.count}${since}.`;
13529
+ return index.messageIdAtOrdinal(ordinal);
13443
13530
  }
13444
- function failureBelongsToRun(failures, run) {
13445
- return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
13531
+ function isSemanticBoundaryCandidate(messageParts, role) {
13532
+ if (role === "user" && hasMeaningfulUserText2(messageParts))
13533
+ return true;
13534
+ if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
13535
+ return true;
13536
+ }
13537
+ return false;
13446
13538
  }
13447
- function describeHistorianJoinRefusal(input) {
13448
- const now = input.now ?? Date.now();
13449
- const { run, failures } = input;
13450
- const sentences = [
13451
- `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.`
13452
- ];
13453
- const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
13454
- const ownFailure = failureBelongsToRun(failures, run);
13455
- const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
13456
- if (ownFailure) {
13457
- sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
13458
- } else if (run && run.endedAt === undefined) {
13459
- sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
13460
- } else if (run) {
13461
- sentences.push(`${subject} finished after the wait ended.`);
13539
+ function semanticSnapBoundary(args) {
13540
+ const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
13541
+ let snapped = candidate;
13542
+ for (const message of messages) {
13543
+ if (message.ordinal > candidate)
13544
+ break;
13545
+ if (message.ordinal < lastCompartmentEndOrdinal + 1)
13546
+ continue;
13547
+ if (!isSemanticBoundaryCandidate(message.parts, message.role))
13548
+ continue;
13549
+ snapped = message.ordinal;
13462
13550
  }
13463
- if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
13464
- sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
13551
+ if (snapped === candidate)
13552
+ return candidate;
13553
+ const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
13554
+ if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
13555
+ return candidate;
13556
+ const snappedMessage = messages.find((message) => message.ordinal === snapped);
13557
+ if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
13558
+ return candidate;
13465
13559
  }
13466
- const streak = streakSentence(failures, now);
13467
- if (streak)
13468
- sentences.push(streak);
13469
- sentences.push(ACTIONS);
13470
- return sentences.join(" ");
13471
- }
13472
- function describeRepeatedHistorianFailures(input) {
13473
- const now = input.now ?? Date.now();
13474
- const { failures } = input;
13475
- const facts = [
13476
- streakSentence(failures, now) ?? "Summary runs are failing.",
13477
- ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
13478
- ...failures.lastError ? [
13479
- endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
13480
- ] : [],
13481
- `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
13482
- ];
13483
- return [
13484
- "## Magic Context — History summaries keep failing",
13485
- "",
13486
- facts.join(" "),
13487
- "",
13488
- ACTIONS
13489
- ].join(`
13490
- `);
13560
+ return snapped;
13491
13561
  }
13492
- var repeatedFailureWarnings = new Map;
13493
- function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
13494
- const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
13495
- if (failureCount < step || failureCount % step !== 0)
13496
- return false;
13497
- const last = repeatedFailureWarnings.get(sessionId);
13498
- if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
13499
- return false;
13562
+ function snapWrapupBoundaryToUser(args) {
13563
+ const { messages, index, candidate, offset, triggerBudget } = args;
13564
+ if (candidate <= offset)
13565
+ return candidate;
13566
+ const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
13567
+ for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
13568
+ const message = messages.find((m) => m.ordinal === ordinal);
13569
+ if (!message)
13570
+ continue;
13571
+ if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
13572
+ continue;
13573
+ const extraTokens = index.rangeTokens(ordinal, candidate);
13574
+ if (extraTokens <= snapTokenLimit)
13575
+ return ordinal;
13576
+ return candidate;
13500
13577
  }
13501
- repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
13502
- return true;
13578
+ return candidate;
13503
13579
  }
13504
- function takeRepeatedHistorianFailureWarning(input) {
13505
- const now = input.now ?? Date.now();
13506
- if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
13507
- return null;
13508
- }
13509
- const failures = readHistorianFailureStreak(input.db, input.sessionId, {
13510
- unrecordedFailures: input.unrecordedFailures
13511
- });
13512
- return describeRepeatedHistorianFailures({
13513
- chunk: input.chunk,
13514
- failures: { ...failures, count: input.failureCount },
13515
- usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
13516
- now
13517
- });
13518
- }
13519
-
13520
- // src/hooks/magic-context/historian-history-wait.ts
13521
- var historyWaits = new Map;
13522
- function newestMessageId(snapshot) {
13523
- try {
13524
- const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
13525
- const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
13526
- const newest = ids.keys().next().value;
13527
- if (newest)
13528
- return newest;
13529
- } catch {}
13530
- return snapshot.rawLastMessageIdAtTrigger;
13531
- }
13532
- function recoveryWindow(snapshot, percentage) {
13533
- return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
13534
- }
13535
- function clearHistorianHistoryWait(sessionId) {
13536
- historyWaits.delete(sessionId);
13580
+ function fenceWrapupBoundaryForToolArcs(args) {
13581
+ let boundary = args.candidate;
13582
+ const maxPasses = args.arcs.length + 1;
13583
+ for (let pass = 0;pass < maxPasses; pass += 1) {
13584
+ let next = boundary;
13585
+ for (const arc of args.arcs) {
13586
+ if (arc.resOrdinal === null) {
13587
+ continue;
13588
+ }
13589
+ if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
13590
+ next = arc.invOrdinal;
13591
+ }
13592
+ }
13593
+ if (next === boundary)
13594
+ return boundary;
13595
+ boundary = next;
13596
+ }
13597
+ return boundary;
13537
13598
  }
13538
- function recordHistorianNoProgress(snapshot, emergency = false) {
13539
- const newest = newestMessageId(snapshot);
13540
- if (!newest)
13541
- return;
13542
- const previous = historyWaits.get(snapshot.sessionId);
13543
- const sameHistory = previous?.newestMessageId === newest;
13544
- historyWaits.set(snapshot.sessionId, {
13545
- newestMessageId: newest,
13546
- recoveryAttempted: sameHistory && previous.recoveryAttempted || emergency || recoveryWindow(snapshot, snapshot.usagePercentage),
13547
- floorLiftAttempted: sameHistory && previous.floorLiftAttempted || snapshot.liftLivePromptFloor === true
13599
+ function applyHeadCap(args) {
13600
+ const {
13601
+ index,
13602
+ protectedTailStart,
13603
+ offset,
13604
+ arcs,
13605
+ lastCompartmentEndOrdinal,
13606
+ capTokens,
13607
+ recentOpenArcCutoff
13608
+ } = args;
13609
+ const diagnostics = {
13610
+ offset,
13611
+ capEnd: offset,
13612
+ capTokenSum: 0,
13613
+ completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
13614
+ oversizeAdmission: { from: offset, to: offset },
13615
+ openArcClamp: { from: offset, to: offset },
13616
+ completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
13617
+ eligibleEnd: offset
13618
+ };
13619
+ if (offset >= protectedTailStart) {
13620
+ args.observeDiagnostics?.(diagnostics);
13621
+ return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
13622
+ }
13623
+ let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
13624
+ diagnostics.capEnd = end;
13625
+ diagnostics.capTokenSum = index.rangeTokens(offset, end);
13626
+ let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
13627
+ let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
13628
+ diagnostics.completedFence.arcs = component.map((arc) => ({
13629
+ assistant: arc.invocation,
13630
+ result: arc.result
13631
+ }));
13632
+ diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
13548
13633
  });
13549
- }
13550
- function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
13551
- const wait = historyWaits.get(snapshot.sessionId);
13552
- if (!wait)
13553
- return false;
13554
- const newest = newestMessageId(snapshot);
13555
- if (newest && newest !== wait.newestMessageId) {
13556
- try {
13557
- const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
13558
- if (order === null || order > 0)
13559
- return false;
13560
- } catch {}
13634
+ diagnostics.completedFence.from = end;
13635
+ diagnostics.completedFence.to = completedFence;
13636
+ diagnostics.oversizeAdmission.from = completedFence;
13637
+ if (completedFence <= offset && end > offset) {
13638
+ const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
13639
+ if (afterFirstArc <= protectedTailStart)
13640
+ completedFence = afterFirstArc;
13561
13641
  }
13562
- const recovery = options.emergency || recoveryWindow(snapshot, options.usagePercentage ?? snapshot.usagePercentage);
13563
- const floorLift = snapshot.liftLivePromptFloor === true;
13564
- if (recovery && !wait.recoveryAttempted || floorLift && !wait.floorLiftAttempted) {
13565
- if (options.claim) {
13566
- wait.recoveryAttempted ||= recovery;
13567
- wait.floorLiftAttempted ||= floorLift;
13568
- }
13569
- return false;
13642
+ diagnostics.oversizeAdmission.to = completedFence;
13643
+ if (completedFence > end) {
13644
+ end = Math.min(protectedTailStart, completedFence);
13645
+ if (index.rangeTokens(offset, end) > capTokens)
13646
+ oversizeAtomicUnit = true;
13647
+ } else {
13648
+ end = completedFence;
13570
13649
  }
13571
- return true;
13572
- }
13573
-
13574
- // src/tools/ctx-note/render.ts
13575
- var GLANCE_TITLE_MAX = 80;
13576
- var NUDGE_TITLE_MAX = 60;
13577
- var STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
13578
- var EMPTY_READ_REPLY = `## Notes
13579
-
13580
- No session notes or smart notes.`;
13581
- function noteTouchedAt(note) {
13582
- return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
13583
- }
13584
- function formatNoteAge(touchedAt, nowMs) {
13585
- const elapsed = Math.max(0, nowMs - touchedAt);
13586
- const minutes = Math.floor(elapsed / 60000);
13587
- if (minutes < 60)
13588
- return `${minutes}m`;
13589
- const hours = Math.floor(elapsed / 3600000);
13590
- if (hours < 24)
13591
- return `${hours}h`;
13592
- const days = Math.floor(elapsed / 86400000);
13593
- if (days < 7)
13594
- return `${days}d`;
13595
- return `${Math.floor(days / 7)}w`;
13596
- }
13597
- function clipNoteTitle(content, max) {
13598
- const firstLine = (content.split(`
13599
- `, 1)[0] ?? "").trim();
13600
- const characters = [...firstLine];
13601
- if (characters.length <= max)
13602
- return firstLine;
13603
- return `${characters.slice(0, max).join("")}…`;
13604
- }
13605
- function formatGlanceRow(note, nowMs) {
13606
- const touchedAt = noteTouchedAt(note);
13607
- const markers = [];
13608
- if (note.status !== "active")
13609
- markers.push(note.status);
13610
- if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
13611
- markers.push(`parked: ${note.readyReason ?? "Condition can't be checked"}`);
13650
+ diagnostics.openArcClamp.from = end;
13651
+ for (const arc of arcs) {
13652
+ const resOrdinal = arc.resOrdinal;
13653
+ if (resOrdinal === null) {
13654
+ if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
13655
+ end = Math.min(end, arc.invOrdinal);
13656
+ }
13657
+ }
13612
13658
  }
13613
- if (nowMs - touchedAt >= STALE_AFTER_MS)
13614
- markers.push("stale");
13615
- const suffix = markers.length > 0 ? ` · ${markers.join(" · ")}` : "";
13616
- const title = clipNoteTitle(note.content, GLANCE_TITLE_MAX);
13617
- return `#${note.id} · ${formatNoteAge(touchedAt, nowMs)} · ${title}${suffix}`;
13618
- }
13619
- function newestFirst(left, right) {
13620
- return right.updatedAt - left.updatedAt || right.id - left.id;
13621
- }
13622
- function orderGlanceNotes(notes) {
13623
- const ready = notes.filter((note) => note.status === "ready").sort(newestFirst);
13624
- const pending = notes.filter((note) => note.status === "pending").sort(newestFirst);
13625
- const rest = notes.filter((note) => note.status !== "ready" && note.status !== "pending").sort(newestFirst);
13626
- return [...ready, ...pending, ...rest];
13627
- }
13628
- function renderGlance(notes, options) {
13629
- const ordered = orderGlanceNotes(notes);
13630
- const page = ordered.slice(options.offset, options.offset + options.limit);
13631
- if (page.length === 0)
13632
- return EMPTY_READ_REPLY;
13633
- const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
13634
- `);
13635
- const remaining = ordered.length - options.offset - page.length;
13636
- const footer = remaining > 0 ? `
13637
-
13638
- Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
13639
- return `## Notes
13640
-
13641
- ${rows}${footer}`;
13642
- }
13643
- function formatNoteBody(note, nowMs) {
13644
- const touchedAt = noteTouchedAt(note);
13645
- const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
13646
- const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
13647
- if (note.type !== "smart")
13648
- return head;
13649
- const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
13650
- const label = note.status === "ready" ? "Condition met" : "Condition";
13651
- const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
13652
- ${note.readyReason}` : "";
13653
- return `${head}
13654
- ${label}: ${condition}${failure}`;
13655
- }
13656
- function renderNotesById(entries, nowMs) {
13657
- const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
13658
- return `## Notes by ID
13659
-
13660
- ${lines.join(`
13661
-
13662
- `)}`;
13663
- }
13664
- function formatTraySuffix(tray, nowMs) {
13665
- if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
13666
- return "";
13667
- return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
13668
- }
13669
- function formatWriteReply(noteId, tray, nowMs) {
13670
- return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
13671
- }
13672
- function noteNudgePickIndex(sessionId, counter, poolSize) {
13673
- if (poolSize <= 0)
13674
- return 0;
13675
- const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
13676
- let hash = 2166136261;
13677
- for (const byte of bytes) {
13678
- hash ^= byte;
13679
- hash = Math.imul(hash, 16777619) >>> 0;
13659
+ diagnostics.openArcClamp.to = end;
13660
+ diagnostics.completedRefence.from = end;
13661
+ end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
13662
+ diagnostics.completedRefence.arcs = component.map((arc) => ({
13663
+ assistant: arc.invocation,
13664
+ result: arc.result
13665
+ }));
13666
+ diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
13667
+ });
13668
+ diagnostics.completedRefence.to = end;
13669
+ if (end > protectedTailStart)
13670
+ end = offset;
13671
+ diagnostics.eligibleEnd = end <= offset ? offset : end;
13672
+ args.observeDiagnostics?.(diagnostics);
13673
+ if (end <= offset && offset < protectedTailStart) {
13674
+ return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
13680
13675
  }
13681
- return hash % poolSize;
13682
- }
13683
- function formatNoteNudge(args) {
13684
- const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
13685
- const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
13686
- const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
13687
- return `${counts}${oldest}${shown}`;
13676
+ return { eligibleEndOrdinal: end, oversizeAtomicUnit };
13688
13677
  }
13689
-
13690
- // src/hooks/magic-context/note-nudger.ts
13691
- var observedUsers = new WeakMap;
13692
- function observeNoteNudgeServe(args) {
13693
- let sessions = observedUsers.get(args.db);
13694
- if (!sessions) {
13695
- sessions = new Map;
13696
- observedUsers.set(args.db, sessions);
13697
- }
13698
- let seen = sessions.get(args.sessionId);
13699
- const warm = seen !== undefined && seen.size > 0;
13700
- if (!seen)
13701
- seen = new Set;
13702
- const firstServe = args.anchorMessageId !== null && !seen.has(args.anchorMessageId);
13703
- for (const id of args.userMessageIds)
13704
- seen.add(id);
13705
- sessions.set(args.sessionId, seen);
13706
- return {
13707
- isFirstServe: warm && args.isLiveTail && firstServe,
13708
- prefixRewriteCoversAnchor: args.anchorMessageId !== null && args.prefixRewriteCoversAnchor
13709
- };
13710
- }
13711
- var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
13712
- var lastDeliveredAt = new Map;
13713
- function isCoolingDown(deliveredAt, now) {
13714
- return now - deliveredAt < NOTE_NUDGE_COOLDOWN_MS;
13715
- }
13716
- function getNoteNudgeDeliveredAt(sessionId) {
13717
- const deliveredAt = lastDeliveredAt.get(sessionId);
13718
- if (deliveredAt === undefined)
13719
- return 0;
13720
- if (!isCoolingDown(deliveredAt, Date.now())) {
13721
- lastDeliveredAt.delete(sessionId);
13722
- return 0;
13723
- }
13724
- return deliveredAt;
13725
- }
13726
- function recordNoteNudgeDeliveryTime(sessionId) {
13727
- const now = Date.now();
13728
- for (const [otherSessionId, deliveredAt] of lastDeliveredAt) {
13729
- if (!isCoolingDown(deliveredAt, now))
13730
- lastDeliveredAt.delete(otherSessionId);
13731
- }
13732
- lastDeliveredAt.set(sessionId, now);
13733
- }
13734
- function onNoteTrigger(db, sessionId, trigger) {
13735
- let transactionStartedAt = 0;
13736
- db.transaction(() => {
13737
- transactionStartedAt = performance.now();
13738
- setPersistedNoteNudgeTrigger(db, sessionId);
13739
- }).immediate();
13740
- logSlowWriteTransaction("note_nudge_trigger", transactionStartedAt);
13741
- sessionLog2(sessionId, `note-nudge: trigger fired (${trigger}), triggerPending=true`);
13742
- }
13743
- function peekNoteNudgeText(db, sessionId, currentUserMessageId, projectIdentity, noteReadStillVisible, eligibility) {
13744
- const state = getPersistedNoteNudge(db, sessionId);
13745
- if (!state.triggerPending)
13746
- return null;
13747
- if (eligibility && !eligibility.isFirstServe && !eligibility.prefixRewriteCoversAnchor) {
13748
- sessionLog2(sessionId, "note-nudge: deferring — user already served or first serve unproven");
13749
- return null;
13750
- }
13751
- if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
13752
- setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
13753
- state.triggerMessageId = currentUserMessageId;
13754
- }
13755
- if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
13756
- sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
13757
- return null;
13678
+ function resolveProtectedTailBoundary(ctx) {
13679
+ const createdAt = ctx.createdAt ?? Date.now();
13680
+ const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
13681
+ const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
13682
+ const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
13683
+ const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
13684
+ const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
13685
+ const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
13686
+ const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
13687
+ providerShapeVersion: ctx.providerShapeVersion,
13688
+ cacheNamespace: ctx.cacheNamespace,
13689
+ calibration: ctx.calibration,
13690
+ absoluteMessageCount,
13691
+ storedTotalForMessage: storedTotals ? (m) => {
13692
+ const v = storedTotals.get(m.id);
13693
+ return v === undefined ? null : v;
13694
+ } : undefined
13695
+ });
13696
+ const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
13697
+ providerShapeVersion: ctx.providerShapeVersion,
13698
+ cacheNamespace: ctx.cacheNamespace,
13699
+ calibration: ctx.calibration,
13700
+ absoluteMessageCount,
13701
+ measure: "summary-removed",
13702
+ storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
13703
+ });
13704
+ const rawMessageCount = index.rawMessageCount;
13705
+ const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
13706
+ const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
13707
+ if (rawMessageCount === 0) {
13708
+ return {
13709
+ sessionId: ctx.sessionId,
13710
+ mode: ctx.mode,
13711
+ offset,
13712
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
13713
+ offsetMessageId: null,
13714
+ protectedTailStart: 1,
13715
+ protectedTailStartMessageId: null,
13716
+ eligibleEndOrdinal: 1,
13717
+ eligibleEndMessageId: null,
13718
+ rawMessageCountAtTrigger: 0,
13719
+ rawLastMessageIdAtTrigger: null,
13720
+ N: 0,
13721
+ usagePercentage,
13722
+ usageInputTokens,
13723
+ usageSource: ctx.usageSource,
13724
+ contextLimit: ctx.contextLimit,
13725
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
13726
+ triggerBudget: ctx.triggerBudget,
13727
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
13728
+ migrationFloorActive: ctx.migrationFloorActive,
13729
+ emergencyTailScale: ctx.emergencyTailScale,
13730
+ recovery: ctx.recovery,
13731
+ providerShapeVersion: ctx.providerShapeVersion,
13732
+ cacheNamespace: ctx.cacheNamespace,
13733
+ createdAt,
13734
+ rawRangeFingerprint: "",
13735
+ trueRawEligibleTokens: 0,
13736
+ summaryRemovedEligibleTokens: 0,
13737
+ oversizeAtomicUnit: false,
13738
+ boundaryReason: "empty-session"
13739
+ };
13758
13740
  }
13759
- const deliveredAt = getNoteNudgeDeliveredAt(sessionId);
13760
- if (deliveredAt > 0) {
13761
- sessionLog2(sessionId, `note-nudge: suppressing — last delivered ${Math.round((Date.now() - deliveredAt) / 1000)}s ago (cooldown ${NOTE_NUDGE_COOLDOWN_MS / 60000}m)`);
13762
- clearNoteNudgeTriggerOnly(db, sessionId);
13763
- return null;
13741
+ if (ctx.mode === "manual-full-recomp") {
13742
+ const arcs = buildToolArcs(messages);
13743
+ const recompTarget = deriveProtectedTailTokenTarget({
13744
+ contextLimit: ctx.contextLimit,
13745
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
13746
+ usagePercentage: 0,
13747
+ triggerBudget: ctx.triggerBudget
13748
+ });
13749
+ const recentOpenArcCutoff = index.findSuffixStartForTokens(recompTarget.N);
13750
+ const firstOpenArc = arcs.find((arc) => arc.resOrdinal === null && arc.invOrdinal >= offset && arc.invOrdinal >= recentOpenArcCutoff);
13751
+ const protectedTailStart = firstOpenArc?.invOrdinal ?? rawMessageCount + 1;
13752
+ const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, protectedTailStart);
13753
+ return {
13754
+ sessionId: ctx.sessionId,
13755
+ mode: ctx.mode,
13756
+ offset,
13757
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
13758
+ offsetMessageId: boundaryMessageId(index, offset),
13759
+ protectedTailStart,
13760
+ protectedTailStartMessageId: null,
13761
+ eligibleEndOrdinal: protectedTailStart,
13762
+ eligibleEndMessageId: boundaryMessageId(index, protectedTailStart - 1),
13763
+ rawMessageCountAtTrigger: rawMessageCount,
13764
+ rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
13765
+ N: 0,
13766
+ usagePercentage: 0,
13767
+ usageInputTokens: 0,
13768
+ usageSource: "manual-none",
13769
+ contextLimit: ctx.contextLimit,
13770
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
13771
+ triggerBudget: ctx.triggerBudget,
13772
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
13773
+ migrationFloorActive: false,
13774
+ emergencyTailScale: ctx.emergencyTailScale,
13775
+ recovery: ctx.recovery,
13776
+ providerShapeVersion: ctx.providerShapeVersion,
13777
+ cacheNamespace: ctx.cacheNamespace,
13778
+ createdAt,
13779
+ rawRangeFingerprint,
13780
+ trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
13781
+ summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
13782
+ oversizeAtomicUnit: false,
13783
+ boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
13784
+ };
13764
13785
  }
13765
- const notes = getSessionNotes(db, sessionId);
13766
- const readySmartNotes = projectIdentity ? getReadySmartNotes(db, projectIdentity) : [];
13767
- const totalCount = notes.length + readySmartNotes.length;
13768
- if (totalCount === 0) {
13769
- sessionLog2(sessionId, "note-nudge: triggerPending but no notes found, skipping");
13770
- clearNoteNudgeTriggerOnly(db, sessionId);
13771
- return null;
13786
+ const target = deriveProtectedTailTokenTarget({
13787
+ contextLimit: ctx.contextLimit,
13788
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
13789
+ usagePercentage,
13790
+ triggerBudget: ctx.triggerBudget
13791
+ });
13792
+ const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
13793
+ const arcs = buildToolArcs(messages);
13794
+ let boundary = index.findSuffixStartForTokens(scaledN);
13795
+ const recentOpenArcCutoff = boundary;
13796
+ let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
13797
+ const tokenAtBoundary = index.tokenForOrdinal(boundary);
13798
+ if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
13799
+ boundary += 1;
13800
+ boundaryReason = "huge-message-exception";
13772
13801
  }
13773
- const lastReadAt = getNoteLastReadAt(db, sessionId);
13774
- if (lastReadAt > 0 && noteReadStillVisible) {
13775
- const mostRecentNoteActivity = maxNoteActivityTime([...notes, ...readySmartNotes]);
13776
- if (mostRecentNoteActivity > 0 && lastReadAt > mostRecentNoteActivity) {
13777
- 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()}`);
13778
- clearNoteNudgeTriggerOnly(db, sessionId);
13779
- return null;
13802
+ boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
13803
+ const snapped = semanticSnapBoundary({
13804
+ messages,
13805
+ index,
13806
+ candidate: boundary,
13807
+ scaledN,
13808
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
13809
+ });
13810
+ if (snapped !== boundary)
13811
+ boundaryReason = "semantic-snap";
13812
+ boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
13813
+ let runtimeFloor = offset;
13814
+ if (ctx.migrationFloorActive)
13815
+ runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
13816
+ let protectedTailStart = Math.max(boundary, runtimeFloor);
13817
+ const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
13818
+ const livePromptFloor = {
13819
+ ordinal: null,
13820
+ from: protectedTailStart,
13821
+ to: protectedTailStart
13822
+ };
13823
+ if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
13824
+ let lastMeaningfulUserOrdinal = 0;
13825
+ for (let i = messages.length - 1;i >= 0; i--) {
13826
+ const message = messages[i];
13827
+ if (message.role !== "user")
13828
+ continue;
13829
+ if (!hasMeaningfulUserText2(message.parts))
13830
+ continue;
13831
+ lastMeaningfulUserOrdinal = message.ordinal;
13832
+ break;
13833
+ }
13834
+ livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
13835
+ livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
13836
+ if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
13837
+ protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
13780
13838
  }
13781
13839
  }
13782
- const failureNotice = notes.find((note) => /^Smart note #\d+ cannot be checked\.\nCondition: /.test(note.content));
13783
- if (failureNotice) {
13784
- const reason = failureNotice.content.split(`
13785
- Reason: `)[1]?.split(`
13786
- `)[0] ?? "check unavailable";
13787
- 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.`;
13840
+ livePromptFloor.to = protectedTailStart;
13841
+ if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
13842
+ protectedTailStart = offset;
13788
13843
  }
13789
- const parts = [];
13790
- if (notes.length > 0) {
13791
- parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
13792
- }
13793
- if (readySmartNotes.length > 0) {
13794
- parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
13795
- }
13796
- sessionLog2(sessionId, `note-nudge: delivering nudge for ${parts.join(" and ")}`);
13797
- return formatNoteNudge({
13798
- readyCount: readySmartNotes.length,
13799
- activeCount: notes.length,
13800
- oldestActiveTouchedAt: oldestTouchedAt(notes),
13801
- shown: pickNudgeNote({ db, sessionId, activeNotes: notes, readySmartNotes }),
13802
- nowMs: Date.now()
13844
+ protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
13845
+ protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
13846
+ protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
13847
+ const perRunCap = selectPerRunCap({
13848
+ usagePercentage,
13849
+ N: scaledN,
13850
+ contextLimit: ctx.contextLimit,
13851
+ executeThresholdPercentage: ctx.executeThresholdPercentage
13803
13852
  });
13853
+ let headDiagnostics;
13854
+ const head = applyHeadCap({
13855
+ observeDiagnostics: (value) => {
13856
+ headDiagnostics = value;
13857
+ },
13858
+ index: summaryRemovedIndex,
13859
+ protectedTailStart,
13860
+ offset,
13861
+ arcs,
13862
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
13863
+ capTokens: perRunCap,
13864
+ recentOpenArcCutoff
13865
+ });
13866
+ const servedEndOrdinal = retreatPastHostUnservedRows(messages, head.eligibleEndOrdinal, offset);
13867
+ const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
13868
+ const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
13869
+ return {
13870
+ sessionId: ctx.sessionId,
13871
+ mode: ctx.mode,
13872
+ offset,
13873
+ lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
13874
+ offsetMessageId: boundaryMessageId(index, offset),
13875
+ protectedTailStart,
13876
+ protectedTailStartMessageId: boundaryMessageId(index, protectedTailStart),
13877
+ eligibleEndOrdinal,
13878
+ eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
13879
+ rawMessageCountAtTrigger: rawMessageCount,
13880
+ rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
13881
+ N: scaledN,
13882
+ usagePercentage,
13883
+ usageInputTokens,
13884
+ usageSource: ctx.usageSource,
13885
+ contextLimit: ctx.contextLimit,
13886
+ executeThresholdPercentage: ctx.executeThresholdPercentage,
13887
+ triggerBudget: ctx.triggerBudget,
13888
+ priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
13889
+ migrationFloorActive: ctx.migrationFloorActive,
13890
+ emergencyTailScale: ctx.emergencyTailScale,
13891
+ recovery: ctx.recovery,
13892
+ liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
13893
+ providerShapeVersion: ctx.providerShapeVersion,
13894
+ cacheNamespace: ctx.cacheNamespace,
13895
+ createdAt,
13896
+ rawRangeFingerprint,
13897
+ trueRawEligibleTokens: index.rangeTokens(offset, eligibleEndOrdinal),
13898
+ summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
13899
+ oversizeAtomicUnit: head.oversizeAtomicUnit,
13900
+ boundaryReason,
13901
+ diagnostics: boundaryDiagnostics({
13902
+ tailTarget: target,
13903
+ usable: target.usable,
13904
+ usagePercentage,
13905
+ N: scaledN,
13906
+ triggerBudget: ctx.triggerBudget,
13907
+ capTokens: perRunCap,
13908
+ sizeWalkStart: recentOpenArcCutoff,
13909
+ protectedTailStart,
13910
+ livePromptFloor,
13911
+ head: headDiagnostics
13912
+ })
13913
+ };
13804
13914
  }
13805
- function oldestTouchedAt(notes) {
13806
- return notes.reduce((min, note) => {
13807
- const touchedAt = noteTouchedAt(note);
13808
- return min === null || touchedAt < min ? touchedAt : min;
13809
- }, null);
13810
- }
13811
- function pickNudgeNote(args) {
13812
- const pool = args.readySmartNotes.length > 0 ? [...args.readySmartNotes].sort((left, right) => left.id - right.id) : [...args.activeNotes].sort((left, right) => left.id - right.id);
13813
- if (pool.length === 0)
13814
- return null;
13815
- const counter = getNoteNudgeAnchors(args.db, args.sessionId).length;
13816
- return pool[noteNudgePickIndex(args.sessionId, counter, pool.length)] ?? null;
13817
- }
13818
- function maxNoteActivityTime(notes) {
13819
- let max = 0;
13820
- for (const note of notes) {
13821
- if (note.updatedAt > max)
13822
- max = note.updatedAt;
13823
- if (note.readyAt !== null && note.readyAt > max)
13824
- max = note.readyAt;
13825
- }
13826
- return max;
13915
+ function readLastCompartmentBoundary(db, sessionId) {
13916
+ const row = db.prepare(`SELECT COALESCE(MAX(end_message), -1) AS max_end,
13917
+ (SELECT end_message_id FROM compartments
13918
+ WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
13919
+ FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
13920
+ const endMessageId = row?.end_message_id;
13921
+ return {
13922
+ endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
13923
+ endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
13924
+ };
13827
13925
  }
13828
- function markNoteNudgeDelivered(db, sessionId, text, messageId) {
13829
- if (!messageId) {
13830
- clearNoteNudgeTriggerAndCooldown(db, sessionId);
13831
- sessionLog2(sessionId, "note-nudge: marked delivered without anchor");
13832
- return { ok: true, kind: "already-present" };
13833
- }
13834
- const outcome = db.transaction(() => {
13835
- const delivered = deliverNoteNudgeAtomic(db, sessionId, messageId, text);
13836
- const nudgeText = text?.replace(/^\s*<instruction name="deferred_notes">/, "") ?? "";
13837
- const noticeId = nudgeText.match(/^Smart note check unavailable: [\s\S]*Read ctx_note #(\d+) for the condition/);
13838
- if (delivered.ok && noticeId) {
13839
- db.prepare(`UPDATE notes SET status = 'dismissed', updated_at = ?
13840
- WHERE id = ? AND type = 'session' AND session_id = ?
13841
- AND content LIKE 'Smart note #% cannot be checked.%'`).run(Date.now(), Number(noticeId[1]), sessionId);
13926
+ function resolveBoundaryContext(args) {
13927
+ const lastCompartmentBoundary = readLastCompartmentBoundary(args.db, args.sessionId);
13928
+ const lastCompartmentEndOrdinal = lastCompartmentBoundary.endOrdinal;
13929
+ const triggerBudget = deriveTriggerBudget2(args.contextLimit, args.executeThresholdPercentage);
13930
+ let meta = args.protectedTailMeta ?? loadProtectedTailMeta(args.db, args.sessionId);
13931
+ let migrationFloorActive = false;
13932
+ if (meta.protectedTailPolicyVersion < 3) {
13933
+ let legacyBoundary = 1;
13934
+ try {
13935
+ legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
13936
+ } catch (error) {
13937
+ sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
13842
13938
  }
13843
- return delivered;
13844
- }).immediate();
13845
- if (outcome.ok) {
13846
- recordNoteNudgeDeliveryTime(sessionId);
13847
- }
13848
- sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
13849
- return outcome;
13850
- }
13851
- function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
13852
- db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
13853
- lastDeliveredAt.delete(sessionId);
13854
- }
13855
- function clearNoteNudgeTriggerOnly(db, sessionId) {
13856
- db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
13857
- }
13858
-
13859
- // src/hooks/magic-context/persist-filtered-noise.ts
13860
- function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
13861
- const rows = chunk.filteredNoiseLines ?? [];
13862
- const start = chunk.startIndex;
13863
- if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
13864
- return false;
13865
- const endId = rows[rows.length - 1].messageId;
13866
- if (!hasRawSessionMessageById2(sessionId, endId)) {
13867
- sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
13868
- return false;
13939
+ const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
13940
+ meta = seedResult;
13941
+ migrationFloorActive = seedResult.seeded;
13869
13942
  }
13870
- const saved = db.transaction(() => {
13871
- const prior = getCompartments(db, sessionId);
13872
- const last = prior.at(-1);
13873
- if ((last?.endMessage ?? 0) + 1 !== start)
13874
- return false;
13875
- appendCompartments(db, sessionId, [
13876
- {
13877
- sequence: (last?.sequence ?? -1) + 1,
13878
- startMessage: start,
13879
- endMessage: eligibleEnd - 1,
13880
- startMessageId: rows[0].messageId,
13881
- endMessageId: rows[rows.length - 1].messageId,
13882
- title: "",
13883
- content: "",
13884
- p1: "",
13885
- p2: "",
13886
- p3: "",
13887
- p4: "",
13888
- episodeType: "filtered-noise",
13889
- importance: 1
13890
- }
13891
- ]);
13892
- return true;
13893
- }).immediate();
13894
- if (saved)
13895
- sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
13896
- return saved;
13943
+ const calibration = sessionDecisionCalibration(args.db, args.sessionId);
13944
+ const storedTokenTotalsForMessages = (messageIds, messages = []) => {
13945
+ try {
13946
+ const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
13947
+ return {
13948
+ totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
13949
+ summaryRemovedTotals: weights.summaryRemovedTotals
13950
+ };
13951
+ } catch (error) {
13952
+ sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
13953
+ return;
13954
+ }
13955
+ };
13956
+ return {
13957
+ sessionId: args.sessionId,
13958
+ mode: args.mode,
13959
+ contextLimit: args.contextLimit,
13960
+ executeThresholdPercentage: args.executeThresholdPercentage,
13961
+ triggerBudget,
13962
+ usage: args.usage ?? null,
13963
+ usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
13964
+ lastCompartmentEndOrdinal,
13965
+ lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
13966
+ priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
13967
+ protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
13968
+ migrationFloorActive,
13969
+ emergencyTailScale: args.emergencyTailScale,
13970
+ recovery: args.recovery,
13971
+ liftLivePromptFloor: args.liftLivePromptFloor,
13972
+ providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
13973
+ cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
13974
+ storedTokenTotalsForMessages,
13975
+ calibration
13976
+ };
13897
13977
  }
13898
-
13899
- // src/hooks/magic-context/file-token-coverage.ts
13900
- function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
13901
- const filesByMessage = new Map;
13902
- for (const message of messages) {
13903
- const count = message.parts.filter(isFilePart).length;
13904
- if (count > 0 && totals.has(message.id))
13905
- filesByMessage.set(message.id, count);
13906
- }
13907
- if (filesByMessage.size === 0)
13908
- return totals;
13909
- const rows = db.prepare(`
13910
- SELECT o.value AS owner, COUNT(t.id) AS count
13911
- FROM json_each(?) o LEFT JOIN tags t
13912
- ON t.session_id = ? AND t.type = 'file'
13913
- AND t.message_id >= o.value || ':file'
13914
- AND t.message_id < o.value || ':file;'
13915
- GROUP BY o.value
13916
- `).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
13917
- for (const row of rows) {
13918
- if (row.count < (filesByMessage.get(row.owner) ?? 0))
13919
- totals.delete(row.owner);
13920
- }
13921
- return totals;
13978
+ function resolveOpenCodeProtectedTailBoundary(args) {
13979
+ return resolveProtectedTailBoundary(resolveBoundaryContext(args));
13922
13980
  }
13923
-
13924
- // src/hooks/magic-context/protected-tail-boundary.ts
13925
- function describeBoundaryDiagnostics(snapshot) {
13926
- return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
13927
- }
13928
- function boundaryDiagnostics(args) {
13929
- return {
13930
- ...args,
13931
- capTier: args.usagePercentage >= 95 ? "95" : args.usagePercentage >= 80 ? "80" : "normal",
13932
- drainBudget: "not-reserved; does-not-size-cap"
13933
- };
13934
- }
13935
- var ALPHA = 0.3;
13936
- var FLOOR_RATIO = 0.08;
13937
- var FLOOR_MIN = 2000;
13938
- var FLOOR_MAX = 12000;
13939
- var ABS_CAP = 96000;
13940
- var MAX_USABLE_RATIO = 0.4;
13941
- var RESERVED_HEADROOM_MIN = 1000;
13942
- var RESERVED_HEADROOM_RATIO = 0.02;
13943
- var NON_EMERGENCY_MAX_CAP = 250000;
13944
- var FORCE80_MAX_CAP = 500000;
13945
- var FORCE95_MAX_CAP = 750000;
13946
- var NORMAL_HYSTERESIS_TOKENS = 256;
13947
- var RECOVERY_NO_HEAD_LIMIT = 2;
13948
- function clampPercentage(value) {
13949
- if (!Number.isFinite(value))
13950
- return 0;
13951
- return Math.max(0, Math.min(100, value));
13952
- }
13953
- function clampOrdinal(value, rawMessageCount) {
13954
- return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
13955
- }
13956
- function deriveProtectedTailTokenTarget(args) {
13957
- const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
13958
- const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
13959
- const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
13960
- const usage = clampPercentage(args.usagePercentage);
13961
- const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
13962
- const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
13963
- const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
13964
- const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
13965
- const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
13966
- const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
13967
- const effectiveFloor = Math.min(floorN, ceilingN);
13968
- const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
13969
- return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
13970
- }
13971
- function nonEmergencyPerRunCap(usable, N) {
13972
- return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
13973
- }
13974
- function force80PerRunCap(usable, N) {
13975
- return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
13976
- }
13977
- function force95PerRunCap(usable, N) {
13978
- return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
13979
- }
13980
- function selectPerRunCap(snapshot) {
13981
- const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
13982
- if (snapshot.usagePercentage >= 95)
13983
- return force95PerRunCap(usable, snapshot.N);
13984
- if (snapshot.usagePercentage >= 80)
13985
- return force80PerRunCap(usable, snapshot.N);
13986
- return nonEmergencyPerRunCap(usable, snapshot.N);
13987
- }
13988
- function boundaryMessageId(index, ordinal) {
13989
- if (ordinal < 1 || ordinal > index.rawMessageCount)
13990
- return null;
13991
- return index.messageIdAtOrdinal(ordinal);
13992
- }
13993
- function isSemanticBoundaryCandidate(messageParts, role) {
13994
- if (role === "user" && hasMeaningfulUserText2(messageParts))
13995
- return true;
13996
- if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
13997
- return true;
13998
- }
13999
- return false;
14000
- }
14001
- function semanticSnapBoundary(args) {
14002
- const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
14003
- let snapped = candidate;
14004
- for (const message of messages) {
14005
- if (message.ordinal > candidate)
14006
- break;
14007
- if (message.ordinal < lastCompartmentEndOrdinal + 1)
14008
- continue;
14009
- if (!isSemanticBoundaryCandidate(message.parts, message.role))
14010
- continue;
14011
- snapped = message.ordinal;
14012
- }
14013
- if (snapped === candidate)
14014
- return candidate;
14015
- const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
14016
- if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
14017
- return candidate;
14018
- const snappedMessage = messages.find((message) => message.ordinal === snapped);
14019
- if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
14020
- return candidate;
14021
- }
14022
- return snapped;
14023
- }
14024
- function snapWrapupBoundaryToUser(args) {
14025
- const { messages, index, candidate, offset, triggerBudget } = args;
14026
- if (candidate <= offset)
14027
- return candidate;
14028
- const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
14029
- for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
14030
- const message = messages.find((m) => m.ordinal === ordinal);
14031
- if (!message)
14032
- continue;
14033
- if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
14034
- continue;
14035
- const extraTokens = index.rangeTokens(ordinal, candidate);
14036
- if (extraTokens <= snapTokenLimit)
14037
- return ordinal;
14038
- return candidate;
14039
- }
14040
- return candidate;
14041
- }
14042
- function fenceWrapupBoundaryForToolArcs(args) {
14043
- let boundary = args.candidate;
14044
- const maxPasses = args.arcs.length + 1;
14045
- for (let pass = 0;pass < maxPasses; pass += 1) {
14046
- let next = boundary;
14047
- for (const arc of args.arcs) {
14048
- if (arc.resOrdinal === null) {
14049
- continue;
14050
- }
14051
- if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
14052
- next = arc.invOrdinal;
14053
- }
14054
- }
14055
- if (next === boundary)
14056
- return boundary;
14057
- boundary = next;
14058
- }
14059
- return boundary;
14060
- }
14061
- function applyHeadCap(args) {
14062
- const {
14063
- index,
14064
- protectedTailStart,
14065
- offset,
14066
- arcs,
14067
- lastCompartmentEndOrdinal,
14068
- capTokens,
14069
- recentOpenArcCutoff
14070
- } = args;
14071
- const diagnostics = {
14072
- offset,
14073
- capEnd: offset,
14074
- capTokenSum: 0,
14075
- completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
14076
- oversizeAdmission: { from: offset, to: offset },
14077
- openArcClamp: { from: offset, to: offset },
14078
- completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
14079
- eligibleEnd: offset
14080
- };
14081
- if (offset >= protectedTailStart) {
14082
- args.observeDiagnostics?.(diagnostics);
14083
- return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
14084
- }
14085
- let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
14086
- diagnostics.capEnd = end;
14087
- diagnostics.capTokenSum = index.rangeTokens(offset, end);
14088
- let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
14089
- let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
14090
- diagnostics.completedFence.arcs = component.map((arc) => ({
14091
- assistant: arc.invocation,
14092
- result: arc.result
14093
- }));
14094
- diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
14095
- });
14096
- diagnostics.completedFence.from = end;
14097
- diagnostics.completedFence.to = completedFence;
14098
- diagnostics.oversizeAdmission.from = completedFence;
14099
- if (completedFence <= offset && end > offset) {
14100
- const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
14101
- if (afterFirstArc <= protectedTailStart)
14102
- completedFence = afterFirstArc;
14103
- }
14104
- diagnostics.oversizeAdmission.to = completedFence;
14105
- if (completedFence > end) {
14106
- end = Math.min(protectedTailStart, completedFence);
14107
- if (index.rangeTokens(offset, end) > capTokens)
14108
- oversizeAtomicUnit = true;
14109
- } else {
14110
- end = completedFence;
14111
- }
14112
- diagnostics.openArcClamp.from = end;
14113
- for (const arc of arcs) {
14114
- const resOrdinal = arc.resOrdinal;
14115
- if (resOrdinal === null) {
14116
- if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
14117
- end = Math.min(end, arc.invOrdinal);
14118
- }
14119
- }
14120
- }
14121
- diagnostics.openArcClamp.to = end;
14122
- diagnostics.completedRefence.from = end;
14123
- end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
14124
- diagnostics.completedRefence.arcs = component.map((arc) => ({
14125
- assistant: arc.invocation,
14126
- result: arc.result
14127
- }));
14128
- diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
14129
- });
14130
- diagnostics.completedRefence.to = end;
14131
- if (end > protectedTailStart)
14132
- end = offset;
14133
- diagnostics.eligibleEnd = end <= offset ? offset : end;
14134
- args.observeDiagnostics?.(diagnostics);
14135
- if (end <= offset && offset < protectedTailStart) {
14136
- return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
14137
- }
14138
- return { eligibleEndOrdinal: end, oversizeAtomicUnit };
14139
- }
14140
- function resolveProtectedTailBoundary(ctx) {
13981
+ function resolveWrapupProtectedTailBoundary(args) {
13982
+ const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
14141
13983
  const createdAt = ctx.createdAt ?? Date.now();
14142
13984
  const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
14143
13985
  const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
@@ -14151,8 +13993,8 @@ function resolveProtectedTailBoundary(ctx) {
14151
13993
  calibration: ctx.calibration,
14152
13994
  absoluteMessageCount,
14153
13995
  storedTotalForMessage: storedTotals ? (m) => {
14154
- const v = storedTotals.get(m.id);
14155
- return v === undefined ? null : v;
13996
+ const value = storedTotals?.get(m.id);
13997
+ return value === undefined ? null : value;
14156
13998
  } : undefined
14157
13999
  });
14158
14000
  const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
@@ -14164,151 +14006,58 @@ function resolveProtectedTailBoundary(ctx) {
14164
14006
  storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
14165
14007
  });
14166
14008
  const rawMessageCount = index.rawMessageCount;
14009
+ const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
14167
14010
  const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
14168
14011
  const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
14169
- if (rawMessageCount === 0) {
14170
- return {
14171
- sessionId: ctx.sessionId,
14172
- mode: ctx.mode,
14012
+ const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
14013
+ const keep = Math.max(1, Math.floor(args.messagesToKeep));
14014
+ let targetProtectedTailStart = offset;
14015
+ let boundaryReason = "manual-wrapup-empty";
14016
+ if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
14017
+ targetProtectedTailStart = offset;
14018
+ boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
14019
+ } else {
14020
+ targetProtectedTailStart = anchorRawMessageCount - keep + 1;
14021
+ boundaryReason = "manual-wrapup-keep-watermark";
14022
+ const arcs = buildToolArcs(messages);
14023
+ const fenced = fenceWrapupBoundaryForToolArcs({
14024
+ candidate: targetProtectedTailStart,
14025
+ arcs,
14026
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14027
+ });
14028
+ if (fenced !== targetProtectedTailStart)
14029
+ boundaryReason = "manual-wrapup-tool-arc";
14030
+ targetProtectedTailStart = fenced;
14031
+ const snapped = snapWrapupBoundaryToUser({
14032
+ messages,
14033
+ index,
14034
+ candidate: targetProtectedTailStart,
14173
14035
  offset,
14174
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14175
- offsetMessageId: null,
14176
- protectedTailStart: 1,
14177
- protectedTailStartMessageId: null,
14178
- eligibleEndOrdinal: 1,
14179
- eligibleEndMessageId: null,
14180
- rawMessageCountAtTrigger: 0,
14181
- rawLastMessageIdAtTrigger: null,
14182
- N: 0,
14183
- usagePercentage,
14184
- usageInputTokens,
14185
- usageSource: ctx.usageSource,
14186
- contextLimit: ctx.contextLimit,
14187
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14188
- triggerBudget: ctx.triggerBudget,
14189
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14190
- migrationFloorActive: ctx.migrationFloorActive,
14191
- emergencyTailScale: ctx.emergencyTailScale,
14192
- recovery: ctx.recovery,
14193
- providerShapeVersion: ctx.providerShapeVersion,
14194
- cacheNamespace: ctx.cacheNamespace,
14195
- createdAt,
14196
- rawRangeFingerprint: "",
14197
- trueRawEligibleTokens: 0,
14198
- summaryRemovedEligibleTokens: 0,
14199
- oversizeAtomicUnit: false,
14200
- boundaryReason: "empty-session"
14201
- };
14202
- }
14203
- if (ctx.mode === "manual-full-recomp") {
14204
- const arcs = buildToolArcs(messages);
14205
- const recompTarget = deriveProtectedTailTokenTarget({
14206
- contextLimit: ctx.contextLimit,
14207
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14208
- usagePercentage: 0,
14209
14036
  triggerBudget: ctx.triggerBudget
14210
14037
  });
14211
- const recentOpenArcCutoff = index.findSuffixStartForTokens(recompTarget.N);
14212
- const firstOpenArc = arcs.find((arc) => arc.resOrdinal === null && arc.invOrdinal >= offset && arc.invOrdinal >= recentOpenArcCutoff);
14213
- const protectedTailStart = firstOpenArc?.invOrdinal ?? rawMessageCount + 1;
14214
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, protectedTailStart);
14215
- return {
14216
- sessionId: ctx.sessionId,
14217
- mode: ctx.mode,
14218
- offset,
14219
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14220
- offsetMessageId: boundaryMessageId(index, offset),
14221
- protectedTailStart,
14222
- protectedTailStartMessageId: null,
14223
- eligibleEndOrdinal: protectedTailStart,
14224
- eligibleEndMessageId: boundaryMessageId(index, protectedTailStart - 1),
14225
- rawMessageCountAtTrigger: rawMessageCount,
14226
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
14227
- N: 0,
14228
- usagePercentage: 0,
14229
- usageInputTokens: 0,
14230
- usageSource: "manual-none",
14231
- contextLimit: ctx.contextLimit,
14232
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14233
- triggerBudget: ctx.triggerBudget,
14234
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14235
- migrationFloorActive: false,
14236
- emergencyTailScale: ctx.emergencyTailScale,
14237
- recovery: ctx.recovery,
14238
- providerShapeVersion: ctx.providerShapeVersion,
14239
- cacheNamespace: ctx.cacheNamespace,
14240
- createdAt,
14241
- rawRangeFingerprint,
14242
- trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
14243
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
14244
- oversizeAtomicUnit: false,
14245
- boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
14246
- };
14038
+ if (snapped !== targetProtectedTailStart)
14039
+ boundaryReason = "manual-wrapup-user-snap";
14040
+ targetProtectedTailStart = snapped;
14041
+ const refenced = fenceWrapupBoundaryForToolArcs({
14042
+ candidate: targetProtectedTailStart,
14043
+ arcs,
14044
+ lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14045
+ });
14046
+ if (refenced !== targetProtectedTailStart)
14047
+ boundaryReason = "manual-wrapup-tool-arc";
14048
+ targetProtectedTailStart = refenced;
14247
14049
  }
14050
+ targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
14051
+ targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
14248
14052
  const target = deriveProtectedTailTokenTarget({
14249
14053
  contextLimit: ctx.contextLimit,
14250
14054
  executeThresholdPercentage: ctx.executeThresholdPercentage,
14251
14055
  usagePercentage,
14252
14056
  triggerBudget: ctx.triggerBudget
14253
14057
  });
14254
- const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
14255
- const arcs = buildToolArcs(messages);
14256
- let boundary = index.findSuffixStartForTokens(scaledN);
14257
- const recentOpenArcCutoff = boundary;
14258
- let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
14259
- const tokenAtBoundary = index.tokenForOrdinal(boundary);
14260
- if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
14261
- boundary += 1;
14262
- boundaryReason = "huge-message-exception";
14263
- }
14264
- boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
14265
- const snapped = semanticSnapBoundary({
14266
- messages,
14267
- index,
14268
- candidate: boundary,
14269
- scaledN,
14270
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14271
- });
14272
- if (snapped !== boundary)
14273
- boundaryReason = "semantic-snap";
14274
- boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
14275
- let runtimeFloor = offset;
14276
- if (ctx.migrationFloorActive)
14277
- runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
14278
- let protectedTailStart = Math.max(boundary, runtimeFloor);
14279
- const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
14280
- const livePromptFloor = {
14281
- ordinal: null,
14282
- from: protectedTailStart,
14283
- to: protectedTailStart
14284
- };
14285
- if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
14286
- let lastMeaningfulUserOrdinal = 0;
14287
- for (let i = messages.length - 1;i >= 0; i--) {
14288
- const message = messages[i];
14289
- if (message.role !== "user")
14290
- continue;
14291
- if (!hasMeaningfulUserText2(message.parts))
14292
- continue;
14293
- lastMeaningfulUserOrdinal = message.ordinal;
14294
- break;
14295
- }
14296
- livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
14297
- livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
14298
- if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
14299
- protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
14300
- }
14301
- }
14302
- livePromptFloor.to = protectedTailStart;
14303
- if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
14304
- protectedTailStart = offset;
14305
- }
14306
- protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
14307
- protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
14308
- protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
14309
14058
  const perRunCap = selectPerRunCap({
14310
14059
  usagePercentage,
14311
- N: scaledN,
14060
+ N: target.N,
14312
14061
  contextLimit: ctx.contextLimit,
14313
14062
  executeThresholdPercentage: ctx.executeThresholdPercentage
14314
14063
  });
@@ -14318,29 +14067,28 @@ function resolveProtectedTailBoundary(ctx) {
14318
14067
  headDiagnostics = value;
14319
14068
  },
14320
14069
  index: summaryRemovedIndex,
14321
- protectedTailStart,
14070
+ protectedTailStart: targetProtectedTailStart,
14322
14071
  offset,
14323
- arcs,
14072
+ arcs: buildToolArcs(messages),
14324
14073
  lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
14325
14074
  capTokens: perRunCap,
14326
- recentOpenArcCutoff
14075
+ recentOpenArcCutoff: targetProtectedTailStart
14327
14076
  });
14328
- const servedEndOrdinal = retreatPastHostUnservedRows(messages, head.eligibleEndOrdinal, offset);
14329
- const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
14077
+ const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
14330
14078
  const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
14331
- return {
14079
+ const snapshot = {
14332
14080
  sessionId: ctx.sessionId,
14333
- mode: ctx.mode,
14081
+ mode: "manual-wrapup",
14334
14082
  offset,
14335
14083
  lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14336
14084
  offsetMessageId: boundaryMessageId(index, offset),
14337
- protectedTailStart,
14338
- protectedTailStartMessageId: boundaryMessageId(index, protectedTailStart),
14085
+ protectedTailStart: targetProtectedTailStart,
14086
+ protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
14339
14087
  eligibleEndOrdinal,
14340
14088
  eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
14341
14089
  rawMessageCountAtTrigger: rawMessageCount,
14342
14090
  rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
14343
- N: scaledN,
14091
+ N: keep,
14344
14092
  usagePercentage,
14345
14093
  usageInputTokens,
14346
14094
  usageSource: ctx.usageSource,
@@ -14350,13 +14098,11 @@ function resolveProtectedTailBoundary(ctx) {
14350
14098
  priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14351
14099
  migrationFloorActive: ctx.migrationFloorActive,
14352
14100
  emergencyTailScale: ctx.emergencyTailScale,
14353
- recovery: ctx.recovery,
14354
- liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
14355
14101
  providerShapeVersion: ctx.providerShapeVersion,
14356
14102
  cacheNamespace: ctx.cacheNamespace,
14357
14103
  createdAt,
14358
14104
  rawRangeFingerprint,
14359
- trueRawEligibleTokens: index.rangeTokens(offset, eligibleEndOrdinal),
14105
+ trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
14360
14106
  summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
14361
14107
  oversizeAtomicUnit: head.oversizeAtomicUnit,
14362
14108
  boundaryReason,
@@ -14364,332 +14110,678 @@ function resolveProtectedTailBoundary(ctx) {
14364
14110
  tailTarget: target,
14365
14111
  usable: target.usable,
14366
14112
  usagePercentage,
14367
- N: scaledN,
14113
+ N: target.N,
14368
14114
  triggerBudget: ctx.triggerBudget,
14369
14115
  capTokens: perRunCap,
14370
- sizeWalkStart: recentOpenArcCutoff,
14371
- protectedTailStart,
14372
- livePromptFloor,
14116
+ sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
14117
+ protectedTailStart: targetProtectedTailStart,
14118
+ livePromptFloor: {
14119
+ ordinal: null,
14120
+ from: targetProtectedTailStart,
14121
+ to: targetProtectedTailStart
14122
+ },
14373
14123
  head: headDiagnostics
14374
14124
  })
14375
14125
  };
14126
+ return {
14127
+ snapshot,
14128
+ rawMessagesAboveLastCompartment,
14129
+ anchorRawMessageCount,
14130
+ targetProtectedTailStart,
14131
+ targetEligibleEndOrdinal: targetProtectedTailStart
14132
+ };
14133
+ }
14134
+ function getRawHistoryEligibility(db, sessionId) {
14135
+ const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
14136
+ const offset = Math.max(1, lastCompartmentEnd + 1);
14137
+ const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
14138
+ const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
14139
+ return {
14140
+ lastCompartmentEnd,
14141
+ offset,
14142
+ rawMessageCount,
14143
+ hasRawBeyondLastCompartment: rawMessageCount >= offset
14144
+ };
14145
+ }
14146
+ function hasRunnableCompartmentWindow(snapshot) {
14147
+ if (snapshot.offset >= snapshot.protectedTailStart)
14148
+ return false;
14149
+ if (snapshot.eligibleEndOrdinal <= snapshot.offset)
14150
+ return false;
14151
+ if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
14152
+ return true;
14153
+ const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
14154
+ if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
14155
+ return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
14156
+ }
14157
+ return snapshot.eligibleEndOrdinal > snapshot.offset;
14158
+ }
14159
+ function boundarySnapshotIdChecks(snapshot) {
14160
+ const checks = [
14161
+ [snapshot.offset, snapshot.offsetMessageId, "offset"],
14162
+ [snapshot.rawMessageCountAtTrigger, snapshot.rawLastMessageIdAtTrigger, "last"]
14163
+ ];
14164
+ if (snapshot.protectedTailStart <= snapshot.rawMessageCountAtTrigger) {
14165
+ checks.push([
14166
+ snapshot.protectedTailStart,
14167
+ snapshot.protectedTailStartMessageId,
14168
+ "protectedTailStart"
14169
+ ]);
14170
+ }
14171
+ if (snapshot.eligibleEndOrdinal > snapshot.offset) {
14172
+ checks.push([
14173
+ snapshot.eligibleEndOrdinal - 1,
14174
+ snapshot.eligibleEndMessageId,
14175
+ "eligibleEnd"
14176
+ ]);
14177
+ }
14178
+ return checks;
14179
+ }
14180
+ function validateBoundarySnapshot(args) {
14181
+ const { snapshot, exactIds } = args;
14182
+ if (args.currentContextLimit && args.currentContextLimit !== snapshot.contextLimit) {
14183
+ return {
14184
+ ok: false,
14185
+ reason: "model_or_limit_changed",
14186
+ detail: `context limit changed from ${snapshot.contextLimit} to ${args.currentContextLimit}`
14187
+ };
14188
+ }
14189
+ const currentRawMessageCount = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
14190
+ if (snapshot.rawMessageCountAtTrigger > currentRawMessageCount) {
14191
+ return { ok: false, reason: "stale_snapshot", detail: "raw message count shrank" };
14192
+ }
14193
+ const idAt = (ordinal) => {
14194
+ if (!exactIds)
14195
+ return readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, ordinal, ordinal).keys().next().value ?? null;
14196
+ const id = exactIds.get(ordinal);
14197
+ if (id === undefined)
14198
+ throw new Error(`boundary validation was given no exact id for ordinal ${ordinal}`);
14199
+ return id;
14200
+ };
14201
+ for (const [ordinal, expected, label] of boundarySnapshotIdChecks(snapshot)) {
14202
+ if (expected !== idAt(ordinal)) {
14203
+ return {
14204
+ ok: false,
14205
+ reason: "stale_snapshot",
14206
+ detail: `${label} ordinal ${ordinal} id changed`
14207
+ };
14208
+ }
14209
+ }
14210
+ const expectedOffset = Math.max(1, getLastCompartmentEndMessage(args.db, snapshot.sessionId) + 1);
14211
+ if (expectedOffset !== snapshot.offset) {
14212
+ return {
14213
+ ok: false,
14214
+ reason: "stale_snapshot",
14215
+ detail: `last compartment moved: offset ${snapshot.offset} -> ${expectedOffset}`
14216
+ };
14217
+ }
14218
+ const fingerprintMessages = readRawSessionMessageRange2(snapshot.sessionId, snapshot.offset, snapshot.eligibleEndOrdinal - 1);
14219
+ const fingerprint = computeRawRangeFingerprint(fingerprintMessages, snapshot.offset, snapshot.eligibleEndOrdinal);
14220
+ if (fingerprint !== snapshot.rawRangeFingerprint) {
14221
+ return { ok: false, reason: "stale_snapshot", detail: "raw range fingerprint changed" };
14222
+ }
14223
+ return { ok: true };
14224
+ }
14225
+ function recordHighPressureNoEligibleHead(db, snapshot) {
14226
+ const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
14227
+ if (snapshot.usagePercentage < forceMaterializationPercentage && !snapshot.emergencyTailScale) {
14228
+ return 0;
14229
+ }
14230
+ return recordProtectedTailNoEligibleHead(db, snapshot.sessionId);
14231
+ }
14232
+
14233
+ // src/hooks/magic-context/historian-drain-gate.ts
14234
+ var loggedWindows = new WeakMap;
14235
+ function reportProviderRecoveryDrainSkip(sessionId) {
14236
+ let logged = false;
14237
+ return (skip) => {
14238
+ if (logged)
14239
+ return;
14240
+ logged = true;
14241
+ sessionLog2(sessionId, `historian skip during provider recovery: ${skip.reason}; next eligible at ${new Date(skip.nextEligibleAt).toISOString()}`);
14242
+ };
14243
+ }
14244
+ function resolveHistorianDrainBudgetGeometry(args) {
14245
+ const target = deriveProtectedTailTokenTarget(args);
14246
+ return { usable: target.usable, perRunCap: selectPerRunCap({ ...args, N: target.N }) };
14247
+ }
14248
+ function isHistorianDrainBudgetSpent(args) {
14249
+ const usagePercentage = args.recoveryUsagePercentage ?? args.usagePercentage;
14250
+ const state = getProtectedTailDrainBudgetSkip({
14251
+ ...args,
14252
+ usagePercentage,
14253
+ providerRecovery: args.recoveryUsagePercentage !== undefined,
14254
+ ...resolveHistorianDrainBudgetGeometry({ ...args, usagePercentage })
14255
+ });
14256
+ if (!state)
14257
+ return false;
14258
+ if (args.reportSkip) {
14259
+ args.reportSkip(state);
14260
+ return true;
14261
+ }
14262
+ let windows = loggedWindows.get(args.db);
14263
+ if (!windows) {
14264
+ windows = new Map;
14265
+ loggedWindows.set(args.db, windows);
14266
+ }
14267
+ if (windows.get(args.sessionId) !== state.resetsAt) {
14268
+ windows.set(args.sessionId, state.resetsAt);
14269
+ sessionLog2(args.sessionId, `historian skip: internal drain budget spent (${state.spentTokens}/${state.limitTokens} tokens); next eligible at ${new Date(state.nextEligibleAt).toISOString()}`);
14270
+ }
14271
+ return true;
14272
+ }
14273
+
14274
+ // src/hooks/magic-context/historian-failure-report.ts
14275
+ var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
14276
+ var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
14277
+ 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.";
14278
+ var REFUSAL_ERROR_MAX_CHARS = 500;
14279
+ var WARNING_ERROR_MAX_CHARS = 200;
14280
+ function readHistorianFailureStreak(db, sessionId, options = {}) {
14281
+ const state = getHistorianFailureState(db, sessionId);
14282
+ const count = state.failureCount;
14283
+ let since = null;
14284
+ if (count > 0) {
14285
+ const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
14286
+ if (recorded <= 0) {
14287
+ since = state.lastFailureAt;
14288
+ } else {
14289
+ const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
14290
+ since = times.length === recorded ? times[recorded - 1] ?? null : null;
14291
+ }
14292
+ }
14293
+ return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
14294
+ }
14295
+ function formatHistorianClockTime(at, now = Date.now()) {
14296
+ const date = new Date(at);
14297
+ const pad = (value) => String(value).padStart(2, "0");
14298
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
14299
+ const today = new Date(now);
14300
+ const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
14301
+ return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
14302
+ }
14303
+ function formatHistorianSeconds(ms) {
14304
+ const seconds = Math.max(0, ms) / 1000;
14305
+ return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
14306
+ }
14307
+ function singleLine(text) {
14308
+ return text.replace(/\s+/g, " ").trim();
14309
+ }
14310
+ function quoteError(error, maxChars) {
14311
+ const text = sanitizeDiagnosticText(singleLine(error));
14312
+ return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
14313
+ }
14314
+ function endSentence(text) {
14315
+ return /[.!?]$/.test(text) ? text : `${text}.`;
14316
+ }
14317
+ function usageClause(usagePercentage) {
14318
+ return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
14319
+ }
14320
+ function capitalize(text) {
14321
+ return text.charAt(0).toUpperCase() + text.slice(1);
14322
+ }
14323
+ function chunkLabel(chunk) {
14324
+ return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
14325
+ }
14326
+ function streakSentence(failures, now) {
14327
+ if (failures.count <= 0)
14328
+ return null;
14329
+ const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
14330
+ return `Summary runs failed in a row: ${failures.count}${since}.`;
14331
+ }
14332
+ function failureBelongsToRun(failures, run) {
14333
+ return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
14334
+ }
14335
+ function describeHistorianJoinRefusal(input) {
14336
+ const now = input.now ?? Date.now();
14337
+ const { run, failures } = input;
14338
+ const sentences = [
14339
+ `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.`
14340
+ ];
14341
+ const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
14342
+ const ownFailure = failureBelongsToRun(failures, run);
14343
+ const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
14344
+ if (ownFailure) {
14345
+ sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
14346
+ } else if (run && run.endedAt === undefined) {
14347
+ sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
14348
+ } else if (run) {
14349
+ sentences.push(`${subject} finished after the wait ended.`);
14350
+ }
14351
+ if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
14352
+ sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
14353
+ }
14354
+ const streak = streakSentence(failures, now);
14355
+ if (streak)
14356
+ sentences.push(streak);
14357
+ sentences.push(ACTIONS);
14358
+ return sentences.join(" ");
14359
+ }
14360
+ function describeRepeatedHistorianFailures(input) {
14361
+ const now = input.now ?? Date.now();
14362
+ const { failures } = input;
14363
+ const facts = [
14364
+ streakSentence(failures, now) ?? "Summary runs are failing.",
14365
+ ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
14366
+ ...failures.lastError ? [
14367
+ endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
14368
+ ] : [],
14369
+ `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
14370
+ ];
14371
+ return [
14372
+ "## Magic Context — History summaries keep failing",
14373
+ "",
14374
+ facts.join(" "),
14375
+ "",
14376
+ ACTIONS
14377
+ ].join(`
14378
+ `);
14379
+ }
14380
+ var repeatedFailureWarnings = new Map;
14381
+ function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
14382
+ const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
14383
+ if (failureCount < step || failureCount % step !== 0)
14384
+ return false;
14385
+ const last = repeatedFailureWarnings.get(sessionId);
14386
+ if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
14387
+ return false;
14388
+ }
14389
+ repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
14390
+ return true;
14391
+ }
14392
+ function takeRepeatedHistorianFailureWarning(input) {
14393
+ const now = input.now ?? Date.now();
14394
+ if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
14395
+ return null;
14396
+ }
14397
+ const failures = readHistorianFailureStreak(input.db, input.sessionId, {
14398
+ unrecordedFailures: input.unrecordedFailures
14399
+ });
14400
+ return describeRepeatedHistorianFailures({
14401
+ chunk: input.chunk,
14402
+ failures: { ...failures, count: input.failureCount },
14403
+ usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
14404
+ now
14405
+ });
14406
+ }
14407
+
14408
+ // src/hooks/magic-context/historian-history-wait.ts
14409
+ var historyWaits = new Map;
14410
+ function newestMessageId(snapshot) {
14411
+ try {
14412
+ const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
14413
+ const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
14414
+ const newest = ids.keys().next().value;
14415
+ if (newest)
14416
+ return newest;
14417
+ } catch {}
14418
+ return snapshot.rawLastMessageIdAtTrigger;
14419
+ }
14420
+ function recoveryWindow(snapshot, percentage) {
14421
+ return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
14422
+ }
14423
+ function clearHistorianHistoryWait(sessionId) {
14424
+ historyWaits.delete(sessionId);
14425
+ }
14426
+ function recordHistorianNoProgress(snapshot, emergency = false) {
14427
+ const newest = newestMessageId(snapshot);
14428
+ if (!newest)
14429
+ return;
14430
+ const previous = historyWaits.get(snapshot.sessionId);
14431
+ const sameHistory = previous?.newestMessageId === newest;
14432
+ historyWaits.set(snapshot.sessionId, {
14433
+ newestMessageId: newest,
14434
+ recoveryAttempted: sameHistory && previous.recoveryAttempted || emergency || recoveryWindow(snapshot, snapshot.usagePercentage),
14435
+ floorLiftAttempted: sameHistory && previous.floorLiftAttempted || snapshot.liftLivePromptFloor === true
14436
+ });
14437
+ }
14438
+ function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
14439
+ const wait = historyWaits.get(snapshot.sessionId);
14440
+ if (!wait)
14441
+ return false;
14442
+ const newest = newestMessageId(snapshot);
14443
+ if (newest && newest !== wait.newestMessageId) {
14444
+ try {
14445
+ const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
14446
+ if (order === null || order > 0)
14447
+ return false;
14448
+ } catch {}
14449
+ }
14450
+ const recovery = options.emergency || recoveryWindow(snapshot, options.usagePercentage ?? snapshot.usagePercentage);
14451
+ const floorLift = snapshot.liftLivePromptFloor === true;
14452
+ if (recovery && !wait.recoveryAttempted || floorLift && !wait.floorLiftAttempted) {
14453
+ if (options.claim) {
14454
+ wait.recoveryAttempted ||= recovery;
14455
+ wait.floorLiftAttempted ||= floorLift;
14456
+ }
14457
+ return false;
14458
+ }
14459
+ return true;
14460
+ }
14461
+
14462
+ // src/tools/ctx-note/render.ts
14463
+ var GLANCE_TITLE_MAX = 80;
14464
+ var NUDGE_TITLE_MAX = 60;
14465
+ var STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
14466
+ var EMPTY_READ_REPLY = `## Notes
14467
+
14468
+ No session notes or smart notes.`;
14469
+ function noteTouchedAt(note) {
14470
+ return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
14471
+ }
14472
+ function formatNoteAge(touchedAt, nowMs) {
14473
+ const elapsed = Math.max(0, nowMs - touchedAt);
14474
+ const minutes = Math.floor(elapsed / 60000);
14475
+ if (minutes < 60)
14476
+ return `${minutes}m`;
14477
+ const hours = Math.floor(elapsed / 3600000);
14478
+ if (hours < 24)
14479
+ return `${hours}h`;
14480
+ const days = Math.floor(elapsed / 86400000);
14481
+ if (days < 7)
14482
+ return `${days}d`;
14483
+ return `${Math.floor(days / 7)}w`;
14484
+ }
14485
+ function clipNoteTitle(content, max) {
14486
+ const firstLine = (content.split(`
14487
+ `, 1)[0] ?? "").trim();
14488
+ const characters = [...firstLine];
14489
+ if (characters.length <= max)
14490
+ return firstLine;
14491
+ return `${characters.slice(0, max).join("")}…`;
14492
+ }
14493
+ function formatGlanceRow(note, nowMs) {
14494
+ const touchedAt = noteTouchedAt(note);
14495
+ const markers = [];
14496
+ if (note.status !== "active")
14497
+ markers.push(note.status);
14498
+ if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
14499
+ markers.push(`parked: ${note.readyReason ?? "Condition can't be checked"}`);
14500
+ }
14501
+ if (nowMs - touchedAt >= STALE_AFTER_MS)
14502
+ markers.push("stale");
14503
+ const suffix = markers.length > 0 ? ` · ${markers.join(" · ")}` : "";
14504
+ const title = clipNoteTitle(note.content, GLANCE_TITLE_MAX);
14505
+ return `#${note.id} · ${formatNoteAge(touchedAt, nowMs)} · ${title}${suffix}`;
14506
+ }
14507
+ function newestFirst(left, right) {
14508
+ return right.updatedAt - left.updatedAt || right.id - left.id;
14509
+ }
14510
+ function orderGlanceNotes(notes) {
14511
+ const ready = notes.filter((note) => note.status === "ready").sort(newestFirst);
14512
+ const pending = notes.filter((note) => note.status === "pending").sort(newestFirst);
14513
+ const rest = notes.filter((note) => note.status !== "ready" && note.status !== "pending").sort(newestFirst);
14514
+ return [...ready, ...pending, ...rest];
14515
+ }
14516
+ function renderGlance(notes, options) {
14517
+ const ordered = orderGlanceNotes(notes);
14518
+ const page = ordered.slice(options.offset, options.offset + options.limit);
14519
+ if (page.length === 0)
14520
+ return EMPTY_READ_REPLY;
14521
+ const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
14522
+ `);
14523
+ const remaining = ordered.length - options.offset - page.length;
14524
+ const footer = remaining > 0 ? `
14525
+
14526
+ Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
14527
+ return `## Notes
14528
+
14529
+ ${rows}${footer}`;
14530
+ }
14531
+ function formatNoteBody(note, nowMs) {
14532
+ const touchedAt = noteTouchedAt(note);
14533
+ const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
14534
+ const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
14535
+ if (note.type !== "smart")
14536
+ return head;
14537
+ const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
14538
+ const label = note.status === "ready" ? "Condition met" : "Condition";
14539
+ const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
14540
+ ${note.readyReason}` : "";
14541
+ return `${head}
14542
+ ${label}: ${condition}${failure}`;
14543
+ }
14544
+ function renderNotesById(entries, nowMs) {
14545
+ const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
14546
+ return `## Notes by ID
14547
+
14548
+ ${lines.join(`
14549
+
14550
+ `)}`;
14551
+ }
14552
+ function formatTraySuffix(tray, nowMs) {
14553
+ if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
14554
+ return "";
14555
+ return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
14376
14556
  }
14377
- function readLastCompartmentBoundary(db, sessionId) {
14378
- const row = db.prepare(`SELECT COALESCE(MAX(end_message), -1) AS max_end,
14379
- (SELECT end_message_id FROM compartments
14380
- WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
14381
- FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
14382
- const endMessageId = row?.end_message_id;
14383
- return {
14384
- endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
14385
- endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
14386
- };
14557
+ function formatWriteReply(noteId, tray, nowMs) {
14558
+ return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
14387
14559
  }
14388
- function resolveBoundaryContext(args) {
14389
- const lastCompartmentBoundary = readLastCompartmentBoundary(args.db, args.sessionId);
14390
- const lastCompartmentEndOrdinal = lastCompartmentBoundary.endOrdinal;
14391
- const triggerBudget = deriveTriggerBudget2(args.contextLimit, args.executeThresholdPercentage);
14392
- let meta = args.protectedTailMeta ?? loadProtectedTailMeta(args.db, args.sessionId);
14393
- let migrationFloorActive = false;
14394
- if (meta.protectedTailPolicyVersion < 3) {
14395
- let legacyBoundary = 1;
14396
- try {
14397
- legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
14398
- } catch (error) {
14399
- sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
14400
- }
14401
- const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
14402
- meta = seedResult;
14403
- migrationFloorActive = seedResult.seeded;
14560
+ function noteNudgePickIndex(sessionId, counter, poolSize) {
14561
+ if (poolSize <= 0)
14562
+ return 0;
14563
+ const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
14564
+ let hash = 2166136261;
14565
+ for (const byte of bytes) {
14566
+ hash ^= byte;
14567
+ hash = Math.imul(hash, 16777619) >>> 0;
14404
14568
  }
14405
- const calibration = sessionDecisionCalibration(args.db, args.sessionId);
14406
- const storedTokenTotalsForMessages = (messageIds, messages = []) => {
14407
- try {
14408
- const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
14409
- return {
14410
- totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
14411
- summaryRemovedTotals: weights.summaryRemovedTotals
14412
- };
14413
- } catch (error) {
14414
- sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
14415
- return;
14416
- }
14417
- };
14418
- return {
14419
- sessionId: args.sessionId,
14420
- mode: args.mode,
14421
- contextLimit: args.contextLimit,
14422
- executeThresholdPercentage: args.executeThresholdPercentage,
14423
- triggerBudget,
14424
- usage: args.usage ?? null,
14425
- usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
14426
- lastCompartmentEndOrdinal,
14427
- lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
14428
- priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
14429
- protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
14430
- migrationFloorActive,
14431
- emergencyTailScale: args.emergencyTailScale,
14432
- recovery: args.recovery,
14433
- liftLivePromptFloor: args.liftLivePromptFloor,
14434
- providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
14435
- cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
14436
- storedTokenTotalsForMessages,
14437
- calibration
14438
- };
14569
+ return hash % poolSize;
14439
14570
  }
14440
- function resolveOpenCodeProtectedTailBoundary(args) {
14441
- return resolveProtectedTailBoundary(resolveBoundaryContext(args));
14571
+ function formatNoteNudge(args) {
14572
+ const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
14573
+ const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
14574
+ const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
14575
+ return `${counts}${oldest}${shown}`;
14442
14576
  }
14443
- function resolveWrapupProtectedTailBoundary(args) {
14444
- const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
14445
- const createdAt = ctx.createdAt ?? Date.now();
14446
- const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
14447
- const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
14448
- const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
14449
- const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
14450
- const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
14451
- const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
14452
- const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
14453
- providerShapeVersion: ctx.providerShapeVersion,
14454
- cacheNamespace: ctx.cacheNamespace,
14455
- calibration: ctx.calibration,
14456
- absoluteMessageCount,
14457
- storedTotalForMessage: storedTotals ? (m) => {
14458
- const value = storedTotals?.get(m.id);
14459
- return value === undefined ? null : value;
14460
- } : undefined
14461
- });
14462
- const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
14463
- providerShapeVersion: ctx.providerShapeVersion,
14464
- cacheNamespace: ctx.cacheNamespace,
14465
- calibration: ctx.calibration,
14466
- absoluteMessageCount,
14467
- measure: "summary-removed",
14468
- storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
14469
- });
14470
- const rawMessageCount = index.rawMessageCount;
14471
- const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
14472
- const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
14473
- const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
14474
- const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
14475
- const keep = Math.max(1, Math.floor(args.messagesToKeep));
14476
- let targetProtectedTailStart = offset;
14477
- let boundaryReason = "manual-wrapup-empty";
14478
- if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
14479
- targetProtectedTailStart = offset;
14480
- boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
14481
- } else {
14482
- targetProtectedTailStart = anchorRawMessageCount - keep + 1;
14483
- boundaryReason = "manual-wrapup-keep-watermark";
14484
- const arcs = buildToolArcs(messages);
14485
- const fenced = fenceWrapupBoundaryForToolArcs({
14486
- candidate: targetProtectedTailStart,
14487
- arcs,
14488
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14489
- });
14490
- if (fenced !== targetProtectedTailStart)
14491
- boundaryReason = "manual-wrapup-tool-arc";
14492
- targetProtectedTailStart = fenced;
14493
- const snapped = snapWrapupBoundaryToUser({
14494
- messages,
14495
- index,
14496
- candidate: targetProtectedTailStart,
14497
- offset,
14498
- triggerBudget: ctx.triggerBudget
14499
- });
14500
- if (snapped !== targetProtectedTailStart)
14501
- boundaryReason = "manual-wrapup-user-snap";
14502
- targetProtectedTailStart = snapped;
14503
- const refenced = fenceWrapupBoundaryForToolArcs({
14504
- candidate: targetProtectedTailStart,
14505
- arcs,
14506
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14507
- });
14508
- if (refenced !== targetProtectedTailStart)
14509
- boundaryReason = "manual-wrapup-tool-arc";
14510
- targetProtectedTailStart = refenced;
14577
+
14578
+ // src/hooks/magic-context/note-nudger.ts
14579
+ var observedUsers = new WeakMap;
14580
+ function observeNoteNudgeServe(args) {
14581
+ let sessions = observedUsers.get(args.db);
14582
+ if (!sessions) {
14583
+ sessions = new Map;
14584
+ observedUsers.set(args.db, sessions);
14511
14585
  }
14512
- targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
14513
- targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
14514
- const target = deriveProtectedTailTokenTarget({
14515
- contextLimit: ctx.contextLimit,
14516
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14517
- usagePercentage,
14518
- triggerBudget: ctx.triggerBudget
14519
- });
14520
- const perRunCap = selectPerRunCap({
14521
- usagePercentage,
14522
- N: target.N,
14523
- contextLimit: ctx.contextLimit,
14524
- executeThresholdPercentage: ctx.executeThresholdPercentage
14525
- });
14526
- let headDiagnostics;
14527
- const head = applyHeadCap({
14528
- observeDiagnostics: (value) => {
14529
- headDiagnostics = value;
14530
- },
14531
- index: summaryRemovedIndex,
14532
- protectedTailStart: targetProtectedTailStart,
14533
- offset,
14534
- arcs: buildToolArcs(messages),
14535
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
14536
- capTokens: perRunCap,
14537
- recentOpenArcCutoff: targetProtectedTailStart
14538
- });
14539
- const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
14540
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
14541
- const snapshot = {
14542
- sessionId: ctx.sessionId,
14543
- mode: "manual-wrapup",
14544
- offset,
14545
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14546
- offsetMessageId: boundaryMessageId(index, offset),
14547
- protectedTailStart: targetProtectedTailStart,
14548
- protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
14549
- eligibleEndOrdinal,
14550
- eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
14551
- rawMessageCountAtTrigger: rawMessageCount,
14552
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
14553
- N: keep,
14554
- usagePercentage,
14555
- usageInputTokens,
14556
- usageSource: ctx.usageSource,
14557
- contextLimit: ctx.contextLimit,
14558
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14559
- triggerBudget: ctx.triggerBudget,
14560
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14561
- migrationFloorActive: ctx.migrationFloorActive,
14562
- emergencyTailScale: ctx.emergencyTailScale,
14563
- providerShapeVersion: ctx.providerShapeVersion,
14564
- cacheNamespace: ctx.cacheNamespace,
14565
- createdAt,
14566
- rawRangeFingerprint,
14567
- trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
14568
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
14569
- oversizeAtomicUnit: head.oversizeAtomicUnit,
14570
- boundaryReason,
14571
- diagnostics: boundaryDiagnostics({
14572
- tailTarget: target,
14573
- usable: target.usable,
14574
- usagePercentage,
14575
- N: target.N,
14576
- triggerBudget: ctx.triggerBudget,
14577
- capTokens: perRunCap,
14578
- sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
14579
- protectedTailStart: targetProtectedTailStart,
14580
- livePromptFloor: {
14581
- ordinal: null,
14582
- from: targetProtectedTailStart,
14583
- to: targetProtectedTailStart
14584
- },
14585
- head: headDiagnostics
14586
- })
14587
- };
14588
- return {
14589
- snapshot,
14590
- rawMessagesAboveLastCompartment,
14591
- anchorRawMessageCount,
14592
- targetProtectedTailStart,
14593
- targetEligibleEndOrdinal: targetProtectedTailStart
14594
- };
14595
- }
14596
- function getRawHistoryEligibility(db, sessionId) {
14597
- const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
14598
- const offset = Math.max(1, lastCompartmentEnd + 1);
14599
- const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
14600
- const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
14601
- return {
14602
- lastCompartmentEnd,
14603
- offset,
14604
- rawMessageCount,
14605
- hasRawBeyondLastCompartment: rawMessageCount >= offset
14586
+ let seen = sessions.get(args.sessionId);
14587
+ const warm = seen !== undefined && seen.size > 0;
14588
+ if (!seen)
14589
+ seen = new Set;
14590
+ const firstServe = args.anchorMessageId !== null && !seen.has(args.anchorMessageId);
14591
+ for (const id of args.userMessageIds)
14592
+ seen.add(id);
14593
+ sessions.set(args.sessionId, seen);
14594
+ return {
14595
+ isFirstServe: warm && args.isLiveTail && firstServe,
14596
+ prefixRewriteCoversAnchor: args.anchorMessageId !== null && args.prefixRewriteCoversAnchor
14606
14597
  };
14607
14598
  }
14608
- function hasRunnableCompartmentWindow(snapshot) {
14609
- if (snapshot.offset >= snapshot.protectedTailStart)
14610
- return false;
14611
- if (snapshot.eligibleEndOrdinal <= snapshot.offset)
14612
- return false;
14613
- if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
14614
- return true;
14615
- const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
14616
- if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
14617
- return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
14618
- }
14619
- return snapshot.eligibleEndOrdinal > snapshot.offset;
14599
+ var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
14600
+ var lastDeliveredAt = new Map;
14601
+ function isCoolingDown(deliveredAt, now) {
14602
+ return now - deliveredAt < NOTE_NUDGE_COOLDOWN_MS;
14620
14603
  }
14621
- function boundarySnapshotIdChecks(snapshot) {
14622
- const checks = [
14623
- [snapshot.offset, snapshot.offsetMessageId, "offset"],
14624
- [snapshot.rawMessageCountAtTrigger, snapshot.rawLastMessageIdAtTrigger, "last"]
14625
- ];
14626
- if (snapshot.protectedTailStart <= snapshot.rawMessageCountAtTrigger) {
14627
- checks.push([
14628
- snapshot.protectedTailStart,
14629
- snapshot.protectedTailStartMessageId,
14630
- "protectedTailStart"
14631
- ]);
14604
+ function getNoteNudgeDeliveredAt(sessionId) {
14605
+ const deliveredAt = lastDeliveredAt.get(sessionId);
14606
+ if (deliveredAt === undefined)
14607
+ return 0;
14608
+ if (!isCoolingDown(deliveredAt, Date.now())) {
14609
+ lastDeliveredAt.delete(sessionId);
14610
+ return 0;
14632
14611
  }
14633
- if (snapshot.eligibleEndOrdinal > snapshot.offset) {
14634
- checks.push([
14635
- snapshot.eligibleEndOrdinal - 1,
14636
- snapshot.eligibleEndMessageId,
14637
- "eligibleEnd"
14638
- ]);
14612
+ return deliveredAt;
14613
+ }
14614
+ function recordNoteNudgeDeliveryTime(sessionId) {
14615
+ const now = Date.now();
14616
+ for (const [otherSessionId, deliveredAt] of lastDeliveredAt) {
14617
+ if (!isCoolingDown(deliveredAt, now))
14618
+ lastDeliveredAt.delete(otherSessionId);
14639
14619
  }
14640
- return checks;
14620
+ lastDeliveredAt.set(sessionId, now);
14641
14621
  }
14642
- function validateBoundarySnapshot(args) {
14643
- const { snapshot, exactIds } = args;
14644
- if (args.currentContextLimit && args.currentContextLimit !== snapshot.contextLimit) {
14645
- return {
14646
- ok: false,
14647
- reason: "model_or_limit_changed",
14648
- detail: `context limit changed from ${snapshot.contextLimit} to ${args.currentContextLimit}`
14649
- };
14622
+ function onNoteTrigger(db, sessionId, trigger) {
14623
+ let transactionStartedAt = 0;
14624
+ db.transaction(() => {
14625
+ transactionStartedAt = performance.now();
14626
+ setPersistedNoteNudgeTrigger(db, sessionId);
14627
+ }).immediate();
14628
+ logSlowWriteTransaction("note_nudge_trigger", transactionStartedAt);
14629
+ sessionLog2(sessionId, `note-nudge: trigger fired (${trigger}), triggerPending=true`);
14630
+ }
14631
+ function peekNoteNudgeText(db, sessionId, currentUserMessageId, projectIdentity, noteReadStillVisible, eligibility) {
14632
+ const state = getPersistedNoteNudge(db, sessionId);
14633
+ if (!state.triggerPending)
14634
+ return null;
14635
+ if (eligibility && !eligibility.isFirstServe && !eligibility.prefixRewriteCoversAnchor) {
14636
+ sessionLog2(sessionId, "note-nudge: deferring — user already served or first serve unproven");
14637
+ return null;
14650
14638
  }
14651
- const currentRawMessageCount = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
14652
- if (snapshot.rawMessageCountAtTrigger > currentRawMessageCount) {
14653
- return { ok: false, reason: "stale_snapshot", detail: "raw message count shrank" };
14639
+ if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
14640
+ setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
14641
+ state.triggerMessageId = currentUserMessageId;
14654
14642
  }
14655
- const idAt = (ordinal) => {
14656
- if (!exactIds)
14657
- return readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, ordinal, ordinal).keys().next().value ?? null;
14658
- const id = exactIds.get(ordinal);
14659
- if (id === undefined)
14660
- throw new Error(`boundary validation was given no exact id for ordinal ${ordinal}`);
14661
- return id;
14662
- };
14663
- for (const [ordinal, expected, label] of boundarySnapshotIdChecks(snapshot)) {
14664
- if (expected !== idAt(ordinal)) {
14665
- return {
14666
- ok: false,
14667
- reason: "stale_snapshot",
14668
- detail: `${label} ordinal ${ordinal} id changed`
14669
- };
14643
+ if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
14644
+ sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
14645
+ return null;
14646
+ }
14647
+ const deliveredAt = getNoteNudgeDeliveredAt(sessionId);
14648
+ if (deliveredAt > 0) {
14649
+ sessionLog2(sessionId, `note-nudge: suppressing — last delivered ${Math.round((Date.now() - deliveredAt) / 1000)}s ago (cooldown ${NOTE_NUDGE_COOLDOWN_MS / 60000}m)`);
14650
+ clearNoteNudgeTriggerOnly(db, sessionId);
14651
+ return null;
14652
+ }
14653
+ const notes = getSessionNotes(db, sessionId);
14654
+ const readySmartNotes = projectIdentity ? getReadySmartNotes(db, projectIdentity) : [];
14655
+ const totalCount = notes.length + readySmartNotes.length;
14656
+ if (totalCount === 0) {
14657
+ sessionLog2(sessionId, "note-nudge: triggerPending but no notes found, skipping");
14658
+ clearNoteNudgeTriggerOnly(db, sessionId);
14659
+ return null;
14660
+ }
14661
+ const lastReadAt = getNoteLastReadAt(db, sessionId);
14662
+ if (lastReadAt > 0 && noteReadStillVisible) {
14663
+ const mostRecentNoteActivity = maxNoteActivityTime([...notes, ...readySmartNotes]);
14664
+ if (mostRecentNoteActivity > 0 && lastReadAt > mostRecentNoteActivity) {
14665
+ 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()}`);
14666
+ clearNoteNudgeTriggerOnly(db, sessionId);
14667
+ return null;
14670
14668
  }
14671
14669
  }
14672
- const expectedOffset = Math.max(1, getLastCompartmentEndMessage(args.db, snapshot.sessionId) + 1);
14673
- if (expectedOffset !== snapshot.offset) {
14674
- return {
14675
- ok: false,
14676
- reason: "stale_snapshot",
14677
- detail: `last compartment moved: offset ${snapshot.offset} -> ${expectedOffset}`
14678
- };
14670
+ const failureNotice = notes.find((note) => /^Smart note #\d+ cannot be checked\.\nCondition: /.test(note.content));
14671
+ if (failureNotice) {
14672
+ const reason = failureNotice.content.split(`
14673
+ Reason: `)[1]?.split(`
14674
+ `)[0] ?? "check unavailable";
14675
+ 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.`;
14679
14676
  }
14680
- const fingerprintMessages = readRawSessionMessageRange2(snapshot.sessionId, snapshot.offset, snapshot.eligibleEndOrdinal - 1);
14681
- const fingerprint = computeRawRangeFingerprint(fingerprintMessages, snapshot.offset, snapshot.eligibleEndOrdinal);
14682
- if (fingerprint !== snapshot.rawRangeFingerprint) {
14683
- return { ok: false, reason: "stale_snapshot", detail: "raw range fingerprint changed" };
14677
+ const parts = [];
14678
+ if (notes.length > 0) {
14679
+ parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
14684
14680
  }
14685
- return { ok: true };
14681
+ if (readySmartNotes.length > 0) {
14682
+ parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
14683
+ }
14684
+ sessionLog2(sessionId, `note-nudge: delivering nudge for ${parts.join(" and ")}`);
14685
+ return formatNoteNudge({
14686
+ readyCount: readySmartNotes.length,
14687
+ activeCount: notes.length,
14688
+ oldestActiveTouchedAt: oldestTouchedAt(notes),
14689
+ shown: pickNudgeNote({ db, sessionId, activeNotes: notes, readySmartNotes }),
14690
+ nowMs: Date.now()
14691
+ });
14686
14692
  }
14687
- function recordHighPressureNoEligibleHead(db, snapshot) {
14688
- const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
14689
- if (snapshot.usagePercentage < forceMaterializationPercentage && !snapshot.emergencyTailScale) {
14690
- return 0;
14693
+ function oldestTouchedAt(notes) {
14694
+ return notes.reduce((min, note) => {
14695
+ const touchedAt = noteTouchedAt(note);
14696
+ return min === null || touchedAt < min ? touchedAt : min;
14697
+ }, null);
14698
+ }
14699
+ function pickNudgeNote(args) {
14700
+ const pool = args.readySmartNotes.length > 0 ? [...args.readySmartNotes].sort((left, right) => left.id - right.id) : [...args.activeNotes].sort((left, right) => left.id - right.id);
14701
+ if (pool.length === 0)
14702
+ return null;
14703
+ const counter = getNoteNudgeAnchors(args.db, args.sessionId).length;
14704
+ return pool[noteNudgePickIndex(args.sessionId, counter, pool.length)] ?? null;
14705
+ }
14706
+ function maxNoteActivityTime(notes) {
14707
+ let max = 0;
14708
+ for (const note of notes) {
14709
+ if (note.updatedAt > max)
14710
+ max = note.updatedAt;
14711
+ if (note.readyAt !== null && note.readyAt > max)
14712
+ max = note.readyAt;
14691
14713
  }
14692
- return recordProtectedTailNoEligibleHead(db, snapshot.sessionId);
14714
+ return max;
14715
+ }
14716
+ function markNoteNudgeDelivered(db, sessionId, text, messageId) {
14717
+ if (!messageId) {
14718
+ clearNoteNudgeTriggerAndCooldown(db, sessionId);
14719
+ sessionLog2(sessionId, "note-nudge: marked delivered without anchor");
14720
+ return { ok: true, kind: "already-present" };
14721
+ }
14722
+ const outcome = db.transaction(() => {
14723
+ const delivered = deliverNoteNudgeAtomic(db, sessionId, messageId, text);
14724
+ const nudgeText = text?.replace(/^\s*<instruction name="deferred_notes">/, "") ?? "";
14725
+ const noticeId = nudgeText.match(/^Smart note check unavailable: [\s\S]*Read ctx_note #(\d+) for the condition/);
14726
+ if (delivered.ok && noticeId) {
14727
+ db.prepare(`UPDATE notes SET status = 'dismissed', updated_at = ?
14728
+ WHERE id = ? AND type = 'session' AND session_id = ?
14729
+ AND content LIKE 'Smart note #% cannot be checked.%'`).run(Date.now(), Number(noticeId[1]), sessionId);
14730
+ }
14731
+ return delivered;
14732
+ }).immediate();
14733
+ if (outcome.ok) {
14734
+ recordNoteNudgeDeliveryTime(sessionId);
14735
+ }
14736
+ sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
14737
+ return outcome;
14738
+ }
14739
+ function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
14740
+ db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
14741
+ lastDeliveredAt.delete(sessionId);
14742
+ }
14743
+ function clearNoteNudgeTriggerOnly(db, sessionId) {
14744
+ db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
14745
+ }
14746
+
14747
+ // src/hooks/magic-context/persist-filtered-noise.ts
14748
+ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
14749
+ const rows = chunk.filteredNoiseLines ?? [];
14750
+ const start = chunk.startIndex;
14751
+ if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
14752
+ return false;
14753
+ const endId = rows[rows.length - 1].messageId;
14754
+ if (!hasRawSessionMessageById2(sessionId, endId)) {
14755
+ sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
14756
+ return false;
14757
+ }
14758
+ const saved = db.transaction(() => {
14759
+ const prior = getCompartments(db, sessionId);
14760
+ const last = prior.at(-1);
14761
+ if ((last?.endMessage ?? 0) + 1 !== start)
14762
+ return false;
14763
+ appendCompartments(db, sessionId, [
14764
+ {
14765
+ sequence: (last?.sequence ?? -1) + 1,
14766
+ startMessage: start,
14767
+ endMessage: eligibleEnd - 1,
14768
+ startMessageId: rows[0].messageId,
14769
+ endMessageId: rows[rows.length - 1].messageId,
14770
+ title: "",
14771
+ content: "",
14772
+ p1: "",
14773
+ p2: "",
14774
+ p3: "",
14775
+ p4: "",
14776
+ episodeType: "filtered-noise",
14777
+ importance: 1
14778
+ }
14779
+ ]);
14780
+ return true;
14781
+ }).immediate();
14782
+ if (saved)
14783
+ sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
14784
+ return saved;
14693
14785
  }
14694
14786
 
14695
14787
  // src/hooks/magic-context/raw-exact-ordinal-read.ts
@@ -15212,7 +15304,6 @@ async function runCompartmentAgent(deps) {
15212
15304
  if (promptFit.trimmed || chunkTokens < historianChunkTokens) {
15213
15305
  sessionLog2(sessionId, `historian prompt fit: sized to ${producerModel ?? "unknown"} (${describeHistorianPromptTrim(promptFit)}; requestedChunkTokens=${historianChunkTokens})`);
15214
15306
  }
15215
- const perRunCap = selectPerRunCap(boundarySnapshot);
15216
15307
  if (!deps.forceDrainQuota && shouldWaitForNewHistorianHistory(boundarySnapshot, {
15217
15308
  emergency: getOverflowState(db, sessionId).needsEmergencyRecovery
15218
15309
  })) {
@@ -15221,19 +15312,27 @@ async function runCompartmentAgent(deps) {
15221
15312
  sessionLog2(sessionId, "historian no-op: waiting for new history after no forward progress");
15222
15313
  return;
15223
15314
  }
15224
- const usable = Math.max(1, Math.round(boundarySnapshot.contextLimit * boundarySnapshot.executeThresholdPercentage / 100));
15315
+ const usagePercentage = deps.drainBudgetUsagePercentage ?? boundarySnapshot.usagePercentage;
15316
+ const { usable, perRunCap } = deps.drainBudgetUsagePercentage === undefined ? {
15317
+ usable: Math.max(1, Math.round(boundarySnapshot.contextLimit * boundarySnapshot.executeThresholdPercentage / 100)),
15318
+ perRunCap: selectPerRunCap(boundarySnapshot)
15319
+ } : resolveHistorianDrainBudgetGeometry({ ...boundarySnapshot, usagePercentage });
15225
15320
  const reserve = deps.forceDrainQuota ? { ok: true, reservation: null } : reserveProtectedTailDrainTokens({
15226
15321
  db,
15227
15322
  sessionId,
15228
15323
  runId: crypto.randomUUID(),
15229
15324
  trueRawTokens: boundarySnapshot.summaryRemovedEligibleTokens,
15230
- usagePercentage: boundarySnapshot.usagePercentage,
15325
+ usagePercentage,
15326
+ providerRecovery: deps.drainBudgetUsagePercentage !== undefined,
15231
15327
  usable,
15232
15328
  perRunCap,
15233
15329
  executeThresholdPercentage: boundarySnapshot.executeThresholdPercentage
15234
15330
  });
15235
15331
  if (!reserve.ok) {
15236
- sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
15332
+ if (deps.reportDrainSkip && reserve.drainSkip)
15333
+ deps.reportDrainSkip(reserve.drainSkip);
15334
+ else
15335
+ sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
15237
15336
  telemetry.status = "noop";
15238
15337
  telemetry.failureReason = "internal protected-tail drain budget spent";
15239
15338
  return;
@@ -15403,6 +15502,8 @@ ${chunkText}`,
15403
15502
  const discardedLast = persistedCompartments.length < emittedCompartments.length;
15404
15503
  const weakLookaheadFinalCompartment = forceKeepLastCompartmentForChunk;
15405
15504
  const skipUnanchoredPromotion = discardedLast || weakLookaheadFinalCompartment;
15505
+ const facts = validatedPass.facts;
15506
+ const publishableFacts = !skipUnanchoredPromotion ? facts : retainAnchoredHistorianFacts(facts, weakLookaheadFinalCompartment ? Math.min(persistedCompartments.length, emittedCompartments.length - 1) : persistedCompartments.length);
15406
15507
  const embeddingActive = !!promotionDirectory;
15407
15508
  const promotionActive = embeddingActive && deps.memoryEnabled !== false && deps.autoPromote !== false;
15408
15509
  const promotionProjectIdentity = promotionDirectory ? resolveProjectIdentity(promotionDirectory) : "";
@@ -15416,10 +15517,7 @@ ${chunkText}`,
15416
15517
  }
15417
15518
  return true;
15418
15519
  });
15419
- const unanchoredPromotionSkipReason = discardedLast ? "discarded_last" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
15420
- if (unanchoredPromotionSkipReason) {
15421
- 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}`);
15422
- }
15520
+ const weakTailReason = telemetry.discardedLast ? "discarded_last" : discardedLast ? "unserved_final_compartment" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
15423
15521
  let promotedFactRefs = [];
15424
15522
  let promotedFactCount = 0;
15425
15523
  let publishedEventCount = 0;
@@ -15462,9 +15560,9 @@ ${chunkText}`,
15462
15560
  }
15463
15561
  appendCompartments(db, sessionId, persistedCompartments);
15464
15562
  persistedIds = getNewestCompartmentIds(db, sessionId, persistedCompartments.length);
15465
- if (promotionActive && !skipUnanchoredPromotion) {
15563
+ if (promotionActive && publishableFacts.length > 0) {
15466
15564
  try {
15467
- const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, validatedPass.facts ?? []);
15565
+ const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, publishableFacts);
15468
15566
  promotedFactRefs = promotion.newMemoryRefs;
15469
15567
  promotedFactCount = promotion.factsPromoted;
15470
15568
  } catch (error) {
@@ -15532,6 +15630,13 @@ ${chunkText}`,
15532
15630
  }
15533
15631
  updateSessionMeta(db, sessionId, { compartmentInProgress: false });
15534
15632
  completedSuccessfully = true;
15633
+ if (weakTailReason) {
15634
+ logWeakTailFactPromotion(sessionId, {
15635
+ reason: weakTailReason,
15636
+ emitted: facts.length,
15637
+ stored: promotedFactCount
15638
+ });
15639
+ }
15535
15640
  {
15536
15641
  const facts = validatedPass.facts ?? [];
15537
15642
  const validIds = persistedIds.filter((id) => typeof id === "number");
@@ -16948,4 +17053,4 @@ ${failure}`;
16948
17053
  }
16949
17054
  }
16950
17055
 
16951
- export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, 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, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, 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, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };
17056
+ export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, 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, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, 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, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, 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, clearNoteNudgeTriggerOnly, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };