@cortexkit/opencode-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.
Files changed (70) hide show
  1. package/dist/config/project-security.d.ts +3 -2
  2. package/dist/config/project-security.d.ts.map +1 -1
  3. package/dist/config/schema/magic-context.d.ts +20 -0
  4. package/dist/config/schema/magic-context.d.ts.map +1 -1
  5. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +8 -4
  6. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  7. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  8. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
  9. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  10. package/dist/features/magic-context/memory/embedding-identity.d.ts.map +1 -1
  11. package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
  12. package/dist/features/magic-context/memory/embedding-model-match.d.ts +41 -0
  13. package/dist/features/magic-context/memory/embedding-model-match.d.ts.map +1 -0
  14. package/dist/features/magic-context/memory/embedding-openai.d.ts +7 -20
  15. package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
  16. package/dist/features/magic-context/memory/embedding-provider.d.ts +2 -2
  17. package/dist/features/magic-context/memory/embedding-provider.d.ts.map +1 -1
  18. package/dist/features/magic-context/memory/embedding-synapse.d.ts +5 -4
  19. package/dist/features/magic-context/memory/embedding-synapse.d.ts.map +1 -1
  20. package/dist/features/magic-context/memory/embedding.d.ts.map +1 -1
  21. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/compartment-runner-validation.d.ts +1 -1
  26. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/embed-session-state.d.ts +1 -1
  28. package/dist/hooks/magic-context/embed-session-state.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/execute-status.d.ts +2 -0
  30. package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/format-embed-failure.d.ts +2 -1
  32. package/dist/hooks/magic-context/format-embed-failure.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/maintenance-authority.d.ts +2 -2
  34. package/dist/hooks/magic-context/maintenance-authority.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  36. package/dist/{index-c9hamh36.js → index-1q9kay7n.js} +534 -120
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +264 -108
  39. package/dist/plugin/embedding-bootstrap-helpers.d.ts.map +1 -1
  40. package/dist/plugin/embedding-routing.d.ts.map +1 -1
  41. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  42. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  43. package/dist/{recomp-orchestrator-3atsasjy.js → recomp-orchestrator-m33b3rk9.js} +1 -1
  44. package/dist/shared/rpc-types.d.ts +10 -0
  45. package/dist/shared/rpc-types.d.ts.map +1 -1
  46. package/dist/shared/status-detail-text.d.ts +3 -1
  47. package/dist/shared/status-detail-text.d.ts.map +1 -1
  48. package/dist/shared/status-summary.d.ts +30 -0
  49. package/dist/shared/status-summary.d.ts.map +1 -0
  50. package/dist/shared/tail-hygiene-status.d.ts +1 -0
  51. package/dist/shared/tail-hygiene-status.d.ts.map +1 -1
  52. package/dist/shared/user-facing-codes.d.ts +191 -0
  53. package/dist/shared/user-facing-codes.d.ts.map +1 -0
  54. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  55. package/dist/tools/ctx-note/tools.d.ts.map +1 -1
  56. package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
  57. package/package.json +1 -1
  58. package/src/config/project-security.test.ts +10 -2
  59. package/src/config/project-security.ts +12 -5
  60. package/src/config/schema/magic-context.test.ts +29 -0
  61. package/src/config/schema/magic-context.ts +24 -0
  62. package/src/shared/rpc-types.ts +10 -0
  63. package/src/shared/status-detail-text.test.ts +93 -24
  64. package/src/shared/status-detail-text.ts +9 -2
  65. package/src/shared/status-summary.ts +167 -0
  66. package/src/shared/tail-hygiene-status.ts +8 -0
  67. package/src/shared/user-facing-codes.test.ts +140 -0
  68. package/src/shared/user-facing-codes.ts +276 -0
  69. package/src/tui/index.tsx +41 -8
  70. package/src/tui-compiled/index.tsx +660 -647
@@ -15771,6 +15771,28 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
15771
15771
  return payload;
15772
15772
  };
15773
15773
  });
15774
+ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
15775
+ $ZodType.init(inst, def);
15776
+ if (def.values.length === 0) {
15777
+ throw new Error("Cannot create literal schema with no valid values");
15778
+ }
15779
+ const values = new Set(def.values);
15780
+ inst._zod.values = values;
15781
+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
15782
+ inst._zod.parse = (payload, _ctx) => {
15783
+ const input = payload.value;
15784
+ if (values.has(input)) {
15785
+ return payload;
15786
+ }
15787
+ payload.issues.push({
15788
+ code: "invalid_value",
15789
+ values: def.values,
15790
+ input,
15791
+ inst
15792
+ });
15793
+ return payload;
15794
+ };
15795
+ });
15774
15796
  var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
15775
15797
  $ZodType.init(inst, def);
15776
15798
  inst._zod.optin = "optional";
@@ -16976,6 +16998,44 @@ var enumProcessor = (schema, _ctx, json, _params) => {
16976
16998
  json.type = "string";
16977
16999
  json.enum = values;
16978
17000
  };
17001
+ var literalProcessor = (schema, ctx, json, _params) => {
17002
+ const def = schema._zod.def;
17003
+ const vals = [];
17004
+ for (const val of def.values) {
17005
+ if (val === undefined) {
17006
+ if (ctx.unrepresentable === "throw") {
17007
+ throw new Error("Literal `undefined` cannot be represented in JSON Schema");
17008
+ }
17009
+ } else if (typeof val === "bigint") {
17010
+ if (ctx.unrepresentable === "throw") {
17011
+ throw new Error("BigInt literals cannot be represented in JSON Schema");
17012
+ } else {
17013
+ vals.push(Number(val));
17014
+ }
17015
+ } else {
17016
+ vals.push(val);
17017
+ }
17018
+ }
17019
+ if (vals.length === 0) {} else if (vals.length === 1) {
17020
+ const val = vals[0];
17021
+ json.type = val === null ? "null" : typeof val;
17022
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
17023
+ json.enum = [val];
17024
+ } else {
17025
+ json.const = val;
17026
+ }
17027
+ } else {
17028
+ if (vals.every((v) => typeof v === "number"))
17029
+ json.type = "number";
17030
+ if (vals.every((v) => typeof v === "string"))
17031
+ json.type = "string";
17032
+ if (vals.every((v) => typeof v === "boolean"))
17033
+ json.type = "boolean";
17034
+ if (vals.every((v) => v === null))
17035
+ json.type = "null";
17036
+ json.enum = vals;
17037
+ }
17038
+ };
16979
17039
  var customProcessor = (_schema, ctx, _json, _params) => {
16980
17040
  if (ctx.unrepresentable === "throw") {
16981
17041
  throw new Error("Custom types cannot be represented in JSON Schema");
@@ -17914,6 +17974,27 @@ function _enum(values, params) {
17914
17974
  ...normalizeParams(params)
17915
17975
  });
17916
17976
  }
17977
+ var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
17978
+ $ZodLiteral.init(inst, def);
17979
+ ZodType.init(inst, def);
17980
+ inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
17981
+ inst.values = new Set(def.values);
17982
+ Object.defineProperty(inst, "value", {
17983
+ get() {
17984
+ if (def.values.length > 1) {
17985
+ throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
17986
+ }
17987
+ return def.values[0];
17988
+ }
17989
+ });
17990
+ });
17991
+ function literal(value, params) {
17992
+ return new ZodLiteral({
17993
+ type: "literal",
17994
+ values: Array.isArray(value) ? value : [value],
17995
+ ...normalizeParams(params)
17996
+ });
17997
+ }
17917
17998
  var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
17918
17999
  $ZodTransform.init(inst, def);
17919
18000
  ZodType.init(inst, def);
@@ -18604,6 +18685,8 @@ var BaseEmbeddingConfigSchema = object({
18604
18685
  api_key: string().optional().describe("API key for remote embedding provider (optional)"),
18605
18686
  input_type: string().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."),
18606
18687
  query_input_type: string().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."),
18688
+ query_instruction: union([string(), 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."),
18689
+ document_prefix: string().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."),
18607
18690
  truncate: string().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."),
18608
18691
  max_input_tokens: number2().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
18609
18692
  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."),
@@ -18655,6 +18738,8 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
18655
18738
  ...apiKey ? { api_key: apiKey } : {},
18656
18739
  ...inputType ? { input_type: inputType } : {},
18657
18740
  ...queryInputType ? { query_input_type: queryInputType } : {},
18741
+ ...data.query_instruction !== undefined ? { query_instruction: data.query_instruction } : {},
18742
+ ...data.document_prefix !== undefined ? { document_prefix: data.document_prefix } : {},
18658
18743
  ...truncate ? { truncate } : {},
18659
18744
  ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {}
18660
18745
  };
@@ -18680,6 +18765,8 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
18680
18765
  ...apiKey ? { api_key: apiKey } : {},
18681
18766
  ...inputType ? { input_type: inputType } : {},
18682
18767
  ...queryInputType ? { query_input_type: queryInputType } : {},
18768
+ ...data.query_instruction !== undefined ? { query_instruction: data.query_instruction } : {},
18769
+ ...data.document_prefix !== undefined ? { document_prefix: data.document_prefix } : {},
18683
18770
  ...truncate ? { truncate } : {},
18684
18771
  ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {}
18685
18772
  };
@@ -23846,6 +23933,242 @@ async function runMemoryMigration(deps) {
23846
23933
  }
23847
23934
  }
23848
23935
 
23936
+ // src/shared/user-facing-codes.ts
23937
+ var USER_FACING_FAILURES = {
23938
+ historian_unavailable: {
23939
+ code: "MC-H01",
23940
+ sentence: "History compression could not finish this turn.",
23941
+ action: "It will retry automatically."
23942
+ },
23943
+ recomp_unavailable: {
23944
+ code: "MC-R01",
23945
+ sentence: "History compression could not be rebuilt.",
23946
+ action: "Run /ctx-recomp again."
23947
+ },
23948
+ dream_provider_timeout: {
23949
+ code: "MC-D01",
23950
+ sentence: "Memory maintenance took too long to respond.",
23951
+ action: "Run /ctx-dream again."
23952
+ },
23953
+ dream_provider_error: {
23954
+ code: "MC-D02",
23955
+ sentence: "Memory maintenance could not reach its model.",
23956
+ action: "Check the model connection, then run /ctx-dream again."
23957
+ },
23958
+ dream_empty_completion: {
23959
+ code: "MC-D03",
23960
+ sentence: "Memory maintenance received no usable response.",
23961
+ action: "Run /ctx-dream again."
23962
+ },
23963
+ dream_no_models: {
23964
+ code: "MC-D04",
23965
+ sentence: "Memory maintenance has no model available.",
23966
+ action: "Check the model settings, then run /ctx-dream again."
23967
+ },
23968
+ dream_child_aborted: {
23969
+ code: "MC-D05",
23970
+ sentence: "Memory maintenance was interrupted.",
23971
+ action: "Run /ctx-dream again."
23972
+ },
23973
+ dream_parse_failed: {
23974
+ code: "MC-D06",
23975
+ sentence: "Memory maintenance could not use the model response.",
23976
+ action: "Run /ctx-dream again."
23977
+ },
23978
+ dream_unknown: {
23979
+ code: "MC-D07",
23980
+ sentence: "Memory maintenance could not finish.",
23981
+ action: "Run /ctx-dream again."
23982
+ },
23983
+ embedding_substitution_rejected: {
23984
+ code: "MC-E01",
23985
+ sentence: "Search indexing could not use the selected model.",
23986
+ action: "Check the embedding model setting, then run /ctx-embed start again."
23987
+ },
23988
+ embedding_http_error: {
23989
+ code: "MC-E02",
23990
+ sentence: "The search indexing provider refused the request.",
23991
+ action: "Check the provider connection and credentials, then run /ctx-embed start again."
23992
+ },
23993
+ embedding_transport_error: {
23994
+ code: "MC-E03",
23995
+ sentence: "Search indexing could not reach its provider.",
23996
+ action: "Check the connection, then run /ctx-embed start again."
23997
+ },
23998
+ embedding_invalid_envelope: {
23999
+ code: "MC-E04",
24000
+ sentence: "Search indexing received an unsupported response.",
24001
+ action: "Check the embedding endpoint, then run /ctx-embed start again."
24002
+ },
24003
+ embedding_empty_result: {
24004
+ code: "MC-E05",
24005
+ sentence: "Search indexing received no usable result.",
24006
+ action: "Run /ctx-embed start again."
24007
+ },
24008
+ embedding_certification_refusal: {
24009
+ code: "MC-E06",
24010
+ sentence: "Search indexing is not ready for this provider.",
24011
+ action: "Finish the provider setup, or set a fallback provider in the embedding settings, then run /ctx-embed start again."
24012
+ },
24013
+ embedding_credential_required: {
24014
+ code: "MC-E07",
24015
+ sentence: "Search indexing needs provider credentials.",
24016
+ action: "Sign in to the provider, then run /ctx-embed start again."
24017
+ },
24018
+ embedding_local_binding_missing: {
24019
+ code: "MC-E08",
24020
+ sentence: "Local search indexing is unavailable on this system.",
24021
+ action: "Run `npx @cortexkit/magic-context doctor`, then retry."
24022
+ },
24023
+ embedding_local_fs_unavailable: {
24024
+ code: "MC-E09",
24025
+ sentence: "Local search indexing cannot save its model files.",
24026
+ action: "Update or reinstall Magic Context, then retry."
24027
+ },
24028
+ embedding_local_download_failure: {
24029
+ code: "MC-E10",
24030
+ sentence: "Local search indexing could not download its model.",
24031
+ action: "Check the network connection, then retry."
24032
+ },
24033
+ embedding_local_runtime_error: {
24034
+ code: "MC-E11",
24035
+ sentence: "Local search indexing could not start.",
24036
+ action: "Run `npx @cortexkit/magic-context doctor`, then retry."
24037
+ },
24038
+ embedding_unavailable: {
24039
+ code: "MC-E12",
24040
+ sentence: "Search indexing could not finish.",
24041
+ action: "Run /ctx-embed start again."
24042
+ },
24043
+ status_unavailable: {
24044
+ code: "MC-S01",
24045
+ sentence: "Magic Context status is temporarily unavailable.",
24046
+ action: "Retry /ctx-status in a moment."
24047
+ },
24048
+ transform_update_failed: {
24049
+ code: "MC-S02",
24050
+ sentence: "The last context update did not finish.",
24051
+ action: "Send another message to retry."
24052
+ },
24053
+ configuration_warning: {
24054
+ code: "MC-S03",
24055
+ sentence: "Some configuration settings could not be applied.",
24056
+ action: "Fix the configuration warning shown in /ctx-status diagnostics, then restart."
24057
+ },
24058
+ status_log_unavailable: {
24059
+ code: "MC-S04",
24060
+ sentence: "Some diagnostic details could not be saved.",
24061
+ action: "Retry /ctx-status in a moment."
24062
+ },
24063
+ memory_writes_paused: {
24064
+ code: "MC-C01",
24065
+ sentence: "Memory writes are paused while the engine syncs.",
24066
+ action: "Retry in a moment."
24067
+ },
24068
+ memory_access_unavailable: {
24069
+ code: "MC-C02",
24070
+ sentence: "Memory access is temporarily unavailable.",
24071
+ action: "Retry in a moment."
24072
+ },
24073
+ note_changes_paused: {
24074
+ code: "MC-C03",
24075
+ sentence: "Note changes are paused while the engine syncs.",
24076
+ action: "Retry in a moment."
24077
+ },
24078
+ note_access_unavailable: {
24079
+ code: "MC-C04",
24080
+ sentence: "Notes are temporarily unavailable.",
24081
+ action: "Retry in a moment."
24082
+ },
24083
+ context_cleanup_paused: {
24084
+ code: "MC-C05",
24085
+ sentence: "Context cleanup is paused while the engine syncs.",
24086
+ action: "Retry in a moment."
24087
+ },
24088
+ partial_history_unavailable: {
24089
+ code: "MC-C06",
24090
+ sentence: "Partial history compression is not available in the current mode.",
24091
+ action: "Run /ctx-recomp without a range."
24092
+ },
24093
+ session_upgrade_unavailable: {
24094
+ code: "MC-C07",
24095
+ sentence: "Session upgrade is not available in the current mode.",
24096
+ action: "Run /ctx-recomp instead."
24097
+ },
24098
+ smart_note_conditions_unavailable: {
24099
+ code: "MC-C08",
24100
+ sentence: "Conditional notes are not available in the current mode.",
24101
+ action: "Save a regular note without a condition."
24102
+ },
24103
+ history_compression_paused: {
24104
+ code: "MC-C09",
24105
+ sentence: "History compression is paused while the engine syncs.",
24106
+ action: "Retry in a moment."
24107
+ },
24108
+ context_service_unavailable: {
24109
+ code: "MC-C10",
24110
+ sentence: "Magic Context is temporarily unavailable.",
24111
+ action: "Retry in a moment."
24112
+ }
24113
+ };
24114
+ function renderUserFacingFailure(key, style = "markdown") {
24115
+ const failure = USER_FACING_FAILURES[key];
24116
+ const action = style === "plain" ? failure.action.replaceAll("`", "") : failure.action;
24117
+ return `${failure.sentence} ${action} (${failure.code})`;
24118
+ }
24119
+ function userFacingFailureCode(key) {
24120
+ return USER_FACING_FAILURES[key].code;
24121
+ }
24122
+ var CAPABILITY_FAILURES = {
24123
+ memory_write: "memory_writes_paused",
24124
+ memory_access: "memory_access_unavailable",
24125
+ note_change: "note_changes_paused",
24126
+ note_access: "note_access_unavailable",
24127
+ context_cleanup: "context_cleanup_paused",
24128
+ partial_history: "partial_history_unavailable",
24129
+ session_upgrade: "session_upgrade_unavailable",
24130
+ smart_note_condition: "smart_note_conditions_unavailable",
24131
+ history_compression: "history_compression_paused",
24132
+ context_service: "context_service_unavailable"
24133
+ };
24134
+ function renderCapabilityRefusal(capability) {
24135
+ return renderUserFacingFailure(CAPABILITY_FAILURES[capability]);
24136
+ }
24137
+ function capabilityRefusalCode(capability) {
24138
+ return userFacingFailureCode(CAPABILITY_FAILURES[capability]);
24139
+ }
24140
+ var DREAM_FAILURE_KEYS = {
24141
+ provider_timeout: "dream_provider_timeout",
24142
+ provider_error: "dream_provider_error",
24143
+ empty_completion: "dream_empty_completion",
24144
+ no_models: "dream_no_models",
24145
+ child_aborted: "dream_child_aborted",
24146
+ parse_failed: "dream_parse_failed",
24147
+ unknown: "dream_unknown"
24148
+ };
24149
+ var EMBEDDING_FAILURE_KEYS = {
24150
+ substitution_rejected: "embedding_substitution_rejected",
24151
+ http_error: "embedding_http_error",
24152
+ transport_error: "embedding_transport_error",
24153
+ invalid_envelope: "embedding_invalid_envelope",
24154
+ empty_result: "embedding_empty_result",
24155
+ certification_refusal: "embedding_certification_refusal",
24156
+ credential_required: "embedding_credential_required",
24157
+ local_binding_missing: "embedding_local_binding_missing",
24158
+ local_fs_unavailable: "embedding_local_fs_unavailable",
24159
+ local_download_failure: "embedding_local_download_failure",
24160
+ local_runtime_error: "embedding_local_runtime_error"
24161
+ };
24162
+ function renderDreamFailure(failureClass, style = "markdown") {
24163
+ return renderUserFacingFailure(DREAM_FAILURE_KEYS[failureClass], style);
24164
+ }
24165
+ function dreamFailureCode(failureClass) {
24166
+ return userFacingFailureCode(DREAM_FAILURE_KEYS[failureClass]);
24167
+ }
24168
+ function renderEmbeddingFailure(failureClass, style = "markdown") {
24169
+ return renderUserFacingFailure(EMBEDDING_FAILURE_KEYS[failureClass], style);
24170
+ }
24171
+
23849
24172
  // src/features/magic-context/compartment-chunk-embedding.ts
23850
24173
  import { createHash as createHash14 } from "node:crypto";
23851
24174
 
@@ -25628,7 +25951,8 @@ function getSynapseBatchRequestKey(args) {
25628
25951
  allow_equivalent: false,
25629
25952
  accept_declared: false,
25630
25953
  ids: args.items.map((item) => item.id),
25631
- content_sha256: args.items.map((item) => item.contentSha256)
25954
+ content_sha256: args.items.map((item) => item.contentSha256),
25955
+ ...args.purpose === "query" ? { purpose: args.purpose } : {}
25632
25956
  }));
25633
25957
  }
25634
25958
  function hashContent(text) {
@@ -25889,7 +26213,7 @@ class SynapseEmbeddingProvider {
25889
26213
  })();
25890
26214
  return this.initializing;
25891
26215
  }
25892
- async embed(text, signal) {
26216
+ async embed(text, signal, purpose = "passage") {
25893
26217
  if (!await this.initialize() || signal?.aborted || !this.metadata)
25894
26218
  return null;
25895
26219
  if (estimateTokens(text) > this.metadata.max_tokens)
@@ -25899,6 +26223,7 @@ class SynapseEmbeddingProvider {
25899
26223
  const value = await this.callWithRetry("embed.query", this.requestConstraints({
25900
26224
  id,
25901
26225
  text,
26226
+ purpose,
25902
26227
  deadline_ms: this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS
25903
26228
  }), this.options.queryTimeoutMs ?? SYNAPSE_DEFAULT_QUERY_TIMEOUT_MS, true, signal);
25904
26229
  const extracted = extractVector(value);
@@ -25918,7 +26243,7 @@ class SynapseEmbeddingProvider {
25918
26243
  return null;
25919
26244
  }
25920
26245
  }
25921
- async embedBatch(texts, signal) {
26246
+ async embedBatch(texts, signal, purpose = "passage") {
25922
26247
  if (texts.length === 0)
25923
26248
  return [];
25924
26249
  const items = texts.map((text, index) => ({
@@ -25926,10 +26251,10 @@ class SynapseEmbeddingProvider {
25926
26251
  text,
25927
26252
  contentSha256: hashContent(text)
25928
26253
  }));
25929
- const map = await this.embedItems(items, signal);
26254
+ const map = await this.embedItems(items, signal, purpose);
25930
26255
  return items.map((item) => map.get(item.id) ?? null);
25931
26256
  }
25932
- async embedItems(items, signal) {
26257
+ async embedItems(items, signal, purpose = "passage") {
25933
26258
  const output = new Map;
25934
26259
  if (items.length === 0 || !await this.initialize() || !this.metadata || signal?.aborted) {
25935
26260
  return output;
@@ -25942,12 +26267,12 @@ class SynapseEmbeddingProvider {
25942
26267
  const page = this.nextPage(eligibleItems, start);
25943
26268
  start += page.length;
25944
26269
  try {
25945
- const requestKey = this.requestKey(page);
26270
+ const requestKey = this.requestKey(page, purpose);
25946
26271
  let body = {};
25947
26272
  let restarted = false;
25948
26273
  for (;; ) {
25949
26274
  try {
25950
- body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
26275
+ body = await this.callWithRetry("embed.batch", this.batchRequest(page, requestKey, purpose), this.options.batchTimeoutMs ?? SYNAPSE_DEFAULT_BATCH_TIMEOUT_MS, true, signal);
25951
26276
  const first = responseBody(body);
25952
26277
  const jobId = typeof first.job_id === "string" ? first.job_id : null;
25953
26278
  if (jobId)
@@ -26017,24 +26342,26 @@ class SynapseEmbeddingProvider {
26017
26342
  accept_declared: false
26018
26343
  };
26019
26344
  }
26020
- batchRequest(items, requestKey) {
26345
+ batchRequest(items, requestKey, purpose) {
26021
26346
  return this.requestConstraints({
26022
26347
  items: items.map((item) => ({
26023
26348
  id: item.id,
26024
26349
  text: item.text,
26025
26350
  content_sha256: item.contentSha256
26026
26351
  })),
26027
- request_key: requestKey
26352
+ request_key: requestKey,
26353
+ purpose
26028
26354
  });
26029
26355
  }
26030
- requestKey(items) {
26356
+ requestKey(items, purpose) {
26031
26357
  if (!this.metadata)
26032
26358
  throw new SynapseEmbeddingError("transport", "Synapse metadata is unavailable");
26033
26359
  return getSynapseBatchRequestKey({
26034
26360
  model: this.metadata.model,
26035
26361
  fingerprint: this.metadata.fingerprint,
26036
26362
  tableEpoch: this.metadata.table_epoch,
26037
- items
26363
+ items,
26364
+ purpose
26038
26365
  });
26039
26366
  }
26040
26367
  async pollBatch(jobId, requestKey, signal) {
@@ -26244,6 +26571,7 @@ var existingHashStatements = new WeakMap;
26244
26571
  var existingHashByProjectStatements = new WeakMap;
26245
26572
  var deleteByCompartmentStatements = new WeakMap;
26246
26573
  var insertEmbeddingStatements = new WeakMap;
26574
+ var renumberEmbeddingWindowStatements = new WeakMap;
26247
26575
  var searchRowsStatements = new WeakMap;
26248
26576
  var searchRowsByModelStatements = new WeakMap;
26249
26577
  var searchPoolProbeStatements = new WeakMap;
@@ -26294,6 +26622,19 @@ function getInsertEmbeddingStatement(db) {
26294
26622
  }
26295
26623
  return stmt;
26296
26624
  }
26625
+ function getRenumberEmbeddingWindowStatement(db) {
26626
+ let stmt = renumberEmbeddingWindowStatements.get(db);
26627
+ if (!stmt) {
26628
+ stmt = db.prepare(`UPDATE compartment_chunk_embeddings
26629
+ SET window_index = ?
26630
+ WHERE compartment_id = ?
26631
+ AND model_id = ?
26632
+ AND project_path = ?
26633
+ AND window_index = ?`);
26634
+ renumberEmbeddingWindowStatements.set(db, stmt);
26635
+ }
26636
+ return stmt;
26637
+ }
26297
26638
  function getSearchPoolProbeStatement(db) {
26298
26639
  let stmt = searchPoolProbeStatements.get(db);
26299
26640
  if (!stmt) {
@@ -26455,6 +26796,11 @@ function parseCanonicalLineRange(line) {
26455
26796
  return null;
26456
26797
  return { start, end };
26457
26798
  }
26799
+ function assertOrdinalRangeWithinCompartment(rangeStart, rangeEnd, compartmentStart, compartmentEnd) {
26800
+ if (rangeStart < compartmentStart || rangeEnd > compartmentEnd || rangeEnd < rangeStart) {
26801
+ throw new RangeError(`Canonical chunk range ${rangeStart}-${rangeEnd} lies outside compartment ${compartmentStart}-${compartmentEnd}`);
26802
+ }
26803
+ }
26458
26804
  function hashChunkText(text) {
26459
26805
  return createHash14("sha256").update(text).digest("hex");
26460
26806
  }
@@ -26543,6 +26889,10 @@ function canonicalizeInMemoryChunkTextForEmbedding(chunkText, startOrdinal, endO
26543
26889
  lines.push(`${formatOrdinalRange(retainedStart, retainedEnd)} ${roleLabel} ${retained.map(({ part }) => part).join(" / ")}`);
26544
26890
  continue;
26545
26891
  }
26892
+ const clipsRequestedRange = startOrdinal != null && lineStart < startOrdinal || endOrdinal != null && lineEnd > endOrdinal;
26893
+ if (clipsRequestedRange) {
26894
+ return "";
26895
+ }
26546
26896
  const parts = rawParts.filter((part) => !part.startsWith("TC:"));
26547
26897
  if (parts.length === 0)
26548
26898
  continue;
@@ -26555,6 +26905,12 @@ function chunkCanonicalText(canonicalText, startOrdinal, endOrdinal, maxInputTok
26555
26905
  const lines = canonicalText.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
26556
26906
  if (lines.length === 0 || endOrdinal < startOrdinal)
26557
26907
  return [];
26908
+ for (const line of lines) {
26909
+ const range = parseCanonicalLineRange(line);
26910
+ if (range) {
26911
+ assertOrdinalRangeWithinCompartment(range.start, range.end, startOrdinal, endOrdinal);
26912
+ }
26913
+ }
26558
26914
  const normalizedMax = normalizeCompartmentChunkMaxInputTokens(maxInputTokens);
26559
26915
  const effectiveMax = Math.max(1, Math.floor(normalizedMax * CHUNK_WINDOW_SAFETY_RATIO));
26560
26916
  const fullText = lines.join(`
@@ -26580,8 +26936,9 @@ function chunkCanonicalText(canonicalText, startOrdinal, endOrdinal, maxInputTok
26580
26936
  return;
26581
26937
  const text = currentLines.join(`
26582
26938
  `);
26939
+ assertOrdinalRangeWithinCompartment(currentStart, currentEnd, startOrdinal, endOrdinal);
26583
26940
  windows.push({
26584
- windowIndex: windows.length + 1,
26941
+ windowIndex: windows.length,
26585
26942
  startOrdinal: currentStart,
26586
26943
  endOrdinal: currentEnd,
26587
26944
  text,
@@ -26600,8 +26957,9 @@ function chunkCanonicalText(canonicalText, startOrdinal, endOrdinal, maxInputTok
26600
26957
  if (lineTokens > effectiveMax) {
26601
26958
  flush();
26602
26959
  for (const slice of splitOversizedLine(line, effectiveMax)) {
26960
+ assertOrdinalRangeWithinCompartment(lineStart, lineEnd, startOrdinal, endOrdinal);
26603
26961
  windows.push({
26604
- windowIndex: windows.length + 1,
26962
+ windowIndex: windows.length,
26605
26963
  startOrdinal: lineStart,
26606
26964
  endOrdinal: lineEnd,
26607
26965
  text: slice,
@@ -26751,34 +27109,57 @@ function mapBackfillCandidateRows(rows) {
26751
27109
  title: row.title
26752
27110
  }));
26753
27111
  }
27112
+ function renumberOneBasedChunkWindows(db, candidate, projectPath, modelId, windows) {
27113
+ const update = getRenumberEmbeddingWindowStatement(db);
27114
+ db.transaction(() => {
27115
+ for (const window of windows) {
27116
+ const result = update.run(window.windowIndex, candidate.id, modelId, projectPath, window.windowIndex + 1);
27117
+ if (result.changes !== 1) {
27118
+ throw new Error(`Failed to renumber compartment ${candidate.id} window ${window.windowIndex + 1}`);
27119
+ }
27120
+ }
27121
+ })();
27122
+ invalidateDecodedSearchPools(db, ([sessionId, cachedProjectPath, cachedModelId]) => sessionId === candidate.sessionId && cachedProjectPath === projectPath && cachedModelId === modelId);
27123
+ }
26754
27124
  function classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens) {
26755
27125
  const mappedText = buildCanonicalChunkTextFromFts(db, candidate.sessionId, candidate.startMessage, candidate.endMessage);
26756
27126
  if (mappedText === null)
26757
- return "deferred";
27127
+ return { defect: "deferred", windows: [] };
26758
27128
  const canonicalText = mappedText || buildCompartmentSummaryFallbackText(db, candidate.id);
26759
27129
  const windows = chunkCanonicalText(canonicalText, candidate.startMessage, candidate.endMessage, maxInputTokens);
26760
27130
  const existing = getExistingChunkHashes(db, candidate.id, modelId, projectPath);
26761
- if (windows.some((window) => !existing.has(window.windowIndex)))
26762
- return "missing";
27131
+ const isMatchingOneBasedSet = windows.length > 0 && existing.size === windows.length && windows.every((window) => existing.get(window.windowIndex + 1) === window.chunkHash);
27132
+ if (isMatchingOneBasedSet)
27133
+ return { defect: "renumber", windows };
27134
+ const expectedWindowIndexes = new Set(windows.map((window) => window.windowIndex));
27135
+ if ([...existing.keys()].some((windowIndex) => !expectedWindowIndexes.has(windowIndex))) {
27136
+ return { defect: "stale", windows };
27137
+ }
27138
+ if (windows.some((window) => !existing.has(window.windowIndex))) {
27139
+ return { defect: "missing", windows };
27140
+ }
26763
27141
  if (existing.size !== windows.length || windows.some((window) => existing.get(window.windowIndex) !== window.chunkHash)) {
26764
- return "stale";
27142
+ return { defect: "stale", windows };
26765
27143
  }
26766
- return null;
27144
+ return { defect: null, windows };
26767
27145
  }
26768
- function selectHashIncompleteChunkCandidates(db, projectPath, modelId, candidates, limit, maxInputTokens) {
27146
+ function selectHashIncompleteChunkCandidates(db, projectPath, modelId, candidates, limit, maxInputTokens, leaseHeldRenumber = false) {
26769
27147
  const missing = [];
26770
27148
  const stale = [];
26771
27149
  for (const candidate of candidates) {
26772
- const defect = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
27150
+ const { defect, windows } = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
26773
27151
  if (defect === "missing")
26774
27152
  missing.push(candidate);
26775
27153
  else if (defect === "stale")
26776
27154
  stale.push(candidate);
27155
+ else if (defect === "renumber" && leaseHeldRenumber) {
27156
+ renumberOneBasedChunkWindows(db, candidate, projectPath, modelId, windows);
27157
+ }
26777
27158
  }
26778
27159
  return [...missing, ...stale].slice(0, limit);
26779
27160
  }
26780
27161
  var sessionBackfillCandidateStatements = new WeakMap;
26781
- function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, limit, excludeIds, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS) {
27162
+ function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, limit, excludeIds, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, leaseHeldRenumber = false) {
26782
27163
  const exclusions = excludeIds && excludeIds.length > 0 ? excludeIds : [];
26783
27164
  const exclusionSql = exclusions.length > 0 ? `AND c.id NOT IN (${exclusions.map(() => "?").join(", ")})` : "";
26784
27165
  const stmt = exclusions.length > 0 ? db.prepare(`SELECT c.id AS id,
@@ -26817,7 +27198,7 @@ function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelI
26817
27198
  return cached;
26818
27199
  })();
26819
27200
  const rows = stmt.all(projectPath, sessionId, ...exclusions);
26820
- return selectHashIncompleteChunkCandidates(db, projectPath, modelId, mapBackfillCandidateRows(rows), Math.max(1, limit), maxInputTokens);
27201
+ return selectHashIncompleteChunkCandidates(db, projectPath, modelId, mapBackfillCandidateRows(rows), Math.max(1, limit), maxInputTokens, leaseHeldRenumber);
26821
27202
  }
26822
27203
  function countUnembeddedSessionCompartments(db, projectPath, sessionId, modelId, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS) {
26823
27204
  return loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, Number.MAX_SAFE_INTEGER, undefined, maxInputTokens).length;
@@ -26840,9 +27221,9 @@ function countSessionCompartmentEmbedCoverage(db, projectPath, sessionId, modelI
26840
27221
  const candidates = mapBackfillCandidateRows(rows);
26841
27222
  let embedded = 0;
26842
27223
  for (const candidate of candidates) {
26843
- if (classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens) === null) {
27224
+ const { defect } = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
27225
+ if (defect === null || defect === "renumber")
26844
27226
  embedded += 1;
26845
- }
26846
27227
  }
26847
27228
  return { embedded, total: candidates.length };
26848
27229
  }
@@ -27262,6 +27643,78 @@ function dominantEmbeddingFailure(failures) {
27262
27643
  return dominant?.failure;
27263
27644
  }
27264
27645
 
27646
+ // src/features/magic-context/memory/embedding-model-match.ts
27647
+ function parseEmbeddingModel(model) {
27648
+ const lastColon = model.lastIndexOf(":");
27649
+ if (lastColon > model.lastIndexOf("/")) {
27650
+ return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
27651
+ }
27652
+ return { base: model };
27653
+ }
27654
+ function normalizeEmbeddingModelId(model) {
27655
+ return parseEmbeddingModel(model.trim().toLowerCase()).base;
27656
+ }
27657
+ function matchNormalizedEmbeddingModels(a, b) {
27658
+ if (a.length === 0 || b.length === 0)
27659
+ return true;
27660
+ if (a === b)
27661
+ return true;
27662
+ const longer = a.length >= b.length ? a : b;
27663
+ const shorter = a.length >= b.length ? b : a;
27664
+ const isBoundary = (ch) => ch === "-" || ch === "/";
27665
+ if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
27666
+ return true;
27667
+ if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
27668
+ return true;
27669
+ return false;
27670
+ }
27671
+ function embeddingModelsMatch(served, requested) {
27672
+ const servedNormalized = served.trim().toLowerCase();
27673
+ const requestedNormalized = requested.trim().toLowerCase();
27674
+ const servedModel = parseEmbeddingModel(servedNormalized);
27675
+ const requestedModel = parseEmbeddingModel(requestedNormalized);
27676
+ if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
27677
+ return false;
27678
+ }
27679
+ return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
27680
+ }
27681
+ var QWEN3_QUERY_INSTRUCTION = `Instruct: Given a web search query, retrieve relevant passages that answer the query
27682
+ Query: `;
27683
+ var INSTRUCT_WEB_SEARCH_QUERY_PREFIX = QWEN3_QUERY_INSTRUCTION;
27684
+ var EMBEDDING_MODEL_PREFIX_FAMILIES = [
27685
+ {
27686
+ family: "qwen3-embedding",
27687
+ basenamePattern: /^qwen3-embedding(?:-|$)/,
27688
+ prefixes: { queryPrefix: QWEN3_QUERY_INSTRUCTION, documentPrefix: "" }
27689
+ },
27690
+ {
27691
+ family: "gte-qwen-instruct",
27692
+ basenamePattern: /^gte-qwen.*-instruct(?:-|$)/,
27693
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
27694
+ },
27695
+ {
27696
+ family: "e5-instruct",
27697
+ basenamePattern: /^(?:multilingual-)?e5-.*-instruct(?:-|$)/,
27698
+ prefixes: { queryPrefix: INSTRUCT_WEB_SEARCH_QUERY_PREFIX, documentPrefix: "" }
27699
+ },
27700
+ {
27701
+ family: "nomic-embed-text",
27702
+ basenamePattern: /^nomic-embed-text(?:-|$)/,
27703
+ prefixes: { queryPrefix: "search_query: ", documentPrefix: "search_document: " }
27704
+ }
27705
+ ];
27706
+ function modelBasename(model) {
27707
+ const normalized = normalizeEmbeddingModelId(model);
27708
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
27709
+ }
27710
+ function resolveEmbeddingTextPrefixes(model, queryInstruction, documentPrefix) {
27711
+ const family = EMBEDDING_MODEL_PREFIX_FAMILIES.find(({ basenamePattern }) => basenamePattern.test(modelBasename(model)));
27712
+ return {
27713
+ queryPrefix: queryInstruction === false ? "" : queryInstruction !== undefined ? queryInstruction : family?.prefixes.queryPrefix ?? "",
27714
+ documentPrefix: documentPrefix ?? family?.prefixes.documentPrefix ?? ""
27715
+ };
27716
+ }
27717
+
27265
27718
  // src/features/magic-context/memory/embedding-identity.ts
27266
27719
  function normalizeEndpoint(endpoint) {
27267
27720
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
@@ -27280,6 +27733,7 @@ function getEmbeddingProviderIdentity(config) {
27280
27733
  throw new Error("Unknown embedding provider");
27281
27734
  }
27282
27735
  const truncate = config.provider === "openai-compatible" ? config.truncate?.trim() : undefined;
27736
+ const documentPrefix = config.provider === "openai-compatible" ? resolveEmbeddingTextPrefixes(config.model, config.query_instruction, config.document_prefix).documentPrefix : "";
27283
27737
  const localDtype = config.provider === "local" && config.local_dtype && config.local_dtype !== "fp32" ? config.local_dtype : undefined;
27284
27738
  const identityInput = config.provider === "openai-compatible" ? {
27285
27739
  provider: "openai-compatible",
@@ -27287,6 +27741,7 @@ function getEmbeddingProviderIdentity(config) {
27287
27741
  endpoint: normalizeEndpoint(config.endpoint),
27288
27742
  apiKeyPresent: Boolean(config.api_key?.trim()),
27289
27743
  inputType: config.input_type?.trim() || "",
27744
+ ...documentPrefix ? { documentPrefix } : {},
27290
27745
  ...truncate ? { truncate } : {}
27291
27746
  } : {
27292
27747
  provider: "local",
@@ -27968,37 +28423,6 @@ function blockedEmbeddingEndpointReason(endpoint) {
27968
28423
  function normalizeEndpoint2(endpoint) {
27969
28424
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
27970
28425
  }
27971
- function parseEmbeddingModel(model) {
27972
- const lastColon = model.lastIndexOf(":");
27973
- if (lastColon > model.lastIndexOf("/")) {
27974
- return { base: model.slice(0, lastColon), tag: model.slice(lastColon + 1) };
27975
- }
27976
- return { base: model };
27977
- }
27978
- function matchNormalizedEmbeddingModels(a, b) {
27979
- if (a.length === 0 || b.length === 0)
27980
- return true;
27981
- if (a === b)
27982
- return true;
27983
- const longer = a.length >= b.length ? a : b;
27984
- const shorter = a.length >= b.length ? b : a;
27985
- const isBoundary = (ch) => ch === "-" || ch === "/";
27986
- if (longer.startsWith(shorter) && isBoundary(longer.charAt(shorter.length)))
27987
- return true;
27988
- if (longer.endsWith(shorter) && isBoundary(longer.charAt(longer.length - shorter.length - 1)))
27989
- return true;
27990
- return false;
27991
- }
27992
- function embeddingModelsMatch(served, requested) {
27993
- const a = served.trim().toLowerCase();
27994
- const b = requested.trim().toLowerCase();
27995
- const servedModel = parseEmbeddingModel(a);
27996
- const requestedModel = parseEmbeddingModel(b);
27997
- if (servedModel.tag !== undefined && requestedModel.tag !== undefined && servedModel.tag !== requestedModel.tag) {
27998
- return false;
27999
- }
28000
- return matchNormalizedEmbeddingModels(servedModel.base, requestedModel.base);
28001
- }
28002
28426
  var FAILURE_THRESHOLD = 3;
28003
28427
  var FAILURE_WINDOW_MS = 60000;
28004
28428
  var OPEN_DURATION_MS = 5 * 60000;
@@ -28012,6 +28436,8 @@ class OpenAICompatibleEmbeddingProvider {
28012
28436
  apiKey;
28013
28437
  inputType;
28014
28438
  queryInputType;
28439
+ queryPrefix;
28440
+ documentPrefix;
28015
28441
  truncate;
28016
28442
  initialized = false;
28017
28443
  failureTimes = [];
@@ -28026,6 +28452,9 @@ class OpenAICompatibleEmbeddingProvider {
28026
28452
  this.apiKey = options.apiKey?.trim() ?? "";
28027
28453
  this.inputType = options.inputType?.trim() ?? "";
28028
28454
  this.queryInputType = options.queryInputType?.trim() ?? "";
28455
+ const prefixes = resolveEmbeddingTextPrefixes(this.model, options.queryInstruction, options.documentPrefix);
28456
+ this.queryPrefix = prefixes.queryPrefix;
28457
+ this.documentPrefix = prefixes.documentPrefix;
28029
28458
  this.truncate = options.truncate?.trim() ?? "";
28030
28459
  this.maxInputTokens = typeof options.maxInputTokens === "number" && Number.isFinite(options.maxInputTokens) ? Math.max(1, Math.floor(options.maxInputTokens)) : 512;
28031
28460
  this.modelId = getEmbeddingProviderIdentity({
@@ -28034,6 +28463,7 @@ class OpenAICompatibleEmbeddingProvider {
28034
28463
  model: this.model,
28035
28464
  ...this.apiKey ? { api_key: this.apiKey } : {},
28036
28465
  ...this.inputType ? { input_type: this.inputType } : {},
28466
+ ...options.documentPrefix !== undefined ? { document_prefix: options.documentPrefix } : {},
28037
28467
  ...this.truncate ? { truncate: this.truncate } : {}
28038
28468
  });
28039
28469
  }
@@ -28068,7 +28498,8 @@ class OpenAICompatibleEmbeddingProvider {
28068
28498
  if (texts.length === 0) {
28069
28499
  return [];
28070
28500
  }
28071
- const requestTexts = texts.map((t) => t.trim().length === 0 ? " " : t);
28501
+ const textPrefix = purpose === "query" ? this.queryPrefix : this.documentPrefix;
28502
+ const requestTexts = texts.map((text) => `${textPrefix}${text.trim().length === 0 ? " " : text}`);
28072
28503
  if (!await this.initialize()) {
28073
28504
  return Array.from({ length: texts.length }, () => null);
28074
28505
  }
@@ -28624,6 +29055,8 @@ function resolveEmbeddingConfig(config) {
28624
29055
  ...apiKey ? { api_key: apiKey } : {},
28625
29056
  ...inputType ? { input_type: inputType } : {},
28626
29057
  ...queryInputType ? { query_input_type: queryInputType } : {},
29058
+ ...config.query_instruction !== undefined ? { query_instruction: config.query_instruction } : {},
29059
+ ...config.document_prefix !== undefined ? { document_prefix: config.document_prefix } : {},
28627
29060
  ...truncate ? { truncate } : {},
28628
29061
  ...config.max_input_tokens ? {
28629
29062
  max_input_tokens: normalizeCompartmentChunkMaxInputTokens(config.max_input_tokens)
@@ -28671,6 +29104,8 @@ function createProvider(config, context) {
28671
29104
  apiKey: config.api_key,
28672
29105
  inputType: config.input_type,
28673
29106
  queryInputType: config.query_input_type,
29107
+ queryInstruction: config.query_instruction,
29108
+ documentPrefix: config.document_prefix,
28674
29109
  truncate: config.truncate,
28675
29110
  maxInputTokens: config.max_input_tokens
28676
29111
  });
@@ -29971,8 +30406,6 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
29971
30406
  recordSessionProjectIdentity(db, sessionId, projectIdentity);
29972
30407
  const maxInputTokens = getProjectEmbeddingMaxInputTokens(projectIdentity);
29973
30408
  const total = countUnembeddedSessionCompartments(db, projectIdentity, sessionId, snapshot.chunkModelId, maxInputTokens);
29974
- if (total === 0)
29975
- return { status: "nothing", embedded: 0, total: 0 };
29976
30409
  const holderId = `session-embed-${randomUUID2()}`;
29977
30410
  const lease = acquireGitSweepLease(db, projectIdentity, holderId, { ignoreCooldown: true });
29978
30411
  if (!lease.acquired)
@@ -30008,7 +30441,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
30008
30441
  aborted = true;
30009
30442
  break;
30010
30443
  }
30011
- const candidates = loadUnembeddedSessionChunkCandidates(db, projectIdentity, sessionId, snapshot.chunkModelId, batchSize, [...skipIds, ...failedIds], maxInputTokens);
30444
+ const candidates = loadUnembeddedSessionChunkCandidates(db, projectIdentity, sessionId, snapshot.chunkModelId, batchSize, [...skipIds, ...failedIds], maxInputTokens, true);
30012
30445
  if (candidates.length === 0)
30013
30446
  break;
30014
30447
  const {
@@ -30050,6 +30483,8 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
30050
30483
  log("[magic-context] embed drain: lease release failed (will TTL-expire):", error);
30051
30484
  }
30052
30485
  }
30486
+ if (total === 0)
30487
+ return { status: "nothing", embedded: 0, total: 0 };
30053
30488
  if (aborted)
30054
30489
  return { status: "aborted", embedded, total, failed: failedIds.length };
30055
30490
  if (providerDown || failedIds.length > 0) {
@@ -30243,6 +30678,8 @@ function createProvider2(config) {
30243
30678
  apiKey: config.api_key,
30244
30679
  inputType: config.input_type,
30245
30680
  queryInputType: config.query_input_type,
30681
+ queryInstruction: config.query_instruction,
30682
+ documentPrefix: config.document_prefix,
30246
30683
  truncate: config.truncate,
30247
30684
  maxInputTokens: config.max_input_tokens
30248
30685
  });
@@ -32689,24 +33126,9 @@ function validateHistorianOutput(text, _sessionId, chunk, _priorCompartments, se
32689
33126
  };
32690
33127
  }
32691
33128
  var HISTORIAN_PERSISTENT_FAILURE_THRESHOLD = 3;
32692
- function buildHistorianFailureNotice(failureCount, lastError) {
32693
- if (failureCount >= HISTORIAN_PERSISTENT_FAILURE_THRESHOLD) {
32694
- return [
32695
- "## Magic Context — history comparting needs attention",
32696
- "",
32697
- `Magic Context has been unable to compart this session's history ${failureCount} times in a row. This usually means the configured historian model is misconfigured or unreachable (Magic Context already retried every fallback model automatically).`,
32698
- "",
32699
- `Last error: ${lastError}`,
32700
- "",
32701
- "Check your historian model in magic-context.jsonc, then restart. Your conversation keeps working normally in the meantime — this only affects how older history is summarized."
32702
- ].join(`
32703
- `);
32704
- }
32705
- return [
32706
- "## Magic Context",
32707
- "",
32708
- "Hit a transient issue comparting history this turn — Magic Context will retry automatically on the next turn. Nothing is lost and your conversation continues normally. You'll only be alerted again if this keeps happening."
32709
- ].join(`
33129
+ function buildHistorianFailureNotice(failureCount, _lastError) {
33130
+ const heading = failureCount >= HISTORIAN_PERSISTENT_FAILURE_THRESHOLD ? "## Magic Context — History compression" : "## Magic Context";
33131
+ return [heading, "", renderUserFacingFailure("historian_unavailable")].join(`
32710
33132
  `);
32711
33133
  }
32712
33134
  function buildHistorianRepairPrompt(originalPrompt, previousOutput, validationError, language) {
@@ -39571,10 +39993,10 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
39571
39993
  }
39572
39994
  }
39573
39995
  }
39996
+ sessionLog(sessionId, `recomp partial code=${userFacingFailureCode("recomp_unavailable")} reason="${reason}"`);
39574
39997
  return [
39575
- `Persisted ${promoted.compartments.length} compartment${promoted.compartments.length === 1 ? "" : "s"} from ${passCount} successful pass${passCount === 1 ? "" : "es"}.`,
39576
- `Covered raw history 1-${lastCompartmentEnd} out of ${rawMessageCount} total messages.`,
39577
- `Remaining messages ${lastCompartmentEnd + 1}-${protectedTailStart - 1} were not rebuilt (${reason}).`
39998
+ `Rebuilt ${promoted.compartments.length} history block${promoted.compartments.length === 1 ? "" : "s"} across ${passCount} successful pass${passCount === 1 ? "" : "es"}.`,
39999
+ renderUserFacingFailure("recomp_unavailable")
39578
40000
  ].join(`
39579
40001
  `);
39580
40002
  }
@@ -39599,11 +40021,10 @@ Recomp stopped because raw history ${offset}-${protectedTailStart - 1} could not
39599
40021
 
39600
40022
  ${partial}`;
39601
40023
  }
40024
+ sessionLog(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${chunkCoverageError}"`);
39602
40025
  return `## Magic Recomp — Failed
39603
40026
 
39604
- Recomp stopped because the raw chunk could not be represented safely: ${chunkCoverageError}
39605
-
39606
- Nothing was written.`;
40027
+ ${renderUserFacingFailure("recomp_unavailable")}`;
39607
40028
  }
39608
40029
  const references = buildReferenceBlocks({
39609
40030
  sessionId,
@@ -39645,11 +40066,10 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
39645
40066
  callbacks: {
39646
40067
  onRepairRetry: async (error) => {
39647
40068
  emitProgress(`Repair retry (pass ${passCount + 1})…`);
40069
+ sessionLog(sessionId, `recomp retry code=${userFacingFailureCode("recomp_unavailable")} reason="${error}"`);
39648
40070
  await sendStatusNotification2(client, sessionId, `## Magic Recomp
39649
40071
 
39650
- Historian pass ${passCount + 1}, attempt ${passAttempt} is continuing with a repair retry for messages ${chunk.startIndex}-${chunk.endIndex}.
39651
-
39652
- The previous output did not validate: ${error}`, notifParams());
40072
+ History compression is retrying this pass. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
39653
40073
  },
39654
40074
  onModelFallback: (modelId, index, total) => {
39655
40075
  const short = modelId.includes("/") ? modelId.split("/").pop() : modelId;
@@ -39664,9 +40084,7 @@ The previous output did not validate: ${error}`, notifParams());
39664
40084
  if (smallerChunk.messageCount > 0 && smallerChunk.endIndex < chunk.endIndex) {
39665
40085
  await sendStatusNotification2(client, sessionId, `## Magic Recomp
39666
40086
 
39667
- Historian pass ${passCount + 1}, attempt ${passAttempt} is continuing with a smaller chunk ending at ${smallerChunk.endIndex} because messages ${chunk.startIndex}-${chunk.endIndex} could not be validated.
39668
-
39669
- Validator result: ${validatedPass.error}`, notifParams());
40087
+ History compression is retrying with a smaller set of messages. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
39670
40088
  currentTokenBudget = reducedBudget;
39671
40089
  passAttempt += 1;
39672
40090
  continue;
@@ -39683,7 +40101,8 @@ Validator result: ${validatedPass.error}`, notifParams());
39683
40101
  chunkEndOrdinal: chunk.endIndex,
39684
40102
  compartmentsProduced: 0
39685
40103
  });
39686
- const partial = await promoteAndFinalize(`historian failed to validate messages ${chunk.startIndex}-${chunk.endIndex}: ${validatedPass.error}`);
40104
+ sessionLog(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${validatedPass.error}" messageRange=${chunk.startIndex}-${chunk.endIndex}`);
40105
+ const partial = await promoteAndFinalize(`history model response did not validate for messages ${chunk.startIndex}-${chunk.endIndex}`);
39687
40106
  if (partial) {
39688
40107
  return `## Magic Recomp — Partial
39689
40108
 
@@ -39691,9 +40110,7 @@ ${partial}`;
39691
40110
  }
39692
40111
  return `## Magic Recomp — Failed
39693
40112
 
39694
- Recomp failed while rebuilding messages ${chunk.startIndex}-${chunk.endIndex}: ${validatedPass.error}
39695
-
39696
- Nothing was written.`;
40113
+ ${renderUserFacingFailure("recomp_unavailable")}`;
39697
40114
  }
39698
40115
  {
39699
40116
  const passComps = validatedPass.compartments ?? [];
@@ -39744,11 +40161,10 @@ Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIn
39744
40161
  const mergedValidationError = validateStoredCompartments(candidateCompartments);
39745
40162
  if (mergedValidationError) {
39746
40163
  clearRecompStaging(db, sessionId);
40164
+ sessionLog(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${mergedValidationError}"`);
39747
40165
  return `## Magic Recomp — Failed
39748
40166
 
39749
- Recomp completed ${passCount} pass${passCount === 1 ? "" : "es"} but produced an invalid final compartment set: ${mergedValidationError}
39750
-
39751
- Nothing was written.`;
40167
+ ${renderUserFacingFailure("recomp_unavailable")}`;
39752
40168
  }
39753
40169
  saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
39754
40170
  const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
@@ -39800,11 +40216,10 @@ Another process acquired the compartment-state lease before recomp could publish
39800
40216
  `);
39801
40217
  } catch (error) {
39802
40218
  const message = getErrorMessage(error);
40219
+ sessionLog(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${message}"`);
39803
40220
  return `## Magic Recomp — Failed
39804
40221
 
39805
- Recomp failed unexpectedly: ${message}
39806
-
39807
- Staging data preserved for resume on next attempt.`;
40222
+ ${renderUserFacingFailure("recomp_unavailable")}`;
39808
40223
  } finally {
39809
40224
  updateSessionMeta2(db, sessionId, { compartmentInProgress: false });
39810
40225
  cleanupHistorianStateFile(currentStateFilePath);
@@ -40022,11 +40437,10 @@ Recomp stopped because raw history ${offset}-${snapEnd} could not be turned into
40022
40437
  }
40023
40438
  const chunkCoverageError = validateChunkCoverage(chunk);
40024
40439
  if (chunkCoverageError) {
40440
+ log(`[magic-context] partial recomp failed session=${sessionId} code=${userFacingFailureCode("recomp_unavailable")} reason="${chunkCoverageError}"`);
40025
40441
  return `## Magic Recomp — Failed
40026
40442
 
40027
- Partial recomp stopped because the raw chunk could not be represented safely: ${chunkCoverageError}
40028
-
40029
- Original state preserved (staging kept for retry).`;
40443
+ ${renderUserFacingFailure("recomp_unavailable")}`;
40030
40444
  }
40031
40445
  const references = buildReferenceBlocks({
40032
40446
  sessionId,
@@ -40066,11 +40480,10 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
40066
40480
  language: deps.language,
40067
40481
  callbacks: {
40068
40482
  onRepairRetry: async (error) => {
40483
+ log(`[magic-context] partial recomp retry session=${sessionId} code=${userFacingFailureCode("recomp_unavailable")} reason="${error}"`);
40069
40484
  await sendStatusNotification2(client, sessionId, `## Magic Recomp — Partial
40070
40485
 
40071
- Historian pass ${passCount + 1}, attempt ${passAttempt} is continuing with a repair retry for messages ${chunk.startIndex}-${chunk.endIndex}.
40072
-
40073
- The previous output did not validate: ${error}`, notifParams());
40486
+ History compression is retrying this pass. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
40074
40487
  }
40075
40488
  }
40076
40489
  });
@@ -40081,19 +40494,16 @@ The previous output did not validate: ${error}`, notifParams());
40081
40494
  if (smallerChunk.messageCount > 0 && smallerChunk.endIndex < chunk.endIndex) {
40082
40495
  await sendStatusNotification2(client, sessionId, `## Magic Recomp — Partial
40083
40496
 
40084
- Historian pass ${passCount + 1}, attempt ${passAttempt} is continuing with a smaller chunk ending at ${smallerChunk.endIndex} because messages ${chunk.startIndex}-${chunk.endIndex} could not be validated.
40085
-
40086
- Validator result: ${validatedPass.error}`, notifParams());
40497
+ History compression is retrying with a smaller set of messages. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
40087
40498
  currentTokenBudget = reducedBudget;
40088
40499
  passAttempt += 1;
40089
40500
  continue;
40090
40501
  }
40091
40502
  }
40503
+ log(`[magic-context] partial recomp failed session=${sessionId} code=${userFacingFailureCode("recomp_unavailable")} reason="${validatedPass.error}" messageRange=${chunk.startIndex}-${chunk.endIndex}`);
40092
40504
  return `## Magic Recomp — Failed
40093
40505
 
40094
- Partial recomp failed while rebuilding messages ${chunk.startIndex}-${chunk.endIndex}: ${validatedPass.error}
40095
-
40096
- Original state preserved (staging kept for retry).`;
40506
+ ${renderUserFacingFailure("recomp_unavailable")}`;
40097
40507
  }
40098
40508
  candidateCompartments = [
40099
40509
  ...candidateCompartments,
@@ -40128,11 +40538,10 @@ Partial recomp completed historian passes but the final compartment set failed v
40128
40538
  `);
40129
40539
  } catch (error) {
40130
40540
  const message = getErrorMessage(error);
40541
+ log(`[magic-context] partial recomp failed session=${sessionId} code=${userFacingFailureCode("recomp_unavailable")} reason="${message}"`);
40131
40542
  return `## Magic Recomp — Failed
40132
40543
 
40133
- Partial recomp failed unexpectedly: ${message}
40134
-
40135
- Staging preserved for resume on next attempt.`;
40544
+ ${renderUserFacingFailure("recomp_unavailable")}`;
40136
40545
  } finally {
40137
40546
  updateSessionMeta2(db, sessionId, { compartmentInProgress: false });
40138
40547
  const leftoverStaging = getRecompStaging(db, sessionId);
@@ -40834,10 +41243,12 @@ async function runManagedRecomp2(ctx, sessionId, options) {
40834
41243
  setRecompTerminal2(ctx.liveSessionState, sessionId, terminalPhase, extractRecompReason(message));
40835
41244
  return message;
40836
41245
  } catch (error) {
40837
- setRecompTerminal2(ctx.liveSessionState, sessionId, "failed", `Recomp crashed: ${String(error)}`);
41246
+ const failure = renderUserFacingFailure("recomp_unavailable");
41247
+ sessionLog(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")}`, error);
41248
+ setRecompTerminal2(ctx.liveSessionState, sessionId, "failed", failure);
40838
41249
  return `## Magic Recomp — Failed
40839
41250
 
40840
- Recomp crashed: ${String(error)}`;
41251
+ ${failure}`;
40841
41252
  }
40842
41253
  }
40843
41254
  async function runManagedUpgrade2(ctx, sessionId) {
@@ -40896,10 +41307,12 @@ ${migrationSummary}` : ""
40896
41307
  ].join(`
40897
41308
  `);
40898
41309
  } catch (error) {
40899
- setRecompTerminal2(ctx.liveSessionState, sessionId, "failed", `Upgrade crashed: ${String(error)}`);
41310
+ const failure = renderUserFacingFailure("recomp_unavailable");
41311
+ sessionLog(sessionId, `session upgrade failed code=${userFacingFailureCode("recomp_unavailable")}`, error);
41312
+ setRecompTerminal2(ctx.liveSessionState, sessionId, "failed", failure);
40900
41313
  return `## Session Upgrade — Failed
40901
41314
 
40902
- Upgrade crashed: ${String(error)}`;
41315
+ ${failure}`;
40903
41316
  }
40904
41317
  }
40905
41318
  async function runUpgradeMemoryMigration(ctx, sessionId, migrationDirectory) {
@@ -40930,8 +41343,9 @@ async function runUpgradeMemoryMigration(ctx, sessionId, migrationDirectory) {
40930
41343
  });
40931
41344
  return outcome.summary;
40932
41345
  } catch (error) {
40933
- return `Memory migration skipped (error): ${String(error)}`;
41346
+ sessionLog(sessionId, `memory migration failed code=${userFacingFailureCode("dream_unknown")}`, error);
41347
+ return renderUserFacingFailure("dream_unknown");
40934
41348
  }
40935
41349
  }
40936
41350
 
40937
- export { withContentLanguageDirective, buildPrimaryLanguageDirective, setJsoncValue, removeJsoncValue, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, MagicContextConfigSchema, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, directoryHasGitMetadata, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, applyMirroredNoteCompileFields, drainMirrorPages, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, isRecord, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, updateTagMessageId, markTagsCompactedByMessageIds, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, createDroppedInputToolExecuteBeforeHook, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, readRawSessionSeedTail, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, readFrozenMergedReasoningParts, getProtectionWindowForSession, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getSessionsWithPendingMarker, setSessionWorkMetrics, getObservedEpochFloor, resolveEpochFloorForPass, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNotes, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, detectThinkingBindingMismatch, isFable51ThinkingBindingModel, detectOverflow, modelBodyField, toModelEntry, getPromptFailureDetail, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, teardownChildSession, getCompartmentEvents, SYNAPSE_DEFAULT_MODEL, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, SynapseEmbeddingProvider, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, computeNormalizedHash, getLocalEmbeddingNativeMemoryStats, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, describeShadowBackfillWriteRefusal, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, recordChildInvocation, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, beginLkgPass, visitMessageContentFields, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getInMemorySlot, getSlot, dropSlot, noteEntry, getLkgSlotHeapStats, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, setRecompStarting2, setRecompTerminal2, runManagedRecomp2, runManagedUpgrade2 };
41351
+ export { withContentLanguageDirective, buildPrimaryLanguageDirective, setJsoncValue, removeJsoncValue, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, MagicContextConfigSchema, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, directoryHasGitMetadata, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, applyMirroredNoteCompileFields, drainMirrorPages, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, isRecord, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, updateTagMessageId, markTagsCompactedByMessageIds, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, createDroppedInputToolExecuteBeforeHook, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, readRawSessionSeedTail, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, readFrozenMergedReasoningParts, getProtectionWindowForSession, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getSessionsWithPendingMarker, setSessionWorkMetrics, getObservedEpochFloor, resolveEpochFloorForPass, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNotes, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, detectThinkingBindingMismatch, isFable51ThinkingBindingModel, detectOverflow, modelBodyField, toModelEntry, getPromptFailureDetail, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, teardownChildSession, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, capabilityRefusalCode, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, getCompartmentEvents, SYNAPSE_DEFAULT_MODEL, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, SynapseEmbeddingProvider, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, computeNormalizedHash, getLocalEmbeddingNativeMemoryStats, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, describeShadowBackfillWriteRefusal, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, recordChildInvocation, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, beginLkgPass, visitMessageContentFields, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getInMemorySlot, getSlot, dropSlot, noteEntry, getLkgSlotHeapStats, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, setRecompStarting2, setRecompTerminal2, runManagedRecomp2, runManagedUpgrade2 };