@cortexkit/pi-magic-context 0.49.39 → 0.49.41

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.
@@ -4,7 +4,7 @@ import {
4
4
  readMarkerCandidateBasis2,
5
5
  prepareMarkerCandidateBasis2,
6
6
  scanMarkerCandidateSnapshot2
7
- } from "./index-y90fxz4t.js";
7
+ } from "./index-p8jpbrj4.js";
8
8
  import"./index-wfqysrwq.js";
9
9
  import"./index-8sqebjzk.js";
10
10
  import"./index-2qtx0q6h.js";
@@ -7,7 +7,7 @@ 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-9fzqg6y0.js")
10
+ import("./compaction-marker-candidates-8qhackvy.js")
11
11
  ]);
12
12
  let db;
13
13
  let reply;
@@ -174,7 +174,7 @@ import {
174
174
  isMarkerCandidateBasisCurrent2,
175
175
  invalidateMarkerCandidateBasis2,
176
176
  readMarkerCandidateBasis2
177
- } from "./index-y90fxz4t.js";
177
+ } from "./index-p8jpbrj4.js";
178
178
  import {
179
179
  renderSearchArchive2
180
180
  } from "./index-ry84c8dr.js";
@@ -4809,6 +4809,7 @@ function getOpenCodeDbPath() {
4809
4809
  }
4810
4810
  var cachedWriteDb = null;
4811
4811
  var cachedRemovalDb = null;
4812
+ var cachedSnapshotDb = null;
4812
4813
  var MARKER_BUSY_TIMEOUT_MS = 250;
4813
4814
  var MARKER_REMOVAL_BUSY_TIMEOUT_MS = 5000;
4814
4815
  function runMarkerWriteTransaction(db, site, operation) {
@@ -4839,7 +4840,7 @@ function runMarkerWriteTransaction(db, site, operation) {
4839
4840
  try {
4840
4841
  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"}`);
4841
4842
  if (finishedAt - startedAt > 100) {
4842
- const autoCheckpoint = db.prepare("PRAGMA wal_autocheckpoint").get();
4843
+ const autoCheckpoint = db.prepare("PRAGMA wal_autocheckpoint").all()[0];
4843
4844
  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"}`);
4844
4845
  }
4845
4846
  } catch {}
@@ -4847,7 +4848,7 @@ function runMarkerWriteTransaction(db, site, operation) {
4847
4848
  }
4848
4849
  function markerWalPages(db) {
4849
4850
  try {
4850
- const row = db.prepare("PRAGMA page_size").get();
4851
+ const row = db.prepare("PRAGMA page_size").all()[0];
4851
4852
  const bytes = statSync4(`${getOpenCodeDbPath()}-wal`).size;
4852
4853
  return Math.max(0, Math.floor((bytes - 32) / (row.page_size + 24)));
4853
4854
  } catch {
@@ -5014,8 +5015,18 @@ function isCompactionMarkerIntentAbsent(marker, targetEndMessageId) {
5014
5015
  return !db.prepare(`SELECT 1 FROM message WHERE id IN (?, ?)
5015
5016
  UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(targetEndMessageId, marker.summaryMessageId, marker.compactionPartId, marker.summaryPartId);
5016
5017
  }
5017
- function withCompactionMarkerPublicationLock(operation) {
5018
- return runMarkerWriteTransaction(getWritableOpenCodeDb(), "compaction-marker-replace", operation);
5018
+ function withCompactionMarkerPublicationLock(operation, sessionId) {
5019
+ const db = getWritableOpenCodeDb();
5020
+ 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
+ });
5019
5030
  }
5020
5031
  function inspectCompactionMarkerPublication(sessionId, recognized, summaryText, targetBoundaryMessageId, preferred) {
5021
5032
  const db = getWritableOpenCodeDb();
@@ -5165,6 +5176,11 @@ function injectCompactionMarkerFromBasis(args, validatedBasis, preserveExistingL
5165
5176
  summaryMessageId: summaryMsgId,
5166
5177
  compactionPartId
5167
5178
  });
5179
+ const discovered = markerReplacementSnapshots.get(db)?.get(args.sessionId);
5180
+ if (discovered && !discovered.partIds.includes(compactionPartId))
5181
+ discovered.partIds.push(compactionPartId);
5182
+ if (discovered && !discovered.messageIds.includes(summaryMsgId))
5183
+ discovered.messageIds.push(summaryMsgId);
5168
5184
  db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data)
5169
5185
  VALUES (?, ?, ?, ?, ?, ?)
5170
5186
  ON CONFLICT(id) DO UPDATE SET
@@ -5206,6 +5222,100 @@ function injectCompactionMarkerFromBasis(args, validatedBasis, preserveExistingL
5206
5222
 
5207
5223
  class MarkerCandidateUnavailableError extends Error {
5208
5224
  }
5225
+ var activeMarkerReplacementSnapshots = new WeakMap;
5226
+ 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
+ }
5239
+ function prepareMarkerReplacementSnapshot(db, sessionId) {
5240
+ const sessions = markerReplacementSnapshots.get(db) ?? new Map;
5241
+ markerReplacementSnapshots.set(db, sessions);
5242
+ if (db.inTransaction) {
5243
+ sessions.delete(sessionId);
5244
+ return;
5245
+ }
5246
+ try {
5247
+ if (cachedSnapshotDb?.writer !== db) {
5248
+ if (cachedSnapshotDb)
5249
+ closeQuietly(cachedSnapshotDb.db);
5250
+ const reader = new Database2(getOpenCodeDbPath(), {
5251
+ readonly: true,
5252
+ fileMustExist: true
5253
+ });
5254
+ reader.exec(`PRAGMA busy_timeout=${MARKER_BUSY_TIMEOUT_MS}`);
5255
+ cachedSnapshotDb = { writer: db, db: reader };
5256
+ }
5257
+ const reader = cachedSnapshotDb.db;
5258
+ reader.exec("BEGIN");
5259
+ let snapshot;
5260
+ try {
5261
+ const basis = readMarkerCandidateBasis2(db, sessionId, reader);
5262
+ if (!basis) {
5263
+ sessions.delete(sessionId);
5264
+ return;
5265
+ }
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 ? [
5269
+ ...new Map([
5270
+ ...readKnownMarkerReferenceRows(reader, sessionId, table, ids),
5271
+ ...readMarkerReferenceRows(reader, sessionId, table, highest)
5272
+ ].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 ?? "");
5276
+ snapshot = {
5277
+ sessionId,
5278
+ basis,
5279
+ partIds: parts.map((row) => row.id),
5280
+ messageIds: messages.map((row) => row.id),
5281
+ highestPartId: highestId("part"),
5282
+ highestMessageId: highestId("message"),
5283
+ references: [...parts, ...messages]
5284
+ };
5285
+ } finally {
5286
+ reader.exec("ROLLBACK");
5287
+ }
5288
+ sessions.set(sessionId, snapshot);
5289
+ return snapshot;
5290
+ } catch (error) {
5291
+ markerReplacementSnapshots.delete(db);
5292
+ if (cachedSnapshotDb?.writer === db) {
5293
+ closeQuietly(cachedSnapshotDb.db);
5294
+ cachedSnapshotDb = null;
5295
+ }
5296
+ throw error;
5297
+ }
5298
+ }
5299
+ function markerRowsAreReferenced(db, snapshot, existing) {
5300
+ const deleted = new Set([
5301
+ existing.summaryMessageId,
5302
+ existing.summaryPartId,
5303
+ existing.compactionPartId
5304
+ ]);
5305
+ const referencesDeleted = (row) => !deleted.has(row.id) && [row.direct, row.nested].some((id) => typeof id === "string" && deleted.has(id));
5306
+ if (snapshot.references.some(referencesDeleted))
5307
+ 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]
5311
+ ]) {
5312
+ if (readKnownMarkerReferenceRows(db, snapshot.sessionId, table, ids).some(referencesDeleted))
5313
+ return true;
5314
+ if (readMarkerReferenceRows(db, snapshot.sessionId, table, highestId).some(referencesDeleted))
5315
+ return true;
5316
+ }
5317
+ return false;
5318
+ }
5209
5319
  function replaceCompactionMarker(existing, args, preserveExistingLineages = false) {
5210
5320
  let connection;
5211
5321
  let entered = false;
@@ -5213,32 +5323,21 @@ function replaceCompactionMarker(existing, args, preserveExistingLineages = fals
5213
5323
  try {
5214
5324
  const db = getWritableOpenCodeDb();
5215
5325
  connection = db;
5216
- const basis = readMarkerCandidateBasis2(db, args.sessionId);
5217
- if (!basis) {
5326
+ const snapshot = activeMarkerReplacementSnapshots.get(db) ?? prepareMarkerReplacementSnapshot(db, args.sessionId);
5327
+ if (!snapshot || snapshot.sessionId !== args.sessionId) {
5218
5328
  return {
5219
5329
  kind: "deferred",
5220
5330
  error: new Error("marker candidate preparation pending; marker unchanged")
5221
5331
  };
5222
5332
  }
5333
+ const { basis } = snapshot;
5223
5334
  const marker = runMarkerWriteTransaction(db, "compaction-marker-replace", () => {
5224
5335
  entered = true;
5225
5336
  if (!isMarkerCandidateBasisCurrent2(db, basis))
5226
5337
  throw new MarkerCandidateUnavailableError("host store changed after marker candidate preparation; marker unchanged");
5227
5338
  if (existing) {
5228
- const referenced = db.prepare(`WITH deleted(id) AS (VALUES (?), (?), (?)), surviving(data) AS (
5229
- SELECT data FROM part WHERE session_id = ?
5230
- AND id NOT IN (SELECT id FROM deleted)
5231
- AND json_extract(data, '$.type') = 'compaction'
5232
- UNION ALL
5233
- SELECT data FROM message WHERE session_id = ?
5234
- AND id NOT IN (SELECT id FROM deleted)
5235
- )
5236
- SELECT 1 FROM surviving
5237
- WHERE json_extract(data, '$.tail_start_id') IN (SELECT id FROM deleted)
5238
- OR json_extract(data, '$.compaction.tail_start_id') IN (SELECT id FROM deleted)
5239
- LIMIT 1`).get(existing.summaryMessageId, existing.summaryPartId, existing.compactionPartId, args.sessionId, args.sessionId);
5240
- if (referenced)
5241
- throw new Error("a surviving tail_start_id references a recorded marker row; marker unchanged");
5339
+ if (markerRowsAreReferenced(db, snapshot, existing))
5340
+ throw new MarkerCandidateUnavailableError("a surviving tail_start_id references a recorded marker row; marker unchanged");
5242
5341
  db.prepare("DELETE FROM part WHERE id = ?").run(existing.summaryPartId);
5243
5342
  db.prepare("DELETE FROM message WHERE id = ?").run(existing.summaryMessageId);
5244
5343
  db.prepare("DELETE FROM part WHERE id = ?").run(existing.compactionPartId);
@@ -5375,7 +5474,7 @@ function publishRecoverableCompactionMarker(db, args, targetIsCurrent) {
5375
5474
  if (replacement.kind !== "committed")
5376
5475
  cut = replacement.kind === "uncertain" ? "uncertain" : "definitely-no-cut";
5377
5476
  return replacement;
5378
- });
5477
+ }, sessionId);
5379
5478
  if (result.kind === "committed") {
5380
5479
  if (!intended)
5381
5480
  throw new Error("committed marker has no publication intent");
@@ -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
  }
package/dist/index.js CHANGED
@@ -150,7 +150,7 @@ import {
150
150
  registerTodoStateLifecycle,
151
151
  syncCtxMemoryToolEnabled,
152
152
  registerMagicContextTools
153
- } from "./index-rtg4a0sg.js";
153
+ } from "./index-6cvt64cn.js";
154
154
  import"./index-4knyh1kt.js";
155
155
  import {
156
156
  canonicalModelIdentity,
@@ -798,7 +798,7 @@ import {
798
798
  clearSessionTracking,
799
799
  createAutoSearchDiagnostics
800
800
  } from "./index-g2j58qpq.js";
801
- import"./index-y90fxz4t.js";
801
+ import"./index-p8jpbrj4.js";
802
802
  import {
803
803
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
804
804
  buildHiddenAgentRegistrations,
@@ -3584,7 +3584,7 @@ function startHostStallProfilerSwitch() {
3584
3584
  // package.json
3585
3585
  var package_default = {
3586
3586
  name: "@cortexkit/pi-magic-context",
3587
- version: "0.49.39",
3587
+ version: "0.49.41",
3588
3588
  type: "module",
3589
3589
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3590
3590
  main: "dist/index.js",
@@ -34,7 +34,7 @@ import {
34
34
  ensureProjectRegisteredFromPiDirectory,
35
35
  resolvePiHarnessKind,
36
36
  registerMagicContextTools
37
- } from "./index-rtg4a0sg.js";
37
+ } from "./index-6cvt64cn.js";
38
38
  import"./index-ccanzg8p.js";
39
39
  import"./index-rzfr7wdv.js";
40
40
  import"./index-f9qet7y8.js";
@@ -56,7 +56,7 @@ import"./index-k0csz6pb.js";
56
56
  import"./index-ry84c8dr.js";
57
57
  import"./index-29nw7n1r.js";
58
58
  import"./index-g2j58qpq.js";
59
- import"./index-y90fxz4t.js";
59
+ import"./index-p8jpbrj4.js";
60
60
  import"./index-0wtm7g7f.js";
61
61
  import {
62
62
  setStoragePrivatePermissionEnforcement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.39",
3
+ "version": "0.49.41",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",