@cortexkit/opencode-magic-context 0.49.91 → 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 (121) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +2 -2
  3. package/dist/{conflict-warning-hook-kbq6ppjf.js → conflict-warning-hook-exf96bpt.js} +3 -3
  4. package/dist/{context-6qq5e1ry.js → context-e8qd2v00.js} +78 -66
  5. package/dist/features/magic-context/overflow-detection.d.ts +7 -1
  6. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  7. package/dist/features/magic-context/storage-meta-persisted.d.ts +13 -3
  8. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  9. package/dist/hooks/magic-context/compartment-parser.d.ts +2 -0
  10. package/dist/hooks/magic-context/compartment-parser.d.ts.map +1 -1
  11. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  12. package/dist/hooks/magic-context/compartment-runner-types.d.ts +5 -5
  13. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  14. package/dist/hooks/magic-context/compartment-runner-validation.d.ts +3 -0
  15. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/compartment-trigger.d.ts +2 -1
  17. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/event-handler.d.ts +4 -0
  19. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/event-resolvers.d.ts +5 -0
  21. package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/historian-drain-gate.d.ts +15 -0
  23. package/dist/hooks/magic-context/historian-drain-gate.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/historian-prompt.generated.d.ts +1 -1
  25. package/dist/hooks/magic-context/historian-prompt.generated.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/historian-publish-stage-logger.d.ts +5 -0
  27. package/dist/hooks/magic-context/historian-publish-stage-logger.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/provider-overflow-notice.d.ts +8 -0
  30. package/dist/hooks/magic-context/provider-overflow-notice.d.ts.map +1 -0
  31. package/dist/hooks/magic-context/read-session-db.d.ts +2 -0
  32. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +5 -0
  34. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  36. package/dist/{index-czz0w2c4.js → index-01h7tqe3.js} +11 -0
  37. package/dist/{index-febyth5n.js → index-3f3d548g.js} +1372 -1307
  38. package/dist/{index-nmkv8yvs.js → index-41bma6qs.js} +2 -2
  39. package/dist/{index-r6r2eh90.js → index-5a9kwapd.js} +3 -3
  40. package/dist/{index-e8my7q6m.js → index-5pmf4jpj.js} +5 -5
  41. package/dist/{index-mq97qmb8.js → index-5y9w2ax7.js} +2 -2
  42. package/dist/{index-5wgdbj2h.js → index-6rk44cer.js} +2 -2
  43. package/dist/{index-gqhebzxx.js → index-901exj0f.js} +89 -24
  44. package/dist/{index-6zewd2n5.js → index-9ffntwyr.js} +1 -1
  45. package/dist/{index-wfahebsc.js → index-anwy2mfb.js} +4 -4
  46. package/dist/{index-83qd3n7s.js → index-et39x9k3.js} +1 -1
  47. package/dist/{index-dva352qe.js → index-hbn5g7rt.js} +1 -1
  48. package/dist/{index-capcna4r.js → index-hre29c1a.js} +1 -1
  49. package/dist/{index-sr8dmp7p.js → index-j2w79s9r.js} +76 -6
  50. package/dist/{index-qna2ra0s.js → index-jba6ny4m.js} +27 -3
  51. package/dist/{index-ywgv1xcb.js → index-mjy2k9jr.js} +1 -1
  52. package/dist/{index-3yw525kb.js → index-n71006wq.js} +6 -6
  53. package/dist/{index-m6vhxsce.js → index-r3tdqqtq.js} +86 -62
  54. package/dist/{index-x40zr813.js → index-sp5pvs95.js} +9 -1
  55. package/dist/{index-6t7jvp76.js → index-wvbg9m0h.js} +3 -3
  56. package/dist/{index-7rgnh11t.js → index-xg1zjht5.js} +5 -5
  57. package/dist/{index-ran2b3fn.js → index-zzhcshdk.js} +72 -64
  58. package/dist/index.js +78 -41
  59. package/dist/{message-index-bounded-wvnp6fcp.js → message-index-bounded-f6fc00ze.js} +4 -4
  60. package/dist/migration-worker.js +2 -2
  61. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  62. package/dist/raw-ordinal-warmup-worker.js +4 -4
  63. package/dist/{read-session-chunk-j4hjc1pk.js → read-session-chunk-y2ew3630.js} +3 -3
  64. package/dist/{recomp-orchestrator-ps1c8c5h.js → recomp-orchestrator-ggtcvb9g.js} +12 -12
  65. package/dist/{render-nfj7280n.js → render-q8c6wrq9.js} +10 -10
  66. package/dist/{search-archive-1etwnve4.js → search-archive-pz1jf655.js} +5 -5
  67. package/dist/{search-3r8b0jfa.js → search-gjyrwapc.js} +8 -8
  68. package/dist/{send-session-notification-gzxz88vq.js → send-session-notification-0779tyd9.js} +2 -2
  69. package/dist/{storage-tags-nh2ftqhx.js → storage-tags-7raphcw6.js} +1 -1
  70. package/dist/{store-reader-a2v34xnh.js → store-reader-qbq6q4v0.js} +1 -1
  71. package/dist/{store-019k3ek7.js → store-yr443ye8.js} +2 -2
  72. package/dist/{transform-postprocess-phase-tqp968w4.js → transform-postprocess-phase-pmzdd3s2.js} +13 -13
  73. package/dist/v2/auto-search-worker.js +1 -1
  74. package/dist/v2/chunk-embedding-write-worker.js +2 -2
  75. package/dist/v2/{context-d57v8c10.js → context-qqbpzk1q.js} +145 -105
  76. package/dist/v2/fold/host-media.d.ts.map +1 -1
  77. package/dist/v2/fold/native-replay.d.ts +1 -0
  78. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  79. package/dist/v2/fold/restore.d.ts +15 -0
  80. package/dist/v2/fold/restore.d.ts.map +1 -1
  81. package/dist/v2/hidden-child-native.d.ts.map +1 -1
  82. package/dist/v2/hidden-run-holder.d.ts +4 -4
  83. package/dist/v2/hooks/overflow-recovery.d.ts +6 -0
  84. package/dist/v2/hooks/overflow-recovery.d.ts.map +1 -1
  85. package/dist/v2/{message-index-bounded-2nhbwry6.js → message-index-bounded-70g28hyg.js} +4 -4
  86. package/dist/v2/migration-worker.js +2 -2
  87. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  88. package/dist/v2/{read-session-chunk-jrrhwxgx.js → read-session-chunk-9rf0n9e6.js} +3 -3
  89. package/dist/v2/{recomp-orchestrator-n79hdd7n.js → recomp-orchestrator-cwghhjc9.js} +11 -11
  90. package/dist/v2/{render-7emcjdt1.js → render-e852zmxz.js} +10 -10
  91. package/dist/v2/{search-archive-fpjbmxcx.js → search-archive-tmn6b5w8.js} +5 -5
  92. package/dist/v2/{search-vz2cpgr0.js → search-jd3vczhn.js} +7 -7
  93. package/dist/v2/{send-session-notification-zazaxxpf.js → send-session-notification-v69y04f5.js} +2 -2
  94. package/dist/v2/{server-r4816kwv.js → server-6t3asmx8.js} +4 -4
  95. package/dist/v2/{server-4axv6kq6.js → server-7x5a46hf.js} +1371 -1306
  96. package/dist/v2/{server-4bfk1sky.js → server-9011eteb.js} +2 -2
  97. package/dist/v2/{server-vfa7byfa.js → server-bvr9xs8h.js} +5 -5
  98. package/dist/v2/{server-q104czn6.js → server-d4trxrj3.js} +89 -24
  99. package/dist/v2/{server-n431vzn5.js → server-fj3pekz2.js} +2 -2
  100. package/dist/v2/{server-6250cxzs.js → server-gs2251jr.js} +1 -1
  101. package/dist/v2/{server-8r32etq0.js → server-jkj1dq6j.js} +27 -3
  102. package/dist/v2/{server-3z8rhacq.js → server-js2v309w.js} +4 -4
  103. package/dist/v2/{server-kwsqytwj.js → server-mgxqfprb.js} +1 -1
  104. package/dist/v2/{server-q2ap5cty.js → server-p4g021y5.js} +3 -3
  105. package/dist/v2/{server-0h875f56.js → server-rkj44mez.js} +76 -6
  106. package/dist/v2/{server-j9cm1czj.js → server-vtgeyhq6.js} +11 -0
  107. package/dist/v2/{server-xmgvy3cq.js → server-x69fqsvz.js} +1 -1
  108. package/dist/v2/{server-hgfd6c3e.js → server-ysjjcatk.js} +2 -2
  109. package/dist/v2/server.js +2 -2
  110. package/dist/v2/{storage-tags-t0f9njdp.js → storage-tags-wgsemtw1.js} +1 -1
  111. package/dist/v2/{store-q3ef5rvz.js → store-enef5jcn.js} +2 -2
  112. package/dist/v2/{store-reader-wc01y2rc.js → store-reader-jbaqv1yp.js} +1 -1
  113. package/dist/v2/store-reader.d.ts +16 -0
  114. package/dist/v2/store-reader.d.ts.map +1 -1
  115. package/dist/v2/{v2-archive-reader-9p84yzk5.js → v2-archive-reader-dm1aeqk2.js} +1 -1
  116. package/dist/v2/{wrapup-orchestrator-acebazx8.js → wrapup-orchestrator-cke368np.js} +11 -11
  117. package/dist/{v2-archive-reader-w1bbaqe8.js → v2-archive-reader-39ye0d3b.js} +1 -1
  118. package/dist/{wrapup-orchestrator-fwbe0mvm.js → wrapup-orchestrator-ggnk0r4r.js} +13 -13
  119. package/package.json +1 -1
  120. package/src/shared/models-dev-cache.test.ts +15 -0
  121. /package/dist/v2/{server-3ap5dmhc.js → server-5hwf5c7r.js} +0 -0
@@ -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,7 +102,7 @@ import {
101
102
  foldShrunkPartTags2,
102
103
  getTagNumberByMessageId2,
103
104
  getActiveTagsBySession2
104
- } from "./server-q104czn6.js";
105
+ } from "./server-d4trxrj3.js";
105
106
  import {
106
107
  hasMeaningfulUserText2,
107
108
  estimateTokens,
@@ -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-4bfk1sky.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-kwsqytwj.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-r4816kwv.js";
214
+ } from "./server-6t3asmx8.js";
214
215
  import {
215
216
  invalidateAutoEmbedSession
216
217
  } from "./server-2amn2s73.js";
@@ -270,7 +271,7 @@ import {
270
271
  LATEST_SUPPORTED_VERSION,
271
272
  getPersistedSchemaVersion,
272
273
  openDatabase
273
- } from "./server-n431vzn5.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-8r32etq0.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-xmgvy3cq.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,7 +2747,7 @@ 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 ?? "");
@@ -5707,6 +5708,10 @@ Facts capture stable properties of the project that survive past any single comp
5707
5708
  - One fact bullet = exactly one rule/default/constraint/decision/name.
5708
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.
5709
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
+
5710
5715
  ### The 5 categories
5711
5716
 
5712
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.
@@ -6022,19 +6027,19 @@ Closing tags must match their opening tier tag (e.g. \`<p1>...</p1>\`, never \`<
6022
6027
  </compartments>
6023
6028
  <facts>
6024
6029
  <PROJECT_RULES>
6025
- * Fact text
6030
+ * [at_compartment=N] Fact text
6026
6031
  </PROJECT_RULES>
6027
6032
  <ARCHITECTURE>
6028
- * Fact text
6033
+ * [at_compartment=N] Fact text
6029
6034
  </ARCHITECTURE>
6030
6035
  <CONSTRAINTS>
6031
- * Fact text
6036
+ * [at_compartment=N] Fact text
6032
6037
  </CONSTRAINTS>
6033
6038
  <CONFIG_VALUES>
6034
- * Fact text
6039
+ * [at_compartment=N] Fact text
6035
6040
  </CONFIG_VALUES>
6036
6041
  <NAMING>
6037
- * Fact text
6042
+ * [at_compartment=N] Fact text
6038
6043
  </NAMING>
6039
6044
  </facts>
6040
6045
  <events>
@@ -6430,6 +6435,9 @@ function mapParsedCompartmentsToChunk(compartments, chunk, sequenceOffset) {
6430
6435
  }
6431
6436
 
6432
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
+ }
6433
6441
  function startHistorianPublishStage(sessionId, stage, extra) {
6434
6442
  const suffix = extra ? ` ${extra}` : "";
6435
6443
  sessionLog2(sessionId, `historian publish stage: stage=${stage} status=started elapsed=0.0ms${suffix}`);
@@ -6489,6 +6497,9 @@ function shouldDiscardLastHistorianCompartment(compartments, chunk) {
6489
6497
  const lookaheadMargin = chunk.endIndex - last.endMessage;
6490
6498
  return lookaheadMargin <= HISTORIAN_BOUNDARY_HEALING_SLACK && !boundarySplitsCompletedToolArc(previous.endMessage + 1, chunk.completedToolArcs);
6491
6499
  }
6500
+ function retainAnchoredHistorianFacts(facts, trustedCount) {
6501
+ return facts.filter(({ originCompartmentIndex }) => originCompartmentIndex !== undefined && originCompartmentIndex >= 1 && originCompartmentIndex <= trustedCount);
6502
+ }
6492
6503
  function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, sequenceOffset) {
6493
6504
  const parseStarted = startHistorianPublishStage(sessionId, "parse", `response_chars=${text.length}`);
6494
6505
  const parsed = parseCompartmentOutput(text);
@@ -10771,21 +10782,21 @@ Acorn Suite made JWT tenant_id the single tenant authority across REST, GraphQL,
10771
10782
  </compartment>
10772
10783
  <facts>
10773
10784
  <PROJECT_RULES>
10774
- * 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.
10775
- * 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.
10776
10787
  </PROJECT_RULES>
10777
10788
  <ARCHITECTURE>
10778
- * Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
10779
- * 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.
10780
10791
  </ARCHITECTURE>
10781
10792
  <CONSTRAINTS>
10782
- * 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.
10783
10794
  </CONSTRAINTS>
10784
10795
  <CONFIG_VALUES>
10785
- * 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.
10786
10797
  </CONFIG_VALUES>
10787
10798
  <NAMING>
10788
- * 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.
10789
10800
  </NAMING>
10790
10801
  </facts>
10791
10802
  <events>
@@ -10832,19 +10843,19 @@ OpLog; SnapshotCache; vector_clock; max_ops_before_compact=10000; crates/chorus-
10832
10843
  </compartment>
10833
10844
  <facts>
10834
10845
  <ARCHITECTURE>
10835
- * 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.
10836
10847
  </ARCHITECTURE>
10837
10848
  <CONSTRAINTS>
10838
- * 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).
10839
10850
  </CONSTRAINTS>
10840
10851
  <PROJECT_RULES>
10841
- * 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.
10842
10853
  </PROJECT_RULES>
10843
10854
  <NAMING>
10844
- * 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).
10845
10856
  </NAMING>
10846
10857
  <CONFIG_VALUES>
10847
- * Chorus compaction threshold: max_ops_before_compact=10000 per document.
10858
+ * [at_compartment=7] Chorus compaction threshold: max_ops_before_compact=10000 per document.
10848
10859
  </CONFIG_VALUES>
10849
10860
  </facts>
10850
10861
  <events>
@@ -10887,28 +10898,28 @@ The durable decision was to allow standby replicas to do read-heavy reconcile wo
10887
10898
  </compartment>
10888
10899
  <facts>
10889
10900
  <PROJECT_RULES>
10890
- * Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
10891
- * 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.
10892
10903
  </PROJECT_RULES>
10893
10904
  <ARCHITECTURE>
10894
- * The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
10895
- * 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.
10896
10907
  </ARCHITECTURE>
10897
10908
  <CONSTRAINTS>
10898
- * 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.
10899
10910
  </CONSTRAINTS>
10900
10911
  <CONFIG_VALUES>
10901
- * Leader election lease name: workspacemesh-controller-lock.
10902
- * 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.
10903
10914
  </CONFIG_VALUES>
10904
10915
  <NAMING>
10905
- * The controller write gate wrapper is named LeaseGuard.
10916
+ * [at_compartment=1] The controller write gate wrapper is named LeaseGuard.
10906
10917
  </NAMING>
10907
10918
  </facts>`
10908
10919
  },
10909
10920
  {
10910
10921
  importance: 94,
10911
- 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>'
10912
10923
  },
10913
10924
  {
10914
10925
  importance: 92,
@@ -10936,22 +10947,22 @@ Tenant authorization now flows from membership state rather than browser-selecte
10936
10947
  </compartment>
10937
10948
  <facts>
10938
10949
  <PROJECT_RULES>
10939
- * New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
10940
- * 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.
10941
10952
  </PROJECT_RULES>
10942
10953
  <ARCHITECTURE>
10943
- * 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.
10944
- * 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.
10945
10956
  </ARCHITECTURE>
10946
10957
  <CONSTRAINTS>
10947
- * 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.
10948
10959
  </CONSTRAINTS>
10949
10960
  <CONFIG_VALUES>
10950
- * Internal tenant hop header: x-ledgerleaf-tenant-id.
10951
- * 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.
10952
10963
  </CONFIG_VALUES>
10953
10964
  <NAMING>
10954
- * 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.
10955
10966
  </NAMING>
10956
10967
  </facts>
10957
10968
  <user_observations>
@@ -10986,16 +10997,16 @@ internal/leaderelection/release.go shim removed; PreStop hook; lease 30s / retry
10986
10997
  </compartment>
10987
10998
  <facts>
10988
10999
  <PROJECT_RULES>
10989
- * 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.
10990
11001
  </PROJECT_RULES>
10991
11002
  <ARCHITECTURE>
10992
- * 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.
10993
11004
  </ARCHITECTURE>
10994
11005
  <CONSTRAINTS>
10995
- * 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.
10996
11007
  </CONSTRAINTS>
10997
11008
  <CONFIG_VALUES>
10998
- * 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.
10999
11010
  </CONFIG_VALUES>
11000
11011
  </facts>
11001
11012
  <events>
@@ -11037,19 +11048,19 @@ run_id; pipeline_run; IntegrityError; idempotent retry; {pipeline_name}_{YYYYMMD
11037
11048
  </compartment>
11038
11049
  <facts>
11039
11050
  <ARCHITECTURE>
11040
- * 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.
11041
11052
  </ARCHITECTURE>
11042
11053
  <PROJECT_RULES>
11043
- * 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.
11044
11055
  </PROJECT_RULES>
11045
11056
  <CONSTRAINTS>
11046
- * 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.
11047
11058
  </CONSTRAINTS>
11048
11059
  <NAMING>
11049
- * 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).
11050
11061
  </NAMING>
11051
11062
  <CONFIG_VALUES>
11052
- * 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).
11053
11064
  </CONFIG_VALUES>
11054
11065
  </facts>`
11055
11066
  },
@@ -11073,20 +11084,20 @@ Harborlight sharding is namespace-scoped: one operator binary can run cluster-wi
11073
11084
  </compartment>
11074
11085
  <facts>
11075
11086
  <PROJECT_RULES>
11076
- * 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.
11077
11088
  </PROJECT_RULES>
11078
11089
  <ARCHITECTURE>
11079
- * Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
11080
- * 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.
11081
11092
  </ARCHITECTURE>
11082
11093
  <CONSTRAINTS>
11083
- * 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.
11084
11095
  </CONSTRAINTS>
11085
11096
  <CONFIG_VALUES>
11086
- * 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.
11087
11098
  </CONFIG_VALUES>
11088
11099
  <NAMING>
11089
- * 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.
11090
11101
  </NAMING>
11091
11102
  </facts>
11092
11103
  <events>
@@ -11121,13 +11132,13 @@ CAN RX no longer allocates or sends BLE notifications inside the ISR; frames are
11121
11132
  </compartment>
11122
11133
  <facts>
11123
11134
  <PROJECT_RULES>
11124
- * 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.
11125
11136
  </PROJECT_RULES>
11126
11137
  <CONSTRAINTS>
11127
- * 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.
11128
11139
  </CONSTRAINTS>
11129
11140
  <CONFIG_VALUES>
11130
- * 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.
11131
11142
  </CONFIG_VALUES>
11132
11143
  </facts>
11133
11144
  <events>
@@ -11164,10 +11175,10 @@ unscale_ → clip_grad_norm_ → step
11164
11175
  </compartment>
11165
11176
  <facts>
11166
11177
  <CONSTRAINTS>
11167
- * \`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.
11168
11179
  </CONSTRAINTS>
11169
11180
  <ARCHITECTURE>
11170
- * 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.
11171
11182
  </ARCHITECTURE>
11172
11183
  </facts>
11173
11184
  <events>
@@ -11206,13 +11217,13 @@ LoomDoc wraps Y.Doc; HLC (physical_ms, logical, node_id); skew cap 300s
11206
11217
  </compartment>
11207
11218
  <facts>
11208
11219
  <ARCHITECTURE>
11209
- * 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.
11210
11221
  </ARCHITECTURE>
11211
11222
  <CONSTRAINTS>
11212
- * 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.
11213
11224
  </CONSTRAINTS>
11214
11225
  <NAMING>
11215
- * 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\`.
11216
11227
  </NAMING>
11217
11228
  </facts>`
11218
11229
  },
@@ -11236,21 +11247,21 @@ Billetto made proration credits auditable by storing them in its own ledger tabl
11236
11247
  </compartment>
11237
11248
  <facts>
11238
11249
  <PROJECT_RULES>
11239
- * 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/.
11240
11251
  </PROJECT_RULES>
11241
11252
  <ARCHITECTURE>
11242
- * Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
11243
- * 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.
11244
11255
  </ARCHITECTURE>
11245
11256
  <CONSTRAINTS>
11246
- * 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.
11247
11258
  </CONSTRAINTS>
11248
11259
  <CONFIG_VALUES>
11249
- * Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
11250
- * 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}.
11251
11262
  </CONFIG_VALUES>
11252
11263
  <NAMING>
11253
- * 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.
11254
11265
  </NAMING>
11255
11266
  </facts>`
11256
11267
  },
@@ -11272,10 +11283,10 @@ Nereid contrastive training stabilized after restoring per-worker augmentation s
11272
11283
  </compartment>
11273
11284
  <facts>
11274
11285
  <CONSTRAINTS>
11275
- * 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.
11276
11287
  </CONSTRAINTS>
11277
11288
  <CONFIG_VALUES>
11278
- * 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.
11279
11290
  </CONFIG_VALUES>
11280
11291
  </facts>
11281
11292
  <events>
@@ -11314,19 +11325,19 @@ billing.stripe_event_idempotency; key = event.id; TTL 90d
11314
11325
  </compartment>
11315
11326
  <facts>
11316
11327
  <PROJECT_RULES>
11317
- * 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.
11318
11329
  </PROJECT_RULES>
11319
11330
  <CONSTRAINTS>
11320
- * 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.
11321
11332
  </CONSTRAINTS>
11322
11333
  <ARCHITECTURE>
11323
- * 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.
11324
11335
  </ARCHITECTURE>
11325
11336
  <CONFIG_VALUES>
11326
- * \`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\`.
11327
11338
  </CONFIG_VALUES>
11328
11339
  <NAMING>
11329
- * 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\`.
11330
11341
  </NAMING>
11331
11342
  </facts>
11332
11343
  <events>
@@ -11369,13 +11380,13 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
11369
11380
  </compartment>
11370
11381
  <facts>
11371
11382
  <CONSTRAINTS>
11372
- * 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).
11373
11384
  </CONSTRAINTS>
11374
11385
  <PROJECT_RULES>
11375
- * 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.
11376
11387
  </PROJECT_RULES>
11377
11388
  <CONFIG_VALUES>
11378
- * 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.
11379
11390
  </CONFIG_VALUES>
11380
11391
  </facts>
11381
11392
  <events>
@@ -11395,7 +11406,7 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
11395
11406
  },
11396
11407
  {
11397
11408
  importance: 74,
11398
- 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>'
11399
11410
  },
11400
11411
  {
11401
11412
  importance: 74,
@@ -11415,16 +11426,16 @@ Partition membership changes now fence planner statistics through partition_epoc
11415
11426
  </compartment>
11416
11427
  <facts>
11417
11428
  <PROJECT_RULES>
11418
- * 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.
11419
11430
  </PROJECT_RULES>
11420
11431
  <ARCHITECTURE>
11421
- * 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.
11422
11433
  </ARCHITECTURE>
11423
11434
  <CONSTRAINTS>
11424
- * 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.
11425
11436
  </CONSTRAINTS>
11426
11437
  <CONFIG_VALUES>
11427
- * New planner cache key field: partition_epoch.
11438
+ * [at_compartment=13] New planner cache key field: partition_epoch.
11428
11439
  </CONFIG_VALUES>
11429
11440
  </facts>
11430
11441
  <events>
@@ -11459,13 +11470,13 @@ CollabPad CRDT ordering now follows document clocks rather than server receive t
11459
11470
  </compartment>
11460
11471
  <facts>
11461
11472
  <ARCHITECTURE>
11462
- * 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.
11463
11474
  </ARCHITECTURE>
11464
11475
  <CONSTRAINTS>
11465
- * 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.
11466
11477
  </CONSTRAINTS>
11467
11478
  <NAMING>
11468
- * 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.
11469
11480
  </NAMING>
11470
11481
  </facts>
11471
11482
  <events>
@@ -11502,10 +11513,10 @@ bond_table partition 0x7E000–0x7FFFF; pm_static.yml
11502
11513
  </compartment>
11503
11514
  <facts>
11504
11515
  <CONSTRAINTS>
11505
- * 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\`.
11506
11517
  </CONSTRAINTS>
11507
11518
  <CONFIG_VALUES>
11508
- * \`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.
11509
11520
  </CONFIG_VALUES>
11510
11521
  </facts>
11511
11522
  <events>
@@ -11542,10 +11553,10 @@ leader election; Lease resource; VESPER_LEASE_DURATION_S; VESPER_RENEW_INTERVAL_
11542
11553
  </compartment>
11543
11554
  <facts>
11544
11555
  <ARCHITECTURE>
11545
- * 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.
11546
11557
  </ARCHITECTURE>
11547
11558
  <CONFIG_VALUES>
11548
- * 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).
11549
11560
  </CONFIG_VALUES>
11550
11561
  </facts>`
11551
11562
  },
@@ -11577,13 +11588,13 @@ onPreInstall; onPostInstall; onRemove; schema_version; dependency-declaration or
11577
11588
  </compartment>
11578
11589
  <facts>
11579
11590
  <ARCHITECTURE>
11580
- * 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.
11581
11592
  </ARCHITECTURE>
11582
11593
  <NAMING>
11583
- * 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).
11584
11595
  </NAMING>
11585
11596
  <PROJECT_RULES>
11586
- * 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.
11587
11598
  </PROJECT_RULES>
11588
11599
  </facts>
11589
11600
  <events>
@@ -11615,16 +11626,16 @@ Subscription MRR history moved into a daily fact table instead of being reconstr
11615
11626
  </compartment>
11616
11627
  <facts>
11617
11628
  <PROJECT_RULES>
11618
- * 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.
11619
11630
  </PROJECT_RULES>
11620
11631
  <ARCHITECTURE>
11621
- * 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.
11622
11633
  </ARCHITECTURE>
11623
11634
  <CONFIG_VALUES>
11624
- * 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.
11625
11636
  </CONFIG_VALUES>
11626
11637
  <NAMING>
11627
- * The subscription daily snapshot model is named fct_subscription_day.
11638
+ * [at_compartment=1] The subscription daily snapshot model is named fct_subscription_day.
11628
11639
  </NAMING>
11629
11640
  </facts>`
11630
11641
  },
@@ -11652,10 +11663,10 @@ bucket width 50; K=24; asymmetric expansion down-only first 60s
11652
11663
  </compartment>
11653
11664
  <facts>
11654
11665
  <CONFIG_VALUES>
11655
- * 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.
11656
11667
  </CONFIG_VALUES>
11657
11668
  <ARCHITECTURE>
11658
- * 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.
11659
11670
  </ARCHITECTURE>
11660
11671
  </facts>
11661
11672
  <user_observations>
@@ -11678,7 +11689,7 @@ PDF page rotation is captured before OCR rasterization so Tesseract sees the cor
11678
11689
  </compartment>
11679
11690
  <facts>
11680
11691
  <CONSTRAINTS>
11681
- * 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.
11682
11693
  </CONSTRAINTS>
11683
11694
  </facts>
11684
11695
  <events>
@@ -11709,13 +11720,13 @@ Synonym edits are now shipped by building and promoting a shadow index, not by r
11709
11720
  </compartment>
11710
11721
  <facts>
11711
11722
  <PROJECT_RULES>
11712
- * 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.
11713
11724
  </PROJECT_RULES>
11714
11725
  <ARCHITECTURE>
11715
- * 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.
11716
11727
  </ARCHITECTURE>
11717
11728
  <NAMING>
11718
- * The paired search aliases are products_live and products_next.
11729
+ * [at_compartment=1] The paired search aliases are products_live and products_next.
11719
11730
  </NAMING>
11720
11731
  </facts>`
11721
11732
  },
@@ -11737,16 +11748,16 @@ Ranked duo matchmaking now preserves parties even when it increases queue time.
11737
11748
  </compartment>
11738
11749
  <facts>
11739
11750
  <PROJECT_RULES>
11740
- * 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.
11741
11752
  </PROJECT_RULES>
11742
11753
  <CONFIG_VALUES>
11743
- * 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.
11744
11755
  </CONFIG_VALUES>
11745
11756
  </facts>`
11746
11757
  },
11747
11758
  {
11748
11759
  importance: 52,
11749
- 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>'
11750
11761
  },
11751
11762
  {
11752
11763
  importance: 48,
@@ -11785,10 +11796,10 @@ tesseract=5.3.3; docker/ocr/Dockerfile; upstream #4117
11785
11796
  </compartment>
11786
11797
  <facts>
11787
11798
  <CONFIG_VALUES>
11788
- * \`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.
11789
11800
  </CONFIG_VALUES>
11790
11801
  <CONSTRAINTS>
11791
- * 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.
11792
11803
  </CONSTRAINTS>
11793
11804
  </facts>
11794
11805
  <events>
@@ -11821,10 +11832,10 @@ Snapbench recording examples became runnable instead of descriptive only.
11821
11832
  </compartment>
11822
11833
  <facts>
11823
11834
  <CONFIG_VALUES>
11824
- * Snapbench's default snapshot directory is .snapbench/.
11835
+ * [at_compartment=1] Snapbench's default snapshot directory is .snapbench/.
11825
11836
  </CONFIG_VALUES>
11826
11837
  <NAMING>
11827
- * The Snapbench capture subcommand is named snapbench record.
11838
+ * [at_compartment=1] The Snapbench capture subcommand is named snapbench record.
11828
11839
  </NAMING>
11829
11840
  </facts>
11830
11841
  <user_observations>
@@ -11857,7 +11868,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
11857
11868
  </compartment>
11858
11869
  <facts>
11859
11870
  <CONSTRAINTS>
11860
- * 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.
11861
11872
  </CONSTRAINTS>
11862
11873
  </facts>
11863
11874
  <events>
@@ -11874,7 +11885,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
11874
11885
  },
11875
11886
  {
11876
11887
  importance: 36,
11877
- 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>'
11878
11889
  },
11879
11890
  {
11880
11891
  importance: 36,
@@ -11909,7 +11920,7 @@ Polaris; data/preprocessed/; preprocessor.py; polaris.preprocess; preprocess.yam
11909
11920
  </compartment>
11910
11921
  <facts>
11911
11922
  <CONFIG_VALUES>
11912
- * 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.
11913
11924
  </CONFIG_VALUES>
11914
11925
  </facts>`
11915
11926
  },
@@ -11932,10 +11943,10 @@ The SKU importer now defaults to a safe preview workflow instead of assuming liv
11932
11943
  </compartment>
11933
11944
  <facts>
11934
11945
  <PROJECT_RULES>
11935
- * 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.
11936
11947
  </PROJECT_RULES>
11937
11948
  <CONFIG_VALUES>
11938
- * 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.
11939
11950
  </CONFIG_VALUES>
11940
11951
  </facts>
11941
11952
  <events>
@@ -11968,7 +11979,7 @@ Invalid IoT telemetry is retained in a DLQ instead of silently disappearing.
11968
11979
  </compartment>
11969
11980
  <facts>
11970
11981
  <CONFIG_VALUES>
11971
- * 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.
11972
11983
  </CONFIG_VALUES>
11973
11984
  </facts>`
11974
11985
  },
@@ -11990,7 +12001,7 @@ Mobile offline sync shipped with a narrow notes-only scope.
11990
12001
  </compartment>
11991
12002
  <facts>
11992
12003
  <CONFIG_VALUES>
11993
- * 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.
11994
12005
  </CONFIG_VALUES>
11995
12006
  </facts>`
11996
12007
  },
@@ -12016,10 +12027,10 @@ Low-confidence scan rotation is now handled through a manual override path, with
12016
12027
  </compartment>
12017
12028
  <facts>
12018
12029
  <CONSTRAINTS>
12019
- * 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.
12020
12031
  </CONSTRAINTS>
12021
12032
  <CONFIG_VALUES>
12022
- * Automatic rotation threshold: angle_confidence 0.98 or higher.
12033
+ * [at_compartment=19] Automatic rotation threshold: angle_confidence 0.98 or higher.
12023
12034
  </CONFIG_VALUES>
12024
12035
  </facts>
12025
12036
  <events>
@@ -12093,7 +12104,7 @@ This was a scoped replay, not a lasting data-model change: the useful outcome wa
12093
12104
  </compartment>
12094
12105
  <facts>
12095
12106
  <CONFIG_VALUES>
12096
- * 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.
12097
12108
  </CONFIG_VALUES>
12098
12109
  </facts>
12099
12110
  <events>
@@ -12138,13 +12149,13 @@ README install path fixed for Apple Silicon.
12138
12149
  </compartment>
12139
12150
  <facts>
12140
12151
  <NAMING>
12141
- * 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\`.
12142
12153
  </NAMING>
12143
12154
  </facts>`
12144
12155
  },
12145
12156
  {
12146
12157
  importance: 17,
12147
- 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>'
12148
12159
  },
12149
12160
  {
12150
12161
  importance: 14,
@@ -12186,7 +12197,7 @@ kind; ci/kind-config.yaml; kindest/node:v1.29.2; integration.yml
12186
12197
  </compartment>
12187
12198
  <facts>
12188
12199
  <CONFIG_VALUES>
12189
- * 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.
12190
12201
  </CONFIG_VALUES>
12191
12202
  </facts>`
12192
12203
  },
@@ -12243,7 +12254,7 @@ False start: attempted-and-reverted controller-runtime cache bypass.
12243
12254
  </compartment>
12244
12255
  <facts>
12245
12256
  <CONSTRAINTS>
12246
- * 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.
12247
12258
  </CONSTRAINTS>
12248
12259
  </facts>
12249
12260
  <events>
@@ -12368,7 +12379,7 @@ Captured high-load CAN bus limitation in firmware docs.
12368
12379
  </compartment>
12369
12380
  <facts>
12370
12381
  <CONSTRAINTS>
12371
- * 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.
12372
12383
  </CONSTRAINTS>
12373
12384
  </facts>`
12374
12385
  },
@@ -12418,7 +12429,7 @@ Docs examples section was renamed.
12418
12429
  </compartment>
12419
12430
  <facts>
12420
12431
  <NAMING>
12421
- * 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".
12422
12433
  </NAMING>
12423
12434
  </facts>`
12424
12435
  }
@@ -13423,761 +13434,552 @@ function sanitizeDumpName(value) {
13423
13434
  return value.replace(/[^a-zA-Z0-9._-]/g, "-");
13424
13435
  }
13425
13436
 
13426
- // src/hooks/magic-context/historian-failure-report.ts
13427
- var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
13428
- var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
13429
- 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.";
13430
- var REFUSAL_ERROR_MAX_CHARS = 500;
13431
- var WARNING_ERROR_MAX_CHARS = 200;
13432
- function readHistorianFailureStreak(db, sessionId, options = {}) {
13433
- const state = getHistorianFailureState(db, sessionId);
13434
- const count = state.failureCount;
13435
- let since = null;
13436
- if (count > 0) {
13437
- const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
13438
- if (recorded <= 0) {
13439
- since = state.lastFailureAt;
13440
- } else {
13441
- const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
13442
- since = times.length === recorded ? times[recorded - 1] ?? null : null;
13443
- }
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);
13444
13444
  }
13445
- 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;
13446
13460
  }
13447
- function formatHistorianClockTime(at, now = Date.now()) {
13448
- const date = new Date(at);
13449
- const pad = (value) => String(value).padStart(2, "0");
13450
- const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
13451
- const today = new Date(now);
13452
- const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
13453
- 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 })}`;
13454
13465
  }
13455
- function formatHistorianSeconds(ms) {
13456
- const seconds = Math.max(0, ms) / 1000;
13457
- 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
+ };
13458
13472
  }
13459
- function singleLine(text) {
13460
- 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));
13461
13490
  }
13462
- function quoteError(error, maxChars) {
13463
- const text = sanitizeDiagnosticText(singleLine(error));
13464
- 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)));
13465
13493
  }
13466
- function endSentence(text) {
13467
- 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 };
13468
13508
  }
13469
- function usageClause(usagePercentage) {
13470
- 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)));
13471
13511
  }
13472
- function capitalize(text) {
13473
- 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)));
13474
13514
  }
13475
- function chunkLabel(chunk) {
13476
- 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)));
13477
13517
  }
13478
- function streakSentence(failures, now) {
13479
- 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)
13480
13528
  return null;
13481
- const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
13482
- return `Summary runs failed in a row: ${failures.count}${since}.`;
13529
+ return index.messageIdAtOrdinal(ordinal);
13483
13530
  }
13484
- function failureBelongsToRun(failures, run) {
13485
- 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;
13486
13538
  }
13487
- function describeHistorianJoinRefusal(input) {
13488
- const now = input.now ?? Date.now();
13489
- const { run, failures } = input;
13490
- const sentences = [
13491
- `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.`
13492
- ];
13493
- const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
13494
- const ownFailure = failureBelongsToRun(failures, run);
13495
- const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
13496
- if (ownFailure) {
13497
- sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
13498
- } else if (run && run.endedAt === undefined) {
13499
- sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
13500
- } else if (run) {
13501
- 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;
13502
13550
  }
13503
- if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
13504
- 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;
13505
13559
  }
13506
- const streak = streakSentence(failures, now);
13507
- if (streak)
13508
- sentences.push(streak);
13509
- sentences.push(ACTIONS);
13510
- return sentences.join(" ");
13511
- }
13512
- function describeRepeatedHistorianFailures(input) {
13513
- const now = input.now ?? Date.now();
13514
- const { failures } = input;
13515
- const facts = [
13516
- streakSentence(failures, now) ?? "Summary runs are failing.",
13517
- ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
13518
- ...failures.lastError ? [
13519
- endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
13520
- ] : [],
13521
- `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
13522
- ];
13523
- return [
13524
- "## Magic Context — History summaries keep failing",
13525
- "",
13526
- facts.join(" "),
13527
- "",
13528
- ACTIONS
13529
- ].join(`
13530
- `);
13560
+ return snapped;
13531
13561
  }
13532
- var repeatedFailureWarnings = new Map;
13533
- function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
13534
- const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
13535
- if (failureCount < step || failureCount % step !== 0)
13536
- return false;
13537
- const last = repeatedFailureWarnings.get(sessionId);
13538
- if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
13539
- 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;
13540
13577
  }
13541
- repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
13542
- return true;
13578
+ return candidate;
13543
13579
  }
13544
- function takeRepeatedHistorianFailureWarning(input) {
13545
- const now = input.now ?? Date.now();
13546
- if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
13547
- return null;
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;
13548
13596
  }
13549
- const failures = readHistorianFailureStreak(input.db, input.sessionId, {
13550
- unrecordedFailures: input.unrecordedFailures
13551
- });
13552
- return describeRepeatedHistorianFailures({
13553
- chunk: input.chunk,
13554
- failures: { ...failures, count: input.failureCount },
13555
- usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
13556
- now
13557
- });
13558
- }
13559
-
13560
- // src/hooks/magic-context/historian-history-wait.ts
13561
- var historyWaits = new Map;
13562
- function newestMessageId(snapshot) {
13563
- try {
13564
- const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
13565
- const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
13566
- const newest = ids.keys().next().value;
13567
- if (newest)
13568
- return newest;
13569
- } catch {}
13570
- return snapshot.rawLastMessageIdAtTrigger;
13571
- }
13572
- function recoveryWindow(snapshot, percentage) {
13573
- return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
13574
- }
13575
- function clearHistorianHistoryWait(sessionId) {
13576
- historyWaits.delete(sessionId);
13597
+ return boundary;
13577
13598
  }
13578
- function recordHistorianNoProgress(snapshot, emergency = false) {
13579
- const newest = newestMessageId(snapshot);
13580
- if (!newest)
13581
- return;
13582
- const previous = historyWaits.get(snapshot.sessionId);
13583
- const sameHistory = previous?.newestMessageId === newest;
13584
- historyWaits.set(snapshot.sessionId, {
13585
- newestMessageId: newest,
13586
- recoveryAttempted: sameHistory && previous.recoveryAttempted || emergency || recoveryWindow(snapshot, snapshot.usagePercentage),
13587
- 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);
13588
13633
  });
13589
- }
13590
- function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
13591
- const wait = historyWaits.get(snapshot.sessionId);
13592
- if (!wait)
13593
- return false;
13594
- const newest = newestMessageId(snapshot);
13595
- if (newest && newest !== wait.newestMessageId) {
13596
- try {
13597
- const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
13598
- if (order === null || order > 0)
13599
- return false;
13600
- } 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;
13601
13641
  }
13602
- const recovery = options.emergency || recoveryWindow(snapshot, options.usagePercentage ?? snapshot.usagePercentage);
13603
- const floorLift = snapshot.liftLivePromptFloor === true;
13604
- if (recovery && !wait.recoveryAttempted || floorLift && !wait.floorLiftAttempted) {
13605
- if (options.claim) {
13606
- wait.recoveryAttempted ||= recovery;
13607
- wait.floorLiftAttempted ||= floorLift;
13608
- }
13609
- 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;
13610
13649
  }
13611
- return true;
13612
- }
13613
-
13614
- // src/tools/ctx-note/render.ts
13615
- var GLANCE_TITLE_MAX = 80;
13616
- var NUDGE_TITLE_MAX = 60;
13617
- var STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
13618
- var EMPTY_READ_REPLY = `## Notes
13619
-
13620
- No session notes or smart notes.`;
13621
- function noteTouchedAt(note) {
13622
- return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
13623
- }
13624
- function formatNoteAge(touchedAt, nowMs) {
13625
- const elapsed = Math.max(0, nowMs - touchedAt);
13626
- const minutes = Math.floor(elapsed / 60000);
13627
- if (minutes < 60)
13628
- return `${minutes}m`;
13629
- const hours = Math.floor(elapsed / 3600000);
13630
- if (hours < 24)
13631
- return `${hours}h`;
13632
- const days = Math.floor(elapsed / 86400000);
13633
- if (days < 7)
13634
- return `${days}d`;
13635
- return `${Math.floor(days / 7)}w`;
13636
- }
13637
- function clipNoteTitle(content, max) {
13638
- const firstLine = (content.split(`
13639
- `, 1)[0] ?? "").trim();
13640
- const characters = [...firstLine];
13641
- if (characters.length <= max)
13642
- return firstLine;
13643
- return `${characters.slice(0, max).join("")}…`;
13644
- }
13645
- function formatGlanceRow(note, nowMs) {
13646
- const touchedAt = noteTouchedAt(note);
13647
- const markers = [];
13648
- if (note.status !== "active")
13649
- markers.push(note.status);
13650
- if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
13651
- 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
+ }
13652
13658
  }
13653
- if (nowMs - touchedAt >= STALE_AFTER_MS)
13654
- markers.push("stale");
13655
- const suffix = markers.length > 0 ? ` · ${markers.join(" · ")}` : "";
13656
- const title = clipNoteTitle(note.content, GLANCE_TITLE_MAX);
13657
- return `#${note.id} · ${formatNoteAge(touchedAt, nowMs)} · ${title}${suffix}`;
13658
- }
13659
- function newestFirst(left, right) {
13660
- return right.updatedAt - left.updatedAt || right.id - left.id;
13661
- }
13662
- function orderGlanceNotes(notes) {
13663
- const ready = notes.filter((note) => note.status === "ready").sort(newestFirst);
13664
- const pending = notes.filter((note) => note.status === "pending").sort(newestFirst);
13665
- const rest = notes.filter((note) => note.status !== "ready" && note.status !== "pending").sort(newestFirst);
13666
- return [...ready, ...pending, ...rest];
13667
- }
13668
- function renderGlance(notes, options) {
13669
- const ordered = orderGlanceNotes(notes);
13670
- const page = ordered.slice(options.offset, options.offset + options.limit);
13671
- if (page.length === 0)
13672
- return EMPTY_READ_REPLY;
13673
- const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
13674
- `);
13675
- const remaining = ordered.length - options.offset - page.length;
13676
- const footer = remaining > 0 ? `
13677
-
13678
- Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
13679
- return `## Notes
13680
-
13681
- ${rows}${footer}`;
13682
- }
13683
- function formatNoteBody(note, nowMs) {
13684
- const touchedAt = noteTouchedAt(note);
13685
- const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
13686
- const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
13687
- if (note.type !== "smart")
13688
- return head;
13689
- const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
13690
- const label = note.status === "ready" ? "Condition met" : "Condition";
13691
- const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
13692
- ${note.readyReason}` : "";
13693
- return `${head}
13694
- ${label}: ${condition}${failure}`;
13695
- }
13696
- function renderNotesById(entries, nowMs) {
13697
- const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
13698
- return `## Notes by ID
13699
-
13700
- ${lines.join(`
13701
-
13702
- `)}`;
13703
- }
13704
- function formatTraySuffix(tray, nowMs) {
13705
- if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
13706
- return "";
13707
- return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
13708
- }
13709
- function formatWriteReply(noteId, tray, nowMs) {
13710
- return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
13711
- }
13712
- function noteNudgePickIndex(sessionId, counter, poolSize) {
13713
- if (poolSize <= 0)
13714
- return 0;
13715
- const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
13716
- let hash = 2166136261;
13717
- for (const byte of bytes) {
13718
- hash ^= byte;
13719
- 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 };
13720
13675
  }
13721
- return hash % poolSize;
13722
- }
13723
- function formatNoteNudge(args) {
13724
- const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
13725
- const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
13726
- const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
13727
- return `${counts}${oldest}${shown}`;
13676
+ return { eligibleEndOrdinal: end, oversizeAtomicUnit };
13728
13677
  }
13729
-
13730
- // src/hooks/magic-context/note-nudger.ts
13731
- var observedUsers = new WeakMap;
13732
- function observeNoteNudgeServe(args) {
13733
- let sessions = observedUsers.get(args.db);
13734
- if (!sessions) {
13735
- sessions = new Map;
13736
- observedUsers.set(args.db, sessions);
13737
- }
13738
- let seen = sessions.get(args.sessionId);
13739
- const warm = seen !== undefined && seen.size > 0;
13740
- if (!seen)
13741
- seen = new Set;
13742
- const firstServe = args.anchorMessageId !== null && !seen.has(args.anchorMessageId);
13743
- for (const id of args.userMessageIds)
13744
- seen.add(id);
13745
- sessions.set(args.sessionId, seen);
13746
- return {
13747
- isFirstServe: warm && args.isLiveTail && firstServe,
13748
- prefixRewriteCoversAnchor: args.anchorMessageId !== null && args.prefixRewriteCoversAnchor
13749
- };
13750
- }
13751
- var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
13752
- var lastDeliveredAt = new Map;
13753
- function isCoolingDown(deliveredAt, now) {
13754
- return now - deliveredAt < NOTE_NUDGE_COOLDOWN_MS;
13755
- }
13756
- function getNoteNudgeDeliveredAt(sessionId) {
13757
- const deliveredAt = lastDeliveredAt.get(sessionId);
13758
- if (deliveredAt === undefined)
13759
- return 0;
13760
- if (!isCoolingDown(deliveredAt, Date.now())) {
13761
- lastDeliveredAt.delete(sessionId);
13762
- return 0;
13763
- }
13764
- return deliveredAt;
13765
- }
13766
- function recordNoteNudgeDeliveryTime(sessionId) {
13767
- const now = Date.now();
13768
- for (const [otherSessionId, deliveredAt] of lastDeliveredAt) {
13769
- if (!isCoolingDown(deliveredAt, now))
13770
- lastDeliveredAt.delete(otherSessionId);
13771
- }
13772
- lastDeliveredAt.set(sessionId, now);
13773
- }
13774
- function onNoteTrigger(db, sessionId, trigger) {
13775
- let transactionStartedAt = 0;
13776
- db.transaction(() => {
13777
- transactionStartedAt = performance.now();
13778
- setPersistedNoteNudgeTrigger(db, sessionId);
13779
- }).immediate();
13780
- logSlowWriteTransaction("note_nudge_trigger", transactionStartedAt);
13781
- sessionLog2(sessionId, `note-nudge: trigger fired (${trigger}), triggerPending=true`);
13782
- }
13783
- function peekNoteNudgeText(db, sessionId, currentUserMessageId, projectIdentity, noteReadStillVisible, eligibility) {
13784
- const state = getPersistedNoteNudge(db, sessionId);
13785
- if (!state.triggerPending)
13786
- return null;
13787
- if (eligibility && !eligibility.isFirstServe && !eligibility.prefixRewriteCoversAnchor) {
13788
- sessionLog2(sessionId, "note-nudge: deferring — user already served or first serve unproven");
13789
- return null;
13790
- }
13791
- if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
13792
- setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
13793
- state.triggerMessageId = currentUserMessageId;
13794
- }
13795
- if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
13796
- sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
13797
- 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
+ };
13798
13740
  }
13799
- const deliveredAt = getNoteNudgeDeliveredAt(sessionId);
13800
- if (deliveredAt > 0) {
13801
- sessionLog2(sessionId, `note-nudge: suppressing — last delivered ${Math.round((Date.now() - deliveredAt) / 1000)}s ago (cooldown ${NOTE_NUDGE_COOLDOWN_MS / 60000}m)`);
13802
- clearNoteNudgeTriggerOnly(db, sessionId);
13803
- 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
+ };
13804
13785
  }
13805
- const notes = getSessionNotes(db, sessionId);
13806
- const readySmartNotes = projectIdentity ? getReadySmartNotes(db, projectIdentity) : [];
13807
- const totalCount = notes.length + readySmartNotes.length;
13808
- if (totalCount === 0) {
13809
- sessionLog2(sessionId, "note-nudge: triggerPending but no notes found, skipping");
13810
- clearNoteNudgeTriggerOnly(db, sessionId);
13811
- 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";
13812
13801
  }
13813
- const lastReadAt = getNoteLastReadAt(db, sessionId);
13814
- if (lastReadAt > 0 && noteReadStillVisible) {
13815
- const mostRecentNoteActivity = maxNoteActivityTime([...notes, ...readySmartNotes]);
13816
- if (mostRecentNoteActivity > 0 && lastReadAt > mostRecentNoteActivity) {
13817
- 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()}`);
13818
- clearNoteNudgeTriggerOnly(db, sessionId);
13819
- 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);
13820
13838
  }
13821
13839
  }
13822
- const failureNotice = notes.find((note) => /^Smart note #\d+ cannot be checked\.\nCondition: /.test(note.content));
13823
- if (failureNotice) {
13824
- const reason = failureNotice.content.split(`
13825
- Reason: `)[1]?.split(`
13826
- `)[0] ?? "check unavailable";
13827
- 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.`;
13828
- }
13829
- const parts = [];
13830
- if (notes.length > 0) {
13831
- parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
13832
- }
13833
- if (readySmartNotes.length > 0) {
13834
- parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
13840
+ livePromptFloor.to = protectedTailStart;
13841
+ if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
13842
+ protectedTailStart = offset;
13835
13843
  }
13836
- sessionLog2(sessionId, `note-nudge: delivering nudge for ${parts.join(" and ")}`);
13837
- return formatNoteNudge({
13838
- readyCount: readySmartNotes.length,
13839
- activeCount: notes.length,
13840
- oldestActiveTouchedAt: oldestTouchedAt(notes),
13841
- shown: pickNudgeNote({ db, sessionId, activeNotes: notes, readySmartNotes }),
13842
- nowMs: Date.now()
13843
- });
13844
- }
13845
- function oldestTouchedAt(notes) {
13846
- return notes.reduce((min, note) => {
13847
- const touchedAt = noteTouchedAt(note);
13848
- return min === null || touchedAt < min ? touchedAt : min;
13849
- }, null);
13850
- }
13851
- function pickNudgeNote(args) {
13852
- const pool = args.readySmartNotes.length > 0 ? [...args.readySmartNotes].sort((left, right) => left.id - right.id) : [...args.activeNotes].sort((left, right) => left.id - right.id);
13853
- if (pool.length === 0)
13854
- return null;
13855
- const counter = getNoteNudgeAnchors(args.db, args.sessionId).length;
13856
- return pool[noteNudgePickIndex(args.sessionId, counter, pool.length)] ?? null;
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
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
+ };
13857
13914
  }
13858
- function maxNoteActivityTime(notes) {
13859
- let max = 0;
13860
- for (const note of notes) {
13861
- if (note.updatedAt > max)
13862
- max = note.updatedAt;
13863
- if (note.readyAt !== null && note.readyAt > max)
13864
- max = note.readyAt;
13865
- }
13866
- 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
+ };
13867
13925
  }
13868
- function markNoteNudgeDelivered(db, sessionId, text, messageId) {
13869
- if (!messageId) {
13870
- clearNoteNudgeTriggerAndCooldown(db, sessionId);
13871
- sessionLog2(sessionId, "note-nudge: marked delivered without anchor");
13872
- return { ok: true, kind: "already-present" };
13873
- }
13874
- const outcome = db.transaction(() => {
13875
- const delivered = deliverNoteNudgeAtomic(db, sessionId, messageId, text);
13876
- const nudgeText = text?.replace(/^\s*<instruction name="deferred_notes">/, "") ?? "";
13877
- const noticeId = nudgeText.match(/^Smart note check unavailable: [\s\S]*Read ctx_note #(\d+) for the condition/);
13878
- if (delivered.ok && noticeId) {
13879
- db.prepare(`UPDATE notes SET status = 'dismissed', updated_at = ?
13880
- WHERE id = ? AND type = 'session' AND session_id = ?
13881
- 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);
13882
13938
  }
13883
- return delivered;
13884
- }).immediate();
13885
- if (outcome.ok) {
13886
- recordNoteNudgeDeliveryTime(sessionId);
13887
- }
13888
- sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
13889
- return outcome;
13890
- }
13891
- function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
13892
- db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
13893
- lastDeliveredAt.delete(sessionId);
13894
- }
13895
- function clearNoteNudgeTriggerOnly(db, sessionId) {
13896
- db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
13897
- }
13898
-
13899
- // src/hooks/magic-context/persist-filtered-noise.ts
13900
- function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
13901
- const rows = chunk.filteredNoiseLines ?? [];
13902
- const start = chunk.startIndex;
13903
- if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
13904
- return false;
13905
- const endId = rows[rows.length - 1].messageId;
13906
- if (!hasRawSessionMessageById2(sessionId, endId)) {
13907
- sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
13908
- return false;
13909
- }
13910
- const saved = db.transaction(() => {
13911
- const prior = getCompartments(db, sessionId);
13912
- const last = prior.at(-1);
13913
- if ((last?.endMessage ?? 0) + 1 !== start)
13914
- return false;
13915
- appendCompartments(db, sessionId, [
13916
- {
13917
- sequence: (last?.sequence ?? -1) + 1,
13918
- startMessage: start,
13919
- endMessage: eligibleEnd - 1,
13920
- startMessageId: rows[0].messageId,
13921
- endMessageId: rows[rows.length - 1].messageId,
13922
- title: "",
13923
- content: "",
13924
- p1: "",
13925
- p2: "",
13926
- p3: "",
13927
- p4: "",
13928
- episodeType: "filtered-noise",
13929
- importance: 1
13930
- }
13931
- ]);
13932
- return true;
13933
- }).immediate();
13934
- if (saved)
13935
- sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
13936
- return saved;
13937
- }
13938
-
13939
- // src/hooks/magic-context/file-token-coverage.ts
13940
- function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
13941
- const filesByMessage = new Map;
13942
- for (const message of messages) {
13943
- const count = message.parts.filter(isFilePart).length;
13944
- if (count > 0 && totals.has(message.id))
13945
- filesByMessage.set(message.id, count);
13946
- }
13947
- if (filesByMessage.size === 0)
13948
- return totals;
13949
- const rows = db.prepare(`
13950
- SELECT o.value AS owner, COUNT(t.id) AS count
13951
- FROM json_each(?) o LEFT JOIN tags t
13952
- ON t.session_id = ? AND t.type = 'file'
13953
- AND t.message_id >= o.value || ':file'
13954
- AND t.message_id < o.value || ':file;'
13955
- GROUP BY o.value
13956
- `).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
13957
- for (const row of rows) {
13958
- if (row.count < (filesByMessage.get(row.owner) ?? 0))
13959
- totals.delete(row.owner);
13939
+ const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
13940
+ meta = seedResult;
13941
+ migrationFloorActive = seedResult.seeded;
13960
13942
  }
13961
- return totals;
13962
- }
13963
-
13964
- // src/hooks/magic-context/protected-tail-boundary.ts
13965
- function describeBoundaryDiagnostics(snapshot) {
13966
- return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
13967
- }
13968
- function boundaryDiagnostics(args) {
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
+ };
13969
13956
  return {
13970
- ...args,
13971
- capTier: args.usagePercentage >= 95 ? "95" : args.usagePercentage >= 80 ? "80" : "normal",
13972
- drainBudget: "not-reserved; does-not-size-cap"
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
13973
13976
  };
13974
13977
  }
13975
- var ALPHA = 0.3;
13976
- var FLOOR_RATIO = 0.08;
13977
- var FLOOR_MIN = 2000;
13978
- var FLOOR_MAX = 12000;
13979
- var ABS_CAP = 96000;
13980
- var MAX_USABLE_RATIO = 0.4;
13981
- var RESERVED_HEADROOM_MIN = 1000;
13982
- var RESERVED_HEADROOM_RATIO = 0.02;
13983
- var NON_EMERGENCY_MAX_CAP = 250000;
13984
- var FORCE80_MAX_CAP = 500000;
13985
- var FORCE95_MAX_CAP = 750000;
13986
- var NORMAL_HYSTERESIS_TOKENS = 256;
13987
- var RECOVERY_NO_HEAD_LIMIT = 2;
13988
- function clampPercentage(value) {
13989
- if (!Number.isFinite(value))
13990
- return 0;
13991
- return Math.max(0, Math.min(100, value));
13992
- }
13993
- function clampOrdinal(value, rawMessageCount) {
13994
- return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
13995
- }
13996
- function deriveProtectedTailTokenTarget(args) {
13997
- const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
13998
- const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
13999
- const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
14000
- const usage = clampPercentage(args.usagePercentage);
14001
- const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
14002
- const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
14003
- const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
14004
- const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
14005
- const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
14006
- const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
14007
- const effectiveFloor = Math.min(floorN, ceilingN);
14008
- const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
14009
- return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
14010
- }
14011
- function nonEmergencyPerRunCap(usable, N) {
14012
- return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
14013
- }
14014
- function force80PerRunCap(usable, N) {
14015
- return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
14016
- }
14017
- function force95PerRunCap(usable, N) {
14018
- return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
14019
- }
14020
- function selectPerRunCap(snapshot) {
14021
- const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
14022
- if (snapshot.usagePercentage >= 95)
14023
- return force95PerRunCap(usable, snapshot.N);
14024
- if (snapshot.usagePercentage >= 80)
14025
- return force80PerRunCap(usable, snapshot.N);
14026
- return nonEmergencyPerRunCap(usable, snapshot.N);
14027
- }
14028
- function boundaryMessageId(index, ordinal) {
14029
- if (ordinal < 1 || ordinal > index.rawMessageCount)
14030
- return null;
14031
- return index.messageIdAtOrdinal(ordinal);
14032
- }
14033
- function isSemanticBoundaryCandidate(messageParts, role) {
14034
- if (role === "user" && hasMeaningfulUserText2(messageParts))
14035
- return true;
14036
- if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
14037
- return true;
14038
- }
14039
- return false;
14040
- }
14041
- function semanticSnapBoundary(args) {
14042
- const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
14043
- let snapped = candidate;
14044
- for (const message of messages) {
14045
- if (message.ordinal > candidate)
14046
- break;
14047
- if (message.ordinal < lastCompartmentEndOrdinal + 1)
14048
- continue;
14049
- if (!isSemanticBoundaryCandidate(message.parts, message.role))
14050
- continue;
14051
- snapped = message.ordinal;
14052
- }
14053
- if (snapped === candidate)
14054
- return candidate;
14055
- const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
14056
- if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
14057
- return candidate;
14058
- const snappedMessage = messages.find((message) => message.ordinal === snapped);
14059
- if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
14060
- return candidate;
14061
- }
14062
- return snapped;
14063
- }
14064
- function snapWrapupBoundaryToUser(args) {
14065
- const { messages, index, candidate, offset, triggerBudget } = args;
14066
- if (candidate <= offset)
14067
- return candidate;
14068
- const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
14069
- for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
14070
- const message = messages.find((m) => m.ordinal === ordinal);
14071
- if (!message)
14072
- continue;
14073
- if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
14074
- continue;
14075
- const extraTokens = index.rangeTokens(ordinal, candidate);
14076
- if (extraTokens <= snapTokenLimit)
14077
- return ordinal;
14078
- return candidate;
14079
- }
14080
- return candidate;
14081
- }
14082
- function fenceWrapupBoundaryForToolArcs(args) {
14083
- let boundary = args.candidate;
14084
- const maxPasses = args.arcs.length + 1;
14085
- for (let pass = 0;pass < maxPasses; pass += 1) {
14086
- let next = boundary;
14087
- for (const arc of args.arcs) {
14088
- if (arc.resOrdinal === null) {
14089
- continue;
14090
- }
14091
- if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
14092
- next = arc.invOrdinal;
14093
- }
14094
- }
14095
- if (next === boundary)
14096
- return boundary;
14097
- boundary = next;
14098
- }
14099
- return boundary;
14100
- }
14101
- function applyHeadCap(args) {
14102
- const {
14103
- index,
14104
- protectedTailStart,
14105
- offset,
14106
- arcs,
14107
- lastCompartmentEndOrdinal,
14108
- capTokens,
14109
- recentOpenArcCutoff
14110
- } = args;
14111
- const diagnostics = {
14112
- offset,
14113
- capEnd: offset,
14114
- capTokenSum: 0,
14115
- completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
14116
- oversizeAdmission: { from: offset, to: offset },
14117
- openArcClamp: { from: offset, to: offset },
14118
- completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
14119
- eligibleEnd: offset
14120
- };
14121
- if (offset >= protectedTailStart) {
14122
- args.observeDiagnostics?.(diagnostics);
14123
- return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
14124
- }
14125
- let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
14126
- diagnostics.capEnd = end;
14127
- diagnostics.capTokenSum = index.rangeTokens(offset, end);
14128
- let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
14129
- let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
14130
- diagnostics.completedFence.arcs = component.map((arc) => ({
14131
- assistant: arc.invocation,
14132
- result: arc.result
14133
- }));
14134
- diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
14135
- });
14136
- diagnostics.completedFence.from = end;
14137
- diagnostics.completedFence.to = completedFence;
14138
- diagnostics.oversizeAdmission.from = completedFence;
14139
- if (completedFence <= offset && end > offset) {
14140
- const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
14141
- if (afterFirstArc <= protectedTailStart)
14142
- completedFence = afterFirstArc;
14143
- }
14144
- diagnostics.oversizeAdmission.to = completedFence;
14145
- if (completedFence > end) {
14146
- end = Math.min(protectedTailStart, completedFence);
14147
- if (index.rangeTokens(offset, end) > capTokens)
14148
- oversizeAtomicUnit = true;
14149
- } else {
14150
- end = completedFence;
14151
- }
14152
- diagnostics.openArcClamp.from = end;
14153
- for (const arc of arcs) {
14154
- const resOrdinal = arc.resOrdinal;
14155
- if (resOrdinal === null) {
14156
- if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
14157
- end = Math.min(end, arc.invOrdinal);
14158
- }
14159
- }
14160
- }
14161
- diagnostics.openArcClamp.to = end;
14162
- diagnostics.completedRefence.from = end;
14163
- end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
14164
- diagnostics.completedRefence.arcs = component.map((arc) => ({
14165
- assistant: arc.invocation,
14166
- result: arc.result
14167
- }));
14168
- diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
14169
- });
14170
- diagnostics.completedRefence.to = end;
14171
- if (end > protectedTailStart)
14172
- end = offset;
14173
- diagnostics.eligibleEnd = end <= offset ? offset : end;
14174
- args.observeDiagnostics?.(diagnostics);
14175
- if (end <= offset && offset < protectedTailStart) {
14176
- return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
14177
- }
14178
- return { eligibleEndOrdinal: end, oversizeAtomicUnit };
13978
+ function resolveOpenCodeProtectedTailBoundary(args) {
13979
+ return resolveProtectedTailBoundary(resolveBoundaryContext(args));
14179
13980
  }
14180
- function resolveProtectedTailBoundary(ctx) {
13981
+ function resolveWrapupProtectedTailBoundary(args) {
13982
+ const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
14181
13983
  const createdAt = ctx.createdAt ?? Date.now();
14182
13984
  const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
14183
13985
  const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
@@ -14191,8 +13993,8 @@ function resolveProtectedTailBoundary(ctx) {
14191
13993
  calibration: ctx.calibration,
14192
13994
  absoluteMessageCount,
14193
13995
  storedTotalForMessage: storedTotals ? (m) => {
14194
- const v = storedTotals.get(m.id);
14195
- return v === undefined ? null : v;
13996
+ const value = storedTotals?.get(m.id);
13997
+ return value === undefined ? null : value;
14196
13998
  } : undefined
14197
13999
  });
14198
14000
  const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
@@ -14204,151 +14006,58 @@ function resolveProtectedTailBoundary(ctx) {
14204
14006
  storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
14205
14007
  });
14206
14008
  const rawMessageCount = index.rawMessageCount;
14009
+ const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
14207
14010
  const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
14208
14011
  const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
14209
- if (rawMessageCount === 0) {
14210
- return {
14211
- sessionId: ctx.sessionId,
14212
- mode: ctx.mode,
14213
- offset,
14214
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14215
- offsetMessageId: null,
14216
- protectedTailStart: 1,
14217
- protectedTailStartMessageId: null,
14218
- eligibleEndOrdinal: 1,
14219
- eligibleEndMessageId: null,
14220
- rawMessageCountAtTrigger: 0,
14221
- rawLastMessageIdAtTrigger: null,
14222
- N: 0,
14223
- usagePercentage,
14224
- usageInputTokens,
14225
- usageSource: ctx.usageSource,
14226
- contextLimit: ctx.contextLimit,
14227
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14228
- triggerBudget: ctx.triggerBudget,
14229
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14230
- migrationFloorActive: ctx.migrationFloorActive,
14231
- emergencyTailScale: ctx.emergencyTailScale,
14232
- recovery: ctx.recovery,
14233
- providerShapeVersion: ctx.providerShapeVersion,
14234
- cacheNamespace: ctx.cacheNamespace,
14235
- createdAt,
14236
- rawRangeFingerprint: "",
14237
- trueRawEligibleTokens: 0,
14238
- summaryRemovedEligibleTokens: 0,
14239
- oversizeAtomicUnit: false,
14240
- boundaryReason: "empty-session"
14241
- };
14242
- }
14243
- if (ctx.mode === "manual-full-recomp") {
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";
14244
14022
  const arcs = buildToolArcs(messages);
14245
- const recompTarget = deriveProtectedTailTokenTarget({
14246
- contextLimit: ctx.contextLimit,
14247
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14248
- usagePercentage: 0,
14249
- triggerBudget: ctx.triggerBudget
14250
- });
14251
- const recentOpenArcCutoff = index.findSuffixStartForTokens(recompTarget.N);
14252
- const firstOpenArc = arcs.find((arc) => arc.resOrdinal === null && arc.invOrdinal >= offset && arc.invOrdinal >= recentOpenArcCutoff);
14253
- const protectedTailStart = firstOpenArc?.invOrdinal ?? rawMessageCount + 1;
14254
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, protectedTailStart);
14255
- return {
14256
- sessionId: ctx.sessionId,
14257
- mode: ctx.mode,
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,
14258
14035
  offset,
14259
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14260
- offsetMessageId: boundaryMessageId(index, offset),
14261
- protectedTailStart,
14262
- protectedTailStartMessageId: null,
14263
- eligibleEndOrdinal: protectedTailStart,
14264
- eligibleEndMessageId: boundaryMessageId(index, protectedTailStart - 1),
14265
- rawMessageCountAtTrigger: rawMessageCount,
14266
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
14267
- N: 0,
14268
- usagePercentage: 0,
14269
- usageInputTokens: 0,
14270
- usageSource: "manual-none",
14271
- contextLimit: ctx.contextLimit,
14272
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14273
- triggerBudget: ctx.triggerBudget,
14274
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14275
- migrationFloorActive: false,
14276
- emergencyTailScale: ctx.emergencyTailScale,
14277
- recovery: ctx.recovery,
14278
- providerShapeVersion: ctx.providerShapeVersion,
14279
- cacheNamespace: ctx.cacheNamespace,
14280
- createdAt,
14281
- rawRangeFingerprint,
14282
- trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
14283
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
14284
- oversizeAtomicUnit: false,
14285
- boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
14286
- };
14036
+ triggerBudget: ctx.triggerBudget
14037
+ });
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;
14287
14049
  }
