@cortexkit/pi-magic-context 0.36.0 → 0.36.1

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.
@@ -7696,10 +7696,10 @@ var require_stringify = __commonJS((exports, module) => {
7696
7696
  replacer = null;
7697
7697
  indent = EMPTY;
7698
7698
  };
7699
- var join6 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two)), gap) : EMPTY;
7699
+ var join7 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two)), gap) : EMPTY;
7700
7700
  var join_content = (inside, value, gap) => {
7701
7701
  const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
7702
- return join6(comment, inside, gap);
7702
+ return join7(comment, inside, gap);
7703
7703
  };
7704
7704
  var stringify_string = (holder, key, value) => {
7705
7705
  const raw = get_raw_string_literal(holder, key);
@@ -7721,13 +7721,13 @@ var require_stringify = __commonJS((exports, module) => {
7721
7721
  if (i !== 0) {
7722
7722
  inside += COMMA;
7723
7723
  }
7724
- const before = join6(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
7724
+ const before = join7(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
7725
7725
  inside += before || LF + deeper_gap;
7726
7726
  inside += stringify(i, value, deeper_gap) || STR_NULL;
7727
7727
  inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
7728
7728
  after_comma = process_comments(value, AFTER(i), deeper_gap);
7729
7729
  }
7730
- inside += join6(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7730
+ inside += join7(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7731
7731
  return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
7732
7732
  };
7733
7733
  var object_stringify = (value, gap) => {
@@ -7748,13 +7748,13 @@ var require_stringify = __commonJS((exports, module) => {
7748
7748
  inside += COMMA;
7749
7749
  }
7750
7750
  first = false;
7751
- const before = join6(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
7751
+ const before = join7(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
7752
7752
  inside += before || LF + deeper_gap;
7753
7753
  inside += quote(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
7754
7754
  after_comma = process_comments(value, AFTER(key), deeper_gap);
7755
7755
  };
7756
7756
  keys.forEach(iteratee);
7757
- inside += join6(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7757
+ inside += join7(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7758
7758
  return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
7759
7759
  };
7760
7760
  function stringify(key, holder, gap) {
@@ -8648,6 +8648,311 @@ function scheduleAfterBootQuiet(task, additionalDelayMs = 0) {
8648
8648
  return timer;
8649
8649
  }
8650
8650
 
8651
+ // ../plugin/src/hooks/magic-context/read-session-formatting.ts
8652
+ import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
8653
+ import { createRequire } from "node:module";
8654
+ import { homedir as homedir3 } from "node:os";
8655
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
8656
+ import { pathToFileURL } from "node:url";
8657
+
8658
+ // ../plugin/src/shared/commit-detection.ts
8659
+ var HASH_HEX = "[0-9a-f]{7,12}";
8660
+ var COMMIT_HASH_TEST_PATTERN = new RegExp(`\\b${HASH_HEX}\\b`, "i");
8661
+ var COMMIT_VERB_PATTERN = /\b(?:commit(?:ted|ting|s)?|cherry-?pick(?:ed|ing|s)?|merge[ds]?|merging|rebas(?:e|ed|es|ing))\b/i;
8662
+ function textMentionsRecentCommit(text) {
8663
+ return COMMIT_HASH_TEST_PATTERN.test(text) && COMMIT_VERB_PATTERN.test(text);
8664
+ }
8665
+ function createCommitHashExtractPattern() {
8666
+ return new RegExp(`\`?\\b(${HASH_HEX})\\b\`?`, "gi");
8667
+ }
8668
+
8669
+ // ../plugin/src/shared/internal-initiator-marker.ts
8670
+ var OMO_INTERNAL_INITIATOR_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
8671
+
8672
+ // ../plugin/src/shared/system-directive.ts
8673
+ var SYSTEM_DIRECTIVE_PREFIX = "[SYSTEM DIRECTIVE: MAGIC-CONTEXT";
8674
+ function isSystemDirective(text) {
8675
+ return text.trimStart().startsWith(SYSTEM_DIRECTIVE_PREFIX);
8676
+ }
8677
+ function removeSystemReminders(text) {
8678
+ return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
8679
+ }
8680
+
8681
+ // ../plugin/src/hooks/magic-context/read-session-formatting.ts
8682
+ var MAX_COMMITS_PER_BLOCK = 5;
8683
+ function hasMeaningfulUserText(parts) {
8684
+ for (const part of parts) {
8685
+ if (part === null || typeof part !== "object")
8686
+ continue;
8687
+ const candidate = part;
8688
+ if (candidate.type !== "text" || typeof candidate.text !== "string")
8689
+ continue;
8690
+ if (candidate.ignored === true)
8691
+ continue;
8692
+ const cleaned = removeSystemReminders(candidate.text).replace(OMO_INTERNAL_INITIATOR_MARKER, "").trim();
8693
+ if (!cleaned)
8694
+ continue;
8695
+ if (isSystemDirective(cleaned))
8696
+ continue;
8697
+ return true;
8698
+ }
8699
+ return false;
8700
+ }
8701
+ function extractTexts(parts) {
8702
+ const texts = [];
8703
+ for (const part of parts) {
8704
+ if (part === null || typeof part !== "object")
8705
+ continue;
8706
+ const p = part;
8707
+ if (p.type === "text" && typeof p.text === "string" && p.text.trim().length > 0) {
8708
+ texts.push(p.text.trim());
8709
+ }
8710
+ }
8711
+ return texts;
8712
+ }
8713
+ function extractToolCallSummaries(parts) {
8714
+ const summaries = [];
8715
+ for (const part of parts) {
8716
+ if (part === null || typeof part !== "object")
8717
+ continue;
8718
+ const p = part;
8719
+ if (p.type !== "tool" || typeof p.tool !== "string")
8720
+ continue;
8721
+ const state = p.state;
8722
+ if (!state || typeof state !== "object")
8723
+ continue;
8724
+ const input = state.input;
8725
+ const metadata = state.metadata;
8726
+ const description = input && typeof input.description === "string" && input.description || metadata && typeof metadata.description === "string" && metadata.description;
8727
+ if (description) {
8728
+ summaries.push(`TC: ${description}`);
8729
+ continue;
8730
+ }
8731
+ const toolName = p.tool;
8732
+ const keyArg = extractKeyArg(toolName, input);
8733
+ summaries.push(keyArg ? `TC: ${toolName}(${keyArg})` : `TC: ${toolName}`);
8734
+ }
8735
+ return summaries;
8736
+ }
8737
+ function extractKeyArg(_toolName, input) {
8738
+ if (!input)
8739
+ return null;
8740
+ if (typeof input.filePath === "string")
8741
+ return truncateArg(input.filePath);
8742
+ if (typeof input.path === "string")
8743
+ return truncateArg(input.path);
8744
+ if (typeof input.pattern === "string")
8745
+ return truncateArg(input.pattern);
8746
+ if (typeof input.query === "string")
8747
+ return truncateArg(input.query);
8748
+ if (typeof input.symbol === "string")
8749
+ return input.symbol;
8750
+ if (typeof input.module === "string")
8751
+ return input.module;
8752
+ if (typeof input.action === "string")
8753
+ return input.action;
8754
+ return null;
8755
+ }
8756
+ function truncateArg(value, maxLen = 60) {
8757
+ if (value.length <= maxLen)
8758
+ return value;
8759
+ return `${value.slice(0, maxLen)}…`;
8760
+ }
8761
+ var TOKENIZER_PACKAGE_DIRS = [
8762
+ ["@cortexkit", "opencode-magic-context"],
8763
+ ["@cortexkit", "pi-magic-context"]
8764
+ ];
8765
+ var tokenizer;
8766
+ var tokenizerLoadAttempted = false;
8767
+ var tokenizerLoadPromise;
8768
+ var tokenizerWarningSent = false;
8769
+ function tokenizerPackageRoots() {
8770
+ const cwd = process.cwd();
8771
+ const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir3(), ".cache"), "opencode");
8772
+ const roots = [cwd, openCodeCache];
8773
+ const candidates = [];
8774
+ for (const root of roots) {
8775
+ for (const packageDir of TOKENIZER_PACKAGE_DIRS) {
8776
+ candidates.push(join2(root, "node_modules", ...packageDir, "node_modules", "ai-tokenizer"));
8777
+ }
8778
+ candidates.push(join2(root, "node_modules", "ai-tokenizer"));
8779
+ }
8780
+ let ancestor = process.argv[1] ? dirname2(resolve(process.argv[1])) : cwd;
8781
+ while (true) {
8782
+ candidates.push(join2(ancestor, "node_modules", "ai-tokenizer"));
8783
+ const parent = dirname2(ancestor);
8784
+ if (parent === ancestor)
8785
+ break;
8786
+ ancestor = parent;
8787
+ }
8788
+ return [...new Set(candidates)];
8789
+ }
8790
+ function packageImportTarget(value) {
8791
+ if (typeof value === "string")
8792
+ return value;
8793
+ if (!value || typeof value !== "object")
8794
+ return;
8795
+ const conditions = value;
8796
+ return packageImportTarget(conditions.import) ?? packageImportTarget(conditions.default);
8797
+ }
8798
+ function findTokenizerImportPaths() {
8799
+ for (const packageRoot of tokenizerPackageRoots()) {
8800
+ const packageJsonPath = join2(packageRoot, "package.json");
8801
+ if (!existsSync3(packageJsonPath))
8802
+ continue;
8803
+ try {
8804
+ const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
8805
+ const tokenizerTarget = packageImportTarget(packageJson.exports?.["."]) ?? (typeof packageJson.module === "string" ? packageJson.module : undefined) ?? (typeof packageJson.main === "string" ? packageJson.main : undefined);
8806
+ const encodingTarget = packageImportTarget(packageJson.exports?.["./encoding/claude"]);
8807
+ if (!tokenizerTarget || !encodingTarget)
8808
+ continue;
8809
+ return {
8810
+ tokenizerPath: realpathSync2(join2(packageRoot, tokenizerTarget)),
8811
+ encodingPath: realpathSync2(join2(packageRoot, encodingTarget))
8812
+ };
8813
+ } catch {}
8814
+ }
8815
+ return;
8816
+ }
8817
+ function constructTokenizer(tokenizerModule, claudeEncoding) {
8818
+ const typedModule = tokenizerModule;
8819
+ const Tokenizer = typedModule.default ?? typedModule.Tokenizer;
8820
+ if (!Tokenizer) {
8821
+ throw new Error("ai-tokenizer does not expose a Tokenizer constructor");
8822
+ }
8823
+ return new Tokenizer(claudeEncoding);
8824
+ }
8825
+ function loadTokenizer() {
8826
+ const requireFromThisModule = createRequire(import.meta.url);
8827
+ return constructTokenizer(requireFromThisModule("ai-" + "tokenizer"), requireFromThisModule("ai-tokenizer/encoding/" + "claude"));
8828
+ }
8829
+ async function loadTokenizerFromInstalledPackage() {
8830
+ const installedPaths = findTokenizerImportPaths();
8831
+ if (!installedPaths) {
8832
+ throw new Error("ai-tokenizer was not found under the project, runtime, or OpenCode cache node_modules roots");
8833
+ }
8834
+ const [tokenizerModule, claudeEncoding] = await Promise.all([
8835
+ import(pathToFileURL(installedPaths.tokenizerPath).href),
8836
+ import(pathToFileURL(installedPaths.encodingPath).href)
8837
+ ]);
8838
+ return constructTokenizer(tokenizerModule, claudeEncoding);
8839
+ }
8840
+ function warnTokenizerFallback(error) {
8841
+ if (tokenizerWarningSent)
8842
+ return;
8843
+ tokenizerWarningSent = true;
8844
+ const reason = error instanceof Error ? error.message : String(error);
8845
+ console.warn("[magic-context] ai-tokenizer is unavailable; using approximate character-based token counts for this process. Token budgets, persisted per-message counts, and protected-tail/compartment boundaries may be less accurate until restart:", reason);
8846
+ }
8847
+ async function preloadTokenizer() {
8848
+ if (tokenizer)
8849
+ return true;
8850
+ if (tokenizerLoadAttempted)
8851
+ return false;
8852
+ if (tokenizerLoadPromise)
8853
+ return tokenizerLoadPromise;
8854
+ tokenizerLoadPromise = (async () => {
8855
+ try {
8856
+ try {
8857
+ tokenizer = loadTokenizer();
8858
+ } catch {
8859
+ tokenizer = await loadTokenizerFromInstalledPackage();
8860
+ }
8861
+ tokenizerLoadAttempted = true;
8862
+ return true;
8863
+ } catch (error) {
8864
+ tokenizerLoadAttempted = true;
8865
+ warnTokenizerFallback(error);
8866
+ return false;
8867
+ } finally {
8868
+ tokenizerLoadPromise = undefined;
8869
+ }
8870
+ })();
8871
+ return tokenizerLoadPromise;
8872
+ }
8873
+ function getTokenizer() {
8874
+ if (tokenizer || tokenizerLoadAttempted)
8875
+ return tokenizer;
8876
+ tokenizerLoadAttempted = true;
8877
+ try {
8878
+ tokenizer = loadTokenizer();
8879
+ } catch (error) {
8880
+ warnTokenizerFallback(error);
8881
+ }
8882
+ return tokenizer;
8883
+ }
8884
+ function estimateTokensHeuristically(text) {
8885
+ return Math.ceil(text.length / 3.5);
8886
+ }
8887
+ function estimateTokens(text) {
8888
+ if (!text)
8889
+ return 0;
8890
+ const activeTokenizer = getTokenizer();
8891
+ if (!activeTokenizer)
8892
+ return estimateTokensHeuristically(text);
8893
+ try {
8894
+ return activeTokenizer.encode(text, "all").length;
8895
+ } catch (error) {
8896
+ tokenizer = undefined;
8897
+ tokenizerLoadAttempted = true;
8898
+ warnTokenizerFallback(error);
8899
+ return estimateTokensHeuristically(text);
8900
+ }
8901
+ }
8902
+ function normalizeText(text) {
8903
+ return text.replace(/\s+/g, " ").trim();
8904
+ }
8905
+ function compactRole(role) {
8906
+ if (role === "assistant")
8907
+ return "A";
8908
+ if (role === "user")
8909
+ return "U";
8910
+ return role.slice(0, 1).toUpperCase() || "M";
8911
+ }
8912
+ function formatBlock(block) {
8913
+ const range = block.startOrdinal === block.endOrdinal ? `[${block.startOrdinal}]` : `[${block.startOrdinal}-${block.endOrdinal}]`;
8914
+ const commitSuffix = block.commitHashes.length > 0 ? ` commits: ${block.commitHashes.join(", ")}` : "";
8915
+ return `${range} ${block.role}:${commitSuffix} ${block.parts.join(" / ")}`;
8916
+ }
8917
+ function extractCommitHashes(text) {
8918
+ const hashes = [];
8919
+ const seen = new Set;
8920
+ for (const match of text.matchAll(createCommitHashExtractPattern())) {
8921
+ const hash = match[1]?.toLowerCase();
8922
+ if (!hash || seen.has(hash))
8923
+ continue;
8924
+ seen.add(hash);
8925
+ hashes.push(hash);
8926
+ if (hashes.length >= MAX_COMMITS_PER_BLOCK)
8927
+ break;
8928
+ }
8929
+ return hashes;
8930
+ }
8931
+ function compactTextForSummary(text, role) {
8932
+ const commitHashes = role === "assistant" ? extractCommitHashes(text) : [];
8933
+ if (commitHashes.length === 0 || !COMMIT_VERB_PATTERN.test(text)) {
8934
+ return { text, commitHashes };
8935
+ }
8936
+ const withoutHashes = text.replace(createCommitHashExtractPattern(), "").replace(/\(\s*\)/g, "").replace(/\s+,/g, ",").replace(/,\s*,+/g, ", ").replace(/\s{2,}/g, " ").replace(/\s+([,.;:])/g, "$1").trim();
8937
+ return {
8938
+ text: withoutHashes.length > 0 ? withoutHashes : text,
8939
+ commitHashes
8940
+ };
8941
+ }
8942
+ function mergeCommitHashes(existing, next) {
8943
+ if (next.length === 0)
8944
+ return existing;
8945
+ const merged = [...existing];
8946
+ for (const hash of next) {
8947
+ if (merged.includes(hash))
8948
+ continue;
8949
+ merged.push(hash);
8950
+ if (merged.length >= MAX_COMMITS_PER_BLOCK)
8951
+ break;
8952
+ }
8953
+ return merged;
8954
+ }
8955
+
8651
8956
  // ../plugin/src/shared/storage-permissions.ts
8652
8957
  var enforcePrivateStoragePermissions = true;
8653
8958
  function setStoragePrivatePermissionEnforcement(enforce) {
@@ -8662,14 +8967,14 @@ import {
8662
8967
  chmodSync,
8663
8968
  copyFileSync,
8664
8969
  cpSync,
8665
- existsSync as existsSync4,
8970
+ existsSync as existsSync5,
8666
8971
  mkdirSync as mkdirSync2,
8667
8972
  readdirSync,
8668
- readFileSync as readFileSync3,
8973
+ readFileSync as readFileSync4,
8669
8974
  statSync as statSync3,
8670
8975
  unlinkSync as unlinkSync2
8671
8976
  } from "node:fs";
8672
- import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
8977
+ import { basename as basename2, dirname as dirname3, join as join4 } from "node:path";
8673
8978
 
8674
8979
  // ../plugin/src/shared/error-message.ts
8675
8980
  function getErrorMessage(error) {
@@ -8749,7 +9054,7 @@ function safeString(value) {
8749
9054
 
8750
9055
  // ../plugin/src/shared/rpc-utils.ts
8751
9056
  import { execFileSync as execFileSync2 } from "node:child_process";
8752
- import { readFileSync as readFileSync2 } from "node:fs";
9057
+ import { readFileSync as readFileSync3 } from "node:fs";
8753
9058
  function isPidAlive(pid) {
8754
9059
  if (!Number.isInteger(pid) || pid <= 0)
8755
9060
  return false;
@@ -8764,8 +9069,9 @@ var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
8764
9069
  var LINUX_CLOCK_TICKS_PER_SECOND = 100;
8765
9070
  var PS_PROBE_TIMEOUT_MS = 1000;
8766
9071
  var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
8767
- var rpcIdentityReadFileSync = readFileSync2;
9072
+ var rpcIdentityReadFileSync = readFileSync3;
8768
9073
  var rpcIdentityExecFileSync = execFileSync2;
9074
+ var rpcProcessListExecFileSync = execFileSync2;
8769
9075
  var rpcIdentityPlatform = process.platform;
8770
9076
  var rpcIdentityNowMs = () => Date.now();
8771
9077
  function parseLinuxProcessStartTime(statContent, uptimeContent) {
@@ -8838,6 +9144,49 @@ function isPidIdentityPlausible(record) {
8838
9144
  return true;
8839
9145
  return commandLooksLikeOpenCode(command);
8840
9146
  }
9147
+ function commandLooksLikePi(command) {
9148
+ const normalized = command.trim().toLowerCase().replaceAll("\\", "/");
9149
+ const tokens = normalized.split(/\s+/).filter(Boolean);
9150
+ const executableName = (token) => (token ?? "").split("/").at(-1) ?? "";
9151
+ const first = executableName(tokens[0]).replace(/\.exe$/, "");
9152
+ if (["pi", "pi.cmd", "omp", "oh-my-pi"].includes(first))
9153
+ return true;
9154
+ if (["node", "bun", "deno"].includes(first)) {
9155
+ const script = executableName(tokens[1]);
9156
+ return ["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script) || normalized.includes("pi-coding-agent");
9157
+ }
9158
+ return false;
9159
+ }
9160
+ function inspectLivePiProcesses() {
9161
+ if (false) {}
9162
+ try {
9163
+ const output = String(rpcProcessListExecFileSync("ps", ["-axo", "pid=,command="], {
9164
+ encoding: "utf8",
9165
+ timeout: PS_PROBE_TIMEOUT_MS
9166
+ }));
9167
+ const pids = new Set;
9168
+ for (const line of output.split(/\r?\n/)) {
9169
+ const match = /^\s*(\d+)\s+(.+)$/.exec(line);
9170
+ if (!match)
9171
+ continue;
9172
+ const pid = Number(match[1]);
9173
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
9174
+ continue;
9175
+ if (commandLooksLikePi(match[2]))
9176
+ pids.add(pid);
9177
+ }
9178
+ return { state: "known", processIds: [...pids].sort((left, right) => left - right) };
9179
+ } catch (error) {
9180
+ return {
9181
+ state: "unreadable",
9182
+ processIds: [],
9183
+ error: error instanceof Error ? error.message : String(error)
9184
+ };
9185
+ }
9186
+ }
9187
+ function discoverLivePiProcessIds() {
9188
+ return inspectLivePiProcesses().processIds;
9189
+ }
8841
9190
  function parseRpcPortFile(content, fallbackPid = 0) {
8842
9191
  const trimmed = content.trim();
8843
9192
  if (!trimmed)
@@ -11803,7 +12152,7 @@ function runMigrations(db) {
11803
12152
  }
11804
12153
  async function runMigrationsWithRetry(db, options = {}) {
11805
12154
  const retryDelaysMs = options.retryDelaysMs ?? MIGRATION_LOCK_RETRY_DELAYS_MS;
11806
- const sleep = options.sleep ?? ((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));
12155
+ const sleep = options.sleep ?? ((delayMs) => new Promise((resolve2) => setTimeout(resolve2, delayMs)));
11807
12156
  const totalAttempts = retryDelaysMs.length + 1;
11808
12157
  for (let attempt = 1;attempt <= totalAttempts; attempt += 1) {
11809
12158
  log(`[migrations] migration lock check attempt ${attempt}/${totalAttempts}`);
@@ -11822,184 +12171,6 @@ async function runMigrationsWithRetry(db, options = {}) {
11822
12171
  }
11823
12172
  }
11824
12173
 
11825
- // ../plugin/src/hooks/magic-context/read-session-formatting.ts
11826
- import { createRequire } from "node:module";
11827
-
11828
- // ../plugin/src/shared/commit-detection.ts
11829
- var HASH_HEX = "[0-9a-f]{7,12}";
11830
- var COMMIT_HASH_TEST_PATTERN = new RegExp(`\\b${HASH_HEX}\\b`, "i");
11831
- var COMMIT_VERB_PATTERN = /\b(?:commit(?:ted|ting|s)?|cherry-?pick(?:ed|ing|s)?|merge[ds]?|merging|rebas(?:e|ed|es|ing))\b/i;
11832
- function textMentionsRecentCommit(text) {
11833
- return COMMIT_HASH_TEST_PATTERN.test(text) && COMMIT_VERB_PATTERN.test(text);
11834
- }
11835
- function createCommitHashExtractPattern() {
11836
- return new RegExp(`\`?\\b(${HASH_HEX})\\b\`?`, "gi");
11837
- }
11838
-
11839
- // ../plugin/src/shared/internal-initiator-marker.ts
11840
- var OMO_INTERNAL_INITIATOR_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
11841
-
11842
- // ../plugin/src/shared/system-directive.ts
11843
- var SYSTEM_DIRECTIVE_PREFIX = "[SYSTEM DIRECTIVE: MAGIC-CONTEXT";
11844
- function isSystemDirective(text) {
11845
- return text.trimStart().startsWith(SYSTEM_DIRECTIVE_PREFIX);
11846
- }
11847
- function removeSystemReminders(text) {
11848
- return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
11849
- }
11850
-
11851
- // ../plugin/src/hooks/magic-context/read-session-formatting.ts
11852
- var MAX_COMMITS_PER_BLOCK = 5;
11853
- function hasMeaningfulUserText(parts) {
11854
- for (const part of parts) {
11855
- if (part === null || typeof part !== "object")
11856
- continue;
11857
- const candidate = part;
11858
- if (candidate.type !== "text" || typeof candidate.text !== "string")
11859
- continue;
11860
- if (candidate.ignored === true)
11861
- continue;
11862
- const cleaned = removeSystemReminders(candidate.text).replace(OMO_INTERNAL_INITIATOR_MARKER, "").trim();
11863
- if (!cleaned)
11864
- continue;
11865
- if (isSystemDirective(cleaned))
11866
- continue;
11867
- return true;
11868
- }
11869
- return false;
11870
- }
11871
- function extractTexts(parts) {
11872
- const texts = [];
11873
- for (const part of parts) {
11874
- if (part === null || typeof part !== "object")
11875
- continue;
11876
- const p = part;
11877
- if (p.type === "text" && typeof p.text === "string" && p.text.trim().length > 0) {
11878
- texts.push(p.text.trim());
11879
- }
11880
- }
11881
- return texts;
11882
- }
11883
- function extractToolCallSummaries(parts) {
11884
- const summaries = [];
11885
- for (const part of parts) {
11886
- if (part === null || typeof part !== "object")
11887
- continue;
11888
- const p = part;
11889
- if (p.type !== "tool" || typeof p.tool !== "string")
11890
- continue;
11891
- const state = p.state;
11892
- if (!state || typeof state !== "object")
11893
- continue;
11894
- const input = state.input;
11895
- const metadata = state.metadata;
11896
- const description = input && typeof input.description === "string" && input.description || metadata && typeof metadata.description === "string" && metadata.description;
11897
- if (description) {
11898
- summaries.push(`TC: ${description}`);
11899
- continue;
11900
- }
11901
- const toolName = p.tool;
11902
- const keyArg = extractKeyArg(toolName, input);
11903
- summaries.push(keyArg ? `TC: ${toolName}(${keyArg})` : `TC: ${toolName}`);
11904
- }
11905
- return summaries;
11906
- }
11907
- function extractKeyArg(_toolName, input) {
11908
- if (!input)
11909
- return null;
11910
- if (typeof input.filePath === "string")
11911
- return truncateArg(input.filePath);
11912
- if (typeof input.path === "string")
11913
- return truncateArg(input.path);
11914
- if (typeof input.pattern === "string")
11915
- return truncateArg(input.pattern);
11916
- if (typeof input.query === "string")
11917
- return truncateArg(input.query);
11918
- if (typeof input.symbol === "string")
11919
- return input.symbol;
11920
- if (typeof input.module === "string")
11921
- return input.module;
11922
- if (typeof input.action === "string")
11923
- return input.action;
11924
- return null;
11925
- }
11926
- function truncateArg(value, maxLen = 60) {
11927
- if (value.length <= maxLen)
11928
- return value;
11929
- return `${value.slice(0, maxLen)}…`;
11930
- }
11931
- var requireFromThisModule = createRequire(import.meta.url);
11932
- var tokenizer;
11933
- function getTokenizer() {
11934
- if (tokenizer)
11935
- return tokenizer;
11936
- const tokenizerModule = requireFromThisModule("ai-" + "tokenizer");
11937
- const Tokenizer = tokenizerModule.default ?? tokenizerModule.Tokenizer;
11938
- if (!Tokenizer)
11939
- throw new Error("ai-tokenizer does not expose a Tokenizer constructor");
11940
- const claudeEncoding = requireFromThisModule("ai-tokenizer/encoding/" + "claude");
11941
- tokenizer = new Tokenizer(claudeEncoding);
11942
- return tokenizer;
11943
- }
11944
- function estimateTokens(text) {
11945
- if (!text)
11946
- return 0;
11947
- return getTokenizer().encode(text, "all").length;
11948
- }
11949
- function normalizeText(text) {
11950
- return text.replace(/\s+/g, " ").trim();
11951
- }
11952
- function compactRole(role) {
11953
- if (role === "assistant")
11954
- return "A";
11955
- if (role === "user")
11956
- return "U";
11957
- return role.slice(0, 1).toUpperCase() || "M";
11958
- }
11959
- function formatBlock(block) {
11960
- const range = block.startOrdinal === block.endOrdinal ? `[${block.startOrdinal}]` : `[${block.startOrdinal}-${block.endOrdinal}]`;
11961
- const commitSuffix = block.commitHashes.length > 0 ? ` commits: ${block.commitHashes.join(", ")}` : "";
11962
- return `${range} ${block.role}:${commitSuffix} ${block.parts.join(" / ")}`;
11963
- }
11964
- function extractCommitHashes(text) {
11965
- const hashes = [];
11966
- const seen = new Set;
11967
- for (const match of text.matchAll(createCommitHashExtractPattern())) {
11968
- const hash = match[1]?.toLowerCase();
11969
- if (!hash || seen.has(hash))
11970
- continue;
11971
- seen.add(hash);
11972
- hashes.push(hash);
11973
- if (hashes.length >= MAX_COMMITS_PER_BLOCK)
11974
- break;
11975
- }
11976
- return hashes;
11977
- }
11978
- function compactTextForSummary(text, role) {
11979
- const commitHashes = role === "assistant" ? extractCommitHashes(text) : [];
11980
- if (commitHashes.length === 0 || !COMMIT_VERB_PATTERN.test(text)) {
11981
- return { text, commitHashes };
11982
- }
11983
- const withoutHashes = text.replace(createCommitHashExtractPattern(), "").replace(/\(\s*\)/g, "").replace(/\s+,/g, ",").replace(/,\s*,+/g, ", ").replace(/\s{2,}/g, " ").replace(/\s+([,.;:])/g, "$1").trim();
11984
- return {
11985
- text: withoutHashes.length > 0 ? withoutHashes : text,
11986
- commitHashes
11987
- };
11988
- }
11989
- function mergeCommitHashes(existing, next) {
11990
- if (next.length === 0)
11991
- return existing;
11992
- const merged = [...existing];
11993
- for (const hash of next) {
11994
- if (merged.includes(hash))
11995
- continue;
11996
- merged.push(hash);
11997
- if (merged.length >= MAX_COMMITS_PER_BLOCK)
11998
- break;
11999
- }
12000
- return merged;
12001
- }
12002
-
12003
12174
  // ../plugin/src/shared/stable-json.ts
12004
12175
  function stableStringify(value, seen = new WeakSet) {
12005
12176
  if (value === undefined)
@@ -12054,12 +12225,12 @@ function loadToolDefinitionMeasurements(db) {
12054
12225
  }
12055
12226
 
12056
12227
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
12057
- import { existsSync as existsSync3 } from "node:fs";
12058
- import { join as join2 } from "node:path";
12228
+ import { existsSync as existsSync4 } from "node:fs";
12229
+ import { join as join3 } from "node:path";
12059
12230
  var LEASE_DURATION_MS = 5 * 60 * 1000;
12060
12231
  var LEASE_RENEWAL_MS = 60 * 1000;
12061
12232
  function resolveOpencodeDbPath() {
12062
- return join2(getDataDir(), "opencode", "opencode.db");
12233
+ return join3(getDataDir(), "opencode", "opencode.db");
12063
12234
  }
12064
12235
  function ensureBackfillStateTable(db) {
12065
12236
  db.exec(`
@@ -12094,7 +12265,7 @@ function runToolOwnerBackfill(db) {
12094
12265
  return result;
12095
12266
  }
12096
12267
  const opencodeDbPath = resolveOpencodeDbPath();
12097
- if (!existsSync3(opencodeDbPath)) {
12268
+ if (!existsSync4(opencodeDbPath)) {
12098
12269
  log(`[backfill] OpenCode DB not found at ${opencodeDbPath} — marking all unbackfilled sessions as skipped. Lazy adoption (defense-in-depth) handles legacy rows at runtime.`);
12099
12270
  markAllUnbackfilledSessionsSkipped(db);
12100
12271
  result.sessionsSkippedNoOcDb = countSessionsByStatus(db, "skipped");
@@ -12344,7 +12515,7 @@ function restrictDatabaseFilePermissions(dbPath) {
12344
12515
  return;
12345
12516
  for (const suffix of ["", "-wal", "-shm"]) {
12346
12517
  const file = `${dbPath}${suffix}`;
12347
- if (!existsSync4(file))
12518
+ if (!existsSync5(file))
12348
12519
  continue;
12349
12520
  try {
12350
12521
  storagePermissionFs.chmodSync(file, 384);
@@ -12355,20 +12526,20 @@ function restrictDatabaseFilePermissions(dbPath) {
12355
12526
  }
12356
12527
  function resolveDatabasePath(dbPathOverride) {
12357
12528
  if (dbPathOverride) {
12358
- return { dbDir: dirname2(dbPathOverride), dbPath: dbPathOverride };
12529
+ return { dbDir: dirname3(dbPathOverride), dbPath: dbPathOverride };
12359
12530
  }
12360
12531
  const dbDir = getMagicContextStorageDir();
12361
- return { dbDir, dbPath: join3(dbDir, "context.db") };
12532
+ return { dbDir, dbPath: join4(dbDir, "context.db") };
12362
12533
  }
12363
12534
  function getDatabasePath(db) {
12364
12535
  return pathByDatabase.get(db) ?? null;
12365
12536
  }
12366
12537
  function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
12367
- if (existsSync4(targetDbPath))
12538
+ if (existsSync5(targetDbPath))
12368
12539
  return;
12369
12540
  const legacyDir = getLegacyOpenCodeMagicContextStorageDir();
12370
- const legacyDbPath = join3(legacyDir, "context.db");
12371
- if (!existsSync4(legacyDbPath))
12541
+ const legacyDbPath = join4(legacyDir, "context.db");
12542
+ if (!existsSync5(legacyDbPath))
12372
12543
  return;
12373
12544
  log(`[magic-context] migrating legacy plugin storage: ${legacyDir} -> ${targetDbDir} (legacy left in place as backup)`);
12374
12545
  ensureSecureStorageDir(targetDbDir);
@@ -12384,8 +12555,8 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
12384
12555
  }
12385
12556
  for (const suffix of ["", "-wal", "-shm"]) {
12386
12557
  const src = `${legacyDbPath}${suffix}`;
12387
- const dst = join3(targetDbDir, `context.db${suffix}`);
12388
- if (existsSync4(src)) {
12558
+ const dst = join4(targetDbDir, `context.db${suffix}`);
12559
+ if (existsSync5(src)) {
12389
12560
  try {
12390
12561
  copyFileSync(src, dst);
12391
12562
  } catch (error) {
@@ -12393,9 +12564,9 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
12393
12564
  }
12394
12565
  }
12395
12566
  }
12396
- const legacyModelsDir = join3(legacyDir, "models");
12397
- const targetModelsDir = join3(targetDbDir, "models");
12398
- if (existsSync4(legacyModelsDir) && !existsSync4(targetModelsDir)) {
12567
+ const legacyModelsDir = join4(legacyDir, "models");
12568
+ const targetModelsDir = join4(targetDbDir, "models");
12569
+ if (existsSync5(legacyModelsDir) && !existsSync5(targetModelsDir)) {
12399
12570
  try {
12400
12571
  cpSync(legacyModelsDir, targetModelsDir, { recursive: true });
12401
12572
  } catch (error) {
@@ -12449,7 +12620,7 @@ function unreadableDiscovery(path2, arm) {
12449
12620
  var RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
12450
12621
  var defaultRpcDiscoveryFs = {
12451
12622
  readdirSync: (path2, options) => options?.withFileTypes ? readdirSync(path2, { withFileTypes: true }) : readdirSync(path2),
12452
- readFileSync: (path2, encoding) => String(readFileSync3(path2, encoding)),
12623
+ readFileSync: (path2, encoding) => String(readFileSync4(path2, encoding)),
12453
12624
  statSync: (path2) => ({ mtimeMs: statSync3(path2).mtimeMs }),
12454
12625
  unlinkSync: (path2) => unlinkSync2(path2)
12455
12626
  };
@@ -12487,7 +12658,7 @@ function classifyJunkDiscovery(portFile, raw, staleFiles) {
12487
12658
  return null;
12488
12659
  }
12489
12660
  function inspectRpcServerDiscovery(storageDir) {
12490
- const rpcRoot = join3(storageDir, "rpc");
12661
+ const rpcRoot = join4(storageDir, "rpc");
12491
12662
  let projectEntries;
12492
12663
  try {
12493
12664
  projectEntries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
@@ -12501,7 +12672,7 @@ function inspectRpcServerDiscovery(storageDir) {
12501
12672
  for (const projectEntry of projectEntries) {
12502
12673
  if (!projectEntry.isDirectory())
12503
12674
  continue;
12504
- const projectDir = join3(rpcRoot, projectEntry.name);
12675
+ const projectDir = join4(rpcRoot, projectEntry.name);
12505
12676
  let entries;
12506
12677
  try {
12507
12678
  entries = rpcDiscoveryFs.readdirSync(projectDir);
@@ -12512,7 +12683,7 @@ function inspectRpcServerDiscovery(storageDir) {
12512
12683
  }
12513
12684
  for (const entry of entries) {
12514
12685
  if (entry === "port" || entry.startsWith("port-") && entry.endsWith(".json")) {
12515
- portFiles.push(join3(projectDir, entry));
12686
+ portFiles.push(join4(projectDir, entry));
12516
12687
  }
12517
12688
  }
12518
12689
  }
@@ -12565,14 +12736,16 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12565
12736
  return true;
12566
12737
  }
12567
12738
  const discovery = inspectRpcServerDiscovery(dbDir);
12568
- if (discovery.state === "absent" || discovery.state === "stale") {
12739
+ const piPids = discoverLivePiProcessIds();
12740
+ if ((discovery.state === "absent" || discovery.state === "stale") && piPids.length === 0) {
12569
12741
  lastMigrationOnOpenRefusal = null;
12570
12742
  return true;
12571
12743
  }
12744
+ const blockingPids = [...new Set([...discovery.serverPids, ...piPids])].sort((left, right) => left - right);
12572
12745
  lastMigrationOnOpenRefusal = {
12573
12746
  persistedVersion,
12574
12747
  supportedVersion: latestSupportedVersion,
12575
- serverPids: discovery.serverPids,
12748
+ serverPids: blockingPids,
12576
12749
  ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {},
12577
12750
  ...discovery.unreadableArm ? { unreadableArm: discovery.unreadableArm } : {}
12578
12751
  };
@@ -12582,7 +12755,11 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12582
12755
  const recovery = arm === "io" ? `If no OpenCode server is running, it is safe to delete ${unreadableFile} and retry.` : `Retry after the file is older than the ten-minute grace window, or stop OpenCode before deleting it.`;
12583
12756
  log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} because RPC discovery file ${unreadableFile} is uncertain (${arm} arm), so the absence of a live OpenCode server cannot be proven. ${recovery}`);
12584
12757
  } else {
12585
- log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while live OpenCode server PID(s) ${discovery.serverPids.join(", ")} may still use the old plugin build. Restart OpenCode, then retry this process.`);
12758
+ const blockers = [
12759
+ ...discovery.serverPids.map((pid) => `OpenCode server PID ${pid}`),
12760
+ ...piPids.map((pid) => `Pi harness PID ${pid}`)
12761
+ ];
12762
+ log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while ${blockers.join(", ")} may still use the old plugin build. Restart the blocking harness, then retry this process.`);
12586
12763
  }
12587
12764
  return false;
12588
12765
  }
@@ -15227,13 +15404,13 @@ function clearCompressionDepthRange(db, sessionId, startOrdinal, endOrdinal) {
15227
15404
  import { createHash as createHash4 } from "node:crypto";
15228
15405
 
15229
15406
  // ../plugin/src/hooks/magic-context/read-session-db.ts
15230
- import { existsSync as existsSync5 } from "node:fs";
15231
- import { join as join4 } from "node:path";
15407
+ import { existsSync as existsSync6 } from "node:fs";
15408
+ import { join as join5 } from "node:path";
15232
15409
  function getOpenCodeDbPath() {
15233
- return join4(getDataDir(), "opencode", "opencode.db");
15410
+ return join5(getDataDir(), "opencode", "opencode.db");
15234
15411
  }
15235
15412
  function openCodeDbExists() {
15236
- return existsSync5(getOpenCodeDbPath());
15413
+ return existsSync6(getOpenCodeDbPath());
15237
15414
  }
15238
15415
  var cachedReadOnlyDb = null;
15239
15416
  function closeCachedReadOnlyDb() {
@@ -17313,7 +17490,7 @@ function escapeXmlContent(s) {
17313
17490
  }
17314
17491
  // ../plugin/src/features/magic-context/project-docs-hash.ts
17315
17492
  import { createHash as createHash5 } from "node:crypto";
17316
- import { lstatSync, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
17493
+ import { lstatSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
17317
17494
  import path2 from "node:path";
17318
17495
  var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
17319
17496
  var PROJECT_DOCS_DELIMITER = `
@@ -17387,7 +17564,7 @@ function readCanonicalPieces(projectDirectory, files) {
17387
17564
  if (!safeToRead) {
17388
17565
  continue;
17389
17566
  }
17390
- const canonicalContent = canonicalizeDocContent(readFileSync4(filePath, "utf8"));
17567
+ const canonicalContent = canonicalizeDocContent(readFileSync5(filePath, "utf8"));
17391
17568
  hashPieces.push(`file:${filename}
17392
17569
  ${canonicalContent}`);
17393
17570
  renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
@@ -17460,6 +17637,67 @@ function mapMessageId(filter, messageId) {
17460
17637
  return null;
17461
17638
  return filter.mapMessageId?.(messageId) ?? messageId;
17462
17639
  }
17640
+ function tableExists3(db, table) {
17641
+ const row = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
17642
+ return row !== null && row !== undefined;
17643
+ }
17644
+ function insertDynamicRow(db, table, row) {
17645
+ const names = Object.keys(row);
17646
+ const quoted = names.map((name) => `"${name.replaceAll('"', '""')}"`);
17647
+ const placeholders2 = names.map(() => "?").join(", ");
17648
+ db.prepare(`INSERT INTO "${table.replaceAll('"', '""')}" (${quoted.join(", ")}) VALUES (${placeholders2})`).run(...names.map((name) => row[name]));
17649
+ }
17650
+ function anchoredMessageId(blockId) {
17651
+ const separator = blockId.lastIndexOf("#");
17652
+ return separator > 0 ? blockId.slice(0, separator) : blockId;
17653
+ }
17654
+ function copyPiSessionNotesAndFacts(db, sourceSessionId, destinationSessionId, filter) {
17655
+ let notesCopied = 0;
17656
+ if (tableExists3(db, "notes")) {
17657
+ const sourceNotes = db.prepare("SELECT * FROM notes WHERE session_id = ? AND type = 'session' ORDER BY id ASC").all(sourceSessionId);
17658
+ for (const source of sourceNotes) {
17659
+ const row = {
17660
+ ...source,
17661
+ session_id: destinationSessionId
17662
+ };
17663
+ delete row.id;
17664
+ const blockId = typeof source.anchor_block_id === "string" ? source.anchor_block_id : "";
17665
+ if (blockId) {
17666
+ const sourceMessageId = anchoredMessageId(blockId);
17667
+ if (!filter.includeMessageId(sourceMessageId))
17668
+ continue;
17669
+ const mappedMessageId = mapMessageId(filter, sourceMessageId) ?? sourceMessageId;
17670
+ row.anchor_block_id = `${mappedMessageId}${blockId.slice(sourceMessageId.length)}`;
17671
+ const mappedOrdinal = filter.resolveBoundaryOrdinal(sourceMessageId);
17672
+ if (mappedOrdinal === undefined)
17673
+ continue;
17674
+ if ("anchor_ordinal" in row)
17675
+ row.anchor_ordinal = mappedOrdinal;
17676
+ } else if (typeof source.anchor_ordinal === "number" && filter.mapOrdinal) {
17677
+ const mappedOrdinal = filter.mapOrdinal(source.anchor_ordinal);
17678
+ if (mappedOrdinal === undefined)
17679
+ continue;
17680
+ row.anchor_ordinal = mappedOrdinal;
17681
+ }
17682
+ insertDynamicRow(db, "notes", row);
17683
+ notesCopied += 1;
17684
+ }
17685
+ }
17686
+ let factsCopied = 0;
17687
+ if (tableExists3(db, "session_facts")) {
17688
+ const sourceFacts = db.prepare("SELECT * FROM session_facts WHERE session_id = ? ORDER BY id ASC").all(sourceSessionId);
17689
+ for (const source of sourceFacts) {
17690
+ const row = {
17691
+ ...source,
17692
+ session_id: destinationSessionId
17693
+ };
17694
+ delete row.id;
17695
+ insertDynamicRow(db, "session_facts", row);
17696
+ factsCopied += 1;
17697
+ }
17698
+ }
17699
+ return { notesCopied, factsCopied };
17700
+ }
17463
17701
  function filterIdBlob(raw, filter) {
17464
17702
  if (!raw)
17465
17703
  return "";
@@ -17480,12 +17718,14 @@ function clampWatermark(value, maxCopiedTag) {
17480
17718
  }
17481
17719
  function copySessionStateForClone(db, sourceSessionId, destinationSessionId, filter) {
17482
17720
  return runImmediate(db, () => {
17483
- if (countRows(db, "compartments", destinationSessionId) > 0 || countRows(db, "tags", destinationSessionId) > 0) {
17721
+ if (countRows(db, "compartments", destinationSessionId) > 0 || countRows(db, "tags", destinationSessionId) > 0 || filter.copySessionNotesAndFacts === true && (tableExists3(db, "notes") && countRows(db, "notes", destinationSessionId) > 0 || tableExists3(db, "session_facts") && countRows(db, "session_facts", destinationSessionId) > 0)) {
17484
17722
  return {
17485
17723
  kind: "destination-not-empty",
17486
17724
  compartmentsCopied: 0,
17487
17725
  tagsCopied: 0,
17488
17726
  pendingOpsCopied: 0,
17727
+ notesCopied: 0,
17728
+ factsCopied: 0,
17489
17729
  pendingMarkerMigrated: false
17490
17730
  };
17491
17731
  }
@@ -17569,6 +17809,7 @@ function copySessionStateForClone(db, sourceSessionId, destinationSessionId, fil
17569
17809
  insertPendingOp.run(destinationSessionId, destinationTagId, row.operation, row.queued_at, row.harness);
17570
17810
  }
17571
17811
  }
17812
+ const inherited = filter.copySessionNotesAndFacts === true ? copyPiSessionNotesAndFacts(db, sourceSessionId, destinationSessionId, filter) : { notesCopied: 0, factsCopied: 0 };
17572
17813
  const meta = db.prepare(`SELECT cleared_reasoning_through_tag, tool_reclaim_watermark,
17573
17814
  pi_stable_id_scheme, stripped_placeholder_ids,
17574
17815
  stale_reduce_stripped_ids, processed_image_stripped_ids,
@@ -17610,6 +17851,8 @@ function copySessionStateForClone(db, sourceSessionId, destinationSessionId, fil
17610
17851
  compartmentsCopied: copiedCompartments.length,
17611
17852
  tagsCopied: copiedTagNumbers.length,
17612
17853
  pendingOpsCopied: typeof pendingOpsRow?.count === "number" ? pendingOpsRow.count : 0,
17854
+ notesCopied: inherited.notesCopied,
17855
+ factsCopied: inherited.factsCopied,
17613
17856
  pendingMarkerMigrated: pendingMarker !== null
17614
17857
  };
17615
17858
  });
@@ -19040,6 +19283,20 @@ function getTagsByNumbers(db, sessionId, tagNumbers) {
19040
19283
  const rows = db.prepare(`SELECT ${TAG_SELECT_COLUMNS} FROM tags WHERE session_id = ? AND tag_number IN (${placeholders3}) ORDER BY tag_number ASC, id ASC`).all(sessionId, ...tagNumbers).filter(isTagRow);
19041
19284
  return rows.map(toTagEntry);
19042
19285
  }
19286
+ function getDroppedTagsByNumbers(db, sessionId, tagNumbers) {
19287
+ if (tagNumbers.length === 0)
19288
+ return [];
19289
+ if (tagNumbers.length > 900) {
19290
+ const all = [];
19291
+ for (let i = 0;i < tagNumbers.length; i += 900) {
19292
+ all.push(...getDroppedTagsByNumbers(db, sessionId, tagNumbers.slice(i, i + 900)));
19293
+ }
19294
+ return all;
19295
+ }
19296
+ const placeholders3 = tagNumbers.map(() => "?").join(",");
19297
+ const rows = db.prepare(`SELECT ${TAG_SELECT_COLUMNS} FROM tags WHERE session_id = ? AND status = 'dropped' AND tag_number IN (${placeholders3}) ORDER BY tag_number ASC, id ASC`).all(sessionId, ...tagNumbers).filter(isTagRow);
19298
+ return rows.map(toTagEntry);
19299
+ }
19043
19300
  function getMaxDroppedTagNumber(db, sessionId) {
19044
19301
  const row = getMaxDroppedTagNumberStatement(db).get(sessionId);
19045
19302
  return isMaxTagNumberRow(row) ? row.max_tag_number : 0;
@@ -19109,6 +19366,47 @@ var ERROR_CLASSES = new Set([
19109
19366
  "permission_denied",
19110
19367
  "unknown"
19111
19368
  ]);
19369
+ // ../plugin/src/shared/harness-provider-map.ts
19370
+ var CANONICAL_TO_PI_PROVIDER = {
19371
+ openai: "openai-codex",
19372
+ google: "google-antigravity"
19373
+ };
19374
+ var PI_TO_CANONICAL_PROVIDER = {
19375
+ "openai-codex": "openai",
19376
+ "google-antigravity": "google"
19377
+ };
19378
+ var CANONICAL_TO_OMP_PROVIDER = {
19379
+ openai: "openai-codex",
19380
+ google: "google-antigravity"
19381
+ };
19382
+ var OMP_TO_CANONICAL_PROVIDER = {
19383
+ "openai-codex": "openai",
19384
+ "google-antigravity": "google"
19385
+ };
19386
+ function remapProviderPrefix(ref, map) {
19387
+ if (typeof ref !== "string")
19388
+ return ref;
19389
+ const slash = ref.indexOf("/");
19390
+ if (slash <= 0)
19391
+ return ref;
19392
+ const provider = ref.slice(0, slash);
19393
+ if (!Object.hasOwn(map, provider))
19394
+ return ref;
19395
+ return `${map[provider]}${ref.slice(slash)}`;
19396
+ }
19397
+ function piModelRefToCanonical(ref) {
19398
+ return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
19399
+ }
19400
+ function resolveModelRefForPi(ref) {
19401
+ return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
19402
+ }
19403
+ function ompModelRefToCanonical(ref) {
19404
+ return remapProviderPrefix(ref, OMP_TO_CANONICAL_PROVIDER);
19405
+ }
19406
+ function resolveModelRefForOmp(ref) {
19407
+ return remapProviderPrefix(ompModelRefToCanonical(ref), CANONICAL_TO_OMP_PROVIDER);
19408
+ }
19409
+
19112
19410
  // ../plugin/src/hooks/magic-context/todo-view.ts
19113
19411
  import { createHash as createHash7 } from "node:crypto";
19114
19412
  var TODO_STATUS_PENDING = "pending";
@@ -19217,8 +19515,8 @@ function isTodoItem(value) {
19217
19515
  }
19218
19516
 
19219
19517
  // ../plugin/src/shared/prompt-surface-runtime.ts
19220
- import { existsSync as existsSync7, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
19221
- import { dirname as dirname3, isAbsolute as isAbsolute2, resolve } from "node:path";
19518
+ import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
19519
+ import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
19222
19520
 
19223
19521
  // ../plugin/src/tools/light-descriptions.ts
19224
19522
  var CTX_REDUCE_LIGHT_DESCRIPTION = `For ctx_reduce users, mark spent §N§ outputs discardable; release is QUEUED, not immediate, so content stays visible until space is needed. Newest tags stay protected until they age out. Released content becomes a placeholder; recover it only by rerunning the source or recovery tool, so mark only genuinely finished material. Mark analyzed, redundant, persisted, or merely confirmatory outputs; keep user messages, unresolved errors, unextracted evidence, and exact wording. NEVER blanket-mark a large range: review every tag first.`;
@@ -19228,7 +19526,7 @@ var CTX_MEMORY_LIGHT_DESCRIPTION = `For ctx_memory users, write one standalone d
19228
19526
  var CTX_SEARCH_LIGHT_DESCRIPTION = `For ctx_search users, retrieve only hidden recall: memories not already in <project-memory>, compacted messages outside the live tail, commits, and notes. Omit sources for broad search; select memory, message, git_commit, or note to target a source, or pass memory IDs to bypass text search. Message hits continue through ctx_expand.`;
19229
19527
 
19230
19528
  // ../plugin/src/shared/jsonc-parser.ts
19231
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
19529
+ import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
19232
19530
  function stripJsonComments(content) {
19233
19531
  let result = "";
19234
19532
  let inString = false;
@@ -19283,13 +19581,43 @@ function stripJsonComments(content) {
19283
19581
  }
19284
19582
  return result;
19285
19583
  }
19584
+ var PROTOTYPE_POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
19585
+ function isPrototypePollutionKey(key) {
19586
+ return PROTOTYPE_POLLUTION_KEYS.has(key);
19587
+ }
19588
+ function sanitizeParsedJson(value, options = {}, path3 = []) {
19589
+ if (Array.isArray(value)) {
19590
+ return value.map((entry, index) => sanitizeParsedJson(entry, options, [...path3, index]));
19591
+ }
19592
+ if (value === null || typeof value !== "object")
19593
+ return value;
19594
+ const source = value;
19595
+ const sourcePrototype = Object.getPrototypeOf(source);
19596
+ if (sourcePrototype !== null && sourcePrototype !== Object.prototype) {
19597
+ options.onRejectedKey?.([...path3, "__proto__"]);
19598
+ }
19599
+ const sanitized = {};
19600
+ for (const key of Object.keys(source)) {
19601
+ if (isPrototypePollutionKey(key)) {
19602
+ options.onRejectedKey?.([...path3, key]);
19603
+ continue;
19604
+ }
19605
+ Object.defineProperty(sanitized, key, {
19606
+ value: sanitizeParsedJson(source[key], options, [...path3, key]),
19607
+ enumerable: true,
19608
+ configurable: true,
19609
+ writable: true
19610
+ });
19611
+ }
19612
+ return sanitized;
19613
+ }
19286
19614
  function detectConfigFile(basePath) {
19287
19615
  const jsoncPath = `${basePath}.jsonc`;
19288
19616
  const jsonPath = `${basePath}.json`;
19289
- if (existsSync6(jsoncPath)) {
19617
+ if (existsSync7(jsoncPath)) {
19290
19618
  return { format: "jsonc", path: jsoncPath };
19291
19619
  }
19292
- if (existsSync6(jsonPath)) {
19620
+ if (existsSync7(jsonPath)) {
19293
19621
  return { format: "json", path: jsonPath };
19294
19622
  }
19295
19623
  return { format: "none", path: jsoncPath };
@@ -19300,7 +19628,9 @@ function isValidPromptSurfaceModelKey(key) {
19300
19628
  if (key.length === 0 || key.trim() !== key)
19301
19629
  return false;
19302
19630
  const slash = key.indexOf("/");
19303
- if (slash <= 0 || slash === key.length - 1)
19631
+ if (slash < 0)
19632
+ return !key.includes("*");
19633
+ if (slash === 0 || slash === key.length - 1)
19304
19634
  return false;
19305
19635
  const provider = key.slice(0, slash);
19306
19636
  const modelID = key.slice(slash + 1);
@@ -19351,7 +19681,7 @@ function resolveModelConfigValue(values, modelKey) {
19351
19681
  function resolvePromptSurface(config, modelKey) {
19352
19682
  const fallback = config?.default ?? "full";
19353
19683
  const match = resolveModelConfigValue(config?.models, modelKey);
19354
- if (match && match.source !== "bare") {
19684
+ if (match) {
19355
19685
  return { preset: match.value, source: match.source };
19356
19686
  }
19357
19687
  return { preset: fallback, source: "default" };
@@ -19384,17 +19714,17 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
19384
19714
  var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
19385
19715
  function resolveUserConfigDirectory(options) {
19386
19716
  if (options.userConfigDirectory)
19387
- return resolve(options.userConfigDirectory);
19717
+ return resolve2(options.userConfigDirectory);
19388
19718
  const sharedBase = cortexKitUserConfigBasePath();
19389
19719
  const shared = detectConfigFile(sharedBase);
19390
19720
  if (shared.format !== "none")
19391
- return dirname3(shared.path);
19721
+ return dirname4(shared.path);
19392
19722
  if (options.harness) {
19393
- const legacy = resolveLegacyConfigSourcesForHarness(options.directory ?? process.cwd(), options.harness).user.find((source) => existsSync7(source.path));
19723
+ const legacy = resolveLegacyConfigSourcesForHarness(options.directory ?? process.cwd(), options.harness).user.find((source) => existsSync8(source.path));
19394
19724
  if (legacy)
19395
- return dirname3(legacy.path);
19725
+ return dirname4(legacy.path);
19396
19726
  }
19397
- return dirname3(sharedBase);
19727
+ return dirname4(sharedBase);
19398
19728
  }
19399
19729
  function markerCount(content) {
19400
19730
  return content.match(GUIDANCE_MARKER_LINE)?.length ?? 0;
@@ -19411,14 +19741,14 @@ function createPromptSurfaceRuntime(options) {
19411
19741
  const readGuidanceOverride = (configuredPath) => {
19412
19742
  if (!configuredPath)
19413
19743
  return;
19414
- const path3 = isAbsolute2(configuredPath) ? configuredPath : resolve(userConfigDirectory, configuredPath);
19744
+ const path3 = isAbsolute2(configuredPath) ? configuredPath : resolve2(userConfigDirectory, configuredPath);
19415
19745
  let content;
19416
19746
  try {
19417
19747
  if (!statSync5(path3).isFile()) {
19418
19748
  warnOnce(`guidance-not-file:${path3}`, `prompt_surface.guidance_override_path (${path3}) is not a file; using built-in guidance.`);
19419
19749
  return;
19420
19750
  }
19421
- content = readFileSync6(path3, "utf8");
19751
+ content = readFileSync7(path3, "utf8");
19422
19752
  } catch (error) {
19423
19753
  const reason = error instanceof Error ? error.message : String(error);
19424
19754
  warnOnce(`guidance-unreadable:${path3}:${reason}`, `prompt_surface.guidance_override_path (${path3}) could not be read (${reason}); using built-in guidance.`);
@@ -19835,7 +20165,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
19835
20165
  }
19836
20166
 
19837
20167
  // src/config/index.ts
19838
- import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
20168
+ import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
19839
20169
 
19840
20170
  // ../plugin/src/config/migrate-dreamer-v2.ts
19841
20171
  var OLD_VERIFY_TASK = "verify";
@@ -20146,7 +20476,7 @@ function migrateLegacyExperimental(rawConfig, warnings) {
20146
20476
  }
20147
20477
 
20148
20478
  // ../plugin/src/config/schema/magic-context.ts
20149
- import { homedir as homedir3 } from "node:os";
20479
+ import { homedir as homedir4 } from "node:os";
20150
20480
 
20151
20481
  // ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
20152
20482
  var exports_external = {};
@@ -34694,14 +35024,14 @@ var PiConfigSchema = exports_external.object({
34694
35024
  }).optional();
34695
35025
  var PromptSurfacePresetSchema = exports_external.enum(["full", "light"]);
34696
35026
  var PromptSurfaceModelKeySchema = exports_external.string().refine(isValidPromptSurfaceModelKey, {
34697
- message: "Use a non-empty provider/model key or the literal provider/* wildcard; model IDs may contain additional slashes and matching is case-sensitive."
35027
+ message: "Use a non-empty bare model key, provider/model key, or the literal provider/* wildcard; model IDs may contain additional slashes and matching is case-sensitive."
34698
35028
  });
34699
35029
  var PromptSurfaceToolKeySchema = exports_external.string().refine((value) => value.trim().length > 0, {
34700
35030
  message: "tool description keys must not be empty or whitespace-only"
34701
35031
  });
34702
35032
  var PromptSurfaceConfigSchema = exports_external.object({
34703
35033
  default: PromptSurfacePresetSchema.default("full").describe('Fallback prompt-surface preset ("full" or "light").'),
34704
- models: exports_external.record(PromptSurfaceModelKeySchema, PromptSurfacePresetSchema).optional().describe("Literal per-model routing. Keys are provider/model or provider/*; matching is case-sensitive and preserves additional slashes in model IDs."),
35034
+ models: exports_external.record(PromptSurfaceModelKeySchema, PromptSurfacePresetSchema).optional().describe("Literal per-model routing. Keys are bare model IDs, provider/model, or provider/*; matching is case-sensitive and preserves additional slashes in model IDs."),
34705
35035
  guidance_override_path: exports_external.string().refine((value) => value.trim().length > 0, {
34706
35036
  message: "guidance_override_path must not be empty or whitespace-only"
34707
35037
  }).optional().describe("USER-LEVEL ONLY path to a complete primary guidance section. Relative paths resolve from the user config file."),
@@ -34785,9 +35115,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
34785
35115
  function expandConfigPath(value) {
34786
35116
  const trimmed = value.trim();
34787
35117
  if (trimmed === "~")
34788
- return homedir3();
35118
+ return homedir4();
34789
35119
  if (trimmed.startsWith("~/"))
34790
- return `${homedir3()}/${trimmed.slice(2)}`;
35120
+ return `${homedir4()}/${trimmed.slice(2)}`;
34791
35121
  return trimmed;
34792
35122
  }
34793
35123
  var BaseEmbeddingConfigSchema = exports_external.object({
@@ -34894,7 +35224,7 @@ var MagicContextConfigSchema = exports_external.object({
34894
35224
  retina_handoff: exports_external.boolean().default(false).describe("When true, dreamer skips smart notes whose surface conditions compiled to retina provider configs at authoring time. Default false keeps both paths active until the retina consumer is deployed.")
34895
35225
  }).default({ retina_handoff: false }).describe("Smart-note ownership transition controls."),
34896
35226
  cache_ttl: exports_external.union([exports_external.string(), exports_external.object({ default: exports_external.string() }).catchall(exports_external.string())]).default("5m").describe('Cache TTL: string (e.g. "5m", "1h", "30s") or per-model object ({ default: "5m", "model-id": "10m" }). Set to "never" for lanes kept warm by an external keepwarm proxy — disables the idle-TTL heuristic so MC never initiates a rebuild based on elapsed time.'),
34897
- prompt_surface: PromptSurfaceConfigSchema.default({ default: "full" }).describe("Prompt-surface presets: default is full; models use the literal provider/model or provider/* routing grammar. Guidance and tool-description overrides are user-level only. On OpenCode and Pi, per-model routing applies to the guidance block only: tool descriptions are registered once per process, so they follow the default preset (a v1 plugin-surface limitation; per-model tool descriptions are planned for the OpenCode v2 plugin API once the SDK stabilizes)."),
35227
+ prompt_surface: PromptSurfaceConfigSchema.default({ default: "full" }).describe("Prompt-surface presets: default is full; models use bare model IDs, provider/model, or provider/* routing keys. Guidance and tool-description overrides are user-level only. On OpenCode and Pi, per-model routing applies to the guidance block only: tool descriptions are registered once per process, so they follow the default preset (a v1 plugin-surface limitation; per-model tool descriptions are planned for the OpenCode v2 plugin API once the SDK stabilizes)."),
34898
35228
  output_reserve: exports_external.union([
34899
35229
  exports_external.number().min(0),
34900
35230
  exports_external.object({ default: exports_external.number().min(0) }).catchall(exports_external.number().min(0))
@@ -35334,18 +35664,18 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
35334
35664
  }
35335
35665
 
35336
35666
  // ../plugin/src/config/variable.ts
35337
- import { existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
35338
- import { homedir as homedir4 } from "node:os";
35339
- import { dirname as dirname4, isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
35667
+ import { existsSync as existsSync9, readFileSync as readFileSync8 } from "node:fs";
35668
+ import { homedir as homedir5 } from "node:os";
35669
+ import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve3 } from "node:path";
35340
35670
  var ENV_PATTERN = /\{env:([^}]+)\}/g;
35341
35671
  var FILE_PATTERN = /\{file:([^}]+)\}/g;
35342
35672
  function sensitiveFilePathReason(resolvedPath) {
35343
- const home = homedir4();
35673
+ const home = homedir5();
35344
35674
  const sensitiveDirs = [
35345
- { dir: resolve2(home, ".ssh"), label: "SSH keys" },
35346
- { dir: resolve2(home, ".aws"), label: "AWS credentials" },
35347
- { dir: resolve2(home, ".gnupg"), label: "GnuPG keyring" },
35348
- { dir: resolve2(home, ".config", "gh"), label: "GitHub CLI auth" }
35675
+ { dir: resolve3(home, ".ssh"), label: "SSH keys" },
35676
+ { dir: resolve3(home, ".aws"), label: "AWS credentials" },
35677
+ { dir: resolve3(home, ".gnupg"), label: "GnuPG keyring" },
35678
+ { dir: resolve3(home, ".config", "gh"), label: "GitHub CLI auth" }
35349
35679
  ];
35350
35680
  for (const { dir, label } of sensitiveDirs) {
35351
35681
  if (resolvedPath === dir || resolvedPath.startsWith(`${dir}/`)) {
@@ -35385,7 +35715,7 @@ function substituteConfigVariables(input) {
35385
35715
  if (fileMatches.length === 0) {
35386
35716
  return { text, warnings };
35387
35717
  }
35388
- const configDir = input.configPath ? dirname4(input.configPath) : process.cwd();
35718
+ const configDir = input.configPath ? dirname5(input.configPath) : process.cwd();
35389
35719
  let output = "";
35390
35720
  let cursor = 0;
35391
35721
  for (const match of fileMatches) {
@@ -35403,21 +35733,21 @@ function substituteConfigVariables(input) {
35403
35733
  }
35404
35734
  let filePath = rawPath.trim();
35405
35735
  if (filePath.startsWith("~/")) {
35406
- filePath = resolve2(homedir4(), filePath.slice(2));
35736
+ filePath = resolve3(homedir5(), filePath.slice(2));
35407
35737
  } else if (!isAbsolute3(filePath)) {
35408
- filePath = resolve2(configDir, filePath);
35738
+ filePath = resolve3(configDir, filePath);
35409
35739
  }
35410
35740
  const sensitiveReason = sensitiveFilePathReason(filePath);
35411
35741
  if (sensitiveReason) {
35412
35742
  warnings.push(`${token} resolves to a sensitive path (${sensitiveReason}: ${filePath}); ` + "inlining its contents into config — make sure this is intentional.");
35413
35743
  }
35414
- if (!existsSync8(filePath)) {
35744
+ if (!existsSync9(filePath)) {
35415
35745
  warnings.push(`File not found for ${token} (resolved to ${filePath}); using empty string`);
35416
35746
  continue;
35417
35747
  }
35418
35748
  let contents;
35419
35749
  try {
35420
- contents = readFileSync7(filePath, "utf-8").trim();
35750
+ contents = readFileSync8(filePath, "utf-8").trim();
35421
35751
  } catch (error51) {
35422
35752
  const message = error51 instanceof Error ? error51.message : String(error51);
35423
35753
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -35430,51 +35760,8 @@ function substituteConfigVariables(input) {
35430
35760
  }
35431
35761
 
35432
35762
  // ../plugin/src/shared/models-dev-cache.ts
35433
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync8, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
35434
- import { join as join5 } from "node:path";
35435
-
35436
- // ../plugin/src/shared/harness-provider-map.ts
35437
- var CANONICAL_TO_PI_PROVIDER = {
35438
- openai: "openai-codex",
35439
- google: "google-antigravity"
35440
- };
35441
- var PI_TO_CANONICAL_PROVIDER = {
35442
- "openai-codex": "openai",
35443
- "google-antigravity": "google"
35444
- };
35445
- var CANONICAL_TO_OMP_PROVIDER = {
35446
- openai: "openai-codex",
35447
- google: "google-antigravity"
35448
- };
35449
- var OMP_TO_CANONICAL_PROVIDER = {
35450
- "openai-codex": "openai",
35451
- "google-antigravity": "google"
35452
- };
35453
- function remapProviderPrefix(ref, map2) {
35454
- if (typeof ref !== "string")
35455
- return ref;
35456
- const slash = ref.indexOf("/");
35457
- if (slash <= 0)
35458
- return ref;
35459
- const provider = ref.slice(0, slash);
35460
- if (!Object.hasOwn(map2, provider))
35461
- return ref;
35462
- return `${map2[provider]}${ref.slice(slash)}`;
35463
- }
35464
- function piModelRefToCanonical(ref) {
35465
- return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
35466
- }
35467
- function resolveModelRefForPi(ref) {
35468
- return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
35469
- }
35470
- function ompModelRefToCanonical(ref) {
35471
- return remapProviderPrefix(ref, OMP_TO_CANONICAL_PROVIDER);
35472
- }
35473
- function resolveModelRefForOmp(ref) {
35474
- return remapProviderPrefix(ompModelRefToCanonical(ref), CANONICAL_TO_OMP_PROVIDER);
35475
- }
35476
-
35477
- // ../plugin/src/shared/models-dev-cache.ts
35763
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync9, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
35764
+ import { join as join6 } from "node:path";
35478
35765
  var MIN_SANE_LIMIT = 20000;
35479
35766
  var MAX_SANE_LIMIT = 3000000;
35480
35767
  function isSaneLimit(limit) {
@@ -35488,14 +35775,14 @@ var reserveClampLogSeen = new Set;
35488
35775
  var apiCache = null;
35489
35776
  var persistSeedLoaded = false;
35490
35777
  function persistFilePath() {
35491
- return join5(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
35778
+ return join6(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
35492
35779
  }
35493
35780
  function loadPersistedApiCacheOnce() {
35494
35781
  if (persistSeedLoaded || apiCache !== null)
35495
35782
  return;
35496
35783
  persistSeedLoaded = true;
35497
35784
  try {
35498
- const raw = readFileSync8(persistFilePath(), "utf-8");
35785
+ const raw = readFileSync9(persistFilePath(), "utf-8");
35499
35786
  const obj = JSON.parse(raw);
35500
35787
  const map2 = new Map;
35501
35788
  for (const [key, persisted] of Object.entries(obj)) {
@@ -35637,25 +35924,28 @@ function getUserConfigPaths() {
35637
35924
  return [`${basePath}.jsonc`, `${basePath}.json`];
35638
35925
  }
35639
35926
  function resolveFirstExisting(paths) {
35640
- return paths.find((path3) => existsSync9(path3));
35927
+ return paths.find((path3) => existsSync10(path3));
35641
35928
  }
35642
35929
  function resolvePiLegacyFallback(sources) {
35643
- return sources.find((source) => existsSync9(source.path)) ?? null;
35930
+ return sources.find((source) => existsSync10(source.path)) ?? null;
35644
35931
  }
35645
35932
  function loadConfigFile(path3, scope) {
35646
35933
  try {
35647
- const rawText = readFileSync9(path3, "utf-8");
35934
+ const rawText = readFileSync10(path3, "utf-8");
35648
35935
  const substituted = substituteConfigVariables({
35649
35936
  text: rawText,
35650
35937
  configPath: path3,
35651
35938
  isProjectConfig: scope === "project"
35652
35939
  });
35940
+ const rejectedKeyPaths = [];
35941
+ const config2 = sanitizeParsedJson(import_comment_json.parse(substituted.text), { onRejectedKey: (keyPath) => rejectedKeyPaths.push(keyPath.join(".")) });
35942
+ const unsafeKeyWarnings = rejectedKeyPaths.map((keyPath) => `Ignored unsafe config key "${keyPath}" (security: prototype-pollution keys are not allowed).`);
35653
35943
  return {
35654
35944
  path: path3,
35655
35945
  scope,
35656
- config: import_comment_json.parse(substituted.text),
35657
- warnings: substituted.warnings.map((warning) => `${path3}: ${warning}`),
35658
- loadOutcome: substituted.warnings.length > 0 ? "substitution-failure" : "ok"
35946
+ config: config2,
35947
+ warnings: [...substituted.warnings, ...unsafeKeyWarnings].map((warning) => `${path3}: ${warning}`),
35948
+ loadOutcome: rejectedKeyPaths.length > 0 ? "schema-recovery" : substituted.warnings.length > 0 ? "substitution-failure" : "ok"
35659
35949
  };
35660
35950
  } catch (error51) {
35661
35951
  const message = error51 instanceof Error ? error51.message : String(error51);
@@ -35693,11 +35983,28 @@ function redactConfigValue(value) {
35693
35983
  function isPlainObject4(value) {
35694
35984
  return typeof value === "object" && value !== null && !Array.isArray(value);
35695
35985
  }
35986
+ function defineOwnConfigValue(target, key, value) {
35987
+ Object.defineProperty(target, key, {
35988
+ value,
35989
+ enumerable: true,
35990
+ configurable: true,
35991
+ writable: true
35992
+ });
35993
+ }
35696
35994
  function mergeRawConfigs(base, override) {
35697
- const merged = { ...base };
35698
- for (const [key, overrideValue] of Object.entries(override)) {
35699
- const baseValue = merged[key];
35700
- merged[key] = isPlainObject4(baseValue) && isPlainObject4(overrideValue) ? mergeRawConfigs(baseValue, overrideValue) : overrideValue;
35995
+ const merged = {};
35996
+ for (const key of Object.keys(base)) {
35997
+ if (isPrototypePollutionKey(key))
35998
+ continue;
35999
+ defineOwnConfigValue(merged, key, base[key]);
36000
+ }
36001
+ for (const key of Object.keys(override)) {
36002
+ if (isPrototypePollutionKey(key))
36003
+ continue;
36004
+ const overrideValue = override[key];
36005
+ const baseValue = Object.hasOwn(base, key) ? base[key] : undefined;
36006
+ const mergedValue = isPlainObject4(baseValue) && isPlainObject4(overrideValue) ? mergeRawConfigs(baseValue, overrideValue) : overrideValue;
36007
+ defineOwnConfigValue(merged, key, mergedValue);
35701
36008
  }
35702
36009
  return merged;
35703
36010
  }
@@ -35777,7 +36084,7 @@ function loadPiConfig(opts = {}) {
35777
36084
  if (loaded)
35778
36085
  loadedFiles.push(loaded);
35779
36086
  }
35780
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync9(source.path));
36087
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync10(source.path));
35781
36088
  const userPath = resolveFirstExisting(getUserConfigPaths());
35782
36089
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
35783
36090
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -35786,7 +36093,7 @@ function loadPiConfig(opts = {}) {
35786
36093
  if (loaded)
35787
36094
  loadedFiles.push(loaded);
35788
36095
  }
35789
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync9(source.path));
36096
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync10(source.path));
35790
36097
  if (userLegacyFallback) {
35791
36098
  warnings.push(`[user config] reading legacy config from ${userLegacyFallback.path} until migration completes; run \`npx @cortexkit/magic-context doctor\` to consolidate into the shared CortexKit location.`);
35792
36099
  } else if (legacyUserUnmigrated) {
@@ -35897,7 +36204,7 @@ function loadPiConfigDetailed(opts = {}) {
35897
36204
  if (loaded)
35898
36205
  loadedFiles.push(loaded);
35899
36206
  }
35900
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync9(source.path));
36207
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync10(source.path));
35901
36208
  const userPath = resolveFirstExisting(getUserConfigPaths());
35902
36209
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
35903
36210
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -35906,7 +36213,7 @@ function loadPiConfigDetailed(opts = {}) {
35906
36213
  if (loaded)
35907
36214
  loadedFiles.push(loaded);
35908
36215
  }
35909
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync9(source.path));
36216
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync10(source.path));
35910
36217
  if (userLegacyFallback) {
35911
36218
  warnings.push(`[user config] reading legacy config from ${userLegacyFallback.path} until migration completes; run \`npx @cortexkit/magic-context doctor\` to consolidate into the shared CortexKit location.`);
35912
36219
  } else if (legacyUserUnmigrated) {
@@ -37046,7 +37353,7 @@ class SubcSocket {
37046
37353
  return this.sock.localPort ?? null;
37047
37354
  }
37048
37355
  static connect(host, port, deadlineMs) {
37049
- return new Promise((resolve3, reject) => {
37356
+ return new Promise((resolve4, reject) => {
37050
37357
  const sock = net.connect({ host, port });
37051
37358
  sock.setNoDelay(true);
37052
37359
  const timer = setTimeout(() => {
@@ -37055,7 +37362,7 @@ class SubcSocket {
37055
37362
  }, Math.max(0, deadlineMs - Date.now()));
37056
37363
  sock.once("connect", () => {
37057
37364
  clearTimeout(timer);
37058
- resolve3(new SubcSocket(sock));
37365
+ resolve4(new SubcSocket(sock));
37059
37366
  });
37060
37367
  sock.once("error", (err) => {
37061
37368
  clearTimeout(timer);
@@ -37087,7 +37394,7 @@ class SubcSocket {
37087
37394
  }
37088
37395
  if (n === 0)
37089
37396
  return Promise.resolve(new Uint8Array(0));
37090
- return new Promise((resolve3, reject) => {
37397
+ return new Promise((resolve4, reject) => {
37091
37398
  let timer = null;
37092
37399
  if (Number.isFinite(deadlineMs)) {
37093
37400
  const remaining = deadlineMs - Date.now();
@@ -37100,7 +37407,7 @@ class SubcSocket {
37100
37407
  reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
37101
37408
  }, remaining);
37102
37409
  }
37103
- this.waiter = { need: n, resolve: resolve3, reject, timer };
37410
+ this.waiter = { need: n, resolve: resolve4, reject, timer };
37104
37411
  this.tryServe();
37105
37412
  });
37106
37413
  }
@@ -37124,7 +37431,7 @@ class SubcSocket {
37124
37431
  let queued = false;
37125
37432
  let settled = false;
37126
37433
  let timer = null;
37127
- const completed = new Promise((resolve3, reject) => {
37434
+ const completed = new Promise((resolve4, reject) => {
37128
37435
  const settle = (run) => {
37129
37436
  if (settled)
37130
37437
  return;
@@ -37148,7 +37455,7 @@ class SubcSocket {
37148
37455
  if (err) {
37149
37456
  reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
37150
37457
  } else {
37151
- resolve3();
37458
+ resolve4();
37152
37459
  }
37153
37460
  });
37154
37461
  });
@@ -37364,14 +37671,14 @@ class SubcClient {
37364
37671
  const admission = opts.admissionClass ?? AdmissionClass.Normal;
37365
37672
  const corr = this.allocateCorr();
37366
37673
  const key = pendingKey(handle, corr);
37367
- const closed = new Promise((resolve3, reject) => {
37674
+ const closed = new Promise((resolve4, reject) => {
37368
37675
  if (this.closedErr) {
37369
37676
  reject(this.closedErr);
37370
37677
  return;
37371
37678
  }
37372
37679
  this.pending.set(key, {
37373
37680
  handle,
37374
- resolve: () => resolve3(),
37681
+ resolve: () => resolve4(),
37375
37682
  reject,
37376
37683
  onProgress: onEvent,
37377
37684
  timer: null,
@@ -37456,11 +37763,11 @@ class SubcClient {
37456
37763
  const waiters = [];
37457
37764
  for (const pending of this.pending.values()) {
37458
37765
  if (pending.handle === handle && !pending.subscription) {
37459
- waiters.push(new Promise((resolve3) => {
37766
+ waiters.push(new Promise((resolve4) => {
37460
37767
  const previous = pending.onSettle;
37461
37768
  pending.onSettle = () => {
37462
37769
  previous?.();
37463
- resolve3();
37770
+ resolve4();
37464
37771
  };
37465
37772
  }));
37466
37773
  }
@@ -37516,11 +37823,11 @@ class SubcClient {
37516
37823
  const channel = handle?.channel ?? 0;
37517
37824
  const epoch = handle?.epoch ?? 0;
37518
37825
  const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false, admission), channel, epoch, corr, body);
37519
- return new Promise((resolve3, reject) => {
37826
+ return new Promise((resolve4, reject) => {
37520
37827
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
37521
37828
  const pending = {
37522
37829
  handle,
37523
- resolve: resolve3,
37830
+ resolve: resolve4,
37524
37831
  reject,
37525
37832
  onProgress,
37526
37833
  timer: null,
@@ -37594,11 +37901,11 @@ class SubcClient {
37594
37901
  }
37595
37902
  return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error51);
37596
37903
  };
37597
- return new Promise((resolve3, reject) => {
37904
+ return new Promise((resolve4, reject) => {
37598
37905
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
37599
37906
  const pending = {
37600
37907
  handle,
37601
- resolve: resolve3,
37908
+ resolve: resolve4,
37602
37909
  reject,
37603
37910
  onProgress,
37604
37911
  timer: null,
@@ -37986,7 +38293,7 @@ function normalizeConnectOptions(opts) {
37986
38293
  identity: opts.identity,
37987
38294
  targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
37988
38295
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
37989
- sleep: opts.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms))),
38296
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms))),
37990
38297
  timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS
37991
38298
  };
37992
38299
  }
@@ -38043,8 +38350,8 @@ class AsyncPermitPool {
38043
38350
  this.available -= 1;
38044
38351
  return this.releaseOnce();
38045
38352
  }
38046
- await new Promise((resolve3) => {
38047
- this.waiters.push(resolve3);
38353
+ await new Promise((resolve4) => {
38354
+ this.waiters.push(resolve4);
38048
38355
  });
38049
38356
  return this.releaseOnce();
38050
38357
  }
@@ -38100,8 +38407,8 @@ class SubcProvider {
38100
38407
  this.currentConn = currentConn;
38101
38408
  this.opts = opts;
38102
38409
  this.storage = storage;
38103
- this.closed = new Promise((resolve3) => {
38104
- this.resolveClosed = resolve3;
38410
+ this.closed = new Promise((resolve4) => {
38411
+ this.resolveClosed = resolve4;
38105
38412
  });
38106
38413
  this.readLoop(sock, this.generation);
38107
38414
  this.enqueueConnectionState({ state: "connected", epoch: this.connectionEpoch });
@@ -38121,13 +38428,13 @@ class SubcProvider {
38121
38428
  const key = routeKey(handle, corr);
38122
38429
  const timeoutMs = opts.timeoutMs ?? WRITE_TIMEOUT_MS;
38123
38430
  const frame = buildFrame(FrameType.Request, buildFlags(false, opts.priority ?? Priority.Interactive, false, opts.admissionClass ?? AdmissionClass.Normal), handle.channel, handle.epoch, corr, body);
38124
- return await new Promise((resolve3, reject) => {
38431
+ return await new Promise((resolve4, reject) => {
38125
38432
  const timer = setTimeout(() => {
38126
38433
  if (this.pending.delete(key))
38127
38434
  reject(new SubcProviderError("reverse request timed out", "request_timeout"));
38128
38435
  }, timeoutMs);
38129
38436
  this.pending.set(key, {
38130
- resolve: (response) => resolve3(response.body),
38437
+ resolve: (response) => resolve4(response.body),
38131
38438
  reject,
38132
38439
  timer
38133
38440
  });
@@ -38599,7 +38906,7 @@ function normalizeProviderConnectOptions(opts) {
38599
38906
  onBound: opts.onBound,
38600
38907
  onRouteGone: opts.onRouteGone,
38601
38908
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
38602
- sleep: opts.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms))),
38909
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms))),
38603
38910
  restoredDebounceMs: opts.restoredDebounceMs ?? DEFAULT_RESTORED_DEBOUNCE_MS,
38604
38911
  onConnectionState: opts.onConnectionState,
38605
38912
  launchNonce: opts.launchNonce
@@ -38644,7 +38951,7 @@ function errorCode2(err) {
38644
38951
  return;
38645
38952
  }
38646
38953
  async function pauseBeforeStateRetry() {
38647
- await new Promise((resolve3) => setTimeout(resolve3, 0));
38954
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
38648
38955
  }
38649
38956
  function controlFlags() {
38650
38957
  return buildFlags(false, Priority.Passive, false);
@@ -38882,7 +39189,7 @@ function classifyError(value) {
38882
39189
  });
38883
39190
  }
38884
39191
  function wait(ms) {
38885
- return new Promise((resolve3) => setTimeout(resolve3, ms));
39192
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
38886
39193
  }
38887
39194
  function sha256(value) {
38888
39195
  return createHash9("sha256").update(value).digest("hex");
@@ -39361,8 +39668,8 @@ function getEmbeddingProviderIdentity(config2) {
39361
39668
  // ../plugin/src/features/magic-context/memory/embedding-local.ts
39362
39669
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync4 } from "node:fs";
39363
39670
  import { open, stat, unlink, writeFile } from "node:fs/promises";
39364
- import { dirname as dirname5, join as join6 } from "node:path";
39365
- import { pathToFileURL } from "node:url";
39671
+ import { dirname as dirname6, join as join7 } from "node:path";
39672
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
39366
39673
  var LOCK_POLL_MS = 150;
39367
39674
  var STALE_LOCK_MS = 3 * 60000;
39368
39675
  var MAX_LOCK_WAIT_MS = 5 * 60000;
@@ -39401,7 +39708,7 @@ async function acquireModelLoadLock(lockPath) {
39401
39708
  if (Date.now() - waitStart > MAX_LOCK_WAIT_MS) {
39402
39709
  throw new Error(`[magic-context] embedding-load lock wait exceeded ${MAX_LOCK_WAIT_MS}ms; another process is still loading the model. Skipping this init attempt to avoid an unsynchronized native load.`);
39403
39710
  }
39404
- await new Promise((resolve3) => setTimeout(resolve3, LOCK_POLL_MS));
39711
+ await new Promise((resolve4) => setTimeout(resolve4, LOCK_POLL_MS));
39405
39712
  }
39406
39713
  }
39407
39714
  }
@@ -39425,8 +39732,8 @@ async function injectWasmOrtForElectron() {
39425
39732
  const { createRequire: createRequireFn } = await import("node:module");
39426
39733
  const requireFn = createRequireFn(import.meta.url);
39427
39734
  const mainEntry = requireFn.resolve("onnxruntime-web");
39428
- const distDir = dirname5(mainEntry);
39429
- const wasmPathsPrefix = `${pathToFileURL(distDir).href}/`;
39735
+ const distDir = dirname6(mainEntry);
39736
+ const wasmPathsPrefix = `${pathToFileURL2(distDir).href}/`;
39430
39737
  if (ortWeb.env?.wasm) {
39431
39738
  ortWeb.env.wasm.wasmPaths = wasmPathsPrefix;
39432
39739
  }
@@ -39562,7 +39869,7 @@ class LocalEmbeddingProvider {
39562
39869
  if (LogLevel && "ERROR" in LogLevel) {
39563
39870
  env.logLevel = LogLevel.ERROR;
39564
39871
  }
39565
- const modelCacheDir = join6(getMagicContextStorageDir(), "models");
39872
+ const modelCacheDir = join7(getMagicContextStorageDir(), "models");
39566
39873
  try {
39567
39874
  if (shouldEnforcePrivateStoragePermissions()) {
39568
39875
  mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
@@ -39579,7 +39886,7 @@ class LocalEmbeddingProvider {
39579
39886
  log("[magic-context] could not create model cache dir, using library default");
39580
39887
  }
39581
39888
  const createPipeline = transformersModule.pipeline;
39582
- const lockPath = join6(modelCacheDir, ".load.lock");
39889
+ const lockPath = join7(modelCacheDir, ".load.lock");
39583
39890
  const releaseLock = await acquireModelLoadLock(lockPath);
39584
39891
  const stopHeartbeat = startLockHeartbeat(lockPath);
39585
39892
  try {
@@ -39606,7 +39913,7 @@ class LocalEmbeddingProvider {
39606
39913
  }
39607
39914
  const delayMs = 300 * attempt + Math.floor(Math.random() * 200);
39608
39915
  log(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
39609
- await new Promise((resolve3) => setTimeout(resolve3, delayMs));
39916
+ await new Promise((resolve4) => setTimeout(resolve4, delayMs));
39610
39917
  }
39611
39918
  }
39612
39919
  if (this.pipeline) {
@@ -39639,8 +39946,8 @@ class LocalEmbeddingProvider {
39639
39946
  if (this.inFlight === 0) {
39640
39947
  return Promise.resolve();
39641
39948
  }
39642
- return new Promise((resolve3) => {
39643
- this.inFlightWaiters.push(resolve3);
39949
+ return new Promise((resolve4) => {
39950
+ this.inFlightWaiters.push(resolve4);
39644
39951
  });
39645
39952
  }
39646
39953
  finishInFlight() {
@@ -41338,7 +41645,7 @@ async function runShadowWorker() {
41338
41645
  }
41339
41646
  processed += item.ids.length;
41340
41647
  processedBytes += itemBytes;
41341
- await new Promise((resolve3) => setTimeout(resolve3, 0));
41648
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
41342
41649
  }
41343
41650
  }
41344
41651
  function registerProjectInObservationMode(db, projectIdentity, sourceDirectory, failedConfig, failureSummary) {
@@ -41699,7 +42006,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
41699
42006
  if (Date.now() - attemptStart >= EMBED_SLOW_FAILURE_NO_RETRY_MS)
41700
42007
  break;
41701
42008
  if (attempt < EMBED_SLICE_RETRY_ATTEMPTS - 1) {
41702
- await new Promise((resolve3) => setTimeout(resolve3, EMBED_SLICE_RETRY_BASE_MS * 2 ** attempt));
42009
+ await new Promise((resolve4) => setTimeout(resolve4, EMBED_SLICE_RETRY_BASE_MS * 2 ** attempt));
41703
42010
  }
41704
42011
  }
41705
42012
  embedded += persistedIds.size;
@@ -41784,7 +42091,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
41784
42091
  }
41785
42092
  embedded += n;
41786
42093
  options?.onProgress?.({ embedded: Math.min(embedded, total), total });
41787
- await new Promise((resolve3) => setTimeout(resolve3, 0));
42094
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
41788
42095
  }
41789
42096
  } finally {
41790
42097
  clearInterval(renewal);
@@ -48145,7 +48452,7 @@ function getMemoryVerifications(db, memoryIds) {
48145
48452
  }
48146
48453
  // ../plugin/src/features/magic-context/memory/verification-paths.ts
48147
48454
  import { execFile } from "node:child_process";
48148
- import { existsSync as existsSync10, realpathSync as realpathSync2, statSync as statSync7 } from "node:fs";
48455
+ import { existsSync as existsSync11, realpathSync as realpathSync3, statSync as statSync7 } from "node:fs";
48149
48456
  import path3 from "node:path";
48150
48457
  import { promisify } from "node:util";
48151
48458
  var execFileAsync = promisify(execFile);
@@ -48174,7 +48481,7 @@ function isWithin(root, candidate) {
48174
48481
  }
48175
48482
  function safeRealpath(value) {
48176
48483
  try {
48177
- return realpathSync2.native(value);
48484
+ return realpathSync3.native(value);
48178
48485
  } catch {
48179
48486
  return null;
48180
48487
  }
@@ -48252,7 +48559,7 @@ function verificationFileExists(baseRoot, filePath) {
48252
48559
  return false;
48253
48560
  const root = path3.resolve(baseRoot);
48254
48561
  const candidate = path3.resolve(root, filePath);
48255
- return isWithin(root, candidate) && existsSync10(candidate);
48562
+ return isWithin(root, candidate) && existsSync11(candidate);
48256
48563
  }
48257
48564
  async function normalizeVerificationFiles(args) {
48258
48565
  const cwd = path3.resolve(args.cwd);
@@ -48285,7 +48592,7 @@ async function normalizeVerificationFiles(args) {
48285
48592
  warnings.push(`Skipped verification path "${value}" because it is the repo/project root.`);
48286
48593
  continue;
48287
48594
  }
48288
- if (existsSync10(candidate)) {
48595
+ if (existsSync11(candidate)) {
48289
48596
  try {
48290
48597
  if (statSync7(candidate).isDirectory()) {
48291
48598
  warnings.push(`Skipped verification path "${value}" because it is a directory.`);
@@ -48316,7 +48623,7 @@ async function normalizeVerificationFiles(args) {
48316
48623
  }
48317
48624
  normalized.push(tracked);
48318
48625
  } else {
48319
- if (!existsSync10(candidate)) {
48626
+ if (!existsSync11(candidate)) {
48320
48627
  warnings.push(`Skipped verification path "${value}" because it does not exist.`);
48321
48628
  continue;
48322
48629
  }
@@ -48806,13 +49113,13 @@ function createCtxMemoryTool(deps) {
48806
49113
  }
48807
49114
 
48808
49115
  // ../plugin/src/features/magic-context/smart-notes/condition-compiler.ts
48809
- import { existsSync as existsSync11 } from "node:fs";
49116
+ import { existsSync as existsSync12 } from "node:fs";
48810
49117
  import { isAbsolute as isAbsolute5 } from "node:path";
48811
49118
 
48812
49119
  // ../retina-local-fs/src/path-fence.ts
48813
49120
  import { lstat, readlink, realpath } from "node:fs/promises";
48814
- import { homedir as homedir5 } from "node:os";
48815
- import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve3, sep } from "node:path";
49121
+ import { homedir as homedir6 } from "node:os";
49122
+ import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve4, sep } from "node:path";
48816
49123
 
48817
49124
  // ../retina-local-fs/src/errors.ts
48818
49125
  class ProviderError extends Error {
@@ -48826,20 +49133,26 @@ class ProviderError extends Error {
48826
49133
 
48827
49134
  // ../retina-local-fs/src/path-fence.ts
48828
49135
  async function resolveAndFenceProviderPath(configuredPath, options) {
48829
- const configuredHomePath = resolve3(options.homeDirectory ?? process.env.HOME ?? homedir5());
49136
+ const { home, dataDirectory } = await resolveFenceRoots(options);
49137
+ const expanded = configuredPath.startsWith("~/") ? join8(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
49138
+ const absolute = isAbsolute4(expanded) ? resolve4(expanded) : resolve4(options.cwd ?? process.cwd(), expanded);
49139
+ const canonical = await canonicalPath(absolute, options.allowMissing);
49140
+ if (isFencedPath(canonical, home, dataDirectory)) {
49141
+ throw new ProviderError("fenced_path", `Refusing fenced path: ${canonical}`);
49142
+ }
49143
+ return canonical;
49144
+ }
49145
+ async function resolveFenceRoots(options) {
49146
+ const configuredHomePath = resolve4(options.homeDirectory ?? process.env.HOME ?? homedir6());
48830
49147
  let home;
48831
49148
  try {
48832
49149
  home = await realpath(configuredHomePath);
48833
49150
  } catch (error51) {
48834
49151
  throw fsError(configuredHomePath, error51);
48835
49152
  }
48836
- const expanded = configuredPath.startsWith("~/") ? join7(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
48837
- const absolute = isAbsolute4(expanded) ? resolve3(expanded) : resolve3(options.cwd ?? process.cwd(), expanded);
48838
- const canonical = await canonicalPath(absolute, options.allowMissing);
48839
- if (isFencedPath(canonical, home)) {
48840
- throw new ProviderError("fenced_path", `Refusing fenced path: ${canonical}`);
48841
- }
48842
- return canonical;
49153
+ const configuredDataDirectory = resolve4(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join8(home, ".local", "share"));
49154
+ const dataDirectory = await canonicalPath(configuredDataDirectory, true);
49155
+ return { home, dataDirectory };
48843
49156
  }
48844
49157
  async function canonicalPath(path4, allowMissing) {
48845
49158
  try {
@@ -48855,22 +49168,22 @@ async function canonicalPath(path4, allowMissing) {
48855
49168
  const metadata = await lstat(candidate);
48856
49169
  if (metadata.isSymbolicLink()) {
48857
49170
  const target2 = await readlink(candidate);
48858
- const resolvedTarget = resolve3(dirname6(candidate), target2);
48859
- return canonicalPath(join7(resolvedTarget, ...suffix), true);
49171
+ const resolvedTarget = resolve4(dirname7(candidate), target2);
49172
+ return canonicalPath(join8(resolvedTarget, ...suffix), true);
48860
49173
  }
48861
49174
  } catch (candidateError) {
48862
49175
  if (!isMissingError(candidateError)) {
48863
49176
  throw fsError(path4, candidateError);
48864
49177
  }
48865
49178
  }
48866
- const parent = dirname6(candidate);
49179
+ const parent = dirname7(candidate);
48867
49180
  if (parent === candidate) {
48868
49181
  throw fsError(path4, error51);
48869
49182
  }
48870
49183
  suffix.unshift(basename3(candidate));
48871
49184
  candidate = parent;
48872
49185
  try {
48873
- return join7(await realpath(candidate), ...suffix);
49186
+ return join8(await realpath(candidate), ...suffix);
48874
49187
  } catch (parentError) {
48875
49188
  if (!isMissingError(parentError)) {
48876
49189
  throw fsError(path4, parentError);
@@ -48879,9 +49192,8 @@ async function canonicalPath(path4, allowMissing) {
48879
49192
  }
48880
49193
  }
48881
49194
  }
48882
- function isFencedPath(canonicalPath2, homeDirectory) {
48883
- const home = resolve3(homeDirectory);
48884
- const cortexkitRoot = join7(home, ".local", "share", "cortexkit");
49195
+ function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join8(resolve4(homeDirectory), ".local", "share")) {
49196
+ const cortexkitRoot = join8(resolve4(dataDirectory), "cortexkit");
48885
49197
  const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
48886
49198
  const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
48887
49199
  const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
@@ -48890,10 +49202,11 @@ function isFencedPath(canonicalPath2, homeDirectory) {
48890
49202
  const catalogDirectoryCarveIn = pathParts.includes("catalog");
48891
49203
  const moduleBinCarveIn = parts.length >= 2 && parts[1] === "bin";
48892
49204
  const catalogJsonCarveIn = name.endsWith(".json") && name.includes("catalog");
48893
- if (catalogDirectoryCarveIn || moduleBinCarveIn || catalogJsonCarveIn) {
49205
+ const rootWithoutCarveIns = insideCortexkit && (parts[0] === "run" || parts[0] === "magic-context");
49206
+ if (!rootWithoutCarveIns && (catalogDirectoryCarveIn || moduleBinCarveIn || catalogJsonCarveIn)) {
48894
49207
  return false;
48895
49208
  }
48896
- const inFencedRoot = insideCortexkit && ["plexus", "claustrum", "staging"].includes(parts[0] ?? "");
49209
+ const inFencedRoot = insideCortexkit && ["plexus", "claustrum", "staging", "run", "magic-context"].includes(parts[0] ?? "");
48897
49210
  const fencedBasename = name.includes("binding-key") || name.endsWith(".handle");
48898
49211
  const plexusStore = insideCortexkit && parts[0] === "plexus" && name.startsWith("store.db");
48899
49212
  return inFencedRoot || fencedBasename || plexusStore;
@@ -49043,6 +49356,9 @@ function invalid(message) {
49043
49356
  var RETINA_LOCAL_FS_PROVIDER = "local-fs";
49044
49357
  var VALUE = String.raw`(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)`;
49045
49358
  async function compileSurfaceCondition(surfaceCondition, options) {
49359
+ const plainReason = unsafeGrammarReason(surfaceCondition);
49360
+ if (plainReason)
49361
+ return { status: "plain", reason: plainReason };
49046
49362
  const parsed = parseCondition(surfaceCondition, options.projectPath);
49047
49363
  if (parsed === null)
49048
49364
  return { status: "plain" };
@@ -49053,7 +49369,7 @@ async function compileSurfaceCondition(surfaceCondition, options) {
49053
49369
  homeDirectory: options.homeDirectory,
49054
49370
  cwd: options.projectPath
49055
49371
  });
49056
- return { path: resolved, exists: existsSync11(resolved) };
49372
+ return { path: resolved, exists: existsSync12(resolved) };
49057
49373
  });
49058
49374
  let predicates;
49059
49375
  try {
@@ -49124,23 +49440,27 @@ function parseCondition(surfaceCondition, projectPath) {
49124
49440
  return predicates.every((predicate) => predicate !== null) ? predicates : null;
49125
49441
  }
49126
49442
  function parseAtomicCondition(text, projectPath) {
49127
- const fileContains = text.match(new RegExp(`^(?:when\\s+)?file\\s+(${VALUE})\\s+(no longer contains|contains)\\s+(.+)$`, "i"));
49443
+ const fileContains = text.match(new RegExp(`^(?:when\\s+)?file\\s+(${VALUE})\\s+(no longer contains|contains)\\s+(${VALUE})$`, "i"));
49128
49444
  if (fileContains) {
49445
+ const path4 = unquote(fileContains[1]);
49129
49446
  const needle = unquote(fileContains[3].trim());
49130
- if (needle === null)
49447
+ if (path4 === null || needle === null)
49131
49448
  return null;
49132
49449
  return {
49133
49450
  kind: "file_contains",
49134
- path: unquote(fileContains[1]) ?? fileContains[1],
49451
+ path: path4,
49135
49452
  needle,
49136
49453
  ...fileContains[2].toLowerCase() === "no longer contains" ? { absent: true } : {}
49137
49454
  };
49138
49455
  }
49139
49456
  const commit = text.match(new RegExp(`^(?:when\\s+)?(?:repo(?:sitory)?\\s+)?(${VALUE})\\s+has\\s+a\\s+commit\\s+(?:after|newer than)\\s+([0-9a-f]{7,64})$`, "i"));
49140
49457
  if (commit) {
49458
+ const repoPath = unquote(commit[1]);
49459
+ if (repoPath === null)
49460
+ return null;
49141
49461
  return {
49142
49462
  kind: "git_commit_after",
49143
- repo_path: unquote(commit[1]) ?? commit[1],
49463
+ repo_path: repoPath,
49144
49464
  sha: commit[2]
49145
49465
  };
49146
49466
  }
@@ -49160,16 +49480,22 @@ function parseAtomicCondition(text, projectPath) {
49160
49480
  }
49161
49481
  const mtime = text.match(new RegExp(`^(?:when\\s+)?(?:file\\s+)?(${VALUE})\\s+(changes|is rebuilt|mtime moves)$`, "i"));
49162
49482
  if (mtime) {
49483
+ const path4 = unquote(mtime[1]);
49484
+ if (path4 === null)
49485
+ return null;
49163
49486
  return {
49164
49487
  kind: "mtime_after",
49165
- path: unquote(mtime[1]) ?? mtime[1]
49488
+ path: path4
49166
49489
  };
49167
49490
  }
49168
49491
  const pathExists = text.match(new RegExp(`^(?:when\\s+)?(?:path\\s+)?(${VALUE})\\s+(exists|is gone)$`, "i"));
49169
49492
  if (pathExists) {
49493
+ const path4 = unquote(pathExists[1]);
49494
+ if (path4 === null)
49495
+ return null;
49170
49496
  return {
49171
49497
  kind: "path_exists",
49172
- path: unquote(pathExists[1]) ?? pathExists[1],
49498
+ path: path4,
49173
49499
  ...pathExists[2].toLowerCase() === "is gone" ? { gone: true } : {}
49174
49500
  };
49175
49501
  }
@@ -49224,12 +49550,42 @@ function splitOrClauses(text) {
49224
49550
  clauses.push(text.slice(start).trim());
49225
49551
  return clauses.filter(Boolean);
49226
49552
  }
49553
+ function unsafeGrammarReason(value) {
49554
+ let quote = null;
49555
+ let escaped = false;
49556
+ for (const character of value) {
49557
+ if (escaped) {
49558
+ escaped = false;
49559
+ continue;
49560
+ }
49561
+ if (quote && character === "\\") {
49562
+ escaped = true;
49563
+ continue;
49564
+ }
49565
+ if (character === '"' || character === "'") {
49566
+ quote = quote === character ? null : quote === null ? character : quote;
49567
+ }
49568
+ }
49569
+ if (quote !== null)
49570
+ return "unbalanced quote; leaving condition dreamer-evaluated";
49571
+ if (/\bcontains\s+no(?:\s|$)/i.test(value)) {
49572
+ return "ambiguous negation after contains; leaving condition dreamer-evaluated";
49573
+ }
49574
+ const temporalSuffix = new RegExp(`\\bcontains\\s+${VALUE}\\s+(?:since|until|after|before|when|while|for|as\\s+of)\\b`, "i");
49575
+ if (temporalSuffix.test(value)) {
49576
+ return "temporal suffix after contains; leaving condition dreamer-evaluated";
49577
+ }
49578
+ return null;
49579
+ }
49227
49580
  function unquote(value) {
49228
- if (value.length < 2)
49229
- return value;
49230
49581
  const quote = value[0];
49231
- if (quote !== '"' && quote !== "'" || value.at(-1) !== quote)
49582
+ const final = value.at(-1);
49583
+ const startsQuoted = quote === '"' || quote === "'";
49584
+ const endsQuoted = final === '"' || final === "'";
49585
+ if (!startsQuoted && !endsQuoted)
49232
49586
  return value;
49587
+ if (!startsQuoted || final !== quote || value.length < 2)
49588
+ return null;
49233
49589
  if (quote === '"') {
49234
49590
  try {
49235
49591
  const parsed = JSON.parse(value);
@@ -52008,8 +52364,8 @@ class BoundedSessionMap {
52008
52364
 
52009
52365
  // ../plugin/src/features/magic-context/compaction-marker.ts
52010
52366
  import { createHash as createHash16 } from "node:crypto";
52011
- import { existsSync as existsSync12 } from "node:fs";
52012
- import { join as join8 } from "node:path";
52367
+ import { existsSync as existsSync13 } from "node:fs";
52368
+ import { join as join9 } from "node:path";
52013
52369
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
52014
52370
  var ID_PREFIX_HEX_LENGTH = 12;
52015
52371
  var ID_SUFFIX_LENGTH = 14;
@@ -52035,7 +52391,7 @@ function generatePartId(timestampMs, counter = 0n, identity = "") {
52035
52391
  return generateId("prt", timestampMs, counter, identity);
52036
52392
  }
52037
52393
  function getOpenCodeDbPath2() {
52038
- return join8(getDataDir(), "opencode", "opencode.db");
52394
+ return join9(getDataDir(), "opencode", "opencode.db");
52039
52395
  }
52040
52396
  var cachedWriteDb = null;
52041
52397
  var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
@@ -52080,7 +52436,7 @@ function getWritableOpenCodeDb() {
52080
52436
  closeQuietly(cachedWriteDb.db);
52081
52437
  } catch {}
52082
52438
  }
52083
- if (!existsSync12(dbPath)) {
52439
+ if (!existsSync13(dbPath)) {
52084
52440
  throw new Error(`OpenCode database not found at ${dbPath} (is OpenCode installed?)`);
52085
52441
  }
52086
52442
  const db = new Database(dbPath);
@@ -52356,24 +52712,52 @@ function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEn
52356
52712
  // ../plugin/src/hooks/magic-context/compartment-render-epoch.ts
52357
52713
  var COMPARTMENT_RENDER_EPOCH = "cre2";
52358
52714
  var EPOCH_COMPONENT_PREFIX = "|compartment-render:";
52359
- function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH) {
52360
- if (compartmentRenderEpoch === null)
52361
- return upgradeState;
52362
- return `${upgradeState ?? ""}${EPOCH_COMPONENT_PREFIX}${compartmentRenderEpoch}`;
52715
+ var MURAL_COMPONENT_PREFIX = "|mural-enabled:";
52716
+ var BUDGET_COMPONENT_PREFIX = "|render-budgets:";
52717
+ function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH, muralEnabled = null, renderBudgetIdentity = null) {
52718
+ let encoded = upgradeState ?? "";
52719
+ if (compartmentRenderEpoch !== null) {
52720
+ encoded += `${EPOCH_COMPONENT_PREFIX}${compartmentRenderEpoch}`;
52721
+ }
52722
+ if (muralEnabled !== null) {
52723
+ encoded += `${MURAL_COMPONENT_PREFIX}${muralEnabled ? "1" : "0"}`;
52724
+ }
52725
+ if (renderBudgetIdentity !== null) {
52726
+ encoded += `${BUDGET_COMPONENT_PREFIX}${renderBudgetIdentity}`;
52727
+ }
52728
+ return encoded.length > 0 ? encoded : null;
52729
+ }
52730
+ function component(value, prefix) {
52731
+ const start = value.lastIndexOf(prefix);
52732
+ if (start < 0)
52733
+ return null;
52734
+ const valueStart = start + prefix.length;
52735
+ const end = value.indexOf("|", valueStart);
52736
+ const result = value.slice(valueStart, end < 0 ? value.length : end);
52737
+ return result.length > 0 ? result : null;
52363
52738
  }
52364
52739
  function decodeCachedM0UpgradeIdentity(value) {
52365
52740
  if (value === null) {
52366
- return { upgradeState: null, compartmentRenderEpoch: null };
52367
- }
52368
- const componentIndex = value.lastIndexOf(EPOCH_COMPONENT_PREFIX);
52369
- if (componentIndex < 0) {
52370
- return { upgradeState: value, compartmentRenderEpoch: null };
52741
+ return {
52742
+ upgradeState: null,
52743
+ compartmentRenderEpoch: null,
52744
+ muralEnabled: null,
52745
+ renderBudgetIdentity: null
52746
+ };
52371
52747
  }
52372
- const upgradeState = value.slice(0, componentIndex);
52373
- const compartmentRenderEpoch = value.slice(componentIndex + EPOCH_COMPONENT_PREFIX.length);
52748
+ const componentIndexes = [
52749
+ value.indexOf(EPOCH_COMPONENT_PREFIX),
52750
+ value.indexOf(MURAL_COMPONENT_PREFIX),
52751
+ value.indexOf(BUDGET_COMPONENT_PREFIX)
52752
+ ].filter((index) => index >= 0);
52753
+ const identityEnd = componentIndexes.length > 0 ? Math.min(...componentIndexes) : value.length;
52754
+ const upgradeState = value.slice(0, identityEnd);
52755
+ const muralComponent = component(value, MURAL_COMPONENT_PREFIX);
52374
52756
  return {
52375
52757
  upgradeState: upgradeState.length > 0 ? upgradeState : null,
52376
- compartmentRenderEpoch: compartmentRenderEpoch.length > 0 ? compartmentRenderEpoch : null
52758
+ compartmentRenderEpoch: component(value, EPOCH_COMPONENT_PREFIX),
52759
+ muralEnabled: muralComponent === "1" ? true : muralComponent === "0" ? false : null,
52760
+ renderBudgetIdentity: component(value, BUDGET_COMPONENT_PREFIX)
52377
52761
  };
52378
52762
  }
52379
52763
 
@@ -53193,4 +53577,4 @@ function registerMagicContextTools(pi, opts) {
53193
53577
  }
53194
53578
  }
53195
53579
 
53196
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, 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, 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, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, 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, updateTagByteSize, getActiveTagTokenAggregate, 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, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, piModelRefToCanonical, resolveModelRefForPi, ompModelRefToCanonical, resolveModelRefForOmp, isSaneLimit, resolveLimit, getSdkContextLimit, resolveModelConfigOrDefault, normalizeTodoStateJson, buildSyntheticTodoPart, 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, readNewMemoriesForM1Union, 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, 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 };
53580
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, 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, 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, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, 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, updateTagByteSize, getActiveTagTokenAggregate, 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, piModelRefToCanonical, resolveModelRefForPi, ompModelRefToCanonical, resolveModelRefForOmp, isSaneLimit, resolveLimit, getSdkContextLimit, resolveModelConfigOrDefault, normalizeTodoStateJson, buildSyntheticTodoPart, 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, readNewMemoriesForM1Union, 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, 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 };