@cortexkit/pi-magic-context 0.35.1 → 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.
@@ -5,7 +5,7 @@ import {
5
5
  getMagicContextStorageDir,
6
6
  log,
7
7
  sessionLog
8
- } from "./index-zmyx6nf5.js";
8
+ } from "./index-npnqc564.js";
9
9
  import {
10
10
  __commonJS,
11
11
  __export,
@@ -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,15 +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
- mkdtempSync,
8668
8972
  readdirSync,
8669
- readFileSync as readFileSync3,
8973
+ readFileSync as readFileSync4,
8670
8974
  statSync as statSync3,
8671
8975
  unlinkSync as unlinkSync2
8672
8976
  } from "node:fs";
8673
- 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";
8674
8978
 
8675
8979
  // ../plugin/src/shared/error-message.ts
8676
8980
  function getErrorMessage(error) {
@@ -8750,7 +9054,7 @@ function safeString(value) {
8750
9054
 
8751
9055
  // ../plugin/src/shared/rpc-utils.ts
8752
9056
  import { execFileSync as execFileSync2 } from "node:child_process";
8753
- import { readFileSync as readFileSync2 } from "node:fs";
9057
+ import { readFileSync as readFileSync3 } from "node:fs";
8754
9058
  function isPidAlive(pid) {
8755
9059
  if (!Number.isInteger(pid) || pid <= 0)
8756
9060
  return false;
@@ -8765,8 +9069,9 @@ var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
8765
9069
  var LINUX_CLOCK_TICKS_PER_SECOND = 100;
8766
9070
  var PS_PROBE_TIMEOUT_MS = 1000;
8767
9071
  var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
8768
- var rpcIdentityReadFileSync = readFileSync2;
9072
+ var rpcIdentityReadFileSync = readFileSync3;
8769
9073
  var rpcIdentityExecFileSync = execFileSync2;
9074
+ var rpcProcessListExecFileSync = execFileSync2;
8770
9075
  var rpcIdentityPlatform = process.platform;
8771
9076
  var rpcIdentityNowMs = () => Date.now();
8772
9077
  function parseLinuxProcessStartTime(statContent, uptimeContent) {
@@ -8839,6 +9144,49 @@ function isPidIdentityPlausible(record) {
8839
9144
  return true;
8840
9145
  return commandLooksLikeOpenCode(command);
8841
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
+ }
8842
9190
  function parseRpcPortFile(content, fallbackPid = 0) {
8843
9191
  const trimmed = content.trim();
8844
9192
  if (!trimmed)
@@ -9785,7 +10133,11 @@ var MIGRATIONS = [
9785
10133
  updated_at INTEGER NOT NULL,
9786
10134
  last_checked_at INTEGER,
9787
10135
  ready_at INTEGER,
9788
- ready_reason TEXT
10136
+ ready_reason TEXT,
10137
+ compiled_provider TEXT,
10138
+ compiled_config TEXT,
10139
+ compiled_at INTEGER,
10140
+ compile_status TEXT CHECK(compile_status IN ('compiled', 'plain', 'refused'))
9789
10141
  );
9790
10142
  CREATE INDEX IF NOT EXISTS idx_notes_session_status ON notes(session_id, status);
9791
10143
  CREATE INDEX IF NOT EXISTS idx_notes_project_status ON notes(project_path, status);
@@ -11694,6 +12046,18 @@ var MIGRATIONS = [
11694
12046
  return;
11695
12047
  ensureColumn(db, "memories", "mural_cue_rejection_count", "INTEGER NOT NULL DEFAULT 0");
11696
12048
  }
12049
+ },
12050
+ {
12051
+ version: 76,
12052
+ description: "persist retina provider compilation for smart-note conditions",
12053
+ up(db) {
12054
+ if (!tableExists2(db, "notes"))
12055
+ return;
12056
+ ensureColumn(db, "notes", "compiled_provider", "TEXT");
12057
+ ensureColumn(db, "notes", "compiled_config", "TEXT");
12058
+ ensureColumn(db, "notes", "compiled_at", "INTEGER");
12059
+ ensureColumn(db, "notes", "compile_status", "TEXT CHECK(compile_status IN ('compiled', 'plain', 'refused'))");
12060
+ }
11697
12061
  }
11698
12062
  ];
11699
12063
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -11788,7 +12152,7 @@ function runMigrations(db) {
11788
12152
  }
11789
12153
  async function runMigrationsWithRetry(db, options = {}) {
11790
12154
  const retryDelaysMs = options.retryDelaysMs ?? MIGRATION_LOCK_RETRY_DELAYS_MS;
11791
- const sleep = options.sleep ?? ((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));
12155
+ const sleep = options.sleep ?? ((delayMs) => new Promise((resolve2) => setTimeout(resolve2, delayMs)));
11792
12156
  const totalAttempts = retryDelaysMs.length + 1;
11793
12157
  for (let attempt = 1;attempt <= totalAttempts; attempt += 1) {
11794
12158
  log(`[migrations] migration lock check attempt ${attempt}/${totalAttempts}`);
@@ -11807,184 +12171,6 @@ async function runMigrationsWithRetry(db, options = {}) {
11807
12171
  }
11808
12172
  }
11809
12173
 
11810
- // ../plugin/src/hooks/magic-context/read-session-formatting.ts
11811
- import { createRequire } from "node:module";
11812
-
11813
- // ../plugin/src/shared/commit-detection.ts
11814
- var HASH_HEX = "[0-9a-f]{7,12}";
11815
- var COMMIT_HASH_TEST_PATTERN = new RegExp(`\\b${HASH_HEX}\\b`, "i");
11816
- var COMMIT_VERB_PATTERN = /\b(?:commit(?:ted|ting|s)?|cherry-?pick(?:ed|ing|s)?|merge[ds]?|merging|rebas(?:e|ed|es|ing))\b/i;
11817
- function textMentionsRecentCommit(text) {
11818
- return COMMIT_HASH_TEST_PATTERN.test(text) && COMMIT_VERB_PATTERN.test(text);
11819
- }
11820
- function createCommitHashExtractPattern() {
11821
- return new RegExp(`\`?\\b(${HASH_HEX})\\b\`?`, "gi");
11822
- }
11823
-
11824
- // ../plugin/src/shared/internal-initiator-marker.ts
11825
- var OMO_INTERNAL_INITIATOR_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
11826
-
11827
- // ../plugin/src/shared/system-directive.ts
11828
- var SYSTEM_DIRECTIVE_PREFIX = "[SYSTEM DIRECTIVE: MAGIC-CONTEXT";
11829
- function isSystemDirective(text) {
11830
- return text.trimStart().startsWith(SYSTEM_DIRECTIVE_PREFIX);
11831
- }
11832
- function removeSystemReminders(text) {
11833
- return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
11834
- }
11835
-
11836
- // ../plugin/src/hooks/magic-context/read-session-formatting.ts
11837
- var MAX_COMMITS_PER_BLOCK = 5;
11838
- function hasMeaningfulUserText(parts) {
11839
- for (const part of parts) {
11840
- if (part === null || typeof part !== "object")
11841
- continue;
11842
- const candidate = part;
11843
- if (candidate.type !== "text" || typeof candidate.text !== "string")
11844
- continue;
11845
- if (candidate.ignored === true)
11846
- continue;
11847
- const cleaned = removeSystemReminders(candidate.text).replace(OMO_INTERNAL_INITIATOR_MARKER, "").trim();
11848
- if (!cleaned)
11849
- continue;
11850
- if (isSystemDirective(cleaned))
11851
- continue;
11852
- return true;
11853
- }
11854
- return false;
11855
- }
11856
- function extractTexts(parts) {
11857
- const texts = [];
11858
- for (const part of parts) {
11859
- if (part === null || typeof part !== "object")
11860
- continue;
11861
- const p = part;
11862
- if (p.type === "text" && typeof p.text === "string" && p.text.trim().length > 0) {
11863
- texts.push(p.text.trim());
11864
- }
11865
- }
11866
- return texts;
11867
- }
11868
- function extractToolCallSummaries(parts) {
11869
- const summaries = [];
11870
- for (const part of parts) {
11871
- if (part === null || typeof part !== "object")
11872
- continue;
11873
- const p = part;
11874
- if (p.type !== "tool" || typeof p.tool !== "string")
11875
- continue;
11876
- const state = p.state;
11877
- if (!state || typeof state !== "object")
11878
- continue;
11879
- const input = state.input;
11880
- const metadata = state.metadata;
11881
- const description = input && typeof input.description === "string" && input.description || metadata && typeof metadata.description === "string" && metadata.description;
11882
- if (description) {
11883
- summaries.push(`TC: ${description}`);
11884
- continue;
11885
- }
11886
- const toolName = p.tool;
11887
- const keyArg = extractKeyArg(toolName, input);
11888
- summaries.push(keyArg ? `TC: ${toolName}(${keyArg})` : `TC: ${toolName}`);
11889
- }
11890
- return summaries;
11891
- }
11892
- function extractKeyArg(_toolName, input) {
11893
- if (!input)
11894
- return null;
11895
- if (typeof input.filePath === "string")
11896
- return truncateArg(input.filePath);
11897
- if (typeof input.path === "string")
11898
- return truncateArg(input.path);
11899
- if (typeof input.pattern === "string")
11900
- return truncateArg(input.pattern);
11901
- if (typeof input.query === "string")
11902
- return truncateArg(input.query);
11903
- if (typeof input.symbol === "string")
11904
- return input.symbol;
11905
- if (typeof input.module === "string")
11906
- return input.module;
11907
- if (typeof input.action === "string")
11908
- return input.action;
11909
- return null;
11910
- }
11911
- function truncateArg(value, maxLen = 60) {
11912
- if (value.length <= maxLen)
11913
- return value;
11914
- return `${value.slice(0, maxLen)}…`;
11915
- }
11916
- var requireFromThisModule = createRequire(import.meta.url);
11917
- var tokenizer;
11918
- function getTokenizer() {
11919
- if (tokenizer)
11920
- return tokenizer;
11921
- const tokenizerModule = requireFromThisModule("ai-tokenizer");
11922
- const Tokenizer = tokenizerModule.default ?? tokenizerModule.Tokenizer;
11923
- if (!Tokenizer)
11924
- throw new Error("ai-tokenizer does not expose a Tokenizer constructor");
11925
- const claudeEncoding = requireFromThisModule("ai-tokenizer/encoding/claude");
11926
- tokenizer = new Tokenizer(claudeEncoding);
11927
- return tokenizer;
11928
- }
11929
- function estimateTokens(text) {
11930
- if (!text)
11931
- return 0;
11932
- return getTokenizer().encode(text, "all").length;
11933
- }
11934
- function normalizeText(text) {
11935
- return text.replace(/\s+/g, " ").trim();
11936
- }
11937
- function compactRole(role) {
11938
- if (role === "assistant")
11939
- return "A";
11940
- if (role === "user")
11941
- return "U";
11942
- return role.slice(0, 1).toUpperCase() || "M";
11943
- }
11944
- function formatBlock(block) {
11945
- const range = block.startOrdinal === block.endOrdinal ? `[${block.startOrdinal}]` : `[${block.startOrdinal}-${block.endOrdinal}]`;
11946
- const commitSuffix = block.commitHashes.length > 0 ? ` commits: ${block.commitHashes.join(", ")}` : "";
11947
- return `${range} ${block.role}:${commitSuffix} ${block.parts.join(" / ")}`;
11948
- }
11949
- function extractCommitHashes(text) {
11950
- const hashes = [];
11951
- const seen = new Set;
11952
- for (const match of text.matchAll(createCommitHashExtractPattern())) {
11953
- const hash = match[1]?.toLowerCase();
11954
- if (!hash || seen.has(hash))
11955
- continue;
11956
- seen.add(hash);
11957
- hashes.push(hash);
11958
- if (hashes.length >= MAX_COMMITS_PER_BLOCK)
11959
- break;
11960
- }
11961
- return hashes;
11962
- }
11963
- function compactTextForSummary(text, role) {
11964
- const commitHashes = role === "assistant" ? extractCommitHashes(text) : [];
11965
- if (commitHashes.length === 0 || !COMMIT_VERB_PATTERN.test(text)) {
11966
- return { text, commitHashes };
11967
- }
11968
- const withoutHashes = text.replace(createCommitHashExtractPattern(), "").replace(/\(\s*\)/g, "").replace(/\s+,/g, ",").replace(/,\s*,+/g, ", ").replace(/\s{2,}/g, " ").replace(/\s+([,.;:])/g, "$1").trim();
11969
- return {
11970
- text: withoutHashes.length > 0 ? withoutHashes : text,
11971
- commitHashes
11972
- };
11973
- }
11974
- function mergeCommitHashes(existing, next) {
11975
- if (next.length === 0)
11976
- return existing;
11977
- const merged = [...existing];
11978
- for (const hash of next) {
11979
- if (merged.includes(hash))
11980
- continue;
11981
- merged.push(hash);
11982
- if (merged.length >= MAX_COMMITS_PER_BLOCK)
11983
- break;
11984
- }
11985
- return merged;
11986
- }
11987
-
11988
12174
  // ../plugin/src/shared/stable-json.ts
11989
12175
  function stableStringify(value, seen = new WeakSet) {
11990
12176
  if (value === undefined)
@@ -12039,12 +12225,12 @@ function loadToolDefinitionMeasurements(db) {
12039
12225
  }
12040
12226
 
12041
12227
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
12042
- import { existsSync as existsSync3 } from "node:fs";
12043
- import { join as join2 } from "node:path";
12228
+ import { existsSync as existsSync4 } from "node:fs";
12229
+ import { join as join3 } from "node:path";
12044
12230
  var LEASE_DURATION_MS = 5 * 60 * 1000;
12045
12231
  var LEASE_RENEWAL_MS = 60 * 1000;
12046
12232
  function resolveOpencodeDbPath() {
12047
- return join2(getDataDir(), "opencode", "opencode.db");
12233
+ return join3(getDataDir(), "opencode", "opencode.db");
12048
12234
  }
12049
12235
  function ensureBackfillStateTable(db) {
12050
12236
  db.exec(`
@@ -12079,7 +12265,7 @@ function runToolOwnerBackfill(db) {
12079
12265
  return result;
12080
12266
  }
12081
12267
  const opencodeDbPath = resolveOpencodeDbPath();
12082
- if (!existsSync3(opencodeDbPath)) {
12268
+ if (!existsSync4(opencodeDbPath)) {
12083
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.`);
12084
12270
  markAllUnbackfilledSessionsSkipped(db);
12085
12271
  result.sessionsSkippedNoOcDb = countSessionsByStatus(db, "skipped");
@@ -12306,7 +12492,7 @@ function getSchemaFenceRejection() {
12306
12492
  function getMigrationOnOpenRefusal() {
12307
12493
  return lastMigrationOnOpenRefusal;
12308
12494
  }
12309
- var LATEST_SUPPORTED_VERSION = 75;
12495
+ var LATEST_SUPPORTED_VERSION = 76;
12310
12496
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
12311
12497
  var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
12312
12498
  var storagePermissionFs = defaultStoragePermissionFs;
@@ -12329,7 +12515,7 @@ function restrictDatabaseFilePermissions(dbPath) {
12329
12515
  return;
12330
12516
  for (const suffix of ["", "-wal", "-shm"]) {
12331
12517
  const file = `${dbPath}${suffix}`;
12332
- if (!existsSync4(file))
12518
+ if (!existsSync5(file))
12333
12519
  continue;
12334
12520
  try {
12335
12521
  storagePermissionFs.chmodSync(file, 384);
@@ -12340,26 +12526,20 @@ function restrictDatabaseFilePermissions(dbPath) {
12340
12526
  }
12341
12527
  function resolveDatabasePath(dbPathOverride) {
12342
12528
  if (dbPathOverride) {
12343
- return { dbDir: dirname2(dbPathOverride), dbPath: dbPathOverride };
12344
- }
12345
- const testDataDir = process.env.MAGIC_CONTEXT_TEST_DATA_DIR;
12346
- if (testDataDir && !process.env.XDG_DATA_HOME) {
12347
- const dbDir2 = join3(testDataDir, "cortexkit", "magic-context");
12348
- return { dbDir: dbDir2, dbPath: join3(dbDir2, "context.db") };
12529
+ return { dbDir: dirname3(dbPathOverride), dbPath: dbPathOverride };
12349
12530
  }
12350
- if (false) {}
12351
12531
  const dbDir = getMagicContextStorageDir();
12352
- return { dbDir, dbPath: join3(dbDir, "context.db") };
12532
+ return { dbDir, dbPath: join4(dbDir, "context.db") };
12353
12533
  }
12354
12534
  function getDatabasePath(db) {
12355
12535
  return pathByDatabase.get(db) ?? null;
12356
12536
  }
12357
12537
  function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
12358
- if (existsSync4(targetDbPath))
12538
+ if (existsSync5(targetDbPath))
12359
12539
  return;
12360
12540
  const legacyDir = getLegacyOpenCodeMagicContextStorageDir();
12361
- const legacyDbPath = join3(legacyDir, "context.db");
12362
- if (!existsSync4(legacyDbPath))
12541
+ const legacyDbPath = join4(legacyDir, "context.db");
12542
+ if (!existsSync5(legacyDbPath))
12363
12543
  return;
12364
12544
  log(`[magic-context] migrating legacy plugin storage: ${legacyDir} -> ${targetDbDir} (legacy left in place as backup)`);
12365
12545
  ensureSecureStorageDir(targetDbDir);
@@ -12375,8 +12555,8 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
12375
12555
  }
12376
12556
  for (const suffix of ["", "-wal", "-shm"]) {
12377
12557
  const src = `${legacyDbPath}${suffix}`;
12378
- const dst = join3(targetDbDir, `context.db${suffix}`);
12379
- if (existsSync4(src)) {
12558
+ const dst = join4(targetDbDir, `context.db${suffix}`);
12559
+ if (existsSync5(src)) {
12380
12560
  try {
12381
12561
  copyFileSync(src, dst);
12382
12562
  } catch (error) {
@@ -12384,9 +12564,9 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
12384
12564
  }
12385
12565
  }
12386
12566
  }
12387
- const legacyModelsDir = join3(legacyDir, "models");
12388
- const targetModelsDir = join3(targetDbDir, "models");
12389
- if (existsSync4(legacyModelsDir) && !existsSync4(targetModelsDir)) {
12567
+ const legacyModelsDir = join4(legacyDir, "models");
12568
+ const targetModelsDir = join4(targetDbDir, "models");
12569
+ if (existsSync5(legacyModelsDir) && !existsSync5(targetModelsDir)) {
12390
12570
  try {
12391
12571
  cpSync(legacyModelsDir, targetModelsDir, { recursive: true });
12392
12572
  } catch (error) {
@@ -12440,7 +12620,7 @@ function unreadableDiscovery(path2, arm) {
12440
12620
  var RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
12441
12621
  var defaultRpcDiscoveryFs = {
12442
12622
  readdirSync: (path2, options) => options?.withFileTypes ? readdirSync(path2, { withFileTypes: true }) : readdirSync(path2),
12443
- readFileSync: (path2, encoding) => String(readFileSync3(path2, encoding)),
12623
+ readFileSync: (path2, encoding) => String(readFileSync4(path2, encoding)),
12444
12624
  statSync: (path2) => ({ mtimeMs: statSync3(path2).mtimeMs }),
12445
12625
  unlinkSync: (path2) => unlinkSync2(path2)
12446
12626
  };
@@ -12478,7 +12658,7 @@ function classifyJunkDiscovery(portFile, raw, staleFiles) {
12478
12658
  return null;
12479
12659
  }
12480
12660
  function inspectRpcServerDiscovery(storageDir) {
12481
- const rpcRoot = join3(storageDir, "rpc");
12661
+ const rpcRoot = join4(storageDir, "rpc");
12482
12662
  let projectEntries;
12483
12663
  try {
12484
12664
  projectEntries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
@@ -12492,7 +12672,7 @@ function inspectRpcServerDiscovery(storageDir) {
12492
12672
  for (const projectEntry of projectEntries) {
12493
12673
  if (!projectEntry.isDirectory())
12494
12674
  continue;
12495
- const projectDir = join3(rpcRoot, projectEntry.name);
12675
+ const projectDir = join4(rpcRoot, projectEntry.name);
12496
12676
  let entries;
12497
12677
  try {
12498
12678
  entries = rpcDiscoveryFs.readdirSync(projectDir);
@@ -12503,7 +12683,7 @@ function inspectRpcServerDiscovery(storageDir) {
12503
12683
  }
12504
12684
  for (const entry of entries) {
12505
12685
  if (entry === "port" || entry.startsWith("port-") && entry.endsWith(".json")) {
12506
- portFiles.push(join3(projectDir, entry));
12686
+ portFiles.push(join4(projectDir, entry));
12507
12687
  }
12508
12688
  }
12509
12689
  }
@@ -12556,14 +12736,16 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12556
12736
  return true;
12557
12737
  }
12558
12738
  const discovery = inspectRpcServerDiscovery(dbDir);
12559
- if (discovery.state === "absent" || discovery.state === "stale") {
12739
+ const piPids = discoverLivePiProcessIds();
12740
+ if ((discovery.state === "absent" || discovery.state === "stale") && piPids.length === 0) {
12560
12741
  lastMigrationOnOpenRefusal = null;
12561
12742
  return true;
12562
12743
  }
12744
+ const blockingPids = [...new Set([...discovery.serverPids, ...piPids])].sort((left, right) => left - right);
12563
12745
  lastMigrationOnOpenRefusal = {
12564
12746
  persistedVersion,
12565
12747
  supportedVersion: latestSupportedVersion,
12566
- serverPids: discovery.serverPids,
12748
+ serverPids: blockingPids,
12567
12749
  ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {},
12568
12750
  ...discovery.unreadableArm ? { unreadableArm: discovery.unreadableArm } : {}
12569
12751
  };
@@ -12573,7 +12755,11 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12573
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.`;
12574
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}`);
12575
12757
  } else {
12576
- 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.`);
12577
12763
  }
12578
12764
  return false;
12579
12765
  }
@@ -15218,13 +15404,13 @@ function clearCompressionDepthRange(db, sessionId, startOrdinal, endOrdinal) {
15218
15404
  import { createHash as createHash4 } from "node:crypto";
15219
15405
 
15220
15406
  // ../plugin/src/hooks/magic-context/read-session-db.ts
15221
- import { existsSync as existsSync5 } from "node:fs";
15222
- import { join as join4 } from "node:path";
15407
+ import { existsSync as existsSync6 } from "node:fs";
15408
+ import { join as join5 } from "node:path";
15223
15409
  function getOpenCodeDbPath() {
15224
- return join4(getDataDir(), "opencode", "opencode.db");
15410
+ return join5(getDataDir(), "opencode", "opencode.db");
15225
15411
  }
15226
15412
  function openCodeDbExists() {
15227
- return existsSync5(getOpenCodeDbPath());
15413
+ return existsSync6(getOpenCodeDbPath());
15228
15414
  }
15229
15415
  var cachedReadOnlyDb = null;
15230
15416
  function closeCachedReadOnlyDb() {
@@ -17304,7 +17490,7 @@ function escapeXmlContent(s) {
17304
17490
  }
17305
17491
  // ../plugin/src/features/magic-context/project-docs-hash.ts
17306
17492
  import { createHash as createHash5 } from "node:crypto";
17307
- import { lstatSync, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
17493
+ import { lstatSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
17308
17494
  import path2 from "node:path";
17309
17495
  var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
17310
17496
  var PROJECT_DOCS_DELIMITER = `
@@ -17378,7 +17564,7 @@ function readCanonicalPieces(projectDirectory, files) {
17378
17564
  if (!safeToRead) {
17379
17565
  continue;
17380
17566
  }
17381
- const canonicalContent = canonicalizeDocContent(readFileSync4(filePath, "utf8"));
17567
+ const canonicalContent = canonicalizeDocContent(readFileSync5(filePath, "utf8"));
17382
17568
  hashPieces.push(`file:${filename}
17383
17569
  ${canonicalContent}`);
17384
17570
  renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
@@ -17451,6 +17637,67 @@ function mapMessageId(filter, messageId) {
17451
17637
  return null;
17452
17638
  return filter.mapMessageId?.(messageId) ?? messageId;
17453
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
+ }
17454
17701
  function filterIdBlob(raw, filter) {
17455
17702
  if (!raw)
17456
17703
  return "";
@@ -17471,12 +17718,14 @@ function clampWatermark(value, maxCopiedTag) {
17471
17718
  }
17472
17719
  function copySessionStateForClone(db, sourceSessionId, destinationSessionId, filter) {
17473
17720
  return runImmediate(db, () => {
17474
- 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)) {
17475
17722
  return {
17476
17723
  kind: "destination-not-empty",
17477
17724
  compartmentsCopied: 0,
17478
17725
  tagsCopied: 0,
17479
17726
  pendingOpsCopied: 0,
17727
+ notesCopied: 0,
17728
+ factsCopied: 0,
17480
17729
  pendingMarkerMigrated: false
17481
17730
  };
17482
17731
  }
@@ -17560,6 +17809,7 @@ function copySessionStateForClone(db, sourceSessionId, destinationSessionId, fil
17560
17809
  insertPendingOp.run(destinationSessionId, destinationTagId, row.operation, row.queued_at, row.harness);
17561
17810
  }
17562
17811
  }
17812
+ const inherited = filter.copySessionNotesAndFacts === true ? copyPiSessionNotesAndFacts(db, sourceSessionId, destinationSessionId, filter) : { notesCopied: 0, factsCopied: 0 };
17563
17813
  const meta = db.prepare(`SELECT cleared_reasoning_through_tag, tool_reclaim_watermark,
17564
17814
  pi_stable_id_scheme, stripped_placeholder_ids,
17565
17815
  stale_reduce_stripped_ids, processed_image_stripped_ids,
@@ -17601,6 +17851,8 @@ function copySessionStateForClone(db, sourceSessionId, destinationSessionId, fil
17601
17851
  compartmentsCopied: copiedCompartments.length,
17602
17852
  tagsCopied: copiedTagNumbers.length,
17603
17853
  pendingOpsCopied: typeof pendingOpsRow?.count === "number" ? pendingOpsRow.count : 0,
17854
+ notesCopied: inherited.notesCopied,
17855
+ factsCopied: inherited.factsCopied,
17604
17856
  pendingMarkerMigrated: pendingMarker !== null
17605
17857
  };
17606
17858
  });
@@ -17868,6 +18120,11 @@ var NOTE_CHECK_STATUSES = new Set([
17868
18120
  "failing",
17869
18121
  "fallback"
17870
18122
  ]);
18123
+ var CONDITION_COMPILE_STATUSES = new Set([
18124
+ "compiled",
18125
+ "plain",
18126
+ "refused"
18127
+ ]);
17871
18128
  var DEFAULT_SMART_STATUSES = ["pending", "ready"];
17872
18129
  function toNullableString(value) {
17873
18130
  return typeof value === "string" && value.length > 0 ? value : null;
@@ -17890,6 +18147,10 @@ function toNote(row) {
17890
18147
  sessionId: toNullableString(row.session_id),
17891
18148
  projectPath: toNullableString(row.project_path),
17892
18149
  surfaceCondition: toNullableString(row.surface_condition),
18150
+ compiledProvider: toNullableString(row.compiled_provider),
18151
+ compiledConfig: toNullableString(row.compiled_config),
18152
+ compiledAt: toNullableNumber(row.compiled_at),
18153
+ compileStatus: typeof row.compile_status === "string" && CONDITION_COMPILE_STATUSES.has(row.compile_status) ? row.compile_status : null,
17893
18154
  createdAt: row.created_at,
17894
18155
  updatedAt: row.updated_at,
17895
18156
  lastCheckedAt: toNullableNumber(row.last_checked_at),
@@ -17969,7 +18230,7 @@ function getNotes(db, options = {}) {
17969
18230
  }
17970
18231
  function addNote(db, type, options) {
17971
18232
  const now = Date.now();
17972
- const result = type === "session" ? db.prepare("INSERT INTO notes (type, status, content, session_id, created_at, updated_at, harness, anchor_ordinal) VALUES ('session', 'active', ?, ?, ?, ?, ?, ?) RETURNING *").get(options.content, options.sessionId, now, now, getHarness(), options.anchorOrdinal ?? null) : db.prepare("INSERT INTO notes (type, status, content, session_id, project_path, surface_condition, created_at, updated_at, harness, anchor_ordinal) VALUES ('smart', 'pending', ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *").get(options.content, options.sessionId ?? null, options.projectPath, options.surfaceCondition, now, now, getHarness(), options.anchorOrdinal ?? null);
18233
+ const result = type === "session" ? db.prepare("INSERT INTO notes (type, status, content, session_id, created_at, updated_at, harness, anchor_ordinal) VALUES ('session', 'active', ?, ?, ?, ?, ?, ?) RETURNING *").get(options.content, options.sessionId, now, now, getHarness(), options.anchorOrdinal ?? null) : db.prepare("INSERT INTO notes (type, status, content, session_id, project_path, surface_condition, compiled_provider, compiled_config, compiled_at, compile_status, created_at, updated_at, harness, anchor_ordinal) VALUES ('smart', 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *").get(options.content, options.sessionId ?? null, options.projectPath, options.surfaceCondition, options.compiledProvider ?? null, options.compiledConfig ?? null, options.compiledAt ?? null, options.compileStatus ?? null, now, now, getHarness(), options.anchorOrdinal ?? null);
17973
18234
  if (!isNoteRow(result)) {
17974
18235
  throw new Error("[notes] failed to insert note");
17975
18236
  }
@@ -18023,6 +18284,8 @@ function updateNote(db, noteId, updates, scope) {
18023
18284
  }
18024
18285
  if (smartConditionChanged) {
18025
18286
  sets.push("status = 'pending'", "last_checked_at = NULL", "ready_at = NULL", "ready_reason = NULL");
18287
+ sets.push("compiled_provider = ?", "compiled_config = ?", "compiled_at = ?", "compile_status = ?");
18288
+ params.push(updates.compiledProvider ?? null, updates.compiledConfig ?? null, updates.compiledAt ?? null, updates.compileStatus ?? null);
18026
18289
  if (noteCheckColumnsExist(db)) {
18027
18290
  sets.push("compiled_check = NULL", "manifest_json = NULL", "check_hash = NULL", "check_cron = NULL", "check_version = 0", "check_status = 'uncompiled'", "check_failure_count = 0", "check_network_failure_count = 0", "check_quarantined_until = NULL", "check_next_due_at = NULL", "check_compiled_at = NULL", "check_false_since_at = NULL", "check_last_liveness_at = NULL");
18028
18291
  }
@@ -19020,6 +19283,20 @@ function getTagsByNumbers(db, sessionId, tagNumbers) {
19020
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);
19021
19284
  return rows.map(toTagEntry);
19022
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
+ }
19023
19300
  function getMaxDroppedTagNumber(db, sessionId) {
19024
19301
  const row = getMaxDroppedTagNumberStatement(db).get(sessionId);
19025
19302
  return isMaxTagNumberRow(row) ? row.max_tag_number : 0;
@@ -19089,6 +19366,47 @@ var ERROR_CLASSES = new Set([
19089
19366
  "permission_denied",
19090
19367
  "unknown"
19091
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
+
19092
19410
  // ../plugin/src/hooks/magic-context/todo-view.ts
19093
19411
  import { createHash as createHash7 } from "node:crypto";
19094
19412
  var TODO_STATUS_PENDING = "pending";
@@ -19197,8 +19515,8 @@ function isTodoItem(value) {
19197
19515
  }
19198
19516
 
19199
19517
  // ../plugin/src/shared/prompt-surface-runtime.ts
19200
- import { existsSync as existsSync7, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
19201
- 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";
19202
19520
 
19203
19521
  // ../plugin/src/tools/light-descriptions.ts
19204
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.`;
@@ -19208,7 +19526,7 @@ var CTX_MEMORY_LIGHT_DESCRIPTION = `For ctx_memory users, write one standalone d
19208
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.`;
19209
19527
 
19210
19528
  // ../plugin/src/shared/jsonc-parser.ts
19211
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
19529
+ import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
19212
19530
  function stripJsonComments(content) {
19213
19531
  let result = "";
19214
19532
  let inString = false;
@@ -19263,13 +19581,43 @@ function stripJsonComments(content) {
19263
19581
  }
19264
19582
  return result;
19265
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
+ }
19266
19614
  function detectConfigFile(basePath) {
19267
19615
  const jsoncPath = `${basePath}.jsonc`;
19268
19616
  const jsonPath = `${basePath}.json`;
19269
- if (existsSync6(jsoncPath)) {
19617
+ if (existsSync7(jsoncPath)) {
19270
19618
  return { format: "jsonc", path: jsoncPath };
19271
19619
  }
19272
- if (existsSync6(jsonPath)) {
19620
+ if (existsSync7(jsonPath)) {
19273
19621
  return { format: "json", path: jsonPath };
19274
19622
  }
19275
19623
  return { format: "none", path: jsoncPath };
@@ -19280,7 +19628,9 @@ function isValidPromptSurfaceModelKey(key) {
19280
19628
  if (key.length === 0 || key.trim() !== key)
19281
19629
  return false;
19282
19630
  const slash = key.indexOf("/");
19283
- if (slash <= 0 || slash === key.length - 1)
19631
+ if (slash < 0)
19632
+ return !key.includes("*");
19633
+ if (slash === 0 || slash === key.length - 1)
19284
19634
  return false;
19285
19635
  const provider = key.slice(0, slash);
19286
19636
  const modelID = key.slice(slash + 1);
@@ -19331,7 +19681,7 @@ function resolveModelConfigValue(values, modelKey) {
19331
19681
  function resolvePromptSurface(config, modelKey) {
19332
19682
  const fallback = config?.default ?? "full";
19333
19683
  const match = resolveModelConfigValue(config?.models, modelKey);
19334
- if (match && match.source !== "bare") {
19684
+ if (match) {
19335
19685
  return { preset: match.value, source: match.source };
19336
19686
  }
19337
19687
  return { preset: fallback, source: "default" };
@@ -19343,7 +19693,7 @@ function resolveModelConfigOrDefault(values, modelKey, fallback) {
19343
19693
  // ../plugin/src/shared/prompt-surface-runtime.ts
19344
19694
  var GUIDANCE_MARKER = "## Magic Context";
19345
19695
  var GUIDANCE_MARKER_LINE = /^## Magic Context[\t ]*\r?$/gm;
19346
- var PROMPT_SURFACE_TOOL_IDS = [
19696
+ var ACTIVE_TOOL_IDS = [
19347
19697
  "ctx_reduce",
19348
19698
  "ctx_expand",
19349
19699
  "ctx_note",
@@ -19361,20 +19711,20 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
19361
19711
  return preset === "full" ? systemContent : `${systemContent}
19362
19712
  \x00magic-context-prompt-surface:${preset}`;
19363
19713
  }
19364
- var PROMPT_SURFACE_TOOL_ID_SET = new Set(PROMPT_SURFACE_TOOL_IDS);
19714
+ var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
19365
19715
  function resolveUserConfigDirectory(options) {
19366
19716
  if (options.userConfigDirectory)
19367
- return resolve(options.userConfigDirectory);
19717
+ return resolve2(options.userConfigDirectory);
19368
19718
  const sharedBase = cortexKitUserConfigBasePath();
19369
19719
  const shared = detectConfigFile(sharedBase);
19370
19720
  if (shared.format !== "none")
19371
- return dirname3(shared.path);
19721
+ return dirname4(shared.path);
19372
19722
  if (options.harness) {
19373
- 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));
19374
19724
  if (legacy)
19375
- return dirname3(legacy.path);
19725
+ return dirname4(legacy.path);
19376
19726
  }
19377
- return dirname3(sharedBase);
19727
+ return dirname4(sharedBase);
19378
19728
  }
19379
19729
  function markerCount(content) {
19380
19730
  return content.match(GUIDANCE_MARKER_LINE)?.length ?? 0;
@@ -19391,14 +19741,14 @@ function createPromptSurfaceRuntime(options) {
19391
19741
  const readGuidanceOverride = (configuredPath) => {
19392
19742
  if (!configuredPath)
19393
19743
  return;
19394
- const path3 = isAbsolute2(configuredPath) ? configuredPath : resolve(userConfigDirectory, configuredPath);
19744
+ const path3 = isAbsolute2(configuredPath) ? configuredPath : resolve2(userConfigDirectory, configuredPath);
19395
19745
  let content;
19396
19746
  try {
19397
19747
  if (!statSync5(path3).isFile()) {
19398
19748
  warnOnce(`guidance-not-file:${path3}`, `prompt_surface.guidance_override_path (${path3}) is not a file; using built-in guidance.`);
19399
19749
  return;
19400
19750
  }
19401
- content = readFileSync6(path3, "utf8");
19751
+ content = readFileSync7(path3, "utf8");
19402
19752
  } catch (error) {
19403
19753
  const reason = error instanceof Error ? error.message : String(error);
19404
19754
  warnOnce(`guidance-unreadable:${path3}:${reason}`, `prompt_surface.guidance_override_path (${path3}) could not be read (${reason}); using built-in guidance.`);
@@ -19815,7 +20165,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
19815
20165
  }
19816
20166
 
19817
20167
  // src/config/index.ts
19818
- import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
20168
+ import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
19819
20169
 
19820
20170
  // ../plugin/src/config/migrate-dreamer-v2.ts
19821
20171
  var OLD_VERIFY_TASK = "verify";
@@ -20126,7 +20476,7 @@ function migrateLegacyExperimental(rawConfig, warnings) {
20126
20476
  }
20127
20477
 
20128
20478
  // ../plugin/src/config/schema/magic-context.ts
20129
- import { homedir as homedir3 } from "node:os";
20479
+ import { homedir as homedir4 } from "node:os";
20130
20480
 
20131
20481
  // ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
20132
20482
  var exports_external = {};
@@ -34674,14 +35024,14 @@ var PiConfigSchema = exports_external.object({
34674
35024
  }).optional();
34675
35025
  var PromptSurfacePresetSchema = exports_external.enum(["full", "light"]);
34676
35026
  var PromptSurfaceModelKeySchema = exports_external.string().refine(isValidPromptSurfaceModelKey, {
34677
- 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."
34678
35028
  });
34679
35029
  var PromptSurfaceToolKeySchema = exports_external.string().refine((value) => value.trim().length > 0, {
34680
35030
  message: "tool description keys must not be empty or whitespace-only"
34681
35031
  });
34682
35032
  var PromptSurfaceConfigSchema = exports_external.object({
34683
35033
  default: PromptSurfacePresetSchema.default("full").describe('Fallback prompt-surface preset ("full" or "light").'),
34684
- 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."),
34685
35035
  guidance_override_path: exports_external.string().refine((value) => value.trim().length > 0, {
34686
35036
  message: "guidance_override_path must not be empty or whitespace-only"
34687
35037
  }).optional().describe("USER-LEVEL ONLY path to a complete primary guidance section. Relative paths resolve from the user config file."),
@@ -34765,9 +35115,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
34765
35115
  function expandConfigPath(value) {
34766
35116
  const trimmed = value.trim();
34767
35117
  if (trimmed === "~")
34768
- return homedir3();
35118
+ return homedir4();
34769
35119
  if (trimmed.startsWith("~/"))
34770
- return `${homedir3()}/${trimmed.slice(2)}`;
35120
+ return `${homedir4()}/${trimmed.slice(2)}`;
34771
35121
  return trimmed;
34772
35122
  }
34773
35123
  var BaseEmbeddingConfigSchema = exports_external.object({
@@ -34870,8 +35220,11 @@ var MagicContextConfigSchema = exports_external.object({
34870
35220
  language: exports_external.string().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian, dreamer, sidekick, and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
34871
35221
  historian: HistorianConfigSchema.describe("Historian agent configuration (model, fallback_models, variant, temperature, maxTokens, permission, two_pass, etc.)"),
34872
35222
  dreamer: DreamerConfigSchema.optional().describe("Dreamer agent + scheduling configuration (model, fallback_models, disable, schedule, tasks, etc.)"),
35223
+ smart_notes: exports_external.object({
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.")
35225
+ }).default({ retina_handoff: false }).describe("Smart-note ownership transition controls."),
34873
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.'),
34874
- 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)."),
34875
35228
  output_reserve: exports_external.union([
34876
35229
  exports_external.number().min(0),
34877
35230
  exports_external.object({ default: exports_external.number().min(0) }).catchall(exports_external.number().min(0))
@@ -35311,18 +35664,18 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
35311
35664
  }
35312
35665
 
35313
35666
  // ../plugin/src/config/variable.ts
35314
- import { existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
35315
- import { homedir as homedir4 } from "node:os";
35316
- 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";
35317
35670
  var ENV_PATTERN = /\{env:([^}]+)\}/g;
35318
35671
  var FILE_PATTERN = /\{file:([^}]+)\}/g;
35319
35672
  function sensitiveFilePathReason(resolvedPath) {
35320
- const home = homedir4();
35673
+ const home = homedir5();
35321
35674
  const sensitiveDirs = [
35322
- { dir: resolve2(home, ".ssh"), label: "SSH keys" },
35323
- { dir: resolve2(home, ".aws"), label: "AWS credentials" },
35324
- { dir: resolve2(home, ".gnupg"), label: "GnuPG keyring" },
35325
- { 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" }
35326
35679
  ];
35327
35680
  for (const { dir, label } of sensitiveDirs) {
35328
35681
  if (resolvedPath === dir || resolvedPath.startsWith(`${dir}/`)) {
@@ -35362,7 +35715,7 @@ function substituteConfigVariables(input) {
35362
35715
  if (fileMatches.length === 0) {
35363
35716
  return { text, warnings };
35364
35717
  }
35365
- const configDir = input.configPath ? dirname4(input.configPath) : process.cwd();
35718
+ const configDir = input.configPath ? dirname5(input.configPath) : process.cwd();
35366
35719
  let output = "";
35367
35720
  let cursor = 0;
35368
35721
  for (const match of fileMatches) {
@@ -35380,21 +35733,21 @@ function substituteConfigVariables(input) {
35380
35733
  }
35381
35734
  let filePath = rawPath.trim();
35382
35735
  if (filePath.startsWith("~/")) {
35383
- filePath = resolve2(homedir4(), filePath.slice(2));
35736
+ filePath = resolve3(homedir5(), filePath.slice(2));
35384
35737
  } else if (!isAbsolute3(filePath)) {
35385
- filePath = resolve2(configDir, filePath);
35738
+ filePath = resolve3(configDir, filePath);
35386
35739
  }
35387
35740
  const sensitiveReason = sensitiveFilePathReason(filePath);
35388
35741
  if (sensitiveReason) {
35389
35742
  warnings.push(`${token} resolves to a sensitive path (${sensitiveReason}: ${filePath}); ` + "inlining its contents into config — make sure this is intentional.");
35390
35743
  }
35391
- if (!existsSync8(filePath)) {
35744
+ if (!existsSync9(filePath)) {
35392
35745
  warnings.push(`File not found for ${token} (resolved to ${filePath}); using empty string`);
35393
35746
  continue;
35394
35747
  }
35395
35748
  let contents;
35396
35749
  try {
35397
- contents = readFileSync7(filePath, "utf-8").trim();
35750
+ contents = readFileSync8(filePath, "utf-8").trim();
35398
35751
  } catch (error51) {
35399
35752
  const message = error51 instanceof Error ? error51.message : String(error51);
35400
35753
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -35407,36 +35760,8 @@ function substituteConfigVariables(input) {
35407
35760
  }
35408
35761
 
35409
35762
  // ../plugin/src/shared/models-dev-cache.ts
35410
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync8, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
35411
- import { join as join5 } from "node:path";
35412
-
35413
- // ../plugin/src/shared/harness-provider-map.ts
35414
- var CANONICAL_TO_PI_PROVIDER = {
35415
- openai: "openai-codex",
35416
- google: "google-antigravity"
35417
- };
35418
- var PI_TO_CANONICAL_PROVIDER = {
35419
- "openai-codex": "openai",
35420
- "google-antigravity": "google"
35421
- };
35422
- function remapProviderPrefix(ref, map2) {
35423
- if (typeof ref !== "string")
35424
- return ref;
35425
- const slash = ref.indexOf("/");
35426
- if (slash <= 0)
35427
- return ref;
35428
- const provider = ref.slice(0, slash);
35429
- const mapped = map2[provider];
35430
- return mapped ? `${mapped}${ref.slice(slash)}` : ref;
35431
- }
35432
- function piModelRefToCanonical(ref) {
35433
- return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
35434
- }
35435
- function resolveModelRefForPi(ref) {
35436
- return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
35437
- }
35438
-
35439
- // ../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";
35440
35765
  var MIN_SANE_LIMIT = 20000;
35441
35766
  var MAX_SANE_LIMIT = 3000000;
35442
35767
  function isSaneLimit(limit) {
@@ -35450,14 +35775,14 @@ var reserveClampLogSeen = new Set;
35450
35775
  var apiCache = null;
35451
35776
  var persistSeedLoaded = false;
35452
35777
  function persistFilePath() {
35453
- return join5(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
35778
+ return join6(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
35454
35779
  }
35455
35780
  function loadPersistedApiCacheOnce() {
35456
35781
  if (persistSeedLoaded || apiCache !== null)
35457
35782
  return;
35458
35783
  persistSeedLoaded = true;
35459
35784
  try {
35460
- const raw = readFileSync8(persistFilePath(), "utf-8");
35785
+ const raw = readFileSync9(persistFilePath(), "utf-8");
35461
35786
  const obj = JSON.parse(raw);
35462
35787
  const map2 = new Map;
35463
35788
  for (const [key, persisted] of Object.entries(obj)) {
@@ -35599,25 +35924,28 @@ function getUserConfigPaths() {
35599
35924
  return [`${basePath}.jsonc`, `${basePath}.json`];
35600
35925
  }
35601
35926
  function resolveFirstExisting(paths) {
35602
- return paths.find((path3) => existsSync9(path3));
35927
+ return paths.find((path3) => existsSync10(path3));
35603
35928
  }
35604
35929
  function resolvePiLegacyFallback(sources) {
35605
- return sources.find((source) => existsSync9(source.path)) ?? null;
35930
+ return sources.find((source) => existsSync10(source.path)) ?? null;
35606
35931
  }
35607
35932
  function loadConfigFile(path3, scope) {
35608
35933
  try {
35609
- const rawText = readFileSync9(path3, "utf-8");
35934
+ const rawText = readFileSync10(path3, "utf-8");
35610
35935
  const substituted = substituteConfigVariables({
35611
35936
  text: rawText,
35612
35937
  configPath: path3,
35613
35938
  isProjectConfig: scope === "project"
35614
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).`);
35615
35943
  return {
35616
35944
  path: path3,
35617
35945
  scope,
35618
- config: import_comment_json.parse(substituted.text),
35619
- warnings: substituted.warnings.map((warning) => `${path3}: ${warning}`),
35620
- 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"
35621
35949
  };
35622
35950
  } catch (error51) {
35623
35951
  const message = error51 instanceof Error ? error51.message : String(error51);
@@ -35655,11 +35983,28 @@ function redactConfigValue(value) {
35655
35983
  function isPlainObject4(value) {
35656
35984
  return typeof value === "object" && value !== null && !Array.isArray(value);
35657
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
+ }
35658
35994
  function mergeRawConfigs(base, override) {
35659
- const merged = { ...base };
35660
- for (const [key, overrideValue] of Object.entries(override)) {
35661
- const baseValue = merged[key];
35662
- 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);
35663
36008
  }
35664
36009
  return merged;
35665
36010
  }
@@ -35739,7 +36084,7 @@ function loadPiConfig(opts = {}) {
35739
36084
  if (loaded)
35740
36085
  loadedFiles.push(loaded);
35741
36086
  }
35742
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync9(source.path));
36087
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync10(source.path));
35743
36088
  const userPath = resolveFirstExisting(getUserConfigPaths());
35744
36089
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
35745
36090
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -35748,7 +36093,7 @@ function loadPiConfig(opts = {}) {
35748
36093
  if (loaded)
35749
36094
  loadedFiles.push(loaded);
35750
36095
  }
35751
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync9(source.path));
36096
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync10(source.path));
35752
36097
  if (userLegacyFallback) {
35753
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.`);
35754
36099
  } else if (legacyUserUnmigrated) {
@@ -35859,7 +36204,7 @@ function loadPiConfigDetailed(opts = {}) {
35859
36204
  if (loaded)
35860
36205
  loadedFiles.push(loaded);
35861
36206
  }
35862
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync9(source.path));
36207
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync10(source.path));
35863
36208
  const userPath = resolveFirstExisting(getUserConfigPaths());
35864
36209
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
35865
36210
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -35868,7 +36213,7 @@ function loadPiConfigDetailed(opts = {}) {
35868
36213
  if (loaded)
35869
36214
  loadedFiles.push(loaded);
35870
36215
  }
35871
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync9(source.path));
36216
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync10(source.path));
35872
36217
  if (userLegacyFallback) {
35873
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.`);
35874
36219
  } else if (legacyUserUnmigrated) {
@@ -37008,7 +37353,7 @@ class SubcSocket {
37008
37353
  return this.sock.localPort ?? null;
37009
37354
  }
37010
37355
  static connect(host, port, deadlineMs) {
37011
- return new Promise((resolve3, reject) => {
37356
+ return new Promise((resolve4, reject) => {
37012
37357
  const sock = net.connect({ host, port });
37013
37358
  sock.setNoDelay(true);
37014
37359
  const timer = setTimeout(() => {
@@ -37017,7 +37362,7 @@ class SubcSocket {
37017
37362
  }, Math.max(0, deadlineMs - Date.now()));
37018
37363
  sock.once("connect", () => {
37019
37364
  clearTimeout(timer);
37020
- resolve3(new SubcSocket(sock));
37365
+ resolve4(new SubcSocket(sock));
37021
37366
  });
37022
37367
  sock.once("error", (err) => {
37023
37368
  clearTimeout(timer);
@@ -37049,7 +37394,7 @@ class SubcSocket {
37049
37394
  }
37050
37395
  if (n === 0)
37051
37396
  return Promise.resolve(new Uint8Array(0));
37052
- return new Promise((resolve3, reject) => {
37397
+ return new Promise((resolve4, reject) => {
37053
37398
  let timer = null;
37054
37399
  if (Number.isFinite(deadlineMs)) {
37055
37400
  const remaining = deadlineMs - Date.now();
@@ -37062,7 +37407,7 @@ class SubcSocket {
37062
37407
  reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
37063
37408
  }, remaining);
37064
37409
  }
37065
- this.waiter = { need: n, resolve: resolve3, reject, timer };
37410
+ this.waiter = { need: n, resolve: resolve4, reject, timer };
37066
37411
  this.tryServe();
37067
37412
  });
37068
37413
  }
@@ -37086,7 +37431,7 @@ class SubcSocket {
37086
37431
  let queued = false;
37087
37432
  let settled = false;
37088
37433
  let timer = null;
37089
- const completed = new Promise((resolve3, reject) => {
37434
+ const completed = new Promise((resolve4, reject) => {
37090
37435
  const settle = (run) => {
37091
37436
  if (settled)
37092
37437
  return;
@@ -37110,7 +37455,7 @@ class SubcSocket {
37110
37455
  if (err) {
37111
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))));
37112
37457
  } else {
37113
- resolve3();
37458
+ resolve4();
37114
37459
  }
37115
37460
  });
37116
37461
  });
@@ -37326,14 +37671,14 @@ class SubcClient {
37326
37671
  const admission = opts.admissionClass ?? AdmissionClass.Normal;
37327
37672
  const corr = this.allocateCorr();
37328
37673
  const key = pendingKey(handle, corr);
37329
- const closed = new Promise((resolve3, reject) => {
37674
+ const closed = new Promise((resolve4, reject) => {
37330
37675
  if (this.closedErr) {
37331
37676
  reject(this.closedErr);
37332
37677
  return;
37333
37678
  }
37334
37679
  this.pending.set(key, {
37335
37680
  handle,
37336
- resolve: () => resolve3(),
37681
+ resolve: () => resolve4(),
37337
37682
  reject,
37338
37683
  onProgress: onEvent,
37339
37684
  timer: null,
@@ -37418,11 +37763,11 @@ class SubcClient {
37418
37763
  const waiters = [];
37419
37764
  for (const pending of this.pending.values()) {
37420
37765
  if (pending.handle === handle && !pending.subscription) {
37421
- waiters.push(new Promise((resolve3) => {
37766
+ waiters.push(new Promise((resolve4) => {
37422
37767
  const previous = pending.onSettle;
37423
37768
  pending.onSettle = () => {
37424
37769
  previous?.();
37425
- resolve3();
37770
+ resolve4();
37426
37771
  };
37427
37772
  }));
37428
37773
  }
@@ -37478,11 +37823,11 @@ class SubcClient {
37478
37823
  const channel = handle?.channel ?? 0;
37479
37824
  const epoch = handle?.epoch ?? 0;
37480
37825
  const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false, admission), channel, epoch, corr, body);
37481
- return new Promise((resolve3, reject) => {
37826
+ return new Promise((resolve4, reject) => {
37482
37827
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
37483
37828
  const pending = {
37484
37829
  handle,
37485
- resolve: resolve3,
37830
+ resolve: resolve4,
37486
37831
  reject,
37487
37832
  onProgress,
37488
37833
  timer: null,
@@ -37556,11 +37901,11 @@ class SubcClient {
37556
37901
  }
37557
37902
  return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error51);
37558
37903
  };
37559
- return new Promise((resolve3, reject) => {
37904
+ return new Promise((resolve4, reject) => {
37560
37905
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
37561
37906
  const pending = {
37562
37907
  handle,
37563
- resolve: resolve3,
37908
+ resolve: resolve4,
37564
37909
  reject,
37565
37910
  onProgress,
37566
37911
  timer: null,
@@ -37948,7 +38293,7 @@ function normalizeConnectOptions(opts) {
37948
38293
  identity: opts.identity,
37949
38294
  targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
37950
38295
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
37951
- sleep: opts.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms))),
38296
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms))),
37952
38297
  timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS
37953
38298
  };
37954
38299
  }
@@ -38005,8 +38350,8 @@ class AsyncPermitPool {
38005
38350
  this.available -= 1;
38006
38351
  return this.releaseOnce();
38007
38352
  }
38008
- await new Promise((resolve3) => {
38009
- this.waiters.push(resolve3);
38353
+ await new Promise((resolve4) => {
38354
+ this.waiters.push(resolve4);
38010
38355
  });
38011
38356
  return this.releaseOnce();
38012
38357
  }
@@ -38062,8 +38407,8 @@ class SubcProvider {
38062
38407
  this.currentConn = currentConn;
38063
38408
  this.opts = opts;
38064
38409
  this.storage = storage;
38065
- this.closed = new Promise((resolve3) => {
38066
- this.resolveClosed = resolve3;
38410
+ this.closed = new Promise((resolve4) => {
38411
+ this.resolveClosed = resolve4;
38067
38412
  });
38068
38413
  this.readLoop(sock, this.generation);
38069
38414
  this.enqueueConnectionState({ state: "connected", epoch: this.connectionEpoch });
@@ -38083,13 +38428,13 @@ class SubcProvider {
38083
38428
  const key = routeKey(handle, corr);
38084
38429
  const timeoutMs = opts.timeoutMs ?? WRITE_TIMEOUT_MS;
38085
38430
  const frame = buildFrame(FrameType.Request, buildFlags(false, opts.priority ?? Priority.Interactive, false, opts.admissionClass ?? AdmissionClass.Normal), handle.channel, handle.epoch, corr, body);
38086
- return await new Promise((resolve3, reject) => {
38431
+ return await new Promise((resolve4, reject) => {
38087
38432
  const timer = setTimeout(() => {
38088
38433
  if (this.pending.delete(key))
38089
38434
  reject(new SubcProviderError("reverse request timed out", "request_timeout"));
38090
38435
  }, timeoutMs);
38091
38436
  this.pending.set(key, {
38092
- resolve: (response) => resolve3(response.body),
38437
+ resolve: (response) => resolve4(response.body),
38093
38438
  reject,
38094
38439
  timer
38095
38440
  });
@@ -38561,7 +38906,7 @@ function normalizeProviderConnectOptions(opts) {
38561
38906
  onBound: opts.onBound,
38562
38907
  onRouteGone: opts.onRouteGone,
38563
38908
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
38564
- sleep: opts.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms))),
38909
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms))),
38565
38910
  restoredDebounceMs: opts.restoredDebounceMs ?? DEFAULT_RESTORED_DEBOUNCE_MS,
38566
38911
  onConnectionState: opts.onConnectionState,
38567
38912
  launchNonce: opts.launchNonce
@@ -38606,7 +38951,7 @@ function errorCode2(err) {
38606
38951
  return;
38607
38952
  }
38608
38953
  async function pauseBeforeStateRetry() {
38609
- await new Promise((resolve3) => setTimeout(resolve3, 0));
38954
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
38610
38955
  }
38611
38956
  function controlFlags() {
38612
38957
  return buildFlags(false, Priority.Passive, false);
@@ -38844,7 +39189,7 @@ function classifyError(value) {
38844
39189
  });
38845
39190
  }
38846
39191
  function wait(ms) {
38847
- return new Promise((resolve3) => setTimeout(resolve3, ms));
39192
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
38848
39193
  }
38849
39194
  function sha256(value) {
38850
39195
  return createHash9("sha256").update(value).digest("hex");
@@ -39323,8 +39668,8 @@ function getEmbeddingProviderIdentity(config2) {
39323
39668
  // ../plugin/src/features/magic-context/memory/embedding-local.ts
39324
39669
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync4 } from "node:fs";
39325
39670
  import { open, stat, unlink, writeFile } from "node:fs/promises";
39326
- import { dirname as dirname5, join as join6 } from "node:path";
39327
- import { pathToFileURL } from "node:url";
39671
+ import { dirname as dirname6, join as join7 } from "node:path";
39672
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
39328
39673
  var LOCK_POLL_MS = 150;
39329
39674
  var STALE_LOCK_MS = 3 * 60000;
39330
39675
  var MAX_LOCK_WAIT_MS = 5 * 60000;
@@ -39363,7 +39708,7 @@ async function acquireModelLoadLock(lockPath) {
39363
39708
  if (Date.now() - waitStart > MAX_LOCK_WAIT_MS) {
39364
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.`);
39365
39710
  }
39366
- await new Promise((resolve3) => setTimeout(resolve3, LOCK_POLL_MS));
39711
+ await new Promise((resolve4) => setTimeout(resolve4, LOCK_POLL_MS));
39367
39712
  }
39368
39713
  }
39369
39714
  }
@@ -39387,8 +39732,8 @@ async function injectWasmOrtForElectron() {
39387
39732
  const { createRequire: createRequireFn } = await import("node:module");
39388
39733
  const requireFn = createRequireFn(import.meta.url);
39389
39734
  const mainEntry = requireFn.resolve("onnxruntime-web");
39390
- const distDir = dirname5(mainEntry);
39391
- const wasmPathsPrefix = `${pathToFileURL(distDir).href}/`;
39735
+ const distDir = dirname6(mainEntry);
39736
+ const wasmPathsPrefix = `${pathToFileURL2(distDir).href}/`;
39392
39737
  if (ortWeb.env?.wasm) {
39393
39738
  ortWeb.env.wasm.wasmPaths = wasmPathsPrefix;
39394
39739
  }
@@ -39524,7 +39869,7 @@ class LocalEmbeddingProvider {
39524
39869
  if (LogLevel && "ERROR" in LogLevel) {
39525
39870
  env.logLevel = LogLevel.ERROR;
39526
39871
  }
39527
- const modelCacheDir = join6(getMagicContextStorageDir(), "models");
39872
+ const modelCacheDir = join7(getMagicContextStorageDir(), "models");
39528
39873
  try {
39529
39874
  if (shouldEnforcePrivateStoragePermissions()) {
39530
39875
  mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
@@ -39541,7 +39886,7 @@ class LocalEmbeddingProvider {
39541
39886
  log("[magic-context] could not create model cache dir, using library default");
39542
39887
  }
39543
39888
  const createPipeline = transformersModule.pipeline;
39544
- const lockPath = join6(modelCacheDir, ".load.lock");
39889
+ const lockPath = join7(modelCacheDir, ".load.lock");
39545
39890
  const releaseLock = await acquireModelLoadLock(lockPath);
39546
39891
  const stopHeartbeat = startLockHeartbeat(lockPath);
39547
39892
  try {
@@ -39568,7 +39913,7 @@ class LocalEmbeddingProvider {
39568
39913
  }
39569
39914
  const delayMs = 300 * attempt + Math.floor(Math.random() * 200);
39570
39915
  log(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
39571
- await new Promise((resolve3) => setTimeout(resolve3, delayMs));
39916
+ await new Promise((resolve4) => setTimeout(resolve4, delayMs));
39572
39917
  }
39573
39918
  }
39574
39919
  if (this.pipeline) {
@@ -39601,8 +39946,8 @@ class LocalEmbeddingProvider {
39601
39946
  if (this.inFlight === 0) {
39602
39947
  return Promise.resolve();
39603
39948
  }
39604
- return new Promise((resolve3) => {
39605
- this.inFlightWaiters.push(resolve3);
39949
+ return new Promise((resolve4) => {
39950
+ this.inFlightWaiters.push(resolve4);
39606
39951
  });
39607
39952
  }
39608
39953
  finishInFlight() {
@@ -41300,7 +41645,7 @@ async function runShadowWorker() {
41300
41645
  }
41301
41646
  processed += item.ids.length;
41302
41647
  processedBytes += itemBytes;
41303
- await new Promise((resolve3) => setTimeout(resolve3, 0));
41648
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
41304
41649
  }
41305
41650
  }
41306
41651
  function registerProjectInObservationMode(db, projectIdentity, sourceDirectory, failedConfig, failureSummary) {
@@ -41661,7 +42006,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
41661
42006
  if (Date.now() - attemptStart >= EMBED_SLOW_FAILURE_NO_RETRY_MS)
41662
42007
  break;
41663
42008
  if (attempt < EMBED_SLICE_RETRY_ATTEMPTS - 1) {
41664
- 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));
41665
42010
  }
41666
42011
  }
41667
42012
  embedded += persistedIds.size;
@@ -41746,7 +42091,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
41746
42091
  }
41747
42092
  embedded += n;
41748
42093
  options?.onProgress?.({ embedded: Math.min(embedded, total), total });
41749
- await new Promise((resolve3) => setTimeout(resolve3, 0));
42094
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
41750
42095
  }
41751
42096
  } finally {
41752
42097
  clearInterval(renewal);
@@ -48107,7 +48452,7 @@ function getMemoryVerifications(db, memoryIds) {
48107
48452
  }
48108
48453
  // ../plugin/src/features/magic-context/memory/verification-paths.ts
48109
48454
  import { execFile } from "node:child_process";
48110
- 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";
48111
48456
  import path3 from "node:path";
48112
48457
  import { promisify } from "node:util";
48113
48458
  var execFileAsync = promisify(execFile);
@@ -48136,7 +48481,7 @@ function isWithin(root, candidate) {
48136
48481
  }
48137
48482
  function safeRealpath(value) {
48138
48483
  try {
48139
- return realpathSync2.native(value);
48484
+ return realpathSync3.native(value);
48140
48485
  } catch {
48141
48486
  return null;
48142
48487
  }
@@ -48214,7 +48559,7 @@ function verificationFileExists(baseRoot, filePath) {
48214
48559
  return false;
48215
48560
  const root = path3.resolve(baseRoot);
48216
48561
  const candidate = path3.resolve(root, filePath);
48217
- return isWithin(root, candidate) && existsSync10(candidate);
48562
+ return isWithin(root, candidate) && existsSync11(candidate);
48218
48563
  }
48219
48564
  async function normalizeVerificationFiles(args) {
48220
48565
  const cwd = path3.resolve(args.cwd);
@@ -48247,7 +48592,7 @@ async function normalizeVerificationFiles(args) {
48247
48592
  warnings.push(`Skipped verification path "${value}" because it is the repo/project root.`);
48248
48593
  continue;
48249
48594
  }
48250
- if (existsSync10(candidate)) {
48595
+ if (existsSync11(candidate)) {
48251
48596
  try {
48252
48597
  if (statSync7(candidate).isDirectory()) {
48253
48598
  warnings.push(`Skipped verification path "${value}" because it is a directory.`);
@@ -48278,7 +48623,7 @@ async function normalizeVerificationFiles(args) {
48278
48623
  }
48279
48624
  normalized.push(tracked);
48280
48625
  } else {
48281
- if (!existsSync10(candidate)) {
48626
+ if (!existsSync11(candidate)) {
48282
48627
  warnings.push(`Skipped verification path "${value}" because it does not exist.`);
48283
48628
  continue;
48284
48629
  }
@@ -48767,6 +49112,494 @@ function createCtxMemoryTool(deps) {
48767
49112
  };
48768
49113
  }
48769
49114
 
49115
+ // ../plugin/src/features/magic-context/smart-notes/condition-compiler.ts
49116
+ import { existsSync as existsSync12 } from "node:fs";
49117
+ import { isAbsolute as isAbsolute5 } from "node:path";
49118
+
49119
+ // ../retina-local-fs/src/path-fence.ts
49120
+ import { lstat, readlink, realpath } from "node:fs/promises";
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";
49123
+
49124
+ // ../retina-local-fs/src/errors.ts
49125
+ class ProviderError extends Error {
49126
+ code;
49127
+ constructor(code, message) {
49128
+ super(message);
49129
+ this.code = code;
49130
+ this.name = "ProviderError";
49131
+ }
49132
+ }
49133
+
49134
+ // ../retina-local-fs/src/path-fence.ts
49135
+ async function resolveAndFenceProviderPath(configuredPath, options) {
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());
49147
+ let home;
49148
+ try {
49149
+ home = await realpath(configuredHomePath);
49150
+ } catch (error51) {
49151
+ throw fsError(configuredHomePath, error51);
49152
+ }
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 };
49156
+ }
49157
+ async function canonicalPath(path4, allowMissing) {
49158
+ try {
49159
+ return await realpath(path4);
49160
+ } catch (error51) {
49161
+ if (!allowMissing || !isMissingError(error51)) {
49162
+ throw fsError(path4, error51);
49163
+ }
49164
+ const suffix = [];
49165
+ let candidate = path4;
49166
+ while (true) {
49167
+ try {
49168
+ const metadata = await lstat(candidate);
49169
+ if (metadata.isSymbolicLink()) {
49170
+ const target2 = await readlink(candidate);
49171
+ const resolvedTarget = resolve4(dirname7(candidate), target2);
49172
+ return canonicalPath(join8(resolvedTarget, ...suffix), true);
49173
+ }
49174
+ } catch (candidateError) {
49175
+ if (!isMissingError(candidateError)) {
49176
+ throw fsError(path4, candidateError);
49177
+ }
49178
+ }
49179
+ const parent = dirname7(candidate);
49180
+ if (parent === candidate) {
49181
+ throw fsError(path4, error51);
49182
+ }
49183
+ suffix.unshift(basename3(candidate));
49184
+ candidate = parent;
49185
+ try {
49186
+ return join8(await realpath(candidate), ...suffix);
49187
+ } catch (parentError) {
49188
+ if (!isMissingError(parentError)) {
49189
+ throw fsError(path4, parentError);
49190
+ }
49191
+ }
49192
+ }
49193
+ }
49194
+ }
49195
+ function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join8(resolve4(homeDirectory), ".local", "share")) {
49196
+ const cortexkitRoot = join8(resolve4(dataDirectory), "cortexkit");
49197
+ const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
49198
+ const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
49199
+ const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
49200
+ const pathParts = canonicalPath2.split(sep).filter(Boolean);
49201
+ const name = basename3(canonicalPath2);
49202
+ const catalogDirectoryCarveIn = pathParts.includes("catalog");
49203
+ const moduleBinCarveIn = parts.length >= 2 && parts[1] === "bin";
49204
+ const catalogJsonCarveIn = name.endsWith(".json") && name.includes("catalog");
49205
+ const rootWithoutCarveIns = insideCortexkit && (parts[0] === "run" || parts[0] === "magic-context");
49206
+ if (!rootWithoutCarveIns && (catalogDirectoryCarveIn || moduleBinCarveIn || catalogJsonCarveIn)) {
49207
+ return false;
49208
+ }
49209
+ const inFencedRoot = insideCortexkit && ["plexus", "claustrum", "staging", "run", "magic-context"].includes(parts[0] ?? "");
49210
+ const fencedBasename = name.includes("binding-key") || name.endsWith(".handle");
49211
+ const plexusStore = insideCortexkit && parts[0] === "plexus" && name.startsWith("store.db");
49212
+ return inFencedRoot || fencedBasename || plexusStore;
49213
+ }
49214
+ function fsError(path4, error51) {
49215
+ const message = error51 instanceof Error ? error51.message : String(error51);
49216
+ return new ProviderError("unreadable_path", `Could not read ${path4}: ${message}`);
49217
+ }
49218
+ function isMissingError(error51) {
49219
+ return error51 !== null && typeof error51 === "object" && "code" in error51 && (error51.code === "ENOENT" || error51.code === "ENOTDIR");
49220
+ }
49221
+
49222
+ // ../retina-local-fs/src/provider.ts
49223
+ import { execFile as execFile2 } from "node:child_process";
49224
+ import { promisify as promisify2 } from "node:util";
49225
+ var execFileAsync2 = promisify2(execFile2);
49226
+ function parseSemver(value) {
49227
+ const match = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
49228
+ if (!match) {
49229
+ throw new ProviderError("invalid_config", `Invalid semantic version: ${value}`);
49230
+ }
49231
+ return {
49232
+ major: Number(match[1]),
49233
+ minor: Number(match[2]),
49234
+ patch: Number(match[3]),
49235
+ prerelease: match[4] ? match[4].split(".").map((part) => /^\d+$/.test(part) ? Number(part) : part) : []
49236
+ };
49237
+ }
49238
+ function validateProviderConfig(input) {
49239
+ try {
49240
+ return { success: true, config: parseConfig(input) };
49241
+ } catch (error51) {
49242
+ return {
49243
+ success: false,
49244
+ reason: error51 instanceof Error ? error51.message : String(error51)
49245
+ };
49246
+ }
49247
+ }
49248
+ function parseConfig(value) {
49249
+ const config2 = requireObject(value, "config");
49250
+ if ("any" in config2) {
49251
+ requireOnlyKeys(config2, ["any"], "compound config");
49252
+ if (!Array.isArray(config2.any) || config2.any.length < 1 || config2.any.length > 4) {
49253
+ invalid("config.any must contain between 1 and 4 predicates");
49254
+ }
49255
+ return { any: config2.any.map(parseAtomicPredicate) };
49256
+ }
49257
+ return parseAtomicPredicate(config2);
49258
+ }
49259
+ function parseAtomicPredicate(value) {
49260
+ const predicate = requireObject(value, "predicate");
49261
+ if (typeof predicate.kind !== "string") {
49262
+ invalid("predicate.kind must be a string");
49263
+ }
49264
+ switch (predicate.kind) {
49265
+ case "file_contains":
49266
+ requireOnlyKeys(predicate, ["kind", "path", "needle", "absent", "resolved_path_exists"], predicate.kind);
49267
+ return {
49268
+ kind: predicate.kind,
49269
+ path: requireString(predicate.path, "path"),
49270
+ needle: requireString(predicate.needle, "needle", true),
49271
+ ...optionalBoolean(predicate.absent, "absent") === undefined ? {} : { absent: predicate.absent },
49272
+ ...predicateAudit(predicate)
49273
+ };
49274
+ case "path_exists":
49275
+ requireOnlyKeys(predicate, ["kind", "path", "gone", "resolved_path_exists"], predicate.kind);
49276
+ return {
49277
+ kind: predicate.kind,
49278
+ path: requireString(predicate.path, "path"),
49279
+ ...optionalBoolean(predicate.gone, "gone") === undefined ? {} : { gone: predicate.gone },
49280
+ ...predicateAudit(predicate)
49281
+ };
49282
+ case "mtime_after":
49283
+ requireOnlyKeys(predicate, ["kind", "path", "since_ms", "resolved_path_exists"], predicate.kind);
49284
+ return {
49285
+ kind: predicate.kind,
49286
+ path: requireString(predicate.path, "path"),
49287
+ since_ms: requireFiniteNumber(predicate.since_ms, "since_ms"),
49288
+ ...predicateAudit(predicate)
49289
+ };
49290
+ case "git_commit_after":
49291
+ requireOnlyKeys(predicate, ["kind", "repo_path", "ref", "sha", "resolved_path_exists"], predicate.kind);
49292
+ return {
49293
+ kind: predicate.kind,
49294
+ repo_path: requireString(predicate.repo_path, "repo_path"),
49295
+ sha: requireString(predicate.sha, "sha"),
49296
+ ...predicate.ref === undefined ? {} : { ref: requireString(predicate.ref, "ref") },
49297
+ ...predicateAudit(predicate)
49298
+ };
49299
+ case "git_tag_matching": {
49300
+ requireOnlyKeys(predicate, ["kind", "repo_path", "pattern", "above", "resolved_path_exists"], predicate.kind);
49301
+ const above = predicate.above === undefined ? undefined : requireString(predicate.above, "above");
49302
+ if (above !== undefined) {
49303
+ parseSemver(above);
49304
+ }
49305
+ return {
49306
+ kind: predicate.kind,
49307
+ repo_path: requireString(predicate.repo_path, "repo_path"),
49308
+ pattern: requireString(predicate.pattern, "pattern"),
49309
+ ...above === undefined ? {} : { above },
49310
+ ...predicateAudit(predicate)
49311
+ };
49312
+ }
49313
+ default:
49314
+ invalid(`Unsupported predicate kind: ${predicate.kind}`);
49315
+ }
49316
+ }
49317
+ function requireObject(value, field) {
49318
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
49319
+ invalid(`${field} must be an object`);
49320
+ }
49321
+ return value;
49322
+ }
49323
+ function requireOnlyKeys(value, allowed, field) {
49324
+ const unknown4 = Object.keys(value).filter((key) => !allowed.includes(key));
49325
+ if (unknown4.length > 0) {
49326
+ invalid(`${field} contains unknown field(s): ${unknown4.join(", ")}`);
49327
+ }
49328
+ }
49329
+ function requireString(value, field, allowEmpty = false) {
49330
+ if (typeof value !== "string" || !allowEmpty && value.length === 0) {
49331
+ invalid(`${field} must be ${allowEmpty ? "a string" : "a non-empty string"}`);
49332
+ }
49333
+ return value;
49334
+ }
49335
+ function predicateAudit(predicate) {
49336
+ const exists = optionalBoolean(predicate.resolved_path_exists, "resolved_path_exists");
49337
+ return exists === undefined ? {} : { resolved_path_exists: exists };
49338
+ }
49339
+ function optionalBoolean(value, field) {
49340
+ if (value !== undefined && typeof value !== "boolean") {
49341
+ invalid(`${field} must be a boolean`);
49342
+ }
49343
+ return value;
49344
+ }
49345
+ function requireFiniteNumber(value, field) {
49346
+ if (typeof value !== "number" || !Number.isFinite(value)) {
49347
+ invalid(`${field} must be a finite number`);
49348
+ }
49349
+ return value;
49350
+ }
49351
+ function invalid(message) {
49352
+ throw new ProviderError("invalid_config", message);
49353
+ }
49354
+
49355
+ // ../plugin/src/features/magic-context/smart-notes/condition-compiler.ts
49356
+ var RETINA_LOCAL_FS_PROVIDER = "local-fs";
49357
+ var VALUE = String.raw`(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)`;
49358
+ async function compileSurfaceCondition(surfaceCondition, options) {
49359
+ const plainReason = unsafeGrammarReason(surfaceCondition);
49360
+ if (plainReason)
49361
+ return { status: "plain", reason: plainReason };
49362
+ const parsed = parseCondition(surfaceCondition, options.projectPath);
49363
+ if (parsed === null)
49364
+ return { status: "plain" };
49365
+ const now = (options.now ?? Date.now)();
49366
+ const resolvePath = options.resolvePath ?? (async (path4) => {
49367
+ const resolved = await resolveAndFenceProviderPath(path4, {
49368
+ allowMissing: true,
49369
+ homeDirectory: options.homeDirectory,
49370
+ cwd: options.projectPath
49371
+ });
49372
+ return { path: resolved, exists: existsSync12(resolved) };
49373
+ });
49374
+ let predicates;
49375
+ try {
49376
+ predicates = [];
49377
+ for (const predicate of parsed) {
49378
+ predicates.push(await resolvePredicate(predicate, resolvePath, now));
49379
+ }
49380
+ } catch (error51) {
49381
+ const code = error51 !== null && typeof error51 === "object" && "code" in error51 ? error51.code : undefined;
49382
+ return {
49383
+ status: "refused",
49384
+ reason: code === "fenced_path" ? "fenced path" : "path resolution failed"
49385
+ };
49386
+ }
49387
+ const candidate = predicates.length === 1 ? predicates[0] : { any: predicates };
49388
+ const validation = validateProviderConfig(candidate);
49389
+ if (!validation.success) {
49390
+ return {
49391
+ status: "refused",
49392
+ reason: `provider schema: ${singleLine(validation.reason)}`.slice(0, 180)
49393
+ };
49394
+ }
49395
+ return {
49396
+ status: "compiled",
49397
+ provider: RETINA_LOCAL_FS_PROVIDER,
49398
+ config: validation.config,
49399
+ compiledAt: now
49400
+ };
49401
+ }
49402
+ function conditionCompileStorageFields(result) {
49403
+ if (result.status === "compiled") {
49404
+ return {
49405
+ compiledProvider: result.provider,
49406
+ compiledConfig: JSON.stringify(result.config),
49407
+ compiledAt: result.compiledAt,
49408
+ compileStatus: result.status
49409
+ };
49410
+ }
49411
+ return {
49412
+ compiledProvider: null,
49413
+ compiledConfig: null,
49414
+ compiledAt: null,
49415
+ compileStatus: result.status
49416
+ };
49417
+ }
49418
+ function conditionCompileReplySuffix(result) {
49419
+ if (result.status === "compiled") {
49420
+ return `
49421
+ - Retina provider: ${result.provider}`;
49422
+ }
49423
+ if (result.status === "refused") {
49424
+ return `
49425
+ - Retina compile refused: ${result.reason}`;
49426
+ }
49427
+ return "";
49428
+ }
49429
+ function parseCondition(surfaceCondition, projectPath) {
49430
+ const trimmed = surfaceCondition.trim();
49431
+ const either = trimmed.match(/^either\s+(.+)$/i);
49432
+ if (!either) {
49433
+ const predicate = parseAtomicCondition(trimmed, projectPath);
49434
+ return predicate ? [predicate] : null;
49435
+ }
49436
+ const clauses = splitOrClauses(either[1]);
49437
+ if (clauses.length < 2)
49438
+ return null;
49439
+ const predicates = clauses.map((clause) => parseAtomicCondition(clause, projectPath));
49440
+ return predicates.every((predicate) => predicate !== null) ? predicates : null;
49441
+ }
49442
+ function parseAtomicCondition(text, projectPath) {
49443
+ const fileContains = text.match(new RegExp(`^(?:when\\s+)?file\\s+(${VALUE})\\s+(no longer contains|contains)\\s+(${VALUE})$`, "i"));
49444
+ if (fileContains) {
49445
+ const path4 = unquote(fileContains[1]);
49446
+ const needle = unquote(fileContains[3].trim());
49447
+ if (path4 === null || needle === null)
49448
+ return null;
49449
+ return {
49450
+ kind: "file_contains",
49451
+ path: path4,
49452
+ needle,
49453
+ ...fileContains[2].toLowerCase() === "no longer contains" ? { absent: true } : {}
49454
+ };
49455
+ }
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"));
49457
+ if (commit) {
49458
+ const repoPath = unquote(commit[1]);
49459
+ if (repoPath === null)
49460
+ return null;
49461
+ return {
49462
+ kind: "git_commit_after",
49463
+ repo_path: repoPath,
49464
+ sha: commit[2]
49465
+ };
49466
+ }
49467
+ const tag = text.match(new RegExp(`^(?:when\\s+)?a\\s+tag\\s+(?:(?:matching\\s+(${VALUE})(?:\\s+above\\s+semver\\s+(${VALUE}))?)|(?:above\\s+semver\\s+(${VALUE})))\\s+appears(?:\\s+in\\s+(?:repo(?:sitory)?\\s+)?(${VALUE}))?$`, "i"));
49468
+ if (tag) {
49469
+ const pattern2 = tag[1] ? unquote(tag[1]) : "*";
49470
+ const above = unquote(tag[2] ?? tag[3] ?? "");
49471
+ const repoPath = tag[4] ? unquote(tag[4]) : projectPath;
49472
+ if (pattern2 === null || above === null || repoPath === null)
49473
+ return null;
49474
+ return {
49475
+ kind: "git_tag_matching",
49476
+ repo_path: repoPath,
49477
+ pattern: pattern2,
49478
+ ...above.length > 0 ? { above } : {}
49479
+ };
49480
+ }
49481
+ const mtime = text.match(new RegExp(`^(?:when\\s+)?(?:file\\s+)?(${VALUE})\\s+(changes|is rebuilt|mtime moves)$`, "i"));
49482
+ if (mtime) {
49483
+ const path4 = unquote(mtime[1]);
49484
+ if (path4 === null)
49485
+ return null;
49486
+ return {
49487
+ kind: "mtime_after",
49488
+ path: path4
49489
+ };
49490
+ }
49491
+ const pathExists = text.match(new RegExp(`^(?:when\\s+)?(?:path\\s+)?(${VALUE})\\s+(exists|is gone)$`, "i"));
49492
+ if (pathExists) {
49493
+ const path4 = unquote(pathExists[1]);
49494
+ if (path4 === null)
49495
+ return null;
49496
+ return {
49497
+ kind: "path_exists",
49498
+ path: path4,
49499
+ ...pathExists[2].toLowerCase() === "is gone" ? { gone: true } : {}
49500
+ };
49501
+ }
49502
+ return null;
49503
+ }
49504
+ async function resolvePredicate(predicate, resolvePath, now) {
49505
+ const configuredPath = "repo_path" in predicate ? predicate.repo_path : predicate.path;
49506
+ const resolved = await resolvePath(configuredPath);
49507
+ const sourceIsResolvable = isAbsolute5(configuredPath) || configuredPath === "~" || configuredPath.startsWith("~/");
49508
+ const audit = sourceIsResolvable && resolved.exists ? {} : { resolved_path_exists: false };
49509
+ switch (predicate.kind) {
49510
+ case "file_contains":
49511
+ return { ...predicate, path: resolved.path, ...audit };
49512
+ case "path_exists":
49513
+ return { ...predicate, path: resolved.path, ...audit };
49514
+ case "mtime_after":
49515
+ return { kind: predicate.kind, path: resolved.path, since_ms: now, ...audit };
49516
+ case "git_commit_after":
49517
+ return { ...predicate, repo_path: resolved.path, ...audit };
49518
+ case "git_tag_matching":
49519
+ return { ...predicate, repo_path: resolved.path, ...audit };
49520
+ }
49521
+ }
49522
+ function splitOrClauses(text) {
49523
+ const clauses = [];
49524
+ let start = 0;
49525
+ let quote = null;
49526
+ let escaped = false;
49527
+ for (let index = 0;index < text.length; index += 1) {
49528
+ const character = text[index];
49529
+ if (escaped) {
49530
+ escaped = false;
49531
+ continue;
49532
+ }
49533
+ if (quote && character === "\\") {
49534
+ escaped = true;
49535
+ continue;
49536
+ }
49537
+ if (character === '"' || character === "'") {
49538
+ quote = quote === character ? null : quote === null ? character : quote;
49539
+ continue;
49540
+ }
49541
+ if (quote !== null)
49542
+ continue;
49543
+ const separator = text.slice(index).match(/^\s+or\s+/i);
49544
+ if (!separator)
49545
+ continue;
49546
+ clauses.push(text.slice(start, index).trim());
49547
+ index += separator[0].length - 1;
49548
+ start = index + 1;
49549
+ }
49550
+ clauses.push(text.slice(start).trim());
49551
+ return clauses.filter(Boolean);
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
+ }
49580
+ function unquote(value) {
49581
+ const quote = value[0];
49582
+ const final = value.at(-1);
49583
+ const startsQuoted = quote === '"' || quote === "'";
49584
+ const endsQuoted = final === '"' || final === "'";
49585
+ if (!startsQuoted && !endsQuoted)
49586
+ return value;
49587
+ if (!startsQuoted || final !== quote || value.length < 2)
49588
+ return null;
49589
+ if (quote === '"') {
49590
+ try {
49591
+ const parsed = JSON.parse(value);
49592
+ return typeof parsed === "string" ? parsed : null;
49593
+ } catch {
49594
+ return null;
49595
+ }
49596
+ }
49597
+ return value.slice(1, -1).replace(/\\'/g, "'").replace(/\\\\/g, "\\");
49598
+ }
49599
+ function singleLine(value) {
49600
+ return value.replace(/\s+/g, " ").trim();
49601
+ }
49602
+
48770
49603
  // ../plugin/src/tools/ctx-note/constants.ts
48771
49604
  var CTX_NOTE_DESCRIPTION = `Working notes for this session's future — reminders, follow-ups, and things to revisit later.
48772
49605
 
@@ -48901,16 +49734,20 @@ function createCtxNoteTool(deps) {
48901
49734
  if (!projectIdentity) {
48902
49735
  return err3("Error: Could not resolve project identity for smart note.");
48903
49736
  }
49737
+ const compilation = await compileSurfaceCondition(surfaceCondition, {
49738
+ projectPath: ctx.cwd
49739
+ });
48904
49740
  const note2 = addNote(deps.db, "smart", {
48905
49741
  content,
48906
49742
  sessionId,
48907
49743
  projectPath: projectIdentity,
48908
49744
  surfaceCondition,
48909
- anchorOrdinal
49745
+ anchorOrdinal,
49746
+ ...conditionCompileStorageFields(compilation)
48910
49747
  });
48911
49748
  return ok3(`Created smart note #${note2.id}. Dreamer will evaluate the condition during nightly runs:
48912
49749
  - Content: ${content}
48913
- - Condition: ${surfaceCondition}`);
49750
+ - Condition: ${surfaceCondition}${conditionCompileReplySuffix(compilation)}`);
48914
49751
  }
48915
49752
  const note = addNote(deps.db, "session", {
48916
49753
  sessionId,
@@ -48940,8 +49777,15 @@ function createCtxNoteTool(deps) {
48940
49777
  const updates = {};
48941
49778
  if (params.content?.trim())
48942
49779
  updates.content = params.content.trim();
48943
- if (params.surface_condition?.trim())
48944
- updates.surfaceCondition = params.surface_condition.trim();
49780
+ let compilation;
49781
+ if (params.surface_condition?.trim()) {
49782
+ const surfaceCondition = params.surface_condition.trim();
49783
+ updates.surfaceCondition = surfaceCondition;
49784
+ compilation = await compileSurfaceCondition(surfaceCondition, {
49785
+ projectPath: ctx.cwd
49786
+ });
49787
+ Object.assign(updates, conditionCompileStorageFields(compilation));
49788
+ }
48945
49789
  if (!updates.content && !updates.surfaceCondition) {
48946
49790
  return err3("Error: Provide 'content' and/or 'surface_condition' to update.");
48947
49791
  }
@@ -48963,7 +49807,7 @@ function createCtxNoteTool(deps) {
48963
49807
  parts.push(`condition: ${updates.surfaceCondition}`);
48964
49808
  return ok3(`Updated note #${params.note_id}
48965
49809
  - ${parts.join(`
48966
- - `)}`);
49810
+ - `)}${compilation ? conditionCompileReplySuffix(compilation) : ""}`);
48967
49811
  }
48968
49812
  const limit = typeof params.limit === "number" && params.limit > 0 ? Math.floor(params.limit) : DEFAULT_READ_LIMIT;
48969
49813
  const offset = typeof params.offset === "number" && params.offset > 0 ? Math.floor(params.offset) : 0;
@@ -49225,9 +50069,9 @@ function createCtxReduceTool(deps) {
49225
50069
  }
49226
50070
 
49227
50071
  // ../plugin/src/features/magic-context/git-commits/git-log-reader.ts
49228
- import { execFile as execFile2 } from "node:child_process";
49229
- import { promisify as promisify2 } from "node:util";
49230
- var execFileAsync2 = promisify2(execFile2);
50072
+ import { execFile as execFile3 } from "node:child_process";
50073
+ import { promisify as promisify3 } from "node:util";
50074
+ var execFileAsync3 = promisify3(execFile3);
49231
50075
  var GIT_TIMEOUT_MS3 = 1e4;
49232
50076
  var DEFAULT_MAX_COMMITS = 5000;
49233
50077
  var RECORD_SEPARATOR = "\x1E";
@@ -49259,7 +50103,7 @@ async function readGitCommitsResult(directory, options = {}) {
49259
50103
  }
49260
50104
  let stdout;
49261
50105
  try {
49262
- const result = await execFileAsync2("git", args, {
50106
+ const result = await execFileAsync3("git", args, {
49263
50107
  cwd: directory,
49264
50108
  timeout: GIT_TIMEOUT_MS3,
49265
50109
  maxBuffer: 32 * 1024 * 1024,
@@ -51520,8 +52364,8 @@ class BoundedSessionMap {
51520
52364
 
51521
52365
  // ../plugin/src/features/magic-context/compaction-marker.ts
51522
52366
  import { createHash as createHash16 } from "node:crypto";
51523
- import { existsSync as existsSync11 } from "node:fs";
51524
- import { join as join7 } from "node:path";
52367
+ import { existsSync as existsSync13 } from "node:fs";
52368
+ import { join as join9 } from "node:path";
51525
52369
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
51526
52370
  var ID_PREFIX_HEX_LENGTH = 12;
51527
52371
  var ID_SUFFIX_LENGTH = 14;
@@ -51547,7 +52391,7 @@ function generatePartId(timestampMs, counter = 0n, identity = "") {
51547
52391
  return generateId("prt", timestampMs, counter, identity);
51548
52392
  }
51549
52393
  function getOpenCodeDbPath2() {
51550
- return join7(getDataDir(), "opencode", "opencode.db");
52394
+ return join9(getDataDir(), "opencode", "opencode.db");
51551
52395
  }
51552
52396
  var cachedWriteDb = null;
51553
52397
  var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
@@ -51592,7 +52436,7 @@ function getWritableOpenCodeDb() {
51592
52436
  closeQuietly(cachedWriteDb.db);
51593
52437
  } catch {}
51594
52438
  }
51595
- if (!existsSync11(dbPath)) {
52439
+ if (!existsSync13(dbPath)) {
51596
52440
  throw new Error(`OpenCode database not found at ${dbPath} (is OpenCode installed?)`);
51597
52441
  }
51598
52442
  const db = new Database(dbPath);
@@ -51868,24 +52712,52 @@ function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEn
51868
52712
  // ../plugin/src/hooks/magic-context/compartment-render-epoch.ts
51869
52713
  var COMPARTMENT_RENDER_EPOCH = "cre2";
51870
52714
  var EPOCH_COMPONENT_PREFIX = "|compartment-render:";
51871
- function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH) {
51872
- if (compartmentRenderEpoch === null)
51873
- return upgradeState;
51874
- 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;
51875
52738
  }
51876
52739
  function decodeCachedM0UpgradeIdentity(value) {
51877
52740
  if (value === null) {
51878
- return { upgradeState: null, compartmentRenderEpoch: null };
51879
- }
51880
- const componentIndex = value.lastIndexOf(EPOCH_COMPONENT_PREFIX);
51881
- if (componentIndex < 0) {
51882
- return { upgradeState: value, compartmentRenderEpoch: null };
52741
+ return {
52742
+ upgradeState: null,
52743
+ compartmentRenderEpoch: null,
52744
+ muralEnabled: null,
52745
+ renderBudgetIdentity: null
52746
+ };
51883
52747
  }
51884
- const upgradeState = value.slice(0, componentIndex);
51885
- 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);
51886
52756
  return {
51887
52757
  upgradeState: upgradeState.length > 0 ? upgradeState : null,
51888
- 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)
51889
52761
  };
51890
52762
  }
51891
52763
 
@@ -52705,4 +53577,4 @@ function registerMagicContextTools(pi, opts) {
52705
53577
  }
52706
53578
  }
52707
53579
 
52708
- 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, 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 };