@cortexkit/pi-magic-context 0.49.43 → 0.49.45

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 (43) hide show
  1. package/dist/auto-search-worker.js +4 -4
  2. package/dist/chunk-embedding-write-worker.js +6 -6
  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/{compartment-chunk-embedding-jpcme6tz.js → compartment-chunk-embedding-nyjs3dfh.js} +5 -5
  6. package/dist/{embedding-backfill-002vyexq.js → embedding-backfill-er9jc4xf.js} +9 -9
  7. package/dist/embedding-worker.js +4 -4
  8. package/dist/{index-wt7vmyj4.js → index-000fthre.js} +4 -0
  9. package/dist/{index-p8jpbrj4.js → index-2kmwjq42.js} +64 -12
  10. package/dist/{index-c1dqxr10.js → index-3g9fnq6y.js} +2 -1
  11. package/dist/{index-f9qet7y8.js → index-4sa1rx3h.js} +3 -3
  12. package/dist/{index-p9jfa33t.js → index-6bedye3n.js} +7 -7
  13. package/dist/{index-mx757f3g.js → index-7esg5v2x.js} +7 -4
  14. package/dist/{index-ck8wj35v.js → index-bbbp8zs1.js} +1 -1
  15. package/dist/{index-j0h89gxy.js → index-fzadydec.js} +3 -3
  16. package/dist/{index-rzfr7wdv.js → index-gwvahsdz.js} +1 -1
  17. package/dist/{index-ccanzg8p.js → index-gzk7d940.js} +1 -1
  18. package/dist/{index-wwsfevck.js → index-jaqdcqwz.js} +1 -1
  19. package/dist/{index-6cvt64cn.js → index-k7gdgs11.js} +143 -57
  20. package/dist/{index-k0csz6pb.js → index-nvgq29cw.js} +3 -3
  21. package/dist/{index-g2j58qpq.js → index-qt711raa.js} +6 -6
  22. package/dist/{index-z7dktknj.js → index-rcenqffj.js} +64 -22
  23. package/dist/{index-2qqsnh1b.js → index-tsg6swzr.js} +2 -2
  24. package/dist/{index-ry84c8dr.js → index-v7m1nqwz.js} +2 -2
  25. package/dist/{index-a7sj2bam.js → index-wwf9vxpf.js} +2 -2
  26. package/dist/{index-pwp6zyx3.js → index-zchc0df8.js} +1 -1
  27. package/dist/{index-jbkwszd5.js → index-zwbgxt01.js} +4 -4
  28. package/dist/index.js +217 -73
  29. package/dist/{message-fts-rowid-map-hmgyfxxa.js → message-fts-rowid-map-ff4qg3e4.js} +2 -2
  30. package/dist/{message-index-bounded-39z2atfj.js → message-index-bounded-cqn6x6fc.js} +7 -7
  31. package/dist/migration-worker.js +4 -4
  32. package/dist/{project-embedding-registry-16pj4vyf.js → project-embedding-registry-ysaezfqw.js} +8 -8
  33. package/dist/raw-ordinal-warmup-worker.js +7 -7
  34. package/dist/{read-session-chunk-jxq427v6.js → read-session-chunk-0ecmbegv.js} +5 -5
  35. package/dist/{read-session-raw-a9ntjqap.js → read-session-raw-nttnwy8p.js} +1 -1
  36. package/dist/{render-6bhqgkpq.js → render-s6k2xqhj.js} +11 -11
  37. package/dist/{search-archive-yvdq2nfp.js → search-archive-qza20zkm.js} +7 -7
  38. package/dist/{search-45wknkb6.js → search-p4fj69gn.js} +13 -13
  39. package/dist/{storage-tags-p9y3bnw7.js → storage-tags-g0j9mr4b.js} +2 -2
  40. package/dist/subagent-entry.js +19 -19
  41. package/dist/tag-snapshot-worker-pi.js +6 -6
  42. package/dist/{v2-archive-reader-bd94n954.js → v2-archive-reader-2v7a879f.js} +1 -1
  43. package/package.json +1 -1
@@ -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,
@@ -38,25 +38,25 @@ import {
38
38
  } from "./index-135e8hvg.js";
39
39
  import {
40
40
  estimateTokens
41
- } from "./index-wt7vmyj4.js";
41
+ } from "./index-000fthre.js";
42
42
  import {
43
43
  SubcClient,
44
44
  connectionFileExists,
45
45
  SYNAPSE_DEFAULT_MODEL,
46
46
  toSynapseLaneDescriptor,
47
47
  SynapseEmbeddingProvider
48
- } from "./index-rzfr7wdv.js";
48
+ } from "./index-gwvahsdz.js";
49
49
  import {
50
50
  inRootAsyncContext2,
51
51
  Database2
52
52
  } from "./index-2qtx0q6h.js";
53
53
  import {
54
54
  noteRawSessionSummaryRowWritten2
55
- } from "./index-c1dqxr10.js";
55
+ } from "./index-3g9fnq6y.js";
56
56
  import {
57
57
  piHarnessKindFromExecutable,
58
58
  getErrorMessage
59
- } from "./index-a7sj2bam.js";
59
+ } from "./index-wwf9vxpf.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-6bedye3n.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
- } from "./index-j0h89gxy.js";
76
+ } from "./index-fzadydec.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-7esg5v2x.js";
87
87
  import {
88
88
  stableStringify
89
89
  } from "./index-yacs388s.js";
@@ -109,8 +109,9 @@ import {
109
109
  } from "./index-yhzhdp3m.js";
110
110
  import {
111
111
  preflightLocalEmbeddingPooling
112
- } from "./index-2qqsnh1b.js";
112
+ } from "./index-tsg6swzr.js";
113
113
  import {
114
+ withQueryEmbeddingDeadline,
114
115
  markProjectLoadUntrusted2,
115
116
  drainProjectEmbeddingIdentityMaintenance2,
116
117
  registerProjectEmbedding2,
@@ -120,7 +121,7 @@ import {
120
121
  unregisterProjectEmbedding2,
121
122
  getProjectEmbeddingSnapshot2,
122
123
  embedTextForProject2
123
- } from "./index-z7dktknj.js";
124
+ } from "./index-rcenqffj.js";
124
125
  import {
125
126
  directoryHasGitMetadata,
126
127
  resolveProjectIdentityForSession,
@@ -133,7 +134,7 @@ import {
133
134
  resolveMemoriesByIdsForSearch2,
134
135
  unifiedSearch2,
135
136
  formatSearchResults2
136
- } from "./index-g2j58qpq.js";
137
+ } from "./index-qt711raa.js";
137
138
  import {
138
139
  TODO_STATUSES,
139
140
  TODO_PRIORITIES,
@@ -144,7 +145,7 @@ import {
144
145
  getInertWhitespaceAssistantTagsByNumbers2,
145
146
  getTagNumberByMessageId2,
146
147
  getTagsBySession2
147
- } from "./index-pwp6zyx3.js";
148
+ } from "./index-zchc0df8.js";
148
149
  import {
149
150
  resolveOpenCodeDbPath,
150
151
  assertOpenCodeStoreGeneration
@@ -173,11 +174,17 @@ import {
173
174
  import {
174
175
  isMarkerCandidateBasisCurrent2,
175
176
  invalidateMarkerCandidateBasis2,
176
- readMarkerCandidateBasis2
177
- } from "./index-p8jpbrj4.js";
177
+ discardMarkerCandidateBasis2,
178
+ readMarkerCandidateBasis2,
179
+ prepareMarkerCandidateBasis2,
180
+ readMarkerFrontiers2,
181
+ certifiedMarkerReferenceFloor2,
182
+ readMarkerReferenceRows2,
183
+ readKnownMarkerReferenceRows2
184
+ } from "./index-2kmwjq42.js";
178
185
  import {
179
186
  renderSearchArchive2
180
- } from "./index-ry84c8dr.js";
187
+ } from "./index-v7m1nqwz.js";
181
188
  import {
182
189
  computeNormalizedHash
183
190
  } from "./index-9x1f96r8.js";
@@ -5015,18 +5022,27 @@ function isCompactionMarkerIntentAbsent(marker, targetEndMessageId) {
5015
5022
  return !db.prepare(`SELECT 1 FROM message WHERE id IN (?, ?)
5016
5023
  UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(targetEndMessageId, marker.summaryMessageId, marker.compactionPartId, marker.summaryPartId);
5017
5024
  }
5018
- function withCompactionMarkerPublicationLock(operation, sessionId) {
5025
+ function withCompactionMarkerPublicationLock(operation, sessionId, onReferencesMissing) {
5019
5026
  const db = getWritableOpenCodeDb();
5020
5027
  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
- });
5028
+ if (snapshot === "references-missing" && onReferencesMissing) {
5029
+ startCompactionMarkerCandidatePreparation(sessionId);
5030
+ return onReferencesMissing();
5031
+ }
5032
+ try {
5033
+ return runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
5034
+ if (typeof snapshot === "object")
5035
+ activeMarkerReplacementSnapshots.set(db, snapshot);
5036
+ try {
5037
+ return operation();
5038
+ } finally {
5039
+ activeMarkerReplacementSnapshots.delete(db);
5040
+ }
5041
+ });
5042
+ } finally {
5043
+ if (warmAfterCommit.delete(sessionId) && !db.inTransaction)
5044
+ startCompactionMarkerCandidatePreparation(sessionId);
5045
+ }
5030
5046
  }
5031
5047
  function inspectCompactionMarkerPublication(sessionId, recognized, summaryText, targetBoundaryMessageId, preferred) {
5032
5048
  const db = getWritableOpenCodeDb();
@@ -5130,6 +5146,41 @@ function removeLegacyMarkerLineageRows(db, args) {
5130
5146
  AND COALESCE(json_extract(data, '$.type'), '') = 'compaction'
5131
5147
  AND COALESCE(json_extract(data, '$.auto'), 0) = 1`).run(args.sessionId, args.boundaryMessageId, args.compactionPartId);
5132
5148
  }
5149
+ async function prepareCompactionMarkerCandidates(sessionId, options = {}) {
5150
+ if (!harnessOwnsOpenCodeStore2())
5151
+ return true;
5152
+ try {
5153
+ const db = getWritableOpenCodeDb();
5154
+ if (markerDiscoveryReady(db, sessionId))
5155
+ return true;
5156
+ discardMarkerCandidateBasis2(db, sessionId);
5157
+ const prepared = await prepareMarkerCandidateBasis2(db, sessionId, {
5158
+ references: !markerReplacementSnapshots.get(db)?.has(sessionId),
5159
+ ...options
5160
+ });
5161
+ return prepared && markerDiscoveryReady(db, sessionId);
5162
+ } catch (error) {
5163
+ log2(`[magic-context] compaction-marker: deferred candidate preparation for ${sessionId}: ${error instanceof Error ? error.message : String(error)}; marker unchanged`);
5164
+ return false;
5165
+ }
5166
+ }
5167
+ function startCompactionMarkerCandidatePreparation(sessionId) {
5168
+ if (!harnessOwnsOpenCodeStore2())
5169
+ return "ready";
5170
+ try {
5171
+ if (markerDiscoveryReady(getWritableOpenCodeDb(), sessionId))
5172
+ return "ready";
5173
+ } catch (error) {
5174
+ log2(`[magic-context] compaction-marker: deferred candidate preparation for ${sessionId}: ${error instanceof Error ? error.message : String(error)}; marker unchanged`);
5175
+ return "unavailable";
5176
+ }
5177
+ prepareCompactionMarkerCandidates(sessionId);
5178
+ return "preparing";
5179
+ }
5180
+ function markerDiscoveryReady(db, sessionId) {
5181
+ const basis = readMarkerCandidateBasis2(db, sessionId);
5182
+ return basis !== undefined && (basis.references !== undefined || markerReplacementSnapshots.get(db)?.has(sessionId) === true);
5183
+ }
5133
5184
  function injectCompactionMarkerFromBasis(args, validatedBasis, preserveExistingLineages = false) {
5134
5185
  const db = getWritableOpenCodeDb();
5135
5186
  if (!isOpenCodeSchemaCompatible(db, getOpenCodeDbPath())) {
@@ -5224,18 +5275,7 @@ class MarkerCandidateUnavailableError extends Error {
5224
5275
  }
5225
5276
  var activeMarkerReplacementSnapshots = new WeakMap;
5226
5277
  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
- }
5278
+ var warmAfterCommit = new Set;
5239
5279
  function prepareMarkerReplacementSnapshot(db, sessionId) {
5240
5280
  const sessions = markerReplacementSnapshots.get(db) ?? new Map;
5241
5281
  markerReplacementSnapshots.set(db, sessions);
@@ -5263,23 +5303,37 @@ function prepareMarkerReplacementSnapshot(db, sessionId) {
5263
5303
  sessions.delete(sessionId);
5264
5304
  return;
5265
5305
  }
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 ? [
5306
+ const cached = sessions.get(sessionId);
5307
+ let knownParts;
5308
+ for (const seed of [cached, basis.references]) {
5309
+ const floor = seed ? certifiedMarkerReferenceFloor2(reader, "part", seed.partFrontiers) : undefined;
5310
+ if (seed && floor !== undefined) {
5311
+ knownParts = { seed, floor };
5312
+ break;
5313
+ }
5314
+ }
5315
+ if (!knownParts) {
5316
+ sessions.delete(sessionId);
5317
+ discardMarkerCandidateBasis2(db, sessionId);
5318
+ log2(`[magic-context] compaction-marker: deferred replacement for ${sessionId}: part reference discovery is missing or its frontier changed; marker unchanged`);
5319
+ return "references-missing";
5320
+ }
5321
+ const discover = (table, ids, floor) => [
5269
5322
  ...new Map([
5270
- ...readKnownMarkerReferenceRows(reader, sessionId, table, ids),
5271
- ...readMarkerReferenceRows(reader, sessionId, table, highest)
5323
+ ...readKnownMarkerReferenceRows2(reader, sessionId, table, ids),
5324
+ ...readMarkerReferenceRows2(reader, sessionId, table, floor)
5272
5325
  ].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 ?? "");
5326
+ ];
5327
+ const parts = discover("part", knownParts.seed.partIds, knownParts.floor);
5328
+ const messageFloor = cached ? certifiedMarkerReferenceFloor2(reader, "message", cached.messageFrontiers) : undefined;
5329
+ const messages = cached && messageFloor !== undefined ? discover("message", cached.messageIds, messageFloor) : readMarkerReferenceRows2(reader, sessionId, "message");
5276
5330
  snapshot = {
5277
5331
  sessionId,
5278
5332
  basis,
5279
5333
  partIds: parts.map((row) => row.id),
5280
5334
  messageIds: messages.map((row) => row.id),
5281
- highestPartId: highestId("part"),
5282
- highestMessageId: highestId("message"),
5335
+ partFrontiers: readMarkerFrontiers2(reader, "part"),
5336
+ messageFrontiers: readMarkerFrontiers2(reader, "message"),
5283
5337
  references: [...parts, ...messages]
5284
5338
  };
5285
5339
  } finally {
@@ -5296,7 +5350,7 @@ function prepareMarkerReplacementSnapshot(db, sessionId) {
5296
5350
  throw error;
5297
5351
  }
5298
5352
  }
5299
- function markerRowsAreReferenced(db, snapshot, existing) {
5353
+ function markerRowsAreReferenced(db, snapshot, existing, seen) {
5300
5354
  const deleted = new Set([
5301
5355
  existing.summaryMessageId,
5302
5356
  existing.summaryPartId,
@@ -5305,13 +5359,18 @@ function markerRowsAreReferenced(db, snapshot, existing) {
5305
5359
  const referencesDeleted = (row) => !deleted.has(row.id) && [row.direct, row.nested].some((id) => typeof id === "string" && deleted.has(id));
5306
5360
  if (snapshot.references.some(referencesDeleted))
5307
5361
  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]
5362
+ for (const [table, ids, frontiers] of [
5363
+ ["part", snapshot.partIds, snapshot.partFrontiers],
5364
+ ["message", snapshot.messageIds, snapshot.messageFrontiers]
5311
5365
  ]) {
5312
- if (readKnownMarkerReferenceRows(db, snapshot.sessionId, table, ids).some(referencesDeleted))
5366
+ const floor = certifiedMarkerReferenceFloor2(db, table, frontiers);
5367
+ if (floor === undefined)
5368
+ throw new MarkerCandidateUnavailableError(`host ${table} frontier changed after marker reference discovery; marker unchanged`);
5369
+ if (readKnownMarkerReferenceRows2(db, snapshot.sessionId, table, ids).some(referencesDeleted))
5313
5370
  return true;
5314
- if (readMarkerReferenceRows(db, snapshot.sessionId, table, highestId).some(referencesDeleted))
5371
+ const suffix = readMarkerReferenceRows2(db, snapshot.sessionId, table, floor);
5372
+ seen[table].push(...suffix.map((row) => row.id));
5373
+ if (suffix.some(referencesDeleted))
5315
5374
  return true;
5316
5375
  }
5317
5376
  return false;
@@ -5324,19 +5383,21 @@ function replaceCompactionMarker(existing, args, preserveExistingLineages = fals
5324
5383
  const db = getWritableOpenCodeDb();
5325
5384
  connection = db;
5326
5385
  const snapshot = activeMarkerReplacementSnapshots.get(db) ?? prepareMarkerReplacementSnapshot(db, args.sessionId);
5327
- if (!snapshot || snapshot.sessionId !== args.sessionId) {
5386
+ if (typeof snapshot !== "object" || snapshot.sessionId !== args.sessionId) {
5328
5387
  return {
5329
5388
  kind: "deferred",
5330
5389
  error: new Error("marker candidate preparation pending; marker unchanged")
5331
5390
  };
5332
5391
  }
5333
5392
  const { basis } = snapshot;
5393
+ let advanceFrontiers;
5334
5394
  const marker = runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
5335
5395
  entered = true;
5336
5396
  if (!isMarkerCandidateBasisCurrent2(db, basis))
5337
5397
  throw new MarkerCandidateUnavailableError("host store changed after marker candidate preparation; marker unchanged");
5398
+ const seen = { part: [], message: [] };
5338
5399
  if (existing) {
5339
- if (markerRowsAreReferenced(db, snapshot, existing))
5400
+ if (markerRowsAreReferenced(db, snapshot, existing, seen))
5340
5401
  throw new MarkerCandidateUnavailableError("a surviving tail_start_id references a recorded marker row; marker unchanged");
5341
5402
  db.prepare("DELETE FROM part WHERE id = ?").run(existing.summaryPartId);
5342
5403
  db.prepare("DELETE FROM message WHERE id = ?").run(existing.summaryMessageId);
@@ -5346,9 +5407,28 @@ function replaceCompactionMarker(existing, args, preserveExistingLineages = fals
5346
5407
  if (!replacement) {
5347
5408
  throw new Error(`failed to inject replacement marker at ordinal ${args.endOrdinal}`);
5348
5409
  }
5410
+ if (existing) {
5411
+ try {
5412
+ const partFrontiers = readMarkerFrontiers2(db, "part");
5413
+ const messageFrontiers = readMarkerFrontiers2(db, "message");
5414
+ advanceFrontiers = () => {
5415
+ snapshot.partIds = [...new Set([...snapshot.partIds, ...seen.part])];
5416
+ snapshot.messageIds = [
5417
+ ...new Set([...snapshot.messageIds, ...seen.message])
5418
+ ];
5419
+ snapshot.partFrontiers = partFrontiers;
5420
+ snapshot.messageFrontiers = messageFrontiers;
5421
+ };
5422
+ } catch {}
5423
+ }
5349
5424
  readyToCommit = true;
5350
5425
  return replacement;
5351
5426
  });
5427
+ advanceFrontiers?.();
5428
+ if (db.inTransaction)
5429
+ warmAfterCommit.add(args.sessionId);
5430
+ else
5431
+ startCompactionMarkerCandidatePreparation(args.sessionId);
5352
5432
  return { kind: "committed", marker };
5353
5433
  } catch (error) {
5354
5434
  if (error instanceof MarkerCandidateUnavailableError)
@@ -5474,7 +5554,13 @@ function publishRecoverableCompactionMarker(db, args, targetIsCurrent) {
5474
5554
  if (replacement.kind !== "committed")
5475
5555
  cut = replacement.kind === "uncertain" ? "uncertain" : "definitely-no-cut";
5476
5556
  return replacement;
5477
- }, sessionId);
5557
+ }, sessionId, () => {
5558
+ reason = "candidate-preparation";
5559
+ return {
5560
+ kind: "deferred",
5561
+ error: new Error("marker reference discovery pending; marker unchanged")
5562
+ };
5563
+ });
5478
5564
  if (result.kind === "committed") {
5479
5565
  if (!intended)
5480
5566
  throw new Error("committed marker has no publication intent");
@@ -9968,7 +10054,7 @@ function createCtxSearchTool(deps) {
9968
10054
  memoryEnabled,
9969
10055
  embeddingEnabled,
9970
10056
  embedQuery: async (text, signal) => {
9971
- const result = await embedTextForProject2(projectIdentity, text, signal, "query");
10057
+ const result = await withQueryEmbeddingDeadline((embeddingSignal) => embedTextForProject2(projectIdentity, text, embeddingSignal, "query"), signal);
9972
10058
  return result?.vector ?? null;
9973
10059
  },
9974
10060
  isEmbeddingRuntimeEnabled: () => embeddingEnabled === true,
@@ -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-0ecmbegv.js"),
143
+ import("./render-s6k2xqhj.js"),
144
+ import("./search-archive-qza20zkm.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -15,7 +15,7 @@ import {
15
15
  } from "./index-gymgz20n.js";
16
16
  import {
17
17
  SubcClient
18
- } from "./index-rzfr7wdv.js";
18
+ } from "./index-gwvahsdz.js";
19
19
  import {
20
20
  inRootAsyncContext2,
21
21
  getSqliteDatabasePath2,
@@ -24,13 +24,13 @@ import {
24
24
  } from "./index-2qtx0q6h.js";
25
25
  import {
26
26
  runSessionWarmupWorker
27
- } from "./index-c1dqxr10.js";
27
+ } from "./index-3g9fnq6y.js";
28
28
  import {
29
29
  buildCanonicalChunkTextFromFts2,
30
30
  loadCompartmentChunkEmbeddingsForSearch2,
31
31
  peekCompartmentChunkSearchPool2,
32
32
  warmCompartmentChunkSearchPool2
33
- } from "./index-f9qet7y8.js";
33
+ } from "./index-4sa1rx3h.js";
34
34
  import {
35
35
  saveCommitEmbedding,
36
36
  loadProjectCommitEmbeddings,
@@ -47,7 +47,7 @@ import {
47
47
  getProjectEmbeddingSnapshot2,
48
48
  embedTextForProject2,
49
49
  embedItemsForProject2
50
- } from "./index-z7dktknj.js";
50
+ } from "./index-rcenqffj.js";
51
51
  import {
52
52
  recordEmbeddingMeasurement
53
53
  } from "./index-hgd00nas.js";
@@ -63,7 +63,7 @@ import {
63
63
  isEmbeddingEnabled,
64
64
  embedText,
65
65
  ensureMemoryEmbeddings2
66
- } from "./index-jbkwszd5.js";
66
+ } from "./index-zwbgxt01.js";
67
67
  import {
68
68
  getMemorySelectColumns2,
69
69
  isMemoryRow2,
@@ -91,7 +91,7 @@ import {
91
91
  clearIndexedMessages,
92
92
  indexSingleMessage,
93
93
  indexMessagesAfterOrdinal
94
- } from "./index-j0h89gxy.js";
94
+ } from "./index-fzadydec.js";
95
95
  import {
96
96
  MESSAGE_FTS_SESSION_FILTER_SQL,
97
97
  withMessageFtsSessionFilter
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  estimateTokens
3
- } from "./index-wt7vmyj4.js";
3
+ } from "./index-000fthre.js";
4
4
  import {
5
5
  getHarness2
6
6
  } from "./index-0h2mkab2.js";
@@ -15,7 +15,7 @@ import {
15
15
  isSynapseEmbeddingTruncated,
16
16
  getSynapseBatchRequestKey,
17
17
  SynapseEmbeddingProvider
18
- } from "./index-rzfr7wdv.js";
18
+ } from "./index-gwvahsdz.js";
19
19
  import {
20
20
  inRootAsyncContext2,
21
21
  getSqliteDatabasePath2
@@ -43,10 +43,10 @@ import {
43
43
  countSessionCompartmentEmbedCoverage2,
44
44
  countSessionCompartmentEmbedCoveragePolite2,
45
45
  countUnembeddedSessionCompartmentsPolite2
46
- } from "./index-f9qet7y8.js";
46
+ } from "./index-4sa1rx3h.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-tsg6swzr.js";
60
60
  import {
61
61
  embedPauseBySession,
62
62
  activeEmbeddingSessions,
@@ -94,6 +94,36 @@ import {
94
94
  // ../plugin/src/features/magic-context/memory/embedding-openai.ts
95
95
  import { createHash } from "node:crypto";
96
96
 
97
+ // ../plugin/src/features/magic-context/memory/embedding-query-deadline.ts
98
+ var QUERY_EMBEDDING_TIMEOUT_MS = 5000;
99
+
100
+ class EmbeddingQueryTimeoutError extends Error {
101
+ timeoutMs = QUERY_EMBEDDING_TIMEOUT_MS;
102
+ constructor() {
103
+ super(`query embedding timed out after ${QUERY_EMBEDDING_TIMEOUT_MS}ms`);
104
+ this.name = "EmbeddingQueryTimeoutError";
105
+ }
106
+ }
107
+ async function withQueryEmbeddingDeadline(embed, signal) {
108
+ if (signal?.aborted)
109
+ return null;
110
+ const deadline = new AbortController;
111
+ const combined = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
112
+ let onAbort;
113
+ const aborted = new Promise((resolve) => {
114
+ onAbort = () => resolve(null);
115
+ combined.addEventListener("abort", onAbort, { once: true });
116
+ });
117
+ const timer = setTimeout(() => deadline.abort(new EmbeddingQueryTimeoutError), QUERY_EMBEDDING_TIMEOUT_MS);
118
+ try {
119
+ return await Promise.race([embed(combined), aborted]);
120
+ } finally {
121
+ clearTimeout(timer);
122
+ if (onAbort)
123
+ combined.removeEventListener("abort", onAbort);
124
+ }
125
+ }
126
+
97
127
  // ../plugin/src/features/magic-context/memory/embedding-ssrf.ts
98
128
  var METADATA_HOSTNAMES = new Set(["metadata.google.internal", "metadata.goog"]);
99
129
  var IPV6_METADATA_HOSTS = new Set(["fd00:ec2::254"]);
@@ -190,9 +220,9 @@ function normalizeEndpoint(endpoint) {
190
220
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
191
221
  }
192
222
  var FAILURE_THRESHOLD = 3;
193
- var FAILURE_WINDOW_MS = 60000;
194
223
  var OPEN_DURATION_MS = 5 * 60000;
195
224
  var FETCH_TIMEOUT_MS = 30000;
225
+ var FAILURE_WINDOW_MS = FAILURE_THRESHOLD * FETCH_TIMEOUT_MS;
196
226
  var RETRY_AFTER_CAP_MS = 60000;
197
227
  var RATE_LIMIT_BACKOFF_BASE_MS = 1000;
198
228
  var RATE_LIMIT_BACKOFF_CAP_MS = 30000;
@@ -364,6 +394,8 @@ class OpenAICompatibleEmbeddingProvider {
364
394
  let internalController;
365
395
  let timeoutHandle;
366
396
  let onOuterAbort;
397
+ let rateLimitedResponse = false;
398
+ const requestStartedAt = Date.now();
367
399
  try {
368
400
  const claim = this.claimProbeOrShortCircuit();
369
401
  if (claim === "short_circuit") {
@@ -372,7 +404,14 @@ class OpenAICompatibleEmbeddingProvider {
372
404
  isProbe = claim === "probe";
373
405
  internalController = new AbortController;
374
406
  timeoutHandle = setTimeout(() => internalController?.abort(), FETCH_TIMEOUT_MS);
375
- onOuterAbort = () => internalController?.abort();
407
+ onOuterAbort = () => {
408
+ if (signal?.reason instanceof EmbeddingQueryTimeoutError && !rateLimitedResponse) {
409
+ const timeoutMs = signal.reason.timeoutMs;
410
+ log2(`[magic-context] openai-compatible embedding request timed out after ${timeoutMs}ms`);
411
+ this.recordFailure(requestStartedAt, isProbe, this.failure("transport_error", `request timed out after ${timeoutMs}ms`, true));
412
+ }
413
+ internalController?.abort();
414
+ };
376
415
  if (signal) {
377
416
  signal.addEventListener("abort", onOuterAbort, { once: true });
378
417
  }
@@ -393,22 +432,25 @@ class OpenAICompatibleEmbeddingProvider {
393
432
  signal: internalController.signal
394
433
  });
395
434
  if (response.status === 429) {
435
+ rateLimitedResponse = true;
396
436
  await response.text().catch(() => "");
397
437
  this.noteRateLimit(response.headers.get("retry-after"));
398
438
  return RATE_LIMITED;
399
439
  }
400
440
  if (!response.ok) {
401
441
  const excerpt = await response.text().catch(() => "");
442
+ if (signal?.aborted)
443
+ return Array.from({ length: texts.length }, () => null);
402
444
  const failure = this.failure("http_error", `HTTP ${response.status} from endpoint${this.bodyExcerpt(excerpt)}`, response.status >= 500 || response.status === 408);
403
445
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
404
- this.recordFailure(isProbe, failure);
446
+ this.recordFailure(requestStartedAt, isProbe, failure);
405
447
  return Array.from({ length: texts.length }, () => null);
406
448
  }
407
449
  const rawBody = await response.text();
408
450
  if (rawBody.trim().length === 0) {
409
451
  const failure = this.failure("invalid_envelope", "response body was empty", false);
410
452
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
411
- this.recordFailure(isProbe, failure);
453
+ this.recordFailure(requestStartedAt, isProbe, failure);
412
454
  return Array.from({ length: texts.length }, () => null);
413
455
  }
414
456
  let body;
@@ -417,7 +459,7 @@ class OpenAICompatibleEmbeddingProvider {
417
459
  } catch {
418
460
  const failure = this.failure("invalid_envelope", `response body was not valid JSON${this.bodyExcerpt(rawBody)}`, false);
419
461
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
420
- this.recordFailure(isProbe, failure);
462
+ this.recordFailure(requestStartedAt, isProbe, failure);
421
463
  return Array.from({ length: texts.length }, () => null);
422
464
  }
423
465
  const servedModel = typeof body.model === "string" ? body.model : "";
@@ -426,27 +468,27 @@ class OpenAICompatibleEmbeddingProvider {
426
468
  log2(`[magic-context] embedding endpoint served a DIFFERENT model than requested — refusing the substituted vectors (they have the wrong dimensions/space). requested="${sanitizeDiagnosticText(this.model)}" served="${sanitizeDiagnosticText(servedModel)}". Check that the endpoint serves the requested model; variant suffixes and vendor prefixes are matched automatically.`);
427
469
  this.modelMismatchLogged = true;
428
470
  }
429
- this.recordFailure(isProbe, this.failure("substitution_rejected", `served model '${sanitizeDiagnosticText(servedModel)}' does not match requested '${sanitizeDiagnosticText(this.model)}' (substitution guard)`, false));
471
+ this.recordFailure(requestStartedAt, isProbe, this.failure("substitution_rejected", `served model '${sanitizeDiagnosticText(servedModel)}' does not match requested '${sanitizeDiagnosticText(this.model)}' (substitution guard)`, false));
430
472
  return Array.from({ length: texts.length }, () => null);
431
473
  }
432
474
  const responseKeys = Object.keys(body).sort();
433
475
  if (!Array.isArray(body.data)) {
434
476
  const failure = this.failure("invalid_envelope", `response had keys [${responseKeys.join(", ")}] but data[] was absent`, false);
435
477
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
436
- this.recordFailure(isProbe, failure);
478
+ this.recordFailure(requestStartedAt, isProbe, failure);
437
479
  return Array.from({ length: texts.length }, () => null);
438
480
  }
439
481
  if (body.data.length === 0) {
440
482
  const failure = this.failure("empty_result", "response data[] was empty", true);
441
483
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
442
- this.recordFailure(isProbe, failure);
484
+ this.recordFailure(requestStartedAt, isProbe, failure);
443
485
  return Array.from({ length: texts.length }, () => null);
444
486
  }
445
487
  const slots = responseSlots(body.data, texts.length);
446
488
  if (!slots) {
447
489
  const failure = this.failure("invalid_envelope", "response data[].index values were missing, duplicated or out of range", false);
448
490
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
449
- this.recordFailure(isProbe, failure);
491
+ this.recordFailure(requestStartedAt, isProbe, failure);
450
492
  return Array.from({ length: texts.length }, () => null);
451
493
  }
452
494
  const results = Array.from({ length: texts.length }, () => null);
@@ -460,7 +502,7 @@ class OpenAICompatibleEmbeddingProvider {
460
502
  if (results.every((r) => r === null)) {
461
503
  const failure = this.failure("invalid_envelope", `response had keys [${responseKeys.join(", ")}] but data[].embedding was absent`, false);
462
504
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
463
- this.recordFailure(isProbe, failure);
505
+ this.recordFailure(requestStartedAt, isProbe, failure);
464
506
  } else {
465
507
  this.recordSuccess();
466
508
  }
@@ -471,13 +513,13 @@ class OpenAICompatibleEmbeddingProvider {
471
513
  if (signal?.aborted) {} else {
472
514
  log2(`[magic-context] openai-compatible embedding request timed out after ${FETCH_TIMEOUT_MS}ms`);
473
515
  const failure = this.failure("transport_error", `request timed out after ${FETCH_TIMEOUT_MS}ms`, true);
474
- this.recordFailure(isProbe, failure);
516
+ this.recordFailure(requestStartedAt, isProbe, failure);
475
517
  }
476
518
  } else {
477
519
  const detail = error instanceof Error ? error.message : String(error);
478
520
  const failure = this.failure("transport_error", `transport error: ${sanitizeDiagnosticText(detail)}`, true);
479
521
  log2(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
480
- this.recordFailure(isProbe, failure);
522
+ this.recordFailure(requestStartedAt, isProbe, failure);
481
523
  }
482
524
  return Array.from({ length: texts.length }, () => null);
483
525
  } finally {
@@ -549,7 +591,7 @@ class OpenAICompatibleEmbeddingProvider {
549
591
  const excerpt = sanitizeDiagnosticText(body).replace(/\s+/g, " ").trim().slice(0, 200);
550
592
  return excerpt ? `: ${excerpt}` : "";
551
593
  }
552
- recordFailure(isProbe, failure) {
594
+ recordFailure(requestStartedAt, isProbe, failure) {
553
595
  if (failure)
554
596
  this.lastFailureReason = failure;
555
597
  if (isProbe) {
@@ -562,9 +604,9 @@ class OpenAICompatibleEmbeddingProvider {
562
604
  return;
563
605
  }
564
606
  const now = Date.now();
565
- const cutoff = now - FAILURE_WINDOW_MS;
566
- this.failureTimes = this.failureTimes.filter((t) => t > cutoff);
567
- this.failureTimes.push(now);
607
+ const cutoff = requestStartedAt - FAILURE_WINDOW_MS;
608
+ this.failureTimes = this.failureTimes.filter((t) => t >= cutoff);
609
+ this.failureTimes.push(requestStartedAt);
568
610
  if (this.failureTimes.length >= FAILURE_THRESHOLD) {
569
611
  this.circuitOpenUntil = now + OPEN_DURATION_MS;
570
612
  if (!this.openLogged) {
@@ -3086,4 +3128,4 @@ function _resetProjectEmbeddingRegistryForTests2() {
3086
3128
  setBootQuietPeriodForTests(null);
3087
3129
  }
3088
3130
 
3089
- export { OpenAICompatibleEmbeddingProvider, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitSha, enforceProjectCap, describeShadowBackfillWriteRefusal2, listShadowBackfillStalls2, getShadowBackfillStopReason2, markProjectLoadUntrusted2, contentSha2562, drainProjectEmbeddingIdentityMaintenance2, drainStaleEmbeddingIdentitiesForProject2, registerProjectEmbedding2, registerProjectShadowEmbedding2, getShadowEmbeddingMeasurementCohort2, getPrimaryEmbeddingMeasurementCohort2, embedShadowTextForProject2, enqueueShadowEmbeddingItems2, getShadowBackfillRemaining2, flushShadowEmbeddingBacklog2, registerProjectInObservationMode2, unregisterProjectShadowEmbedding2, unregisterProjectEmbedding2, getProjectEmbeddingSnapshot2, installProjectEmbeddingSearchBridge2, getProjectChunkEmbeddingModelId2, getProjectEmbeddingMaxInputTokens2, embedTextForProject2, embedBatchForProject2, embedItemsForProject2, embedUnembeddedMemoriesForProject2, drainCommitBacklogForProject2, embedUnembeddedCompartmentChunksForProject2, embedSessionCompartmentChunks2, getEmbeddingCoverageStatus2, getAutoEmbeddingSessionCoverage2, sweepAllRegisteredProjects2, _setTestProviderFactoryForProject2, _resetProjectEmbeddingRegistryForTests2 };
3131
+ export { withQueryEmbeddingDeadline, OpenAICompatibleEmbeddingProvider, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitSha, enforceProjectCap, describeShadowBackfillWriteRefusal2, listShadowBackfillStalls2, getShadowBackfillStopReason2, markProjectLoadUntrusted2, contentSha2562, drainProjectEmbeddingIdentityMaintenance2, drainStaleEmbeddingIdentitiesForProject2, registerProjectEmbedding2, registerProjectShadowEmbedding2, getShadowEmbeddingMeasurementCohort2, getPrimaryEmbeddingMeasurementCohort2, embedShadowTextForProject2, enqueueShadowEmbeddingItems2, getShadowBackfillRemaining2, flushShadowEmbeddingBacklog2, registerProjectInObservationMode2, unregisterProjectShadowEmbedding2, unregisterProjectEmbedding2, getProjectEmbeddingSnapshot2, installProjectEmbeddingSearchBridge2, getProjectChunkEmbeddingModelId2, getProjectEmbeddingMaxInputTokens2, embedTextForProject2, embedBatchForProject2, embedItemsForProject2, embedUnembeddedMemoriesForProject2, drainCommitBacklogForProject2, embedUnembeddedCompartmentChunksForProject2, embedSessionCompartmentChunks2, getEmbeddingCoverageStatus2, getAutoEmbeddingSessionCoverage2, sweepAllRegisteredProjects2, _setTestProviderFactoryForProject2, _resetProjectEmbeddingRegistryForTests2 };