@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
@@ -997,7 +997,7 @@ function getConfigForEnv() {
997
997
  } else {
998
998
  console.error(`[getConfigForEnv] embedding.provider "${provider}" has no env-projection branch \u2014 no embedding env vars were set`);
999
999
  }
1000
- env.LOG_LEVEL = config.logging.level;
1000
+ env.MASSA_AI_LOG_LEVEL = config.logging.level;
1001
1001
  env.ENABLE_METRICS = String(config.logging.enableMetrics);
1002
1002
  return env;
1003
1003
  }
@@ -1571,7 +1571,7 @@ var init_config = __esm(() => {
1571
1571
  corsOrigins: envList("MASSA_AI_API_CORS_ORIGINS", fileConfig.security?.corsOrigins ?? [])
1572
1572
  },
1573
1573
  logging: {
1574
- level: process.env.LOG_LEVEL || fileConfig.logging?.level || "info",
1574
+ level: process.env.MASSA_AI_LOG_LEVEL || fileConfig.logging?.level || "info",
1575
1575
  enableMetrics: process.env.ENABLE_METRICS === "true" || process.env.ENABLE_METRICS === undefined && !!fileConfig.logging?.enableMetrics,
1576
1576
  file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || path4.join(resolvedDataDir, "logs", "massa-ai.log"),
1577
1577
  enableFileSink: envBool("MASSA_AI_LOG_ENABLE_FILE_SINK", fileConfig.logging?.enableFileSink ?? true),
@@ -1904,6 +1904,32 @@ var init_log_buffer = __esm(() => {
1904
1904
  });
1905
1905
 
1906
1906
  // ../../packages/shared/dist/utils/logger.js
1907
+ function formatAgo(ms) {
1908
+ const totalSeconds = Math.floor(ms / 1000);
1909
+ if (totalSeconds < 60)
1910
+ return `${totalSeconds}s`;
1911
+ return `${Math.floor(totalSeconds / 60)}m`;
1912
+ }
1913
+ function capErrorText(value) {
1914
+ if (value.length <= MAX_ERROR_TEXT_CHARS)
1915
+ return value;
1916
+ const truncatedChars = value.length - MAX_ERROR_TEXT_CHARS;
1917
+ return `${value.slice(0, MAX_ERROR_TEXT_CHARS)}\u2026(truncated ${truncatedChars} chars)`;
1918
+ }
1919
+ function pickErrorFields(err, includeStack) {
1920
+ const out = { name: err.name, message: capErrorText(err.message) };
1921
+ if (includeStack)
1922
+ out.stack = err.stack;
1923
+ const code = err.code;
1924
+ if (code !== undefined)
1925
+ out.code = code;
1926
+ const cause = err.cause;
1927
+ if (cause !== undefined) {
1928
+ out.cause = capErrorText(cause instanceof Error ? cause.message : String(cause));
1929
+ }
1930
+ return out;
1931
+ }
1932
+
1907
1933
  class Logger {
1908
1934
  _level;
1909
1935
  _enableMetrics;
@@ -1912,6 +1938,7 @@ class Logger {
1912
1938
  _maxFileSizeBytes;
1913
1939
  _maxFiles;
1914
1940
  _initialized = false;
1941
+ repeats = new Map;
1915
1942
  constructor() {}
1916
1943
  ensureInitialized() {
1917
1944
  if (!this._initialized) {
@@ -1972,13 +1999,70 @@ class Logger {
1972
1999
  shouldLog(level) {
1973
2000
  return level >= this.level;
1974
2001
  }
2002
+ serializeMetaErrors(meta) {
2003
+ if (!meta)
2004
+ return meta;
2005
+ let out;
2006
+ for (const [key, value] of Object.entries(meta)) {
2007
+ if (value instanceof Error) {
2008
+ if (!out)
2009
+ out = { ...meta };
2010
+ out[key] = pickErrorFields(value, false);
2011
+ }
2012
+ }
2013
+ return out ?? meta;
2014
+ }
2015
+ applyRepeatAccounting(level, message, meta) {
2016
+ if (level !== LogLevel.WARN && level !== LogLevel.ERROR)
2017
+ return meta;
2018
+ const label = typeof meta?.label === "string" ? meta.label : "";
2019
+ const key = `${level}|${message}|${label}`;
2020
+ const now = Date.now();
2021
+ const existing = this.repeats.get(key);
2022
+ if (!existing || now - existing.firstSeenAt > REPEAT_WINDOW_MS) {
2023
+ if (this.repeats.size >= MAX_REPEAT_KEYS)
2024
+ this.repeats.clear();
2025
+ this.repeats.set(key, { firstSeenAt: now, count: 1 });
2026
+ return meta;
2027
+ }
2028
+ existing.count += 1;
2029
+ return {
2030
+ ...meta,
2031
+ occurrences: existing.count,
2032
+ firstSeenAgo: formatAgo(now - existing.firstSeenAt)
2033
+ };
2034
+ }
2035
+ _resetRepeatsForTesting() {
2036
+ this.repeats.clear();
2037
+ }
2038
+ safeStringifyMeta(meta) {
2039
+ const seen = new WeakSet;
2040
+ try {
2041
+ return JSON.stringify(meta, (_key, value) => {
2042
+ if (typeof value === "bigint")
2043
+ return value.toString();
2044
+ if (typeof value === "object" && value !== null) {
2045
+ if (seen.has(value))
2046
+ return "[Circular]";
2047
+ seen.add(value);
2048
+ }
2049
+ return value;
2050
+ });
2051
+ } catch (err) {
2052
+ return JSON.stringify({
2053
+ metaUnserializable: err instanceof Error ? err.message : String(err)
2054
+ });
2055
+ }
2056
+ }
1975
2057
  formatMessage(level, message, meta, timestamp = new Date().toISOString()) {
1976
- const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
2058
+ const metaStr = meta ? ` ${this.safeStringifyMeta(meta)}` : "";
1977
2059
  return `[${timestamp}] [${level}] ${message}${metaStr}`;
1978
2060
  }
1979
2061
  emit(level, message, meta) {
2062
+ const serializedMeta = this.serializeMetaErrors(meta);
2063
+ const finalMeta = this.applyRepeatAccounting(level, message, serializedMeta);
1980
2064
  const ts = new Date().toISOString();
1981
- const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, meta, ts);
2065
+ const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, finalMeta, ts);
1982
2066
  console.error(line);
1983
2067
  if (this.enableFileSink) {
1984
2068
  const filePath = this.logFilePath;
@@ -1990,7 +2074,7 @@ class Logger {
1990
2074
  ts,
1991
2075
  level: LOG_LEVEL_BUFFER_TAGS[level],
1992
2076
  message,
1993
- ...meta ? { meta } : {}
2077
+ ...finalMeta ? { meta: finalMeta } : {}
1994
2078
  });
1995
2079
  }
1996
2080
  debug(message, meta) {
@@ -2012,11 +2096,7 @@ class Logger {
2012
2096
  if (this.shouldLog(LogLevel.ERROR)) {
2013
2097
  const errorMeta = error ? {
2014
2098
  ...meta,
2015
- error: {
2016
- name: error.name,
2017
- message: error.message,
2018
- stack: error.stack
2019
- }
2099
+ error: error instanceof Error ? pickErrorFields(error, true) : { message: String(error) }
2020
2100
  } : meta;
2021
2101
  this.emit(LogLevel.ERROR, message, errorMeta);
2022
2102
  }
@@ -2047,7 +2127,7 @@ class Logger {
2047
2127
  return childLogger;
2048
2128
  }
2049
2129
  }
2050
- var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, logger;
2130
+ var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, REPEAT_WINDOW_MS, MAX_REPEAT_KEYS = 500, MAX_ERROR_TEXT_CHARS = 300, logger;
2051
2131
  var init_logger = __esm(() => {
2052
2132
  init_config();
2053
2133
  init_log_sink();
@@ -2070,6 +2150,7 @@ var init_logger = __esm(() => {
2070
2150
  [LogLevel.WARN]: "warn",
2071
2151
  [LogLevel.ERROR]: "error"
2072
2152
  };
2153
+ REPEAT_WINDOW_MS = 15 * 60 * 1000;
2073
2154
  logger = new Logger;
2074
2155
  });
2075
2156
 
@@ -2125,8 +2206,9 @@ var init_metrics = __esm(() => {
2125
2206
  }
2126
2207
  } catch (error) {
2127
2208
  const err = error instanceof Error ? error : new Error(String(error));
2128
- logger.warn(`Failed to fetch pricing for ${modelId}`, {
2129
- error: { name: err.name, message: err.message }
2209
+ logger.warn("MetricsCollector: failed to fetch pricing", {
2210
+ modelId,
2211
+ error: err
2130
2212
  });
2131
2213
  }
2132
2214
  const fallback = FALLBACK_PRICING[modelId];
@@ -2134,7 +2216,7 @@ var init_metrics = __esm(() => {
2134
2216
  logger.debug(`Using fallback pricing for ${modelId}`);
2135
2217
  return fallback;
2136
2218
  }
2137
- logger.warn(`Unknown model ${modelId}, using gpt-4 pricing as default`);
2219
+ logger.warn("MetricsCollector: unknown model, using gpt-4 pricing as default", { modelId });
2138
2220
  return FALLBACK_PRICING["gpt-4"];
2139
2221
  }
2140
2222
  static calculateCost(inputTokens, outputTokens, model) {
@@ -2313,7 +2395,9 @@ class SmartRateLimiter {
2313
2395
  const hasRequestCapacity = this.requestLimiter.tryConsume(1);
2314
2396
  const hasTokenCapacity = this.tokenLimiter.tryConsume(estimatedTokens);
2315
2397
  if (!hasRequestCapacity) {
2316
- logger.warn("Request rate limit exceeded");
2398
+ logger.warn("Request rate limit exceeded", {
2399
+ availableTokens: this.requestLimiter.getAvailableTokens()
2400
+ });
2317
2401
  return false;
2318
2402
  }
2319
2403
  if (!hasTokenCapacity) {
@@ -2365,12 +2449,12 @@ import path6 from "path";
2365
2449
  function isHost(v) {
2366
2450
  return typeof v === "string" && HOSTS.includes(v);
2367
2451
  }
2368
- function fileLayout(host, activeDir, activeGlob, variantsRoot) {
2452
+ function fileLayout(host, activeDir, activeExt, variantsRoot) {
2369
2453
  return {
2370
2454
  host,
2371
2455
  route: "files",
2372
2456
  activeDir,
2373
- activeGlob,
2457
+ activeExt,
2374
2458
  variantsRoot,
2375
2459
  variantDir: (profile) => path6.join(variantsRoot, profile)
2376
2460
  };
@@ -2384,19 +2468,19 @@ function resolveHostLayout(host, opts = {}) {
2384
2468
  case "claude": {
2385
2469
  const marketplaceRoot = opts.marketplaceRoot?.claude;
2386
2470
  if (override === undefined && marketplaceRoot !== undefined) {
2387
- return fileLayout(host, path6.join(marketplaceRoot, "agents"), "massa-ai-*.md", path6.join(marketplaceRoot, "agent-profiles"));
2471
+ return fileLayout(host, path6.join(marketplaceRoot, "agents"), ".md", path6.join(marketplaceRoot, "agent-profiles"));
2388
2472
  }
2389
2473
  const root = override ?? path6.join(targetHome, ".claude");
2390
- return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.md", path6.join(root, "massa-ai", "agent-profiles"));
2474
+ return fileLayout(host, path6.join(root, "agents"), ".md", path6.join(root, "massa-ai", "agent-profiles"));
2391
2475
  }
2392
2476
  case "codex": {
2393
2477
  const root = override ?? path6.join(targetHome, ".codex");
2394
- return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.toml", path6.join(root, "massa-ai", "agent-profiles"));
2478
+ return fileLayout(host, path6.join(root, "agents"), ".toml", path6.join(root, "massa-ai", "agent-profiles"));
2395
2479
  }
2396
2480
  case "opencode": {
2397
2481
  const root = override ?? path6.join(targetHome, ".config", "opencode");
2398
2482
  const pluginsDir = path6.join(root, "plugins", "massa-ai");
2399
- return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.md", path6.join(pluginsDir, "agent-profiles"));
2483
+ return fileLayout(host, path6.join(root, "agents"), ".md", path6.join(pluginsDir, "agent-profiles"));
2400
2484
  }
2401
2485
  }
2402
2486
  }
@@ -2730,6 +2814,90 @@ function readInstalledPluginVersion(opts = {}) {
2730
2814
  var DEFAULT_PLUGIN_KEY = "massa-ai@massa-ai";
2731
2815
  var init_claude_marketplace = () => {};
2732
2816
 
2817
+ // ../../packages/shared/dist/profile-switch/ownership.js
2818
+ import fs6 from "fs";
2819
+ import path10 from "path";
2820
+ function isLegacyAgentName(fileName) {
2821
+ const base = path10.basename(fileName).replace(/\.[^.]*$/, "");
2822
+ return base.startsWith("massa-ai-") && LEGACY_AGENT_NAMES.includes(base.slice("massa-ai-".length));
2823
+ }
2824
+ function hasOwnedMarker(content) {
2825
+ const lines = content.split(`
2826
+ `);
2827
+ if (lines[0] !== "---")
2828
+ return false;
2829
+ const close = lines.indexOf("---", 1);
2830
+ return close !== -1 && lines[close + 1] === OWNED_MARKER_MD;
2831
+ }
2832
+ function isRegularFile(filePath) {
2833
+ try {
2834
+ return fs6.lstatSync(filePath).isFile();
2835
+ } catch {
2836
+ return false;
2837
+ }
2838
+ }
2839
+ function isOwnedAgentFile(filePath) {
2840
+ if (!isRegularFile(filePath))
2841
+ return false;
2842
+ if (!filePath.endsWith(".toml") && isLegacyAgentName(filePath))
2843
+ return true;
2844
+ let content;
2845
+ try {
2846
+ content = fs6.readFileSync(filePath, "utf8");
2847
+ } catch {
2848
+ return false;
2849
+ }
2850
+ if (filePath.endsWith(".toml"))
2851
+ return content.split(`
2852
+ `)[0] === OWNED_MARKER_TOML;
2853
+ return hasOwnedMarker(content);
2854
+ }
2855
+ function isOwnedAgentLink(linkPath) {
2856
+ try {
2857
+ if (!fs6.lstatSync(linkPath).isSymbolicLink())
2858
+ return false;
2859
+ } catch {
2860
+ return false;
2861
+ }
2862
+ if (isLegacyAgentName(linkPath))
2863
+ return true;
2864
+ const base = path10.basename(linkPath);
2865
+ const target = fs6.readlinkSync(linkPath);
2866
+ if (target.endsWith(`/opencode-plugin/agents/${base}`))
2867
+ return true;
2868
+ const escaped = base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2869
+ if (new RegExp(`/plugins/massa-ai/agent-profiles/.*/${escaped}$`).test(target))
2870
+ return true;
2871
+ try {
2872
+ return fs6.statSync(linkPath).isFile() && hasOwnedMarker(fs6.readFileSync(linkPath, "utf8"));
2873
+ } catch {
2874
+ return false;
2875
+ }
2876
+ }
2877
+ var OWNED_MARKER_MD = "<!-- massa-ai-owned: true -->", OWNED_MARKER_TOML = "# massa-ai-owned", LEGACY_AGENT_NAMES;
2878
+ var init_ownership = __esm(() => {
2879
+ LEGACY_AGENT_NAMES = [
2880
+ "architecture-specialist",
2881
+ "audit-specialist",
2882
+ "builder",
2883
+ "context-curator",
2884
+ "designer",
2885
+ "documentation-agent",
2886
+ "furps-analyst",
2887
+ "investigator",
2888
+ "judge",
2889
+ "meta-judge",
2890
+ "mobile-specialist",
2891
+ "navigator",
2892
+ "plan-critic",
2893
+ "planner",
2894
+ "requirements-analyst",
2895
+ "reviewer",
2896
+ "test-engineer",
2897
+ "verification-agent"
2898
+ ];
2899
+ });
2900
+
2733
2901
  // ../../packages/shared/dist/profile-switch/frontmatter.js
2734
2902
  function parseFrontmatter(raw2) {
2735
2903
  const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/.exec(raw2);
@@ -2787,12 +2955,12 @@ function unquoteScalar(s) {
2787
2955
  }
2788
2956
 
2789
2957
  // ../../packages/shared/dist/profile-switch/doctor.js
2790
- import fs6 from "fs";
2958
+ import fs7 from "fs";
2791
2959
  import os6 from "os";
2792
- import path10 from "path";
2960
+ import path11 from "path";
2793
2961
  function readTextFile(filePath) {
2794
2962
  try {
2795
- return fs6.readFileSync(filePath, "utf8");
2963
+ return fs7.readFileSync(filePath, "utf8");
2796
2964
  } catch {
2797
2965
  return null;
2798
2966
  }
@@ -2808,7 +2976,7 @@ function readJsonFile(filePath) {
2808
2976
  }
2809
2977
  }
2810
2978
  function readPluginVersion(pluginRoot) {
2811
- const manifest = readJsonFile(path10.join(pluginRoot, ".claude-plugin", "plugin.json"));
2979
+ const manifest = readJsonFile(path11.join(pluginRoot, ".claude-plugin", "plugin.json"));
2812
2980
  return typeof manifest?.version === "string" ? manifest.version : null;
2813
2981
  }
2814
2982
  function detectEnvOverride(env) {
@@ -2821,19 +2989,19 @@ function detectEnvOverride(env) {
2821
2989
  return null;
2822
2990
  }
2823
2991
  function readRoles(liveRoot, activeProfile) {
2824
- const agentsDir = path10.join(liveRoot, "agents");
2992
+ const agentsDir = path11.join(liveRoot, "agents");
2825
2993
  let entries;
2826
2994
  try {
2827
- entries = fs6.readdirSync(agentsDir, { withFileTypes: true });
2995
+ entries = fs7.readdirSync(agentsDir, { withFileTypes: true });
2828
2996
  } catch {
2829
2997
  return [];
2830
2998
  }
2831
2999
  const roles = [];
2832
3000
  for (const entry of entries) {
2833
- if (!entry.isFile() || !entry.name.startsWith("massa-ai-") || !entry.name.endsWith(".md")) {
3001
+ if (!entry.name.endsWith(".md") || !isOwnedAgentFile(path11.join(agentsDir, entry.name))) {
2834
3002
  continue;
2835
3003
  }
2836
- const activeRaw = readTextFile(path10.join(agentsDir, entry.name));
3004
+ const activeRaw = readTextFile(path11.join(agentsDir, entry.name));
2837
3005
  let model = null;
2838
3006
  let effort = null;
2839
3007
  if (activeRaw !== null) {
@@ -2845,7 +3013,7 @@ function readRoles(liveRoot, activeProfile) {
2845
3013
  }
2846
3014
  let staleVariant = false;
2847
3015
  if (activeProfile && activeRaw !== null) {
2848
- const variantRaw = readTextFile(path10.join(liveRoot, "agent-profiles", activeProfile, entry.name));
3016
+ const variantRaw = readTextFile(path11.join(liveRoot, "agent-profiles", activeProfile, entry.name));
2849
3017
  if (variantRaw !== null) {
2850
3018
  staleVariant = variantRaw !== activeRaw;
2851
3019
  }
@@ -2856,7 +3024,8 @@ function readRoles(liveRoot, activeProfile) {
2856
3024
  }
2857
3025
  function runtimeDriftReport(opts = {}) {
2858
3026
  const targetHome = opts.targetHome ?? os6.homedir();
2859
- const stateFilePath = opts.stateFilePath ?? path10.join(targetHome, ".config", "massa-ai", "install-state.json");
3027
+ const host = opts.host ?? "claude";
3028
+ const stateFilePath = opts.stateFilePath ?? path11.join(targetHome, ".config", "massa-ai", "install-state.json");
2860
3029
  let state = opts.state ?? null;
2861
3030
  if (state === null) {
2862
3031
  try {
@@ -2865,9 +3034,24 @@ function runtimeDriftReport(opts = {}) {
2865
3034
  state = null;
2866
3035
  }
2867
3036
  }
2868
- const platform = state?.platforms?.claude;
3037
+ const platform = state?.platforms?.[host];
2869
3038
  const stateVersion = typeof platform?.plugin?.version === "string" ? platform.plugin.version : null;
2870
3039
  const activeProfile = platform?.modelProfile?.profile ?? null;
3040
+ if (host !== "claude") {
3041
+ return {
3042
+ host,
3043
+ route: "unresolved",
3044
+ liveRoot: null,
3045
+ sourceVersion: null,
3046
+ stateVersion,
3047
+ pinnedVersion: null,
3048
+ activeProfile,
3049
+ roles: [],
3050
+ envOverride: detectEnvOverride(opts.env ?? process.env),
3051
+ versionDrift: false,
3052
+ profileMaterialized: false
3053
+ };
3054
+ }
2871
3055
  const install = resolveClaudeMarketplaceInstall({ targetHome, pluginKey: opts.pluginKey });
2872
3056
  const liveRoot = install?.root ?? null;
2873
3057
  const sourceVersion = liveRoot === null ? null : readPluginVersion(liveRoot);
@@ -2890,13 +3074,14 @@ function runtimeDriftReport(opts = {}) {
2890
3074
  var ENV_OVERRIDE_VARS;
2891
3075
  var init_doctor = __esm(() => {
2892
3076
  init_claude_marketplace();
3077
+ init_ownership();
2893
3078
  init_state();
2894
3079
  ENV_OVERRIDE_VARS = ["CLAUDE_CODE_SUBAGENT_MODEL"];
2895
3080
  });
2896
3081
 
2897
3082
  // ../../packages/shared/dist/profile-switch/engine.js
2898
- import fs7 from "fs";
2899
- import path11 from "path";
3083
+ import fs8 from "fs";
3084
+ import path12 from "path";
2900
3085
  import os7 from "os";
2901
3086
  import crypto4 from "crypto";
2902
3087
  import { execFileSync as execFileSync2 } from "child_process";
@@ -2906,7 +3091,7 @@ function namedError3(name, message) {
2906
3091
  return err;
2907
3092
  }
2908
3093
  function defaultStatePath(targetHome) {
2909
- return path11.join(targetHome, ".config", "massa-ai", "install-state.json");
3094
+ return path12.join(targetHome, ".config", "massa-ai", "install-state.json");
2910
3095
  }
2911
3096
  function resolveCommon(opts) {
2912
3097
  const targetHome = opts.targetHome ?? os7.homedir();
@@ -2917,7 +3102,7 @@ function marketplaceRoots(targetHome, state) {
2917
3102
  return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
2918
3103
  }
2919
3104
  function claudeMarketplaceUnresolvedReason(targetHome) {
2920
- const registryPath = path11.join(targetHome, ".claude", "plugins", "installed_plugins.json");
3105
+ const registryPath = path12.join(targetHome, ".claude", "plugins", "installed_plugins.json");
2921
3106
  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";
2922
3107
  }
2923
3108
  function listProfiles(opts = {}) {
@@ -2939,7 +3124,7 @@ function listProfiles(opts = {}) {
2939
3124
  installed: false,
2940
3125
  skipped: false,
2941
3126
  skipReason: null,
2942
- activeProfile: platform2.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
3127
+ activeProfile: platform2.modelProfile?.profile ?? "balanced",
2943
3128
  bundleVersion: platform2.plugin?.version ?? null,
2944
3129
  availableProfiles: [],
2945
3130
  ...claudeDriftFields(host)
@@ -2958,7 +3143,7 @@ function listProfiles(opts = {}) {
2958
3143
  ...claudeDriftFields(host)
2959
3144
  };
2960
3145
  }
2961
- const installed = fs7.existsSync(layout.activeDir);
3146
+ const installed = fs8.existsSync(layout.activeDir);
2962
3147
  const availableProfiles = listVariantProfiles(layout);
2963
3148
  const platform = state.platforms[host];
2964
3149
  return {
@@ -2966,7 +3151,7 @@ function listProfiles(opts = {}) {
2966
3151
  installed,
2967
3152
  skipped: false,
2968
3153
  skipReason: null,
2969
- activeProfile: platform?.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
3154
+ activeProfile: platform?.modelProfile?.profile ?? "balanced",
2970
3155
  bundleVersion: platform?.plugin?.version ?? null,
2971
3156
  availableProfiles,
2972
3157
  ...claudeDriftFields(host)
@@ -2975,20 +3160,20 @@ function listProfiles(opts = {}) {
2975
3160
  return { hosts };
2976
3161
  }
2977
3162
  function listVariantProfiles(layout) {
2978
- if (!fs7.existsSync(layout.variantsRoot))
3163
+ if (!fs8.existsSync(layout.variantsRoot))
2979
3164
  return [];
2980
- return fs7.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
3165
+ return fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
2981
3166
  }
2982
- function matchesGlob(filename, glob) {
2983
- const starIdx = glob.indexOf("*");
2984
- if (starIdx === -1)
2985
- return filename === glob;
2986
- const prefix = glob.slice(0, starIdx);
2987
- const suffix = glob.slice(starIdx + 1);
2988
- return filename.length >= prefix.length + suffix.length && filename.startsWith(prefix) && filename.endsWith(suffix);
3167
+ function matchingFileNames(dir, ext) {
3168
+ 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);
2989
3169
  }
2990
- function matchingFileNames(dir, glob) {
2991
- return fs7.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && matchesGlob(e.name, glob)).map((e) => e.name);
3170
+ function destIsAbsent(dest) {
3171
+ try {
3172
+ fs8.lstatSync(dest);
3173
+ return false;
3174
+ } catch {
3175
+ return true;
3176
+ }
2992
3177
  }
2993
3178
  function detectGitAvailability(dir) {
2994
3179
  try {
@@ -3014,7 +3199,7 @@ function gitTrackedFileNames(dir, filenames) {
3014
3199
  }
3015
3200
  }
3016
3201
  function checkTrackedPathGuard(activeDir, filenames) {
3017
- if (filenames.length === 0 || !fs7.existsSync(activeDir))
3202
+ if (filenames.length === 0 || !fs8.existsSync(activeDir))
3018
3203
  return GUARD_PASS;
3019
3204
  const availability = detectGitAvailability(activeDir);
3020
3205
  if (availability === "no-git")
@@ -3025,53 +3210,45 @@ function checkTrackedPathGuard(activeDir, filenames) {
3025
3210
  if (tracked.size === 0)
3026
3211
  return GUARD_PASS;
3027
3212
  const offending = filenames.find((name) => tracked.has(name));
3028
- return { blocked: true, path: path11.join(activeDir, offending), unchecked: false };
3213
+ return { blocked: true, path: path12.join(activeDir, offending), unchecked: false };
3029
3214
  }
3030
3215
  function assertStateWritable(stateFilePath) {
3031
- const dir = path11.dirname(stateFilePath);
3216
+ const dir = path12.dirname(stateFilePath);
3032
3217
  try {
3033
- fs7.mkdirSync(dir, { recursive: true });
3218
+ fs8.mkdirSync(dir, { recursive: true });
3034
3219
  } catch (err) {
3035
3220
  throw UnwritableInstallStateError(stateFilePath, err.message);
3036
3221
  }
3037
- const checkPath = fs7.existsSync(stateFilePath) ? stateFilePath : dir;
3222
+ const checkPath = fs8.existsSync(stateFilePath) ? stateFilePath : dir;
3038
3223
  try {
3039
- fs7.accessSync(checkPath, fs7.constants.W_OK);
3224
+ fs8.accessSync(checkPath, fs8.constants.W_OK);
3040
3225
  } catch (err) {
3041
3226
  throw UnwritableInstallStateError(stateFilePath, err.message);
3042
3227
  }
3043
3228
  }
3044
3229
  function copyFileRouteVariant(layout, variantDir) {
3045
- fs7.mkdirSync(layout.activeDir, { recursive: true });
3230
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
3046
3231
  let changed = 0;
3047
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
3048
- if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
3232
+ for (const name of matchingFileNames(variantDir, layout.activeExt)) {
3233
+ const dest = path12.join(layout.activeDir, name);
3234
+ if (!destIsAbsent(dest) && !isOwnedAgentFile(dest))
3049
3235
  continue;
3050
- fs7.copyFileSync(path11.join(variantDir, entry.name), path11.join(layout.activeDir, entry.name));
3236
+ fs8.copyFileSync(path12.join(variantDir, name), dest);
3051
3237
  changed++;
3052
3238
  }
3053
3239
  return changed;
3054
3240
  }
3055
3241
  function repointOpencodeVariant(layout, variantDir) {
3056
- fs7.mkdirSync(layout.activeDir, { recursive: true });
3242
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
3057
3243
  let changed = 0;
3058
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
3059
- if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
3060
- continue;
3061
- const dest = path11.join(layout.activeDir, entry.name);
3062
- const target = path11.resolve(path11.join(variantDir, entry.name));
3063
- let destExists = true;
3064
- let destIsSymlink = false;
3065
- try {
3066
- destIsSymlink = fs7.lstatSync(dest).isSymbolicLink();
3067
- } catch {
3068
- destExists = false;
3069
- }
3070
- if (destExists && !destIsSymlink)
3244
+ for (const name of matchingFileNames(variantDir, layout.activeExt)) {
3245
+ const dest = path12.join(layout.activeDir, name);
3246
+ const target = path12.resolve(path12.join(variantDir, name));
3247
+ if (!destIsAbsent(dest) && !isOwnedAgentLink(dest))
3071
3248
  continue;
3072
3249
  const tmp = `${dest}.massa-ai-switch.${crypto4.randomUUID()}`;
3073
- fs7.symlinkSync(target, tmp);
3074
- fs7.renameSync(tmp, dest);
3250
+ fs8.symlinkSync(target, tmp);
3251
+ fs8.renameSync(tmp, dest);
3075
3252
  changed++;
3076
3253
  }
3077
3254
  return changed;
@@ -3111,13 +3288,13 @@ function switchProfile(opts) {
3111
3288
  if (fileHosts.length === 0) {
3112
3289
  return { profile: opts.profile, dryRun, hosts: orderRows(universe, skipRows), restartRequired: false };
3113
3290
  }
3114
- const installedFileHosts = fileHosts.filter((h) => fs7.existsSync(h.layout.activeDir));
3291
+ const installedFileHosts = fileHosts.filter((h) => fs8.existsSync(h.layout.activeDir));
3115
3292
  if (installedFileHosts.length === 0)
3116
3293
  throw NoHostsDetectedError();
3117
3294
  const withAvailability = fileHosts.map((h) => {
3118
- const variantsRootExists = fs7.existsSync(h.layout.variantsRoot);
3295
+ const variantsRootExists = fs8.existsSync(h.layout.variantsRoot);
3119
3296
  const variantDir = h.layout.variantDir(opts.profile);
3120
- const available = variantsRootExists && fs7.existsSync(variantDir) && fs7.statSync(variantDir).isDirectory();
3297
+ const available = variantsRootExists && fs8.existsSync(variantDir) && fs8.statSync(variantDir).isDirectory();
3121
3298
  return { ...h, variantsRootExists, variantDir, available };
3122
3299
  });
3123
3300
  if (!withAvailability.some((h) => h.available)) {
@@ -3156,7 +3333,7 @@ function switchProfile(opts) {
3156
3333
  rows.push({ host: h.host, status: "would-switch" });
3157
3334
  continue;
3158
3335
  }
3159
- const candidateNames = matchingFileNames(h.variantDir, h.layout.activeGlob);
3336
+ const candidateNames = matchingFileNames(h.variantDir, h.layout.activeExt);
3160
3337
  const guard = checkTrackedPathGuard(h.layout.activeDir, candidateNames);
3161
3338
  if (guard.blocked) {
3162
3339
  rows.push({
@@ -3198,6 +3375,7 @@ var init_engine = __esm(() => {
3198
3375
  init_state();
3199
3376
  init_lock();
3200
3377
  init_claude_marketplace();
3378
+ init_ownership();
3201
3379
  init_doctor();
3202
3380
  SwitchEngineError = class SwitchEngineError extends Error {
3203
3381
  constructor(message) {
@@ -3215,25 +3393,25 @@ function reportSucceeded(report) {
3215
3393
  }
3216
3394
 
3217
3395
  // ../../packages/shared/dist/profile-switch/variant-sync.js
3218
- import fs8 from "fs";
3219
- import path12 from "path";
3396
+ import fs9 from "fs";
3397
+ import path13 from "path";
3220
3398
  import os8 from "os";
3221
3399
  import crypto5 from "crypto";
3222
3400
  function defaultStatePath2(targetHome) {
3223
- return path12.join(targetHome, ".config", "massa-ai", "install-state.json");
3401
+ return path13.join(targetHome, ".config", "massa-ai", "install-state.json");
3224
3402
  }
3225
3403
  function marketplaceRoots2(targetHome, state) {
3226
3404
  return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
3227
3405
  }
3228
3406
  function writeFileIntoDirAtomically(destDir, destName, content) {
3229
3407
  const unique = `${process.pid}.${++tempFileCounter2}.${crypto5.randomBytes(6).toString("hex")}`;
3230
- const tempFile = path12.join(destDir, `.${destName}.${unique}.tmp`);
3408
+ const tempFile = path13.join(destDir, `.${destName}.${unique}.tmp`);
3231
3409
  try {
3232
- fs8.writeFileSync(tempFile, content);
3233
- fs8.renameSync(tempFile, path12.join(destDir, destName));
3410
+ fs9.writeFileSync(tempFile, content);
3411
+ fs9.renameSync(tempFile, path13.join(destDir, destName));
3234
3412
  } catch (error) {
3235
3413
  try {
3236
- fs8.unlinkSync(tempFile);
3414
+ fs9.unlinkSync(tempFile);
3237
3415
  } catch {}
3238
3416
  throw error;
3239
3417
  }
@@ -3241,20 +3419,20 @@ function writeFileIntoDirAtomically(destDir, destName, content) {
3241
3419
  function isSafeDirName(name) {
3242
3420
  if (name === "." || name === "..")
3243
3421
  return false;
3244
- if (name.includes("/") || name.includes("\\") || name.includes(path12.sep))
3422
+ if (name.includes("/") || name.includes("\\") || name.includes(path13.sep))
3245
3423
  return false;
3246
- return path12.basename(name) === name;
3424
+ return path13.basename(name) === name;
3247
3425
  }
3248
3426
  function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
3249
3427
  const layout = resolveHostLayout(host, { targetHome, marketplaceRoot });
3250
3428
  if (layout.route === "skip") {
3251
3429
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: layout.reason };
3252
3430
  }
3253
- const srcDir = path12.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
3254
- if (!fs8.existsSync(srcDir) || !fs8.statSync(srcDir).isDirectory()) {
3431
+ const srcDir = path13.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
3432
+ if (!fs9.existsSync(srcDir) || !fs9.statSync(srcDir).isDirectory()) {
3255
3433
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: "no generated variants for this host" };
3256
3434
  }
3257
- if (!fs8.existsSync(layout.variantsRoot)) {
3435
+ if (!fs9.existsSync(layout.variantsRoot)) {
3258
3436
  return {
3259
3437
  host,
3260
3438
  status: "skipped",
@@ -3266,24 +3444,24 @@ function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
3266
3444
  }
3267
3445
  const profiles = [];
3268
3446
  let files = 0;
3269
- for (const entry of fs8.readdirSync(srcDir, { withFileTypes: true })) {
3447
+ for (const entry of fs9.readdirSync(srcDir, { withFileTypes: true })) {
3270
3448
  if (!entry.isDirectory())
3271
3449
  continue;
3272
3450
  if (!isSafeDirName(entry.name))
3273
3451
  continue;
3274
- const srcProfileDir = path12.join(srcDir, entry.name);
3275
- const destProfileDir = path12.join(layout.variantsRoot, entry.name);
3276
- fs8.mkdirSync(destProfileDir, { recursive: true });
3277
- for (const fileEntry of fs8.readdirSync(srcProfileDir, { withFileTypes: true })) {
3452
+ const srcProfileDir = path13.join(srcDir, entry.name);
3453
+ const destProfileDir = path13.join(layout.variantsRoot, entry.name);
3454
+ fs9.mkdirSync(destProfileDir, { recursive: true });
3455
+ for (const fileEntry of fs9.readdirSync(srcProfileDir, { withFileTypes: true })) {
3278
3456
  if (!fileEntry.isFile())
3279
3457
  continue;
3280
- const content = fs8.readFileSync(path12.join(srcProfileDir, fileEntry.name));
3458
+ const content = fs9.readFileSync(path13.join(srcProfileDir, fileEntry.name));
3281
3459
  writeFileIntoDirAtomically(destProfileDir, fileEntry.name, content);
3282
3460
  files++;
3283
3461
  }
3284
3462
  profiles.push(entry.name);
3285
3463
  }
3286
- const retained = fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
3464
+ const retained = fs9.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
3287
3465
  return { host, status: "synced", profiles: profiles.sort(), retained, files };
3288
3466
  }
3289
3467
  function syncGeneratedVariants(opts) {
@@ -3318,14 +3496,14 @@ var init_variant_sync = __esm(() => {
3318
3496
  });
3319
3497
 
3320
3498
  // ../../packages/shared/dist/profile-switch/repo-root.js
3321
- import fs9 from "fs";
3322
- import path13 from "path";
3499
+ import fs10 from "fs";
3500
+ import path14 from "path";
3323
3501
  function findRepoRootWithMarker(startDir, marker, maxLevels) {
3324
3502
  let dir = startDir;
3325
3503
  for (let i = 0;i <= maxLevels; i++) {
3326
- if (fs9.existsSync(path13.join(dir, marker)))
3504
+ if (fs10.existsSync(path14.join(dir, marker)))
3327
3505
  return dir;
3328
- const parent = path13.dirname(dir);
3506
+ const parent = path14.dirname(dir);
3329
3507
  if (parent === dir)
3330
3508
  break;
3331
3509
  dir = parent;
@@ -3335,6 +3513,9 @@ function findRepoRootWithMarker(startDir, marker, maxLevels) {
3335
3513
  var init_repo_root = () => {};
3336
3514
 
3337
3515
  // ../../packages/shared/dist/bootstrap/rules.js
3516
+ function isRetiredRuleId(value) {
3517
+ return RETIRED_RULE_IDS.includes(value);
3518
+ }
3338
3519
  function isBootstrapRuleId(value) {
3339
3520
  return typeof value === "string" && BOOTSTRAP_RULE_IDS.includes(value);
3340
3521
  }
@@ -3353,12 +3534,14 @@ function assertKnownRuleId(id) {
3353
3534
  if (!isBootstrapRuleId(id))
3354
3535
  throw UnknownRuleError(id, BOOTSTRAP_RULE_IDS);
3355
3536
  }
3356
- 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(", ")}`);
3537
+ var BOOTSTRAP_RULE_IDS, RETIRED_RULE_IDS, BOOTSTRAP_RULES, RULES_BY_ID, BootstrapRuleError, UnknownRuleError = (id, known = BOOTSTRAP_RULE_IDS) => {
3538
+ const what = isRetiredRuleId(id) ? `bootstrap rule "${id}" was retired and can no longer be toggled` : `unknown bootstrap rule "${id}"`;
3539
+ return namedError4("UnknownRuleError", `${what} \u2014 valid ids: ${known.join(", ")}`);
3540
+ };
3357
3541
  var init_rules = __esm(() => {
3358
3542
  BOOTSTRAP_RULE_IDS = [
3359
3543
  "caveman",
3360
3544
  "massa-ai-router",
3361
- "persona-router",
3362
3545
  "dedupe-guardrails",
3363
3546
  "plan-challenge",
3364
3547
  "conversation-feedback",
@@ -3366,6 +3549,7 @@ var init_rules = __esm(() => {
3366
3549
  "english-code",
3367
3550
  "code-comments"
3368
3551
  ];
3552
+ RETIRED_RULE_IDS = ["persona-router"];
3369
3553
  BOOTSTRAP_RULES = [
3370
3554
  {
3371
3555
  id: "caveman",
@@ -3377,11 +3561,6 @@ var init_rules = __esm(() => {
3377
3561
  defaultEnabled: true,
3378
3562
  description: "Load the massa-ai skill as the workflow router before substantive work."
3379
3563
  },
3380
- {
3381
- id: "persona-router",
3382
- defaultEnabled: true,
3383
- description: "Select one cataloged specialist persona after massa-ai context is available."
3384
- },
3385
3564
  {
3386
3565
  id: "dedupe-guardrails",
3387
3566
  defaultEnabled: true,
@@ -3423,7 +3602,7 @@ var init_rules = __esm(() => {
3423
3602
  });
3424
3603
 
3425
3604
  // ../../packages/shared/dist/bootstrap/state.js
3426
- import fs10 from "fs";
3605
+ import fs11 from "fs";
3427
3606
  function isPlainObject2(value) {
3428
3607
  return typeof value === "object" && value !== null && !Array.isArray(value);
3429
3608
  }
@@ -3444,6 +3623,8 @@ function resolveBootstrapState(doc) {
3444
3623
  return { state, ignoredStateKeys: [BOOTSTRAP_STATE_PATH] };
3445
3624
  }
3446
3625
  for (const [key, value] of Object.entries(rules)) {
3626
+ if (isRetiredRuleId(key))
3627
+ continue;
3447
3628
  if (!isBootstrapRuleId(key) || typeof value !== "boolean") {
3448
3629
  ignored.push(key);
3449
3630
  continue;
@@ -3454,7 +3635,7 @@ function resolveBootstrapState(doc) {
3454
3635
  }
3455
3636
  function readConfigBytes() {
3456
3637
  try {
3457
- return fs10.readFileSync(getConfigPath(), "utf-8");
3638
+ return fs11.readFileSync(getConfigPath(), "utf-8");
3458
3639
  } catch (error) {
3459
3640
  if (error?.code === "ENOENT")
3460
3641
  return "";
@@ -3509,7 +3690,7 @@ var init_state2 = __esm(() => {
3509
3690
  });
3510
3691
 
3511
3692
  // ../../packages/shared/dist/bootstrap/render.js
3512
- import path14 from "path";
3693
+ import path15 from "path";
3513
3694
  function wrapBootstrapBlock(body) {
3514
3695
  return `${BOOTSTRAP_BLOCK_START}
3515
3696
  ${body.replace(/\n+$/, "")}
@@ -3522,19 +3703,19 @@ function ruleMarker(id, suffix) {
3522
3703
  function resolveHostRoot(host, targetHome, hostRoot) {
3523
3704
  requireAbsoluteTargetHome(targetHome);
3524
3705
  if (hostRoot === undefined)
3525
- return path14.join(targetHome, ...HOST_CONFIG_DIR[host]);
3526
- const relative = path14.relative(targetHome, hostRoot);
3527
- if (!path14.isAbsolute(hostRoot) || relative === "" || relative.startsWith("..") || path14.isAbsolute(relative)) {
3706
+ return path15.join(targetHome, ...HOST_CONFIG_DIR[host]);
3707
+ const relative = path15.relative(targetHome, hostRoot);
3708
+ if (!path15.isAbsolute(hostRoot) || relative === "" || relative.startsWith("..") || path15.isAbsolute(relative)) {
3528
3709
  throw new BootstrapRenderError("HostRootOutsideTargetHomeError", `hostRoot must be an absolute directory inside targetHome, got "${hostRoot}" for targetHome "${targetHome}"`, [hostRoot, targetHome]);
3529
3710
  }
3530
3711
  return hostRoot;
3531
3712
  }
3532
3713
  function bootstrapContractPath(host, targetHome, hostRoot) {
3533
- return path14.join(resolveHostRoot(host, targetHome, hostRoot), CONTRACT_FILENAME);
3714
+ return path15.join(resolveHostRoot(host, targetHome, hostRoot), CONTRACT_FILENAME);
3534
3715
  }
3535
3716
  function bootstrapStateFilePath(targetHome) {
3536
3717
  requireAbsoluteTargetHome(targetHome);
3537
- return path14.join(targetHome, ".config", "massa-ai", "config.json");
3718
+ return path15.join(targetHome, ".config", "massa-ai", "config.json");
3538
3719
  }
3539
3720
  function renderBootstrap(options) {
3540
3721
  const { source, state, host, targetHome, hostRoot } = options;
@@ -3557,7 +3738,7 @@ ${body}`;
3557
3738
  return { contract, pointer };
3558
3739
  }
3559
3740
  function requireAbsoluteTargetHome(targetHome) {
3560
- if (!path14.isAbsolute(targetHome)) {
3741
+ if (!path15.isAbsolute(targetHome)) {
3561
3742
  throw new BootstrapRenderError("TargetHomeNotAbsoluteError", `targetHome must be an absolute path, got "${targetHome}"`, [targetHome]);
3562
3743
  }
3563
3744
  }
@@ -3734,14 +3915,14 @@ var init_report = __esm(() => {
3734
3915
  });
3735
3916
 
3736
3917
  // ../../packages/shared/dist/bootstrap/engine.js
3737
- import fs11 from "fs";
3738
- import path15 from "path";
3918
+ import fs12 from "fs";
3919
+ import path16 from "path";
3739
3920
  function applyBootstrapState(options) {
3740
3921
  const { targetHome } = options;
3741
3922
  const dryRun = options.dryRun ?? false;
3742
3923
  const warn = options.onWarning ?? ((message) => console.warn(message));
3743
3924
  const configPath = bootstrapStateFilePath(targetHome);
3744
- const installStatePath = path15.join(path15.dirname(configPath), INSTALL_STATE_FILENAME);
3925
+ const installStatePath = path16.join(path16.dirname(configPath), INSTALL_STATE_FILENAME);
3745
3926
  const { platforms } = readInstallState(installStatePath);
3746
3927
  const installed = HOSTS.filter((host) => platforms[host] !== undefined);
3747
3928
  if (installed.length === 0) {
@@ -3834,22 +4015,22 @@ function applyHost(input) {
3834
4015
  }
3835
4016
  function wiringArtifact(host, targetHome, hostRoot) {
3836
4017
  const root = resolveHostRoot(host, targetHome, hostRoot);
3837
- const contractPath = path15.join(root, CONTRACT_FILENAME);
4018
+ const contractPath = path16.join(root, CONTRACT_FILENAME);
3838
4019
  switch (host) {
3839
4020
  case "claude":
3840
- return { file: path15.join(root, "CLAUDE.md"), token: `@${CONTRACT_FILENAME}` };
4021
+ return { file: path16.join(root, "CLAUDE.md"), token: `@${CONTRACT_FILENAME}` };
3841
4022
  case "codex":
3842
4023
  case "cursor":
3843
- return { file: path15.join(root, "AGENTS.md"), token: contractPath };
4024
+ return { file: path16.join(root, "AGENTS.md"), token: contractPath };
3844
4025
  case "opencode":
3845
4026
  return { file: openCodeConfigPath(root), token: `"${contractPath}"` };
3846
4027
  }
3847
4028
  }
3848
4029
  function openCodeConfigPath(root) {
3849
- const json = path15.join(root, "opencode.json");
3850
- if (fs11.existsSync(json))
4030
+ const json = path16.join(root, "opencode.json");
4031
+ if (fs12.existsSync(json))
3851
4032
  return json;
3852
- return path15.join(root, "opencode.jsonc");
4033
+ return path16.join(root, "opencode.jsonc");
3853
4034
  }
3854
4035
  function isWired(host, targetHome, hostRoot) {
3855
4036
  const artifact = wiringArtifact(host, targetHome, hostRoot);
@@ -3862,7 +4043,7 @@ function notWiredReason(host, targetHome, hostRoot) {
3862
4043
  }
3863
4044
  function readFileOrNull(filePath) {
3864
4045
  try {
3865
- return fs11.readFileSync(filePath, "utf-8");
4046
+ return fs12.readFileSync(filePath, "utf-8");
3866
4047
  } catch {
3867
4048
  return null;
3868
4049
  }
@@ -3944,8 +4125,10 @@ var init_dist = __esm(() => {
3944
4125
  init_state();
3945
4126
  init_lock();
3946
4127
  init_engine();
4128
+ init_ownership();
3947
4129
  init_variant_sync();
3948
4130
  init_repo_root();
4131
+ init_doctor();
3949
4132
  init_bootstrap();
3950
4133
  init_types();
3951
4134
  init_interfaces();
@@ -5468,7 +5651,7 @@ var import_brace_expansion, minimatch = (p, pattern, options = {}) => {
5468
5651
  }, qmarksTestNoExtDot = ([$0]) => {
5469
5652
  const len = $0.length;
5470
5653
  return (f) => f.length === len && f !== "." && f !== "..";
5471
- }, 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) => {
5654
+ }, 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) => {
5472
5655
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
5473
5656
  return minimatch;
5474
5657
  }
@@ -5526,11 +5709,11 @@ var init_esm = __esm(() => {
5526
5709
  starRE = /^\*+$/;
5527
5710
  qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
5528
5711
  defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
5529
- path16 = {
5712
+ path17 = {
5530
5713
  win32: { sep: "\\" },
5531
5714
  posix: { sep: "/" }
5532
5715
  };
5533
- sep = defaultPlatform === "win32" ? path16.win32.sep : path16.posix.sep;
5716
+ sep = defaultPlatform === "win32" ? path17.win32.sep : path17.posix.sep;
5534
5717
  minimatch.sep = sep;
5535
5718
  GLOBSTAR = Symbol("globstar **");
5536
5719
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -7496,12 +7679,12 @@ var init_esm4 = __esm(() => {
7496
7679
  childrenCache() {
7497
7680
  return this.#children;
7498
7681
  }
7499
- resolve(path17) {
7500
- if (!path17) {
7682
+ resolve(path18) {
7683
+ if (!path18) {
7501
7684
  return this;
7502
7685
  }
7503
- const rootPath = this.getRootString(path17);
7504
- const dir = path17.substring(rootPath.length);
7686
+ const rootPath = this.getRootString(path18);
7687
+ const dir = path18.substring(rootPath.length);
7505
7688
  const dirParts = dir.split(this.splitSep);
7506
7689
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
7507
7690
  return result;
@@ -8029,8 +8212,8 @@ var init_esm4 = __esm(() => {
8029
8212
  newChild(name, type = UNKNOWN, opts = {}) {
8030
8213
  return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
8031
8214
  }
8032
- getRootString(path17) {
8033
- return win32.parse(path17).root;
8215
+ getRootString(path18) {
8216
+ return win32.parse(path18).root;
8034
8217
  }
8035
8218
  getRoot(rootPath) {
8036
8219
  rootPath = uncToDrive(rootPath.toUpperCase());
@@ -8055,8 +8238,8 @@ var init_esm4 = __esm(() => {
8055
8238
  constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
8056
8239
  super(name, type, root, roots, nocase, children, opts);
8057
8240
  }
8058
- getRootString(path17) {
8059
- return path17.startsWith("/") ? "/" : "";
8241
+ getRootString(path18) {
8242
+ return path18.startsWith("/") ? "/" : "";
8060
8243
  }
8061
8244
  getRoot(_rootPath) {
8062
8245
  return this.root;
@@ -8075,8 +8258,8 @@ var init_esm4 = __esm(() => {
8075
8258
  #children;
8076
8259
  nocase;
8077
8260
  #fs;
8078
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs12 = defaultFS } = {}) {
8079
- this.#fs = fsFromOption(fs12);
8261
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs13 = defaultFS } = {}) {
8262
+ this.#fs = fsFromOption(fs13);
8080
8263
  if (cwd instanceof URL || cwd.startsWith("file://")) {
8081
8264
  cwd = fileURLToPath(cwd);
8082
8265
  }
@@ -8112,11 +8295,11 @@ var init_esm4 = __esm(() => {
8112
8295
  }
8113
8296
  this.cwd = prev;
8114
8297
  }
8115
- depth(path17 = this.cwd) {
8116
- if (typeof path17 === "string") {
8117
- path17 = this.cwd.resolve(path17);
8298
+ depth(path18 = this.cwd) {
8299
+ if (typeof path18 === "string") {
8300
+ path18 = this.cwd.resolve(path18);
8118
8301
  }
8119
- return path17.depth();
8302
+ return path18.depth();
8120
8303
  }
8121
8304
  childrenCache() {
8122
8305
  return this.#children;
@@ -8532,9 +8715,9 @@ var init_esm4 = __esm(() => {
8532
8715
  process2();
8533
8716
  return results;
8534
8717
  }
8535
- chdir(path17 = this.cwd) {
8718
+ chdir(path18 = this.cwd) {
8536
8719
  const oldCwd = this.cwd;
8537
- this.cwd = typeof path17 === "string" ? this.cwd.resolve(path17) : path17;
8720
+ this.cwd = typeof path18 === "string" ? this.cwd.resolve(path18) : path18;
8538
8721
  this.cwd[setAsCwd](oldCwd);
8539
8722
  }
8540
8723
  };
@@ -8551,8 +8734,8 @@ var init_esm4 = __esm(() => {
8551
8734
  parseRootPath(dir) {
8552
8735
  return win32.parse(dir).root.toUpperCase();
8553
8736
  }
8554
- newRoot(fs12) {
8555
- return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs12 });
8737
+ newRoot(fs13) {
8738
+ return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs13 });
8556
8739
  }
8557
8740
  isAbsolute(p) {
8558
8741
  return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
@@ -8568,8 +8751,8 @@ var init_esm4 = __esm(() => {
8568
8751
  parseRootPath(_dir) {
8569
8752
  return "/";
8570
8753
  }
8571
- newRoot(fs12) {
8572
- return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs12 });
8754
+ newRoot(fs13) {
8755
+ return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs13 });
8573
8756
  }
8574
8757
  isAbsolute(p) {
8575
8758
  return p.startsWith("/");
@@ -8826,8 +9009,8 @@ class MatchRecord {
8826
9009
  this.store.set(target, current === undefined ? n : n & current);
8827
9010
  }
8828
9011
  entries() {
8829
- return [...this.store.entries()].map(([path17, n]) => [
8830
- path17,
9012
+ return [...this.store.entries()].map(([path18, n]) => [
9013
+ path18,
8831
9014
  !!(n & 2),
8832
9015
  !!(n & 1)
8833
9016
  ]);
@@ -9031,9 +9214,9 @@ class GlobUtil {
9031
9214
  signal;
9032
9215
  maxDepth;
9033
9216
  includeChildMatches;
9034
- constructor(patterns, path17, opts) {
9217
+ constructor(patterns, path18, opts) {
9035
9218
  this.patterns = patterns;
9036
- this.path = path17;
9219
+ this.path = path18;
9037
9220
  this.opts = opts;
9038
9221
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
9039
9222
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -9052,11 +9235,11 @@ class GlobUtil {
9052
9235
  });
9053
9236
  }
9054
9237
  }
9055
- #ignored(path17) {
9056
- return this.seen.has(path17) || !!this.#ignore?.ignored?.(path17);
9238
+ #ignored(path18) {
9239
+ return this.seen.has(path18) || !!this.#ignore?.ignored?.(path18);
9057
9240
  }
9058
- #childrenIgnored(path17) {
9059
- return !!this.#ignore?.childrenIgnored?.(path17);
9241
+ #childrenIgnored(path18) {
9242
+ return !!this.#ignore?.childrenIgnored?.(path18);
9060
9243
  }
9061
9244
  pause() {
9062
9245
  this.paused = true;
@@ -9273,8 +9456,8 @@ var init_walker = __esm(() => {
9273
9456
  init_processor();
9274
9457
  GlobWalker = class GlobWalker extends GlobUtil {
9275
9458
  matches = new Set;
9276
- constructor(patterns, path17, opts) {
9277
- super(patterns, path17, opts);
9459
+ constructor(patterns, path18, opts) {
9460
+ super(patterns, path18, opts);
9278
9461
  }
9279
9462
  matchEmit(e) {
9280
9463
  this.matches.add(e);
@@ -9311,8 +9494,8 @@ var init_walker = __esm(() => {
9311
9494
  };
9312
9495
  GlobStream = class GlobStream extends GlobUtil {
9313
9496
  results;
9314
- constructor(patterns, path17, opts) {
9315
- super(patterns, path17, opts);
9497
+ constructor(patterns, path18, opts) {
9498
+ super(patterns, path18, opts);
9316
9499
  this.results = new Minipass({
9317
9500
  signal: this.signal,
9318
9501
  objectMode: true
@@ -9740,20 +9923,20 @@ var require_ignore = __commonJS((exports, module) => {
9740
9923
  var throwError = (message, Ctor) => {
9741
9924
  throw new Ctor(message);
9742
9925
  };
9743
- var checkPath = (path17, originalPath, doThrow) => {
9744
- if (!isString(path17)) {
9926
+ var checkPath = (path18, originalPath, doThrow) => {
9927
+ if (!isString(path18)) {
9745
9928
  return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
9746
9929
  }
9747
- if (!path17) {
9930
+ if (!path18) {
9748
9931
  return doThrow(`path must not be empty`, TypeError);
9749
9932
  }
9750
- if (checkPath.isNotRelative(path17)) {
9933
+ if (checkPath.isNotRelative(path18)) {
9751
9934
  const r = "`path.relative()`d";
9752
9935
  return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
9753
9936
  }
9754
9937
  return true;
9755
9938
  };
9756
- var isNotRelative = (path17) => REGEX_TEST_INVALID_PATH.test(path17);
9939
+ var isNotRelative = (path18) => REGEX_TEST_INVALID_PATH.test(path18);
9757
9940
  checkPath.isNotRelative = isNotRelative;
9758
9941
  checkPath.convert = (p) => p;
9759
9942
 
@@ -9796,7 +9979,7 @@ var require_ignore = __commonJS((exports, module) => {
9796
9979
  addPattern(pattern) {
9797
9980
  return this.add(pattern);
9798
9981
  }
9799
- _testOne(path17, checkUnignored) {
9982
+ _testOne(path18, checkUnignored) {
9800
9983
  let ignored = false;
9801
9984
  let unignored = false;
9802
9985
  this._rules.forEach((rule) => {
@@ -9804,7 +9987,7 @@ var require_ignore = __commonJS((exports, module) => {
9804
9987
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
9805
9988
  return;
9806
9989
  }
9807
- const matched = rule.regex.test(path17);
9990
+ const matched = rule.regex.test(path18);
9808
9991
  if (matched) {
9809
9992
  ignored = !negative;
9810
9993
  unignored = negative;
@@ -9816,39 +9999,39 @@ var require_ignore = __commonJS((exports, module) => {
9816
9999
  };
9817
10000
  }
9818
10001
  _test(originalPath, cache, checkUnignored, slices) {
9819
- const path17 = originalPath && checkPath.convert(originalPath);
9820
- checkPath(path17, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
9821
- return this._t(path17, cache, checkUnignored, slices);
10002
+ const path18 = originalPath && checkPath.convert(originalPath);
10003
+ checkPath(path18, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
10004
+ return this._t(path18, cache, checkUnignored, slices);
9822
10005
  }
9823
- _t(path17, cache, checkUnignored, slices) {
9824
- if (path17 in cache) {
9825
- return cache[path17];
10006
+ _t(path18, cache, checkUnignored, slices) {
10007
+ if (path18 in cache) {
10008
+ return cache[path18];
9826
10009
  }
9827
10010
  if (!slices) {
9828
- slices = path17.split(SLASH2);
10011
+ slices = path18.split(SLASH2);
9829
10012
  }
9830
10013
  slices.pop();
9831
10014
  if (!slices.length) {
9832
- return cache[path17] = this._testOne(path17, checkUnignored);
10015
+ return cache[path18] = this._testOne(path18, checkUnignored);
9833
10016
  }
9834
10017
  const parent = this._t(slices.join(SLASH2) + SLASH2, cache, checkUnignored, slices);
9835
- return cache[path17] = parent.ignored ? parent : this._testOne(path17, checkUnignored);
10018
+ return cache[path18] = parent.ignored ? parent : this._testOne(path18, checkUnignored);
9836
10019
  }
9837
- ignores(path17) {
9838
- return this._test(path17, this._ignoreCache, false).ignored;
10020
+ ignores(path18) {
10021
+ return this._test(path18, this._ignoreCache, false).ignored;
9839
10022
  }
9840
10023
  createFilter() {
9841
- return (path17) => !this.ignores(path17);
10024
+ return (path18) => !this.ignores(path18);
9842
10025
  }
9843
10026
  filter(paths) {
9844
10027
  return makeArray(paths).filter(this.createFilter());
9845
10028
  }
9846
- test(path17) {
9847
- return this._test(path17, this._testCache, true);
10029
+ test(path18) {
10030
+ return this._test(path18, this._testCache, true);
9848
10031
  }
9849
10032
  }
9850
10033
  var factory = (options) => new Ignore2(options);
9851
- var isPathValid = (path17) => checkPath(path17 && checkPath.convert(path17), path17, RETURN_FALSE);
10034
+ var isPathValid = (path18) => checkPath(path18 && checkPath.convert(path18), path18, RETURN_FALSE);
9852
10035
  factory.isPathValid = isPathValid;
9853
10036
  factory.default = factory;
9854
10037
  module.exports = factory;
@@ -9856,7 +10039,7 @@ var require_ignore = __commonJS((exports, module) => {
9856
10039
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
9857
10040
  checkPath.convert = makePosix;
9858
10041
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
9859
- checkPath.isNotRelative = (path17) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path17) || isNotRelative(path17);
10042
+ checkPath.isNotRelative = (path18) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path18) || isNotRelative(path18);
9860
10043
  }
9861
10044
  });
9862
10045
 
@@ -9918,18 +10101,18 @@ function validatePolicy(policy, opts = {}) {
9918
10101
  }
9919
10102
  }
9920
10103
  }
9921
- function matchesGlob2(path17, pattern) {
10104
+ function matchesGlob(path18, pattern) {
9922
10105
  let re = regexCache.get(pattern);
9923
10106
  if (!re) {
9924
10107
  re = globToRegex(pattern);
9925
10108
  regexCache.set(pattern, re);
9926
10109
  }
9927
- return re.test(path17);
10110
+ return re.test(path18);
9928
10111
  }
9929
10112
  var DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
9930
10113
  const normalized = filePath.trim();
9931
10114
  for (const rule of policy.rules) {
9932
- if (matchesGlob2(normalized, rule.pattern))
10115
+ if (matchesGlob(normalized, rule.pattern))
9933
10116
  return rule.disposition;
9934
10117
  }
9935
10118
  return "Keep";
@@ -9941,8 +10124,8 @@ var init_capture_policy = __esm(() => {
9941
10124
  });
9942
10125
 
9943
10126
  // ../../packages/core/dist/services/search/ignore-patterns.js
9944
- import fs12 from "fs/promises";
9945
- import path17 from "path";
10127
+ import fs13 from "fs/promises";
10128
+ import path18 from "path";
9946
10129
  function buildExtensionGlob(extensions) {
9947
10130
  return extensions.map((ext2) => `**/*${ext2}`);
9948
10131
  }
@@ -9965,8 +10148,8 @@ async function loadProjectIgnore(projectPath) {
9965
10148
  const ig = ignore();
9966
10149
  ig.add(DEFAULT_IGNORES);
9967
10150
  try {
9968
- const gitignorePath = path17.join(projectPath, ".gitignore");
9969
- const gitignoreContent = await fs12.readFile(gitignorePath, "utf8");
10151
+ const gitignorePath = path18.join(projectPath, ".gitignore");
10152
+ const gitignoreContent = await fs13.readFile(gitignorePath, "utf8");
9970
10153
  const rules = gitignoreContent.split(`
9971
10154
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
9972
10155
  ig.add(rules);
@@ -11565,15 +11748,15 @@ var require_pg_connection_string = __commonJS((exports, module) => {
11565
11748
  if (config2.sslnegotiation === "direct" && config2.ssl === undefined) {
11566
11749
  config2.ssl = true;
11567
11750
  }
11568
- const fs13 = config2.sslcert || config2.sslkey || config2.sslrootcert ? __require("fs") : null;
11751
+ const fs14 = config2.sslcert || config2.sslkey || config2.sslrootcert ? __require("fs") : null;
11569
11752
  if (config2.sslcert) {
11570
- config2.ssl.cert = fs13.readFileSync(config2.sslcert).toString();
11753
+ config2.ssl.cert = fs14.readFileSync(config2.sslcert).toString();
11571
11754
  }
11572
11755
  if (config2.sslkey) {
11573
- config2.ssl.key = fs13.readFileSync(config2.sslkey).toString();
11756
+ config2.ssl.key = fs14.readFileSync(config2.sslkey).toString();
11574
11757
  }
11575
11758
  if (config2.sslrootcert) {
11576
- config2.ssl.ca = fs13.readFileSync(config2.sslrootcert).toString();
11759
+ config2.ssl.ca = fs14.readFileSync(config2.sslrootcert).toString();
11577
11760
  }
11578
11761
  if (options.useLibpqCompat && config2.uselibpqcompat) {
11579
11762
  throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");
@@ -13287,7 +13470,7 @@ var require_split2 = __commonJS((exports, module) => {
13287
13470
 
13288
13471
  // ../../node_modules/pgpass/lib/helper.js
13289
13472
  var require_helper = __commonJS((exports, module) => {
13290
- var path18 = __require("path");
13473
+ var path19 = __require("path");
13291
13474
  var Stream2 = __require("stream").Stream;
13292
13475
  var split = require_split2();
13293
13476
  var util = __require("util");
@@ -13327,7 +13510,7 @@ var require_helper = __commonJS((exports, module) => {
13327
13510
  };
13328
13511
  exports.getFileName = function(rawEnv) {
13329
13512
  var env = rawEnv || process.env;
13330
- var file = env.PGPASSFILE || (isWin ? path18.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path18.join(env.HOME || "./", ".pgpass"));
13513
+ var file = env.PGPASSFILE || (isWin ? path19.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path19.join(env.HOME || "./", ".pgpass"));
13331
13514
  return file;
13332
13515
  };
13333
13516
  exports.usePgPass = function(stats, fname) {
@@ -13451,16 +13634,16 @@ var require_helper = __commonJS((exports, module) => {
13451
13634
 
13452
13635
  // ../../node_modules/pgpass/lib/index.js
13453
13636
  var require_lib = __commonJS((exports, module) => {
13454
- var path18 = __require("path");
13455
- var fs13 = __require("fs");
13637
+ var path19 = __require("path");
13638
+ var fs14 = __require("fs");
13456
13639
  var helper = require_helper();
13457
13640
  module.exports = function(connInfo, cb) {
13458
13641
  var file = helper.getFileName();
13459
- fs13.stat(file, function(err, stat) {
13642
+ fs14.stat(file, function(err, stat) {
13460
13643
  if (err || !helper.usePgPass(stat, file)) {
13461
13644
  return cb(undefined);
13462
13645
  }
13463
- var st = fs13.createReadStream(file);
13646
+ var st = fs14.createReadStream(file);
13464
13647
  helper.getPassword(connInfo, st, cb);
13465
13648
  });
13466
13649
  };
@@ -15098,7 +15281,7 @@ class ProjectIdentityAliasResolver {
15098
15281
  this.cache.set(projectId, { canonical, expiresAt: this.now() + this.ttlMs });
15099
15282
  return canonical;
15100
15283
  } catch (error) {
15101
- logger.warn("[project-identity] alias resolution failed; using original id", safeErrorSummary(error));
15284
+ logger.warn("[project-identity] alias resolution failed; using original id", { projectId, ...safeErrorSummary(error) });
15102
15285
  return projectId;
15103
15286
  }
15104
15287
  }
@@ -15159,8 +15342,8 @@ var init_alias_resolver = __esm(() => {
15159
15342
  });
15160
15343
 
15161
15344
  // ../../packages/core/dist/services/search/index-manager.js
15162
- import fs13 from "fs";
15163
- import path18 from "path";
15345
+ import fs14 from "fs";
15346
+ import path19 from "path";
15164
15347
 
15165
15348
  class IndexManager {
15166
15349
  metadataCache = new Map;
@@ -15253,9 +15436,9 @@ class IndexManager {
15253
15436
  const fileMetadata = {};
15254
15437
  let totalSize = 0;
15255
15438
  for (const filePath of indexedFiles) {
15256
- const fullPath = path18.join(projectPath, filePath);
15439
+ const fullPath = path19.join(projectPath, filePath);
15257
15440
  try {
15258
- const stat = await fs13.promises.stat(fullPath);
15441
+ const stat = await fs14.promises.stat(fullPath);
15259
15442
  fileMetadata[filePath] = {
15260
15443
  path: filePath,
15261
15444
  mtime: stat.mtimeMs,
@@ -15306,9 +15489,9 @@ class IndexManager {
15306
15489
  if (ig.ignores(match2)) {
15307
15490
  continue;
15308
15491
  }
15309
- const fullPath = path18.join(projectPath, match2);
15492
+ const fullPath = path19.join(projectPath, match2);
15310
15493
  try {
15311
- const stat = await fs13.promises.stat(fullPath);
15494
+ const stat = await fs14.promises.stat(fullPath);
15312
15495
  files.set(match2, {
15313
15496
  path: match2,
15314
15497
  mtime: stat.mtimeMs,
@@ -15759,10 +15942,10 @@ function mergeDefs(...defs) {
15759
15942
  function cloneDef(schema) {
15760
15943
  return mergeDefs(schema._zod.def);
15761
15944
  }
15762
- function getElementAtPath(obj, path19) {
15763
- if (!path19)
15945
+ function getElementAtPath(obj, path20) {
15946
+ if (!path20)
15764
15947
  return obj;
15765
- return path19.reduce((acc, key) => acc?.[key], obj);
15948
+ return path20.reduce((acc, key) => acc?.[key], obj);
15766
15949
  }
15767
15950
  function promiseAllObject(promisesObj) {
15768
15951
  const keys = Object.keys(promisesObj);
@@ -16090,11 +16273,11 @@ function explicitlyAborted(x, startIndex = 0) {
16090
16273
  }
16091
16274
  return false;
16092
16275
  }
16093
- function prefixIssues(path19, issues) {
16276
+ function prefixIssues(path20, issues) {
16094
16277
  return issues.map((iss) => {
16095
16278
  var _a3;
16096
16279
  (_a3 = iss).path ?? (_a3.path = []);
16097
- iss.path.unshift(path19);
16280
+ iss.path.unshift(path20);
16098
16281
  return iss;
16099
16282
  });
16100
16283
  }
@@ -16307,16 +16490,16 @@ function flattenError(error, mapper = (issue2) => issue2.message) {
16307
16490
  }
16308
16491
  function formatError(error, mapper = (issue2) => issue2.message) {
16309
16492
  const fieldErrors = { _errors: [] };
16310
- const processError = (error2, path19 = []) => {
16493
+ const processError = (error2, path20 = []) => {
16311
16494
  for (const issue2 of error2.issues) {
16312
16495
  if (issue2.code === "invalid_union" && issue2.errors.length) {
16313
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
16496
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
16314
16497
  } else if (issue2.code === "invalid_key") {
16315
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
16498
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
16316
16499
  } else if (issue2.code === "invalid_element") {
16317
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
16500
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
16318
16501
  } else {
16319
- const fullpath = [...path19, ...issue2.path];
16502
+ const fullpath = [...path20, ...issue2.path];
16320
16503
  if (fullpath.length === 0) {
16321
16504
  fieldErrors._errors.push(mapper(issue2));
16322
16505
  } else {
@@ -16343,17 +16526,17 @@ function formatError(error, mapper = (issue2) => issue2.message) {
16343
16526
  }
16344
16527
  function treeifyError(error, mapper = (issue2) => issue2.message) {
16345
16528
  const result = { errors: [] };
16346
- const processError = (error2, path19 = []) => {
16529
+ const processError = (error2, path20 = []) => {
16347
16530
  var _a3, _b;
16348
16531
  for (const issue2 of error2.issues) {
16349
16532
  if (issue2.code === "invalid_union" && issue2.errors.length) {
16350
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
16533
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
16351
16534
  } else if (issue2.code === "invalid_key") {
16352
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
16535
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
16353
16536
  } else if (issue2.code === "invalid_element") {
16354
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
16537
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
16355
16538
  } else {
16356
- const fullpath = [...path19, ...issue2.path];
16539
+ const fullpath = [...path20, ...issue2.path];
16357
16540
  if (fullpath.length === 0) {
16358
16541
  result.errors.push(mapper(issue2));
16359
16542
  continue;
@@ -16385,8 +16568,8 @@ function treeifyError(error, mapper = (issue2) => issue2.message) {
16385
16568
  }
16386
16569
  function toDotPath(_path) {
16387
16570
  const segs = [];
16388
- const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
16389
- for (const seg of path19) {
16571
+ const path20 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
16572
+ for (const seg of path20) {
16390
16573
  if (typeof seg === "number")
16391
16574
  segs.push(`[${seg}]`);
16392
16575
  else if (typeof seg === "symbol")
@@ -29389,13 +29572,13 @@ function resolveRef(ref, ctx) {
29389
29572
  if (!ref.startsWith("#")) {
29390
29573
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
29391
29574
  }
29392
- const path19 = ref.slice(1).split("/").filter(Boolean);
29393
- if (path19.length === 0) {
29575
+ const path20 = ref.slice(1).split("/").filter(Boolean);
29576
+ if (path20.length === 0) {
29394
29577
  return ctx.rootSchema;
29395
29578
  }
29396
29579
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
29397
- if (path19[0] === defsKey) {
29398
- const key = path19[1];
29580
+ if (path20[0] === defsKey) {
29581
+ const key = path20[1];
29399
29582
  if (!key || !ctx.defs[key]) {
29400
29583
  throw new Error(`Reference not found: ${ref}`);
29401
29584
  }
@@ -30884,8 +31067,8 @@ class ParseStatus {
30884
31067
  }
30885
31068
  }
30886
31069
  var makeIssue = (params) => {
30887
- const { data, path: path19, errorMaps, issueData } = params;
30888
- const fullPath = [...path19, ...issueData.path || []];
31070
+ const { data, path: path20, errorMaps, issueData } = params;
31071
+ const fullPath = [...path20, ...issueData.path || []];
30889
31072
  const fullIssue = {
30890
31073
  ...issueData,
30891
31074
  path: fullPath
@@ -30930,11 +31113,11 @@ var init_errorUtil = __esm(() => {
30930
31113
 
30931
31114
  // ../../node_modules/zod/v3/types.js
30932
31115
  class ParseInputLazyPath {
30933
- constructor(parent, value, path19, key) {
31116
+ constructor(parent, value, path20, key) {
30934
31117
  this._cachedPath = [];
30935
31118
  this.parent = parent;
30936
31119
  this.data = value;
30937
- this._path = path19;
31120
+ this._path = path20;
30938
31121
  this._key = key;
30939
31122
  }
30940
31123
  get path() {
@@ -36999,23 +37182,23 @@ var require_auth_config = __commonJS((exports, module) => {
36999
37182
  writeAuthConfig: () => writeAuthConfig
37000
37183
  });
37001
37184
  module.exports = __toCommonJS2(auth_config_exports);
37002
- var fs14 = __toESM2(__require("fs"));
37003
- var path19 = __toESM2(__require("path"));
37185
+ var fs15 = __toESM2(__require("fs"));
37186
+ var path20 = __toESM2(__require("path"));
37004
37187
  var import_token_util = require_token_util();
37005
37188
  function getAuthConfigPath() {
37006
37189
  const dataDir = (0, import_token_util.getVercelDataDir)();
37007
37190
  if (!dataDir) {
37008
37191
  throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
37009
37192
  }
37010
- return path19.join(dataDir, "auth.json");
37193
+ return path20.join(dataDir, "auth.json");
37011
37194
  }
37012
37195
  function readAuthConfig() {
37013
37196
  try {
37014
37197
  const authPath = getAuthConfigPath();
37015
- if (!fs14.existsSync(authPath)) {
37198
+ if (!fs15.existsSync(authPath)) {
37016
37199
  return null;
37017
37200
  }
37018
- const content = fs14.readFileSync(authPath, "utf8");
37201
+ const content = fs15.readFileSync(authPath, "utf8");
37019
37202
  if (!content) {
37020
37203
  return null;
37021
37204
  }
@@ -37026,11 +37209,11 @@ var require_auth_config = __commonJS((exports, module) => {
37026
37209
  }
37027
37210
  function writeAuthConfig(config3) {
37028
37211
  const authPath = getAuthConfigPath();
37029
- const authDir = path19.dirname(authPath);
37030
- if (!fs14.existsSync(authDir)) {
37031
- fs14.mkdirSync(authDir, { mode: 504, recursive: true });
37212
+ const authDir = path20.dirname(authPath);
37213
+ if (!fs15.existsSync(authDir)) {
37214
+ fs15.mkdirSync(authDir, { mode: 504, recursive: true });
37032
37215
  }
37033
- fs14.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
37216
+ fs15.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
37034
37217
  }
37035
37218
  function isValidAccessToken(authConfig, expirationBufferMs = 0) {
37036
37219
  if (!authConfig.token)
@@ -37205,8 +37388,8 @@ var require_token_util = __commonJS((exports, module) => {
37205
37388
  saveToken: () => saveToken
37206
37389
  });
37207
37390
  module.exports = __toCommonJS2(token_util_exports);
37208
- var path19 = __toESM2(__require("path"));
37209
- var fs14 = __toESM2(__require("fs"));
37391
+ var path20 = __toESM2(__require("path"));
37392
+ var fs15 = __toESM2(__require("fs"));
37210
37393
  var import_token_error = require_token_error();
37211
37394
  var import_token_io = require_token_io();
37212
37395
  var import_auth_config = require_auth_config();
@@ -37218,7 +37401,7 @@ var require_token_util = __commonJS((exports, module) => {
37218
37401
  if (!dataDir) {
37219
37402
  return null;
37220
37403
  }
37221
- return path19.join(dataDir, vercelFolder);
37404
+ return path20.join(dataDir, vercelFolder);
37222
37405
  }
37223
37406
  async function getVercelToken2(options) {
37224
37407
  const authConfig = (0, import_auth_config.readAuthConfig)();
@@ -37286,11 +37469,11 @@ var require_token_util = __commonJS((exports, module) => {
37286
37469
  if (!dir) {
37287
37470
  throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");
37288
37471
  }
37289
- const prjPath = path19.join(dir, ".vercel", "project.json");
37290
- if (!fs14.existsSync(prjPath)) {
37472
+ const prjPath = path20.join(dir, ".vercel", "project.json");
37473
+ if (!fs15.existsSync(prjPath)) {
37291
37474
  throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");
37292
37475
  }
37293
- const prj = JSON.parse(fs14.readFileSync(prjPath, "utf8"));
37476
+ const prj = JSON.parse(fs15.readFileSync(prjPath, "utf8"));
37294
37477
  if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") {
37295
37478
  throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");
37296
37479
  }
@@ -37301,11 +37484,11 @@ var require_token_util = __commonJS((exports, module) => {
37301
37484
  if (!dir) {
37302
37485
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
37303
37486
  }
37304
- const tokenPath = path19.join(dir, "com.vercel.token", `${projectId}.json`);
37487
+ const tokenPath = path20.join(dir, "com.vercel.token", `${projectId}.json`);
37305
37488
  const tokenJson = JSON.stringify(token);
37306
- fs14.mkdirSync(path19.dirname(tokenPath), { mode: 504, recursive: true });
37307
- fs14.writeFileSync(tokenPath, tokenJson);
37308
- fs14.chmodSync(tokenPath, 432);
37489
+ fs15.mkdirSync(path20.dirname(tokenPath), { mode: 504, recursive: true });
37490
+ fs15.writeFileSync(tokenPath, tokenJson);
37491
+ fs15.chmodSync(tokenPath, 432);
37309
37492
  return;
37310
37493
  }
37311
37494
  function loadToken(projectId) {
@@ -37313,11 +37496,11 @@ var require_token_util = __commonJS((exports, module) => {
37313
37496
  if (!dir) {
37314
37497
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
37315
37498
  }
37316
- const tokenPath = path19.join(dir, "com.vercel.token", `${projectId}.json`);
37317
- if (!fs14.existsSync(tokenPath)) {
37499
+ const tokenPath = path20.join(dir, "com.vercel.token", `${projectId}.json`);
37500
+ if (!fs15.existsSync(tokenPath)) {
37318
37501
  return null;
37319
37502
  }
37320
- const token = JSON.parse(fs14.readFileSync(tokenPath, "utf8"));
37503
+ const token = JSON.parse(fs15.readFileSync(tokenPath, "utf8"));
37321
37504
  assertVercelOidcTokenResponse(token);
37322
37505
  return token;
37323
37506
  }
@@ -48159,37 +48342,37 @@ function createOpenAI(options = {}) {
48159
48342
  }, `ai-sdk/openai/${VERSION4}`);
48160
48343
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
48161
48344
  provider: `${providerName}.chat`,
48162
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48345
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48163
48346
  headers: getHeaders,
48164
48347
  fetch: options.fetch
48165
48348
  });
48166
48349
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
48167
48350
  provider: `${providerName}.completion`,
48168
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48351
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48169
48352
  headers: getHeaders,
48170
48353
  fetch: options.fetch
48171
48354
  });
48172
48355
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
48173
48356
  provider: `${providerName}.embedding`,
48174
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48357
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48175
48358
  headers: getHeaders,
48176
48359
  fetch: options.fetch
48177
48360
  });
48178
48361
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
48179
48362
  provider: `${providerName}.image`,
48180
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48363
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48181
48364
  headers: getHeaders,
48182
48365
  fetch: options.fetch
48183
48366
  });
48184
48367
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
48185
48368
  provider: `${providerName}.transcription`,
48186
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48369
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48187
48370
  headers: getHeaders,
48188
48371
  fetch: options.fetch
48189
48372
  });
48190
48373
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
48191
48374
  provider: `${providerName}.speech`,
48192
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48375
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48193
48376
  headers: getHeaders,
48194
48377
  fetch: options.fetch
48195
48378
  });
@@ -48202,7 +48385,7 @@ function createOpenAI(options = {}) {
48202
48385
  const createResponsesModel = (modelId) => {
48203
48386
  return new OpenAIResponsesLanguageModel(modelId, {
48204
48387
  provider: `${providerName}.responses`,
48205
- url: ({ path: path19 }) => `${baseURL}${path19}`,
48388
+ url: ({ path: path20 }) => `${baseURL}${path20}`,
48206
48389
  headers: getHeaders,
48207
48390
  fetch: options.fetch,
48208
48391
  fileIdPrefixes: ["file-"]
@@ -52643,7 +52826,7 @@ async function _checkJsonSchemaSupport() {
52643
52826
  } catch (e) {
52644
52827
  _jsonSchemaSupported = false;
52645
52828
  logger.warn("json_schema: version check error \u2014 falling back to json_object", {
52646
- error: e.message
52829
+ error: e
52647
52830
  });
52648
52831
  return false;
52649
52832
  }
@@ -52691,7 +52874,7 @@ function hostPort(url2) {
52691
52874
  return null;
52692
52875
  }
52693
52876
  }
52694
- function resolveInferenceSpec(baseUrl) {
52877
+ function resolveMatchedProviderSpec(baseUrl) {
52695
52878
  const target = hostPort(baseUrl);
52696
52879
  if (target) {
52697
52880
  const match2 = inferenceProviderList().find((spec) => hostPort(spec.defaultLlmBaseUrl) === target);
@@ -52709,7 +52892,13 @@ function resolveInferenceSpec(baseUrl) {
52709
52892
  if (embeddingProvider && LOCAL_INFERENCE_IDS.includes(embeddingProvider)) {
52710
52893
  return INFERENCE_PROVIDERS[embeddingProvider];
52711
52894
  }
52712
- return INFERENCE_PROVIDERS.ollama;
52895
+ return;
52896
+ }
52897
+ function resolveInferenceSpec(baseUrl) {
52898
+ return resolveMatchedProviderSpec(baseUrl) ?? INFERENCE_PROVIDERS.ollama;
52899
+ }
52900
+ function resolveProviderIdForLogging(baseUrl) {
52901
+ return resolveMatchedProviderSpec(baseUrl)?.id ?? "unknown";
52713
52902
  }
52714
52903
  function _wrapFetchDisableThink(baseFetch) {
52715
52904
  const wrapped = async (input, init) => {
@@ -52852,12 +53041,40 @@ function _isAbortOrTimeoutError(err) {
52852
53041
  }
52853
53042
  return false;
52854
53043
  }
52855
- async function llmComplete(prompt, opts = {}) {
53044
+ function summarizeZodIssues(error51, maxIssues = 5) {
53045
+ return error51.issues.slice(0, maxIssues).map((issue2) => `${issue2.path.join(".") || "(root)"}: ${issue2.message}`).join("; ");
53046
+ }
53047
+ function recordLlmFailure(label, role, model, baseUrl, timeoutMs, elapsedMs, err) {
53048
+ const consecutiveFailures = (llmFailureStreaks.get(label) ?? 0) + 1;
53049
+ llmFailureStreaks.set(label, consecutiveFailures);
53050
+ logger.warn("LLM call failed \u2014 using non-LLM fallback", {
53051
+ label,
53052
+ role,
53053
+ model,
53054
+ provider: resolveProviderIdForLogging(baseUrl),
53055
+ timeoutMs,
53056
+ elapsedMs,
53057
+ timedOut: _isAbortOrTimeoutError(err),
53058
+ error: err,
53059
+ consecutiveFailures
53060
+ });
53061
+ return consecutiveFailures;
53062
+ }
53063
+ function recordLlmSuccess(label, model) {
53064
+ const priorFailures = llmFailureStreaks.get(label) ?? 0;
53065
+ if (priorFailures > 0) {
53066
+ logger.info("LLM call recovered", { label, model, afterFailures: priorFailures });
53067
+ }
53068
+ llmFailureStreaks.set(label, 0);
53069
+ }
53070
+ async function llmComplete(prompt, opts) {
52856
53071
  if (!isLlmEnabled()) {
52857
53072
  return { ok: false, error: "llm disabled" };
52858
53073
  }
52859
53074
  const llm = getLlmConfig({ modelRole: opts.modelRole });
53075
+ const role = opts.modelRole ?? "instruct";
52860
53076
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
53077
+ const startedAt = Date.now();
52861
53078
  try {
52862
53079
  const result = await generateText({
52863
53080
  model: buildProvider(llm),
@@ -52868,14 +53085,17 @@ async function llmComplete(prompt, opts = {}) {
52868
53085
  abortSignal: timeoutSignal(timeoutMs)
52869
53086
  });
52870
53087
  const text2 = result.text ?? "";
52871
- if (text2.length > 0)
53088
+ if (text2.length > 0) {
53089
+ recordLlmSuccess(opts.label, llm.model);
52872
53090
  return { ok: true, value: text2 };
53091
+ }
52873
53092
  if (llm.disableThink) {
52874
53093
  const reasoning = _reasoningToText(result);
52875
53094
  if (reasoning.length > 0) {
52876
53095
  logger.warn("llmComplete: empty content \u2014 recovered from reasoning channel", {
52877
53096
  reasoningLen: reasoning.length
52878
53097
  });
53098
+ recordLlmSuccess(opts.label, llm.model);
52879
53099
  return { ok: true, value: reasoning };
52880
53100
  }
52881
53101
  logger.warn("llm reasoning-recovery empty", {
@@ -52883,21 +53103,22 @@ async function llmComplete(prompt, opts = {}) {
52883
53103
  finishReason: result?.finishReason ?? null
52884
53104
  });
52885
53105
  }
52886
- logger.warn("llmComplete: empty content and no reasoning \u2014 degrading", {});
52887
- return { ok: false, error: "empty content (thinking model)" };
53106
+ const emptyErr = new Error("empty content (thinking model)");
53107
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, emptyErr);
53108
+ return { ok: false, error: emptyErr.message };
52888
53109
  } catch (e) {
52889
- logger.warn("llmComplete failed \u2014 degrading to non-LLM path", {
52890
- error: e.message
52891
- });
53110
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, e);
52892
53111
  return { ok: false, error: e.message };
52893
53112
  }
52894
53113
  }
52895
- async function llmObject(prompt, schema, opts = {}) {
53114
+ async function llmObject(prompt, schema, opts) {
52896
53115
  if (!isLlmEnabled()) {
52897
53116
  return { ok: false, error: "llm disabled" };
52898
53117
  }
52899
53118
  const llm = getLlmConfig({ modelRole: opts.modelRole });
53119
+ const role = opts.modelRole ?? "instruct";
52900
53120
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
53121
+ const startedAt = Date.now();
52901
53122
  let result = null;
52902
53123
  try {
52903
53124
  const useJsonSchema = llm.disableThink && await _checkJsonSchemaSupport();
@@ -52912,7 +53133,8 @@ async function llmObject(prompt, schema, opts = {}) {
52912
53133
  maxOutputTokens: llm.maxOutputTokens,
52913
53134
  abortSignal: timeoutSignal(timeoutMs)
52914
53135
  });
52915
- logger.info("json_schema: constrained decoding used", {});
53136
+ logger.debug("json_schema: constrained decoding used", { label: opts.label, model: llm.model });
53137
+ recordLlmSuccess(opts.label, llm.model);
52916
53138
  return { ok: true, value: result.object };
52917
53139
  }
52918
53140
  result = await generateObject({
@@ -52926,7 +53148,8 @@ async function llmObject(prompt, schema, opts = {}) {
52926
53148
  });
52927
53149
  const validated = schema.safeParse(result.object);
52928
53150
  if (validated.success) {
52929
- logger.info("json_schema: fallback to json_object \u2014 validated", {});
53151
+ logger.debug("json_schema: fallback to json_object \u2014 validated", { label: opts.label, model: llm.model });
53152
+ recordLlmSuccess(opts.label, llm.model);
52930
53153
  return { ok: true, value: validated.data };
52931
53154
  }
52932
53155
  if (llm.disableThink) {
@@ -52939,15 +53162,17 @@ async function llmObject(prompt, schema, opts = {}) {
52939
53162
  logger.warn("llmObject: recovered object from reasoning channel (fallback path)", {
52940
53163
  reasoningLen: reasoning.length
52941
53164
  });
53165
+ recordLlmSuccess(opts.label, llm.model);
52942
53166
  return { ok: true, value: recovered.data };
52943
53167
  }
52944
53168
  }
52945
53169
  }
52946
53170
  }
52947
- logger.warn("llmObject: fallback validation failed", {
52948
- zodError: validated.error.issues.map((i) => i.message).join("; ")
53171
+ const validationErr = new Error("schema validation failed (fallback path)", {
53172
+ cause: summarizeZodIssues(validated.error)
52949
53173
  });
52950
- return { ok: false, error: "schema validation failed (fallback path)" };
53174
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, validationErr);
53175
+ return { ok: false, error: validationErr.message };
52951
53176
  } catch (e) {
52952
53177
  if (llm.disableThink && !_isAbortOrTimeoutError(e)) {
52953
53178
  const reasoning = _reasoningToText(result).length > 0 ? _reasoningToText(result) : _reasoningToText(e);
@@ -52959,6 +53184,7 @@ async function llmObject(prompt, schema, opts = {}) {
52959
53184
  logger.warn("llmObject: recovered object from reasoning channel", {
52960
53185
  reasoningLen: reasoning.length
52961
53186
  });
53187
+ recordLlmSuccess(opts.label, llm.model);
52962
53188
  return { ok: true, value: validated.data };
52963
53189
  }
52964
53190
  }
@@ -52968,19 +53194,18 @@ async function llmObject(prompt, schema, opts = {}) {
52968
53194
  finishReason: e?.finishReason ?? null
52969
53195
  });
52970
53196
  }
52971
- logger.warn("llmObject failed \u2014 degrading to non-LLM path", {
52972
- error: e.message
52973
- });
53197
+ recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, e);
52974
53198
  return { ok: false, error: e.message };
52975
53199
  }
52976
53200
  }
52977
- var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llm;
53201
+ var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llmFailureStreaks, llm;
52978
53202
  var init_llm_client = __esm(() => {
52979
53203
  init_dist6();
52980
53204
  init_dist7();
52981
53205
  init_dist();
52982
53206
  init_config();
52983
53207
  init_inference_providers();
53208
+ llmFailureStreaks = new Map;
52984
53209
  llm = {
52985
53210
  complete: llmComplete,
52986
53211
  object: llmObject,
@@ -61993,7 +62218,7 @@ class MetricsCollector2 {
61993
62218
  try {
61994
62219
  writeFileSync(this.metricsPath, JSON.stringify(this.currentMetrics, null, 2));
61995
62220
  } catch (error51) {
61996
- logger.error("[Metrics] Failed to save:", error51);
62221
+ logger.error("Metrics: failed to save", error51, { path: this.metricsPath });
61997
62222
  }
61998
62223
  }
61999
62224
  reset() {
@@ -62168,7 +62393,8 @@ class EmbeddingRateLimiter {
62168
62393
  }
62169
62394
  }
62170
62395
  if (this.config.requestsPerDay && this.dailyRequestsWindow.length >= this.config.requestsPerDay) {
62171
- logger.warn(`[${this.providerId}] RPD limit reached, waiting 60s`, {
62396
+ logger.warn("EmbeddingRateLimiter: RPD limit reached, waiting 60s", {
62397
+ providerId: this.providerId,
62172
62398
  rpd: this.config.requestsPerDay,
62173
62399
  current: this.dailyRequestsWindow.length
62174
62400
  });
@@ -64814,26 +65040,26 @@ var require_process = __commonJS((exports, module) => {
64814
65040
 
64815
65041
  // ../../node_modules/detect-libc/lib/filesystem.js
64816
65042
  var require_filesystem = __commonJS((exports, module) => {
64817
- var fs14 = __require("fs");
65043
+ var fs15 = __require("fs");
64818
65044
  var LDD_PATH = "/usr/bin/ldd";
64819
65045
  var SELF_PATH = "/proc/self/exe";
64820
65046
  var MAX_LENGTH = 2048;
64821
- var readFileSync2 = (path19) => {
64822
- const fd = fs14.openSync(path19, "r");
65047
+ var readFileSync2 = (path20) => {
65048
+ const fd = fs15.openSync(path20, "r");
64823
65049
  const buffer = Buffer.alloc(MAX_LENGTH);
64824
- const bytesRead = fs14.readSync(fd, buffer, 0, MAX_LENGTH, 0);
64825
- fs14.close(fd, () => {});
65050
+ const bytesRead = fs15.readSync(fd, buffer, 0, MAX_LENGTH, 0);
65051
+ fs15.close(fd, () => {});
64826
65052
  return buffer.subarray(0, bytesRead);
64827
65053
  };
64828
- var readFile = (path19) => new Promise((resolve4, reject) => {
64829
- fs14.open(path19, "r", (err, fd) => {
65054
+ var readFile = (path20) => new Promise((resolve4, reject) => {
65055
+ fs15.open(path20, "r", (err, fd) => {
64830
65056
  if (err) {
64831
65057
  reject(err);
64832
65058
  } else {
64833
65059
  const buffer = Buffer.alloc(MAX_LENGTH);
64834
- fs14.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
65060
+ fs15.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
64835
65061
  resolve4(buffer.subarray(0, bytesRead));
64836
- fs14.close(fd, () => {});
65062
+ fs15.close(fd, () => {});
64837
65063
  });
64838
65064
  }
64839
65065
  });
@@ -64938,11 +65164,11 @@ var require_detect_libc = __commonJS((exports, module) => {
64938
65164
  }
64939
65165
  return null;
64940
65166
  };
64941
- var familyFromInterpreterPath = (path19) => {
64942
- if (path19) {
64943
- if (path19.includes("/ld-musl-")) {
65167
+ var familyFromInterpreterPath = (path20) => {
65168
+ if (path20) {
65169
+ if (path20.includes("/ld-musl-")) {
64944
65170
  return MUSL;
64945
- } else if (path19.includes("/ld-linux-")) {
65171
+ } else if (path20.includes("/ld-linux-")) {
64946
65172
  return GLIBC;
64947
65173
  }
64948
65174
  }
@@ -64987,8 +65213,8 @@ var require_detect_libc = __commonJS((exports, module) => {
64987
65213
  cachedFamilyInterpreter = null;
64988
65214
  try {
64989
65215
  const selfContent = await readFile(SELF_PATH);
64990
- const path19 = interpreterPath(selfContent);
64991
- cachedFamilyInterpreter = familyFromInterpreterPath(path19);
65216
+ const path20 = interpreterPath(selfContent);
65217
+ cachedFamilyInterpreter = familyFromInterpreterPath(path20);
64992
65218
  } catch (e) {}
64993
65219
  return cachedFamilyInterpreter;
64994
65220
  };
@@ -64999,8 +65225,8 @@ var require_detect_libc = __commonJS((exports, module) => {
64999
65225
  cachedFamilyInterpreter = null;
65000
65226
  try {
65001
65227
  const selfContent = readFileSync2(SELF_PATH);
65002
- const path19 = interpreterPath(selfContent);
65003
- cachedFamilyInterpreter = familyFromInterpreterPath(path19);
65228
+ const path20 = interpreterPath(selfContent);
65229
+ cachedFamilyInterpreter = familyFromInterpreterPath(path20);
65004
65230
  } catch (e) {}
65005
65231
  return cachedFamilyInterpreter;
65006
65232
  };
@@ -66662,18 +66888,18 @@ var require_sharp = __commonJS((exports, module) => {
66662
66888
  `@img/sharp-${runtimePlatform}/sharp.node`,
66663
66889
  "@img/sharp-wasm32/sharp.node"
66664
66890
  ];
66665
- var path19;
66891
+ var path20;
66666
66892
  var sharp;
66667
66893
  var errors4 = [];
66668
- for (path19 of paths) {
66894
+ for (path20 of paths) {
66669
66895
  try {
66670
- sharp = __require(path19);
66896
+ sharp = __require(path20);
66671
66897
  break;
66672
66898
  } catch (err) {
66673
66899
  errors4.push(err);
66674
66900
  }
66675
66901
  }
66676
- if (sharp && path19.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
66902
+ if (sharp && path20.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
66677
66903
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
66678
66904
  err.code = "Unsupported CPU";
66679
66905
  errors4.push(err);
@@ -69535,15 +69761,15 @@ var require_color = __commonJS((exports, module) => {
69535
69761
  };
69536
69762
  }
69537
69763
  function wrapConversion(toModel, graph) {
69538
- const path19 = [graph[toModel].parent, toModel];
69764
+ const path20 = [graph[toModel].parent, toModel];
69539
69765
  let fn = conversions_default[graph[toModel].parent][toModel];
69540
69766
  let cur = graph[toModel].parent;
69541
69767
  while (graph[cur].parent) {
69542
- path19.unshift(graph[cur].parent);
69768
+ path20.unshift(graph[cur].parent);
69543
69769
  fn = link(conversions_default[graph[cur].parent][cur], fn);
69544
69770
  cur = graph[cur].parent;
69545
69771
  }
69546
- fn.conversion = path19;
69772
+ fn.conversion = path20;
69547
69773
  return fn;
69548
69774
  }
69549
69775
  function route(fromModel) {
@@ -70148,7 +70374,7 @@ var require_output = __commonJS((exports, module) => {
70148
70374
  Copyright 2013 Lovell Fuller and others.
70149
70375
  SPDX-License-Identifier: Apache-2.0
70150
70376
  */
70151
- var path19 = __require("path");
70377
+ var path20 = __require("path");
70152
70378
  var is = require_is();
70153
70379
  var sharp = require_sharp();
70154
70380
  var formats = new Map([
@@ -70179,9 +70405,9 @@ var require_output = __commonJS((exports, module) => {
70179
70405
  let err;
70180
70406
  if (!is.string(fileOut)) {
70181
70407
  err = new Error("Missing output file path");
70182
- } else if (is.string(this.options.input.file) && path19.resolve(this.options.input.file) === path19.resolve(fileOut)) {
70408
+ } else if (is.string(this.options.input.file) && path20.resolve(this.options.input.file) === path20.resolve(fileOut)) {
70183
70409
  err = new Error("Cannot use same file for input and output");
70184
- } else if (jp2Regex.test(path19.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
70410
+ } else if (jp2Regex.test(path20.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
70185
70411
  err = errJp2Save();
70186
70412
  }
70187
70413
  if (err) {
@@ -77428,11 +77654,11 @@ var init_transformers_node = __esm(() => {
77428
77654
  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}).`);
77429
77655
  }
77430
77656
  for (let i = 0;i < num_chunks; ++i) {
77431
- const path19 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
77432
- const fullPath = `${options.subfolder ?? ""}/${path19}`;
77657
+ const path20 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
77658
+ const fullPath = `${options.subfolder ?? ""}/${path20}`;
77433
77659
  externalDataPromises.push(new Promise(async (resolve4, reject) => {
77434
77660
  const data = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path);
77435
- resolve4(data instanceof Uint8Array ? { path: path19, data } : path19);
77661
+ resolve4(data instanceof Uint8Array ? { path: path20, data } : path20);
77436
77662
  }));
77437
77663
  }
77438
77664
  } else if (session_options.externalData !== undefined) {
@@ -90496,7 +90722,7 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90496
90722
  const blob = new Blob([wav], { type: "audio/wav" });
90497
90723
  return blob;
90498
90724
  }
90499
- async save(path19) {
90725
+ async save(path20) {
90500
90726
  let fn;
90501
90727
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) {
90502
90728
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) {
@@ -90504,14 +90730,14 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90504
90730
  }
90505
90731
  fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob;
90506
90732
  } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) {
90507
- fn = async (path20, blob) => {
90733
+ fn = async (path21, blob) => {
90508
90734
  let buffer = await blob.arrayBuffer();
90509
- node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path20, Buffer.from(buffer));
90735
+ node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path21, Buffer.from(buffer));
90510
90736
  };
90511
90737
  } else {
90512
90738
  throw new Error("Unable to save because filesystem is disabled in this environment.");
90513
90739
  }
90514
- await fn(path19, this.toBlob());
90740
+ await fn(path20, this.toBlob());
90515
90741
  }
90516
90742
  }
90517
90743
  },
@@ -90607,11 +90833,11 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90607
90833
  function calculateReflectOffset(i, w) {
90608
90834
  return Math.abs((i + w) % (2 * w) - w);
90609
90835
  }
90610
- function saveBlob(path19, blob) {
90836
+ function saveBlob(path20, blob) {
90611
90837
  const dataURL = URL.createObjectURL(blob);
90612
90838
  const downloadLink = document.createElement("a");
90613
90839
  downloadLink.href = dataURL;
90614
- downloadLink.download = path19;
90840
+ downloadLink.download = path20;
90615
90841
  downloadLink.click();
90616
90842
  downloadLink.remove();
90617
90843
  URL.revokeObjectURL(dataURL);
@@ -91212,8 +91438,8 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
91212
91438
  }
91213
91439
 
91214
91440
  class FileCache {
91215
- constructor(path19) {
91216
- this.path = path19;
91441
+ constructor(path20) {
91442
+ this.path = path20;
91217
91443
  }
91218
91444
  async match(request) {
91219
91445
  let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].join(this.path, request);
@@ -91969,20 +92195,20 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
91969
92195
  }
91970
92196
  return this;
91971
92197
  }
91972
- async save(path19) {
92198
+ async save(path20) {
91973
92199
  if (IS_BROWSER_OR_WEBWORKER) {
91974
92200
  if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) {
91975
92201
  throw new Error("Unable to save an image from a Web Worker.");
91976
92202
  }
91977
- const extension = path19.split(".").pop().toLowerCase();
92203
+ const extension = path20.split(".").pop().toLowerCase();
91978
92204
  const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
91979
92205
  const blob = await this.toBlob(mime);
91980
- (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path19, blob);
92206
+ (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path20, blob);
91981
92207
  } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) {
91982
92208
  throw new Error("Unable to save the image because filesystem is disabled in this environment.");
91983
92209
  } else {
91984
92210
  const img = this.toSharp();
91985
- return await img.toFile(path19);
92211
+ return await img.toFile(path20);
91986
92212
  }
91987
92213
  }
91988
92214
  toSharp() {
@@ -95471,16 +95697,16 @@ class LocalTransformersEmbeddingProvider {
95471
95697
  const out = await extractor("test", { pooling: "mean", normalize: true });
95472
95698
  const vec = Array.from(out.data);
95473
95699
  if (!Array.isArray(vec) || vec.length !== this.dimensions) {
95474
- logger.error(`[${this.id}] Invalid embedding dimensions`, undefined, { expected: this.dimensions, got: vec.length });
95700
+ logger.error("LocalTransformersProvider: invalid embedding dimensions", undefined, { providerId: this.id, expected: this.dimensions, got: vec.length });
95475
95701
  return false;
95476
95702
  }
95477
95703
  if (vec.some((v) => typeof v !== "number" || isNaN(v))) {
95478
- logger.error(`[${this.id}] Invalid embedding values (not numbers)`);
95704
+ logger.error("LocalTransformersProvider: invalid embedding values (not numbers)", undefined, { providerId: this.id });
95479
95705
  return false;
95480
95706
  }
95481
95707
  return true;
95482
95708
  } catch (error51) {
95483
- logger.error(`[${this.id}] Local provider unavailable`, error51);
95709
+ logger.error("LocalTransformersProvider: provider unavailable", error51, { providerId: this.id });
95484
95710
  return false;
95485
95711
  }
95486
95712
  }
@@ -95520,7 +95746,13 @@ async function withRetry(fn, config3, context2) {
95520
95746
  lastError2 = error51;
95521
95747
  if (attempt < config3.maxRetries) {
95522
95748
  const delay2 = getRetryDelay(attempt, config3);
95523
- logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError2.message });
95749
+ logger.warn("EmbeddingProvider: operation failed, retrying", {
95750
+ context: context2,
95751
+ attempt: attempt + 1,
95752
+ maxAttempts: config3.maxRetries + 1,
95753
+ delayMs: delay2,
95754
+ error: lastError2
95755
+ });
95524
95756
  await sleep(delay2);
95525
95757
  }
95526
95758
  }
@@ -95836,7 +96068,7 @@ var init_provider = __esm(() => {
95836
96068
  return output;
95837
96069
  }, this.retryConfig, `[${this.id}] embedBatchDirect (${texts.length} texts)`), this.timeout, `[${this.id}] embedBatchDirect`);
95838
96070
  } catch (error51) {
95839
- logger.warn(`[${this.id}] Ollama batch endpoint unavailable, falling back to sequential embeds: ${error51.message}`);
96071
+ logger.warn("EmbeddingProvider: Ollama batch endpoint unavailable, falling back to sequential embeds", { providerId: this.id, textCount: texts.length, error: error51 });
95840
96072
  const embeddings = [];
95841
96073
  let consecutiveFailures = 0;
95842
96074
  for (const text2 of texts) {
@@ -95875,11 +96107,11 @@ var init_provider = __esm(() => {
95875
96107
  });
95876
96108
  clearTimeout(timeoutId);
95877
96109
  if (!response.ok) {
95878
- logger.error(`[${this.id}] Ollama API returned ${response.status}`);
96110
+ logger.error("EmbeddingProvider: Ollama API returned non-OK status", undefined, { providerId: this.id, status: response.status });
95879
96111
  return false;
95880
96112
  }
95881
96113
  } catch {
95882
- logger.error(`[${this.id}] Ollama service unreachable`, undefined, { baseURL: this.baseURL, timeoutMs: 2000 });
96114
+ logger.error("EmbeddingProvider: Ollama service unreachable", undefined, { providerId: this.id, baseURL: this.baseURL, timeoutMs: 2000 });
95883
96115
  return false;
95884
96116
  }
95885
96117
  }
@@ -95889,16 +96121,16 @@ var init_provider = __esm(() => {
95889
96121
  if (Array.isArray(embedding)) {
95890
96122
  this.lastDimensionMismatch = new DimensionMismatchError(this.id, this.dimensions, embedding.length);
95891
96123
  }
95892
- logger.error(`[${this.id}] Invalid embedding dimensions`, undefined, { expected: this.dimensions, got: embedding.length });
96124
+ logger.error("EmbeddingProvider: invalid embedding dimensions", undefined, { providerId: this.id, expected: this.dimensions, got: embedding.length });
95893
96125
  return false;
95894
96126
  }
95895
96127
  if (!embedding.every((v) => typeof v === "number" && !isNaN(v))) {
95896
- logger.error(`[${this.id}] Invalid embedding values (not numbers)`);
96128
+ logger.error("EmbeddingProvider: invalid embedding values (not numbers)", undefined, { providerId: this.id });
95897
96129
  return false;
95898
96130
  }
95899
96131
  return true;
95900
96132
  } catch (error51) {
95901
- logger.error(`[${this.id}] Provider unavailable`, error51);
96133
+ logger.error("EmbeddingProvider: provider unavailable", error51, { providerId: this.id });
95902
96134
  return false;
95903
96135
  }
95904
96136
  }
@@ -101516,10 +101748,10 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a;
101516
101748
  super(t, "P2023", r);
101517
101749
  }
101518
101750
  };
101519
- var fs14 = new WeakMap;
101751
+ var fs15 = new WeakMap;
101520
101752
  function Ep(e) {
101521
- let t = fs14.get(e);
101522
- return t || (t = Object.entries(e), fs14.set(e, t)), t;
101753
+ let t = fs15.get(e);
101754
+ return t || (t = Object.entries(e), fs15.set(e, t)), t;
101523
101755
  }
101524
101756
  function hs(e, t, r) {
101525
101757
  switch (t.type) {
@@ -105487,7 +105719,7 @@ var require_prisma = __commonJS((exports) => {
105487
105719
  Prisma.JsonNull = JsonNull2;
105488
105720
  Prisma.AnyNull = AnyNull2;
105489
105721
  Prisma.NullTypes = NullTypes2;
105490
- var path19 = __require("path");
105722
+ var path20 = __require("path");
105491
105723
  exports.Prisma.TransactionIsolationLevel = makeStrictEnum2({
105492
105724
  ReadUncommitted: "ReadUncommitted",
105493
105725
  ReadCommitted: "ReadCommitted",
@@ -108114,7 +108346,7 @@ function getPrismaClient2() {
108114
108346
  const pg2 = _adapters.loadPg();
108115
108347
  const { PrismaPg: PrismaPg2 } = _adapters.loadPrismaPg();
108116
108348
  const pool = new pg2.Pool({ connectionString: databaseUrl, max: 10, idleTimeoutMillis: 30000, connectionTimeoutMillis: 5000 });
108117
- pool.on("error", (error51) => logger.error("Unexpected PG pool error", error51));
108349
+ pool.on("error", (error51) => logger.error("prisma-client: unexpected PG pool error", error51, { poolMax: 10 }));
108118
108350
  prismaPool = pool;
108119
108351
  prismaInstance = new import_prisma.PrismaClient({ adapter: new PrismaPg2(pool) });
108120
108352
  logger.info("Prisma Client initialized with PostgreSQL");
@@ -108423,7 +108655,10 @@ var init_config2 = __esm(() => {
108423
108655
  "local"
108424
108656
  ]);
108425
108657
  if (!SELECTABLE_PROVIDERS.has(selectedProvider)) {
108426
- 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" });
108658
+ logger.warn("EmbeddingConfig: selected provider has no runtime entry, falling back to priority order", {
108659
+ selectedProvider,
108660
+ source: process.env.EMBEDDING_PROVIDER ? "EMBEDDING_PROVIDER env" : "config.json embedding.provider"
108661
+ });
108427
108662
  }
108428
108663
  embeddingProviders = {
108429
108664
  google: (() => {
@@ -108463,7 +108698,12 @@ var init_config2 = __esm(() => {
108463
108698
  const envDimensions = Number.isInteger(rawEnvDimensions) && rawEnvDimensions > 0 ? rawEnvDimensions : undefined;
108464
108699
  const resolvedDimensions = resolveEmbeddingDimensions(model, file2?.dimensions, envDimensions);
108465
108700
  if (resolvedDimensions.correctedFrom !== undefined) {
108466
- 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.");
108701
+ logger.warn("EmbeddingConfig: ollama config.json dimensions mismatch corrected", {
108702
+ provider: "ollama",
108703
+ model,
108704
+ configuredDimensions: resolvedDimensions.correctedFrom,
108705
+ correctedDimensions: resolvedDimensions.dimensions
108706
+ });
108467
108707
  }
108468
108708
  return {
108469
108709
  provider: "ollama",
@@ -108615,8 +108855,8 @@ class EmbeddingService {
108615
108855
  dimensions: this.provider.dimensions
108616
108856
  });
108617
108857
  } catch (error51) {
108618
- logger.error("Failed to initialize embedding service", error51);
108619
- logger.warn("Embedding service will use fallback mode");
108858
+ logger.error("Failed to initialize embedding service", error51, { stage: "initialize" });
108859
+ logger.warn("Embedding service will use fallback mode", { stage: "initialize" });
108620
108860
  }
108621
108861
  }
108622
108862
  async ensureInitialized() {
@@ -108698,7 +108938,7 @@ async function tryCreateProvider(config3, providerId, skipHealthCheck) {
108698
108938
  return { provider };
108699
108939
  }
108700
108940
  function refuseOnDimensionMismatch(providerId, mismatch) {
108701
- 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.");
108941
+ logger.error("EmbeddingProvider: configured provider failed with a dimension mismatch, refusing to fall through", mismatch, { providerId, configuredDimensions: mismatch.expected, modelDimensions: mismatch.got });
108702
108942
  throw mismatch;
108703
108943
  }
108704
108944
  async function createEmbeddingProvider(options = {}) {
@@ -108797,6 +109037,7 @@ Write the hypothetical implementation paragraph.`;
108797
109037
  }
108798
109038
  async function rewriteQuery(query, surface, opts = {}) {
108799
109039
  const res = await surface.object(rewritePrompt(query), QueryRewriteSchema, {
109040
+ label: "query-rewrite",
108800
109041
  system: REWRITE_SYSTEM,
108801
109042
  timeoutMs: opts.timeoutMs
108802
109043
  });
@@ -108809,6 +109050,7 @@ async function rewriteQuery(query, surface, opts = {}) {
108809
109050
  }
108810
109051
  async function hyde(query, surface, embedFn, opts = {}) {
108811
109052
  const text2 = await surface.complete(hydePrompt(query), {
109053
+ label: "hyde",
108812
109054
  system: HYDE_SYSTEM,
108813
109055
  timeoutMs: opts.timeoutMs
108814
109056
  });
@@ -108822,7 +109064,7 @@ async function hyde(query, surface, embedFn, opts = {}) {
108822
109064
  return vec;
108823
109065
  } catch (e) {
108824
109066
  logger.warn("hyde embed failed \u2014 skipping HyDE stream", {
108825
- error: e.message
109067
+ error: e
108826
109068
  });
108827
109069
  return null;
108828
109070
  }
@@ -110550,7 +110792,7 @@ class KeywordSearchPg {
110550
110792
  `);
110551
110793
  this.trigramAvailable = true;
110552
110794
  } catch (error51) {
110553
- logger.warn("pg_trgm unavailable \u2014 trigram RRF stream disabled on PG", { err: error51.message });
110795
+ logger.warn("pg_trgm unavailable \u2014 trigram RRF stream disabled on PG", { error: error51 });
110554
110796
  this.trigramAvailable = false;
110555
110797
  }
110556
110798
  logger.info("PostgreSQL keyword search initialized", {
@@ -111089,7 +111331,8 @@ var init_postgres_vector_store = __esm(() => {
111089
111331
  this.schemaDimensions = providerDimensions;
111090
111332
  const { rows } = await client.query(`SELECT tablename FROM pg_tables WHERE tablename = $1`, [this.tableName]);
111091
111333
  if (rows.length === 0) {
111092
- logger.warn(`Table ${this.tableName} not found. Creating fallback table.`, {
111334
+ logger.warn("PostgresVectorStore: table not found, creating fallback table", {
111335
+ tableName: this.tableName,
111093
111336
  note: 'Run "prisma migrate deploy" to create tables via migrations'
111094
111337
  });
111095
111338
  await this.createFallbackTable(client, providerDimensions);
@@ -111126,10 +111369,12 @@ var init_postgres_vector_store = __esm(() => {
111126
111369
  if (projects.length === 0)
111127
111370
  continue;
111128
111371
  const otherDim = tablename.match(/_([0-9]+)d$/)?.[1];
111129
- 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.`, {
111372
+ logger.warn("PostgresVectorStore: orphaned chunks detected, embedding model likely changed, reindex required", {
111130
111373
  currentTable: this.tableName,
111131
111374
  currentCount,
111375
+ currentDim,
111132
111376
  orphanedTable: tablename,
111377
+ orphanedDim: otherDim,
111133
111378
  affectedProjects: projects.map((p) => ({ projectId: p.project_id, chunks: p.n }))
111134
111379
  });
111135
111380
  }
@@ -111273,7 +111518,7 @@ var init_postgres_vector_store = __esm(() => {
111273
111518
  logger.warn("[postgres] Sub-batch embedding failed, falling back per-document", {
111274
111519
  subBatchIndex: Math.floor(i / EMBED_SUB_BATCH_SIZE),
111275
111520
  count: subBatch.length,
111276
- error: error51.message
111521
+ error: error51
111277
111522
  });
111278
111523
  }
111279
111524
  if (embeddings) {
@@ -111285,7 +111530,7 @@ var init_postgres_vector_store = __esm(() => {
111285
111530
  logger.warn("[postgres] Sub-batch insert failed, falling back per-document", {
111286
111531
  subBatchIndex: Math.floor(i / EMBED_SUB_BATCH_SIZE),
111287
111532
  count: subBatch.length,
111288
- error: error51.message
111533
+ error: error51
111289
111534
  });
111290
111535
  }
111291
111536
  }
@@ -111298,7 +111543,7 @@ var init_postgres_vector_store = __esm(() => {
111298
111543
  totalFailed++;
111299
111544
  logger.warn("[postgres] Skipping document due to embedding/insert error", {
111300
111545
  id: doc2.id,
111301
- error: singleError.message
111546
+ error: singleError
111302
111547
  });
111303
111548
  }
111304
111549
  }
@@ -111970,7 +112215,9 @@ class SearchAnalyticsPg {
111970
112215
  }
111971
112216
  trackSearch(event) {
111972
112217
  this.trackSearchAsync(event).catch((err) => {
111973
- logger.error("Failed to track search event", err);
112218
+ logger.error("Failed to track search event", err, {
112219
+ projectId: event.projectId
112220
+ });
111974
112221
  });
111975
112222
  }
111976
112223
  async trackSearchAsync(event) {
@@ -111995,7 +112242,9 @@ class SearchAnalyticsPg {
111995
112242
  event.score || null
111996
112243
  ]);
111997
112244
  } catch (error51) {
111998
- logger.error("Failed to track search event in PostgreSQL", error51);
112245
+ logger.error("Failed to track search event in PostgreSQL", error51, {
112246
+ projectId: event.projectId
112247
+ });
111999
112248
  }
112000
112249
  }
112001
112250
  async recordQuery(query, projectId, resultsCount = 0, duration3 = 0, cacheHit = false) {
@@ -114596,7 +114845,11 @@ class GraphStorePg {
114596
114845
  `;
114597
114846
  return rows[0] ? rowToEdge(rows[0]) : null;
114598
114847
  } catch (error51) {
114599
- logger.error("Failed to create edge", error51);
114848
+ logger.error("Failed to create edge", error51, {
114849
+ sourceId: edge.sourceId,
114850
+ targetId: edge.targetId,
114851
+ relationType: edge.relationType
114852
+ });
114600
114853
  return null;
114601
114854
  }
114602
114855
  }
@@ -115192,7 +115445,7 @@ class PgSynapseSessionStore {
115192
115445
  } catch (e) {
115193
115446
  this.hydrateFailedAt = Date.now();
115194
115447
  logger.warn("PgSynapseSessionStore hydrate failed (best-effort)", {
115195
- error: e.message
115448
+ error: e
115196
115449
  });
115197
115450
  } finally {
115198
115451
  this.hydrating = null;
@@ -115327,7 +115580,7 @@ class PgSynapseSessionStore {
115327
115580
  const next = prev.then(fn).catch((e) => {
115328
115581
  logger.warn("PgSynapseSessionStore write failed (best-effort)", {
115329
115582
  key,
115330
- error: e.message
115583
+ error: e
115331
115584
  });
115332
115585
  });
115333
115586
  this.inflight.set(key, next);
@@ -115433,7 +115686,7 @@ class SessionRegistry {
115433
115686
  try {
115434
115687
  this.store?.save(session);
115435
115688
  } catch (error51) {
115436
- logger.warn("[SessionRegistry] store save failed:", { error: error51.message });
115689
+ logger.warn("SessionRegistry: store save failed", { sessionId: session.sessionId, error: error51 });
115437
115690
  }
115438
115691
  return session;
115439
115692
  }
@@ -115441,7 +115694,7 @@ class SessionRegistry {
115441
115694
  try {
115442
115695
  await this.store?.ensureReady();
115443
115696
  } catch (error51) {
115444
- logger.warn("[SessionRegistry] store ensureReady failed:", { error: error51.message });
115697
+ logger.warn("SessionRegistry: store ensureReady failed", { error: error51 });
115445
115698
  }
115446
115699
  }
115447
115700
  async getAsync(sessionId, now2 = Date.now()) {
@@ -115462,7 +115715,7 @@ class SessionRegistry {
115462
115715
  session = loaded;
115463
115716
  }
115464
115717
  } catch (error51) {
115465
- logger.warn("[SessionRegistry] store load failed:", { error: error51.message });
115718
+ logger.warn("SessionRegistry: store load failed", { sessionId, error: error51 });
115466
115719
  }
115467
115720
  }
115468
115721
  if (!session)
@@ -115472,7 +115725,7 @@ class SessionRegistry {
115472
115725
  try {
115473
115726
  this.store?.delete(sessionId);
115474
115727
  } catch (error51) {
115475
- logger.warn("[SessionRegistry] store delete (expired) failed:", { error: error51.message });
115728
+ logger.warn("SessionRegistry: store delete (expired) failed", { sessionId, error: error51 });
115476
115729
  }
115477
115730
  return null;
115478
115731
  }
@@ -115494,7 +115747,7 @@ class SessionRegistry {
115494
115747
  try {
115495
115748
  this.store?.save(session);
115496
115749
  } catch (error51) {
115497
- logger.warn("[SessionRegistry] store save (updateTaskContext) failed:", { error: error51.message });
115750
+ logger.warn("SessionRegistry: store save (updateTaskContext) failed", { sessionId, error: error51 });
115498
115751
  }
115499
115752
  return session;
115500
115753
  }
@@ -115521,7 +115774,7 @@ class SessionRegistry {
115521
115774
  try {
115522
115775
  this.store?.recordAccess(sessionId, memoryId, nextCount);
115523
115776
  } catch (error51) {
115524
- logger.warn("[SessionRegistry] store recordAccess failed:", { error: error51.message });
115777
+ logger.warn("SessionRegistry: store recordAccess failed", { sessionId, memoryId, error: error51 });
115525
115778
  }
115526
115779
  }
115527
115780
  delete(sessionId) {
@@ -115529,7 +115782,7 @@ class SessionRegistry {
115529
115782
  try {
115530
115783
  this.store?.delete(sessionId);
115531
115784
  } catch (error51) {
115532
- logger.warn("[SessionRegistry] store delete failed:", { error: error51.message });
115785
+ logger.warn("SessionRegistry: store delete failed", { sessionId, error: error51 });
115533
115786
  }
115534
115787
  return removed;
115535
115788
  }
@@ -115557,7 +115810,7 @@ function getSessionRegistry() {
115557
115810
  const { getSessionStore: getSessionStore2 } = (init_session_store(), __toCommonJS(exports_session_store));
115558
115811
  store2 = getSessionStore2();
115559
115812
  } catch (error51) {
115560
- logger.warn("[SessionRegistry] store init failed, falling back to MemorySessionStore:", { error: error51.message });
115813
+ logger.warn("SessionRegistry: store init failed, falling back to MemorySessionStore", { error: error51 });
115561
115814
  const { MemorySessionStore: MemorySessionStore2 } = (init_session_store(), __toCommonJS(exports_session_store));
115562
115815
  store2 = new MemorySessionStore2;
115563
115816
  }
@@ -116374,19 +116627,22 @@ class LLMJudgeReranker {
116374
116627
  const tail = results.slice(k);
116375
116628
  const prompt = buildPrompt(query, head);
116376
116629
  let verdict;
116630
+ let verdictError;
116377
116631
  try {
116378
- const res = await this.llm.object(prompt, RerankVerdictSchema, { modelRole: "code" });
116632
+ const res = await this.llm.object(prompt, RerankVerdictSchema, { label: "reranker", modelRole: "code" });
116379
116633
  verdict = res.ok ? res.value ?? null : null;
116634
+ verdictError = res.ok ? undefined : res.error;
116380
116635
  } catch (e) {
116381
116636
  logger.warn("LLMJudgeReranker threw \u2014 degrading to input order", {
116382
116637
  query,
116383
- error: e.message
116638
+ error: e
116384
116639
  });
116385
116640
  return results;
116386
116641
  }
116387
116642
  if (!verdict) {
116388
116643
  logger.warn("LLMJudgeReranker got {ok:false} \u2014 degrading to input order", {
116389
- query
116644
+ query,
116645
+ error: verdictError
116390
116646
  });
116391
116647
  return results;
116392
116648
  }
@@ -117185,10 +117441,10 @@ var init_chunker_code = __esm(() => {
117185
117441
  });
117186
117442
 
117187
117443
  // ../../packages/core/dist/services/search/smart-chunker.js
117188
- import path19 from "path";
117444
+ import path20 from "path";
117189
117445
  function smartChunk(content, filePath, config3 = {}) {
117190
117446
  const cfg = { ...DEFAULT_CONFIG, ...config3 };
117191
- const ext2 = path19.extname(filePath).toLowerCase();
117447
+ const ext2 = path20.extname(filePath).toLowerCase();
117192
117448
  const relativePath = filePath;
117193
117449
  const fileImports = isCodeFile(ext2) ? extractFileImports(content, ext2) : undefined;
117194
117450
  let chunks;
@@ -117526,8 +117782,8 @@ var init_embedding_freshness = __esm(() => {
117526
117782
  });
117527
117783
 
117528
117784
  // ../../packages/core/dist/services/search/project-indexer.js
117529
- import fs14 from "fs/promises";
117530
- import path20 from "path";
117785
+ import fs15 from "fs/promises";
117786
+ import path21 from "path";
117531
117787
  import { randomUUID as randomUUID3 } from "crypto";
117532
117788
  async function runWithIndexLock(lockMap, projectId, work) {
117533
117789
  const prevLock = lockMap.get(projectId);
@@ -117570,7 +117826,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
117570
117826
  dot: false
117571
117827
  });
117572
117828
  const filteredFiles = files.filter((file2) => {
117573
- const relativePath = path20.relative(projectPath, file2);
117829
+ const relativePath = path21.relative(projectPath, file2);
117574
117830
  const shouldIgnore = ig.ignores(relativePath);
117575
117831
  if (shouldIgnore) {
117576
117832
  logger.debug("Ignoring file per .gitignore during indexing", {
@@ -117610,7 +117866,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
117610
117866
  });
117611
117867
  }
117612
117868
  }
117613
- const indexedFilesList = filteredFiles.map((f) => path20.relative(projectPath, f));
117869
+ const indexedFilesList = filteredFiles.map((f) => path21.relative(projectPath, f));
117614
117870
  await deps.indexManager.updateIndexMetadata(projectId, projectPath, indexedFilesList);
117615
117871
  logger.info("Project indexing completed", {
117616
117872
  projectId,
@@ -117740,7 +117996,7 @@ async function ensureFreshIndex(deps, projectId, projectPath, options = {}) {
117740
117996
  let errors4 = 0;
117741
117997
  for (const relativeFilePath of filesToReindex) {
117742
117998
  try {
117743
- const fullPath = path20.join(projectPath, relativeFilePath);
117999
+ const fullPath = path21.join(projectPath, relativeFilePath);
117744
118000
  const result = await deps.indexFile(fullPath, projectId, projectPath, centralityMap);
117745
118001
  filesIndexed++;
117746
118002
  chunksIndexed += result.chunks;
@@ -117800,8 +118056,8 @@ async function checkSearchAdmission(deps, projectId, projectPath) {
117800
118056
  }
117801
118057
  async function indexFile(deps, filePath, projectId, projectRoot, centralityMap) {
117802
118058
  projectId = await getProjectIdentityAliasResolver().resolve(projectId);
117803
- const content = await fs14.readFile(filePath, "utf-8");
117804
- const relativePath = path20.relative(projectRoot, filePath);
118059
+ const content = await fs15.readFile(filePath, "utf-8");
118060
+ const relativePath = path21.relative(projectRoot, filePath);
117805
118061
  const maxFileSize = config.get("security").maxFileSize || 1024 * 1024;
117806
118062
  if (content.length > maxFileSize) {
117807
118063
  logger.warn("File too large, skipping", {
@@ -117821,7 +118077,7 @@ async function indexFile(deps, filePath, projectId, projectRoot, centralityMap)
117821
118077
  chunkIndex: i,
117822
118078
  totalChunks: chunks.length,
117823
118079
  type: chunk.type,
117824
- language: path20.extname(filePath).slice(1),
118080
+ language: path21.extname(filePath).slice(1),
117825
118081
  lineStart: chunk.lineStart,
117826
118082
  lineEnd: chunk.lineEnd,
117827
118083
  label: chunk.label,
@@ -118232,7 +118488,7 @@ class TaskEnvelopeService {
118232
118488
  errors4.push("prime");
118233
118489
  logger.warn("synapse_task_begin: prime sub-step failed", {
118234
118490
  sessionId,
118235
- error: err instanceof Error ? err.message : String(err)
118491
+ error: err
118236
118492
  });
118237
118493
  }
118238
118494
  }
@@ -118255,7 +118511,7 @@ class TaskEnvelopeService {
118255
118511
  errors4.push("search");
118256
118512
  logger.warn("synapse_task_begin: search sub-step failed", {
118257
118513
  sessionId,
118258
- error: err instanceof Error ? err.message : String(err)
118514
+ error: err
118259
118515
  });
118260
118516
  }
118261
118517
  if (firstHitFile) {
@@ -118278,7 +118534,7 @@ class TaskEnvelopeService {
118278
118534
  errors4.push("prefetch");
118279
118535
  logger.warn("synapse_task_begin: prefetch sub-step failed", {
118280
118536
  sessionId,
118281
- error: err instanceof Error ? err.message : String(err)
118537
+ error: err
118282
118538
  });
118283
118539
  }
118284
118540
  }
@@ -118289,7 +118545,7 @@ class TaskEnvelopeService {
118289
118545
  errors4.push("access");
118290
118546
  logger.warn("synapse_task_begin: access sub-step failed", {
118291
118547
  sessionId,
118292
- error: err instanceof Error ? err.message : String(err)
118548
+ error: err
118293
118549
  });
118294
118550
  }
118295
118551
  }
@@ -118632,7 +118888,7 @@ async function applySynapseState(deps, baseResults, query, projectId, sessionId,
118632
118888
  logger.warn("Synapse session lookup failed \u2014 using stateless search", {
118633
118889
  sessionId,
118634
118890
  projectId,
118635
- error: error51.message
118891
+ error: error51
118636
118892
  });
118637
118893
  return baseResults;
118638
118894
  }
@@ -118653,7 +118909,7 @@ async function applySynapseState(deps, baseResults, query, projectId, sessionId,
118653
118909
  logger.warn("Synapse processing failed \u2014 using stateless search", {
118654
118910
  sessionId,
118655
118911
  projectId,
118656
- error: error51.message
118912
+ error: error51
118657
118913
  });
118658
118914
  return baseResults;
118659
118915
  }
@@ -119548,7 +119804,7 @@ class RelationExtractor {
119548
119804
  } catch (error51) {
119549
119805
  logger.warn("RelationExtractor: extraction failed", {
119550
119806
  memoryId,
119551
- error: error51.message
119807
+ error: error51
119552
119808
  });
119553
119809
  }
119554
119810
  return edgesCreated;
@@ -119995,7 +120251,7 @@ class MemoryGraphService {
119995
120251
  } catch (error51) {
119996
120252
  logger.warn("Graph update failed after memory store", {
119997
120253
  memoryId,
119998
- error: error51.message
120254
+ error: error51
119999
120255
  });
120000
120256
  }
120001
120257
  }
@@ -120011,7 +120267,7 @@ class MemoryGraphService {
120011
120267
  } catch (error51) {
120012
120268
  logger.warn("Graph cleanup failed after memory delete", {
120013
120269
  memoryId,
120014
- error: error51.message
120270
+ error: error51
120015
120271
  });
120016
120272
  }
120017
120273
  }
@@ -120160,7 +120416,7 @@ async function consolidateWindow(candidates, llm2, opts = {}) {
120160
120416
  if (!llm2.isEnabled())
120161
120417
  return null;
120162
120418
  const prompt = buildPrompt2(window2);
120163
- const result = await llm2.object(prompt, ConsolidatedBatchSchema);
120419
+ const result = await llm2.object(prompt, ConsolidatedBatchSchema, { label: "memory-consolidation" });
120164
120420
  if (!result.ok || !result.value)
120165
120421
  return null;
120166
120422
  const batch = {
@@ -120261,7 +120517,7 @@ class MemoryConsolidationJob {
120261
120517
  } catch (error51) {
120262
120518
  logger.warn("Memory consolidation skipped", {
120263
120519
  trigger,
120264
- error: error51.message
120520
+ error: error51
120265
120521
  });
120266
120522
  } finally {
120267
120523
  this.running = false;
@@ -120284,7 +120540,7 @@ class MemoryConsolidationJob {
120284
120540
  candidates = await Promise.resolve(repo.listConsolidationCandidates(staleSinceMs, 500));
120285
120541
  } catch (e) {
120286
120542
  logger.warn("consolidation: candidate list failed (decay)", {
120287
- error: e.message
120543
+ error: e
120288
120544
  });
120289
120545
  return 0;
120290
120546
  }
@@ -120306,7 +120562,7 @@ class MemoryConsolidationJob {
120306
120562
  } catch (e) {
120307
120563
  logger.warn("consolidation: decay write failed", {
120308
120564
  id: row.id,
120309
- error: e.message
120565
+ error: e
120310
120566
  });
120311
120567
  }
120312
120568
  }
@@ -120335,14 +120591,14 @@ class MemoryConsolidationJob {
120335
120591
  } catch (e) {
120336
120592
  logger.warn("consolidation: soft-delete failed", {
120337
120593
  id: row.id,
120338
- error: e.message
120594
+ error: e
120339
120595
  });
120340
120596
  }
120341
120597
  }
120342
120598
  }
120343
120599
  } catch (e) {
120344
120600
  logger.warn("consolidation: prune scan failed", {
120345
- error: e.message
120601
+ error: e
120346
120602
  });
120347
120603
  }
120348
120604
  return pruned;
@@ -120353,7 +120609,7 @@ class MemoryConsolidationJob {
120353
120609
  candidates = await Promise.resolve(repo.listConsolidationCandidates(staleSinceMs, 200));
120354
120610
  } catch (e) {
120355
120611
  logger.warn("consolidation: candidate list failed (merge)", {
120356
- error: e.message
120612
+ error: e
120357
120613
  });
120358
120614
  return { merged: 0, batchesCreated: 0 };
120359
120615
  }
@@ -120379,7 +120635,7 @@ class MemoryConsolidationJob {
120379
120635
  } catch (e) {
120380
120636
  logger.warn("consolidation: merge insert failed", {
120381
120637
  batchId: batch.id,
120382
- error: e.message
120638
+ error: e
120383
120639
  });
120384
120640
  return { merged: 0, batchesCreated: 0 };
120385
120641
  }
@@ -120392,7 +120648,7 @@ class MemoryConsolidationJob {
120392
120648
  logger.warn("consolidation: addSupercedesEdge failed", {
120393
120649
  newId,
120394
120650
  sourceId,
120395
- error: e.message
120651
+ error: e
120396
120652
  });
120397
120653
  }
120398
120654
  }
@@ -120432,7 +120688,7 @@ class MemoryConsolidationJob {
120432
120688
  return result;
120433
120689
  } catch (e) {
120434
120690
  logger.warn("consolidation: promote (PG) failed", {
120435
- error: e.message
120691
+ error: e
120436
120692
  });
120437
120693
  return 0;
120438
120694
  }
@@ -120471,19 +120727,22 @@ class SalienceJudge {
120471
120727
  }
120472
120728
  const prompt = buildPrompt3(trimmed, type);
120473
120729
  let verdict;
120730
+ let verdictError;
120474
120731
  try {
120475
- const res = await this.llm.object(prompt, SalienceSchema);
120732
+ const res = await this.llm.object(prompt, SalienceSchema, { label: "salience-judge" });
120476
120733
  verdict = res.ok ? res.value ?? null : null;
120734
+ verdictError = res.ok ? undefined : res.error;
120477
120735
  } catch (e) {
120478
120736
  logger.warn("SalienceJudge threw \u2014 degrading to neutral default", {
120479
120737
  type,
120480
- error: e.message
120738
+ error: e
120481
120739
  });
120482
120740
  return { salience: NEUTRAL_SALIENCE, source: "default" };
120483
120741
  }
120484
120742
  if (!verdict) {
120485
120743
  logger.warn("SalienceJudge got {ok:false} \u2014 degrading to neutral default", {
120486
- type
120744
+ type,
120745
+ error: verdictError
120487
120746
  });
120488
120747
  return { salience: NEUTRAL_SALIENCE, source: "default" };
120489
120748
  }
@@ -120698,7 +120957,8 @@ class MemoryController {
120698
120957
  }
120699
120958
  } catch (err) {
120700
120959
  logger.warn("Graph enrichment failed", {
120701
- error: err.message
120960
+ projectId,
120961
+ error: err
120702
120962
  });
120703
120963
  }
120704
120964
  }
@@ -120900,7 +121160,7 @@ class CodeCompressor {
120900
121160
  }
120901
121161
  const prompt = buildLlmCompressPrompt(content, language3, targetRatio, preservedElements);
120902
121162
  try {
120903
- const res = await this.llmCompleteFn(prompt, { timeoutMs, modelRole: "code" });
121163
+ const res = await this.llmCompleteFn(prompt, { label: "code-compressor", timeoutMs, modelRole: "code" });
120904
121164
  if (res.ok && typeof res.value === "string" && res.value.trim().length > 0 && res.value.length <= content.length) {
120905
121165
  compressed = res.value;
120906
121166
  compressionSource = "llm";
@@ -120940,7 +121200,10 @@ class CodeCompressor {
120940
121200
  });
120941
121201
  return compressedContent;
120942
121202
  } catch (error51) {
120943
- logger.error("Code compression failed", error51);
121203
+ logger.error("Code compression failed", error51, {
121204
+ strategy: useStrategy,
121205
+ originalLength: content.length
121206
+ });
120944
121207
  return CompressedContent.identity(content);
120945
121208
  }
120946
121209
  }
@@ -121250,9 +121513,9 @@ class TokenMetrics {
121250
121513
  }
121251
121514
  throw new Error("Model not found in models.dev");
121252
121515
  } catch (error51) {
121253
- logger.warn("Failed to fetch pricing from models.dev, using fallback", {
121516
+ logger.warn("TokenMetrics: failed to fetch pricing from models.dev, using fallback", {
121254
121517
  modelId,
121255
- error: error51 instanceof Error ? error51.message : String(error51)
121518
+ error: error51
121256
121519
  });
121257
121520
  const fallback = FALLBACK_PRICING2[modelId] || FALLBACK_PRICING2["gpt-4"];
121258
121521
  this.pricingCache.set(modelId, {
@@ -122372,16 +122635,16 @@ function detectRoutes(httpEdges, defs, opts = {}) {
122372
122635
  const seen = new Set;
122373
122636
  const out = [];
122374
122637
  for (const e of httpEdges) {
122375
- const path21 = e.route;
122376
- if (!path21)
122638
+ const path22 = e.route;
122639
+ if (!path22)
122377
122640
  continue;
122378
122641
  const method = (e.method ?? "ANY").toUpperCase();
122379
- const key = method + " " + path21;
122642
+ const key = method + " " + path22;
122380
122643
  if (seen.has(key))
122381
122644
  continue;
122382
122645
  seen.add(key);
122383
122646
  out.push({
122384
- path: path21,
122647
+ path: path22,
122385
122648
  method: e.method,
122386
122649
  file: e.fromFile,
122387
122650
  handler: e.targetFqn ?? e.symbolName
@@ -122392,12 +122655,12 @@ function detectRoutes(httpEdges, defs, opts = {}) {
122392
122655
  continue;
122393
122656
  const parsed = parseRouteName(d.name);
122394
122657
  const method = parsed?.method ?? "ANY";
122395
- const path21 = parsed?.path ?? d.name;
122396
- const key = method + " " + path21;
122658
+ const path22 = parsed?.path ?? d.name;
122659
+ const key = method + " " + path22;
122397
122660
  if (seen.has(key))
122398
122661
  continue;
122399
122662
  seen.add(key);
122400
- out.push({ path: path21, method: parsed?.method, file: d.filePath, handler: d.name });
122663
+ out.push({ path: path22, method: parsed?.method, file: d.filePath, handler: d.name });
122401
122664
  }
122402
122665
  for (const d of defs) {
122403
122666
  const parsed = parseRouteName(d.name);
@@ -122618,8 +122881,8 @@ __export(exports_symbol_graph_service, {
122618
122881
  symbolGraphService: () => symbolGraphService,
122619
122882
  SymbolGraphService: () => SymbolGraphService
122620
122883
  });
122621
- import path21 from "path";
122622
- import fs15 from "fs/promises";
122884
+ import path22 from "path";
122885
+ import fs16 from "fs/promises";
122623
122886
 
122624
122887
  class SymbolGraphService {
122625
122888
  identityLookup;
@@ -122790,9 +123053,9 @@ class SymbolGraphService {
122790
123053
  return null;
122791
123054
  const workspace = graphSnapshot.workspace;
122792
123055
  const arch = await this.computeArchitectureMapSafe(graphSnapshot.architecture).catch((err) => {
122793
- logger.warn("getProjectMap: architecture map failed; skipping", {
123056
+ logger.warn("SymbolGraphService: getProjectMap architecture map failed, skipping", {
122794
123057
  projectId,
122795
- error: err?.message?.slice(0, 160)
123058
+ error: err
122796
123059
  });
122797
123060
  return null;
122798
123061
  });
@@ -122947,7 +123210,7 @@ class SymbolGraphService {
122947
123210
  async readSnippet(relativePath, lineStart, lineEnd, projectId) {
122948
123211
  try {
122949
123212
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
122950
- const content = await fs15.readFile(absolutePath, "utf-8");
123213
+ const content = await fs16.readFile(absolutePath, "utf-8");
122951
123214
  const lines = content.split(`
122952
123215
  `);
122953
123216
  return lines.slice(Math.max(0, lineStart - 1), Math.min(lines.length, lineEnd)).join(`
@@ -122959,7 +123222,7 @@ class SymbolGraphService {
122959
123222
  async readContext(relativePath, lineNumber, contextLines, projectId) {
122960
123223
  try {
122961
123224
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
122962
- const content = await fs15.readFile(absolutePath, "utf-8");
123225
+ const content = await fs16.readFile(absolutePath, "utf-8");
122963
123226
  const lines = content.split(`
122964
123227
  `);
122965
123228
  const start = Math.max(0, lineNumber - contextLines - 1);
@@ -122972,7 +123235,7 @@ class SymbolGraphService {
122972
123235
  }
122973
123236
  async resolveToAbsolute(relativePath, projectId) {
122974
123237
  const root = await this.getProjectRoot(projectId);
122975
- return root ? path21.resolve(root, relativePath) : relativePath;
123238
+ return root ? path22.resolve(root, relativePath) : relativePath;
122976
123239
  }
122977
123240
  async getProjectRoot(projectId) {
122978
123241
  const cached2 = this.projectRootCache.get(projectId);
@@ -123067,7 +123330,7 @@ class ContextController {
123067
123330
  });
123068
123331
  }
123069
123332
  } catch (err) {
123070
- logger.warn("Graph prefilter failed", { query, error: err.message });
123333
+ logger.warn("ContextController: graph prefilter failed", { projectId, query, error: err });
123071
123334
  }
123072
123335
  }
123073
123336
  const [searchResult, memories] = await Promise.all([
@@ -123221,9 +123484,11 @@ class ContextController {
123221
123484
  });
123222
123485
  return result.memories;
123223
123486
  } catch (error51) {
123224
- logger.warn("Memory search failed, continuing without memories", {
123225
- error: error51.message,
123226
- query: query.slice(0, 30)
123487
+ logger.warn("ContextController: memory search failed, continuing without memories", {
123488
+ projectId: opts.projectId,
123489
+ sessionId: opts.sessionId,
123490
+ query: query.slice(0, 30),
123491
+ error: error51
123227
123492
  });
123228
123493
  return [];
123229
123494
  }
@@ -123545,7 +123810,7 @@ function warnSandboxUnavailable() {
123545
123810
  return;
123546
123811
  _warnedAboutNoSandbox = true;
123547
123812
  const missingTool = process.platform === "darwin" ? "sandbox-exec" : "docker";
123548
- 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" });
123813
+ logger.warn("Sandbox: no sandbox tool found for auto mode, falling back to best-effort containment", { missingTool, platform: process.platform, effectiveMode: "none" });
123549
123814
  }
123550
123815
  function getSandboxMode() {
123551
123816
  const env4 = process.env.MASSA_AI_EXECUTOR_SANDBOX ?? "auto";
@@ -124460,7 +124725,10 @@ class ExecutorController {
124460
124725
  }
124461
124726
  };
124462
124727
  } catch (error51) {
124463
- logger.error("batch_execute failed", error51);
124728
+ logger.error("batch_execute failed", error51, {
124729
+ commandCount: commands.length,
124730
+ concurrency: effectiveConcurrency
124731
+ });
124464
124732
  return {
124465
124733
  success: false,
124466
124734
  error: `batch_execute failed: ${error51.message}`
@@ -124750,31 +125018,31 @@ class TracePathService {
124750
125018
  const chains = [];
124751
125019
  const seen = new Set;
124752
125020
  let walks = 0;
124753
- const walk = (fqn, path22) => {
125021
+ const walk = (fqn, path23) => {
124754
125022
  if (chains.length >= CHAIN_CAP)
124755
125023
  return;
124756
125024
  if (walks >= MAX_WALKS)
124757
125025
  return;
124758
125026
  walks++;
124759
- const key = path22.join("\u2192");
125027
+ const key = path23.join("\u2192");
124760
125028
  if (seen.has(key))
124761
125029
  return;
124762
125030
  seen.add(key);
124763
125031
  const next = adj.get(fqn);
124764
125032
  if (!next || next.length === 0 || !whoHasChild.has(fqn)) {
124765
- if (path22.length > 1)
124766
- chains.push(path22.map((n) => this.fqnToName(n)).join(" \u2192 "));
125033
+ if (path23.length > 1)
125034
+ chains.push(path23.map((n) => this.fqnToName(n)).join(" \u2192 "));
124767
125035
  return;
124768
125036
  }
124769
125037
  for (const child of next) {
124770
125038
  if (chains.length >= CHAIN_CAP || walks >= MAX_WALKS)
124771
125039
  return;
124772
- if (path22.includes(child)) {
124773
- const cycled = [...path22, `${this.fqnToName(child)}\u21BA`];
125040
+ if (path23.includes(child)) {
125041
+ const cycled = [...path23, `${this.fqnToName(child)}\u21BA`];
124774
125042
  chains.push(cycled.map((n) => n).join(" \u2192 "));
124775
125043
  continue;
124776
125044
  }
124777
- walk(child, [...path22, child]);
125045
+ walk(child, [...path23, child]);
124778
125046
  }
124779
125047
  };
124780
125048
  for (const seed of seeds) {
@@ -126797,9 +127065,9 @@ var init_inference_probe = __esm(() => {
126797
127065
  });
126798
127066
 
126799
127067
  // ../../packages/core/dist/services/health/local-health-checker.js
126800
- import fs16 from "fs/promises";
127068
+ import fs17 from "fs/promises";
126801
127069
  import { existsSync as existsSync3 } from "fs";
126802
- import path22 from "path";
127070
+ import path23 from "path";
126803
127071
 
126804
127072
  class LocalHealthChecker {
126805
127073
  dataDir = config.get("dataDir");
@@ -126877,10 +127145,10 @@ class LocalHealthChecker {
126877
127145
  const start = Date.now();
126878
127146
  try {
126879
127147
  if (!existsSync3(this.dataDir))
126880
- await fs16.mkdir(this.dataDir, { recursive: true });
126881
- const probe = path22.join(this.dataDir, ".health-check-test");
126882
- await fs16.writeFile(probe, "ok");
126883
- await fs16.unlink(probe);
127148
+ await fs17.mkdir(this.dataDir, { recursive: true });
127149
+ const probe = path23.join(this.dataDir, ".health-check-test");
127150
+ await fs17.writeFile(probe, "ok");
127151
+ await fs17.unlink(probe);
126884
127152
  return { available: true, latency: Date.now() - start, details: { path: this.dataDir, writable: true } };
126885
127153
  } catch (error51) {
126886
127154
  return { available: false, latency: Date.now() - start, error: `Data directory error: ${error51.message}` };
@@ -127016,7 +127284,7 @@ class PgJobStore {
127016
127284
  } catch (e) {
127017
127285
  this.recovered = true;
127018
127286
  logger.warn("PgJobStore markStaleRunningFailed failed (best-effort)", {
127019
- error: e.message
127287
+ error: e
127020
127288
  });
127021
127289
  }
127022
127290
  }
@@ -127042,7 +127310,7 @@ class PgJobStore {
127042
127310
  logger.info("PgJobStore hydrated", { rows: this.mirror.size });
127043
127311
  } catch (e) {
127044
127312
  logger.warn("PgJobStore hydrate failed (best-effort)", {
127045
- error: e.message
127313
+ error: e
127046
127314
  });
127047
127315
  } finally {
127048
127316
  this.hydrating = null;
@@ -127065,7 +127333,7 @@ class PgJobStore {
127065
127333
  next.catch((e) => {
127066
127334
  logger.warn("PgJobStore.save failed (best-effort)", {
127067
127335
  jobId: job.jobId,
127068
- error: e.message
127336
+ error: e
127069
127337
  });
127070
127338
  });
127071
127339
  }
@@ -127197,7 +127465,7 @@ class PgJobStore {
127197
127465
  }
127198
127466
  } catch (e) {
127199
127467
  logger.warn("PgJobStore markStaleRunningFailed failed (best-effort)", {
127200
- error: e.message
127468
+ error: e
127201
127469
  });
127202
127470
  }
127203
127471
  })();
@@ -127387,7 +127655,13 @@ class IndexJobTracker {
127387
127655
  const stale = hbMs != null && hbMs < cutoff || hbMs == null && startedMs != null && startedMs < cutoff;
127388
127656
  if (!stale)
127389
127657
  continue;
127390
- 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 });
127658
+ logger.warn("indexJobTracker: reaping stale running job", {
127659
+ jobId: job.jobId,
127660
+ projectId: job.projectId,
127661
+ staleMs,
127662
+ heartbeatAt: job.heartbeatAt?.toISOString() ?? "n/a",
127663
+ startedAt: job.startedAt?.toISOString() ?? "n/a"
127664
+ });
127391
127665
  this.jobs.set(job.jobId, job);
127392
127666
  const reapedPrevStatus = job.status;
127393
127667
  this.setResult(job.jobId, undefined, "heartbeat stale (possible crash/OOM)");
@@ -127412,7 +127686,7 @@ class IndexJobTracker {
127412
127686
  try {
127413
127687
  this.store?.save(job);
127414
127688
  } catch (err) {
127415
- logger.warn(`indexJobTracker: job store write failed for ${jobId} on setResult`, { jobId, error: err?.message ?? String(err) });
127689
+ logger.warn("indexJobTracker: job store write failed on setResult", { jobId, error: err });
127416
127690
  }
127417
127691
  if (prevStatus === "pending") {
127418
127692
  this.publishStateChange(job, prevStatus);
@@ -127442,7 +127716,7 @@ class IndexJobTracker {
127442
127716
  const survivors = remaining.slice(0, this.MAX_JOBS);
127443
127717
  const overflow = remaining.slice(this.MAX_JOBS);
127444
127718
  for (const job of overflow) {
127445
- 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 });
127719
+ 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 });
127446
127720
  this.jobs.delete(job.jobId);
127447
127721
  }
127448
127722
  }
@@ -127679,7 +127953,7 @@ class PgScheduledJobStore {
127679
127953
  logger.info("PgScheduledJobStore hydrated", { rows: this.mirror.size });
127680
127954
  } catch (e) {
127681
127955
  logger.warn("PgScheduledJobStore hydrate failed (best-effort)", {
127682
- error: e.message
127956
+ error: e
127683
127957
  });
127684
127958
  } finally {
127685
127959
  this.hydrating = null;
@@ -127693,9 +127967,10 @@ class PgScheduledJobStore {
127693
127967
  try {
127694
127968
  await action();
127695
127969
  } catch (e) {
127696
- logger.warn(`PgScheduledJobStore.${operation} failed (best-effort)`, {
127970
+ logger.warn("PgScheduledJobStore mutation failed (best-effort)", {
127697
127971
  id,
127698
- error: e.message
127972
+ operation,
127973
+ error: e
127699
127974
  });
127700
127975
  }
127701
127976
  };
@@ -127948,7 +128223,7 @@ class Scheduler {
127948
128223
  this.timer = setInterval(() => {
127949
128224
  this.tick().catch((e) => {
127950
128225
  logger.warn("Scheduler tick failed (swallowed)", {
127951
- error: e.message
128226
+ error: e
127952
128227
  });
127953
128228
  });
127954
128229
  }, this.tickIntervalMs);
@@ -128063,7 +128338,7 @@ class Scheduler {
128063
128338
  logger.warn("Scheduler: job handler threw (caught)", {
128064
128339
  id: job.id,
128065
128340
  jobKind: job.jobKind,
128066
- error: errMsg
128341
+ error: e
128067
128342
  });
128068
128343
  } finally {
128069
128344
  if (succeeded) {
@@ -128082,7 +128357,7 @@ class Scheduler {
128082
128357
  } catch (e) {
128083
128358
  logger.warn("Scheduler: persist after fire failed", {
128084
128359
  id: job.id,
128085
- error: e.message
128360
+ error: e
128086
128361
  });
128087
128362
  }
128088
128363
  this.running.delete(job.jobKind);
@@ -128102,6 +128377,8 @@ class Scheduler {
128102
128377
  enabled: j.enabled,
128103
128378
  nextRunAt: j.nextRunAt,
128104
128379
  lastRunAt: j.lastRunAt,
128380
+ lastSuccessAt: j.lastSuccessAt ?? null,
128381
+ consecutiveFailures: j.consecutiveFailures ?? 0,
128105
128382
  due: j.enabled && j.nextRunAt <= now2,
128106
128383
  currentlyRunning: this.running.has(j.jobKind)
128107
128384
  }))
@@ -128603,7 +128880,7 @@ class PgObservationStore {
128603
128880
  } catch (e) {
128604
128881
  this.hydrateFailedAt = Date.now();
128605
128882
  logger.warn("PgObservationStore hydrate failed (best-effort)", {
128606
- error: e.message
128883
+ error: e
128607
128884
  });
128608
128885
  } finally {
128609
128886
  this.hydrating = null;
@@ -128654,7 +128931,7 @@ class PgObservationStore {
128654
128931
  const next = prev.then(fn).catch((e) => {
128655
128932
  logger.warn("PgObservationStore.insert failed (best-effort)", {
128656
128933
  id: key,
128657
- error: e.message
128934
+ error: e
128658
128935
  });
128659
128936
  });
128660
128937
  this.inflight.set(key, next);
@@ -128968,7 +129245,7 @@ async function enrichWithLlm(candidates, observations, surface) {
128968
129245
  const prompt = buildEnrichmentPrompt(candidates, observations);
128969
129246
  let enrichment = null;
128970
129247
  try {
128971
- const res = await surface.object(prompt, ProposalEnrichmentSchema);
129248
+ const res = await surface.object(prompt, ProposalEnrichmentSchema, { label: "auto-improve" });
128972
129249
  if (!res.ok || !res.value || !Array.isArray(res.value.items)) {
128973
129250
  return { candidates, used: false };
128974
129251
  }
@@ -129164,7 +129441,7 @@ async function runOnce(job, projectId) {
129164
129441
  try {
129165
129442
  observations = job.observationStore.listRecent(projectId, job.maxWindow);
129166
129443
  } catch (e) {
129167
- logger.warn("auto-improve: listRecent failed", { projectId, error: e.message });
129444
+ logger.warn("auto-improve: listRecent failed", { projectId, error: e });
129168
129445
  return noop2;
129169
129446
  }
129170
129447
  if (observations.length < 2)
@@ -129179,7 +129456,7 @@ async function runOnce(job, projectId) {
129179
129456
  if (res.used)
129180
129457
  source = "llm";
129181
129458
  } catch (e) {
129182
- logger.warn("auto-improve: enrichWithLlm threw (silent)", { projectId, error: e.message });
129459
+ logger.warn("auto-improve: enrichWithLlm threw (silent)", { projectId, error: e });
129183
129460
  }
129184
129461
  const seen = new Set;
129185
129462
  const unique = candidates.filter((c) => {
@@ -129227,7 +129504,7 @@ async function runOnce(job, projectId) {
129227
129504
  } catch (e) {
129228
129505
  if (e instanceof SearchServiceError)
129229
129506
  throw e;
129230
- logger.warn("proposal:auto-approved:threw", { id: r.id, projectId, error: e.message });
129507
+ logger.warn("proposal:auto-approved:threw", { id: r.id, projectId, error: e });
129231
129508
  }
129232
129509
  }
129233
129510
  result.proposalsApplied = applied;
@@ -129256,7 +129533,7 @@ async function approve(job, id, projectId, source = "rule-based") {
129256
129533
  appliedMemoryId = await applyProposal(job, row);
129257
129534
  } catch (e) {
129258
129535
  const reason = e instanceof ApplyRejection ? e.reason : "apply-failed";
129259
- logger.warn("proposal:apply-failed", { id, projectId: row.projectId, reason, error: e.message });
129536
+ logger.warn("proposal:apply-failed", { id, projectId: row.projectId, reason, error: e });
129260
129537
  return { ok: false, reason };
129261
129538
  }
129262
129539
  let updated;
@@ -129391,9 +129668,9 @@ class AutoImproveJob {
129391
129668
  return;
129392
129669
  this.newSinceRun = 0;
129393
129670
  this.lastRunAt = now2;
129394
- this.runOnce(projectId).catch((e) => logger.warn("auto-improve: runOnce failed (silent)", { projectId, error: e.message }));
129671
+ this.runOnce(projectId).catch((e) => logger.warn("auto-improve: runOnce failed (silent)", { projectId, error: e }));
129395
129672
  } catch (e) {
129396
- logger.warn("auto-improve: maybeRun swallowed", { projectId, error: e.message });
129673
+ logger.warn("auto-improve: maybeRun swallowed", { projectId, error: e });
129397
129674
  }
129398
129675
  }
129399
129676
  async runOnce(projectId) {
@@ -129493,13 +129770,13 @@ class ObservationConsolidationJob {
129493
129770
  this.runOnce(projectId).catch((e) => {
129494
129771
  logger.warn("observation consolidation: runOnce failed (silent)", {
129495
129772
  projectId,
129496
- error: e.message
129773
+ error: e
129497
129774
  });
129498
129775
  });
129499
129776
  } catch (e) {
129500
129777
  logger.warn("observation consolidation: maybeRun swallowed", {
129501
129778
  projectId,
129502
- error: e.message
129779
+ error: e
129503
129780
  });
129504
129781
  }
129505
129782
  }
@@ -129523,7 +129800,7 @@ class ObservationConsolidationJob {
129523
129800
  } catch (e) {
129524
129801
  logger.warn("observation consolidation: listRecent failed", {
129525
129802
  projectId,
129526
- error: e.message
129803
+ error: e
129527
129804
  });
129528
129805
  return noop2;
129529
129806
  }
@@ -129534,7 +129811,7 @@ class ObservationConsolidationJob {
129534
129811
  const prompt = buildObservationPrompt(window2);
129535
129812
  let batch;
129536
129813
  try {
129537
- const res = await this.llm.object(prompt, ConsolidatedBatchSchema);
129814
+ const res = await this.llm.object(prompt, ConsolidatedBatchSchema, { label: "observation-consolidation" });
129538
129815
  if (!res.ok || !res.value) {
129539
129816
  return noop2;
129540
129817
  }
@@ -129550,7 +129827,7 @@ class ObservationConsolidationJob {
129550
129827
  } catch (e) {
129551
129828
  logger.warn("observation consolidation: llm.object threw (silent)", {
129552
129829
  projectId,
129553
- error: e.message
129830
+ error: e
129554
129831
  });
129555
129832
  return noop2;
129556
129833
  }
@@ -129579,7 +129856,7 @@ class ObservationConsolidationJob {
129579
129856
  } catch (e) {
129580
129857
  logger.warn("observation consolidation: summary insert failed", {
129581
129858
  batchId: batch.id,
129582
- error: e.message
129859
+ error: e
129583
129860
  });
129584
129861
  return noop2;
129585
129862
  }
@@ -129690,7 +129967,7 @@ class PgCheckpointStore {
129690
129967
  } catch (e) {
129691
129968
  this.hydrateFailedAt = Date.now();
129692
129969
  logger.warn("PgCheckpointStore hydrate failed (best-effort)", {
129693
- error: e.message
129970
+ error: e
129694
129971
  });
129695
129972
  } finally {
129696
129973
  this.hydrating = null;
@@ -129884,8 +130161,9 @@ class PgCheckpointStore {
129884
130161
  }
129885
130162
  return existing;
129886
130163
  } catch (e) {
129887
- logger.warn("countExistingMemoryIds failed (best-effort: assuming all exist)", {
129888
- error: e.message
130164
+ logger.warn("PgCheckpointStore: countExistingMemoryIds failed (best-effort, assuming all exist)", {
130165
+ memoryIdCount: memoryIds.length,
130166
+ error: e
129889
130167
  });
129890
130168
  return memoryIds;
129891
130169
  }
@@ -129952,7 +130230,7 @@ class PgCheckpointStore {
129952
130230
  const next = prev.then(fn).catch((e) => {
129953
130231
  logger.warn("PgCheckpointStore write failed (best-effort)", {
129954
130232
  key,
129955
- error: e.message
130233
+ error: e
129956
130234
  });
129957
130235
  });
129958
130236
  this.inflight.set(key, next);
@@ -130171,9 +130449,9 @@ var init_scheduler2 = __esm(() => {
130171
130449
  });
130172
130450
 
130173
130451
  // ../../packages/core/dist/services/pricing/models-dev-client.js
130174
- import fs17 from "fs/promises";
130452
+ import fs18 from "fs/promises";
130175
130453
  import { existsSync as existsSync4 } from "fs";
130176
- import path23 from "path";
130454
+ import path24 from "path";
130177
130455
  function getModelsDevClient() {
130178
130456
  if (!clientInstance) {
130179
130457
  clientInstance = new ModelsDevClient;
@@ -130193,7 +130471,7 @@ var init_models_dev_client = __esm(() => {
130193
130471
  memoryCacheTimestamp = 0;
130194
130472
  getLocalCachePath() {
130195
130473
  const dataDir = config.get("dataDir");
130196
- return path23.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
130474
+ return path24.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
130197
130475
  }
130198
130476
  async loadLocalCache() {
130199
130477
  const cachePath = this.getLocalCachePath();
@@ -130201,7 +130479,7 @@ var init_models_dev_client = __esm(() => {
130201
130479
  if (!existsSync4(cachePath)) {
130202
130480
  return null;
130203
130481
  }
130204
- const content = await fs17.readFile(cachePath, "utf-8");
130482
+ const content = await fs18.readFile(cachePath, "utf-8");
130205
130483
  const data = JSON.parse(content);
130206
130484
  const age = Date.now() - data.timestamp;
130207
130485
  if (age > ModelsDevClient.LOCAL_CACHE_TTL) {
@@ -130228,21 +130506,22 @@ var init_models_dev_client = __esm(() => {
130228
130506
  async saveLocalCache(models) {
130229
130507
  const cachePath = this.getLocalCachePath();
130230
130508
  try {
130231
- const dir = path23.dirname(cachePath);
130232
- await fs17.mkdir(dir, { recursive: true });
130509
+ const dir = path24.dirname(cachePath);
130510
+ await fs18.mkdir(dir, { recursive: true });
130233
130511
  const data = {
130234
130512
  timestamp: Date.now(),
130235
130513
  version: "1.0.0",
130236
130514
  models: Object.fromEntries(models)
130237
130515
  };
130238
- await fs17.writeFile(cachePath, JSON.stringify(data), "utf-8");
130516
+ await fs18.writeFile(cachePath, JSON.stringify(data), "utf-8");
130239
130517
  logger.debug("Saved pricing to local cache", {
130240
130518
  models: models.size,
130241
130519
  path: cachePath
130242
130520
  });
130243
130521
  } catch (error51) {
130244
- logger.warn("Failed to save local pricing cache", {
130245
- error: error51.message
130522
+ logger.warn("ModelsDevClient: failed to save local pricing cache", {
130523
+ path: cachePath,
130524
+ error: error51
130246
130525
  });
130247
130526
  }
130248
130527
  }
@@ -130464,7 +130743,7 @@ var init_models_dev_client = __esm(() => {
130464
130743
  return value;
130465
130744
  }
130466
130745
  }
130467
- logger.warn(`Model pricing not found: ${modelId}`);
130746
+ logger.warn("ModelsDevClient: model pricing not found", { modelId });
130468
130747
  return null;
130469
130748
  }
130470
130749
  async searchModels(query) {
@@ -130564,12 +130843,13 @@ var init_models_dev_client = __esm(() => {
130564
130843
  const cachePath = this.getLocalCachePath();
130565
130844
  try {
130566
130845
  if (existsSync4(cachePath)) {
130567
- await fs17.unlink(cachePath);
130846
+ await fs18.unlink(cachePath);
130568
130847
  logger.debug("Local pricing cache file deleted");
130569
130848
  }
130570
130849
  } catch (error51) {
130571
- logger.warn("Failed to delete local pricing cache", {
130572
- error: error51.message
130850
+ logger.warn("ModelsDevClient: failed to delete local pricing cache", {
130851
+ path: cachePath,
130852
+ error: error51
130573
130853
  });
130574
130854
  }
130575
130855
  }
@@ -131167,8 +131447,8 @@ function stripNul(content) {
131167
131447
  }
131168
131448
 
131169
131449
  // ../../packages/core/dist/services/etl/stages/discover.js
131170
- import fs18 from "fs/promises";
131171
- import path24 from "path";
131450
+ import fs19 from "fs/promises";
131451
+ import path25 from "path";
131172
131452
  import { createHash as createHash8 } from "crypto";
131173
131453
 
131174
131454
  class DiscoverStage {
@@ -131194,7 +131474,7 @@ class DiscoverStage {
131194
131474
  dot: false,
131195
131475
  absolute: false
131196
131476
  });
131197
- relPaths = found.map((p) => path24.isAbsolute(p) ? path24.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
131477
+ relPaths = found.map((p) => path25.isAbsolute(p) ? path25.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
131198
131478
  }
131199
131479
  if (ctx.resumeCursor?.path) {
131200
131480
  const cursorPath = ctx.resumeCursor.path;
@@ -131253,10 +131533,10 @@ class DiscoverStage {
131253
131533
  return discovered;
131254
131534
  }
131255
131535
  async processFile(ctx, relativePath, forceReindex) {
131256
- const absolutePath = path24.join(ctx.projectPath, relativePath);
131536
+ const absolutePath = path25.join(ctx.projectPath, relativePath);
131257
131537
  try {
131258
- const stat = await fs18.stat(absolutePath);
131259
- const content = stripNul(await fs18.readFile(absolutePath, "utf-8"));
131538
+ const stat = await fs19.stat(absolutePath);
131539
+ const content = stripNul(await fs19.readFile(absolutePath, "utf-8"));
131260
131540
  const contentHash = createHash8("sha256").update(content).digest("hex");
131261
131541
  let needsReparse = forceReindex;
131262
131542
  if (!forceReindex) {
@@ -131274,8 +131554,9 @@ class DiscoverStage {
131274
131554
  };
131275
131555
  } catch (err) {
131276
131556
  logger.warn("DiscoverStage: failed to stat/read file", {
131557
+ projectId: ctx.projectId,
131277
131558
  relativePath,
131278
- error: err.message
131559
+ error: err
131279
131560
  });
131280
131561
  throw new Error(`required_file_unreadable:${relativePath}:${err.message}`);
131281
131562
  }
@@ -131299,8 +131580,8 @@ class DiscoverStage {
131299
131580
  ig.add(pattern);
131300
131581
  }
131301
131582
  try {
131302
- const gitignorePath = path24.join(projectPath, ".gitignore");
131303
- const gitignoreContent = await fs18.readFile(gitignorePath, "utf8");
131583
+ const gitignorePath = path25.join(projectPath, ".gitignore");
131584
+ const gitignoreContent = await fs19.readFile(gitignorePath, "utf8");
131304
131585
  const rules = gitignoreContent.split(`
131305
131586
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
131306
131587
  ig.add(rules);
@@ -132655,8 +132936,8 @@ function rustUseLeaves(node, source, prefix = []) {
132655
132936
  }
132656
132937
  if (node.type === "use_wildcard")
132657
132938
  return [{ path: [...prefix, "*"], glob: true }];
132658
- const path25 = rustPathSegments(node, source);
132659
- return path25.length ? [{ path: [...prefix, ...path25] }] : [];
132939
+ const path26 = rustPathSegments(node, source);
132940
+ return path26.length ? [{ path: [...prefix, ...path26] }] : [];
132660
132941
  }
132661
132942
  function functionalCaptures(captures, source, family) {
132662
132943
  if (family !== "clojure")
@@ -133628,8 +133909,8 @@ var init_structural_runtime = __esm(() => {
133628
133909
  });
133629
133910
 
133630
133911
  // ../../packages/core/dist/services/etl/stages/parse.js
133631
- import path25 from "path";
133632
- import fs19 from "fs/promises";
133912
+ import path26 from "path";
133913
+ import fs20 from "fs/promises";
133633
133914
  function resolveChunkerMaxChars() {
133634
133915
  const global2 = Number(process.env.EMBEDDING_MAX_CHARS);
133635
133916
  if (Number.isFinite(global2) && global2 > 0)
@@ -133657,8 +133938,8 @@ class ParseStage {
133657
133938
  const results = new Map;
133658
133939
  let processed = 0;
133659
133940
  const phases = [
133660
- files.filter((file2) => path25.extname(file2.relativePath).toLowerCase() !== ".h"),
133661
- files.filter((file2) => path25.extname(file2.relativePath).toLowerCase() === ".h")
133941
+ files.filter((file2) => path26.extname(file2.relativePath).toLowerCase() !== ".h"),
133942
+ files.filter((file2) => path26.extname(file2.relativePath).toLowerCase() === ".h")
133662
133943
  ];
133663
133944
  const batches = phases.flatMap((phase) => Array.from({ length: Math.ceil(phase.length / BATCH_SIZE) }, (_, index) => phase.slice(index * BATCH_SIZE, (index + 1) * BATCH_SIZE)));
133664
133945
  for (const batch of batches) {
@@ -133696,19 +133977,19 @@ class ParseStage {
133696
133977
  return files.map((file2) => results.get(file2.relativePath));
133697
133978
  }
133698
133979
  recordHeaderImporterEvidence(ctx, files, parsedFiles) {
133699
- const knownHeaders = new Set(files.filter((file2) => path25.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path25.posix.normalize(file2.relativePath)));
133980
+ const knownHeaders = new Set(files.filter((file2) => path26.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path26.posix.normalize(file2.relativePath)));
133700
133981
  const mutable = {
133701
133982
  ...ctx.structuralHeaderEvidenceByFile
133702
133983
  };
133703
133984
  for (const parsed of parsedFiles) {
133704
- const extension = path25.extname(parsed.file.relativePath).toLowerCase();
133985
+ const extension = path26.extname(parsed.file.relativePath).toLowerCase();
133705
133986
  const key = extension === ".c" ? "cImporters" : [".cpp", ".hpp"].includes(extension) ? "cppImporters" : undefined;
133706
133987
  if (!key)
133707
133988
  continue;
133708
133989
  for (const imported of parsed.rawImports) {
133709
133990
  if (!["c_include", "cpp_include"].includes(imported.form) || imported.specifier.startsWith("<"))
133710
133991
  continue;
133711
- const header = path25.posix.normalize(path25.posix.join(path25.posix.dirname(parsed.file.relativePath), imported.specifier));
133992
+ const header = path26.posix.normalize(path26.posix.join(path26.posix.dirname(parsed.file.relativePath), imported.specifier));
133712
133993
  if (!knownHeaders.has(header))
133713
133994
  continue;
133714
133995
  const existing = mutable[header] ?? {};
@@ -133719,9 +134000,9 @@ class ParseStage {
133719
134000
  }
133720
134001
  async parseFile(ctx, file2) {
133721
134002
  if (!file2.needsReparse) {
133722
- const extension = path25.extname(file2.relativePath).toLowerCase();
134003
+ const extension = path26.extname(file2.relativePath).toLowerCase();
133723
134004
  if ([".c", ".cpp", ".hpp"].includes(extension)) {
133724
- const content = file2.snapshotContent ?? await fs19.readFile(file2.absolutePath, "utf8");
134005
+ const content = file2.snapshotContent ?? await fs20.readFile(file2.absolutePath, "utf8");
133725
134006
  const outcome = await this.runtime.parse({ extension, source: Buffer.from(content) });
133726
134007
  if (outcome.status === "failed")
133727
134008
  throw new StructuralEtlParseError(file2.relativePath, outcome.failureKind, `Structural evidence parse failed (${outcome.failureKind})`, outcome.diagnosticCount, outcome.diagnostics.slice(0, 10));
@@ -133733,8 +134014,8 @@ class ParseStage {
133733
134014
  return { file: file2, chunks: [], symbols: [], rawImports: [], rawEdges: [] };
133734
134015
  }
133735
134016
  try {
133736
- const content = file2.snapshotContent ?? await fs19.readFile(file2.absolutePath, "utf-8");
133737
- const ext2 = path25.extname(file2.relativePath).toLowerCase();
134017
+ const content = file2.snapshotContent ?? await fs20.readFile(file2.absolutePath, "utf-8");
134018
+ const ext2 = path26.extname(file2.relativePath).toLowerCase();
133738
134019
  const chunkerMaxChars = resolveChunkerMaxChars();
133739
134020
  const chunks = smartChunk(content, file2.relativePath, chunkerMaxChars ? { maxChunkChars: chunkerMaxChars } : {});
133740
134021
  let symbols;
@@ -133800,8 +134081,9 @@ class ParseStage {
133800
134081
  timestamp: Date.now()
133801
134082
  });
133802
134083
  logger.warn("ParseStage: failed to parse file", {
134084
+ projectId: ctx.projectId,
133803
134085
  filePath: file2.relativePath,
133804
- error: err.message
134086
+ error: err
133805
134087
  });
133806
134088
  if (err instanceof StructuralEtlParseError)
133807
134089
  throw err;
@@ -134288,7 +134570,7 @@ var init_resolver = __esm(() => {
134288
134570
  });
134289
134571
 
134290
134572
  // ../../packages/core/dist/services/structural/resolvers/typescript.js
134291
- import path26 from "path";
134573
+ import path27 from "path";
134292
134574
  function candidates(identities) {
134293
134575
  return Object.freeze(identities.map((identity) => Object.freeze({
134294
134576
  fqn: identity.fqn,
@@ -134383,7 +134665,7 @@ function probe(base, known, dialect = "typescript") {
134383
134665
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
134384
134666
  for (const candidateBase of bases)
134385
134667
  for (const suffix of DIALECT_PROBES[dialect] ?? [""]) {
134386
- const value = path26.posix.normalize(`${candidateBase}${suffix}`);
134668
+ const value = path27.posix.normalize(`${candidateBase}${suffix}`);
134387
134669
  if (!value.startsWith("../") && value !== ".." && known.has(value))
134388
134670
  return value;
134389
134671
  }
@@ -134392,7 +134674,7 @@ function probe(base, known, dialect = "typescript") {
134392
134674
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
134393
134675
  const known = new Set(build.knownFiles.map(normalizeStructuralFile));
134394
134676
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
134395
- return probe(path26.posix.join(path26.posix.dirname(fromFile), specifier), known, dialect);
134677
+ return probe(path27.posix.join(path27.posix.dirname(fromFile), specifier), known, dialect);
134396
134678
  }
134397
134679
  const aliases = build.pathAliasesByFile?.[normalizeStructuralFile(fromFile)] ?? build.pathAliases ?? [];
134398
134680
  for (const alias of aliases) {
@@ -134656,7 +134938,7 @@ var init_scripting2 = __esm(() => {
134656
134938
  });
134657
134939
 
134658
134940
  // ../../packages/core/dist/services/structural/resolvers/systems.js
134659
- import path27 from "path";
134941
+ import path28 from "path";
134660
134942
  var DIALECTS, SYSTEMS_LANGUAGE_RESOLVER;
134661
134943
  var init_systems2 = __esm(() => {
134662
134944
  init_typescript2();
@@ -134675,7 +134957,7 @@ var init_systems2 = __esm(() => {
134675
134957
  const bindings = item.bindings.map((binding) => binding.imported === "*" && binding.local === "*" && unresolvedTarget && !unresolvedTarget.qualifier ? { ...binding, imported: unresolvedTarget.name, local: unresolvedTarget.name } : binding);
134676
134958
  if (item.specifier === "crate" || item.specifier.startsWith("crate/")) {
134677
134959
  const crateRoot = file2.file.startsWith("src/") ? "src" : "";
134678
- return { ...item, bindings, specifier: `./${path27.posix.relative(path27.posix.dirname(file2.file), path27.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
134960
+ return { ...item, bindings, specifier: `./${path28.posix.relative(path28.posix.dirname(file2.file), path28.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
134679
134961
  }
134680
134962
  if (item.specifier === "self" || item.specifier.startsWith("self/"))
134681
134963
  return { ...item, bindings, specifier: `./${item.specifier.replace(/^self\/?/u, "")}` };
@@ -134773,8 +135055,8 @@ var init_data_document2 = __esm(() => {
134773
135055
  });
134774
135056
 
134775
135057
  // ../../packages/core/dist/services/etl/stages/resolve.js
134776
- import path28 from "path";
134777
- import fs20 from "fs";
135058
+ import path29 from "path";
135059
+ import fs21 from "fs";
134778
135060
 
134779
135061
  class ResolveStage {
134780
135062
  symbolRepository;
@@ -134798,7 +135080,7 @@ class ResolveStage {
134798
135080
  const structuralDocuments = files.flatMap((file2) => {
134799
135081
  if (!file2.structure)
134800
135082
  return [];
134801
- const language = resolveStructuralLanguage(path28.extname(file2.file.relativePath));
135083
+ const language = resolveStructuralLanguage(path29.extname(file2.file.relativePath));
134802
135084
  if (language.status !== "supported")
134803
135085
  throw new Error(`structural_manifest_missing:${file2.file.relativePath}`);
134804
135086
  return [{
@@ -134810,13 +135092,13 @@ class ResolveStage {
134810
135092
  }];
134811
135093
  });
134812
135094
  const currentStructuralFiles = new Set(structuralDocuments.map((document2) => document2.file));
134813
- const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path28.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
135095
+ const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path29.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
134814
135096
  const pathAliasesByFile = Object.fromEntries([...knownRelPaths].map((file2) => [
134815
135097
  file2,
134816
135098
  this.structuralAliasesFor(file2, rootAliases, monorepoPackages)
134817
135099
  ]));
134818
135100
  const buildMetadata = { knownFiles: [...knownRelPaths], pathAliasesByFile };
134819
- const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path28.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
135101
+ const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path29.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
134820
135102
  const seedIds = new Set;
134821
135103
  for (const definition of seedRows) {
134822
135104
  if (seedIds.has(definition.id))
@@ -134909,7 +135191,7 @@ class ResolveStage {
134909
135191
  if (parsed.file !== definition.file_path) {
134910
135192
  throw new Error(`structural_repository_seed_file_mismatch:${definition.id}`);
134911
135193
  }
134912
- const language = resolveStructuralLanguage(path28.extname(definition.file_path));
135194
+ const language = resolveStructuralLanguage(path29.extname(definition.file_path));
134913
135195
  if (language.status !== "supported")
134914
135196
  throw new Error(`structural_repository_seed_language:${definition.id}`);
134915
135197
  let identity;
@@ -134961,7 +135243,7 @@ class ResolveStage {
134961
135243
  });
134962
135244
  }
134963
135245
  resolveFile(parsed, projectPath, knownRelPaths, rootAliases, monorepoPackages, symbolIndex, knownFqns) {
134964
- const fromDir = path28.dirname(path28.join(projectPath, parsed.file.relativePath));
135246
+ const fromDir = path29.dirname(path29.join(projectPath, parsed.file.relativePath));
134965
135247
  const packageAliases = this.getPackageAliases(parsed.file.relativePath, monorepoPackages);
134966
135248
  const allAliases = [...packageAliases, ...rootAliases];
134967
135249
  const resolvedImports = parsed.rawImports.map((raw2) => {
@@ -135032,12 +135314,12 @@ class ResolveStage {
135032
135314
  index.set(def.name, `${def.file_path}#${def.name}`);
135033
135315
  }
135034
135316
  } catch (err) {
135035
- const skippedStructural = files.some((file2) => !file2.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path28.extname(file2.file.relativePath).toLowerCase()));
135317
+ const skippedStructural = files.some((file2) => !file2.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path29.extname(file2.file.relativePath).toLowerCase()));
135036
135318
  if (skippedStructural)
135037
135319
  throw new Error("structural_repository_seed_failed", { cause: err });
135038
135320
  logger.warn("buildSymbolIndex: repo seed failed, in-batch only", {
135039
135321
  projectId,
135040
- error: err?.message
135322
+ error: err
135041
135323
  });
135042
135324
  }
135043
135325
  const inBatch = new Map;
@@ -135056,7 +135338,7 @@ class ResolveStage {
135056
135338
  }
135057
135339
  resolveSpecifier(specifier, fromDir, projectPath, knownRelPaths, aliases) {
135058
135340
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
135059
- const resolved = this.probeExtensions(path28.resolve(fromDir, specifier), projectPath, knownRelPaths);
135341
+ const resolved = this.probeExtensions(path29.resolve(fromDir, specifier), projectPath, knownRelPaths);
135060
135342
  return { resolvedPath: resolved, external: false };
135061
135343
  }
135062
135344
  for (const alias of aliases) {
@@ -135064,8 +135346,8 @@ class ResolveStage {
135064
135346
  const suffix = specifier.slice(alias.prefix.length);
135065
135347
  for (const target of alias.targets) {
135066
135348
  const cleanTarget = target.replace(/\/\*$/, "");
135067
- const basePath = alias.packagePath ? path28.join(projectPath, alias.packagePath) : projectPath;
135068
- const absPath = path28.join(basePath, cleanTarget + suffix);
135349
+ const basePath = alias.packagePath ? path29.join(projectPath, alias.packagePath) : projectPath;
135350
+ const absPath = path29.join(basePath, cleanTarget + suffix);
135069
135351
  const resolved = this.probeExtensions(absPath, projectPath, knownRelPaths);
135070
135352
  if (resolved)
135071
135353
  return { resolvedPath: resolved, external: false };
@@ -135081,7 +135363,7 @@ class ResolveStage {
135081
135363
  ...TS_EXTENSIONS.map((ext2) => absPath.replace(/\.[^.]+$/, ext2))
135082
135364
  ];
135083
135365
  for (const candidate2 of candidates2) {
135084
- const rel = path28.relative(projectPath, candidate2).replace(/\\/g, "/");
135366
+ const rel = path29.relative(projectPath, candidate2).replace(/\\/g, "/");
135085
135367
  if (knownRelPaths.has(rel))
135086
135368
  return rel;
135087
135369
  }
@@ -135089,9 +135371,9 @@ class ResolveStage {
135089
135371
  }
135090
135372
  loadTsConfigPaths(projectPath, packageBase) {
135091
135373
  const aliases = [];
135092
- const tsconfigPath = path28.join(projectPath, "tsconfig.json");
135374
+ const tsconfigPath = path29.join(projectPath, "tsconfig.json");
135093
135375
  try {
135094
- const raw2 = fs20.readFileSync(tsconfigPath, "utf-8");
135376
+ const raw2 = fs21.readFileSync(tsconfigPath, "utf-8");
135095
135377
  const stripped = raw2.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
135096
135378
  const tsconfig = JSON.parse(stripped);
135097
135379
  const paths = tsconfig?.compilerOptions?.paths ?? {};
@@ -135120,7 +135402,7 @@ class ResolveStage {
135120
135402
  }
135121
135403
  }
135122
135404
  for (const packageRelPath of packagePaths) {
135123
- const absPackagePath = path28.join(projectPath, packageRelPath);
135405
+ const absPackagePath = path29.join(projectPath, packageRelPath);
135124
135406
  const aliases = this.loadTsConfigPaths(absPackagePath, packageRelPath);
135125
135407
  if (aliases.length > 0) {
135126
135408
  packages.push({
@@ -135150,7 +135432,7 @@ class ResolveStage {
135150
135432
  structuralAliasesFor(filePath, rootAliases, packages) {
135151
135433
  return [...this.getPackageAliases(filePath, packages), ...rootAliases].map((alias) => ({
135152
135434
  pattern: alias.prefix + (alias.targets.some((target) => target.includes("*")) ? "/*" : ""),
135153
- targets: alias.targets.map((target) => alias.packagePath ? path28.posix.join(alias.packagePath, target) : target)
135435
+ targets: alias.targets.map((target) => alias.packagePath ? path29.posix.join(alias.packagePath, target) : target)
135154
135436
  }));
135155
135437
  }
135156
135438
  }
@@ -135200,7 +135482,7 @@ async function withDeadlockRetry(operation, options = {}) {
135200
135482
  attempt,
135201
135483
  maxAttempts,
135202
135484
  delayMs,
135203
- error: error51?.message?.slice(0, 120)
135485
+ error: error51
135204
135486
  });
135205
135487
  await new Promise((resolve7) => setTimeout(resolve7, delayMs));
135206
135488
  }
@@ -135214,7 +135496,7 @@ var init_with_deadlock_retry = __esm(() => {
135214
135496
  });
135215
135497
 
135216
135498
  // ../../packages/core/dist/services/etl/stages/load.js
135217
- import path29 from "path";
135499
+ import path30 from "path";
135218
135500
  function formatDuration(ms) {
135219
135501
  const totalSec = Math.max(0, Math.round(ms / 1000));
135220
135502
  if (totalSec < 60)
@@ -135491,7 +135773,7 @@ class LoadStage {
135491
135773
  const filePath = file2.file.relativePath;
135492
135774
  const batch = buildSymbolPersistenceBatch(ctx.projectId, file2);
135493
135775
  if (ctx.graphGenerationLease) {
135494
- const manifest = getLanguageManifestEntry(path29.extname(filePath));
135776
+ const manifest = getLanguageManifestEntry(path30.extname(filePath));
135495
135777
  const diagnostics2 = (file2.structuralDiagnostics ?? []).slice(0, 10).map((diagnostic2) => ({
135496
135778
  code: diagnostic2.code,
135497
135779
  severity: diagnostic2.severity,
@@ -135948,9 +136230,9 @@ var init_graph_generation_coordinator = __esm(() => {
135948
136230
  // ../../packages/core/dist/services/etl/pipeline.js
135949
136231
  import { createHash as createHash10 } from "crypto";
135950
136232
  import { setTimeout as delay2 } from "timers/promises";
135951
- import path30 from "path";
136233
+ import path31 from "path";
135952
136234
  function buildHeaderLanguageEvidence(files) {
135953
- const headers = new Set(files.filter((file2) => path30.posix.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path30.posix.normalize(file2.relativePath)));
136235
+ const headers = new Set(files.filter((file2) => path31.posix.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path31.posix.normalize(file2.relativePath)));
135954
136236
  const mutable = new Map;
135955
136237
  const entry2 = (header) => {
135956
136238
  let value = mutable.get(header);
@@ -135961,7 +136243,7 @@ function buildHeaderLanguageEvidence(files) {
135961
136243
  return value;
135962
136244
  };
135963
136245
  for (const file2 of files) {
135964
- if (path30.posix.basename(file2.relativePath) !== "compile_commands.json" || file2.snapshotContent === undefined)
136246
+ if (path31.posix.basename(file2.relativePath) !== "compile_commands.json" || file2.snapshotContent === undefined)
135965
136247
  continue;
135966
136248
  let commands;
135967
136249
  try {
@@ -135977,11 +136259,11 @@ function buildHeaderLanguageEvidence(files) {
135977
136259
  const record2 = command;
135978
136260
  if (typeof record2.file !== "string")
135979
136261
  continue;
135980
- const projectRoot = path30.resolve(file2.absolutePath, ...file2.relativePath.split("/").map(() => ".."));
135981
- const commandDirectory = typeof record2.directory === "string" ? path30.resolve(projectRoot, record2.directory) : projectRoot;
135982
- const absoluteInput = path30.resolve(commandDirectory, record2.file);
135983
- const relative3 = path30.relative(projectRoot, absoluteInput);
135984
- const header = path30.posix.normalize(relative3.replaceAll(path30.sep, "/"));
136262
+ const projectRoot = path31.resolve(file2.absolutePath, ...file2.relativePath.split("/").map(() => ".."));
136263
+ const commandDirectory = typeof record2.directory === "string" ? path31.resolve(projectRoot, record2.directory) : projectRoot;
136264
+ const absoluteInput = path31.resolve(commandDirectory, record2.file);
136265
+ const relative3 = path31.relative(projectRoot, absoluteInput);
136266
+ const header = path31.posix.normalize(relative3.replaceAll(path31.sep, "/"));
135985
136267
  if (!headers.has(header))
135986
136268
  continue;
135987
136269
  const invocation = typeof record2.command === "string" ? record2.command : Array.isArray(record2.arguments) ? record2.arguments.join(" ") : "";
@@ -136330,7 +136612,7 @@ var init_pipeline = __esm(() => {
136330
136612
  logger.warn("EtlPipeline: search-admission marker write failed", {
136331
136613
  projectId,
136332
136614
  jobId,
136333
- error: markerError.message.slice(0, 160)
136615
+ error: markerError
136334
136616
  });
136335
136617
  }
136336
136618
  if (forceReindex) {
@@ -136342,7 +136624,7 @@ var init_pipeline = __esm(() => {
136342
136624
  logger.warn("EtlPipeline: embedding fingerprint stamp failed", {
136343
136625
  projectId,
136344
136626
  jobId,
136345
- error: stampError.message.slice(0, 160)
136627
+ error: stampError
136346
136628
  });
136347
136629
  }
136348
136630
  }
@@ -136505,9 +136787,10 @@ class SearchSessionHook {
136505
136787
  });
136506
136788
  } catch (err) {
136507
136789
  logger.warn("SearchSessionHook: store failed (best-effort)", {
136508
- error: err.message,
136509
136790
  projectId,
136510
- query: query.slice(0, 60)
136791
+ sessionId,
136792
+ query: query.slice(0, 60),
136793
+ error: err
136511
136794
  });
136512
136795
  }
136513
136796
  }
@@ -136583,8 +136866,10 @@ class CoRetrievalHook {
136583
136866
  peers = await this.findPeers(memoryId, projectId, sessionId);
136584
136867
  } catch (err) {
136585
136868
  logger.warn("CoRetrievalHook: peer lookup failed", {
136586
- error: err.message,
136587
- memoryId
136869
+ projectId,
136870
+ sessionId,
136871
+ memoryId,
136872
+ error: err
136588
136873
  });
136589
136874
  return;
136590
136875
  }
@@ -136755,7 +137040,7 @@ var TOOL_NAME_NORMALIZE, classifyToolCall = (_source, payload) => {
136755
137040
  if (lowerPrompt.includes("blocked on") || lowerPrompt.includes("waiting on") || lowerPrompt.includes("can't proceed") || lowerPrompt.includes("stuck on")) {
136756
137041
  return "blocked-on";
136757
137042
  }
136758
- if (lowerPrompt.startsWith("/persona") || lowerPrompt.startsWith("act as") || lowerPrompt.startsWith("you are a")) {
137043
+ if (lowerPrompt.startsWith("act as") || lowerPrompt.startsWith("you are a")) {
136759
137044
  return "role";
136760
137045
  }
136761
137046
  return "user-prompts";
@@ -141863,33 +142148,33 @@ var require_URL = __commonJS((exports, module) => {
141863
142148
  else
141864
142149
  return basepath.substring(0, lastslash + 1) + refpath;
141865
142150
  }
141866
- function remove_dot_segments(path31) {
141867
- if (!path31)
141868
- return path31;
142151
+ function remove_dot_segments(path32) {
142152
+ if (!path32)
142153
+ return path32;
141869
142154
  var output = "";
141870
- while (path31.length > 0) {
141871
- if (path31 === "." || path31 === "..") {
141872
- path31 = "";
142155
+ while (path32.length > 0) {
142156
+ if (path32 === "." || path32 === "..") {
142157
+ path32 = "";
141873
142158
  break;
141874
142159
  }
141875
- var twochars = path31.substring(0, 2);
141876
- var threechars = path31.substring(0, 3);
141877
- var fourchars = path31.substring(0, 4);
142160
+ var twochars = path32.substring(0, 2);
142161
+ var threechars = path32.substring(0, 3);
142162
+ var fourchars = path32.substring(0, 4);
141878
142163
  if (threechars === "../") {
141879
- path31 = path31.substring(3);
142164
+ path32 = path32.substring(3);
141880
142165
  } else if (twochars === "./") {
141881
- path31 = path31.substring(2);
142166
+ path32 = path32.substring(2);
141882
142167
  } else if (threechars === "/./") {
141883
- path31 = "/" + path31.substring(3);
141884
- } else if (twochars === "/." && path31.length === 2) {
141885
- path31 = "/";
141886
- } else if (fourchars === "/../" || threechars === "/.." && path31.length === 3) {
141887
- path31 = "/" + path31.substring(4);
142168
+ path32 = "/" + path32.substring(3);
142169
+ } else if (twochars === "/." && path32.length === 2) {
142170
+ path32 = "/";
142171
+ } else if (fourchars === "/../" || threechars === "/.." && path32.length === 3) {
142172
+ path32 = "/" + path32.substring(4);
141888
142173
  output = output.replace(/\/?[^\/]*$/, "");
141889
142174
  } else {
141890
- var segment = path31.match(/(\/?([^\/]*))/)[0];
142175
+ var segment = path32.match(/(\/?([^\/]*))/)[0];
141891
142176
  output += segment;
141892
- path31 = path31.substring(segment.length);
142177
+ path32 = path32.substring(segment.length);
141893
142178
  }
141894
142179
  }
141895
142180
  return output;
@@ -153959,21 +154244,21 @@ function jsonToKeyPathChunks(value, label = "$") {
153959
154244
  walk(value, label, out);
153960
154245
  return out;
153961
154246
  }
153962
- function walk(val, path31, out) {
154247
+ function walk(val, path32, out) {
153963
154248
  if (val === null || val === undefined)
153964
154249
  return;
153965
154250
  if (Array.isArray(val)) {
153966
154251
  if (val.length === 0) {
153967
- out.push({ path: path31, content: `**${path31}** = _[]_` });
154252
+ out.push({ path: path32, content: `**${path32}** = _[]_` });
153968
154253
  return;
153969
154254
  }
153970
154255
  if (val.every((v) => v !== null && typeof v === "object")) {
153971
- val.forEach((v, i) => walk(v, `${path31}[${i}]`, out));
154256
+ val.forEach((v, i) => walk(v, `${path32}[${i}]`, out));
153972
154257
  return;
153973
154258
  }
153974
154259
  const items = val.map((v) => `- \`${String(v)}\``).join(`
153975
154260
  `);
153976
- out.push({ path: path31, content: `**${path31}**
154261
+ out.push({ path: path32, content: `**${path32}**
153977
154262
 
153978
154263
  ${items}` });
153979
154264
  return;
@@ -153981,16 +154266,16 @@ ${items}` });
153981
154266
  if (typeof val === "object") {
153982
154267
  const entries = Object.entries(val);
153983
154268
  if (entries.length === 0) {
153984
- out.push({ path: path31, content: `**${path31}** = _{}_` });
154269
+ out.push({ path: path32, content: `**${path32}** = _{}_` });
153985
154270
  return;
153986
154271
  }
153987
154272
  for (const [k, v] of entries) {
153988
154273
  const safeKey = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k);
153989
- walk(v, `${path31}.${safeKey}`, out);
154274
+ walk(v, `${path32}.${safeKey}`, out);
153990
154275
  }
153991
154276
  return;
153992
154277
  }
153993
- out.push({ path: path31, content: `**${path31}** = \`${String(val)}\`` });
154278
+ out.push({ path: path32, content: `**${path32}** = \`${String(val)}\`` });
153994
154279
  }
153995
154280
  var gfm, STRIP_SELECTORS, tdCache = null;
153996
154281
  var init_html_to_md = __esm(() => {
@@ -154094,6 +154379,7 @@ async function fetchAndConvertOne(url2, deps, opts = {}) {
154094
154379
  } catch (err) {
154095
154380
  const msg = err instanceof Error ? err.message : String(err);
154096
154381
  logger.error("fetch_and_index indexChunk failed", err, {
154382
+ projectId,
154097
154383
  url: url2,
154098
154384
  chunkId: chunk.id
154099
154385
  });
@@ -154284,6 +154570,7 @@ class WebController {
154284
154570
  return s.value;
154285
154571
  const msg = s.reason instanceof Error ? s.reason.message : String(s.reason);
154286
154572
  logger.error("fetch_and_index job rejected", s.reason, {
154573
+ projectId,
154287
154574
  url: batch[i].url
154288
154575
  });
154289
154576
  return { kind: "error", url: batch[i].url, error: msg };
@@ -154416,7 +154703,7 @@ init_config();
154416
154703
  init_dist();
154417
154704
  init_inference_providers();
154418
154705
  import os9 from "os";
154419
- import path31 from "path";
154706
+ import path32 from "path";
154420
154707
  var WRITABLE_PROVIDERS = ["ollama", "lmstudio", "mistral", "openai", "google", "cohere"];
154421
154708
  var GENERATOR_MARKER = "scripts/generate-subagent-artifacts.ts";
154422
154709
  var GENERATOR_MARKER_MAX_LEVELS = 6;
@@ -154459,6 +154746,14 @@ Commands:
154459
154746
  profile set <name> [--host <h>] [--dry-run]
154460
154747
  Switch installed agents to a profile (restart required after)
154461
154748
 
154749
+ doctor [--fix] [--host <h>] [--target <dir>]
154750
+ Report agent model/profile drift: live-tree vs recorded
154751
+ versions, per-role models, variant staleness, env
154752
+ overrides. --fix re-runs the profile switch for the
154753
+ recorded active profile (restart required after).
154754
+ --target redirects the home the state/registries are
154755
+ read from (test seam, same convention as bootstrap)
154756
+
154462
154757
  bootstrap list List every startup-contract rule: state, default, description
154463
154758
  bootstrap show Same as 'bootstrap list'
154464
154759
  bootstrap enable <rule-id> [--target <dir> --yes] [--dry-run]
@@ -154476,6 +154771,8 @@ Examples:
154476
154771
  massa-ai-config set embedding.dimensions 1024
154477
154772
  massa-ai-config recover my-project --path /home/user/renamed-dir
154478
154773
  massa-ai-config profile set work --dry-run
154774
+ massa-ai-config doctor
154775
+ massa-ai-config doctor --fix
154479
154776
  massa-ai-config bootstrap list
154480
154777
  massa-ai-config bootstrap disable caveman
154481
154778
  `);
@@ -154519,6 +154816,30 @@ function formatSwitchReport(report) {
154519
154816
  A host session restart is required for the change to take effect.`);
154520
154817
  }
154521
154818
  }
154819
+ function formatDriftReport(report) {
154820
+ console.log(`doctor (${report.host}, route: ${report.route})`);
154821
+ console.log(` live root: ${report.liveRoot ?? "n/a"}`);
154822
+ console.log(` source version: ${report.sourceVersion ?? "n/a"} (live tree)`);
154823
+ console.log(` state version: ${report.stateVersion ?? "n/a"} (install-state)`);
154824
+ console.log(` pinned version: ${report.pinnedVersion ?? "n/a"} (installed_plugins)`);
154825
+ console.log(` active profile: ${report.activeProfile ?? "n/a"}`);
154826
+ for (const role of report.roles) {
154827
+ const stale = role.staleVariant ? " \u2014 STALE vs the recorded profile's variant" : "";
154828
+ console.log(` ${role.name}: model=${role.model ?? "unknown"} effort=${role.effort ?? "unknown"}${stale}`);
154829
+ }
154830
+ if (report.versionDrift) {
154831
+ console.log(` drift: live tree ${report.sourceVersion} != recorded ${report.stateVersion} \u2014 update the plugin (or re-run the installer)`);
154832
+ }
154833
+ if (report.profileMaterialized) {
154834
+ console.log(" drift: active agent files differ from the recorded profile's variants \u2014 run `massa-ai-config doctor --fix` (re-runs the profile switch)");
154835
+ }
154836
+ if (report.envOverride) {
154837
+ console.log(` override: ${report.envOverride.name}=${report.envOverride.value} wins over every per-agent model at runtime \u2014 remove it from the host env to let profiles govern`);
154838
+ }
154839
+ if (report.route !== "unresolved" && !report.versionDrift && !report.profileMaterialized && !report.envOverride) {
154840
+ console.log(" healthy: every recording agrees.");
154841
+ }
154842
+ }
154522
154843
  async function runCli(argv) {
154523
154844
  const args = argv;
154524
154845
  const command = args[0];
@@ -154754,6 +155075,39 @@ Using defaults:`);
154754
155075
  console.error("Usage: massa-ai-config profile <list|show|set> ...");
154755
155076
  return 1;
154756
155077
  }
155078
+ case "doctor": {
155079
+ const fix = options["fix"] === true;
155080
+ const hostOpt = typeof options.host === "string" ? options.host : undefined;
155081
+ if (hostOpt !== undefined && !isHost(hostOpt)) {
155082
+ console.error(`Error: unknown host "${hostOpt}"`);
155083
+ return 1;
155084
+ }
155085
+ const host = hostOpt ?? "claude";
155086
+ const targetHome = typeof options.target === "string" ? options.target : os9.homedir();
155087
+ try {
155088
+ let report = runtimeDriftReport({ targetHome, host });
155089
+ if (fix) {
155090
+ const profile = report.activeProfile;
155091
+ if (!profile) {
155092
+ console.error("Error: no recorded active profile in install-state.json \u2014 run " + "`massa-ai-config profile set <name>` first; there is nothing to fix from.");
155093
+ return 1;
155094
+ }
155095
+ const sourceRoot = findRepoRootWithMarker(import.meta.dirname, GENERATOR_MARKER, GENERATOR_MARKER_MAX_LEVELS);
155096
+ formatVariantSync(syncGeneratedVariants({ sourceRoot, targetHome }));
155097
+ const switchReport = switchProfile({ profile, host, targetHome });
155098
+ formatSwitchReport(switchReport);
155099
+ if (!reportSucceeded(switchReport)) {
155100
+ return 1;
155101
+ }
155102
+ report = runtimeDriftReport({ targetHome, host });
155103
+ }
155104
+ formatDriftReport(report);
155105
+ return 0;
155106
+ } catch (e) {
155107
+ console.error(`Error: ${e.message}`);
155108
+ return 1;
155109
+ }
155110
+ }
154757
155111
  case "bootstrap": {
154758
155112
  const subcommand = args[1];
154759
155113
  if (subcommand === "list" || subcommand === "show") {
@@ -154778,7 +155132,7 @@ Using defaults:`);
154778
155132
  return 1;
154779
155133
  }
154780
155134
  const targetOpt = typeof options.target === "string" ? options.target : undefined;
154781
- const targetHome = targetOpt === undefined ? os9.homedir() : path31.resolve(targetOpt);
155135
+ const targetHome = targetOpt === undefined ? os9.homedir() : path32.resolve(targetOpt);
154782
155136
  if (targetHome !== os9.homedir() && options.yes !== true) {
154783
155137
  console.error(`Error: --target ${targetHome} is not your home (${os9.homedir()}) \u2014 pass --yes to confirm writing there`);
154784
155138
  return 1;
@@ -154798,7 +155152,7 @@ Using defaults:`);
154798
155152
  const report = applyBootstrapState({
154799
155153
  targetHome,
154800
155154
  dryRun,
154801
- sourcePath: repoRoot === null ? undefined : path31.join(repoRoot, "skills", "AGENTS.md")
155155
+ sourcePath: repoRoot === null ? undefined : path32.join(repoRoot, "skills", "AGENTS.md")
154802
155156
  });
154803
155157
  console.log(formatBootstrapReport(report));
154804
155158
  return bootstrapReportSucceeded(report) ? 0 : 1;