@cortexkit/pi-magic-context 0.44.2 → 0.44.4

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.
@@ -9,6 +9,10 @@ import {
9
9
  sessionLog
10
10
  } from "./index-59dmj4zs.js";
11
11
  import {
12
+ registerSlowWriteReporter,
13
+ detectSqliteRuntime,
14
+ Database,
15
+ withPrivilegedWriter,
12
16
  removeSystemReminders,
13
17
  hasMeaningfulUserText2,
14
18
  extractTexts2,
@@ -28,10 +32,6 @@ import {
28
32
  assertOpenCodeStoreGeneration,
29
33
  openCodeDbPathExists,
30
34
  getOpenCodeDbProbeDescriptions,
31
- registerSlowWriteReporter,
32
- detectSqliteRuntime,
33
- Database,
34
- withPrivilegedWriter,
35
35
  closeQuietly,
36
36
  withReadOnlySessionDb,
37
37
  setDatabase,
@@ -42,7 +42,7 @@ import {
42
42
  cleanUserText2,
43
43
  visitRawSessionMessages2,
44
44
  readSessionChunk2
45
- } from "./index-gsff513e.js";
45
+ } from "./index-npagr1cy.js";
46
46
  import {
47
47
  logSlowWriteTransaction
48
48
  } from "./index-97e5fzy3.js";
@@ -8800,6 +8800,12 @@ var dubiousOwnershipLoggedDirectories = new Set;
8800
8800
  var dubiousOwnershipWarnedDirectories = new Set;
8801
8801
  var transientGitIdentityReuseLoggedDirectories = new Set;
8802
8802
  var sessionIdentityCache = new Map;
8803
+ var homeProjectPermission = false;
8804
+ var pausedIdentityReasons = new Map;
8805
+ var pausedIdentityLogged = new Set;
8806
+ function setHomeProjectPermission(allowed) {
8807
+ homeProjectPermission = allowed;
8808
+ }
8803
8809
  var execFileSyncForIdentity = execFileSync;
8804
8810
  var userHomeDirectoryForIdentity = () => homedir3();
8805
8811
  var nowMs = () => Date.now();
@@ -8881,6 +8887,27 @@ function isGitTimeoutError(error) {
8881
8887
  const signal = getErrorSignal(error);
8882
8888
  return code === "ETIMEDOUT" || signal === "SIGTERM" || signal === "SIGKILL" || getErrorKilled(error);
8883
8889
  }
8890
+ function hasUnbornHead(directory) {
8891
+ const options = {
8892
+ cwd: directory,
8893
+ encoding: "utf8",
8894
+ env: { ...process.env, LC_ALL: "C", LANG: "C" },
8895
+ stdio: ["ignore", "pipe", "pipe"],
8896
+ timeout: GIT_TIMEOUT_MS,
8897
+ windowsHide: true
8898
+ };
8899
+ try {
8900
+ execFileSyncForIdentity("git", ["rev-parse", "--git-dir"], options);
8901
+ try {
8902
+ execFileSyncForIdentity("git", ["rev-parse", "--verify", "--quiet", "HEAD"], options);
8903
+ return false;
8904
+ } catch (error) {
8905
+ return !isGitTimeoutError(error) && typeof error === "object" && error !== null && "status" in error && error.status === 1 && getErrorStderr(error) === "";
8906
+ }
8907
+ } catch {
8908
+ return false;
8909
+ }
8910
+ }
8884
8911
  function classifyGitError(error, rawDirectory) {
8885
8912
  if (isGitTimeoutError(error)) {
8886
8913
  return new ProjectIdentityError("git_timeout", rawDirectory, `git rev-list timed out after ${GIT_TIMEOUT_MS}ms`, asError(error));
@@ -8901,7 +8928,7 @@ function classifyGitError(error, rawDirectory) {
8901
8928
  }
8902
8929
  return new ProjectIdentityError("unknown", rawDirectory, "git rev-list failed while resolving project identity", asError(error));
8903
8930
  }
8904
- function resolveProjectIdentityStrict(directory, allowHomeProject = false) {
8931
+ function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectPermission) {
8905
8932
  assertProjectAllowed(directory, allowHomeProject);
8906
8933
  const canonical = path2.resolve(directory);
8907
8934
  const cached = identityCache.get(canonical);
@@ -8923,7 +8950,11 @@ function resolveProjectIdentityStrict(directory, allowHomeProject = false) {
8923
8950
  windowsHide: true
8924
8951
  });
8925
8952
  } catch (error) {
8926
- throw classifyGitError(error, directory);
8953
+ const classified = classifyGitError(error, directory);
8954
+ if (classified.errorClass === "not_git_repo" && hasUnbornHead(canonical)) {
8955
+ throw new ProjectIdentityError("no_commits", directory, "Git repository has no commits yet");
8956
+ }
8957
+ throw classified;
8927
8958
  }
8928
8959
  const rootCommit = output.split(`
8929
8960
  `).map((line) => line.trim().slice(0, 64)).filter((line) => /^[0-9a-f]{7,64}$/.test(line)).sort()[0];
@@ -9029,7 +9060,7 @@ function assertProjectAllowed(directory, allowHomeProject) {
9029
9060
  throw new ProjectIdentityError("home_project_disabled", directory, "Home project memory is disabled; set allow_home_project to opt in");
9030
9061
  }
9031
9062
  }
