@cortexkit/pi-magic-context 0.40.0 → 0.41.0

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,8 +4,9 @@ import {
4
4
  getLegacyOpenCodeMagicContextStorageDir,
5
5
  getMagicContextStorageDir,
6
6
  log,
7
+ sanitizeDiagnosticText,
7
8
  sessionLog
8
- } from "./index-hk6sj7dn.js";
9
+ } from "./index-3k71e196.js";
9
10
  import {
10
11
  __commonJS,
11
12
  __export,
@@ -8283,153 +8284,6 @@ function migrateMagicContextConfigLocations(directory, logger) {
8283
8284
  return warnings;
8284
8285
  }
8285
8286
 
8286
- // ../plugin/src/shared/redaction.ts
8287
- import { homedir as homedir2, userInfo } from "node:os";
8288
- function escapeRegex(value) {
8289
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8290
- }
8291
- var SECRET_WORDS = [
8292
- "key",
8293
- "token",
8294
- "secret",
8295
- "password",
8296
- "auth",
8297
- "authorization",
8298
- "bearer",
8299
- "credential"
8300
- ];
8301
- var SECRET_SEGMENT_PATTERN = new RegExp(`^(?:${SECRET_WORDS.map((w) => `${w}s?`).join("|")})$`, "i");
8302
- var TRAILING_DESCRIPTORS = new Set(["id", "ids", "value", "values", "header", "headers"]);
8303
- function redactionTypeForKey(key) {
8304
- const normalized = key.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, "_");
8305
- const suffix = normalized.split(".").filter(Boolean).at(-1) ?? normalized;
8306
- return suffix || "secret";
8307
- }
8308
- function isNonSecretScalarValue(value) {
8309
- const v = value.trim();
8310
- if (v === "true" || v === "false" || v === "null" || v === "undefined")
8311
- return true;
8312
- return /^[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(v);
8313
- }
8314
- var SECRET_QUALIFIERS = new Set([
8315
- "api",
8316
- "access",
8317
- "private",
8318
- "client",
8319
- "auth",
8320
- "authorization",
8321
- "secret",
8322
- "bearer",
8323
- "session",
8324
- "refresh",
8325
- "service",
8326
- "x",
8327
- "openai",
8328
- "anthropic",
8329
- "google",
8330
- "github",
8331
- "huggingface",
8332
- "aws",
8333
- "azure"
8334
- ]);
8335
- function sanitizePathString(value) {
8336
- const home = homedir2();
8337
- const username = userInfo().username;
8338
- let sanitized = value;
8339
- if (home) {
8340
- sanitized = sanitized.replace(new RegExp(escapeRegex(home), "g"), "~");
8341
- }
8342
- sanitized = sanitized.replace(/\/Users\/[^/]+\//g, "/Users/<USER>/");
8343
- sanitized = sanitized.replace(/\/home\/[^/]+\//g, "/home/<USER>/");
8344
- sanitized = sanitized.replace(/C:\\Users\\[^\\]+\\/g, "C:\\Users\\<USER>\\");
8345
- if (username) {
8346
- sanitized = sanitized.replace(new RegExp(escapeRegex(username), "g"), "<USER>");
8347
- }
8348
- return sanitized;
8349
- }
8350
- var SECRET_TEXT_PATTERNS = [
8351
- {
8352
- pattern: /\bsk-ant-(?:api03-)?[A-Za-z0-9_-]{32,}/g,
8353
- replacement: "<ANTHROPIC_API_KEY_REDACTED>"
8354
- },
8355
- {
8356
- pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/g,
8357
- replacement: "<OPENAI_API_KEY_REDACTED>"
8358
- },
8359
- {
8360
- pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
8361
- replacement: "<GITHUB_PAT_REDACTED>"
8362
- },
8363
- {
8364
- pattern: /\b(?:gh[opsu]|ghr)_[A-Za-z0-9]{30,}/g,
8365
- replacement: "<GITHUB_TOKEN_REDACTED>"
8366
- },
8367
- {
8368
- pattern: /\bhf_[A-Za-z0-9]{30,}/g,
8369
- replacement: "<HUGGINGFACE_TOKEN_REDACTED>"
8370
- },
8371
- {
8372
- pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
8373
- replacement: "<AWS_ACCESS_KEY_ID_REDACTED>"
8374
- },
8375
- {
8376
- pattern: /\bxox[abprsuvc]-[A-Za-z0-9-]{10,}/g,
8377
- replacement: "<SLACK_TOKEN_REDACTED>"
8378
- },
8379
- {
8380
- pattern: /\bAIza[A-Za-z0-9_-]{35}\b/g,
8381
- replacement: "<GOOGLE_API_KEY_REDACTED>"
8382
- },
8383
- {
8384
- pattern: /\b(Authorization\s*:\s*Bearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi,
8385
- replacement: (_full, prefix) => `${prefix}<REDACTED:bearer>`
8386
- },
8387
- {
8388
- pattern: /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
8389
- replacement: "<JWT_REDACTED>"
8390
- },
8391
- {
8392
- pattern: /(["'])([^"']*(?:key|token|secret|password|auth|bearer|credential)[^"']*)\1(\s*:\s*)(["'])([^"']*)\4/gi,
8393
- replacement: (full, quote, key, separator, valueQuote, value) => isNonSecretScalarValue(value) ? full : `${quote}${key}${quote}${separator}${valueQuote}<REDACTED:${redactionTypeForKey(key)}>${valueQuote}`
8394
- },
8395
- {
8396
- pattern: /\b([A-Za-z0-9_.-]*(?:key|token|secret|password|auth|bearer|credential)[A-Za-z0-9_.-]*)\s*=\s*([^\s'"`]+)/gi,
8397
- replacement: (full, key, value) => isNonSecretScalarValue(value) ? full : `${key}=<REDACTED:${redactionTypeForKey(key)}>`
8398
- }
8399
- ];
8400
- function redactSecretText(value) {
8401
- let redacted = value;
8402
- for (const { pattern, replacement } of SECRET_TEXT_PATTERNS) {
8403
- if (typeof replacement === "string") {
8404
- redacted = redacted.replace(pattern, replacement);
8405
- } else {
8406
- redacted = redacted.replace(pattern, replacement);
8407
- }
8408
- }
8409
- return redacted;
8410
- }
8411
- function sanitizeDiagnosticText(value) {
8412
- return redactSecretText(sanitizePathString(value));
8413
- }
8414
- var SHAREABILITY_SENSITIVE_PATTERNS = [
8415
- /\bC:\/Users\/[^/\s]+/i,
8416
- /(?:^|\s)~\/[^\s]+/,
8417
- /\b(?:api[_-]?key|secret|token|password|passwd|pwd|client[_-]?secret|access[_-]?key)\b\s*[:=]\s*\S+/i,
8418
- /\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\b/i,
8419
- /\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
8420
- /\b192\.168\.\d{1,3}\.\d{1,3}\b/,
8421
- /\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/
8422
- ];
8423
- function hasShareabilitySensitiveText(text) {
8424
- try {
8425
- if (sanitizeDiagnosticText(text) !== text)
8426
- return true;
8427
- return SHAREABILITY_SENSITIVE_PATTERNS.some((pattern) => pattern.test(text));
8428
- } catch {
8429
- return true;
8430
- }
8431
- }
8432
-
8433
8287
  // ../plugin/src/features/magic-context/fail-closed-block.ts
8434
8288
  var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
8435
8289
  var FAIL_CLOSED_REPROBE_EVERY_N = 5;
@@ -8656,7 +8510,7 @@ function createFailClosedController(options) {
8656
8510
  import { execFileSync } from "node:child_process";
8657
8511
  import { createHash } from "node:crypto";
8658
8512
  import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
8659
- import { homedir as homedir3 } from "node:os";
8513
+ import { homedir as homedir2 } from "node:os";
8660
8514
  import path from "node:path";
8661
8515
  var GIT_TIMEOUT_MS = 5000;
8662
8516
  var TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
@@ -8670,7 +8524,7 @@ var dubiousOwnershipLoggedDirectories = new Set;
8670
8524
  var dubiousOwnershipWarnedDirectories = new Set;
8671
8525
  var transientGitIdentityReuseLoggedDirectories = new Set;
8672
8526
  var execFileSyncForIdentity = execFileSync;
8673
- var userHomeDirectoryForIdentity = () => homedir3();
8527
+ var userHomeDirectoryForIdentity = () => homedir2();
8674
8528
  var nowMs = () => Date.now();
8675
8529
 
8676
8530
  class ProjectIdentityError extends Error {
@@ -9026,7 +8880,7 @@ function scheduleAfterBootQuiet(task, additionalDelayMs = 0) {
9026
8880
  // ../plugin/src/hooks/magic-context/read-session-formatting.ts
9027
8881
  import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
9028
8882
  import { createRequire } from "node:module";
9029
- import { homedir as homedir4 } from "node:os";
8883
+ import { homedir as homedir3 } from "node:os";
9030
8884
  import { dirname as dirname2, join as join2, resolve } from "node:path";
9031
8885
  import { pathToFileURL } from "node:url";
9032
8886
 
@@ -9143,7 +8997,7 @@ var tokenizerLoadPromise;
9143
8997
  var tokenizerWarningSent = false;
9144
8998
  function tokenizerPackageRoots() {
9145
8999
  const cwd = process.cwd();
9146
- const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir4(), ".cache"), "opencode");
9000
+ const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir3(), ".cache"), "opencode");
9147
9001
  const roots = [cwd, openCodeCache];
9148
9002
  const candidates = [];
9149
9003
  for (const root of roots) {
@@ -9961,6 +9815,7 @@ function closeQuietly(db) {
9961
9815
 
9962
9816
  // ../plugin/src/features/magic-context/context-authority.ts
9963
9817
  import { createHash as createHash2, randomUUID } from "node:crypto";
9818
+ var observedAuthorityRoutingByProject = new Map;
9964
9819
  var moduleNoteEvaluationBridges = new Map;
9965
9820
  function getModuleNoteEvaluationBridge(projectPath) {
9966
9821
  return moduleNoteEvaluationBridges.get(projectPath);
@@ -10162,6 +10017,17 @@ function unescapeXml(s) {
10162
10017
  return s.replace(/&amp;/g, "&").replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">");
10163
10018
  }
10164
10019
 
10020
+ // ../plugin/src/shared/write-transaction-timing.ts
10021
+ var SLOW_WRITE_TRANSACTION_THRESHOLD_MS = 1000;
10022
+ function logSlowWriteTransaction(site, startedAt, thresholdMs = SLOW_WRITE_TRANSACTION_THRESHOLD_MS) {
10023
+ try {
10024
+ const durationMs = performance.now() - startedAt;
10025
+ if (durationMs < thresholdMs)
10026
+ return;
10027
+ log(`[magic-context] slow write transaction: site=${site} held=${durationMs.toFixed(1)}ms`);
10028
+ } catch {}
10029
+ }
10030
+
10165
10031
  // ../plugin/src/features/magic-context/storage-schema-helpers.ts
10166
10032
  function ensureColumn(db, table, column, definition) {
10167
10033
  if (!/^[a-z][a-z0-9_]*$/.test(table) || !/^[a-z][a-z0-9_]*$/.test(column) || !/^[A-Z0-9_"'(),[\]\s]+$/i.test(definition)) {
@@ -12709,6 +12575,15 @@ var MIGRATIONS = [
12709
12575
  );
12710
12576
  `);
12711
12577
  }
12578
+ },
12579
+ {
12580
+ version: 82,
12581
+ description: "record the origin of memory file-independent mappings",
12582
+ up(db) {
12583
+ if (!tableExists2(db, "memory_verifications"))
12584
+ return;
12585
+ ensureColumn(db, "memory_verifications", "mapping_origin", "TEXT NOT NULL DEFAULT 'mapper'");
12586
+ }
12712
12587
  }
12713
12588
  ];
12714
12589
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -12754,6 +12629,7 @@ function runMigrations(db) {
12754
12629
  let migration;
12755
12630
  let currentVersion = 0;
12756
12631
  try {
12632
+ const transactionStartedAt = performance.now();
12757
12633
  const applied = db.transaction(() => {
12758
12634
  currentVersion = getCurrentVersion(db);
12759
12635
  migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
@@ -12768,6 +12644,7 @@ function runMigrations(db) {
12768
12644
  db.prepare("INSERT INTO schema_migrations (version, description, applied_at) VALUES (?, ?, ?)").run(migration.version, migration.description, Date.now());
12769
12645
  return true;
12770
12646
  }).immediate();
12647
+ logSlowWriteTransaction("migration-runner", transactionStartedAt);
12771
12648
  if (!applied || !migration)
12772
12649
  break;
12773
12650
  if (migration.version <= 61)
@@ -12792,7 +12669,9 @@ function runMigrations(db) {
12792
12669
  }
12793
12670
  if (touchedLegacyAuthorityBatch) {
12794
12671
  try {
12672
+ const transactionStartedAt = performance.now();
12795
12673
  db.transaction(() => installLatestAuthorityTriggers(db)).immediate();
12674
+ logSlowWriteTransaction("migration-runner", transactionStartedAt);
12796
12675
  } catch (error) {
12797
12676
  throw new Error(`Migration authority-trigger postcondition failed: ${error instanceof Error ? error.message : String(error)}. Database may need manual repair.`);
12798
12677
  }
@@ -13143,7 +13022,7 @@ function getSchemaFenceRejection() {
13143
13022
  function getMigrationOnOpenRefusal() {
13144
13023
  return lastMigrationOnOpenRefusal;
13145
13024
  }
13146
- var LATEST_SUPPORTED_VERSION = 81;
13025
+ var LATEST_SUPPORTED_VERSION = 82;
13147
13026
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
13148
13027
  var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
13149
13028
  var storagePermissionFs = defaultStoragePermissionFs;
@@ -13892,8 +13771,10 @@ function initializeDatabase(db) {
13892
13771
  -- verified_at=0 means "mapped (files known) but not yet content-verified".
13893
13772
  -- map-memories sets mapped_at + verified_at=0; verify sets verified_at=now.
13894
13773
  verified_at INTEGER NOT NULL,
13895
- mapped_at INTEGER NOT NULL DEFAULT 0,
13896
- PRIMARY KEY (memory_id, file_path)
13774
+ mapped_at INTEGER NOT NULL DEFAULT 0,
13775
+ -- Distinguishes mapper-authored independence from a host rejection fallback.
13776
+ mapping_origin TEXT NOT NULL DEFAULT 'mapper',
13777
+ PRIMARY KEY (memory_id, file_path)
13897
13778
  );
13898
13779
  CREATE INDEX IF NOT EXISTS idx_memory_verifications_memory ON memory_verifications(memory_id);
13899
13780
 
@@ -14085,8 +13966,6 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
14085
13966
  updated_at INTEGER NOT NULL,
14086
13967
  harness TEXT NOT NULL DEFAULT 'opencode'
14087
13968
  );
14088
- CREATE INDEX IF NOT EXISTS idx_message_history_index_orphan_sweep
14089
- ON message_history_index(harness, session_id, updated_at);
14090
13969
 
14091
13970
  CREATE TABLE IF NOT EXISTS message_history_source (
14092
13971
  session_id TEXT NOT NULL,
@@ -14673,6 +14552,10 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
14673
14552
  ensureColumn(db, "recomp_compartments", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
14674
14553
  ensureColumn(db, "recomp_facts", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
14675
14554
  ensureColumn(db, "message_history_index", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
14555
+ db.exec(`
14556
+ CREATE INDEX IF NOT EXISTS idx_message_history_index_orphan_sweep
14557
+ ON message_history_index(harness, session_id, updated_at);
14558
+ `);
14676
14559
  ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
14677
14560
  }
14678
14561
  var CHANNEL2_CLAIM_TTL_MS = 10 * 60000;
@@ -15152,6 +15035,13 @@ function clearCachedM0M1(db, sessionId) {
15152
15035
  var emergencyRecoveryArmedSessions = new Set;
15153
15036
  var emergencyRecoveryArmedAtBySession = new Map;
15154
15037
  var providerOverflowReconfirmedSessions = new Set;
15038
+ function describeProtectedTailDrainBudgetSkip(result) {
15039
+ const state = result.budgetState;
15040
+ if (!state)
15041
+ return "historian skip: internal drain budget spent";
15042
+ const resetMinutes = Math.max(1, Math.ceil(state.resetInMs / 60000));
15043
+ return `historian skip: internal drain budget spent (${state.spentTokens}/${state.limitTokens} tokens; resets in ${resetMinutes}m)`;
15044
+ }
15155
15045
  var CAS_RETRY_LIMIT = 5;
15156
15046
  var AUTO_SEARCH_NO_HINT_REASONS = new Set([
15157
15047
  "below-threshold",
@@ -15498,19 +15388,28 @@ function reserveProtectedTailDrainTokens(args) {
15498
15388
  const now = args.now ?? Date.now();
15499
15389
  const requested = Math.max(0, Math.floor(args.trueRawTokens));
15500
15390
  if (requested === 0) {
15501
- return { ok: true, reservedTokens: 0, overQuotaBypass: false, reservation: null };
15391
+ return {
15392
+ ok: true,
15393
+ reservedTokens: 0,
15394
+ overQuotaBypass: false,
15395
+ reservation: null,
15396
+ budgetState: null
15397
+ };
15502
15398
  }
15503
15399
  let result = {
15504
15400
  ok: false,
15505
15401
  reservedTokens: 0,
15506
15402
  overQuotaBypass: false,
15507
15403
  reservation: null,
15508
- skippedReason: "quota exhausted"
15404
+ budgetState: null,
15405
+ skippedReason: "internal drain budget spent"
15509
15406
  };
15510
15407
  args.db.transaction(() => {
15511
15408
  ensureSessionMetaRow(args.db, args.sessionId);
15512
15409
  let meta = loadProtectedTailMeta(args.db, args.sessionId);
15513
- if (now - meta.protectedTailDrainWindowStartedAt > DRAIN_WINDOW_MS) {
15410
+ const windowStartedAt = meta.protectedTailDrainWindowStartedAt;
15411
+ const windowExpired = windowStartedAt <= 0 || windowStartedAt > now || now - windowStartedAt >= DRAIN_WINDOW_MS;
15412
+ if (windowExpired) {
15514
15413
  args.db.prepare(`UPDATE session_meta
15515
15414
  SET protected_tail_drain_window_started_at = ?, protected_tail_drain_tokens = 0
15516
15415
  WHERE session_id = ?`).run(now, args.sessionId);
@@ -15535,22 +15434,35 @@ function reserveProtectedTailDrainTokens(args) {
15535
15434
  const remaining = Math.max(0, budget - meta.protectedTailDrainTokens);
15536
15435
  let reserved = Math.min(requested, args.perRunCap, remaining);
15537
15436
  let bypass = false;
15538
- const inFailureBackoff = meta.historianDrainFailureAt > 0 && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
15437
+ const inFailureBackoff = meta.historianDrainFailureAt > 0 && meta.historianDrainFailureAt <= now && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
15539
15438
  if (reserved <= 0 && latchActive && !inFailureBackoff) {
15540
15439
  reserved = Math.min(requested, args.perRunCap);
15541
15440
  bypass = true;
15542
15441
  }
15543
- if (reserved <= 0)
15442
+ const activeWindowStartedAt = meta.protectedTailDrainWindowStartedAt;
15443
+ const budgetState = (spentTokens) => ({
15444
+ windowStartedAt: activeWindowStartedAt,
15445
+ resetsAt: activeWindowStartedAt + DRAIN_WINDOW_MS,
15446
+ resetInMs: Math.max(0, activeWindowStartedAt + DRAIN_WINDOW_MS - now),
15447
+ spentTokens,
15448
+ limitTokens: budget
15449
+ });
15450
+ if (reserved <= 0) {
15451
+ result = {
15452
+ ...result,
15453
+ budgetState: budgetState(meta.protectedTailDrainTokens)
15454
+ };
15544
15455
  return;
15456
+ }
15545
15457
  args.db.prepare(`UPDATE session_meta
15546
- SET protected_tail_drain_window_started_at = CASE WHEN protected_tail_drain_window_started_at = 0 THEN ? ELSE protected_tail_drain_window_started_at END,
15547
- protected_tail_drain_tokens = COALESCE(protected_tail_drain_tokens, 0) + ?
15548
- WHERE session_id = ?`).run(now, reserved, args.sessionId);
15458
+ SET protected_tail_drain_tokens = COALESCE(protected_tail_drain_tokens, 0) + ?
15459
+ WHERE session_id = ?`).run(reserved, args.sessionId);
15549
15460
  result = {
15550
15461
  ok: true,
15551
15462
  reservedTokens: reserved,
15552
15463
  overQuotaBypass: bypass,
15553
- reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved }
15464
+ reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved },
15465
+ budgetState: budgetState(meta.protectedTailDrainTokens + reserved)
15554
15466
  };
15555
15467
  })();
15556
15468
  return result;
@@ -15624,19 +15536,38 @@ function parseChannel1NudgeState(raw) {
15624
15536
  try {
15625
15537
  const parsed = JSON.parse(raw);
15626
15538
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
15627
- return {
15539
+ const state = {
15628
15540
  level: normalizeLastNudgeLevel(parsed.level),
15629
15541
  ordinal: typeof parsed.ordinal === "number" ? Math.max(0, Math.round(parsed.ordinal)) : 0
15630
15542
  };
15543
+ if (parsed.postReduceGracePending === true)
15544
+ state.postReduceGracePending = true;
15545
+ if (typeof parsed.postReduceGraceBaselineU === "number" && Number.isFinite(parsed.postReduceGraceBaselineU)) {
15546
+ state.postReduceGraceBaselineU = Math.max(0, Math.round(parsed.postReduceGraceBaselineU));
15547
+ }
15548
+ const preLevel = normalizeLastNudgeLevel(parsed.postReduceGracePreLevel);
15549
+ if (preLevel !== "" || parsed.postReduceGracePreLevel === "") {
15550
+ state.postReduceGracePreLevel = preLevel;
15551
+ }
15552
+ return state;
15631
15553
  }
15632
15554
  } catch {}
15633
15555
  return { level: normalizeLastNudgeLevel(raw), ordinal: 0 };
15634
15556
  }
15635
15557
  function serializeChannel1NudgeState(value) {
15636
- return JSON.stringify({
15558
+ const serialized = {
15637
15559
  level: normalizeLastNudgeLevel(value.level),
15638
15560
  ordinal: Math.max(0, Math.round(value.ordinal))
15639
- });
15561
+ };
15562
+ if (value.postReduceGracePending === true)
15563
+ serialized.postReduceGracePending = true;
15564
+ if (value.postReduceGraceBaselineU !== undefined) {
15565
+ serialized.postReduceGraceBaselineU = Math.max(0, Math.round(value.postReduceGraceBaselineU));
15566
+ }
15567
+ if (value.postReduceGracePreLevel !== undefined) {
15568
+ serialized.postReduceGracePreLevel = normalizeLastNudgeLevel(value.postReduceGracePreLevel);
15569
+ }
15570
+ return JSON.stringify(serialized);
15640
15571
  }
15641
15572
  function getLastNudgeUndropped(db, sessionId) {
15642
15573
  const result = db.prepare("SELECT last_nudge_undropped FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -15658,20 +15589,36 @@ function setChannel1NudgeState(db, sessionId, value) {
15658
15589
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
15659
15590
  })();
15660
15591
  }
15661
- function resetLastNudgeCycle(db, sessionId) {
15662
- db.transaction(() => {
15592
+ function markChannel1PostReduceGracePending(db, sessionId) {
15593
+ return db.transaction(() => {
15663
15594
  ensureSessionMetaRow(db, sessionId);
15664
- db.prepare("UPDATE session_meta SET last_nudge_undropped = 0, last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(EMPTY_CHANNEL1_NUDGE_STATE), sessionId);
15595
+ const current = getChannel1NudgeState(db, sessionId);
15596
+ const next = {
15597
+ level: current.level,
15598
+ ordinal: current.ordinal,
15599
+ postReduceGracePending: true,
15600
+ postReduceGracePreLevel: current.level
15601
+ };
15602
+ db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
15603
+ return next;
15665
15604
  })();
15666
15605
  }
15667
- function resetLastNudgeCycleIfTailShrank(db, sessionId, measuredUndropped) {
15668
- let changed = false;
15669
- db.transaction(() => {
15606
+ function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
15607
+ return db.transaction(() => {
15670
15608
  ensureSessionMetaRow(db, sessionId);
15671
- const result = db.prepare("UPDATE session_meta SET last_nudge_undropped = 0, last_nudge_level = ? WHERE session_id = ? AND last_nudge_undropped > ?").run(serializeChannel1NudgeState(EMPTY_CHANNEL1_NUDGE_STATE), sessionId, Math.max(0, Math.round(measuredUndropped)));
15672
- changed = (result.changes ?? 0) > 0;
15609
+ const current = getChannel1NudgeState(db, sessionId);
15610
+ if (current.postReduceGracePending !== true)
15611
+ return current;
15612
+ const baselineU = Math.max(0, Math.round(measuredUndropped));
15613
+ const next = {
15614
+ level: current.level,
15615
+ ordinal: current.ordinal,
15616
+ postReduceGraceBaselineU: baselineU,
15617
+ postReduceGracePreLevel: current.postReduceGracePreLevel ?? current.level
15618
+ };
15619
+ db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
15620
+ return next;
15673
15621
  })();
15674
- return changed;
15675
15622
  }
15676
15623
  function isChannel2StateRow(row) {
15677
15624
  return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
@@ -16471,9 +16418,11 @@ function retryPendingSessionCleanups(db, limit = 200) {
16471
16418
  return { attempted: rows.length, cleared, failedSessionIds };
16472
16419
  }
16473
16420
  function clearSession(db, sessionId) {
16421
+ const transactionStartedAt = performance.now();
16474
16422
  db.transaction(() => {
16475
16423
  deleteSessionScopedRows(db, [sessionId]);
16476
16424
  })();
16425
+ logSlowWriteTransaction("clear-session", transactionStartedAt);
16477
16426
  }
16478
16427
  // ../plugin/src/hooks/magic-context/todo-view.ts
16479
16428
  import { createHash as createHash4 } from "node:crypto";
@@ -17354,15 +17303,32 @@ function buildToolArcs(messages) {
17354
17303
  }
17355
17304
  return arcs.sort((a, b) => a.invOrdinal - b.invOrdinal || (a.resOrdinal ?? Number.MAX_SAFE_INTEGER) - (b.resOrdinal ?? Number.MAX_SAFE_INTEGER));
17356
17305
  }
17306
+ function fenceBoundaryForCompletedToolArcs(candidate, arcs, publicationFloorOrdinal) {
17307
+ const completed = arcs.filter((arc) => arc.resOrdinal !== null).map((arc) => ({ invocation: arc.invOrdinal, result: arc.resOrdinal }));
17308
+ const component = completed.filter((arc) => completedToolArcCrossesBoundary(arc.invocation, arc.result, candidate));
17309
+ if (component.length === 0)
17310
+ return candidate;
17311
+ for (let pass = 0;pass <= completed.length; pass += 1) {
17312
+ const minInvocation2 = Math.min(...component.map((arc) => arc.invocation));
17313
+ const maxResult2 = Math.max(...component.map((arc) => arc.result));
17314
+ const before = component.length;
17315
+ for (const arc of completed) {
17316
+ if (arc.invocation <= maxResult2 && arc.result >= minInvocation2 && !component.includes(arc)) {
17317
+ component.push(arc);
17318
+ }
17319
+ }
17320
+ if (component.length === before)
17321
+ break;
17322
+ }
17323
+ const minInvocation = Math.min(...component.map((arc) => arc.invocation));
17324
+ const maxResult = Math.max(...component.map((arc) => arc.result));
17325
+ return minInvocation < publicationFloorOrdinal ? maxResult + 1 : minInvocation;
17326
+ }
17357
17327
  function fenceBoundaryForToolArcs(candidate, arcs, lastCompartmentEndOrdinal, recentOpenArcCutoff) {
17358
- let boundary = candidate;
17328
+ const boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
17359
17329
  for (const arc of arcs) {
17360
- if (arc.resOrdinal !== null) {
17361
- if (completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, boundary)) {
17362
- boundary = arc.resOrdinal + 1;
17363
- }
17330
+ if (arc.resOrdinal !== null)
17364
17331
  continue;
17365
- }
17366
17332
  if (arc.invOrdinal < recentOpenArcCutoff)
17367
17333
  continue;
17368
17334
  if (arc.invOrdinal >= lastCompartmentEndOrdinal + 1 && arc.invOrdinal < boundary) {
@@ -19804,47 +19770,74 @@ function decideChannel1(input) {
19804
19770
  const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
19805
19771
  const undroppedTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
19806
19772
  const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
19807
- const resetCycle = input.hasRecentReduce || undroppedTokens < input.lastNudgeUndropped;
19808
- const lastNudge = resetCycle ? 0 : input.lastNudgeUndropped;
19809
- const lastLevel = resetCycle ? "" : input.lastNudgeLevel;
19810
- const quiet = () => ({
19773
+ const previousLevel = input.lastNudgeLevel;
19774
+ let lastNudge = Math.max(0, input.lastNudgeUndropped);
19775
+ let nextLevel = previousLevel;
19776
+ let clearPostReduceGrace = false;
19777
+ const quiet = (level2 = "gentle") => ({
19811
19778
  fire: false,
19812
- level: "gentle",
19779
+ sticky: false,
19780
+ level: level2,
19813
19781
  undroppedTokens,
19814
19782
  tailTokens,
19815
19783
  severity,
19816
19784
  nextLastNudge: lastNudge,
19817
- nextLastNudgeLevel: lastLevel
19785
+ nextLastNudgeLevel: nextLevel,
19786
+ clearPostReduceGrace
19818
19787
  });
19819
19788
  if (input.evaluable === false || input.generationInvalidated === true)
19820
19789
  return quiet();
19821
- if (input.hasRecentReduce)
19790
+ if (input.hasRecentReduce || input.postReduceGracePending)
19822
19791
  return quiet();
19823
- if (tailTokens < CHANNEL1_MIN_TOKENS)
19824
- return quiet();
19825
- if (undroppedTokens < CHANNEL1_FLOOR_TOKENS || undroppedTokens === 0)
19826
- return quiet();
19827
- if (severity < S_GENTLE)
19828
- return quiet();
19829
- let level;
19830
- if (severity >= S_URGENT)
19831
- level = "urgent";
19832
- else if (severity >= S_FIRM)
19833
- level = "firm";
19834
- else
19835
- level = "gentle";
19836
- const escalated = lastLevel === "" || LEVEL_RANK[level] > LEVEL_RANK[lastLevel];
19837
- const cadenceReached = lastLevel !== "" && undroppedTokens - lastNudge >= channel1RefireTokens(tailTokens);
19838
- if (!escalated && !cadenceReached)
19792
+ let level = "";
19793
+ if (tailTokens >= CHANNEL1_MIN_TOKENS && undroppedTokens >= CHANNEL1_FLOOR_TOKENS && severity >= S_GENTLE) {
19794
+ if (severity >= S_URGENT)
19795
+ level = "urgent";
19796
+ else if (severity >= S_FIRM)
19797
+ level = "firm";
19798
+ else
19799
+ level = "gentle";
19800
+ }
19801
+ const previousRank = previousLevel === "" ? 0 : LEVEL_RANK[previousLevel];
19802
+ const currentRank = level === "" ? 0 : LEVEL_RANK[level];
19803
+ const graceBaseline = input.postReduceGraceBaselineU;
19804
+ if (graceBaseline !== undefined) {
19805
+ const preReduceLevel = input.postReduceGracePreLevel ?? previousLevel;
19806
+ const preReduceRank = preReduceLevel === "" ? 0 : LEVEL_RANK[preReduceLevel];
19807
+ const regrowthReached = undroppedTokens - Math.max(0, graceBaseline) >= channel1RefireTokens(tailTokens);
19808
+ const escalatedAbovePreReduceBand = currentRank > preReduceRank;
19809
+ if (!regrowthReached && !escalatedAbovePreReduceBand) {
19810
+ return quiet(level === "" ? "gentle" : level);
19811
+ }
19812
+ clearPostReduceGrace = true;
19813
+ }
19814
+ if (level === "") {
19815
+ nextLevel = "";
19816
+ lastNudge = 0;
19839
19817
  return quiet();
19818
+ }
19819
+ if (currentRank < previousRank) {
19820
+ nextLevel = level;
19821
+ lastNudge = undroppedTokens;
19822
+ return quiet(level);
19823
+ }
19824
+ const crossedFromBelow = currentRank > previousRank;
19825
+ const cadenceReached = currentRank === previousRank && undroppedTokens - lastNudge >= channel1RefireTokens(tailTokens);
19826
+ const currentTurn = input.currentRealUserTurnCount;
19827
+ const lastFireTurn = input.lastFireOrdinal;
19828
+ const stickyTurnGapReached = currentTurn === undefined || lastFireTurn === undefined || lastFireTurn > currentTurn || currentTurn - lastFireTurn >= CHANNEL1_STICKY_REAL_USER_TURN_GAP;
19829
+ if (!crossedFromBelow && (!cadenceReached || !stickyTurnGapReached))
19830
+ return quiet(level);
19840
19831
  return {
19841
19832
  fire: true,
19833
+ sticky: !crossedFromBelow,
19842
19834
  level,
19843
19835
  undroppedTokens,
19844
19836
  tailTokens,
19845
19837
  severity,
19846
19838
  nextLastNudge: undroppedTokens,
19847
- nextLastNudgeLevel: level
19839
+ nextLastNudgeLevel: level,
19840
+ clearPostReduceGrace
19848
19841
  };
19849
19842
  }
19850
19843
  var CHANNEL2_SEVERITY_THRESHOLD = 0.75;
@@ -19881,44 +19874,42 @@ function formatOldestReclaimableHint(hint) {
19881
19874
  return rendered.length > 0 ? `
19882
19875
  oldest reclaimable: ${rendered}.` : "";
19883
19876
  }
19884
- function buildChannel2Reminder(undroppedTokens, usableWindowTokens, hint) {
19885
- const amount = approxThousands(undroppedTokens);
19886
- const usableWindow = approxThousands(usableWindowTokens);
19877
+ function reclaimableToolOutputCount(parts) {
19878
+ return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
19879
+ }
19880
+ function formatReclaimableOutputSummary(count, tokens) {
19881
+ const outputCount = Math.max(0, Math.floor(count));
19882
+ const outputs = outputCount === 0 ? "spent tool outputs" : `${outputCount} spent tool output${outputCount === 1 ? "" : "s"}`;
19883
+ return `${outputs} (~${approxThousands(tokens)} tokens)`;
19884
+ }
19885
+ function buildChannel2Reminder(undroppedTokens, reclaimableToolOutputs, hint) {
19886
+ const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
19887
19887
  const hintText = formatOldestReclaimableHint(hint);
19888
19888
  return `<system-reminder>
19889
- ` + `Routine housekeeping: an older span of this session folds into compact history automatically — nothing is lost and nothing pauses. ` + `Drop spent tool outputs with ctx_reduce first so the archive keeps only what matters (~${amount} of ~${usableWindow} reclaimable).${hintText}
19889
+ ` + `Routine housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.${hintText}
19890
19890
  ` + `</system-reminder>`;
19891
19891
  }
19892
- var CHANNEL1_STICKY_REAL_USER_TURN_GAP = 3;
19893
- function shouldUseStickyChannel1Reminder(input) {
19894
- if (input.lastLevel !== input.level)
19895
- return false;
19896
- if (input.lastOrdinal > input.currentRealUserTurnCount)
19897
- return false;
19898
- const gap = input.currentRealUserTurnCount - input.lastOrdinal;
19899
- return gap >= 0 && gap < CHANNEL1_STICKY_REAL_USER_TURN_GAP;
19900
- }
19901
- function buildChannel1Reminder(level, undroppedTokens, usableWindowTokens, hint, sticky = false) {
19892
+ var CHANNEL1_STICKY_REAL_USER_TURN_GAP = 5;
19893
+ function buildChannel1Reminder(level, undroppedTokens, reclaimableToolOutputs, hint, sticky = false) {
19894
+ const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
19902
19895
  const hintText = formatOldestReclaimableHint(hint);
19903
19896
  if (sticky) {
19904
19897
  return `
19905
19898
 
19906
19899
  <system-reminder>
19907
- Reminder: ctx_reduce housekeeping still pending —${hintText}
19900
+ Reminder: ${summary} are still reclaimable — ctx_reduce them at a natural stopping point.${hintText}
19908
19901
  </system-reminder>`;
19909
19902
  }
19910
- const amount = approxThousands(undroppedTokens);
19911
- const usableWindow = approxThousands(usableWindowTokens);
19912
19903
  let body;
19913
19904
  switch (level) {
19914
19905
  case "gentle":
19915
- body = `Housekeeping: some earlier tool outputs are spent and can be dropped with ctx_reduce when you are done with them. ` + `Context is managed automatically — this is tidiness, never a reason to rush or narrow scope.`;
19906
+ body = `Housekeeping: ${summary} are reclaimable — drop the ones you have already processed with ctx_reduce at a natural stopping point.`;
19916
19907
  break;
19917
19908
  case "firm":
19918
- body = `Housekeeping: ~${amount} of this session's ~${usableWindow} window is spent tool output. ` + `Drop what you have already processed with ctx_reduce at a natural stopping point. ` + `Not a limit — nothing is lost either way.`;
19909
+ body = `Housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.`;
19919
19910
  break;
19920
19911
  case "urgent":
19921
- body = `Housekeeping backlog: ~${amount} of this session's ~${usableWindow} window is spent tool output — worth a ctx_reduce pass now. ` + `This is routine and lossless; it is never a reason to change scope.`;
19912
+ body = `Housekeeping backlog: ${summary} are reclaimable — a ctx_reduce pass is due.`;
19922
19913
  break;
19923
19914
  }
19924
19915
  return `
@@ -19979,8 +19970,8 @@ function planEmergencyDrop(input) {
19979
19970
  if (!Number.isFinite(currentTotalInputTokens) || currentTotalInputTokens <= 0) {
19980
19971
  return noop("unknown-usage");
19981
19972
  }
19982
- if (hasPriorDrop && currentTotalInputTokens === priorInputSample) {
19983
- return noop("same-input-sample (awaiting fresh usage after prior drop)");
19973
+ if (hasPriorDrop) {
19974
+ return noop(`pressure-episode-latched (prior sample ${priorInputSample}; awaiting exit or independent bust)`);
19984
19975
  }
19985
19976
  let tailTokens = 0;
19986
19977
  for (const tag of floorTags) {
@@ -20109,6 +20100,7 @@ function updateTagByteSize(db, sessionId, tagNumber, newByteSize) {
20109
20100
  getUpdateTagByteSizeStatement(db).run(newByteSize, sessionId, tagNumber);
20110
20101
  }
20111
20102
  var CONTENT_ID_SUFFIX = /:(?:p|file)\d+$/;
20103
+ var recentTagOwnerStatements = new WeakMap;
20112
20104
  function ownerMessageIdForTagRow(row) {
20113
20105
  if (row.type === "tool") {
20114
20106
  return row.tool_owner_message_id ?? row.message_id;
@@ -21218,22 +21210,28 @@ function getToolCallIds(content) {
21218
21210
  }
21219
21211
  return ids;
21220
21212
  }
21221
- function readPiSessionMessages(ctx) {
21213
+ function readPiSessionSnapshot(ctx) {
21222
21214
  const sm = ctx.sessionManager;
21223
21215
  if (sm === undefined)
21224
- return [];
21216
+ return { branchEntries: [], rawMessages: [] };
21225
21217
  const getBranch = sm.getBranch;
21226
21218
  if (typeof getBranch !== "function")
21227
- return [];
21219
+ return { branchEntries: [], rawMessages: [] };
21228
21220
  let entries;
21229
21221
  try {
21230
21222
  entries = getBranch.call(sm);
21231
21223
  } catch {
21232
- return [];
21224
+ return { branchEntries: [], rawMessages: [] };
21233
21225
  }
21234
21226
  if (!Array.isArray(entries))
21235
- return [];
21236
- return convertEntriesToRawMessages(entries);
21227
+ return { branchEntries: [], rawMessages: [] };
21228
+ return {
21229
+ branchEntries: entries,
21230
+ rawMessages: convertEntriesToRawMessages(entries)
21231
+ };
21232
+ }
21233
+ function readPiSessionMessages(ctx) {
21234
+ return readPiSessionSnapshot(ctx).rawMessages;
21237
21235
  }
21238
21236
  function findLastModelKeyFromBranch(entries) {
21239
21237
  if (!Array.isArray(entries))
@@ -21783,7 +21781,7 @@ function migrateLegacyExperimental(rawConfig, warnings) {
21783
21781
  }
21784
21782
 
21785
21783
  // ../plugin/src/config/schema/magic-context.ts
21786
- import { homedir as homedir5 } from "node:os";
21784
+ import { homedir as homedir4 } from "node:os";
21787
21785
 
21788
21786
  // ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
21789
21787
  var exports_external = {};
@@ -22410,7 +22408,7 @@ __export(exports_util, {
22410
22408
  createTransparentProxy: () => createTransparentProxy,
22411
22409
  defineLazy: () => defineLazy,
22412
22410
  esc: () => esc,
22413
- escapeRegex: () => escapeRegex2,
22411
+ escapeRegex: () => escapeRegex,
22414
22412
  explicitlyAborted: () => explicitlyAborted,
22415
22413
  extend: () => extend,
22416
22414
  finalizeIssue: () => finalizeIssue,
@@ -22687,7 +22685,7 @@ var primitiveTypes = /* @__PURE__ */ new Set([
22687
22685
  "symbol",
22688
22686
  "undefined"
22689
22687
  ]);
22690
- function escapeRegex2(str) {
22688
+ function escapeRegex(str) {
22691
22689
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22692
22690
  }
22693
22691
  function clone(inst, def, params) {
@@ -23397,7 +23395,7 @@ function emoji() {
23397
23395
  var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
23398
23396
  var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
23399
23397
  var mac = (delimiter) => {
23400
- const escapedDelim = escapeRegex2(delimiter ?? ":");
23398
+ const escapedDelim = escapeRegex(delimiter ?? ":");
23401
23399
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
23402
23400
  };
23403
23401
  var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
@@ -23898,7 +23896,7 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins
23898
23896
  });
23899
23897
  var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
23900
23898
  $ZodCheck.init(inst, def);
23901
- const escapedRegex = escapeRegex2(def.includes);
23899
+ const escapedRegex = escapeRegex(def.includes);
23902
23900
  const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
23903
23901
  def.pattern = pattern;
23904
23902
  inst._zod.onattach.push((inst2) => {
@@ -23922,7 +23920,7 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst,
23922
23920
  });
23923
23921
  var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
23924
23922
  $ZodCheck.init(inst, def);
23925
- const pattern = new RegExp(`^${escapeRegex2(def.prefix)}.*`);
23923
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
23926
23924
  def.pattern ?? (def.pattern = pattern);
23927
23925
  inst._zod.onattach.push((inst2) => {
23928
23926
  const bag = inst2._zod.bag;
@@ -23945,7 +23943,7 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i
23945
23943
  });
23946
23944
  var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
23947
23945
  $ZodCheck.init(inst, def);
23948
- const pattern = new RegExp(`.*${escapeRegex2(def.suffix)}$`);
23946
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
23949
23947
  def.pattern ?? (def.pattern = pattern);
23950
23948
  inst._zod.onattach.push((inst2) => {
23951
23949
  const bag = inst2._zod.bag;
@@ -25592,7 +25590,7 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
25592
25590
  const values = getEnumValues(def.entries);
25593
25591
  const valuesSet = new Set(values);
25594
25592
  inst._zod.values = valuesSet;
25595
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(o) : o.toString()).join("|")})$`);
25593
+ inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
25596
25594
  inst._zod.parse = (payload, _ctx) => {
25597
25595
  const input = payload.value;
25598
25596
  if (valuesSet.has(input)) {
@@ -25614,7 +25612,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
25614
25612
  }
25615
25613
  const values = new Set(def.values);
25616
25614
  inst._zod.values = values;
25617
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex2(o) : o ? escapeRegex2(o.toString()) : String(o)).join("|")})$`);
25615
+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
25618
25616
  inst._zod.parse = (payload, _ctx) => {
25619
25617
  const input = payload.value;
25620
25618
  if (values.has(input)) {
@@ -25979,7 +25977,7 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i
25979
25977
  const end = source.endsWith("$") ? source.length - 1 : source.length;
25980
25978
  regexParts.push(source.slice(start, end));
25981
25979
  } else if (part === null || primitiveTypes.has(typeof part)) {
25982
- regexParts.push(escapeRegex2(`${part}`));
25980
+ regexParts.push(escapeRegex(`${part}`));
25983
25981
  } else {
25984
25982
  throw new Error(`Invalid template literal part: ${part}`);
25985
25983
  }
@@ -36555,9 +36553,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
36555
36553
  function expandConfigPath(value) {
36556
36554
  const trimmed = value.trim();
36557
36555
  if (trimmed === "~")
36558
- return homedir5();
36556
+ return homedir4();
36559
36557
  if (trimmed.startsWith("~/"))
36560
- return `${homedir5()}/${trimmed.slice(2)}`;
36558
+ return `${homedir4()}/${trimmed.slice(2)}`;
36561
36559
  return trimmed;
36562
36560
  }
36563
36561
  var BaseEmbeddingConfigSchema = exports_external.object({
@@ -38998,12 +38996,12 @@ function loadRawConfigFile(options) {
38998
38996
 
38999
38997
  // ../plugin/src/config/variable.ts
39000
38998
  import { existsSync as existsSync10, readFileSync as readFileSync9 } from "node:fs";
39001
- import { homedir as homedir6 } from "node:os";
38999
+ import { homedir as homedir5 } from "node:os";
39002
39000
  import { dirname as dirname6, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
39003
39001
  var ENV_PATTERN = /\{env:([^}]+)\}/g;
39004
39002
  var FILE_PATTERN = /\{file:([^}]+)\}/g;
39005
39003
  function sensitiveFilePathReason(resolvedPath) {
39006
- const home = homedir6();
39004
+ const home = homedir5();
39007
39005
  const sensitiveDirs = [
39008
39006
  { dir: resolve4(home, ".ssh"), label: "SSH keys" },
39009
39007
  { dir: resolve4(home, ".aws"), label: "AWS credentials" },
@@ -39066,7 +39064,7 @@ function substituteConfigVariables(input) {
39066
39064
  }
39067
39065
  let filePath = rawPath.trim();
39068
39066
  if (filePath.startsWith("~/")) {
39069
- filePath = resolve4(homedir6(), filePath.slice(2));
39067
+ filePath = resolve4(homedir5(), filePath.slice(2));
39070
39068
  } else if (!isAbsolute3(filePath)) {
39071
39069
  filePath = resolve4(configDir, filePath);
39072
39070
  }
@@ -42708,33 +42706,123 @@ function startLockHeartbeat(lockPath) {
42708
42706
  timer.unref?.();
42709
42707
  return () => clearInterval(timer);
42710
42708
  }
42711
- async function injectWasmOrtForElectron() {
42712
- if (typeof process === "undefined" || !process.versions?.electron) {
42709
+ var localEmbeddingRuntimeMode = "native";
42710
+ var wasmRuntimeInjected = false;
42711
+ var isElectronForRuntime = () => typeof process !== "undefined" && Boolean(process.versions?.electron);
42712
+ var importWasmOrtForRuntime = async () => {
42713
+ const ortWebSpec = `onnxruntime-${"web"}`;
42714
+ return await import(ortWebSpec);
42715
+ };
42716
+ var importTransformersForRuntime = async () => {
42717
+ const transformersSpec = "@huggingface/transformers";
42718
+ return await import(transformersSpec);
42719
+ };
42720
+ var importTransformersWasmFallbackForRuntime = async () => {
42721
+ const { createRequire: createRequireFn } = await import("node:module");
42722
+ const requireFn = createRequireFn(import.meta.url);
42723
+ const nodeEntry = requireFn.resolve("@huggingface/transformers");
42724
+ const webEntry = pathToFileURL2(join9(dirname7(nodeEntry), "transformers.web.js")).href;
42725
+ return await import(webEntry);
42726
+ };
42727
+ var modelCacheDirForRuntime = () => join9(getMagicContextStorageDir(), "models");
42728
+ var logForRuntime = log;
42729
+ var injectWasmOrtForRuntime = injectWasmOrt;
42730
+ async function ensureWasmOrtInjected() {
42731
+ if (wasmRuntimeInjected)
42732
+ return true;
42733
+ if (!await injectWasmOrtForRuntime())
42713
42734
  return false;
42714
- }
42735
+ wasmRuntimeInjected = true;
42736
+ return true;
42737
+ }
42738
+ async function injectWasmOrt() {
42739
+ if (wasmRuntimeInjected)
42740
+ return true;
42715
42741
  try {
42716
- const ortWebSpec = `onnxruntime-${"web"}`;
42717
- const ortWeb = await import(ortWebSpec);
42742
+ const ortWeb = await importWasmOrtForRuntime();
42718
42743
  try {
42719
42744
  const { createRequire: createRequireFn } = await import("node:module");
42720
42745
  const requireFn = createRequireFn(import.meta.url);
42721
42746
  const mainEntry = requireFn.resolve("onnxruntime-web");
42722
42747
  const distDir = dirname7(mainEntry);
42723
- const wasmPathsPrefix = `${pathToFileURL2(distDir).href}/`;
42724
42748
  if (ortWeb.env?.wasm) {
42725
- ortWeb.env.wasm.wasmPaths = wasmPathsPrefix;
42749
+ ortWeb.env.wasm.wasmPaths = `${pathToFileURL2(distDir).href}/`;
42726
42750
  }
42727
42751
  } catch (pathError) {
42728
42752
  log("[magic-context] could not resolve local onnxruntime-web/dist, falling back to default WASM paths:", pathError instanceof Error ? pathError.message : String(pathError));
42729
42753
  }
42730
42754
  globalThis[Symbol.for("onnxruntime")] = ortWeb;
42731
- log("[magic-context] Electron detected — using onnxruntime-web (WASM) for embeddings (bypasses onnxruntime-node native load)");
42755
+ wasmRuntimeInjected = true;
42732
42756
  return true;
42733
42757
  } catch (error51) {
42734
- log("[magic-context] failed to inject onnxruntime-web for Electron — letting transformers fall back to native:", error51 instanceof Error ? error51.message : String(error51));
42758
+ log("[magic-context] failed to inject onnxruntime-web:", error51 instanceof Error ? error51.message : String(error51));
42735
42759
  return false;
42736
42760
  }
42737
42761
  }
42762
+ function likelyMuslHint() {
42763
+ if (process.platform !== "linux" || typeof process.report?.getReport !== "function")
42764
+ return "";
42765
+ try {
42766
+ const report = process.report.getReport();
42767
+ return typeof report.header?.glibcVersionRuntime === "string" ? "" : " Linux process report has no glibc runtime version (musl likely).";
42768
+ } catch {
42769
+ return "";
42770
+ }
42771
+ }
42772
+ function localEmbeddingRuntimeIsDisabled() {
42773
+ return localEmbeddingRuntimeMode === "disabled";
42774
+ }
42775
+ function disableLocalEmbeddingsAfterRuntimeFailure(detail) {
42776
+ localEmbeddingRuntimeMode = "disabled";
42777
+ logForRuntime(`[magic-context] local embeddings are disabled because both the onnxruntime-node native binding and the onnxruntime-web (WASM) fallback failed to load. Native failure: ${detail}. Run \`npx @cortexkit/magic-context@latest doctor\` for repair guidance (use \`doctor --force\` to reinstall cached plugin packages), or configure an \`openai-compatible\` embedding HTTP endpoint. Existing memories are unaffected.`);
42778
+ }
42779
+ async function loadTransformersForLocalEmbedding() {
42780
+ if (localEmbeddingRuntimeMode === "disabled") {
42781
+ throw new Error("local embedding runtime is disabled");
42782
+ }
42783
+ if (localEmbeddingRuntimeMode === "wasm") {
42784
+ if (!await ensureWasmOrtInjected()) {
42785
+ disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime is unavailable");
42786
+ throw new Error("onnxruntime-web failed to load");
42787
+ }
42788
+ try {
42789
+ return { module: await importTransformersWasmFallbackForRuntime(), usesWasm: true };
42790
+ } catch (wasmError) {
42791
+ disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime failed to load");
42792
+ throw wasmError;
42793
+ }
42794
+ }
42795
+ const electron = isElectronForRuntime();
42796
+ if (electron) {
42797
+ const wasInjected = wasmRuntimeInjected;
42798
+ if (await ensureWasmOrtInjected()) {
42799
+ if (!wasInjected) {
42800
+ logForRuntime("[magic-context] Electron detected — using onnxruntime-web (WASM) for embeddings (bypasses onnxruntime-node native load)");
42801
+ }
42802
+ return { module: await importTransformersForRuntime(), usesWasm: true };
42803
+ }
42804
+ }
42805
+ try {
42806
+ return { module: await importTransformersForRuntime(), usesWasm: false };
42807
+ } catch (nativeError) {
42808
+ if (!isNativeRuntimeMissingError(nativeError) || electron) {
42809
+ throw nativeError;
42810
+ }
42811
+ if (!await ensureWasmOrtInjected()) {
42812
+ disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
42813
+ throw nativeError;
42814
+ }
42815
+ localEmbeddingRuntimeMode = "wasm";
42816
+ try {
42817
+ const module = await importTransformersWasmFallbackForRuntime();
42818
+ logForRuntime("[magic-context] onnxruntime-node failed to load; using onnxruntime-web (WASM) for local embeddings. WASM inference is slower than native; a remote `openai-compatible` provider may be faster." + likelyMuslHint());
42819
+ return { module, usesWasm: true };
42820
+ } catch (wasmError) {
42821
+ disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
42822
+ throw wasmError;
42823
+ }
42824
+ }
42825
+ }
42738
42826
  var DEFAULT_LOCAL_DTYPE = "fp32";
42739
42827
  async function withQuietConsole(fn) {
42740
42828
  const origWarn = console.warn;
@@ -42752,7 +42840,6 @@ async function withQuietConsole(fn) {
42752
42840
  console.error = origError;
42753
42841
  }
42754
42842
  }
42755
- var nativeRuntimeMissing = false;
42756
42843
  function isNativeRuntimeMissingError(error51) {
42757
42844
  const message = error51 instanceof Error ? error51.message : String(error51 ?? "");
42758
42845
  const lower = message.toLowerCase();
@@ -42836,7 +42923,7 @@ class LocalEmbeddingProvider {
42836
42923
  if (this.pipeline) {
42837
42924
  return true;
42838
42925
  }
42839
- if (nativeRuntimeMissing) {
42926
+ if (localEmbeddingRuntimeMode === "disabled") {
42840
42927
  return false;
42841
42928
  }
42842
42929
  if (this.initPromise) {
@@ -42848,15 +42935,13 @@ class LocalEmbeddingProvider {
42848
42935
  if (this.disposing) {
42849
42936
  return;
42850
42937
  }
42851
- const injectedWasmOrt = await injectWasmOrtForElectron();
42852
- const transformersSpec = "@huggingface/transformers";
42853
- const transformersModule = await import(transformersSpec);
42938
+ const { module: transformersModule, usesWasm } = await loadTransformersForLocalEmbedding();
42854
42939
  const env = transformersModule.env;
42855
42940
  const LogLevel = transformersModule.LogLevel;
42856
42941
  if (LogLevel && "ERROR" in LogLevel) {
42857
42942
  env.logLevel = LogLevel.ERROR;
42858
42943
  }
42859
- const modelCacheDir = join9(getMagicContextStorageDir(), "models");
42944
+ const modelCacheDir = modelCacheDirForRuntime();
42860
42945
  try {
42861
42946
  if (shouldEnforcePrivateStoragePermissions()) {
42862
42947
  mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
@@ -42883,7 +42968,7 @@ class LocalEmbeddingProvider {
42883
42968
  try {
42884
42969
  const pipeline = await withQuietConsole(() => createPipeline("feature-extraction", this.model, {
42885
42970
  dtype: this.dtype,
42886
- ...injectedWasmOrt ? { device: "auto" } : {}
42971
+ ...usesWasm ? { device: "auto" } : {}
42887
42972
  }));
42888
42973
  if (this.disposing) {
42889
42974
  await pipeline.dispose?.();
@@ -42915,10 +43000,9 @@ class LocalEmbeddingProvider {
42915
43000
  await releaseLock();
42916
43001
  }
42917
43002
  } catch (error51) {
42918
- if (isNativeRuntimeMissingError(error51)) {
42919
- nativeRuntimeMissing = true;
42920
- log("[magic-context] local embeddings are disabled because the onnxruntime-node native binding is missing or failed to load. Run `npx @cortexkit/magic-context@latest doctor` for repair guidance (use `doctor --force` to reinstall cached plugin packages), or configure an `openai-compatible` embedding HTTP endpoint. Existing memories are unaffected.");
42921
- } else {
43003
+ if (!localEmbeddingRuntimeIsDisabled() && isNativeRuntimeMissingError(error51)) {
43004
+ disableLocalEmbeddingsAfterRuntimeFailure(error51 instanceof Error ? error51.message : String(error51));
43005
+ } else if (!localEmbeddingRuntimeIsDisabled()) {
42922
43006
  log("[magic-context] embedding model failed to load:", error51);
42923
43007
  }
42924
43008
  this.pipeline = null;
@@ -43983,6 +44067,13 @@ function markProjectLoadUntrusted(projectIdentity) {
43983
44067
  untrustedLoadProjects.add(projectIdentity);
43984
44068
  }
43985
44069
  var testProviderFactory = null;
44070
+
44071
+ class TestProviderFactoryRequiredError extends Error {
44072
+ constructor() {
44073
+ super("test constructed a network-capable embedding provider without a test factory — install _setTestProviderFactoryForProject or set embedding.provider off in the fixture");
44074
+ this.name = "TestProviderFactoryRequiredError";
44075
+ }
44076
+ }
43986
44077
  function synapseConfigFields(config2) {
43987
44078
  const raw = config2;
43988
44079
  return {
@@ -44061,11 +44152,14 @@ function resolveEmbeddingConfig(config2) {
44061
44152
  throw new Error("Unknown embedding provider");
44062
44153
  }
44063
44154
  function createProvider(config2, context) {
44155
+ if (config2.provider === "off") {
44156
+ return null;
44157
+ }
44064
44158
  if (testProviderFactory) {
44065
44159
  return testProviderFactory(config2);
44066
44160
  }
44067
- if (config2.provider === "off") {
44068
- return null;
44161
+ if (process.env.MAGIC_CONTEXT_TEST_DATA_DIR?.trim()) {
44162
+ throw new TestProviderFactoryRequiredError;
44069
44163
  }
44070
44164
  if (config2.provider === "openai-compatible") {
44071
44165
  return new OpenAICompatibleEmbeddingProvider({
@@ -45467,6 +45561,10 @@ var STATUS_COLOR = {
45467
45561
  completed: "success",
45468
45562
  cancelled: "error"
45469
45563
  };
45564
+ var SPIN_FRAMES = ["◐", "◓", "◑", "◒"];
45565
+ function spinGlyph() {
45566
+ return SPIN_FRAMES[Math.floor(Date.now() / 160) % SPIN_FRAMES.length];
45567
+ }
45470
45568
  var snapshotsBySession = new Map;
45471
45569
  var MAX_TODOWRITE_RENDER_CACHE_ENTRIES = 50;
45472
45570
  var cachedTodowriteTodosByToolCallId = new Map;
@@ -45607,7 +45705,7 @@ function formatCounts(counts) {
45607
45705
  return parts.join(" · ");
45608
45706
  }
45609
45707
  function formatTodoLine(todo, theme, options = {}) {
45610
- const glyph = theme.fg(STATUS_COLOR[todo.status], STATUS_GLYPH[todo.status]);
45708
+ const glyph = theme.fg(STATUS_COLOR[todo.status], todo.status === "in_progress" ? spinGlyph() : STATUS_GLYPH[todo.status]);
45611
45709
  const id = options.showId && todo.id ? `${theme.fg("accent", `#${todo.id}`)} ` : "";
45612
45710
  const color = todo.status === "pending" || todo.status === "in_progress" ? "text" : "dim";
45613
45711
  let content = theme.fg(color, todo.content);
@@ -45626,6 +45724,9 @@ function lineComponent(renderLines) {
45626
45724
  invalidate() {}
45627
45725
  };
45628
45726
  }
45727
+ function hasAnimatedRow(rows) {
45728
+ return capTodoRows(rows).visible.some(({ todo }) => todo.status === "in_progress");
45729
+ }
45629
45730
  function capTodoRows(rows) {
45630
45731
  if (rows.length <= MAX_TODO_CONTENT_ROWS) {
45631
45732
  return { visible: [...rows], hiddenCount: 0 };
@@ -45714,6 +45815,20 @@ function isOverlayLive(todo) {
45714
45815
  }
45715
45816
 
45716
45817
  class TodoOverlay {
45818
+ spinTimer;
45819
+ syncSpinTimer(hasInProgress) {
45820
+ if (hasInProgress && this.widgetRegistered) {
45821
+ if (this.spinTimer)
45822
+ return;
45823
+ this.spinTimer = setInterval(() => {
45824
+ this.tui?.requestRender();
45825
+ }, 160);
45826
+ this.spinTimer.unref?.();
45827
+ } else if (this.spinTimer) {
45828
+ clearInterval(this.spinTimer);
45829
+ this.spinTimer = undefined;
45830
+ }
45831
+ }
45717
45832
  uiCtx;
45718
45833
  sessionId;
45719
45834
  widgetRegistered = false;
@@ -45741,6 +45856,10 @@ class TodoOverlay {
45741
45856
  this.uiCtx.setWidget(WIDGET_KEY, undefined);
45742
45857
  this.widgetRegistered = false;
45743
45858
  this.tui = undefined;
45859
+ if (this.spinTimer) {
45860
+ clearInterval(this.spinTimer);
45861
+ this.spinTimer = undefined;
45862
+ }
45744
45863
  }
45745
45864
  return;
45746
45865
  }
@@ -45752,11 +45871,17 @@ class TodoOverlay {
45752
45871
  invalidate: () => {
45753
45872
  this.widgetRegistered = false;
45754
45873
  this.tui = undefined;
45874
+ if (this.spinTimer) {
45875
+ clearInterval(this.spinTimer);
45876
+ this.spinTimer = undefined;
45877
+ }
45755
45878
  }
45756
45879
  };
45757
45880
  }, { placement: "aboveEditor" });
45758
45881
  this.widgetRegistered = true;
45882
+ this.syncSpinTimer(hasAnimatedRow(visible));
45759
45883
  } else {
45884
+ this.syncSpinTimer(hasAnimatedRow(visible));
45760
45885
  this.tui?.requestRender();
45761
45886
  }
45762
45887
  }
@@ -45780,6 +45905,10 @@ class TodoOverlay {
45780
45905
  this.dispose();
45781
45906
  }
45782
45907
  dispose() {
45908
+ if (this.spinTimer) {
45909
+ clearInterval(this.spinTimer);
45910
+ this.spinTimer = undefined;
45911
+ }
45783
45912
  if (this.uiCtx)
45784
45913
  this.uiCtx.setWidget(WIDGET_KEY, undefined);
45785
45914
  this.widgetRegistered = false;
@@ -50664,6 +50793,7 @@ var memoryImportanceColumnCache = new WeakMap;
50664
50793
  var memoryScopeColumnCache = new WeakMap;
50665
50794
  var memoryShareableColumnCache = new WeakMap;
50666
50795
  var memoryClassifiedAtColumnCache = new WeakMap;
50796
+ var memoryVerificationsTableCache = new WeakMap;
50667
50797
  function hasMemoryImportanceColumn(db) {
50668
50798
  const cached2 = memoryImportanceColumnCache.get(db);
50669
50799
  if (cached2 !== undefined)
@@ -50700,6 +50830,14 @@ function hasMemoryClassifiedAtColumn(db) {
50700
50830
  memoryClassifiedAtColumnCache.set(db, hasColumn);
50701
50831
  return hasColumn;
50702
50832
  }
50833
+ function hasMemoryVerificationsTable(db) {
50834
+ const cached2 = memoryVerificationsTableCache.get(db);
50835
+ if (cached2 !== undefined)
50836
+ return cached2;
50837
+ const hasTable = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_verifications'").get());
50838
+ memoryVerificationsTableCache.set(db, hasTable);
50839
+ return hasTable;
50840
+ }
50703
50841
  function getUnclassifiedMemoryIds(db, memoryIds) {
50704
50842
  if (!hasMemoryClassifiedAtColumn(db))
50705
50843
  return [...memoryIds];
@@ -51192,6 +51330,9 @@ function updateMemoryContent(db, id, content, normalizedHash) {
51192
51330
  const rejectionReset = hasMuralCueRejectionCountColumn(db) ? ", mural_cue_rejection_count = 0" : "";
51193
51331
  db.prepare(`UPDATE memories SET mural_cue = NULL, mural_cue_hash = NULL, mural_cue_at = NULL${rejectionReset} WHERE id = ?`).run(id);
51194
51332
  }
51333
+ if (hasMemoryVerificationsTable(db)) {
51334
+ db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(id);
51335
+ }
51195
51336
  let stmt = deleteEmbeddingOnContentUpdateStatements.get(db);
51196
51337
  if (!stmt) {
51197
51338
  stmt = db.prepare("DELETE FROM memory_embeddings WHERE memory_id = ?");
@@ -51462,13 +51603,13 @@ function placeholders3(values) {
51462
51603
  function uniqueSortedFiles(files) {
51463
51604
  return Array.from(new Set(files.filter((file2) => file2 !== MEMORY_VERIFICATION_SENTINEL))).sort();
51464
51605
  }
51465
- function recordMemoryMapping(db, memoryId, normalizedFiles, now) {
51606
+ function recordMemoryMapping(db, memoryId, normalizedFiles, now, mappingOrigin = "mapper") {
51466
51607
  const realFiles = uniqueSortedFiles(normalizedFiles);
51467
51608
  const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
51468
51609
  db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
51469
- const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, 0, ?)");
51610
+ const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, 0, ?, ?)");
51470
51611
  for (const file2 of filesToWrite) {
51471
- insert.run(memoryId, file2, now);
51612
+ insert.run(memoryId, file2, now, mappingOrigin);
51472
51613
  }
51473
51614
  return filesToWrite.length;
51474
51615
  }
@@ -51476,7 +51617,7 @@ function recordMemoryVerifications(db, memoryId, normalizedFiles, now) {
51476
51617
  const realFiles = uniqueSortedFiles(normalizedFiles);
51477
51618
  const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
51478
51619
  db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
51479
- const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, ?, ?)");
51620
+ const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, ?, ?, 'mapper')");
51480
51621
  for (const file2 of filesToWrite) {
51481
51622
  insert.run(memoryId, file2, now, now);
51482
51623
  }
@@ -51498,7 +51639,7 @@ function getMemoryVerifications(db, memoryIds) {
51498
51639
  const result = new Map;
51499
51640
  if (ids.length === 0)
51500
51641
  return result;
51501
- const rows = db.prepare(`SELECT memory_id, file_path, verified_at, mapped_at
51642
+ const rows = db.prepare(`SELECT memory_id, file_path, verified_at, mapped_at, mapping_origin
51502
51643
  FROM memory_verifications
51503
51644
  WHERE memory_id IN (${placeholders3(ids)})
51504
51645
  ORDER BY memory_id, file_path`).all(...ids);
@@ -51506,6 +51647,7 @@ function getMemoryVerifications(db, memoryIds) {
51506
51647
  const existing = result.get(row.memory_id) ?? {
51507
51648
  files: [],
51508
51649
  hasSentinel: false,
51650
+ mappingOrigin: "mapper",
51509
51651
  verifiedAt: 0,
51510
51652
  mappedAt: 0
51511
51653
  };
@@ -51514,6 +51656,9 @@ function getMemoryVerifications(db, memoryIds) {
51514
51656
  } else if (!existing.files.includes(row.file_path)) {
51515
51657
  existing.files.push(row.file_path);
51516
51658
  }
51659
+ if (row.mapping_origin === "host_rejected_fallback") {
51660
+ existing.mappingOrigin = "host_rejected_fallback";
51661
+ }
51517
51662
  existing.verifiedAt = Math.max(existing.verifiedAt, row.verified_at);
51518
51663
  existing.mappedAt = Math.max(existing.mappedAt, row.mapped_at ?? 0);
51519
51664
  result.set(row.memory_id, existing);
@@ -52191,7 +52336,7 @@ import { isAbsolute as isAbsolute5 } from "node:path";
52191
52336
 
52192
52337
  // ../retina-local-fs/src/path-fence.ts
52193
52338
  import { lstat, readlink, realpath } from "node:fs/promises";
52194
- import { homedir as homedir7 } from "node:os";
52339
+ import { homedir as homedir6 } from "node:os";
52195
52340
  import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute4, join as join10, relative, resolve as resolve5, sep } from "node:path";
52196
52341
 
52197
52342
  // ../retina-local-fs/src/errors.ts
@@ -52216,7 +52361,7 @@ async function resolveAndFenceProviderPath(configuredPath, options) {
52216
52361
  return canonical;
52217
52362
  }
52218
52363
  async function resolveFenceRoots(options) {
52219
- const configuredHomePath = resolve5(options.homeDirectory ?? process.env.HOME ?? homedir7());
52364
+ const configuredHomePath = resolve5(options.homeDirectory ?? process.env.HOME ?? homedir6());
52220
52365
  let home;
52221
52366
  try {
52222
52367
  home = await realpath(configuredHomePath);
@@ -55825,12 +55970,14 @@ function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
55825
55970
  updateTagStatus(db, sessionId, tagNumber, "dropped");
55826
55971
  }
55827
55972
  function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSummaryMessageId) {
55973
+ const transactionStartedAt = performance.now();
55828
55974
  db.transaction(() => {
55829
55975
  setPersistedCompactionMarkerState(db, sessionId, state);
55830
55976
  if (replacedSummaryMessageId !== null) {
55831
55977
  dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
55832
55978
  }
55833
55979
  })();
55980
+ logSlowWriteTransaction("marker-drain", transactionStartedAt);
55834
55981
  }
55835
55982
  function getCompartmentEndMessageIdForOrdinal(db, sessionId, endOrdinal) {
55836
55983
  const row = db.prepare(`SELECT end_message_id
@@ -56780,4 +56927,4 @@ function registerMagicContextTools(pi, opts) {
56780
56927
  }
56781
56928
  }
56782
56929
 
56783
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, hasShareabilitySensitiveText, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, buildChannel2Reminder, shouldUseStickyChannel1Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, resolveModelConfigOrDefault, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };
56930
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, logSlowWriteTransaction, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, resolveModelConfigOrDefault, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionSnapshot, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };