@cortexkit/pi-magic-context 0.35.1 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,
@@ -8664,7 +8664,6 @@ import {
8664
8664
  cpSync,
8665
8665
  existsSync as existsSync4,
8666
8666
  mkdirSync as mkdirSync2,
8667
- mkdtempSync,
8668
8667
  readdirSync,
8669
8668
  readFileSync as readFileSync3,
8670
8669
  statSync as statSync3,
@@ -9785,7 +9784,11 @@ var MIGRATIONS = [
9785
9784
  updated_at INTEGER NOT NULL,
9786
9785
  last_checked_at INTEGER,
9787
9786
  ready_at INTEGER,
9788
- ready_reason TEXT
9787
+ ready_reason TEXT,
9788
+ compiled_provider TEXT,
9789
+ compiled_config TEXT,
9790
+ compiled_at INTEGER,
9791
+ compile_status TEXT CHECK(compile_status IN ('compiled', 'plain', 'refused'))
9789
9792
  );
9790
9793
  CREATE INDEX IF NOT EXISTS idx_notes_session_status ON notes(session_id, status);
9791
9794
  CREATE INDEX IF NOT EXISTS idx_notes_project_status ON notes(project_path, status);
@@ -11694,6 +11697,18 @@ var MIGRATIONS = [
11694
11697
  return;
11695
11698
  ensureColumn(db, "memories", "mural_cue_rejection_count", "INTEGER NOT NULL DEFAULT 0");
11696
11699
  }
11700
+ },
11701
+ {
11702
+ version: 76,
11703
+ description: "persist retina provider compilation for smart-note conditions",
11704
+ up(db) {
11705
+ if (!tableExists2(db, "notes"))
11706
+ return;
11707
+ ensureColumn(db, "notes", "compiled_provider", "TEXT");
11708
+ ensureColumn(db, "notes", "compiled_config", "TEXT");
11709
+ ensureColumn(db, "notes", "compiled_at", "INTEGER");
11710
+ ensureColumn(db, "notes", "compile_status", "TEXT CHECK(compile_status IN ('compiled', 'plain', 'refused'))");
11711
+ }
11697
11712
  }
11698
11713
  ];
11699
11714
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -11918,11 +11933,11 @@ var tokenizer;
11918
11933
  function getTokenizer() {
11919
11934
  if (tokenizer)
11920
11935
  return tokenizer;
11921
- const tokenizerModule = requireFromThisModule("ai-tokenizer");
11936
+ const tokenizerModule = requireFromThisModule("ai-" + "tokenizer");
11922
11937
  const Tokenizer = tokenizerModule.default ?? tokenizerModule.Tokenizer;
11923
11938
  if (!Tokenizer)
11924
11939
  throw new Error("ai-tokenizer does not expose a Tokenizer constructor");
11925
- const claudeEncoding = requireFromThisModule("ai-tokenizer/encoding/claude");
11940
+ const claudeEncoding = requireFromThisModule("ai-tokenizer/encoding/" + "claude");
11926
11941
  tokenizer = new Tokenizer(claudeEncoding);
11927
11942
  return tokenizer;
11928
11943
  }
@@ -12306,7 +12321,7 @@ function getSchemaFenceRejection() {
12306
12321
  function getMigrationOnOpenRefusal() {
12307
12322
  return lastMigrationOnOpenRefusal;
12308
12323
  }
12309
- var LATEST_SUPPORTED_VERSION = 75;
12324
+ var LATEST_SUPPORTED_VERSION = 76;
12310
12325
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
12311
12326
  var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
12312
12327
  var storagePermissionFs = defaultStoragePermissionFs;
@@ -12342,12 +12357,6 @@ function resolveDatabasePath(dbPathOverride) {
12342
12357
  if (dbPathOverride) {
12343
12358
  return { dbDir: dirname2(dbPathOverride), dbPath: dbPathOverride };
12344
12359
  }
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") };
12349
- }
12350
- if (false) {}
12351
12360
  const dbDir = getMagicContextStorageDir();
12352
12361
  return { dbDir, dbPath: join3(dbDir, "context.db") };
12353
12362
  }
@@ -17868,6 +17877,11 @@ var NOTE_CHECK_STATUSES = new Set([
17868
17877
  "failing",
17869
17878
  "fallback"
17870
17879
  ]);
17880
+ var CONDITION_COMPILE_STATUSES = new Set([
17881
+ "compiled",
17882
+ "plain",
17883
+ "refused"
17884
+ ]);
17871
17885
  var DEFAULT_SMART_STATUSES = ["pending", "ready"];
17872
17886
  function toNullableString(value) {
17873
17887
  return typeof value === "string" && value.length > 0 ? value : null;
@@ -17890,6 +17904,10 @@ function toNote(row) {
17890
17904
  sessionId: toNullableString(row.session_id),
17891
17905
  projectPath: toNullableString(row.project_path),
17892
17906
  surfaceCondition: toNullableString(row.surface_condition),
17907
+ compiledProvider: toNullableString(row.compiled_provider),
17908
+ compiledConfig: toNullableString(row.compiled_config),
17909
+ compiledAt: toNullableNumber(row.compiled_at),
17910
+ compileStatus: typeof row.compile_status === "string" && CONDITION_COMPILE_STATUSES.has(row.compile_status) ? row.compile_status : null,
17893
17911
  createdAt: row.created_at,
17894
17912
  updatedAt: row.updated_at,
17895
17913
  lastCheckedAt: toNullableNumber(row.last_checked_at),
@@ -17969,7 +17987,7 @@ function getNotes(db, options = {}) {
17969
17987
  }
17970
17988
  function addNote(db, type, options) {
17971
17989
  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);
17990
+ 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
17991
  if (!isNoteRow(result)) {
17974
17992
  throw new Error("[notes] failed to insert note");
17975
17993
  }
@@ -18023,6 +18041,8 @@ function updateNote(db, noteId, updates, scope) {
18023
18041
  }
18024
18042
  if (smartConditionChanged) {
18025
18043
  sets.push("status = 'pending'", "last_checked_at = NULL", "ready_at = NULL", "ready_reason = NULL");
18044
+ sets.push("compiled_provider = ?", "compiled_config = ?", "compiled_at = ?", "compile_status = ?");
18045
+ params.push(updates.compiledProvider ?? null, updates.compiledConfig ?? null, updates.compiledAt ?? null, updates.compileStatus ?? null);
18026
18046
  if (noteCheckColumnsExist(db)) {
18027
18047
  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
18048
  }
@@ -19343,7 +19363,7 @@ function resolveModelConfigOrDefault(values, modelKey, fallback) {
19343
19363
  // ../plugin/src/shared/prompt-surface-runtime.ts
19344
19364
  var GUIDANCE_MARKER = "## Magic Context";
19345
19365
  var GUIDANCE_MARKER_LINE = /^## Magic Context[\t ]*\r?$/gm;
19346
- var PROMPT_SURFACE_TOOL_IDS = [
19366
+ var ACTIVE_TOOL_IDS = [
19347
19367
  "ctx_reduce",
19348
19368
  "ctx_expand",
19349
19369
  "ctx_note",
@@ -19361,7 +19381,7 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
19361
19381
  return preset === "full" ? systemContent : `${systemContent}
19362
19382
  \x00magic-context-prompt-surface:${preset}`;
19363
19383
  }
19364
- var PROMPT_SURFACE_TOOL_ID_SET = new Set(PROMPT_SURFACE_TOOL_IDS);
19384
+ var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
19365
19385
  function resolveUserConfigDirectory(options) {
19366
19386
  if (options.userConfigDirectory)
19367
19387
  return resolve(options.userConfigDirectory);
@@ -34870,6 +34890,9 @@ var MagicContextConfigSchema = exports_external.object({
34870
34890
  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
34891
  historian: HistorianConfigSchema.describe("Historian agent configuration (model, fallback_models, variant, temperature, maxTokens, permission, two_pass, etc.)"),
34872
34892
  dreamer: DreamerConfigSchema.optional().describe("Dreamer agent + scheduling configuration (model, fallback_models, disable, schedule, tasks, etc.)"),
34893
+ smart_notes: exports_external.object({
34894
+ retina_handoff: exports_external.boolean().default(false).describe("When true, dreamer skips smart notes whose surface conditions compiled to retina provider configs at authoring time. Default false keeps both paths active until the retina consumer is deployed.")
34895
+ }).default({ retina_handoff: false }).describe("Smart-note ownership transition controls."),
34873
34896
  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
34897
  prompt_surface: PromptSurfaceConfigSchema.default({ default: "full" }).describe("Prompt-surface presets: default is full; models use the literal provider/model or provider/* routing grammar. Guidance and tool-description overrides are user-level only. On OpenCode and Pi, per-model routing applies to the guidance block only: tool descriptions are registered once per process, so they follow the default preset (a v1 plugin-surface limitation; per-model tool descriptions are planned for the OpenCode v2 plugin API once the SDK stabilizes)."),
34875
34898
  output_reserve: exports_external.union([
@@ -35419,6 +35442,14 @@ var PI_TO_CANONICAL_PROVIDER = {
35419
35442
  "openai-codex": "openai",
35420
35443
  "google-antigravity": "google"
35421
35444
  };
35445
+ var CANONICAL_TO_OMP_PROVIDER = {
35446
+ openai: "openai-codex",
35447
+ google: "google-antigravity"
35448
+ };
35449
+ var OMP_TO_CANONICAL_PROVIDER = {
35450
+ "openai-codex": "openai",
35451
+ "google-antigravity": "google"
35452
+ };
35422
35453
  function remapProviderPrefix(ref, map2) {
35423
35454
  if (typeof ref !== "string")
35424
35455
  return ref;
@@ -35426,8 +35457,9 @@ function remapProviderPrefix(ref, map2) {
35426
35457
  if (slash <= 0)
35427
35458
  return ref;
35428
35459
  const provider = ref.slice(0, slash);
35429
- const mapped = map2[provider];
35430
- return mapped ? `${mapped}${ref.slice(slash)}` : ref;
35460
+ if (!Object.hasOwn(map2, provider))
35461
+ return ref;
35462
+ return `${map2[provider]}${ref.slice(slash)}`;
35431
35463
  }
35432
35464
  function piModelRefToCanonical(ref) {
35433
35465
  return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
@@ -35435,6 +35467,12 @@ function piModelRefToCanonical(ref) {
35435
35467
  function resolveModelRefForPi(ref) {
35436
35468
  return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
35437
35469
  }
35470
+ function ompModelRefToCanonical(ref) {
35471
+ return remapProviderPrefix(ref, OMP_TO_CANONICAL_PROVIDER);
35472
+ }
35473
+ function resolveModelRefForOmp(ref) {
35474
+ return remapProviderPrefix(ompModelRefToCanonical(ref), CANONICAL_TO_OMP_PROVIDER);
35475
+ }
35438
35476
 
35439
35477
  // ../plugin/src/shared/models-dev-cache.ts
35440
35478
  var MIN_SANE_LIMIT = 20000;
@@ -48767,6 +48805,445 @@ function createCtxMemoryTool(deps) {
48767
48805
  };
48768
48806
  }
48769
48807
 
48808
+ // ../plugin/src/features/magic-context/smart-notes/condition-compiler.ts
48809
+ import { existsSync as existsSync11 } from "node:fs";
48810
+ import { isAbsolute as isAbsolute5 } from "node:path";
48811
+
48812
+ // ../retina-local-fs/src/path-fence.ts
48813
+ import { lstat, readlink, realpath } from "node:fs/promises";
48814
+ import { homedir as homedir5 } from "node:os";
48815
+ import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve3, sep } from "node:path";
48816
+
48817
+ // ../retina-local-fs/src/errors.ts
48818
+ class ProviderError extends Error {
48819
+ code;
48820
+ constructor(code, message) {
48821
+ super(message);
48822
+ this.code = code;
48823
+ this.name = "ProviderError";
48824
+ }
48825
+ }
48826
+
48827
+ // ../retina-local-fs/src/path-fence.ts
48828
+ async function resolveAndFenceProviderPath(configuredPath, options) {
48829
+ const configuredHomePath = resolve3(options.homeDirectory ?? process.env.HOME ?? homedir5());
48830
+ let home;
48831
+ try {
48832
+ home = await realpath(configuredHomePath);
48833
+ } catch (error51) {
48834
+ throw fsError(configuredHomePath, error51);
48835
+ }
48836
+ const expanded = configuredPath.startsWith("~/") ? join7(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
48837
+ const absolute = isAbsolute4(expanded) ? resolve3(expanded) : resolve3(options.cwd ?? process.cwd(), expanded);
48838
+ const canonical = await canonicalPath(absolute, options.allowMissing);
48839
+ if (isFencedPath(canonical, home)) {
48840
+ throw new ProviderError("fenced_path", `Refusing fenced path: ${canonical}`);
48841
+ }
48842
+ return canonical;
48843
+ }
48844
+ async function canonicalPath(path4, allowMissing) {
48845
+ try {
48846
+ return await realpath(path4);
48847
+ } catch (error51) {
48848
+ if (!allowMissing || !isMissingError(error51)) {
48849
+ throw fsError(path4, error51);
48850
+ }
48851
+ const suffix = [];
48852
+ let candidate = path4;
48853
+ while (true) {
48854
+ try {
48855
+ const metadata = await lstat(candidate);
48856
+ if (metadata.isSymbolicLink()) {
48857
+ const target2 = await readlink(candidate);
48858
+ const resolvedTarget = resolve3(dirname6(candidate), target2);
48859
+ return canonicalPath(join7(resolvedTarget, ...suffix), true);
48860
+ }
48861
+ } catch (candidateError) {
48862
+ if (!isMissingError(candidateError)) {
48863
+ throw fsError(path4, candidateError);
48864
+ }
48865
+ }
48866
+ const parent = dirname6(candidate);
48867
+ if (parent === candidate) {
48868
+ throw fsError(path4, error51);
48869
+ }
48870
+ suffix.unshift(basename3(candidate));
48871
+ candidate = parent;
48872
+ try {
48873
+ return join7(await realpath(candidate), ...suffix);
48874
+ } catch (parentError) {
48875
+ if (!isMissingError(parentError)) {
48876
+ throw fsError(path4, parentError);
48877
+ }
48878
+ }
48879
+ }
48880
+ }
48881
+ }
48882
+ function isFencedPath(canonicalPath2, homeDirectory) {
48883
+ const home = resolve3(homeDirectory);
48884
+ const cortexkitRoot = join7(home, ".local", "share", "cortexkit");
48885
+ const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
48886
+ const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
48887
+ const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
48888
+ const pathParts = canonicalPath2.split(sep).filter(Boolean);
48889
+ const name = basename3(canonicalPath2);
48890
+ const catalogDirectoryCarveIn = pathParts.includes("catalog");
48891
+ const moduleBinCarveIn = parts.length >= 2 && parts[1] === "bin";
48892
+ const catalogJsonCarveIn = name.endsWith(".json") && name.includes("catalog");
48893
+ if (catalogDirectoryCarveIn || moduleBinCarveIn || catalogJsonCarveIn) {
48894
+ return false;
48895
+ }
48896
+ const inFencedRoot = insideCortexkit && ["plexus", "claustrum", "staging"].includes(parts[0] ?? "");
48897
+ const fencedBasename = name.includes("binding-key") || name.endsWith(".handle");
48898
+ const plexusStore = insideCortexkit && parts[0] === "plexus" && name.startsWith("store.db");
48899
+ return inFencedRoot || fencedBasename || plexusStore;
48900
+ }
48901
+ function fsError(path4, error51) {
48902
+ const message = error51 instanceof Error ? error51.message : String(error51);
48903
+ return new ProviderError("unreadable_path", `Could not read ${path4}: ${message}`);
48904
+ }
48905
+ function isMissingError(error51) {
48906
+ return error51 !== null && typeof error51 === "object" && "code" in error51 && (error51.code === "ENOENT" || error51.code === "ENOTDIR");
48907
+ }
48908
+
48909
+ // ../retina-local-fs/src/provider.ts
48910
+ import { execFile as execFile2 } from "node:child_process";
48911
+ import { promisify as promisify2 } from "node:util";
48912
+ var execFileAsync2 = promisify2(execFile2);
48913
+ function parseSemver(value) {
48914
+ 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);
48915
+ if (!match) {
48916
+ throw new ProviderError("invalid_config", `Invalid semantic version: ${value}`);
48917
+ }
48918
+ return {
48919
+ major: Number(match[1]),
48920
+ minor: Number(match[2]),
48921
+ patch: Number(match[3]),
48922
+ prerelease: match[4] ? match[4].split(".").map((part) => /^\d+$/.test(part) ? Number(part) : part) : []
48923
+ };
48924
+ }
48925
+ function validateProviderConfig(input) {
48926
+ try {
48927
+ return { success: true, config: parseConfig(input) };
48928
+ } catch (error51) {
48929
+ return {
48930
+ success: false,
48931
+ reason: error51 instanceof Error ? error51.message : String(error51)
48932
+ };
48933
+ }
48934
+ }
48935
+ function parseConfig(value) {
48936
+ const config2 = requireObject(value, "config");
48937
+ if ("any" in config2) {
48938
+ requireOnlyKeys(config2, ["any"], "compound config");
48939
+ if (!Array.isArray(config2.any) || config2.any.length < 1 || config2.any.length > 4) {
48940
+ invalid("config.any must contain between 1 and 4 predicates");
48941
+ }
48942
+ return { any: config2.any.map(parseAtomicPredicate) };
48943
+ }
48944
+ return parseAtomicPredicate(config2);
48945
+ }
48946
+ function parseAtomicPredicate(value) {
48947
+ const predicate = requireObject(value, "predicate");
48948
+ if (typeof predicate.kind !== "string") {
48949
+ invalid("predicate.kind must be a string");
48950
+ }
48951
+ switch (predicate.kind) {
48952
+ case "file_contains":
48953
+ requireOnlyKeys(predicate, ["kind", "path", "needle", "absent", "resolved_path_exists"], predicate.kind);
48954
+ return {
48955
+ kind: predicate.kind,
48956
+ path: requireString(predicate.path, "path"),
48957
+ needle: requireString(predicate.needle, "needle", true),
48958
+ ...optionalBoolean(predicate.absent, "absent") === undefined ? {} : { absent: predicate.absent },
48959
+ ...predicateAudit(predicate)
48960
+ };
48961
+ case "path_exists":
48962
+ requireOnlyKeys(predicate, ["kind", "path", "gone", "resolved_path_exists"], predicate.kind);
48963
+ return {
48964
+ kind: predicate.kind,
48965
+ path: requireString(predicate.path, "path"),
48966
+ ...optionalBoolean(predicate.gone, "gone") === undefined ? {} : { gone: predicate.gone },
48967
+ ...predicateAudit(predicate)
48968
+ };
48969
+ case "mtime_after":
48970
+ requireOnlyKeys(predicate, ["kind", "path", "since_ms", "resolved_path_exists"], predicate.kind);
48971
+ return {
48972
+ kind: predicate.kind,
48973
+ path: requireString(predicate.path, "path"),
48974
+ since_ms: requireFiniteNumber(predicate.since_ms, "since_ms"),
48975
+ ...predicateAudit(predicate)
48976
+ };
48977
+ case "git_commit_after":
48978
+ requireOnlyKeys(predicate, ["kind", "repo_path", "ref", "sha", "resolved_path_exists"], predicate.kind);
48979
+ return {
48980
+ kind: predicate.kind,
48981
+ repo_path: requireString(predicate.repo_path, "repo_path"),
48982
+ sha: requireString(predicate.sha, "sha"),
48983
+ ...predicate.ref === undefined ? {} : { ref: requireString(predicate.ref, "ref") },
48984
+ ...predicateAudit(predicate)
48985
+ };
48986
+ case "git_tag_matching": {
48987
+ requireOnlyKeys(predicate, ["kind", "repo_path", "pattern", "above", "resolved_path_exists"], predicate.kind);
48988
+ const above = predicate.above === undefined ? undefined : requireString(predicate.above, "above");
48989
+ if (above !== undefined) {
48990
+ parseSemver(above);
48991
+ }
48992
+ return {
48993
+ kind: predicate.kind,
48994
+ repo_path: requireString(predicate.repo_path, "repo_path"),
48995
+ pattern: requireString(predicate.pattern, "pattern"),
48996
+ ...above === undefined ? {} : { above },
48997
+ ...predicateAudit(predicate)
48998
+ };
48999
+ }
49000
+ default:
49001
+ invalid(`Unsupported predicate kind: ${predicate.kind}`);
49002
+ }
49003
+ }
49004
+ function requireObject(value, field) {
49005
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
49006
+ invalid(`${field} must be an object`);
49007
+ }
49008
+ return value;
49009
+ }
49010
+ function requireOnlyKeys(value, allowed, field) {
49011
+ const unknown4 = Object.keys(value).filter((key) => !allowed.includes(key));
49012
+ if (unknown4.length > 0) {
49013
+ invalid(`${field} contains unknown field(s): ${unknown4.join(", ")}`);
49014
+ }
49015
+ }
49016
+ function requireString(value, field, allowEmpty = false) {
49017
+ if (typeof value !== "string" || !allowEmpty && value.length === 0) {
49018
+ invalid(`${field} must be ${allowEmpty ? "a string" : "a non-empty string"}`);
49019
+ }
49020
+ return value;
49021
+ }
49022
+ function predicateAudit(predicate) {
49023
+ const exists = optionalBoolean(predicate.resolved_path_exists, "resolved_path_exists");
49024
+ return exists === undefined ? {} : { resolved_path_exists: exists };
49025
+ }
49026
+ function optionalBoolean(value, field) {
49027
+ if (value !== undefined && typeof value !== "boolean") {
49028
+ invalid(`${field} must be a boolean`);
49029
+ }
49030
+ return value;
49031
+ }
49032
+ function requireFiniteNumber(value, field) {
49033
+ if (typeof value !== "number" || !Number.isFinite(value)) {
49034
+ invalid(`${field} must be a finite number`);
49035
+ }
49036
+ return value;
49037
+ }
49038
+ function invalid(message) {
49039
+ throw new ProviderError("invalid_config", message);
49040
+ }
49041
+
49042
+ // ../plugin/src/features/magic-context/smart-notes/condition-compiler.ts
49043
+ var RETINA_LOCAL_FS_PROVIDER = "local-fs";
49044
+ var VALUE = String.raw`(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)`;
49045
+ async function compileSurfaceCondition(surfaceCondition, options) {
49046
+ const parsed = parseCondition(surfaceCondition, options.projectPath);
49047
+ if (parsed === null)
49048
+ return { status: "plain" };
49049
+ const now = (options.now ?? Date.now)();
49050
+ const resolvePath = options.resolvePath ?? (async (path4) => {
49051
+ const resolved = await resolveAndFenceProviderPath(path4, {
49052
+ allowMissing: true,
49053
+ homeDirectory: options.homeDirectory,
49054
+ cwd: options.projectPath
49055
+ });
49056
+ return { path: resolved, exists: existsSync11(resolved) };
49057
+ });
49058
+ let predicates;
49059
+ try {
49060
+ predicates = [];
49061
+ for (const predicate of parsed) {
49062
+ predicates.push(await resolvePredicate(predicate, resolvePath, now));
49063
+ }
49064
+ } catch (error51) {
49065
+ const code = error51 !== null && typeof error51 === "object" && "code" in error51 ? error51.code : undefined;
49066
+ return {
49067
+ status: "refused",
49068
+ reason: code === "fenced_path" ? "fenced path" : "path resolution failed"
49069
+ };
49070
+ }
49071
+ const candidate = predicates.length === 1 ? predicates[0] : { any: predicates };
49072
+ const validation = validateProviderConfig(candidate);
49073
+ if (!validation.success) {
49074
+ return {
49075
+ status: "refused",
49076
+ reason: `provider schema: ${singleLine(validation.reason)}`.slice(0, 180)
49077
+ };
49078
+ }
49079
+ return {
49080
+ status: "compiled",
49081
+ provider: RETINA_LOCAL_FS_PROVIDER,
49082
+ config: validation.config,
49083
+ compiledAt: now
49084
+ };
49085
+ }
49086
+ function conditionCompileStorageFields(result) {
49087
+ if (result.status === "compiled") {
49088
+ return {
49089
+ compiledProvider: result.provider,
49090
+ compiledConfig: JSON.stringify(result.config),
49091
+ compiledAt: result.compiledAt,
49092
+ compileStatus: result.status
49093
+ };
49094
+ }
49095
+ return {
49096
+ compiledProvider: null,
49097
+ compiledConfig: null,
49098
+ compiledAt: null,
49099
+ compileStatus: result.status
49100
+ };
49101
+ }
49102
+ function conditionCompileReplySuffix(result) {
49103
+ if (result.status === "compiled") {
49104
+ return `
49105
+ - Retina provider: ${result.provider}`;
49106
+ }
49107
+ if (result.status === "refused") {
49108
+ return `
49109
+ - Retina compile refused: ${result.reason}`;
49110
+ }
49111
+ return "";
49112
+ }
49113
+ function parseCondition(surfaceCondition, projectPath) {
49114
+ const trimmed = surfaceCondition.trim();
49115
+ const either = trimmed.match(/^either\s+(.+)$/i);
49116
+ if (!either) {
49117
+ const predicate = parseAtomicCondition(trimmed, projectPath);
49118
+ return predicate ? [predicate] : null;
49119
+ }
49120
+ const clauses = splitOrClauses(either[1]);
49121
+ if (clauses.length < 2)
49122
+ return null;
49123
+ const predicates = clauses.map((clause) => parseAtomicCondition(clause, projectPath));
49124
+ return predicates.every((predicate) => predicate !== null) ? predicates : null;
49125
+ }
49126
+ function parseAtomicCondition(text, projectPath) {
49127
+ const fileContains = text.match(new RegExp(`^(?:when\\s+)?file\\s+(${VALUE})\\s+(no longer contains|contains)\\s+(.+)$`, "i"));
49128
+ if (fileContains) {
49129
+ const needle = unquote(fileContains[3].trim());
49130
+ if (needle === null)
49131
+ return null;
49132
+ return {
49133
+ kind: "file_contains",
49134
+ path: unquote(fileContains[1]) ?? fileContains[1],
49135
+ needle,
49136
+ ...fileContains[2].toLowerCase() === "no longer contains" ? { absent: true } : {}
49137
+ };
49138
+ }
49139
+ const commit = text.match(new RegExp(`^(?:when\\s+)?(?:repo(?:sitory)?\\s+)?(${VALUE})\\s+has\\s+a\\s+commit\\s+(?:after|newer than)\\s+([0-9a-f]{7,64})$`, "i"));
49140
+ if (commit) {
49141
+ return {
49142
+ kind: "git_commit_after",
49143
+ repo_path: unquote(commit[1]) ?? commit[1],
49144
+ sha: commit[2]
49145
+ };
49146
+ }
49147
+ 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"));
49148
+ if (tag) {
49149
+ const pattern2 = tag[1] ? unquote(tag[1]) : "*";
49150
+ const above = unquote(tag[2] ?? tag[3] ?? "");
49151
+ const repoPath = tag[4] ? unquote(tag[4]) : projectPath;
49152
+ if (pattern2 === null || above === null || repoPath === null)
49153
+ return null;
49154
+ return {
49155
+ kind: "git_tag_matching",
49156
+ repo_path: repoPath,
49157
+ pattern: pattern2,
49158
+ ...above.length > 0 ? { above } : {}
49159
+ };
49160
+ }
49161
+ const mtime = text.match(new RegExp(`^(?:when\\s+)?(?:file\\s+)?(${VALUE})\\s+(changes|is rebuilt|mtime moves)$`, "i"));
49162
+ if (mtime) {
49163
+ return {
49164
+ kind: "mtime_after",
49165
+ path: unquote(mtime[1]) ?? mtime[1]
49166
+ };
49167
+ }
49168
+ const pathExists = text.match(new RegExp(`^(?:when\\s+)?(?:path\\s+)?(${VALUE})\\s+(exists|is gone)$`, "i"));
49169
+ if (pathExists) {
49170
+ return {
49171
+ kind: "path_exists",
49172
+ path: unquote(pathExists[1]) ?? pathExists[1],
49173
+ ...pathExists[2].toLowerCase() === "is gone" ? { gone: true } : {}
49174
+ };
49175
+ }
49176
+ return null;
49177
+ }
49178
+ async function resolvePredicate(predicate, resolvePath, now) {
49179
+ const configuredPath = "repo_path" in predicate ? predicate.repo_path : predicate.path;
49180
+ const resolved = await resolvePath(configuredPath);
49181
+ const sourceIsResolvable = isAbsolute5(configuredPath) || configuredPath === "~" || configuredPath.startsWith("~/");
49182
+ const audit = sourceIsResolvable && resolved.exists ? {} : { resolved_path_exists: false };
49183
+ switch (predicate.kind) {
49184
+ case "file_contains":
49185
+ return { ...predicate, path: resolved.path, ...audit };
49186
+ case "path_exists":
49187
+ return { ...predicate, path: resolved.path, ...audit };
49188
+ case "mtime_after":
49189
+ return { kind: predicate.kind, path: resolved.path, since_ms: now, ...audit };
49190
+ case "git_commit_after":
49191
+ return { ...predicate, repo_path: resolved.path, ...audit };
49192
+ case "git_tag_matching":
49193
+ return { ...predicate, repo_path: resolved.path, ...audit };
49194
+ }
49195
+ }
49196
+ function splitOrClauses(text) {
49197
+ const clauses = [];
49198
+ let start = 0;
49199
+ let quote = null;
49200
+ let escaped = false;
49201
+ for (let index = 0;index < text.length; index += 1) {
49202
+ const character = text[index];
49203
+ if (escaped) {
49204
+ escaped = false;
49205
+ continue;
49206
+ }
49207
+ if (quote && character === "\\") {
49208
+ escaped = true;
49209
+ continue;
49210
+ }
49211
+ if (character === '"' || character === "'") {
49212
+ quote = quote === character ? null : quote === null ? character : quote;
49213
+ continue;
49214
+ }
49215
+ if (quote !== null)
49216
+ continue;
49217
+ const separator = text.slice(index).match(/^\s+or\s+/i);
49218
+ if (!separator)
49219
+ continue;
49220
+ clauses.push(text.slice(start, index).trim());
49221
+ index += separator[0].length - 1;
49222
+ start = index + 1;
49223
+ }
49224
+ clauses.push(text.slice(start).trim());
49225
+ return clauses.filter(Boolean);
49226
+ }
49227
+ function unquote(value) {
49228
+ if (value.length < 2)
49229
+ return value;
49230
+ const quote = value[0];
49231
+ if (quote !== '"' && quote !== "'" || value.at(-1) !== quote)
49232
+ return value;
49233
+ if (quote === '"') {
49234
+ try {
49235
+ const parsed = JSON.parse(value);
49236
+ return typeof parsed === "string" ? parsed : null;
49237
+ } catch {
49238
+ return null;
49239
+ }
49240
+ }
49241
+ return value.slice(1, -1).replace(/\\'/g, "'").replace(/\\\\/g, "\\");
49242
+ }
49243
+ function singleLine(value) {
49244
+ return value.replace(/\s+/g, " ").trim();
49245
+ }
49246
+
48770
49247
  // ../plugin/src/tools/ctx-note/constants.ts
48771
49248
  var CTX_NOTE_DESCRIPTION = `Working notes for this session's future — reminders, follow-ups, and things to revisit later.
48772
49249
 
@@ -48901,16 +49378,20 @@ function createCtxNoteTool(deps) {
48901
49378
  if (!projectIdentity) {
48902
49379
  return err3("Error: Could not resolve project identity for smart note.");
48903
49380
  }
49381
+ const compilation = await compileSurfaceCondition(surfaceCondition, {
49382
+ projectPath: ctx.cwd
49383
+ });
48904
49384
  const note2 = addNote(deps.db, "smart", {
48905
49385
  content,
48906
49386
  sessionId,
48907
49387
  projectPath: projectIdentity,
48908
49388
  surfaceCondition,
48909
- anchorOrdinal
49389
+ anchorOrdinal,
49390
+ ...conditionCompileStorageFields(compilation)
48910
49391
  });
48911
49392
  return ok3(`Created smart note #${note2.id}. Dreamer will evaluate the condition during nightly runs:
48912
49393
  - Content: ${content}
48913
- - Condition: ${surfaceCondition}`);
49394
+ - Condition: ${surfaceCondition}${conditionCompileReplySuffix(compilation)}`);
48914
49395
  }
48915
49396
  const note = addNote(deps.db, "session", {
48916
49397
  sessionId,
@@ -48940,8 +49421,15 @@ function createCtxNoteTool(deps) {
48940
49421
  const updates = {};
48941
49422
  if (params.content?.trim())
48942
49423
  updates.content = params.content.trim();
48943
- if (params.surface_condition?.trim())
48944
- updates.surfaceCondition = params.surface_condition.trim();
49424
+ let compilation;
49425
+ if (params.surface_condition?.trim()) {
49426
+ const surfaceCondition = params.surface_condition.trim();
49427
+ updates.surfaceCondition = surfaceCondition;
49428
+ compilation = await compileSurfaceCondition(surfaceCondition, {
49429
+ projectPath: ctx.cwd
49430
+ });
49431
+ Object.assign(updates, conditionCompileStorageFields(compilation));
49432
+ }
48945
49433
  if (!updates.content && !updates.surfaceCondition) {
48946
49434
  return err3("Error: Provide 'content' and/or 'surface_condition' to update.");
48947
49435
  }
@@ -48963,7 +49451,7 @@ function createCtxNoteTool(deps) {
48963
49451
  parts.push(`condition: ${updates.surfaceCondition}`);
48964
49452
  return ok3(`Updated note #${params.note_id}
48965
49453
  - ${parts.join(`
48966
- - `)}`);
49454
+ - `)}${compilation ? conditionCompileReplySuffix(compilation) : ""}`);
48967
49455
  }
48968
49456
  const limit = typeof params.limit === "number" && params.limit > 0 ? Math.floor(params.limit) : DEFAULT_READ_LIMIT;
48969
49457
  const offset = typeof params.offset === "number" && params.offset > 0 ? Math.floor(params.offset) : 0;
@@ -49225,9 +49713,9 @@ function createCtxReduceTool(deps) {
49225
49713
  }
49226
49714
 
49227
49715
  // ../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);
49716
+ import { execFile as execFile3 } from "node:child_process";
49717
+ import { promisify as promisify3 } from "node:util";
49718
+ var execFileAsync3 = promisify3(execFile3);
49231
49719
  var GIT_TIMEOUT_MS3 = 1e4;
49232
49720
  var DEFAULT_MAX_COMMITS = 5000;
49233
49721
  var RECORD_SEPARATOR = "\x1E";
@@ -49259,7 +49747,7 @@ async function readGitCommitsResult(directory, options = {}) {
49259
49747
  }
49260
49748
  let stdout;
49261
49749
  try {
49262
- const result = await execFileAsync2("git", args, {
49750
+ const result = await execFileAsync3("git", args, {
49263
49751
  cwd: directory,
49264
49752
  timeout: GIT_TIMEOUT_MS3,
49265
49753
  maxBuffer: 32 * 1024 * 1024,
@@ -51520,8 +52008,8 @@ class BoundedSessionMap {
51520
52008
 
51521
52009
  // ../plugin/src/features/magic-context/compaction-marker.ts
51522
52010
  import { createHash as createHash16 } from "node:crypto";
51523
- import { existsSync as existsSync11 } from "node:fs";
51524
- import { join as join7 } from "node:path";
52011
+ import { existsSync as existsSync12 } from "node:fs";
52012
+ import { join as join8 } from "node:path";
51525
52013
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
51526
52014
  var ID_PREFIX_HEX_LENGTH = 12;
51527
52015
  var ID_SUFFIX_LENGTH = 14;
@@ -51547,7 +52035,7 @@ function generatePartId(timestampMs, counter = 0n, identity = "") {
51547
52035
  return generateId("prt", timestampMs, counter, identity);
51548
52036
  }
51549
52037
  function getOpenCodeDbPath2() {
51550
- return join7(getDataDir(), "opencode", "opencode.db");
52038
+ return join8(getDataDir(), "opencode", "opencode.db");
51551
52039
  }
51552
52040
  var cachedWriteDb = null;
51553
52041
  var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
@@ -51592,7 +52080,7 @@ function getWritableOpenCodeDb() {
51592
52080
  closeQuietly(cachedWriteDb.db);
51593
52081
  } catch {}
51594
52082
  }
51595
- if (!existsSync11(dbPath)) {
52083
+ if (!existsSync12(dbPath)) {
51596
52084
  throw new Error(`OpenCode database not found at ${dbPath} (is OpenCode installed?)`);
51597
52085
  }
51598
52086
  const db = new Database(dbPath);
@@ -52705,4 +53193,4 @@ function registerMagicContextTools(pi, opts) {
52705
53193
  }
52706
53194
  }
52707
53195
 
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 };
53196
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, piModelRefToCanonical, resolveModelRefForPi, ompModelRefToCanonical, resolveModelRefForOmp, isSaneLimit, resolveLimit, getSdkContextLimit, resolveModelConfigOrDefault, normalizeTodoStateJson, buildSyntheticTodoPart, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };