memorix 1.10.0 → 1.10.2

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 (51) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +2 -0
  3. package/README.zh-CN.md +2 -0
  4. package/dist/cli/index.js +575 -196
  5. package/dist/index.js +375 -134
  6. package/dist/maintenance-runner.js +210 -46
  7. package/dist/media-audio-runner.js +182 -18
  8. package/dist/media-video-runner.js +209 -45
  9. package/dist/memcode-runtime/CHANGELOG.md +25 -0
  10. package/dist/sdk.js +426 -134
  11. package/dist/vector-backfill-runner.js +209 -45
  12. package/docs/1.2.0-EVALUATION-HARNESS.md +18 -0
  13. package/docs/CONFIGURATION.md +25 -0
  14. package/docs/DEVELOPMENT.md +3 -3
  15. package/docs/PERFORMANCE.md +23 -0
  16. package/docs/README.md +2 -2
  17. package/docs/ROADMAP-1.9.12-2.0.md +13 -6
  18. package/package.json +1 -1
  19. package/plugins/antigravity/memorix/plugin.json +1 -1
  20. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  21. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  22. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  23. package/plugins/copilot/memorix/plugin.json +1 -1
  24. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  25. package/plugins/hermes/memorix/__init__.py +1 -2
  26. package/plugins/hermes/memorix/plugin.yaml +1 -1
  27. package/plugins/omp/memorix/package.json +1 -1
  28. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  29. package/plugins/pi/memorix/package.json +1 -1
  30. package/server.json +2 -2
  31. package/src/cli/commands/init.ts +6 -2
  32. package/src/cli/commands/repair.ts +17 -3
  33. package/src/cli/tui/ConfigureView.tsx +2 -0
  34. package/src/codegraph/auto-context.ts +17 -0
  35. package/src/codegraph/context-pack.ts +15 -0
  36. package/src/compact/engine.ts +11 -0
  37. package/src/compact/index-format.ts +1 -1
  38. package/src/config/dotenv-loader.ts +1 -0
  39. package/src/config/resolved-config.ts +5 -2
  40. package/src/config/yaml-loader.ts +2 -2
  41. package/src/dashboard/server.ts +3 -0
  42. package/src/knowledge/context-assembly.ts +13 -0
  43. package/src/knowledge/context-receipt.ts +35 -0
  44. package/src/knowledge/workset.ts +8 -0
  45. package/src/llm/provider.ts +2 -1
  46. package/src/memory/observations.ts +7 -5
  47. package/src/multimodal/image-loader.ts +2 -2
  48. package/src/search/derived-view-receipt.ts +62 -0
  49. package/src/search/semantic-index.ts +149 -1
  50. package/src/server.ts +18 -3
  51. package/src/store/orama-store.ts +80 -2
