@massa-ai/mcp-client 1.60.1 → 1.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/config-cli.js +932 -578
  2. package/dist/index.js +926 -633
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -25994,7 +25994,7 @@ function getConfigForEnv() {
25994
25994
  } else {
25995
25995
  console.error(`[getConfigForEnv] embedding.provider "${provider}" has no env-projection branch \u2014 no embedding env vars were set`);
25996
25996
  }
25997
- env.LOG_LEVEL = config2.logging.level;
25997
+ env.MASSA_AI_LOG_LEVEL = config2.logging.level;
25998
25998
  env.ENABLE_METRICS = String(config2.logging.enableMetrics);
25999
25999
  return env;
26000
26000
  }
@@ -26568,7 +26568,7 @@ var init_config = __esm(() => {
26568
26568
  corsOrigins: envList("MASSA_AI_API_CORS_ORIGINS", fileConfig.security?.corsOrigins ?? [])
26569
26569
  },
26570
26570
  logging: {
26571
- level: process.env.LOG_LEVEL || fileConfig.logging?.level || "info",
26571
+ level: process.env.MASSA_AI_LOG_LEVEL || fileConfig.logging?.level || "info",
26572
26572
  enableMetrics: process.env.ENABLE_METRICS === "true" || process.env.ENABLE_METRICS === undefined && !!fileConfig.logging?.enableMetrics,
26573
26573
  file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || path4.join(resolvedDataDir, "logs", "massa-ai.log"),
26574
26574
  enableFileSink: envBool("MASSA_AI_LOG_ENABLE_FILE_SINK", fileConfig.logging?.enableFileSink ?? true),
@@ -26901,6 +26901,32 @@ var init_log_buffer = __esm(() => {
26901
26901
  });
26902
26902
 
26903
26903
  // ../../packages/shared/dist/utils/logger.js
26904
+ function formatAgo(ms) {
26905
+ const totalSeconds = Math.floor(ms / 1000);
26906
+ if (totalSeconds < 60)
26907
+ return `${totalSeconds}s`;
26908
+ return `${Math.floor(totalSeconds / 60)}m`;
26909
+ }
26910
+ function capErrorText(value) {
26911
+ if (value.length <= MAX_ERROR_TEXT_CHARS)
26912
+ return value;
26913
+ const truncatedChars = value.length - MAX_ERROR_TEXT_CHARS;
26914
+ return `${value.slice(0, MAX_ERROR_TEXT_CHARS)}\u2026(truncated ${truncatedChars} chars)`;
26915
+ }
26916
+ function pickErrorFields(err, includeStack) {
26917
+ const out = { name: err.name, message: capErrorText(err.message) };
26918
+ if (includeStack)
26919
+ out.stack = err.stack;
26920
+ const code = err.code;
26921
+ if (code !== undefined)
26922
+ out.code = code;
26923
+ const cause = err.cause;
26924
+ if (cause !== undefined) {
26925
+ out.cause = capErrorText(cause instanceof Error ? cause.message : String(cause));
26926
+ }
26927
+ return out;
26928
+ }
26929
+
26904
26930
  class Logger {
26905
26931
  _level;
26906
26932
  _enableMetrics;
@@ -26909,6 +26935,7 @@ class Logger {
26909
26935
  _maxFileSizeBytes;
26910
26936
  _maxFiles;
26911
26937
  _initialized = false;
26938
+ repeats = new Map;
26912
26939
  constructor() {}
26913
26940
  ensureInitialized() {
26914
26941
  if (!this._initialized) {
@@ -26969,13 +26996,70 @@ class Logger {
26969
26996
  shouldLog(level) {
26970
26997
  return level >= this.level;
26971
26998
  }
26999
+ serializeMetaErrors(meta3) {
27000
+ if (!meta3)
27001
+ return meta3;
27002
+ let out;
27003
+ for (const [key, value] of Object.entries(meta3)) {
27004
+ if (value instanceof Error) {
27005
+ if (!out)
27006
+ out = { ...meta3 };
27007
+ out[key] = pickErrorFields(value, false);
27008
+ }
27009
+ }
27010
+ return out ?? meta3;
27011
+ }
27012
+ applyRepeatAccounting(level, message, meta3) {
27013
+ if (level !== LogLevel.WARN && level !== LogLevel.ERROR)
27014
+ return meta3;
27015
+ const label = typeof meta3?.label === "string" ? meta3.label : "";
27016
+ const key = `${level}|${message}|${label}`;
27017
+ const now = Date.now();
27018
+ const existing = this.repeats.get(key);
27019
+ if (!existing || now - existing.firstSeenAt > REPEAT_WINDOW_MS) {
27020
+ if (this.repeats.size >= MAX_REPEAT_KEYS)
27021
+ this.repeats.clear();
27022
+ this.repeats.set(key, { firstSeenAt: now, count: 1 });
27023
+ return meta3;
27024
+ }
27025
+ existing.count += 1;
27026
+ return {
27027
+ ...meta3,
27028
+ occurrences: existing.count,
27029
+ firstSeenAgo: formatAgo(now - existing.firstSeenAt)
27030
+ };
27031
+ }
27032
+ _resetRepeatsForTesting() {
27033
+ this.repeats.clear();
27034
+ }
27035
+ safeStringifyMeta(meta3) {
27036
+ const seen = new WeakSet;
27037
+ try {
27038
+ return JSON.stringify(meta3, (_key, value) => {
27039
+ if (typeof value === "bigint")
27040
+ return value.toString();
27041
+ if (typeof value === "object" && value !== null) {
27042
+ if (seen.has(value))
27043
+ return "[Circular]";
27044
+ seen.add(value);
27045
+ }
27046
+ return value;
27047
+ });
27048
+ } catch (err) {
27049
+ return JSON.stringify({
27050
+ metaUnserializable: err instanceof Error ? err.message : String(err)
27051
+ });
27052
+ }
27053
+ }
26972
27054
  formatMessage(level, message, meta3, timestamp = new Date().toISOString()) {
26973
- const metaStr = meta3 ? ` ${JSON.stringify(meta3)}` : "";
27055
+ const metaStr = meta3 ? ` ${this.safeStringifyMeta(meta3)}` : "";
26974
27056
  return `[${timestamp}] [${level}] ${message}${metaStr}`;
26975
27057
  }
26976
27058
  emit(level, message, meta3) {
27059
+ const serializedMeta = this.serializeMetaErrors(meta3);
27060
+ const finalMeta = this.applyRepeatAccounting(level, message, serializedMeta);
26977
27061
  const ts = new Date().toISOString();
26978
- const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, meta3, ts);
27062
+ const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, finalMeta, ts);
26979
27063
  console.error(line);
26980
27064
  if (this.enableFileSink) {
26981
27065
  const filePath = this.logFilePath;
@@ -26987,7 +27071,7 @@ class Logger {
26987
27071
  ts,
26988
27072
  level: LOG_LEVEL_BUFFER_TAGS[level],
26989
27073
  message,
26990
- ...meta3 ? { meta: meta3 } : {}
27074
+ ...finalMeta ? { meta: finalMeta } : {}
26991
27075
  });
26992
27076
  }
26993
27077
  debug(message, meta3) {
@@ -27009,11 +27093,7 @@ class Logger {
27009
27093
  if (this.shouldLog(LogLevel.ERROR)) {
27010
27094
  const errorMeta = error51 ? {
27011
27095
  ...meta3,
27012
- error: {
27013
- name: error51.name,
27014
- message: error51.message,
27015
- stack: error51.stack
27016
- }
27096
+ error: error51 instanceof Error ? pickErrorFields(error51, true) : { message: String(error51) }
27017
27097
  } : meta3;
27018
27098
  this.emit(LogLevel.ERROR, message, errorMeta);
27019
27099
  }
@@ -27044,7 +27124,7 @@ class Logger {
27044
27124
  return childLogger;
27045
27125
  }
27046
27126
  }
27047
- var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, logger;
27127
+ var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, REPEAT_WINDOW_MS, MAX_REPEAT_KEYS = 500, MAX_ERROR_TEXT_CHARS = 300, logger;
27048
27128
  var init_logger = __esm(() => {
27049
27129
  init_config();
27050
27130
  init_log_sink();
@@ -27067,6 +27147,7 @@ var init_logger = __esm(() => {
27067
27147
  [LogLevel.WARN]: "warn",
27068
27148
  [LogLevel.ERROR]: "error"
27069
27149
  };
27150
+ REPEAT_WINDOW_MS = 15 * 60 * 1000;
27070
27151
  logger = new Logger;
27071
27152
  });
27072
27153
 
@@ -27122,8 +27203,9 @@ var init_metrics = __esm(() => {
27122
27203
  }
27123
27204
  } catch (error51) {
27124
27205
  const err = error51 instanceof Error ? error51 : new Error(String(error51));
27125
- logger.warn(`Failed to fetch pricing for ${modelId}`, {
27126
- error: { name: err.name, message: err.message }
27206
+ logger.warn("MetricsCollector: failed to fetch pricing", {
27207
+ modelId,
27208
+ error: err
27127
27209
  });
27128
27210
  }
27129
27211
  const fallback = FALLBACK_PRICING[modelId];
@@ -27131,7 +27213,7 @@ var init_metrics = __esm(() => {
27131
27213
  logger.debug(`Using fallback pricing for ${modelId}`);
27132
27214
  return fallback;
27133
27215
  }
27134
- logger.warn(`Unknown model ${modelId}, using gpt-4 pricing as default`);
27216
+ logger.warn("MetricsCollector: unknown model, using gpt-4 pricing as default", { modelId });
27135
27217
  return FALLBACK_PRICING["gpt-4"];
27136
27218
  }
27137
27219
  static calculateCost(inputTokens, outputTokens, model) {
@@ -27310,7 +27392,9 @@ class SmartRateLimiter {
27310
27392
  const hasRequestCapacity = this.requestLimiter.tryConsume(1);
27311
27393
  const hasTokenCapacity = this.tokenLimiter.tryConsume(estimatedTokens);
27312
27394
  if (!hasRequestCapacity) {
27313
- logger.warn("Request rate limit exceeded");
27395
+ logger.warn("Request rate limit exceeded", {
27396
+ availableTokens: this.requestLimiter.getAvailableTokens()
27397
+ });
27314
27398
  return false;
27315
27399
  }
27316
27400
  if (!hasTokenCapacity) {
@@ -27362,12 +27446,12 @@ import path6 from "path";
27362
27446
  function isHost(v) {
27363
27447
  return typeof v === "string" && HOSTS.includes(v);
27364
27448
  }
27365
- function fileLayout(host, activeDir, activeGlob, variantsRoot) {
27449
+ function fileLayout(host, activeDir, activeExt, variantsRoot) {
27366
27450
  return {
27367
27451
  host,
27368
27452
  route: "files",
27369
27453
  activeDir,
27370
- activeGlob,
27454
+ activeExt,
27371
27455
  variantsRoot,
27372
27456
  variantDir: (profile) => path6.join(variantsRoot, profile)
27373
27457
  };
@@ -27381,19 +27465,19 @@ function resolveHostLayout(host, opts = {}) {
27381
27465
  case "claude": {
27382
27466
  const marketplaceRoot = opts.marketplaceRoot?.claude;
27383
27467
  if (override === undefined && marketplaceRoot !== undefined) {
27384
- return fileLayout(host, path6.join(marketplaceRoot, "agents"), "massa-ai-*.md", path6.join(marketplaceRoot, "agent-profiles"));
27468
+ return fileLayout(host, path6.join(marketplaceRoot, "agents"), ".md", path6.join(marketplaceRoot, "agent-profiles"));
27385
27469
  }
27386
27470
  const root = override ?? path6.join(targetHome, ".claude");
27387
- return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.md", path6.join(root, "massa-ai", "agent-profiles"));
27471
+ return fileLayout(host, path6.join(root, "agents"), ".md", path6.join(root, "massa-ai", "agent-profiles"));
27388
27472
  }
27389
27473
  case "codex": {
27390
27474
  const root = override ?? path6.join(targetHome, ".codex");
27391
- return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.toml", path6.join(root, "massa-ai", "agent-profiles"));
27475
+ return fileLayout(host, path6.join(root, "agents"), ".toml", path6.join(root, "massa-ai", "agent-profiles"));
27392
27476
  }
27393
27477
  case "opencode": {
27394
27478
  const root = override ?? path6.join(targetHome, ".config", "opencode");
27395
27479
  const pluginsDir = path6.join(root, "plugins", "massa-ai");
27396
- return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.md", path6.join(pluginsDir, "agent-profiles"));
27480
+ return fileLayout(host, path6.join(root, "agents"), ".md", path6.join(pluginsDir, "agent-profiles"));
27397
27481
  }
27398
27482
  }
27399
27483
  }
@@ -27727,6 +27811,90 @@ function readInstalledPluginVersion(opts = {}) {
27727
27811
  var DEFAULT_PLUGIN_KEY = "massa-ai@massa-ai";
27728
27812
  var init_claude_marketplace = () => {};
27729
27813
 
27814
+ // ../../packages/shared/dist/profile-switch/ownership.js
27815
+ import fs6 from "fs";
27816
+ import path10 from "path";
27817
+ function isLegacyAgentName(fileName) {
27818
+ const base = path10.basename(fileName).replace(/\.[^.]*$/, "");
27819
+ return base.startsWith("massa-ai-") && LEGACY_AGENT_NAMES.includes(base.slice("massa-ai-".length));
27820
+ }
27821
+ function hasOwnedMarker(content) {
27822
+ const lines = content.split(`
27823
+ `);
27824
+ if (lines[0] !== "---")
27825
+ return false;
27826
+ const close = lines.indexOf("---", 1);
27827
+ return close !== -1 && lines[close + 1] === OWNED_MARKER_MD;
27828
+ }
27829
+ function isRegularFile(filePath) {
27830
+ try {
27831
+ return fs6.lstatSync(filePath).isFile();
27832
+ } catch {
27833
+ return false;
27834
+ }
27835
+ }
27836
+ function isOwnedAgentFile(filePath) {
27837
+ if (!isRegularFile(filePath))
27838
+ return false;
27839
+ if (!filePath.endsWith(".toml") && isLegacyAgentName(filePath))
27840
+ return true;
27841
+ let content;
27842
+ try {
27843
+ content = fs6.readFileSync(filePath, "utf8");
27844
+ } catch {
27845
+ return false;
27846
+ }
27847
+ if (filePath.endsWith(".toml"))
27848
+ return content.split(`
27849
+ `)[0] === OWNED_MARKER_TOML;
27850
+ return hasOwnedMarker(content);
27851
+ }
27852
+ function isOwnedAgentLink(linkPath) {
27853
+ try {
27854
+ if (!fs6.lstatSync(linkPath).isSymbolicLink())
27855
+ return false;
27856
+ } catch {
27857
+ return false;
27858
+ }
27859
+ if (isLegacyAgentName(linkPath))
27860
+ return true;
27861
+ const base = path10.basename(linkPath);
27862
+ const target = fs6.readlinkSync(linkPath);
27863
+ if (target.endsWith(`/opencode-plugin/agents/${base}`))
27864
+ return true;
27865
+ const escaped = base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27866
+ if (new RegExp(`/plugins/massa-ai/agent-profiles/.*/${escaped}$`).test(target))
27867
+ return true;
27868
+ try {
27869
+ return fs6.statSync(linkPath).isFile() && hasOwnedMarker(fs6.readFileSync(linkPath, "utf8"));
27870
+ } catch {
27871
+ return false;
27872
+ }
27873
+ }
27874
+ var OWNED_MARKER_MD = "<!-- massa-ai-owned: true -->", OWNED_MARKER_TOML = "# massa-ai-owned", LEGACY_AGENT_NAMES;
27875
+ var init_ownership = __esm(() => {
27876
+ LEGACY_AGENT_NAMES = [
27877
+ "architecture-specialist",
27878
+ "audit-specialist",
27879
+ "builder",
27880
+ "context-curator",
27881
+ "designer",
27882
+ "documentation-agent",
27883
+ "furps-analyst",
27884
+ "investigator",
27885
+ "judge",
27886
+ "meta-judge",
27887
+ "mobile-specialist",
27888
+ "navigator",
27889
+ "plan-critic",
27890
+ "planner",
27891
+ "requirements-analyst",
27892
+ "reviewer",
27893
+ "test-engineer",
27894
+ "verification-agent"
27895
+ ];
27896
+ });
27897
+
27730
27898
  // ../../packages/shared/dist/profile-switch/frontmatter.js
27731
27899
  function parseFrontmatter(raw2) {
27732
27900
  const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/.exec(raw2);
@@ -27784,12 +27952,12 @@ function unquoteScalar(s) {
27784
27952
  }
27785
27953
 
27786
27954
  // ../../packages/shared/dist/profile-switch/doctor.js
27787
- import fs6 from "fs";
27955
+ import fs7 from "fs";
27788
27956
  import os6 from "os";
27789
- import path10 from "path";
27957
+ import path11 from "path";
27790
27958
  function readTextFile(filePath) {
27791
27959
  try {
27792
- return fs6.readFileSync(filePath, "utf8");
27960
+ return fs7.readFileSync(filePath, "utf8");
27793
27961
  } catch {
27794
27962
  return null;
27795
27963
  }
@@ -27805,7 +27973,7 @@ function readJsonFile(filePath) {
27805
27973
  }
27806
27974
  }
27807
27975
  function readPluginVersion(pluginRoot) {
27808
- const manifest = readJsonFile(path10.join(pluginRoot, ".claude-plugin", "plugin.json"));
27976
+ const manifest = readJsonFile(path11.join(pluginRoot, ".claude-plugin", "plugin.json"));
27809
27977
  return typeof manifest?.version === "string" ? manifest.version : null;
27810
27978
  }
27811
27979
  function detectEnvOverride(env) {
@@ -27818,19 +27986,19 @@ function detectEnvOverride(env) {
27818
27986
  return null;
27819
27987
  }
27820
27988
  function readRoles(liveRoot, activeProfile) {
27821
- const agentsDir = path10.join(liveRoot, "agents");
27989
+ const agentsDir = path11.join(liveRoot, "agents");
27822
27990
  let entries;
27823
27991
  try {
27824
- entries = fs6.readdirSync(agentsDir, { withFileTypes: true });
27992
+ entries = fs7.readdirSync(agentsDir, { withFileTypes: true });
27825
27993
  } catch {
27826
27994
  return [];
27827
27995
  }
27828
27996
  const roles = [];
27829
27997
  for (const entry of entries) {
27830
- if (!entry.isFile() || !entry.name.startsWith("massa-ai-") || !entry.name.endsWith(".md")) {
27998
+ if (!entry.name.endsWith(".md") || !isOwnedAgentFile(path11.join(agentsDir, entry.name))) {
27831
27999
  continue;
27832
28000
  }
27833
- const activeRaw = readTextFile(path10.join(agentsDir, entry.name));
28001
+ const activeRaw = readTextFile(path11.join(agentsDir, entry.name));
27834
28002
  let model = null;
27835
28003
  let effort = null;
27836
28004
  if (activeRaw !== null) {
@@ -27842,7 +28010,7 @@ function readRoles(liveRoot, activeProfile) {
27842
28010
  }
27843
28011
  let staleVariant = false;
27844
28012
  if (activeProfile && activeRaw !== null) {
27845
- const variantRaw = readTextFile(path10.join(liveRoot, "agent-profiles", activeProfile, entry.name));
28013
+ const variantRaw = readTextFile(path11.join(liveRoot, "agent-profiles", activeProfile, entry.name));
27846
28014
  if (variantRaw !== null) {
27847
28015
  staleVariant = variantRaw !== activeRaw;
27848
28016
  }
@@ -27853,7 +28021,8 @@ function readRoles(liveRoot, activeProfile) {
27853
28021
  }
27854
28022
  function runtimeDriftReport(opts = {}) {
27855
28023
  const targetHome = opts.targetHome ?? os6.homedir();
27856
- const stateFilePath = opts.stateFilePath ?? path10.join(targetHome, ".config", "massa-ai", "install-state.json");
28024
+ const host = opts.host ?? "claude";
28025
+ const stateFilePath = opts.stateFilePath ?? path11.join(targetHome, ".config", "massa-ai", "install-state.json");
27857
28026
  let state = opts.state ?? null;
27858
28027
  if (state === null) {
27859
28028
  try {
@@ -27862,9 +28031,24 @@ function runtimeDriftReport(opts = {}) {
27862
28031
  state = null;
27863
28032
  }
27864
28033
  }
27865
- const platform = state?.platforms?.claude;
28034
+ const platform = state?.platforms?.[host];
27866
28035
  const stateVersion = typeof platform?.plugin?.version === "string" ? platform.plugin.version : null;
27867
28036
  const activeProfile = platform?.modelProfile?.profile ?? null;
28037
+ if (host !== "claude") {
28038
+ return {
28039
+ host,
28040
+ route: "unresolved",
28041
+ liveRoot: null,
28042
+ sourceVersion: null,
28043
+ stateVersion,
28044
+ pinnedVersion: null,
28045
+ activeProfile,
28046
+ roles: [],
28047
+ envOverride: detectEnvOverride(opts.env ?? process.env),
28048
+ versionDrift: false,
28049
+ profileMaterialized: false
28050
+ };
28051
+ }
27868
28052
  const install = resolveClaudeMarketplaceInstall({ targetHome, pluginKey: opts.pluginKey });
27869
28053
  const liveRoot = install?.root ?? null;
27870
28054
  const sourceVersion = liveRoot === null ? null : readPluginVersion(liveRoot);
@@ -27887,13 +28071,14 @@ function runtimeDriftReport(opts = {}) {
27887
28071
  var ENV_OVERRIDE_VARS;
27888
28072
  var init_doctor = __esm(() => {
27889
28073
  init_claude_marketplace();
28074
+ init_ownership();
27890
28075
  init_state();
27891
28076
  ENV_OVERRIDE_VARS = ["CLAUDE_CODE_SUBAGENT_MODEL"];
27892
28077
  });
27893
28078
 
27894
28079
  // ../../packages/shared/dist/profile-switch/engine.js
27895
- import fs7 from "fs";
27896
- import path11 from "path";
28080
+ import fs8 from "fs";
28081
+ import path12 from "path";
27897
28082
  import os7 from "os";
27898
28083
  import crypto4 from "crypto";
27899
28084
  import { execFileSync as execFileSync2 } from "child_process";
@@ -27903,7 +28088,7 @@ function namedError3(name, message) {
27903
28088
  return err;
27904
28089
  }
27905
28090
  function defaultStatePath(targetHome) {
27906
- return path11.join(targetHome, ".config", "massa-ai", "install-state.json");
28091
+ return path12.join(targetHome, ".config", "massa-ai", "install-state.json");
27907
28092
  }
27908
28093
  function resolveCommon(opts) {
27909
28094
  const targetHome = opts.targetHome ?? os7.homedir();
@@ -27914,7 +28099,7 @@ function marketplaceRoots(targetHome, state) {
27914
28099
  return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
27915
28100
  }
27916
28101
  function claudeMarketplaceUnresolvedReason(targetHome) {
27917
- const registryPath = path11.join(targetHome, ".claude", "plugins", "installed_plugins.json");
28102
+ const registryPath = path12.join(targetHome, ".claude", "plugins", "installed_plugins.json");
27918
28103
  return `claude installRoute is "marketplace" but no install root could be resolved from ${registryPath} ` + "\u2014 re-run the Claude plugin installer, or verify the plugin registry file";
27919
28104
  }
27920
28105
  function listProfiles(opts = {}) {
@@ -27936,7 +28121,7 @@ function listProfiles(opts = {}) {
27936
28121
  installed: false,
27937
28122
  skipped: false,
27938
28123
  skipReason: null,
27939
- activeProfile: platform2.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
28124
+ activeProfile: platform2.modelProfile?.profile ?? "balanced",
27940
28125
  bundleVersion: platform2.plugin?.version ?? null,
27941
28126
  availableProfiles: [],
27942
28127
  ...claudeDriftFields(host)
@@ -27955,7 +28140,7 @@ function listProfiles(opts = {}) {
27955
28140
  ...claudeDriftFields(host)
27956
28141
  };
27957
28142
  }
27958
- const installed = fs7.existsSync(layout.activeDir);
28143
+ const installed = fs8.existsSync(layout.activeDir);
27959
28144
  const availableProfiles = listVariantProfiles(layout);
27960
28145
  const platform = state.platforms[host];
27961
28146
  return {
@@ -27963,7 +28148,7 @@ function listProfiles(opts = {}) {
27963
28148
  installed,
27964
28149
  skipped: false,
27965
28150
  skipReason: null,
27966
- activeProfile: platform?.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
28151
+ activeProfile: platform?.modelProfile?.profile ?? "balanced",
27967
28152
  bundleVersion: platform?.plugin?.version ?? null,
27968
28153
  availableProfiles,
27969
28154
  ...claudeDriftFields(host)
@@ -27972,20 +28157,20 @@ function listProfiles(opts = {}) {
27972
28157
  return { hosts };
27973
28158
  }
27974
28159
  function listVariantProfiles(layout) {
27975
- if (!fs7.existsSync(layout.variantsRoot))
28160
+ if (!fs8.existsSync(layout.variantsRoot))
27976
28161
  return [];
27977
- return fs7.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
28162
+ return fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
27978
28163
  }
27979
- function matchesGlob(filename, glob) {
27980
- const starIdx = glob.indexOf("*");
27981
- if (starIdx === -1)
27982
- return filename === glob;
27983
- const prefix = glob.slice(0, starIdx);
27984
- const suffix = glob.slice(starIdx + 1);
27985
- return filename.length >= prefix.length + suffix.length && filename.startsWith(prefix) && filename.endsWith(suffix);
28164
+ function matchingFileNames(dir, ext) {
28165
+ return fs8.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && e.name.endsWith(ext) && !isLegacyAgentName(e.name) && isOwnedAgentFile(path12.join(dir, e.name))).map((e) => e.name);
27986
28166
  }
27987
- function matchingFileNames(dir, glob) {
27988
- return fs7.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && matchesGlob(e.name, glob)).map((e) => e.name);
28167
+ function destIsAbsent(dest) {
28168
+ try {
28169
+ fs8.lstatSync(dest);
28170
+ return false;
28171
+ } catch {
28172
+ return true;
28173
+ }
27989
28174
  }
27990
28175
  function detectGitAvailability(dir) {
27991
28176
  try {
@@ -28011,7 +28196,7 @@ function gitTrackedFileNames(dir, filenames) {
28011
28196
  }
28012
28197
  }
28013
28198
  function checkTrackedPathGuard(activeDir, filenames) {
28014
- if (filenames.length === 0 || !fs7.existsSync(activeDir))
28199
+ if (filenames.length === 0 || !fs8.existsSync(activeDir))
28015
28200
  return GUARD_PASS;
28016
28201
  const availability = detectGitAvailability(activeDir);
28017
28202
  if (availability === "no-git")
@@ -28022,53 +28207,45 @@ function checkTrackedPathGuard(activeDir, filenames) {
28022
28207
  if (tracked.size === 0)
28023
28208
  return GUARD_PASS;
28024
28209
  const offending = filenames.find((name) => tracked.has(name));
28025
- return { blocked: true, path: path11.join(activeDir, offending), unchecked: false };
28210
+ return { blocked: true, path: path12.join(activeDir, offending), unchecked: false };
28026
28211
  }
28027
28212
  function assertStateWritable(stateFilePath) {
28028
- const dir = path11.dirname(stateFilePath);
28213
+ const dir = path12.dirname(stateFilePath);
28029
28214
  try {
28030
- fs7.mkdirSync(dir, { recursive: true });
28215
+ fs8.mkdirSync(dir, { recursive: true });
28031
28216
  } catch (err) {
28032
28217
  throw UnwritableInstallStateError(stateFilePath, err.message);
28033
28218
  }
28034
- const checkPath = fs7.existsSync(stateFilePath) ? stateFilePath : dir;
28219
+ const checkPath = fs8.existsSync(stateFilePath) ? stateFilePath : dir;
28035
28220
  try {
28036
- fs7.accessSync(checkPath, fs7.constants.W_OK);
28221
+ fs8.accessSync(checkPath, fs8.constants.W_OK);
28037
28222
  } catch (err) {
28038
28223
  throw UnwritableInstallStateError(stateFilePath, err.message);
28039
28224
  }
28040
28225
  }
28041
28226
  function copyFileRouteVariant(layout, variantDir) {
28042
- fs7.mkdirSync(layout.activeDir, { recursive: true });
28227
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
28043
28228
  let changed = 0;
28044
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
28045
- if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
28229
+ for (const name of matchingFileNames(variantDir, layout.activeExt)) {
28230
+ const dest = path12.join(layout.activeDir, name);
28231
+ if (!destIsAbsent(dest) && !isOwnedAgentFile(dest))
28046
28232
  continue;
28047
- fs7.copyFileSync(path11.join(variantDir, entry.name), path11.join(layout.activeDir, entry.name));
28233
+ fs8.copyFileSync(path12.join(variantDir, name), dest);
28048
28234
  changed++;
28049
28235
  }
28050
28236
  return changed;
28051
28237
  }
28052
28238
  function repointOpencodeVariant(layout, variantDir) {
28053
- fs7.mkdirSync(layout.activeDir, { recursive: true });
28239
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
28054
28240
  let changed = 0;
28055
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
28056
- if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
28057
- continue;
28058
- const dest = path11.join(layout.activeDir, entry.name);
28059
- const target = path11.resolve(path11.join(variantDir, entry.name));
28060
- let destExists = true;
28061
- let destIsSymlink = false;
28062
- try {
28063
- destIsSymlink = fs7.lstatSync(dest).isSymbolicLink();
28064
- } catch {
28065
- destExists = false;
28066
- }
28067
- if (destExists && !destIsSymlink)
28241
+ for (const name of matchingFileNames(variantDir, layout.activeExt)) {
28242
+ const dest = path12.join(layout.activeDir, name);
28243
+ const target = path12.resolve(path12.join(variantDir, name));
28244
+ if (!destIsAbsent(dest) && !isOwnedAgentLink(dest))
28068
28245
  continue;
28069
28246
  const tmp = `${dest}.massa-ai-switch.${crypto4.randomUUID()}`;
28070
- fs7.symlinkSync(target, tmp);
28071
- fs7.renameSync(tmp, dest);
28247
+ fs8.symlinkSync(target, tmp);
28248
+ fs8.renameSync(tmp, dest);
28072
28249
  changed++;
28073
28250
  }
28074
28251
  return changed;
@@ -28108,13 +28285,13 @@ function switchProfile(opts) {
28108
28285
  if (fileHosts.length === 0) {
28109
28286
  return { profile: opts.profile, dryRun, hosts: orderRows(universe, skipRows), restartRequired: false };
28110
28287
  }
28111
- const installedFileHosts = fileHosts.filter((h) => fs7.existsSync(h.layout.activeDir));
28288
+ const installedFileHosts = fileHosts.filter((h) => fs8.existsSync(h.layout.activeDir));
28112
28289
  if (installedFileHosts.length === 0)
28113
28290
  throw NoHostsDetectedError();
28114
28291
  const withAvailability = fileHosts.map((h) => {
28115
- const variantsRootExists = fs7.existsSync(h.layout.variantsRoot);
28292
+ const variantsRootExists = fs8.existsSync(h.layout.variantsRoot);
28116
28293
  const variantDir = h.layout.variantDir(opts.profile);
28117
- const available = variantsRootExists && fs7.existsSync(variantDir) && fs7.statSync(variantDir).isDirectory();
28294
+ const available = variantsRootExists && fs8.existsSync(variantDir) && fs8.statSync(variantDir).isDirectory();
28118
28295
  return { ...h, variantsRootExists, variantDir, available };
28119
28296
  });
28120
28297
  if (!withAvailability.some((h) => h.available)) {
@@ -28153,7 +28330,7 @@ function switchProfile(opts) {
28153
28330
  rows.push({ host: h.host, status: "would-switch" });
28154
28331
  continue;
28155
28332
  }
28156
- const candidateNames = matchingFileNames(h.variantDir, h.layout.activeGlob);
28333
+ const candidateNames = matchingFileNames(h.variantDir, h.layout.activeExt);
28157
28334
  const guard = checkTrackedPathGuard(h.layout.activeDir, candidateNames);
28158
28335
  if (guard.blocked) {
28159
28336
  rows.push({
@@ -28195,6 +28372,7 @@ var init_engine = __esm(() => {
28195
28372
  init_state();
28196
28373
  init_lock();
28197
28374
  init_claude_marketplace();
28375
+ init_ownership();
28198
28376
  init_doctor();
28199
28377
  SwitchEngineError = class SwitchEngineError extends Error {
28200
28378
  constructor(message) {
@@ -28212,25 +28390,25 @@ function reportSucceeded(report) {
28212
28390
  }
28213
28391
 
28214
28392
  // ../../packages/shared/dist/profile-switch/variant-sync.js
28215
- import fs8 from "fs";
28216
- import path12 from "path";
28393
+ import fs9 from "fs";
28394
+ import path13 from "path";
28217
28395
  import os8 from "os";
28218
28396
  import crypto5 from "crypto";
28219
28397
  function defaultStatePath2(targetHome) {
28220
- return path12.join(targetHome, ".config", "massa-ai", "install-state.json");
28398
+ return path13.join(targetHome, ".config", "massa-ai", "install-state.json");
28221
28399
  }
28222
28400
  function marketplaceRoots2(targetHome, state) {
28223
28401
  return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
28224
28402
  }
28225
28403
  function writeFileIntoDirAtomically(destDir, destName, content) {
28226
28404
  const unique = `${process.pid}.${++tempFileCounter2}.${crypto5.randomBytes(6).toString("hex")}`;
28227
- const tempFile = path12.join(destDir, `.${destName}.${unique}.tmp`);
28405
+ const tempFile = path13.join(destDir, `.${destName}.${unique}.tmp`);
28228
28406
  try {
28229
- fs8.writeFileSync(tempFile, content);
28230
- fs8.renameSync(tempFile, path12.join(destDir, destName));
28407
+ fs9.writeFileSync(tempFile, content);
28408
+ fs9.renameSync(tempFile, path13.join(destDir, destName));
28231
28409
  } catch (error51) {
28232
28410
  try {
28233
- fs8.unlinkSync(tempFile);
28411
+ fs9.unlinkSync(tempFile);
28234
28412
  } catch {}
28235
28413
  throw error51;
28236
28414
  }
@@ -28238,20 +28416,20 @@ function writeFileIntoDirAtomically(destDir, destName, content) {
28238
28416
  function isSafeDirName(name) {
28239
28417
  if (name === "." || name === "..")
28240
28418
  return false;
28241
- if (name.includes("/") || name.includes("\\") || name.includes(path12.sep))
28419
+ if (name.includes("/") || name.includes("\\") || name.includes(path13.sep))
28242
28420
  return false;
28243
- return path12.basename(name) === name;
28421
+ return path13.basename(name) === name;
28244
28422
  }
28245
28423
  function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
28246
28424
  const layout = resolveHostLayout(host, { targetHome, marketplaceRoot });
28247
28425
  if (layout.route === "skip") {
28248
28426
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: layout.reason };
28249
28427
  }
28250
- const srcDir = path12.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
28251
- if (!fs8.existsSync(srcDir) || !fs8.statSync(srcDir).isDirectory()) {
28428
+ const srcDir = path13.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
28429
+ if (!fs9.existsSync(srcDir) || !fs9.statSync(srcDir).isDirectory()) {
28252
28430
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: "no generated variants for this host" };
28253
28431
  }
28254
- if (!fs8.existsSync(layout.variantsRoot)) {
28432
+ if (!fs9.existsSync(layout.variantsRoot)) {
28255
28433
  return {
28256
28434
  host,
28257
28435
  status: "skipped",
@@ -28263,24 +28441,24 @@ function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
28263
28441
  }
28264
28442
  const profiles = [];
28265
28443
  let files = 0;
28266
- for (const entry of fs8.readdirSync(srcDir, { withFileTypes: true })) {
28444
+ for (const entry of fs9.readdirSync(srcDir, { withFileTypes: true })) {
28267
28445
  if (!entry.isDirectory())
28268
28446
  continue;
28269
28447
  if (!isSafeDirName(entry.name))
28270
28448
  continue;
28271
- const srcProfileDir = path12.join(srcDir, entry.name);
28272
- const destProfileDir = path12.join(layout.variantsRoot, entry.name);
28273
- fs8.mkdirSync(destProfileDir, { recursive: true });
28274
- for (const fileEntry of fs8.readdirSync(srcProfileDir, { withFileTypes: true })) {
28449
+ const srcProfileDir = path13.join(srcDir, entry.name);
28450
+ const destProfileDir = path13.join(layout.variantsRoot, entry.name);
28451
+ fs9.mkdirSync(destProfileDir, { recursive: true });
28452
+ for (const fileEntry of fs9.readdirSync(srcProfileDir, { withFileTypes: true })) {
28275
28453
  if (!fileEntry.isFile())
28276
28454
  continue;
28277
- const content = fs8.readFileSync(path12.join(srcProfileDir, fileEntry.name));
28455
+ const content = fs9.readFileSync(path13.join(srcProfileDir, fileEntry.name));
28278
28456
  writeFileIntoDirAtomically(destProfileDir, fileEntry.name, content);
28279
28457
  files++;
28280
28458
  }
28281
28459
  profiles.push(entry.name);
28282
28460
  }
28283
- const retained = fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
28461
+ const retained = fs9.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
28284
28462
  return { host, status: "synced", profiles: profiles.sort(), retained, files };
28285
28463
  }
28286
28464
  function syncGeneratedVariants(opts) {
@@ -28315,14 +28493,14 @@ var init_variant_sync = __esm(() => {
28315
28493
  });
28316
28494
 
28317
28495
  // ../../packages/shared/dist/profile-switch/repo-root.js
28318
- import fs9 from "fs";
28319
- import path13 from "path";
28496
+ import fs10 from "fs";
28497
+ import path14 from "path";
28320
28498
  function findRepoRootWithMarker(startDir, marker, maxLevels) {
28321
28499
  let dir = startDir;
28322
28500
  for (let i = 0;i <= maxLevels; i++) {
28323
- if (fs9.existsSync(path13.join(dir, marker)))
28501
+ if (fs10.existsSync(path14.join(dir, marker)))
28324
28502
  return dir;
28325
- const parent = path13.dirname(dir);
28503
+ const parent = path14.dirname(dir);
28326
28504
  if (parent === dir)
28327
28505
  break;
28328
28506
  dir = parent;
@@ -28332,6 +28510,9 @@ function findRepoRootWithMarker(startDir, marker, maxLevels) {
28332
28510
  var init_repo_root = () => {};
28333
28511
 
28334
28512
  // ../../packages/shared/dist/bootstrap/rules.js
28513
+ function isRetiredRuleId(value) {
28514
+ return RETIRED_RULE_IDS.includes(value);
28515
+ }
28335
28516
  function isBootstrapRuleId(value) {
28336
28517
  return typeof value === "string" && BOOTSTRAP_RULE_IDS.includes(value);
28337
28518
  }
@@ -28350,12 +28531,14 @@ function assertKnownRuleId(id) {
28350
28531
  if (!isBootstrapRuleId(id))
28351
28532
  throw UnknownRuleError(id, BOOTSTRAP_RULE_IDS);
28352
28533
  }
28353
- var BOOTSTRAP_RULE_IDS, BOOTSTRAP_RULES, RULES_BY_ID, BootstrapRuleError, UnknownRuleError = (id, known = BOOTSTRAP_RULE_IDS) => namedError4("UnknownRuleError", `unknown bootstrap rule "${id}" \u2014 valid ids: ${known.join(", ")}`);
28534
+ var BOOTSTRAP_RULE_IDS, RETIRED_RULE_IDS, BOOTSTRAP_RULES, RULES_BY_ID, BootstrapRuleError, UnknownRuleError = (id, known = BOOTSTRAP_RULE_IDS) => {
28535
+ const what = isRetiredRuleId(id) ? `bootstrap rule "${id}" was retired and can no longer be toggled` : `unknown bootstrap rule "${id}"`;
28536
+ return namedError4("UnknownRuleError", `${what} \u2014 valid ids: ${known.join(", ")}`);
28537
+ };
28354
28538
  var init_rules = __esm(() => {
28355
28539
  BOOTSTRAP_RULE_IDS = [
28356
28540
  "caveman",
28357
28541
  "massa-ai-router",
28358
- "persona-router",
28359
28542
  "dedupe-guardrails",
28360
28543
  "plan-challenge",
28361
28544
  "conversation-feedback",
@@ -28363,6 +28546,7 @@ var init_rules = __esm(() => {
28363
28546
  "english-code",
28364
28547
  "code-comments"
28365
28548
  ];
28549
+ RETIRED_RULE_IDS = ["persona-router"];
28366
28550
  BOOTSTRAP_RULES = [
28367
28551
  {
28368
28552
  id: "caveman",
@@ -28374,11 +28558,6 @@ var init_rules = __esm(() => {
28374
28558
  defaultEnabled: true,
28375
28559
  description: "Load the massa-ai skill as the workflow router before substantive work."
28376
28560
  },
28377
- {
28378
- id: "persona-router",
28379
- defaultEnabled: true,
28380
- description: "Select one cataloged specialist persona after massa-ai context is available."
28381
- },
28382
28561
  {
28383
28562
  id: "dedupe-guardrails",
28384
28563
  defaultEnabled: true,
@@ -28420,7 +28599,7 @@ var init_rules = __esm(() => {
28420
28599
  });
28421
28600
 
28422
28601
  // ../../packages/shared/dist/bootstrap/state.js
28423
- import fs10 from "fs";
28602
+ import fs11 from "fs";
28424
28603
  function isPlainObject4(value) {
28425
28604
  return typeof value === "object" && value !== null && !Array.isArray(value);
28426
28605
  }
@@ -28441,6 +28620,8 @@ function resolveBootstrapState(doc2) {
28441
28620
  return { state, ignoredStateKeys: [BOOTSTRAP_STATE_PATH] };
28442
28621
  }
28443
28622
  for (const [key, value] of Object.entries(rules)) {
28623
+ if (isRetiredRuleId(key))
28624
+ continue;
28444
28625
  if (!isBootstrapRuleId(key) || typeof value !== "boolean") {
28445
28626
  ignored.push(key);
28446
28627
  continue;
@@ -28451,7 +28632,7 @@ function resolveBootstrapState(doc2) {
28451
28632
  }
28452
28633
  function readConfigBytes() {
28453
28634
  try {
28454
- return fs10.readFileSync(getConfigPath(), "utf-8");
28635
+ return fs11.readFileSync(getConfigPath(), "utf-8");
28455
28636
  } catch (error51) {
28456
28637
  if (error51?.code === "ENOENT")
28457
28638
  return "";
@@ -28506,7 +28687,7 @@ var init_state2 = __esm(() => {
28506
28687
  });
28507
28688
 
28508
28689
  // ../../packages/shared/dist/bootstrap/render.js
28509
- import path14 from "path";
28690
+ import path15 from "path";
28510
28691
  function wrapBootstrapBlock(body) {
28511
28692
  return `${BOOTSTRAP_BLOCK_START}
28512
28693
  ${body.replace(/\n+$/, "")}
@@ -28519,19 +28700,19 @@ function ruleMarker(id, suffix) {
28519
28700
  function resolveHostRoot(host, targetHome, hostRoot) {
28520
28701
  requireAbsoluteTargetHome(targetHome);
28521
28702
  if (hostRoot === undefined)
28522
- return path14.join(targetHome, ...HOST_CONFIG_DIR[host]);
28523
- const relative = path14.relative(targetHome, hostRoot);
28524
- if (!path14.isAbsolute(hostRoot) || relative === "" || relative.startsWith("..") || path14.isAbsolute(relative)) {
28703
+ return path15.join(targetHome, ...HOST_CONFIG_DIR[host]);
28704
+ const relative = path15.relative(targetHome, hostRoot);
28705
+ if (!path15.isAbsolute(hostRoot) || relative === "" || relative.startsWith("..") || path15.isAbsolute(relative)) {
28525
28706
  throw new BootstrapRenderError("HostRootOutsideTargetHomeError", `hostRoot must be an absolute directory inside targetHome, got "${hostRoot}" for targetHome "${targetHome}"`, [hostRoot, targetHome]);
28526
28707
  }
28527
28708
  return hostRoot;
28528
28709
  }
28529
28710
  function bootstrapContractPath(host, targetHome, hostRoot) {
28530
- return path14.join(resolveHostRoot(host, targetHome, hostRoot), CONTRACT_FILENAME);
28711
+ return path15.join(resolveHostRoot(host, targetHome, hostRoot), CONTRACT_FILENAME);
28531
28712
  }
28532
28713
  function bootstrapStateFilePath(targetHome) {
28533
28714
  requireAbsoluteTargetHome(targetHome);
28534
- return path14.join(targetHome, ".config", "massa-ai", "config.json");
28715
+ return path15.join(targetHome, ".config", "massa-ai", "config.json");
28535
28716
  }
28536
28717
  function renderBootstrap(options) {
28537
28718
  const { source, state, host, targetHome, hostRoot } = options;
@@ -28554,7 +28735,7 @@ ${body}`;
28554
28735
  return { contract, pointer };
28555
28736
  }
28556
28737
  function requireAbsoluteTargetHome(targetHome) {
28557
- if (!path14.isAbsolute(targetHome)) {
28738
+ if (!path15.isAbsolute(targetHome)) {
28558
28739
  throw new BootstrapRenderError("TargetHomeNotAbsoluteError", `targetHome must be an absolute path, got "${targetHome}"`, [targetHome]);
28559
28740
  }
28560
28741
  }
@@ -28731,14 +28912,14 @@ var init_report = __esm(() => {
28731
28912
  });
28732
28913
 
28733
28914
  // ../../packages/shared/dist/bootstrap/engine.js
28734
- import fs11 from "fs";
28735
- import path15 from "path";
28915
+ import fs12 from "fs";
28916
+ import path16 from "path";
28736
28917
  function applyBootstrapState(options) {
28737
28918
  const { targetHome } = options;
28738
28919
  const dryRun = options.dryRun ?? false;
28739
28920
  const warn = options.onWarning ?? ((message) => console.warn(message));
28740
28921
  const configPath = bootstrapStateFilePath(targetHome);
28741
- const installStatePath = path15.join(path15.dirname(configPath), INSTALL_STATE_FILENAME);
28922
+ const installStatePath = path16.join(path16.dirname(configPath), INSTALL_STATE_FILENAME);
28742
28923
  const { platforms } = readInstallState(installStatePath);
28743
28924
  const installed = HOSTS.filter((host) => platforms[host] !== undefined);
28744
28925
  if (installed.length === 0) {
@@ -28831,22 +29012,22 @@ function applyHost(input) {
28831
29012
  }
28832
29013
  function wiringArtifact(host, targetHome, hostRoot) {
28833
29014
  const root = resolveHostRoot(host, targetHome, hostRoot);
28834
- const contractPath = path15.join(root, CONTRACT_FILENAME);
29015
+ const contractPath = path16.join(root, CONTRACT_FILENAME);
28835
29016
  switch (host) {
28836
29017
  case "claude":
28837
- return { file: path15.join(root, "CLAUDE.md"), token: `@${CONTRACT_FILENAME}` };
29018
+ return { file: path16.join(root, "CLAUDE.md"), token: `@${CONTRACT_FILENAME}` };
28838
29019
  case "codex":
28839
29020
  case "cursor":
28840
- return { file: path15.join(root, "AGENTS.md"), token: contractPath };
29021
+ return { file: path16.join(root, "AGENTS.md"), token: contractPath };
28841
29022
  case "opencode":
28842
29023
  return { file: openCodeConfigPath(root), token: `"${contractPath}"` };
28843
29024
  }
28844
29025
  }
28845
29026
  function openCodeConfigPath(root) {
28846
- const json2 = path15.join(root, "opencode.json");
28847
- if (fs11.existsSync(json2))
29027
+ const json2 = path16.join(root, "opencode.json");
29028
+ if (fs12.existsSync(json2))
28848
29029
  return json2;
28849
- return path15.join(root, "opencode.jsonc");
29030
+ return path16.join(root, "opencode.jsonc");
28850
29031
  }
28851
29032
  function isWired(host, targetHome, hostRoot) {
28852
29033
  const artifact = wiringArtifact(host, targetHome, hostRoot);
@@ -28859,7 +29040,7 @@ function notWiredReason(host, targetHome, hostRoot) {
28859
29040
  }
28860
29041
  function readFileOrNull(filePath) {
28861
29042
  try {
28862
- return fs11.readFileSync(filePath, "utf-8");
29043
+ return fs12.readFileSync(filePath, "utf-8");
28863
29044
  } catch {
28864
29045
  return null;
28865
29046
  }
@@ -28941,8 +29122,10 @@ var init_dist = __esm(() => {
28941
29122
  init_state();
28942
29123
  init_lock();
28943
29124
  init_engine();
29125
+ init_ownership();
28944
29126
  init_variant_sync();
28945
29127
  init_repo_root();
29128
+ init_doctor();
28946
29129
  init_bootstrap();
28947
29130
  init_types2();
28948
29131
  init_interfaces();
@@ -30465,7 +30648,7 @@ var import_brace_expansion, minimatch = (p, pattern, options = {}) => {
30465
30648
  }, qmarksTestNoExtDot = ([$0]) => {
30466
30649
  const len = $0.length;
30467
30650
  return (f) => f.length === len && f !== "." && f !== "..";
30468
- }, defaultPlatform, path16, sep, GLOBSTAR, qmark2 = "[^/]", star2, twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options), ext = (a, b = {}) => Object.assign({}, a, b), defaults = (def) => {
30651
+ }, defaultPlatform, path17, sep, GLOBSTAR, qmark2 = "[^/]", star2, twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options), ext = (a, b = {}) => Object.assign({}, a, b), defaults = (def) => {
30469
30652
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
30470
30653
  return minimatch;
30471
30654
  }
@@ -30523,11 +30706,11 @@ var init_esm = __esm(() => {
30523
30706
  starRE = /^\*+$/;
30524
30707
  qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
30525
30708
  defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
30526
- path16 = {
30709
+ path17 = {
30527
30710
  win32: { sep: "\\" },
30528
30711
  posix: { sep: "/" }
30529
30712
  };
30530
- sep = defaultPlatform === "win32" ? path16.win32.sep : path16.posix.sep;
30713
+ sep = defaultPlatform === "win32" ? path17.win32.sep : path17.posix.sep;
30531
30714
  minimatch.sep = sep;
30532
30715
  GLOBSTAR = Symbol("globstar **");
30533
30716
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -32493,12 +32676,12 @@ var init_esm4 = __esm(() => {
32493
32676
  childrenCache() {
32494
32677
  return this.#children;
32495
32678
  }
32496
- resolve(path17) {
32497
- if (!path17) {
32679
+ resolve(path18) {
32680
+ if (!path18) {
32498
32681
  return this;
32499
32682
  }
32500
- const rootPath = this.getRootString(path17);
32501
- const dir = path17.substring(rootPath.length);
32683
+ const rootPath = this.getRootString(path18);
32684
+ const dir = path18.substring(rootPath.length);
32502
32685
  const dirParts = dir.split(this.splitSep);
32503
32686
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
32504
32687
  return result;
@@ -33026,8 +33209,8 @@ var init_esm4 = __esm(() => {
33026
33209
  newChild(name, type = UNKNOWN, opts = {}) {
33027
33210
  return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
33028
33211
  }
33029
- getRootString(path17) {
33030
- return win32.parse(path17).root;
33212
+ getRootString(path18) {
33213
+ return win32.parse(path18).root;
33031
33214
  }
33032
33215
  getRoot(rootPath) {
33033
33216
  rootPath = uncToDrive(rootPath.toUpperCase());
@@ -33052,8 +33235,8 @@ var init_esm4 = __esm(() => {
33052
33235
  constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
33053
33236
  super(name, type, root, roots, nocase, children, opts);
33054
33237
  }
33055
- getRootString(path17) {
33056
- return path17.startsWith("/") ? "/" : "";
33238
+ getRootString(path18) {
33239
+ return path18.startsWith("/") ? "/" : "";
33057
33240
  }
33058
33241
  getRoot(_rootPath) {
33059
33242
  return this.root;
@@ -33072,8 +33255,8 @@ var init_esm4 = __esm(() => {
33072
33255
  #children;
33073
33256
  nocase;
33074
33257
  #fs;
33075
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs12 = defaultFS } = {}) {
33076
- this.#fs = fsFromOption(fs12);
33258
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs13 = defaultFS } = {}) {
33259
+ this.#fs = fsFromOption(fs13);
33077
33260
  if (cwd instanceof URL || cwd.startsWith("file://")) {
33078
33261
  cwd = fileURLToPath(cwd);
33079
33262
  }
@@ -33109,11 +33292,11 @@ var init_esm4 = __esm(() => {
33109
33292
  }
33110
33293
  this.cwd = prev;
33111
33294
  }
33112
- depth(path17 = this.cwd) {
33113
- if (typeof path17 === "string") {
33114
- path17 = this.cwd.resolve(path17);
33295
+ depth(path18 = this.cwd) {
33296
+ if (typeof path18 === "string") {
33297
+ path18 = this.cwd.resolve(path18);
33115
33298
  }
33116
- return path17.depth();
33299
+ return path18.depth();
33117
33300
  }
33118
33301
  childrenCache() {
33119
33302
  return this.#children;
@@ -33529,9 +33712,9 @@ var init_esm4 = __esm(() => {
33529
33712
  process4();
33530
33713
  return results;
33531
33714
  }
33532
- chdir(path17 = this.cwd) {
33715
+ chdir(path18 = this.cwd) {
33533
33716
  const oldCwd = this.cwd;
33534
- this.cwd = typeof path17 === "string" ? this.cwd.resolve(path17) : path17;
33717
+ this.cwd = typeof path18 === "string" ? this.cwd.resolve(path18) : path18;
33535
33718
  this.cwd[setAsCwd](oldCwd);
33536
33719
  }
33537
33720
  };
@@ -33548,8 +33731,8 @@ var init_esm4 = __esm(() => {
33548
33731
  parseRootPath(dir) {
33549
33732
  return win32.parse(dir).root.toUpperCase();
33550
33733
  }
33551
- newRoot(fs12) {
33552
- return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs12 });
33734
+ newRoot(fs13) {
33735
+ return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs13 });
33553
33736
  }
33554
33737
  isAbsolute(p) {
33555
33738
  return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
@@ -33565,8 +33748,8 @@ var init_esm4 = __esm(() => {
33565
33748
  parseRootPath(_dir) {
33566
33749
  return "/";
33567
33750
  }
33568
- newRoot(fs12) {
33569
- return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs12 });
33751
+ newRoot(fs13) {
33752
+ return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs13 });
33570
33753
  }
33571
33754
  isAbsolute(p) {
33572
33755
  return p.startsWith("/");
@@ -33823,8 +34006,8 @@ class MatchRecord {
33823
34006
  this.store.set(target, current === undefined ? n : n & current);
33824
34007
  }
33825
34008
  entries() {
33826
- return [...this.store.entries()].map(([path17, n]) => [
33827
- path17,
34009
+ return [...this.store.entries()].map(([path18, n]) => [
34010
+ path18,
33828
34011
  !!(n & 2),
33829
34012
  !!(n & 1)
33830
34013
  ]);
@@ -34028,9 +34211,9 @@ class GlobUtil {
34028
34211
  signal;
34029
34212
  maxDepth;
34030
34213
  includeChildMatches;
34031
- constructor(patterns, path17, opts) {
34214
+ constructor(patterns, path18, opts) {
34032
34215
  this.patterns = patterns;
34033
- this.path = path17;
34216
+ this.path = path18;
34034
34217
  this.opts = opts;
34035
34218
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
34036
34219
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -34049,11 +34232,11 @@ class GlobUtil {
34049
34232
  });
34050
34233
  }
34051
34234
  }
34052
- #ignored(path17) {
34053
- return this.seen.has(path17) || !!this.#ignore?.ignored?.(path17);
34235
+ #ignored(path18) {
34236
+ return this.seen.has(path18) || !!this.#ignore?.ignored?.(path18);
34054
34237
  }
34055
- #childrenIgnored(path17) {
34056
- return !!this.#ignore?.childrenIgnored?.(path17);
34238
+ #childrenIgnored(path18) {
34239
+ return !!this.#ignore?.childrenIgnored?.(path18);
34057
34240
  }
34058
34241
  pause() {
34059
34242
  this.paused = true;
@@ -34270,8 +34453,8 @@ var init_walker = __esm(() => {
34270
34453
  init_processor();
34271
34454
  GlobWalker = class GlobWalker extends GlobUtil {
34272
34455
  matches = new Set;
34273
- constructor(patterns, path17, opts) {
34274
- super(patterns, path17, opts);
34456
+ constructor(patterns, path18, opts) {
34457
+ super(patterns, path18, opts);
34275
34458
  }
34276
34459
  matchEmit(e) {
34277
34460
  this.matches.add(e);
@@ -34308,8 +34491,8 @@ var init_walker = __esm(() => {
34308
34491
  };
34309
34492
  GlobStream = class GlobStream extends GlobUtil {
34310
34493
  results;
34311
- constructor(patterns, path17, opts) {
34312
- super(patterns, path17, opts);
34494
+ constructor(patterns, path18, opts) {
34495
+ super(patterns, path18, opts);
34313
34496
  this.results = new Minipass({
34314
34497
  signal: this.signal,
34315
34498
  objectMode: true
@@ -34737,20 +34920,20 @@ var require_ignore = __commonJS((exports, module) => {
34737
34920
  var throwError = (message, Ctor) => {
34738
34921
  throw new Ctor(message);
34739
34922
  };
34740
- var checkPath = (path17, originalPath, doThrow) => {
34741
- if (!isString(path17)) {
34923
+ var checkPath = (path18, originalPath, doThrow) => {
34924
+ if (!isString(path18)) {
34742
34925
  return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
34743
34926
  }
34744
- if (!path17) {
34927
+ if (!path18) {
34745
34928
  return doThrow(`path must not be empty`, TypeError);
34746
34929
  }
34747
- if (checkPath.isNotRelative(path17)) {
34930
+ if (checkPath.isNotRelative(path18)) {
34748
34931
  const r = "`path.relative()`d";
34749
34932
  return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
34750
34933
  }
34751
34934
  return true;
34752
34935
  };
34753
- var isNotRelative = (path17) => REGEX_TEST_INVALID_PATH.test(path17);
34936
+ var isNotRelative = (path18) => REGEX_TEST_INVALID_PATH.test(path18);
34754
34937
  checkPath.isNotRelative = isNotRelative;
34755
34938
  checkPath.convert = (p) => p;
34756
34939
 
@@ -34793,7 +34976,7 @@ var require_ignore = __commonJS((exports, module) => {
34793
34976
  addPattern(pattern) {
34794
34977
  return this.add(pattern);
34795
34978
  }
34796
- _testOne(path17, checkUnignored) {
34979
+ _testOne(path18, checkUnignored) {
34797
34980
  let ignored = false;
34798
34981
  let unignored = false;
34799
34982
  this._rules.forEach((rule) => {
@@ -34801,7 +34984,7 @@ var require_ignore = __commonJS((exports, module) => {
34801
34984
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
34802
34985
  return;
34803
34986
  }
34804
- const matched = rule.regex.test(path17);
34987
+ const matched = rule.regex.test(path18);
34805
34988
  if (matched) {
34806
34989
  ignored = !negative;
34807
34990
  unignored = negative;
@@ -34813,39 +34996,39 @@ var require_ignore = __commonJS((exports, module) => {
34813
34996
  };
34814
34997
  }
34815
34998
  _test(originalPath, cache, checkUnignored, slices) {
34816
- const path17 = originalPath && checkPath.convert(originalPath);
34817
- checkPath(path17, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
34818
- return this._t(path17, cache, checkUnignored, slices);
34999
+ const path18 = originalPath && checkPath.convert(originalPath);
35000
+ checkPath(path18, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
35001
+ return this._t(path18, cache, checkUnignored, slices);
34819
35002
  }
34820
- _t(path17, cache, checkUnignored, slices) {
34821
- if (path17 in cache) {
34822
- return cache[path17];
35003
+ _t(path18, cache, checkUnignored, slices) {
35004
+ if (path18 in cache) {
35005
+ return cache[path18];
34823
35006
  }
34824
35007
  if (!slices) {
34825
- slices = path17.split(SLASH2);
35008
+ slices = path18.split(SLASH2);
34826
35009
  }
34827
35010
  slices.pop();
34828
35011
  if (!slices.length) {
34829
- return cache[path17] = this._testOne(path17, checkUnignored);
35012
+ return cache[path18] = this._testOne(path18, checkUnignored);
34830
35013
  }
34831
35014
  const parent = this._t(slices.join(SLASH2) + SLASH2, cache, checkUnignored, slices);
34832
- return cache[path17] = parent.ignored ? parent : this._testOne(path17, checkUnignored);
35015
+ return cache[path18] = parent.ignored ? parent : this._testOne(path18, checkUnignored);
34833
35016
  }
34834
- ignores(path17) {
34835
- return this._test(path17, this._ignoreCache, false).ignored;
35017
+ ignores(path18) {
35018
+ return this._test(path18, this._ignoreCache, false).ignored;
34836
35019
  }
34837
35020
  createFilter() {
34838
- return (path17) => !this.ignores(path17);
35021
+ return (path18) => !this.ignores(path18);
34839
35022
  }
34840
35023
  filter(paths) {
34841
35024
  return makeArray(paths).filter(this.createFilter());
34842
35025
  }
34843
- test(path17) {
34844
- return this._test(path17, this._testCache, true);
35026
+ test(path18) {
35027
+ return this._test(path18, this._testCache, true);
34845
35028
  }
34846
35029
  }
34847
35030
  var factory = (options) => new Ignore2(options);
34848
- var isPathValid = (path17) => checkPath(path17 && checkPath.convert(path17), path17, RETURN_FALSE);
35031
+ var isPathValid = (path18) => checkPath(path18 && checkPath.convert(path18), path18, RETURN_FALSE);
34849
35032
  factory.isPathValid = isPathValid;
34850
35033
  factory.default = factory;
34851
35034
  module.exports = factory;
@@ -34853,7 +35036,7 @@ var require_ignore = __commonJS((exports, module) => {
34853
35036
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
34854
35037
  checkPath.convert = makePosix;
34855
35038
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
34856
- checkPath.isNotRelative = (path17) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path17) || isNotRelative(path17);
35039
+ checkPath.isNotRelative = (path18) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path18) || isNotRelative(path18);
34857
35040
  }
34858
35041
  });
34859
35042
 
@@ -34915,18 +35098,18 @@ function validatePolicy(policy, opts = {}) {
34915
35098
  }
34916
35099
  }
34917
35100
  }
34918
- function matchesGlob2(path17, pattern) {
35101
+ function matchesGlob(path18, pattern) {
34919
35102
  let re = regexCache.get(pattern);
34920
35103
  if (!re) {
34921
35104
  re = globToRegex(pattern);
34922
35105
  regexCache.set(pattern, re);
34923
35106
  }
34924
- return re.test(path17);
35107
+ return re.test(path18);
34925
35108
  }
34926
35109
  var DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
34927
35110
  const normalized = filePath.trim();
34928
35111
  for (const rule of policy.rules) {
34929
- if (matchesGlob2(normalized, rule.pattern))
35112
+ if (matchesGlob(normalized, rule.pattern))
34930
35113
  return rule.disposition;
34931
35114
  }
34932
35115
  return "Keep";
@@ -34938,8 +35121,8 @@ var init_capture_policy = __esm(() => {
34938
35121
  });
34939
35122
 
34940
35123
  // ../../packages/core/dist/services/search/ignore-patterns.js
34941
- import fs12 from "fs/promises";
34942
- import path17 from "path";
35124
+ import fs13 from "fs/promises";
35125
+ import path18 from "path";
34943
35126
  function buildExtensionGlob(extensions) {
34944
35127
  return extensions.map((ext2) => `**/*${ext2}`);
34945
35128
  }
@@ -34962,8 +35145,8 @@ async function loadProjectIgnore(projectPath) {
34962
35145
  const ig = ignore();
34963
35146
  ig.add(DEFAULT_IGNORES);
34964
35147
  try {
34965
- const gitignorePath = path17.join(projectPath, ".gitignore");
34966
- const gitignoreContent = await fs12.readFile(gitignorePath, "utf8");
35148
+ const gitignorePath = path18.join(projectPath, ".gitignore");
35149
+ const gitignoreContent = await fs13.readFile(gitignorePath, "utf8");
34967
35150
  const rules = gitignoreContent.split(`
34968
35151
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
34969
35152
  ig.add(rules);
@@ -36562,15 +36745,15 @@ var require_pg_connection_string = __commonJS((exports, module) => {
36562
36745
  if (config3.sslnegotiation === "direct" && config3.ssl === undefined) {
36563
36746
  config3.ssl = true;
36564
36747
  }
36565
- const fs13 = config3.sslcert || config3.sslkey || config3.sslrootcert ? __require("fs") : null;
36748
+ const fs14 = config3.sslcert || config3.sslkey || config3.sslrootcert ? __require("fs") : null;
36566
36749
  if (config3.sslcert) {
36567
- config3.ssl.cert = fs13.readFileSync(config3.sslcert).toString();
36750
+ config3.ssl.cert = fs14.readFileSync(config3.sslcert).toString();
36568
36751
  }
36569
36752
  if (config3.sslkey) {
36570
- config3.ssl.key = fs13.readFileSync(config3.sslkey).toString();
36753
+ config3.ssl.key = fs14.readFileSync(config3.sslkey).toString();
36571
36754
  }
36572
36755
  if (config3.sslrootcert) {
36573
- config3.ssl.ca = fs13.readFileSync(config3.sslrootcert).toString();
36756
+ config3.ssl.ca = fs14.readFileSync(config3.sslrootcert).toString();
36574
36757
  }
36575
36758
  if (options.useLibpqCompat && config3.uselibpqcompat) {
36576
36759
  throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");
@@ -38284,7 +38467,7 @@ var require_split2 = __commonJS((exports, module) => {
38284
38467
 
38285
38468
  // ../../node_modules/pgpass/lib/helper.js
38286
38469
  var require_helper = __commonJS((exports, module) => {
38287
- var path18 = __require("path");
38470
+ var path19 = __require("path");
38288
38471
  var Stream2 = __require("stream").Stream;
38289
38472
  var split = require_split2();
38290
38473
  var util3 = __require("util");
@@ -38324,7 +38507,7 @@ var require_helper = __commonJS((exports, module) => {
38324
38507
  };
38325
38508
  exports.getFileName = function(rawEnv) {
38326
38509
  var env = rawEnv || process.env;
38327
- var file2 = env.PGPASSFILE || (isWin ? path18.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path18.join(env.HOME || "./", ".pgpass"));
38510
+ var file2 = env.PGPASSFILE || (isWin ? path19.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path19.join(env.HOME || "./", ".pgpass"));
38328
38511
  return file2;
38329
38512
  };
38330
38513
  exports.usePgPass = function(stats, fname) {
@@ -38448,16 +38631,16 @@ var require_helper = __commonJS((exports, module) => {
38448
38631
 
38449
38632
  // ../../node_modules/pgpass/lib/index.js
38450
38633
  var require_lib = __commonJS((exports, module) => {
38451
- var path18 = __require("path");
38452
- var fs13 = __require("fs");
38634
+ var path19 = __require("path");
38635
+ var fs14 = __require("fs");
38453
38636
  var helper = require_helper();
38454
38637
  module.exports = function(connInfo, cb) {
38455
38638
  var file2 = helper.getFileName();
38456
- fs13.stat(file2, function(err, stat) {
38639
+ fs14.stat(file2, function(err, stat) {
38457
38640
  if (err || !helper.usePgPass(stat, file2)) {
38458
38641
  return cb(undefined);
38459
38642
  }
38460
- var st = fs13.createReadStream(file2);
38643
+ var st = fs14.createReadStream(file2);
38461
38644
  helper.getPassword(connInfo, st, cb);
38462
38645
  });
38463
38646
  };
@@ -40095,7 +40278,7 @@ class ProjectIdentityAliasResolver {
40095
40278
  this.cache.set(projectId, { canonical, expiresAt: this.now() + this.ttlMs });
40096
40279
  return canonical;
40097
40280
  } catch (error51) {
40098
- logger.warn("[project-identity] alias resolution failed; using original id", safeErrorSummary(error51));
40281
+ logger.warn("[project-identity] alias resolution failed; using original id", { projectId, ...safeErrorSummary(error51) });
40099
40282
  return projectId;
40100
40283
  }
40101
40284
  }
@@ -40156,8 +40339,8 @@ var init_alias_resolver = __esm(() => {
40156
40339
  });
40157
40340
 
40158
40341
  // ../../packages/core/dist/services/search/index-manager.js
40159
- import fs13 from "fs";
40160
- import path18 from "path";
40342
+ import fs14 from "fs";
40343
+ import path19 from "path";
40161
40344
 
40162
40345
  class IndexManager {
40163
40346
  metadataCache = new Map;
@@ -40250,9 +40433,9 @@ class IndexManager {
40250
40433
  const fileMetadata = {};
40251
40434
  let totalSize = 0;
40252
40435
  for (const filePath of indexedFiles) {
40253
- const fullPath = path18.join(projectPath, filePath);
40436
+ const fullPath = path19.join(projectPath, filePath);
40254
40437
  try {
40255
- const stat = await fs13.promises.stat(fullPath);
40438
+ const stat = await fs14.promises.stat(fullPath);
40256
40439
  fileMetadata[filePath] = {
40257
40440
  path: filePath,
40258
40441
  mtime: stat.mtimeMs,
@@ -40303,9 +40486,9 @@ class IndexManager {
40303
40486
  if (ig.ignores(match2)) {
40304
40487
  continue;
40305
40488
  }
40306
- const fullPath = path18.join(projectPath, match2);
40489
+ const fullPath = path19.join(projectPath, match2);
40307
40490
  try {
40308
- const stat = await fs13.promises.stat(fullPath);
40491
+ const stat = await fs14.promises.stat(fullPath);
40309
40492
  files.set(match2, {
40310
40493
  path: match2,
40311
40494
  mtime: stat.mtimeMs,
@@ -43558,23 +43741,23 @@ var require_auth_config = __commonJS((exports, module) => {
43558
43741
  writeAuthConfig: () => writeAuthConfig
43559
43742
  });
43560
43743
  module.exports = __toCommonJS2(auth_config_exports);
43561
- var fs14 = __toESM2(__require("fs"));
43562
- var path19 = __toESM2(__require("path"));
43744
+ var fs15 = __toESM2(__require("fs"));
43745
+ var path20 = __toESM2(__require("path"));
43563
43746
  var import_token_util = require_token_util();
43564
43747
  function getAuthConfigPath() {
43565
43748
  const dataDir = (0, import_token_util.getVercelDataDir)();
43566
43749
  if (!dataDir) {
43567
43750
  throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
43568
43751
  }
43569
- return path19.join(dataDir, "auth.json");
43752
+ return path20.join(dataDir, "auth.json");
43570
43753
  }
43571
43754
  function readAuthConfig() {
43572
43755
  try {
43573
43756
  const authPath = getAuthConfigPath();
43574
- if (!fs14.existsSync(authPath)) {
43757
+ if (!fs15.existsSync(authPath)) {
43575
43758
  return null;
43576
43759
  }
43577
- const content = fs14.readFileSync(authPath, "utf8");
43760
+ const content = fs15.readFileSync(authPath, "utf8");
43578
43761
  if (!content) {
43579
43762
  return null;
43580
43763
  }
@@ -43585,11 +43768,11 @@ var require_auth_config = __commonJS((exports, module) => {
43585
43768
  }
43586
43769
  function writeAuthConfig(config3) {
43587
43770
  const authPath = getAuthConfigPath();
43588
- const authDir = path19.dirname(authPath);
43589
- if (!fs14.existsSync(authDir)) {
43590
- fs14.mkdirSync(authDir, { mode: 504, recursive: true });
43771
+ const authDir = path20.dirname(authPath);
43772
+ if (!fs15.existsSync(authDir)) {
43773
+ fs15.mkdirSync(authDir, { mode: 504, recursive: true });
43591
43774
  }
43592
- fs14.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
43775
+ fs15.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
43593
43776
  }
43594
43777
  function isValidAccessToken(authConfig, expirationBufferMs = 0) {
43595
43778
  if (!authConfig.token)
@@ -43764,8 +43947,8 @@ var require_token_util = __commonJS((exports, module) => {
43764
43947
  saveToken: () => saveToken
43765
43948
  });
43766
43949
  module.exports = __toCommonJS2(token_util_exports);
43767
- var path19 = __toESM2(__require("path"));
43768
- var fs14 = __toESM2(__require("fs"));
43950
+ var path20 = __toESM2(__require("path"));
43951
+ var fs15 = __toESM2(__require("fs"));
43769
43952
  var import_token_error = require_token_error();
43770
43953
  var import_token_io = require_token_io();
43771
43954
  var import_auth_config = require_auth_config();
@@ -43777,7 +43960,7 @@ var require_token_util = __commonJS((exports, module) => {
43777
43960
  if (!dataDir) {
43778
43961
  return null;
43779
43962
  }
43780
- return path19.join(dataDir, vercelFolder);
43963
+ return path20.join(dataDir, vercelFolder);
43781
43964
  }
43782
43965
  async function getVercelToken2(options) {
43783
43966
  const authConfig = (0, import_auth_config.readAuthConfig)();
@@ -43845,11 +44028,11 @@ var require_token_util = __commonJS((exports, module) => {
43845
44028
  if (!dir) {
43846
44029
  throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");
43847
44030
  }
43848
- const prjPath = path19.join(dir, ".vercel", "project.json");
43849
- if (!fs14.existsSync(prjPath)) {
44031
+ const prjPath = path20.join(dir, ".vercel", "project.json");
44032
+ if (!fs15.existsSync(prjPath)) {
43850
44033
  throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");
43851
44034
  }
43852
- const prj = JSON.parse(fs14.readFileSync(prjPath, "utf8"));
44035
+ const prj = JSON.parse(fs15.readFileSync(prjPath, "utf8"));
43853
44036
  if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") {
43854
44037
  throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");
43855
44038
  }
@@ -43860,11 +44043,11 @@ var require_token_util = __commonJS((exports, module) => {
43860
44043
  if (!dir) {
43861
44044
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
43862
44045
  }
43863
- const tokenPath = path19.join(dir, "com.vercel.token", `${projectId}.json`);
44046
+ const tokenPath = path20.join(dir, "com.vercel.token", `${projectId}.json`);
43864
44047
  const tokenJson = JSON.stringify(token);
43865
- fs14.mkdirSync(path19.dirname(tokenPath), { mode: 504, recursive: true });
43866
- fs14.writeFileSync(tokenPath, tokenJson);
43867
- fs14.chmodSync(tokenPath, 432);
44048
+ fs15.mkdirSync(path20.dirname(tokenPath), { mode: 504, recursive: true });
44049
+ fs15.writeFileSync(tokenPath, tokenJson);
44050
+ fs15.chmodSync(tokenPath, 432);
43868
44051
  return;
43869
44052
  }
43870
44053
  function loadToken(projectId) {
@@ -43872,11 +44055,11 @@ var require_token_util = __commonJS((exports, module) => {
43872
44055
  if (!dir) {
43873
44056
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
43874
44057
  }
43875
- const tokenPath = path19.join(dir, "com.vercel.token", `${projectId}.json`);
43876
- if (!fs14.existsSync(tokenPath)) {
44058
+ const tokenPath = path20.join(dir, "com.vercel.token", `${projectId}.json`);
44059
+ if (!fs15.existsSync(tokenPath)) {
43877
44060
  return null;
43878
44061
  }
43879
- const token = JSON.parse(fs14.readFileSync(tokenPath, "utf8"));
44062
+ const token = JSON.parse(fs15.readFileSync(tokenPath, "utf8"));
43880
44063
  assertVercelOidcTokenResponse(token);
43881
44064
  return token;
43882
44065
  }
@@ -54718,37 +54901,37 @@ function createOpenAI(options = {}) {
54718
54901
  }, `ai-sdk/openai/${VERSION4}`);
54719
54902
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
54720
54903
  provider: `${providerName}.chat`,
54721
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54904
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54722
54905
  headers: getHeaders,
54723
54906
  fetch: options.fetch
54724
54907
  });
54725
54908
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
54726
54909
  provider: `${providerName}.completion`,
54727
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54910
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54728
54911
  headers: getHeaders,
54729
54912
  fetch: options.fetch
54730
54913
  });
54731
54914
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
54732
54915
  provider: `${providerName}.embedding`,
54733
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54916
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54734
54917
  headers: getHeaders,
54735
54918
  fetch: options.fetch
54736
54919
  });
54737
54920
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
54738
54921
  provider: `${providerName}.image`,
54739
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54922
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54740
54923
  headers: getHeaders,
54741
54924
  fetch: options.fetch
54742
54925
  });
54743
54926
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
54744
54927
  provider: `${providerName}.transcription`,
54745
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54928
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54746
54929
  headers: getHeaders,
54747
54930
  fetch: options.fetch
54748
54931
  });
54749
54932
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
54750
54933
  provider: `${providerName}.speech`,
54751
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54934
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54752
54935
  headers: getHeaders,
54753
54936
  fetch: options.fetch
54754
54937
  });
@@ -54761,7 +54944,7 @@ function createOpenAI(options = {}) {
54761
54944
  const createResponsesModel = (modelId) => {
54762
54945
  return new OpenAIResponsesLanguageModel(modelId, {
54763
54946
  provider: `${providerName}.responses`,
54764
- url: ({ path: path19 }) => `${baseURL}${path19}`,
54947
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
54765
54948
  headers: getHeaders,
54766
54949
  fetch: options.fetch,
54767
54950
  fileIdPrefixes: ["file-"]
@@ -59202,7 +59385,7 @@ async function _checkJsonSchemaSupport() {
59202
59385
  } catch (e) {
59203
59386
  _jsonSchemaSupported = false;
59204
59387
  logger.warn("json_schema: version check error \u2014 falling back to json_object", {
59205
- error: e.message
59388
+ error: e
59206
59389
  });
59207
59390
  return false;
59208
59391
  }
@@ -59250,7 +59433,7 @@ function hostPort(url2) {
59250
59433
  return null;
59251
59434
  }
59252
59435
  }
59253
- function resolveInferenceSpec(baseUrl) {
59436
+ function resolveMatchedProviderSpec(baseUrl) {
59254
59437
  const target = hostPort(baseUrl);
59255
59438
  if (target) {
59256
59439
  const match2 = inferenceProviderList().find((spec) => hostPort(spec.defaultLlmBaseUrl) === target);
@@ -59268,7 +59451,13 @@ function resolveInferenceSpec(baseUrl) {
59268
59451
  if (embeddingProvider && LOCAL_INFERENCE_IDS.includes(embeddingProvider)) {
59269
59452
  return INFERENCE_PROVIDERS[embeddingProvider];
59270
59453
  }
59271
- return INFERENCE_PROVIDERS.ollama;
59454
+ return;
59455
+ }
59456
+ function resolveInferenceSpec(baseUrl) {
59457
+ return resolveMatchedProviderSpec(baseUrl) ?? INFERENCE_PROVIDERS.ollama;
59458
+ }
59459
+ function resolveProviderIdForLogging(baseUrl) {
59460
+ return resolveMatchedProviderSpec(baseUrl)?.id ?? "unknown";
59272
59461
  }
59273
59462
  function _wrapFetchDisableThink(baseFetch) {
59274
59463
  const wrapped = async (input, init) => {
@@ -59411,12 +59600,40 @@ function _isAbortOrTimeoutError(err) {
59411
59600
  }
59412
59601
  return false;
59413
59602
  }
59414
- async function llmComplete(prompt, opts = {}) {
59603
+ function summarizeZodIssues(error51, maxIssues = 5) {
59604
+ return error51.issues.slice(0, maxIssues).map((issue2) => `${issue2.path.join(".") || "(root)"}: ${issue2.message}`).join("; ");
59605
+ }
59606
+ function recordLlmFailure(label, role, model, baseUrl, timeoutMs, elapsedMs, err) {
59607
+ const consecutiveFailures = (llmFailureStreaks.get(label) ?? 0) + 1;
59608
+ llmFailureStreaks.set(label, consecutiveFailures);
59609
+ logger.warn("LLM call failed \u2014 using non-LLM fallback", {
59610
+ label,
59611
+ role,
59612
+ model,
59613
+ provider: resolveProviderIdForLogging(baseUrl),
59614
+ timeoutMs,
59615
+ elapsedMs,
59616
+ timedOut: _isAbortOrTimeoutError(err),
59617
+ error: err,
59618
+ consecutiveFailures
59619
+ });
59620
+ return consecutiveFailures;
59621
+ }
59622
+ function recordLlmSuccess(label, model) {
59623
+ const priorFailures = llmFailureStreaks.get(label) ?? 0;
59624
+ if (priorFailures > 0) {
59625
+ logger.info("LLM call recovered", { label, model, afterFailures: priorFailures });
59626
+ }
59627
+ llmFailureStreaks.set(label, 0);
59628
+ }
59629
+ async function llmComplete(prompt, opts) {
59415
59630
  if (!isLlmEnabled()) {
59416
59631
  return { ok: false, error: "llm disabled" };
59417
59632
  }
59418
59633
  const llm = getLlmConfig({ modelRole: opts.modelRole });
59634
+ const role = opts.modelRole ?? "instruct";
59419
59635
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
59636
+ const startedAt = Date.now();
59420
59637
  try {
59421
59638
  const result = await generateText({
59422
59639
  model: buildProvider(llm),
@@ -59427,14 +59644,17 @@ async function llmComplete(prompt, opts = {}) {
59427
59644
  abortSignal: timeoutSignal(timeoutMs)
59428
59645
  });
59429
59646
  const text2 = result.text ?? "";
59430
- if (text2.length > 0)
59647
+ if (text2.length > 0) {
59648
+ recordLlmSuccess(opts.label, llm.model);
59431
59649
  return { ok: true, value: text2 };
59650
+ }
59432
59651
  if (llm.disableThink) {
59433
59652
  const reasoning = _reasoningToText(result);
59434
59653
  if (reasoning.length > 0) {
59435
59654
  logger.warn("llmComplete: empty content \u2014 recovered from reasoning channel", {
59436
59655
  reasoningLen: reasoning.length
59437
59656
  });
59657
+ recordLlmSuccess(opts.label, llm.model);
59438
59658
  return { ok: true, value: reasoning };
59439
59659
  }
59440
59660
  logger.warn("llm reasoning-recovery empty", {
@@ -59442,21 +59662,22 @@ async function llmComplete(prompt, opts = {}) {
59442
59662
  finishReason: result?.finishReason ?? null
59443
59663
  });
59444
59664
  }
59445
- logger.warn("llmComplete: empty content and no reasoning \u2014 degrading", {});
59446
- return { ok: false, error: "empty content (thinking model)" };
59665
+ const emptyErr = new Error("empty content (thinking model)");
59666
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, emptyErr);
59667
+ return { ok: false, error: emptyErr.message };
59447
59668
  } catch (e) {
59448
- logger.warn("llmComplete failed \u2014 degrading to non-LLM path", {
59449
- error: e.message
59450
- });
59669
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, e);
59451
59670
  return { ok: false, error: e.message };
59452
59671
  }
59453
59672
  }
59454
- async function llmObject(prompt, schema, opts = {}) {
59673
+ async function llmObject(prompt, schema, opts) {
59455
59674
  if (!isLlmEnabled()) {
59456
59675
  return { ok: false, error: "llm disabled" };
59457
59676
  }
59458
59677
  const llm = getLlmConfig({ modelRole: opts.modelRole });
59678
+ const role = opts.modelRole ?? "instruct";
59459
59679
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
59680
+ const startedAt = Date.now();
59460
59681
  let result = null;
59461
59682
  try {
59462
59683
  const useJsonSchema = llm.disableThink && await _checkJsonSchemaSupport();
@@ -59471,7 +59692,8 @@ async function llmObject(prompt, schema, opts = {}) {
59471
59692
  maxOutputTokens: llm.maxOutputTokens,
59472
59693
  abortSignal: timeoutSignal(timeoutMs)
59473
59694
  });
59474
- logger.info("json_schema: constrained decoding used", {});
59695
+ logger.debug("json_schema: constrained decoding used", { label: opts.label, model: llm.model });
59696
+ recordLlmSuccess(opts.label, llm.model);
59475
59697
  return { ok: true, value: result.object };
59476
59698
  }
59477
59699
  result = await generateObject({
@@ -59485,7 +59707,8 @@ async function llmObject(prompt, schema, opts = {}) {
59485
59707
  });
59486
59708
  const validated = schema.safeParse(result.object);
59487
59709
  if (validated.success) {
59488
- logger.info("json_schema: fallback to json_object \u2014 validated", {});
59710
+ logger.debug("json_schema: fallback to json_object \u2014 validated", { label: opts.label, model: llm.model });
59711
+ recordLlmSuccess(opts.label, llm.model);
59489
59712
  return { ok: true, value: validated.data };
59490
59713
  }
59491
59714
  if (llm.disableThink) {
@@ -59498,15 +59721,17 @@ async function llmObject(prompt, schema, opts = {}) {
59498
59721
  logger.warn("llmObject: recovered object from reasoning channel (fallback path)", {
59499
59722
  reasoningLen: reasoning.length
59500
59723
  });
59724
+ recordLlmSuccess(opts.label, llm.model);
59501
59725
  return { ok: true, value: recovered.data };
59502
59726
  }
59503
59727
  }
59504
59728
  }
59505
59729
  }
59506
- logger.warn("llmObject: fallback validation failed", {
59507
- zodError: validated.error.issues.map((i) => i.message).join("; ")
59730
+ const validationErr = new Error("schema validation failed (fallback path)", {
59731
+ cause: summarizeZodIssues(validated.error)
59508
59732
  });
59509
- return { ok: false, error: "schema validation failed (fallback path)" };
59733
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, validationErr);
59734
+ return { ok: false, error: validationErr.message };
59510
59735
  } catch (e) {
59511
59736
  if (llm.disableThink && !_isAbortOrTimeoutError(e)) {
59512
59737
  const reasoning = _reasoningToText(result).length > 0 ? _reasoningToText(result) : _reasoningToText(e);
@@ -59518,6 +59743,7 @@ async function llmObject(prompt, schema, opts = {}) {
59518
59743
  logger.warn("llmObject: recovered object from reasoning channel", {
59519
59744
  reasoningLen: reasoning.length
59520
59745
  });
59746
+ recordLlmSuccess(opts.label, llm.model);
59521
59747
  return { ok: true, value: validated.data };
59522
59748
  }
59523
59749
  }
@@ -59527,19 +59753,18 @@ async function llmObject(prompt, schema, opts = {}) {
59527
59753
  finishReason: e?.finishReason ?? null
59528
59754
  });
59529
59755
  }
59530
- logger.warn("llmObject failed \u2014 degrading to non-LLM path", {
59531
- error: e.message
59532
- });
59756
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, e);
59533
59757
  return { ok: false, error: e.message };
59534
59758
  }
59535
59759
  }
59536
- var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llm;
59760
+ var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llmFailureStreaks, llm;
59537
59761
  var init_llm_client = __esm(() => {
59538
59762
  init_dist6();
59539
59763
  init_dist7();
59540
59764
  init_dist();
59541
59765
  init_config();
59542
59766
  init_inference_providers();
59767
+ llmFailureStreaks = new Map;
59543
59768
  llm = {
59544
59769
  complete: llmComplete,
59545
59770
  object: llmObject,
@@ -68552,7 +68777,7 @@ class MetricsCollector2 {
68552
68777
  try {
68553
68778
  writeFileSync(this.metricsPath, JSON.stringify(this.currentMetrics, null, 2));
68554
68779
  } catch (error51) {
68555
- logger.error("[Metrics] Failed to save:", error51);
68780
+ logger.error("Metrics: failed to save", error51, { path: this.metricsPath });
68556
68781
  }
68557
68782
  }
68558
68783
  reset() {
@@ -68727,7 +68952,8 @@ class EmbeddingRateLimiter {
68727
68952
  }
68728
68953
  }
68729
68954
  if (this.config.requestsPerDay && this.dailyRequestsWindow.length >= this.config.requestsPerDay) {
68730
- logger.warn(`[${this.providerId}] RPD limit reached, waiting 60s`, {
68955
+ logger.warn("EmbeddingRateLimiter: RPD limit reached, waiting 60s", {
68956
+ providerId: this.providerId,
68731
68957
  rpd: this.config.requestsPerDay,
68732
68958
  current: this.dailyRequestsWindow.length
68733
68959
  });
@@ -71373,26 +71599,26 @@ var require_process = __commonJS((exports, module) => {
71373
71599
 
71374
71600
  // ../../node_modules/detect-libc/lib/filesystem.js
71375
71601
  var require_filesystem = __commonJS((exports, module) => {
71376
- var fs14 = __require("fs");
71602
+ var fs15 = __require("fs");
71377
71603
  var LDD_PATH = "/usr/bin/ldd";
71378
71604
  var SELF_PATH = "/proc/self/exe";
71379
71605
  var MAX_LENGTH = 2048;
71380
- var readFileSync2 = (path19) => {
71381
- const fd = fs14.openSync(path19, "r");
71606
+ var readFileSync2 = (path20) => {
71607
+ const fd = fs15.openSync(path20, "r");
71382
71608
  const buffer = Buffer.alloc(MAX_LENGTH);
71383
- const bytesRead = fs14.readSync(fd, buffer, 0, MAX_LENGTH, 0);
71384
- fs14.close(fd, () => {});
71609
+ const bytesRead = fs15.readSync(fd, buffer, 0, MAX_LENGTH, 0);
71610
+ fs15.close(fd, () => {});
71385
71611
  return buffer.subarray(0, bytesRead);
71386
71612
  };
71387
- var readFile = (path19) => new Promise((resolve4, reject) => {
71388
- fs14.open(path19, "r", (err, fd) => {
71613
+ var readFile = (path20) => new Promise((resolve4, reject) => {
71614
+ fs15.open(path20, "r", (err, fd) => {
71389
71615
  if (err) {
71390
71616
  reject(err);
71391
71617
  } else {
71392
71618
  const buffer = Buffer.alloc(MAX_LENGTH);
71393
- fs14.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
71619
+ fs15.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
71394
71620
  resolve4(buffer.subarray(0, bytesRead));
71395
- fs14.close(fd, () => {});
71621
+ fs15.close(fd, () => {});
71396
71622
  });
71397
71623
  }
71398
71624
  });
@@ -71497,11 +71723,11 @@ var require_detect_libc = __commonJS((exports, module) => {
71497
71723
  }
71498
71724
  return null;
71499
71725
  };
71500
- var familyFromInterpreterPath = (path19) => {
71501
- if (path19) {
71502
- if (path19.includes("/ld-musl-")) {
71726
+ var familyFromInterpreterPath = (path20) => {
71727
+ if (path20) {
71728
+ if (path20.includes("/ld-musl-")) {
71503
71729
  return MUSL;
71504
- } else if (path19.includes("/ld-linux-")) {
71730
+ } else if (path20.includes("/ld-linux-")) {
71505
71731
  return GLIBC;
71506
71732
  }
71507
71733
  }
@@ -71546,8 +71772,8 @@ var require_detect_libc = __commonJS((exports, module) => {
71546
71772
  cachedFamilyInterpreter = null;
71547
71773
  try {
71548
71774
  const selfContent = await readFile(SELF_PATH);
71549
- const path19 = interpreterPath(selfContent);
71550
- cachedFamilyInterpreter = familyFromInterpreterPath(path19);
71775
+ const path20 = interpreterPath(selfContent);
71776
+ cachedFamilyInterpreter = familyFromInterpreterPath(path20);
71551
71777
  } catch (e) {}
71552
71778
  return cachedFamilyInterpreter;
71553
71779
  };
@@ -71558,8 +71784,8 @@ var require_detect_libc = __commonJS((exports, module) => {
71558
71784
  cachedFamilyInterpreter = null;
71559
71785
  try {
71560
71786
  const selfContent = readFileSync2(SELF_PATH);
71561
- const path19 = interpreterPath(selfContent);
71562
- cachedFamilyInterpreter = familyFromInterpreterPath(path19);
71787
+ const path20 = interpreterPath(selfContent);
71788
+ cachedFamilyInterpreter = familyFromInterpreterPath(path20);
71563
71789
  } catch (e) {}
71564
71790
  return cachedFamilyInterpreter;
71565
71791
  };
@@ -73221,18 +73447,18 @@ var require_sharp = __commonJS((exports, module) => {
73221
73447
  `@img/sharp-${runtimePlatform}/sharp.node`,
73222
73448
  "@img/sharp-wasm32/sharp.node"
73223
73449
  ];
73224
- var path19;
73450
+ var path20;
73225
73451
  var sharp;
73226
73452
  var errors4 = [];
73227
- for (path19 of paths) {
73453
+ for (path20 of paths) {
73228
73454
  try {
73229
- sharp = __require(path19);
73455
+ sharp = __require(path20);
73230
73456
  break;
73231
73457
  } catch (err) {
73232
73458
  errors4.push(err);
73233
73459
  }
73234
73460
  }
73235
- if (sharp && path19.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
73461
+ if (sharp && path20.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
73236
73462
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
73237
73463
  err.code = "Unsupported CPU";
73238
73464
  errors4.push(err);
@@ -76094,15 +76320,15 @@ var require_color = __commonJS((exports, module) => {
76094
76320
  };
76095
76321
  }
76096
76322
  function wrapConversion(toModel, graph) {
76097
- const path19 = [graph[toModel].parent, toModel];
76323
+ const path20 = [graph[toModel].parent, toModel];
76098
76324
  let fn = conversions_default[graph[toModel].parent][toModel];
76099
76325
  let cur = graph[toModel].parent;
76100
76326
  while (graph[cur].parent) {
76101
- path19.unshift(graph[cur].parent);
76327
+ path20.unshift(graph[cur].parent);
76102
76328
  fn = link(conversions_default[graph[cur].parent][cur], fn);
76103
76329
  cur = graph[cur].parent;
76104
76330
  }
76105
- fn.conversion = path19;
76331
+ fn.conversion = path20;
76106
76332
  return fn;
76107
76333
  }
76108
76334
  function route(fromModel) {
@@ -76707,7 +76933,7 @@ var require_output = __commonJS((exports, module) => {
76707
76933
  Copyright 2013 Lovell Fuller and others.
76708
76934
  SPDX-License-Identifier: Apache-2.0
76709
76935
  */
76710
- var path19 = __require("path");
76936
+ var path20 = __require("path");
76711
76937
  var is = require_is();
76712
76938
  var sharp = require_sharp();
76713
76939
  var formats = new Map([
@@ -76738,9 +76964,9 @@ var require_output = __commonJS((exports, module) => {
76738
76964
  let err;
76739
76965
  if (!is.string(fileOut)) {
76740
76966
  err = new Error("Missing output file path");
76741
- } else if (is.string(this.options.input.file) && path19.resolve(this.options.input.file) === path19.resolve(fileOut)) {
76967
+ } else if (is.string(this.options.input.file) && path20.resolve(this.options.input.file) === path20.resolve(fileOut)) {
76742
76968
  err = new Error("Cannot use same file for input and output");
76743
- } else if (jp2Regex.test(path19.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
76969
+ } else if (jp2Regex.test(path20.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
76744
76970
  err = errJp2Save();
76745
76971
  }
76746
76972
  if (err) {
@@ -83987,11 +84213,11 @@ var init_transformers_node = __esm(() => {
83987
84213
  throw new Error(`The number of external data chunks (${num_chunks}) exceeds the maximum allowed value (${_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS}).`);
83988
84214
  }
83989
84215
  for (let i = 0;i < num_chunks; ++i) {
83990
- const path19 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
83991
- const fullPath = `${options.subfolder ?? ""}/${path19}`;
84216
+ const path20 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
84217
+ const fullPath = `${options.subfolder ?? ""}/${path20}`;
83992
84218
  externalDataPromises.push(new Promise(async (resolve4, reject) => {
83993
84219
  const data = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path);
83994
- resolve4(data instanceof Uint8Array ? { path: path19, data } : path19);
84220
+ resolve4(data instanceof Uint8Array ? { path: path20, data } : path20);
83995
84221
  }));
83996
84222
  }
83997
84223
  } else if (session_options.externalData !== undefined) {
@@ -97055,7 +97281,7 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
97055
97281
  const blob = new Blob([wav], { type: "audio/wav" });
97056
97282
  return blob;
97057
97283
  }
97058
- async save(path19) {
97284
+ async save(path20) {
97059
97285
  let fn;
97060
97286
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) {
97061
97287
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) {
@@ -97063,14 +97289,14 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
97063
97289
  }
97064
97290
  fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob;
97065
97291
  } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) {
97066
- fn = async (path20, blob) => {
97292
+ fn = async (path21, blob) => {
97067
97293
  let buffer = await blob.arrayBuffer();
97068
- node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path20, Buffer.from(buffer));
97294
+ node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path21, Buffer.from(buffer));
97069
97295
  };
97070
97296
  } else {
97071
97297
  throw new Error("Unable to save because filesystem is disabled in this environment.");
97072
97298
  }
97073
- await fn(path19, this.toBlob());
97299
+ await fn(path20, this.toBlob());
97074
97300
  }
97075
97301
  }
97076
97302
  },
@@ -97166,11 +97392,11 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
97166
97392
  function calculateReflectOffset(i, w) {
97167
97393
  return Math.abs((i + w) % (2 * w) - w);
97168
97394
  }
97169
- function saveBlob(path19, blob) {
97395
+ function saveBlob(path20, blob) {
97170
97396
  const dataURL = URL.createObjectURL(blob);
97171
97397
  const downloadLink = document.createElement("a");
97172
97398
  downloadLink.href = dataURL;
97173
- downloadLink.download = path19;
97399
+ downloadLink.download = path20;
97174
97400
  downloadLink.click();
97175
97401
  downloadLink.remove();
97176
97402
  URL.revokeObjectURL(dataURL);
@@ -97771,8 +97997,8 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
97771
97997
  }
97772
97998
 
97773
97999
  class FileCache {
97774
- constructor(path19) {
97775
- this.path = path19;
98000
+ constructor(path20) {
98001
+ this.path = path20;
97776
98002
  }
97777
98003
  async match(request) {
97778
98004
  let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].join(this.path, request);
@@ -98528,20 +98754,20 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
98528
98754
  }
98529
98755
  return this;
98530
98756
  }
98531
- async save(path19) {
98757
+ async save(path20) {
98532
98758
  if (IS_BROWSER_OR_WEBWORKER) {
98533
98759
  if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) {
98534
98760
  throw new Error("Unable to save an image from a Web Worker.");
98535
98761
  }
98536
- const extension = path19.split(".").pop().toLowerCase();
98762
+ const extension = path20.split(".").pop().toLowerCase();
98537
98763
  const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
98538
98764
  const blob = await this.toBlob(mime);
98539
- (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path19, blob);
98765
+ (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path20, blob);
98540
98766
  } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) {
98541
98767
  throw new Error("Unable to save the image because filesystem is disabled in this environment.");
98542
98768
  } else {
98543
98769
  const img = this.toSharp();
98544
- return await img.toFile(path19);
98770
+ return await img.toFile(path20);
98545
98771
  }
98546
98772
  }
98547
98773
  toSharp() {
@@ -102030,16 +102256,16 @@ class LocalTransformersEmbeddingProvider {
102030
102256
  const out = await extractor("test", { pooling: "mean", normalize: true });
102031
102257
  const vec = Array.from(out.data);
102032
102258
  if (!Array.isArray(vec) || vec.length !== this.dimensions) {
102033
- logger.error(`[${this.id}] Invalid embedding dimensions`, undefined, { expected: this.dimensions, got: vec.length });
102259
+ logger.error("LocalTransformersProvider: invalid embedding dimensions", undefined, { providerId: this.id, expected: this.dimensions, got: vec.length });
102034
102260
  return false;
102035
102261
  }
102036
102262
  if (vec.some((v) => typeof v !== "number" || isNaN(v))) {
102037
- logger.error(`[${this.id}] Invalid embedding values (not numbers)`);
102263
+ logger.error("LocalTransformersProvider: invalid embedding values (not numbers)", undefined, { providerId: this.id });
102038
102264
  return false;
102039
102265
  }
102040
102266
  return true;
102041
102267
  } catch (error51) {
102042
- logger.error(`[${this.id}] Local provider unavailable`, error51);
102268
+ logger.error("LocalTransformersProvider: provider unavailable", error51, { providerId: this.id });
102043
102269
  return false;
102044
102270
  }
102045
102271
  }
@@ -102079,7 +102305,13 @@ async function withRetry(fn, config3, context2) {
102079
102305
  lastError2 = error51;
102080
102306
  if (attempt < config3.maxRetries) {
102081
102307
  const delay2 = getRetryDelay(attempt, config3);
102082
- logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError2.message });
102308
+ logger.warn("EmbeddingProvider: operation failed, retrying", {
102309
+ context: context2,
102310
+ attempt: attempt + 1,
102311
+ maxAttempts: config3.maxRetries + 1,
102312
+ delayMs: delay2,
102313
+ error: lastError2
102314
+ });
102083
102315
  await sleep(delay2);
102084
102316
  }
102085
102317
  }
@@ -102395,7 +102627,7 @@ var init_provider = __esm(() => {
102395
102627
  return output;
102396
102628
  }, this.retryConfig, `[${this.id}] embedBatchDirect (${texts.length} texts)`), this.timeout, `[${this.id}] embedBatchDirect`);
102397
102629
  } catch (error51) {
102398
- logger.warn(`[${this.id}] Ollama batch endpoint unavailable, falling back to sequential embeds: ${error51.message}`);
102630
+ logger.warn("EmbeddingProvider: Ollama batch endpoint unavailable, falling back to sequential embeds", { providerId: this.id, textCount: texts.length, error: error51 });
102399
102631
  const embeddings = [];
102400
102632
  let consecutiveFailures = 0;
102401
102633
  for (const text2 of texts) {
@@ -102434,11 +102666,11 @@ var init_provider = __esm(() => {
102434
102666
  });
102435
102667
  clearTimeout(timeoutId);
102436
102668
  if (!response.ok) {
102437
- logger.error(`[${this.id}] Ollama API returned ${response.status}`);
102669
+ logger.error("EmbeddingProvider: Ollama API returned non-OK status", undefined, { providerId: this.id, status: response.status });
102438
102670
  return false;
102439
102671
  }
102440
102672
  } catch {
102441
- logger.error(`[${this.id}] Ollama service unreachable`, undefined, { baseURL: this.baseURL, timeoutMs: 2000 });
102673
+ logger.error("EmbeddingProvider: Ollama service unreachable", undefined, { providerId: this.id, baseURL: this.baseURL, timeoutMs: 2000 });
102442
102674
  return false;
102443
102675
  }
102444
102676
  }
@@ -102448,16 +102680,16 @@ var init_provider = __esm(() => {
102448
102680
  if (Array.isArray(embedding)) {
102449
102681
  this.lastDimensionMismatch = new DimensionMismatchError(this.id, this.dimensions, embedding.length);
102450
102682
  }
102451
- logger.error(`[${this.id}] Invalid embedding dimensions`, undefined, { expected: this.dimensions, got: embedding.length });
102683
+ logger.error("EmbeddingProvider: invalid embedding dimensions", undefined, { providerId: this.id, expected: this.dimensions, got: embedding.length });
102452
102684
  return false;
102453
102685
  }
102454
102686
  if (!embedding.every((v) => typeof v === "number" && !isNaN(v))) {
102455
- logger.error(`[${this.id}] Invalid embedding values (not numbers)`);
102687
+ logger.error("EmbeddingProvider: invalid embedding values (not numbers)", undefined, { providerId: this.id });
102456
102688
  return false;
102457
102689
  }
102458
102690
  return true;
102459
102691
  } catch (error51) {
102460
- logger.error(`[${this.id}] Provider unavailable`, error51);
102692
+ logger.error("EmbeddingProvider: provider unavailable", error51, { providerId: this.id });
102461
102693
  return false;
102462
102694
  }
102463
102695
  }
@@ -108075,10 +108307,10 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a;
108075
108307
  super(t, "P2023", r);
108076
108308
  }
108077
108309
  };
108078
- var fs14 = new WeakMap;
108310
+ var fs15 = new WeakMap;
108079
108311
  function Ep(e) {
108080
- let t = fs14.get(e);
108081
- return t || (t = Object.entries(e), fs14.set(e, t)), t;
108312
+ let t = fs15.get(e);
108313
+ return t || (t = Object.entries(e), fs15.set(e, t)), t;
108082
108314
  }
108083
108315
  function hs(e, t, r) {
108084
108316
  switch (t.type) {
@@ -112046,7 +112278,7 @@ var require_prisma = __commonJS((exports) => {
112046
112278
  Prisma.JsonNull = JsonNull2;
112047
112279
  Prisma.AnyNull = AnyNull2;
112048
112280
  Prisma.NullTypes = NullTypes2;
112049
- var path19 = __require("path");
112281
+ var path20 = __require("path");
112050
112282
  exports.Prisma.TransactionIsolationLevel = makeStrictEnum2({
112051
112283
  ReadUncommitted: "ReadUncommitted",
112052
112284
  ReadCommitted: "ReadCommitted",
@@ -114673,7 +114905,7 @@ function getPrismaClient2() {
114673
114905
  const pg2 = _adapters.loadPg();
114674
114906
  const { PrismaPg: PrismaPg2 } = _adapters.loadPrismaPg();
114675
114907
  const pool = new pg2.Pool({ connectionString: databaseUrl, max: 10, idleTimeoutMillis: 30000, connectionTimeoutMillis: 5000 });
114676
- pool.on("error", (error51) => logger.error("Unexpected PG pool error", error51));
114908
+ pool.on("error", (error51) => logger.error("prisma-client: unexpected PG pool error", error51, { poolMax: 10 }));
114677
114909
  prismaPool = pool;
114678
114910
  prismaInstance = new import_prisma.PrismaClient({ adapter: new PrismaPg2(pool) });
114679
114911
  logger.info("Prisma Client initialized with PostgreSQL");
@@ -114982,7 +115214,10 @@ var init_config2 = __esm(() => {
114982
115214
  "local"
114983
115215
  ]);
114984
115216
  if (!SELECTABLE_PROVIDERS.has(selectedProvider)) {
114985
- logger.warn(`[EmbeddingConfig] selected provider "${selectedProvider}" has no runtime entry \u2014 falling back to priority order`, { source: process.env.EMBEDDING_PROVIDER ? "EMBEDDING_PROVIDER env" : "config.json embedding.provider" });
115217
+ logger.warn("EmbeddingConfig: selected provider has no runtime entry, falling back to priority order", {
115218
+ selectedProvider,
115219
+ source: process.env.EMBEDDING_PROVIDER ? "EMBEDDING_PROVIDER env" : "config.json embedding.provider"
115220
+ });
114986
115221
  }
114987
115222
  embeddingProviders = {
114988
115223
  google: (() => {
@@ -115022,7 +115257,12 @@ var init_config2 = __esm(() => {
115022
115257
  const envDimensions = Number.isInteger(rawEnvDimensions) && rawEnvDimensions > 0 ? rawEnvDimensions : undefined;
115023
115258
  const resolvedDimensions = resolveEmbeddingDimensions(model, file2?.dimensions, envDimensions);
115024
115259
  if (resolvedDimensions.correctedFrom !== undefined) {
115025
- logger.warn(`[ollama] config.json records embedding.dimensions ${resolvedDimensions.correctedFrom} for model ` + `"${model}", which emits ${resolvedDimensions.dimensions}. Using ${resolvedDimensions.dimensions}. ` + "Update embedding.dimensions in config.json (or set OLLAMA_EMBEDDING_DIMENSIONS) to silence this.");
115260
+ logger.warn("EmbeddingConfig: ollama config.json dimensions mismatch corrected", {
115261
+ provider: "ollama",
115262
+ model,
115263
+ configuredDimensions: resolvedDimensions.correctedFrom,
115264
+ correctedDimensions: resolvedDimensions.dimensions
115265
+ });
115026
115266
  }
115027
115267
  return {
115028
115268
  provider: "ollama",
@@ -115174,8 +115414,8 @@ class EmbeddingService {
115174
115414
  dimensions: this.provider.dimensions
115175
115415
  });
115176
115416
  } catch (error51) {
115177
- logger.error("Failed to initialize embedding service", error51);
115178
- logger.warn("Embedding service will use fallback mode");
115417
+ logger.error("Failed to initialize embedding service", error51, { stage: "initialize" });
115418
+ logger.warn("Embedding service will use fallback mode", { stage: "initialize" });
115179
115419
  }
115180
115420
  }
115181
115421
  async ensureInitialized() {
@@ -115257,7 +115497,7 @@ async function tryCreateProvider(config3, providerId, skipHealthCheck) {
115257
115497
  return { provider };
115258
115498
  }
115259
115499
  function refuseOnDimensionMismatch(providerId, mismatch) {
115260
- logger.error(`[${providerId}] Configured embedding provider failed with a dimension mismatch \u2014 refusing to ` + `fall through to another provider (that would silently degrade retrieval quality). ` + `configured dimensions ${mismatch.expected} \u2260 model output ${mismatch.got} \u2014 fix ` + "`embedding.dimensions` in config.json or OLLAMA_EMBEDDING_DIMENSIONS to match the model actually pulled.");
115500
+ logger.error("EmbeddingProvider: configured provider failed with a dimension mismatch, refusing to fall through", mismatch, { providerId, configuredDimensions: mismatch.expected, modelDimensions: mismatch.got });
115261
115501
  throw mismatch;
115262
115502
  }
115263
115503
  async function createEmbeddingProvider(options = {}) {
@@ -115356,6 +115596,7 @@ Write the hypothetical implementation paragraph.`;
115356
115596
  }
115357
115597
  async function rewriteQuery(query, surface, opts = {}) {
115358
115598
  const res = await surface.object(rewritePrompt(query), QueryRewriteSchema, {
115599
+ label: "query-rewrite",
115359
115600
  system: REWRITE_SYSTEM,
115360
115601
  timeoutMs: opts.timeoutMs
115361
115602
  });
@@ -115368,6 +115609,7 @@ async function rewriteQuery(query, surface, opts = {}) {
115368
115609
  }
115369
115610
  async function hyde(query, surface, embedFn, opts = {}) {
115370
115611
  const text2 = await surface.complete(hydePrompt(query), {
115612
+ label: "hyde",
115371
115613
  system: HYDE_SYSTEM,
115372
115614
  timeoutMs: opts.timeoutMs
115373
115615
  });
@@ -115381,7 +115623,7 @@ async function hyde(query, surface, embedFn, opts = {}) {
115381
115623
  return vec;
115382
115624
  } catch (e) {
115383
115625
  logger.warn("hyde embed failed \u2014 skipping HyDE stream", {
115384
- error: e.message
115626
+ error: e
115385
115627
  });
115386
115628
  return null;
115387
115629
  }
@@ -117109,7 +117351,7 @@ class KeywordSearchPg {
117109
117351
  `);
117110
117352
  this.trigramAvailable = true;
117111
117353
  } catch (error51) {
117112
- logger.warn("pg_trgm unavailable \u2014 trigram RRF stream disabled on PG", { err: error51.message });
117354
+ logger.warn("pg_trgm unavailable \u2014 trigram RRF stream disabled on PG", { error: error51 });
117113
117355
  this.trigramAvailable = false;
117114
117356
  }
117115
117357
  logger.info("PostgreSQL keyword search initialized", {
@@ -117648,7 +117890,8 @@ var init_postgres_vector_store = __esm(() => {
117648
117890
  this.schemaDimensions = providerDimensions;
117649
117891
  const { rows } = await client.query(`SELECT tablename FROM pg_tables WHERE tablename = $1`, [this.tableName]);
117650
117892
  if (rows.length === 0) {
117651
- logger.warn(`Table ${this.tableName} not found. Creating fallback table.`, {
117893
+ logger.warn("PostgresVectorStore: table not found, creating fallback table", {
117894
+ tableName: this.tableName,
117652
117895
  note: 'Run "prisma migrate deploy" to create tables via migrations'
117653
117896
  });
117654
117897
  await this.createFallbackTable(client, providerDimensions);
@@ -117685,10 +117928,12 @@ var init_postgres_vector_store = __esm(() => {
117685
117928
  if (projects.length === 0)
117686
117929
  continue;
117687
117930
  const otherDim = tablename.match(/_([0-9]+)d$/)?.[1];
117688
- logger.warn(`[vector] Orphaned chunks detected: ${tablename} has data for projects not in ${this.tableName}. Embedding model likely changed from ${otherDim}d \u2192 ${currentDim}d. Reindex required.`, {
117931
+ logger.warn("PostgresVectorStore: orphaned chunks detected, embedding model likely changed, reindex required", {
117689
117932
  currentTable: this.tableName,
117690
117933
  currentCount,
117934
+ currentDim,
117691
117935
  orphanedTable: tablename,
117936
+ orphanedDim: otherDim,
117692
117937
  affectedProjects: projects.map((p) => ({ projectId: p.project_id, chunks: p.n }))
117693
117938
  });
117694
117939
  }
@@ -117832,7 +118077,7 @@ var init_postgres_vector_store = __esm(() => {
117832
118077
  logger.warn("[postgres] Sub-batch embedding failed, falling back per-document", {
117833
118078
  subBatchIndex: Math.floor(i / EMBED_SUB_BATCH_SIZE),
117834
118079
  count: subBatch.length,
117835
- error: error51.message
118080
+ error: error51
117836
118081
  });
117837
118082
  }
117838
118083
  if (embeddings) {
@@ -117844,7 +118089,7 @@ var init_postgres_vector_store = __esm(() => {
117844
118089
  logger.warn("[postgres] Sub-batch insert failed, falling back per-document", {
117845
118090
  subBatchIndex: Math.floor(i / EMBED_SUB_BATCH_SIZE),
117846
118091
  count: subBatch.length,
117847
- error: error51.message
118092
+ error: error51
117848
118093
  });
117849
118094
  }
117850
118095
  }
@@ -117857,7 +118102,7 @@ var init_postgres_vector_store = __esm(() => {
117857
118102
  totalFailed++;
117858
118103
  logger.warn("[postgres] Skipping document due to embedding/insert error", {
117859
118104
  id: doc2.id,
117860
- error: singleError.message
118105
+ error: singleError
117861
118106
  });
117862
118107
  }
117863
118108
  }
@@ -118529,7 +118774,9 @@ class SearchAnalyticsPg {
118529
118774
  }
118530
118775
  trackSearch(event) {
118531
118776
  this.trackSearchAsync(event).catch((err) => {
118532
- logger.error("Failed to track search event", err);
118777
+ logger.error("Failed to track search event", err, {
118778
+ projectId: event.projectId
118779
+ });
118533
118780
  });
118534
118781
  }
118535
118782
  async trackSearchAsync(event) {
@@ -118554,7 +118801,9 @@ class SearchAnalyticsPg {
118554
118801
  event.score || null
118555
118802
  ]);
118556
118803
  } catch (error51) {
118557
- logger.error("Failed to track search event in PostgreSQL", error51);
118804
+ logger.error("Failed to track search event in PostgreSQL", error51, {
118805
+ projectId: event.projectId
118806
+ });
118558
118807
  }
118559
118808
  }
118560
118809
  async recordQuery(query, projectId, resultsCount = 0, duration3 = 0, cacheHit = false) {
@@ -121155,7 +121404,11 @@ class GraphStorePg {
121155
121404
  `;
121156
121405
  return rows[0] ? rowToEdge(rows[0]) : null;
121157
121406
  } catch (error51) {
121158
- logger.error("Failed to create edge", error51);
121407
+ logger.error("Failed to create edge", error51, {
121408
+ sourceId: edge.sourceId,
121409
+ targetId: edge.targetId,
121410
+ relationType: edge.relationType
121411
+ });
121159
121412
  return null;
121160
121413
  }
121161
121414
  }
@@ -121751,7 +122004,7 @@ class PgSynapseSessionStore {
121751
122004
  } catch (e) {
121752
122005
  this.hydrateFailedAt = Date.now();
121753
122006
  logger.warn("PgSynapseSessionStore hydrate failed (best-effort)", {
121754
- error: e.message
122007
+ error: e
121755
122008
  });
121756
122009
  } finally {
121757
122010
  this.hydrating = null;
@@ -121886,7 +122139,7 @@ class PgSynapseSessionStore {
121886
122139
  const next = prev.then(fn).catch((e) => {
121887
122140
  logger.warn("PgSynapseSessionStore write failed (best-effort)", {
121888
122141
  key,
121889
- error: e.message
122142
+ error: e
121890
122143
  });
121891
122144
  });
121892
122145
  this.inflight.set(key, next);
@@ -121992,7 +122245,7 @@ class SessionRegistry {
121992
122245
  try {
121993
122246
  this.store?.save(session);
121994
122247
  } catch (error51) {
121995
- logger.warn("[SessionRegistry] store save failed:", { error: error51.message });
122248
+ logger.warn("SessionRegistry: store save failed", { sessionId: session.sessionId, error: error51 });
121996
122249
  }
121997
122250
  return session;
121998
122251
  }
@@ -122000,7 +122253,7 @@ class SessionRegistry {
122000
122253
  try {
122001
122254
  await this.store?.ensureReady();
122002
122255
  } catch (error51) {
122003
- logger.warn("[SessionRegistry] store ensureReady failed:", { error: error51.message });
122256
+ logger.warn("SessionRegistry: store ensureReady failed", { error: error51 });
122004
122257
  }
122005
122258
  }
122006
122259
  async getAsync(sessionId, now2 = Date.now()) {
@@ -122021,7 +122274,7 @@ class SessionRegistry {
122021
122274
  session = loaded;
122022
122275
  }
122023
122276
  } catch (error51) {
122024
- logger.warn("[SessionRegistry] store load failed:", { error: error51.message });
122277
+ logger.warn("SessionRegistry: store load failed", { sessionId, error: error51 });
122025
122278
  }
122026
122279
  }
122027
122280
  if (!session)
@@ -122031,7 +122284,7 @@ class SessionRegistry {
122031
122284
  try {
122032
122285
  this.store?.delete(sessionId);
122033
122286
  } catch (error51) {
122034
- logger.warn("[SessionRegistry] store delete (expired) failed:", { error: error51.message });
122287
+ logger.warn("SessionRegistry: store delete (expired) failed", { sessionId, error: error51 });
122035
122288
  }
122036
122289
  return null;
122037
122290
  }
@@ -122053,7 +122306,7 @@ class SessionRegistry {
122053
122306
  try {
122054
122307
  this.store?.save(session);
122055
122308
  } catch (error51) {
122056
- logger.warn("[SessionRegistry] store save (updateTaskContext) failed:", { error: error51.message });
122309
+ logger.warn("SessionRegistry: store save (updateTaskContext) failed", { sessionId, error: error51 });
122057
122310
  }
122058
122311
  return session;
122059
122312
  }
@@ -122080,7 +122333,7 @@ class SessionRegistry {
122080
122333
  try {
122081
122334
  this.store?.recordAccess(sessionId, memoryId, nextCount);
122082
122335
  } catch (error51) {
122083
- logger.warn("[SessionRegistry] store recordAccess failed:", { error: error51.message });
122336
+ logger.warn("SessionRegistry: store recordAccess failed", { sessionId, memoryId, error: error51 });
122084
122337
  }
122085
122338
  }
122086
122339
  delete(sessionId) {
@@ -122088,7 +122341,7 @@ class SessionRegistry {
122088
122341
  try {
122089
122342
  this.store?.delete(sessionId);
122090
122343
  } catch (error51) {
122091
- logger.warn("[SessionRegistry] store delete failed:", { error: error51.message });
122344
+ logger.warn("SessionRegistry: store delete failed", { sessionId, error: error51 });
122092
122345
  }
122093
122346
  return removed;
122094
122347
  }
@@ -122116,7 +122369,7 @@ function getSessionRegistry() {
122116
122369
  const { getSessionStore: getSessionStore2 } = (init_session_store(), __toCommonJS(exports_session_store));
122117
122370
  store2 = getSessionStore2();
122118
122371
  } catch (error51) {
122119
- logger.warn("[SessionRegistry] store init failed, falling back to MemorySessionStore:", { error: error51.message });
122372
+ logger.warn("SessionRegistry: store init failed, falling back to MemorySessionStore", { error: error51 });
122120
122373
  const { MemorySessionStore: MemorySessionStore2 } = (init_session_store(), __toCommonJS(exports_session_store));
122121
122374
  store2 = new MemorySessionStore2;
122122
122375
  }
@@ -122933,19 +123186,22 @@ class LLMJudgeReranker {
122933
123186
  const tail = results.slice(k);
122934
123187
  const prompt = buildPrompt(query, head);
122935
123188
  let verdict;
123189
+ let verdictError;
122936
123190
  try {
122937
- const res = await this.llm.object(prompt, RerankVerdictSchema, { modelRole: "code" });
123191
+ const res = await this.llm.object(prompt, RerankVerdictSchema, { label: "reranker", modelRole: "code" });
122938
123192
  verdict = res.ok ? res.value ?? null : null;
123193
+ verdictError = res.ok ? undefined : res.error;
122939
123194
  } catch (e) {
122940
123195
  logger.warn("LLMJudgeReranker threw \u2014 degrading to input order", {
122941
123196
  query,
122942
- error: e.message
123197
+ error: e
122943
123198
  });
122944
123199
  return results;
122945
123200
  }
122946
123201
  if (!verdict) {
122947
123202
  logger.warn("LLMJudgeReranker got {ok:false} \u2014 degrading to input order", {
122948
- query
123203
+ query,
123204
+ error: verdictError
122949
123205
  });
122950
123206
  return results;
122951
123207
  }
@@ -123744,10 +124000,10 @@ var init_chunker_code = __esm(() => {
123744
124000
  });
123745
124001
 
123746
124002
  // ../../packages/core/dist/services/search/smart-chunker.js
123747
- import path19 from "path";
124003
+ import path20 from "path";
123748
124004
  function smartChunk(content, filePath, config3 = {}) {
123749
124005
  const cfg = { ...DEFAULT_CONFIG, ...config3 };
123750
- const ext2 = path19.extname(filePath).toLowerCase();
124006
+ const ext2 = path20.extname(filePath).toLowerCase();
123751
124007
  const relativePath = filePath;
123752
124008
  const fileImports = isCodeFile(ext2) ? extractFileImports(content, ext2) : undefined;
123753
124009
  let chunks;
@@ -124085,8 +124341,8 @@ var init_embedding_freshness = __esm(() => {
124085
124341
  });
124086
124342
 
124087
124343
  // ../../packages/core/dist/services/search/project-indexer.js
124088
- import fs14 from "fs/promises";
124089
- import path20 from "path";
124344
+ import fs15 from "fs/promises";
124345
+ import path21 from "path";
124090
124346
  import { randomUUID as randomUUID3 } from "crypto";
124091
124347
  async function runWithIndexLock(lockMap, projectId, work) {
124092
124348
  const prevLock = lockMap.get(projectId);
@@ -124129,7 +124385,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
124129
124385
  dot: false
124130
124386
  });
124131
124387
  const filteredFiles = files.filter((file2) => {
124132
- const relativePath = path20.relative(projectPath, file2);
124388
+ const relativePath = path21.relative(projectPath, file2);
124133
124389
  const shouldIgnore = ig.ignores(relativePath);
124134
124390
  if (shouldIgnore) {
124135
124391
  logger.debug("Ignoring file per .gitignore during indexing", {
@@ -124169,7 +124425,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
124169
124425
  });
124170
124426
  }
124171
124427
  }
124172
- const indexedFilesList = filteredFiles.map((f) => path20.relative(projectPath, f));
124428
+ const indexedFilesList = filteredFiles.map((f) => path21.relative(projectPath, f));
124173
124429
  await deps.indexManager.updateIndexMetadata(projectId, projectPath, indexedFilesList);
124174
124430
  logger.info("Project indexing completed", {
124175
124431
  projectId,
@@ -124299,7 +124555,7 @@ async function ensureFreshIndex(deps, projectId, projectPath, options = {}) {
124299
124555
  let errors4 = 0;
124300
124556
  for (const relativeFilePath of filesToReindex) {
124301
124557
  try {
124302
- const fullPath = path20.join(projectPath, relativeFilePath);
124558
+ const fullPath = path21.join(projectPath, relativeFilePath);
124303
124559
  const result = await deps.indexFile(fullPath, projectId, projectPath, centralityMap);
124304
124560
  filesIndexed++;
124305
124561
  chunksIndexed += result.chunks;
@@ -124359,8 +124615,8 @@ async function checkSearchAdmission(deps, projectId, projectPath) {
124359
124615
  }
124360
124616
  async function indexFile(deps, filePath, projectId, projectRoot, centralityMap) {
124361
124617
  projectId = await getProjectIdentityAliasResolver().resolve(projectId);
124362
- const content = await fs14.readFile(filePath, "utf-8");
124363
- const relativePath = path20.relative(projectRoot, filePath);
124618
+ const content = await fs15.readFile(filePath, "utf-8");
124619
+ const relativePath = path21.relative(projectRoot, filePath);
124364
124620
  const maxFileSize = config2.get("security").maxFileSize || 1024 * 1024;
124365
124621
  if (content.length > maxFileSize) {
124366
124622
  logger.warn("File too large, skipping", {
@@ -124380,7 +124636,7 @@ async function indexFile(deps, filePath, projectId, projectRoot, centralityMap)
124380
124636
  chunkIndex: i,
124381
124637
  totalChunks: chunks.length,
124382
124638
  type: chunk.type,
124383
- language: path20.extname(filePath).slice(1),
124639
+ language: path21.extname(filePath).slice(1),
124384
124640
  lineStart: chunk.lineStart,
124385
124641
  lineEnd: chunk.lineEnd,
124386
124642
  label: chunk.label,
@@ -124791,7 +125047,7 @@ class TaskEnvelopeService {
124791
125047
  errors4.push("prime");
124792
125048
  logger.warn("synapse_task_begin: prime sub-step failed", {
124793
125049
  sessionId,
124794
- error: err instanceof Error ? err.message : String(err)
125050
+ error: err
124795
125051
  });
124796
125052
  }
124797
125053
  }
@@ -124814,7 +125070,7 @@ class TaskEnvelopeService {
124814
125070
  errors4.push("search");
124815
125071
  logger.warn("synapse_task_begin: search sub-step failed", {
124816
125072
  sessionId,
124817
- error: err instanceof Error ? err.message : String(err)
125073
+ error: err
124818
125074
  });
124819
125075
  }
124820
125076
  if (firstHitFile) {
@@ -124837,7 +125093,7 @@ class TaskEnvelopeService {
124837
125093
  errors4.push("prefetch");
124838
125094
  logger.warn("synapse_task_begin: prefetch sub-step failed", {
124839
125095
  sessionId,
124840
- error: err instanceof Error ? err.message : String(err)
125096
+ error: err
124841
125097
  });
124842
125098
  }
124843
125099
  }
@@ -124848,7 +125104,7 @@ class TaskEnvelopeService {
124848
125104
  errors4.push("access");
124849
125105
  logger.warn("synapse_task_begin: access sub-step failed", {
124850
125106
  sessionId,
124851
- error: err instanceof Error ? err.message : String(err)
125107
+ error: err
124852
125108
  });
124853
125109
  }
124854
125110
  }
@@ -125191,7 +125447,7 @@ async function applySynapseState(deps, baseResults, query, projectId, sessionId,
125191
125447
  logger.warn("Synapse session lookup failed \u2014 using stateless search", {
125192
125448
  sessionId,
125193
125449
  projectId,
125194
- error: error51.message
125450
+ error: error51
125195
125451
  });
125196
125452
  return baseResults;
125197
125453
  }
@@ -125212,7 +125468,7 @@ async function applySynapseState(deps, baseResults, query, projectId, sessionId,
125212
125468
  logger.warn("Synapse processing failed \u2014 using stateless search", {
125213
125469
  sessionId,
125214
125470
  projectId,
125215
- error: error51.message
125471
+ error: error51
125216
125472
  });
125217
125473
  return baseResults;
125218
125474
  }
@@ -125972,7 +126228,7 @@ class PgJobStore {
125972
126228
  } catch (e) {
125973
126229
  this.recovered = true;
125974
126230
  logger.warn("PgJobStore markStaleRunningFailed failed (best-effort)", {
125975
- error: e.message
126231
+ error: e
125976
126232
  });
125977
126233
  }
125978
126234
  }
@@ -125998,7 +126254,7 @@ class PgJobStore {
125998
126254
  logger.info("PgJobStore hydrated", { rows: this.mirror.size });
125999
126255
  } catch (e) {
126000
126256
  logger.warn("PgJobStore hydrate failed (best-effort)", {
126001
- error: e.message
126257
+ error: e
126002
126258
  });
126003
126259
  } finally {
126004
126260
  this.hydrating = null;
@@ -126021,7 +126277,7 @@ class PgJobStore {
126021
126277
  next.catch((e) => {
126022
126278
  logger.warn("PgJobStore.save failed (best-effort)", {
126023
126279
  jobId: job.jobId,
126024
- error: e.message
126280
+ error: e
126025
126281
  });
126026
126282
  });
126027
126283
  }
@@ -126153,7 +126409,7 @@ class PgJobStore {
126153
126409
  }
126154
126410
  } catch (e) {
126155
126411
  logger.warn("PgJobStore markStaleRunningFailed failed (best-effort)", {
126156
- error: e.message
126412
+ error: e
126157
126413
  });
126158
126414
  }
126159
126415
  })();
@@ -126343,7 +126599,13 @@ class IndexJobTracker {
126343
126599
  const stale = hbMs != null && hbMs < cutoff || hbMs == null && startedMs != null && startedMs < cutoff;
126344
126600
  if (!stale)
126345
126601
  continue;
126346
- logger.warn(`indexJobTracker: reaping stale running job ${job.jobId} (heartbeatAt=${job.heartbeatAt?.toISOString() ?? "n/a"}, startedAt=${job.startedAt?.toISOString() ?? "n/a"}, staleMs=${staleMs})`, { jobId: job.jobId, projectId: job.projectId, staleMs });
126602
+ logger.warn("indexJobTracker: reaping stale running job", {
126603
+ jobId: job.jobId,
126604
+ projectId: job.projectId,
126605
+ staleMs,
126606
+ heartbeatAt: job.heartbeatAt?.toISOString() ?? "n/a",
126607
+ startedAt: job.startedAt?.toISOString() ?? "n/a"
126608
+ });
126347
126609
  this.jobs.set(job.jobId, job);
126348
126610
  const reapedPrevStatus = job.status;
126349
126611
  this.setResult(job.jobId, undefined, "heartbeat stale (possible crash/OOM)");
@@ -126368,7 +126630,7 @@ class IndexJobTracker {
126368
126630
  try {
126369
126631
  this.store?.save(job);
126370
126632
  } catch (err) {
126371
- logger.warn(`indexJobTracker: job store write failed for ${jobId} on setResult`, { jobId, error: err?.message ?? String(err) });
126633
+ logger.warn("indexJobTracker: job store write failed on setResult", { jobId, error: err });
126372
126634
  }
126373
126635
  if (prevStatus === "pending") {
126374
126636
  this.publishStateChange(job, prevStatus);
@@ -126398,7 +126660,7 @@ class IndexJobTracker {
126398
126660
  const survivors = remaining.slice(0, this.MAX_JOBS);
126399
126661
  const overflow = remaining.slice(this.MAX_JOBS);
126400
126662
  for (const job of overflow) {
126401
- logger.warn(`indexJobTracker: evicting non-terminal job ${job.jobId} (status=${job.status}) to honor MAX_JOBS cap \u2014 caller may lose visibility`, { jobId: job.jobId, projectId: job.projectId, status: job.status });
126663
+ logger.warn("indexJobTracker: evicting non-terminal job to honor MAX_JOBS cap \u2014 caller may lose visibility", { jobId: job.jobId, projectId: job.projectId, status: job.status });
126402
126664
  this.jobs.delete(job.jobId);
126403
126665
  }
126404
126666
  }
@@ -126445,8 +126707,8 @@ function stripNul(content) {
126445
126707
  }
126446
126708
 
126447
126709
  // ../../packages/core/dist/services/etl/stages/discover.js
126448
- import fs15 from "fs/promises";
126449
- import path21 from "path";
126710
+ import fs16 from "fs/promises";
126711
+ import path22 from "path";
126450
126712
  import { createHash as createHash5 } from "crypto";
126451
126713
 
126452
126714
  class DiscoverStage {
@@ -126472,7 +126734,7 @@ class DiscoverStage {
126472
126734
  dot: false,
126473
126735
  absolute: false
126474
126736
  });
126475
- relPaths = found.map((p) => path21.isAbsolute(p) ? path21.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
126737
+ relPaths = found.map((p) => path22.isAbsolute(p) ? path22.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
126476
126738
  }
126477
126739
  if (ctx.resumeCursor?.path) {
126478
126740
  const cursorPath = ctx.resumeCursor.path;
@@ -126531,10 +126793,10 @@ class DiscoverStage {
126531
126793
  return discovered;
126532
126794
  }
126533
126795
  async processFile(ctx, relativePath, forceReindex) {
126534
- const absolutePath = path21.join(ctx.projectPath, relativePath);
126796
+ const absolutePath = path22.join(ctx.projectPath, relativePath);
126535
126797
  try {
126536
- const stat = await fs15.stat(absolutePath);
126537
- const content = stripNul(await fs15.readFile(absolutePath, "utf-8"));
126798
+ const stat = await fs16.stat(absolutePath);
126799
+ const content = stripNul(await fs16.readFile(absolutePath, "utf-8"));
126538
126800
  const contentHash = createHash5("sha256").update(content).digest("hex");
126539
126801
  let needsReparse = forceReindex;
126540
126802
  if (!forceReindex) {
@@ -126552,8 +126814,9 @@ class DiscoverStage {
126552
126814
  };
126553
126815
  } catch (err) {
126554
126816
  logger.warn("DiscoverStage: failed to stat/read file", {
126817
+ projectId: ctx.projectId,
126555
126818
  relativePath,
126556
- error: err.message
126819
+ error: err
126557
126820
  });
126558
126821
  throw new Error(`required_file_unreadable:${relativePath}:${err.message}`);
126559
126822
  }
@@ -126577,8 +126840,8 @@ class DiscoverStage {
126577
126840
  ig.add(pattern);
126578
126841
  }
126579
126842
  try {
126580
- const gitignorePath = path21.join(projectPath, ".gitignore");
126581
- const gitignoreContent = await fs15.readFile(gitignorePath, "utf8");
126843
+ const gitignorePath = path22.join(projectPath, ".gitignore");
126844
+ const gitignoreContent = await fs16.readFile(gitignorePath, "utf8");
126582
126845
  const rules = gitignoreContent.split(`
126583
126846
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
126584
126847
  ig.add(rules);
@@ -127933,8 +128196,8 @@ function rustUseLeaves(node, source, prefix = []) {
127933
128196
  }
127934
128197
  if (node.type === "use_wildcard")
127935
128198
  return [{ path: [...prefix, "*"], glob: true }];
127936
- const path22 = rustPathSegments(node, source);
127937
- return path22.length ? [{ path: [...prefix, ...path22] }] : [];
128199
+ const path23 = rustPathSegments(node, source);
128200
+ return path23.length ? [{ path: [...prefix, ...path23] }] : [];
127938
128201
  }
127939
128202
  function functionalCaptures(captures, source, family) {
127940
128203
  if (family !== "clojure")
@@ -128906,8 +129169,8 @@ var init_structural_runtime = __esm(() => {
128906
129169
  });
128907
129170
 
128908
129171
  // ../../packages/core/dist/services/etl/stages/parse.js
128909
- import path22 from "path";
128910
- import fs16 from "fs/promises";
129172
+ import path23 from "path";
129173
+ import fs17 from "fs/promises";
128911
129174
  function resolveChunkerMaxChars() {
128912
129175
  const global2 = Number(process.env.EMBEDDING_MAX_CHARS);
128913
129176
  if (Number.isFinite(global2) && global2 > 0)
@@ -128935,8 +129198,8 @@ class ParseStage {
128935
129198
  const results = new Map;
128936
129199
  let processed = 0;
128937
129200
  const phases = [
128938
- files.filter((file2) => path22.extname(file2.relativePath).toLowerCase() !== ".h"),
128939
- files.filter((file2) => path22.extname(file2.relativePath).toLowerCase() === ".h")
129201
+ files.filter((file2) => path23.extname(file2.relativePath).toLowerCase() !== ".h"),
129202
+ files.filter((file2) => path23.extname(file2.relativePath).toLowerCase() === ".h")
128940
129203
  ];
128941
129204
  const batches = phases.flatMap((phase) => Array.from({ length: Math.ceil(phase.length / BATCH_SIZE) }, (_, index) => phase.slice(index * BATCH_SIZE, (index + 1) * BATCH_SIZE)));
128942
129205
  for (const batch of batches) {
@@ -128974,19 +129237,19 @@ class ParseStage {
128974
129237
  return files.map((file2) => results.get(file2.relativePath));
128975
129238
  }
128976
129239
  recordHeaderImporterEvidence(ctx, files, parsedFiles) {
128977
- const knownHeaders = new Set(files.filter((file2) => path22.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path22.posix.normalize(file2.relativePath)));
129240
+ const knownHeaders = new Set(files.filter((file2) => path23.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path23.posix.normalize(file2.relativePath)));
128978
129241
  const mutable = {
128979
129242
  ...ctx.structuralHeaderEvidenceByFile
128980
129243
  };
128981
129244
  for (const parsed of parsedFiles) {
128982
- const extension = path22.extname(parsed.file.relativePath).toLowerCase();
129245
+ const extension = path23.extname(parsed.file.relativePath).toLowerCase();
128983
129246
  const key = extension === ".c" ? "cImporters" : [".cpp", ".hpp"].includes(extension) ? "cppImporters" : undefined;
128984
129247
  if (!key)
128985
129248
  continue;
128986
129249
  for (const imported of parsed.rawImports) {
128987
129250
  if (!["c_include", "cpp_include"].includes(imported.form) || imported.specifier.startsWith("<"))
128988
129251
  continue;
128989
- const header = path22.posix.normalize(path22.posix.join(path22.posix.dirname(parsed.file.relativePath), imported.specifier));
129252
+ const header = path23.posix.normalize(path23.posix.join(path23.posix.dirname(parsed.file.relativePath), imported.specifier));
128990
129253
  if (!knownHeaders.has(header))
128991
129254
  continue;
128992
129255
  const existing = mutable[header] ?? {};
@@ -128997,9 +129260,9 @@ class ParseStage {
128997
129260
  }
128998
129261
  async parseFile(ctx, file2) {
128999
129262
  if (!file2.needsReparse) {
129000
- const extension = path22.extname(file2.relativePath).toLowerCase();
129263
+ const extension = path23.extname(file2.relativePath).toLowerCase();
129001
129264
  if ([".c", ".cpp", ".hpp"].includes(extension)) {
129002
- const content = file2.snapshotContent ?? await fs16.readFile(file2.absolutePath, "utf8");
129265
+ const content = file2.snapshotContent ?? await fs17.readFile(file2.absolutePath, "utf8");
129003
129266
  const outcome = await this.runtime.parse({ extension, source: Buffer.from(content) });
129004
129267
  if (outcome.status === "failed")
129005
129268
  throw new StructuralEtlParseError(file2.relativePath, outcome.failureKind, `Structural evidence parse failed (${outcome.failureKind})`, outcome.diagnosticCount, outcome.diagnostics.slice(0, 10));
@@ -129011,8 +129274,8 @@ class ParseStage {
129011
129274
  return { file: file2, chunks: [], symbols: [], rawImports: [], rawEdges: [] };
129012
129275
  }
129013
129276
  try {
129014
- const content = file2.snapshotContent ?? await fs16.readFile(file2.absolutePath, "utf-8");
129015
- const ext2 = path22.extname(file2.relativePath).toLowerCase();
129277
+ const content = file2.snapshotContent ?? await fs17.readFile(file2.absolutePath, "utf-8");
129278
+ const ext2 = path23.extname(file2.relativePath).toLowerCase();
129016
129279
  const chunkerMaxChars = resolveChunkerMaxChars();
129017
129280
  const chunks = smartChunk(content, file2.relativePath, chunkerMaxChars ? { maxChunkChars: chunkerMaxChars } : {});
129018
129281
  let symbols;
@@ -129078,8 +129341,9 @@ class ParseStage {
129078
129341
  timestamp: Date.now()
129079
129342
  });
129080
129343
  logger.warn("ParseStage: failed to parse file", {
129344
+ projectId: ctx.projectId,
129081
129345
  filePath: file2.relativePath,
129082
- error: err.message
129346
+ error: err
129083
129347
  });
129084
129348
  if (err instanceof StructuralEtlParseError)
129085
129349
  throw err;
@@ -129566,7 +129830,7 @@ var init_resolver = __esm(() => {
129566
129830
  });
129567
129831
 
129568
129832
  // ../../packages/core/dist/services/structural/resolvers/typescript.js
129569
- import path23 from "path";
129833
+ import path24 from "path";
129570
129834
  function candidates(identities) {
129571
129835
  return Object.freeze(identities.map((identity) => Object.freeze({
129572
129836
  fqn: identity.fqn,
@@ -129661,7 +129925,7 @@ function probe(base, known, dialect = "typescript") {
129661
129925
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
129662
129926
  for (const candidateBase of bases)
129663
129927
  for (const suffix of DIALECT_PROBES[dialect] ?? [""]) {
129664
- const value = path23.posix.normalize(`${candidateBase}${suffix}`);
129928
+ const value = path24.posix.normalize(`${candidateBase}${suffix}`);
129665
129929
  if (!value.startsWith("../") && value !== ".." && known.has(value))
129666
129930
  return value;
129667
129931
  }
@@ -129670,7 +129934,7 @@ function probe(base, known, dialect = "typescript") {
129670
129934
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
129671
129935
  const known = new Set(build.knownFiles.map(normalizeStructuralFile));
129672
129936
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
129673
- return probe(path23.posix.join(path23.posix.dirname(fromFile), specifier), known, dialect);
129937
+ return probe(path24.posix.join(path24.posix.dirname(fromFile), specifier), known, dialect);
129674
129938
  }
129675
129939
  const aliases = build.pathAliasesByFile?.[normalizeStructuralFile(fromFile)] ?? build.pathAliases ?? [];
129676
129940
  for (const alias of aliases) {
@@ -129934,7 +130198,7 @@ var init_scripting2 = __esm(() => {
129934
130198
  });
129935
130199
 
129936
130200
  // ../../packages/core/dist/services/structural/resolvers/systems.js
129937
- import path24 from "path";
130201
+ import path25 from "path";
129938
130202
  var DIALECTS, SYSTEMS_LANGUAGE_RESOLVER;
129939
130203
  var init_systems2 = __esm(() => {
129940
130204
  init_typescript2();
@@ -129953,7 +130217,7 @@ var init_systems2 = __esm(() => {
129953
130217
  const bindings = item.bindings.map((binding) => binding.imported === "*" && binding.local === "*" && unresolvedTarget && !unresolvedTarget.qualifier ? { ...binding, imported: unresolvedTarget.name, local: unresolvedTarget.name } : binding);
129954
130218
  if (item.specifier === "crate" || item.specifier.startsWith("crate/")) {
129955
130219
  const crateRoot = file2.file.startsWith("src/") ? "src" : "";
129956
- return { ...item, bindings, specifier: `./${path24.posix.relative(path24.posix.dirname(file2.file), path24.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
130220
+ return { ...item, bindings, specifier: `./${path25.posix.relative(path25.posix.dirname(file2.file), path25.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
129957
130221
  }
129958
130222
  if (item.specifier === "self" || item.specifier.startsWith("self/"))
129959
130223
  return { ...item, bindings, specifier: `./${item.specifier.replace(/^self\/?/u, "")}` };
@@ -130051,8 +130315,8 @@ var init_data_document2 = __esm(() => {
130051
130315
  });
130052
130316
 
130053
130317
  // ../../packages/core/dist/services/etl/stages/resolve.js
130054
- import path25 from "path";
130055
- import fs17 from "fs";
130318
+ import path26 from "path";
130319
+ import fs18 from "fs";
130056
130320
 
130057
130321
  class ResolveStage {
130058
130322
  symbolRepository;
@@ -130076,7 +130340,7 @@ class ResolveStage {
130076
130340
  const structuralDocuments = files.flatMap((file2) => {
130077
130341
  if (!file2.structure)
130078
130342
  return [];
130079
- const language = resolveStructuralLanguage(path25.extname(file2.file.relativePath));
130343
+ const language = resolveStructuralLanguage(path26.extname(file2.file.relativePath));
130080
130344
  if (language.status !== "supported")
130081
130345
  throw new Error(`structural_manifest_missing:${file2.file.relativePath}`);
130082
130346
  return [{
@@ -130088,13 +130352,13 @@ class ResolveStage {
130088
130352
  }];
130089
130353
  });
130090
130354
  const currentStructuralFiles = new Set(structuralDocuments.map((document2) => document2.file));
130091
- const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path25.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
130355
+ const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path26.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
130092
130356
  const pathAliasesByFile = Object.fromEntries([...knownRelPaths].map((file2) => [
130093
130357
  file2,
130094
130358
  this.structuralAliasesFor(file2, rootAliases, monorepoPackages)
130095
130359
  ]));
130096
130360
  const buildMetadata = { knownFiles: [...knownRelPaths], pathAliasesByFile };
130097
- const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path25.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
130361
+ const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path26.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
130098
130362
  const seedIds = new Set;
130099
130363
  for (const definition of seedRows) {
130100
130364
  if (seedIds.has(definition.id))
@@ -130187,7 +130451,7 @@ class ResolveStage {
130187
130451
  if (parsed.file !== definition.file_path) {
130188
130452
  throw new Error(`structural_repository_seed_file_mismatch:${definition.id}`);
130189
130453
  }
130190
- const language = resolveStructuralLanguage(path25.extname(definition.file_path));
130454
+ const language = resolveStructuralLanguage(path26.extname(definition.file_path));
130191
130455
  if (language.status !== "supported")
130192
130456
  throw new Error(`structural_repository_seed_language:${definition.id}`);
130193
130457
  let identity;
@@ -130239,7 +130503,7 @@ class ResolveStage {
130239
130503
  });
130240
130504
  }
130241
130505
  resolveFile(parsed, projectPath, knownRelPaths, rootAliases, monorepoPackages, symbolIndex, knownFqns) {
130242
- const fromDir = path25.dirname(path25.join(projectPath, parsed.file.relativePath));
130506
+ const fromDir = path26.dirname(path26.join(projectPath, parsed.file.relativePath));
130243
130507
  const packageAliases = this.getPackageAliases(parsed.file.relativePath, monorepoPackages);
130244
130508
  const allAliases = [...packageAliases, ...rootAliases];
130245
130509
  const resolvedImports = parsed.rawImports.map((raw2) => {
@@ -130310,12 +130574,12 @@ class ResolveStage {
130310
130574
  index.set(def.name, `${def.file_path}#${def.name}`);
130311
130575
  }
130312
130576
  } catch (err) {
130313
- const skippedStructural = files.some((file2) => !file2.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path25.extname(file2.file.relativePath).toLowerCase()));
130577
+ const skippedStructural = files.some((file2) => !file2.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path26.extname(file2.file.relativePath).toLowerCase()));
130314
130578
  if (skippedStructural)
130315
130579
  throw new Error("structural_repository_seed_failed", { cause: err });
130316
130580
  logger.warn("buildSymbolIndex: repo seed failed, in-batch only", {
130317
130581
  projectId,
130318
- error: err?.message
130582
+ error: err
130319
130583
  });
130320
130584
  }
130321
130585
  const inBatch = new Map;
@@ -130334,7 +130598,7 @@ class ResolveStage {
130334
130598
  }
130335
130599
  resolveSpecifier(specifier, fromDir, projectPath, knownRelPaths, aliases) {
130336
130600
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
130337
- const resolved = this.probeExtensions(path25.resolve(fromDir, specifier), projectPath, knownRelPaths);
130601
+ const resolved = this.probeExtensions(path26.resolve(fromDir, specifier), projectPath, knownRelPaths);
130338
130602
  return { resolvedPath: resolved, external: false };
130339
130603
  }
130340
130604
  for (const alias of aliases) {
@@ -130342,8 +130606,8 @@ class ResolveStage {
130342
130606
  const suffix = specifier.slice(alias.prefix.length);
130343
130607
  for (const target of alias.targets) {
130344
130608
  const cleanTarget = target.replace(/\/\*$/, "");
130345
- const basePath = alias.packagePath ? path25.join(projectPath, alias.packagePath) : projectPath;
130346
- const absPath = path25.join(basePath, cleanTarget + suffix);
130609
+ const basePath = alias.packagePath ? path26.join(projectPath, alias.packagePath) : projectPath;
130610
+ const absPath = path26.join(basePath, cleanTarget + suffix);
130347
130611
  const resolved = this.probeExtensions(absPath, projectPath, knownRelPaths);
130348
130612
  if (resolved)
130349
130613
  return { resolvedPath: resolved, external: false };
@@ -130359,7 +130623,7 @@ class ResolveStage {
130359
130623
  ...TS_EXTENSIONS.map((ext2) => absPath.replace(/\.[^.]+$/, ext2))
130360
130624
  ];
130361
130625
  for (const candidate2 of candidates2) {
130362
- const rel = path25.relative(projectPath, candidate2).replace(/\\/g, "/");
130626
+ const rel = path26.relative(projectPath, candidate2).replace(/\\/g, "/");
130363
130627
  if (knownRelPaths.has(rel))
130364
130628
  return rel;
130365
130629
  }
@@ -130367,9 +130631,9 @@ class ResolveStage {
130367
130631
  }
130368
130632
  loadTsConfigPaths(projectPath, packageBase) {
130369
130633
  const aliases = [];
130370
- const tsconfigPath = path25.join(projectPath, "tsconfig.json");
130634
+ const tsconfigPath = path26.join(projectPath, "tsconfig.json");
130371
130635
  try {
130372
- const raw2 = fs17.readFileSync(tsconfigPath, "utf-8");
130636
+ const raw2 = fs18.readFileSync(tsconfigPath, "utf-8");
130373
130637
  const stripped = raw2.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
130374
130638
  const tsconfig = JSON.parse(stripped);
130375
130639
  const paths = tsconfig?.compilerOptions?.paths ?? {};
@@ -130398,7 +130662,7 @@ class ResolveStage {
130398
130662
  }
130399
130663
  }
130400
130664
  for (const packageRelPath of packagePaths) {
130401
- const absPackagePath = path25.join(projectPath, packageRelPath);
130665
+ const absPackagePath = path26.join(projectPath, packageRelPath);
130402
130666
  const aliases = this.loadTsConfigPaths(absPackagePath, packageRelPath);
130403
130667
  if (aliases.length > 0) {
130404
130668
  packages.push({
@@ -130428,7 +130692,7 @@ class ResolveStage {
130428
130692
  structuralAliasesFor(filePath, rootAliases, packages) {
130429
130693
  return [...this.getPackageAliases(filePath, packages), ...rootAliases].map((alias) => ({
130430
130694
  pattern: alias.prefix + (alias.targets.some((target) => target.includes("*")) ? "/*" : ""),
130431
- targets: alias.targets.map((target) => alias.packagePath ? path25.posix.join(alias.packagePath, target) : target)
130695
+ targets: alias.targets.map((target) => alias.packagePath ? path26.posix.join(alias.packagePath, target) : target)
130432
130696
  }));
130433
130697
  }
130434
130698
  }
@@ -130478,7 +130742,7 @@ async function withDeadlockRetry(operation, options = {}) {
130478
130742
  attempt,
130479
130743
  maxAttempts,
130480
130744
  delayMs,
130481
- error: error51?.message?.slice(0, 120)
130745
+ error: error51
130482
130746
  });
130483
130747
  await new Promise((resolve5) => setTimeout(resolve5, delayMs));
130484
130748
  }
@@ -130492,7 +130756,7 @@ var init_with_deadlock_retry = __esm(() => {
130492
130756
  });
130493
130757
 
130494
130758
  // ../../packages/core/dist/services/etl/stages/load.js
130495
- import path26 from "path";
130759
+ import path27 from "path";
130496
130760
  function formatDuration(ms) {
130497
130761
  const totalSec = Math.max(0, Math.round(ms / 1000));
130498
130762
  if (totalSec < 60)
@@ -130769,7 +131033,7 @@ class LoadStage {
130769
131033
  const filePath = file2.file.relativePath;
130770
131034
  const batch = buildSymbolPersistenceBatch(ctx.projectId, file2);
130771
131035
  if (ctx.graphGenerationLease) {
130772
- const manifest = getLanguageManifestEntry(path26.extname(filePath));
131036
+ const manifest = getLanguageManifestEntry(path27.extname(filePath));
130773
131037
  const diagnostics2 = (file2.structuralDiagnostics ?? []).slice(0, 10).map((diagnostic2) => ({
130774
131038
  code: diagnostic2.code,
130775
131039
  severity: diagnostic2.severity,
@@ -131226,9 +131490,9 @@ var init_graph_generation_coordinator = __esm(() => {
131226
131490
  // ../../packages/core/dist/services/etl/pipeline.js
131227
131491
  import { createHash as createHash7 } from "crypto";
131228
131492
  import { setTimeout as delay2 } from "timers/promises";
131229
- import path27 from "path";
131493
+ import path28 from "path";
131230
131494
  function buildHeaderLanguageEvidence(files) {
131231
- const headers = new Set(files.filter((file2) => path27.posix.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path27.posix.normalize(file2.relativePath)));
131495
+ const headers = new Set(files.filter((file2) => path28.posix.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path28.posix.normalize(file2.relativePath)));
131232
131496
  const mutable = new Map;
131233
131497
  const entry2 = (header) => {
131234
131498
  let value = mutable.get(header);
@@ -131239,7 +131503,7 @@ function buildHeaderLanguageEvidence(files) {
131239
131503
  return value;
131240
131504
  };
131241
131505
  for (const file2 of files) {
131242
- if (path27.posix.basename(file2.relativePath) !== "compile_commands.json" || file2.snapshotContent === undefined)
131506
+ if (path28.posix.basename(file2.relativePath) !== "compile_commands.json" || file2.snapshotContent === undefined)
131243
131507
  continue;
131244
131508
  let commands;
131245
131509
  try {
@@ -131255,11 +131519,11 @@ function buildHeaderLanguageEvidence(files) {
131255
131519
  const record3 = command;
131256
131520
  if (typeof record3.file !== "string")
131257
131521
  continue;
131258
- const projectRoot = path27.resolve(file2.absolutePath, ...file2.relativePath.split("/").map(() => ".."));
131259
- const commandDirectory = typeof record3.directory === "string" ? path27.resolve(projectRoot, record3.directory) : projectRoot;
131260
- const absoluteInput = path27.resolve(commandDirectory, record3.file);
131261
- const relative2 = path27.relative(projectRoot, absoluteInput);
131262
- const header = path27.posix.normalize(relative2.replaceAll(path27.sep, "/"));
131522
+ const projectRoot = path28.resolve(file2.absolutePath, ...file2.relativePath.split("/").map(() => ".."));
131523
+ const commandDirectory = typeof record3.directory === "string" ? path28.resolve(projectRoot, record3.directory) : projectRoot;
131524
+ const absoluteInput = path28.resolve(commandDirectory, record3.file);
131525
+ const relative2 = path28.relative(projectRoot, absoluteInput);
131526
+ const header = path28.posix.normalize(relative2.replaceAll(path28.sep, "/"));
131263
131527
  if (!headers.has(header))
131264
131528
  continue;
131265
131529
  const invocation = typeof record3.command === "string" ? record3.command : Array.isArray(record3.arguments) ? record3.arguments.join(" ") : "";
@@ -131608,7 +131872,7 @@ var init_pipeline = __esm(() => {
131608
131872
  logger.warn("EtlPipeline: search-admission marker write failed", {
131609
131873
  projectId,
131610
131874
  jobId,
131611
- error: markerError.message.slice(0, 160)
131875
+ error: markerError
131612
131876
  });
131613
131877
  }
131614
131878
  if (forceReindex) {
@@ -131620,7 +131884,7 @@ var init_pipeline = __esm(() => {
131620
131884
  logger.warn("EtlPipeline: embedding fingerprint stamp failed", {
131621
131885
  projectId,
131622
131886
  jobId,
131623
- error: stampError.message.slice(0, 160)
131887
+ error: stampError
131624
131888
  });
131625
131889
  }
131626
131890
  }
@@ -131806,9 +132070,9 @@ var init_acquire_indexing_lease = __esm(() => {
131806
132070
 
131807
132071
  // ../../packages/core/dist/services/project-identity/project-root-identity.js
131808
132072
  import { realpath as realpath2 } from "fs/promises";
131809
- import path28 from "path";
132073
+ import path29 from "path";
131810
132074
  async function canonicalizeProjectRoot(projectPath, canonicalize = realpath2) {
131811
- return canonicalize(path28.resolve(projectPath));
132075
+ return canonicalize(path29.resolve(projectPath));
131812
132076
  }
131813
132077
  async function assertProjectRootReuse(options) {
131814
132078
  if (!options.storedProjectPath || options.forceReindex)
@@ -131816,9 +132080,9 @@ async function assertProjectRootReuse(options) {
131816
132080
  const canonicalize = options.canonicalize ?? realpath2;
131817
132081
  let storedCanonical;
131818
132082
  try {
131819
- storedCanonical = await canonicalize(path28.resolve(options.storedProjectPath));
132083
+ storedCanonical = await canonicalize(path29.resolve(options.storedProjectPath));
131820
132084
  } catch {
131821
- storedCanonical = path28.resolve(options.storedProjectPath);
132085
+ storedCanonical = path29.resolve(options.storedProjectPath);
131822
132086
  }
131823
132087
  if (storedCanonical !== options.canonicalProjectPath) {
131824
132088
  throw new Error(`Project ID "${options.projectId}" already indexes canonical root ` + `"${storedCanonical}", not "${options.canonicalProjectPath}"; ` + "use forceReindex only after verifying ownership of the existing project");
@@ -132561,16 +132825,16 @@ function detectRoutes(httpEdges, defs, opts = {}) {
132561
132825
  const seen = new Set;
132562
132826
  const out = [];
132563
132827
  for (const e of httpEdges) {
132564
- const path29 = e.route;
132565
- if (!path29)
132828
+ const path30 = e.route;
132829
+ if (!path30)
132566
132830
  continue;
132567
132831
  const method = (e.method ?? "ANY").toUpperCase();
132568
- const key = method + " " + path29;
132832
+ const key = method + " " + path30;
132569
132833
  if (seen.has(key))
132570
132834
  continue;
132571
132835
  seen.add(key);
132572
132836
  out.push({
132573
- path: path29,
132837
+ path: path30,
132574
132838
  method: e.method,
132575
132839
  file: e.fromFile,
132576
132840
  handler: e.targetFqn ?? e.symbolName
@@ -132581,12 +132845,12 @@ function detectRoutes(httpEdges, defs, opts = {}) {
132581
132845
  continue;
132582
132846
  const parsed = parseRouteName(d.name);
132583
132847
  const method = parsed?.method ?? "ANY";
132584
- const path29 = parsed?.path ?? d.name;
132585
- const key = method + " " + path29;
132848
+ const path30 = parsed?.path ?? d.name;
132849
+ const key = method + " " + path30;
132586
132850
  if (seen.has(key))
132587
132851
  continue;
132588
132852
  seen.add(key);
132589
- out.push({ path: path29, method: parsed?.method, file: d.filePath, handler: d.name });
132853
+ out.push({ path: path30, method: parsed?.method, file: d.filePath, handler: d.name });
132590
132854
  }
132591
132855
  for (const d of defs) {
132592
132856
  const parsed = parseRouteName(d.name);
@@ -132807,8 +133071,8 @@ __export(exports_symbol_graph_service, {
132807
133071
  symbolGraphService: () => symbolGraphService,
132808
133072
  SymbolGraphService: () => SymbolGraphService
132809
133073
  });
132810
- import path29 from "path";
132811
- import fs18 from "fs/promises";
133074
+ import path30 from "path";
133075
+ import fs19 from "fs/promises";
132812
133076
 
132813
133077
  class SymbolGraphService {
132814
133078
  identityLookup;
@@ -132979,9 +133243,9 @@ class SymbolGraphService {
132979
133243
  return null;
132980
133244
  const workspace = graphSnapshot.workspace;
132981
133245
  const arch = await this.computeArchitectureMapSafe(graphSnapshot.architecture).catch((err) => {
132982
- logger.warn("getProjectMap: architecture map failed; skipping", {
133246
+ logger.warn("SymbolGraphService: getProjectMap architecture map failed, skipping", {
132983
133247
  projectId,
132984
- error: err?.message?.slice(0, 160)
133248
+ error: err
132985
133249
  });
132986
133250
  return null;
132987
133251
  });
@@ -133136,7 +133400,7 @@ class SymbolGraphService {
133136
133400
  async readSnippet(relativePath, lineStart, lineEnd, projectId) {
133137
133401
  try {
133138
133402
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
133139
- const content = await fs18.readFile(absolutePath, "utf-8");
133403
+ const content = await fs19.readFile(absolutePath, "utf-8");
133140
133404
  const lines = content.split(`
133141
133405
  `);
133142
133406
  return lines.slice(Math.max(0, lineStart - 1), Math.min(lines.length, lineEnd)).join(`
@@ -133148,7 +133412,7 @@ class SymbolGraphService {
133148
133412
  async readContext(relativePath, lineNumber, contextLines, projectId) {
133149
133413
  try {
133150
133414
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
133151
- const content = await fs18.readFile(absolutePath, "utf-8");
133415
+ const content = await fs19.readFile(absolutePath, "utf-8");
133152
133416
  const lines = content.split(`
133153
133417
  `);
133154
133418
  const start = Math.max(0, lineNumber - contextLines - 1);
@@ -133161,7 +133425,7 @@ class SymbolGraphService {
133161
133425
  }
133162
133426
  async resolveToAbsolute(relativePath, projectId) {
133163
133427
  const root = await this.getProjectRoot(projectId);
133164
- return root ? path29.resolve(root, relativePath) : relativePath;
133428
+ return root ? path30.resolve(root, relativePath) : relativePath;
133165
133429
  }
133166
133430
  async getProjectRoot(projectId) {
133167
133431
  const cached2 = this.projectRootCache.get(projectId);
@@ -133304,7 +133568,7 @@ var init_workspace_manager = __esm(() => {
133304
133568
  });
133305
133569
 
133306
133570
  // ../../packages/core/dist/tools/index_project.js
133307
- import path30 from "path";
133571
+ import path31 from "path";
133308
133572
 
133309
133573
  class IndexProjectTool {
133310
133574
  name = "index_project";
@@ -133352,7 +133616,7 @@ class IndexProjectTool {
133352
133616
  try {
133353
133617
  await assertParserReadyForIndexing();
133354
133618
  const canonicalProjectPath = await canonicalizeProjectRoot(projectPath);
133355
- const finalProjectId = projectId || path30.basename(canonicalProjectPath) || "default";
133619
+ const finalProjectId = projectId || path31.basename(canonicalProjectPath) || "default";
133356
133620
  const existing = await workspaceManager.getWorkspace(finalProjectId);
133357
133621
  await assertProjectRootReuse({
133358
133622
  projectId: finalProjectId,
@@ -133905,17 +134169,17 @@ function applyReplacer(root, replacer) {
133905
134169
  return transformChildren(root, replacer, []);
133906
134170
  return transformChildren(normalizeValue(replacedRoot), replacer, []);
133907
134171
  }
133908
- function transformChildren(value, replacer, path31) {
134172
+ function transformChildren(value, replacer, path32) {
133909
134173
  if (isJsonObject(value))
133910
- return transformObject(value, replacer, path31);
134174
+ return transformObject(value, replacer, path32);
133911
134175
  if (isJsonArray(value))
133912
- return transformArray(value, replacer, path31);
134176
+ return transformArray(value, replacer, path32);
133913
134177
  return value;
133914
134178
  }
133915
- function transformObject(obj, replacer, path31) {
134179
+ function transformObject(obj, replacer, path32) {
133916
134180
  const result = {};
133917
134181
  for (const [key, value] of Object.entries(obj)) {
133918
- const childPath = [...path31, key];
134182
+ const childPath = [...path32, key];
133919
134183
  const replacedValue = replacer(key, value, childPath);
133920
134184
  if (replacedValue === undefined)
133921
134185
  continue;
@@ -133923,11 +134187,11 @@ function transformObject(obj, replacer, path31) {
133923
134187
  }
133924
134188
  return result;
133925
134189
  }
133926
- function transformArray(arr, replacer, path31) {
134190
+ function transformArray(arr, replacer, path32) {
133927
134191
  const result = [];
133928
134192
  for (let i = 0;i < arr.length; i++) {
133929
134193
  const value = arr[i];
133930
- const childPath = [...path31, i];
134194
+ const childPath = [...path32, i];
133931
134195
  const replacedValue = replacer(String(i), value, childPath);
133932
134196
  if (replacedValue === undefined)
133933
134197
  continue;
@@ -134700,7 +134964,7 @@ class RelationExtractor {
134700
134964
  } catch (error51) {
134701
134965
  logger.warn("RelationExtractor: extraction failed", {
134702
134966
  memoryId,
134703
- error: error51.message
134967
+ error: error51
134704
134968
  });
134705
134969
  }
134706
134970
  return edgesCreated;
@@ -135147,7 +135411,7 @@ class MemoryGraphService {
135147
135411
  } catch (error51) {
135148
135412
  logger.warn("Graph update failed after memory store", {
135149
135413
  memoryId,
135150
- error: error51.message
135414
+ error: error51
135151
135415
  });
135152
135416
  }
135153
135417
  }
@@ -135163,7 +135427,7 @@ class MemoryGraphService {
135163
135427
  } catch (error51) {
135164
135428
  logger.warn("Graph cleanup failed after memory delete", {
135165
135429
  memoryId,
135166
- error: error51.message
135430
+ error: error51
135167
135431
  });
135168
135432
  }
135169
135433
  }
@@ -135312,7 +135576,7 @@ async function consolidateWindow(candidates2, llm2, opts = {}) {
135312
135576
  if (!llm2.isEnabled())
135313
135577
  return null;
135314
135578
  const prompt = buildPrompt2(window2);
135315
- const result = await llm2.object(prompt, ConsolidatedBatchSchema);
135579
+ const result = await llm2.object(prompt, ConsolidatedBatchSchema, { label: "memory-consolidation" });
135316
135580
  if (!result.ok || !result.value)
135317
135581
  return null;
135318
135582
  const batch = {
@@ -135413,7 +135677,7 @@ class MemoryConsolidationJob {
135413
135677
  } catch (error51) {
135414
135678
  logger.warn("Memory consolidation skipped", {
135415
135679
  trigger,
135416
- error: error51.message
135680
+ error: error51
135417
135681
  });
135418
135682
  } finally {
135419
135683
  this.running = false;
@@ -135436,7 +135700,7 @@ class MemoryConsolidationJob {
135436
135700
  candidates2 = await Promise.resolve(repo.listConsolidationCandidates(staleSinceMs, 500));
135437
135701
  } catch (e) {
135438
135702
  logger.warn("consolidation: candidate list failed (decay)", {
135439
- error: e.message
135703
+ error: e
135440
135704
  });
135441
135705
  return 0;
135442
135706
  }
@@ -135458,7 +135722,7 @@ class MemoryConsolidationJob {
135458
135722
  } catch (e) {
135459
135723
  logger.warn("consolidation: decay write failed", {
135460
135724
  id: row.id,
135461
- error: e.message
135725
+ error: e
135462
135726
  });
135463
135727
  }
135464
135728
  }
@@ -135487,14 +135751,14 @@ class MemoryConsolidationJob {
135487
135751
  } catch (e) {
135488
135752
  logger.warn("consolidation: soft-delete failed", {
135489
135753
  id: row.id,
135490
- error: e.message
135754
+ error: e
135491
135755
  });
135492
135756
  }
135493
135757
  }
135494
135758
  }
135495
135759
  } catch (e) {
135496
135760
  logger.warn("consolidation: prune scan failed", {
135497
- error: e.message
135761
+ error: e
135498
135762
  });
135499
135763
  }
135500
135764
  return pruned;
@@ -135505,7 +135769,7 @@ class MemoryConsolidationJob {
135505
135769
  candidates2 = await Promise.resolve(repo.listConsolidationCandidates(staleSinceMs, 200));
135506
135770
  } catch (e) {
135507
135771
  logger.warn("consolidation: candidate list failed (merge)", {
135508
- error: e.message
135772
+ error: e
135509
135773
  });
135510
135774
  return { merged: 0, batchesCreated: 0 };
135511
135775
  }
@@ -135531,7 +135795,7 @@ class MemoryConsolidationJob {
135531
135795
  } catch (e) {
135532
135796
  logger.warn("consolidation: merge insert failed", {
135533
135797
  batchId: batch.id,
135534
- error: e.message
135798
+ error: e
135535
135799
  });
135536
135800
  return { merged: 0, batchesCreated: 0 };
135537
135801
  }
@@ -135544,7 +135808,7 @@ class MemoryConsolidationJob {
135544
135808
  logger.warn("consolidation: addSupercedesEdge failed", {
135545
135809
  newId,
135546
135810
  sourceId,
135547
- error: e.message
135811
+ error: e
135548
135812
  });
135549
135813
  }
135550
135814
  }
@@ -135584,7 +135848,7 @@ class MemoryConsolidationJob {
135584
135848
  return result;
135585
135849
  } catch (e) {
135586
135850
  logger.warn("consolidation: promote (PG) failed", {
135587
- error: e.message
135851
+ error: e
135588
135852
  });
135589
135853
  return 0;
135590
135854
  }
@@ -135623,19 +135887,22 @@ class SalienceJudge {
135623
135887
  }
135624
135888
  const prompt = buildPrompt3(trimmed, type);
135625
135889
  let verdict;
135890
+ let verdictError;
135626
135891
  try {
135627
- const res = await this.llm.object(prompt, SalienceSchema);
135892
+ const res = await this.llm.object(prompt, SalienceSchema, { label: "salience-judge" });
135628
135893
  verdict = res.ok ? res.value ?? null : null;
135894
+ verdictError = res.ok ? undefined : res.error;
135629
135895
  } catch (e) {
135630
135896
  logger.warn("SalienceJudge threw \u2014 degrading to neutral default", {
135631
135897
  type,
135632
- error: e.message
135898
+ error: e
135633
135899
  });
135634
135900
  return { salience: NEUTRAL_SALIENCE, source: "default" };
135635
135901
  }
135636
135902
  if (!verdict) {
135637
135903
  logger.warn("SalienceJudge got {ok:false} \u2014 degrading to neutral default", {
135638
- type
135904
+ type,
135905
+ error: verdictError
135639
135906
  });
135640
135907
  return { salience: NEUTRAL_SALIENCE, source: "default" };
135641
135908
  }
@@ -135850,7 +136117,8 @@ class MemoryController {
135850
136117
  }
135851
136118
  } catch (err) {
135852
136119
  logger.warn("Graph enrichment failed", {
135853
- error: err.message
136120
+ projectId,
136121
+ error: err
135854
136122
  });
135855
136123
  }
135856
136124
  }
@@ -136052,7 +136320,7 @@ class CodeCompressor {
136052
136320
  }
136053
136321
  const prompt = buildLlmCompressPrompt(content, language3, targetRatio, preservedElements);
136054
136322
  try {
136055
- const res = await this.llmCompleteFn(prompt, { timeoutMs, modelRole: "code" });
136323
+ const res = await this.llmCompleteFn(prompt, { label: "code-compressor", timeoutMs, modelRole: "code" });
136056
136324
  if (res.ok && typeof res.value === "string" && res.value.trim().length > 0 && res.value.length <= content.length) {
136057
136325
  compressed = res.value;
136058
136326
  compressionSource = "llm";
@@ -136092,7 +136360,10 @@ class CodeCompressor {
136092
136360
  });
136093
136361
  return compressedContent;
136094
136362
  } catch (error51) {
136095
- logger.error("Code compression failed", error51);
136363
+ logger.error("Code compression failed", error51, {
136364
+ strategy: useStrategy,
136365
+ originalLength: content.length
136366
+ });
136096
136367
  return CompressedContent.identity(content);
136097
136368
  }
136098
136369
  }
@@ -136402,9 +136673,9 @@ class TokenMetrics {
136402
136673
  }
136403
136674
  throw new Error("Model not found in models.dev");
136404
136675
  } catch (error51) {
136405
- logger.warn("Failed to fetch pricing from models.dev, using fallback", {
136676
+ logger.warn("TokenMetrics: failed to fetch pricing from models.dev, using fallback", {
136406
136677
  modelId,
136407
- error: error51 instanceof Error ? error51.message : String(error51)
136678
+ error: error51
136408
136679
  });
136409
136680
  const fallback = FALLBACK_PRICING2[modelId] || FALLBACK_PRICING2["gpt-4"];
136410
136681
  this.pricingCache.set(modelId, {
@@ -136742,7 +137013,7 @@ class ContextController {
136742
137013
  });
136743
137014
  }
136744
137015
  } catch (err) {
136745
- logger.warn("Graph prefilter failed", { query, error: err.message });
137016
+ logger.warn("ContextController: graph prefilter failed", { projectId, query, error: err });
136746
137017
  }
136747
137018
  }
136748
137019
  const [searchResult, memories] = await Promise.all([
@@ -136896,9 +137167,11 @@ class ContextController {
136896
137167
  });
136897
137168
  return result.memories;
136898
137169
  } catch (error51) {
136899
- logger.warn("Memory search failed, continuing without memories", {
136900
- error: error51.message,
136901
- query: query.slice(0, 30)
137170
+ logger.warn("ContextController: memory search failed, continuing without memories", {
137171
+ projectId: opts.projectId,
137172
+ sessionId: opts.sessionId,
137173
+ query: query.slice(0, 30),
137174
+ error: error51
136902
137175
  });
136903
137176
  return [];
136904
137177
  }
@@ -137574,7 +137847,7 @@ class PgCheckpointStore {
137574
137847
  } catch (e) {
137575
137848
  this.hydrateFailedAt = Date.now();
137576
137849
  logger.warn("PgCheckpointStore hydrate failed (best-effort)", {
137577
- error: e.message
137850
+ error: e
137578
137851
  });
137579
137852
  } finally {
137580
137853
  this.hydrating = null;
@@ -137768,8 +138041,9 @@ class PgCheckpointStore {
137768
138041
  }
137769
138042
  return existing;
137770
138043
  } catch (e) {
137771
- logger.warn("countExistingMemoryIds failed (best-effort: assuming all exist)", {
137772
- error: e.message
138044
+ logger.warn("PgCheckpointStore: countExistingMemoryIds failed (best-effort, assuming all exist)", {
138045
+ memoryIdCount: memoryIds.length,
138046
+ error: e
137773
138047
  });
137774
138048
  return memoryIds;
137775
138049
  }
@@ -137836,7 +138110,7 @@ class PgCheckpointStore {
137836
138110
  const next = prev.then(fn).catch((e) => {
137837
138111
  logger.warn("PgCheckpointStore write failed (best-effort)", {
137838
138112
  key,
137839
- error: e.message
138113
+ error: e
137840
138114
  });
137841
138115
  });
137842
138116
  this.inflight.set(key, next);
@@ -138262,7 +138536,7 @@ class ListCheckpointsTool {
138262
138536
  };
138263
138537
  return serializeToolResponse(responseData, { format, fields });
138264
138538
  } catch (error51) {
138265
- logger.error("Failed to list checkpoints", error51);
138539
+ logger.error("Failed to list checkpoints", error51, { taskId, projectId });
138266
138540
  return {
138267
138541
  success: false,
138268
138542
  error: `Failed to list checkpoints: ${error51.message}`
@@ -138354,7 +138628,7 @@ class PgObservationStore {
138354
138628
  } catch (e) {
138355
138629
  this.hydrateFailedAt = Date.now();
138356
138630
  logger.warn("PgObservationStore hydrate failed (best-effort)", {
138357
- error: e.message
138631
+ error: e
138358
138632
  });
138359
138633
  } finally {
138360
138634
  this.hydrating = null;
@@ -138405,7 +138679,7 @@ class PgObservationStore {
138405
138679
  const next = prev.then(fn).catch((e) => {
138406
138680
  logger.warn("PgObservationStore.insert failed (best-effort)", {
138407
138681
  id: key,
138408
- error: e.message
138682
+ error: e
138409
138683
  });
138410
138684
  });
138411
138685
  this.inflight.set(key, next);
@@ -138607,7 +138881,7 @@ var TOOL_NAME_NORMALIZE, classifyToolCall = (_source, payload) => {
138607
138881
  if (lowerPrompt.includes("blocked on") || lowerPrompt.includes("waiting on") || lowerPrompt.includes("can't proceed") || lowerPrompt.includes("stuck on")) {
138608
138882
  return "blocked-on";
138609
138883
  }
138610
- if (lowerPrompt.startsWith("/persona") || lowerPrompt.startsWith("act as") || lowerPrompt.startsWith("you are a")) {
138884
+ if (lowerPrompt.startsWith("act as") || lowerPrompt.startsWith("you are a")) {
138611
138885
  return "role";
138612
138886
  }
138613
138887
  return "user-prompts";
@@ -139008,9 +139282,9 @@ var init_session_pin_store = __esm(() => {
139008
139282
  });
139009
139283
 
139010
139284
  // ../../packages/core/dist/services/hooks/attribution-resolver.js
139011
- import fs19 from "fs";
139285
+ import fs20 from "fs";
139012
139286
  import os9 from "os";
139013
- import path31 from "path";
139287
+ import path32 from "path";
139014
139288
 
139015
139289
  class PgWorkspaceRootProvider {
139016
139290
  cache = null;
@@ -139060,7 +139334,7 @@ class AttributionResolver {
139060
139334
  this.pins = options.pins ?? new SessionPinStore;
139061
139335
  this.canonicalize = options.canonicalize ?? defaultCanonicalize;
139062
139336
  this.homedir = options.homedir ?? os9.homedir;
139063
- this.fsRoot = options.fsRoot ?? (() => path31.parse(path31.sep).root);
139337
+ this.fsRoot = options.fsRoot ?? (() => path32.parse(path32.sep).root);
139064
139338
  }
139065
139339
  async resolve(input) {
139066
139340
  const caller = input.callerProjectId;
@@ -139111,7 +139385,7 @@ class AttributionResolver {
139111
139385
  }
139112
139386
  let bestPath = null;
139113
139387
  for (const candidate2 of byPath.keys()) {
139114
- if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path31.sep) ? candidate2 : candidate2 + path31.sep)) {
139388
+ if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path32.sep) ? candidate2 : candidate2 + path32.sep)) {
139115
139389
  if (bestPath === null || candidate2.length > bestPath.length) {
139116
139390
  bestPath = candidate2;
139117
139391
  }
@@ -139134,7 +139408,7 @@ class AttributionResolver {
139134
139408
  return projectPath2;
139135
139409
  const fsRoot = this.fsRoot();
139136
139410
  let normalized = projectPath2;
139137
- while (normalized.length > fsRoot.length && normalized.endsWith(path31.sep)) {
139411
+ while (normalized.length > fsRoot.length && normalized.endsWith(path32.sep)) {
139138
139412
  normalized = normalized.slice(0, -1);
139139
139413
  }
139140
139414
  return normalized;
@@ -139142,10 +139416,10 @@ class AttributionResolver {
139142
139416
  }
139143
139417
  function defaultCanonicalize(cwd) {
139144
139418
  try {
139145
- return fs19.realpathSync(cwd);
139419
+ return fs20.realpathSync(cwd);
139146
139420
  } catch {
139147
139421
  try {
139148
- return path31.resolve(cwd);
139422
+ return path32.resolve(cwd);
139149
139423
  } catch {
139150
139424
  return;
139151
139425
  }
@@ -139248,7 +139522,8 @@ class CompactSnapshotTool {
139248
139522
  });
139249
139523
  } catch (e) {
139250
139524
  logger.warn("compact_snapshot: persist failed (non-fatal)", {
139251
- error: e.message
139525
+ sessionId,
139526
+ error: e
139252
139527
  });
139253
139528
  persistedId = undefined;
139254
139529
  }
@@ -139893,31 +140168,31 @@ class TracePathService {
139893
140168
  const chains = [];
139894
140169
  const seen = new Set;
139895
140170
  let walks = 0;
139896
- const walk = (fqn, path32) => {
140171
+ const walk = (fqn, path33) => {
139897
140172
  if (chains.length >= CHAIN_CAP)
139898
140173
  return;
139899
140174
  if (walks >= MAX_WALKS)
139900
140175
  return;
139901
140176
  walks++;
139902
- const key = path32.join("\u2192");
140177
+ const key = path33.join("\u2192");
139903
140178
  if (seen.has(key))
139904
140179
  return;
139905
140180
  seen.add(key);
139906
140181
  const next = adj.get(fqn);
139907
140182
  if (!next || next.length === 0 || !whoHasChild.has(fqn)) {
139908
- if (path32.length > 1)
139909
- chains.push(path32.map((n) => this.fqnToName(n)).join(" \u2192 "));
140183
+ if (path33.length > 1)
140184
+ chains.push(path33.map((n) => this.fqnToName(n)).join(" \u2192 "));
139910
140185
  return;
139911
140186
  }
139912
140187
  for (const child of next) {
139913
140188
  if (chains.length >= CHAIN_CAP || walks >= MAX_WALKS)
139914
140189
  return;
139915
- if (path32.includes(child)) {
139916
- const cycled = [...path32, `${this.fqnToName(child)}\u21BA`];
140190
+ if (path33.includes(child)) {
140191
+ const cycled = [...path33, `${this.fqnToName(child)}\u21BA`];
139917
140192
  chains.push(cycled.map((n) => n).join(" \u2192 "));
139918
140193
  continue;
139919
140194
  }
139920
- walk(child, [...path32, child]);
140195
+ walk(child, [...path33, child]);
139921
140196
  }
139922
140197
  };
139923
140198
  for (const seed of seeds) {
@@ -140750,7 +141025,7 @@ var init_get_architecture = __esm(() => {
140750
141025
  });
140751
141026
 
140752
141027
  // ../../packages/core/dist/services/file-read/file-content-cache.js
140753
- import fs20 from "fs/promises";
141028
+ import fs21 from "fs/promises";
140754
141029
 
140755
141030
  class FileContentCache {
140756
141031
  extractMetadata;
@@ -140783,7 +141058,7 @@ class FileContentCache {
140783
141058
  metadata: cached2.metadata
140784
141059
  };
140785
141060
  }
140786
- const content = await fs20.readFile(filePath, "utf-8");
141061
+ const content = await fs21.readFile(filePath, "utf-8");
140787
141062
  const metadata = await this.extractMetadata(content, filePath, options);
140788
141063
  evictOldest(this.fileCache, this.FILE_CACHE_MAX_ENTRIES - 1);
140789
141064
  this.fileCache.set(cacheKey, {
@@ -140800,7 +141075,7 @@ var init_file_content_cache = __esm(() => {
140800
141075
  });
140801
141076
 
140802
141077
  // ../../packages/core/dist/services/file-read/file-metadata.js
140803
- import path32 from "path";
141078
+ import path33 from "path";
140804
141079
 
140805
141080
  class FileMetadataExtractor {
140806
141081
  symbolGraph;
@@ -140836,7 +141111,7 @@ class FileMetadataExtractor {
140836
141111
  return metadata;
140837
141112
  }
140838
141113
  detectLanguage(filePath) {
140839
- const ext2 = path32.extname(filePath).toLowerCase();
141114
+ const ext2 = path33.extname(filePath).toLowerCase();
140840
141115
  const languageMap2 = {
140841
141116
  ".ts": "TypeScript",
140842
141117
  ".tsx": "TypeScript",
@@ -140958,7 +141233,7 @@ var init_line_range = __esm(() => {
140958
141233
  });
140959
141234
 
140960
141235
  // ../../packages/core/dist/services/file-read/path-containment.js
140961
- import path33 from "path";
141236
+ import path34 from "path";
140962
141237
 
140963
141238
  class PathContainment {
140964
141239
  projectRoots;
@@ -140966,14 +141241,14 @@ class PathContainment {
140966
141241
  this.projectRoots = projectRoots;
140967
141242
  }
140968
141243
  async resolveFilePath(filePath, projectId) {
140969
- if (path33.isAbsolute(filePath)) {
140970
- return path33.resolve(filePath);
141244
+ if (path34.isAbsolute(filePath)) {
141245
+ return path34.resolve(filePath);
140971
141246
  }
140972
141247
  if (projectId) {
140973
141248
  const root = await this.projectRoots.getProjectRoot(projectId);
140974
141249
  if (root) {
140975
141250
  const cleaned = sanitizeFilePath(filePath);
140976
- return path33.resolve(root, cleaned);
141251
+ return path34.resolve(root, cleaned);
140977
141252
  }
140978
141253
  return null;
140979
141254
  }
@@ -140984,17 +141259,17 @@ class PathContainment {
140984
141259
  if (projectId) {
140985
141260
  const root = await this.projectRoots.getProjectRoot(projectId);
140986
141261
  if (root)
140987
- roots.push(path33.resolve(root));
141262
+ roots.push(path34.resolve(root));
140988
141263
  }
140989
- roots.push(path33.resolve(process.cwd()));
141264
+ roots.push(path34.resolve(process.cwd()));
140990
141265
  const envRoots = (process.env.MASSA_AI_READ_FILE_ROOTS ?? "").split(":").map((s) => s.trim()).filter((s) => s.length > 0);
140991
141266
  for (const extra of envRoots) {
140992
- roots.push(path33.resolve(extra));
141267
+ roots.push(path34.resolve(extra));
140993
141268
  }
140994
- const target = path33.resolve(absoluteFilePath);
141269
+ const target = path34.resolve(absoluteFilePath);
140995
141270
  for (const root of roots) {
140996
- const rel = path33.relative(root, target);
140997
- if (rel !== "" && !rel.startsWith("..") && !path33.isAbsolute(rel)) {
141271
+ const rel = path34.relative(root, target);
141272
+ if (rel !== "" && !rel.startsWith("..") && !path34.isAbsolute(rel)) {
140998
141273
  return { allowed: true };
140999
141274
  }
141000
141275
  if (rel === "")
@@ -141042,7 +141317,7 @@ class ProjectRootCache {
141042
141317
  return workspace.project_path;
141043
141318
  }
141044
141319
  } catch (error51) {
141045
- logger.warn("Failed to look up project root", { projectId, error: error51.message });
141320
+ logger.warn("ProjectRootCache: failed to look up project root", { projectId, error: error51 });
141046
141321
  }
141047
141322
  return null;
141048
141323
  }
@@ -141710,7 +141985,7 @@ function warnSandboxUnavailable() {
141710
141985
  return;
141711
141986
  _warnedAboutNoSandbox = true;
141712
141987
  const missingTool = process.platform === "darwin" ? "sandbox-exec" : "docker";
141713
- logger.warn(`sandbox: MASSA_AI_EXECUTOR_SANDBOX=auto found no '${missingTool}' on this platform, ` + `so code is executing with best-effort containment and no OS-level isolation. ` + `Install '${missingTool}', or set MASSA_AI_EXECUTOR_SANDBOX=on to fail loudly instead of falling back.`, { missingTool, platform: process.platform, effectiveMode: "none" });
141988
+ logger.warn("Sandbox: no sandbox tool found for auto mode, falling back to best-effort containment", { missingTool, platform: process.platform, effectiveMode: "none" });
141714
141989
  }
141715
141990
  function getSandboxMode() {
141716
141991
  const env4 = process.env.MASSA_AI_EXECUTOR_SANDBOX ?? "auto";
@@ -142625,7 +142900,10 @@ class ExecutorController {
142625
142900
  }
142626
142901
  };
142627
142902
  } catch (error51) {
142628
- logger.error("batch_execute failed", error51);
142903
+ logger.error("batch_execute failed", error51, {
142904
+ commandCount: commands.length,
142905
+ concurrency: effectiveConcurrency
142906
+ });
142629
142907
  return {
142630
142908
  success: false,
142631
142909
  error: `batch_execute failed: ${error51.message}`
@@ -144237,9 +144515,9 @@ var init_inference_probe = __esm(() => {
144237
144515
  });
144238
144516
 
144239
144517
  // ../../packages/core/dist/services/health/local-health-checker.js
144240
- import fs21 from "fs/promises";
144518
+ import fs22 from "fs/promises";
144241
144519
  import { existsSync as existsSync3 } from "fs";
144242
- import path34 from "path";
144520
+ import path35 from "path";
144243
144521
 
144244
144522
  class LocalHealthChecker {
144245
144523
  dataDir = config2.get("dataDir");
@@ -144317,10 +144595,10 @@ class LocalHealthChecker {
144317
144595
  const start = Date.now();
144318
144596
  try {
144319
144597
  if (!existsSync3(this.dataDir))
144320
- await fs21.mkdir(this.dataDir, { recursive: true });
144321
- const probe2 = path34.join(this.dataDir, ".health-check-test");
144322
- await fs21.writeFile(probe2, "ok");
144323
- await fs21.unlink(probe2);
144598
+ await fs22.mkdir(this.dataDir, { recursive: true });
144599
+ const probe2 = path35.join(this.dataDir, ".health-check-test");
144600
+ await fs22.writeFile(probe2, "ok");
144601
+ await fs22.unlink(probe2);
144324
144602
  return { available: true, latency: Date.now() - start, details: { path: this.dataDir, writable: true } };
144325
144603
  } catch (error51) {
144326
144604
  return { available: false, latency: Date.now() - start, error: `Data directory error: ${error51.message}` };
@@ -144567,7 +144845,7 @@ class PgScheduledJobStore {
144567
144845
  logger.info("PgScheduledJobStore hydrated", { rows: this.mirror.size });
144568
144846
  } catch (e) {
144569
144847
  logger.warn("PgScheduledJobStore hydrate failed (best-effort)", {
144570
- error: e.message
144848
+ error: e
144571
144849
  });
144572
144850
  } finally {
144573
144851
  this.hydrating = null;
@@ -144581,9 +144859,10 @@ class PgScheduledJobStore {
144581
144859
  try {
144582
144860
  await action();
144583
144861
  } catch (e) {
144584
- logger.warn(`PgScheduledJobStore.${operation} failed (best-effort)`, {
144862
+ logger.warn("PgScheduledJobStore mutation failed (best-effort)", {
144585
144863
  id,
144586
- error: e.message
144864
+ operation,
144865
+ error: e
144587
144866
  });
144588
144867
  }
144589
144868
  };
@@ -144836,7 +145115,7 @@ class Scheduler {
144836
145115
  this.timer = setInterval(() => {
144837
145116
  this.tick().catch((e) => {
144838
145117
  logger.warn("Scheduler tick failed (swallowed)", {
144839
- error: e.message
145118
+ error: e
144840
145119
  });
144841
145120
  });
144842
145121
  }, this.tickIntervalMs);
@@ -144951,7 +145230,7 @@ class Scheduler {
144951
145230
  logger.warn("Scheduler: job handler threw (caught)", {
144952
145231
  id: job.id,
144953
145232
  jobKind: job.jobKind,
144954
- error: errMsg
145233
+ error: e
144955
145234
  });
144956
145235
  } finally {
144957
145236
  if (succeeded) {
@@ -144970,7 +145249,7 @@ class Scheduler {
144970
145249
  } catch (e) {
144971
145250
  logger.warn("Scheduler: persist after fire failed", {
144972
145251
  id: job.id,
144973
- error: e.message
145252
+ error: e
144974
145253
  });
144975
145254
  }
144976
145255
  this.running.delete(job.jobKind);
@@ -144990,6 +145269,8 @@ class Scheduler {
144990
145269
  enabled: j.enabled,
144991
145270
  nextRunAt: j.nextRunAt,
144992
145271
  lastRunAt: j.lastRunAt,
145272
+ lastSuccessAt: j.lastSuccessAt ?? null,
145273
+ consecutiveFailures: j.consecutiveFailures ?? 0,
144993
145274
  due: j.enabled && j.nextRunAt <= now2,
144994
145275
  currentlyRunning: this.running.has(j.jobKind)
144995
145276
  }))
@@ -145636,7 +145917,7 @@ async function enrichWithLlm(candidates2, observations, surface) {
145636
145917
  const prompt = buildEnrichmentPrompt(candidates2, observations);
145637
145918
  let enrichment = null;
145638
145919
  try {
145639
- const res = await surface.object(prompt, ProposalEnrichmentSchema);
145920
+ const res = await surface.object(prompt, ProposalEnrichmentSchema, { label: "auto-improve" });
145640
145921
  if (!res.ok || !res.value || !Array.isArray(res.value.items)) {
145641
145922
  return { candidates: candidates2, used: false };
145642
145923
  }
@@ -145832,7 +146113,7 @@ async function runOnce(job, projectId) {
145832
146113
  try {
145833
146114
  observations = job.observationStore.listRecent(projectId, job.maxWindow);
145834
146115
  } catch (e) {
145835
- logger.warn("auto-improve: listRecent failed", { projectId, error: e.message });
146116
+ logger.warn("auto-improve: listRecent failed", { projectId, error: e });
145836
146117
  return noop2;
145837
146118
  }
145838
146119
  if (observations.length < 2)
@@ -145847,7 +146128,7 @@ async function runOnce(job, projectId) {
145847
146128
  if (res.used)
145848
146129
  source = "llm";
145849
146130
  } catch (e) {
145850
- logger.warn("auto-improve: enrichWithLlm threw (silent)", { projectId, error: e.message });
146131
+ logger.warn("auto-improve: enrichWithLlm threw (silent)", { projectId, error: e });
145851
146132
  }
145852
146133
  const seen = new Set;
145853
146134
  const unique = candidates2.filter((c) => {
@@ -145895,7 +146176,7 @@ async function runOnce(job, projectId) {
145895
146176
  } catch (e) {
145896
146177
  if (e instanceof SearchServiceError)
145897
146178
  throw e;
145898
- logger.warn("proposal:auto-approved:threw", { id: r.id, projectId, error: e.message });
146179
+ logger.warn("proposal:auto-approved:threw", { id: r.id, projectId, error: e });
145899
146180
  }
145900
146181
  }
145901
146182
  result.proposalsApplied = applied;
@@ -145924,7 +146205,7 @@ async function approve(job, id, projectId, source = "rule-based") {
145924
146205
  appliedMemoryId = await applyProposal(job, row);
145925
146206
  } catch (e) {
145926
146207
  const reason = e instanceof ApplyRejection ? e.reason : "apply-failed";
145927
- logger.warn("proposal:apply-failed", { id, projectId: row.projectId, reason, error: e.message });
146208
+ logger.warn("proposal:apply-failed", { id, projectId: row.projectId, reason, error: e });
145928
146209
  return { ok: false, reason };
145929
146210
  }
145930
146211
  let updated;
@@ -146059,9 +146340,9 @@ class AutoImproveJob {
146059
146340
  return;
146060
146341
  this.newSinceRun = 0;
146061
146342
  this.lastRunAt = now2;
146062
- this.runOnce(projectId).catch((e) => logger.warn("auto-improve: runOnce failed (silent)", { projectId, error: e.message }));
146343
+ this.runOnce(projectId).catch((e) => logger.warn("auto-improve: runOnce failed (silent)", { projectId, error: e }));
146063
146344
  } catch (e) {
146064
- logger.warn("auto-improve: maybeRun swallowed", { projectId, error: e.message });
146345
+ logger.warn("auto-improve: maybeRun swallowed", { projectId, error: e });
146065
146346
  }
146066
146347
  }
146067
146348
  async runOnce(projectId) {
@@ -146161,13 +146442,13 @@ class ObservationConsolidationJob {
146161
146442
  this.runOnce(projectId).catch((e) => {
146162
146443
  logger.warn("observation consolidation: runOnce failed (silent)", {
146163
146444
  projectId,
146164
- error: e.message
146445
+ error: e
146165
146446
  });
146166
146447
  });
146167
146448
  } catch (e) {
146168
146449
  logger.warn("observation consolidation: maybeRun swallowed", {
146169
146450
  projectId,
146170
- error: e.message
146451
+ error: e
146171
146452
  });
146172
146453
  }
146173
146454
  }
@@ -146191,7 +146472,7 @@ class ObservationConsolidationJob {
146191
146472
  } catch (e) {
146192
146473
  logger.warn("observation consolidation: listRecent failed", {
146193
146474
  projectId,
146194
- error: e.message
146475
+ error: e
146195
146476
  });
146196
146477
  return noop2;
146197
146478
  }
@@ -146202,7 +146483,7 @@ class ObservationConsolidationJob {
146202
146483
  const prompt = buildObservationPrompt(window2);
146203
146484
  let batch;
146204
146485
  try {
146205
- const res = await this.llm.object(prompt, ConsolidatedBatchSchema);
146486
+ const res = await this.llm.object(prompt, ConsolidatedBatchSchema, { label: "observation-consolidation" });
146206
146487
  if (!res.ok || !res.value) {
146207
146488
  return noop2;
146208
146489
  }
@@ -146218,7 +146499,7 @@ class ObservationConsolidationJob {
146218
146499
  } catch (e) {
146219
146500
  logger.warn("observation consolidation: llm.object threw (silent)", {
146220
146501
  projectId,
146221
- error: e.message
146502
+ error: e
146222
146503
  });
146223
146504
  return noop2;
146224
146505
  }
@@ -146247,7 +146528,7 @@ class ObservationConsolidationJob {
146247
146528
  } catch (e) {
146248
146529
  logger.warn("observation consolidation: summary insert failed", {
146249
146530
  batchId: batch.id,
146250
- error: e.message
146531
+ error: e
146251
146532
  });
146252
146533
  return noop2;
146253
146534
  }
@@ -146454,9 +146735,9 @@ var init_scheduler2 = __esm(() => {
146454
146735
  });
146455
146736
 
146456
146737
  // ../../packages/core/dist/services/pricing/models-dev-client.js
146457
- import fs22 from "fs/promises";
146738
+ import fs23 from "fs/promises";
146458
146739
  import { existsSync as existsSync4 } from "fs";
146459
- import path35 from "path";
146740
+ import path36 from "path";
146460
146741
  function getModelsDevClient() {
146461
146742
  if (!clientInstance) {
146462
146743
  clientInstance = new ModelsDevClient;
@@ -146476,7 +146757,7 @@ var init_models_dev_client = __esm(() => {
146476
146757
  memoryCacheTimestamp = 0;
146477
146758
  getLocalCachePath() {
146478
146759
  const dataDir = config2.get("dataDir");
146479
- return path35.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
146760
+ return path36.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
146480
146761
  }
146481
146762
  async loadLocalCache() {
146482
146763
  const cachePath = this.getLocalCachePath();
@@ -146484,7 +146765,7 @@ var init_models_dev_client = __esm(() => {
146484
146765
  if (!existsSync4(cachePath)) {
146485
146766
  return null;
146486
146767
  }
146487
- const content = await fs22.readFile(cachePath, "utf-8");
146768
+ const content = await fs23.readFile(cachePath, "utf-8");
146488
146769
  const data = JSON.parse(content);
146489
146770
  const age = Date.now() - data.timestamp;
146490
146771
  if (age > ModelsDevClient.LOCAL_CACHE_TTL) {
@@ -146511,21 +146792,22 @@ var init_models_dev_client = __esm(() => {
146511
146792
  async saveLocalCache(models) {
146512
146793
  const cachePath = this.getLocalCachePath();
146513
146794
  try {
146514
- const dir = path35.dirname(cachePath);
146515
- await fs22.mkdir(dir, { recursive: true });
146795
+ const dir = path36.dirname(cachePath);
146796
+ await fs23.mkdir(dir, { recursive: true });
146516
146797
  const data = {
146517
146798
  timestamp: Date.now(),
146518
146799
  version: "1.0.0",
146519
146800
  models: Object.fromEntries(models)
146520
146801
  };
146521
- await fs22.writeFile(cachePath, JSON.stringify(data), "utf-8");
146802
+ await fs23.writeFile(cachePath, JSON.stringify(data), "utf-8");
146522
146803
  logger.debug("Saved pricing to local cache", {
146523
146804
  models: models.size,
146524
146805
  path: cachePath
146525
146806
  });
146526
146807
  } catch (error51) {
146527
- logger.warn("Failed to save local pricing cache", {
146528
- error: error51.message
146808
+ logger.warn("ModelsDevClient: failed to save local pricing cache", {
146809
+ path: cachePath,
146810
+ error: error51
146529
146811
  });
146530
146812
  }
146531
146813
  }
@@ -146747,7 +147029,7 @@ var init_models_dev_client = __esm(() => {
146747
147029
  return value;
146748
147030
  }
146749
147031
  }
146750
- logger.warn(`Model pricing not found: ${modelId}`);
147032
+ logger.warn("ModelsDevClient: model pricing not found", { modelId });
146751
147033
  return null;
146752
147034
  }
146753
147035
  async searchModels(query) {
@@ -146847,12 +147129,13 @@ var init_models_dev_client = __esm(() => {
146847
147129
  const cachePath = this.getLocalCachePath();
146848
147130
  try {
146849
147131
  if (existsSync4(cachePath)) {
146850
- await fs22.unlink(cachePath);
147132
+ await fs23.unlink(cachePath);
146851
147133
  logger.debug("Local pricing cache file deleted");
146852
147134
  }
146853
147135
  } catch (error51) {
146854
- logger.warn("Failed to delete local pricing cache", {
146855
- error: error51.message
147136
+ logger.warn("ModelsDevClient: failed to delete local pricing cache", {
147137
+ path: cachePath,
147138
+ error: error51
146856
147139
  });
146857
147140
  }
146858
147141
  }
@@ -147508,9 +147791,10 @@ class SearchSessionHook {
147508
147791
  });
147509
147792
  } catch (err) {
147510
147793
  logger.warn("SearchSessionHook: store failed (best-effort)", {
147511
- error: err.message,
147512
147794
  projectId,
147513
- query: query.slice(0, 60)
147795
+ sessionId,
147796
+ query: query.slice(0, 60),
147797
+ error: err
147514
147798
  });
147515
147799
  }
147516
147800
  }
@@ -147586,8 +147870,10 @@ class CoRetrievalHook {
147586
147870
  peers = await this.findPeers(memoryId, projectId, sessionId);
147587
147871
  } catch (err) {
147588
147872
  logger.warn("CoRetrievalHook: peer lookup failed", {
147589
- error: err.message,
147590
- memoryId
147873
+ projectId,
147874
+ sessionId,
147875
+ memoryId,
147876
+ error: err
147591
147877
  });
147592
147878
  return;
147593
147879
  }
@@ -152402,33 +152688,33 @@ var require_URL = __commonJS((exports, module) => {
152402
152688
  else
152403
152689
  return basepath.substring(0, lastslash + 1) + refpath;
152404
152690
  }
152405
- function remove_dot_segments(path36) {
152406
- if (!path36)
152407
- return path36;
152691
+ function remove_dot_segments(path37) {
152692
+ if (!path37)
152693
+ return path37;
152408
152694
  var output = "";
152409
- while (path36.length > 0) {
152410
- if (path36 === "." || path36 === "..") {
152411
- path36 = "";
152695
+ while (path37.length > 0) {
152696
+ if (path37 === "." || path37 === "..") {
152697
+ path37 = "";
152412
152698
  break;
152413
152699
  }
152414
- var twochars = path36.substring(0, 2);
152415
- var threechars = path36.substring(0, 3);
152416
- var fourchars = path36.substring(0, 4);
152700
+ var twochars = path37.substring(0, 2);
152701
+ var threechars = path37.substring(0, 3);
152702
+ var fourchars = path37.substring(0, 4);
152417
152703
  if (threechars === "../") {
152418
- path36 = path36.substring(3);
152704
+ path37 = path37.substring(3);
152419
152705
  } else if (twochars === "./") {
152420
- path36 = path36.substring(2);
152706
+ path37 = path37.substring(2);
152421
152707
  } else if (threechars === "/./") {
152422
- path36 = "/" + path36.substring(3);
152423
- } else if (twochars === "/." && path36.length === 2) {
152424
- path36 = "/";
152425
- } else if (fourchars === "/../" || threechars === "/.." && path36.length === 3) {
152426
- path36 = "/" + path36.substring(4);
152708
+ path37 = "/" + path37.substring(3);
152709
+ } else if (twochars === "/." && path37.length === 2) {
152710
+ path37 = "/";
152711
+ } else if (fourchars === "/../" || threechars === "/.." && path37.length === 3) {
152712
+ path37 = "/" + path37.substring(4);
152427
152713
  output = output.replace(/\/?[^\/]*$/, "");
152428
152714
  } else {
152429
- var segment = path36.match(/(\/?([^\/]*))/)[0];
152715
+ var segment = path37.match(/(\/?([^\/]*))/)[0];
152430
152716
  output += segment;
152431
- path36 = path36.substring(segment.length);
152717
+ path37 = path37.substring(segment.length);
152432
152718
  }
152433
152719
  }
152434
152720
  return output;
@@ -164498,21 +164784,21 @@ function jsonToKeyPathChunks(value, label = "$") {
164498
164784
  walk(value, label, out);
164499
164785
  return out;
164500
164786
  }
164501
- function walk(val, path36, out) {
164787
+ function walk(val, path37, out) {
164502
164788
  if (val === null || val === undefined)
164503
164789
  return;
164504
164790
  if (Array.isArray(val)) {
164505
164791
  if (val.length === 0) {
164506
- out.push({ path: path36, content: `**${path36}** = _[]_` });
164792
+ out.push({ path: path37, content: `**${path37}** = _[]_` });
164507
164793
  return;
164508
164794
  }
164509
164795
  if (val.every((v) => v !== null && typeof v === "object")) {
164510
- val.forEach((v, i) => walk(v, `${path36}[${i}]`, out));
164796
+ val.forEach((v, i) => walk(v, `${path37}[${i}]`, out));
164511
164797
  return;
164512
164798
  }
164513
164799
  const items = val.map((v) => `- \`${String(v)}\``).join(`
164514
164800
  `);
164515
- out.push({ path: path36, content: `**${path36}**
164801
+ out.push({ path: path37, content: `**${path37}**
164516
164802
 
164517
164803
  ${items}` });
164518
164804
  return;
@@ -164520,16 +164806,16 @@ ${items}` });
164520
164806
  if (typeof val === "object") {
164521
164807
  const entries = Object.entries(val);
164522
164808
  if (entries.length === 0) {
164523
- out.push({ path: path36, content: `**${path36}** = _{}_` });
164809
+ out.push({ path: path37, content: `**${path37}** = _{}_` });
164524
164810
  return;
164525
164811
  }
164526
164812
  for (const [k, v] of entries) {
164527
164813
  const safeKey = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k);
164528
- walk(v, `${path36}.${safeKey}`, out);
164814
+ walk(v, `${path37}.${safeKey}`, out);
164529
164815
  }
164530
164816
  return;
164531
164817
  }
164532
- out.push({ path: path36, content: `**${path36}** = \`${String(val)}\`` });
164818
+ out.push({ path: path37, content: `**${path37}** = \`${String(val)}\`` });
164533
164819
  }
164534
164820
  var gfm, STRIP_SELECTORS, tdCache = null;
164535
164821
  var init_html_to_md = __esm(() => {
@@ -164633,6 +164919,7 @@ async function fetchAndConvertOne(url2, deps, opts = {}) {
164633
164919
  } catch (err) {
164634
164920
  const msg = err instanceof Error ? err.message : String(err);
164635
164921
  logger.error("fetch_and_index indexChunk failed", err, {
164922
+ projectId,
164636
164923
  url: url2,
164637
164924
  chunkId: chunk.id
164638
164925
  });
@@ -164823,6 +165110,7 @@ class WebController {
164823
165110
  return s.value;
164824
165111
  const msg = s.reason instanceof Error ? s.reason.message : String(s.reason);
164825
165112
  logger.error("fetch_and_index job rejected", s.reason, {
165113
+ projectId,
164826
165114
  url: batch[i].url
164827
165115
  });
164828
165116
  return { kind: "error", url: batch[i].url, error: msg };
@@ -165011,7 +165299,7 @@ class OperationLogRepositoryPg {
165011
165299
  op: input.op,
165012
165300
  projectId,
165013
165301
  result: input.result,
165014
- error: err.message
165302
+ error: err
165015
165303
  });
165016
165304
  }
165017
165305
  }
@@ -165224,9 +165512,11 @@ class HookService {
165224
165512
  });
165225
165513
  this.bridge.maybeRun(obs.projectId);
165226
165514
  } catch (e) {
165227
- logger.warn("observation persist failed", {
165515
+ logger.warn("HookService: observation persist failed", {
165228
165516
  id: obs.id,
165229
- error: e.message
165517
+ projectId: obs.projectId,
165518
+ sessionId: obs.sessionId,
165519
+ error: e
165230
165520
  });
165231
165521
  }
165232
165522
  });
@@ -165292,8 +165582,8 @@ var init_hook_service = __esm(() => {
165292
165582
 
165293
165583
  // ../../packages/core/dist/services/bootstrap/bootstrap-service.js
165294
165584
  import { randomUUID as randomUUID9 } from "crypto";
165295
- import fs23 from "fs";
165296
- import path36 from "path";
165585
+ import fs24 from "fs";
165586
+ import path37 from "path";
165297
165587
  import { spawn as spawn2 } from "child_process";
165298
165588
  function readBootstrapConfig() {
165299
165589
  try {
@@ -165352,7 +165642,7 @@ class BootstrapService {
165352
165642
  } catch (e) {
165353
165643
  logger.warn("bootstrap: marker check threw (continuing)", {
165354
165644
  projectId,
165355
- error: e.message
165645
+ error: e
165356
165646
  });
165357
165647
  }
165358
165648
  } else if (!cfg.refreshEnabled) {
@@ -165400,7 +165690,7 @@ class BootstrapService {
165400
165690
  } catch (e) {
165401
165691
  logger.warn("bootstrap: storeSeeds failed (silent)", {
165402
165692
  projectId,
165403
- error: e.message
165693
+ error: e
165404
165694
  });
165405
165695
  return { ...noopResult("insert-failed"), signalCount, source };
165406
165696
  }
@@ -165453,9 +165743,9 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
165453
165743
  }
165454
165744
  try {
165455
165745
  for (const name26 of README_CANDIDATES) {
165456
- const p = path36.join(projectRoot, name26);
165457
- if (fs23.existsSync(p) && fs23.statSync(p).isFile()) {
165458
- const buf = fs23.readFileSync(p);
165746
+ const p = path37.join(projectRoot, name26);
165747
+ if (fs24.existsSync(p) && fs24.statSync(p).isFile()) {
165748
+ const buf = fs24.readFileSync(p);
165459
165749
  signals.readme = buf.slice(0, MAX_README_BYTES).toString("utf8");
165460
165750
  break;
165461
165751
  }
@@ -165464,14 +165754,14 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
165464
165754
  logger.debug("bootstrap scan: README read failed", { error: e.message });
165465
165755
  }
165466
165756
  try {
165467
- const docsDir = path36.join(projectRoot, "docs");
165468
- if (fs23.existsSync(docsDir) && fs23.statSync(docsDir).isDirectory()) {
165757
+ const docsDir = path37.join(projectRoot, "docs");
165758
+ if (fs24.existsSync(docsDir) && fs24.statSync(docsDir).isDirectory()) {
165469
165759
  const entries = walkMarkdown(docsDir).slice(0, MAX_DOCS);
165470
165760
  for (const rel of entries) {
165471
165761
  try {
165472
- const buf = fs23.readFileSync(rel);
165762
+ const buf = fs24.readFileSync(rel);
165473
165763
  signals.docs.push({
165474
- path: path36.relative(projectRoot, rel),
165764
+ path: path37.relative(projectRoot, rel),
165475
165765
  snippet: buf.slice(0, MAX_DOC_BYTES).toString("utf8")
165476
165766
  });
165477
165767
  } catch {}
@@ -165482,10 +165772,10 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
165482
165772
  }
165483
165773
  try {
165484
165774
  for (const name26 of MANIFEST_FILES) {
165485
- const p = path36.join(projectRoot, name26);
165486
- if (!fs23.existsSync(p) || !fs23.statSync(p).isFile())
165775
+ const p = path37.join(projectRoot, name26);
165776
+ if (!fs24.existsSync(p) || !fs24.statSync(p).isFile())
165487
165777
  continue;
165488
- const raw2 = fs23.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
165778
+ const raw2 = fs24.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
165489
165779
  const kind = name26;
165490
165780
  if (name26 === "package.json") {
165491
165781
  try {
@@ -165525,12 +165815,12 @@ function walkMarkdown(dir) {
165525
165815
  const cur = stack.pop();
165526
165816
  let entries;
165527
165817
  try {
165528
- entries = fs23.readdirSync(cur, { withFileTypes: true });
165818
+ entries = fs24.readdirSync(cur, { withFileTypes: true });
165529
165819
  } catch {
165530
165820
  continue;
165531
165821
  }
165532
165822
  for (const e of entries) {
165533
- const full = path36.join(cur, e.name);
165823
+ const full = path37.join(cur, e.name);
165534
165824
  if (e.isDirectory()) {
165535
165825
  if (e.name === "node_modules" || e.name.startsWith("."))
165536
165826
  continue;
@@ -165553,7 +165843,7 @@ async function summarizeWithLlm(signals, surface, maxSeedMemories) {
165553
165843
  return { ok: false, reason: "llm disabled" };
165554
165844
  const prompt = buildSummarizePrompt(signals, maxSeedMemories);
165555
165845
  try {
165556
- const res = await surface.object(prompt, SeedMemoriesSchema, { modelRole: "code" });
165846
+ const res = await surface.object(prompt, SeedMemoriesSchema, { label: "bootstrap-seed", modelRole: "code" });
165557
165847
  if (!res.ok || !res.value) {
165558
165848
  return { ok: false, reason: res.error || "llm returned no value" };
165559
165849
  }
@@ -166236,7 +166526,7 @@ function formatMemoryContent(record3) {
166236
166526
  }
166237
166527
  async function polishSummary(surface, input) {
166238
166528
  const prompt = buildPolishPrompt(input);
166239
- const res = await surface.object(prompt, HandoffSummarySchema);
166529
+ const res = await surface.object(prompt, HandoffSummarySchema, { label: "handoff-summary" });
166240
166530
  if (!res.ok || !res.value || !res.value.summary)
166241
166531
  return null;
166242
166532
  return res.value.summary;
@@ -169060,7 +169350,7 @@ class StdioServerTransport {
169060
169350
  }
169061
169351
 
169062
169352
  // src/index.ts
169063
- import fs26 from "fs/promises";
169353
+ import fs27 from "fs/promises";
169064
169354
 
169065
169355
  // src/api-client.ts
169066
169356
  init_config();
@@ -169170,8 +169460,8 @@ init_dist();
169170
169460
  init_dist();
169171
169461
  init_dist15();
169172
169462
  init_dist();
169173
- import fs24 from "fs/promises";
169174
- import path37 from "path";
169463
+ import fs25 from "fs/promises";
169464
+ import path38 from "path";
169175
169465
  var _indexProjectTool = null;
169176
169466
  function indexProjectTool() {
169177
169467
  if (!_indexProjectTool)
@@ -169474,8 +169764,8 @@ class EmbeddedApiClient {
169474
169764
  } else {
169475
169765
  end = start + 20;
169476
169766
  }
169477
- const absolutePath = path37.join(workspace.project_path, file2);
169478
- const content = await fs24.readFile(absolutePath, "utf-8");
169767
+ const absolutePath = path38.join(workspace.project_path, file2);
169768
+ const content = await fs25.readFile(absolutePath, "utf-8");
169479
169769
  const lines = content.split(/\r?\n/);
169480
169770
  const slice = lines.slice(start - 1, Math.min(lines.length, end));
169481
169771
  const formatted = slice.map((text3, idx) => ({ lineNumber: start + idx, content: text3 }));
@@ -169730,22 +170020,22 @@ class EmbeddedApiClient {
169730
170020
  async uploadAndIndex(params) {
169731
170021
  const rawBase = params.projectId || params.projectPath.replace(/\\/g, "/").split("/").filter(Boolean).pop() || "default";
169732
170022
  const finalProjectId = rawBase.replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 128);
169733
- const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path37.join(getGlobalDataDir(), "uploads");
169734
- const stagingDir = path37.resolve(uploadRoot, finalProjectId);
169735
- await fs24.rm(stagingDir, { recursive: true, force: true });
169736
- await fs24.mkdir(stagingDir, { recursive: true });
170023
+ const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path38.join(getGlobalDataDir(), "uploads");
170024
+ const stagingDir = path38.resolve(uploadRoot, finalProjectId);
170025
+ await fs25.rm(stagingDir, { recursive: true, force: true });
170026
+ await fs25.mkdir(stagingDir, { recursive: true });
169737
170027
  const WRITE_BATCH = 20;
169738
170028
  for (let i = 0;i < params.files.length; i += WRITE_BATCH) {
169739
170029
  await Promise.all(params.files.slice(i, i + WRITE_BATCH).map(async (file2) => {
169740
- if (path37.isAbsolute(file2.relativePath) || file2.relativePath.includes("..")) {
170030
+ if (path38.isAbsolute(file2.relativePath) || file2.relativePath.includes("..")) {
169741
170031
  throw new Error(`Invalid file path: ${file2.relativePath}`);
169742
170032
  }
169743
- const dest = path37.resolve(stagingDir, file2.relativePath.replace(/\//g, path37.sep));
169744
- if (!dest.startsWith(stagingDir + path37.sep)) {
170033
+ const dest = path38.resolve(stagingDir, file2.relativePath.replace(/\//g, path38.sep));
170034
+ if (!dest.startsWith(stagingDir + path38.sep)) {
169745
170035
  throw new Error(`Path escapes staging directory: ${file2.relativePath}`);
169746
170036
  }
169747
- await fs24.mkdir(path37.dirname(dest), { recursive: true });
169748
- await fs24.writeFile(dest, file2.content, "utf-8");
170037
+ await fs25.mkdir(path38.dirname(dest), { recursive: true });
170038
+ await fs25.writeFile(dest, file2.content, "utf-8");
169749
170039
  }));
169750
170040
  }
169751
170041
  return await indexProjectTool().handle({
@@ -169791,7 +170081,10 @@ class EmbeddedApiClient {
169791
170081
  const rows = filtered.slice(offset, offset + limit);
169792
170082
  return { success: true, data: { memories: rows, total, limit, offset } };
169793
170083
  } catch (error51) {
169794
- logger.error("Failed to list memories (embedded)", error51);
170084
+ logger.error("Failed to list memories (embedded)", error51, {
170085
+ projectId: body.projectId,
170086
+ sessionId: body.sessionId
170087
+ });
169795
170088
  return { success: false, error: `Failed to list memories: ${error51.message}` };
169796
170089
  }
169797
170090
  }
@@ -170242,8 +170535,8 @@ class EmbeddedApiClient {
170242
170535
 
170243
170536
  // src/file-collector.ts
170244
170537
  init_config();
170245
- import fs25 from "fs/promises";
170246
- import path38 from "path";
170538
+ import fs26 from "fs/promises";
170539
+ import path39 from "path";
170247
170540
  var SKIP_DIRS = new Set([
170248
170541
  "node_modules",
170249
170542
  ".git",
@@ -170284,7 +170577,7 @@ async function walk2(root2, dir, files, state, allowed) {
170284
170577
  return;
170285
170578
  let entries;
170286
170579
  try {
170287
- entries = await fs25.readdir(dir, { withFileTypes: true });
170580
+ entries = await fs26.readdir(dir, { withFileTypes: true });
170288
170581
  } catch {
170289
170582
  return;
170290
170583
  }
@@ -170293,22 +170586,22 @@ async function walk2(root2, dir, files, state, allowed) {
170293
170586
  break;
170294
170587
  if (entry2.isDirectory()) {
170295
170588
  if (!SKIP_DIRS.has(entry2.name) && !entry2.name.startsWith(".")) {
170296
- await walk2(root2, path38.join(dir, entry2.name), files, state, allowed);
170589
+ await walk2(root2, path39.join(dir, entry2.name), files, state, allowed);
170297
170590
  }
170298
170591
  } else if (entry2.isFile()) {
170299
- const ext2 = path38.extname(entry2.name).toLowerCase();
170592
+ const ext2 = path39.extname(entry2.name).toLowerCase();
170300
170593
  if (!allowed.has(ext2))
170301
170594
  continue;
170302
- const fullPath = path38.join(dir, entry2.name);
170595
+ const fullPath = path39.join(dir, entry2.name);
170303
170596
  try {
170304
- const stat = await fs25.stat(fullPath);
170597
+ const stat = await fs26.stat(fullPath);
170305
170598
  if (stat.size > MAX_FILE_BYTES)
170306
170599
  continue;
170307
170600
  if (state.totalBytes + stat.size > MAX_TOTAL_BYTES)
170308
170601
  continue;
170309
- const content = await fs25.readFile(fullPath, "utf-8");
170602
+ const content = await fs26.readFile(fullPath, "utf-8");
170310
170603
  state.totalBytes += stat.size;
170311
- const relativePath = path38.relative(root2, fullPath).split(path38.sep).join("/");
170604
+ const relativePath = path39.relative(root2, fullPath).split(path39.sep).join("/");
170312
170605
  files.push({ relativePath, content });
170313
170606
  } catch {}
170314
170607
  }
@@ -172291,7 +172584,7 @@ class McpProxyServer {
172291
172584
  return textContent(JSON.stringify({ success: false, error: "projectPath is required" }));
172292
172585
  }
172293
172586
  try {
172294
- if (!(await fs26.stat(projectPath2)).isDirectory()) {
172587
+ if (!(await fs27.stat(projectPath2)).isDirectory()) {
172295
172588
  return textContent(JSON.stringify({ success: false, error: `${projectPath2} is not a directory` }));
172296
172589
  }
172297
172590
  } catch {