@cortexkit/pi-magic-context 0.42.0 → 0.42.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.
@@ -4165,6 +4165,28 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
4165
4165
  return payload;
4166
4166
  };
4167
4167
  });
4168
+ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
4169
+ $ZodType.init(inst, def);
4170
+ if (def.values.length === 0) {
4171
+ throw new Error("Cannot create literal schema with no valid values");
4172
+ }
4173
+ const values = new Set(def.values);
4174
+ inst._zod.values = values;
4175
+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
4176
+ inst._zod.parse = (payload, _ctx) => {
4177
+ const input = payload.value;
4178
+ if (values.has(input)) {
4179
+ return payload;
4180
+ }
4181
+ payload.issues.push({
4182
+ code: "invalid_value",
4183
+ values: def.values,
4184
+ input,
4185
+ inst
4186
+ });
4187
+ return payload;
4188
+ };
4189
+ });
4168
4190
  var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
4169
4191
  $ZodType.init(inst, def);
4170
4192
  inst._zod.optin = "optional";
@@ -5370,6 +5392,44 @@ var enumProcessor = (schema, _ctx, json, _params) => {
5370
5392
  json.type = "string";
5371
5393
  json.enum = values;
5372
5394
  };
5395
+ var literalProcessor = (schema, ctx, json, _params) => {
5396
+ const def = schema._zod.def;
5397
+ const vals = [];
5398
+ for (const val of def.values) {
5399
+ if (val === undefined) {
5400
+ if (ctx.unrepresentable === "throw") {
5401
+ throw new Error("Literal `undefined` cannot be represented in JSON Schema");
5402
+ }
5403
+ } else if (typeof val === "bigint") {
5404
+ if (ctx.unrepresentable === "throw") {
5405
+ throw new Error("BigInt literals cannot be represented in JSON Schema");
5406
+ } else {
5407
+ vals.push(Number(val));
5408
+ }
5409
+ } else {
5410
+ vals.push(val);
5411
+ }
5412
+ }
5413
+ if (vals.length === 0) {} else if (vals.length === 1) {
5414
+ const val = vals[0];
5415
+ json.type = val === null ? "null" : typeof val;
5416
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
5417
+ json.enum = [val];
5418
+ } else {
5419
+ json.const = val;
5420
+ }
5421
+ } else {
5422
+ if (vals.every((v) => typeof v === "number"))
5423
+ json.type = "number";
5424
+ if (vals.every((v) => typeof v === "string"))
5425
+ json.type = "string";
5426
+ if (vals.every((v) => typeof v === "boolean"))
5427
+ json.type = "boolean";
5428
+ if (vals.every((v) => v === null))
5429
+ json.type = "null";
5430
+ json.enum = vals;
5431
+ }
5432
+ };
5373
5433
  var customProcessor = (_schema, ctx, _json, _params) => {
5374
5434
  if (ctx.unrepresentable === "throw") {
5375
5435
  throw new Error("Custom types cannot be represented in JSON Schema");
@@ -6246,6 +6306,27 @@ function _enum(values, params) {
6246
6306
  ...normalizeParams(params)
6247
6307
  });
6248
6308
  }
6309
+ var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
6310
+ $ZodLiteral.init(inst, def);
6311
+ ZodType.init(inst, def);
6312
+ inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
6313
+ inst.values = new Set(def.values);
6314
+ Object.defineProperty(inst, "value", {
6315
+ get() {
6316
+ if (def.values.length > 1) {
6317
+ throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
6318
+ }
6319
+ return def.values[0];
6320
+ }
6321
+ });
6322
+ });
6323
+ function literal(value, params) {
6324
+ return new ZodLiteral({
6325
+ type: "literal",
6326
+ values: Array.isArray(value) ? value : [value],
6327
+ ...normalizeParams(params)
6328
+ });
6329
+ }
6249
6330
  var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
6250
6331
  $ZodTransform.init(inst, def);
6251
6332
  ZodType.init(inst, def);
@@ -7017,6 +7098,8 @@ var BaseEmbeddingConfigSchema = object({
7017
7098
  api_key: string2().optional().describe("API key for remote embedding provider (optional)"),
7018
7099
  input_type: string2().optional().describe("Default input_type for stored/indexed (passage) embeddings in the request body. Required by some openai-compatible providers (e.g. NVIDIA NIM). Omitted from the request when unset."),
7019
7100
  query_input_type: string2().optional().describe("Optional input_type for query (search) embeddings on asymmetric models (e.g. NVIDIA NIM 'query'). When unset, query embeddings use embedding.input_type. Passage/stored content always uses embedding.input_type."),
7101
+ query_instruction: union([string2(), literal(false)]).optional().describe("OpenAI-compatible query prefix override. A string is prepended verbatim to search queries; false disables the built-in model-family instruction. Qwen3-Embedding, gte-Qwen instruct, e5 instruct, and Nomic families have built-in recipes. Query-only changes do not re-embed stored content. User-level only; project values are ignored."),
7102
+ document_prefix: string2().optional().describe("OpenAI-compatible stored-document prefix override, prepended verbatim. Defaults to the model-family recipe (empty for Qwen3/gte/e5 instruct; 'search_document: ' for Nomic). Changing it changes stored vectors and triggers re-embedding. User-level only; project values are ignored."),
7020
7103
  truncate: string2().optional().describe("Optional truncate mode sent in the embedding request body (e.g. NVIDIA NIM accepts 'NONE' | 'START' | 'END'). Omitted from the request when unset."),
7021
7104
  max_input_tokens: number2().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
7022
7105
  local_runtime: _enum(["auto", "native", "wasm"]).default("auto").describe("Local provider only: ONNX runtime selection. 'auto' uses native under Node and uses WASM under Bun versions before 1.4.0, where Bun's NAPI teardown race can panic on quit; native is restored automatically on Bun 1.4.0+. Set 'native' only to prefer speed while accepting that pre-1.4.0 Bun crash risk, or 'wasm' to avoid loading the native addon."),
@@ -7068,6 +7151,8 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
7068
7151
  ...apiKey ? { api_key: apiKey } : {},
7069
7152
  ...inputType ? { input_type: inputType } : {},
7070
7153
  ...queryInputType ? { query_input_type: queryInputType } : {},
7154
+ ...data.query_instruction !== undefined ? { query_instruction: data.query_instruction } : {},
7155
+ ...data.document_prefix !== undefined ? { document_prefix: data.document_prefix } : {},
7071
7156
  ...truncate ? { truncate } : {},
7072
7157
  ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {}
7073
7158
  };
@@ -7093,6 +7178,8 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
7093
7178
  ...apiKey ? { api_key: apiKey } : {},
7094
7179
  ...inputType ? { input_type: inputType } : {},
7095
7180
  ...queryInputType ? { query_input_type: queryInputType } : {},
7181
+ ...data.query_instruction !== undefined ? { query_instruction: data.query_instruction } : {},
7182
+ ...data.document_prefix !== undefined ? { document_prefix: data.document_prefix } : {},
7096
7183
  ...truncate ? { truncate } : {},
7097
7184
  ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {}
7098
7185
  };
@@ -7226,7 +7313,13 @@ var HARNESS_KEYS = PER_HARNESS_MODEL_KEYS;
7226
7313
  var HISTORIAN_USER_ONLY_FIELDS = PER_HARNESS_MIGRATION_INVENTORY.historian.migrated_execution;
7227
7314
  var PROMPT_SURFACE_USER_ONLY_FIELDS = ["guidance_override_path", "tool_descriptions"];
7228
7315
  var AGENT_ESCALATION_FIELDS = ["prompt", "permission", "tools"];
7229
- var EMBEDDING_DESTINATION_FIELDS = ["endpoint", "provider", "fallback_provider"];
7316
+ var EMBEDDING_USER_ONLY_FIELDS = [
7317
+ "endpoint",
7318
+ "provider",
7319
+ "fallback_provider",
7320
+ "query_instruction",
7321
+ "document_prefix"
7322
+ ];
7230
7323
  var PERCENTAGE_THRESHOLD_REASON = "security: a repository may only raise compaction thresholds above the user's effective value; it cannot force earlier historian work or cloned-repo cost escalation.";
7231
7324
  var TOKEN_THRESHOLD_REASON = "security: a repository may only raise execute_threshold_tokens above the user's trusted token threshold; it cannot force earlier historian work or cloned-repo cost escalation.";
7232
7325
  var TOKEN_THRESHOLD_INTRODUCTION_REASON = "security: a repository cannot introduce a new execute_threshold_tokens override when the user has no trusted token threshold for that key; that could force earlier historian work or cloned-repo cost escalation.";
@@ -7460,14 +7553,14 @@ function stripUnsafeProjectConfigFields(projectRaw) {
7460
7553
  const embedding = projectRaw.embedding;
7461
7554
  if (isPlainObject2(embedding)) {
7462
7555
  const removed = [];
7463
- for (const field of EMBEDDING_DESTINATION_FIELDS) {
7556
+ for (const field of EMBEDDING_USER_ONLY_FIELDS) {
7464
7557
  if (field in embedding) {
7465
7558
  delete embedding[field];
7466
7559
  removed.push(field);
7467
7560
  }
7468
7561
  }
7469
7562
  if (removed.length > 0) {
7470
- warnings.push(`Ignoring embedding.${removed.join("/")} from project config ` + "(security: a repository cannot choose where private text is embedded).");
7563
+ warnings.push(`Ignoring embedding.${removed.join("/")} from project config ` + "(security: a repository cannot choose where or how private text is embedded).");
7471
7564
  }
7472
7565
  }
7473
7566
  for (const agentKey of HIDDEN_AGENT_KEYS) {
@@ -13272,29 +13365,6 @@ function resolveOpenCodeDbPath() {
13272
13365
  function openCodeDbPathExists(resolution = resolveOpenCodeDbPath()) {
13273
13366
  return resolution.path !== ":memory:" && existsSync5(resolution.path);
13274
13367
  }
13275
- function getOpenCodeDbProbeDescriptions(resolution = resolveOpenCodeDbPath()) {
13276
- if (resolution.source === "OPENCODE_DB")
13277
- return [resolution.path];
13278
- if (resolution.source === "channel" || process.env.OPENCODE_DISABLE_CHANNEL_DB === "1" || process.env.OPENCODE_DISABLE_CHANNEL_DB === "true") {
13279
- return [resolution.path];
13280
- }
13281
- const dataDir = openCodeDataDir();
13282
- return [
13283
- join4(dataDir, "opencode.db"),
13284
- join4(dataDir, "opencode-local.db"),
13285
- join4(dataDir, "opencode-dev.db"),
13286
- join4(dataDir, "opencode-<channel>.db")
13287
- ];
13288
- }
13289
- function lookedForText(resolution) {
13290
- return getOpenCodeDbProbeDescriptions(resolution).join(", ");
13291
- }
13292
- function formatOpenCodeDbMissingStatusLine(resolution = resolveOpenCodeDbPath()) {
13293
- return `OpenCode DB: MISSING (looked for ${lookedForText(resolution)}). History compaction (historian) and the mid-turn valve are disabled; set OPENCODE_DB if OpenCode stores it elsewhere.`;
13294
- }
13295
- function formatOpenCodeDbReadFailureStatusLine(failure) {
13296
- return `OpenCode DB: READ FAILED (path=${failure.path}, source=${failure.source}) — ${failure.message}`;
13297
- }
13298
13368
  function recordOpenCodeDbReadFailure(resolution, error) {
13299
13369
  const message = error instanceof Error ? error.message : String(error);
13300
13370
  lastReadFailure = { ...resolution, message };
@@ -13304,9 +13374,6 @@ function clearOpenCodeDbReadFailure(path) {
13304
13374
  if (path === undefined || lastReadFailure?.path === path)
13305
13375
  lastReadFailure = null;
13306
13376
  }
13307
- function getOpenCodeDbReadFailure() {
13308
- return lastReadFailure;
13309
- }
13310
13377
  function claimOpenCodeDbDiagnosticOnce(surface, resolution) {
13311
13378
  const key = `${surface}\x00${resolution.path}\x00${resolution.source}`;
13312
13379
  if (claimedDiagnostics.has(key))
@@ -26846,7 +26913,8 @@ function getSynapseBatchRequestKey(args) {
26846
26913
  allow_equivalent: false,
26847
26914
  accept_declared: false,
26848
26915
  ids: args.items.map((item) => item.id),
26849
- content_sha256: args.items.map((item) => item.contentSha256)
26916
+ content_sha256: args.items.map((item) => item.contentSha256),
26917
+ ...args.purpose === "query" ? { purpose: args.purpose } : {}
26850
26918
  }));
26851
26919
  }
26852
26920
  function hashContent(text) {
@@ -27107,7 +27175,7 @@ class SynapseEmbeddingProvider {
27107
27175
  })();
27108
27176
  return this.initializing;
27109
27177
  }
27110
- async embed(text, signal) {
27178
+ async embed(text, signal, purpose = "passage") {
27111
27179
  if (!await this.initialize() || signal?.aborted || !this.metadata)
27112
27180
  return null;
27113
27181
  if (estimateTokens(text) > this.metadata.max_tokens)
@@ -27117,6 +27185,7 @@ class SynapseEmbeddingProvider {
27117
27185
  const value = await this.callWithRetry("embed.query", this.requestConstraints({
27118
27186
  id,
27119
27187
  text,
27188
+ purpose,
27120
27189
  deadline_ms: this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS
27121
27190
  }), this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, true, signal);
27122
27191
  const extracted = extractVector(value);
@@ -27136,7 +27205,7 @@ class SynapseEmbeddingProvider {
27136
27205
  return null;
27137
27206
  }
27138
27207
  }
27139
- async embedBatch(texts, signal) {
27208
+ async embedBatch(texts, signal, purpose = "passage") {
27140
27209
  if (texts.length === 0)
27141
27210
  return [];
27142
27211
  const items = texts.map((text, index) => ({
@@ -27144,10 +27213,10 @@ class SynapseEmbeddingProvider {
27144
27213
  text,
27145
27214
  contentSha256: hashContent(text)
27146
27215
  }));
27147
- const map = await this.embedItems(items, signal);
27216
+ const map = await this.embedItems(items, signal, purpose);
27148
27217
  return items.map((item) => map.get(item.id) ?? null);
27149
27218
  }
27150
- async embedItems(items, signal) {
27219
+ async embedItems(items, signal, purpose = "passage") {
27151
27220
  const output = new Map;
27152
27221
  if (items.length === 0 || !await this.initialize() || !this.metadata || signal?.aborted) {
27153
27222
  return output;
@@ -27160,12 +27229,12 @@ class SynapseEmbeddingProvider {
27160
27229
  const page = this.nextPage(eligibleItems, start);
27161
27230
  start += page.length;
27162
27231
  try {
27163
- const requestKey = this.requestKey(page);
27232
+ const requestKey = this.requestKey(page, purpose);
27164
27233
  let body = {};
27165
27234
  let restarted = false;
27166
27235
  for (;; ) {
27167
27236
  try {
27168
- body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
27237
+ body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey, purpose), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
27169
27238
  const first = responseBody(body);
27170
27239
  const jobId = typeof first.job_id === "string" ? first.job_id : null;
27171
27240
  if (jobId)
@@ -27235,24 +27304,26 @@ class SynapseEmbeddingProvider {
27235
27304
  accept_declared: false
27236
27305
  };
27237
27306
  }
27238
- batchRequest(items, requestKey) {
27307
+ batchRequest(items, requestKey, purpose) {
27239
27308
  return this.requestConstraints({
27240
27309
  items: items.map((item) => ({
27241
27310
  id: item.id,
27242
27311
  text: item.text,
27243
27312
  content_sha256: item.contentSha256
27244
27313
  })),
27245
- request_key: requestKey
27314
+ request_key: requestKey,
27315
+ purpose
27246
27316
  });
27247
27317
  }
27248
- requestKey(items) {
27318
+ requestKey(items, purpose) {
27249
27319
  if (!this.metadata)
27250
27320
  throw new SynapseEmbeddingError("transport", "Synapse metadata is unavailable");
27251
27321
  return getSynapseBatchRequestKey({
27252
27322
  model: this.metadata.model,
27253
27323
  fingerprint: this.metadata.fingerprint,
27254
27324
  tableEpoch: this.metadata.table_epoch,
27255
- items
27325
+ items,
27326
+ purpose
27256
27327
  });
27257
27328
  }
27258
27329
  async pollBatch(jobId, requestKey, signal) {
@@ -27462,6 +27533,7 @@ var existingHashStatements = new WeakMap;
27462
27533
  var existingHashByProjectStatements = new WeakMap;
27463
27534
  var deleteByCompartmentStatements = new WeakMap;
27464
27535
  var insertEmbeddingStatements = new WeakMap;
27536
+ var renumberEmbeddingWindowStatements = new WeakMap;
27465
27537
  var searchRowsStatements = new WeakMap;
27466
27538
  var searchRowsByModelStatements = new WeakMap;
27467
27539
  var searchPoolProbeStatements = new WeakMap;
@@ -27512,6 +27584,19 @@ function getInsertEmbeddingStatement(db) {
27512
27584
  }
27513
27585
  return stmt;
27514
27586
  }
27587
+ function getRenumberEmbeddingWindowStatement(db) {
27588
+ let stmt = renumberEmbeddingWindowStatements.get(db);
27589
+ if (!stmt) {
27590
+ stmt = db.prepare(`UPDATE compartment_chunk_embeddings
27591
+ SET window_index = ?
27592
+ WHERE compartment_id = ?
27593
+ AND model_id = ?
27594
+ AND project_path = ?
27595
+ AND window_index = ?`);
27596
+ renumberEmbeddingWindowStatements.set(db, stmt);
27597
+ }
27598
+ return stmt;
27599
+ }
27515
27600
  function getSearchPoolProbeStatement(db) {
27516
27601
  let stmt = searchPoolProbeStatements.get(db);
27517
27602
  if (!stmt) {
@@ -27673,6 +27758,11 @@ function parseCanonicalLineRange(line) {
27673
27758
  return null;
27674
27759
  return { start, end };
27675
27760
  }
27761
+ function assertOrdinalRangeWithinCompartment(rangeStart, rangeEnd, compartmentStart, compartmentEnd) {
27762
+ if (rangeStart < compartmentStart || rangeEnd > compartmentEnd || rangeEnd < rangeStart) {
27763
+ throw new RangeError(`Canonical chunk range ${rangeStart}-${rangeEnd} lies outside compartment ${compartmentStart}-${compartmentEnd}`);
27764
+ }
27765
+ }
27676
27766
  function hashChunkText(text) {
27677
27767
  return createHash10("sha256").update(text).digest("hex");
27678
27768
  }
@@ -27761,6 +27851,10 @@ function canonicalizeInMemoryChunkTextForEmbedding(chunkText, startOrdinal, endO
27761
27851
  lines.push(`${formatOrdinalRange(retainedStart, retainedEnd)} ${roleLabel} ${retained.map(({ part }) => part).join(" / ")}`);
27762
27852
  continue;
27763
27853
  }
27854
+ const clipsRequestedRange = startOrdinal != null && lineStart < startOrdinal || endOrdinal != null && lineEnd > endOrdinal;
27855
+ if (clipsRequestedRange) {
27856
+ return "";
27857
+ }
27764
27858
  const parts = rawParts.filter((part) => !part.startsWith("TC:"));
27765
27859
  if (parts.length === 0)
27766
27860
  continue;
@@ -27773,6 +27867,12 @@ function chunkCanonicalText(canonicalText, startOrdinal, endOrdinal, maxInputTok
27773
27867
  const lines = canonicalText.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
27774
27868
  if (lines.length === 0 || endOrdinal < startOrdinal)
27775
27869
  return [];
27870
+ for (const line of lines) {
27871
+ const range = parseCanonicalLineRange(line);
27872
+ if (range) {
27873
+ assertOrdinalRangeWithinCompartment(range.start, range.end, startOrdinal, endOrdinal);
27874
+ }
27875
+ }
27776
27876
  const normalizedMax = normalizeCompartmentChunkMaxInputTokens(maxInputTokens);
27777
27877
  const effectiveMax = Math.max(1, Math.floor(normalizedMax * CHUNK_WINDOW_SAFETY_RATIO));
27778
27878
  const fullText = lines.join(`
@@ -27798,8 +27898,9 @@ function chunkCanonicalText(canonicalText, startOrdinal, endOrdinal, maxInputTok
27798
27898
  return;
27799
27899
  const text = currentLines.join(`
27800
27900
  `);
27901
+ assertOrdinalRangeWithinCompartment(currentStart, currentEnd, startOrdinal, endOrdinal);
27801
27902
  windows.push({
27802
- windowIndex: windows.length + 1,
27903
+ windowIndex: windows.length,
27803
27904
  startOrdinal: currentStart,
27804
27905
  endOrdinal: currentEnd,
27805
27906
  text,
@@ -27818,8 +27919,9 @@ function chunkCanonicalText(canonicalText, startOrdinal, endOrdinal, maxInputTok
27818
27919
  if (lineTokens > effectiveMax) {
27819
27920
  flush();
27820
27921
  for (const slice of splitOversizedLine(line, effectiveMax)) {
27922
+ assertOrdinalRangeWithinCompartment(lineStart, lineEnd, startOrdinal, endOrdinal);
27821
27923
  windows.push({
27822
- windowIndex: windows.length + 1,
27924
+ windowIndex: windows.length,
27823
27925
  startOrdinal: lineStart,
27824
27926
  endOrdinal: lineEnd,
27825
27927
  text: slice,
@@ -27969,34 +28071,57 @@ function mapBackfillCandidateRows(rows) {
27969
28071
  title: row.title
27970
28072
  }));
27971
28073
  }
28074
+ function renumberOneBasedChunkWindows(db, candidate, projectPath, modelId, windows) {
28075
+ const update = getRenumberEmbeddingWindowStatement(db);
28076
+ db.transaction(() => {
28077
+ for (const window of windows) {
28078
+ const result = update.run(window.windowIndex, candidate.id, modelId, projectPath, window.windowIndex + 1);
28079
+ if (result.changes !== 1) {
28080
+ throw new Error(`Failed to renumber compartment ${candidate.id} window ${window.windowIndex + 1}`);
28081
+ }
28082
+ }
28083
+ })();
28084
+ invalidateDecodedSearchPools(db, ([sessionId, cachedProjectPath, cachedModelId]) => sessionId === candidate.sessionId && cachedProjectPath === projectPath && cachedModelId === modelId);
28085
+ }
27972
28086
  function classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens) {
27973
28087
  const mappedText = buildCanonicalChunkTextFromFts(db, candidate.sessionId, candidate.startMessage, candidate.endMessage);
27974
28088
  if (mappedText === null)
27975
- return "deferred";
28089
+ return { defect: "deferred", windows: [] };
27976
28090
  const canonicalText = mappedText || buildCompartmentSummaryFallbackText(db, candidate.id);
27977
28091
  const windows = chunkCanonicalText(canonicalText, candidate.startMessage, candidate.endMessage, maxInputTokens);
27978
28092
  const existing = getExistingChunkHashes(db, candidate.id, modelId, projectPath);
27979
- if (windows.some((window) => !existing.has(window.windowIndex)))
27980
- return "missing";
28093
+ const isMatchingOneBasedSet = windows.length > 0 && existing.size === windows.length && windows.every((window) => existing.get(window.windowIndex + 1) === window.chunkHash);
28094
+ if (isMatchingOneBasedSet)
28095
+ return { defect: "renumber", windows };
28096
+ const expectedWindowIndexes = new Set(windows.map((window) => window.windowIndex));
28097
+ if ([...existing.keys()].some((windowIndex) => !expectedWindowIndexes.has(windowIndex))) {
28098
+ return { defect: "stale", windows };
28099
+ }
28100
+ if (windows.some((window) => !existing.has(window.windowIndex))) {
28101
+ return { defect: "missing", windows };
28102
+ }
27981
28103
  if (existing.size !== windows.length || windows.some((window) => existing.get(window.windowIndex) !== window.chunkHash)) {
27982
- return "stale";
28104
+ return { defect: "stale", windows };
27983
28105
  }
27984
- return null;
28106
+ return { defect: null, windows };
27985
28107
  }
27986
- function selectHashIncompleteChunkCandidates(db, projectPath, modelId, candidates, limit, maxInputTokens) {
28108
+ function selectHashIncompleteChunkCandidates(db, projectPath, modelId, candidates, limit, maxInputTokens, leaseHeldRenumber = false) {
27987
28109
  const missing = [];
27988
28110
  const stale = [];
27989
28111
  for (const candidate of candidates) {
27990
- const defect = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
28112
+ const { defect, windows } = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
27991
28113
  if (defect === "missing")
27992
28114
  missing.push(candidate);
27993
28115
  else if (defect === "stale")
27994
28116
  stale.push(candidate);
28117
+ else if (defect === "renumber" && leaseHeldRenumber) {
28118
+ renumberOneBasedChunkWindows(db, candidate, projectPath, modelId, windows);
28119
+ }
27995
28120
  }
27996
28121
  return [...missing, ...stale].slice(0, limit);
27997
28122
  }
27998
28123
  var sessionBackfillCandidateStatements = new WeakMap;
27999
- function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, limit, excludeIds, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS) {
28124
+ function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, limit, excludeIds, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, leaseHeldRenumber = false) {
28000
28125
  const exclusions = excludeIds && excludeIds.length > 0 ? excludeIds : [];
28001
28126
  const exclusionSql = exclusions.length > 0 ? `AND c.id NOT IN (${exclusions.map(() => "?").join(", ")})` : "";
28002
28127
  const stmt = exclusions.length > 0 ? db.prepare(`SELECT c.id AS id,
@@ -28035,7 +28160,7 @@ function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelI
28035
28160
  return cached;
28036
28161
  })();
28037
28162
  const rows = stmt.all(projectPath, sessionId, ...exclusions);
28038
- return selectHashIncompleteChunkCandidates(db, projectPath, modelId, mapBackfillCandidateRows(rows), Math.max(1, limit), maxInputTokens);
28163
+ return selectHashIncompleteChunkCandidates(db, projectPath, modelId, mapBackfillCandidateRows(rows), Math.max(1, limit), maxInputTokens, leaseHeldRenumber);
28039
28164
  }
28040
28165
  function countUnembeddedSessionCompartments(db, projectPath, sessionId, modelId, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS) {
28041
28166
  return loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, Number.MAX_SAFE_INTEGER, undefined, maxInputTokens).length;
@@ -28058,9 +28183,9 @@ function countSessionCompartmentEmbedCoverage(db, projectPath, sessionId, modelI
28058
28183
  const candidates = mapBackfillCandidateRows(rows);
28059
28184
  let embedded = 0;
28060
28185
  for (const candidate of candidates) {
28061
- if (classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens) === null) {
28186
+ const { defect } = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
28187
+ if (defect === null || defect === "renumber")
28062
28188
  embedded += 1;
28063
- }
28064
28189
  }
28065
28190
  return { embedded, total: candidates.length };
28066
28191
  }
@@ -28082,6 +28207,78 @@ function cosineSimilarity(a, b) {
28082
28207
  return denominator === 0 ? 0 : dotProduct / denominator;
28083
28208
  }
28084
28209
 
28210
+ // ../plugin/src/features/magic-context/memory/embedding-model-match.ts
28211
+ function parseEmbeddingModel(model) {
28212
+ const lastColon = model.lastIndexOf(":");
28213
+ if (lastColon > model.lastIndexOf("/")) {
28214
+ return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
28215
+ }
28216
+ return { base: model };
28217
+ }
28218
+ function normalizeEmbeddingModelId(model) {
28219
+ return parseEmbeddingModel(model.trim().toLowerCase()).base;
28220
+ }
28221
+ function matchNormalizedEmbeddingModels(a, b) {
28222
+ if (a.length === 0 || b.length === 0)
28223
+ return true;
28224
+ if (a === b)
28225
+ return true;
28226
+ const longer = a.length >= b.length ? a : b;
28227
+ const shorter = a.length >= b.length ? b : a;
28228
+ const isBoundary = (ch) => ch === "-" || ch === "/";
28229
+ if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
28230
+ return true;
28231
+ if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
28232
+ return true;
28233
+ return false;
28234
+ }
28235
+ function embeddingModelsMatch(served, requested) {
28236
+ const servedNormalized = served.trim().toLowerCase();
28237
+ const requestedNormalized = requested.trim().toLowerCase();
28238
+ const servedModel = parseEmbeddingModel(servedNormalized);
28239
+ const requestedModel = parseEmbeddingModel(requestedNormalized);
28240
+ if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
28241
+ return false;
28242
+ }
28243
+ return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
28244
+ }
28245
+ var QWEN3_QUERY_INSTRUCTION = `Instruct: Given a web search query, retrieve relevant passages that answer the query
28246
+ Query: `;
28247
+ var INSTRUCT_WEB_SEARCH_QUERY_PREFIX = QWEN3_QUERY_INSTRUCTION;
28248
+ var EMBEDDING_MODEL_PREFIX_FAMILIES = [
28249
+ {
28250
+ family: "qwen3-embedding",
28251
+ basenamePattern: /^qwen3-embedding(?:-|$)/,
28252
+ prefixes: { queryPrefix: QWEN3_QUERY_INSTRUCTION, documentPrefix: "" }
28253
+ },
28254
+ {
28255
+ family: "gte-qwen-instruct",
28256
+ basenamePattern: /^gte-qwen.*-instruct(?:-|$)/,
28257
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
28258
+ },
28259
+ {
28260
+ family: "e5-instruct",
28261
+ basenamePattern: /^(?:multilingual-)?e5-.*-instruct(?:-|$)/,
28262
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
28263
+ },
28264
+ {
28265
+ family: "nomic-embed-text",
28266
+ basenamePattern: /^nomic-embed-text(?:-|$)/,
28267
+ prefixes: { queryPrefix: "search_query: ", documentPrefix: "search_document: " }
28268
+ }
28269
+ ];
28270
+ function modelBasename(model) {
28271
+ const normalized = normalizeEmbeddingModelId(model);
28272
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
28273
+ }
28274
+ function resolveEmbeddingTextPrefixes(model, queryInstruction, documentPrefix) {
28275
+ const family = EMBEDDING_MODEL_PREFIX_FAMILIES.find(({ basenamePattern }) => basenamePattern.test(modelBasename(model)));
28276
+ return {
28277
+ queryPrefix: queryInstruction === false ? "" : queryInstruction !== undefined ? queryInstruction : family?.prefixes.queryPrefix ?? "",
28278
+ documentPrefix: documentPrefix ?? family?.prefixes.documentPrefix ?? ""
28279
+ };
28280
+ }
28281
+
28085
28282
  // ../plugin/src/features/magic-context/memory/normalize-hash.ts
28086
28283
  import { createHash as createHash11 } from "node:crypto";
28087
28284
  function normalizeMemoryContent(content) {
@@ -28110,6 +28307,7 @@ function getEmbeddingProviderIdentity(config) {
28110
28307
  throw new Error("Unknown embedding provider");
28111
28308
  }
28112
28309
  const truncate = config.provider === "openai-compatible" ? config.truncate?.trim() : undefined;
28310
+ const documentPrefix = config.provider === "openai-compatible" ? resolveEmbeddingTextPrefixes(config.model, config.query_instruction, config.document_prefix).documentPrefix : "";
28113
28311
  const localDtype = config.provider === "local" && config.local_dtype && config.local_dtype !== "fp32" ? config.local_dtype : undefined;
28114
28312
  const identityInput = config.provider === "openai-compatible" ? {
28115
28313
  provider: "openai-compatible",
@@ -28117,6 +28315,7 @@ function getEmbeddingProviderIdentity(config) {
28117
28315
  endpoint: normalizeEndpoint2(config.endpoint),
28118
28316
  apiKeyPresent: Boolean(config.api_key?.trim()),
28119
28317
  inputType: config.input_type?.trim() || "",
28318
+ ...documentPrefix ? { documentPrefix } : {},
28120
28319
  ...truncate ? { truncate } : {}
28121
28320
  } : {
28122
28321
  provider: "local",
@@ -28863,37 +29062,6 @@ function blockedEmbeddingEndpointReason(endpoint) {
28863
29062
  function normalizeEndpoint3(endpoint) {
28864
29063
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
28865
29064
  }
28866
- function parseEmbeddingModel(model) {
28867
- const lastColon = model.lastIndexOf(":");
28868
- if (lastColon > model.lastIndexOf("/")) {
28869
- return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
28870
- }
28871
- return { base: model };
28872
- }
28873
- function matchNormalizedEmbeddingModels(a, b) {
28874
- if (a.length === 0 || b.length === 0)
28875
- return true;
28876
- if (a === b)
28877
- return true;
28878
- const longer = a.length >= b.length ? a : b;
28879
- const shorter = a.length >= b.length ? b : a;
28880
- const isBoundary = (ch) => ch === "-" || ch === "/";
28881
- if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
28882
- return true;
28883
- if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
28884
- return true;
28885
- return false;
28886
- }
28887
- function embeddingModelsMatch(served, requested) {
28888
- const a = served.trim().toLowerCase();
28889
- const b = requested.trim().toLowerCase();
28890
- const servedModel = parseEmbeddingModel(a);
28891
- const requestedModel = parseEmbeddingModel(b);
28892
- if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
28893
- return false;
28894
- }
28895
- return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
28896
- }
28897
29065
  var FAILURE_THRESHOLD = 3;
28898
29066
  var FAILURE_WINDOW_MS = 60000;
28899
29067
  var OPEN_DURATION_MS = 5 * 60000;
@@ -28907,6 +29075,8 @@ class OpenAICompatibleEmbeddingProvider {
28907
29075
  apiKey;
28908
29076
  inputType;
28909
29077
  queryInputType;
29078
+ queryPrefix;
29079
+ documentPrefix;
28910
29080
  truncate;
28911
29081
  initialized = false;
28912
29082
  failureTimes = [];
@@ -28921,6 +29091,9 @@ class OpenAICompatibleEmbeddingProvider {
28921
29091
  this.apiKey = options.apiKey?.trim() ?? "";
28922
29092
  this.inputType = options.inputType?.trim() ?? "";
28923
29093
  this.queryInputType = options.queryInputType?.trim() ?? "";
29094
+ const prefixes = resolveEmbeddingTextPrefixes(this.model, options.queryInstruction, options.documentPrefix);
29095
+ this.queryPrefix = prefixes.queryPrefix;
29096
+ this.documentPrefix = prefixes.documentPrefix;
28924
29097
  this.truncate = options.truncate?.trim() ?? "";
28925
29098
  this.maxInputTokens = typeof options.maxInputTokens === "number" && Number.isFinite(options.maxInputTokens) ? Math.max(1, Math.floor(options.maxInputTokens)) : 512;
28926
29099
  this.modelId = getEmbeddingProviderIdentity({
@@ -28929,6 +29102,7 @@ class OpenAICompatibleEmbeddingProvider {
28929
29102
  model: this.model,
28930
29103
  ...this.apiKey ? { api_key: this.apiKey } : {},
28931
29104
  ...this.inputType ? { input_type: this.inputType } : {},
29105
+ ...options.documentPrefix !== undefined ? { document_prefix: options.documentPrefix } : {},
28932
29106
  ...this.truncate ? { truncate: this.truncate } : {}
28933
29107
  });
28934
29108
  }
@@ -28963,7 +29137,8 @@ class OpenAICompatibleEmbeddingProvider {
28963
29137
  if (texts.length === 0) {
28964
29138
  return [];
28965
29139
  }
28966
- const requestTexts = texts.map((t) => t.trim().length === 0 ? " " : t);
29140
+ const textPrefix = purpose === "query" ? this.queryPrefix : this.documentPrefix;
29141
+ const requestTexts = texts.map((text) => `${textPrefix}${text.trim().length === 0 ? " " : text}`);
28967
29142
  if (!await this.initialize()) {
28968
29143
  return Array.from({ length: texts.length }, () => null);
28969
29144
  }
@@ -29930,6 +30105,8 @@ function resolveEmbeddingConfig(config) {
29930
30105
  ...apiKey ? { api_key: apiKey } : {},
29931
30106
  ...inputType ? { input_type: inputType } : {},
29932
30107
  ...queryInputType ? { query_input_type: queryInputType } : {},
30108
+ ...config.query_instruction !== undefined ? { query_instruction: config.query_instruction } : {},
30109
+ ...config.document_prefix !== undefined ? { document_prefix: config.document_prefix } : {},
29933
30110
  ...truncate ? { truncate } : {},
29934
30111
  ...config.max_input_tokens ? {
29935
30112
  max_input_tokens: normalizeCompartmentChunkMaxInputTokens(config.max_input_tokens)
@@ -29977,6 +30154,8 @@ function createProvider(config, context) {
29977
30154
  apiKey: config.api_key,
29978
30155
  inputType: config.input_type,
29979
30156
  queryInputType: config.query_input_type,
30157
+ queryInstruction: config.query_instruction,
30158
+ documentPrefix: config.document_prefix,
29980
30159
  truncate: config.truncate,
29981
30160
  maxInputTokens: config.max_input_tokens
29982
30161
  });
@@ -31142,8 +31321,6 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
31142
31321
  recordSessionProjectIdentity(db, sessionId, projectIdentity);
31143
31322
  const maxInputTokens = getProjectEmbeddingMaxInputTokens(projectIdentity);
31144
31323
  const total = countUnembeddedSessionCompartments(db, projectIdentity, sessionId, snapshot.chunkModelId, maxInputTokens);
31145
- if (total === 0)
31146
- return { status: "nothing", embedded: 0, total: 0 };
31147
31324
  const holderId = `session-embed-${randomUUID2()}`;
31148
31325
  const lease = acquireGitSweepLease(db, projectIdentity, holderId, { ignoreCooldown: true });
31149
31326
  if (!lease.acquired)
@@ -31179,7 +31356,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
31179
31356
  aborted = true;
31180
31357
  break;
31181
31358
  }
31182
- const candidates = loadUnembeddedSessionChunkCandidates(db, projectIdentity, sessionId, snapshot.chunkModelId, batchSize, [...skipIds, ...failedIds], maxInputTokens);
31359
+ const candidates = loadUnembeddedSessionChunkCandidates(db, projectIdentity, sessionId, snapshot.chunkModelId, batchSize, [...skipIds, ...failedIds], maxInputTokens, true);
31183
31360
  if (candidates.length === 0)
31184
31361
  break;
31185
31362
  const {
@@ -31221,6 +31398,8 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
31221
31398
  log("[magic-context] embed drain: lease release failed (will TTL-expire):", error);
31222
31399
  }
31223
31400
  }
31401
+ if (total === 0)
31402
+ return { status: "nothing", embedded: 0, total: 0 };
31224
31403
  if (aborted)
31225
31404
  return { status: "aborted", embedded, total, failed: failedIds.length };
31226
31405
  if (providerDown || failedIds.length > 0) {
@@ -31291,6 +31470,8 @@ function createProvider2(config) {
31291
31470
  apiKey: config.api_key,
31292
31471
  inputType: config.input_type,
31293
31472
  queryInputType: config.query_input_type,
31473
+ queryInstruction: config.query_instruction,
31474
+ documentPrefix: config.document_prefix,
31294
31475
  truncate: config.truncate,
31295
31476
  maxInputTokens: config.max_input_tokens
31296
31477
  });
@@ -31349,6 +31530,8 @@ var EMBEDDING_AFFECTING_KEYS = new Set([
31349
31530
  "embedding.truncate",
31350
31531
  "embedding.max_input_tokens",
31351
31532
  "embedding.query_input_type",
31533
+ "embedding.query_instruction",
31534
+ "embedding.document_prefix",
31352
31535
  "embedding.fallback_provider",
31353
31536
  "subc",
31354
31537
  "subc.connection_file",
@@ -39480,4 +39663,4 @@ function registerMagicContextTools(pi, opts) {
39480
39663
  }
39481
39664
  }
39482
39665
 
39483
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, resolveModelConfigValue, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, getProtectedTokensTierOverrides, sanitizeDiagnosticText, hasShareabilitySensitiveText, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHarness, getHarness, ensureCortexKitArtifactGitignore, getProjectMagicContextHistorianDir, getMagicContextStorageResolution, getMagicContextStorageDir, log, sessionLog, flushLogger, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, getRecentTagOwnerMessageIds, 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, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, resolveOpenCodeDbPath, openCodeDbPathExists, formatOpenCodeDbMissingStatusLine, formatOpenCodeDbReadFailureStatusLine, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, getOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, Database, closeQuietly, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, DROPPED_INPUT_MESSAGE, droppedInputMarker, containsDroppedInputPlaceholder, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, logSlowWriteTransaction, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, piHarnessKindFromExecutable, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, isProviderOverflowFailClosedProven, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, BoundedSessionMap, MIN_PLAUSIBLE_CONTEXT_LIMIT, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, 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, syncCtxMemoryToolEnabled, registerMagicContextTools };
39666
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, resolveModelConfigValue, resolveModelConfigOrDefault, DEFAULT_HISTORIAN_TIMEOUT_MS, getProtectedTokensTierOverrides, sanitizeDiagnosticText, hasShareabilitySensitiveText, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHarness, getHarness, ensureCortexKitArtifactGitignore, getProjectMagicContextHistorianDir, getMagicContextStorageResolution, getMagicContextStorageDir, log, sessionLog, flushLogger, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, getRecentTagOwnerMessageIds, 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, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, resolveOpenCodeDbPath, openCodeDbPathExists, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, Database, closeQuietly, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, DROPPED_INPUT_MESSAGE, droppedInputMarker, containsDroppedInputPlaceholder, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, logSlowWriteTransaction, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, piHarnessKindFromExecutable, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, isProviderOverflowFailClosedProven, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, BoundedSessionMap, MIN_PLAUSIBLE_CONTEXT_LIMIT, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, 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, syncCtxMemoryToolEnabled, registerMagicContextTools };