package/dist/sdk.js CHANGED
@@ -3870,7 +3870,8 @@ function getResolvedConfig(options = {}) {
3870
3870
  const isAtlasCloud = memoryLlmProvider === "atlascloud";
3871
3871
  const isRequesty = memoryLlmProvider === "requesty";
3872
3872
  const isApiRoute = memoryLlmProvider === "apiroute";
3873
- const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute;
3873
+ const isCheaperInference = memoryLlmProvider === "cheaperinference";
3874
+ const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference;
3874
3875
  const memoryLlmApiKey = first(
3875
3876
  process.env.MEMORIX_LLM_API_KEY,
3876
3877
  process.env.MEMORIX_API_KEY,
@@ -3878,7 +3879,7 @@ function getResolvedConfig(options = {}) {
3878
3879
  yaml.llm?.apiKey,
3879
3880
  legacy.llm?.apiKey,
3880
3881
  // Never borrow another provider's credentials for these gateway presets.
3881
- isAtlasCloud ? process.env.ATLASCLOUD_API_KEY : isRequesty ? process.env.REQUESTY_API_KEY : isApiRoute ? process.env.API_ROUTE_API_KEY : process.env.OPENAI_API_KEY,
3882
+ isAtlasCloud ? process.env.ATLASCLOUD_API_KEY : isRequesty ? process.env.REQUESTY_API_KEY : isApiRoute ? process.env.API_ROUTE_API_KEY : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY : process.env.OPENAI_API_KEY,
3882
3883
  usesPresetKeyOnly ? void 0 : process.env.ANTHROPIC_API_KEY,
3883
3884
  usesPresetKeyOnly ? void 0 : openRouterMemoryLlmApiKey
3884
3885
  );
@@ -4062,6 +4063,7 @@ function getEnvSourceNames() {
4062
4063
  "OPENROUTER_API_KEY",
4063
4064
  "REQUESTY_API_KEY",
4064
4065
  "API_ROUTE_API_KEY",
4066
+ "CHEAPER_INFERENCE_API_KEY",
4065
4067
  "ATLASCLOUD_API_KEY"
4066
4068
  ].filter((name) => process.env[name]);
4067
4069
  }
@@ -7056,6 +7058,7 @@ var init_provider2 = __esm({
7056
7058
  openrouter: { baseUrl: "https://openrouter.ai/api/v1", model: "openai/gpt-4.1-nano" },
7057
7059
  requesty: { baseUrl: "https://router.requesty.ai/v1", model: "openai/gpt-4.1-nano" },
7058
7060
  apiroute: { baseUrl: "https://global.api-route.com/v1", model: "deepseek-v4.1-flash" },
7061
+ cheaperinference: { baseUrl: "https://api.cheaperinference.com/v1", model: "gpt-5.4-mini" },
7059
7062
  atlascloud: { baseUrl: "https://api.atlascloud.ai/v1", model: "deepseek-ai/deepseek-v3.2" },
7060
7063
  custom: { baseUrl: "http://localhost:11434/v1", model: "llama3" }
7061
7064
  };
@@ -7840,13 +7843,18 @@ __export(semantic_index_exports, {
7840
7843
  createSemanticIndexProfile: () => createSemanticIndexProfile,
7841
7844
  deleteSemanticVector: () => deleteSemanticVector,
7842
7845
  ensureSemanticIndex: () => ensureSemanticIndex,
7846
+ getSemanticIndexStats: () => getSemanticIndexStats,
7843
7847
  isSemanticIndexAvailable: () => isSemanticIndexAvailable,
7848
+ listSemanticVectorIds: () => listSemanticVectorIds,
7849
+ optimizeSemanticIndex: () => optimizeSemanticIndex,
7850
+ optimizeSemanticIndexes: () => optimizeSemanticIndexes,
7844
7851
  resetSemanticIndexRuntime: () => resetSemanticIndexRuntime,
7845
7852
  searchSemanticVectors: () => searchSemanticVectors,
7846
7853
  upsertSemanticVector: () => upsertSemanticVector,
7847
7854
  upsertSemanticVectors: () => upsertSemanticVectors
7848
7855
  });
7849
7856
  import { createHash as createHash4 } from "crypto";
7857
+ import { existsSync as existsSync8 } from "fs";
7850
7858
  import { createRequire as createRequire3 } from "module";
7851
7859
  import path11 from "path";
7852
7860
  function createSemanticIndexProfile(provider2) {
@@ -7948,20 +7956,120 @@ function queueOperation(key, operation) {
7948
7956
  writeQueues.set(key, run.catch(() => void 0));
7949
7957
  return run;
7950
7958
  }
7959
+ function positiveEnvInt(name, fallback) {
7960
+ const value = Number.parseInt(process.env[name] ?? "", 10);
7961
+ return Number.isSafeInteger(value) && value > 0 ? value : fallback;
7962
+ }
7963
+ function semanticWriteBatchSize() {
7964
+ return positiveEnvInt("MEMORIX_SEMANTIC_WRITE_BATCH_SIZE", DEFAULT_WRITE_BATCH_SIZE);
7965
+ }
7966
+ function semanticWriteFlushMs() {
7967
+ return positiveEnvInt("MEMORIX_SEMANTIC_WRITE_FLUSH_MS", DEFAULT_WRITE_FLUSH_MS);
7968
+ }
7969
+ function semanticOptimizeEvery() {
7970
+ return positiveEnvInt("MEMORIX_SEMANTIC_OPTIMIZE_EVERY", DEFAULT_OPTIMIZE_EVERY);
7971
+ }
7972
+ function semanticVersionRetentionMs() {
7973
+ return positiveEnvInt("MEMORIX_SEMANTIC_VERSION_RETENTION_MS", DEFAULT_VERSION_RETENTION_MS);
7974
+ }
7975
+ async function optimizeState(state) {
7976
+ if (!state.table || typeof state.table.optimize !== "function") return;
7977
+ await state.table.optimize({
7978
+ cleanupOlderThan: new Date(Date.now() - semanticVersionRetentionMs()),
7979
+ deleteUnverified: false
7980
+ });
7981
+ }
7951
7982
  async function mergeVectors(dataDir, profile, records) {
7952
7983
  if (records.length === 0) return;
7953
7984
  const state = await getState(dataDir, profile, records);
7954
7985
  if (!state?.table) return;
7955
7986
  const rows = records.map(toLanceRow);
7956
7987
  await state.table.mergeInsert("observation_id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(rows);
7988
+ const key = stateKey(dataDir, profile);
7989
+ const mutationCount = (mutationCounts.get(key) ?? 0) + 1;
7990
+ if (mutationCount >= semanticOptimizeEvery()) {
7991
+ mutationCounts.set(key, 0);
7992
+ await optimizeState(state).catch(() => void 0);
7993
+ } else {
7994
+ mutationCounts.set(key, mutationCount);
7995
+ }
7957
7996
  void ensureSemanticIndex(dataDir, profile);
7958
7997
  }
7998
+ function flushPendingVectorBatch(key) {
7999
+ const pending = pendingVectorBatches.get(key);
8000
+ if (!pending) return Promise.resolve();
8001
+ if (pending.timer) clearTimeout(pending.timer);
8002
+ pendingVectorBatches.delete(key);
8003
+ const records = [...pending.records.values()];
8004
+ const waiters = pending.waiters.splice(0);
8005
+ return queueOperation(key, () => mergeVectors(pending.dataDir, pending.profile, records)).then(() => waiters.forEach((waiter) => waiter.resolve())).catch((error) => {
8006
+ waiters.forEach((waiter) => waiter.reject(error));
8007
+ });
8008
+ }
7959
8009
  function upsertSemanticVector(dataDir, profile, record80) {
7960
- return queueOperation(stateKey(dataDir, profile), () => mergeVectors(dataDir, profile, [record80]));
8010
+ const key = stateKey(dataDir, profile);
8011
+ let pending = pendingVectorBatches.get(key);
8012
+ if (!pending) {
8013
+ pending = { dataDir, profile, records: /* @__PURE__ */ new Map(), waiters: [] };
8014
+ pendingVectorBatches.set(key, pending);
8015
+ }
8016
+ pending.records.set(`${record80.projectId}:${record80.observationId}`, record80);
8017
+ const promise = new Promise((resolve5, reject) => pending.waiters.push({ resolve: resolve5, reject }));
8018
+ if (pending.records.size >= semanticWriteBatchSize()) void flushPendingVectorBatch(key);
8019
+ else if (!pending.timer) pending.timer = setTimeout(() => {
8020
+ void flushPendingVectorBatch(key);
8021
+ }, semanticWriteFlushMs());
8022
+ return promise;
7961
8023
  }
7962
8024
  function upsertSemanticVectors(dataDir, profile, records) {
7963
8025
  return queueOperation(stateKey(dataDir, profile), () => mergeVectors(dataDir, profile, records));
7964
8026
  }
8027
+ async function listSemanticVectorIds(dataDir, profile) {
8028
+ const state = await getState(dataDir, profile);
8029
+ if (!state?.table) return null;
8030
+ const rows = await state.table.query().select(["observation_id"]).toArray();
8031
+ return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
8032
+ }
8033
+ async function getSemanticIndexStats(dataDir, profile) {
8034
+ const state = await getState(dataDir, profile);
8035
+ if (!state?.table) return null;
8036
+ return {
8037
+ rowCount: await state.table.countRows(),
8038
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
8039
+ };
8040
+ }
8041
+ function optimizeSemanticIndex(dataDir, profile) {
8042
+ const key = stateKey(dataDir, profile);
8043
+ return queueOperation(key, async () => {
8044
+ const state = await getState(dataDir, profile);
8045
+ if (state) await optimizeState(state);
8046
+ mutationCounts.set(key, 0);
8047
+ });
8048
+ }
8049
+ async function optimizeSemanticIndexes(dataDir) {
8050
+ if (!existsSync8(indexRoot(dataDir))) return [];
8051
+ const lance = await loadLanceDb();
8052
+ if (!lance) throw new Error("LanceDB is unavailable; install the optional @lancedb/lancedb package");
8053
+ const connection = await lance.connect(indexRoot(dataDir));
8054
+ try {
8055
+ const names = typeof connection.tableNames === "function" ? await connection.tableNames() : (await connection.listTables()).tables;
8056
+ const optimized = [];
8057
+ for (const name of names.filter((value) => value.startsWith(TABLE_PREFIX))) {
8058
+ const table = await connection.openTable(name);
8059
+ await table.optimize({
8060
+ cleanupOlderThan: new Date(Date.now() - semanticVersionRetentionMs()),
8061
+ deleteUnverified: false
8062
+ });
8063
+ optimized.push(name);
8064
+ }
8065
+ return optimized;
8066
+ } finally {
8067
+ try {
8068
+ connection.close?.();
8069
+ } catch {
8070
+ }
8071
+ }
8072
+ }
7965
8073
  function deleteSemanticVector(dataDir, profile, observationId2) {
7966
8074
  return queueOperation(stateKey(dataDir, profile), async () => {
7967
8075
  const state = await getState(dataDir, profile);
@@ -8021,6 +8129,8 @@ async function searchSemanticVectors(options) {
8021
8129
  })).filter((row) => Number.isFinite(row.distance));
8022
8130
  }
8023
8131
  async function closeSemanticIndexes() {
8132
+ await Promise.all([...pendingVectorBatches.keys()].map((key) => flushPendingVectorBatch(key)));
8133
+ await Promise.all([...writeQueues.values()]);
8024
8134
  for (const statePromise of statePromises.values()) {
8025
8135
  const state = await statePromise.catch(() => null);
8026
8136
  try {
@@ -8031,9 +8141,12 @@ async function closeSemanticIndexes() {
8031
8141
  statePromises.clear();
8032
8142
  writeQueues.clear();
8033
8143
  indexBuilds.clear();
8144
+ mutationCounts.clear();
8034
8145
  }
8035
8146
  async function closeSemanticIndex(dataDir) {
8036
8147
  const prefix = `${path11.resolve(dataDir)}::`;
8148
+ await Promise.all([...pendingVectorBatches.keys()].filter((key) => key.startsWith(prefix)).map(flushPendingVectorBatch));
8149
+ await Promise.all([...writeQueues.entries()].filter(([key]) => key.startsWith(prefix)).map(([, queue]) => queue));
8037
8150
  for (const [key, statePromise] of statePromises.entries()) {
8038
8151
  if (!key.startsWith(prefix)) continue;
8039
8152
  const state = await statePromise.catch(() => null);
@@ -8044,15 +8157,21 @@ async function closeSemanticIndex(dataDir) {
8044
8157
  statePromises.delete(key);
8045
8158
  writeQueues.delete(key);
8046
8159
  indexBuilds.delete(key);
8160
+ mutationCounts.delete(key);
8047
8161
  }
8048
8162
  }
8049
8163
  function resetSemanticIndexRuntime() {
8164
+ for (const pending of pendingVectorBatches.values()) {
8165
+ if (pending.timer) clearTimeout(pending.timer);
8166
+ }
8167
+ pendingVectorBatches.clear();
8050
8168
  statePromises.clear();
8051
8169
  writeQueues.clear();
8052
8170
  indexBuilds.clear();
8171
+ mutationCounts.clear();
8053
8172
  availability = void 0;
8054
8173
  }
8055
- var SEMANTIC_INDEX_DIR, TABLE_PREFIX, DEFAULT_INDEX_THRESHOLD, MAX_INDEX_PARTITIONS, statePromises, writeQueues, indexBuilds, availability, requireFromHere2;
8174
+ var SEMANTIC_INDEX_DIR, TABLE_PREFIX, DEFAULT_INDEX_THRESHOLD, MAX_INDEX_PARTITIONS, DEFAULT_WRITE_BATCH_SIZE, DEFAULT_WRITE_FLUSH_MS, DEFAULT_OPTIMIZE_EVERY, DEFAULT_VERSION_RETENTION_MS, statePromises, writeQueues, indexBuilds, mutationCounts, pendingVectorBatches, availability, requireFromHere2;
8056
8175
  var init_semantic_index = __esm({
8057
8176
  "src/search/semantic-index.ts"() {
8058
8177
  "use strict";
@@ -8061,13 +8180,84 @@ var init_semantic_index = __esm({
8061
8180
  TABLE_PREFIX = "observations_";
8062
8181
  DEFAULT_INDEX_THRESHOLD = 1e4;
8063
8182
  MAX_INDEX_PARTITIONS = 32;
8183
+ DEFAULT_WRITE_BATCH_SIZE = 100;
8184
+ DEFAULT_WRITE_FLUSH_MS = 50;
8185
+ DEFAULT_OPTIMIZE_EVERY = 20;
8186
+ DEFAULT_VERSION_RETENTION_MS = 24 * 60 * 60 * 1e3;
8064
8187
  statePromises = /* @__PURE__ */ new Map();
8065
8188
  writeQueues = /* @__PURE__ */ new Map();
8066
8189
  indexBuilds = /* @__PURE__ */ new Map();
8190
+ mutationCounts = /* @__PURE__ */ new Map();
8191
+ pendingVectorBatches = /* @__PURE__ */ new Map();
8067
8192
  requireFromHere2 = createRequire3(import.meta.url);
8068
8193
  }
8069
8194
  });
8070
8195
 
8196
+ // src/memory/secret-filter.ts
8197
+ function applyRedaction(text3) {
8198
+ if (!text3) return text3;
8199
+ let out = text3;
8200
+ out = out.replace(
8201
+ /((?:password|passwd|pwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)\s*[:=]\s*["']?)([^\s"',;\n]{6,})/gi,
8202
+ "$1[REDACTED]"
8203
+ );
8204
+ out = out.replace(
8205
+ /(Bearer\s+)([A-Za-z0-9._\-/+]{20,})/g,
8206
+ "$1[REDACTED]"
8207
+ );
8208
+ out = out.replace(/\b(?:ghp|ghs|gho|github_pat)_[A-Za-z0-9]{36,}\b/g, "[REDACTED]");
8209
+ out = out.replace(/\bsk-[A-Za-z0-9T-]{20,}\b/g, "[REDACTED]");
8210
+ out = out.replace(/\beyJ[A-Za-z0-9._-]{40,}\b/g, "[REDACTED]");
8211
+ return out;
8212
+ }
8213
+ function sanitizeCredentials(text3) {
8214
+ return applyRedaction(text3);
8215
+ }
8216
+ function redactCredentials(text3) {
8217
+ return applyRedaction(text3);
8218
+ }
8219
+ var init_secret_filter = __esm({
8220
+ "src/memory/secret-filter.ts"() {
8221
+ "use strict";
8222
+ init_esm_shims();
8223
+ }
8224
+ });
8225
+
8226
+ // src/search/derived-view-receipt.ts
8227
+ function sanitizeDerivedViewFailureReason(reason) {
8228
+ const safe = sanitizeCredentials(reason).replace(/(?:[A-Za-z]:[\\/]|\\\\[^\\/\s]+[\\/]|\/(?:home|Users|tmp|var|private|mnt|workspace|workspaces)\/)[^\s"'<>|]*/gi, "[path]").replace(/\s+/g, " ").trim();
8229
+ return safe.slice(0, 240) || "derived view failed";
8230
+ }
8231
+ function embeddingHealthReceipt(health, embeddingEnabled2) {
8232
+ if (health?.status === "disabled") {
8233
+ return { freshness: "current", rebuildStatus: "disabled" };
8234
+ }
8235
+ if (health?.status === "ready" || embeddingEnabled2) {
8236
+ return { freshness: "current", rebuildStatus: "idle" };
8237
+ }
8238
+ if (health?.status === "degraded") {
8239
+ return {
8240
+ freshness: "stale",
8241
+ rebuildStatus: "failed",
8242
+ ...health.failure ? {
8243
+ failureReason: `embedding ${health.failure.kind}; retry in ${health.failure.retryAfterMs}ms`
8244
+ } : { failureReason: "embedding provider degraded" }
8245
+ };
8246
+ }
8247
+ return {
8248
+ freshness: "unknown",
8249
+ rebuildStatus: "unavailable",
8250
+ failureReason: "embedding provider is not initialized"
8251
+ };
8252
+ }
8253
+ var init_derived_view_receipt = __esm({
8254
+ "src/search/derived-view-receipt.ts"() {
8255
+ "use strict";
8256
+ init_esm_shims();
8257
+ init_secret_filter();
8258
+ }
8259
+ });
8260
+
8071
8261
  // src/project/aliases.ts
8072
8262
  var aliases_exports = {};
8073
8263
  __export(aliases_exports, {
@@ -8676,6 +8866,8 @@ __export(orama_store_exports, {
8676
8866
  getLastSearchMode: () => getLastSearchMode,
8677
8867
  getObservationCount: () => getObservationCount,
8678
8868
  getObservationsByIds: () => getObservationsByIds,
8869
+ getPersistentSemanticVectorIds: () => getPersistentSemanticVectorIds,
8870
+ getSearchDerivedViews: () => getSearchDerivedViews,
8679
8871
  getTimeline: () => getTimeline,
8680
8872
  getVectorDimensions: () => getVectorDimensions,
8681
8873
  hasObservationVector: () => hasObservationVector,
@@ -8706,6 +8898,52 @@ function getLastSearchDiagnostics(projectId) {
8706
8898
  const diagnostics = lastSearchDiagnosticsByProject.get(projectId ?? SEARCH_MODE_DEFAULT_KEY);
8707
8899
  return diagnostics ? { ...diagnostics } : void 0;
8708
8900
  }
8901
+ function getSearchDerivedViews() {
8902
+ const views = {};
8903
+ const store = getOptionalObservationStore();
8904
+ if (store) {
8905
+ try {
8906
+ const generation = store.getGeneration();
8907
+ if (store.hasLexicalIndex?.()) {
8908
+ views.fts = { generation, freshness: "current", rebuildStatus: "idle" };
8909
+ } else {
8910
+ views.fts = {
8911
+ generation,
8912
+ freshness: "unknown",
8913
+ rebuildStatus: "unavailable",
8914
+ failureReason: sanitizeDerivedViewFailureReason(
8915
+ store.getBackendReason?.() ?? "persistent lexical index unavailable"
8916
+ )
8917
+ };
8918
+ }
8919
+ } catch (error) {
8920
+ views.fts = {
8921
+ freshness: "unknown",
8922
+ rebuildStatus: "failed",
8923
+ failureReason: sanitizeDerivedViewFailureReason(error instanceof Error ? error.message : String(error))
8924
+ };
8925
+ }
8926
+ } else {
8927
+ views.fts = {
8928
+ freshness: "unknown",
8929
+ rebuildStatus: "unavailable",
8930
+ failureReason: "observation store is not initialized"
8931
+ };
8932
+ }
8933
+ views.orama = db ? { generation: dbGeneration, freshness: "current", rebuildStatus: "idle" } : {
8934
+ generation: dbGeneration,
8935
+ freshness: "unknown",
8936
+ rebuildStatus: "unavailable",
8937
+ failureReason: "Orama index is not initialized"
8938
+ };
8939
+ let embeddingHealth;
8940
+ try {
8941
+ embeddingHealth = getEmbeddingRuntimeHealth?.();
8942
+ } catch {
8943
+ }
8944
+ views.embedding = embeddingHealthReceipt(embeddingHealth, embeddingEnabled);
8945
+ return views;
8946
+ }
8709
8947
  function rememberSearchDiagnostics(key, value) {
8710
8948
  if (!lastSearchDiagnosticsByProject.has(key) && lastSearchDiagnosticsByProject.size >= MAX_SEARCH_MODE_KEYS) {
8711
8949
  const oldest = lastSearchDiagnosticsByProject.keys().next().value;
@@ -9007,12 +9245,16 @@ function getVectorDimensions() {
9007
9245
  function getActiveSemanticIndexProfile() {
9008
9246
  return indexEmbeddingProvider ? createSemanticIndexProfile(indexEmbeddingProvider) : null;
9009
9247
  }
9248
+ async function getPersistentSemanticVectorIds(dataDir) {
9249
+ if (!indexEmbeddingProvider) return null;
9250
+ return listSemanticVectorIds(dataDir, createSemanticIndexProfile(indexEmbeddingProvider));
9251
+ }
9010
9252
  async function queueSemanticVector(dataDir, record80) {
9011
9253
  const provider2 = indexEmbeddingProvider ?? await getEmbeddingProvider();
9012
9254
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
9013
9255
  if (!profile) return;
9014
9256
  try {
9015
- await upsertSemanticVectors(dataDir, profile, [record80]);
9257
+ await upsertSemanticVector(dataDir, profile, record80);
9016
9258
  } catch {
9017
9259
  }
9018
9260
  }
@@ -9074,6 +9316,7 @@ function isCompatibleCachedVector(vector) {
9074
9316
  async function attachCachedVectors(database, observations2) {
9075
9317
  const semanticDataDir = (await Promise.resolve().then(() => (init_observations(), observations_exports))).getObservationDataDir();
9076
9318
  const semanticProfile = getActiveSemanticIndexProfile();
9319
+ const persistedSemanticIds = semanticDataDir && semanticProfile ? await listSemanticVectorIds(semanticDataDir, semanticProfile).catch(() => null) : null;
9077
9320
  const batchSize = 200;
9078
9321
  for (let start = 0; start < observations2.length; start += batchSize) {
9079
9322
  const batch = observations2.slice(start, start + batchSize);
@@ -9084,7 +9327,7 @@ async function attachCachedVectors(database, observations2) {
9084
9327
  const vector = cachedVectors[index];
9085
9328
  if (!isCompatibleCachedVector(vector)) continue;
9086
9329
  const observation = batch[index];
9087
- if (semanticDataDir && semanticProfile) {
9330
+ if (semanticDataDir && semanticProfile && !persistedSemanticIds?.has(observation.id)) {
9088
9331
  semanticRecords.push({
9089
9332
  observationId: observation.id,
9090
9333
  projectId: observation.projectId,
@@ -9857,6 +10100,7 @@ var init_orama_store = __esm({
9857
10100
  init_mini_skills();
9858
10101
  init_visibility();
9859
10102
  init_provider();
10103
+ init_provider();
9860
10104
  init_project_affinity();
9861
10105
  init_intent_detector();
9862
10106
  init_query_expansion();
@@ -9864,6 +10108,7 @@ var init_orama_store = __esm({
9864
10108
  init_timeout();
9865
10109
  init_obs_store();
9866
10110
  init_semantic_index();
10111
+ init_derived_view_receipt();
9867
10112
  db = null;
9868
10113
  dbInitPromise = null;
9869
10114
  dbGeneration = 0;
@@ -9988,36 +10233,6 @@ var init_entity_extractor = __esm({
9988
10233
  }
9989
10234
  });
9990
10235
 
9991
- // src/memory/secret-filter.ts
9992
- function applyRedaction(text3) {
9993
- if (!text3) return text3;
9994
- let out = text3;
9995
- out = out.replace(
9996
- /((?:password|passwd|pwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)\s*[:=]\s*["']?)([^\s"',;\n]{6,})/gi,
9997
- "$1[REDACTED]"
9998
- );
9999
- out = out.replace(
10000
- /(Bearer\s+)([A-Za-z0-9._\-/+]{20,})/g,
10001
- "$1[REDACTED]"
10002
- );
10003
- out = out.replace(/\b(?:ghp|ghs|gho|github_pat)_[A-Za-z0-9]{36,}\b/g, "[REDACTED]");
10004
- out = out.replace(/\bsk-[A-Za-z0-9T-]{20,}\b/g, "[REDACTED]");
10005
- out = out.replace(/\beyJ[A-Za-z0-9._-]{40,}\b/g, "[REDACTED]");
10006
- return out;
10007
- }
10008
- function sanitizeCredentials(text3) {
10009
- return applyRedaction(text3);
10010
- }
10011
- function redactCredentials(text3) {
10012
- return applyRedaction(text3);
10013
- }
10014
- var init_secret_filter = __esm({
10015
- "src/memory/secret-filter.ts"() {
10016
- "use strict";
10017
- init_esm_shims();
10018
- }
10019
- });
10020
-
10021
10236
  // src/runtime/maintenance-jobs.ts
10022
10237
  var maintenance_jobs_exports = {};
10023
10238
  __export(maintenance_jobs_exports, {
@@ -10868,7 +11083,7 @@ var init_maintenance_targets = __esm({
10868
11083
 
10869
11084
  // src/runtime/isolated-maintenance.ts
10870
11085
  import { spawn } from "child_process";
10871
- import { existsSync as existsSync8 } from "fs";
11086
+ import { existsSync as existsSync9 } from "fs";
10872
11087
  import os4 from "os";
10873
11088
  import path13 from "path";
10874
11089
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -10886,7 +11101,7 @@ function childError(prefix, detail) {
10886
11101
  }
10887
11102
  function isolatedMaintenanceCwd() {
10888
11103
  const tmp = os4.tmpdir();
10889
- return existsSync8(tmp) ? tmp : process.cwd();
11104
+ return existsSync9(tmp) ? tmp : process.cwd();
10890
11105
  }
10891
11106
  function resolveMaintenanceRunnerPath(moduleUrl = import.meta.url) {
10892
11107
  const moduleDir = path13.dirname(fileURLToPath2(moduleUrl));
@@ -10943,7 +11158,7 @@ function collectOutput(stream2, limit2, onOverflow) {
10943
11158
  async function runMaintenanceInChildProcess(request, options = {}) {
10944
11159
  validateRequest(request);
10945
11160
  const runnerPath = options.runnerPath ?? resolveMaintenanceRunnerPath();
10946
- if (!existsSync8(runnerPath)) {
11161
+ if (!existsSync9(runnerPath)) {
10947
11162
  throw new Error(`Maintenance runner is unavailable at ${runnerPath}. Reinstall or rebuild Memorix.`);
10948
11163
  }
10949
11164
  const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(1e3, Math.floor(options.timeoutMs)) : DEFAULT_TIMEOUT_MS;
@@ -146098,7 +146313,7 @@ __export(video_jobs_exports, {
146098
146313
  runMiniMaxVideoGenerationJob: () => runMiniMaxVideoGenerationJob
146099
146314
  });
146100
146315
  import { spawn as spawn2 } from "child_process";
146101
- import { existsSync as existsSync9 } from "fs";
146316
+ import { existsSync as existsSync10 } from "fs";
146102
146317
  import path19 from "path";
146103
146318
  import { fileURLToPath as fileURLToPath3 } from "url";
146104
146319
  function safeError2(error) {
@@ -146346,7 +146561,7 @@ function resolveMediaVideoRunnerPath(moduleUrl = import.meta.url) {
146346
146561
  }
146347
146562
  function launchMediaVideoRunner(request, options = {}) {
146348
146563
  const runnerPath = options.runnerPath ?? resolveMediaVideoRunnerPath();
146349
- if (!existsSync9(runnerPath)) {
146564
+ if (!existsSync10(runnerPath)) {
146350
146565
  return { launched: false, reason: "Media video runner is unavailable until Memorix is built or reinstalled." };
146351
146566
  }
146352
146567
  try {
@@ -146391,7 +146606,7 @@ __export(audio_jobs_exports, {
146391
146606
  transcribeAudio: () => transcribeAudio
146392
146607
  });
146393
146608
  import { spawn as spawn3 } from "child_process";
146394
- import { existsSync as existsSync10 } from "fs";
146609
+ import { existsSync as existsSync11 } from "fs";
146395
146610
  import path20 from "path";
146396
146611
  import { fileURLToPath as fileURLToPath4 } from "url";
146397
146612
  function safeError3(error) {
@@ -146642,7 +146857,7 @@ function resolveMediaAudioRunnerPath(moduleUrl = import.meta.url) {
146642
146857
  }
146643
146858
  function launchMediaAudioRunner(request, options = {}) {
146644
146859
  const runnerPath = options.runnerPath ?? resolveMediaAudioRunnerPath();
146645
- if (!existsSync10(runnerPath)) return { launched: false, reason: "Audio runner is unavailable until Memorix is built or reinstalled." };
146860
+ if (!existsSync11(runnerPath)) return { launched: false, reason: "Audio runner is unavailable until Memorix is built or reinstalled." };
146646
146861
  try {
146647
146862
  const child = spawn3(process.execPath, [runnerPath, JSON.stringify(request)], {
146648
146863
  cwd: request.projectRoot,
@@ -149611,7 +149826,7 @@ __export(lite_provider_exports, {
149611
149826
  refreshProjectLite: () => refreshProjectLite
149612
149827
  });
149613
149828
  import { createHash as createHash11 } from "crypto";
149614
- import { existsSync as existsSync12, readdirSync as readdirSync2, readFileSync as readFileSync8, statSync as statSync3 } from "fs";
149829
+ import { existsSync as existsSync13, readdirSync as readdirSync2, readFileSync as readFileSync8, statSync as statSync3 } from "fs";
149615
149830
  import { join as join4, relative as relative2 } from "path";
149616
149831
  function hashText2(text3) {
149617
149832
  return createHash11("sha256").update(text3).digest("hex");
@@ -149629,7 +149844,7 @@ function resolveMaxFileBytes(value) {
149629
149844
  return Math.max(1, Math.floor(value));
149630
149845
  }
149631
149846
  function isPythonVirtualenvDir(dir) {
149632
- return existsSync12(join4(dir, "pyvenv.cfg"));
149847
+ return existsSync13(join4(dir, "pyvenv.cfg"));
149633
149848
  }
149634
149849
  function walk(root, exclude, maxFiles) {
149635
149850
  const out = [];
@@ -153545,7 +153760,7 @@ __export(vector_backfill_runner_exports, {
153545
153760
  import { spawn as spawn4 } from "child_process";
153546
153761
  import {
153547
153762
  closeSync,
153548
- existsSync as existsSync13,
153763
+ existsSync as existsSync14,
153549
153764
  mkdirSync as mkdirSync2,
153550
153765
  openSync,
153551
153766
  readFileSync as readFileSync9,
@@ -153673,7 +153888,7 @@ function releaseVectorBackfillLock(lockPath = process.env.MEMORIX_VECTOR_BACKFIL
153673
153888
  }
153674
153889
  function launchDetachedVectorBackfill(request, options = {}) {
153675
153890
  const runnerPath = options.runnerPath ?? resolveVectorBackfillRunnerPath();
153676
- const exists = options.exists ?? existsSync13;
153891
+ const exists = options.exists ?? existsSync14;
153677
153892
  if (!exists(runnerPath)) return false;
153678
153893
  const lock = acquireVectorBackfillLock(request.dataDir, request.projectId, options.lockPath);
153679
153894
  if (!lock) return false;
@@ -154692,13 +154907,14 @@ async function prepareSearchIndex(options = {}) {
154692
154907
  return 0;
154693
154908
  }
154694
154909
  const hydratedProjectDir = projectDir;
154695
- const queueMissingVectors = () => {
154696
- if (projectDir !== hydratedProjectDir) return;
154910
+ const queueMissingVectors = async () => {
154911
+ if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
154697
154912
  vectorMissingIds.clear();
154698
154913
  if (!isEmbeddingExplicitlyDisabled()) {
154914
+ const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
154699
154915
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
154700
154916
  for (const obs of observations) {
154701
- if (!hasObservationVector(obs.projectId, obs.id)) {
154917
+ if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
154702
154918
  vectorMissingIds.add(obs.id);
154703
154919
  projectsWithMissingVectors.add(obs.projectId);
154704
154920
  }
@@ -154708,9 +154924,9 @@ async function prepareSearchIndex(options = {}) {
154708
154924
  };
154709
154925
  const cacheHydration = getDeferredCachedVectorHydration();
154710
154926
  if (cacheHydration) {
154711
- void cacheHydration.finally(queueMissingVectors);
154927
+ void cacheHydration.then(queueMissingVectors, queueMissingVectors).catch(() => void 0);
154712
154928
  } else {
154713
- queueMissingVectors();
154929
+ await queueMissingVectors();
154714
154930
  }
154715
154931
  searchIndexPrepared = true;
154716
154932
  return count2;
@@ -156376,7 +156592,7 @@ __export(behavior_exports, {
156376
156592
  getBehaviorConfig: () => getBehaviorConfig,
156377
156593
  resetBehaviorConfigCache: () => resetBehaviorConfigCache
156378
156594
  });
156379
- import { existsSync as existsSync16, readFileSync as readFileSync11 } from "fs";
156595
+ import { existsSync as existsSync17, readFileSync as readFileSync11 } from "fs";
156380
156596
  import { homedir as homedir22 } from "os";
156381
156597
  function isSessionInject(value) {
156382
156598
  return value === "full" || value === "minimal" || value === "silent";
@@ -156387,7 +156603,7 @@ function isFormationMode(value) {
156387
156603
  function legacyBehavior(homeDir) {
156388
156604
  const configPath = getLegacyConfigJsonPath(homeDir);
156389
156605
  try {
156390
- if (!existsSync16(configPath)) return {};
156606
+ if (!existsSync17(configPath)) return {};
156391
156607
  const parsed = JSON.parse(readFileSync11(configPath, "utf-8"));
156392
156608
  return parsed.behavior && typeof parsed.behavior === "object" && !Array.isArray(parsed.behavior) ? parsed.behavior : {};
156393
156609
  } catch {
@@ -157750,6 +157966,10 @@ async function buildTaskWorkset(input) {
157750
157966
  budget: { maxTokens }
157751
157967
  });
157752
157968
  const omittedReceipt = receiptOmissions(rendered.omittedItems, base.hiddenCautionMemoryCount);
157969
+ const derivedViews = {
157970
+ ...getSearchDerivedViews(),
157971
+ ...input.retrieval?.derivedViews ?? {}
157972
+ };
157753
157973
  const retrieval = {
157754
157974
  mode: input.retrieval?.mode ?? (input.semanticCode ? "hybrid" : "unknown"),
157755
157975
  ...input.retrieval?.codeProvider || input.providerQuality?.selected ? { codeProvider: input.retrieval?.codeProvider ?? input.providerQuality?.selected } : {},
@@ -157757,7 +157977,8 @@ async function buildTaskWorkset(input) {
157757
157977
  ...input.retrieval?.fallbackReason ? { fallbackReason: input.retrieval.fallbackReason } : {},
157758
157978
  candidateCount: governed.plan.decisions.length,
157759
157979
  selectedCount: rendered.selected.length,
157760
- omittedCount: omittedReceipt.reduce((total, omission) => total + omission.count, 0)
157980
+ omittedCount: omittedReceipt.reduce((total, omission) => total + omission.count, 0),
157981
+ derivedViews
157761
157982
  };
157762
157983
  const receipt = {
157763
157984
  version: "1.3",
@@ -157816,6 +158037,7 @@ var init_workset = __esm({
157816
158037
  init_workflows2();
157817
158038
  init_long_term();
157818
158039
  init_governor();
158040
+ init_orama_store();
157819
158041
  CONTINUATION_DETAIL_TOKEN_BUDGET = 20;
157820
158042
  }
157821
158043
  });
@@ -157827,11 +158049,11 @@ __export(current_facts_exports, {
157827
158049
  formatGitFact: () => formatGitFact
157828
158050
  });
157829
158051
  import { execFileSync } from "child_process";
157830
- import { existsSync as existsSync17, readFileSync as readFileSync12 } from "fs";
158052
+ import { existsSync as existsSync18, readFileSync as readFileSync12 } from "fs";
157831
158053
  import path29 from "path";
157832
158054
  function readTextIfExists(filePath) {
157833
158055
  try {
157834
- if (!existsSync17(filePath)) return null;
158056
+ if (!existsSync18(filePath)) return null;
157835
158057
  return readFileSync12(filePath, "utf8");
157836
158058
  } catch {
157837
158059
  return null;
@@ -158122,7 +158344,7 @@ __export(external_provider_exports, {
158122
158344
  runExternalCodeGraphLifecycle: () => runExternalCodeGraphLifecycle
158123
158345
  });
158124
158346
  import { spawn as spawn5 } from "child_process";
158125
- import { existsSync as existsSync18, readFileSync as readFileSync13 } from "fs";
158347
+ import { existsSync as existsSync19, readFileSync as readFileSync13 } from "fs";
158126
158348
  import { delimiter, dirname as dirname2, extname, isAbsolute as isAbsolute3, join as join20, relative as relative4, resolve as resolve3, sep } from "path";
158127
158349
  function boundedTimeout(value) {
158128
158350
  if (!Number.isFinite(value)) return DEFAULT_EXTERNAL_CODEGRAPH_TIMEOUT_MS;
@@ -158159,13 +158381,13 @@ function resolveCommandCandidates(command) {
158159
158381
  }
158160
158382
  function resolveLaunch(command) {
158161
158383
  for (const candidate of resolveCommandCandidates(command)) {
158162
- if (!existsSync18(candidate)) continue;
158384
+ if (!existsSync19(candidate)) continue;
158163
158385
  const extension3 = extname(candidate).toLowerCase();
158164
158386
  if (extension3 === ".cmd") {
158165
158387
  const bundleRoot = resolve3(dirname2(candidate), "..");
158166
158388
  const node = join20(bundleRoot, "node.exe");
158167
158389
  const entry = join20(bundleRoot, "lib", "dist", "bin", "codegraph.js");
158168
- if (existsSync18(node) && existsSync18(entry)) {
158390
+ if (existsSync19(node) && existsSync19(entry)) {
158169
158391
  return { executable: node, prefixArgs: ["--liftoff-only", entry] };
158170
158392
  }
158171
158393
  try {
@@ -158174,7 +158396,7 @@ function resolveLaunch(command) {
158174
158396
  if (match2?.[1]) {
158175
158397
  const base = dirname2(candidate).endsWith(sep) ? dirname2(candidate) : dirname2(candidate) + sep;
158176
158398
  const entry2 = resolve3(match2[1].replace(/%(?:~)?dp0%?/gi, base));
158177
- if (existsSync18(entry2)) return { executable: process.execPath, prefixArgs: [entry2] };
158399
+ if (existsSync19(entry2)) return { executable: process.execPath, prefixArgs: [entry2] };
158178
158400
  }
158179
158401
  } catch {
158180
158402
  }
@@ -158322,7 +158544,7 @@ async function inspectExternalCodeGraph(input) {
158322
158544
  const health2 = { state: "disabled", reason: "External CodeGraph is disabled by configuration." };
158323
158545
  return { health: health2, quality: providerQuality({ mode, health: health2 }) };
158324
158546
  }
158325
- if (!existsSync18(join20(input.projectRoot, ".codegraph"))) {
158547
+ if (!existsSync19(join20(input.projectRoot, ".codegraph"))) {
158326
158548
  const health2 = { state: "not-detected", reason: "No local .codegraph index is present for this project." };
158327
158549
  return { health: health2, quality: providerQuality({ mode, health: health2 }) };
158328
158550
  }
@@ -158358,7 +158580,7 @@ async function runExternalCodeGraphLifecycle(input) {
158358
158580
  };
158359
158581
  }
158360
158582
  const indexPath = join20(input.projectRoot, ".codegraph");
158361
- if (input.action === "sync" && !existsSync18(indexPath)) {
158583
+ if (input.action === "sync" && !existsSync19(indexPath)) {
158362
158584
  const health = { state: "not-detected", reason: "No local .codegraph index is present for this project." };
158363
158585
  return {
158364
158586
  action: input.action,
@@ -158368,7 +158590,7 @@ async function runExternalCodeGraphLifecycle(input) {
158368
158590
  quality: providerQuality({ mode, health })
158369
158591
  };
158370
158592
  }
158371
- if (input.action === "init" && existsSync18(indexPath)) {
158593
+ if (input.action === "init" && existsSync19(indexPath)) {
158372
158594
  const inspected2 = await inspectExternalCodeGraph(input);
158373
158595
  return {
158374
158596
  action: input.action,
@@ -159115,6 +159337,61 @@ var init_project_context = __esm({
159115
159337
  }
159116
159338
  });
159117
159339
 
159340
+ // src/knowledge/context-receipt.ts
159341
+ var context_receipt_exports = {};
159342
+ __export(context_receipt_exports, {
159343
+ buildBoundedContextReceipt: () => buildBoundedContextReceipt,
159344
+ buildCodeGraphDerivedView: () => buildCodeGraphDerivedView
159345
+ });
159346
+ function buildCodeGraphDerivedView(input) {
159347
+ const provider2 = input.providerQuality;
159348
+ const snapshot = input.snapshot;
159349
+ const externalFailure = provider2?.external.state !== void 0 && !["ready", "disabled", "not-detected"].includes(provider2.external.state);
159350
+ if (snapshot?.id) {
159351
+ return {
159352
+ ...snapshot.sourceEpoch !== void 0 ? { generation: snapshot.sourceEpoch } : {},
159353
+ freshness: snapshot.incomplete ? "stale" : "current",
159354
+ rebuildStatus: snapshot.incomplete ? "failed" : "idle",
159355
+ ...snapshot.incomplete ? { failureReason: "latest CodeGraph snapshot is incomplete" } : externalFailure && provider2?.external.reason ? { failureReason: sanitizeDerivedViewFailureReason(provider2.external.reason) } : {}
159356
+ };
159357
+ }
159358
+ return {
159359
+ freshness: "unknown",
159360
+ rebuildStatus: externalFailure ? "failed" : "unavailable",
159361
+ ...provider2?.external.reason ? { failureReason: sanitizeDerivedViewFailureReason(provider2.external.reason) } : { failureReason: "CodeGraph snapshot is not initialized" }
159362
+ };
159363
+ }
159364
+ function buildBoundedContextReceipt(input) {
159365
+ const provider2 = input.providerQuality ?? input.workset.provenance.codeProvider;
159366
+ return {
159367
+ schemaVersion: "1",
159368
+ task: input.workset.task,
159369
+ brief: input.workset.prompt,
159370
+ receipt: input.workset.receipt,
159371
+ code: {
159372
+ selected: provider2?.selected ?? "lite",
159373
+ quality: provider2?.selectedQuality ?? "heuristic",
159374
+ externalState: provider2?.external.state ?? "not-detected",
159375
+ ...input.workset.provenance.snapshotId ? { snapshotId: input.workset.provenance.snapshotId } : {}
159376
+ },
159377
+ ...input.workset.agentLoadout ? { loadout: input.workset.agentLoadout } : {},
159378
+ ...input.workset.continuity ? {
159379
+ continuity: {
159380
+ taskId: input.workset.continuity.taskId,
159381
+ status: input.workset.continuity.status,
159382
+ outcome: input.workset.continuity.outcome
159383
+ }
159384
+ } : {}
159385
+ };
159386
+ }
159387
+ var init_context_receipt = __esm({
159388
+ "src/knowledge/context-receipt.ts"() {
159389
+ "use strict";
159390
+ init_esm_shims();
159391
+ init_derived_view_receipt();
159392
+ }
159393
+ });
159394
+
159118
159395
  // src/store/compaction-checkpoint-store.ts
159119
159396
  var compaction_checkpoint_store_exports = {};
159120
159397
  __export(compaction_checkpoint_store_exports, {
@@ -159728,7 +160005,7 @@ __export(auto_context_exports, {
159728
160005
  formatAutoProjectContextSummary: () => formatAutoProjectContextSummary,
159729
160006
  formatLegacyAutoProjectContextPrompt: () => formatLegacyAutoProjectContextPrompt
159730
160007
  });
159731
- import { existsSync as existsSync19, statSync as statSync5 } from "fs";
160008
+ import { existsSync as existsSync20, statSync as statSync5 } from "fs";
159732
160009
  import path30 from "path";
159733
160010
  function activeProjectObservations(observations2, projectId) {
159734
160011
  return observations2.filter((obs) => obs.projectId === projectId && (obs.status ?? "active") === "active");
@@ -160004,7 +160281,19 @@ async function buildAutoProjectContext(input) {
160004
160281
  retrieval: {
160005
160282
  mode: semanticOutline ? "hybrid" : "lexical",
160006
160283
  codeProvider: providerQuality2.selected,
160007
- ...externalCaution ? { fallbackReason: externalCaution } : {}
160284
+ ...externalCaution ? { fallbackReason: externalCaution } : {},
160285
+ derivedViews: {
160286
+ graph: buildCodeGraphDerivedView({
160287
+ providerQuality: providerQuality2,
160288
+ ...latestSnapshot ? {
160289
+ snapshot: {
160290
+ id: latestSnapshot.id,
160291
+ sourceEpoch: latestSnapshot.sourceEpoch,
160292
+ incomplete: latestSnapshot.completeness.skippedOversizedFiles > 0 || (latestSnapshot.completeness.unreadableFiles ?? 0) > 0 || latestSnapshot.completeness.removalScanDeferred
160293
+ }
160294
+ } : {}
160295
+ })
160296
+ }
160008
160297
  },
160009
160298
  currentFacts: worksetFactLines(currentFacts),
160010
160299
  ...continuation ? { continuation } : {},
@@ -160091,7 +160380,7 @@ function existingLensCandidates(rootPath, lens) {
160091
160380
  for (const candidate of lensPathCandidates(lens)) {
160092
160381
  const absolute = path30.join(rootPath, candidate);
160093
160382
  try {
160094
- if (!existsSync19(absolute)) continue;
160383
+ if (!existsSync20(absolute)) continue;
160095
160384
  const stat5 = statSync5(absolute);
160096
160385
  if (stat5.isFile()) out.push(candidate);
160097
160386
  if (stat5.isDirectory()) out.push(candidate.replace(/\\/g, "/"));
@@ -160334,47 +160623,13 @@ var init_auto_context = __esm({
160334
160623
  init_long_term();
160335
160624
  init_visibility();
160336
160625
  init_session_store();
160626
+ init_context_receipt();
160337
160627
  init_task_lens();
160338
160628
  DEFAULT_MAX_AGE_MS = 10 * 60 * 1e3;
160339
160629
  COMPACT_CHECKPOINT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
160340
160630
  }
160341
160631
  });
160342
160632
 
160343
- // src/knowledge/context-receipt.ts
160344
- var context_receipt_exports = {};
160345
- __export(context_receipt_exports, {
160346
- buildBoundedContextReceipt: () => buildBoundedContextReceipt
160347
- });
160348
- function buildBoundedContextReceipt(input) {
160349
- const provider2 = input.providerQuality ?? input.workset.provenance.codeProvider;
160350
- return {
160351
- schemaVersion: "1",
160352
- task: input.workset.task,
160353
- brief: input.workset.prompt,
160354
- receipt: input.workset.receipt,
160355
- code: {
160356
- selected: provider2?.selected ?? "lite",
160357
- quality: provider2?.selectedQuality ?? "heuristic",
160358
- externalState: provider2?.external.state ?? "not-detected",
160359
- ...input.workset.provenance.snapshotId ? { snapshotId: input.workset.provenance.snapshotId } : {}
160360
- },
160361
- ...input.workset.agentLoadout ? { loadout: input.workset.agentLoadout } : {},
160362
- ...input.workset.continuity ? {
160363
- continuity: {
160364
- taskId: input.workset.continuity.taskId,
160365
- status: input.workset.continuity.status,
160366
- outcome: input.workset.continuity.outcome
160367
- }
160368
- } : {}
160369
- };
160370
- }
160371
- var init_context_receipt = __esm({
160372
- "src/knowledge/context-receipt.ts"() {
160373
- "use strict";
160374
- init_esm_shims();
160375
- }
160376
- });
160377
-
160378
160633
  // src/codegraph/context-pack.ts
160379
160634
  var context_pack_exports = {};
160380
160635
  __export(context_pack_exports, {
@@ -160553,7 +160808,19 @@ async function attachTaskWorkset(input) {
160553
160808
  ...input.providerQuality ? { providerQuality: input.providerQuality } : {},
160554
160809
  retrieval: {
160555
160810
  mode: semanticCode ? "hybrid" : "unknown",
160556
- ...input.providerQuality?.selected ? { codeProvider: input.providerQuality.selected } : {}
160811
+ ...input.providerQuality?.selected ? { codeProvider: input.providerQuality.selected } : {},
160812
+ derivedViews: {
160813
+ graph: buildCodeGraphDerivedView({
160814
+ providerQuality: input.providerQuality,
160815
+ ...input.snapshot ? {
160816
+ snapshot: {
160817
+ id: input.snapshot.id,
160818
+ sourceEpoch: input.snapshot.sourceEpoch,
160819
+ incomplete: input.snapshot.incomplete
160820
+ }
160821
+ } : {}
160822
+ })
160823
+ }
160557
160824
  },
160558
160825
  reliableMemory: input.pack.memories.filter((memory) => memory.status === "current").map((memory) => ({
160559
160826
  id: memory.id,
@@ -160625,6 +160892,7 @@ var init_context_pack = __esm({
160625
160892
  "use strict";
160626
160893
  init_esm_shims();
160627
160894
  init_freshness2();
160895
+ init_context_receipt();
160628
160896
  init_workset();
160629
160897
  init_exclude3();
160630
160898
  init_semantic_context();
@@ -160636,7 +160904,7 @@ var engine_exports2 = {};
160636
160904
  __export(engine_exports2, {
160637
160905
  SkillsEngine: () => SkillsEngine
160638
160906
  });
160639
- import { existsSync as existsSync20, readFileSync as readFileSync14, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, readdirSync as readdirSync4 } from "fs";
160907
+ import { existsSync as existsSync21, readFileSync as readFileSync14, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, readdirSync as readdirSync4 } from "fs";
160640
160908
  import { join as join21 } from "path";
160641
160909
  import { homedir as homedir23 } from "os";
160642
160910
  var SKILLS_DIRS, SKILL_WORTHY_TYPES, MIN_OBS_FOR_SKILL, MIN_SCORE_FOR_SKILL, LOW_SIGNAL_TITLE_PATTERNS, LOW_SIGNAL_ENTITY_PATTERNS, COMMAND_TRACE_PATTERNS2, SkillsEngine;
@@ -160717,7 +160985,7 @@ var init_engine3 = __esm({
160717
160985
  paths.push(join21(home, dir));
160718
160986
  }
160719
160987
  for (const skillsRoot of paths) {
160720
- if (!existsSync20(skillsRoot)) continue;
160988
+ if (!existsSync21(skillsRoot)) continue;
160721
160989
  try {
160722
160990
  const entries = readdirSync4(skillsRoot, { withFileTypes: true });
160723
160991
  for (const entry of entries) {
@@ -160725,7 +160993,7 @@ var init_engine3 = __esm({
160725
160993
  const name = entry.name;
160726
160994
  if (seen.has(name)) continue;
160727
160995
  const skillMd = join21(skillsRoot, name, "SKILL.md");
160728
- if (!existsSync20(skillMd)) continue;
160996
+ if (!existsSync21(skillMd)) continue;
160729
160997
  try {
160730
160998
  const content = readFileSync14(skillMd, "utf-8");
160731
160999
  const description = this.parseDescription(content);
@@ -163749,7 +164017,7 @@ async function handleApi(req, res, dataDir, projectId, projectName, baseDir, pro
163749
164017
  }
163750
164018
  case "/config": {
163751
164019
  const os6 = await import("os");
163752
- const { existsSync: existsSync23 } = await import("fs");
164020
+ const { existsSync: existsSync24 } = await import("fs");
163753
164021
  const { join: join25 } = await import("path");
163754
164022
  const configProjectRoot = effectiveProjectRoot;
163755
164023
  const resolved = getResolvedConfig({ projectRoot: configProjectRoot });
@@ -163777,7 +164045,7 @@ async function handleApi(req, res, dataDir, projectId, projectName, baseDir, pro
163777
164045
  if (fpath === null) {
163778
164046
  files[key] = { exists: false, path: "unavailable", unavailable: true };
163779
164047
  } else {
163780
- files[key] = { exists: existsSync23(fpath), path: fpath };
164048
+ files[key] = { exists: existsSync24(fpath), path: fpath };
163781
164049
  }
163782
164050
  }
163783
164051
  } catch {
@@ -163801,7 +164069,8 @@ async function handleApi(req, res, dataDir, projectId, projectName, baseDir, pro
163801
164069
  "ANTHROPIC_API_KEY",
163802
164070
  ...resolved.memory.llm.provider === "openrouter" || resolved.memory.llm.baseUrl?.includes("openrouter.ai") ? ["OPENROUTER_API_KEY"] : [],
163803
164071
  ...resolved.memory.llm.provider === "requesty" ? ["REQUESTY_API_KEY"] : [],
163804
- ...resolved.memory.llm.provider === "apiroute" ? ["API_ROUTE_API_KEY"] : []
164072
+ ...resolved.memory.llm.provider === "apiroute" ? ["API_ROUTE_API_KEY"] : [],
164073
+ ...resolved.memory.llm.provider === "cheaperinference" ? ["CHEAPER_INFERENCE_API_KEY"] : []
163805
164074
  ];
163806
164075
  if (llmKey) {
163807
164076
  const src = resolveDashboardKeySource({ value: llmKey, envKeys: memoryKeyEnv, configSource });
@@ -164588,7 +164857,7 @@ var init_task_graph = __esm({
164588
164857
 
164589
164858
  // src/orchestrate/context-collector.ts
164590
164859
  import { execFileSync as execFileSync2 } from "child_process";
164591
- import { readFileSync as readFileSync15, existsSync as existsSync21 } from "fs";
164860
+ import { readFileSync as readFileSync15, existsSync as existsSync22 } from "fs";
164592
164861
  import { join as join22 } from "path";
164593
164862
  function normalizeEntryLimit(value, fallback) {
164594
164863
  if (!Number.isSafeInteger(value) || value < 1) return fallback;
@@ -164665,7 +164934,7 @@ function collectFileTree(projectDir2, maxEntries) {
164665
164934
  function collectDependencies(projectDir2) {
164666
164935
  try {
164667
164936
  const pkgPath = join22(projectDir2, "package.json");
164668
- if (!existsSync21(pkgPath)) return "";
164937
+ if (!existsSync22(pkgPath)) return "";
164669
164938
  const pkg = JSON.parse(readFileSync15(pkgPath, "utf-8"));
164670
164939
  const parts = [];
164671
164940
  if (pkg.dependencies && Object.keys(pkg.dependencies).length > 0) {
@@ -165387,7 +165656,7 @@ async function analyzeImage(input) {
165387
165656
  const config = getLLMConfig();
165388
165657
  if (!OPENAI_COMPATIBLE_PROVIDERS.has(config.provider)) {
165389
165658
  throw new Error(
165390
- `Image analysis requires an OpenAI-compatible provider (openai, openrouter, requesty, apiroute, or custom). Current provider "${config.provider}" uses a different API shape. Set MEMORIX_LLM_PROVIDER=openai or configure an OpenAI-compatible base URL.`
165659
+ `Image analysis requires an OpenAI-compatible provider (openai, openrouter, requesty, apiroute, cheaperinference, or custom). Current provider "${config.provider}" uses a different API shape. Set MEMORIX_LLM_PROVIDER=openai or configure an OpenAI-compatible base URL.`
165391
165660
  );
165392
165661
  }
165393
165662
  const bytes = decodeBase64ImagePayload(input.base64, MAX_VISION_IMAGE_BYTES);
@@ -165426,7 +165695,7 @@ var init_image_loader = __esm({
165426
165695
  init_provider2();
165427
165696
  init_secret_filter();
165428
165697
  init_image_payload();
165429
- OPENAI_COMPATIBLE_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openrouter", "requesty", "apiroute", "custom"]);
165698
+ OPENAI_COMPATIBLE_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openrouter", "requesty", "apiroute", "cheaperinference", "custom"]);
165430
165699
  MAX_VISION_PROMPT_CHARS = 12e3;
165431
165700
  MAX_VISION_DESCRIPTION_CHARS = 12e3;
165432
165701
  MAX_VISION_LABELS = 50;
@@ -167486,11 +167755,11 @@ __export(hooks_path_exports, {
167486
167755
  resolveGitDir: () => resolveGitDir,
167487
167756
  resolveHooksDir: () => resolveHooksDir
167488
167757
  });
167489
- import { existsSync as existsSync22, readFileSync as readFileSync16, statSync as statSync6, mkdirSync as mkdirSync6 } from "fs";
167758
+ import { existsSync as existsSync23, readFileSync as readFileSync16, statSync as statSync6, mkdirSync as mkdirSync6 } from "fs";
167490
167759
  import path35 from "path";
167491
167760
  function resolveGitDir(projectRoot) {
167492
167761
  const dotGit = path35.join(projectRoot, ".git");
167493
- if (!existsSync22(dotGit)) return null;
167762
+ if (!existsSync23(dotGit)) return null;
167494
167763
  const stat5 = statSync6(dotGit);
167495
167764
  if (stat5.isDirectory()) {
167496
167765
  return dotGit;
@@ -167502,7 +167771,7 @@ function resolveGitDir(projectRoot) {
167502
167771
  if (match2) {
167503
167772
  const gitdir = match2[1].trim();
167504
167773
  const resolved = path35.isAbsolute(gitdir) ? gitdir : path35.resolve(projectRoot, gitdir);
167505
- if (existsSync22(resolved)) {
167774
+ if (existsSync23(resolved)) {
167506
167775
  return resolved;
167507
167776
  }
167508
167777
  }
@@ -168118,6 +168387,14 @@ This project does have stored Memorix memories, but none matched the current que
168118
168387
  }
168119
168388
  const totalTokens = countTextTokens(formatted);
168120
168389
  const diagnostics = getLastSearchDiagnostics(options.projectId);
168390
+ const derivedViews = getSearchDerivedViews();
168391
+ if (diagnostics?.fallbackUsed && diagnostics.fallbackReason) {
168392
+ derivedViews.embedding = {
168393
+ freshness: "stale",
168394
+ rebuildStatus: "failed",
168395
+ failureReason: diagnostics.fallbackReason
168396
+ };
168397
+ }
168121
168398
  return {
168122
168399
  entries,
168123
168400
  formatted,
@@ -168132,6 +168409,7 @@ This project does have stored Memorix memories, but none matched the current que
168132
168409
  omittedByTokenBudget: diagnostics?.omittedByTokenBudget ?? 0,
168133
168410
  fallbackUsed: diagnostics?.fallbackUsed ?? false,
168134
168411
  ...diagnostics?.fallbackReason ? { fallbackReason: diagnostics.fallbackReason } : {},
168412
+ derivedViews,
168135
168413
  tokenCount: totalTokens,
168136
168414
  elapsedMs: Math.max(0, Date.now() - startedAt)
168137
168415
  }
@@ -169738,7 +170016,7 @@ var RulesSyncer = class {
169738
170016
 
169739
170017
  // src/workspace/engine.ts
169740
170018
  init_esm_shims();
169741
- import { readFileSync as readFileSync10, readdirSync as readdirSync3, existsSync as existsSync15, cpSync, mkdirSync as mkdirSync4 } from "fs";
170019
+ import { readFileSync as readFileSync10, readdirSync as readdirSync3, existsSync as existsSync16, cpSync, mkdirSync as mkdirSync4 } from "fs";
169742
170020
  import { join as join19 } from "path";
169743
170021
  import { homedir as homedir21 } from "os";
169744
170022
 
@@ -170690,7 +170968,7 @@ function sanitize(input) {
170690
170968
 
170691
170969
  // src/workspace/applier.ts
170692
170970
  init_esm_shims();
170693
- import { existsSync as existsSync14, mkdirSync as mkdirSync3, copyFileSync, writeFileSync as writeFileSync3, unlinkSync as unlinkSync2, renameSync } from "fs";
170971
+ import { existsSync as existsSync15, mkdirSync as mkdirSync3, copyFileSync, writeFileSync as writeFileSync3, unlinkSync as unlinkSync2, renameSync } from "fs";
170694
170972
  import { dirname } from "path";
170695
170973
  var WorkspaceSyncApplier = class {
170696
170974
  /**
@@ -170716,7 +170994,7 @@ var WorkspaceSyncApplier = class {
170716
170994
  for (const file of files) {
170717
170995
  try {
170718
170996
  const dir = dirname(file.filePath);
170719
- if (!existsSync14(dir)) {
170997
+ if (!existsSync15(dir)) {
170720
170998
  mkdirSync3(dir, { recursive: true });
170721
170999
  }
170722
171000
  } catch (err) {
@@ -170725,7 +171003,7 @@ var WorkspaceSyncApplier = class {
170725
171003
  }
170726
171004
  }
170727
171005
  for (const file of files) {
170728
- if (existsSync14(file.filePath)) {
171006
+ if (existsSync15(file.filePath)) {
170729
171007
  try {
170730
171008
  const backupPath = file.filePath + `.backup-${Date.now()}`;
170731
171009
  copyFileSync(file.filePath, backupPath);
@@ -170776,7 +171054,7 @@ var WorkspaceSyncApplier = class {
170776
171054
  cleanBackups(backups) {
170777
171055
  for (const backup of backups) {
170778
171056
  try {
170779
- if (existsSync14(backup.backupPath)) {
171057
+ if (existsSync15(backup.backupPath)) {
170780
171058
  unlinkSync2(backup.backupPath);
170781
171059
  }
170782
171060
  } catch {
@@ -170841,7 +171119,7 @@ var WorkspaceSyncEngine = class _WorkspaceSyncEngine {
170841
171119
  }
170842
171120
  const merged = /* @__PURE__ */ new Map();
170843
171121
  for (const path37 of pathsToCheck) {
170844
- if (existsSync15(path37)) {
171122
+ if (existsSync16(path37)) {
170845
171123
  try {
170846
171124
  const content = readFileSync10(path37, "utf-8");
170847
171125
  const servers = adapter.parse(content);
@@ -170895,7 +171173,7 @@ var WorkspaceSyncEngine = class _WorkspaceSyncEngine {
170895
171173
  const adapter = this.adapters.get(target);
170896
171174
  const configPath = adapter.getConfigPath(this.projectRoot);
170897
171175
  let configContent;
170898
- if (target === "antigravity" && existsSync15(configPath)) {
171176
+ if (target === "antigravity" && existsSync16(configPath)) {
170899
171177
  try {
170900
171178
  const existing = JSON.parse(readFileSync10(configPath, "utf-8"));
170901
171179
  const generated = JSON.parse(adapter.generate(result.mcpServers.scanned));
@@ -170971,13 +171249,13 @@ var WorkspaceSyncEngine = class _WorkspaceSyncEngine {
170971
171249
  join19(home, dir)
170972
171250
  ];
170973
171251
  for (const skillsRoot of paths) {
170974
- if (!existsSync15(skillsRoot)) continue;
171252
+ if (!existsSync16(skillsRoot)) continue;
170975
171253
  try {
170976
171254
  const entries = readdirSync3(skillsRoot, { withFileTypes: true });
170977
171255
  for (const entry of entries) {
170978
171256
  if (!entry.isDirectory()) continue;
170979
171257
  const skillMd = join19(skillsRoot, entry.name, "SKILL.md");
170980
- if (!existsSync15(skillMd)) continue;
171258
+ if (!existsSync16(skillMd)) continue;
170981
171259
  let description = "";
170982
171260
  try {
170983
171261
  const content = readFileSync10(skillMd, "utf-8");
@@ -171026,7 +171304,7 @@ var WorkspaceSyncEngine = class _WorkspaceSyncEngine {
171026
171304
  for (const skill2 of skills) {
171027
171305
  if (skill2.sourceAgent === target) continue;
171028
171306
  const dest = join19(targetDir, skill2.name);
171029
- if (existsSync15(dest)) {
171307
+ if (existsSync16(dest)) {
171030
171308
  skipped.push(`${skill2.name} (already exists in ${target})`);
171031
171309
  continue;
171032
171310
  }
@@ -171042,7 +171320,7 @@ var WorkspaceSyncEngine = class _WorkspaceSyncEngine {
171042
171320
  scanWorkflows() {
171043
171321
  const workflows = [];
171044
171322
  const wfDir = join19(this.projectRoot, ".windsurf", "workflows");
171045
- if (!existsSync15(wfDir)) return workflows;
171323
+ if (!existsSync16(wfDir)) return workflows;
171046
171324
  try {
171047
171325
  const files = readdirSync3(wfDir).filter((f3) => f3.endsWith(".md"));
171048
171326
  for (const file of files) {
@@ -171435,7 +171713,7 @@ var MCP_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo";
171435
171713
  function getMcpServerInfo() {
171436
171714
  return {
171437
171715
  name: "memorix",
171438
- version: true ? "1.10.0" : "1.0.1"
171716
+ version: true ? "1.10.2" : "1.0.1"
171439
171717
  };
171440
171718
  }
171441
171719
  function createMcpDiscoverResult(capabilities, serverInfo) {
@@ -172665,7 +172943,18 @@ _Search mode: ${result.receipt.mode}_`;
172665
172943
  text: text3
172666
172944
  }
172667
172945
  ],
172668
- structuredContent: { retrieval: result.receipt }
172946
+ // Clients that surface only structuredContent (e.g. Claude Code) must
172947
+ // still see the results, not just the retrieval diagnostics.
172948
+ structuredContent: {
172949
+ results: result.entries.map((entry) => ({
172950
+ ref: formatEntryRef(entry),
172951
+ title: entry.title,
172952
+ type: entry.type,
172953
+ time: entry.time,
172954
+ tokens: entry.tokens
172955
+ })),
172956
+ retrieval: result.receipt
172957
+ }
172669
172958
  };
172670
172959
  }, { loadCorpus: false });
172671
172960
  }
@@ -174733,9 +175022,12 @@ ${s2.instruction}`.toLowerCase();
174733
175022
  }
174734
175023
  } catch {
174735
175024
  }
175025
+ const card = lines.filter(Boolean).join("\n");
174736
175026
  return {
174737
- content: [{ type: "text", text: lines.filter(Boolean).join("\n") }],
174738
- structuredContent: { binding: bindingReceipt }
175027
+ content: [{ type: "text", text: card }],
175028
+ // Clients that surface only structuredContent (e.g. Claude Code) must
175029
+ // still see the session card, not just the binding receipt.
175030
+ structuredContent: { card, binding: bindingReceipt }
174739
175031
  };
174740
175032
  }
174741
175033
  );
@@ -176165,10 +176457,10 @@ Preview: ${analysis.description.slice(0, 300)}${analysis.description.length > 30
176165
176457
  const { ensureHooksDir: ensureHooksDir2 } = await Promise.resolve().then(() => (init_hooks_path(), hooks_path_exports));
176166
176458
  const resolved = ensureHooksDir2(project.rootPath);
176167
176459
  if (resolved) {
176168
- const { existsSync: existsSync23, readFileSync: readFileSync17, writeFileSync: writeFileSync5, chmodSync } = await import("fs");
176460
+ const { existsSync: existsSync24, readFileSync: readFileSync17, writeFileSync: writeFileSync5, chmodSync } = await import("fs");
176169
176461
  const { hookPath } = resolved;
176170
176462
  const HOOK_MARKER = "# [memorix-git-hook]";
176171
- const needsInstall = !existsSync23(hookPath) || !readFileSync17(hookPath, "utf-8").includes(HOOK_MARKER);
176463
+ const needsInstall = !existsSync24(hookPath) || !readFileSync17(hookPath, "utf-8").includes(HOOK_MARKER);
176172
176464
  if (needsInstall) {
176173
176465
  const hookScript = `#!/bin/sh
176174
176466
  ${HOOK_MARKER}
@@ -176177,7 +176469,7 @@ if command -v memorix >/dev/null 2>&1; then
176177
176469
  memorix ingest commit --auto >/dev/null 2>&1 &
176178
176470
  fi
176179
176471
  `;
176180
- if (existsSync23(hookPath)) {
176472
+ if (existsSync24(hookPath)) {
176181
176473
  const existing = readFileSync17(hookPath, "utf-8");
176182
176474
  writeFileSync5(hookPath, existing.trimEnd() + `
176183
176475