@cortexkit/opencode-magic-context 0.49.92 → 0.49.95

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 (151) hide show
  1. package/dist/auto-search-worker.js +4 -4
  2. package/dist/chunk-embedding-write-worker.js +3 -3
  3. package/dist/{compartment-chunk-embedding-rp4asvk0.js → compartment-chunk-embedding-4nn3hsw2.js} +2 -2
  4. package/dist/{context-e8qd2v00.js → context-h9x9m2p3.js} +192 -68
  5. package/dist/{embedding-backfill-w0yq71q2.js → embedding-backfill-wdrqkw09.js} +6 -6
  6. package/dist/embedding-worker.js +3 -3
  7. package/dist/features/magic-context/compartment-storage.d.ts.map +1 -1
  8. package/dist/features/magic-context/dreamer/docs-proposals.d.ts +5 -2
  9. package/dist/features/magic-context/dreamer/docs-proposals.d.ts.map +1 -1
  10. package/dist/features/magic-context/history-gap-recovery.d.ts +42 -0
  11. package/dist/features/magic-context/history-gap-recovery.d.ts.map +1 -0
  12. package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
  13. package/dist/features/magic-context/memory/embedding-synapse.d.ts +18 -5
  14. package/dist/features/magic-context/memory/embedding-synapse.d.ts.map +1 -1
  15. package/dist/features/magic-context/memory/embedding-worker-client.d.ts +3 -0
  16. package/dist/features/magic-context/memory/embedding-worker-client.d.ts.map +1 -1
  17. package/dist/features/magic-context/message-visibility.d.ts +10 -0
  18. package/dist/features/magic-context/message-visibility.d.ts.map +1 -0
  19. package/dist/features/magic-context/search.d.ts +4 -0
  20. package/dist/features/magic-context/search.d.ts.map +1 -1
  21. package/dist/features/magic-context/session-decision-calibration.d.ts.map +1 -1
  22. package/dist/features/magic-context/session-project-backfill.d.ts.map +1 -1
  23. package/dist/features/magic-context/store-generation-rebase.d.ts.map +1 -1
  24. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/compartment-trigger.d.ts +1 -1
  27. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/history-boundary-repair.d.ts +2 -2
  29. package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/lkg-measured-request.d.ts +1 -0
  31. package/dist/hooks/magic-context/lkg-measured-request.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/lkg-persist.d.ts +3 -1
  33. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts +1 -0
  35. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/lkg-replay.d.ts +4 -0
  37. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts +1 -0
  39. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/tail-hygiene-output-count.d.ts +4 -0
  41. package/dist/hooks/magic-context/tail-hygiene-output-count.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +2 -0
  43. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  44. package/dist/hooks/magic-context/transform-stage-logger.d.ts +6 -0
  45. package/dist/hooks/magic-context/transform-stage-logger.d.ts.map +1 -1
  46. package/dist/{index-3f3d548g.js → index-2gewejcz.js} +18 -9
  47. package/dist/{index-n71006wq.js → index-2v9qpmb3.js} +5 -5
  48. package/dist/{index-zzhcshdk.js → index-3tmbvn0z.js} +9 -9
  49. package/dist/{index-f25ha337.js → index-3ywyr4zx.js} +1 -1
  50. package/dist/{index-hbn5g7rt.js → index-47hst5me.js} +1 -1
  51. package/dist/{index-xg1zjht5.js → index-7dzaamqg.js} +6 -6
  52. package/dist/{index-5y9w2ax7.js → index-7r11k4xr.js} +2 -2
  53. package/dist/{index-5pmf4jpj.js → index-7skgrbsg.js} +100 -52
  54. package/dist/{index-6rk44cer.js → index-c81tggen.js} +1 -1
  55. package/dist/{index-0twg41mh.js → index-ejgp0z9p.js} +1 -1
  56. package/dist/{index-hre29c1a.js → index-esacb9d0.js} +1 -1
  57. package/dist/{index-5a9kwapd.js → index-ewta5h87.js} +4 -4
  58. package/dist/{index-6r99v53h.js → index-j7n64sg4.js} +162 -60
  59. package/dist/{index-r3tdqqtq.js → index-jm62g83a.js} +180 -64
  60. package/dist/{index-anwy2mfb.js → index-pc49a7zt.js} +162 -31
  61. package/dist/{index-ydhymf0b.js → index-qmm8xpbc.js} +4 -4
  62. package/dist/{index-3n376ann.js → index-tedck05r.js} +4 -4
  63. package/dist/{index-j2w79s9r.js → index-tm799pq7.js} +1 -1
  64. package/dist/{index-01h7tqe3.js → index-tr4ep2ej.js} +21 -6
  65. package/dist/{index-wvbg9m0h.js → index-wqwjawer.js} +27 -11
  66. package/dist/index-xe34pwb6.js +119 -0
  67. package/dist/{index-xn9efn18.js → index-xjaf9g90.js} +13 -6
  68. package/dist/{index-6nqz8hsz.js → index-y915t3ey.js} +1 -1
  69. package/dist/{index-41bma6qs.js → index-yzzxb5e1.js} +2 -2
  70. package/dist/{index-901exj0f.js → index-zk6gtf43.js} +45 -9
  71. package/dist/index.js +27 -27
  72. package/dist/{message-index-bounded-f6fc00ze.js → message-index-bounded-d3x8rhpz.js} +4 -4
  73. package/dist/migration-worker.js +1 -1
  74. package/dist/{project-embedding-registry-8je0xg18.js → project-embedding-registry-az68q792.js} +5 -5
  75. package/dist/raw-ordinal-warmup-worker.js +5 -5
  76. package/dist/{read-session-chunk-y2ew3630.js → read-session-chunk-70r1snq3.js} +3 -3
  77. package/dist/{recomp-orchestrator-ggtcvb9g.js → recomp-orchestrator-cn4r2gz6.js} +15 -15
  78. package/dist/{render-q8c6wrq9.js → render-g45k3gts.js} +10 -10
  79. package/dist/{search-archive-pz1jf655.js → search-archive-s9t3exc1.js} +9 -7
  80. package/dist/{search-gjyrwapc.js → search-b0cb342r.js} +13 -13
  81. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  82. package/dist/{storage-tags-7raphcw6.js → storage-tags-xvbje7jm.js} +2 -2
  83. package/dist/{store-yr443ye8.js → store-91kawq9a.js} +2 -2
  84. package/dist/{store-reader-qbq6q4v0.js → store-reader-dgh3ssxx.js} +1 -1
  85. package/dist/tools/ctx-expand/search-archive.d.ts +3 -2
  86. package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
  87. package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
  88. package/dist/tools/ctx-expand/v2-archive-reader.d.ts +2 -0
  89. package/dist/tools/ctx-expand/v2-archive-reader.d.ts.map +1 -1
  90. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  91. package/dist/{transform-postprocess-phase-pmzdd3s2.js → transform-postprocess-phase-r1xhsjrh.js} +16 -16
  92. package/dist/v2/auto-search-worker.js +4 -4
  93. package/dist/v2/chunk-embedding-write-worker.js +3 -3
  94. package/dist/v2/{compartment-chunk-embedding-w7ht0t9v.js → compartment-chunk-embedding-a7ddvz7v.js} +2 -2
  95. package/dist/v2/{context-qqbpzk1q.js → context-2hssw26q.js} +351 -111
  96. package/dist/v2/{embedding-backfill-95m72gxa.js → embedding-backfill-gveter8p.js} +6 -6
  97. package/dist/v2/embedding-worker.js +3 -3
  98. package/dist/v2/fold/memory-cache.d.ts +2 -0
  99. package/dist/v2/fold/memory-cache.d.ts.map +1 -1
  100. package/dist/v2/fold/native-replay.d.ts +22 -5
  101. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  102. package/dist/v2/hooks/context.d.ts.map +1 -1
  103. package/dist/v2/hooks/revert-message-state.d.ts.map +1 -1
  104. package/dist/v2/hooks/session-project-backfill.d.ts +2 -1
  105. package/dist/v2/hooks/session-project-backfill.d.ts.map +1 -1
  106. package/dist/v2/{message-index-bounded-70g28hyg.js → message-index-bounded-tbwrff24.js} +4 -4
  107. package/dist/v2/migration-worker.js +1 -1
  108. package/dist/v2/{project-embedding-registry-fcxf4qht.js → project-embedding-registry-2zeycxek.js} +5 -5
  109. package/dist/v2/raw-ordinal-warmup-worker.js +5 -5
  110. package/dist/v2/{read-session-chunk-9rf0n9e6.js → read-session-chunk-cvgsfsgr.js} +3 -3
  111. package/dist/v2/{recomp-orchestrator-cwghhjc9.js → recomp-orchestrator-k4cj62f2.js} +15 -15
  112. package/dist/v2/{render-e852zmxz.js → render-ys7a3zks.js} +10 -10
  113. package/dist/v2/{search-archive-tmn6b5w8.js → search-archive-k2yh0jj3.js} +9 -7
  114. package/dist/v2/{search-jd3vczhn.js → search-x1cac8t6.js} +12 -12
  115. package/dist/v2/{server-vsqmkvxc.js → server-00adcfjd.js} +1 -1
  116. package/dist/v2/{server-rkj44mez.js → server-476anw1w.js} +1 -1
  117. package/dist/v2/{server-barj0mjz.js → server-5016ccyn.js} +1 -1
  118. package/dist/v2/{server-72k2r3kt.js → server-6aj72z52.js} +4 -4
  119. package/dist/v2/{server-7x5a46hf.js → server-6nh36020.js} +70 -61
  120. package/dist/v2/{server-fj3pekz2.js → server-88pjnecb.js} +1 -1
  121. package/dist/v2/{server-js2v309w.js → server-bfct1yvb.js} +99 -51
  122. package/dist/v2/{server-6t3asmx8.js → server-cd93xyyx.js} +162 -31
  123. package/dist/v2/{server-ysjjcatk.js → server-cvm1qrqc.js} +2 -2
  124. package/dist/v2/{server-rz6g5xne.js → server-e6xneh68.js} +1 -1
  125. package/dist/v2/{server-d4trxrj3.js → server-gj259dqy.js} +45 -9
  126. package/dist/v2/{server-8ps3717t.js → server-prrx17q3.js} +4 -4
  127. package/dist/v2/{server-7e89a2kf.js → server-qy58c11s.js} +13 -6
  128. package/dist/v2/{server-9011eteb.js → server-s81b3nct.js} +2 -2
  129. package/dist/v2/{server-p4g021y5.js → server-s8mk882p.js} +27 -11
  130. package/dist/v2/{server-mgxqfprb.js → server-srtq37nh.js} +1 -1
  131. package/dist/v2/{server-bvr9xs8h.js → server-vbr1rdkg.js} +6 -6
  132. package/dist/v2/{server-vtgeyhq6.js → server-vtkbxzw1.js} +21 -6
  133. package/dist/v2/{server-ps6zrzwj.js → server-xepfjgv5.js} +162 -60
  134. package/dist/v2/server-y0pd600x.js +119 -0
  135. package/dist/v2/{server-b4efn08m.js → server-zc8s06gx.js} +1 -1
  136. package/dist/v2/server.js +4 -4
  137. package/dist/v2/{storage-tags-wgsemtw1.js → storage-tags-y20j3jdp.js} +2 -2
  138. package/dist/v2/{store-enef5jcn.js → store-b95snz31.js} +2 -2
  139. package/dist/v2/{store-reader-jbaqv1yp.js → store-reader-qt2msa8z.js} +1 -1
  140. package/dist/v2/store-reader.d.ts +1 -1
  141. package/dist/v2/store-reader.d.ts.map +1 -1
  142. package/dist/v2/{v2-archive-reader-dm1aeqk2.js → v2-archive-reader-q92kwkr5.js} +1 -1
  143. package/dist/v2/{wrapup-orchestrator-cke368np.js → wrapup-orchestrator-ydqkxkhj.js} +15 -15
  144. package/dist/{v2-archive-reader-39ye0d3b.js → v2-archive-reader-x62hsr4c.js} +1 -1
  145. package/dist/{wrapup-orchestrator-ggnk0r4r.js → wrapup-orchestrator-kt81d6et.js} +16 -16
  146. package/package.json +1 -1
  147. package/src/config/schema/magic-context.ts +1 -1
  148. package/src/shared/storage-file-mutex-review.test.ts +110 -0
  149. package/src/shared/storage-file-mutex.ts +12 -0
  150. package/dist/index-52x68mj4.js +0 -58
  151. package/dist/v2/server-52x68mj4.js +0 -58
@@ -0,0 +1,119 @@
1
+ import {
2
+ TEXT_TAG_IDENTITY_MARKER
3
+ } from "./index-zk6gtf43.js";
4
+
5
+ // src/features/magic-context/message-fts-session-filter.ts
6
+ var MESSAGE_FTS_SESSION_FILTER_SQL = `+message_history_fts.rowid IN (
7
+ SELECT fts_rowid FROM message_fts_rowid_map WHERE session_id = ?
8
+ ) AND `;
9
+ var coverageCaches = new WeakMap;
10
+ var coverageScansOnThisThread = 0;
11
+ function getCoverageCache(db) {
12
+ let cache = coverageCaches.get(db);
13
+ if (!cache) {
14
+ cache = {
15
+ pin: db.prepare("SELECT fts_rowid FROM message_fts_rowid_map LIMIT 1"),
16
+ stamp: db.prepare("SELECT total_changes() AS changes, data_version AS version FROM pragma_data_version"),
17
+ missing: db.prepare(`SELECT DISTINCT session_id AS sessionId
18
+ FROM message_history_fts WHERE rowid IN (
19
+ SELECT id FROM message_history_fts_docsize
20
+ EXCEPT SELECT fts_rowid FROM message_fts_rowid_map
21
+ )`)
22
+ };
23
+ coverageCaches.set(db, cache);
24
+ }
25
+ return cache;
26
+ }
27
+ function withMessageFtsSessionFilter(db, sessionId, read) {
28
+ let cacheable = false;
29
+ try {
30
+ const transaction = db;
31
+ cacheable = transaction.inTransaction === false || transaction.isTransaction === false;
32
+ if (!cacheable)
33
+ coverageCaches.delete(db);
34
+ } catch {
35
+ coverageCaches.delete(db);
36
+ }
37
+ return db.transaction(() => {
38
+ let sessionFirst = false;
39
+ try {
40
+ const cache = getCoverageCache(db);
41
+ cache.pin.get();
42
+ const stamp = cache.stamp.get();
43
+ let incomplete = cache.incompleteSessions;
44
+ if (!cacheable || !incomplete || cache.version !== stamp.version || cache.changes !== stamp.changes) {
45
+ coverageScansOnThisThread += 1;
46
+ const rows = cache.missing.all();
47
+ incomplete = new Set(rows.map((row) => row.sessionId));
48
+ if (cacheable) {
49
+ cache.version = stamp.version;
50
+ cache.changes = stamp.changes;
51
+ cache.incompleteSessions = incomplete;
52
+ }
53
+ }
54
+ sessionFirst = !incomplete.has(sessionId);
55
+ } catch {
56
+ coverageCaches.delete(db);
57
+ }
58
+ return read(sessionFirst);
59
+ }).deferred();
60
+ }
61
+
62
+ // src/features/magic-context/message-visibility.ts
63
+ function partDropSql(session, id, prefix, type, validSuffix) {
64
+ const next = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
65
+ const suffix = `substr(t.message_id, length(${id}) + ${prefix.length + 1})`;
66
+ return `EXISTS (SELECT 1 FROM tags AS t INDEXED BY idx_tags_session_message_id
67
+ WHERE t.session_id = ${session} AND t.message_id >= ${id} || '${prefix}'
68
+ AND t.message_id < ${id} || '${next}' AND t.type = '${type}' AND t.status = 'dropped'
69
+ AND (${validSuffix(suffix)}))`;
70
+ }
71
+ var numericSuffix = (suffix) => `${suffix} <> '' AND ${suffix} NOT GLOB '*[^0-9]*'`;
72
+ function textDropSql(session, id) {
73
+ return `EXISTS (SELECT 1 FROM tags AS t INDEXED BY idx_tags_session_message_id
74
+ WHERE t.session_id = ${session} AND t.message_id = ${id} AND t.status = 'dropped'
75
+ AND t.type = 'message')
76
+ OR ${partDropSql(session, id, ":p", "message", numericSuffix)}
77
+ OR ${partDropSql(session, id, TEXT_TAG_IDENTITY_MARKER, "message", (suffix) => `${suffix} GLOB '[0-9a-f]*:[0-9a-f]*:o[0-9]*' AND ${suffix} NOT GLOB '*[^0-9a-f:o]*'
78
+ AND length(${suffix}) - length(replace(${suffix}, ':', '')) = 2`)}`;
79
+ }
80
+ function unresolvedCoverageSql(session, start, end) {
81
+ return `EXISTS (SELECT 1 FROM compartments AS unresolved
82
+ WHERE unresolved.session_id = ${session} AND unresolved.rebase_status = 'unresolved'
83
+ AND unresolved.start_message <= ${end} AND unresolved.end_message >= ${start})`;
84
+ }
85
+ function visibleSql(session, ordinal, lastSummaryEnd, dropped) {
86
+ return `CASE WHEN ${ordinal} <= ${lastSummaryEnd} THEN 0
87
+ WHEN ${unresolvedCoverageSql(session, ordinal, ordinal)} THEN 1 ELSE NOT (${dropped}) END`;
88
+ }
89
+ function liveTailRangeTouchesUnresolvedCoverage(db, sessionId, start, end, lastSummaryEnd) {
90
+ if (lastSummaryEnd < 0 || start <= lastSummaryEnd)
91
+ return false;
92
+ return !!db.prepare(`SELECT 1 WHERE ${unresolvedCoverageSql("?", "?", "?")}`).get(sessionId, end, start);
93
+ }
94
+ function messageTextVisibleInRequestSql(session, id, ordinal, lastSummaryEnd) {
95
+ return visibleSql(session, ordinal, lastSummaryEnd, textDropSql(session, id));
96
+ }
97
+ function messageVisibleInRequestSql(session, id, ordinal, lastSummaryEnd) {
98
+ return visibleSql(session, ordinal, lastSummaryEnd, `${textDropSql(session, id)}
99
+ OR ${partDropSql(session, id, ":file", "file", numericSuffix)}
100
+ OR EXISTS (SELECT 1 FROM tags AS t INDEXED BY idx_tags_pi_fallback_tool_owner
101
+ WHERE t.session_id = ${session} AND t.tool_owner_message_id = ${id}
102
+ AND t.type = 'tool' AND t.status = 'dropped')`);
103
+ }
104
+ function rangeHasHiddenMessages(db, sessionId, candidates, lastSummaryEnd, start, end) {
105
+ return !!db.prepare(`
106
+ WITH range(sessionId, start, end) AS (VALUES (?, ?, ?)), candidates(id, ordinal) AS (
107
+ SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?)
108
+ UNION
109
+ SELECT message_id, message_ordinal FROM range CROSS JOIN message_history_source
110
+ INDEXED BY idx_message_history_source_session_ordinal
111
+ WHERE session_id = range.sessionId AND message_ordinal BETWEEN range.start AND range.end
112
+ )
113
+ SELECT 1 FROM range CROSS JOIN candidates
114
+ WHERE NOT (${messageVisibleInRequestSql("range.sessionId", "candidates.id", "candidates.ordinal", "?")})
115
+ LIMIT 1
116
+ `).get(sessionId, start, end, JSON.stringify([...candidates]), lastSummaryEnd);
117
+ }
118
+
119
+ export { MESSAGE_FTS_SESSION_FILTER_SQL, withMessageFtsSessionFilter, liveTailRangeTouchesUnresolvedCoverage, messageTextVisibleInRequestSql, rangeHasHiddenMessages };
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  DEFAULT_LOCAL_EMBEDDING_MODEL
3
- } from "./index-6nqz8hsz.js";
3
+ } from "./index-y915t3ey.js";
4
4
  import {
5
5
  getSynapseLaneIdentity
6
- } from "./index-6r99v53h.js";
6
+ } from "./index-j7n64sg4.js";
7
7
  import {
8
8
  getHarness2
9
9
  } from "./index-pavzsdc6.js";
@@ -795,6 +795,11 @@ async function prepareNativeOnnxTelemetry() {
795
795
  }
796
796
 
797
797
  // src/features/magic-context/memory/embedding-worker-client.ts
798
+ class EmbeddingRequestAbortedError extends Error {
799
+ constructor() {
800
+ super("embedding request aborted");
801
+ }
802
+ }
798
803
  var warnedWindowsTelemetry = false;
799
804
  var EMBEDDING_WORKER_STOP_GRACE_MS = 5000;
800
805
  var EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS = 2000;
@@ -968,7 +973,7 @@ class EmbeddingWorkerClient {
968
973
  }
969
974
  async request(texts, signal) {
970
975
  if (signal?.aborted)
971
- return Promise.reject(new Error("embedding request aborted"));
976
+ throw new EmbeddingRequestAbortedError;
972
977
  this.activeRequests++;
973
978
  this.clearIdleTimer();
974
979
  try {
@@ -998,7 +1003,7 @@ class EmbeddingWorkerClient {
998
1003
  if (this.disposed)
999
1004
  throw new Error("embedding worker disposed");
1000
1005
  if (signal?.aborted)
1001
- throw new Error("embedding request aborted");
1006
+ throw new EmbeddingRequestAbortedError;
1002
1007
  return new Promise((resolve, reject) => {
1003
1008
  const id = this.nextId++;
1004
1009
  const timer = setTimeout(() => {
@@ -1008,7 +1013,7 @@ class EmbeddingWorkerClient {
1008
1013
  clearTimeout(timer);
1009
1014
  this.pending.delete(id);
1010
1015
  signal?.removeEventListener("abort", abort);
1011
- reject(new Error("embedding request aborted"));
1016
+ reject(new EmbeddingRequestAbortedError);
1012
1017
  if (this.pending.size === 0) {
1013
1018
  worker.unref();
1014
1019
  if (!(worker instanceof Worker))
@@ -1729,7 +1734,9 @@ class LocalEmbeddingProvider {
1729
1734
  this.recordWorkerReply(reply);
1730
1735
  return reply.vectors ?? texts.map(() => null);
1731
1736
  } catch (error) {
1732
- this.recordWorkerFailure(error);
1737
+ if (!(signal?.aborted && error instanceof EmbeddingRequestAbortedError)) {
1738
+ this.recordWorkerFailure(error);
1739
+ }
1733
1740
  return texts.map(() => null);
1734
1741
  }
1735
1742
  }
@@ -7029,7 +7029,7 @@ var MagicContextConfigSchema = object({
7029
7029
  execute_threshold_percentage: union([
7030
7030
  number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE),
7031
7031
  object({ default: number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE) }).catchall(number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE))
7032
- ]).default(DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE).describe('Context percentage that forces queued operations to execute. Number or per-model object ({ default: 65, "provider/model": 45 }). Values above 90 are rejected because the runtime caps at 90% of the output-reserved safe window (MAX_EXECUTE_THRESHOLD). Default: DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE'),
7032
+ ]).default(DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE).describe('Context usage above which a pass counts as an execute pass. Queued drops and cleanup then apply on the next rewrite of the cached prompt (a new summary, a fold, /ctx-flush, or high pressure); the threshold does not start a rewrite for every queued drop. Number or per-model object ({ default: 65, "provider/model": 45 }). Values above 90 are rejected because the runtime caps at 90% of the output-reserved safe window (MAX_EXECUTE_THRESHOLD). Default: DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE'),
7033
7033
  execute_threshold_tokens: object({
7034
7034
  default: number().min(5000).max(2000000).optional()
7035
7035
  }).catchall(number().min(5000).max(2000000)).optional().describe("Absolute token thresholds per model. When matched, overrides execute_threshold_percentage for that model. Accepts `default` for all models or per-model keys. Values above 90% × context_limit are clamped with a warning log. Min 5_000, max 2_000_000."),
@@ -3,12 +3,12 @@ import {
3
3
  } from "./index-s7460efs.js";
4
4
  import {
5
5
  getTagById2
6
- } from "./index-901exj0f.js";
6
+ } from "./index-zk6gtf43.js";
7
7
  import {
8
8
  expandToolPart,
9
9
  visitRawSessionMessages2,
10
10
  readRawSessionMessageById2
11
- } from "./index-5y9w2ax7.js";
11
+ } from "./index-7r11k4xr.js";
12
12
 
13
13
  // src/tools/ctx-expand/render.ts
14
14
  import { createHash } from "node:crypto";
@@ -32,7 +32,7 @@ import {
32
32
  normalizeProtectedToolName,
33
33
  mergeProtectedTools,
34
34
  deriveDefaultProtectedTokens
35
- } from "./index-6nqz8hsz.js";
35
+ } from "./index-y915t3ey.js";
36
36
  import {
37
37
  getTagIdentityWriteGeneration2,
38
38
  getSqliteDatabasePath2,
@@ -151,9 +151,13 @@ function isThinkingPart(part) {
151
151
  }
152
152
 
153
153
  // src/hooks/magic-context/tail-hygiene-output-count.ts
154
+ var CTX_REDUCE_OUTPUT = Symbol.for("magic-context.ctx-reduce-output");
155
+ function isCtxReduceTool(name) {
156
+ return normalizeProtectedToolName(name) === "ctx_reduce";
157
+ }
154
158
  var CURRENT_OUTPUT_COUNT = Symbol.for("magic-context.current-reclaimable-tool-output-count");
155
159
  function countReclaimableToolOutputs(parts) {
156
- return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
160
+ return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0 && !part[CTX_REDUCE_OUTPUT]).length;
157
161
  }
158
162
  function rememberCurrentToolOutputCount(baseline, measurement) {
159
163
  return Object.assign(baseline, {
@@ -1105,6 +1109,10 @@ function buildTagAttribution(args) {
1105
1109
  function reclaimableTailTokens(part) {
1106
1110
  return part.tagStatus === "active" && !part.protected && !part.queuedForDrop && part.kind !== "excluded" && part.kind !== "text" ? part.tokens : 0;
1107
1111
  }
1112
+ function isCtxReduceResult(part, tag) {
1113
+ const name = isRecord(part) ? part.type === "tool" ? part.tool : part.toolName : null;
1114
+ return isCtxReduceTool(typeof name === "string" ? name : tag?.toolName ?? null);
1115
+ }
1108
1116
  function snapshot(args) {
1109
1117
  const memo = memoizedContent(args.kind, args.content);
1110
1118
  const tag = args.tag;
@@ -1280,6 +1288,7 @@ function measureWithReplay(input, replay) {
1280
1288
  const tag = prior.kind === "text" ? attribution.messageTags.get(`${message.info.id}:p${partIndex}`) : prior.kind === "file" ? attribution.messageTags.get(`${message.info.id}:file${partIndex}`) : prior.kind === "toolInput" || prior.kind === "toolOutput" ? attribution.toolTagsByPart.get(message.parts[partIndex]) : undefined;
1281
1289
  const protectedPart = tag ? attribution.protectedNumbers.has(tag.tagNumber) : false;
1282
1290
  const queuedForDrop = tag ? pendingDropTagNumbers.has(tag.tagNumber) : false;
1291
+ const ctxReduceOutput = prior.kind === "toolOutput" && isCtxReduceResult(message.parts[partIndex], tag);
1283
1292
  const uTokens = reclaimableTailTokens({
1284
1293
  kind: prior.kind,
1285
1294
  tokens: prior.tokens,
@@ -1287,12 +1296,13 @@ function measureWithReplay(input, replay) {
1287
1296
  protected: protectedPart,
1288
1297
  queuedForDrop
1289
1298
  });
1290
- const measured = prior.tagNumber === (tag?.tagNumber ?? null) && prior.tagStatus === (tag?.status ?? null) && prior.protected === protectedPart && prior.queuedForDrop === queuedForDrop && prior.uTokens === uTokens ? prior : {
1299
+ const measured = prior.tagNumber === (tag?.tagNumber ?? null) && prior.tagStatus === (tag?.status ?? null) && prior.protected === protectedPart && prior.queuedForDrop === queuedForDrop && Boolean(prior[CTX_REDUCE_OUTPUT]) === ctxReduceOutput && prior.uTokens === uTokens ? prior : {
1291
1300
  ...prior,
1292
1301
  tagNumber: tag?.tagNumber ?? null,
1293
1302
  tagStatus: tag?.status ?? null,
1294
1303
  protected: protectedPart,
1295
1304
  queuedForDrop,
1305
+ ...ctxReduceOutput || prior[CTX_REDUCE_OUTPUT] ? { [CTX_REDUCE_OUTPUT]: ctxReduceOutput } : {},
1296
1306
  uTokens
1297
1307
  };
1298
1308
  parts.push(measured);
@@ -1398,6 +1408,8 @@ function measureWithReplay(input, replay) {
1398
1408
  protectedNumbers: attribution.protectedNumbers,
1399
1409
  pendingDropTagNumbers
1400
1410
  });
1411
+ if (isCtxReduceResult(part, tag))
1412
+ measured[CTX_REDUCE_OUTPUT] = true;
1401
1413
  parts.push(measured);
1402
1414
  t += measured.tokens;
1403
1415
  u += measured.uTokens;
@@ -2250,9 +2262,30 @@ function thawCalibration(frozen) {
2250
2262
  function sameCalibration(left, right) {
2251
2263
  return left.revision === right.revision && left.providerId === right.providerId && left.modelId === right.modelId && left.systemRatio === right.systemRatio && left.toolsRatio === right.toolsRatio && left.proseRatio === right.proseRatio && left.source === right.source;
2252
2264
  }
2253
- function persistNamespace(db, sessionId, root, namespace) {
2254
- root[CALIBRATION_STATE_KEY] = namespace;
2255
- db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(root), sessionId);
2265
+ function persistNamespace(db, sessionId, observedState, root, namespace) {
2266
+ const observed = observedState ?? null;
2267
+ try {
2268
+ const update = db.prepare(`UPDATE session_meta SET deferred_execute_state = json_set(
2269
+ CASE
2270
+ WHEN deferred_execute_state IS ? THEN ?
2271
+ WHEN json_type(deferred_execute_state) = 'object' THEN deferred_execute_state
2272
+ ELSE '{}'
2273
+ END, '$.${CALIBRATION_STATE_KEY}', json(?))
2274
+ WHERE session_id = ? AND (deferred_execute_state IS ? OR json_valid(deferred_execute_state))`).run(observed, JSON.stringify(root), JSON.stringify(namespace), sessionId, observed);
2275
+ if (update.changes > 0)
2276
+ return;
2277
+ } catch (error) {
2278
+ if (!(error instanceof Error) || !/malformed JSON/i.test(error.message))
2279
+ throw error;
2280
+ }
2281
+ db.transaction(() => {
2282
+ const current = db.prepare("SELECT deferred_execute_state FROM session_meta WHERE session_id = ?").get(sessionId);
2283
+ if (!current)
2284
+ return;
2285
+ const latestRoot = parseStateRoot(current.deferred_execute_state);
2286
+ latestRoot[CALIBRATION_STATE_KEY] = namespace;
2287
+ db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(latestRoot), sessionId);
2288
+ }).immediate();
2256
2289
  }
2257
2290
  function sessionDecisionCalibration(db, sessionId, pass) {
2258
2291
  const row = readSessionRow(db, sessionId);
@@ -2265,7 +2298,10 @@ function sessionDecisionCalibration(db, sessionId, pass) {
2265
2298
  const candidate = freezeCalibration(calibrationForModelKey(key));
2266
2299
  if (!namespace.active || !sameCalibration(namespace.active, candidate)) {
2267
2300
  const previousRevision = namespace.active?.revision ?? "unfrozen";
2268
- persistNamespace(db, sessionId, root, { ...namespace, active: candidate });
2301
+ persistNamespace(db, sessionId, row?.deferred_execute_state, root, {
2302
+ ...namespace,
2303
+ active: candidate
2304
+ });
2269
2305
  if (namespace.active) {
2270
2306
  pass.onAdopt?.(`calibration revision ${previousRevision} → ${candidate.revision} adopted (bust=${pass.bustReason ?? "unknown"})`);
2271
2307
  }
@@ -2308,7 +2344,7 @@ function transitionSessionHygieneUnits(db, sessionId, bustPermitted, calibration
2308
2344
  nudgeLevel.postReduceGraceBaselineU = grace;
2309
2345
  }
2310
2346
  db.prepare("UPDATE session_meta SET last_nudge_undropped = COALESCE(?, last_nudge_undropped), last_nudge_level = COALESCE(?, last_nudge_level) WHERE session_id = ?").run(lastNudge, nudgeLevel ? JSON.stringify(nudgeLevel) : null, sessionId);
2311
- persistNamespace(db, sessionId, root, {
2347
+ persistNamespace(db, sessionId, row?.deferred_execute_state, root, {
2312
2348
  ...namespace,
2313
2349
  hygieneUnitsVersion: HYGIENE_PROVIDER_UNITS_VERSION
2314
2350
  });
@@ -9023,4 +9059,4 @@ function deleteToolTagsByOwner(db, sessionId, ownerMsgId) {
9023
9059
  return getDeleteToolTagsByOwnerStatement(db).all(sessionId, ownerMsgId).length;
9024
9060
  }
9025
9061
 
9026
- export { protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, currentReclaimableToolOutputCount, isRecord, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisiblePart, providerVisibleMessage, CLEARED_TODO_STATE_JSON, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, buildChannel2Reminder, buildChannel1Reminder, createFinalWireIncompleteLogger, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, readFrozenMergedReasoningParts, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, readEpochFloorSnapshot, getProtectionWindowForSession, CACHED_TRIM_PARTIAL_SQL, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, clearCachedM0, withReplayEnvelopeSnapshot, invalidateReplayEnvelopeSnapshot, isRustMarkerAdmissionFenced, setRustMarkerAdmissionFence, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadPersistedUsage, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, resetProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, removeNoteNudgeAnchorByMessageId, pruneAutoSearchHintDecisions, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, getCompactionMarkerPublicationState, compareAndSetCompactionMarkerPublicationState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, compactionOffThinkingFrozenId, compactionOffFrozenThinkingIds, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, noteBindingRecoveryAwaitingClear, bindingRecoveryAwaitingClear, retryBindingRecoveryClear, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, getProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingMarker, cachedHeadCoversPendingCompactionMarker, getObservedEpochFloor, resolveEpochFloorForPass, getReasoningRemovalState, addRemovedReasoningIds, markDropLeavesReasoning, detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, overflowLimitToStore, isProviderRateLimit, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, isSentinel, replaySentinelByMessageIds, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, markServedShapeRepair, prepareServedShapeRepair, stripSystemInjectedMessages, stripDroppedPlaceholderMessages, replayClearedReasoning, replayStrippedInlineThinking, clearOldReasoning, stripClearedReasoning, captureInlineThinkingRepairs, stripInlineThinking, findReasoningBearingAssistantIds, findLatestAssistantReasoningMutationExemptMessage, snapshotTrailingBlankSourceDecisions, findTrailingBlankDecisionCandidates, applyFrozenTrailingBlankDecisions, stripReasoningFromAssistantIds, findMergedReasoningStripDecisions, stripReasoningFromMergedAssistants, getEmptyImageParts, stripProcessedImages, projectOpencodeReasoningBudgetCutoff, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opencodeReasoningBudgetCutoff, describeFinalWireTail, estimatePartImageTokens, openCode2ThinkingPayload, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, estimateAppendedWireTokens, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, snapshotEmergencyServedMass, tagsSinceReading, emergencyServedMassRemovedSince, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, hasPendingDropOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize2, getRecentTagOwnerMessageIds2, getActiveTagTokenAggregate2, AGE_RECLAIM_MIN_TOKENS2, getOldestActiveUnprotectedToolTags2, getActiveToolTagsForAgeReclaim2, getTriggerTagTokenUpperBound2, getActiveTagTokenTotalsByMessage2, updateTagTokenCount2, getPersistedToolTagAccounting2, getAllStatusTagTokenTotalsFlat2, getReasoningTokenEstimatesByMessage2, tryGetReasoningTokenEstimatesByMessage2, getMaxTagNumberByOwnerMessage2, TagOwnerSummaryNotReady2, scanTagOwnerSummary2, cachedTagOwnerRatios2, tagOwnerWarmupState2, scanTagOwnerDelta2, installTagOwnerDelta2, installTagOwnerSummary2, isTagOwnerSummaryReady2, tagTokenCountIsNull2, backfillTagTokenCounts2, insertTag2, updateTagStatus2, markTagDropped2, markWhitespaceAssistantTagInert2, getInertWhitespaceAssistantTags2, getInertWhitespaceAssistantTagsByNumbers2, updateTagDropMode2, updateCavemanDepth2, updateTagMessageId2, hasPiFallbackMessageTags2, findAdoptableFallbackTags2, adoptFallbackTagMessageId2, foldShrunkPartTags2, hasPiFallbackToolOwnerTags2, findPiFallbackToolOwnerTags2, adoptPiFallbackToolOwnerTag2, adoptPiFallbackMessageTag2, markTagsCompactedByMessageIds2, deleteTagsByMessageId2, getMaxTagNumberBySession2, getTagNumberByMessageId2, getAssignableTagNumberByMessageId2, getMinMessageTagNumberForRawId2, deriveTagLoadFloor2, TAG_SELECT_COLUMNS2, getTagsBySession2, getActiveTagsBySession2, getTailHygieneTags2, getDroppedTagsBySession2, getTagsForPendingOperations2, getTagsByNumbers2, getNewestToolTagNumbers2, getDroppedTagsByNumbers2, getMaxDroppedTagNumber2, getTagById2, getTopNBySize2, getToolTagNumberByOwner2, getNullOwnerToolTag2, adoptNullOwnerToolTag2, getCandidateToolOwners2, pickNearestPriorOwner2 };
9062
+ export { protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, currentReclaimableToolOutputCount, isRecord, TEXT_TAG_IDENTITY_MARKER, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisiblePart, providerVisibleMessage, CLEARED_TODO_STATE_JSON, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, buildChannel2Reminder, buildChannel1Reminder, createFinalWireIncompleteLogger, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, readFrozenMergedReasoningParts, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, readEpochFloorSnapshot, getProtectionWindowForSession, CACHED_TRIM_PARTIAL_SQL, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, clearCachedM0, withReplayEnvelopeSnapshot, invalidateReplayEnvelopeSnapshot, isRustMarkerAdmissionFenced, setRustMarkerAdmissionFence, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadPersistedUsage, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, resetProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, removeNoteNudgeAnchorByMessageId, pruneAutoSearchHintDecisions, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, getCompactionMarkerPublicationState, compareAndSetCompactionMarkerPublicationState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, compactionOffThinkingFrozenId, compactionOffFrozenThinkingIds, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, noteBindingRecoveryAwaitingClear, bindingRecoveryAwaitingClear, retryBindingRecoveryClear, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, getProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingMarker, cachedHeadCoversPendingCompactionMarker, getObservedEpochFloor, resolveEpochFloorForPass, getReasoningRemovalState, addRemovedReasoningIds, markDropLeavesReasoning, detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, overflowLimitToStore, isProviderRateLimit, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, isSentinel, replaySentinelByMessageIds, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, markServedShapeRepair, prepareServedShapeRepair, stripSystemInjectedMessages, stripDroppedPlaceholderMessages, replayClearedReasoning, replayStrippedInlineThinking, clearOldReasoning, stripClearedReasoning, captureInlineThinkingRepairs, stripInlineThinking, findReasoningBearingAssistantIds, findLatestAssistantReasoningMutationExemptMessage, snapshotTrailingBlankSourceDecisions, findTrailingBlankDecisionCandidates, applyFrozenTrailingBlankDecisions, stripReasoningFromAssistantIds, findMergedReasoningStripDecisions, stripReasoningFromMergedAssistants, getEmptyImageParts, stripProcessedImages, projectOpencodeReasoningBudgetCutoff, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opencodeReasoningBudgetCutoff, describeFinalWireTail, estimatePartImageTokens, openCode2ThinkingPayload, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, estimateAppendedWireTokens, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, snapshotEmergencyServedMass, tagsSinceReading, emergencyServedMassRemovedSince, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, hasPendingDropOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize2, getRecentTagOwnerMessageIds2, getActiveTagTokenAggregate2, AGE_RECLAIM_MIN_TOKENS2, getOldestActiveUnprotectedToolTags2, getActiveToolTagsForAgeReclaim2, getTriggerTagTokenUpperBound2, getActiveTagTokenTotalsByMessage2, updateTagTokenCount2, getPersistedToolTagAccounting2, getAllStatusTagTokenTotalsFlat2, getReasoningTokenEstimatesByMessage2, tryGetReasoningTokenEstimatesByMessage2, getMaxTagNumberByOwnerMessage2, TagOwnerSummaryNotReady2, scanTagOwnerSummary2, cachedTagOwnerRatios2, tagOwnerWarmupState2, scanTagOwnerDelta2, installTagOwnerDelta2, installTagOwnerSummary2, isTagOwnerSummaryReady2, tagTokenCountIsNull2, backfillTagTokenCounts2, insertTag2, updateTagStatus2, markTagDropped2, markWhitespaceAssistantTagInert2, getInertWhitespaceAssistantTags2, getInertWhitespaceAssistantTagsByNumbers2, updateTagDropMode2, updateCavemanDepth2, updateTagMessageId2, hasPiFallbackMessageTags2, findAdoptableFallbackTags2, adoptFallbackTagMessageId2, foldShrunkPartTags2, hasPiFallbackToolOwnerTags2, findPiFallbackToolOwnerTags2, adoptPiFallbackToolOwnerTag2, adoptPiFallbackMessageTag2, markTagsCompactedByMessageIds2, deleteTagsByMessageId2, getMaxTagNumberBySession2, getTagNumberByMessageId2, getAssignableTagNumberByMessageId2, getMinMessageTagNumberForRawId2, deriveTagLoadFloor2, TAG_SELECT_COLUMNS2, getTagsBySession2, getActiveTagsBySession2, getTailHygieneTags2, getDroppedTagsBySession2, getTagsForPendingOperations2, getTagsByNumbers2, getNewestToolTagNumbers2, getDroppedTagsByNumbers2, getMaxDroppedTagNumber2, getTagById2, getTopNBySize2, getToolTagNumberByOwner2, getNullOwnerToolTag2, adoptNullOwnerToolTag2, getCandidateToolOwners2, pickNearestPriorOwner2 };
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  recordToolParameters,
5
5
  createDroppedInputToolExecuteBeforeHook,
6
6
  readRawSessionMessages2
7
- } from "./index-5y9w2ax7.js";
7
+ } from "./index-7r11k4xr.js";
8
8
  import {
9
9
  setHarness2
10
10
  } from "./index-pavzsdc6.js";
@@ -31,7 +31,7 @@ import {
31
31
  record,
32
32
  DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
33
33
  DEFAULT_HISTORIAN_TIMEOUT_MS
34
- } from "./index-6nqz8hsz.js";
34
+ } from "./index-y915t3ey.js";
35
35
  import {
36
36
  denyTaskRoutingToCallerAgents,
37
37
  buildHiddenAgentRegistrations,
@@ -58,7 +58,7 @@ import {
58
58
  checkCompactionMarkerConsistency,
59
59
  clearInjectionCache,
60
60
  clearNoteNudgeTriggerOnly
61
- } from "./index-3f3d548g.js";
61
+ } from "./index-2gewejcz.js";
62
62
  import"./index-sd3egckz.js";
63
63
  import"./index-gqf8r04r.js";
64
64
  import {
@@ -146,7 +146,7 @@ import {
146
146
  parameterDescriptionsFor,
147
147
  MagicContextRpcServer,
148
148
  applyHiddenSubagentTemperature
149
- } from "./index-r3tdqqtq.js";
149
+ } from "./index-jm62g83a.js";
150
150
  import {
151
151
  resolveOpenCodeDbPath,
152
152
  openCodeDbPathExists,
@@ -198,7 +198,7 @@ import {
198
198
  dropServedRecord,
199
199
  registerLkgPersistence,
200
200
  dropSlot
201
- } from "./index-anwy2mfb.js";
201
+ } from "./index-pc49a7zt.js";
202
202
  import {
203
203
  recordSessionProjectIdentity
204
204
  } from "./index-r4y0dczp.js";
@@ -212,7 +212,7 @@ import {
212
212
  openDatabaseAsync,
213
213
  isDatabasePersisted,
214
214
  getDatabasePersistenceError
215
- } from "./index-6rk44cer.js";
215
+ } from "./index-c81tggen.js";
216
216
  import {
217
217
  registerExitAbort,
218
218
  unregisterExitAbort
@@ -228,11 +228,11 @@ import"./index-fr0wbhdn.js";
228
228
  import {
229
229
  preloadTokenizer
230
230
  } from "./index-s7460efs.js";
231
- import"./index-6r99v53h.js";
231
+ import"./index-j7n64sg4.js";
232
232
  import {
233
233
  getDefaultSubcConnectionFile,
234
234
  SubcModuleTransport
235
- } from "./index-5pmf4jpj.js";
235
+ } from "./index-7skgrbsg.js";
236
236
  import"./index-qt1qqasc.js";
237
237
  import"./index-e6ncz7a6.js";
238
238
  import {
@@ -284,7 +284,7 @@ import {
284
284
  isAnthropicFamilyRoute,
285
285
  deleteTagsByMessageId2,
286
286
  getMaxTagNumberBySession2
287
- } from "./index-901exj0f.js";
287
+ } from "./index-zk6gtf43.js";
288
288
  import {
289
289
  resolveHistorianModel2,
290
290
  resolveOpenCodeAgentOverrides2,
@@ -300,22 +300,22 @@ import {
300
300
  getEmbedDrainUiStatus,
301
301
  clearEmbedSessionState
302
302
  } from "./index-2amn2s73.js";
303
- import"./index-0twg41mh.js";
303
+ import"./index-ejgp0z9p.js";
304
304
  import {
305
305
  deleteIndexedMessage
306
- } from "./index-hre29c1a.js";
307
- import"./index-01h7tqe3.js";
306
+ } from "./index-esacb9d0.js";
307
+ import"./index-tr4ep2ej.js";
308
308
  import"./index-mjy2k9jr.js";
309
309
  import {
310
310
  pushNotification2
311
311
  } from "./index-y14pawe1.js";
312
- import"./index-xn9efn18.js";
312
+ import"./index-xjaf9g90.js";
313
313
  import {
314
314
  getEmbeddingCoverageStatus2
315
- } from "./index-3n376ann.js";
315
+ } from "./index-tedck05r.js";
316
316
  import"./index-qjwpqvnf.js";
317
- import"./index-ydhymf0b.js";
318
- import"./index-f25ha337.js";
317
+ import"./index-qmm8xpbc.js";
318
+ import"./index-3ywyr4zx.js";
319
319
  import"./index-9emdjcb5.js";
320
320
  import"./index-832w615x.js";
321
321
  import {
@@ -338,13 +338,13 @@ import {
338
338
  armBindingRecoverySafely,
339
339
  collectForeignTextParts,
340
340
  resetDegradedCacheCount2
341
- } from "./index-zzhcshdk.js";
341
+ } from "./index-3tmbvn0z.js";
342
342
  import {
343
343
  scheduleClearAndReindex
344
- } from "./index-hbn5g7rt.js";
344
+ } from "./index-47hst5me.js";
345
345
  import {
346
346
  runManagedRecomp2
347
- } from "./index-5a9kwapd.js";
347
+ } from "./index-ewta5h87.js";
348
348
  import {
349
349
  isValidSemver,
350
350
  compareSemverCore
@@ -352,11 +352,11 @@ import {
352
352
  import"./index-fmsr7v69.js";
353
353
  import {
354
354
  runManagedWrapup2
355
- } from "./index-n71006wq.js";
356
- import"./index-41bma6qs.js";
357
- import"./index-52x68mj4.js";
358
- import"./index-xg1zjht5.js";
359
- import"./index-wvbg9m0h.js";
355
+ } from "./index-2v9qpmb3.js";
356
+ import"./index-yzzxb5e1.js";
357
+ import"./index-xe34pwb6.js";
358
+ import"./index-7dzaamqg.js";
359
+ import"./index-wqwjawer.js";
360
360
  import {
361
361
  __toESM,
362
362
  __commonJS
@@ -8212,7 +8212,7 @@ var require_src2 = __commonJS(function(exports, module) {
8212
8212
  // package.json
8213
8213
  var package_default = {
8214
8214
  name: "@cortexkit/opencode-magic-context",
8215
- version: "0.49.92",
8215
+ version: "0.49.95",
8216
8216
  type: "module",
8217
8217
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
8218
8218
  main: "dist/index.js",
@@ -11868,7 +11868,7 @@ async function sendOpenCodeRefusal(client, sessionId, message, refusal) {
11868
11868
  sessionLog2(sessionId, "refusal notice skipped: no terminal viewing the session", refusal.name);
11869
11869
  }
11870
11870
  if (storageBusy) {
11871
- const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-pmzdd3s2.js"));
11871
+ const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-r1xhsjrh.js"));
11872
11872
  await abortSessionFailClosed(client, sessionId);
11873
11873
  }
11874
11874
  }
@@ -12138,7 +12138,7 @@ async function setup(context) {
12138
12138
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
12139
12139
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
12140
12140
  }
12141
- const { registerContext } = await import("./context-e8qd2v00.js");
12141
+ const { registerContext } = await import("./context-h9x9m2p3.js");
12142
12142
  setHarness2("opencode2");
12143
12143
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
12144
12144
  const duties = await registerContext(context);
@@ -4,20 +4,20 @@ import {
4
4
  yieldIndexChunk2
5
5
  } from "./index-gzy5w8ya.js";
6
6
  import"./index-1zx87sdm.js";
7
- import"./index-901exj0f.js";
7
+ import"./index-zk6gtf43.js";
8
8
  import"./index-s7460efs.js";
9
9
  import"./index-pavzsdc6.js";
10
10
  import"./index-ywrz4wy2.js";
11
11
  import"./index-z4p0ry94.js";
12
12
  import"./index-mg9s2rc3.js";
13
- import"./index-6nqz8hsz.js";
13
+ import"./index-y915t3ey.js";
14
14
  import"./index-v0p37hm2.js";
15
15
  import"./index-96ztjvkn.js";
16
16
  import"./index-1d042x6w.js";
17
17
  import"./index-q7q6qp1f.js";
18
18
  import"./index-58e3y90n.js";
19
19
  import"./index-sp5pvs95.js";
20
- import"./index-5y9w2ax7.js";
20
+ import"./index-7r11k4xr.js";
21
21
  import {
22
22
  MESSAGE_INDEX_MAX_FTS_BYTES,
23
23
  messageIndexSkipKey,
@@ -25,7 +25,7 @@ import {
25
25
  markMessageIndexDirty,
26
26
  getIndexableContent,
27
27
  indexSingleMessage
28
- } from "./index-hre29c1a.js";
28
+ } from "./index-esacb9d0.js";
29
29
  import"./index-s32f8y67.js";
30
30
  import"./index-m0pwswv9.js";
31
31
 
@@ -20,7 +20,7 @@ import"./index-fb3zxn06.js";
20
20
  import {
21
21
  setSqlitePragmaConfig,
22
22
  initializeDatabase
23
- } from "./index-6rk44cer.js";
23
+ } from "./index-c81tggen.js";
24
24
  import"./index-wh9fxds5.js";
25
25
  import"./index-v0p37hm2.js";
26
26
  import"./index-96ztjvkn.js";
@@ -39,15 +39,15 @@ import {
39
39
  sweepAllRegisteredProjects2,
40
40
  _setTestProviderFactoryForProject2,
41
41
  _resetProjectEmbeddingRegistryForTests2
42
- } from "./index-3n376ann.js";
42
+ } from "./index-tedck05r.js";
43
43
  import"./index-qjwpqvnf.js";
44
44
  import"./index-2amn2s73.js";
45
45
  import"./index-qt1qqasc.js";
46
- import"./index-xn9efn18.js";
47
- import"./index-6nqz8hsz.js";
46
+ import"./index-xjaf9g90.js";
47
+ import"./index-y915t3ey.js";
48
48
  import"./index-r4y0dczp.js";
49
- import"./index-0twg41mh.js";
50
- import"./index-6r99v53h.js";
49
+ import"./index-ejgp0z9p.js";
50
+ import"./index-j7n64sg4.js";
51
51
  import"./index-5pgyqgmx.js";
52
52
  import"./index-s32f8y67.js";
53
53
  import"./index-q7q6qp1f.js";
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-39ye0d3b.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-x62hsr4c.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-pz1jf655.js");
54
+ const { renderSearchArchive } = await import("./search-archive-s9t3exc1.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-3sc9231y.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -65,7 +65,7 @@ serveWorkerJobs(async (input, port) => {
65
65
  openConnections.add(raw);
66
66
  raw.exec("PRAGMA busy_timeout = 250");
67
67
  return readRawSessionMessageIdOrdinalsForRangeFromDb(raw, input.sessionId, archive.start, archive.end);
68
- })
68
+ }, archive.liveTailAfter)
69
69
  };
70
70
  } finally {
71
71
  if (raw)
@@ -81,7 +81,7 @@ serveWorkerJobs(async (input, port) => {
81
81
  const { setHarness } = await import("./harness-e4avh192.js");
82
82
  setHarness(input.harness ?? "opencode");
83
83
  const [{ indexMessageInShortChunks }, { configureContextDatabasePragmas }] = await Promise.all([
84
- import("./message-index-bounded-f6fc00ze.js"),
84
+ import("./message-index-bounded-d3x8rhpz.js"),
85
85
  import("./sqlite-context-pragmas-mv9jqwjh.js")
86
86
  ]);
87
87
  configureContextDatabasePragmas(db);
@@ -95,7 +95,7 @@ serveWorkerJobs(async (input, port) => {
95
95
  measurements: result.measurements
96
96
  };
97
97
  } else if (input.tagRatio !== undefined) {
98
- const { scanTagOwnerSummary, scanTagOwnerDelta } = await import("./storage-tags-7raphcw6.js");
98
+ const { scanTagOwnerSummary, scanTagOwnerDelta } = await import("./storage-tags-xvbje7jm.js");
99
99
  const delta = input.tagState ? scanTagOwnerDelta(db, input.sessionId, input.tagState) : null;
100
100
  if (delta)
101
101
  reply = { kind: "tag-delta", delta };