14050
+ targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
14051
+ targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
14288
14052
  const target = deriveProtectedTailTokenTarget({
14289
14053
  contextLimit: ctx.contextLimit,
14290
14054
  executeThresholdPercentage: ctx.executeThresholdPercentage,
14291
14055
  usagePercentage,
14292
14056
  triggerBudget: ctx.triggerBudget
14293
14057
  });
14294
- const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
14295
- const arcs = buildToolArcs(messages);
14296
- let boundary = index.findSuffixStartForTokens(scaledN);
14297
- const recentOpenArcCutoff = boundary;
14298
- let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
14299
- const tokenAtBoundary = index.tokenForOrdinal(boundary);
14300
- if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
14301
- boundary += 1;
14302
- boundaryReason = "huge-message-exception";
14303
- }
14304
- boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
14305
- const snapped = semanticSnapBoundary({
14306
- messages,
14307
- index,
14308
- candidate: boundary,
14309
- scaledN,
14310
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14311
- });
14312
- if (snapped !== boundary)
14313
- boundaryReason = "semantic-snap";
14314
- boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
14315
- let runtimeFloor = offset;
14316
- if (ctx.migrationFloorActive)
14317
- runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
14318
- let protectedTailStart = Math.max(boundary, runtimeFloor);
14319
- const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
14320
- const livePromptFloor = {
14321
- ordinal: null,
14322
- from: protectedTailStart,
14323
- to: protectedTailStart
14324
- };
14325
- if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
14326
- let lastMeaningfulUserOrdinal = 0;
14327
- for (let i = messages.length - 1;i >= 0; i--) {
14328
- const message = messages[i];
14329
- if (message.role !== "user")
14330
- continue;
14331
- if (!hasMeaningfulUserText2(message.parts))
14332
- continue;
14333
- lastMeaningfulUserOrdinal = message.ordinal;
14334
- break;
14335
- }
14336
- livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
14337
- livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
14338
- if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
14339
- protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
14340
- }
14341
- }
14342
- livePromptFloor.to = protectedTailStart;
14343
- if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
14344
- protectedTailStart = offset;
14345
- }
14346
- protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
14347
- protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
14348
- protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
14349
14058
  const perRunCap = selectPerRunCap({
14350
14059
  usagePercentage,
14351
- N: scaledN,
14060
+ N: target.N,
14352
14061
  contextLimit: ctx.contextLimit,
14353
14062
  executeThresholdPercentage: ctx.executeThresholdPercentage
14354
14063
  });
@@ -14358,29 +14067,28 @@ function resolveProtectedTailBoundary(ctx) {
14358
14067
  headDiagnostics = value;
14359
14068
  },
14360
14069
  index: summaryRemovedIndex,
14361
- protectedTailStart,
14070
+ protectedTailStart: targetProtectedTailStart,
14362
14071
  offset,
14363
- arcs,
14072
+ arcs: buildToolArcs(messages),
14364
14073
  lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
14365
14074
  capTokens: perRunCap,
14366
- recentOpenArcCutoff
14075
+ recentOpenArcCutoff: targetProtectedTailStart
14367
14076
  });
14368
- const servedEndOrdinal = retreatPastHostUnservedRows(messages, head.eligibleEndOrdinal, offset);
14369
- const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
14077
+ const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
14370
14078
  const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
14371
- return {
14079
+ const snapshot = {
14372
14080
  sessionId: ctx.sessionId,
14373
- mode: ctx.mode,
14081
+ mode: "manual-wrapup",
14374
14082
  offset,
14375
14083
  lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14376
14084
  offsetMessageId: boundaryMessageId(index, offset),
14377
- protectedTailStart,
14378
- protectedTailStartMessageId: boundaryMessageId(index, protectedTailStart),
14085
+ protectedTailStart: targetProtectedTailStart,
14086
+ protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
14379
14087
  eligibleEndOrdinal,
14380
14088
  eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
14381
14089
  rawMessageCountAtTrigger: rawMessageCount,
14382
14090
  rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
14383
- N: scaledN,
14091
+ N: keep,
14384
14092
  usagePercentage,
14385
14093
  usageInputTokens,
14386
14094
  usageSource: ctx.usageSource,
@@ -14390,13 +14098,11 @@ function resolveProtectedTailBoundary(ctx) {
14390
14098
  priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14391
14099
  migrationFloorActive: ctx.migrationFloorActive,
14392
14100
  emergencyTailScale: ctx.emergencyTailScale,
14393
- recovery: ctx.recovery,
14394
- liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
14395
14101
  providerShapeVersion: ctx.providerShapeVersion,
14396
14102
  cacheNamespace: ctx.cacheNamespace,
14397
14103
  createdAt,
14398
14104
  rawRangeFingerprint,
14399
- trueRawEligibleTokens: index.rangeTokens(offset, eligibleEndOrdinal),
14105
+ trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
14400
14106
  summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
14401
14107
  oversizeAtomicUnit: head.oversizeAtomicUnit,
14402
14108
  boundaryReason,
@@ -14404,332 +14110,678 @@ function resolveProtectedTailBoundary(ctx) {
14404
14110
  tailTarget: target,
14405
14111
  usable: target.usable,
14406
14112
  usagePercentage,
14407
- N: scaledN,
14113
+ N: target.N,
14408
14114
  triggerBudget: ctx.triggerBudget,
14409
14115
  capTokens: perRunCap,
14410
- sizeWalkStart: recentOpenArcCutoff,
14411
- protectedTailStart,
14412
- livePromptFloor,
14116
+ sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
14117
+ protectedTailStart: targetProtectedTailStart,
14118
+ livePromptFloor: {
14119
+ ordinal: null,
14120
+ from: targetProtectedTailStart,
14121
+ to: targetProtectedTailStart
14122
+ },
14413
14123
  head: headDiagnostics
14414
14124
  })
14415
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)}.`;
14416
14556
  }
14417
- function readLastCompartmentBoundary(db, sessionId) {
14418
- const row = db.prepare(`SELECT COALESCE(MAX(end_message), -1) AS max_end,
14419
- (SELECT end_message_id FROM compartments
14420
- WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
14421
- FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
14422
- const endMessageId = row?.end_message_id;
14423
- return {
14424
- endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
14425
- endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
14426
- };
14557
+ function formatWriteReply(noteId, tray, nowMs) {
14558
+ return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
14427
14559
  }
14428
- function resolveBoundaryContext(args) {
14429
- const lastCompartmentBoundary = readLastCompartmentBoundary(args.db, args.sessionId);
14430
- const lastCompartmentEndOrdinal = lastCompartmentBoundary.endOrdinal;
14431
- const triggerBudget = deriveTriggerBudget2(args.contextLimit, args.executeThresholdPercentage);
14432
- let meta = args.protectedTailMeta ?? loadProtectedTailMeta(args.db, args.sessionId);
14433
- let migrationFloorActive = false;
14434
- if (meta.protectedTailPolicyVersion < 3) {
14435
- let legacyBoundary = 1;
14436
- try {
14437
- legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
14438
- } catch (error) {
14439
- sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
14440
- }
14441
- const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
14442
- meta = seedResult;
14443
- 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;
14444
14568
  }
14445
- const calibration = sessionDecisionCalibration(args.db, args.sessionId);
14446
- const storedTokenTotalsForMessages = (messageIds, messages = []) => {
14447
- try {
14448
- const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
14449
- return {
14450
- totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
14451
- summaryRemovedTotals: weights.summaryRemovedTotals
14452
- };
14453
- } catch (error) {
14454
- sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
14455
- return;
14456
- }
14457
- };
14458
- return {
14459
- sessionId: args.sessionId,
14460
- mode: args.mode,
14461
- contextLimit: args.contextLimit,
14462
- executeThresholdPercentage: args.executeThresholdPercentage,
14463
- triggerBudget,
14464
- usage: args.usage ?? null,
14465
- usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
14466
- lastCompartmentEndOrdinal,
14467
- lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
14468
- priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
14469
- protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
14470
- migrationFloorActive,
14471
- emergencyTailScale: args.emergencyTailScale,
14472
- recovery: args.recovery,
14473
- liftLivePromptFloor: args.liftLivePromptFloor,
14474
- providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
14475
- cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
14476
- storedTokenTotalsForMessages,
14477
- calibration
14478
- };
14569
+ return hash % poolSize;
14479
14570
  }
14480
- function resolveOpenCodeProtectedTailBoundary(args) {
14481
- 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}`;
14482
14576
  }
14483
- function resolveWrapupProtectedTailBoundary(args) {
14484
- const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
14485
- const createdAt = ctx.createdAt ?? Date.now();
14486
- const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
14487
- const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
14488
- const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
14489
- const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
14490
- const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
14491
- const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
14492
- const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
14493
- providerShapeVersion: ctx.providerShapeVersion,
14494
- cacheNamespace: ctx.cacheNamespace,
14495
- calibration: ctx.calibration,
14496
- absoluteMessageCount,
14497
- storedTotalForMessage: storedTotals ? (m) => {
14498
- const value = storedTotals?.get(m.id);
14499
- return value === undefined ? null : value;
14500
- } : undefined
14501
- });
14502
- const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
14503
- providerShapeVersion: ctx.providerShapeVersion,
14504
- cacheNamespace: ctx.cacheNamespace,
14505
- calibration: ctx.calibration,
14506
- absoluteMessageCount,
14507
- measure: "summary-removed",
14508
- storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
14509
- });
14510
- const rawMessageCount = index.rawMessageCount;
14511
- const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
14512
- const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
14513
- const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
14514
- const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
14515
- const keep = Math.max(1, Math.floor(args.messagesToKeep));
14516
- let targetProtectedTailStart = offset;
14517
- let boundaryReason = "manual-wrapup-empty";
14518
- if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
14519
- targetProtectedTailStart = offset;
14520
- boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
14521
- } else {
14522
- targetProtectedTailStart = anchorRawMessageCount - keep + 1;
14523
- boundaryReason = "manual-wrapup-keep-watermark";
14524
- const arcs = buildToolArcs(messages);
14525
- const fenced = fenceWrapupBoundaryForToolArcs({
14526
- candidate: targetProtectedTailStart,
14527
- arcs,
14528
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14529
- });
14530
- if (fenced !== targetProtectedTailStart)
14531
- boundaryReason = "manual-wrapup-tool-arc";
14532
- targetProtectedTailStart = fenced;
14533
- const snapped = snapWrapupBoundaryToUser({
14534
- messages,
14535
- index,
14536
- candidate: targetProtectedTailStart,
14537
- offset,
14538
- triggerBudget: ctx.triggerBudget
14539
- });
14540
- if (snapped !== targetProtectedTailStart)
14541
- boundaryReason = "manual-wrapup-user-snap";
14542
- targetProtectedTailStart = snapped;
14543
- const refenced = fenceWrapupBoundaryForToolArcs({
14544
- candidate: targetProtectedTailStart,
14545
- arcs,
14546
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
14547
- });
14548
- if (refenced !== targetProtectedTailStart)
14549
- boundaryReason = "manual-wrapup-tool-arc";
14550
- 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);
14551
14585
  }
14552
- targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
14553
- targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
14554
- const target = deriveProtectedTailTokenTarget({
14555
- contextLimit: ctx.contextLimit,
14556
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14557
- usagePercentage,
14558
- triggerBudget: ctx.triggerBudget
14559
- });
14560
- const perRunCap = selectPerRunCap({
14561
- usagePercentage,
14562
- N: target.N,
14563
- contextLimit: ctx.contextLimit,
14564
- executeThresholdPercentage: ctx.executeThresholdPercentage
14565
- });
14566
- let headDiagnostics;
14567
- const head = applyHeadCap({
14568
- observeDiagnostics: (value) => {
14569
- headDiagnostics = value;
14570
- },
14571
- index: summaryRemovedIndex,
14572
- protectedTailStart: targetProtectedTailStart,
14573
- offset,
14574
- arcs: buildToolArcs(messages),
14575
- lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
14576
- capTokens: perRunCap,
14577
- recentOpenArcCutoff: targetProtectedTailStart
14578
- });
14579
- const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
14580
- const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
14581
- const snapshot = {
14582
- sessionId: ctx.sessionId,
14583
- mode: "manual-wrapup",
14584
- offset,
14585
- lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
14586
- offsetMessageId: boundaryMessageId(index, offset),
14587
- protectedTailStart: targetProtectedTailStart,
14588
- protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
14589
- eligibleEndOrdinal,
14590
- eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
14591
- rawMessageCountAtTrigger: rawMessageCount,
14592
- rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
14593
- N: keep,
14594
- usagePercentage,
14595
- usageInputTokens,
14596
- usageSource: ctx.usageSource,
14597
- contextLimit: ctx.contextLimit,
14598
- executeThresholdPercentage: ctx.executeThresholdPercentage,
14599
- triggerBudget: ctx.triggerBudget,
14600
- priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
14601
- migrationFloorActive: ctx.migrationFloorActive,
14602
- emergencyTailScale: ctx.emergencyTailScale,
14603
- providerShapeVersion: ctx.providerShapeVersion,
14604
- cacheNamespace: ctx.cacheNamespace,
14605
- createdAt,
14606
- rawRangeFingerprint,
14607
- trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
14608
- summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
14609
- oversizeAtomicUnit: head.oversizeAtomicUnit,
14610
- boundaryReason,
14611
- diagnostics: boundaryDiagnostics({
14612
- tailTarget: target,
14613
- usable: target.usable,
14614
- usagePercentage,
14615
- N: target.N,
14616
- triggerBudget: ctx.triggerBudget,
14617
- capTokens: perRunCap,
14618
- sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
14619
- protectedTailStart: targetProtectedTailStart,
14620
- livePromptFloor: {
14621
- ordinal: null,
14622
- from: targetProtectedTailStart,
14623
- to: targetProtectedTailStart
14624
- },
14625
- head: headDiagnostics
14626
- })
14627
- };
14628
- return {
14629
- snapshot,
14630
- rawMessagesAboveLastCompartment,
14631
- anchorRawMessageCount,
14632
- targetProtectedTailStart,
14633
- targetEligibleEndOrdinal: targetProtectedTailStart
14634
- };
14635
- }
14636
- function getRawHistoryEligibility(db, sessionId) {
14637
- const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
14638
- const offset = Math.max(1, lastCompartmentEnd + 1);
14639
- const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
14640
- const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
14641
- return {
14642
- lastCompartmentEnd,
14643
- offset,
14644
- rawMessageCount,
14645
- 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
14646
14597
  };
14647
14598
  }
14648
- function hasRunnableCompartmentWindow(snapshot) {
14649
- if (snapshot.offset >= snapshot.protectedTailStart)
14650
- return false;
14651
- if (snapshot.eligibleEndOrdinal <= snapshot.offset)
14652
- return false;
14653
- if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
14654
- return true;
14655
- const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
14656
- if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
14657
- return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
14658
- }
14659
- 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;
14660
14603
  }
14661
- function boundarySnapshotIdChecks(snapshot) {
14662
- const checks = [
14663
- [snapshot.offset, snapshot.offsetMessageId, "offset"],
14664
- [snapshot.rawMessageCountAtTrigger, snapshot.rawLastMessageIdAtTrigger, "last"]
14665
- ];
14666
- if (snapshot.protectedTailStart <= snapshot.rawMessageCountAtTrigger) {
14667
- checks.push([
14668
- snapshot.protectedTailStart,
14669
- snapshot.protectedTailStartMessageId,
14670
- "protectedTailStart"
14671
- ]);
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;
14672
14611
  }
14673
- if (snapshot.eligibleEndOrdinal > snapshot.offset) {
14674
- checks.push([
14675
- snapshot.eligibleEndOrdinal - 1,
14676
- snapshot.eligibleEndMessageId,
14677
- "eligibleEnd"
14678
- ]);
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);
14679
14619
  }
14680
- return checks;
14620
+ lastDeliveredAt.set(sessionId, now);
14681
14621
  }
14682
- function validateBoundarySnapshot(args) {
14683
- const { snapshot, exactIds } = args;
14684
- if (args.currentContextLimit && args.currentContextLimit !== snapshot.contextLimit) {
14685
- return {
14686
- ok: false,
14687
- reason: "model_or_limit_changed",
14688
- detail: `context limit changed from ${snapshot.contextLimit} to ${args.currentContextLimit}`
14689
- };
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;
14690
14638
  }
14691
- const currentRawMessageCount = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
14692
- if (snapshot.rawMessageCountAtTrigger > currentRawMessageCount) {
14693
- 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;
14694
14642
  }
14695
- const idAt = (ordinal) => {
14696
- if (!exactIds)
14697
- return readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, ordinal, ordinal).keys().next().value ?? null;
14698
- const id = exactIds.get(ordinal);
14699
- if (id === undefined)
14700
- throw new Error(`boundary validation was given no exact id for ordinal ${ordinal}`);
14701
- return id;
14702
- };
14703
- for (const [ordinal, expected, label] of boundarySnapshotIdChecks(snapshot)) {
14704
- if (expected !== idAt(ordinal)) {
14705
- return {
14706
- ok: false,
14707
- reason: "stale_snapshot",
14708
- detail: `${label} ordinal ${ordinal} id changed`
14709
- };
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;
14710
14668
  }
14711
14669
  }
14712
- const expectedOffset = Math.max(1, getLastCompartmentEndMessage(args.db, snapshot.sessionId) + 1);
14713
- if (expectedOffset !== snapshot.offset) {
14714
- return {
14715
- ok: false,
14716
- reason: "stale_snapshot",
14717
- detail: `last compartment moved: offset ${snapshot.offset} -> ${expectedOffset}`
14718
- };
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.`;
14719
14676
  }
14720
- const fingerprintMessages = readRawSessionMessageRange2(snapshot.sessionId, snapshot.offset, snapshot.eligibleEndOrdinal - 1);
14721
- const fingerprint = computeRawRangeFingerprint(fingerprintMessages, snapshot.offset, snapshot.eligibleEndOrdinal);
14722
- if (fingerprint !== snapshot.rawRangeFingerprint) {
14723
- 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"}`);
14724
14680
  }
14725
- 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
+ });
14726
14692
  }
14727
- function recordHighPressureNoEligibleHead(db, snapshot) {
14728
- const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
14729
- if (snapshot.usagePercentage < forceMaterializationPercentage && !snapshot.emergencyTailScale) {
14730
- 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;
14731
14713
  }
14732
- 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;
14733
14785
  }
14734
14786
 
14735
14787
  // src/hooks/magic-context/raw-exact-ordinal-read.ts
@@ -15252,7 +15304,6 @@ async function runCompartmentAgent(deps) {
15252
15304
  if (promptFit.trimmed || chunkTokens < historianChunkTokens) {
15253
15305
  sessionLog2(sessionId, `historian prompt fit: sized to ${producerModel ?? "unknown"} (${describeHistorianPromptTrim(promptFit)}; requestedChunkTokens=${historianChunkTokens})`);
15254
15306
  }
15255
- const perRunCap = selectPerRunCap(boundarySnapshot);
15256
15307
  if (!deps.forceDrainQuota && shouldWaitForNewHistorianHistory(boundarySnapshot, {
15257
15308
  emergency: getOverflowState(db, sessionId).needsEmergencyRecovery
15258
15309
  })) {
@@ -15261,19 +15312,27 @@ async function runCompartmentAgent(deps) {
15261
15312
  sessionLog2(sessionId, "historian no-op: waiting for new history after no forward progress");
15262
15313
  return;
15263
15314
  }
15264
- 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 });
15265
15320
  const reserve = deps.forceDrainQuota ? { ok: true, reservation: null } : reserveProtectedTailDrainTokens({
15266
15321
  db,
15267
15322
  sessionId,
15268
15323
  runId: crypto.randomUUID(),
15269
15324
  trueRawTokens: boundarySnapshot.summaryRemovedEligibleTokens,
15270
- usagePercentage: boundarySnapshot.usagePercentage,
15325
+ usagePercentage,
15326
+ providerRecovery: deps.drainBudgetUsagePercentage !== undefined,
15271
15327
  usable,
15272
15328
  perRunCap,
15273
15329
  executeThresholdPercentage: boundarySnapshot.executeThresholdPercentage
15274
15330
  });
15275
15331
  if (!reserve.ok) {
15276
- sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
15332
+ if (deps.reportDrainSkip && reserve.drainSkip)
15333
+ deps.reportDrainSkip(reserve.drainSkip);
15334
+ else
15335
+ sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
15277
15336
  telemetry.status = "noop";
15278
15337
  telemetry.failureReason = "internal protected-tail drain budget spent";
15279
15338
  return;
@@ -15443,6 +15502,8 @@ ${chunkText}`,
15443
15502
  const discardedLast = persistedCompartments.length < emittedCompartments.length;
15444
15503
  const weakLookaheadFinalCompartment = forceKeepLastCompartmentForChunk;
15445
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);
15446
15507
  const embeddingActive = !!promotionDirectory;
15447
15508
  const promotionActive = embeddingActive && deps.memoryEnabled !== false && deps.autoPromote !== false;
15448
15509
  const promotionProjectIdentity = promotionDirectory ? resolveProjectIdentity(promotionDirectory) : "";
@@ -15456,10 +15517,7 @@ ${chunkText}`,
15456
15517
  }
15457
15518
  return true;
15458
15519
  });
15459
- const unanchoredPromotionSkipReason = discardedLast ? "discarded_last" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
15460
- if (unanchoredPromotionSkipReason) {
15461
- 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}`);
15462
- }
15520
+ const weakTailReason = telemetry.discardedLast ? "discarded_last" : discardedLast ? "unserved_final_compartment" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
15463
15521
  let promotedFactRefs = [];
15464
15522
  let promotedFactCount = 0;
15465
15523
  let publishedEventCount = 0;
@@ -15502,9 +15560,9 @@ ${chunkText}`,
15502
15560
  }
15503
15561
  appendCompartments(db, sessionId, persistedCompartments);
15504
15562
  persistedIds = getNewestCompartmentIds(db, sessionId, persistedCompartments.length);
15505
- if (promotionActive && !skipUnanchoredPromotion) {
15563
+ if (promotionActive && publishableFacts.length > 0) {
15506
15564
  try {
15507
- const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, validatedPass.facts ?? []);
15565
+ const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, publishableFacts);
15508
15566
  promotedFactRefs = promotion.newMemoryRefs;
15509
15567
  promotedFactCount = promotion.factsPromoted;
15510
15568
  } catch (error) {
@@ -15572,6 +15630,13 @@ ${chunkText}`,
15572
15630
  }
15573
15631
  updateSessionMeta(db, sessionId, { compartmentInProgress: false });
15574
15632
  completedSuccessfully = true;
15633
+ if (weakTailReason) {
15634
+ logWeakTailFactPromotion(sessionId, {
15635
+ reason: weakTailReason,
15636
+ emitted: facts.length,
15637
+ stored: promotedFactCount
15638
+ });
15639
+ }
15575
15640
  {
15576
15641
  const facts = validatedPass.facts ?? [];
15577
15642
  const validIds = persistedIds.filter((id) => typeof id === "number");
@@ -16988,4 +17053,4 @@ ${failure}`;
16988
17053
  }
16989
17054
  }
16990
17055
 
16991
- 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, 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 };