@cortexkit/opencode-magic-context 0.49.40 → 0.49.42

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 (86) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{compaction-marker-candidates-5p1qkve9.js → compaction-marker-candidates-5c44h1m9.js} +1 -1
  4. package/dist/compaction-marker-candidates-worker.js +1 -1
  5. package/dist/{context-8ktz4j2b.js → context-zf1yj1g0.js} +168 -48
  6. package/dist/features/magic-context/compaction-marker-candidates.d.ts +1 -1
  7. package/dist/features/magic-context/compaction-marker-candidates.d.ts.map +1 -1
  8. package/dist/features/magic-context/compaction-marker.d.ts +1 -1
  9. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  10. package/dist/hooks/magic-context/compaction-marker-publication.d.ts.map +1 -1
  11. package/dist/hooks/magic-context/host-served-rows.d.ts +17 -0
  12. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  13. package/dist/hooks/magic-context/lkg-replay.d.ts +2 -0
  14. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +2 -0
  16. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/transform.d.ts +3 -0
  18. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  19. package/dist/{index-wk7x13qv.js → index-1zv08avf.js} +4 -4
  20. package/dist/{index-4y35msh5.js → index-29gd1zcx.js} +1 -1
  21. package/dist/{index-850vthn3.js → index-3w1pbn85.js} +9 -4
  22. package/dist/{index-m8v7nqgp.js → index-5m2azs6v.js} +3 -3
  23. package/dist/{index-gfd41hm4.js → index-adt3jghq.js} +16 -15
  24. package/dist/{index-hf771sk4.js → index-ayk4we2k.js} +11 -5
  25. package/dist/{index-j5qma52p.js → index-fas76dft.js} +2 -2
  26. package/dist/{index-9z4d2ha0.js → index-gsqz39wk.js} +1 -1
  27. package/dist/{index-9fgmkfaf.js → index-kfsqk1q7.js} +1 -1
  28. package/dist/{index-z7etaphs.js → index-n8bsqg7b.js} +4 -4
  29. package/dist/{index-hb76vdmm.js → index-p2e7j9p1.js} +1 -1
  30. package/dist/{index-72czy45z.js → index-rdx17j04.js} +36 -8
  31. package/dist/{v2/server-z9zygwse.js → index-s9x93tfs.js} +32 -1
  32. package/dist/{index-j105mf16.js → index-xjw9rres.js} +1 -1
  33. package/dist/{index-tr6vcwt0.js → index-xmqj3cf5.js} +126 -27
  34. package/dist/{index-ryz4pdvf.js → index-z6v8086q.js} +2 -2
  35. package/dist/{index-tn9drm1a.js → index-zqsp3z0d.js} +1 -1
  36. package/dist/index.js +18 -18
  37. package/dist/{message-index-bounded-jqm3ezva.js → message-index-bounded-5mj8p6nq.js} +2 -2
  38. package/dist/migration-worker.js +1 -1
  39. package/dist/raw-ordinal-warmup-worker.js +3 -3
  40. package/dist/{read-session-chunk-26yrrhyz.js → read-session-chunk-k70bhfjm.js} +1 -1
  41. package/dist/{recomp-orchestrator-34mh19vm.js → recomp-orchestrator-2q4rmerf.js} +7 -7
  42. package/dist/{render-gqdq6t7f.js → render-36fvvwz6.js} +5 -5
  43. package/dist/{search-vqkmmy9c.js → search-6v2na3af.js} +4 -4
  44. package/dist/{search-archive-kfwpk73t.js → search-archive-jwb2ctnq.js} +3 -3
  45. package/dist/{store-s3eykdjt.js → store-pd1e9hnr.js} +1 -1
  46. package/dist/{transform-postprocess-phase-61f7t9xq.js → transform-postprocess-phase-0ms3ga4h.js} +8 -8
  47. package/dist/v2/auto-search-worker.js +1 -1
  48. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  49. package/dist/v2/{compaction-marker-candidates-yeb2ky46.js → compaction-marker-candidates-jy65jt49.js} +1 -1
  50. package/dist/v2/compaction-marker-candidates-worker.js +1 -1
  51. package/dist/v2/{context-rdch08me.js → context-2xr6vbt2.js} +176 -51
  52. package/dist/v2/fold/code-mode-catalog.d.ts +10 -0
  53. package/dist/v2/fold/code-mode-catalog.d.ts.map +1 -1
  54. package/dist/v2/fold/instruction-supersession.d.ts +9 -0
  55. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -0
  56. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  57. package/dist/v2/hooks/context.d.ts.map +1 -1
  58. package/dist/v2/hooks/payload.d.ts +2 -1
  59. package/dist/v2/hooks/payload.d.ts.map +1 -1
  60. package/dist/v2/{message-index-bounded-dgd8a2x1.js → message-index-bounded-5341qsqd.js} +2 -2
  61. package/dist/v2/migration-worker.js +1 -1
  62. package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
  63. package/dist/v2/{read-session-chunk-tqnh1ret.js → read-session-chunk-dgmq3ntm.js} +1 -1
  64. package/dist/v2/{recomp-orchestrator-x0r6sy3a.js → recomp-orchestrator-2vmyhtst.js} +6 -6
  65. package/dist/v2/{render-yyv8nv4p.js → render-kz0f40ws.js} +5 -5
  66. package/dist/v2/{search-cb1kdgqw.js → search-a9hwy1sw.js} +3 -3
  67. package/dist/v2/{search-archive-gagdnrb3.js → search-archive-wajxd01m.js} +3 -3
  68. package/dist/v2/{server-g3gqq4ac.js → server-09td1wgc.js} +1 -1
  69. package/dist/v2/{server-dt9b00ja.js → server-3m7p4g9w.js} +1 -1
  70. package/dist/v2/{server-405ap0b0.js → server-5ydn39x3.js} +126 -27
  71. package/dist/v2/{server-t8y64xj7.js → server-7qc9tk6z.js} +36 -8
  72. package/dist/v2/{server-r4mmc670.js → server-dqs8e4yt.js} +1 -1
  73. package/dist/v2/{server-r4430x9m.js → server-dwpgzm0t.js} +9 -4
  74. package/dist/v2/{server-jd7vzwn4.js → server-kqrpt2ht.js} +1 -1
  75. package/dist/v2/{server-qjyp27vf.js → server-p78wdf43.js} +1 -1
  76. package/dist/v2/{server-2d01821b.js → server-qehn6btp.js} +2 -2
  77. package/dist/{index-z9zygwse.js → v2/server-s9x93tfs.js} +32 -1
  78. package/dist/v2/{server-2tp6y1qs.js → server-sfcp13bn.js} +4 -4
  79. package/dist/v2/{server-6emy0v9a.js → server-ymn9w46x.js} +1 -1
  80. package/dist/v2/server.js +2 -2
  81. package/dist/v2/{store-z3qe67cg.js → store-pebs9m52.js} +1 -1
  82. package/dist/v2/{v2-archive-reader-2rv5dz7k.js → v2-archive-reader-ag6sk771.js} +1 -1
  83. package/dist/v2/{wrapup-orchestrator-f8w3kcjf.js → wrapup-orchestrator-2a077zew.js} +6 -6
  84. package/dist/{v2-archive-reader-4hz9pnmy.js → v2-archive-reader-chk95syc.js} +1 -1
  85. package/dist/{wrapup-orchestrator-7dxwer1p.js → wrapup-orchestrator-rhs675kj.js} +8 -8
  86. package/package.json +1 -1
@@ -7,22 +7,22 @@ import {
7
7
  setRecompTerminal2,
8
8
  buildRecompDeps2,
9
9
  runManagedRecomp2
10
- } from "./server-405ap0b0.js";
11
- import"./server-r4430x9m.js";
10
+ } from "./server-5ydn39x3.js";
11
+ import"./server-dwpgzm0t.js";
12
12
  import"./server-nq3cb7be.js";
13
13
  import"./server-gkse1wyz.js";
14
14
  import"./server-jjvbk92s.js";
15
15
  import"./server-7acq7815.js";
16
16
  import"./server-4dhv7mqz.js";
17
- import"./server-t8y64xj7.js";
17
+ import"./server-7qc9tk6z.js";
18
18
  import"./server-ypf1ap0v.js";
19
- import"./server-dt9b00ja.js";
19
+ import"./server-3m7p4g9w.js";
20
20
  import"./server-2amn2s73.js";
21
21
  import"./server-ef1mskas.js";
22
22
  import"./server-sd8hvzte.js";
23
23
  import"./server-bez34e60.js";
24
24
  import"./server-qt1qqasc.js";
25
- import"./server-jd7vzwn4.js";
25
+ import"./server-kqrpt2ht.js";
26
26
  import"./server-xfjjbrkt.js";
27
27
  import"./server-1zx87sdm.js";
28
28
  import"./server-mfn1yf9d.js";
@@ -35,7 +35,7 @@ import"./server-7zacmty5.js";
35
35
  import"./server-dcws5831.js";
36
36
  import"./server-cp1a03vc.js";
37
37
  import"./server-zzgtgqmd.js";
38
- import"./server-g3gqq4ac.js";
38
+ import"./server-09td1wgc.js";
39
39
  import"./server-fb3zxn06.js";
40
40
  import"./server-3schkz95.js";
41
41
  import"./server-fr0wbhdn.js";
@@ -2,20 +2,20 @@ import {
2
2
  renderMessageByOrdinal2,
3
3
  renderVerboseRangeForTool2,
4
4
  renderItemByTag2
5
- } from "./server-qjyp27vf.js";
6
- import"./server-t8y64xj7.js";
5
+ } from "./server-p78wdf43.js";
6
+ import"./server-7qc9tk6z.js";
7
7
  import"./server-ypf1ap0v.js";
8
- import"./server-dt9b00ja.js";
8
+ import"./server-3m7p4g9w.js";
9
9
  import"./server-2amn2s73.js";
10
10
  import"./server-ef1mskas.js";
11
- import"./server-jd7vzwn4.js";
11
+ import"./server-kqrpt2ht.js";
12
12
  import"./server-xfjjbrkt.js";
13
13
  import"./server-1zx87sdm.js";
14
14
  import"./server-mfn1yf9d.js";
15
15
  import"./server-7zacmty5.js";
16
16
  import"./server-cp1a03vc.js";
17
17
  import"./server-zzgtgqmd.js";
18
- import"./server-g3gqq4ac.js";
18
+ import"./server-09td1wgc.js";
19
19
  import"./server-fb3zxn06.js";
20
20
  import"./server-3schkz95.js";
21
21
  import"./server-fr0wbhdn.js";
@@ -5,7 +5,7 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./server-r4mmc670.js";
8
+ } from "./server-dqs8e4yt.js";
9
9
  import"./server-kaqs6h31.js";
10
10
  import"./server-nq3cb7be.js";
11
11
  import"./server-gkse1wyz.js";
@@ -13,10 +13,10 @@ import"./server-jjvbk92s.js";
13
13
  import"./server-7acq7815.js";
14
14
  import"./server-4dhv7mqz.js";
15
15
  import"./server-ypf1ap0v.js";
16
- import"./server-dt9b00ja.js";
16
+ import"./server-3m7p4g9w.js";
17
17
  import"./server-2amn2s73.js";
18
18
  import"./server-qt1qqasc.js";
19
- import"./server-jd7vzwn4.js";
19
+ import"./server-kqrpt2ht.js";
20
20
  import"./server-xfjjbrkt.js";
21
21
  import"./server-1zx87sdm.js";
22
22
  import"./server-mfn1yf9d.js";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  renderSearchArchive2,
3
3
  renderSearchArchiveOffThread2
4
- } from "./server-2d01821b.js";
5
- import"./server-2tp6y1qs.js";
4
+ } from "./server-qehn6btp.js";
5
+ import"./server-sfcp13bn.js";
6
6
  import"./server-kaqs6h31.js";
7
- import"./server-jd7vzwn4.js";
7
+ import"./server-kqrpt2ht.js";
8
8
  import"./server-xfjjbrkt.js";
9
9
  import"./server-1zx87sdm.js";
10
10
  import"./server-mfn1yf9d.js";
@@ -1022,7 +1022,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1022
1022
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1023
1023
  if (signal.aborted || !readsOpenCodeStore)
1024
1024
  return;
1025
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-tqnh1ret.js"));
1025
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-dgmq3ntm.js"));
1026
1026
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-0c4h7sg6.js"));
1027
1027
  if (signal.aborted)
1028
1028
  return;
@@ -9,7 +9,7 @@ import {
9
9
  } from "./server-pavzsdc6.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./server-jd7vzwn4.js";
12
+ } from "./server-kqrpt2ht.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -152,7 +152,7 @@ import {
152
152
  getRawSessionTagKeysThrough2,
153
153
  getLegacyProtectedTailStartOrdinal2,
154
154
  readSessionChunk2
155
- } from "./server-jd7vzwn4.js";
155
+ } from "./server-kqrpt2ht.js";
156
156
  import {
157
157
  BoundedSessionMap
158
158
  } from "./server-xy7w7hrd.js";
@@ -162,7 +162,7 @@ import {
162
162
  toMessageIndexSource,
163
163
  clearIndexedMessagesInTransaction,
164
164
  indexSourcesAfterOrdinal
165
- } from "./server-dt9b00ja.js";
165
+ } from "./server-3m7p4g9w.js";
166
166
  import {
167
167
  COMPARTMENT_LEASE_RENEWAL_MS,
168
168
  getCompartmentLeaseBlocker,
@@ -206,7 +206,7 @@ import {
206
206
  getProjectState,
207
207
  recordSubagentInvocation,
208
208
  getLatestHistorianInvocationId
209
- } from "./server-t8y64xj7.js";
209
+ } from "./server-7qc9tk6z.js";
210
210
  import {
211
211
  invalidateAutoEmbedSession
212
212
  } from "./server-2amn2s73.js";
@@ -225,7 +225,7 @@ import {
225
225
  invalidateMarkerCandidateBasis2,
226
226
  readMarkerCandidateBasis2,
227
227
  prepareMarkerCandidateBasis2
228
- } from "./server-r4430x9m.js";
228
+ } from "./server-dwpgzm0t.js";
229
229
  import {
230
230
  shouldSkipHomeProjectMemory,
231
231
  resolveProjectIdentity
@@ -261,7 +261,7 @@ import {
261
261
  LATEST_SUPPORTED_VERSION,
262
262
  getPersistedSchemaVersion,
263
263
  openDatabase
264
- } from "./server-g3gqq4ac.js";
264
+ } from "./server-09td1wgc.js";
265
265
  import {
266
266
  parseCompartmentOutput,
267
267
  resolveWorkspaceShareCategories,
@@ -295,7 +295,7 @@ import {
295
295
  snapTerminalCompartmentToServedRow,
296
296
  isHostRenderedSystemMessage,
297
297
  markCoveredInstructionRow
298
- } from "./server-z9zygwse.js";
298
+ } from "./server-s9x93tfs.js";
299
299
  import {
300
300
  piModelRefToCanonical
301
301
  } from "./server-avwt563y.js";
@@ -1350,6 +1350,7 @@ function getOpenCodeDbPath() {
1350
1350
  }
1351
1351
  var cachedWriteDb = null;
1352
1352
  var cachedRemovalDb = null;
1353
+ var cachedSnapshotDb = null;
1353
1354
  var MARKER_BUSY_TIMEOUT_MS = 250;
1354
1355
  var MARKER_REMOVAL_BUSY_TIMEOUT_MS = 5000;
1355
1356
  function runMarkerRemovalTransaction(db, operation) {
@@ -1383,7 +1384,7 @@ function runMarkerWriteTransaction(db, site, operation) {
1383
1384
  try {
1384
1385
  log2(`[magic-context] sqlite writer site=${site} db=opencode acquire_ms=${Math.round(acquireMs)} hold_ms=${Math.round(holdMs)} work_ms=${Math.round(workMs)} end_ms=${Math.round(endMs)} outcome=${acquiredAt === undefined ? "not_acquired" : committed ? "committed" : "failed"}`);
1385
1386
  if (finishedAt - startedAt > 100) {
1386
- const autoCheckpoint = db.prepare("PRAGMA wal_autocheckpoint").get();
1387
+ const autoCheckpoint = db.prepare("PRAGMA wal_autocheckpoint").all()[0];
1387
1388
  log2(`[magic-context] compaction-marker slow writer site=${site} acquire_ms=${acquireMs.toFixed(1)} statements_ms=${workMs.toFixed(1)} ${committed ? "commit" : "rollback"}_ms=${endMs.toFixed(1)} wal_autocheckpoint=${autoCheckpoint.wal_autocheckpoint} wal_pages_before=${walBefore ?? "unknown"} wal_pages_after=${markerWalPages(db) ?? "unknown"}`);
1388
1389
  }
1389
1390
  } catch {}
@@ -1391,7 +1392,7 @@ function runMarkerWriteTransaction(db, site, operation) {
1391
1392
  }
1392
1393
  function markerWalPages(db) {
1393
1394
  try {
1394
- const row = db.prepare("PRAGMA page_size").get();
1395
+ const row = db.prepare("PRAGMA page_size").all()[0];
1395
1396
  const bytes = statSync2(`${getOpenCodeDbPath()}-wal`).size;
1396
1397
  return Math.max(0, Math.floor((bytes - 32) / (row.page_size + 24)));
1397
1398
  } catch {
@@ -1563,8 +1564,18 @@ function isCompactionMarkerIntentAbsent(marker, targetEndMessageId) {
1563
1564
  return !db.prepare(`SELECT 1 FROM message WHERE id IN (?, ?)
1564
1565
  UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(targetEndMessageId, marker.summaryMessageId, marker.compactionPartId, marker.summaryPartId);
1565
1566
  }
1566
- function withCompactionMarkerPublicationLock(operation) {
1567
- return runMarkerWriteTransaction(getWritableOpenCodeDb(), "compaction-marker-replace", operation);
1567
+ function withCompactionMarkerPublicationLock(operation, sessionId) {
1568
+ const db = getWritableOpenCodeDb();
1569
+ const snapshot = prepareMarkerReplacementSnapshot(db, sessionId);
1570
+ return runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
1571
+ if (snapshot)
1572
+ activeMarkerReplacementSnapshots.set(db, snapshot);
1573
+ try {
1574
+ return operation();
1575
+ } finally {
1576
+ activeMarkerReplacementSnapshots.delete(db);
1577
+ }
1578
+ });
1568
1579
  }
1569
1580
  function inspectCompactionMarkerPublication(sessionId, recognized, summaryText, targetBoundaryMessageId, preferred) {
1570
1581
  const db = getWritableOpenCodeDb();
@@ -1724,6 +1735,11 @@ function injectCompactionMarkerFromBasis(args, validatedBasis, preserveExistingL
1724
1735
  summaryMessageId: summaryMsgId,
1725
1736
  compactionPartId
1726
1737
  });
1738
+ const discovered = markerReplacementSnapshots.get(db)?.get(args.sessionId);
1739
+ if (discovered && !discovered.partIds.includes(compactionPartId))
1740
+ discovered.partIds.push(compactionPartId);
1741
+ if (discovered && !discovered.messageIds.includes(summaryMsgId))
1742
+ discovered.messageIds.push(summaryMsgId);
1727
1743
  db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data)
1728
1744
  VALUES (?, ?, ?, ?, ?, ?)
1729
1745
  ON CONFLICT(id) DO UPDATE SET
@@ -1765,6 +1781,100 @@ function injectCompactionMarkerFromBasis(args, validatedBasis, preserveExistingL
1765
1781
 
1766
1782
  class MarkerCandidateUnavailableError extends Error {
1767
1783
  }
1784
+ var activeMarkerReplacementSnapshots = new WeakMap;
1785
+ var markerReplacementSnapshots = new WeakMap;
1786
+ var MARKER_TAIL_REFERENCE_COLUMNS = `id,
1787
+ CASE WHEN data LIKE '%tail_start_id%' THEN json_extract(data, '$.tail_start_id') END AS direct,
1788
+ CASE WHEN data LIKE '%tail_start_id%' THEN json_extract(data, '$.compaction.tail_start_id') END AS nested`;
1789
+ function readMarkerReferenceRows(db, sessionId, table, highestId) {
1790
+ return db.prepare(`SELECT ${MARKER_TAIL_REFERENCE_COLUMNS} FROM ${table}
1791
+ WHERE ${highestId === undefined ? "session_id = ?" : "id > ? AND +session_id = ?"}
1792
+ AND ${table === "part" ? "data LIKE '%compaction%' AND json_valid(data) AND json_extract(data, '$.type') = 'compaction'" : "(data LIKE '%compaction%' OR data LIKE '%tail_start_id%') AND json_valid(data) AND (json_type(data, '$.compaction') IS NOT NULL OR json_type(data, '$.tail_start_id') IS NOT NULL)"}`).all(...highestId === undefined ? [sessionId] : [highestId, sessionId]);
1793
+ }
1794
+ function readKnownMarkerReferenceRows(db, sessionId, table, ids) {
1795
+ const byId = db.prepare(`SELECT ${MARKER_TAIL_REFERENCE_COLUMNS} FROM ${table} WHERE id = ? AND session_id = ?`);
1796
+ return ids.flatMap((id) => byId.all(id, sessionId));
1797
+ }
1798
+ function prepareMarkerReplacementSnapshot(db, sessionId) {
1799
+ const sessions = markerReplacementSnapshots.get(db) ?? new Map;
1800
+ markerReplacementSnapshots.set(db, sessions);
1801
+ if (db.inTransaction) {
1802
+ sessions.delete(sessionId);
1803
+ return;
1804
+ }
1805
+ try {
1806
+ if (cachedSnapshotDb?.writer !== db) {
1807
+ if (cachedSnapshotDb)
1808
+ closeQuietly(cachedSnapshotDb.db);
1809
+ const reader = new Database2(getOpenCodeDbPath(), {
1810
+ readonly: true,
1811
+ fileMustExist: true
1812
+ });
1813
+ reader.exec(`PRAGMA busy_timeout=${MARKER_BUSY_TIMEOUT_MS}`);
1814
+ cachedSnapshotDb = { writer: db, db: reader };
1815
+ }
1816
+ const reader = cachedSnapshotDb.db;
1817
+ reader.exec("BEGIN");
1818
+ let snapshot;
1819
+ try {
1820
+ const basis = readMarkerCandidateBasis2(db, sessionId, reader);
1821
+ if (!basis) {
1822
+ sessions.delete(sessionId);
1823
+ return;
1824
+ }
1825
+ const previous = sessions.get(sessionId);
1826
+ const highestId = (table) => reader.prepare(`SELECT id FROM ${table} ORDER BY id DESC LIMIT 1`).all()[0]?.id ?? "";
1827
+ const discover = (table, ids, highest) => previous ? [
1828
+ ...new Map([
1829
+ ...readKnownMarkerReferenceRows(reader, sessionId, table, ids),
1830
+ ...readMarkerReferenceRows(reader, sessionId, table, highest)
1831
+ ].map((row) => [row.id, row])).values()
1832
+ ] : readMarkerReferenceRows(reader, sessionId, table);
1833
+ const parts = discover("part", previous?.partIds ?? [], previous?.highestPartId ?? "");
1834
+ const messages = discover("message", previous?.messageIds ?? [], previous?.highestMessageId ?? "");
1835
+ snapshot = {
1836
+ sessionId,
1837
+ basis,
1838
+ partIds: parts.map((row) => row.id),
1839
+ messageIds: messages.map((row) => row.id),
1840
+ highestPartId: highestId("part"),
1841
+ highestMessageId: highestId("message"),
1842
+ references: [...parts, ...messages]
1843
+ };
1844
+ } finally {
1845
+ reader.exec("ROLLBACK");
1846
+ }
1847
+ sessions.set(sessionId, snapshot);
1848
+ return snapshot;
1849
+ } catch (error) {
1850
+ markerReplacementSnapshots.delete(db);
1851
+ if (cachedSnapshotDb?.writer === db) {
1852
+ closeQuietly(cachedSnapshotDb.db);
1853
+ cachedSnapshotDb = null;
1854
+ }
1855
+ throw error;
1856
+ }
1857
+ }
1858
+ function markerRowsAreReferenced(db, snapshot, existing) {
1859
+ const deleted = new Set([
1860
+ existing.summaryMessageId,
1861
+ existing.summaryPartId,
1862
+ existing.compactionPartId
1863
+ ]);
1864
+ const referencesDeleted = (row) => !deleted.has(row.id) && [row.direct, row.nested].some((id) => typeof id === "string" && deleted.has(id));
1865
+ if (snapshot.references.some(referencesDeleted))
1866
+ throw new Error("a surviving tail_start_id references a recorded marker row; marker unchanged");
1867
+ for (const [table, ids, highestId] of [
1868
+ ["part", snapshot.partIds, snapshot.highestPartId],
1869
+ ["message", snapshot.messageIds, snapshot.highestMessageId]
1870
+ ]) {
1871
+ if (readKnownMarkerReferenceRows(db, snapshot.sessionId, table, ids).some(referencesDeleted))
1872
+ return true;
1873
+ if (readMarkerReferenceRows(db, snapshot.sessionId, table, highestId).some(referencesDeleted))
1874
+ return true;
1875
+ }
1876
+ return false;
1877
+ }
1768
1878
  function replaceCompactionMarker(existing, args, preserveExistingLineages = false) {
1769
1879
  let connection;
1770
1880
  let entered = false;
@@ -1772,32 +1882,21 @@ function replaceCompactionMarker(existing, args, preserveExistingLineages = fals
1772
1882
  try {
1773
1883
  const db = getWritableOpenCodeDb();
1774
1884
  connection = db;
1775
- const basis = readMarkerCandidateBasis2(db, args.sessionId);
1776
- if (!basis) {
1885
+ const snapshot = activeMarkerReplacementSnapshots.get(db) ?? prepareMarkerReplacementSnapshot(db, args.sessionId);
1886
+ if (!snapshot || snapshot.sessionId !== args.sessionId) {
1777
1887
  return {
1778
1888
  kind: "deferred",
1779
1889
  error: new Error("marker candidate preparation pending; marker unchanged")
1780
1890
  };
1781
1891
  }
1892
+ const { basis } = snapshot;
1782
1893
  const marker = runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
1783
1894
  entered = true;
1784
1895
  if (!isMarkerCandidateBasisCurrent2(db, basis))
1785
1896
  throw new MarkerCandidateUnavailableError("host store changed after marker candidate preparation; marker unchanged");
1786
1897
  if (existing) {
1787
- const referenced = db.prepare(`WITH deleted(id) AS (VALUES (?), (?), (?)), surviving(data) AS (
1788
- SELECT data FROM part WHERE session_id = ?
1789
- AND id NOT IN (SELECT id FROM deleted)
1790
- AND json_extract(data, '$.type') = 'compaction'
1791
- UNION ALL
1792
- SELECT data FROM message WHERE session_id = ?
1793
- AND id NOT IN (SELECT id FROM deleted)
1794
- )
1795
- SELECT 1 FROM surviving
1796
- WHERE json_extract(data, '$.tail_start_id') IN (SELECT id FROM deleted)
1797
- OR json_extract(data, '$.compaction.tail_start_id') IN (SELECT id FROM deleted)
1798
- LIMIT 1`).get(existing.summaryMessageId, existing.summaryPartId, existing.compactionPartId, args.sessionId, args.sessionId);
1799
- if (referenced)
1800
- throw new Error("a surviving tail_start_id references a recorded marker row; marker unchanged");
1898
+ if (markerRowsAreReferenced(db, snapshot, existing))
1899
+ throw new MarkerCandidateUnavailableError("a surviving tail_start_id references a recorded marker row; marker unchanged");
1801
1900
  db.prepare("DELETE FROM part WHERE id = ?").run(existing.summaryPartId);
1802
1901
  db.prepare("DELETE FROM message WHERE id = ?").run(existing.summaryMessageId);
1803
1902
  db.prepare("DELETE FROM part WHERE id = ?").run(existing.compactionPartId);
@@ -4487,7 +4586,7 @@ function publishRecoverableCompactionMarker(db, args, targetIsCurrent) {
4487
4586
  if (replacement.kind !== "committed")
4488
4587
  cut = replacement.kind === "uncertain" ? "uncertain" : "definitely-no-cut";
4489
4588
  return replacement;
4490
- });
4589
+ }, sessionId);
4491
4590
  if (result.kind === "committed") {
4492
4591
  if (!intended)
4493
4592
  throw new Error("committed marker has no publication intent");
@@ -53,7 +53,7 @@ import {
53
53
  serializeProcessedImageMarkers,
54
54
  getPendingPiCompactionMarkerState,
55
55
  logPiCompactionMarkerClear
56
- } from "./server-jd7vzwn4.js";
56
+ } from "./server-kqrpt2ht.js";
57
57
  import {
58
58
  getTableColumnNames,
59
59
  tagTombstoneOwnerRange,
@@ -83,9 +83,12 @@ import {
83
83
  V2StoreReader2
84
84
  } from "./server-ef1mskas.js";
85
85
  import {
86
+ markHostInstructionRow,
87
+ hostInstructionRowID,
88
+ isRetiredInstructionRow,
86
89
  markCoveredInstructionRow,
87
90
  isCoveredInstructionRow
88
- } from "./server-z9zygwse.js";
91
+ } from "./server-s9x93tfs.js";
89
92
  import {
90
93
  piModelRefToCanonical
91
94
  } from "./server-avwt563y.js";
@@ -2218,6 +2221,15 @@ function projectEntryWithDigests(messages, digests) {
2218
2221
  });
2219
2222
  if (isCoveredInstructionRow(message.info))
2220
2223
  markCoveredInstructionRow(projection);
2224
+ const instructionID = hostInstructionRowID(message.info);
2225
+ if (instructionID) {
2226
+ markHostInstructionRow(projection, { id: instructionID });
2227
+ const retiredDigest = lkgContentDigest({ ...message, parts: [] });
2228
+ Object.defineProperty(projection, "retiredContentDigest", {
2229
+ value: () => retiredDigest,
2230
+ enumerable: false
2231
+ });
2232
+ }
2221
2233
  return projection;
2222
2234
  });
2223
2235
  }
@@ -2327,7 +2339,7 @@ function outputMessageIsPostAnchor(message, inputIndexById, anchorIndex, systemI
2327
2339
  }
2328
2340
  function buildLkgPrefix(input, output, completeOutput = false) {
2329
2341
  const projected = asEntryProjection(input);
2330
- const anchorIndex = completeOutput && projected.length > 0 ? projected.length - 1 : findLkgAnchor(projected);
2342
+ let anchorIndex = completeOutput && projected.length > 0 ? projected.length - 1 : findLkgAnchor(projected);
2331
2343
  if (anchorIndex === null)
2332
2344
  return null;
2333
2345
  const ids = projected.map((message, index) => lkgInputIdentity(message.id, message.role, index));
@@ -2336,10 +2348,6 @@ function buildLkgPrefix(input, output, completeOutput = false) {
2336
2348
  const validIds = ids;
2337
2349
  if (new Set(validIds).size !== validIds.length)
2338
2350
  return null;
2339
- const anchorMessageId = validIds[anchorIndex];
2340
- const inputContentDigests = projected.slice(0, anchorIndex + 1).map((message) => message.contentDigest?.() ?? null);
2341
- if (inputContentDigests.some((digest) => digest === null))
2342
- return null;
2343
2351
  const inputIndexById = new Map(validIds.map((id, index) => [id, index]));
2344
2352
  const systemIndices = new Map;
2345
2353
  if (!completeOutput) {
@@ -2348,22 +2356,42 @@ function buildLkgPrefix(input, output, completeOutput = false) {
2348
2356
  const restoredCount = outputSystems.length - inputSystems.length;
2349
2357
  if (restoredCount < 0 || outputSystems.slice(0, restoredCount).some((message) => !isCoveredInstructionRow(message.info)))
2350
2358
  return null;
2359
+ let retirementAnchor = anchorIndex;
2360
+ let retirementExtensionValid = true;
2351
2361
  for (let index = 0;index < inputSystems.length; index += 1) {
2352
2362
  const source = inputSystems[index];
2353
2363
  const message = outputSystems[index + restoredCount];
2354
2364
  const digest = source.message.contentDigest?.();
2355
- if (!digest || lkgContentDigest(message) !== digest)
2365
+ const servedDigest = lkgContentDigest(message);
2366
+ const sourceID = hostInstructionRowID(source.message);
2367
+ const expectedDigest = isRetiredInstructionRow(message.info) ? sourceID && hostInstructionRowID(message.info) === sourceID ? source.message.retiredContentDigest?.() : undefined : digest;
2368
+ if (!digest)
2356
2369
  return null;
2370
+ if (!expectedDigest || servedDigest !== expectedDigest) {
2371
+ if (!isRetiredInstructionRow(message.info) || source.index <= anchorIndex)
2372
+ return null;
2373
+ retirementExtensionValid = false;
2374
+ } else if (isRetiredInstructionRow(message.info)) {
2375
+ retirementAnchor = Math.max(retirementAnchor, source.index);
2376
+ }
2357
2377
  if (isCoveredInstructionRow(message.info) && source.index > anchorIndex)
2358
2378
  return null;
2359
2379
  systemIndices.set(message, source.index);
2360
2380
  }
2381
+ if (retirementExtensionValid)
2382
+ anchorIndex = retirementAnchor;
2361
2383
  }
2384
+ const anchorMessageId = validIds[anchorIndex];
2385
+ const inputContentDigests = projected.slice(0, anchorIndex + 1).map((message) => message.contentDigest?.() ?? null);
2386
+ if (inputContentDigests.some((digest) => digest === null))
2387
+ return null;
2362
2388
  const prefix = [];
2363
2389
  for (const message of output) {
2364
2390
  const postAnchor = completeOutput ? false : outputMessageIsPostAnchor(message, inputIndexById, anchorIndex, systemIndices);
2365
2391
  if (postAnchor === null)
2366
2392
  return null;
2393
+ if (isRetiredInstructionRow(message.info) && messageRole(message) === "system" && messageParts(message).length === 0)
2394
+ continue;
2367
2395
  if (!postAnchor)
2368
2396
  prefix.push(providerVisibleMessage(message));
2369
2397
  }
@@ -25,7 +25,7 @@ import {
25
25
  isMessageIndexReconciledThrough,
26
26
  clearIndexedMessages,
27
27
  indexMessagesAfterOrdinal
28
- } from "./server-dt9b00ja.js";
28
+ } from "./server-3m7p4g9w.js";
29
29
  import {
30
30
  Priority,
31
31
  AdmissionClass,
@@ -43,7 +43,7 @@ function isMarkerCandidateBasisCurrent2(db, basis) {
43
43
  if (basis.connection !== db || ownWriteRevisions.get(basis.revisionKey) !== basis.ownWriteRevision)
44
44
  return false;
45
45
  try {
46
- const current = db.prepare(MARKER_CERTIFICATION_SQL).get(basis.frontier?.id ?? null, basis.frontier?.rowid ?? 0, basis.sessionId);
46
+ const current = db.prepare(MARKER_CERTIFICATION_SQL).all(basis.frontier?.id ?? null, basis.frontier?.rowid ?? 0, basis.sessionId)[0];
47
47
  if (current.newSummary || basis.frontier && (current.previousRowid !== basis.frontier.rowid || current.newestRowid === null || current.newestRowid < basis.frontier.rowid))
48
48
  return false;
49
49
  if (current.newestRowid !== null && (!Number.isSafeInteger(current.newestRowid) || current.newestId === null))
@@ -64,10 +64,15 @@ function invalidateMarkerCandidateBasis2(db, sessionId) {
64
64
  if (revision !== undefined)
65
65
  ownWriteRevisions.set(key, revision + 1);
66
66
  }
67
- function readMarkerCandidateBasis2(db, sessionId) {
67
+ function readMarkerCandidateBasis2(db, sessionId, readConnection = db) {
68
68
  const basis = candidates.get(db)?.get(sessionId);
69
- if (basis && isMarkerCandidateBasisCurrent2(db, basis))
70
- return basis;
69
+ if (basis) {
70
+ const snapshot = readConnection === db ? basis : { ...basis, connection: readConnection };
71
+ if (isMarkerCandidateBasisCurrent2(readConnection, snapshot)) {
72
+ basis.frontier = snapshot.frontier;
73
+ return readConnection === db ? basis : { ...snapshot, connection: db };
74
+ }
75
+ }
71
76
  candidates.get(db)?.delete(sessionId);
72
77
  return;
73
78
  }
@@ -85,7 +85,7 @@ import {
85
85
  import {
86
86
  markHostUnservedRow,
87
87
  isHostUnservedRow
88
- } from "./server-z9zygwse.js";
88
+ } from "./server-s9x93tfs.js";
89
89
  import {
90
90
  canonicalModelIdentity,
91
91
  piModelRefToCanonical
@@ -5,7 +5,7 @@ import {
5
5
  expandToolPart,
6
6
  visitRawSessionMessages2,
7
7
  readRawSessionMessageById2
8
- } from "./server-jd7vzwn4.js";
8
+ } from "./server-kqrpt2ht.js";
9
9
  import {
10
10
  getTagById2
11
11
  } from "./server-xfjjbrkt.js";
@@ -19,10 +19,10 @@ import {
19
19
  rawMessageWorkerSource2,
20
20
  rawMessageOffThreadRangeReader2,
21
21
  readRawSessionMessageIdOrdinalsForRange2
22
- } from "./server-jd7vzwn4.js";
22
+ } from "./server-kqrpt2ht.js";
23
23
  import {
24
24
  readV2ArchiveOffThread2
25
- } from "./server-2tp6y1qs.js";
25
+ } from "./server-sfcp13bn.js";
26
26
 
27
27
  // src/tools/ctx-expand/search-archive.ts
28
28
  var archiveReadsOnThisThread = 0;
@@ -57,6 +57,32 @@ function isHostRenderedSystemMessage(message) {
57
57
  return (typeof id !== "string" || id.length === 0) && message.info.role === "system";
58
58
  }
59
59
  var COVERED_INSTRUCTION_ROW = "coveredInstructionRow";
60
+ var HOST_INSTRUCTION_ROW = "hostInstructionRow";
61
+ var RETIRED_INSTRUCTION_ROW = "retiredInstructionRow";
62
+ function markHostInstructionRow(target, row) {
63
+ Object.defineProperty(target, HOST_INSTRUCTION_ROW, {
64
+ value: row,
65
+ enumerable: false,
66
+ configurable: true
67
+ });
68
+ }
69
+ function hostInstructionRow(target) {
70
+ return target[HOST_INSTRUCTION_ROW];
71
+ }
72
+ function hostInstructionRowID(target) {
73
+ const row = hostInstructionRow(target);
74
+ return typeof row?.id === "string" && row.id.length > 0 ? row.id : undefined;
75
+ }
76
+ function markRetiredInstructionRow(target) {
77
+ Object.defineProperty(target, RETIRED_INSTRUCTION_ROW, {
78
+ value: true,
79
+ enumerable: false,
80
+ configurable: true
81
+ });
82
+ }
83
+ function isRetiredInstructionRow(target) {
84
+ return target[RETIRED_INSTRUCTION_ROW] === true;
85
+ }
60
86
  function markCoveredInstructionRow(target) {
61
87
  Object.defineProperty(target, COVERED_INSTRUCTION_ROW, {
62
88
  value: true,
@@ -82,8 +108,13 @@ function cloneKeepingCoveredInstructionMarks(messages) {
82
108
  const copied = copy[index];
83
109
  if (copied && isCoveredInstructionRow(message.info))
84
110
  markCoveredInstructionRow(copied.info);
111
+ const row = hostInstructionRow(message.info);
112
+ if (copied && row !== undefined)
113
+ markHostInstructionRow(copied.info, row);
114
+ if (copied && isRetiredInstructionRow(message.info))
115
+ markRetiredInstructionRow(copied.info);
85
116
  });
86
117
  return copy;
87
118
  }
88
119
 
89
- export { markHostUnservedRow, isHostUnservedRow, retreatPastHostUnservedRows, snapTerminalCompartmentToServedRow, isHostRenderedSystemMessage, markCoveredInstructionRow, isCoveredInstructionRow, takeCoveredInstructionRows, cloneKeepingCoveredInstructionMarks };
120
+ export { markHostUnservedRow, isHostUnservedRow, retreatPastHostUnservedRows, snapTerminalCompartmentToServedRow, isHostRenderedSystemMessage, markHostInstructionRow, hostInstructionRow, hostInstructionRowID, markRetiredInstructionRow, isRetiredInstructionRow, markCoveredInstructionRow, isCoveredInstructionRow, takeCoveredInstructionRows, cloneKeepingCoveredInstructionMarks };
@@ -138,10 +138,10 @@ async function serveV2ArchiveReads2(port, openConnections) {
138
138
  ] = await Promise.all([
139
139
  import("./sqlite-zdgm52sv.js"),
140
140
  import("./store-reader-cgx47zkp.js"),
141
- import("./store-z3qe67cg.js"),
142
- import("./read-session-chunk-tqnh1ret.js"),
143
- import("./render-yyv8nv4p.js"),
144
- import("./search-archive-gagdnrb3.js"),
141
+ import("./store-pebs9m52.js"),
142
+ import("./read-session-chunk-dgmq3ntm.js"),
143
+ import("./render-kz0f40ws.js"),
144
+ import("./search-archive-wajxd01m.js"),
145
145
  import("./expand-attachments-h33jbgyz.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -6,7 +6,7 @@ import {
6
6
  } from "./server-ef1mskas.js";
7
7
  import {
8
8
  markHostUnservedRow
9
- } from "./server-z9zygwse.js";
9
+ } from "./server-s9x93tfs.js";
10
10
 
11
11
  // src/v2/tool-result.ts
12
12
  function isToolError(part) {
package/dist/v2/server.js CHANGED
@@ -7875,7 +7875,7 @@ var require_src2 = __commonJS(function(exports, module) {
7875
7875
  // package.json
7876
7876
  var package_default = {
7877
7877
  name: "@cortexkit/opencode-magic-context",
7878
- version: "0.49.40",
7878
+ version: "0.49.42",
7879
7879
  type: "module",
7880
7880
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
7881
7881
  main: "dist/index.js",
@@ -8196,7 +8196,7 @@ async function setup(context) {
8196
8196
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
8197
8197
  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.`);
8198
8198
  }
8199
- const { registerContext } = await import("./context-rdch08me.js");
8199
+ const { registerContext } = await import("./context-2xr6vbt2.js");
8200
8200
  setHarness2("opencode2");
8201
8201
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
8202
8202
  const duties = await registerContext(context);
@@ -5,7 +5,7 @@ import {
5
5
  readV2RawMessagePagesForConversion2,
6
6
  createV2RawMessageReader2,
7
7
  createV2RawMessageProvider2
8
- } from "./server-6emy0v9a.js";
8
+ } from "./server-ymn9w46x.js";
9
9
  import"./server-ef1mskas.js";
10
10
  import"./server-468mya5v.js";
11
11
  import"./server-2ra6pwf3.js";