9032
- function resolveProjectIdentity(directory, allowHomeProject = false) {
9063
+ function resolveProjectIdentity(directory, allowHomeProject = homeProjectPermission) {
9033
9064
  assertProjectAllowed(directory, allowHomeProject);
9034
9065
  const canonical = path2.resolve(directory);
9035
9066
  const cachedFallback = directoryFallbackCache.get(canonical);
@@ -9054,6 +9085,8 @@ function resolveProjectIdentity(directory, allowHomeProject = false) {
9054
9085
  } catch (error) {
9055
9086
  if (error instanceof ProjectIdentityError && shouldUseDirectoryFallback(error)) {
9056
9087
  const fallback = directoryFallback(canonical);
9088
+ if (error.errorClass === "no_commits")
9089
+ return fallback;
9057
9090
  const hasGitMetadata = hasGitDir(canonical);
9058
9091
  if (!hasGitMetadata) {
9059
9092
  if (error.errorClass === "permission_denied")
@@ -9075,7 +9108,7 @@ function resolveProjectIdentity(directory, allowHomeProject = false) {
9075
9108
  throw error;
9076
9109
  }
9077
9110
  }
9078
- function resolveProjectIdentityOrFallback(directory, allowHomeProject = false) {
9111
+ function resolveProjectIdentityOrFallback(directory, allowHomeProject = homeProjectPermission) {
9079
9112
  try {
9080
9113
  return resolveProjectIdentity(directory, allowHomeProject);
9081
9114
  } catch (error) {
@@ -9136,7 +9169,7 @@ function directoryHasGitMetadata(directory) {
9136
9169
  function isUsableProjectIdentity(identity) {
9137
9170
  return typeof identity === "string" && identity.trim().length > 0;
9138
9171
  }
9139
- function resolveProjectIdentityForSession(directory, allowHomeProject = false) {
9172
+ function resolveProjectIdentityForSession(directory, allowHomeProject = homeProjectPermission) {
9140
9173
  const resolvedDirectory = path2.resolve(directory);
9141
9174
  const cacheKey = `${allowHomeProject ? "1" : "0"}\x00${resolvedDirectory}`;
9142
9175
  const cached = sessionIdentityCache.get(cacheKey);
@@ -9165,9 +9198,18 @@ function resolveProjectIdentityForSession(directory, allowHomeProject = false) {
9165
9198
  } catch (error) {
9166
9199
  if (!(error instanceof ProjectIdentityError))
9167
9200
  throw error;
9201
+ const reason = error.errorClass === "git_identity_unavailable" ? pausedIdentityReasons.get(resolvedDirectory) ?? error.errorClass : error.errorClass;
9202
+ pausedIdentityReasons.set(resolvedDirectory, reason);
9203
+ const logKey = `${resolvedDirectory}\x00${reason}`;
9204
+ if (!pausedIdentityLogged.has(logKey)) {
9205
+ pausedIdentityLogged.add(logKey);
9206
+ log(`[magic-context] memory features paused for ${resolvedDirectory}: ${reason}`);
9207
+ }
9168
9208
  identity = undefined;
9169
9209
  }
9170
9210
  }
9211
+ if (identity !== undefined)
9212
+ pausedIdentityReasons.delete(resolvedDirectory);
9171
9213
  sessionIdentityCache.set(cacheKey, {
9172
9214
  identity,
9173
9215
  revalidateAt: identity?.startsWith("git:") === true ? null : nowMs() + TRANSIENT_FAILURE_COOLDOWN_MS
@@ -15232,7 +15274,6 @@ var WINDOWS_CIM_PROBE_TIMEOUT_MS = 5000;
15232
15274
  var WINDOWS_PROCESS_SNAPSHOT_TTL_MS = 2000;
15233
15275
  var MAX_ANCESTOR_WALK_DEPTH = 16;
15234
15276
  var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
15235
- var TASKLIST_NO_TASKS_PATTERN = /^INFO:\s+No tasks are running which match the specified criteria\.?$/im;
15236
15277
  var WINDOWS_CIM_COMMAND = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,CreationDate | ConvertTo-Json -Compress";
15237
15278
  var PI_HARNESS_ARC_MARKERS = [
15238
15279
  "pi-coding-agent",
@@ -15326,18 +15367,14 @@ function parseCsvLine(line) {
15326
15367
  }
15327
15368
  function parseTasklistOutput(output) {
15328
15369
  const entries = [];
15329
- let sawHeader = false;
15330
15370
  for (const rawLine of output.split(/\r?\n/)) {
15331
15371
  const line = rawLine.trim();
15332
15372
  if (!line)
15333
15373
  continue;
15334
- if (TASKLIST_NO_TASKS_PATTERN.test(line))
15335
- return [];
15336
15374
  const fields = parseCsvLine(line);
15337
15375
  if (!fields)
15338
15376
  continue;
15339
15377
  if (fields[1]?.trim().toLowerCase() === "pid") {
15340
- sawHeader = true;
15341
15378
  continue;
15342
15379
  }
15343
15380
  const pid = Number(fields[1]);
@@ -15345,11 +15382,11 @@ function parseTasklistOutput(output) {
15345
15382
  continue;
15346
15383
  entries.push({ pid, command: fields[0] });
15347
15384
  }
15348
- return entries.length > 0 || sawHeader ? entries : null;
15385
+ return entries;
15349
15386
  }
15350
15387
  function readWindowsProcess(pid) {
15351
15388
  try {
15352
- const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/FI", `PID eq ${pid}`], {
15389
+ const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], {
15353
15390
  encoding: "utf8",
15354
15391
  timeout: PS_PROBE_TIMEOUT_MS,
15355
15392
  stdio: ["ignore", "pipe", "pipe"],
@@ -15586,7 +15623,11 @@ function tryReadWindowsCimSnapshot(exec) {
15586
15623
  }
15587
15624
  function tryReadWindowsTasklistSnapshot() {
15588
15625
  try {
15589
- const output = execProcessList(rpcProcessListExecFileSync, "tasklist", ["/FO", "CSV"]);
15626
+ const output = execProcessList(rpcProcessListExecFileSync, "tasklist", [
15627
+ "/FO",
15628
+ "CSV",
15629
+ "/NH"
15630
+ ]);
15590
15631
  const entries = parseTasklistOutput(output);
15591
15632
  if (entries === null)
15592
15633
  return null;
@@ -15795,7 +15836,7 @@ function inspectProcessesAsync(forceFresh = false) {
15795
15836
  snapshot = snapshotFromFacts(facts, "cim");
15796
15837
  } catch {}
15797
15838
  if (!snapshot) {
15798
- const entries = parseTasklistOutput(await asyncProcessExec("tasklist", ["/FO", "CSV"], PS_PROBE_TIMEOUT_MS));
15839
+ const entries = parseTasklistOutput(await asyncProcessExec("tasklist", ["/FO", "CSV", "/NH"], PS_PROBE_TIMEOUT_MS));
15799
15840
  if (entries)
15800
15841
  snapshot = snapshotFromFacts(entries.map(({ pid, command }) => ({
15801
15842
  pid,
@@ -15844,6 +15885,19 @@ function inspectProcessesAsync(forceFresh = false) {
15844
15885
  });
15845
15886
  return asyncInspection;
15846
15887
  }
15888
+ function inspectWindowsProcessesSync() {
15889
+ const snapshot = tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
15890
+ const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
15891
+ return {
15892
+ pi: snapshot ? classifyLivePiSnapshot(snapshot) : { state: "unreadable", processIds: [] },
15893
+ ...snapshot ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } } : {},
15894
+ evidence: (pid) => ({
15895
+ startTime: byPid.get(pid)?.startTime ?? null,
15896
+ commandLine: byPid.get(pid)?.commandLine ?? byPid.get(pid)?.imageName ?? null
15897
+ }),
15898
+ liveness: (pid) => byPid.has(pid) ? "alive" : snapshot ? "dead" : "inconclusive"
15899
+ };
15900
+ }
15847
15901
 
15848
15902
  // ../plugin/src/features/magic-context/context-authority.ts
15849
15903
  import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
@@ -20407,7 +20461,9 @@ function classifyJunkDiscovery(portFile, raw, staleFiles) {
20407
20461
  log(`[magic-context] removing stale RPC discovery file ${portFile}: ${reason} record older than 10 minutes`);
20408
20462
  return null;
20409
20463
  }
20410
- function inspectRpcServerDiscovery(storageDir, processes) {
20464
+ function inspectRpcServerDiscovery(storageDir, processes, options) {
20465
+ const deadline = options?.deadlineMs === undefined ? Number.POSITIVE_INFINITY : Date.now() + options.deadlineMs;
20466
+ let progressAt = Date.now() + 3000;
20411
20467
  const rpcRoot = join3(storageDir, "rpc");
20412
20468
  let projectEntries;
20413
20469
  try {
@@ -20440,11 +20496,19 @@ function inspectRpcServerDiscovery(storageDir, processes) {
20440
20496
  if (portFiles.length === 0) {
20441
20497
  return { state: "absent", serverPids: [], staleFiles: [] };
20442
20498
  }
20499
+ if (!processes && process.platform === "win32")
20500
+ processes = inspectWindowsProcessesSync();
20443
20501
  const pids = new Set;
20444
20502
  const processByPid = new Map;
20445
20503
  const staleFiles = [];
20446
20504
  const inconclusivePids = new Set;
20447
- for (const portFile of portFiles) {
20505
+ for (const [index, portFile] of portFiles.entries()) {
20506
+ if (Date.now() >= deadline)
20507
+ throw new Error(`RPC holder inspection timed out after ${Math.round((options?.deadlineMs ?? 0) / 1000)} seconds (${index}/${portFiles.length} records checked). Close OpenCode and Pi, then retry.`);
20508
+ if (options?.onProgress && Date.now() >= progressAt) {
20509
+ options.onProgress(index, portFiles.length);
20510
+ progressAt = Date.now() + 3000;
20511
+ }
20448
20512
  let raw;
20449
20513
  try {
20450
20514
  raw = rpcDiscoveryFs.readFileSync(portFile, "utf8");
@@ -20482,7 +20546,7 @@ function inspectRpcServerDiscovery(storageDir, processes) {
20482
20546
  if (!previous || previous.kind === "process" && detected.kind !== "process") {
20483
20547
  processByPid.set(record.pid, detected);
20484
20548
  }
20485
- } else if (identity === "implausible") {
20549
+ } else if (identity === "implausible" && !((processes?.processSnapshot?.source === "cim" || processes?.processSnapshot?.source === "tasklist") && liveness === "alive")) {
20486
20550
  staleFiles.push(portFile);
20487
20551
  } else {
20488
20552
  inconclusivePids.add(record.pid);
@@ -20633,7 +20697,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
20633
20697
  { readRawSessionMessagePage, readRawSessionMessages },
20634
20698
  { startMessageTimeBackfill }
20635
20699
  ] = await Promise.all([
20636
- import("./read-session-chunk-zhtcx9f1.js"),
20700
+ import("./read-session-chunk-w493f72c.js"),
20637
20701
  import("./message-time-backfill-5yrp95cx.js")
20638
20702
  ]);
20639
20703
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
@@ -23898,7 +23962,12 @@ function pruneSynapseBatchLedgerForProject(db, projectIdentity, ttlMs = SYNAPSE_
23898
23962
  const ledgerTable = db.prepare("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'synapse_batch_ledger'").get();
23899
23963
  if (!ledgerTable)
23900
23964
  return 0;
23901
- return db.prepare("DELETE FROM synapse_batch_ledger WHERE session_id IN (?, ?) AND updated_at < ?").run(projectIdentity, `shadow:${projectIdentity}`, Date.now() - ttlMs).changes;
23965
+ const shadow = `shadow:${projectIdentity}`;
23966
+ const cutoff = Date.now() - ttlMs;
23967
+ const predicate = "session_id IN (?, ?) AND updated_at < ?";
23968
+ if (!db.prepare(`SELECT 1 FROM synapse_batch_ledger WHERE ${predicate} LIMIT 1`).get(projectIdentity, shadow, cutoff))
23969
+ return 0;
23970
+ return db.prepare(`DELETE FROM synapse_batch_ledger WHERE ${predicate}`).run(projectIdentity, shadow, cutoff).changes;
23902
23971
  }
23903
23972
  // ../plugin/src/features/magic-context/storage-m0-mutation-log.ts
23904
23973
  var M0_MUTATION_TYPES = new Set([
@@ -25201,8 +25270,8 @@ function attachPiPartVersion(parts, version) {
25201
25270
  return part;
25202
25271
  });
25203
25272
  }
25204
- function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark) {
25205
- const result = [];
25273
+ function* iterateEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark) {
25274
+ let emitted = 0;
25206
25275
  const normalizedAfter = Math.max(0, Math.floor(afterOrdinal));
25207
25276
  const normalizedLimit = Math.max(1, Math.floor(limit));
25208
25277
  const normalizedWatermark = Math.max(normalizedAfter, Math.floor(finalWatermark));
@@ -25212,19 +25281,20 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25212
25281
  let pendingFirstRealId = "";
25213
25282
  let pendingFirstRealVersion = "";
25214
25283
  let pendingFirstCreatedAt = null;
25215
- const appendMessage = (id, role, version, createdAt, parts) => {
25284
+ const appendMessage = function* (id, role, version, createdAt, parts) {
25216
25285
  const ordinal = nextOrdinal++;
25217
25286
  if (ordinal > normalizedAfter && ordinal <= normalizedWatermark) {
25218
- result.push({
25287
+ emitted++;
25288
+ yield {
25219
25289
  ordinal,
25220
25290
  id,
25221
25291
  role,
25222
25292
  parts: parts(),
25223
25293
  version,
25224
25294
  ...createdAt === null ? {} : { createdAt }
25225
- });
25295
+ };
25226
25296
  }
25227
- return result.length >= normalizedLimit || nextOrdinal > normalizedWatermark;
25297
+ return emitted >= normalizedLimit || nextOrdinal > normalizedWatermark;
25228
25298
  };
25229
25299
  for (const entry of entries) {
25230
25300
  if (!isMessageEntry(entry))
@@ -25250,7 +25320,7 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25250
25320
  if (role === "user") {
25251
25321
  const version = rawEntryVersion(entry);
25252
25322
  const bufferedToolParts = pendingToolParts;
25253
- const done = appendMessage(entry.id, "user", version, parsePiEntryTimestamp(entry), () => [
25323
+ const done = yield* appendMessage(entry.id, "user", version, parsePiEntryTimestamp(entry), () => [
25254
25324
  ...bufferedToolParts,
25255
25325
  ...attachPiPartVersion(synthesizeUserParts(msg), version)
25256
25326
  ]);
@@ -25268,7 +25338,7 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25268
25338
  const bufferedToolParts = pendingToolParts;
25269
25339
  const pendingId = pendingFirstRealId;
25270
25340
  const pendingVersion = pendingFirstRealVersion;
25271
- const done = appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingId}`, "user", pendingVersion, pendingFirstCreatedAt, () => bufferedToolParts);
25341
+ const done = yield* appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingId}`, "user", pendingVersion, pendingFirstCreatedAt, () => bufferedToolParts);
25272
25342
  pendingToolParts = [];
25273
25343
  hasPendingToolParts = false;
25274
25344
  pendingFirstRealId = "";
@@ -25278,25 +25348,28 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25278
25348
  break;
25279
25349
  }
25280
25350
  const version = rawEntryVersion(entry);
25281
- if (appendMessage(entry.id, "assistant", version, parsePiEntryTimestamp(entry), () => attachPiPartVersion(synthesizeAssistantParts(msg), version))) {
25351
+ if (yield* appendMessage(entry.id, "assistant", version, parsePiEntryTimestamp(entry), () => attachPiPartVersion(synthesizeAssistantParts(msg), version))) {
25282
25352
  break;
25283
25353
  }
25284
25354
  continue;
25285
25355
  }
25286
- if (appendMessage(entry.id, typeof role === "string" ? role : "unknown", rawEntryVersion(entry), parsePiEntryTimestamp(entry), () => [])) {
25356
+ if (yield* appendMessage(entry.id, typeof role === "string" ? role : "unknown", rawEntryVersion(entry), parsePiEntryTimestamp(entry), () => [])) {
25287
25357
  break;
25288
25358
  }
25289
25359
  }
25290
- if (hasPendingToolParts && result.length < normalizedLimit && nextOrdinal <= normalizedWatermark) {
25291
- appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingFirstRealId}`, "user", pendingFirstRealVersion, pendingFirstCreatedAt, () => pendingToolParts);
25360
+ if (hasPendingToolParts && emitted < normalizedLimit && nextOrdinal <= normalizedWatermark) {
25361
+ yield* appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingFirstRealId}`, "user", pendingFirstRealVersion, pendingFirstCreatedAt, () => pendingToolParts);
25292
25362
  }
25293
- return result;
25294
25363
  }
25295
25364
  function convertEntriesToRawMessages(entries) {
25296
- return convertEntriesToRawMessageRange(entries, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
25365
+ return [
25366
+ ...iterateEntriesToRawMessageRange(entries, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
25367
+ ];
25297
25368
  }
25298
25369
  function convertEntriesToRawMessagePage(entries, afterOrdinal, limit, finalWatermark) {
25299
- return convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark);
25370
+ return [
25371
+ ...iterateEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark)
25372
+ ];
25300
25373
  }
25301
25374
  function isMessageEntry(value) {
25302
25375
  if (value === null || typeof value !== "object")
@@ -26445,6 +26518,21 @@ function getSdkOutputLimit(providerID, modelID) {
26445
26518
  loadPersistedApiCacheOnce();
26446
26519
  return lookupMetadataWithTagFallback(apiCache, providerID, modelID)?.outputLimit;
26447
26520
  }
26521
+ function getSdkInputLimit(providerID, modelID) {
26522
+ loadPersistedApiCacheOnce();
26523
+ if (!apiCache)
26524
+ return;
26525
+ const direct = apiCache.get(`${providerID}/${modelID}`)?.inputLimit;
26526
+ if (isSaneLimit(direct))
26527
+ return direct;
26528
+ const colon = modelID.indexOf(":");
26529
+ if (colon > 0) {
26530
+ const tagless = apiCache.get(`${providerID}/${modelID.slice(0, colon)}`)?.inputLimit;
26531
+ if (isSaneLimit(tagless))
26532
+ return tagless;
26533
+ }
26534
+ return;
26535
+ }
26448
26536
  function lookupMetadataWithTagFallback(cache, providerID, modelID) {
26449
26537
  if (!cache)
26450
26538
  return;
@@ -27771,6 +27859,28 @@ function blockedEmbeddingEndpointReason(endpoint) {
27771
27859
  }
27772
27860
 
27773
27861
  // ../plugin/src/features/magic-context/memory/embedding-openai.ts
27862
+ function capEmbeddingInput(input, maxInputTokens, purpose) {
27863
+ const ratio = purpose === "query" ? CHUNK_WINDOW_SAFETY_RATIO : 1;
27864
+ const budget = Math.max(1, Math.floor(maxInputTokens * ratio));
27865
+ if (estimateTokens(input) <= budget)
27866
+ return input;
27867
+ let low = 0;
27868
+ let high = input.length;
27869
+ while (low < high) {
27870
+ const mid = Math.ceil((low + high) / 2);
27871
+ if (estimateTokens(input.slice(0, mid)) <= budget)
27872
+ low = mid;
27873
+ else
27874
+ high = mid - 1;
27875
+ }
27876
+ if (low > 0 && low < input.length) {
27877
+ const last = input.charCodeAt(low - 1);
27878
+ const next = input.charCodeAt(low);
27879
+ if (last >= 55296 && last <= 56319 && next >= 56320 && next <= 57343)
27880
+ low -= 1;
27881
+ }
27882
+ return input.slice(0, low);
27883
+ }
27774
27884
  function normalizeEndpoint3(endpoint) {
27775
27885
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
27776
27886
  }
@@ -27797,6 +27907,7 @@ class OpenAICompatibleEmbeddingProvider {
27797
27907
  modelMismatchLogged = false;
27798
27908
  lastFailureReason = null;
27799
27909
  halfOpenProbeInFlight = false;
27910
+ queryTruncationLogged = false;
27800
27911
  constructor(options) {
27801
27912
  this.endpoint = normalizeEndpoint3(options.endpoint);
27802
27913
  this.model = options.model?.trim() ?? "";
@@ -27850,7 +27961,15 @@ class OpenAICompatibleEmbeddingProvider {
27850
27961
  return [];
27851
27962
  }
27852
27963
  const textPrefix = purpose === "query" ? this.queryPrefix : this.documentPrefix;
27853
- const requestTexts = texts.map((text) => `${textPrefix}${text.trim().length === 0 ? " " : text}`);
27964
+ const requestTexts = texts.map((text) => {
27965
+ const input = `${textPrefix}${text.trim().length === 0 ? " " : text}`;
27966
+ const capped = capEmbeddingInput(input, this.maxInputTokens, purpose);
27967
+ if (purpose === "query" && capped.length < input.length && !this.queryTruncationLogged) {
27968
+ log(`[magic-context] embedding query truncated from ${input.length} to ${capped.length} characters to fit max_input_tokens`);
27969
+ this.queryTruncationLogged = true;
27970
+ }
27971
+ return capped;
27972
+ });
27854
27973
  if (!await this.initialize()) {
27855
27974
  return Array.from({ length: texts.length }, () => null);
27856
27975
  }
@@ -28518,6 +28637,23 @@ var SESSION_CHUNK_REPAIR_BATCH_SIZE = 100;
28518
28637
  var upsertSessionProjectStatements = new WeakMap;
28519
28638
  var repairSessionChunkProjectStatements = new WeakMap;
28520
28639
  var repairProjectChunkProjectStatements = new WeakMap;
28640
+ var misScopedProjectChunkStatements = new WeakMap;
28641
+ var MIS_SCOPED_PROJECT_CHUNK_IDS_SQL = `
28642
+ SELECT e.id FROM compartment_chunk_embeddings e
28643
+ JOIN session_projects sp ON sp.session_id = e.session_id AND sp.harness = e.harness
28644
+ WHERE e.project_path = ? AND sp.project_path <> e.project_path
28645
+ UNION ALL
28646
+ SELECT e.id FROM session_projects sp
28647
+ JOIN compartment_chunk_embeddings e ON e.session_id = sp.session_id
28648
+ WHERE sp.project_path = ? AND e.harness = sp.harness AND e.project_path <> sp.project_path`;
28649
+ function hasMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath) {
28650
+ let stmt = misScopedProjectChunkStatements.get(db);
28651
+ if (!stmt) {
28652
+ stmt = db.prepare(`SELECT 1 FROM (${MIS_SCOPED_PROJECT_CHUNK_IDS_SQL}) LIMIT 1`);
28653
+ misScopedProjectChunkStatements.set(db, stmt);
28654
+ }
28655
+ return !!stmt.get(projectPath, projectPath);
28656
+ }
28521
28657
  function getUpsertSessionProjectStatement(db) {
28522
28658
  let stmt = upsertSessionProjectStatements.get(db);
28523
28659
  if (!stmt) {
@@ -28553,23 +28689,11 @@ function getRepairProjectChunkProjectStatement(db) {
28553
28689
  if (!stmt) {
28554
28690
  stmt = db.prepare(`UPDATE compartment_chunk_embeddings
28555
28691
  SET project_path = (
28556
- SELECT sp.project_path
28557
- FROM session_projects sp
28692
+ SELECT sp.project_path FROM session_projects sp
28558
28693
  WHERE sp.session_id = compartment_chunk_embeddings.session_id
28559
28694
  AND sp.harness = compartment_chunk_embeddings.harness
28560
- LIMIT 1
28561
28695
  )
28562
- WHERE EXISTS (
28563
- SELECT 1
28564
- FROM session_projects sp
28565
- WHERE sp.session_id = compartment_chunk_embeddings.session_id
28566
- AND sp.harness = compartment_chunk_embeddings.harness
28567
- AND sp.project_path <> compartment_chunk_embeddings.project_path
28568
- AND (
28569
- sp.project_path = ?
28570
- OR compartment_chunk_embeddings.project_path = ?
28571
- )
28572
- )`);
28696
+ WHERE id IN (${MIS_SCOPED_PROJECT_CHUNK_IDS_SQL})`);
28573
28697
  repairProjectChunkProjectStatements.set(db, stmt);
28574
28698
  }
28575
28699
  return stmt;
@@ -28589,6 +28713,8 @@ function recordSessionProjectIdentity(db, sessionId, projectPath) {
28589
28713
  function repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath) {
28590
28714
  if (!projectPath)
28591
28715
  return 0;
28716
+ if (!hasMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath))
28717
+ return 0;
28592
28718
  return getRepairProjectChunkProjectStatement(db).run(projectPath, projectPath).changes;
28593
28719
  }
28594
28720
 
@@ -29059,6 +29185,14 @@ function recordActiveEmbeddingIdentity(db, projectIdentity, currentProviderIdent
29059
29185
  if (currentProviderIdentity === OFF_PROVIDER_IDENTITY) {
29060
29186
  return;
29061
29187
  }
29188
+ const scopes = [["chunk", currentChunkIdentity]];
29189
+ if (features.memoryEnabled)
29190
+ scopes.push(["memory", currentProviderIdentity]);
29191
+ if (features.gitCommitEnabled)
29192
+ scopes.push(["commit", currentProviderIdentity]);
29193
+ const active = db.prepare("SELECT 1 FROM embedding_identity_active WHERE project_path = ? AND scope = ? AND model_id = ?");
29194
+ if (scopes.every(([scope, model]) => active.get(projectIdentity, scope, model)) && !hasMisScopedCompartmentChunkEmbeddingsForProject(db, projectIdentity))
29195
+ return;
29062
29196
  const now = Date.now();
29063
29197
  const transactionStartedAt = performance.now();
29064
29198
  db.exec("BEGIN IMMEDIATE");
@@ -29256,7 +29390,9 @@ function registerProjectEmbedding(db, projectIdentity, config, features, sourceD
29256
29390
  observationMode: false
29257
29391
  };
29258
29392
  projectRegistrations.set(projectIdentity, registration);
29259
- persistPrimaryDescriptor(db, registration);
29393
+ if (generationChanged || !db.prepare("SELECT 1 FROM embedding_registrations WHERE project_path = ? AND provider_identity = ? AND chunk_model_id = ? AND generation = ?").get(projectIdentity, providerIdentity, registration.chunkModelId, generation)) {
29394
+ persistPrimaryDescriptor(db, registration);
29395
+ }
29260
29396
  if (!canReuseProvider) {
29261
29397
  disposeProvider(prior?.provider ?? null);
29262
29398
  }
@@ -38661,7 +38797,8 @@ var EPOCH_COMPONENT_PREFIX = "|compartment-render:";
38661
38797
  var MEMORY_EPOCH_COMPONENT_PREFIX = "|memory-render:";
38662
38798
  var MURAL_COMPONENT_PREFIX = "|mural-enabled:";
38663
38799
  var BUDGET_COMPONENT_PREFIX = "|render-budgets:";
38664
- function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH, muralEnabled = null, renderBudgetIdentity = null, memoryRenderEpoch = MEMORY_RENDER_FORMAT_EPOCH) {
38800
+ var RENDERED_BUDGETS_COMPONENT_PREFIX = "|rendered-budgets:";
38801
+ function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH, muralEnabled = null, renderBudgetIdentity = null, memoryRenderEpoch = MEMORY_RENDER_FORMAT_EPOCH, renderedBudgets = null) {
38665
38802
  let encoded = upgradeState ?? "";
38666
38803
  if (compartmentRenderEpoch !== null) {
38667
38804
  encoded += `${EPOCH_COMPONENT_PREFIX}${compartmentRenderEpoch}`;
@@ -38675,6 +38812,9 @@ function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = CO
38675
38812
  if (renderBudgetIdentity !== null) {
38676
38813
  encoded += `${BUDGET_COMPONENT_PREFIX}${renderBudgetIdentity}`;
38677
38814
  }
38815
+ if (renderedBudgets !== null) {
38816
+ encoded += `${RENDERED_BUDGETS_COMPONENT_PREFIX}${renderedBudgets}`;
38817
+ }
38678
38818
  return encoded.length > 0 ? encoded : null;
38679
38819
  }
38680
38820
  function component(value, prefix) {
@@ -38693,14 +38833,16 @@ function decodeCachedM0UpgradeIdentity(value) {
38693
38833
  compartmentRenderEpoch: null,
38694
38834
  memoryRenderEpoch: null,
38695
38835
  muralEnabled: null,
38696
- renderBudgetIdentity: null
38836
+ renderBudgetIdentity: null,
38837
+ renderedBudgets: null
38697
38838
  };
38698
38839
  }
38699
38840
  const componentIndexes = [
38700
38841
  value.indexOf(EPOCH_COMPONENT_PREFIX),
38701
38842
  value.indexOf(MEMORY_EPOCH_COMPONENT_PREFIX),
38702
38843
  value.indexOf(MURAL_COMPONENT_PREFIX),
38703
- value.indexOf(BUDGET_COMPONENT_PREFIX)
38844
+ value.indexOf(BUDGET_COMPONENT_PREFIX),
38845
+ value.indexOf(RENDERED_BUDGETS_COMPONENT_PREFIX)
38704
38846
  ].filter((index) => index >= 0);
38705
38847
  const identityEnd = componentIndexes.length > 0 ? Math.min(...componentIndexes) : value.length;
38706
38848
  const upgradeState = value.slice(0, identityEnd);
@@ -38710,9 +38852,36 @@ function decodeCachedM0UpgradeIdentity(value) {
38710
38852
  compartmentRenderEpoch: component(value, EPOCH_COMPONENT_PREFIX),
38711
38853
  memoryRenderEpoch: component(value, MEMORY_EPOCH_COMPONENT_PREFIX),
38712
38854
  muralEnabled: muralComponent === "1" ? true : muralComponent === "0" ? false : null,
38713
- renderBudgetIdentity: component(value, BUDGET_COMPONENT_PREFIX)
38855
+ renderBudgetIdentity: component(value, BUDGET_COMPONENT_PREFIX),
38856
+ renderedBudgets: component(value, RENDERED_BUDGETS_COMPONENT_PREFIX)
38714
38857
  };
38715
38858
  }
38859
+ function renderBudgetIdentityChanged(cached, current) {
38860
+ const legacy = /^(m[^-]+)-h\d+$/.exec(cached);
38861
+ if (legacy && current.startsWith("m") && current.includes("-hp")) {
38862
+ return legacy[1] !== current.slice(0, current.indexOf("-h"));
38863
+ }
38864
+ return cached !== current;
38865
+ }
38866
+ function renderedBudgetSnapshot(memoryTokens, historyTokens) {
38867
+ return `m${memoryTokens}-h${historyTokens}`;
38868
+ }
38869
+ function readRenderedBudgets(value) {
38870
+ const match = value?.match(/^m(\d+(?:\.\d+)?)-h(\d+(?:\.\d+)?)$/);
38871
+ if (!match)
38872
+ return null;
38873
+ const memory = Number(match[1]);
38874
+ const history = Number(match[2]);
38875
+ return Number.isFinite(memory) && Number.isFinite(history) ? { memory, history } : null;
38876
+ }
38877
+ function renderedBudgetShrinkReason(cached, current) {
38878
+ const before = readRenderedBudgets(cached);
38879
+ const after = readRenderedBudgets(current);
38880
+ if (!before || !after)
38881
+ return null;
38882
+ const shrunk = (oldTokens, newTokens) => oldTokens - newTokens > Math.max(64, oldTokens * 0.01);
38883
+ return shrunk(before.memory, after.memory) || shrunk(before.history, after.history) ? `render_config:budget_shrink(${cached}→${current})` : null;
38884
+ }
38716
38885
 
38717
38886
  // ../plugin/src/hooks/magic-context/decay-curve.ts
38718
38887
  var H50 = 24;
@@ -39563,4 +39732,4 @@ function registerMagicContextTools(pi, opts) {
39563
39732
  }
39564
39733
  }
39565
39734
 
39566
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, setStoragePrivatePermissionEnforcement, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, getSdkOutputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, withContentLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, resolveModelConfigValue, DEFAULT_HISTORIAN_TIMEOUT_MS, DREAM_TASK_PROMOTION_DEFAULTS, LIVE_RELOAD_CONFIG_PATHS, getProtectedTokensTierOverrides, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, ProjectIdentityError, resolveProjectIdentityStrict, isUserHomeDirectory, resolveProjectIdentity, isUsableProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, clearCompressionDepth, clearCompressionDepthRange, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, deleteChunkEmbedBackoffForSession, readSessionActivity, observeSessionActivity, backfillSessionActivity, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, persistCachedM0, clearCachedM0M1, readReplayDocument, updateReplayDocument, isProviderOverflowFailClosedProven, 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, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, recordSessionProjectIdentity, embedPauseBySession, embedRunStateBySession, autoEmbedAttemptedBySession, autoEmbedIdentityBySession, invalidateAutoEmbedSession, getEmbedDrainUiStatus, piHarnessKindFromExecutable, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, getAuthorityManagedMarker, drainMirrorPages, V2_MEMORY_CATEGORIES, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, readProjectDocsCanonical, BoundedSessionMap, registerLkgPersistence, signatureForFields, lkgContentFields, lkgContentDigestFromFields, exactReusablePrefix, incrementalLkgContentDigests, captureSlot, getSlot, dropSlot, noteEntry, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, closeDatabase, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, 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, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getMemoryById, setMemoryClassification, archiveMemory, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, getAutoEmbeddingSessionCoverage, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
39735
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, setStoragePrivatePermissionEnforcement, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, withContentLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, resolveModelConfigValue, DEFAULT_HISTORIAN_TIMEOUT_MS, DREAM_TASK_PROMOTION_DEFAULTS, LIVE_RELOAD_CONFIG_PATHS, getProtectedTokensTierOverrides, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHomeProjectPermission, ProjectIdentityError, resolveProjectIdentityStrict, isUserHomeDirectory, resolveProjectIdentity, isUsableProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, clearCompressionDepth, clearCompressionDepthRange, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, deleteChunkEmbedBackoffForSession, readSessionActivity, observeSessionActivity, backfillSessionActivity, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, persistCachedM0, clearCachedM0M1, readReplayDocument, updateReplayDocument, isProviderOverflowFailClosedProven, 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, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, recordSessionProjectIdentity, embedPauseBySession, embedRunStateBySession, autoEmbedAttemptedBySession, autoEmbedIdentityBySession, invalidateAutoEmbedSession, getEmbedDrainUiStatus, piHarnessKindFromExecutable, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, getAuthorityManagedMarker, drainMirrorPages, V2_MEMORY_CATEGORIES, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, readProjectDocsCanonical, BoundedSessionMap, registerLkgPersistence, signatureForFields, lkgContentFields, lkgContentDigestFromFields, exactReusablePrefix, incrementalLkgContentDigests, captureSlot, getSlot, dropSlot, noteEntry, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, closeDatabase, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, 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, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, iterateEntriesToRawMessageRange, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getMemoryById, setMemoryClassification, archiveMemory, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, getAutoEmbeddingSessionCoverage, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };