@cortexkit/magic-context 0.49.16 → 0.49.18

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 (2) hide show
  1. package/dist/index.js +92 -22
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -12866,6 +12866,7 @@ __export(exports_sqlite, {
12866
12866
  isTransientSqliteError: () => isTransientSqliteError,
12867
12867
  loadSqliteModule: () => loadSqliteModule,
12868
12868
  mayChangeTagIdentity: () => mayChangeTagIdentity,
12869
+ openImmutableDatabase: () => openImmutableDatabase,
12869
12870
  prepareCachedStatement: () => prepareCachedStatement,
12870
12871
  registerSlowWriteReporter: () => registerSlowWriteReporter,
12871
12872
  registerSqliteDiagnosticSink: () => registerSqliteDiagnosticSink,
@@ -12880,6 +12881,7 @@ __export(exports_sqlite, {
12880
12881
  });
12881
12882
  import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
12882
12883
  import { statSync as statSync4 } from "node:fs";
12884
+ import { pathToFileURL } from "node:url";
12883
12885
  function inRootAsyncContext(operation) {
12884
12886
  return resourceRoot.runInAsyncScope(operation);
12885
12887
  }
@@ -12902,6 +12904,14 @@ function detectSqliteRuntime() {
12902
12904
  return hasBunVersion || hasBunGlobal ? "Bun" : "Node.js";
12903
12905
  }
12904
12906
  async function importSqliteModule(specifier) {
12907
+ if (specifier === nodeSpec && typeof process.getBuiltinModule === "function") {
12908
+ const loaded = process.getBuiltinModule(specifier);
12909
+ if (loaded)
12910
+ return loaded;
12911
+ throw Object.assign(new Error(`No such built-in module: ${specifier}`), {
12912
+ code: "ERR_UNKNOWN_BUILTIN_MODULE"
12913
+ });
12914
+ }
12905
12915
  return await import(specifier);
12906
12916
  }
12907
12917
  function isModuleNotFoundError(error, specifier) {
@@ -13198,6 +13208,27 @@ function buildNodeSqliteDatabaseClass(DatabaseSync) {
13198
13208
  }
13199
13209
  return NodeSqliteDatabase;
13200
13210
  }
13211
+ function immutableDatabaseImplementation() {
13212
+ if (!isBun)
13213
+ return DatabaseImpl;
13214
+ if (immutableDatabaseImpl)
13215
+ return immutableDatabaseImpl;
13216
+ const getBuiltinModule = process.getBuiltinModule;
13217
+ if (typeof getBuiltinModule !== "function")
13218
+ throw new SqliteRuntimeUnavailableError("Bun", nodeSpec, new Error("This Bun runtime does not expose process.getBuiltinModule"));
13219
+ const nodeSqlite = getBuiltinModule.call(process, nodeSpec);
13220
+ if (!nodeSqlite?.DatabaseSync)
13221
+ throw new SqliteRuntimeUnavailableError("Bun", nodeSpec, new Error(`No such built-in module: ${nodeSpec}`));
13222
+ immutableDatabaseImpl = buildNodeSqliteDatabaseClass(nodeSqlite.DatabaseSync);
13223
+ return immutableDatabaseImpl;
13224
+ }
13225
+ function openImmutableDatabase(path) {
13226
+ const uri = pathToFileURL(path);
13227
+ uri.searchParams.set("immutable", "1");
13228
+ const target = immutableDatabaseImplementation();
13229
+ const db = inRootAsyncContext(() => Reflect.construct(target, [uri.href, { readonly: true }], target));
13230
+ return trackSqliteConnection(db, uri.href, { readonly: true });
13231
+ }
13201
13232
  function getSqliteDatabasePath(db) {
13202
13233
  for (const connection of trackedSqliteConnections.values()) {
13203
13234
  if (connection.reference.deref() === db) {
@@ -13691,7 +13722,7 @@ async function withIndexChunk(input, operation) {
13691
13722
  async function yieldIndexChunk() {
13692
13723
  await yieldIndexTurn();
13693
13724
  }
13694
- var resourceRoot, reportSlowPrivilegedWrite, sqliteDiagnosticSink, sqliteDiagnosticHost = () => "unknown", bunSpec, nodeSpec, SqliteRuntimeUnavailableError, detectedRuntime, isBun, sqliteModule, DatabaseImpl, trackedSqliteConnections, nextSqliteConnectionSequence = 1, TAG_COLUMNS_OUTSIDE_IDENTITY, tagIdentityWriteGeneration = 0, TrackedDatabase, Database, statementOwners, FIRST_PRUNE_AT = 256, privilegeDepth, transformPassScope, admissionScope, backgroundWriterScope, SqliteAcquisitionBusyError, SHORT_BUSY_TIMEOUT_MS = 25, FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS = 2000, FOREGROUND_ACQUISITION_BUDGET_MS = 16500, SLOW_WRITER_LOG_MS = 100, WRITER_TRANSACTION_END, writerAcquisitionScope, openWriterTransactions, indexCoordinationKey, indexCoordinationHeap, indexCoordinationBuffer, indexCoordinationState, yieldIndexTurn = () => new Promise((resolve) => setTimeout(resolve, 1));
13725
+ var resourceRoot, reportSlowPrivilegedWrite, sqliteDiagnosticSink, sqliteDiagnosticHost = () => "unknown", bunSpec, nodeSpec, SqliteRuntimeUnavailableError, detectedRuntime, isBun, sqliteModule, DatabaseImpl, immutableDatabaseImpl, trackedSqliteConnections, nextSqliteConnectionSequence = 1, TAG_COLUMNS_OUTSIDE_IDENTITY, tagIdentityWriteGeneration = 0, TrackedDatabase, Database, statementOwners, FIRST_PRUNE_AT = 256, privilegeDepth, transformPassScope, admissionScope, backgroundWriterScope, SqliteAcquisitionBusyError, SHORT_BUSY_TIMEOUT_MS = 25, FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS = 2000, FOREGROUND_ACQUISITION_BUDGET_MS = 16500, SLOW_WRITER_LOG_MS = 100, WRITER_TRANSACTION_END, writerAcquisitionScope, openWriterTransactions, indexCoordinationKey, indexCoordinationHeap, indexCoordinationBuffer, indexCoordinationState, yieldIndexTurn = () => new Promise((resolve) => setTimeout(resolve, 1));
13695
13726
  var init_sqlite = __esm(async () => {
13696
13727
  resourceRoot = new AsyncResource("magic-context:root");
13697
13728
  bunSpec = "bun:" + "sqlite";
@@ -27853,7 +27884,7 @@ function installCompartmentHistoryVersions(db) {
27853
27884
 
27854
27885
  // ../plugin/src/features/magic-context/memory/project-identity-cache.ts
27855
27886
  import { createHash as createHash4 } from "node:crypto";
27856
- import { readFileSync as readFileSync15 } from "node:fs";
27887
+ import { promises as fs2, readFileSync as readFileSync15 } from "node:fs";
27857
27888
  import path4 from "node:path";
27858
27889
  function cachePath(directory, storageDir = getMagicContextStorageDir()) {
27859
27890
  const hash = createHash4("sha256").update(projectDirectoryKey(directory)).digest("hex");
@@ -31073,7 +31104,27 @@ function isSystemDirective(text) {
31073
31104
  return text.trimStart().startsWith(SYSTEM_DIRECTIVE_PREFIX);
31074
31105
  }
31075
31106
  function removeSystemReminders(text) {
31076
- return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
31107
+ return removeNestedBlocks(text, ["system-reminder"]).trim();
31108
+ }
31109
+ function removeNestedBlocks(text, names) {
31110
+ const tags = new RegExp(`<(/?)(${names.join("|")})(?:\\s[^<>]*?)?\\s*(/?)>`, "gi");
31111
+ const stack = [];
31112
+ let end = 0;
31113
+ let result = "";
31114
+ for (const match of text.matchAll(tags)) {
31115
+ if (stack.length === 0)
31116
+ result += text.slice(end, match.index);
31117
+ const name = match[2].toLowerCase();
31118
+ if (match[1]) {
31119
+ if (stack[stack.length - 1] === name)
31120
+ stack.pop();
31121
+ } else if (!match[3])
31122
+ stack.push(name);
31123
+ end = match.index + match[0].length;
31124
+ }
31125
+ if (stack.length === 0)
31126
+ result += text.slice(end);
31127
+ return result;
31077
31128
  }
31078
31129
  var SYSTEM_DIRECTIVE_PREFIX = "[SYSTEM DIRECTIVE: MAGIC-CONTEXT";
31079
31130
 
@@ -33394,7 +33445,7 @@ function withRawMessageProvider(sessionId, provider, fn) {
33394
33445
  return result;
33395
33446
  }
33396
33447
  function cleanUserText(text) {
33397
- return stripOutsideSteeringWrappers(text, (segment) => segment.replace(SYSTEM_REMINDER_BLOCK_REGEX, "").replace(OMO_INTERNAL_INITIATOR_MARKER, "")).trim();
33448
+ return stripOutsideSteeringWrappers(text, (segment) => removeSystemReminders(segment).replace(OMO_INTERNAL_INITIATOR_MARKER, "")).trim();
33398
33449
  }
33399
33450
  function hasMeaningfulChunkUserText(parts) {
33400
33451
  for (const part of parts) {
@@ -34277,7 +34328,7 @@ function readRawSessionSeedTail(sessionId, boundaryId, onQuery) {
34277
34328
  return readRawSeedTailFromDb(db, sessionId, boundaryId);
34278
34329
  });
34279
34330
  }
34280
- var BLOCK_TOKEN_MEMO_MAX = 2048, blockTokenMemo, activeRawMessageCache = null, activeAbsoluteCountCache = null, sessionProviders, boundedProviderWrappers, SYSTEM_REMINDER_BLOCK_REGEX, RAW_MESSAGE_RANGE_PAGE_SIZE = 100, RAW_MESSAGE_VISIT_PAGE_SIZE = 50, RAW_SESSION_TAG_KEY_PAGE_SIZE = 32, PROTECTED_TAIL_USER_TURNS = 5;
34331
+ var BLOCK_TOKEN_MEMO_MAX = 2048, blockTokenMemo, activeRawMessageCache = null, activeAbsoluteCountCache = null, sessionProviders, boundedProviderWrappers, RAW_MESSAGE_RANGE_PAGE_SIZE = 100, RAW_MESSAGE_VISIT_PAGE_SIZE = 50, RAW_SESSION_TAG_KEY_PAGE_SIZE = 32, PROTECTED_TAIL_USER_TURNS = 5;
34281
34332
  var init_read_session_chunk = __esm(async () => {
34282
34333
  init_historian_tool_expansions();
34283
34334
  init_logger();
@@ -34296,7 +34347,6 @@ var init_read_session_chunk = __esm(async () => {
34296
34347
  blockTokenMemo = new Map;
34297
34348
  sessionProviders = new Map;
34298
34349
  boundedProviderWrappers = new WeakMap;
34299
- SYSTEM_REMINDER_BLOCK_REGEX = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
34300
34350
  readRawSessionMessages.readPage = readRawSessionMessagePage;
34301
34351
  readRawSessionMessages.getCount = getRawSessionMessageOrdinalCount;
34302
34352
  readRawSessionMessages.prepare = prepareRawSessionOrdinals;
@@ -36334,8 +36384,8 @@ var init_storage_db = __esm(async () => {
36334
36384
 
36335
36385
  // src/lib/database-access.ts
36336
36386
  import { existsSync as existsSync24, rmSync as rmSync6 } from "node:fs";
36337
- import { dirname as dirname13 } from "node:path";
36338
- import { pathToFileURL } from "node:url";
36387
+ import { basename as basename5, dirname as dirname13 } from "node:path";
36388
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
36339
36389
  function getPersistedSchemaVersion2(db) {
36340
36390
  return getPersistedSchemaVersion(db);
36341
36391
  }
@@ -36343,6 +36393,18 @@ function openExistingDatabase(path, options) {
36343
36393
  if (!existsSync24(path))
36344
36394
  return null;
36345
36395
  if (options.readonly) {
36396
+ const name = basename5(path);
36397
+ if ((name === "context.db" || name === "store.db") && !existsSync24(`${path}-wal`) && !existsSync24(`${path}-shm`)) {
36398
+ const probe = probeHostProcessesUsing({
36399
+ files: [path, `${path}-wal`, `${path}-shm`],
36400
+ directories: []
36401
+ });
36402
+ if (probe.status !== "free") {
36403
+ const reason = probe.status === "in_use" ? `database holder PID(s): ${probe.pids.join(", ")}` : probe.reason;
36404
+ throw new Error(`Refusing immutable read-only open of ${path}: ${reason}; close every host and ck-mc first.`);
36405
+ }
36406
+ return openImmutableDatabase(path);
36407
+ }
36346
36408
  const db = new Database(path, { readonly: true });
36347
36409
  return db;
36348
36410
  }
@@ -36350,7 +36412,7 @@ function openExistingDatabase(path, options) {
36350
36412
  const db = new Database(path, { create: false, readwrite: true });
36351
36413
  return db;
36352
36414
  }
36353
- const uri = pathToFileURL(path);
36415
+ const uri = pathToFileURL2(path);
36354
36416
  uri.searchParams.set("mode", "rw");
36355
36417
  const db = new Database(uri.href);
36356
36418
  return db;
@@ -36401,7 +36463,9 @@ async function backupDatabaseSnapshot(db, sourcePath, destination) {
36401
36463
  if (existsSync24(destination)) {
36402
36464
  throw new Error(`Refusing to overwrite existing backup ${destination}`);
36403
36465
  }
36404
- const reader = new Database(sourcePath, { readonly: true });
36466
+ const reader = openExistingDatabase(sourcePath, { readonly: true });
36467
+ if (!reader)
36468
+ throw new Error(`Backup source disappeared: ${sourcePath}`);
36405
36469
  const previousUmask = shouldEnforcePrivateStoragePermissions() ? process.umask(63) : undefined;
36406
36470
  try {
36407
36471
  await sqlite.backup(reader, destination);
@@ -36420,7 +36484,8 @@ var init_database_access = __esm(async () => {
36420
36484
  await __promiseAll([
36421
36485
  init_context_store_uuid(),
36422
36486
  init_storage_db(),
36423
- init_sqlite()
36487
+ init_sqlite(),
36488
+ init_doctor_opencode2_cache()
36424
36489
  ]);
36425
36490
  UnsupportedSchemaVersionError = class UnsupportedSchemaVersionError extends Error {
36426
36491
  path;
@@ -37656,7 +37721,7 @@ var init_conflict_fixer = __esm(() => {
37656
37721
 
37657
37722
  // src/commands/setup-opencode.ts
37658
37723
  import { existsSync as existsSync27 } from "node:fs";
37659
- import { basename as basename5, dirname as dirname15 } from "node:path";
37724
+ import { basename as basename6, dirname as dirname15 } from "node:path";
37660
37725
  function resolveCompactionEnabledForWriter() {
37661
37726
  try {
37662
37727
  const config = loadPluginConfig(process.cwd());
@@ -37966,7 +38031,7 @@ async function runSetup3(dryRun = false) {
37966
38031
  }
37967
38032
  log3.success(`Config written to ${paths.magicContextConfig}`);
37968
38033
  if (hostGeneration === "v1") {
37969
- log3.success(`TUI sidebar plugin added to ${basename5(paths.tuiConfig)}`);
38034
+ log3.success(`TUI sidebar plugin added to ${basename6(paths.tuiConfig)}`);
37970
38035
  } else {
37971
38036
  log3.info("TUI sidebar loads from the plugin entry on OpenCode 2 (tui.json not used)");
37972
38037
  }
@@ -39718,13 +39783,18 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
39718
39783
  if (!existsSync35(engineContextPath()) || realpathSync7(context) !== realpathSync7(engineContextPath()))
39719
39784
  return refuse("single_store_path_mismatch", `CLI ${context}; engine ${engineContextPath()}`);
39720
39785
  const backupRoot = resolve13(options.backupRoot ?? join26(data, "backups"));
39721
- const contextDb = new Database(context, { readonly: true });
39722
- const storeDb = new Database(store, { readonly: true });
39786
+ const contextDb = openExistingDatabase(context, { readonly: true });
39787
+ if (!contextDb)
39788
+ return refuse("single_store_missing_database", `Database disappeared: ${context}`);
39789
+ let storeDb = null;
39723
39790
  let contextVersion;
39724
39791
  let storeVersion;
39725
39792
  let state = null;
39726
39793
  let marker;
39727
39794
  try {
39795
+ storeDb = openExistingDatabase(store, { readonly: true });
39796
+ if (!storeDb)
39797
+ return refuse("single_store_missing_database", `Database disappeared: ${store}`);
39728
39798
  contextVersion = getPersistedSchemaVersion(contextDb);
39729
39799
  storeVersion = storeDb.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM cortexkit_schema_version WHERE namespace = 'mc_cache'").get()?.version ?? 0;
39730
39800
  if (contextDb.prepare("SELECT 1 FROM sqlite_master WHERE name='single_store_state'").get())
@@ -39732,7 +39802,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
39732
39802
  marker = storeVersion >= 58 ? storeDb.prepare("SELECT single_store, single_store_set_at_ms FROM mc_privilege_state WHERE id=1").get() : null;
39733
39803
  } finally {
39734
39804
  contextDb.close();
39735
- storeDb.close();
39805
+ storeDb?.close();
39736
39806
  }
39737
39807
  if (state?.state === "migrated" || marker?.single_store) {
39738
39808
  if (state?.state !== "migrated" || marker?.single_store !== 1 || state.migrated_at !== marker.single_store_set_at_ms)
@@ -39885,7 +39955,7 @@ var init_doctor_single_store = __esm(async () => {
39885
39955
  init_disk_space();
39886
39956
  await __promiseAll([
39887
39957
  init_storage_db(),
39888
- init_sqlite(),
39958
+ init_database_access(),
39889
39959
  init_doctor_opencode2_cache(),
39890
39960
  init_doctor_repair_db(),
39891
39961
  init_doctor_single_store_repair()
@@ -42531,7 +42601,7 @@ var init_auth = __esm(() => {
42531
42601
  });
42532
42602
 
42533
42603
  // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/connection-file.js
42534
- import { promises as fs2 } from "node:fs";
42604
+ import { promises as fs3 } from "node:fs";
42535
42605
  function toBytes(value, field) {
42536
42606
  if (!Array.isArray(value)) {
42537
42607
  throw new ConnectionFileError(`connection file field '${field}' must be a JSON array of bytes`);
@@ -42560,7 +42630,7 @@ function validate(info) {
42560
42630
  async function verifyOwnerOnly(path) {
42561
42631
  if (process.platform === "win32")
42562
42632
  return;
42563
- const stat = await fs2.stat(path);
42633
+ const stat = await fs3.stat(path);
42564
42634
  const mode = stat.mode & 511;
42565
42635
  if ((mode & 63) !== 0) {
42566
42636
  throw new ConnectionFileError(`connection file ${path} has insecure permissions 0o${mode.toString(8)}; expected owner-only 0600`);
@@ -42568,7 +42638,7 @@ async function verifyOwnerOnly(path) {
42568
42638
  }
42569
42639
  async function readConnectionFile(path) {
42570
42640
  await verifyOwnerOnly(path);
42571
- const raw = await fs2.readFile(path, "utf8");
42641
+ const raw = await fs3.readFile(path, "utf8");
42572
42642
  let parsed;
42573
42643
  try {
42574
42644
  parsed = JSON.parse(raw);
@@ -42656,7 +42726,7 @@ var init_route_handle = __esm(() => {
42656
42726
  });
42657
42727
 
42658
42728
  // ../../node_modules/.bun/@cortexkit+subc-client@0.11.1/node_modules/@cortexkit/subc-client/dist/client.js
42659
- import { promises as fs3 } from "node:fs";
42729
+ import { promises as fs4 } from "node:fs";
42660
42730
  import { debuglog } from "node:util";
42661
42731
  function requireBinaryBody(body) {
42662
42732
  if (body instanceof Uint8Array)
@@ -43520,7 +43590,7 @@ function isRetryableRouteOpenCode(code) {
43520
43590
  }
43521
43591
  async function connectionFileExists(path) {
43522
43592
  try {
43523
- await fs3.access(path);
43593
+ await fs4.access(path);
43524
43594
  return true;
43525
43595
  } catch {
43526
43596
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/magic-context",
3
- "version": "0.49.16",
3
+ "version": "0.49.18",
4
4
  "description": "Unified CLI for Magic Context — setup, doctor, and migration across OpenCode, Pi, and OMP",
5
5
  "keywords": [
6
6
  "opencode",