@cortexkit/pi-magic-context 0.49.43 → 0.49.44

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 (32) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{compaction-marker-candidates-8qhackvy.js → compaction-marker-candidates-17a21jfn.js} +12 -2
  4. package/dist/compaction-marker-candidates-worker.js +5 -2
  5. package/dist/{embedding-backfill-002vyexq.js → embedding-backfill-v9b8gkmp.js} +4 -4
  6. package/dist/embedding-worker.js +2 -2
  7. package/dist/{index-j0h89gxy.js → index-025nxwc9.js} +1 -1
  8. package/dist/{index-p8jpbrj4.js → index-2kmwjq42.js} +64 -12
  9. package/dist/{index-z7dktknj.js → index-9tcbabqr.js} +2 -2
  10. package/dist/{index-6cvt64cn.js → index-fjmghcbx.js} +137 -52
  11. package/dist/{index-jbkwszd5.js → index-gajhgp4k.js} +3 -3
  12. package/dist/{index-k0csz6pb.js → index-gg9r701n.js} +3 -3
  13. package/dist/{index-p9jfa33t.js → index-gtd9kaaf.js} +3 -3
  14. package/dist/{index-ccanzg8p.js → index-gzk7d940.js} +1 -1
  15. package/dist/{index-mx757f3g.js → index-j2x88zk0.js} +1 -1
  16. package/dist/{index-a7sj2bam.js → index-p1jxxsth.js} +1 -1
  17. package/dist/{index-ry84c8dr.js → index-pb0ygvpa.js} +1 -1
  18. package/dist/{index-2qqsnh1b.js → index-xf3ndcqd.js} +1 -1
  19. package/dist/{index-g2j58qpq.js → index-zttw4vew.js} +3 -3
  20. package/dist/index.js +22 -55
  21. package/dist/{message-index-bounded-39z2atfj.js → message-index-bounded-1gj1pwjy.js} +3 -3
  22. package/dist/migration-worker.js +1 -1
  23. package/dist/{project-embedding-registry-16pj4vyf.js → project-embedding-registry-e81zewts.js} +3 -3
  24. package/dist/raw-ordinal-warmup-worker.js +3 -3
  25. package/dist/{read-session-chunk-jxq427v6.js → read-session-chunk-r9qy3jzj.js} +2 -2
  26. package/dist/{render-6bhqgkpq.js → render-dvmk12tf.js} +5 -5
  27. package/dist/{search-archive-yvdq2nfp.js → search-archive-23s9g6dx.js} +4 -4
  28. package/dist/{search-45wknkb6.js → search-khaxkbs1.js} +7 -7
  29. package/dist/subagent-entry.js +13 -13
  30. package/dist/tag-snapshot-worker-pi.js +1 -1
  31. package/dist/{v2-archive-reader-bd94n954.js → v2-archive-reader-z7qgxxp0.js} +1 -1
  32. package/package.json +1 -1
@@ -27,11 +27,11 @@ serveWorkerJobs(async (initial, port) => {
27
27
  { Database, registerSqliteDiagnosticSink },
28
28
  { log }
29
29
  ] = await Promise.all([
30
- import("./embedding-backfill-002vyexq.js"),
30
+ import("./embedding-backfill-v9b8gkmp.js"),
31
31
  import("./embedding-cache-7rp4gqzr.js"),
32
32
  import("./storage-memory-0ndn65fm.js"),
33
- import("./project-embedding-registry-16pj4vyf.js"),
34
- import("./search-45wknkb6.js"),
33
+ import("./project-embedding-registry-e81zewts.js"),
34
+ import("./search-khaxkbs1.js"),
35
35
  import("./compartment-chunk-embedding-jpcme6tz.js"),
36
36
  import("./embedding-activity-ew6dshfd.js"),
37
37
  import("./harness-9872e0ym.js"),
@@ -35,7 +35,7 @@ import"./index-6pk49fc3.js";
35
35
  import {
36
36
  LATEST_SUPPORTED_VERSION,
37
37
  enforceSchemaFence
38
- } from "./index-a7sj2bam.js";
38
+ } from "./index-p1jxxsth.js";
39
39
  import"./index-3bb24eb6.js";
40
40
  import"./index-d107f484.js";
41
41
  import"./index-yacs388s.js";
@@ -1,10 +1,15 @@
1
1
  import {
2
2
  isMarkerCandidateBasisCurrent2,
3
3
  invalidateMarkerCandidateBasis2,
4
+ discardMarkerCandidateBasis2,
4
5
  readMarkerCandidateBasis2,
5
6
  prepareMarkerCandidateBasis2,
6
- scanMarkerCandidateSnapshot2
7
- } from "./index-p8jpbrj4.js";
7
+ scanMarkerCandidateSnapshot2,
8
+ readMarkerFrontiers2,
9
+ certifiedMarkerReferenceFloor2,
10
+ readMarkerReferenceRows2,
11
+ readKnownMarkerReferenceRows2
12
+ } from "./index-2kmwjq42.js";
8
13
  import"./index-wfqysrwq.js";
9
14
  import"./index-8sqebjzk.js";
10
15
  import"./index-2qtx0q6h.js";
@@ -13,9 +18,14 @@ import"./index-0h2mkab2.js";
13
18
  import"./index-dnp1jjar.js";
14
19
  import"./index-x2n261wp.js";
15
20
  export {
21
+ certifiedMarkerReferenceFloor2 as certifiedMarkerReferenceFloor,
22
+ discardMarkerCandidateBasis2 as discardMarkerCandidateBasis,
16
23
  invalidateMarkerCandidateBasis2 as invalidateMarkerCandidateBasis,
17
24
  isMarkerCandidateBasisCurrent2 as isMarkerCandidateBasisCurrent,
18
25
  prepareMarkerCandidateBasis2 as prepareMarkerCandidateBasis,
26
+ readKnownMarkerReferenceRows2 as readKnownMarkerReferenceRows,
19
27
  readMarkerCandidateBasis2 as readMarkerCandidateBasis,
28
+ readMarkerFrontiers2 as readMarkerFrontiers,
29
+ readMarkerReferenceRows2 as readMarkerReferenceRows,
20
30
  scanMarkerCandidateSnapshot2 as scanMarkerCandidateSnapshot
21
31
  };
@@ -7,14 +7,17 @@ serveWorkerJobs(async (input, port) => {
7
7
  port.postMessage({ kind: "accepted" });
8
8
  const [{ Database }, { scanMarkerCandidateSnapshot }] = await Promise.all([
9
9
  import("./sqlite-v89bj0yy.js"),
10
- import("./compaction-marker-candidates-8qhackvy.js")
10
+ import("./compaction-marker-candidates-17a21jfn.js")
11
11
  ]);
12
12
  let db;
13
13
  let reply;
14
14
  try {
15
15
  db = new Database(input.path, { readonly: true });
16
16
  db.exec("PRAGMA busy_timeout=250");
17
- reply = { kind: "candidates", snapshot: scanMarkerCandidateSnapshot(db, input.sessionId) };
17
+ reply = {
18
+ kind: "candidates",
19
+ snapshot: scanMarkerCandidateSnapshot(db, input.sessionId, input.references !== false)
20
+ };
18
21
  } catch (error) {
19
22
  reply = { kind: "error", error: error instanceof Error ? error.message : String(error) };
20
23
  } finally {
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  ensureMemoryEmbeddings2
3
- } from "./index-jbkwszd5.js";
4
- import"./index-z7dktknj.js";
3
+ } from "./index-gajhgp4k.js";
4
+ import"./index-9tcbabqr.js";
5
5
  import"./index-9p40dgkm.js";
6
6
  import"./index-hgd00nas.js";
7
7
  import"./index-yhzhdp3m.js";
8
8
  import"./index-mp0gh04g.js";
9
9
  import"./index-f9qet7y8.js";
10
- import"./index-2qqsnh1b.js";
10
+ import"./index-xf3ndcqd.js";
11
11
  import"./index-rzfr7wdv.js";
12
- import"./index-ccanzg8p.js";
12
+ import"./index-gzk7d940.js";
13
13
  import"./index-6pk49fc3.js";
14
14
  import"./index-ck8wj35v.js";
15
15
  import"./index-c1dqxr10.js";
@@ -5,7 +5,7 @@ import {
5
5
  log2
6
6
  } from "./index-gymgz20n.js";
7
7
  import"./index-dnp1jjar.js";
8
- import"./index-ccanzg8p.js";
8
+ import"./index-gzk7d940.js";
9
9
  import"./index-rzfr7wdv.js";
10
10
  import"./index-wt7vmyj4.js";
11
11
  import"./index-2qtx0q6h.js";
@@ -13,7 +13,7 @@ import {
13
13
  resolveLocalEmbeddingWorkerRuntime,
14
14
  getLocalEmbeddingNativeMemoryStats,
15
15
  LocalEmbeddingProvider
16
- } from "./index-2qqsnh1b.js";
16
+ } from "./index-xf3ndcqd.js";
17
17
  import {
18
18
  setStoragePrivatePermissionEnforcement
19
19
  } from "./index-81nthk8j.js";
@@ -9,7 +9,7 @@ import {
9
9
  } from "./index-wt7vmyj4.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./index-mx757f3g.js";
12
+ } from "./index-j2x88zk0.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -26,9 +26,10 @@ var missingWorkerWarnings = new Set;
26
26
  var ownWriteRevisions = new Map;
27
27
  var exitRegistered = false;
28
28
  function reportWorkerUnavailable(entry, detail) {
29
- if (missingWorkerWarnings.has(entry.href))
29
+ const key = `${entry.href}\x00${detail}`;
30
+ if (missingWorkerWarnings.has(key))
30
31
  return;
31
- missingWorkerWarnings.add(entry.href);
32
+ missingWorkerWarnings.add(key);
32
33
  const path = entry.protocol === "file:" ? fileURLToPath(entry) : entry.href;
33
34
  log2(`[magic-context] [ERROR] compaction-marker: candidate worker unavailable ${path}: ${detail}; marker unchanged, advancement deferred`);
34
35
  }
@@ -64,6 +65,9 @@ function invalidateMarkerCandidateBasis2(db, sessionId) {
64
65
  if (revision !== undefined)
65
66
  ownWriteRevisions.set(key, revision + 1);
66
67
  }
68
+ function discardMarkerCandidateBasis2(db, sessionId) {
69
+ candidates.get(db)?.delete(sessionId);
70
+ }
67
71
  function readMarkerCandidateBasis2(db, sessionId, readConnection = db) {
68
72
  const basis = candidates.get(db)?.get(sessionId);
69
73
  if (basis) {
@@ -94,7 +98,7 @@ function prepareMarkerCandidateBasis2(db, sessionId, options = {}) {
94
98
  reportWorkerUnavailable(entry, "file missing");
95
99
  return Promise.resolve(false);
96
100
  }
97
- const preparation = runCandidateWorker(path, sessionId, options).then((snapshot) => {
101
+ const preparation = runCandidateWorker(path, sessionId, options.references !== false, options).then((snapshot) => {
98
102
  if (!snapshot)
99
103
  return false;
100
104
  const basis = {
@@ -124,7 +128,7 @@ function prepareMarkerCandidateBasis2(db, sessionId, options = {}) {
124
128
  function markerWorkerEntry() {
125
129
  return new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./compaction-marker-candidates-worker.ts" : "./compaction-marker-candidates-worker.js", import.meta.url);
126
130
  }
127
- function runCandidateWorker(path, sessionId, options) {
131
+ function runCandidateWorker(path, sessionId, references, options) {
128
132
  if (!exitRegistered) {
129
133
  exitRegistered = true;
130
134
  const controller = new AbortController;
@@ -164,10 +168,14 @@ function runCandidateWorker(path, sessionId, options) {
164
168
  timer.unref?.();
165
169
  };
166
170
  try {
167
- worker = inRootAsyncContext2(() => options.entry ? new Worker(entry, { workerData: { path, sessionId } }) : reuseWorker(entry, { workerData: { path, sessionId } }));
171
+ const pooled = !options.entry || options.shareWorker === true;
172
+ worker = inRootAsyncContext2(() => pooled ? reuseWorker(entry, { workerData: { path, sessionId, references } }) : new Worker(entry, { workerData: { path, sessionId, references } }));
168
173
  workers.add(worker);
169
174
  worker.unref();
170
- deadline(options.acceptMs ?? 2000);
175
+ if (pooled)
176
+ worker.once("online", () => deadline(options.acceptMs ?? 2000));
177
+ else
178
+ deadline(options.acceptMs ?? 2000);
171
179
  worker.on("message", (reply) => {
172
180
  if (reply.kind === "accepted")
173
181
  deadline(options.resultMs ?? 600000);
@@ -205,20 +213,64 @@ function scanMarkerSummaryCandidates(db, sessionId) {
205
213
  db.exec("ROLLBACK");
206
214
  }
207
215
  }
208
- function scanMarkerCandidateSnapshot2(db, sessionId) {
216
+ function scanMarkerCandidateSnapshot2(db, sessionId, references = true) {
209
217
  const ownsSnapshot = !db.inTransaction;
210
218
  if (ownsSnapshot)
211
219
  db.exec("BEGIN");
212
220
  try {
213
221
  const ids = scanMarkerSummaryCandidates(db, sessionId);
214
- const frontier = db.prepare("SELECT rowid,id FROM message ORDER BY rowid DESC LIMIT 1").get() ?? null;
215
- if (frontier && !Number.isSafeInteger(frontier.rowid))
216
- throw new Error("marker frontier rowid is not a safe integer");
217
- return { ids, frontier };
222
+ const frontier = readMarkerFrontier(db, "message");
223
+ if (!references)
224
+ return { ids, frontier };
225
+ return {
226
+ ids,
227
+ frontier,
228
+ references: {
229
+ partIds: readMarkerReferenceRows2(db, sessionId, "part").map((row) => row.id),
230
+ partFrontiers: readMarkerFrontiers2(db, "part")
231
+ }
232
+ };
218
233
  } finally {
219
234
  if (ownsSnapshot)
220
235
  db.exec("ROLLBACK");
221
236
  }
222
237
  }
238
+ function readMarkerFrontier(db, table) {
239
+ const frontier = db.prepare(`SELECT rowid,id FROM ${table} ORDER BY rowid DESC LIMIT 1`).all()[0] ?? null;
240
+ if (frontier && !Number.isSafeInteger(frontier.rowid))
241
+ throw new Error(`marker ${table} frontier rowid is not a safe integer`);
242
+ return frontier;
243
+ }
244
+ var MARKER_FRONTIER_CANDIDATES = 3;
245
+ function readMarkerFrontiers2(db, table, count = MARKER_FRONTIER_CANDIDATES) {
246
+ const frontiers = db.prepare(`SELECT rowid,id FROM ${table} ORDER BY rowid DESC LIMIT ?`).all(count);
247
+ if (frontiers.some((frontier) => !Number.isSafeInteger(frontier.rowid)))
248
+ throw new Error(`marker ${table} frontier rowid is not a safe integer`);
249
+ return frontiers;
250
+ }
251
+ var MARKER_REFERENCE_FRONTIER_SQL = (table) => `SELECT rowid FROM ${table} WHERE id = ?`;
252
+ function certifiedMarkerReferenceFloor2(db, table, frontiers) {
253
+ if (frontiers.length === 0)
254
+ return 0;
255
+ const probe = db.prepare(MARKER_REFERENCE_FRONTIER_SQL(table));
256
+ for (const frontier of [...frontiers].sort((a, b) => b.rowid - a.rowid)) {
257
+ const current = probe.all(frontier.id);
258
+ if (current[0]?.rowid === frontier.rowid)
259
+ return frontier.rowid;
260
+ }
261
+ return;
262
+ }
263
+ var MARKER_TAIL_REFERENCE_COLUMNS = `id,
264
+ CASE WHEN data LIKE '%tail_start_id%' THEN json_extract(data, '$.tail_start_id') END AS direct,
265
+ CASE WHEN data LIKE '%tail_start_id%' THEN json_extract(data, '$.compaction.tail_start_id') END AS nested`;
266
+ function readMarkerReferenceRows2(db, sessionId, table, afterRowid) {
267
+ return db.prepare(`SELECT ${MARKER_TAIL_REFERENCE_COLUMNS} FROM ${table}
268
+ WHERE ${afterRowid === undefined ? "session_id = ?" : "rowid > ? AND +session_id = ?"}
269
+ 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(...afterRowid === undefined ? [sessionId] : [afterRowid, sessionId]);
270
+ }
271
+ function readKnownMarkerReferenceRows2(db, sessionId, table, ids) {
272
+ const byId = db.prepare(`SELECT ${MARKER_TAIL_REFERENCE_COLUMNS} FROM ${table} WHERE id = ? AND session_id = ?`);
273
+ return ids.flatMap((id) => byId.all(id, sessionId));
274
+ }
223
275
 
224
- export { isMarkerCandidateBasisCurrent2, invalidateMarkerCandidateBasis2, readMarkerCandidateBasis2, prepareMarkerCandidateBasis2, scanMarkerCandidateSnapshot2 };
276
+ export { isMarkerCandidateBasisCurrent2, invalidateMarkerCandidateBasis2, discardMarkerCandidateBasis2, readMarkerCandidateBasis2, prepareMarkerCandidateBasis2, scanMarkerCandidateSnapshot2, readMarkerFrontiers2, certifiedMarkerReferenceFloor2, readMarkerReferenceRows2, readKnownMarkerReferenceRows2 };
@@ -46,7 +46,7 @@ import {
46
46
  } from "./index-f9qet7y8.js";
47
47
  import {
48
48
  DEFAULT_LOCAL_EMBEDDING_MODEL
49
- } from "./index-ccanzg8p.js";
49
+ } from "./index-gzk7d940.js";
50
50
  import {
51
51
  embeddingModelsMatch,
52
52
  resolveEmbeddingTextPrefixes,
@@ -56,7 +56,7 @@ import {
56
56
  getEmbeddingProviderIdentity,
57
57
  dominantEmbeddingFailure,
58
58
  LocalEmbeddingProvider
59
- } from "./index-2qqsnh1b.js";
59
+ } from "./index-xf3ndcqd.js";
60
60
  import {
61
61
  embedPauseBySession,
62
62
  activeEmbeddingSessions,
@@ -30,7 +30,7 @@ import {
30
30
  PER_HARNESS_MODEL_KEYS,
31
31
  ConfigProfilesSchema,
32
32
  MagicContextConfigSchema
33
- } from "./index-ccanzg8p.js";
33
+ } from "./index-gzk7d940.js";
34
34
  import {
35
35
  V2_MEMORY_CATEGORIES,
36
36
  CATEGORY_PRIORITY,
@@ -56,7 +56,7 @@ import {
56
56
  import {
57
57
  piHarnessKindFromExecutable,
58
58
  getErrorMessage
59
- } from "./index-a7sj2bam.js";
59
+ } from "./index-p1jxxsth.js";
60
60
  import {
61
61
  getOrCreateSessionMeta,
62
62
  updateSessionMeta,
@@ -70,10 +70,10 @@ import {
70
70
  renderMessageByOrdinal2,
71
71
  renderVerboseRange2,
72
72
  renderItemByTag2
73
- } from "./index-p9jfa33t.js";
73
+ } from "./index-gtd9kaaf.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
- } from "./index-j0h89gxy.js";
76
+ } from "./index-025nxwc9.js";
77
77
  import {
78
78
  setNoteLastReadAt,
79
79
  getPersistedCompactionMarkerState,
@@ -83,7 +83,7 @@ import {
83
83
  hasRawMessageProvider2,
84
84
  setRawMessageProvider2,
85
85
  readSessionChunk2
86
- } from "./index-mx757f3g.js";
86
+ } from "./index-j2x88zk0.js";
87
87
  import {
88
88
  stableStringify
89
89
  } from "./index-yacs388s.js";
@@ -109,7 +109,7 @@ import {
109
109
  } from "./index-yhzhdp3m.js";
110
110
  import {
111
111
  preflightLocalEmbeddingPooling
112
- } from "./index-2qqsnh1b.js";
112
+ } from "./index-xf3ndcqd.js";
113
113
  import {
114
114
  markProjectLoadUntrusted2,
115
115
  drainProjectEmbeddingIdentityMaintenance2,
@@ -120,7 +120,7 @@ import {
120
120
  unregisterProjectEmbedding2,
121
121
  getProjectEmbeddingSnapshot2,
122
122
  embedTextForProject2
123
- } from "./index-z7dktknj.js";
123
+ } from "./index-9tcbabqr.js";
124
124
  import {
125
125
  directoryHasGitMetadata,
126
126
  resolveProjectIdentityForSession,
@@ -133,7 +133,7 @@ import {
133
133
  resolveMemoriesByIdsForSearch2,
134
134
  unifiedSearch2,
135
135
  formatSearchResults2
136
- } from "./index-g2j58qpq.js";
136
+ } from "./index-zttw4vew.js";
137
137
  import {
138
138
  TODO_STATUSES,
139
139
  TODO_PRIORITIES,
@@ -173,11 +173,17 @@ import {
173
173
  import {
174
174
  isMarkerCandidateBasisCurrent2,
175
175
  invalidateMarkerCandidateBasis2,
176
- readMarkerCandidateBasis2
177
- } from "./index-p8jpbrj4.js";
176
+ discardMarkerCandidateBasis2,
177
+ readMarkerCandidateBasis2,
178
+ prepareMarkerCandidateBasis2,
179
+ readMarkerFrontiers2,
180
+ certifiedMarkerReferenceFloor2,
181
+ readMarkerReferenceRows2,
182
+ readKnownMarkerReferenceRows2
183
+ } from "./index-2kmwjq42.js";
178
184
  import {
179
185
  renderSearchArchive2
180
- } from "./index-ry84c8dr.js";
186
+ } from "./index-pb0ygvpa.js";
181
187
  import {
182
188
  computeNormalizedHash
183
189
  } from "./index-9x1f96r8.js";
@@ -5015,18 +5021,27 @@ function isCompactionMarkerIntentAbsent(marker, targetEndMessageId) {
5015
5021
  return !db.prepare(`SELECT 1 FROM message WHERE id IN (?, ?)
5016
5022
  UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(targetEndMessageId, marker.summaryMessageId, marker.compactionPartId, marker.summaryPartId);
5017
5023
  }
5018
- function withCompactionMarkerPublicationLock(operation, sessionId) {
5024
+ function withCompactionMarkerPublicationLock(operation, sessionId, onReferencesMissing) {
5019
5025
  const db = getWritableOpenCodeDb();
5020
5026
  const snapshot = prepareMarkerReplacementSnapshot(db, sessionId);
5021
- return runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
5022
- if (snapshot)
5023
- activeMarkerReplacementSnapshots.set(db, snapshot);
5024
- try {
5025
- return operation();
5026
- } finally {
5027
- activeMarkerReplacementSnapshots.delete(db);
5028
- }
5029
- });
5027
+ if (snapshot === "references-missing" && onReferencesMissing) {
5028
+ startCompactionMarkerCandidatePreparation(sessionId);
5029
+ return onReferencesMissing();
5030
+ }
5031
+ try {
5032
+ return runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
5033
+ if (typeof snapshot === "object")
5034
+ activeMarkerReplacementSnapshots.set(db, snapshot);
5035
+ try {
5036
+ return operation();
5037
+ } finally {
5038
+ activeMarkerReplacementSnapshots.delete(db);
5039
+ }
5040
+ });
5041
+ } finally {
5042
+ if (warmAfterCommit.delete(sessionId) && !db.inTransaction)
5043
+ startCompactionMarkerCandidatePreparation(sessionId);
5044
+ }
5030
5045
  }
5031
5046
  function inspectCompactionMarkerPublication(sessionId, recognized, summaryText, targetBoundaryMessageId, preferred) {
5032
5047
  const db = getWritableOpenCodeDb();
@@ -5130,6 +5145,41 @@ function removeLegacyMarkerLineageRows(db, args) {
5130
5145
  AND COALESCE(json_extract(data, '$.type'), '') = 'compaction'
5131
5146
  AND COALESCE(json_extract(data, '$.auto'), 0) = 1`).run(args.sessionId, args.boundaryMessageId, args.compactionPartId);
5132
5147
  }
5148
+ async function prepareCompactionMarkerCandidates(sessionId, options = {}) {
5149
+ if (!harnessOwnsOpenCodeStore2())
5150
+ return true;
5151
+ try {
5152
+ const db = getWritableOpenCodeDb();
5153
+ if (markerDiscoveryReady(db, sessionId))
5154
+ return true;
5155
+ discardMarkerCandidateBasis2(db, sessionId);
5156
+ const prepared = await prepareMarkerCandidateBasis2(db, sessionId, {
5157
+ references: !markerReplacementSnapshots.get(db)?.has(sessionId),
5158
+ ...options
5159
+ });
5160
+ return prepared && markerDiscoveryReady(db, sessionId);
5161
+ } catch (error) {
5162
+ log2(`[magic-context] compaction-marker: deferred candidate preparation for ${sessionId}: ${error instanceof Error ? error.message : String(error)}; marker unchanged`);
5163
+ return false;
5164
+ }
5165
+ }
5166
+ function startCompactionMarkerCandidatePreparation(sessionId) {
5167
+ if (!harnessOwnsOpenCodeStore2())
5168
+ return "ready";
5169
+ try {
5170
+ if (markerDiscoveryReady(getWritableOpenCodeDb(), sessionId))
5171
+ return "ready";
5172
+ } catch (error) {
5173
+ log2(`[magic-context] compaction-marker: deferred candidate preparation for ${sessionId}: ${error instanceof Error ? error.message : String(error)}; marker unchanged`);
5174
+ return "unavailable";
5175
+ }
5176
+ prepareCompactionMarkerCandidates(sessionId);
5177
+ return "preparing";
5178
+ }
5179
+ function markerDiscoveryReady(db, sessionId) {
5180
+ const basis = readMarkerCandidateBasis2(db, sessionId);
5181
+ return basis !== undefined && (basis.references !== undefined || markerReplacementSnapshots.get(db)?.has(sessionId) === true);
5182
+ }
5133
5183
  function injectCompactionMarkerFromBasis(args, validatedBasis, preserveExistingLineages = false) {
5134
5184
  const db = getWritableOpenCodeDb();
5135
5185
  if (!isOpenCodeSchemaCompatible(db, getOpenCodeDbPath())) {
@@ -5224,18 +5274,7 @@ class MarkerCandidateUnavailableError extends Error {
5224
5274
  }
5225
5275
  var activeMarkerReplacementSnapshots = new WeakMap;
5226
5276
  var markerReplacementSnapshots = new WeakMap;
5227
- var MARKER_TAIL_REFERENCE_COLUMNS = `id,
5228
- CASE WHEN data LIKE '%tail_start_id%' THEN json_extract(data, '$.tail_start_id') END AS direct,
5229
- CASE WHEN data LIKE '%tail_start_id%' THEN json_extract(data, '$.compaction.tail_start_id') END AS nested`;
5230
- function readMarkerReferenceRows(db, sessionId, table, highestId) {
5231
- return db.prepare(`SELECT ${MARKER_TAIL_REFERENCE_COLUMNS} FROM ${table}
5232
- WHERE ${highestId === undefined ? "session_id = ?" : "id > ? AND +session_id = ?"}
5233
- 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]);
5234
- }
5235
- function readKnownMarkerReferenceRows(db, sessionId, table, ids) {
5236
- const byId = db.prepare(`SELECT ${MARKER_TAIL_REFERENCE_COLUMNS} FROM ${table} WHERE id = ? AND session_id = ?`);
5237
- return ids.flatMap((id) => byId.all(id, sessionId));
5238
- }
5277
+ var warmAfterCommit = new Set;
5239
5278
  function prepareMarkerReplacementSnapshot(db, sessionId) {
5240
5279
  const sessions = markerReplacementSnapshots.get(db) ?? new Map;
5241
5280
  markerReplacementSnapshots.set(db, sessions);
@@ -5263,23 +5302,37 @@ function prepareMarkerReplacementSnapshot(db, sessionId) {
5263
5302
  sessions.delete(sessionId);
5264
5303
  return;
5265
5304
  }
5266
- const previous = sessions.get(sessionId);
5267
- const highestId = (table) => reader.prepare(`SELECT id FROM ${table} ORDER BY id DESC LIMIT 1`).all()[0]?.id ?? "";
5268
- const discover = (table, ids, highest) => previous ? [
5305
+ const cached = sessions.get(sessionId);
5306
+ let knownParts;
5307
+ for (const seed of [cached, basis.references]) {
5308
+ const floor = seed ? certifiedMarkerReferenceFloor2(reader, "part", seed.partFrontiers) : undefined;
5309
+ if (seed && floor !== undefined) {
5310
+ knownParts = { seed, floor };
5311
+ break;
5312
+ }
5313
+ }
5314
+ if (!knownParts) {
5315
+ sessions.delete(sessionId);
5316
+ discardMarkerCandidateBasis2(db, sessionId);
5317
+ log2(`[magic-context] compaction-marker: deferred replacement for ${sessionId}: part reference discovery is missing or its frontier changed; marker unchanged`);
5318
+ return "references-missing";
5319
+ }
5320
+ const discover = (table, ids, floor) => [
5269
5321
  ...new Map([
5270
- ...readKnownMarkerReferenceRows(reader, sessionId, table, ids),
5271
- ...readMarkerReferenceRows(reader, sessionId, table, highest)
5322
+ ...readKnownMarkerReferenceRows2(reader, sessionId, table, ids),
5323
+ ...readMarkerReferenceRows2(reader, sessionId, table, floor)
5272
5324
  ].map((row) => [row.id, row])).values()
5273
- ] : readMarkerReferenceRows(reader, sessionId, table);
5274
- const parts = discover("part", previous?.partIds ?? [], previous?.highestPartId ?? "");
5275
- const messages = discover("message", previous?.messageIds ?? [], previous?.highestMessageId ?? "");
5325
+ ];
5326
+ const parts = discover("part", knownParts.seed.partIds, knownParts.floor);
5327
+ const messageFloor = cached ? certifiedMarkerReferenceFloor2(reader, "message", cached.messageFrontiers) : undefined;
5328
+ const messages = cached && messageFloor !== undefined ? discover("message", cached.messageIds, messageFloor) : readMarkerReferenceRows2(reader, sessionId, "message");
5276
5329
  snapshot = {
5277
5330
  sessionId,
5278
5331
  basis,
5279
5332
  partIds: parts.map((row) => row.id),
5280
5333
  messageIds: messages.map((row) => row.id),
5281
- highestPartId: highestId("part"),
5282
- highestMessageId: highestId("message"),
5334
+ partFrontiers: readMarkerFrontiers2(reader, "part"),
5335
+ messageFrontiers: readMarkerFrontiers2(reader, "message"),
5283
5336
  references: [...parts, ...messages]
5284
5337
  };
5285
5338
  } finally {
@@ -5296,7 +5349,7 @@ function prepareMarkerReplacementSnapshot(db, sessionId) {
5296
5349
  throw error;
5297
5350
  }
5298
5351
  }
5299
- function markerRowsAreReferenced(db, snapshot, existing) {
5352
+ function markerRowsAreReferenced(db, snapshot, existing, seen) {
5300
5353
  const deleted = new Set([
5301
5354
  existing.summaryMessageId,
5302
5355
  existing.summaryPartId,
@@ -5305,13 +5358,18 @@ function markerRowsAreReferenced(db, snapshot, existing) {
5305
5358
  const referencesDeleted = (row) => !deleted.has(row.id) && [row.direct, row.nested].some((id) => typeof id === "string" && deleted.has(id));
5306
5359
  if (snapshot.references.some(referencesDeleted))
5307
5360
  throw new Error("a surviving tail_start_id references a recorded marker row; marker unchanged");
5308
- for (const [table, ids, highestId] of [
5309
- ["part", snapshot.partIds, snapshot.highestPartId],
5310
- ["message", snapshot.messageIds, snapshot.highestMessageId]
5361
+ for (const [table, ids, frontiers] of [
5362
+ ["part", snapshot.partIds, snapshot.partFrontiers],
5363
+ ["message", snapshot.messageIds, snapshot.messageFrontiers]
5311
5364
  ]) {
5312
- if (readKnownMarkerReferenceRows(db, snapshot.sessionId, table, ids).some(referencesDeleted))
5365
+ const floor = certifiedMarkerReferenceFloor2(db, table, frontiers);
5366
+ if (floor === undefined)
5367
+ throw new MarkerCandidateUnavailableError(`host ${table} frontier changed after marker reference discovery; marker unchanged`);
5368
+ if (readKnownMarkerReferenceRows2(db, snapshot.sessionId, table, ids).some(referencesDeleted))
5313
5369
  return true;
5314
- if (readMarkerReferenceRows(db, snapshot.sessionId, table, highestId).some(referencesDeleted))
5370
+ const suffix = readMarkerReferenceRows2(db, snapshot.sessionId, table, floor);
5371
+ seen[table].push(...suffix.map((row) => row.id));
5372
+ if (suffix.some(referencesDeleted))
5315
5373
  return true;
5316
5374
  }
5317
5375
  return false;
@@ -5324,19 +5382,21 @@ function replaceCompactionMarker(existing, args, preserveExistingLineages = fals
5324
5382
  const db = getWritableOpenCodeDb();
5325
5383
  connection = db;
5326
5384
  const snapshot = activeMarkerReplacementSnapshots.get(db) ?? prepareMarkerReplacementSnapshot(db, args.sessionId);
5327
- if (!snapshot || snapshot.sessionId !== args.sessionId) {
5385
+ if (typeof snapshot !== "object" || snapshot.sessionId !== args.sessionId) {
5328
5386
  return {
5329
5387
  kind: "deferred",
5330
5388
  error: new Error("marker candidate preparation pending; marker unchanged")
5331
5389
  };
5332
5390
  }
5333
5391
  const { basis } = snapshot;
5392
+ let advanceFrontiers;
5334
5393
  const marker = runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
5335
5394
  entered = true;
5336
5395
  if (!isMarkerCandidateBasisCurrent2(db, basis))
5337
5396
  throw new MarkerCandidateUnavailableError("host store changed after marker candidate preparation; marker unchanged");
5397
+ const seen = { part: [], message: [] };
5338
5398
  if (existing) {
5339
- if (markerRowsAreReferenced(db, snapshot, existing))
5399
+ if (markerRowsAreReferenced(db, snapshot, existing, seen))
5340
5400
  throw new MarkerCandidateUnavailableError("a surviving tail_start_id references a recorded marker row; marker unchanged");
5341
5401
  db.prepare("DELETE FROM part WHERE id = ?").run(existing.summaryPartId);
5342
5402
  db.prepare("DELETE FROM message WHERE id = ?").run(existing.summaryMessageId);
@@ -5346,9 +5406,28 @@ function replaceCompactionMarker(existing, args, preserveExistingLineages = fals
5346
5406
  if (!replacement) {
5347
5407
  throw new Error(`failed to inject replacement marker at ordinal ${args.endOrdinal}`);
5348
5408
  }
5409
+ if (existing) {
5410
+ try {
5411
+ const partFrontiers = readMarkerFrontiers2(db, "part");
5412
+ const messageFrontiers = readMarkerFrontiers2(db, "message");
5413
+ advanceFrontiers = () => {
5414
+ snapshot.partIds = [...new Set([...snapshot.partIds, ...seen.part])];
5415
+ snapshot.messageIds = [
5416
+ ...new Set([...snapshot.messageIds, ...seen.message])
5417
+ ];
5418
+ snapshot.partFrontiers = partFrontiers;
5419
+ snapshot.messageFrontiers = messageFrontiers;
5420
+ };
5421
+ } catch {}
5422
+ }
5349
5423
  readyToCommit = true;
5350
5424
  return replacement;
5351
5425
  });
5426
+ advanceFrontiers?.();
5427
+ if (db.inTransaction)
5428
+ warmAfterCommit.add(args.sessionId);
5429
+ else
5430
+ startCompactionMarkerCandidatePreparation(args.sessionId);
5352
5431
  return { kind: "committed", marker };
5353
5432
  } catch (error) {
5354
5433
  if (error instanceof MarkerCandidateUnavailableError)
@@ -5474,7 +5553,13 @@ function publishRecoverableCompactionMarker(db, args, targetIsCurrent) {
5474
5553
  if (replacement.kind !== "committed")
5475
5554
  cut = replacement.kind === "uncertain" ? "uncertain" : "definitely-no-cut";
5476
5555
  return replacement;
5477
- }, sessionId);
5556
+ }, sessionId, () => {
5557
+ reason = "candidate-preparation";
5558
+ return {
5559
+ kind: "deferred",
5560
+ error: new Error("marker reference discovery pending; marker unchanged")
5561
+ };
5562
+ });
5478
5563
  if (result.kind === "committed") {
5479
5564
  if (!intended)
5480
5565
  throw new Error("committed marker has no publication intent");
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  DEFAULT_LOCAL_EMBEDDING_MODEL
3
- } from "./index-ccanzg8p.js";
3
+ } from "./index-gzk7d940.js";
4
4
  import {
5
5
  log2
6
6
  } from "./index-gymgz20n.js";
@@ -10,12 +10,12 @@ import {
10
10
  } from "./index-rzfr7wdv.js";
11
11
  import {
12
12
  LocalEmbeddingProvider
13
- } from "./index-2qqsnh1b.js";
13
+ } from "./index-xf3ndcqd.js";
14
14
  import {
15
15
  OpenAICompatibleEmbeddingProvider,
16
16
  getProjectEmbeddingSnapshot2,
17
17
  embedBatchForProject2
18
- } from "./index-z7dktknj.js";
18
+ } from "./index-9tcbabqr.js";
19
19
  import {
20
20
  isEmbeddingHostBusy2
21
21
  } from "./index-9p40dgkm.js";
@@ -139,9 +139,9 @@ async function serveV2ArchiveReads2(port, openConnections) {
139
139
  import("./sqlite-v89bj0yy.js"),
140
140
  import("./store-reader-2m80zs5z.js"),
141
141
  import("./store-v60q7dje.js"),
142
- import("./read-session-chunk-jxq427v6.js"),
143
- import("./render-6bhqgkpq.js"),
144
- import("./search-archive-yvdq2nfp.js"),
142
+ import("./read-session-chunk-r9qy3jzj.js"),
143
+ import("./render-dvmk12tf.js"),
144
+ import("./search-archive-23s9g6dx.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;