@fro.bot/systematic 3.30.0 → 3.31.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.
@@ -23,8 +23,8 @@ function parseFrontmatter(content) {
23
23
  }
24
24
 
25
25
  // src/lib/config.ts
26
- import fs3 from "fs";
27
- import path2 from "path";
26
+ import fs4 from "fs";
27
+ import path3 from "path";
28
28
 
29
29
  // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
30
30
  function createScanner(text, ignoreTrivia = false) {
@@ -7522,6 +7522,183 @@ function readBytesBounded(filePath, maxBytes) {
7522
7522
  }
7523
7523
  }
7524
7524
 
7525
+ // src/lib/search-exclude.ts
7526
+ var MAX_EXCLUDE_PATTERNS = 64;
7527
+ var MAX_EXCLUDE_PATTERN_LENGTH = 256;
7528
+ var REASON_NOT_A_STRING = "not a string";
7529
+ var REASON_NOT_AN_ARRAY = "not an array";
7530
+ var REASON_EMPTY = "empty pattern";
7531
+ var REASON_TOO_LONG = `longer than ${MAX_EXCLUDE_PATTERN_LENGTH} characters`;
7532
+ var REASON_BACKSLASH = "backslash is not supported, use / between segments";
7533
+ var REASON_NEGATION = "negation with ! is not supported";
7534
+ var REASON_LEADING_SLASH = "starts with /, patterns are relative to the source root";
7535
+ var REASON_LEADING_DOT_SLASH = "starts with ./, write the path without it";
7536
+ var REASON_CHARACTER_CLASS = "character classes with [ ] are not supported";
7537
+ var REASON_EMPTY_SEGMENT = "contains an empty path segment";
7538
+ var REASON_DOT_SEGMENT = "contains a . path segment";
7539
+ var REASON_DOT_DOT_SEGMENT = "contains a .. path segment";
7540
+ var REASON_EMBEDDED_GLOBSTAR = "** must be a whole path segment";
7541
+ var GLOBSTAR = "**";
7542
+ function invalid(reason) {
7543
+ return { ok: false, reason };
7544
+ }
7545
+ var WHOLE_PATTERN_RULES = [
7546
+ [(pattern) => pattern.length === 0, REASON_EMPTY],
7547
+ [(pattern) => pattern.length > MAX_EXCLUDE_PATTERN_LENGTH, REASON_TOO_LONG],
7548
+ [(pattern) => pattern.includes("\\"), REASON_BACKSLASH],
7549
+ [(pattern) => pattern.startsWith("!"), REASON_NEGATION],
7550
+ [(pattern) => pattern.startsWith("/"), REASON_LEADING_SLASH],
7551
+ [(pattern) => pattern.startsWith("./"), REASON_LEADING_DOT_SLASH],
7552
+ [
7553
+ (pattern) => pattern.includes("[") || pattern.includes("]"),
7554
+ REASON_CHARACTER_CLASS
7555
+ ]
7556
+ ];
7557
+ function segmentProblem(segment) {
7558
+ if (segment.length === 0)
7559
+ return REASON_EMPTY_SEGMENT;
7560
+ if (segment === ".")
7561
+ return REASON_DOT_SEGMENT;
7562
+ if (segment === "..")
7563
+ return REASON_DOT_DOT_SEGMENT;
7564
+ if (segment !== GLOBSTAR && segment.includes(GLOBSTAR)) {
7565
+ return REASON_EMBEDDED_GLOBSTAR;
7566
+ }
7567
+ return;
7568
+ }
7569
+ function parsePattern(pattern) {
7570
+ if (typeof pattern !== "string")
7571
+ return invalid(REASON_NOT_A_STRING);
7572
+ for (const [applies, reason] of WHOLE_PATTERN_RULES) {
7573
+ if (applies(pattern))
7574
+ return invalid(reason);
7575
+ }
7576
+ const body = pattern.endsWith("/") ? pattern.slice(0, -1) : pattern;
7577
+ const segments = [];
7578
+ for (const segment of body.split("/")) {
7579
+ const problem = segmentProblem(segment);
7580
+ if (problem !== undefined)
7581
+ return invalid(problem);
7582
+ if (segment === GLOBSTAR && segments[segments.length - 1] === GLOBSTAR) {
7583
+ continue;
7584
+ }
7585
+ segments.push(segment);
7586
+ }
7587
+ return {
7588
+ ok: true,
7589
+ compiled: { segments, nameOnly: !body.includes("/") }
7590
+ };
7591
+ }
7592
+ function validateExcludePattern(pattern) {
7593
+ const parsed = parsePattern(pattern);
7594
+ return parsed.ok ? { ok: true } : { ok: false, reason: parsed.reason };
7595
+ }
7596
+ function validateExcludeList(value) {
7597
+ if (!Array.isArray(value))
7598
+ return { ok: false, reason: REASON_NOT_AN_ARRAY };
7599
+ const patterns = [];
7600
+ const issues = [];
7601
+ const inspected = Math.min(value.length, MAX_EXCLUDE_PATTERNS);
7602
+ for (let index = 0;index < inspected; index++) {
7603
+ const element = value[index];
7604
+ const verdict = validateExcludePattern(element);
7605
+ if (verdict.ok && typeof element === "string") {
7606
+ patterns.push(element);
7607
+ } else if (!verdict.ok) {
7608
+ issues.push({ index, reason: verdict.reason });
7609
+ }
7610
+ }
7611
+ if (value.length > MAX_EXCLUDE_PATTERNS) {
7612
+ const dropped = value.length - MAX_EXCLUDE_PATTERNS;
7613
+ issues.push({
7614
+ index: MAX_EXCLUDE_PATTERNS,
7615
+ reason: `${dropped} ${dropped === 1 ? "pattern" : "patterns"} over the limit of ${MAX_EXCLUDE_PATTERNS}`
7616
+ });
7617
+ }
7618
+ return { ok: true, patterns, issues };
7619
+ }
7620
+ function compileExcludePattern(pattern) {
7621
+ const parsed = parsePattern(pattern);
7622
+ return parsed.ok ? parsed.compiled : undefined;
7623
+ }
7624
+ function characterLength(text, index) {
7625
+ const high = text.charCodeAt(index);
7626
+ if (high >= 55296 && high <= 56319 && index + 1 < text.length) {
7627
+ const low = text.charCodeAt(index + 1);
7628
+ if (low >= 56320 && low <= 57343)
7629
+ return 2;
7630
+ }
7631
+ return 1;
7632
+ }
7633
+ function matchSegment(pattern, text) {
7634
+ let p = 0;
7635
+ let t = 0;
7636
+ let starP = -1;
7637
+ let starT = 0;
7638
+ while (t < text.length) {
7639
+ const code = p < pattern.length ? pattern.charCodeAt(p) : -1;
7640
+ if (code === 42) {
7641
+ starP = p;
7642
+ starT = t;
7643
+ p++;
7644
+ } else if (code === 63) {
7645
+ p++;
7646
+ t += characterLength(text, t);
7647
+ } else if (code !== -1 && code === text.charCodeAt(t)) {
7648
+ p++;
7649
+ t++;
7650
+ } else if (starP !== -1) {
7651
+ starT += characterLength(text, starT);
7652
+ t = starT;
7653
+ p = starP + 1;
7654
+ } else {
7655
+ return false;
7656
+ }
7657
+ }
7658
+ while (p < pattern.length && pattern.charCodeAt(p) === 42)
7659
+ p++;
7660
+ return p === pattern.length;
7661
+ }
7662
+ function matchAnchored(pattern, path) {
7663
+ let reached = new Array(pattern.length + 1).fill(false);
7664
+ reached[0] = true;
7665
+ for (let j = 1;j <= pattern.length; j++) {
7666
+ reached[j] = pattern[j - 1] === GLOBSTAR && reached[j - 1] === true;
7667
+ }
7668
+ for (const segment of path) {
7669
+ const next = new Array(pattern.length + 1).fill(false);
7670
+ for (let j = 1;j <= pattern.length; j++) {
7671
+ const part = pattern[j - 1] ?? "";
7672
+ next[j] = part === GLOBSTAR ? next[j - 1] === true || reached[j] === true : reached[j - 1] === true && matchSegment(part, segment);
7673
+ }
7674
+ reached = next;
7675
+ }
7676
+ return reached[pattern.length] === true;
7677
+ }
7678
+ function matchesCompiled(compiled, relativePath) {
7679
+ if (compiled.nameOnly) {
7680
+ const name = relativePath.slice(relativePath.lastIndexOf("/") + 1);
7681
+ const part = compiled.segments[0] ?? "";
7682
+ return part === GLOBSTAR || matchSegment(part, name);
7683
+ }
7684
+ return matchAnchored(compiled.segments, relativePath.split("/"));
7685
+ }
7686
+ function compileExcludePatterns(patterns) {
7687
+ const compiled = [];
7688
+ for (const pattern of patterns) {
7689
+ const one = compileExcludePattern(pattern);
7690
+ if (one !== undefined)
7691
+ compiled.push(one);
7692
+ }
7693
+ if (compiled.length === 0)
7694
+ return () => false;
7695
+ return (relativePath) => {
7696
+ if (relativePath.length === 0)
7697
+ return false;
7698
+ return compiled.some((entry) => matchesCompiled(entry, relativePath));
7699
+ };
7700
+ }
7701
+
7525
7702
  // src/lib/search-user-config.ts
7526
7703
  var SEARCH_SOURCE_FORMATS = ["markdown", "deciduous"];
7527
7704
  var SOURCE_NAME_PATTERN = /^[A-Za-z0-9_-]{1,40}$/;
@@ -7542,11 +7719,19 @@ var sourceProjectsSchema = array(string().min(1)).optional().meta({
7542
7719
  description: "User config only, and required there: at least one absolute or `~`-prefixed main repository root this source applies to. A user source that omits it or leaves it empty is dropped with a warning, so a source can never apply to every project by accident. A project config may not set it.",
7543
7720
  examples: [["~/src/github.com/me/app"]]
7544
7721
  });
7722
+ var sourceExcludeSchema = array(string()).optional().meta({
7723
+ description: `Patterns for files and folders to skip under each root. A pattern with no \`/\` matches a file or folder name at any depth (\`log.md\`, \`.stryker-tmp\`), and a matched folder is skipped with everything below it. A pattern with a \`/\` is anchored at the root: \`drafts/*.md\` matches \`drafts/a.md\` but not \`notes/drafts/a.md\`. \`*\` matches any run of characters inside one name, \`?\` matches one character, and \`**\` as a whole segment matches any number of folders (\`a/**/b\`). A trailing \`/\` is ignored. Matching is case-sensitive. Negation (\`!\`), character classes (\`[ ]\`), a leading \`/\` or \`./\`, \`..\`, and backslashes are not supported. A source takes at most ${MAX_EXCLUDE_PATTERNS} patterns of at most ${MAX_EXCLUDE_PATTERN_LENGTH} characters. An invalid pattern is dropped with a warning that names its position, and the other patterns still apply. Allowed in user and project config.`,
7724
+ examples: [
7725
+ ["log.md", ".stryker-tmp"],
7726
+ ["drafts/*.md", "archive/**/old"]
7727
+ ]
7728
+ });
7545
7729
  var SearchSourceSchema = object({
7546
7730
  name: sourceNameSchema,
7547
7731
  format: sourceFormatSchema,
7548
7732
  roots: sourceRootsSchema,
7549
- projects: sourceProjectsSchema
7733
+ projects: sourceProjectsSchema,
7734
+ exclude: sourceExcludeSchema
7550
7735
  }).strict().meta({
7551
7736
  description: "One opt-in decision source: a name, a format and one or more roots.",
7552
7737
  examples: [{ name: "team-rfcs", format: "markdown", roots: ["docs/rfcs"] }]
@@ -7629,6 +7814,9 @@ function unknownKeyWarning(trust, sourcePath) {
7629
7814
  function entryWarning(sourcePath, label, reason) {
7630
7815
  return `[systematic] search source ${label} in ${sourcePath} was dropped: ${reason}. Its valid siblings still load.`;
7631
7816
  }
7817
+ function excludeWarning(sourcePath, label, issue) {
7818
+ return `[systematic] \`exclude[${issue.index}]\` of search source ${label} in ${sourcePath} was dropped: ${issue.reason}. The source and its other patterns still load.`;
7819
+ }
7632
7820
  function isTildePath(value) {
7633
7821
  return value === "~" || value.startsWith("~/") || value.startsWith("~\\");
7634
7822
  }
@@ -7654,7 +7842,8 @@ var ENTRY_KEYS = new Set([
7654
7842
  "name",
7655
7843
  "format",
7656
7844
  "roots",
7657
- "projects"
7845
+ "projects",
7846
+ "exclude"
7658
7847
  ]);
7659
7848
  function isFormat(value) {
7660
7849
  return typeof value === "string" && SEARCH_SOURCE_FORMATS.includes(value);
@@ -7714,21 +7903,30 @@ function validateEntry(raw, index, trust) {
7714
7903
  const projects = validateProjects(raw.projects, trust);
7715
7904
  if (typeof projects === "string")
7716
7905
  return rejectEntry(label, projects);
7906
+ const exclude = Object.hasOwn(raw, "exclude") ? validateExcludeList(raw.exclude) : undefined;
7907
+ if (exclude?.ok === false) {
7908
+ return rejectEntry(label, `exclude is invalid (${exclude.reason})`);
7909
+ }
7910
+ const patterns = exclude?.patterns ?? [];
7717
7911
  return {
7718
7912
  ok: true,
7719
7913
  entry: {
7720
7914
  name,
7721
7915
  format,
7722
7916
  roots: [...roots],
7723
- ...projects !== undefined && { projects: [...projects] }
7724
- }
7917
+ ...projects !== undefined && { projects: [...projects] },
7918
+ ...patterns.length > 0 && { exclude: [...patterns] }
7919
+ },
7920
+ excludeIssues: exclude?.issues ?? []
7725
7921
  };
7726
7922
  }
7727
7923
  function warn(state, message) {
7728
- if (state.warnings.length < MAX_DETAIL_WARNINGS)
7924
+ if (state.warnings.length < MAX_DETAIL_WARNINGS) {
7729
7925
  state.warnings.push(message);
7730
- else
7731
- state.suppressed += 1;
7926
+ return true;
7927
+ }
7928
+ state.suppressed += 1;
7929
+ return false;
7732
7930
  }
7733
7931
  function validateSources(raw, state) {
7734
7932
  if (!Array.isArray(raw)) {
@@ -7742,18 +7940,43 @@ function validateSources(raw, state) {
7742
7940
  raw.forEach((item, index) => {
7743
7941
  const result = validateEntry(item, index, state.trust);
7744
7942
  if (!result.ok) {
7745
- warn(state, entryWarning(state.sourcePath, result.label, result.reason));
7943
+ dropEntry(state, index, result.label, result.reason);
7746
7944
  return;
7747
7945
  }
7748
7946
  if (seen.has(result.entry.name)) {
7749
- warn(state, entryWarning(state.sourcePath, `"${result.entry.name}"`, "the name is already used earlier in this file, so the first entry is kept"));
7947
+ dropEntry(state, index, `"${result.entry.name}"`, "the name is already used earlier in this file, so the first entry is kept");
7750
7948
  return;
7751
7949
  }
7752
7950
  seen.add(result.entry.name);
7753
7951
  kept.push(result.entry);
7952
+ const label = `"${result.entry.name}"`;
7953
+ const warnings = [];
7954
+ for (const issue of result.excludeIssues) {
7955
+ const message = excludeWarning(state.sourcePath, label, issue);
7956
+ if (warn(state, message))
7957
+ warnings.push(message);
7958
+ }
7959
+ state.entries.push({
7960
+ kind: "kept",
7961
+ index,
7962
+ label,
7963
+ entry: result.entry,
7964
+ warnings
7965
+ });
7754
7966
  });
7755
7967
  return kept;
7756
7968
  }
7969
+ function dropEntry(state, index, label, reason) {
7970
+ state.dropped.push({ label, reason });
7971
+ const message = entryWarning(state.sourcePath, label, reason);
7972
+ state.entries.push({
7973
+ kind: "dropped",
7974
+ index,
7975
+ label,
7976
+ reason,
7977
+ warnings: warn(state, message) ? [message] : []
7978
+ });
7979
+ }
7757
7980
  function validateAllowList(raw, state) {
7758
7981
  if (!Array.isArray(raw)) {
7759
7982
  state.unreadable = true;
@@ -7803,6 +8026,8 @@ function validateSearchConfig(value, trust, sourcePath) {
7803
8026
  trust,
7804
8027
  sourcePath: displaySafe(sourcePath),
7805
8028
  warnings: [],
8029
+ dropped: [],
8030
+ entries: [],
7806
8031
  suppressed: 0,
7807
8032
  unreadable: false,
7808
8033
  structural: false
@@ -7813,7 +8038,9 @@ function validateSearchConfig(value, trust, sourcePath) {
7813
8038
  settings: undefined,
7814
8039
  unreadable: true,
7815
8040
  structural: true,
7816
- warnings: state.warnings
8041
+ warnings: state.warnings,
8042
+ dropped: state.dropped,
8043
+ entries: state.entries
7817
8044
  };
7818
8045
  }
7819
8046
  const settings = {};
@@ -7835,20 +8062,27 @@ function validateSearchConfig(value, trust, sourcePath) {
7835
8062
  settings,
7836
8063
  unreadable: state.unreadable,
7837
8064
  structural: state.structural,
7838
- warnings: state.warnings
8065
+ warnings: state.warnings,
8066
+ dropped: state.dropped,
8067
+ entries: state.entries
7839
8068
  };
7840
8069
  }
7841
8070
  function formatSearchFileWarning(sourcePath, reason) {
7842
8071
  return `[systematic] search settings in ${displaySafe(sourcePath)} could not be read (${reason}); the settings were ignored, search still runs and its results carry a \`config unreadable\` note.`;
7843
8072
  }
7844
8073
  function mergeSearchSettings(sources) {
7845
- const acc = { allow: [], byName: new Map };
8074
+ const acc = {
8075
+ allow: [],
8076
+ byName: new Map,
8077
+ layers: new Map
8078
+ };
7846
8079
  let unreadable = false;
7847
8080
  for (const source of sources) {
7848
8081
  if (source.unreadable)
7849
8082
  unreadable = true;
7850
- if (source.settings !== undefined)
7851
- absorb(acc, source.settings);
8083
+ if (source.settings !== undefined) {
8084
+ absorb(acc, source.settings, source.layer);
8085
+ }
7852
8086
  }
7853
8087
  const merged = {
7854
8088
  ...acc.enabled !== undefined && { enabled: acc.enabled },
@@ -7856,23 +8090,37 @@ function mergeSearchSettings(sources) {
7856
8090
  ...acc.byName.size > 0 && { sources: [...acc.byName.values()] }
7857
8091
  };
7858
8092
  if (Object.keys(merged).length === 0) {
7859
- return { settings: undefined, unreadable };
8093
+ return { settings: undefined, unreadable, sourceLayers: acc.layers };
7860
8094
  }
7861
- return { settings: merged, unreadable };
8095
+ return { settings: merged, unreadable, sourceLayers: acc.layers };
7862
8096
  }
7863
- function absorb(acc, settings) {
8097
+ function absorb(acc, settings, layer) {
7864
8098
  if (settings.enabled !== undefined)
7865
8099
  acc.enabled = settings.enabled;
7866
8100
  for (const entry of settings.allow_project_sources ?? []) {
7867
8101
  if (!acc.allow.includes(entry))
7868
8102
  acc.allow.push(entry);
7869
8103
  }
7870
- for (const entry of settings.sources ?? [])
8104
+ for (const entry of settings.sources ?? []) {
7871
8105
  acc.byName.set(entry.name, entry);
8106
+ if (layer === undefined)
8107
+ acc.layers.delete(entry.name);
8108
+ else
8109
+ acc.layers.set(entry.name, layer);
8110
+ }
8111
+ }
8112
+ function configEntryExists(target) {
8113
+ try {
8114
+ fs2.lstatSync(target);
8115
+ return true;
8116
+ } catch (error) {
8117
+ const code = errorCode2(error);
8118
+ return code !== "ENOENT" && code !== "ENOTDIR";
8119
+ }
7872
8120
  }
7873
8121
  function selectConfigFile(dir, basename) {
7874
8122
  const jsoncPath = path.join(dir, `${basename}.jsonc`);
7875
- if (fs2.existsSync(jsoncPath))
8123
+ if (configEntryExists(jsoncPath))
7876
8124
  return jsoncPath;
7877
8125
  return path.join(dir, `${basename}.json`);
7878
8126
  }
@@ -7882,6 +8130,55 @@ function resolveUserLevelConfigDirs(options) {
7882
8130
  const rawCustom = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
7883
8131
  return { homeDir, userConfigDir, customConfigDir: rawCustom || undefined };
7884
8132
  }
8133
+ function realpathOrResolved(dir) {
8134
+ const resolved = path.resolve(dir);
8135
+ try {
8136
+ return fs2.realpathSync(resolved);
8137
+ } catch {
8138
+ return resolved;
8139
+ }
8140
+ }
8141
+ function selectUserLevelConfigFiles(dirs) {
8142
+ const files = [
8143
+ {
8144
+ layer: "user",
8145
+ path: selectConfigFile(dirs.userConfigDir, "systematic")
8146
+ },
8147
+ {
8148
+ layer: "user.local",
8149
+ path: selectConfigFile(dirs.userConfigDir, "systematic.local")
8150
+ }
8151
+ ];
8152
+ const custom = dirs.customConfigDir;
8153
+ if (!custom)
8154
+ return { files, aliased: false };
8155
+ files.push({ layer: "custom", path: selectConfigFile(custom, "systematic") }, {
8156
+ layer: "custom.local",
8157
+ path: selectConfigFile(custom, "systematic.local")
8158
+ });
8159
+ const aliased = path.resolve(custom) === path.resolve(dirs.userConfigDir) || realpathOrResolved(custom) === realpathOrResolved(dirs.userConfigDir);
8160
+ return { files, aliased };
8161
+ }
8162
+ function selectProjectConfigFile(repoRoot) {
8163
+ const opencodeFile = selectConfigFile(path.join(repoRoot, ".opencode"), "systematic");
8164
+ const rootFile = selectConfigFile(repoRoot, ".systematic");
8165
+ if (!configEntryExists(rootFile))
8166
+ return { path: opencodeFile };
8167
+ return configEntryExists(opencodeFile) ? { path: rootFile, ignoredPath: opencodeFile } : { path: rootFile };
8168
+ }
8169
+ function findStartDirProjectConfig(startDir, repoRoot, selectedProjectConfig) {
8170
+ if (!repoRoot.foundGit)
8171
+ return;
8172
+ if (realpathOrResolved(startDir) === repoRoot.root)
8173
+ return;
8174
+ const candidate = selectConfigFile(path.join(startDir, ".opencode"), "systematic");
8175
+ if (!configEntryExists(candidate))
8176
+ return;
8177
+ return realpathOrResolved(candidate) === realpathOrResolved(selectedProjectConfig) ? undefined : candidate;
8178
+ }
8179
+ function startDirProjectWarning(startDirConfig, projectRoot, selectedProjectConfig, safe = displaySafe) {
8180
+ return `[systematic] project config (${safe(startDirConfig)}) is below the repository root (${safe(projectRoot)}) and is not read; project config is read from (${safe(selectedProjectConfig)}).`;
8181
+ }
7885
8182
  function errorCode2(error) {
7886
8183
  return error instanceof Error && "code" in error ? error.code : undefined;
7887
8184
  }
@@ -7892,7 +8189,7 @@ function readTextBounded(filePath, maxBytes) {
7892
8189
  case "bytes":
7893
8190
  return { kind: "text", content: read.bytes.toString("utf-8") };
7894
8191
  case "absent":
7895
- return { kind: "absent" };
8192
+ return absentOrDangling(filePath);
7896
8193
  case "not-regular":
7897
8194
  return { kind: "failed", reason: "not a regular file" };
7898
8195
  case "too-large":
@@ -7904,12 +8201,15 @@ function readTextBounded(filePath, maxBytes) {
7904
8201
  return { kind: "failed", reason: "unable to read file" };
7905
8202
  }
7906
8203
  }
8204
+ function absentOrDangling(filePath) {
8205
+ return configEntryExists(filePath) ? { kind: "failed", reason: "unable to read file" } : { kind: "absent" };
8206
+ }
7907
8207
  function readTextWhole(filePath) {
7908
8208
  try {
7909
8209
  return { kind: "text", content: fs2.readFileSync(filePath, "utf-8") };
7910
8210
  } catch (error) {
7911
8211
  if (errorCode2(error) === "ENOENT")
7912
- return { kind: "absent" };
8212
+ return absentOrDangling(filePath);
7913
8213
  return { kind: "failed", reason: "unable to read file" };
7914
8214
  }
7915
8215
  }
@@ -7936,58 +8236,111 @@ function readSearchBlock(filePath, maxBytes) {
7936
8236
  searchBlock: parsed.search
7937
8237
  };
7938
8238
  }
8239
+ var NOTHING_READ = {
8240
+ source: undefined,
8241
+ warnings: [],
8242
+ readFailures: [],
8243
+ dropped: [],
8244
+ entries: []
8245
+ };
8246
+ function readUserLevelFile(file) {
8247
+ const read = readSearchBlock(file.path);
8248
+ if (read.kind === "absent")
8249
+ return NOTHING_READ;
8250
+ if (read.kind === "failed") {
8251
+ const warning = formatSearchFileWarning(file.path, read.reason);
8252
+ return {
8253
+ source: { unreadable: true },
8254
+ warnings: [warning],
8255
+ readFailures: [warning],
8256
+ dropped: [],
8257
+ entries: []
8258
+ };
8259
+ }
8260
+ if (!read.has)
8261
+ return NOTHING_READ;
8262
+ const validation = validateSearchConfig(read.searchBlock, "user", file.path);
8263
+ return {
8264
+ source: {
8265
+ settings: validation.settings,
8266
+ unreadable: validation.unreadable
8267
+ },
8268
+ warnings: validation.warnings,
8269
+ readFailures: [],
8270
+ dropped: validation.dropped,
8271
+ entries: validation.entries
8272
+ };
8273
+ }
8274
+ var ALIASED_TWIN = { custom: "user", "custom.local": "user.local" };
7939
8275
  function loadUserLevelSearchSettings(options) {
7940
- const dirs = resolveUserLevelConfigDirs(options);
7941
- const files = [
7942
- selectConfigFile(dirs.userConfigDir, "systematic"),
7943
- ...dirs.customConfigDir ? [selectConfigFile(dirs.customConfigDir, "systematic")] : []
7944
- ];
8276
+ const selection = selectUserLevelConfigFiles(resolveUserLevelConfigDirs(options));
7945
8277
  const warnings = [];
8278
+ const readFailures = [];
8279
+ const dropped = [];
8280
+ const entries = [];
7946
8281
  const sources = [];
7947
- for (const filePath of files) {
7948
- const read = readSearchBlock(filePath);
7949
- if (read.kind === "absent")
8282
+ const reads = new Map;
8283
+ for (const file of selection.files) {
8284
+ const twin = selection.aliased ? ALIASED_TWIN[file.layer] : undefined;
8285
+ const shared = twin === undefined ? undefined : reads.get(twin);
8286
+ const read = shared ?? readUserLevelFile(file);
8287
+ reads.set(file.layer, read);
8288
+ if (read.source)
8289
+ sources.push({ ...read.source, layer: file.layer });
8290
+ if (shared !== undefined)
7950
8291
  continue;
7951
- if (read.kind === "failed") {
7952
- warnings.push(formatSearchFileWarning(filePath, read.reason));
7953
- sources.push({ unreadable: true });
7954
- continue;
7955
- }
7956
- if (!read.has)
7957
- continue;
7958
- const validation = validateSearchConfig(read.searchBlock, "user", filePath);
7959
- warnings.push(...validation.warnings);
7960
- sources.push({
7961
- settings: validation.settings,
7962
- unreadable: validation.unreadable
7963
- });
8292
+ warnings.push(...read.warnings);
8293
+ readFailures.push(...read.readFailures);
8294
+ dropped.push(...read.dropped);
8295
+ entries.push(...read.entries);
7964
8296
  }
7965
8297
  const merged = mergeSearchSettings(sources);
7966
- return { ...merged, warnings };
8298
+ return {
8299
+ settings: merged.settings,
8300
+ unreadable: merged.unreadable,
8301
+ warnings,
8302
+ dropped,
8303
+ entries,
8304
+ sourceLayers: merged.sourceLayers,
8305
+ readFailures
8306
+ };
7967
8307
  }
7968
8308
  function formatProjectFileWarning(sourcePath, reason) {
7969
8309
  return `[systematic] project search settings in ${displaySafe(sourcePath)} could not be read (${reason}); the sources it proposes were ignored.`;
7970
8310
  }
8311
+ function formatShadowedProjectWarning(usedPath, ignoredPath) {
8312
+ return `[systematic] project config (${displaySafe(usedPath)}) takes precedence over (${displaySafe(ignoredPath)}), which is ignored; the two files are never merged.`;
8313
+ }
7971
8314
  function loadProjectSearchSources(checkoutRoot) {
7972
- const filePath = selectConfigFile(path.join(checkoutRoot, ".opencode"), "systematic");
8315
+ const selection = selectProjectConfigFile(checkoutRoot);
8316
+ const filePath = selection.path;
8317
+ const shadowed = selection.ignoredPath === undefined ? [] : [formatShadowedProjectWarning(filePath, selection.ignoredPath)];
7973
8318
  const read = readSearchBlock(filePath, MAX_PROJECT_CONFIG_BYTES);
7974
- if (read.kind === "absent") {
7975
- return { sources: [], warnings: [], unreadable: false };
7976
- }
8319
+ const nothing = {
8320
+ sources: [],
8321
+ warnings: shadowed,
8322
+ unreadable: false,
8323
+ dropped: [],
8324
+ entries: []
8325
+ };
8326
+ if (read.kind === "absent")
8327
+ return nothing;
7977
8328
  if (read.kind === "failed") {
7978
8329
  return {
7979
- sources: [],
7980
- warnings: [formatProjectFileWarning(filePath, read.reason)],
8330
+ ...nothing,
8331
+ warnings: [...shadowed, formatProjectFileWarning(filePath, read.reason)],
7981
8332
  unreadable: true
7982
8333
  };
7983
8334
  }
7984
8335
  if (!read.has)
7985
- return { sources: [], warnings: [], unreadable: false };
8336
+ return nothing;
7986
8337
  const validation = validateSearchConfig(read.searchBlock, "project", filePath);
7987
8338
  return {
7988
8339
  sources: validation.structural ? [] : validation.settings?.sources ?? [],
7989
- warnings: validation.warnings,
7990
- unreadable: validation.structural
8340
+ warnings: [...shadowed, ...validation.warnings],
8341
+ unreadable: validation.structural,
8342
+ dropped: validation.dropped,
8343
+ entries: validation.entries
7991
8344
  };
7992
8345
  }
7993
8346
 
@@ -8001,11 +8354,11 @@ var permissionSchema = record(string(), permissionRuleSchema).meta({
8001
8354
  description: "Permission overrides per tool",
8002
8355
  examples: [{ edit: "allow", bash: { curl: "allow", rm: "deny" } }]
8003
8356
  });
8004
- var MODEL_FORMAT_MESSAGE = 'must be in provider/model format (e.g., "anthropic/claude-sonnet-5")';
8357
+ var MODEL_FORMAT_MESSAGE = 'must be in provider/model format (e.g., "anthropic/claude-sonnet-5-5")';
8005
8358
  var MODEL_FORMAT_REGEX = /^[^\s/]+\/\S+$/;
8006
8359
  var modelSchema = string().min(1).regex(MODEL_FORMAT_REGEX, MODEL_FORMAT_MESSAGE).nullable().meta({
8007
8360
  description: "Model identifier in provider/model format, or null to inherit parent model",
8008
- examples: ["anthropic/claude-sonnet-5", null]
8361
+ examples: ["anthropic/claude-sonnet-5-5", null]
8009
8362
  });
8010
8363
  var variantSchema = string().min(1).max(128, "variant must be at most 128 characters").regex(/^\S+$/, "must be a non-empty string without whitespace").meta({
8011
8364
  description: "Model variant identifier",
@@ -8066,7 +8419,7 @@ var OpencodeHarnessBlockSchema = object({
8066
8419
  }).strict().meta({
8067
8420
  description: "OpenCode-specific routing block. When present, model/variant here override the flat model/variant fields for OpenCode only; the flat fields remain the harness-neutral default and still apply to Pi. `variant` is bound to whichever layer supplies `model`: it is used only from that layer or a more specific one, and is dropped when a more specific layer sets (or nulls) `model` without repeating the variant. A `variant` with no `model` anywhere in the merged overlay is a config-load error raised by the routing resolver, not a parse-time error.",
8068
8421
  examples: [
8069
- { model: "anthropic/claude-opus-5", variant: "high" },
8422
+ { model: "anthropic/claude-opus-5-5", variant: "high" },
8070
8423
  { model: null }
8071
8424
  ]
8072
8425
  });
@@ -8076,7 +8429,7 @@ var PiHarnessBlockSchema = object({
8076
8429
  }).strict().meta({
8077
8430
  description: "Pi-specific routing block. When present, model/thinking here override the flat model field and the legacy `pi_subagents.<name>.thinking` value for Pi only; the flat model field remains the harness-neutral default and still applies to OpenCode. Unlike OpenCode's `variant`, `thinking` is independent of `model`: it applies to whatever model the delegate ends up running, including one inherited from the parent session, so `thinking` with no `model` anywhere in the merged overlay is valid and never a config-load error.",
8078
8431
  examples: [
8079
- { model: "anthropic/claude-opus-5", thinking: "high" },
8432
+ { model: "anthropic/claude-opus-5-5", thinking: "high" },
8080
8433
  { model: null }
8081
8434
  ]
8082
8435
  });
@@ -8098,13 +8451,13 @@ var AgentOverlaySchema = object({
8098
8451
  description: "Per-agent configuration overlay",
8099
8452
  examples: [
8100
8453
  {
8101
- model: "anthropic/claude-opus-5",
8454
+ model: "anthropic/claude-opus-5-5",
8102
8455
  temperature: 0.1,
8103
8456
  mode: "subagent"
8104
8457
  },
8105
8458
  {
8106
- opencode: { model: "anthropic/claude-opus-5", variant: "high" },
8107
- pi: { model: "anthropic/claude-opus-5", thinking: "high" }
8459
+ opencode: { model: "anthropic/claude-opus-5-5", variant: "high" },
8460
+ pi: { model: "anthropic/claude-opus-5-5", thinking: "high" }
8108
8461
  }
8109
8462
  ]
8110
8463
  });
@@ -8124,7 +8477,7 @@ var CategoryOverlaySchema = object({
8124
8477
  }).strict().meta({
8125
8478
  description: "Per-category configuration overlay (same fields as agent minus disable)",
8126
8479
  examples: [
8127
- { model: "anthropic/claude-opus-5", temperature: 0.1 },
8480
+ { model: "anthropic/claude-opus-5-5", temperature: 0.1 },
8128
8481
  { opencode: { variant: "high" }, pi: { thinking: "high" } }
8129
8482
  ]
8130
8483
  });
@@ -8138,7 +8491,7 @@ var ProfileOverlaySchema = object({
8138
8491
  }).strict().meta({
8139
8492
  description: "Routing-only overlay fields permitted inside a named profile bundle entry: model, variant, temperature, top_p, and the opencode/pi harness blocks. Non-routing fields (permission, skills, mode, hidden, disable, steps, color) are rejected.",
8140
8493
  examples: [
8141
- { model: "anthropic/claude-opus-5" },
8494
+ { model: "anthropic/claude-opus-5-5" },
8142
8495
  { opencode: { variant: "high" }, pi: { thinking: "high" } }
8143
8496
  ]
8144
8497
  });
@@ -8155,13 +8508,13 @@ function createProfileBundleSchema(agentNames, qualifiedAgentIds) {
8155
8508
  }),
8156
8509
  categories: record(string(), ProfileOverlaySchema).optional().meta({
8157
8510
  description: "Per-category routing overlays for this profile, keyed by category name, using the same routing-only field set as every profile entry.",
8158
- examples: [{ review: { model: "anthropic/claude-opus-5" } }]
8511
+ examples: [{ review: { model: "anthropic/claude-opus-5-5" } }]
8159
8512
  })
8160
8513
  }).strict().meta({
8161
8514
  description: "A named routing-only overlay bundle. Entries under agents/categories have the same shape as the top-level agents/categories overlays, restricted to routing fields.",
8162
8515
  examples: [
8163
8516
  {
8164
- agents: { fixer: { model: "anthropic/claude-opus-5" } },
8517
+ agents: { fixer: { model: "anthropic/claude-opus-5-5" } },
8165
8518
  categories: { review: { pi: { thinking: "high" } } }
8166
8519
  }
8167
8520
  ]
@@ -8260,7 +8613,7 @@ function createSystematicConfigSchema(opts) {
8260
8613
  }),
8261
8614
  categories: record(string(), CategoryOverlaySchema).default({}).meta({
8262
8615
  description: "Per-category configuration overlays keyed by category name. Trust-protected fields (model, variant, skills, permission, opencode, pi) are only valid in user config or OPENCODE_CONFIG_DIR config \u2014 a project config setting them has that field ignored with a warning; other fields in the same overlay still apply.",
8263
- examples: [{ review: { model: "anthropic/claude-opus-5" } }, {}]
8616
+ examples: [{ review: { model: "anthropic/claude-opus-5-5" } }, {}]
8264
8617
  }),
8265
8618
  profiles: record(string(), createProfileBundleSchema(agentNames, qualifiedAgentIds)).default({}).meta({
8266
8619
  description: "Named routing-only overlay bundles, selectable by name via the profile field. Valid in user config and OPENCODE_CONFIG_DIR config. A project config may always select a profile, but may only define this field when the user sets allow_project_profiles; a project-defined bundle is advisory and fills only routing the user has not set.",
@@ -8676,1833 +9029,2065 @@ function collectWrittenLegacyPiSubagentsThinkingWarnings(piSubagentsOverlays) {
8676
9029
  return warnings;
8677
9030
  }
8678
9031
 
8679
- // src/lib/config.ts
8680
- var CONFIG_AUTHORITY_FIELD_PATHS = [
8681
- "bootstrap.enabled",
8682
- "bootstrap.file",
8683
- "skills_as_commands"
8684
- ];
8685
- var DEFAULT_CONFIG = {
8686
- disabled_skills: [],
8687
- disabled_agents: [],
8688
- disabled_commands: [],
8689
- bootstrap: {
8690
- enabled: true
9032
+ // src/lib/search-corpus.ts
9033
+ import fs3 from "fs";
9034
+ import path2 from "path";
9035
+ var MAX_FILE_BYTES = 256 * 1024;
9036
+ var MAX_FILES = 2000;
9037
+ var MAX_DEPTH = 6;
9038
+ var MAX_TOTAL_BYTES = 16 * 1024 * 1024;
9039
+ var MAX_DISCOVERED_FILES = MAX_FILES * 4;
9040
+ var MAX_LISTED_ENTRIES = MAX_DISCOVERED_FILES * 4;
9041
+ var MAX_WARNING_LENGTH = 200;
9042
+ var DEFAULT_EXTENSIONS = [".md"];
9043
+ var KIND_TABLE = {
9044
+ solution: {
9045
+ dir: "docs/solutions",
9046
+ excludedFiles: ["readme.md", "critical-patterns.md"],
9047
+ excludedDirs: ["_archived"],
9048
+ lifecycle: true
8691
9049
  },
8692
- agents: {},
8693
- categories: {},
8694
- pi_subagents: { categories: {}, agents: {} },
8695
- skills_as_commands: true,
8696
- allow_project_profiles: false
8697
- };
8698
- var PROTECTED_OVERLAY_FIELD_PATHS = {
8699
- agents: {
8700
- model: "agents.*.model",
8701
- permission: "agents.*.permission",
8702
- skills: "agents.*.skills",
8703
- variant: "agents.*.variant",
8704
- opencode: "agents.*.opencode",
8705
- pi: "agents.*.pi"
9050
+ plan: {
9051
+ dir: "docs/plans",
9052
+ excludedFiles: ["readme.md"],
9053
+ excludedDirs: ["_archived"],
9054
+ lifecycle: true
8706
9055
  },
8707
- categories: {
8708
- model: "categories.*.model",
8709
- permission: "categories.*.permission",
8710
- skills: "categories.*.skills",
8711
- variant: "categories.*.variant",
8712
- opencode: "categories.*.opencode",
8713
- pi: "categories.*.pi"
9056
+ brainstorm: {
9057
+ dir: "docs/brainstorms",
9058
+ excludedFiles: ["readme.md"],
9059
+ excludedDirs: ["_archived"],
9060
+ lifecycle: true
9061
+ },
9062
+ ideation: {
9063
+ dir: "docs/ideation",
9064
+ excludedFiles: ["readme.md"],
9065
+ excludedDirs: ["_archived"],
9066
+ lifecycle: true
8714
9067
  }
8715
9068
  };
8716
- var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set(["allow_project_profiles"]);
8717
- var PROJECT_PROTECTED_SEARCH_FIELDS = [
8718
- ["enabled", "search.enabled"],
8719
- ["allow_project_sources", "search.allow_project_sources"]
8720
- ];
8721
- var MAX_DIAGNOSTIC_TEXT = 200;
8722
- var MAX_STRIP_WARNINGS = 20;
8723
- var DIAGNOSTIC_ELLIPSIS = "\u2026";
8724
- function sanitizeDiagnosticText(input) {
8725
- const budget = MAX_DIAGNOSTIC_TEXT - DIAGNOSTIC_ELLIPSIS.length;
8726
- let rendered = "";
8727
- let truncated = false;
8728
- for (const char of input) {
8729
- if (rendered.length >= budget) {
8730
- truncated = true;
8731
- break;
8732
- }
8733
- const code = char.codePointAt(0) ?? 0;
8734
- const isControl = code <= 31 || code === 127 || code >= 128 && code <= 159 || code === 8232 || code === 8233;
8735
- const piece = isControl ? `\\u${code.toString(16).padStart(4, "0")}` : char;
8736
- if (rendered.length + piece.length > budget) {
8737
- truncated = true;
8738
- break;
8739
- }
8740
- rendered += piece;
8741
- }
8742
- return truncated ? `${rendered}${DIAGNOSTIC_ELLIPSIS}` : rendered;
9069
+ function isDocumentKind(value) {
9070
+ return typeof value === "string" && Object.hasOwn(KIND_TABLE, value);
8743
9071
  }
8744
- function createBoundedStripWarningSink(warningSink) {
8745
- let emitted = 0;
8746
- let suppressed = 0;
8747
- return {
8748
- sink(message) {
8749
- if (emitted < MAX_STRIP_WARNINGS) {
8750
- emitted++;
8751
- warningSink(message);
8752
- } else {
8753
- suppressed++;
8754
- }
8755
- },
8756
- suppressedCount() {
8757
- return suppressed;
8758
- }
8759
- };
9072
+ var ANSI_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
9073
+ var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
9074
+ function cleanForWarning(text) {
9075
+ const clean = text.replace(ANSI_SEQUENCE, "").replace(CONTROL_CHARACTERS, "");
9076
+ return clean.length > MAX_WARNING_LENGTH ? `${clean.slice(0, MAX_WARNING_LENGTH)}\u2026` : clean;
8760
9077
  }
8761
- var CURRENT_SKILL_NAMES_SET = new Set(BUNDLED_SKILL_NAMES);
8762
- var CURRENT_AGENT_NAMES_SET = new Set([
8763
- ...BUNDLED_AGENT_NAMES,
8764
- ...BUNDLED_AGENT_QUALIFIED_IDS
8765
- ]);
8766
- var REMOVED_AGENT_CATEGORIES_SET = new Set(REMOVED_BUNDLED_AGENT_CATEGORIES);
8767
- var BUNDLED_AGENT_CATEGORY_BY_KEY = new Map(BUNDLED_AGENT_QUALIFIED_IDS.map((qualifiedId) => {
8768
- const separatorIndex = qualifiedId.indexOf("/");
8769
- return [
8770
- qualifiedId.slice(separatorIndex + 1),
8771
- qualifiedId.slice(0, separatorIndex)
8772
- ];
8773
- }));
8774
- var BUNDLED_AGENT_KEYS_BY_CATEGORY = (() => {
8775
- const byCategory = new Map;
8776
- for (const [agentKey, category] of BUNDLED_AGENT_CATEGORY_BY_KEY) {
8777
- const existing = byCategory.get(category) ?? [];
8778
- existing.push(agentKey);
8779
- byCategory.set(category, existing);
8780
- }
8781
- return byCategory;
8782
- })();
8783
- function computeDroppedNames(names, allowedSet) {
8784
- return names.filter((n) => !allowedSet.has(n));
9078
+ function compareCodeUnits(a, b) {
9079
+ if (a < b)
9080
+ return -1;
9081
+ return a > b ? 1 : 0;
8785
9082
  }
8786
- var MIGRATION_DOCS_URL = "https://fro.bot/systematic/guides/v3-migration/";
8787
- function warnDroppedNames(dropped, field, warned, removalVersion, warningSink = console.warn) {
8788
- for (const name of dropped) {
8789
- if (warned.has(name))
8790
- continue;
8791
- warned.add(name);
8792
- const displayName = field === "categories" ? `${field}.${name}` : name;
8793
- const removalNote = removalVersion ? ` It was removed in ${removalVersion}.` : "";
8794
- warningSink(`[systematic] "${displayName}" in \`${field}\` is no longer a bundled name and will be ignored.${removalNote} Remove it from your config to silence this warning. See ${MIGRATION_DOCS_URL} for migration guidance.`);
9083
+ function safeLstat(target) {
9084
+ try {
9085
+ return fs3.lstatSync(target, { throwIfNoEntry: false }) ?? null;
9086
+ } catch {
9087
+ return null;
8795
9088
  }
8796
9089
  }
8797
- function isErrorWithCode(error) {
8798
- return error instanceof Error && "code" in error;
9090
+ function safeRealpath(target) {
9091
+ try {
9092
+ return fs3.realpathSync(target);
9093
+ } catch {
9094
+ return null;
9095
+ }
8799
9096
  }
8800
- function loadJsoncFile(filePath) {
8801
- let content;
9097
+ function isAbsence(error) {
9098
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
9099
+ return code === "ENOENT" || code === "ENOTDIR";
9100
+ }
9101
+ function probeRealpath(target) {
8802
9102
  try {
8803
- content = fs3.readFileSync(filePath, "utf-8");
9103
+ return { kind: "ok", value: fs3.realpathSync(target) };
8804
9104
  } catch (error) {
8805
- if (isErrorWithCode(error) && error.code === "ENOENT")
8806
- return null;
8807
- throw new Error(`Invalid Systematic config in ${filePath}: unable to read file`, { cause: error });
8808
- }
8809
- const errors = [];
8810
- const parsed = parse(content, errors);
8811
- if (errors.length > 0) {
8812
- const error = errors[0];
8813
- const message = error ? `${printParseErrorCode(error.error)} at offset ${error.offset}` : "unknown parse error";
8814
- throw new Error(`Invalid Systematic config in ${filePath}: JSONC parse error: ${message}`);
8815
- }
8816
- if (!isRecord3(parsed)) {
8817
- throw new Error(`Invalid Systematic config in ${filePath}: root must be an object`);
9105
+ return { kind: isAbsence(error) ? "absent" : "failed" };
8818
9106
  }
8819
- return parsed;
8820
9107
  }
8821
- var TYPED_VALIDATION_DOCS_URL = "https://fro.bot/systematic/reference/configuration#typed-validation";
8822
- var TYPED_KEY_FIELDS = new Set([
8823
- "agents",
8824
- "disabled_agents",
8825
- "disabled_skills"
8826
- ]);
8827
- function formatUnrecognizedKeysHint(badKeys, topField) {
8828
- if (badKeys.length === 0) {
8829
- throw new Error("formatUnrecognizedKeysHint requires non-empty keys");
9108
+ function probeLstat(target) {
9109
+ try {
9110
+ const stat = fs3.lstatSync(target, { throwIfNoEntry: false });
9111
+ return stat === undefined ? { kind: "absent" } : { kind: "ok", value: stat };
9112
+ } catch (error) {
9113
+ return { kind: isAbsence(error) ? "absent" : "failed" };
8830
9114
  }
8831
- if (badKeys.length === 1) {
8832
- return `Unrecognized key '${badKeys[0]}' in \`${topField}\`. This must be a bundled name. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
9115
+ }
9116
+ function safeReaddir(target) {
9117
+ try {
9118
+ return fs3.readdirSync(target);
9119
+ } catch {
9120
+ return null;
8833
9121
  }
8834
- const joined = badKeys.map((k) => `'${k}'`).join(", ");
8835
- return `Unrecognized keys ${joined} in \`${topField}\`. These must be bundled names. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
8836
9122
  }
8837
- function formatProfileAgentUnrecognizedKeysHint(badKeys, profileName) {
8838
- const prefixed = badKeys.map((k) => `profiles.${profileName}.agents.${k}`);
8839
- const isAre = prefixed.length === 1 ? "is not a bundled agent" : "are not bundled agents";
8840
- return `${prefixed.join(", ")} ${isAre}. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
9123
+ function newEntryBudget(limit = MAX_LISTED_ENTRIES) {
9124
+ return { remaining: limit, exhausted: false };
8841
9125
  }
8842
- function enrichProfileAgentUnrecognizedKeysIssue(issue) {
8843
- if (issue.code !== "unrecognized_keys" || issue.path[0] !== "profiles" || issue.path[2] !== "agents" || typeof issue.path[1] !== "string") {
9126
+ function listDirectoryWithin(target, budget) {
9127
+ if (budget.remaining <= 0) {
9128
+ budget.exhausted = true;
9129
+ return { names: [], truncated: true };
9130
+ }
9131
+ const listing = listDirectoryBounded(target, budget.remaining);
9132
+ if (listing === null)
8844
9133
  return null;
9134
+ budget.remaining -= listing.names.length;
9135
+ if (listing.truncated) {
9136
+ budget.remaining = 0;
9137
+ budget.exhausted = true;
8845
9138
  }
8846
- const hint = formatProfileAgentUnrecognizedKeysHint(issue.keys, issue.path[1]);
8847
- return { ...issue, message: hint };
9139
+ return listing;
8848
9140
  }
8849
- function enrichTopLevelTypedKeyIssue(issue, rawInput) {
8850
- const topField = issue.path[0];
8851
- if (typeof topField !== "string" || !TYPED_KEY_FIELDS.has(topField)) {
9141
+ function listDirectoryBounded(target, limit) {
9142
+ let directory;
9143
+ try {
9144
+ directory = fs3.opendirSync(target);
9145
+ } catch {
8852
9146
  return null;
8853
9147
  }
8854
- if (issue.code === "unrecognized_keys") {
8855
- const hint = formatUnrecognizedKeysHint(issue.keys, topField);
8856
- return { ...issue, message: hint };
8857
- }
8858
- if (issue.code === "invalid_value" && (topField === "disabled_agents" || topField === "disabled_skills")) {
8859
- const badValue = resolveValueAtPath(rawInput, issue.path);
8860
- const kind = topField === "disabled_agents" ? "agent" : "skill";
8861
- const hint = typeof badValue === "string" ? `Unrecognized ${kind} name '${badValue}' in \`${topField}\`. This must be a bundled name. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.` : `Invalid value in \`${topField}\`. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
8862
- return { ...issue, message: hint };
9148
+ const names = [];
9149
+ try {
9150
+ while (true) {
9151
+ const entry = directory.readSync();
9152
+ if (entry === null)
9153
+ return { names, truncated: false };
9154
+ if (names.length >= limit)
9155
+ return { names, truncated: true };
9156
+ names.push(entry.name);
9157
+ }
9158
+ } catch {
9159
+ return null;
9160
+ } finally {
9161
+ try {
9162
+ directory.closeSync();
9163
+ } catch {}
8863
9164
  }
8864
- return null;
8865
9165
  }
8866
- function enrichUnrecognizedKeyIssues(issues, rawInput) {
8867
- return issues.map((issue) => enrichProfileAgentUnrecognizedKeysIssue(issue) ?? enrichTopLevelTypedKeyIssue(issue, rawInput) ?? issue);
8868
- }
8869
- function resolveValueAtPath(root, path) {
8870
- let current = root;
8871
- for (const segment of path) {
8872
- if (typeof segment === "symbol") {
8873
- return;
8874
- }
8875
- if (typeof segment === "number") {
8876
- if (!Array.isArray(current))
8877
- return;
8878
- current = current[segment];
8879
- } else {
8880
- if (!isRecord3(current))
8881
- return;
8882
- current = current[segment];
9166
+ function walkToGitRoot(startDir) {
9167
+ const resolved = path2.resolve(startDir);
9168
+ const start = safeRealpath(resolved) ?? resolved;
9169
+ let current = start;
9170
+ while (true) {
9171
+ try {
9172
+ if (fs3.lstatSync(path2.join(current, ".git"), { throwIfNoEntry: false })) {
9173
+ return { gitRoot: current, start };
9174
+ }
9175
+ } catch {
9176
+ return { gitRoot: null, start };
8883
9177
  }
9178
+ const parent = path2.dirname(current);
9179
+ if (parent === current)
9180
+ return { gitRoot: null, start };
9181
+ current = parent;
8884
9182
  }
8885
- return current;
8886
9183
  }
8887
- function throwTopLevelConfigSchemaError(filePath, trust, rawIssues, rawInput) {
8888
- const issues = enrichUnrecognizedKeyIssues(rawIssues, rawInput);
8889
- if (issues.length === 0) {
8890
- throw Object.assign(new Error(`Invalid Systematic config in ${filePath}: schema validation failed`), { _tag: "ConfigSchemaError", filePath, trust, issues });
8891
- }
8892
- const formatIssue = (issue) => {
8893
- const fieldPath = issue.code === "unrecognized_keys" ? null : issue.path.join(".");
8894
- return fieldPath ? `${fieldPath} ${issue.message}` : issue.message;
8895
- };
8896
- const formatted = issues.map(formatIssue);
8897
- const message = formatted.length === 1 ? `Invalid Systematic config in ${filePath}: ${formatted[0]}` : `Invalid Systematic config in ${filePath}:
8898
- ${formatted.map((entry) => ` - ${entry}`).join(`
8899
- `)}`;
8900
- throw Object.assign(new Error(message), {
8901
- _tag: "ConfigSchemaError",
8902
- filePath,
8903
- trust,
8904
- issues
8905
- });
9184
+ function resolveSearchRoot(startDir) {
9185
+ const { gitRoot, start } = walkToGitRoot(startDir);
9186
+ return gitRoot ?? start;
8906
9187
  }
8907
- function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProjectProfiles) {
8908
- try {
8909
- const rawConfig = loadJsoncFile(filePath);
8910
- if (!rawConfig) {
8911
- return {
8912
- metadata: { kind: trust, presence: "absent" },
8913
- source: null
8914
- };
8915
- }
8916
- const protectedFields = collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles);
8917
- const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig, allowProjectProfiles) : rawConfig;
8918
- const config = trust === "project" ? stripProjectSecurityOverlayFields(topLevelStripped, filePath, warningSink) : topLevelStripped;
8919
- const { config: configWithoutSearch, search } = splitSearchBlock(config, filePath, trust, warningSink);
8920
- const result = SystematicConfigSchema.safeParse(configWithoutSearch);
8921
- if (!result.success) {
8922
- throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, configWithoutSearch);
9188
+ function lookupSearchRoot(startDir) {
9189
+ const { gitRoot } = walkToGitRoot(startDir);
9190
+ return gitRoot === null ? { root: startDir, foundGit: false } : { root: gitRoot, foundGit: true };
9191
+ }
9192
+ function isInside(root, candidate) {
9193
+ const relative = path2.relative(root, candidate);
9194
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative);
9195
+ }
9196
+ function symlinkedComponent(container, target) {
9197
+ if (!isInside(container, target))
9198
+ return;
9199
+ const segments = path2.relative(container, target).split(path2.sep);
9200
+ let current = container;
9201
+ for (const [index, segment] of segments.entries()) {
9202
+ current = path2.join(current, segment);
9203
+ const stat = safeLstat(current);
9204
+ if (stat === null)
9205
+ return;
9206
+ if (stat.isSymbolicLink()) {
9207
+ return index === segments.length - 1 ? "root" : "ancestor";
8923
9208
  }
8924
- return {
8925
- metadata: { kind: trust, presence: "present" },
8926
- source: {
8927
- kind: "file",
8928
- canonicalPath: resolveConfigSourcePath(filePath),
8929
- config: configWithoutSearch,
8930
- path: filePath,
8931
- protectedFields,
8932
- removedKeys: REMOVED_CONFIG_KEYS.filter((key) => Object.hasOwn(rawConfig, key)),
8933
- ...search && { search },
8934
- trust
8935
- }
8936
- };
8937
- } catch (error) {
8938
- if (invalidSource === "throw")
8939
- throw error;
8940
- return {
8941
- metadata: {
8942
- errorCode: classifyConfigSourceError(error),
8943
- kind: trust,
8944
- presence: "invalid"
8945
- },
8946
- source: null
8947
- };
8948
9209
  }
9210
+ return;
8949
9211
  }
8950
- function splitSearchBlock(config, filePath, trust, warningSink) {
8951
- if (!Object.hasOwn(config, "search"))
8952
- return { config, search: undefined };
8953
- const { search: rawSearch, ...rest } = config;
8954
- const validation = validateSearchConfig(rawSearch, trust === "project" ? "project" : "user", filePath);
8955
- for (const message of validation.warnings)
8956
- warningSink(message);
8957
- return {
8958
- config: rest,
8959
- search: trust === "project" ? undefined : { settings: validation.settings, unreadable: validation.unreadable }
8960
- };
9212
+ var PROJECT_ROOT_REJECTION_REASONS = {
9213
+ root: "a project root is a symlink",
9214
+ ancestor: "a project root passes through a symlink",
9215
+ outside: "a project root resolves outside the project root"
9216
+ };
9217
+ function rejectedProjectRoot(checkoutRoot, root) {
9218
+ const symlinked = symlinkedComponent(checkoutRoot, root);
9219
+ if (symlinked !== undefined)
9220
+ return symlinked;
9221
+ const container = probeRealpath(checkoutRoot);
9222
+ const directory = probeRealpath(root);
9223
+ if (container.kind !== "ok" || directory.kind !== "ok")
9224
+ return;
9225
+ return isInside(container.value, directory.value) ? undefined : "outside";
8961
9226
  }
8962
- function classifyConfigSourceError(error) {
8963
- if (isConfigSchemaError(error))
8964
- return "schema-invalid";
8965
- if (!(error instanceof Error))
8966
- return "source-invalid";
8967
- if (error.message.includes("JSONC parse error"))
8968
- return "parse-failed";
8969
- if (error.message.includes("unable to read file"))
8970
- return "read-failed";
8971
- return "source-invalid";
9227
+ function classifyEntry(spec, name, stat) {
9228
+ if (stat === null || stat.isSymbolicLink())
9229
+ return "ignored";
9230
+ if (stat.isDirectory()) {
9231
+ return spec.excludedDirs.includes(name) ? "ignored" : "directory";
9232
+ }
9233
+ if (!stat.isFile())
9234
+ return "ignored";
9235
+ const lower = name.toLowerCase();
9236
+ const extensions = spec.extensions ?? DEFAULT_EXTENSIONS;
9237
+ const indexable = extensions.some((extension) => lower.endsWith(extension)) && !spec.excludedFiles.includes(lower);
9238
+ return indexable ? "file" : "ignored";
8972
9239
  }
8973
- function isConfigSchemaError(error) {
8974
- return isRecord3(error) && error._tag === "ConfigSchemaError";
9240
+ function wholeListing(directory) {
9241
+ const names = safeReaddir(directory);
9242
+ return names === null ? null : { names, truncated: false };
8975
9243
  }
8976
- function resolveConfigSourcePath(filePath) {
8977
- try {
8978
- return fs3.realpathSync(filePath);
8979
- } catch {
8980
- return path2.resolve(filePath);
9244
+ function listWalkedDirectory(budget, label, directory, prefix, warnings) {
9245
+ const listing = budget === undefined ? wholeListing(directory) : listDirectoryWithin(directory, budget);
9246
+ if (listing === null) {
9247
+ if (prefix !== "") {
9248
+ const shown = `${label}/${prefix.slice(0, -1)}`;
9249
+ warnings.push(cleanForWarning(`could not read directory ${shown}`));
9250
+ }
9251
+ return null;
8981
9252
  }
9253
+ return listing.names;
8982
9254
  }
8983
- function emitTopLevelProtectedFieldWarning(projectSource, fieldPath, messageTemplate, sink) {
8984
- if (!projectSource?.protectedFields.some((field) => field.fieldPath === fieldPath)) {
9255
+ function addCandidate(found, candidate) {
9256
+ if (found.candidates.length >= MAX_DISCOVERED_FILES) {
9257
+ found.truncated = true;
8985
9258
  return;
8986
9259
  }
8987
- const safePath = sanitizeDiagnosticText(projectSource.path);
8988
- sink(`[systematic] ${messageTemplate.replace("%PATH%", safePath)}`);
9260
+ found.candidates.push(candidate);
8989
9261
  }
8990
- function emitProjectSearchProtectedWarnings(projectSource, sink) {
8991
- for (const [, fieldPath] of PROJECT_PROTECTED_SEARCH_FIELDS) {
8992
- emitTopLevelProtectedFieldWarning(projectSource, fieldPath, `\`${fieldPath}\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. A project config may set \`search.sources\` only.`, sink);
9262
+ function discoverFiles(spec, label, directory, prefix, depth, found, warnings) {
9263
+ const names = listWalkedDirectory(found.budget, label, directory, prefix, warnings);
9264
+ if (names === null) {
9265
+ if (depth === 0)
9266
+ found.rootUnreadable = true;
9267
+ return;
9268
+ }
9269
+ names.sort(compareCodeUnits);
9270
+ for (const name of names) {
9271
+ if (found.truncated)
9272
+ return;
9273
+ if (found.isExcluded?.(`${prefix}${name}`) === true)
9274
+ continue;
9275
+ const absolute = path2.join(directory, name);
9276
+ const stat = safeLstat(absolute);
9277
+ const entryKind = classifyEntry(spec, name, stat);
9278
+ if (entryKind === "directory" && depth + 1 <= MAX_DEPTH) {
9279
+ const child = `${prefix}${name}/`;
9280
+ discoverFiles(spec, label, absolute, child, depth + 1, found, warnings);
9281
+ } else if (entryKind === "file" && stat !== null) {
9282
+ addCandidate(found, {
9283
+ relative: `${prefix}${name}`,
9284
+ absolute,
9285
+ size: stat.size
9286
+ });
9287
+ }
8993
9288
  }
8994
9289
  }
8995
- function collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles) {
8996
- if (trust !== "project")
8997
- return [];
8998
- return [
8999
- ...!allowProjectProfiles && Object.hasOwn(rawConfig, "profiles") ? [
9000
- {
9001
- fieldPath: "profiles",
9002
- outcome: "blocked",
9003
- sourceKind: "project"
9004
- }
9005
- ] : [],
9006
- ...Object.hasOwn(rawConfig, "allow_project_profiles") ? [
9007
- {
9008
- fieldPath: "allow_project_profiles",
9009
- outcome: "blocked",
9010
- sourceKind: "project"
9011
- }
9012
- ] : [],
9013
- ...collectSearchProtectedFields(rawConfig.search),
9014
- ...collectOverlayProtectedFields(rawConfig.agents, "agents"),
9015
- ...collectOverlayProtectedFields(rawConfig.categories, "categories")
9016
- ];
9017
- }
9018
- function collectSearchProtectedFields(search) {
9019
- if (!isRecord3(search))
9020
- return [];
9021
- return PROJECT_PROTECTED_SEARCH_FIELDS.filter(([key]) => Object.hasOwn(search, key)).map(([, fieldPath]) => ({
9022
- fieldPath,
9023
- outcome: "blocked",
9024
- sourceKind: "project"
9025
- }));
9026
- }
9027
- function collectOverlayProtectedFields(overlayMap, mapKey) {
9028
- if (!isRecord3(overlayMap))
9029
- return [];
9030
- return Object.values(overlayMap).flatMap((value) => isRecord3(value) ? collectProtectedOverlayValue(value, mapKey) : []);
9031
- }
9032
- function collectProtectedOverlayValue(value, mapKey) {
9033
- return [...SECURITY_OVERLAY_FIELDS].filter((field) => Object.hasOwn(value, field)).map((field) => ({
9034
- fieldPath: PROTECTED_OVERLAY_FIELD_PATHS[mapKey][field],
9035
- outcome: "blocked",
9036
- sourceKind: "project"
9037
- }));
9290
+ function narrowString(value) {
9291
+ return typeof value === "string" ? value : undefined;
9038
9292
  }
9039
- function stripProjectProtectedFields(rawConfig, allowProjectProfiles) {
9040
- const config = { ...rawConfig };
9041
- for (const field of PROJECT_ALWAYS_PROTECTED_FIELDS) {
9042
- delete config[field];
9043
- }
9044
- if (!allowProjectProfiles) {
9045
- delete config.profiles;
9046
- }
9047
- return config;
9293
+ function narrowNonEmptyString(value) {
9294
+ const trimmed = narrowString(value)?.trim();
9295
+ return trimmed ? trimmed : undefined;
9048
9296
  }
9049
- function stripProjectSecurityOverlayFields(rawConfig, filePath, warningSink) {
9050
- const agents = stripSecurityOverlayEntries(rawConfig.agents, "agents", filePath, warningSink);
9051
- const categories = stripSecurityOverlayEntries(rawConfig.categories, "categories", filePath, warningSink);
9052
- if (agents === rawConfig.agents && categories === rawConfig.categories) {
9053
- return rawConfig;
9297
+ function narrowStringList(value) {
9298
+ const items = Array.isArray(value) ? value : [value];
9299
+ const result = [];
9300
+ for (const item of items) {
9301
+ if (typeof item === "string")
9302
+ result.push(item);
9303
+ else if (typeof item === "number" && Number.isFinite(item))
9304
+ result.push(String(item));
9054
9305
  }
9055
- const result = { ...rawConfig };
9056
- if (agents !== rawConfig.agents)
9057
- result.agents = agents;
9058
- if (categories !== rawConfig.categories)
9059
- result.categories = categories;
9060
9306
  return result;
9061
9307
  }
9062
- function stripSecurityOverlayEntries(overlayMap, mapKey, filePath, warningSink) {
9063
- if (!isRecord3(overlayMap))
9064
- return overlayMap;
9065
- let changed = false;
9066
- const result = {};
9067
- for (const [key, value] of Object.entries(overlayMap)) {
9068
- if (!isRecord3(value)) {
9069
- result[key] = value;
9070
- continue;
9071
- }
9072
- const stripped = stripProjectSecurityOverlay(filePath, `${mapKey}.${key}`, value, warningSink);
9073
- if (stripped === value) {
9074
- result[key] = stripped;
9075
- continue;
9076
- }
9077
- changed = true;
9078
- if (Object.keys(stripped).length === 0)
9079
- continue;
9080
- result[key] = stripped;
9081
- }
9082
- return changed ? result : overlayMap;
9083
- }
9084
- function isRecord3(value) {
9085
- return typeof value === "object" && value !== null && !Array.isArray(value);
9086
- }
9087
- function mergeArraysUnique(arr1, arr2) {
9088
- const set = new Set;
9089
- if (arr1)
9090
- for (const item of arr1)
9091
- set.add(item);
9092
- if (arr2)
9093
- for (const item of arr2)
9094
- set.add(item);
9095
- return Array.from(set);
9308
+ function narrowSupersededBy(value) {
9309
+ if (value === undefined || value === null)
9310
+ return { state: "none" };
9311
+ if (typeof value === "string")
9312
+ return { state: "value", value };
9313
+ return { state: "invalid" };
9096
9314
  }
9097
- var PROFILE_DOCS_URL = "https://fro.bot/systematic/reference/configuration#profiles";
9098
- var NO_PROFILE_SELECTION = {
9099
- activeProfile: null,
9100
- profileSelectorSource: null,
9101
- profileFallback: null,
9102
- bundle: null,
9103
- bundleSource: null
9104
- };
9105
- function resolveProfileSelector(input) {
9106
- const envProfile = process.env.SYSTEMATIC_PROFILE?.trim();
9107
- if (envProfile)
9108
- return { value: envProfile, source: "environment" };
9109
- const candidates = [
9110
- ["custom", input.customConfig?.profile],
9111
- ["project", input.projectConfig?.profile],
9112
- ["user", input.userConfig?.profile]
9113
- ];
9114
- for (const [source, value] of candidates) {
9115
- if (value !== undefined)
9116
- return { value, source };
9315
+ function parseMarkdownFrontmatter(content) {
9316
+ let text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
9317
+ if (!text.endsWith(`
9318
+ `))
9319
+ text += `
9320
+ `;
9321
+ const parsed = parseFrontmatter(text);
9322
+ if (parsed.parseError)
9323
+ return { ok: false, reason: "invalid frontmatter" };
9324
+ if (parsed.hadFrontmatter && !isRecord(parsed.data)) {
9325
+ return { ok: false, reason: "frontmatter is not a mapping" };
9117
9326
  }
9118
- return null;
9327
+ return {
9328
+ ok: true,
9329
+ data: isRecord(parsed.data) ? parsed.data : {},
9330
+ body: parsed.body
9331
+ };
9119
9332
  }
9120
- function lookupProfileBundle(input, name) {
9121
- if (input.customSource) {
9122
- const bundle = input.customSource.config.profiles?.[name];
9123
- if (bundle !== undefined) {
9124
- return { bundle, definingSource: input.customSource };
9333
+ function parseCorpusDocument(kind, relativePath, content) {
9334
+ const parsed = parseMarkdownFrontmatter(content);
9335
+ if (!parsed.ok)
9336
+ return parsed;
9337
+ const data = parsed.data;
9338
+ const fileName = relativePath.slice(relativePath.lastIndexOf("/") + 1);
9339
+ const title = narrowNonEmptyString(data.title) ?? narrowNonEmptyString(data.topic) ?? fileName.replace(/\.md$/i, "");
9340
+ return {
9341
+ ok: true,
9342
+ document: {
9343
+ path: relativePath,
9344
+ kind,
9345
+ title,
9346
+ tags: narrowStringList(data.tags),
9347
+ module: narrowString(data.module),
9348
+ component: narrowString(data.component),
9349
+ problemType: narrowString(data.problem_type),
9350
+ symptoms: narrowStringList(data.symptoms),
9351
+ appliesWhen: narrowStringList(data.applies_when),
9352
+ status: narrowString(data.status),
9353
+ supersededBy: narrowSupersededBy(data.superseded_by),
9354
+ staleReason: narrowString(data.stale_reason),
9355
+ body: parsed.body
9125
9356
  }
9357
+ };
9358
+ }
9359
+ function discoverSourceFiles(options, warnings) {
9360
+ const { directory, containedIn, walk, label, entryBudget, isExcluded } = options;
9361
+ const directoryProbe = probeRealpath(directory);
9362
+ const containerProbe = containedIn === undefined ? undefined : probeRealpath(containedIn);
9363
+ if (containerProbe?.kind === "failed" || directoryProbe.kind === "failed") {
9364
+ warnings.push(`could not read ${label}; not loaded`);
9365
+ return { state: "unreadable" };
9126
9366
  }
9127
- if (input.userSource) {
9128
- const bundle = input.userSource.config.profiles?.[name];
9129
- if (bundle !== undefined) {
9130
- return { bundle, definingSource: input.userSource };
9131
- }
9367
+ if (containerProbe !== undefined && containerProbe.kind !== "ok" || directoryProbe.kind !== "ok") {
9368
+ return { state: "missing" };
9132
9369
  }
9133
- if (input.allowProjectProfiles && input.projectSource) {
9134
- const bundle = input.projectSource.config.profiles?.[name];
9135
- if (bundle !== undefined) {
9136
- return { bundle, definingSource: input.projectSource };
9137
- }
9370
+ const directoryReal = directoryProbe.value;
9371
+ const statProbe = probeLstat(directoryReal);
9372
+ if (statProbe.kind === "failed") {
9373
+ warnings.push(`could not read ${label}; not loaded`);
9374
+ return { state: "unreadable" };
9138
9375
  }
9139
- return;
9140
- }
9141
- function trustedDefaultProfileName(input) {
9142
- const userDefault = input.userConfig?.profile;
9143
- return typeof userDefault === "string" ? userDefault : undefined;
9144
- }
9145
- function selectorSourceLabel(source) {
9146
- return source === "environment" ? "SYSTEMATIC_PROFILE" : `${source} config`;
9147
- }
9148
- function resolveActiveProfile(input) {
9149
- const selection = resolveProfileSelector(input);
9150
- if (selection === null)
9151
- return NO_PROFILE_SELECTION;
9152
- if (selection.value === null) {
9153
- return {
9154
- activeProfile: null,
9155
- profileSelectorSource: selection.source,
9156
- profileFallback: null,
9157
- bundle: null,
9158
- bundleSource: null
9159
- };
9376
+ if (statProbe.kind !== "ok" || !statProbe.value.isDirectory()) {
9377
+ return { state: "missing" };
9160
9378
  }
9161
- const requested = selection.value;
9162
- const requestedLookup = lookupProfileBundle(input, requested);
9163
- if (requestedLookup !== undefined) {
9164
- return {
9165
- activeProfile: requested,
9166
- profileSelectorSource: selection.source,
9167
- profileFallback: null,
9168
- bundle: requestedLookup.bundle,
9169
- bundleSource: requestedLookup.definingSource
9170
- };
9379
+ if (containerProbe !== undefined && !isInside(containerProbe.value, directoryReal)) {
9380
+ warnings.push(`${label} resolves outside the project root; not loaded`);
9381
+ return { state: "outside" };
9171
9382
  }
9172
- const trustedDefault = trustedDefaultProfileName(input);
9173
- const fallbackLookup = trustedDefault !== undefined && trustedDefault !== requested ? lookupProfileBundle(input, trustedDefault) : undefined;
9174
- if (fallbackLookup !== undefined && trustedDefault !== undefined) {
9175
- input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}" (selected by ${selectorSourceLabel(selection.source)}) is not defined in \`profiles\`; falling back to your default profile "${sanitizeDiagnosticText(trustedDefault)}". See ${PROFILE_DOCS_URL} for how to define a profile.`);
9176
- return {
9177
- activeProfile: trustedDefault,
9178
- profileSelectorSource: selection.source,
9179
- profileFallback: { requested, usedDefault: trustedDefault },
9180
- bundle: fallbackLookup.bundle,
9181
- bundleSource: fallbackLookup.definingSource
9182
- };
9183
- }
9184
- const sourceNote = selection.source === "user" ? "" : ` (selected by ${selectorSourceLabel(selection.source)})`;
9185
- const alsoMissingNote = trustedDefault !== undefined && trustedDefault !== requested ? ` Your default profile "${sanitizeDiagnosticText(trustedDefault)}" is also not defined in \`profiles\`.` : trustedDefault === undefined ? " No default profile is configured (`profile` in your user config)." : "";
9186
- input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}"${sourceNote} is not defined in \`profiles\`; using base configuration (no profile).${alsoMissingNote} See ${PROFILE_DOCS_URL} for how to define a profile.`);
9187
- return {
9188
- activeProfile: null,
9189
- profileSelectorSource: selection.source,
9190
- profileFallback: { requested, usedDefault: null },
9191
- bundle: null,
9192
- bundleSource: null
9383
+ const found = {
9384
+ candidates: [],
9385
+ truncated: false,
9386
+ rootUnreadable: false,
9387
+ budget: entryBudget,
9388
+ isExcluded
9193
9389
  };
9194
- }
9195
- function loadConfig(projectDir, options) {
9196
- return loadConfigWithSources(projectDir, options).config;
9197
- }
9198
- function resolveAliasedCustomConfigPath(paths, includeProject) {
9199
- if (!includeProject || paths.customConfig === undefined)
9200
- return;
9201
- const sameFile = resolveConfigSourcePath(paths.projectConfig) === resolveConfigSourcePath(paths.customConfig);
9202
- return sameFile ? paths.customConfig : undefined;
9203
- }
9204
- function createAliasStripTracker(warningSink, aliasedCustomConfigPath) {
9205
- if (aliasedCustomConfigPath === undefined) {
9206
- return { sink: warningSink, buffered: [] };
9390
+ discoverFiles(walk, label, directoryReal, "", 0, found, warnings);
9391
+ if (found.rootUnreadable) {
9392
+ warnings.push(`could not read ${label}; not loaded`);
9393
+ return { state: "unreadable" };
9207
9394
  }
9208
- const buffered = [];
9209
9395
  return {
9210
- sink: (message) => {
9211
- buffered.push(message);
9212
- },
9213
- buffered
9396
+ state: "found",
9397
+ candidates: found.candidates.sort((a, b) => compareCodeUnits(a.relative, b.relative)),
9398
+ truncated: found.truncated
9214
9399
  };
9215
9400
  }
9216
- function isAliasNoticeEligible(input) {
9217
- return input.aliasedCustomConfigPath !== undefined && input.bufferedCount > 0;
9401
+ function readAllowance(used, maxFileBytes, sharedBytes) {
9402
+ const source = MAX_TOTAL_BYTES - used;
9403
+ const shared = sharedBytes === undefined ? Infinity : sharedBytes - used;
9404
+ const left = Math.max(Math.min(source, shared), 0);
9405
+ if (maxFileBytes <= left)
9406
+ return { limit: maxFileBytes, bound: "file" };
9407
+ return { limit: left, bound: shared < source ? "shared" : "source" };
9218
9408
  }
9219
- function emitAliasFailureDiagnostics(input) {
9220
- if (!isAliasNoticeEligible({
9221
- aliasedCustomConfigPath: input.aliasedCustomConfigPath,
9222
- bufferedCount: input.buffered.length
9223
- })) {
9224
- return;
9409
+ function readWithinBudgets(options, candidate, used) {
9410
+ const { maxFileBytes, sharedBytes } = options;
9411
+ const tooLarge = `larger than ${maxFileBytes} bytes`;
9412
+ if (candidate.size > maxFileBytes) {
9413
+ return { kind: "skip", reason: tooLarge, bytes: 0 };
9225
9414
  }
9226
- if (input.projectLoaded && input.customLoaded)
9227
- return;
9228
- for (const message of input.buffered)
9229
- input.warningSink(message);
9230
- }
9231
- function buildAliasSuccessNotice(input) {
9232
- if (!isAliasNoticeEligible({
9233
- aliasedCustomConfigPath: input.aliasedCustomConfigPath,
9234
- bufferedCount: input.bufferedCount
9235
- }) || !(input.projectLoaded && input.customLoaded) || input.aliasedCustomConfigPath === undefined) {
9236
- return;
9415
+ if (used + candidate.size > MAX_TOTAL_BYTES) {
9416
+ return { kind: "stop", bound: "source", bytes: 0 };
9237
9417
  }
9238
- const aliasedCustomConfigPath = input.aliasedCustomConfigPath;
9239
- const projectConfigPath = input.projectConfigPath;
9240
- const warningSink = input.warningSink;
9241
- return () => {
9242
- warningSink(`[systematic] project config (${sanitizeDiagnosticText(projectConfigPath)}) and custom config (${sanitizeDiagnosticText(aliasedCustomConfigPath)}) resolve to the same file; protected fields stripped from the project pass (security-overlay fields, \`profiles\`, \`allow_project_profiles\`) apply through the custom-trust pass instead.`);
9418
+ if (sharedBytes !== undefined && used + candidate.size > sharedBytes) {
9419
+ return { kind: "stop", bound: "shared", bytes: 0 };
9420
+ }
9421
+ const allowance = readAllowance(used, maxFileBytes, sharedBytes);
9422
+ const read = readBytesBounded(candidate.absolute, allowance.limit);
9423
+ if (read.kind === "too-large") {
9424
+ return allowance.bound === "file" ? { kind: "skip", reason: tooLarge, bytes: read.bytesRead } : { kind: "stop", bound: allowance.bound, bytes: allowance.limit };
9425
+ }
9426
+ if (read.kind !== "bytes") {
9427
+ return { kind: "skip", reason: "could not be read", bytes: 0 };
9428
+ }
9429
+ return {
9430
+ kind: "text",
9431
+ text: read.bytes.toString("utf8"),
9432
+ bytes: read.bytes.byteLength
9243
9433
  };
9244
9434
  }
9245
- var REMOVED_SETTINGS_DOCS_URL = "https://fro.bot/systematic/reference/configuration#removed-settings";
9246
- function warnRemovedKeys(sources, warningSink) {
9247
- const reported = new Set;
9248
- for (const source of sources) {
9249
- for (const key of source.removedKeys) {
9250
- const identity = `${source.canonicalPath}\x00${key}`;
9251
- if (reported.has(identity))
9252
- continue;
9253
- reported.add(identity);
9254
- warningSink(`[systematic] \`${key}\` in config (${sanitizeDiagnosticText(source.path)}) has been removed and is ignored. Delete it from that file to silence this warning. See ${REMOVED_SETTINGS_DOCS_URL} for details.`);
9435
+ function readCandidates(options, candidates, considered, warnings) {
9436
+ const items = [];
9437
+ let totalBytes = 0;
9438
+ for (let index = 0;index < considered; index++) {
9439
+ const candidate = candidates[index];
9440
+ if (candidate === undefined)
9441
+ break;
9442
+ const logicalPath = `${options.displayPrefix}/${candidate.relative}`;
9443
+ const display = cleanForWarning(logicalPath);
9444
+ const read = readWithinBudgets(options, candidate, totalBytes);
9445
+ totalBytes += read.bytes;
9446
+ if (read.kind === "stop") {
9447
+ return {
9448
+ items,
9449
+ bytesRead: totalBytes,
9450
+ budgetSkipped: considered - index,
9451
+ budgetBound: read.bound
9452
+ };
9255
9453
  }
9454
+ if (read.kind === "skip") {
9455
+ warnings.push(`skipped ${display}: ${read.reason}`);
9456
+ continue;
9457
+ }
9458
+ const parsed = options.parse(logicalPath, read.text);
9459
+ if (parsed.ok)
9460
+ items.push(parsed.value);
9461
+ else
9462
+ warnings.push(`skipped ${display}: ${parsed.reason}`);
9256
9463
  }
9257
- }
9258
- function loadUserAndCustomSources(paths, invalidSource, warningSink) {
9259
- const user = loadConfigSource(paths.userConfig, "user", invalidSource, warningSink, false);
9260
- const custom = paths.customConfig ? loadConfigSource(paths.customConfig, "custom", invalidSource, warningSink, false) : {
9261
- metadata: { kind: "custom", presence: "absent" },
9262
- source: null
9464
+ return {
9465
+ items,
9466
+ bytesRead: totalBytes,
9467
+ budgetSkipped: 0,
9468
+ budgetBound: "source"
9263
9469
  };
9264
- const allowProjectProfiles = custom.source?.config.allow_project_profiles ?? user.source?.config.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles;
9265
- return { user, custom, allowProjectProfiles };
9266
9470
  }
9267
- function buildOverlaySources(profileEntry, bundleSourceTrust, userSource, projectSource, customSource) {
9268
- const ordered = profileEntry !== null && bundleSourceTrust === "project" ? [profileEntry, userSource, projectSource, customSource] : [userSource, profileEntry, projectSource, customSource];
9269
- return ordered.filter((source) => source !== null);
9471
+ function readSourceFiles(options, candidates, truncated, warnings) {
9472
+ const considered = Math.min(candidates.length, MAX_FILES);
9473
+ const { items, bytesRead, budgetSkipped, budgetBound } = readCandidates(options, candidates, considered, warnings);
9474
+ const capSkipped = candidates.length - considered;
9475
+ if (capSkipped > 0) {
9476
+ const atLeast = truncated ? "at least " : "";
9477
+ warnings.push(`${options.label}: file limit of ${MAX_FILES} reached; skipped ${atLeast}${capSkipped} files`);
9478
+ }
9479
+ if (budgetSkipped > 0) {
9480
+ warnings.push(budgetBound === "shared" ? `${options.label}: read budget of this call reached; skipped ${budgetSkipped} files` : `${options.label}: text budget of ${MAX_TOTAL_BYTES} bytes reached; skipped ${budgetSkipped} files`);
9481
+ }
9482
+ return { items, bytesRead };
9270
9483
  }
9271
- function loadConfigWithSources(projectDir, options) {
9272
- const includeProject = options?.includeProject ?? true;
9273
- const invalidSource = options?.invalidSource ?? "throw";
9274
- const paths = getConfigPaths(projectDir, options);
9275
- const warningSink = options?.warningSink ?? console.warn;
9276
- const aliasedCustomConfigPath = resolveAliasedCustomConfigPath(paths, includeProject);
9277
- const projectStrip = createAliasStripTracker(warningSink, aliasedCustomConfigPath);
9278
- const boundedProjectStrip = createBoundedStripWarningSink(projectStrip.sink);
9279
- const { user, custom, allowProjectProfiles } = loadUserAndCustomSources(paths, invalidSource, warningSink);
9280
- const userSource = user.source;
9281
- const customSource = custom.source;
9282
- const project = includeProject ? loadConfigSource(paths.projectConfig, "project", invalidSource, boundedProjectStrip.sink, allowProjectProfiles) : {
9283
- metadata: { kind: "project", presence: "absent" },
9284
- source: null
9285
- };
9286
- const projectSource = project.source;
9287
- emitTopLevelProtectedFieldWarning(projectSource, "profiles", `\`profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. Its bundles are not selectable even if this project also sets \`profile\`.`, boundedProjectStrip.sink);
9288
- emitTopLevelProtectedFieldWarning(projectSource, "allow_project_profiles", `\`allow_project_profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`, boundedProjectStrip.sink);
9289
- emitProjectSearchProtectedWarnings(projectSource, boundedProjectStrip.sink);
9290
- const suppressedStripCount = boundedProjectStrip.suppressedCount();
9291
- if (suppressedStripCount > 0) {
9292
- projectStrip.sink(`[systematic] ${suppressedStripCount} additional project-config protected-field warning(s) in (${sanitizeDiagnosticText(paths.projectConfig)}) were suppressed.`);
9484
+ function loadSourceFiles(discover, read) {
9485
+ const warnings = [];
9486
+ const discovery = discoverSourceFiles(discover, warnings);
9487
+ if (discovery.state !== "found") {
9488
+ return { state: discovery.state, warnings };
9293
9489
  }
9294
- emitAliasFailureDiagnostics({
9295
- aliasedCustomConfigPath,
9296
- buffered: projectStrip.buffered,
9297
- customLoaded: custom.source !== null,
9298
- projectLoaded: project.source !== null,
9299
- warningSink
9300
- });
9301
- const emitAliasSuccessNotice = buildAliasSuccessNotice({
9302
- aliasedCustomConfigPath,
9303
- bufferedCount: projectStrip.buffered.length,
9304
- customLoaded: custom.source !== null,
9305
- projectConfigPath: paths.projectConfig,
9306
- projectLoaded: project.source !== null,
9307
- warningSink
9308
- });
9309
- const sources = [userSource, projectSource, customSource].filter((source) => source !== null);
9310
- warnRemovedKeys(sources, warningSink);
9311
- const userConfig = userSource?.config;
9312
- const projectConfig = projectSource?.config;
9313
- const customConfig = customSource?.config;
9314
- const warned = new Set;
9315
- const mergedSearch = mergeSearchSettings([userSource?.search, customSource?.search].filter((source) => source !== undefined));
9316
- assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig);
9317
- const profileSelection = resolveActiveProfile({
9318
- userConfig,
9319
- userSource,
9320
- projectConfig,
9321
- projectSource,
9322
- customConfig,
9323
- customSource,
9324
- allowProjectProfiles,
9325
- warningSink
9490
+ const { items, bytesRead } = readSourceFiles(read, discovery.candidates, discovery.truncated, warnings);
9491
+ return { state: "loaded", items, bytesRead, warnings };
9492
+ }
9493
+ function loadCorpus(root, kind = "solution") {
9494
+ const spec = KIND_TABLE[kind];
9495
+ const loaded = loadSourceFiles({
9496
+ directory: path2.join(root, ...spec.dir.split("/")),
9497
+ containedIn: root,
9498
+ walk: spec,
9499
+ label: spec.dir
9500
+ }, {
9501
+ displayPrefix: spec.dir,
9502
+ label: spec.dir,
9503
+ maxFileBytes: MAX_FILE_BYTES,
9504
+ parse: (displayPath, content) => {
9505
+ const parsed = parseCorpusDocument(kind, displayPath, content);
9506
+ return parsed.ok ? { ok: true, value: parsed.document } : { ok: false, reason: parsed.reason };
9507
+ }
9326
9508
  });
9327
- const profileEntry = profileSelection.bundle && profileSelection.bundleSource && typeof profileSelection.activeProfile === "string" ? {
9328
- kind: "profile-bundle",
9329
- canonicalPath: profileSelection.bundleSource.canonicalPath,
9330
- path: profileSelection.bundleSource.path,
9331
- config: {
9332
- agents: profileSelection.bundle.agents,
9333
- categories: profileSelection.bundle.categories
9334
- },
9335
- protectedFields: [],
9336
- profileName: profileSelection.activeProfile,
9337
- bundleTrust: profileSelection.bundleSource.trust
9338
- } : null;
9339
- const overlaySources = buildOverlaySources(profileEntry, profileSelection.bundleSource?.trust, userSource, projectSource, customSource);
9340
- const mergedOverlays = mergeOverlaySources(overlaySources);
9341
- const mergedPiSubagentsOverlays = mergePiSubagentsOverlaySources(sources);
9342
- const droppedCategories = Object.keys(mergedOverlays.categories).filter((name) => REMOVED_AGENT_CATEGORIES_SET.has(name));
9343
- warnDroppedNames(droppedCategories, "categories", warned, "v3.0.0", warningSink);
9344
- const droppedCategorySet = new Set(droppedCategories);
9345
- const overlays = droppedCategorySet.size === 0 ? mergedOverlays : {
9346
- ...mergedOverlays,
9347
- categories: Object.fromEntries(Object.entries(mergedOverlays.categories).filter(([key]) => !droppedCategorySet.has(key)))
9348
- };
9349
- const mergedDisabledAgents = mergeArraysUnique(mergeArraysUnique(mergeArraysUnique(DEFAULT_CONFIG.disabled_agents, userConfig?.disabled_agents), projectConfig?.disabled_agents), customConfig?.disabled_agents);
9350
- assertRoutingInvariants(overlays, mergedPiSubagentsOverlays, new Set(mergedDisabledAgents), warningSink);
9351
- const result = {
9352
- disabled_skills: mergeArraysUnique(mergeArraysUnique(mergeArraysUnique(DEFAULT_CONFIG.disabled_skills, userConfig?.disabled_skills), projectConfig?.disabled_skills), customConfig?.disabled_skills),
9353
- disabled_agents: mergedDisabledAgents,
9354
- disabled_commands: mergeArraysUnique(mergeArraysUnique(mergeArraysUnique(DEFAULT_CONFIG.disabled_commands, userConfig?.disabled_commands), projectConfig?.disabled_commands), customConfig?.disabled_commands),
9355
- bootstrap: {
9356
- ...DEFAULT_CONFIG.bootstrap,
9357
- ...userConfig?.bootstrap,
9358
- ...projectConfig?.bootstrap,
9359
- ...customConfig?.bootstrap
9360
- },
9361
- agents: overlayValues(overlays.agents),
9362
- categories: overlayValues(overlays.categories),
9363
- pi_subagents: {
9364
- categories: overlayValues(mergedPiSubagentsOverlays.categories),
9365
- agents: overlayValues(mergedPiSubagentsOverlays.agents)
9366
- },
9367
- skills_as_commands: customConfig?.skills_as_commands ?? projectConfig?.skills_as_commands ?? userConfig?.skills_as_commands ?? DEFAULT_CONFIG.skills_as_commands,
9368
- allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles,
9369
- ...mergedSearch.settings && { search: mergedSearch.settings },
9370
- ...mergedSearch.unreadable && { searchUnreadable: true }
9371
- };
9372
- const droppedSkills = computeDroppedNames(result.disabled_skills, CURRENT_SKILL_NAMES_SET);
9373
- warnDroppedNames(droppedSkills, "disabled_skills", warned, undefined, warningSink);
9374
- const droppedAgents = computeDroppedNames(result.disabled_agents, CURRENT_AGENT_NAMES_SET);
9375
- warnDroppedNames(droppedAgents, "disabled_agents", warned, undefined, warningSink);
9376
- const droppedSkillSet = new Set(droppedSkills);
9377
- const droppedAgentSet = new Set(droppedAgents);
9378
- const effectiveConfig = droppedSkillSet.size === 0 && droppedAgentSet.size === 0 ? result : {
9379
- ...result,
9380
- disabled_skills: result.disabled_skills.filter((n) => !droppedSkillSet.has(n)),
9381
- disabled_agents: result.disabled_agents.filter((n) => !droppedAgentSet.has(n))
9382
- };
9383
- emitAliasSuccessNotice?.();
9509
+ if (loaded.state !== "loaded") {
9510
+ return { state: "none", documents: [], warnings: loaded.warnings };
9511
+ }
9384
9512
  return {
9385
- config: effectiveConfig,
9386
- metadata: buildConfigObservationMetadata({
9387
- custom: custom.metadata,
9388
- profileSelection,
9389
- project: project.metadata,
9390
- sources,
9391
- user: user.metadata
9392
- }),
9393
- overlays,
9394
- piSubagentsOverlays: mergedPiSubagentsOverlays,
9395
- activeProfileSourcePath: profileSelection.bundleSource?.path ?? null
9513
+ state: "loaded",
9514
+ documents: loaded.items,
9515
+ warnings: loaded.warnings
9396
9516
  };
9397
9517
  }
9398
- function buildConfigObservationMetadata(summary) {
9399
- const authorities = [];
9400
- const sourceConfigs = new Map;
9401
- const sourcePaths = new Map;
9402
- for (const source of summary.sources) {
9403
- sourceConfigs.set(source.trust, source.config);
9404
- sourcePaths.set(source.trust, source.canonicalPath);
9518
+
9519
+ // src/lib/config.ts
9520
+ var CONFIG_AUTHORITY_FIELD_PATHS = [
9521
+ "bootstrap.enabled",
9522
+ "bootstrap.file",
9523
+ "skills_as_commands"
9524
+ ];
9525
+ var DEFAULT_CONFIG = {
9526
+ disabled_skills: [],
9527
+ disabled_agents: [],
9528
+ disabled_commands: [],
9529
+ bootstrap: {
9530
+ enabled: true
9531
+ },
9532
+ agents: {},
9533
+ categories: {},
9534
+ pi_subagents: { categories: {}, agents: {} },
9535
+ skills_as_commands: true,
9536
+ allow_project_profiles: false
9537
+ };
9538
+ var LAYER_TRUST = {
9539
+ user: "user",
9540
+ "user.local": "user",
9541
+ project: "project",
9542
+ custom: "custom",
9543
+ "custom.local": "custom"
9544
+ };
9545
+ var PROTECTED_OVERLAY_FIELD_PATHS = {
9546
+ agents: {
9547
+ model: "agents.*.model",
9548
+ permission: "agents.*.permission",
9549
+ skills: "agents.*.skills",
9550
+ variant: "agents.*.variant",
9551
+ opencode: "agents.*.opencode",
9552
+ pi: "agents.*.pi"
9553
+ },
9554
+ categories: {
9555
+ model: "categories.*.model",
9556
+ permission: "categories.*.permission",
9557
+ skills: "categories.*.skills",
9558
+ variant: "categories.*.variant",
9559
+ opencode: "categories.*.opencode",
9560
+ pi: "categories.*.pi"
9405
9561
  }
9406
- const firstDefinedSource = (fieldPath, candidates) => {
9407
- for (const sourceKind of candidates) {
9408
- const config = sourceConfigs.get(sourceKind);
9409
- if (config && hasConfigField(config, fieldPath)) {
9410
- return { fieldPath, sourceKind };
9411
- }
9562
+ };
9563
+ var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set(["allow_project_profiles"]);
9564
+ var PROJECT_PROTECTED_SEARCH_FIELDS = [
9565
+ ["enabled", "search.enabled"],
9566
+ ["allow_project_sources", "search.allow_project_sources"]
9567
+ ];
9568
+ var MAX_DIAGNOSTIC_TEXT = 200;
9569
+ var MAX_STRIP_WARNINGS = 20;
9570
+ var DIAGNOSTIC_ELLIPSIS = "\u2026";
9571
+ function sanitizeDiagnosticText(input) {
9572
+ const budget = MAX_DIAGNOSTIC_TEXT - DIAGNOSTIC_ELLIPSIS.length;
9573
+ let rendered = "";
9574
+ let truncated = false;
9575
+ for (const char of input) {
9576
+ if (rendered.length >= budget) {
9577
+ truncated = true;
9578
+ break;
9412
9579
  }
9413
- return;
9414
- };
9415
- const fieldCandidates = {
9416
- "bootstrap.enabled": ["custom", "project", "user"],
9417
- "bootstrap.file": ["custom", "project", "user"],
9418
- skills_as_commands: ["custom", "project", "user"]
9419
- };
9420
- for (const fieldPath of CONFIG_AUTHORITY_FIELD_PATHS) {
9421
- const authority = firstDefinedSource(fieldPath, fieldCandidates[fieldPath]);
9422
- if (authority)
9423
- authorities.push(authority);
9580
+ const code = char.codePointAt(0) ?? 0;
9581
+ const isControl = code <= 31 || code === 127 || code >= 128 && code <= 159 || code === 8232 || code === 8233;
9582
+ const piece = isControl ? `\\u${code.toString(16).padStart(4, "0")}` : char;
9583
+ if (rendered.length + piece.length > budget) {
9584
+ truncated = true;
9585
+ break;
9586
+ }
9587
+ rendered += piece;
9424
9588
  }
9425
- const protectedFields = collectVisibleProtectedFields(summary.sources);
9426
- const sources = dedupeSourceMetadata([summary.custom, summary.project, summary.user], sourcePaths);
9589
+ return truncated ? `${rendered}${DIAGNOSTIC_ELLIPSIS}` : rendered;
9590
+ }
9591
+ function createBoundedStripWarningSink(warningSink) {
9592
+ let emitted = 0;
9593
+ let suppressed = 0;
9427
9594
  return {
9428
- authorities: sortAuthorities(authorities),
9429
- protectedFields: sortProtectedFields(protectedFields),
9430
- sources,
9431
- activeProfile: summary.profileSelection.activeProfile,
9432
- profileSelectorSource: summary.profileSelection.profileSelectorSource,
9433
- profileFallback: summary.profileSelection.profileFallback
9595
+ sink(message) {
9596
+ if (emitted < MAX_STRIP_WARNINGS) {
9597
+ emitted++;
9598
+ warningSink(message);
9599
+ } else {
9600
+ suppressed++;
9601
+ }
9602
+ },
9603
+ suppressedCount() {
9604
+ return suppressed;
9605
+ }
9434
9606
  };
9435
9607
  }
9436
- function collectVisibleProtectedFields(sources) {
9437
- const projectSource = sources.find((source) => source.trust === "project");
9438
- const customSource = sources.find((source) => source.trust === "custom");
9439
- const projectAppliedViaCustom = projectSource !== undefined && customSource !== undefined && projectSource.canonicalPath === customSource.canonicalPath;
9440
- return sources.flatMap((source) => projectAppliedViaCustom && source.trust === "project" ? [] : source.protectedFields);
9441
- }
9442
- function dedupeSourceMetadata(metadata, sourcePaths) {
9443
- const seen = new Set;
9444
- return metadata.filter((source) => {
9445
- const identity = sourcePaths.get(source.kind) ?? `missing:${source.kind}`;
9446
- if (seen.has(identity))
9447
- return false;
9448
- seen.add(identity);
9449
- return true;
9450
- });
9608
+ var CURRENT_SKILL_NAMES_SET = new Set(BUNDLED_SKILL_NAMES);
9609
+ var CURRENT_AGENT_NAMES_SET = new Set([
9610
+ ...BUNDLED_AGENT_NAMES,
9611
+ ...BUNDLED_AGENT_QUALIFIED_IDS
9612
+ ]);
9613
+ var REMOVED_AGENT_CATEGORIES_SET = new Set(REMOVED_BUNDLED_AGENT_CATEGORIES);
9614
+ var BUNDLED_AGENT_CATEGORY_BY_KEY = new Map(BUNDLED_AGENT_QUALIFIED_IDS.map((qualifiedId) => {
9615
+ const separatorIndex = qualifiedId.indexOf("/");
9616
+ return [
9617
+ qualifiedId.slice(separatorIndex + 1),
9618
+ qualifiedId.slice(0, separatorIndex)
9619
+ ];
9620
+ }));
9621
+ var BUNDLED_AGENT_KEYS_BY_CATEGORY = (() => {
9622
+ const byCategory = new Map;
9623
+ for (const [agentKey, category] of BUNDLED_AGENT_CATEGORY_BY_KEY) {
9624
+ const existing = byCategory.get(category) ?? [];
9625
+ existing.push(agentKey);
9626
+ byCategory.set(category, existing);
9627
+ }
9628
+ return byCategory;
9629
+ })();
9630
+ function computeDroppedNames(names, allowedSet) {
9631
+ return names.filter((n) => !allowedSet.has(n));
9451
9632
  }
9452
- function hasConfigField(config, fieldPath) {
9453
- const [topLevel, nested] = fieldPath.split(".");
9454
- if (nested === undefined)
9455
- return config[topLevel] !== undefined;
9456
- const value = config[topLevel];
9457
- return isRecord3(value) && value[nested] !== undefined;
9633
+ var MIGRATION_DOCS_URL = "https://fro.bot/systematic/guides/v3-migration/";
9634
+ function warnDroppedNames(dropped, field, warned, removalVersion, warningSink = console.warn) {
9635
+ for (const name of dropped) {
9636
+ if (warned.has(name))
9637
+ continue;
9638
+ warned.add(name);
9639
+ const displayName = field === "categories" ? `${field}.${name}` : name;
9640
+ const removalNote = removalVersion ? ` It was removed in ${removalVersion}.` : "";
9641
+ warningSink(`[systematic] "${displayName}" in \`${field}\` is no longer a bundled name and will be ignored.${removalNote} Remove it from your config to silence this warning. See ${MIGRATION_DOCS_URL} for migration guidance.`);
9642
+ }
9458
9643
  }
9459
- function sortAuthorities(authorities) {
9460
- return [...authorities].sort((left, right) => left.fieldPath === right.fieldPath ? left.sourceKind.localeCompare(right.sourceKind) : left.fieldPath.localeCompare(right.fieldPath));
9644
+ function isErrorWithCode(error) {
9645
+ return error instanceof Error && "code" in error;
9461
9646
  }
9462
- function sortProtectedFields(fields) {
9463
- return [...fields].sort((left, right) => left.fieldPath === right.fieldPath ? left.sourceKind.localeCompare(right.sourceKind) : left.fieldPath.localeCompare(right.fieldPath));
9647
+ var OVERSIZED_FILE_REASON = `file is larger than ${MAX_PROJECT_CONFIG_BYTES / (1024 * 1024)} MB`;
9648
+ function readConfigText(filePath, maxBytes) {
9649
+ if (maxBytes === undefined) {
9650
+ try {
9651
+ return fs4.readFileSync(filePath, "utf-8");
9652
+ } catch (error) {
9653
+ if (isErrorWithCode(error) && error.code === "ENOENT" && !configEntryExists(filePath)) {
9654
+ return null;
9655
+ }
9656
+ throw new Error(`Invalid Systematic config in ${filePath}: unable to read file`, { cause: error });
9657
+ }
9658
+ }
9659
+ const read = readBytesBounded(filePath, maxBytes);
9660
+ switch (read.kind) {
9661
+ case "bytes":
9662
+ return read.bytes.toString("utf-8");
9663
+ case "absent":
9664
+ if (!configEntryExists(filePath))
9665
+ return null;
9666
+ throw new Error(`Invalid Systematic config in ${filePath}: unable to read file`);
9667
+ case "too-large":
9668
+ throw new Error(`Invalid Systematic config in ${filePath}: unable to read file (${OVERSIZED_FILE_REASON})`);
9669
+ default:
9670
+ throw new Error(`Invalid Systematic config in ${filePath}: unable to read file`);
9671
+ }
9464
9672
  }
9465
- function isAgentDisabled(disabledAgents, agentOverlays, category, key) {
9466
- const qualifiedId = category ? `${category}/${key}` : key;
9467
- if (disabledAgents.has(key) || disabledAgents.has(qualifiedId))
9468
- return true;
9469
- return agentOverlays[key]?.value.disable === true || agentOverlays[qualifiedId]?.value.disable === true;
9673
+ function loadJsoncFile(filePath, maxBytes) {
9674
+ const content = readConfigText(filePath, maxBytes);
9675
+ if (content === null)
9676
+ return null;
9677
+ const errors = [];
9678
+ const parsed = parse(content, errors);
9679
+ if (errors.length > 0) {
9680
+ const error = errors[0];
9681
+ const message = error ? `${printParseErrorCode(error.error)} at offset ${error.offset}` : "unknown parse error";
9682
+ throw new Error(`Invalid Systematic config in ${filePath}: JSONC parse error: ${message}`);
9683
+ }
9684
+ if (!isRecord3(parsed)) {
9685
+ throw new Error(`Invalid Systematic config in ${filePath}: root must be an object`);
9686
+ }
9687
+ return parsed;
9470
9688
  }
9471
- function collectRoutingTargets(overlays, disabledAgents = new Set) {
9472
- const targets = new Map;
9473
- const addTarget = (agentKey, category) => {
9474
- if (isAgentDisabled(disabledAgents, overlays.agents, category, agentKey)) {
9475
- return;
9476
- }
9477
- targets.set(`${category}/${agentKey}`, { agentKey, category });
9478
- };
9479
- for (const rawKey of Object.keys(overlays.agents)) {
9480
- const separatorIndex = rawKey.indexOf("/");
9481
- if (separatorIndex === -1) {
9482
- const category = BUNDLED_AGENT_CATEGORY_BY_KEY.get(rawKey);
9483
- if (category !== undefined)
9484
- addTarget(rawKey, category);
9485
- continue;
9486
- }
9487
- const category = rawKey.slice(0, separatorIndex);
9488
- const agentKey = rawKey.slice(separatorIndex + 1);
9489
- if (BUNDLED_AGENT_CATEGORY_BY_KEY.get(agentKey) === category) {
9490
- addTarget(agentKey, category);
9491
- }
9689
+ var TYPED_VALIDATION_DOCS_URL = "https://fro.bot/systematic/reference/configuration#typed-validation";
9690
+ var TYPED_KEY_FIELDS = new Set([
9691
+ "agents",
9692
+ "disabled_agents",
9693
+ "disabled_skills"
9694
+ ]);
9695
+ function formatUnrecognizedKeysHint(badKeys, topField) {
9696
+ if (badKeys.length === 0) {
9697
+ throw new Error("formatUnrecognizedKeysHint requires non-empty keys");
9492
9698
  }
9493
- for (const categoryKey of Object.keys(overlays.categories)) {
9494
- const agentKeys = BUNDLED_AGENT_KEYS_BY_CATEGORY.get(categoryKey);
9495
- if (agentKeys === undefined)
9496
- continue;
9497
- for (const agentKey of agentKeys)
9498
- addTarget(agentKey, categoryKey);
9699
+ if (badKeys.length === 1) {
9700
+ return `Unrecognized key '${badKeys[0]}' in \`${topField}\`. This must be a bundled name. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
9499
9701
  }
9500
- return Array.from(targets.values());
9702
+ const joined = badKeys.map((k) => `'${k}'`).join(", ");
9703
+ return `Unrecognized keys ${joined} in \`${topField}\`. These must be bundled names. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
9501
9704
  }
9502
- function assertProfileBundleCategoryKeysAreBundledCategories(profileName, bundle) {
9503
- for (const categoryKey of Object.keys(bundle.categories ?? {})) {
9504
- if (!BUNDLED_AGENT_KEYS_BY_CATEGORY.has(categoryKey)) {
9505
- throw new Error(`Invalid Systematic config: profiles.${profileName}.categories.${categoryKey} is not a bundled agent category. Valid categories: ${Array.from(BUNDLED_AGENT_KEYS_BY_CATEGORY.keys()).join(", ")}`);
9506
- }
9705
+ function formatProfileAgentUnrecognizedKeysHint(badKeys, profileName) {
9706
+ const prefixed = badKeys.map((k) => `profiles.${profileName}.agents.${k}`);
9707
+ const isAre = prefixed.length === 1 ? "is not a bundled agent" : "are not bundled agents";
9708
+ return `${prefixed.join(", ")} ${isAre}. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
9709
+ }
9710
+ function enrichProfileAgentUnrecognizedKeysIssue(issue) {
9711
+ if (issue.code !== "unrecognized_keys" || issue.path[0] !== "profiles" || issue.path[2] !== "agents" || typeof issue.path[1] !== "string") {
9712
+ return null;
9713
+ }
9714
+ const hint = formatProfileAgentUnrecognizedKeysHint(issue.keys, issue.path[1]);
9715
+ return { ...issue, message: hint };
9716
+ }
9717
+ function enrichTopLevelTypedKeyIssue(issue, rawInput) {
9718
+ const topField = issue.path[0];
9719
+ if (typeof topField !== "string" || !TYPED_KEY_FIELDS.has(topField)) {
9720
+ return null;
9721
+ }
9722
+ if (issue.code === "unrecognized_keys") {
9723
+ const hint = formatUnrecognizedKeysHint(issue.keys, topField);
9724
+ return { ...issue, message: hint };
9725
+ }
9726
+ if (issue.code === "invalid_value" && (topField === "disabled_agents" || topField === "disabled_skills")) {
9727
+ const badValue = resolveValueAtPath(rawInput, issue.path);
9728
+ const kind = topField === "disabled_agents" ? "agent" : "skill";
9729
+ const hint = typeof badValue === "string" ? `Unrecognized ${kind} name '${badValue}' in \`${topField}\`. This must be a bundled name. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.` : `Invalid value in \`${topField}\`. See ${TYPED_VALIDATION_DOCS_URL} for the full list of valid names.`;
9730
+ return { ...issue, message: hint };
9507
9731
  }
9732
+ return null;
9508
9733
  }
9509
- function assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig) {
9510
- for (const config of [userConfig, customConfig, projectConfig]) {
9511
- for (const [profileName, bundle] of Object.entries(config?.profiles ?? {})) {
9512
- assertProfileBundleCategoryKeysAreBundledCategories(profileName, bundle);
9513
- }
9514
- }
9734
+ function enrichUnrecognizedKeyIssues(issues, rawInput) {
9735
+ return issues.map((issue) => enrichProfileAgentUnrecognizedKeysIssue(issue) ?? enrichTopLevelTypedKeyIssue(issue, rawInput) ?? issue);
9515
9736
  }
9516
- function assertRoutingInvariants(overlays, piSubagentsOverlays, disabledAgents, warningSink) {
9517
- const targets = collectRoutingTargets(overlays, disabledAgents);
9518
- for (const target of targets) {
9519
- const resolution = resolveRouting({
9520
- overlays,
9521
- piSubagentsOverlays,
9522
- target,
9523
- harness: "opencode"
9524
- });
9525
- if (qualifierResolvesWithoutModel(resolution)) {
9526
- throw new Error(`Invalid Systematic config: agents.${target.agentKey}.variant resolves to "${resolution.qualifier}" on the opencode harness, but no model resolves for agents.${target.agentKey} on opencode at any layer (agent, category, block, or flat). Set a model at the same layer or a lower one, or remove the qualifier.`);
9737
+ function resolveValueAtPath(root, path) {
9738
+ let current = root;
9739
+ for (const segment of path) {
9740
+ if (typeof segment === "symbol") {
9741
+ return;
9742
+ }
9743
+ if (typeof segment === "number") {
9744
+ if (!Array.isArray(current))
9745
+ return;
9746
+ current = current[segment];
9747
+ } else {
9748
+ if (!isRecord3(current))
9749
+ return;
9750
+ current = current[segment];
9527
9751
  }
9528
9752
  }
9529
- for (const warning of collectWrittenLegacyPiSubagentsThinkingWarnings(piSubagentsOverlays)) {
9530
- warningSink(warning);
9531
- }
9753
+ return current;
9532
9754
  }
9533
- function mergeOverlaySources(sources) {
9534
- const result = {
9535
- agents: {},
9536
- categories: {}
9537
- };
9538
- for (const source of sources) {
9539
- mergeOverlayMap(result.agents, source, "agents");
9540
- mergeOverlayMap(result.categories, source, "categories");
9755
+ function throwTopLevelConfigSchemaError(filePath, trust, rawIssues, rawInput) {
9756
+ const issues = enrichUnrecognizedKeyIssues(rawIssues, rawInput);
9757
+ if (issues.length === 0) {
9758
+ throw Object.assign(new Error(`Invalid Systematic config in ${filePath}: schema validation failed`), { _tag: "ConfigSchemaError", filePath, trust, issues });
9541
9759
  }
9542
- return result;
9760
+ const formatIssue = (issue) => {
9761
+ const fieldPath = issue.code === "unrecognized_keys" ? null : issue.path.join(".");
9762
+ return fieldPath ? `${fieldPath} ${issue.message}` : issue.message;
9763
+ };
9764
+ const formatted = issues.map(formatIssue);
9765
+ const message = formatted.length === 1 ? `Invalid Systematic config in ${filePath}: ${formatted[0]}` : `Invalid Systematic config in ${filePath}:
9766
+ ${formatted.map((entry) => ` - ${entry}`).join(`
9767
+ `)}`;
9768
+ throw Object.assign(new Error(message), {
9769
+ _tag: "ConfigSchemaError",
9770
+ filePath,
9771
+ trust,
9772
+ issues
9773
+ });
9543
9774
  }
9544
- function mergeOverlayMap(target, source, mapKey) {
9545
- const overlayMap = source.config[mapKey];
9546
- if (overlayMap === undefined)
9547
- return;
9548
- if (!isRecord3(overlayMap)) {
9549
- throwInvalidOverlay(source.path, mapKey);
9550
- }
9551
- for (const [key, value] of Object.entries(overlayMap)) {
9552
- const keyPath = source.kind === "profile-bundle" ? `profiles.${source.profileName}.${mapKey}.${key}` : `${mapKey}.${key}`;
9553
- if (!isRecord3(value)) {
9554
- throwInvalidOverlay(source.path, keyPath);
9775
+ function loadConfigSource(input) {
9776
+ const { filePath, layer, invalidSource, warningSink, allowProjectProfiles } = input;
9777
+ const trust = LAYER_TRUST[layer];
9778
+ try {
9779
+ const rawConfig = loadJsoncFile(filePath, layer === "project" ? MAX_PROJECT_CONFIG_BYTES : undefined);
9780
+ if (!rawConfig) {
9781
+ return {
9782
+ metadata: { kind: trust, presence: "absent" },
9783
+ source: null
9784
+ };
9555
9785
  }
9556
- const previous = target[key];
9557
- const nextValue = resolveOverlayEntryValue(previous?.value, value, source);
9558
- const nextOrigins = resolveOverlayEntryOrigin(previous?.origins, value, source);
9559
- target[key] = {
9560
- value: nextValue,
9561
- sourcePath: source.path,
9562
- keyPath,
9563
- origins: nextOrigins
9786
+ const protectedFields = collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles);
9787
+ const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig, allowProjectProfiles) : rawConfig;
9788
+ const config = trust === "project" ? stripProjectSecurityOverlayFields(topLevelStripped, filePath, warningSink) : topLevelStripped;
9789
+ const { config: configWithoutSearch, search } = splitSearchBlock(config, filePath, trust, warningSink);
9790
+ const result = SystematicConfigSchema.safeParse(configWithoutSearch);
9791
+ if (!result.success) {
9792
+ throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, configWithoutSearch);
9793
+ }
9794
+ return {
9795
+ metadata: { kind: trust, presence: "present" },
9796
+ source: {
9797
+ kind: "file",
9798
+ layer,
9799
+ canonicalPath: resolveConfigSourcePath(filePath),
9800
+ config: configWithoutSearch,
9801
+ path: filePath,
9802
+ protectedFields,
9803
+ removedKeys: REMOVED_CONFIG_KEYS.filter((key) => Object.hasOwn(rawConfig, key)),
9804
+ ...search && { search },
9805
+ trust
9806
+ }
9807
+ };
9808
+ } catch (error) {
9809
+ if (invalidSource === "throw")
9810
+ throw error;
9811
+ const errorCode = classifyConfigSourceError(error);
9812
+ input.reportInvalid(filePath, errorCode);
9813
+ return {
9814
+ metadata: { errorCode, kind: trust, presence: "invalid" },
9815
+ source: null
9564
9816
  };
9565
9817
  }
9566
9818
  }
9567
- function originForSource(source) {
9568
- if (source.kind === "profile-bundle") {
9569
- return `${source.bundleTrust}-profile`;
9570
- }
9571
- return source.trust;
9819
+ function splitSearchBlock(config, filePath, trust, warningSink) {
9820
+ if (!Object.hasOwn(config, "search"))
9821
+ return { config, search: undefined };
9822
+ const { search: rawSearch, ...rest } = config;
9823
+ const validation = validateSearchConfig(rawSearch, trust === "project" ? "project" : "user", filePath);
9824
+ for (const message of validation.warnings)
9825
+ warningSink(message);
9826
+ return {
9827
+ config: rest,
9828
+ search: trust === "project" ? undefined : { settings: validation.settings, unreadable: validation.unreadable }
9829
+ };
9572
9830
  }
9573
- function routingOriginsFromOwnFields(fragment, tag) {
9574
- const origins = {};
9575
- if (Object.hasOwn(fragment, "model"))
9576
- origins.model = tag;
9577
- if (Object.hasOwn(fragment, "variant"))
9578
- origins.variant = tag;
9579
- const opencodeBlock = fragment.opencode;
9580
- if (isRecord3(opencodeBlock)) {
9581
- if (Object.hasOwn(opencodeBlock, "model"))
9582
- origins.opencodeModel = tag;
9583
- if (Object.hasOwn(opencodeBlock, "variant"))
9584
- origins.opencodeVariant = tag;
9585
- }
9586
- const piBlock = fragment.pi;
9587
- if (isRecord3(piBlock)) {
9588
- if (Object.hasOwn(piBlock, "model"))
9589
- origins.piModel = tag;
9590
- if (Object.hasOwn(piBlock, "thinking"))
9591
- origins.piThinking = tag;
9592
- }
9593
- return origins;
9831
+ function classifyConfigSourceError(error) {
9832
+ if (isConfigSchemaError(error))
9833
+ return "schema-invalid";
9834
+ if (!(error instanceof Error))
9835
+ return "source-invalid";
9836
+ if (error.message.includes("JSONC parse error"))
9837
+ return "parse-failed";
9838
+ if (error.message.includes("unable to read file"))
9839
+ return "read-failed";
9840
+ return "source-invalid";
9594
9841
  }
9595
- function resolveOverlayEntryOrigin(previous, fragment, source) {
9596
- const own = routingOriginsFromOwnFields(fragment, originForSource(source));
9597
- if (!previous)
9598
- return own;
9599
- const preserves = source.kind === "profile-bundle" || source.trust === "project" || source.trust === "user";
9600
- return preserves ? { ...previous, ...own } : own;
9842
+ function isConfigSchemaError(error) {
9843
+ return isRecord3(error) && error._tag === "ConfigSchemaError";
9601
9844
  }
9602
- function resolveOverlayEntryValue(previous, next, source) {
9603
- if (!previous)
9604
- return next;
9605
- if (source.kind === "profile-bundle") {
9606
- return mergeProfileOverlayValue(previous, next);
9845
+ function resolveConfigSourcePath(filePath) {
9846
+ try {
9847
+ return fs4.realpathSync(filePath);
9848
+ } catch {
9849
+ return path3.resolve(filePath);
9607
9850
  }
9608
- if (source.trust === "project")
9609
- return preserveSecurityFields(previous, next);
9610
- if (source.trust === "user")
9611
- return mergeProfileOverlayValue(previous, next);
9612
- return next;
9613
9851
  }
9614
- function stripProjectSecurityOverlay(sourcePath, keyPath, value, warningSink) {
9615
- const safeKeyPath = sanitizeDiagnosticText(keyPath);
9616
- const safeSourcePath = sanitizeDiagnosticText(sourcePath);
9617
- let stripped;
9618
- for (const field of SECURITY_OVERLAY_FIELDS) {
9619
- if (Object.hasOwn(value, field)) {
9620
- stripped ??= { ...value };
9621
- delete stripped[field];
9622
- warningSink(`[systematic] \`${safeKeyPath}.${field}\` in project config (${safeSourcePath}) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`);
9623
- }
9852
+ function emitTopLevelProtectedFieldWarning(projectSource, fieldPath, messageTemplate, sink) {
9853
+ if (!projectSource?.protectedFields.some((field) => field.fieldPath === fieldPath)) {
9854
+ return;
9624
9855
  }
9625
- return stripped ?? value;
9856
+ const safePath = sanitizeDiagnosticText(projectSource.path);
9857
+ sink(`[systematic] ${messageTemplate.replace("%PATH%", safePath)}`);
9626
9858
  }
9627
- function preserveSecurityFields(previous, next) {
9628
- const result = { ...next };
9629
- for (const field of SECURITY_OVERLAY_FIELDS) {
9630
- if (Object.hasOwn(previous, field)) {
9631
- result[field] = previous[field];
9632
- }
9859
+ function emitProjectSearchProtectedWarnings(projectSource, sink) {
9860
+ for (const [, fieldPath] of PROJECT_PROTECTED_SEARCH_FIELDS) {
9861
+ emitTopLevelProtectedFieldWarning(projectSource, fieldPath, `\`${fieldPath}\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. A project config may set \`search.sources\` only.`, sink);
9633
9862
  }
9634
- return result;
9635
9863
  }
9636
- var HARNESS_BLOCK_KEYS = ["opencode", "pi"];
9637
- function mergeProfileOverlayValue(previous, next) {
9638
- const result = { ...previous, ...next };
9639
- for (const blockKey of HARNESS_BLOCK_KEYS) {
9640
- const previousBlock = previous[blockKey];
9641
- const nextBlock = next[blockKey];
9642
- if (isRecord3(previousBlock) && isRecord3(nextBlock)) {
9643
- result[blockKey] = { ...previousBlock, ...nextBlock };
9644
- }
9864
+ function collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles) {
9865
+ if (trust !== "project")
9866
+ return [];
9867
+ return [
9868
+ ...!allowProjectProfiles && Object.hasOwn(rawConfig, "profiles") ? [
9869
+ {
9870
+ fieldPath: "profiles",
9871
+ outcome: "blocked",
9872
+ sourceKind: "project"
9873
+ }
9874
+ ] : [],
9875
+ ...Object.hasOwn(rawConfig, "allow_project_profiles") ? [
9876
+ {
9877
+ fieldPath: "allow_project_profiles",
9878
+ outcome: "blocked",
9879
+ sourceKind: "project"
9880
+ }
9881
+ ] : [],
9882
+ ...collectSearchProtectedFields(rawConfig.search),
9883
+ ...collectOverlayProtectedFields(rawConfig.agents, "agents"),
9884
+ ...collectOverlayProtectedFields(rawConfig.categories, "categories")
9885
+ ];
9886
+ }
9887
+ function collectSearchProtectedFields(search) {
9888
+ if (!isRecord3(search))
9889
+ return [];
9890
+ return PROJECT_PROTECTED_SEARCH_FIELDS.filter(([key]) => Object.hasOwn(search, key)).map(([, fieldPath]) => ({
9891
+ fieldPath,
9892
+ outcome: "blocked",
9893
+ sourceKind: "project"
9894
+ }));
9895
+ }
9896
+ function collectOverlayProtectedFields(overlayMap, mapKey) {
9897
+ if (!isRecord3(overlayMap))
9898
+ return [];
9899
+ return Object.values(overlayMap).flatMap((value) => isRecord3(value) ? collectProtectedOverlayValue(value, mapKey) : []);
9900
+ }
9901
+ function collectProtectedOverlayValue(value, mapKey) {
9902
+ return [...SECURITY_OVERLAY_FIELDS].filter((field) => Object.hasOwn(value, field)).map((field) => ({
9903
+ fieldPath: PROTECTED_OVERLAY_FIELD_PATHS[mapKey][field],
9904
+ outcome: "blocked",
9905
+ sourceKind: "project"
9906
+ }));
9907
+ }
9908
+ function stripProjectProtectedFields(rawConfig, allowProjectProfiles) {
9909
+ const config = { ...rawConfig };
9910
+ for (const field of PROJECT_ALWAYS_PROTECTED_FIELDS) {
9911
+ delete config[field];
9645
9912
  }
9646
- return result;
9913
+ if (!allowProjectProfiles) {
9914
+ delete config.profiles;
9915
+ }
9916
+ return config;
9647
9917
  }
9648
- var PI_SUBAGENTS_PROTECTED_FIELD_SET = new Set(PI_SUBAGENTS_PROTECTED_FIELDS);
9649
- function mergePiSubagentsOverlaySources(sources) {
9650
- const result = {
9651
- agents: {},
9652
- categories: {}
9653
- };
9654
- for (const source of sources) {
9655
- mergePiSubagentsOverlayMap(result.agents, source, "agents");
9656
- mergePiSubagentsOverlayMap(result.categories, source, "categories");
9918
+ function stripProjectSecurityOverlayFields(rawConfig, filePath, warningSink) {
9919
+ const agents = stripSecurityOverlayEntries(rawConfig.agents, "agents", filePath, warningSink);
9920
+ const categories = stripSecurityOverlayEntries(rawConfig.categories, "categories", filePath, warningSink);
9921
+ if (agents === rawConfig.agents && categories === rawConfig.categories) {
9922
+ return rawConfig;
9657
9923
  }
9924
+ const result = { ...rawConfig };
9925
+ if (agents !== rawConfig.agents)
9926
+ result.agents = agents;
9927
+ if (categories !== rawConfig.categories)
9928
+ result.categories = categories;
9658
9929
  return result;
9659
9930
  }
9660
- function stripPiSubagentsProtectedFields(value) {
9931
+ function stripSecurityOverlayEntries(overlayMap, mapKey, filePath, warningSink) {
9932
+ if (!isRecord3(overlayMap))
9933
+ return overlayMap;
9934
+ let changed = false;
9661
9935
  const result = {};
9662
- for (const [field, fieldValue] of Object.entries(value)) {
9663
- if (PI_SUBAGENTS_PROTECTED_FIELD_SET.has(field))
9936
+ for (const [key, value] of Object.entries(overlayMap)) {
9937
+ if (!isRecord3(value)) {
9938
+ result[key] = value;
9664
9939
  continue;
9665
- result[field] = fieldValue;
9666
- }
9667
- return result;
9668
- }
9669
- function preservePiSubagentsProtectedFields(previous, next) {
9670
- const result = { ...next };
9671
- for (const field of PI_SUBAGENTS_PROTECTED_FIELD_SET) {
9672
- if (Object.hasOwn(previous, field)) {
9673
- result[field] = previous[field];
9674
9940
  }
9675
- }
9676
- return result;
9677
- }
9678
- function mergePiSubagentsOverlayMap(target, source, mapKey) {
9679
- const overlayMap = source.config.pi_subagents?.[mapKey];
9680
- if (overlayMap === undefined)
9681
- return;
9682
- if (!isRecord3(overlayMap)) {
9683
- throwInvalidOverlay(source.path, `pi_subagents.${mapKey}`);
9684
- }
9685
- for (const [key, rawValue] of Object.entries(overlayMap)) {
9686
- const keyPath = `pi_subagents.${mapKey}.${key}`;
9687
- if (!isRecord3(rawValue)) {
9688
- throwInvalidOverlay(source.path, keyPath);
9941
+ const stripped = stripProjectSecurityOverlay(filePath, `${mapKey}.${key}`, value, warningSink);
9942
+ if (stripped === value) {
9943
+ result[key] = stripped;
9944
+ continue;
9689
9945
  }
9690
- const previous = target[key];
9691
- const value = source.trust === "project" ? preservePiSubagentsProtectedFields(previous?.value ?? {}, stripPiSubagentsProtectedFields(rawValue)) : rawValue;
9692
- target[key] = {
9693
- value,
9694
- sourcePath: source.path,
9695
- keyPath
9696
- };
9946
+ changed = true;
9947
+ if (Object.keys(stripped).length === 0)
9948
+ continue;
9949
+ result[key] = stripped;
9697
9950
  }
9951
+ return changed ? result : overlayMap;
9698
9952
  }
9699
- function overlayValues(overlays) {
9700
- const result = {};
9701
- for (const [key, overlay] of Object.entries(overlays)) {
9702
- result[key] = overlay.value;
9703
- }
9704
- return result;
9953
+ function isRecord3(value) {
9954
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9705
9955
  }
9706
- function throwInvalidOverlay(sourcePath, keyPath) {
9707
- throw new Error(`Invalid Systematic config in ${sourcePath}: ${keyPath} must be an object`);
9956
+ function mergeArraysUnique(arr1, arr2) {
9957
+ const set = new Set;
9958
+ if (arr1)
9959
+ for (const item of arr1)
9960
+ set.add(item);
9961
+ if (arr2)
9962
+ for (const item of arr2)
9963
+ set.add(item);
9964
+ return Array.from(set);
9708
9965
  }
9709
- function getConfigPaths(projectDir, options) {
9710
- const { homeDir, userConfigDir, customConfigDir } = resolveUserLevelConfigDirs(options);
9711
- const result = {
9712
- userConfig: selectConfigFile(userConfigDir, "systematic"),
9713
- projectConfig: selectConfigFile(path2.join(projectDir, ".opencode"), "systematic"),
9714
- userDir: path2.join(homeDir, ".config/opencode/systematic"),
9715
- projectDir: path2.join(projectDir, ".opencode/systematic"),
9716
- ...customConfigDir && {
9717
- customConfig: selectConfigFile(customConfigDir, "systematic"),
9718
- customDir: path2.join(customConfigDir, "systematic")
9719
- }
9720
- };
9721
- return result;
9966
+ var PROFILE_DOCS_URL = "https://fro.bot/systematic/reference/configuration#profiles";
9967
+ function chainOf(layers) {
9968
+ return [
9969
+ layers.user,
9970
+ layers.userLocal,
9971
+ layers.project,
9972
+ layers.custom,
9973
+ layers.customLocal
9974
+ ].filter((source) => source !== null);
9975
+ }
9976
+ function lastDefined(sources, key) {
9977
+ let found;
9978
+ for (const source of sources) {
9979
+ const value = source?.config[key];
9980
+ if (value !== undefined)
9981
+ found = value;
9982
+ }
9983
+ return found;
9722
9984
  }
9723
-
9724
- // src/lib/walk-dir.ts
9725
- import fs4 from "fs";
9726
- import path3 from "path";
9727
- function isDiscoverableMarkdown(fileName) {
9728
- return fileName.endsWith(".md") && fileName.toLowerCase() !== "readme.md";
9985
+ var NO_PROFILE_SELECTION = {
9986
+ activeProfile: null,
9987
+ profileSelectorSource: null,
9988
+ profileFallback: null,
9989
+ bundle: null,
9990
+ bundleSource: null
9991
+ };
9992
+ function resolveProfileSelector(input) {
9993
+ const envProfile = process.env.SYSTEMATIC_PROFILE?.trim();
9994
+ if (envProfile)
9995
+ return { value: envProfile, source: "environment" };
9996
+ const { layers } = input;
9997
+ const candidates = [
9998
+ ["custom", lastDefined([layers.custom, layers.customLocal], "profile")],
9999
+ ["project", layers.project?.config.profile],
10000
+ ["user", lastDefined([layers.user, layers.userLocal], "profile")]
10001
+ ];
10002
+ for (const [source, value] of candidates) {
10003
+ if (value !== undefined)
10004
+ return { value, source };
10005
+ }
10006
+ return null;
9729
10007
  }
9730
- function walkDir(rootDir, options = {}) {
9731
- const { maxDepth = 3, filter } = options;
9732
- const results = [];
9733
- if (!fs4.existsSync(rootDir))
9734
- return results;
9735
- function recurse(currentDir, depth, category) {
9736
- if (depth > maxDepth)
9737
- return;
9738
- const entries = fs4.readdirSync(currentDir, { withFileTypes: true });
9739
- for (const entry of entries) {
9740
- const fullPath = path3.join(currentDir, entry.name);
9741
- const walkEntry = {
9742
- path: fullPath,
9743
- name: entry.name,
9744
- isDirectory: entry.isDirectory(),
9745
- depth,
9746
- category
9747
- };
9748
- if (!filter || filter(walkEntry)) {
9749
- results.push(walkEntry);
9750
- }
9751
- if (entry.isDirectory()) {
9752
- recurse(fullPath, depth + 1, entry.name);
9753
- }
10008
+ function lookupProfileBundle(input, name) {
10009
+ const { layers } = input;
10010
+ const lookupOrder = [
10011
+ layers.customLocal,
10012
+ layers.custom,
10013
+ layers.userLocal,
10014
+ layers.user,
10015
+ input.allowProjectProfiles ? layers.project : null
10016
+ ];
10017
+ for (const source of lookupOrder) {
10018
+ const bundle = source?.config.profiles?.[name];
10019
+ if (source && bundle !== undefined) {
10020
+ return { bundle, definingSource: source };
9754
10021
  }
9755
10022
  }
9756
- recurse(rootDir, 0);
9757
- return results;
10023
+ return;
9758
10024
  }
9759
-
9760
- // src/lib/agents.ts
9761
- function findAgentsInDir(dir, maxDepth = 2) {
9762
- const entries = walkDir(dir, {
9763
- maxDepth,
9764
- filter: (e) => !e.isDirectory && isDiscoverableMarkdown(e.name)
9765
- });
9766
- return entries.map((entry) => ({
9767
- name: entry.name.replace(/\.md$/, ""),
9768
- file: entry.path,
9769
- category: entry.category
9770
- }));
10025
+ function trustedDefaultProfileName(input) {
10026
+ const userDefault = lastDefined([input.layers.user, input.layers.userLocal], "profile");
10027
+ return typeof userDefault === "string" ? userDefault : undefined;
9771
10028
  }
9772
- function extractAgentFrontmatter(content) {
9773
- const { data, parseError, body } = parseFrontmatter(content);
9774
- if (parseError) {
9775
- return { name: "", description: "", prompt: body.trim() };
10029
+ function selectorSourceLabel(source) {
10030
+ return source === "environment" ? "SYSTEMATIC_PROFILE" : `${source} config`;
10031
+ }
10032
+ function resolveActiveProfile(input) {
10033
+ const selection = resolveProfileSelector(input);
10034
+ if (selection === null)
10035
+ return NO_PROFILE_SELECTION;
10036
+ if (selection.value === null) {
10037
+ return {
10038
+ activeProfile: null,
10039
+ profileSelectorSource: selection.source,
10040
+ profileFallback: null,
10041
+ bundle: null,
10042
+ bundleSource: null
10043
+ };
10044
+ }
10045
+ const requested = selection.value;
10046
+ const requestedLookup = lookupProfileBundle(input, requested);
10047
+ if (requestedLookup !== undefined) {
10048
+ return {
10049
+ activeProfile: requested,
10050
+ profileSelectorSource: selection.source,
10051
+ profileFallback: null,
10052
+ bundle: requestedLookup.bundle,
10053
+ bundleSource: requestedLookup.definingSource
10054
+ };
10055
+ }
10056
+ const trustedDefault = trustedDefaultProfileName(input);
10057
+ const fallbackLookup = trustedDefault !== undefined && trustedDefault !== requested ? lookupProfileBundle(input, trustedDefault) : undefined;
10058
+ if (fallbackLookup !== undefined && trustedDefault !== undefined) {
10059
+ input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}" (selected by ${selectorSourceLabel(selection.source)}) is not defined in \`profiles\`; falling back to your default profile "${sanitizeDiagnosticText(trustedDefault)}". See ${PROFILE_DOCS_URL} for how to define a profile.`);
10060
+ return {
10061
+ activeProfile: trustedDefault,
10062
+ profileSelectorSource: selection.source,
10063
+ profileFallback: { requested, usedDefault: trustedDefault },
10064
+ bundle: fallbackLookup.bundle,
10065
+ bundleSource: fallbackLookup.definingSource
10066
+ };
9776
10067
  }
10068
+ const sourceNote = selection.source === "user" ? "" : ` (selected by ${selectorSourceLabel(selection.source)})`;
10069
+ const alsoMissingNote = trustedDefault !== undefined && trustedDefault !== requested ? ` Your default profile "${sanitizeDiagnosticText(trustedDefault)}" is also not defined in \`profiles\`.` : trustedDefault === undefined ? " No default profile is configured (`profile` in your user config)." : "";
10070
+ input.warningSink(`[systematic] profile "${sanitizeDiagnosticText(requested)}"${sourceNote} is not defined in \`profiles\`; using base configuration (no profile).${alsoMissingNote} See ${PROFILE_DOCS_URL} for how to define a profile.`);
9777
10071
  return {
9778
- name: extractString(data, "name"),
9779
- description: extractString(data, "description"),
9780
- prompt: body.trim(),
9781
- model: extractNonEmptyString(data, "model"),
9782
- variant: extractNonEmptyString(data, "variant"),
9783
- temperature: extractNumber(data, "temperature"),
9784
- top_p: extractNumber(data, "top_p"),
9785
- tools: isToolsMap(data.tools) ? data.tools : undefined,
9786
- disable: extractBoolean(data, "disable"),
9787
- mode: isAgentMode(data.mode) ? data.mode : undefined,
9788
- color: extractNonEmptyString(data, "color"),
9789
- steps: extractNumber(data, "steps"),
9790
- hidden: extractBoolean(data, "hidden") ?? undefined,
9791
- permission: normalizePermission(data.permission)
10072
+ activeProfile: null,
10073
+ profileSelectorSource: selection.source,
10074
+ profileFallback: { requested, usedDefault: null },
10075
+ bundle: null,
10076
+ bundleSource: null
9792
10077
  };
9793
10078
  }
9794
-
9795
- // src/lib/commands.ts
9796
- function findCommandsInDir(dir, maxDepth = 2) {
9797
- const entries = walkDir(dir, {
9798
- maxDepth,
9799
- filter: (e) => !e.isDirectory && isDiscoverableMarkdown(e.name)
9800
- });
9801
- return entries.map((entry) => {
9802
- const baseName = entry.name.replace(/\.md$/, "");
9803
- const commandName = entry.category ? `/${entry.category}:${baseName}` : `/${baseName}`;
9804
- return {
9805
- name: commandName,
9806
- file: entry.path,
9807
- category: entry.category
9808
- };
9809
- });
10079
+ function loadConfig(projectDir, options) {
10080
+ return loadConfigWithSources(projectDir, options).config;
9810
10081
  }
9811
- function extractCommandFrontmatter(content) {
9812
- const { data, parseError } = parseFrontmatter(content);
9813
- if (parseError) {
9814
- return {
9815
- name: "",
9816
- description: "",
9817
- argumentHint: "",
9818
- agent: undefined,
9819
- model: undefined,
9820
- subtask: undefined
9821
- };
10082
+ var USER_LEVEL_SLOT = {
10083
+ user: "user",
10084
+ "user.local": "userLocal",
10085
+ custom: "custom",
10086
+ "custom.local": "customLocal"
10087
+ };
10088
+ function resolveAliasedConfigFiles(paths, includeProject) {
10089
+ if (!includeProject)
10090
+ return [];
10091
+ const candidates = [
10092
+ ["custom", paths.customConfig],
10093
+ ["custom.local", paths.customLocalConfig],
10094
+ ["user", paths.userConfig],
10095
+ ["user.local", paths.userLocalConfig]
10096
+ ];
10097
+ const project = resolveConfigSourcePath(paths.projectConfig);
10098
+ return candidates.flatMap(([layer, file]) => file !== undefined && resolveConfigSourcePath(file) === project ? [{ layer, path: file }] : []);
10099
+ }
10100
+ function createAliasStripTracker(warningSink, aliasedFile) {
10101
+ if (aliasedFile === undefined) {
10102
+ return { sink: warningSink, buffered: [] };
9822
10103
  }
9823
- const argumentHintRaw = extractString(data, "argument-hint");
10104
+ const buffered = [];
9824
10105
  return {
9825
- name: extractString(data, "name"),
9826
- description: extractString(data, "description"),
9827
- argumentHint: argumentHintRaw.replace(/^["']|["']$/g, ""),
9828
- agent: extractNonEmptyString(data, "agent"),
9829
- model: extractNonEmptyString(data, "model"),
9830
- subtask: extractBoolean(data, "subtask")
10106
+ sink: (message) => {
10107
+ buffered.push(message);
10108
+ },
10109
+ buffered
9831
10110
  };
9832
10111
  }
9833
-
9834
- // src/lib/discovered-skills.ts
9835
- import fs6 from "fs";
9836
- import path5 from "path";
9837
-
9838
- // src/lib/skills.ts
9839
- import fs5 from "fs";
9840
- import path4 from "path";
9841
- function parseMetadata(data) {
9842
- const metadataRaw = data.metadata;
9843
- if (!isRecord(metadataRaw)) {
10112
+ function isAliasNoticeEligible(input) {
10113
+ return input.aliasedFile !== undefined && input.bufferedCount > 0;
10114
+ }
10115
+ function emitAliasFailureDiagnostics(input) {
10116
+ if (!isAliasNoticeEligible({
10117
+ aliasedFile: input.aliasedFile,
10118
+ bufferedCount: input.buffered.length
10119
+ })) {
9844
10120
  return;
9845
10121
  }
9846
- const entries = Object.entries(metadataRaw);
9847
- if (!entries.every(([, v]) => typeof v === "string")) {
10122
+ if (input.projectLoaded && input.aliasLoaded)
10123
+ return;
10124
+ for (const message of input.buffered)
10125
+ input.warningSink(message);
10126
+ }
10127
+ function buildAliasSuccessNotice(input) {
10128
+ if (!isAliasNoticeEligible({
10129
+ aliasedFile: input.aliasedFile,
10130
+ bufferedCount: input.bufferedCount
10131
+ }) || !(input.projectLoaded && input.aliasLoaded) || input.aliasedFile === undefined) {
9848
10132
  return;
9849
10133
  }
9850
- return Object.fromEntries(entries);
10134
+ const { layer, path: aliasedPath } = input.aliasedFile;
10135
+ const trust = LAYER_TRUST[layer];
10136
+ const projectConfigPath = input.projectConfigPath;
10137
+ const warningSink = input.warningSink;
10138
+ return () => {
10139
+ warningSink(`[systematic] project config (${sanitizeDiagnosticText(projectConfigPath)}) and ${layer} config (${sanitizeDiagnosticText(aliasedPath)}) resolve to the same file; protected fields stripped from the project pass (security-overlay fields, \`profiles\`, \`allow_project_profiles\`) apply through the ${trust}-trust pass instead.`);
10140
+ };
9851
10141
  }
9852
- function extractFrontmatterFromContent(content) {
9853
- const { data, parseError } = parseFrontmatter(content);
9854
- if (parseError) {
9855
- return { name: "", description: "" };
10142
+ var REMOVED_SETTINGS_DOCS_URL = "https://fro.bot/systematic/reference/configuration#removed-settings";
10143
+ function warnRemovedKeys(sources, warningSink) {
10144
+ const reported = new Set;
10145
+ for (const source of sources) {
10146
+ for (const key of source.removedKeys) {
10147
+ const identity = `${source.canonicalPath}\x00${key}`;
10148
+ if (reported.has(identity))
10149
+ continue;
10150
+ reported.add(identity);
10151
+ warningSink(`[systematic] \`${key}\` in config (${sanitizeDiagnosticText(source.path)}) has been removed and is ignored. Delete it from that file to silence this warning. See ${REMOVED_SETTINGS_DOCS_URL} for details.`);
10152
+ }
9856
10153
  }
9857
- const metadata = parseMetadata(data);
9858
- const argumentHintRaw = extractNonEmptyString(data, "argument-hint");
9859
- const argumentHint = argumentHintRaw?.replace(/^["']|["']$/g, "") || undefined;
10154
+ }
10155
+ function createInvalidFileReporter(warningSink) {
10156
+ const reported = new Set;
10157
+ return (filePath, code) => {
10158
+ const identity = `${resolveConfigSourcePath(filePath)}\x00${code}`;
10159
+ if (reported.has(identity))
10160
+ return;
10161
+ reported.add(identity);
10162
+ warningSink(`[systematic] config file (${sanitizeDiagnosticText(filePath)}) is invalid (${code}) and was not loaded.`);
10163
+ };
10164
+ }
10165
+ function reassignLayer(loaded, layer) {
10166
+ const trust = LAYER_TRUST[layer];
9860
10167
  return {
9861
- name: extractString(data, "name"),
9862
- description: extractString(data, "description"),
9863
- license: extractNonEmptyString(data, "license"),
9864
- compatibility: extractNonEmptyString(data, "compatibility"),
9865
- metadata,
9866
- disableModelInvocation: extractBoolean(data, "disable-model-invocation"),
9867
- userInvocable: extractBoolean(data, "user-invocable"),
9868
- subtask: data.context === "fork" ? true : extractBoolean(data, "subtask") ?? undefined,
9869
- agent: extractNonEmptyString(data, "agent"),
9870
- model: extractNonEmptyString(data, "model"),
9871
- argumentHint: argumentHint !== "" ? argumentHint : undefined,
9872
- allowedTools: extractNonEmptyString(data, "allowed-tools")
10168
+ metadata: { ...loaded.metadata, kind: trust },
10169
+ source: loaded.source && { ...loaded.source, layer, trust }
9873
10170
  };
9874
10171
  }
9875
- function extractFrontmatter(filePath) {
9876
- try {
9877
- const content = fs5.readFileSync(filePath, "utf8");
9878
- return extractFrontmatterFromContent(content);
9879
- } catch {
9880
- return { name: "", description: "" };
9881
- }
10172
+ function loadUserLevelSources(paths, context) {
10173
+ const loadedByRealFile = new Map;
10174
+ const load = (layer, filePath) => {
10175
+ if (filePath === undefined) {
10176
+ return {
10177
+ metadata: { kind: LAYER_TRUST[layer], presence: "absent" },
10178
+ source: null
10179
+ };
10180
+ }
10181
+ const realFile = resolveConfigSourcePath(filePath);
10182
+ const shared = loadedByRealFile.get(realFile);
10183
+ if (shared)
10184
+ return reassignLayer(shared, layer);
10185
+ const loaded = loadConfigSource({
10186
+ ...context,
10187
+ filePath,
10188
+ layer,
10189
+ allowProjectProfiles: false
10190
+ });
10191
+ loadedByRealFile.set(realFile, loaded);
10192
+ return loaded;
10193
+ };
10194
+ const user = load("user", paths.userConfig);
10195
+ const userLocal = load("user.local", paths.userLocalConfig);
10196
+ const custom = load("custom", paths.customConfig);
10197
+ const customLocal = load("custom.local", paths.customLocalConfig);
10198
+ const allowProjectProfiles = lastDefined([user.source, userLocal.source, custom.source, customLocal.source], "allow_project_profiles") ?? DEFAULT_CONFIG.allow_project_profiles;
10199
+ return { user, userLocal, custom, customLocal, allowProjectProfiles };
10200
+ }
10201
+ function emitProjectLocationWarnings(paths, warningSink) {
10202
+ if (paths.ignoredProjectConfig !== undefined) {
10203
+ warningSink(`[systematic] project config (${sanitizeDiagnosticText(paths.projectConfig)}) takes precedence over (${sanitizeDiagnosticText(paths.ignoredProjectConfig)}), which is ignored; the two files are never merged.`);
10204
+ }
10205
+ if (paths.startDirProjectConfig !== undefined) {
10206
+ warningSink(startDirProjectWarning(paths.startDirProjectConfig, paths.projectRoot, paths.projectConfig, sanitizeDiagnosticText));
10207
+ }
10208
+ }
10209
+ function buildOverlaySources(profileEntry, bundleSourceTrust, layers) {
10210
+ const ordered = profileEntry !== null && bundleSourceTrust === "project" ? [
10211
+ profileEntry,
10212
+ layers.user,
10213
+ layers.userLocal,
10214
+ layers.project,
10215
+ layers.custom,
10216
+ layers.customLocal
10217
+ ] : [
10218
+ layers.user,
10219
+ profileEntry,
10220
+ layers.userLocal,
10221
+ layers.project,
10222
+ layers.custom,
10223
+ layers.customLocal
10224
+ ];
10225
+ return ordered.filter((source) => source !== null);
9882
10226
  }
9883
- function findSkillsInDir(dir, maxDepth = 3) {
9884
- const skills = [];
9885
- const entries = walkDir(dir, {
9886
- maxDepth,
9887
- filter: (e) => e.isDirectory
10227
+ function buildProfileEntry(profileSelection) {
10228
+ const { bundle, bundleSource, activeProfile } = profileSelection;
10229
+ if (!bundle || !bundleSource || typeof activeProfile !== "string")
10230
+ return null;
10231
+ return {
10232
+ kind: "profile-bundle",
10233
+ canonicalPath: bundleSource.canonicalPath,
10234
+ path: bundleSource.path,
10235
+ config: { agents: bundle.agents, categories: bundle.categories },
10236
+ protectedFields: [],
10237
+ profileName: activeProfile,
10238
+ bundleTrust: bundleSource.trust
10239
+ };
10240
+ }
10241
+ function unionDisabledList(sources, key) {
10242
+ return sources.reduce((merged, source) => mergeArraysUnique(merged, source.config[key]), mergeArraysUnique(DEFAULT_CONFIG[key], undefined));
10243
+ }
10244
+ function mergeBootstrap(sources) {
10245
+ const merged = { ...DEFAULT_CONFIG.bootstrap };
10246
+ for (const source of sources)
10247
+ Object.assign(merged, source.config.bootstrap);
10248
+ return merged;
10249
+ }
10250
+ function loadConfigWithSources(projectDir, options) {
10251
+ const includeProject = options?.includeProject ?? true;
10252
+ const invalidSource = options?.invalidSource ?? "throw";
10253
+ const paths = getConfigPaths(projectDir, options);
10254
+ const warningSink = options?.warningSink ?? console.warn;
10255
+ const reportInvalid = createInvalidFileReporter(warningSink);
10256
+ if (includeProject)
10257
+ emitProjectLocationWarnings(paths, warningSink);
10258
+ const aliasedFiles = resolveAliasedConfigFiles(paths, includeProject);
10259
+ const aliasedFile = aliasedFiles[0];
10260
+ const projectStrip = createAliasStripTracker(warningSink, aliasedFile);
10261
+ const boundedProjectStrip = createBoundedStripWarningSink(projectStrip.sink);
10262
+ const userLevel = loadUserLevelSources(paths, {
10263
+ invalidSource,
10264
+ reportInvalid,
10265
+ warningSink
9888
10266
  });
9889
- for (const entry of entries) {
9890
- const skillFile = path4.join(entry.path, "SKILL.md");
9891
- if (fs5.existsSync(skillFile)) {
9892
- const frontmatter = extractFrontmatter(skillFile);
9893
- skills.push({
9894
- path: entry.path,
9895
- skillFile,
9896
- name: frontmatter.name || entry.name,
9897
- description: frontmatter.description || "",
9898
- license: frontmatter.license,
9899
- compatibility: frontmatter.compatibility,
9900
- metadata: frontmatter.metadata,
9901
- disableModelInvocation: frontmatter.disableModelInvocation,
9902
- userInvocable: frontmatter.userInvocable,
9903
- subtask: frontmatter.subtask,
9904
- agent: frontmatter.agent,
9905
- model: frontmatter.model,
9906
- argumentHint: frontmatter.argumentHint,
9907
- allowedTools: frontmatter.allowedTools
9908
- });
10267
+ const { allowProjectProfiles } = userLevel;
10268
+ const aliasLoaded = aliasedFiles.some(({ layer }) => userLevel[USER_LEVEL_SLOT[layer]].source !== null);
10269
+ const project = includeProject ? loadConfigSource({
10270
+ filePath: paths.projectConfig,
10271
+ layer: "project",
10272
+ invalidSource,
10273
+ warningSink: boundedProjectStrip.sink,
10274
+ reportInvalid,
10275
+ allowProjectProfiles
10276
+ }) : {
10277
+ metadata: { kind: "project", presence: "absent" },
10278
+ source: null
10279
+ };
10280
+ const projectSource = project.source;
10281
+ emitTopLevelProtectedFieldWarning(projectSource, "profiles", `\`profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. Its bundles are not selectable even if this project also sets \`profile\`.`, boundedProjectStrip.sink);
10282
+ emitTopLevelProtectedFieldWarning(projectSource, "allow_project_profiles", `\`allow_project_profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`, boundedProjectStrip.sink);
10283
+ emitProjectSearchProtectedWarnings(projectSource, boundedProjectStrip.sink);
10284
+ const suppressedStripCount = boundedProjectStrip.suppressedCount();
10285
+ if (suppressedStripCount > 0) {
10286
+ projectStrip.sink(`[systematic] ${suppressedStripCount} additional project-config protected-field warning(s) in (${sanitizeDiagnosticText(paths.projectConfig)}) were suppressed.`);
10287
+ }
10288
+ emitAliasFailureDiagnostics({
10289
+ aliasedFile,
10290
+ buffered: projectStrip.buffered,
10291
+ aliasLoaded,
10292
+ projectLoaded: project.source !== null,
10293
+ warningSink
10294
+ });
10295
+ const emitAliasSuccessNotice = buildAliasSuccessNotice({
10296
+ aliasedFile,
10297
+ bufferedCount: projectStrip.buffered.length,
10298
+ aliasLoaded,
10299
+ projectConfigPath: paths.projectConfig,
10300
+ projectLoaded: project.source !== null,
10301
+ warningSink
10302
+ });
10303
+ const layers = {
10304
+ user: userLevel.user.source,
10305
+ userLocal: userLevel.userLocal.source,
10306
+ project: projectSource,
10307
+ custom: userLevel.custom.source,
10308
+ customLocal: userLevel.customLocal.source
10309
+ };
10310
+ const sources = chainOf(layers);
10311
+ warnRemovedKeys(sources, warningSink);
10312
+ const warned = new Set;
10313
+ const mergedSearch = mergeSearchSettings(["user", "userLocal", "custom", "customLocal"].flatMap((slot) => {
10314
+ const source = layers[slot];
10315
+ return source?.search && isUserLevelLayer(source.layer) ? [{ ...source.search, layer: source.layer }] : [];
10316
+ }));
10317
+ assertAllProfileBundlesAreValid([
10318
+ layers.user,
10319
+ layers.userLocal,
10320
+ layers.custom,
10321
+ layers.customLocal,
10322
+ layers.project
10323
+ ].map((source) => source?.config));
10324
+ const profileSelection = resolveActiveProfile({
10325
+ layers,
10326
+ allowProjectProfiles,
10327
+ warningSink
10328
+ });
10329
+ const profileEntry = buildProfileEntry(profileSelection);
10330
+ const overlaySources = buildOverlaySources(profileEntry, profileSelection.bundleSource?.trust, layers);
10331
+ const mergedOverlays = mergeOverlaySources(overlaySources);
10332
+ const mergedPiSubagentsOverlays = mergePiSubagentsOverlaySources(sources);
10333
+ const droppedCategories = Object.keys(mergedOverlays.categories).filter((name) => REMOVED_AGENT_CATEGORIES_SET.has(name));
10334
+ warnDroppedNames(droppedCategories, "categories", warned, "v3.0.0", warningSink);
10335
+ const droppedCategorySet = new Set(droppedCategories);
10336
+ const overlays = droppedCategorySet.size === 0 ? mergedOverlays : {
10337
+ ...mergedOverlays,
10338
+ categories: Object.fromEntries(Object.entries(mergedOverlays.categories).filter(([key]) => !droppedCategorySet.has(key)))
10339
+ };
10340
+ const mergedDisabledAgents = unionDisabledList(sources, "disabled_agents");
10341
+ assertRoutingInvariants(overlays, mergedPiSubagentsOverlays, new Set(mergedDisabledAgents), warningSink);
10342
+ const result = {
10343
+ disabled_skills: unionDisabledList(sources, "disabled_skills"),
10344
+ disabled_agents: mergedDisabledAgents,
10345
+ disabled_commands: unionDisabledList(sources, "disabled_commands"),
10346
+ bootstrap: mergeBootstrap(sources),
10347
+ agents: overlayValues(overlays.agents),
10348
+ categories: overlayValues(overlays.categories),
10349
+ pi_subagents: {
10350
+ categories: overlayValues(mergedPiSubagentsOverlays.categories),
10351
+ agents: overlayValues(mergedPiSubagentsOverlays.agents)
10352
+ },
10353
+ skills_as_commands: lastDefined(sources, "skills_as_commands") ?? DEFAULT_CONFIG.skills_as_commands,
10354
+ allow_project_profiles: allowProjectProfiles,
10355
+ ...mergedSearch.settings && { search: mergedSearch.settings },
10356
+ ...mergedSearch.unreadable && { searchUnreadable: true }
10357
+ };
10358
+ const droppedSkills = computeDroppedNames(result.disabled_skills, CURRENT_SKILL_NAMES_SET);
10359
+ warnDroppedNames(droppedSkills, "disabled_skills", warned, undefined, warningSink);
10360
+ const droppedAgents = computeDroppedNames(result.disabled_agents, CURRENT_AGENT_NAMES_SET);
10361
+ warnDroppedNames(droppedAgents, "disabled_agents", warned, undefined, warningSink);
10362
+ const droppedSkillSet = new Set(droppedSkills);
10363
+ const droppedAgentSet = new Set(droppedAgents);
10364
+ const effectiveConfig = droppedSkillSet.size === 0 && droppedAgentSet.size === 0 ? result : {
10365
+ ...result,
10366
+ disabled_skills: result.disabled_skills.filter((n) => !droppedSkillSet.has(n)),
10367
+ disabled_agents: result.disabled_agents.filter((n) => !droppedAgentSet.has(n))
10368
+ };
10369
+ emitAliasSuccessNotice?.();
10370
+ return {
10371
+ config: effectiveConfig,
10372
+ metadata: buildConfigObservationMetadata({
10373
+ custom: foldKindMetadata("custom", [
10374
+ userLevel.custom.metadata,
10375
+ userLevel.customLocal.metadata
10376
+ ]),
10377
+ profileSelection,
10378
+ project: project.metadata,
10379
+ sources: foldSiblingSources(sources),
10380
+ user: foldKindMetadata("user", [
10381
+ userLevel.user.metadata,
10382
+ userLevel.userLocal.metadata
10383
+ ])
10384
+ }),
10385
+ overlays,
10386
+ piSubagentsOverlays: mergedPiSubagentsOverlays,
10387
+ activeProfileSourcePath: profileSelection.bundleSource?.path ?? null
10388
+ };
10389
+ }
10390
+ function isUserLevelLayer(layer) {
10391
+ return layer !== "project";
10392
+ }
10393
+ function foldSiblingSources(sources) {
10394
+ const byTrust = new Map;
10395
+ for (const source of sources) {
10396
+ byTrust.set(source.trust, [...byTrust.get(source.trust) ?? [], source]);
10397
+ }
10398
+ return Array.from(byTrust.values(), (files) => ({
10399
+ trust: files[0]?.trust ?? "user",
10400
+ canonicalPaths: files.map((file) => file.canonicalPath),
10401
+ configs: files.map((file) => file.config),
10402
+ protectedFields: files.flatMap((file) => file.protectedFields)
10403
+ }));
10404
+ }
10405
+ function foldKindMetadata(kind, files) {
10406
+ const invalid = files.find((file) => file.presence === "invalid");
10407
+ if (invalid)
10408
+ return invalid;
10409
+ return files.some((file) => file.presence === "present") ? { kind, presence: "present" } : { kind, presence: "absent" };
10410
+ }
10411
+ function buildConfigObservationMetadata(summary) {
10412
+ const authorities = [];
10413
+ const sourceConfigs = new Map;
10414
+ const sourcePaths = new Map;
10415
+ for (const source of summary.sources) {
10416
+ sourceConfigs.set(source.trust, source.configs);
10417
+ sourcePaths.set(source.trust, source.canonicalPaths);
10418
+ }
10419
+ const firstDefinedSource = (fieldPath, candidates) => {
10420
+ for (const sourceKind of candidates) {
10421
+ const configs = sourceConfigs.get(sourceKind);
10422
+ if (configs?.some((config) => hasConfigField(config, fieldPath))) {
10423
+ return { fieldPath, sourceKind };
10424
+ }
9909
10425
  }
10426
+ return;
10427
+ };
10428
+ const fieldCandidates = {
10429
+ "bootstrap.enabled": ["custom", "project", "user"],
10430
+ "bootstrap.file": ["custom", "project", "user"],
10431
+ skills_as_commands: ["custom", "project", "user"]
10432
+ };
10433
+ for (const fieldPath of CONFIG_AUTHORITY_FIELD_PATHS) {
10434
+ const authority = firstDefinedSource(fieldPath, fieldCandidates[fieldPath]);
10435
+ if (authority)
10436
+ authorities.push(authority);
9910
10437
  }
9911
- return skills;
10438
+ const protectedFields = collectVisibleProtectedFields(summary.sources);
10439
+ const sources = dedupeSourceMetadata([summary.custom, summary.project, summary.user], sourcePaths);
10440
+ return {
10441
+ authorities: sortAuthorities(authorities),
10442
+ protectedFields: sortProtectedFields(protectedFields),
10443
+ sources,
10444
+ activeProfile: summary.profileSelection.activeProfile,
10445
+ profileSelectorSource: summary.profileSelection.profileSelectorSource,
10446
+ profileFallback: summary.profileSelection.profileFallback
10447
+ };
9912
10448
  }
9913
-
9914
- // src/lib/discovered-skills.ts
9915
- var SKILL_NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
9916
- function isValidSkillName(name) {
9917
- return name.length >= 1 && name.length <= 64 && SKILL_NAME_REGEX.test(name);
10449
+ function collectVisibleProtectedFields(sources) {
10450
+ const projectSource = sources.find((source) => source.trust === "project");
10451
+ const userLevelPaths = new Set(sources.filter((source) => source.trust !== "project").flatMap((source) => source.canonicalPaths));
10452
+ const projectAppliedViaUserLevel = projectSource?.canonicalPaths.some((file) => userLevelPaths.has(file)) ?? false;
10453
+ return sources.flatMap((source) => projectAppliedViaUserLevel && source.trust === "project" ? [] : source.protectedFields);
9918
10454
  }
9919
- function findGitWorktreeRoot(startDir) {
9920
- let current = path5.resolve(startDir);
9921
- while (true) {
9922
- try {
9923
- if (fs6.existsSync(path5.join(current, ".git"))) {
9924
- return current;
9925
- }
9926
- } catch {
9927
- return null;
9928
- }
9929
- const parent = path5.dirname(current);
9930
- if (parent === current)
9931
- return null;
9932
- current = parent;
10455
+ function dedupeSourceMetadata(metadata, sourcePaths) {
10456
+ const priority = ["custom", "user", "project"];
10457
+ const seen = new Set;
10458
+ const kept = new Set;
10459
+ for (const kind of priority) {
10460
+ const files = sourcePaths.get(kind) ?? [];
10461
+ const presence = metadata.find((source) => source.kind === kind)?.presence;
10462
+ const redundant = files.length > 0 && files.every((file) => seen.has(file)) && presence !== "invalid";
10463
+ if (redundant)
10464
+ continue;
10465
+ for (const file of files)
10466
+ seen.add(file);
10467
+ kept.add(kind);
9933
10468
  }
10469
+ return metadata.filter((source) => kept.has(source.kind));
9934
10470
  }
9935
- function upWalk(targets, start, stop) {
9936
- const results = [];
9937
- let current = path5.resolve(start);
9938
- const resolvedStop = stop === undefined ? undefined : path5.resolve(stop);
9939
- while (true) {
9940
- for (const target of targets) {
9941
- const candidate = path5.join(current, target);
9942
- try {
9943
- if (fs6.existsSync(candidate)) {
9944
- results.push(candidate);
9945
- }
9946
- } catch {}
9947
- }
9948
- if (resolvedStop !== undefined && current === resolvedStop)
9949
- break;
9950
- const parent = path5.dirname(current);
9951
- if (parent === current)
9952
- break;
9953
- current = parent;
9954
- }
9955
- return results;
10471
+ function hasConfigField(config, fieldPath) {
10472
+ const [topLevel, nested] = fieldPath.split(".");
10473
+ if (nested === undefined)
10474
+ return config[topLevel] !== undefined;
10475
+ const value = config[topLevel];
10476
+ return isRecord3(value) && value[nested] !== undefined;
9956
10477
  }
9957
- function uniqueStrings(values) {
9958
- return Array.from(new Set(values));
10478
+ function sortAuthorities(authorities) {
10479
+ return [...authorities].sort((left, right) => left.fieldPath === right.fieldPath ? left.sourceKind.localeCompare(right.sourceKind) : left.fieldPath.localeCompare(right.fieldPath));
9959
10480
  }
9960
- function buildOpencodeConfigDirs(startDir, homeDir, gitRoot, globalConfigDir, opencodeConfigDirOverride) {
9961
- const dirs = [globalConfigDir];
9962
- dirs.push(...upWalk([".opencode"], startDir, gitRoot ?? startDir));
9963
- dirs.push(...upWalk([".opencode"], homeDir, homeDir));
9964
- if (opencodeConfigDirOverride !== undefined) {
9965
- dirs.push(opencodeConfigDirOverride);
9966
- }
9967
- return uniqueStrings(dirs);
10481
+ function sortProtectedFields(fields) {
10482
+ return [...fields].sort((left, right) => left.fieldPath === right.fieldPath ? left.sourceKind.localeCompare(right.sourceKind) : left.fieldPath.localeCompare(right.fieldPath));
9968
10483
  }
9969
- function globSkillFiles(rootDir, subdirNames) {
9970
- const results = [];
9971
- for (const subdirName of subdirNames) {
9972
- const scanRoot = path5.join(rootDir, subdirName);
9973
- try {
9974
- if (!fs6.existsSync(scanRoot))
9975
- continue;
9976
- const entries = walkDir(scanRoot, {
9977
- maxDepth: 10,
9978
- filter: (entry) => entry.name === "SKILL.md"
9979
- });
9980
- for (const entry of entries) {
9981
- results.push(entry.path);
9982
- }
9983
- } catch {}
9984
- }
9985
- return results;
10484
+ function isAgentDisabled(disabledAgents, agentOverlays, category, key) {
10485
+ const qualifiedId = category ? `${category}/${key}` : key;
10486
+ if (disabledAgents.has(key) || disabledAgents.has(qualifiedId))
10487
+ return true;
10488
+ return agentOverlays[key]?.value.disable === true || agentOverlays[qualifiedId]?.value.disable === true;
9986
10489
  }
9987
- function toDiscoveredSkill(skillPath, rootId, onIssue) {
9988
- let content;
9989
- try {
9990
- content = fs6.readFileSync(skillPath, "utf8");
9991
- } catch {
9992
- onIssue?.("read-failed");
9993
- return;
10490
+ function collectRoutingTargets(overlays, disabledAgents = new Set) {
10491
+ const targets = new Map;
10492
+ const addTarget = (agentKey, category) => {
10493
+ if (isAgentDisabled(disabledAgents, overlays.agents, category, agentKey)) {
10494
+ return;
10495
+ }
10496
+ targets.set(`${category}/${agentKey}`, { agentKey, category });
10497
+ };
10498
+ for (const rawKey of Object.keys(overlays.agents)) {
10499
+ const separatorIndex = rawKey.indexOf("/");
10500
+ if (separatorIndex === -1) {
10501
+ const category = BUNDLED_AGENT_CATEGORY_BY_KEY.get(rawKey);
10502
+ if (category !== undefined)
10503
+ addTarget(rawKey, category);
10504
+ continue;
10505
+ }
10506
+ const category = rawKey.slice(0, separatorIndex);
10507
+ const agentKey = rawKey.slice(separatorIndex + 1);
10508
+ if (BUNDLED_AGENT_CATEGORY_BY_KEY.get(agentKey) === category) {
10509
+ addTarget(agentKey, category);
10510
+ }
9994
10511
  }
9995
- if (parseFrontmatter(content).parseError) {
9996
- onIssue?.("source-invalid");
9997
- return;
10512
+ for (const categoryKey of Object.keys(overlays.categories)) {
10513
+ const agentKeys = BUNDLED_AGENT_KEYS_BY_CATEGORY.get(categoryKey);
10514
+ if (agentKeys === undefined)
10515
+ continue;
10516
+ for (const agentKey of agentKeys)
10517
+ addTarget(agentKey, categoryKey);
9998
10518
  }
9999
- const frontmatter = extractFrontmatterFromContent(content);
10000
- const name = frontmatter.name;
10001
- if (!name || !isValidSkillName(name)) {
10002
- onIssue?.("source-invalid");
10003
- return;
10519
+ return Array.from(targets.values());
10520
+ }
10521
+ function assertProfileBundleCategoryKeysAreBundledCategories(profileName, bundle) {
10522
+ for (const categoryKey of Object.keys(bundle.categories ?? {})) {
10523
+ if (!BUNDLED_AGENT_KEYS_BY_CATEGORY.has(categoryKey)) {
10524
+ throw new Error(`Invalid Systematic config: profiles.${profileName}.categories.${categoryKey} is not a bundled agent category. Valid categories: ${Array.from(BUNDLED_AGENT_KEYS_BY_CATEGORY.keys()).join(", ")}`);
10525
+ }
10004
10526
  }
10005
- return {
10006
- name,
10007
- description: frontmatter.description,
10008
- frontmatter,
10009
- body: parseFrontmatter(content).body,
10010
- skillPath,
10011
- root: rootId
10012
- };
10013
10527
  }
10014
- function discoverSkills(options) {
10015
- const { startDir, homeDir, configDir, onIssue, opencodeConfigDirOverride } = options;
10016
- const globalConfigDir = configDir ?? path5.join(homeDir, ".config/opencode");
10017
- const gitRoot = findGitWorktreeRoot(startDir);
10018
- const byName = new Map;
10019
- function upsertAll(skillPaths, rootId) {
10020
- for (const skillPath of skillPaths) {
10021
- const skill = toDiscoveredSkill(skillPath, rootId, onIssue);
10022
- if (skill)
10023
- byName.set(skill.name, skill);
10528
+ function assertAllProfileBundlesAreValid(configs) {
10529
+ for (const config of configs) {
10530
+ for (const [profileName, bundle] of Object.entries(config?.profiles ?? {})) {
10531
+ assertProfileBundleCategoryKeysAreBundledCategories(profileName, bundle);
10024
10532
  }
10025
10533
  }
10026
- upsertAll(globSkillFiles(homeDir, [".claude/skills"]), "global-claude");
10027
- upsertAll(globSkillFiles(homeDir, [".agents/skills"]), "global-agents");
10028
- const externalLevels = upWalk([".claude", ".agents"], startDir, gitRoot ?? startDir);
10029
- for (const levelDir of externalLevels) {
10030
- const isClaudeDir = path5.basename(levelDir) === ".claude";
10031
- const parentDir = path5.dirname(levelDir);
10032
- const subdirGlob = isClaudeDir ? ".claude/skills" : ".agents/skills";
10033
- const rootId = isClaudeDir ? "project-claude" : "project-agents";
10034
- upsertAll(globSkillFiles(parentDir, [subdirGlob]), rootId);
10534
+ }
10535
+ function assertRoutingInvariants(overlays, piSubagentsOverlays, disabledAgents, warningSink) {
10536
+ const targets = collectRoutingTargets(overlays, disabledAgents);
10537
+ for (const target of targets) {
10538
+ const resolution = resolveRouting({
10539
+ overlays,
10540
+ piSubagentsOverlays,
10541
+ target,
10542
+ harness: "opencode"
10543
+ });
10544
+ if (qualifierResolvesWithoutModel(resolution)) {
10545
+ throw new Error(`Invalid Systematic config: agents.${target.agentKey}.variant resolves to "${resolution.qualifier}" on the opencode harness, but no model resolves for agents.${target.agentKey} on opencode at any layer (agent, category, block, or flat). Set a model at the same layer or a lower one, or remove the qualifier.`);
10546
+ }
10035
10547
  }
10036
- const configDirs = buildOpencodeConfigDirs(startDir, homeDir, gitRoot, globalConfigDir, opencodeConfigDirOverride);
10037
- for (const dir of configDirs) {
10038
- const rootId = dir === globalConfigDir ? "global-opencode-config" : "project-opencode";
10039
- upsertAll(globSkillFiles(dir, ["skill", "skills"]), rootId);
10548
+ for (const warning of collectWrittenLegacyPiSubagentsThinkingWarnings(piSubagentsOverlays)) {
10549
+ warningSink(warning);
10040
10550
  }
10041
- return Array.from(byName.values());
10042
10551
  }
10043
-
10044
- // src/lib/search-core.ts
10045
- import fs10 from "fs";
10046
- import path11 from "path";
10047
-
10048
- // src/lib/search-corpus.ts
10049
- import fs7 from "fs";
10050
- import path6 from "path";
10051
- var MAX_FILE_BYTES = 256 * 1024;
10052
- var MAX_FILES = 2000;
10053
- var MAX_DEPTH = 6;
10054
- var MAX_TOTAL_BYTES = 16 * 1024 * 1024;
10055
- var MAX_DISCOVERED_FILES = MAX_FILES * 4;
10056
- var MAX_LISTED_ENTRIES = MAX_DISCOVERED_FILES * 4;
10057
- var MAX_WARNING_LENGTH = 200;
10058
- var DEFAULT_EXTENSIONS = [".md"];
10059
- var KIND_TABLE = {
10060
- solution: {
10061
- dir: "docs/solutions",
10062
- excludedFiles: ["readme.md", "critical-patterns.md"],
10063
- excludedDirs: ["_archived"],
10064
- lifecycle: true
10065
- },
10066
- plan: {
10067
- dir: "docs/plans",
10068
- excludedFiles: ["readme.md"],
10069
- excludedDirs: ["_archived"],
10070
- lifecycle: true
10071
- },
10072
- brainstorm: {
10073
- dir: "docs/brainstorms",
10074
- excludedFiles: ["readme.md"],
10075
- excludedDirs: ["_archived"],
10076
- lifecycle: true
10077
- },
10078
- ideation: {
10079
- dir: "docs/ideation",
10080
- excludedFiles: ["readme.md"],
10081
- excludedDirs: ["_archived"],
10082
- lifecycle: true
10552
+ function mergeOverlaySources(sources) {
10553
+ const result = {
10554
+ agents: {},
10555
+ categories: {}
10556
+ };
10557
+ for (const source of sources) {
10558
+ mergeOverlayMap(result.agents, source, "agents");
10559
+ mergeOverlayMap(result.categories, source, "categories");
10083
10560
  }
10084
- };
10085
- function isDocumentKind(value) {
10086
- return typeof value === "string" && Object.hasOwn(KIND_TABLE, value);
10087
- }
10088
- var ANSI_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
10089
- var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
10090
- function cleanForWarning(text) {
10091
- const clean = text.replace(ANSI_SEQUENCE, "").replace(CONTROL_CHARACTERS, "");
10092
- return clean.length > MAX_WARNING_LENGTH ? `${clean.slice(0, MAX_WARNING_LENGTH)}\u2026` : clean;
10561
+ return result;
10093
10562
  }
10094
- function compareCodeUnits(a, b) {
10095
- if (a < b)
10096
- return -1;
10097
- return a > b ? 1 : 0;
10563
+ function mergeOverlayMap(target, source, mapKey) {
10564
+ const overlayMap = source.config[mapKey];
10565
+ if (overlayMap === undefined)
10566
+ return;
10567
+ if (!isRecord3(overlayMap)) {
10568
+ throwInvalidOverlay(source.path, mapKey);
10569
+ }
10570
+ for (const [key, value] of Object.entries(overlayMap)) {
10571
+ const keyPath = source.kind === "profile-bundle" ? `profiles.${source.profileName}.${mapKey}.${key}` : `${mapKey}.${key}`;
10572
+ if (!isRecord3(value)) {
10573
+ throwInvalidOverlay(source.path, keyPath);
10574
+ }
10575
+ const previous = target[key];
10576
+ const nextValue = resolveOverlayEntryValue(previous?.value, value, source);
10577
+ const nextOrigins = resolveOverlayEntryOrigin(previous?.origins, value, source);
10578
+ target[key] = {
10579
+ value: nextValue,
10580
+ sourcePath: source.path,
10581
+ keyPath,
10582
+ origins: nextOrigins
10583
+ };
10584
+ }
10098
10585
  }
10099
- function safeLstat(target) {
10100
- try {
10101
- return fs7.lstatSync(target, { throwIfNoEntry: false }) ?? null;
10102
- } catch {
10103
- return null;
10586
+ function originForSource(source) {
10587
+ if (source.kind === "profile-bundle") {
10588
+ return `${source.bundleTrust}-profile`;
10104
10589
  }
10590
+ return source.trust;
10105
10591
  }
10106
- function safeRealpath(target) {
10107
- try {
10108
- return fs7.realpathSync(target);
10109
- } catch {
10110
- return null;
10592
+ function routingOriginsFromOwnFields(fragment, tag) {
10593
+ const origins = {};
10594
+ if (Object.hasOwn(fragment, "model"))
10595
+ origins.model = tag;
10596
+ if (Object.hasOwn(fragment, "variant"))
10597
+ origins.variant = tag;
10598
+ const opencodeBlock = fragment.opencode;
10599
+ if (isRecord3(opencodeBlock)) {
10600
+ if (Object.hasOwn(opencodeBlock, "model"))
10601
+ origins.opencodeModel = tag;
10602
+ if (Object.hasOwn(opencodeBlock, "variant"))
10603
+ origins.opencodeVariant = tag;
10604
+ }
10605
+ const piBlock = fragment.pi;
10606
+ if (isRecord3(piBlock)) {
10607
+ if (Object.hasOwn(piBlock, "model"))
10608
+ origins.piModel = tag;
10609
+ if (Object.hasOwn(piBlock, "thinking"))
10610
+ origins.piThinking = tag;
10111
10611
  }
10612
+ return origins;
10112
10613
  }
10113
- function isAbsence(error) {
10114
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
10115
- return code === "ENOENT" || code === "ENOTDIR";
10614
+ function resolveOverlayEntryOrigin(previous, fragment, source) {
10615
+ const own = routingOriginsFromOwnFields(fragment, originForSource(source));
10616
+ if (!previous)
10617
+ return own;
10618
+ const preserves = source.kind === "profile-bundle" || source.layer === "project" || source.layer === "user";
10619
+ return preserves ? { ...previous, ...own } : own;
10116
10620
  }
10117
- function probeRealpath(target) {
10118
- try {
10119
- return { kind: "ok", value: fs7.realpathSync(target) };
10120
- } catch (error) {
10121
- return { kind: isAbsence(error) ? "absent" : "failed" };
10621
+ function resolveOverlayEntryValue(previous, next, source) {
10622
+ if (!previous)
10623
+ return next;
10624
+ if (source.kind === "profile-bundle") {
10625
+ return mergeProfileOverlayValue(previous, next);
10122
10626
  }
10627
+ if (source.layer === "project")
10628
+ return preserveSecurityFields(previous, next);
10629
+ if (source.layer === "user")
10630
+ return mergeProfileOverlayValue(previous, next);
10631
+ return next;
10123
10632
  }
10124
- function probeLstat(target) {
10125
- try {
10126
- const stat = fs7.lstatSync(target, { throwIfNoEntry: false });
10127
- return stat === undefined ? { kind: "absent" } : { kind: "ok", value: stat };
10128
- } catch (error) {
10129
- return { kind: isAbsence(error) ? "absent" : "failed" };
10633
+ function stripProjectSecurityOverlay(sourcePath, keyPath, value, warningSink) {
10634
+ const safeKeyPath = sanitizeDiagnosticText(keyPath);
10635
+ const safeSourcePath = sanitizeDiagnosticText(sourcePath);
10636
+ let stripped;
10637
+ for (const field of SECURITY_OVERLAY_FIELDS) {
10638
+ if (Object.hasOwn(value, field)) {
10639
+ stripped ??= { ...value };
10640
+ delete stripped[field];
10641
+ warningSink(`[systematic] \`${safeKeyPath}.${field}\` in project config (${safeSourcePath}) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`);
10642
+ }
10130
10643
  }
10644
+ return stripped ?? value;
10131
10645
  }
10132
- function safeReaddir(target) {
10133
- try {
10134
- return fs7.readdirSync(target);
10135
- } catch {
10136
- return null;
10646
+ function preserveSecurityFields(previous, next) {
10647
+ const result = { ...next };
10648
+ for (const field of SECURITY_OVERLAY_FIELDS) {
10649
+ if (Object.hasOwn(previous, field)) {
10650
+ result[field] = previous[field];
10651
+ }
10137
10652
  }
10653
+ return result;
10138
10654
  }
10139
- function newEntryBudget(limit = MAX_LISTED_ENTRIES) {
10140
- return { remaining: limit, exhausted: false };
10141
- }
10142
- function listDirectoryWithin(target, budget) {
10143
- if (budget.remaining <= 0) {
10144
- budget.exhausted = true;
10145
- return { names: [], truncated: true };
10146
- }
10147
- const listing = listDirectoryBounded(target, budget.remaining);
10148
- if (listing === null)
10149
- return null;
10150
- budget.remaining -= listing.names.length;
10151
- if (listing.truncated) {
10152
- budget.remaining = 0;
10153
- budget.exhausted = true;
10655
+ var HARNESS_BLOCK_KEYS = ["opencode", "pi"];
10656
+ function mergeProfileOverlayValue(previous, next) {
10657
+ const result = { ...previous, ...next };
10658
+ for (const blockKey of HARNESS_BLOCK_KEYS) {
10659
+ const previousBlock = previous[blockKey];
10660
+ const nextBlock = next[blockKey];
10661
+ if (isRecord3(previousBlock) && isRecord3(nextBlock)) {
10662
+ result[blockKey] = { ...previousBlock, ...nextBlock };
10663
+ }
10154
10664
  }
10155
- return listing;
10665
+ return result;
10156
10666
  }
10157
- function listDirectoryBounded(target, limit) {
10158
- let directory;
10159
- try {
10160
- directory = fs7.opendirSync(target);
10161
- } catch {
10162
- return null;
10667
+ var PI_SUBAGENTS_PROTECTED_FIELD_SET = new Set(PI_SUBAGENTS_PROTECTED_FIELDS);
10668
+ function mergePiSubagentsOverlaySources(sources) {
10669
+ const result = {
10670
+ agents: {},
10671
+ categories: {}
10672
+ };
10673
+ for (const source of sources) {
10674
+ mergePiSubagentsOverlayMap(result.agents, source, "agents");
10675
+ mergePiSubagentsOverlayMap(result.categories, source, "categories");
10163
10676
  }
10164
- const names = [];
10165
- try {
10166
- while (true) {
10167
- const entry = directory.readSync();
10168
- if (entry === null)
10169
- return { names, truncated: false };
10170
- if (names.length >= limit)
10171
- return { names, truncated: true };
10172
- names.push(entry.name);
10173
- }
10174
- } catch {
10175
- return null;
10176
- } finally {
10177
- try {
10178
- directory.closeSync();
10179
- } catch {}
10677
+ return result;
10678
+ }
10679
+ function stripPiSubagentsProtectedFields(value) {
10680
+ const result = {};
10681
+ for (const [field, fieldValue] of Object.entries(value)) {
10682
+ if (PI_SUBAGENTS_PROTECTED_FIELD_SET.has(field))
10683
+ continue;
10684
+ result[field] = fieldValue;
10180
10685
  }
10686
+ return result;
10181
10687
  }
10182
- function resolveSearchRoot(startDir) {
10183
- const resolved = path6.resolve(startDir);
10184
- const start = safeRealpath(resolved) ?? resolved;
10185
- let current = start;
10186
- while (true) {
10187
- try {
10188
- if (fs7.lstatSync(path6.join(current, ".git"), { throwIfNoEntry: false })) {
10189
- return current;
10190
- }
10191
- } catch {
10192
- return start;
10688
+ function preservePiSubagentsProtectedFields(previous, next) {
10689
+ const result = { ...next };
10690
+ for (const field of PI_SUBAGENTS_PROTECTED_FIELD_SET) {
10691
+ if (Object.hasOwn(previous, field)) {
10692
+ result[field] = previous[field];
10193
10693
  }
10194
- const parent = path6.dirname(current);
10195
- if (parent === current)
10196
- return start;
10197
- current = parent;
10198
10694
  }
10695
+ return result;
10199
10696
  }
10200
- function isInside(root, candidate) {
10201
- const relative = path6.relative(root, candidate);
10202
- return relative !== "" && relative !== ".." && !relative.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relative);
10203
- }
10204
- function symlinkedComponent(container, target) {
10205
- if (!isInside(container, target))
10697
+ function mergePiSubagentsOverlayMap(target, source, mapKey) {
10698
+ const overlayMap = source.config.pi_subagents?.[mapKey];
10699
+ if (overlayMap === undefined)
10206
10700
  return;
10207
- const segments = path6.relative(container, target).split(path6.sep);
10208
- let current = container;
10209
- for (const [index, segment] of segments.entries()) {
10210
- current = path6.join(current, segment);
10211
- const stat = safeLstat(current);
10212
- if (stat === null)
10213
- return;
10214
- if (stat.isSymbolicLink()) {
10215
- return index === segments.length - 1 ? "root" : "ancestor";
10701
+ if (!isRecord3(overlayMap)) {
10702
+ throwInvalidOverlay(source.path, `pi_subagents.${mapKey}`);
10703
+ }
10704
+ for (const [key, rawValue] of Object.entries(overlayMap)) {
10705
+ const keyPath = `pi_subagents.${mapKey}.${key}`;
10706
+ if (!isRecord3(rawValue)) {
10707
+ throwInvalidOverlay(source.path, keyPath);
10216
10708
  }
10709
+ const previous = target[key];
10710
+ const value = source.trust === "project" ? preservePiSubagentsProtectedFields(previous?.value ?? {}, stripPiSubagentsProtectedFields(rawValue)) : rawValue;
10711
+ target[key] = {
10712
+ value,
10713
+ sourcePath: source.path,
10714
+ keyPath
10715
+ };
10217
10716
  }
10218
- return;
10219
10717
  }
10220
- function classifyEntry(spec, name, stat) {
10221
- if (stat === null || stat.isSymbolicLink())
10222
- return "ignored";
10223
- if (stat.isDirectory()) {
10224
- return spec.excludedDirs.includes(name) ? "ignored" : "directory";
10718
+ function overlayValues(overlays) {
10719
+ const result = {};
10720
+ for (const [key, overlay] of Object.entries(overlays)) {
10721
+ result[key] = overlay.value;
10225
10722
  }
10226
- if (!stat.isFile())
10227
- return "ignored";
10228
- const lower = name.toLowerCase();
10229
- const extensions = spec.extensions ?? DEFAULT_EXTENSIONS;
10230
- const indexable = extensions.some((extension) => lower.endsWith(extension)) && !spec.excludedFiles.includes(lower);
10231
- return indexable ? "file" : "ignored";
10723
+ return result;
10232
10724
  }
10233
- function wholeListing(directory) {
10234
- const names = safeReaddir(directory);
10235
- return names === null ? null : { names, truncated: false };
10725
+ function throwInvalidOverlay(sourcePath, keyPath) {
10726
+ throw new Error(`Invalid Systematic config in ${sourcePath}: ${keyPath} must be an object`);
10236
10727
  }
10237
- function listWalkedDirectory(budget, label, directory, prefix, warnings) {
10238
- const listing = budget === undefined ? wholeListing(directory) : listDirectoryWithin(directory, budget);
10239
- if (listing === null) {
10240
- if (prefix !== "") {
10241
- const shown = `${label}/${prefix.slice(0, -1)}`;
10242
- warnings.push(cleanForWarning(`could not read directory ${shown}`));
10728
+ function getConfigPaths(projectDir, options) {
10729
+ const dirs = resolveUserLevelConfigDirs(options);
10730
+ const { homeDir, customConfigDir } = dirs;
10731
+ const selection = selectUserLevelConfigFiles(dirs);
10732
+ const fileFor = (layer) => selection.files.find((file) => file.layer === layer)?.path;
10733
+ const userFile = (layer) => {
10734
+ const file = fileFor(layer);
10735
+ if (file === undefined) {
10736
+ throw new Error(`No ${layer} config file was selected`);
10737
+ }
10738
+ return file;
10739
+ };
10740
+ const repoRoot = options?.includeProject ?? true ? lookupSearchRoot(projectDir) : undefined;
10741
+ const projectRoot = repoRoot?.root ?? projectDir;
10742
+ const project = repoRoot ? selectProjectConfigFile(projectRoot) : {
10743
+ path: selectConfigFile(path3.join(projectDir, ".opencode"), "systematic")
10744
+ };
10745
+ const startDirProjectConfig = repoRoot ? findStartDirProjectConfig(projectDir, repoRoot, project.path) : undefined;
10746
+ const ignoredProjectConfig = "ignoredPath" in project ? project.ignoredPath : undefined;
10747
+ const customConfig = fileFor("custom");
10748
+ const customLocalConfig = fileFor("custom.local");
10749
+ return {
10750
+ userConfig: userFile("user"),
10751
+ userLocalConfig: userFile("user.local"),
10752
+ projectConfig: project.path,
10753
+ projectRoot,
10754
+ userDir: path3.join(homeDir, ".config/opencode/systematic"),
10755
+ projectDir: path3.join(projectRoot, ".opencode/systematic"),
10756
+ customAliasesUser: selection.aliased,
10757
+ ...ignoredProjectConfig !== undefined && { ignoredProjectConfig },
10758
+ ...startDirProjectConfig !== undefined && { startDirProjectConfig },
10759
+ ...customConfigDir && customConfig !== undefined && customLocalConfig !== undefined && {
10760
+ customConfig,
10761
+ customLocalConfig,
10762
+ customDir: path3.join(customConfigDir, "systematic")
10243
10763
  }
10244
- return null;
10245
- }
10246
- return listing.names;
10764
+ };
10247
10765
  }
10248
- function discoverFiles(spec, label, directory, prefix, depth, found, warnings) {
10249
- const names = listWalkedDirectory(found.budget, label, directory, prefix, warnings);
10250
- if (names === null) {
10251
- if (depth === 0)
10252
- found.rootUnreadable = true;
10253
- return;
10254
- }
10255
- names.sort(compareCodeUnits);
10256
- for (const name of names) {
10257
- if (found.truncated)
10766
+
10767
+ // src/lib/walk-dir.ts
10768
+ import fs5 from "fs";
10769
+ import path4 from "path";
10770
+ function isDiscoverableMarkdown(fileName) {
10771
+ return fileName.endsWith(".md") && fileName.toLowerCase() !== "readme.md";
10772
+ }
10773
+ function walkDir(rootDir, options = {}) {
10774
+ const { maxDepth = 3, filter } = options;
10775
+ const results = [];
10776
+ if (!fs5.existsSync(rootDir))
10777
+ return results;
10778
+ function recurse(currentDir, depth, category) {
10779
+ if (depth > maxDepth)
10258
10780
  return;
10259
- const absolute = path6.join(directory, name);
10260
- const stat = safeLstat(absolute);
10261
- const entryKind = classifyEntry(spec, name, stat);
10262
- if (entryKind === "directory" && depth + 1 <= MAX_DEPTH) {
10263
- const child = `${prefix}${name}/`;
10264
- discoverFiles(spec, label, absolute, child, depth + 1, found, warnings);
10265
- } else if (entryKind === "file" && stat !== null) {
10266
- if (found.candidates.length >= MAX_DISCOVERED_FILES) {
10267
- found.truncated = true;
10268
- return;
10781
+ const entries = fs5.readdirSync(currentDir, { withFileTypes: true });
10782
+ for (const entry of entries) {
10783
+ const fullPath = path4.join(currentDir, entry.name);
10784
+ const walkEntry = {
10785
+ path: fullPath,
10786
+ name: entry.name,
10787
+ isDirectory: entry.isDirectory(),
10788
+ depth,
10789
+ category
10790
+ };
10791
+ if (!filter || filter(walkEntry)) {
10792
+ results.push(walkEntry);
10793
+ }
10794
+ if (entry.isDirectory()) {
10795
+ recurse(fullPath, depth + 1, entry.name);
10269
10796
  }
10270
- found.candidates.push({
10271
- relative: `${prefix}${name}`,
10272
- absolute,
10273
- size: stat.size
10274
- });
10275
10797
  }
10276
10798
  }
10799
+ recurse(rootDir, 0);
10800
+ return results;
10277
10801
  }
10278
- function narrowString(value) {
10279
- return typeof value === "string" ? value : undefined;
10280
- }
10281
- function narrowNonEmptyString(value) {
10282
- const trimmed = narrowString(value)?.trim();
10283
- return trimmed ? trimmed : undefined;
10284
- }
10285
- function narrowStringList(value) {
10286
- const items = Array.isArray(value) ? value : [value];
10287
- const result = [];
10288
- for (const item of items) {
10289
- if (typeof item === "string")
10290
- result.push(item);
10291
- else if (typeof item === "number" && Number.isFinite(item))
10292
- result.push(String(item));
10293
- }
10294
- return result;
10295
- }
10296
- function narrowSupersededBy(value) {
10297
- if (value === undefined || value === null)
10298
- return { state: "none" };
10299
- if (typeof value === "string")
10300
- return { state: "value", value };
10301
- return { state: "invalid" };
10802
+
10803
+ // src/lib/agents.ts
10804
+ function findAgentsInDir(dir, maxDepth = 2) {
10805
+ const entries = walkDir(dir, {
10806
+ maxDepth,
10807
+ filter: (e) => !e.isDirectory && isDiscoverableMarkdown(e.name)
10808
+ });
10809
+ return entries.map((entry) => ({
10810
+ name: entry.name.replace(/\.md$/, ""),
10811
+ file: entry.path,
10812
+ category: entry.category
10813
+ }));
10302
10814
  }
10303
- function parseMarkdownFrontmatter(content) {
10304
- let text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
10305
- if (!text.endsWith(`
10306
- `))
10307
- text += `
10308
- `;
10309
- const parsed = parseFrontmatter(text);
10310
- if (parsed.parseError)
10311
- return { ok: false, reason: "invalid frontmatter" };
10312
- if (parsed.hadFrontmatter && !isRecord(parsed.data)) {
10313
- return { ok: false, reason: "frontmatter is not a mapping" };
10815
+ function extractAgentFrontmatter(content) {
10816
+ const { data, parseError, body } = parseFrontmatter(content);
10817
+ if (parseError) {
10818
+ return { name: "", description: "", prompt: body.trim() };
10314
10819
  }
10315
10820
  return {
10316
- ok: true,
10317
- data: isRecord(parsed.data) ? parsed.data : {},
10318
- body: parsed.body
10821
+ name: extractString(data, "name"),
10822
+ description: extractString(data, "description"),
10823
+ prompt: body.trim(),
10824
+ model: extractNonEmptyString(data, "model"),
10825
+ variant: extractNonEmptyString(data, "variant"),
10826
+ temperature: extractNumber(data, "temperature"),
10827
+ top_p: extractNumber(data, "top_p"),
10828
+ tools: isToolsMap(data.tools) ? data.tools : undefined,
10829
+ disable: extractBoolean(data, "disable"),
10830
+ mode: isAgentMode(data.mode) ? data.mode : undefined,
10831
+ color: extractNonEmptyString(data, "color"),
10832
+ steps: extractNumber(data, "steps"),
10833
+ hidden: extractBoolean(data, "hidden") ?? undefined,
10834
+ permission: normalizePermission(data.permission)
10319
10835
  };
10320
10836
  }
10321
- function parseCorpusDocument(kind, relativePath, content) {
10322
- const parsed = parseMarkdownFrontmatter(content);
10323
- if (!parsed.ok)
10324
- return parsed;
10325
- const data = parsed.data;
10326
- const fileName = relativePath.slice(relativePath.lastIndexOf("/") + 1);
10327
- const title = narrowNonEmptyString(data.title) ?? narrowNonEmptyString(data.topic) ?? fileName.replace(/\.md$/i, "");
10837
+
10838
+ // src/lib/commands.ts
10839
+ function findCommandsInDir(dir, maxDepth = 2) {
10840
+ const entries = walkDir(dir, {
10841
+ maxDepth,
10842
+ filter: (e) => !e.isDirectory && isDiscoverableMarkdown(e.name)
10843
+ });
10844
+ return entries.map((entry) => {
10845
+ const baseName = entry.name.replace(/\.md$/, "");
10846
+ const commandName = entry.category ? `/${entry.category}:${baseName}` : `/${baseName}`;
10847
+ return {
10848
+ name: commandName,
10849
+ file: entry.path,
10850
+ category: entry.category
10851
+ };
10852
+ });
10853
+ }
10854
+ function extractCommandFrontmatter(content) {
10855
+ const { data, parseError } = parseFrontmatter(content);
10856
+ if (parseError) {
10857
+ return {
10858
+ name: "",
10859
+ description: "",
10860
+ argumentHint: "",
10861
+ agent: undefined,
10862
+ model: undefined,
10863
+ subtask: undefined
10864
+ };
10865
+ }
10866
+ const argumentHintRaw = extractString(data, "argument-hint");
10328
10867
  return {
10329
- ok: true,
10330
- document: {
10331
- path: relativePath,
10332
- kind,
10333
- title,
10334
- tags: narrowStringList(data.tags),
10335
- module: narrowString(data.module),
10336
- component: narrowString(data.component),
10337
- problemType: narrowString(data.problem_type),
10338
- symptoms: narrowStringList(data.symptoms),
10339
- appliesWhen: narrowStringList(data.applies_when),
10340
- status: narrowString(data.status),
10341
- supersededBy: narrowSupersededBy(data.superseded_by),
10342
- staleReason: narrowString(data.stale_reason),
10343
- body: parsed.body
10344
- }
10868
+ name: extractString(data, "name"),
10869
+ description: extractString(data, "description"),
10870
+ argumentHint: argumentHintRaw.replace(/^["']|["']$/g, ""),
10871
+ agent: extractNonEmptyString(data, "agent"),
10872
+ model: extractNonEmptyString(data, "model"),
10873
+ subtask: extractBoolean(data, "subtask")
10345
10874
  };
10346
10875
  }
10347
- function discoverSourceFiles(options, warnings) {
10348
- const { directory, containedIn, walk, label, entryBudget } = options;
10349
- const directoryProbe = probeRealpath(directory);
10350
- const containerProbe = containedIn === undefined ? undefined : probeRealpath(containedIn);
10351
- if (containerProbe?.kind === "failed" || directoryProbe.kind === "failed") {
10352
- warnings.push(`could not read ${label}; not loaded`);
10353
- return { state: "unreadable" };
10876
+
10877
+ // src/lib/discovered-skills.ts
10878
+ import fs7 from "fs";
10879
+ import path6 from "path";
10880
+
10881
+ // src/lib/skills.ts
10882
+ import fs6 from "fs";
10883
+ import path5 from "path";
10884
+ function parseMetadata(data) {
10885
+ const metadataRaw = data.metadata;
10886
+ if (!isRecord(metadataRaw)) {
10887
+ return;
10354
10888
  }
10355
- if (containerProbe !== undefined && containerProbe.kind !== "ok" || directoryProbe.kind !== "ok") {
10356
- return { state: "missing" };
10889
+ const entries = Object.entries(metadataRaw);
10890
+ if (!entries.every(([, v]) => typeof v === "string")) {
10891
+ return;
10357
10892
  }
10358
- const directoryReal = directoryProbe.value;
10359
- const statProbe = probeLstat(directoryReal);
10360
- if (statProbe.kind === "failed") {
10361
- warnings.push(`could not read ${label}; not loaded`);
10362
- return { state: "unreadable" };
10893
+ return Object.fromEntries(entries);
10894
+ }
10895
+ function extractFrontmatterFromContent(content) {
10896
+ const { data, parseError } = parseFrontmatter(content);
10897
+ if (parseError) {
10898
+ return { name: "", description: "" };
10363
10899
  }
10364
- if (statProbe.kind !== "ok" || !statProbe.value.isDirectory()) {
10365
- return { state: "missing" };
10900
+ const metadata = parseMetadata(data);
10901
+ const argumentHintRaw = extractNonEmptyString(data, "argument-hint");
10902
+ const argumentHint = argumentHintRaw?.replace(/^["']|["']$/g, "") || undefined;
10903
+ return {
10904
+ name: extractString(data, "name"),
10905
+ description: extractString(data, "description"),
10906
+ license: extractNonEmptyString(data, "license"),
10907
+ compatibility: extractNonEmptyString(data, "compatibility"),
10908
+ metadata,
10909
+ disableModelInvocation: extractBoolean(data, "disable-model-invocation"),
10910
+ userInvocable: extractBoolean(data, "user-invocable"),
10911
+ subtask: data.context === "fork" ? true : extractBoolean(data, "subtask") ?? undefined,
10912
+ agent: extractNonEmptyString(data, "agent"),
10913
+ model: extractNonEmptyString(data, "model"),
10914
+ argumentHint: argumentHint !== "" ? argumentHint : undefined,
10915
+ allowedTools: extractNonEmptyString(data, "allowed-tools")
10916
+ };
10917
+ }
10918
+ function extractFrontmatter(filePath) {
10919
+ try {
10920
+ const content = fs6.readFileSync(filePath, "utf8");
10921
+ return extractFrontmatterFromContent(content);
10922
+ } catch {
10923
+ return { name: "", description: "" };
10366
10924
  }
10367
- if (containerProbe !== undefined && !isInside(containerProbe.value, directoryReal)) {
10368
- warnings.push(`${label} resolves outside the project root; not loaded`);
10369
- return { state: "outside" };
10925
+ }
10926
+ function findSkillsInDir(dir, maxDepth = 3) {
10927
+ const skills = [];
10928
+ const entries = walkDir(dir, {
10929
+ maxDepth,
10930
+ filter: (e) => e.isDirectory
10931
+ });
10932
+ for (const entry of entries) {
10933
+ const skillFile = path5.join(entry.path, "SKILL.md");
10934
+ if (fs6.existsSync(skillFile)) {
10935
+ const frontmatter = extractFrontmatter(skillFile);
10936
+ skills.push({
10937
+ path: entry.path,
10938
+ skillFile,
10939
+ name: frontmatter.name || entry.name,
10940
+ description: frontmatter.description || "",
10941
+ license: frontmatter.license,
10942
+ compatibility: frontmatter.compatibility,
10943
+ metadata: frontmatter.metadata,
10944
+ disableModelInvocation: frontmatter.disableModelInvocation,
10945
+ userInvocable: frontmatter.userInvocable,
10946
+ subtask: frontmatter.subtask,
10947
+ agent: frontmatter.agent,
10948
+ model: frontmatter.model,
10949
+ argumentHint: frontmatter.argumentHint,
10950
+ allowedTools: frontmatter.allowedTools
10951
+ });
10952
+ }
10370
10953
  }
10371
- const found = {
10372
- candidates: [],
10373
- truncated: false,
10374
- rootUnreadable: false,
10375
- budget: entryBudget
10376
- };
10377
- discoverFiles(walk, label, directoryReal, "", 0, found, warnings);
10378
- if (found.rootUnreadable) {
10379
- warnings.push(`could not read ${label}; not loaded`);
10380
- return { state: "unreadable" };
10954
+ return skills;
10955
+ }
10956
+
10957
+ // src/lib/discovered-skills.ts
10958
+ var SKILL_NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
10959
+ function isValidSkillName(name) {
10960
+ return name.length >= 1 && name.length <= 64 && SKILL_NAME_REGEX.test(name);
10961
+ }
10962
+ function findGitWorktreeRoot(startDir) {
10963
+ let current = path6.resolve(startDir);
10964
+ while (true) {
10965
+ try {
10966
+ if (fs7.existsSync(path6.join(current, ".git"))) {
10967
+ return current;
10968
+ }
10969
+ } catch {
10970
+ return null;
10971
+ }
10972
+ const parent = path6.dirname(current);
10973
+ if (parent === current)
10974
+ return null;
10975
+ current = parent;
10381
10976
  }
10382
- return {
10383
- state: "found",
10384
- candidates: found.candidates.sort((a, b) => compareCodeUnits(a.relative, b.relative)),
10385
- truncated: found.truncated
10386
- };
10387
10977
  }
10388
- function readAllowance(used, maxFileBytes, sharedBytes) {
10389
- const source = MAX_TOTAL_BYTES - used;
10390
- const shared = sharedBytes === undefined ? Infinity : sharedBytes - used;
10391
- const left = Math.max(Math.min(source, shared), 0);
10392
- if (maxFileBytes <= left)
10393
- return { limit: maxFileBytes, bound: "file" };
10394
- return { limit: left, bound: shared < source ? "shared" : "source" };
10978
+ function upWalk(targets, start, stop) {
10979
+ const results = [];
10980
+ let current = path6.resolve(start);
10981
+ const resolvedStop = stop === undefined ? undefined : path6.resolve(stop);
10982
+ while (true) {
10983
+ for (const target of targets) {
10984
+ const candidate = path6.join(current, target);
10985
+ try {
10986
+ if (fs7.existsSync(candidate)) {
10987
+ results.push(candidate);
10988
+ }
10989
+ } catch {}
10990
+ }
10991
+ if (resolvedStop !== undefined && current === resolvedStop)
10992
+ break;
10993
+ const parent = path6.dirname(current);
10994
+ if (parent === current)
10995
+ break;
10996
+ current = parent;
10997
+ }
10998
+ return results;
10395
10999
  }
10396
- function readWithinBudgets(options, candidate, used) {
10397
- const { maxFileBytes, sharedBytes } = options;
10398
- const tooLarge = `larger than ${maxFileBytes} bytes`;
10399
- if (candidate.size > maxFileBytes) {
10400
- return { kind: "skip", reason: tooLarge, bytes: 0 };
11000
+ function uniqueStrings(values) {
11001
+ return Array.from(new Set(values));
11002
+ }
11003
+ function buildOpencodeConfigDirs(startDir, homeDir, gitRoot, globalConfigDir, opencodeConfigDirOverride) {
11004
+ const dirs = [globalConfigDir];
11005
+ dirs.push(...upWalk([".opencode"], startDir, gitRoot ?? startDir));
11006
+ dirs.push(...upWalk([".opencode"], homeDir, homeDir));
11007
+ if (opencodeConfigDirOverride !== undefined) {
11008
+ dirs.push(opencodeConfigDirOverride);
10401
11009
  }
10402
- if (used + candidate.size > MAX_TOTAL_BYTES) {
10403
- return { kind: "stop", bound: "source", bytes: 0 };
11010
+ return uniqueStrings(dirs);
11011
+ }
11012
+ function globSkillFiles(rootDir, subdirNames) {
11013
+ const results = [];
11014
+ for (const subdirName of subdirNames) {
11015
+ const scanRoot = path6.join(rootDir, subdirName);
11016
+ try {
11017
+ if (!fs7.existsSync(scanRoot))
11018
+ continue;
11019
+ const entries = walkDir(scanRoot, {
11020
+ maxDepth: 10,
11021
+ filter: (entry) => entry.name === "SKILL.md"
11022
+ });
11023
+ for (const entry of entries) {
11024
+ results.push(entry.path);
11025
+ }
11026
+ } catch {}
10404
11027
  }
10405
- if (sharedBytes !== undefined && used + candidate.size > sharedBytes) {
10406
- return { kind: "stop", bound: "shared", bytes: 0 };
11028
+ return results;
11029
+ }
11030
+ function toDiscoveredSkill(skillPath, rootId, onIssue) {
11031
+ let content;
11032
+ try {
11033
+ content = fs7.readFileSync(skillPath, "utf8");
11034
+ } catch {
11035
+ onIssue?.("read-failed");
11036
+ return;
10407
11037
  }
10408
- const allowance = readAllowance(used, maxFileBytes, sharedBytes);
10409
- const read = readBytesBounded(candidate.absolute, allowance.limit);
10410
- if (read.kind === "too-large") {
10411
- return allowance.bound === "file" ? { kind: "skip", reason: tooLarge, bytes: read.bytesRead } : { kind: "stop", bound: allowance.bound, bytes: allowance.limit };
11038
+ if (parseFrontmatter(content).parseError) {
11039
+ onIssue?.("source-invalid");
11040
+ return;
10412
11041
  }
10413
- if (read.kind !== "bytes") {
10414
- return { kind: "skip", reason: "could not be read", bytes: 0 };
11042
+ const frontmatter = extractFrontmatterFromContent(content);
11043
+ const name = frontmatter.name;
11044
+ if (!name || !isValidSkillName(name)) {
11045
+ onIssue?.("source-invalid");
11046
+ return;
10415
11047
  }
10416
11048
  return {
10417
- kind: "text",
10418
- text: read.bytes.toString("utf8"),
10419
- bytes: read.bytes.byteLength
11049
+ name,
11050
+ description: frontmatter.description,
11051
+ frontmatter,
11052
+ body: parseFrontmatter(content).body,
11053
+ skillPath,
11054
+ root: rootId
10420
11055
  };
10421
11056
  }
10422
- function readCandidates(options, candidates, considered, warnings) {
10423
- const items = [];
10424
- let totalBytes = 0;
10425
- for (let index = 0;index < considered; index++) {
10426
- const candidate = candidates[index];
10427
- if (candidate === undefined)
10428
- break;
10429
- const logicalPath = `${options.displayPrefix}/${candidate.relative}`;
10430
- const display = cleanForWarning(logicalPath);
10431
- const read = readWithinBudgets(options, candidate, totalBytes);
10432
- totalBytes += read.bytes;
10433
- if (read.kind === "stop") {
10434
- return {
10435
- items,
10436
- bytesRead: totalBytes,
10437
- budgetSkipped: considered - index,
10438
- budgetBound: read.bound
10439
- };
10440
- }
10441
- if (read.kind === "skip") {
10442
- warnings.push(`skipped ${display}: ${read.reason}`);
10443
- continue;
11057
+ function discoverSkills(options) {
11058
+ const { startDir, homeDir, configDir, onIssue, opencodeConfigDirOverride } = options;
11059
+ const globalConfigDir = configDir ?? path6.join(homeDir, ".config/opencode");
11060
+ const gitRoot = findGitWorktreeRoot(startDir);
11061
+ const byName = new Map;
11062
+ function upsertAll(skillPaths, rootId) {
11063
+ for (const skillPath of skillPaths) {
11064
+ const skill = toDiscoveredSkill(skillPath, rootId, onIssue);
11065
+ if (skill)
11066
+ byName.set(skill.name, skill);
10444
11067
  }
10445
- const parsed = options.parse(logicalPath, read.text);
10446
- if (parsed.ok)
10447
- items.push(parsed.value);
10448
- else
10449
- warnings.push(`skipped ${display}: ${parsed.reason}`);
10450
- }
10451
- return {
10452
- items,
10453
- bytesRead: totalBytes,
10454
- budgetSkipped: 0,
10455
- budgetBound: "source"
10456
- };
10457
- }
10458
- function readSourceFiles(options, candidates, truncated, warnings) {
10459
- const considered = Math.min(candidates.length, MAX_FILES);
10460
- const { items, bytesRead, budgetSkipped, budgetBound } = readCandidates(options, candidates, considered, warnings);
10461
- const capSkipped = candidates.length - considered;
10462
- if (capSkipped > 0) {
10463
- const atLeast = truncated ? "at least " : "";
10464
- warnings.push(`${options.label}: file limit of ${MAX_FILES} reached; skipped ${atLeast}${capSkipped} files`);
10465
- }
10466
- if (budgetSkipped > 0) {
10467
- warnings.push(budgetBound === "shared" ? `${options.label}: read budget of this call reached; skipped ${budgetSkipped} files` : `${options.label}: text budget of ${MAX_TOTAL_BYTES} bytes reached; skipped ${budgetSkipped} files`);
10468
11068
  }
10469
- return { items, bytesRead };
10470
- }
10471
- function loadSourceFiles(discover, read) {
10472
- const warnings = [];
10473
- const discovery = discoverSourceFiles(discover, warnings);
10474
- if (discovery.state !== "found") {
10475
- return { state: discovery.state, warnings };
11069
+ upsertAll(globSkillFiles(homeDir, [".claude/skills"]), "global-claude");
11070
+ upsertAll(globSkillFiles(homeDir, [".agents/skills"]), "global-agents");
11071
+ const externalLevels = upWalk([".claude", ".agents"], startDir, gitRoot ?? startDir);
11072
+ for (const levelDir of externalLevels) {
11073
+ const isClaudeDir = path6.basename(levelDir) === ".claude";
11074
+ const parentDir = path6.dirname(levelDir);
11075
+ const subdirGlob = isClaudeDir ? ".claude/skills" : ".agents/skills";
11076
+ const rootId = isClaudeDir ? "project-claude" : "project-agents";
11077
+ upsertAll(globSkillFiles(parentDir, [subdirGlob]), rootId);
10476
11078
  }
10477
- const { items, bytesRead } = readSourceFiles(read, discovery.candidates, discovery.truncated, warnings);
10478
- return { state: "loaded", items, bytesRead, warnings };
10479
- }
10480
- function loadCorpus(root, kind = "solution") {
10481
- const spec = KIND_TABLE[kind];
10482
- const loaded = loadSourceFiles({
10483
- directory: path6.join(root, ...spec.dir.split("/")),
10484
- containedIn: root,
10485
- walk: spec,
10486
- label: spec.dir
10487
- }, {
10488
- displayPrefix: spec.dir,
10489
- label: spec.dir,
10490
- maxFileBytes: MAX_FILE_BYTES,
10491
- parse: (displayPath, content) => {
10492
- const parsed = parseCorpusDocument(kind, displayPath, content);
10493
- return parsed.ok ? { ok: true, value: parsed.document } : { ok: false, reason: parsed.reason };
10494
- }
10495
- });
10496
- if (loaded.state !== "loaded") {
10497
- return { state: "none", documents: [], warnings: loaded.warnings };
11079
+ const configDirs = buildOpencodeConfigDirs(startDir, homeDir, gitRoot, globalConfigDir, opencodeConfigDirOverride);
11080
+ for (const dir of configDirs) {
11081
+ const rootId = dir === globalConfigDir ? "global-opencode-config" : "project-opencode";
11082
+ upsertAll(globSkillFiles(dir, ["skill", "skills"]), rootId);
10498
11083
  }
10499
- return {
10500
- state: "loaded",
10501
- documents: loaded.items,
10502
- warnings: loaded.warnings
10503
- };
11084
+ return Array.from(byName.values());
10504
11085
  }
10505
11086
 
11087
+ // src/lib/search-core.ts
11088
+ import fs10 from "fs";
11089
+ import path11 from "path";
11090
+
10506
11091
  // src/lib/search-external.ts
10507
11092
  import path8 from "path";
10508
11093
 
@@ -10549,9 +11134,11 @@ function probeRoot(root, containedIn) {
10549
11134
  }
10550
11135
  return { kind: "ok", real };
10551
11136
  }
10552
- function classifyJsonEntry(directory, folder, name, skips) {
11137
+ function classifyJsonEntry(directory, folder, name, skips, isExcluded) {
10553
11138
  if (!name.endsWith(JSON_SUFFIX))
10554
11139
  return;
11140
+ if (isExcluded(`${folder}/${name}`))
11141
+ return;
10555
11142
  const absolute = path7.join(directory, name);
10556
11143
  const entry = safeLstat(absolute);
10557
11144
  if (entry === null)
@@ -10580,7 +11167,9 @@ function statFolder(directory) {
10580
11167
  return { kind: isAbsence2(error) ? "absent" : "failed" };
10581
11168
  }
10582
11169
  }
10583
- function scanFolder(rootReal, folder, limit, skips, budget) {
11170
+ function scanFolder(rootReal, folder, limit, skips, budget, isExcluded) {
11171
+ if (isExcluded(folder))
11172
+ return folderScan("excluded");
10584
11173
  const directory = path7.join(rootReal, folder);
10585
11174
  const probed = statFolder(directory);
10586
11175
  if (probed.kind === "absent")
@@ -10600,7 +11189,7 @@ function scanFolder(rootReal, folder, limit, skips, budget) {
10600
11189
  names.sort(compareCodeUnits);
10601
11190
  const candidates = [];
10602
11191
  for (const name of names) {
10603
- const candidate = classifyJsonEntry(directory, folder, name, skips);
11192
+ const candidate = classifyJsonEntry(directory, folder, name, skips, isExcluded);
10604
11193
  if (candidate === undefined)
10605
11194
  continue;
10606
11195
  if (candidates.length >= limit) {
@@ -10644,14 +11233,16 @@ function newTally() {
10644
11233
  return {
10645
11234
  files: new Map,
10646
11235
  listed: false,
11236
+ excluded: false,
10647
11237
  unreadable: false,
10648
11238
  truncated: false
10649
11239
  };
10650
11240
  }
10651
- function scanRoots(reals, folder, tally, otherCount, skips, budget) {
11241
+ function scanRoots(reals, folder, tally, otherCount, skips, budget, isExcluded) {
10652
11242
  for (const real of reals) {
10653
- const scan = scanFolder(real, folder, Math.max(MAX_DISCOVERED_FILES - otherCount - tally.files.size, 0), skips, budget);
11243
+ const scan = scanFolder(real, folder, Math.max(MAX_DISCOVERED_FILES - otherCount - tally.files.size, 0), skips, budget, isExcluded);
10654
11244
  tally.listed = tally.listed || scan.status === "listed";
11245
+ tally.excluded = tally.excluded || scan.status === "excluded";
10655
11246
  tally.unreadable = tally.unreadable || scan.status === "unreadable";
10656
11247
  tally.truncated = tally.truncated || scan.truncated;
10657
11248
  for (const candidate of scan.candidates) {
@@ -10678,8 +11269,9 @@ function gather(input, skips, warnings) {
10678
11269
  const budget = newEntryBudget(limit);
10679
11270
  const nodes = newTally();
10680
11271
  const edges = newTally();
10681
- scanRoots(reals, "nodes", nodes, 0, skips, budget);
10682
- scanRoots(reals, "edges", edges, nodes.files.size, skips, budget);
11272
+ const isExcluded = input.isExcluded ?? (() => false);
11273
+ scanRoots(reals, "nodes", nodes, 0, skips, budget, isExcluded);
11274
+ scanRoots(reals, "edges", edges, nodes.files.size, skips, budget, isExcluded);
10683
11275
  warnings.push(...folderWarnings(input.name, "nodes", nodes), ...folderWarnings(input.name, "edges", edges));
10684
11276
  if (budget.exhausted) {
10685
11277
  warnings.push(`${input.name}: entry limit of ${limit} reached; some entries were not examined`);
@@ -10692,6 +11284,8 @@ function gather(input, skips, warnings) {
10692
11284
  rootsFound: reals.length,
10693
11285
  anyNodesFolder: nodes.listed,
10694
11286
  anyEdgesFolder: edges.listed,
11287
+ nodesExcluded: nodes.excluded,
11288
+ edgesExcluded: edges.excluded,
10695
11289
  nodesUnreadable: nodes.unreadable,
10696
11290
  edgesUnreadable: edges.unreadable,
10697
11291
  truncated: nodes.truncated || edges.truncated,
@@ -10942,7 +11536,7 @@ function loadDeciduousRecords(input) {
10942
11536
  return nothing("unreadable", warnings.map(cleanForWarning));
10943
11537
  }
10944
11538
  if (nodeless === "empty") {
10945
- if (!gathered.anyNodesFolder) {
11539
+ if (!gathered.anyNodesFolder && !gathered.nodesExcluded) {
10946
11540
  warnings.push(`${name}: no nodes/ folder; nothing to index`);
10947
11541
  }
10948
11542
  warnings.push(...skipWarnings(name, skips, input.maxFileBytes));
@@ -10961,7 +11555,7 @@ function loadDeciduousRecords(input) {
10961
11555
  };
10962
11556
  const scan = readNodes(gathered.nodes, input, reader, skips);
10963
11557
  readEdges(gathered.edges, scan, input, reader, skips);
10964
- if (!gathered.anyEdgesFolder && !gathered.edgesUnreadable) {
11558
+ if (!gathered.anyEdgesFolder && !gathered.edgesUnreadable && !gathered.edgesExcluded) {
10965
11559
  warnings.push(`${name}: no edges/ folder; records carry no rationale`);
10966
11560
  }
10967
11561
  warnings.push(...skipWarnings(name, skips, input.maxFileBytes), ...limitWarnings(name, {
@@ -11062,17 +11656,13 @@ function finishGather(source, merge, warnings) {
11062
11656
  const candidates = [...merge.candidates.values()].sort((a, b) => compareCodeUnits(a.relative, b.relative));
11063
11657
  return { kind: "gathered", candidates, truncated: merge.truncated };
11064
11658
  }
11065
- function projectRootProblem(source, context, root) {
11659
+ function projectRootWarning(source, context, root) {
11066
11660
  if (source.origin !== "project")
11067
11661
  return;
11068
- switch (symlinkedComponent(context.checkoutRoot, root)) {
11069
- case "root":
11070
- return "a project root is a symlink";
11071
- case "ancestor":
11072
- return "a project root passes through a symlink";
11073
- default:
11074
- return;
11075
- }
11662
+ const rejection = rejectedProjectRoot(context.checkoutRoot, root);
11663
+ if (rejection === undefined)
11664
+ return;
11665
+ return rejection === "outside" ? `${source.name} resolves outside the project root; not loaded` : `${source.name}: ${PROJECT_ROOT_REJECTION_REASONS[rejection]}; source dropped`;
11076
11666
  }
11077
11667
  function gatherCandidates(source, context, warnings) {
11078
11668
  const { name, origin } = source;
@@ -11088,10 +11678,11 @@ function gatherCandidates(source, context, warnings) {
11088
11678
  outcome: nothing2(source, "dropped", warnings)
11089
11679
  });
11090
11680
  const entryBudget = newEntryBudget(context.entryLimit);
11681
+ const isExcluded = compileExcludePatterns(source.exclude);
11091
11682
  for (const root of source.roots) {
11092
- const problem = projectRootProblem(source, context, root);
11093
- if (problem !== undefined) {
11094
- warnings.push(`${name}: ${problem}; source dropped`);
11683
+ const rootWarning = projectRootWarning(source, context, root);
11684
+ if (rootWarning !== undefined) {
11685
+ warnings.push(rootWarning);
11095
11686
  return drop();
11096
11687
  }
11097
11688
  const discovery = discoverSourceFiles({
@@ -11099,6 +11690,7 @@ function gatherCandidates(source, context, warnings) {
11099
11690
  containedIn: origin === "project" ? context.checkoutRoot : undefined,
11100
11691
  walk: MARKDOWN_WALK,
11101
11692
  entryBudget,
11693
+ isExcluded,
11102
11694
  label: name
11103
11695
  }, warnings);
11104
11696
  if (discovery.state === "outside")
@@ -11159,7 +11751,8 @@ function loadDeciduousSource(source, context) {
11159
11751
  containedIn: origin === "project" ? context.checkoutRoot : undefined,
11160
11752
  remainingBytes: context.remainingBytes,
11161
11753
  maxFileBytes: EXTERNAL_MAX_FILE_BYTES,
11162
- entryLimit: context.entryLimit
11754
+ entryLimit: context.entryLimit,
11755
+ isExcluded: compileExcludePatterns(source.exclude)
11163
11756
  });
11164
11757
  return {
11165
11758
  name,
@@ -11367,22 +11960,54 @@ function capWarning(dropped) {
11367
11960
  const names = `${listed.join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
11368
11961
  return `[systematic] more than ${MAX_ACTIVE_SOURCES} search sources are active for this project; these were dropped: ${names}. Remove a source or narrow its \`projects\` to bring the count down.`;
11369
11962
  }
11370
- function mappedUserSources(declared, identity, homeDir) {
11371
- return declared.filter((entry) => entry.projects !== undefined && isAllowedProject(identity, entry.projects, { homeDir })).map((entry) => ({
11963
+ function mappedUserEntries(declared, identity, homeDir) {
11964
+ return declared.filter((entry) => entry.projects !== undefined && isAllowedProject(identity, entry.projects, { homeDir }));
11965
+ }
11966
+ function userSourceOf(entry, homeDir) {
11967
+ return {
11372
11968
  name: entry.name,
11373
11969
  format: entry.format,
11374
11970
  roots: entry.roots.map((root) => expandHome2(root, homeDir)),
11375
- origin: "user"
11376
- }));
11971
+ origin: "user",
11972
+ exclude: entry.exclude ?? []
11973
+ };
11974
+ }
11975
+ function mappedUserSources(declared, identity, homeDir) {
11976
+ return mappedUserEntries(declared, identity, homeDir).map((entry) => userSourceOf(entry, homeDir));
11977
+ }
11978
+ function projectSourceOf(entry, checkoutRoot) {
11979
+ return {
11980
+ name: entry.name,
11981
+ format: entry.format,
11982
+ roots: entry.roots.map((root) => path10.resolve(checkoutRoot, root)),
11983
+ origin: "project",
11984
+ exclude: entry.exclude ?? []
11985
+ };
11986
+ }
11987
+ function projectSourcesOf(proposals, checkoutRoot, shadowed) {
11988
+ return proposals.filter((entry) => !shadowed.has(entry.name)).map((entry) => projectSourceOf(entry, checkoutRoot));
11989
+ }
11990
+ function forwardedProjectWarnings(project, projectAllowed) {
11991
+ if (projectAllowed)
11992
+ return project.warnings;
11993
+ const aboutEntries = new Set(project.entries.flatMap((entry) => entry.warnings));
11994
+ return project.warnings.filter((warning) => !aboutEntries.has(warning));
11995
+ }
11996
+ function startDirWarnings(startDir, lookup, checkoutRoot) {
11997
+ const selected = selectProjectConfigFile(checkoutRoot).path;
11998
+ const ignored = findStartDirProjectConfig(startDir, lookup, selected);
11999
+ return ignored === undefined ? [] : [startDirProjectWarning(ignored, checkoutRoot, selected)];
11377
12000
  }
11378
12001
  function resolveExternalSources(input) {
11379
12002
  const dirs = resolveUserLevelConfigDirs(input.configOptions);
11380
12003
  const homeDir = dirs.homeDir || os3.homedir();
11381
- const checkoutRoot = resolveSearchRoot(input.startDir);
12004
+ const lookup = lookupSearchRoot(input.startDir);
12005
+ const checkoutRoot = lookup.foundGit ? lookup.root : resolveSearchRoot(input.startDir);
11382
12006
  const identity = input.identity ?? resolveProjectIdentity(checkoutRoot);
11383
12007
  const user = loadUserLevelSearchSettings(input.configOptions);
11384
12008
  const allow = user.settings?.allow_project_sources ?? [];
11385
12009
  const project = loadProjectSearchSources(checkoutRoot);
12010
+ const projectAllowed = isAllowedProject(identity, allow, { homeDir });
11386
12011
  const userSources = mappedUserSources(user.settings?.sources ?? [], identity, homeDir);
11387
12012
  let projectState;
11388
12013
  let projectSources = [];
@@ -11391,30 +12016,139 @@ function resolveExternalSources(input) {
11391
12016
  projectState = { kind: "config-unreadable" };
11392
12017
  } else if (proposals === 0) {
11393
12018
  projectState = { kind: "none" };
11394
- } else if (isAllowedProject(identity, allow, { homeDir })) {
12019
+ } else if (projectAllowed) {
11395
12020
  projectState = { kind: "allowed", proposals };
11396
- const shadowed = new Set(userSources.map((source) => source.name));
11397
- projectSources = project.sources.filter((entry) => !shadowed.has(entry.name)).map((entry) => ({
11398
- name: entry.name,
11399
- format: entry.format,
11400
- roots: entry.roots.map((root) => path10.resolve(checkoutRoot, root)),
11401
- origin: "project"
11402
- }));
12021
+ projectSources = projectSourcesOf(project.sources, checkoutRoot, new Set(userSources.map((source) => source.name)));
11403
12022
  } else {
11404
12023
  projectState = identity.status === "resolved" ? { kind: "not-allowed", proposals, mainRoot: identity.mainRoot } : { kind: "not-allowed", proposals };
11405
12024
  }
11406
12025
  const ordered = [...userSources, ...projectSources];
11407
12026
  const sources = ordered.slice(0, MAX_ACTIVE_SOURCES);
11408
- const dropped = ordered.slice(MAX_ACTIVE_SOURCES);
12027
+ const capped = ordered.slice(MAX_ACTIVE_SOURCES);
11409
12028
  return {
11410
12029
  sources,
11411
12030
  project: projectState,
11412
12031
  userConfigUnreadable: user.unreadable,
11413
12032
  warnings: [
11414
- ...dropped.length > 0 ? [capWarning(dropped)] : [],
12033
+ ...capped.length > 0 ? [capWarning(capped)] : [],
11415
12034
  ...user.warnings,
11416
- ...project.warnings
11417
- ]
12035
+ ...startDirWarnings(input.startDir, lookup, checkoutRoot),
12036
+ ...forwardedProjectWarnings(project, projectAllowed)
12037
+ ],
12038
+ dropped: { user: user.dropped, project: project.dropped }
12039
+ };
12040
+ }
12041
+ function inspectBuiltInKinds(checkoutRoot) {
12042
+ return Object.keys(KIND_TABLE).filter(isDocumentKind).map((kind) => {
12043
+ const spec = KIND_TABLE[kind];
12044
+ const directory = path10.join(checkoutRoot, ...spec.dir.split("/"));
12045
+ const discovery = discoverSourceFiles({
12046
+ directory,
12047
+ containedIn: checkoutRoot,
12048
+ walk: spec,
12049
+ label: spec.dir
12050
+ }, []);
12051
+ const state = discovery.state === "found" ? discovery.candidates.length > 0 ? "present" : "empty" : discovery.state === "missing" ? "missing" : "unreadable";
12052
+ return { kind, directory, state };
12053
+ });
12054
+ }
12055
+ function firstRootRejection(checkoutRoot, roots) {
12056
+ for (const root of roots) {
12057
+ const rejection = rejectedProjectRoot(checkoutRoot, root);
12058
+ if (rejection !== undefined)
12059
+ return rejection;
12060
+ }
12061
+ return;
12062
+ }
12063
+ function inspectSearch(input) {
12064
+ const { checkoutRoot } = input;
12065
+ const dirs = resolveUserLevelConfigDirs(input.configOptions);
12066
+ const homeDir = dirs.homeDir || os3.homedir();
12067
+ const identity = input.identity ?? resolveProjectIdentity(checkoutRoot);
12068
+ const user = loadUserLevelSearchSettings(input.configOptions);
12069
+ const allow = user.settings?.allow_project_sources ?? [];
12070
+ const project = loadProjectSearchSources(checkoutRoot);
12071
+ const projectAllowed = isAllowedProject(identity, allow, { homeDir });
12072
+ const userDeclared = mappedUserEntries(user.settings?.sources ?? [], identity, homeDir).map((entry) => ({ entry, source: userSourceOf(entry, homeDir) }));
12073
+ const shadowed = projectAllowed ? new Set(userDeclared.map(({ source }) => source.name)) : new Set;
12074
+ const projectDeclared = project.sources.filter((entry) => !shadowed.has(entry.name)).map((entry) => ({
12075
+ entry,
12076
+ source: projectSourceOf(entry, checkoutRoot)
12077
+ }));
12078
+ const ordered = [...userDeclared, ...projectAllowed ? projectDeclared : []];
12079
+ const rejected = projectAllowed ? [] : projectDeclared;
12080
+ const loaderRoot = path10.resolve(checkoutRoot);
12081
+ const outcomes = [...user.entries, ...project.entries];
12082
+ const warningsOfKept = new Map;
12083
+ for (const outcome of outcomes) {
12084
+ if (outcome.kind === "kept")
12085
+ warningsOfKept.set(outcome.entry, outcome.warnings);
12086
+ }
12087
+ const named = new Set;
12088
+ const claim = (warnings) => {
12089
+ for (const warning of warnings)
12090
+ named.add(warning);
12091
+ return warnings;
12092
+ };
12093
+ const describe = ({ source, entry }, status) => {
12094
+ const roots = source.roots.map((root) => ({
12095
+ path: root,
12096
+ present: status === "checked" ? safeLstat(root) !== null : null
12097
+ }));
12098
+ const warnings = claim(warningsOfKept.get(entry) ?? []);
12099
+ const rejection = status === "checked" && source.origin === "project" ? firstRootRejection(loaderRoot, source.roots) : undefined;
12100
+ if (rejection !== undefined) {
12101
+ return {
12102
+ status: "root rejected",
12103
+ name: source.name,
12104
+ origin: "project",
12105
+ format: source.format,
12106
+ roots,
12107
+ exclude: source.exclude,
12108
+ reason: PROJECT_ROOT_REJECTION_REASONS[rejection],
12109
+ warnings
12110
+ };
12111
+ }
12112
+ return {
12113
+ status: status === "checked" ? roots.some((root) => root.present === false) ? "missing root" : "active" : status,
12114
+ name: source.name,
12115
+ origin: source.origin === "project" ? "project" : user.sourceLayers.get(source.name) ?? "user",
12116
+ format: source.format,
12117
+ roots,
12118
+ exclude: source.exclude,
12119
+ warnings
12120
+ };
12121
+ };
12122
+ const droppedRows = [
12123
+ ...user.entries.map((outcome) => ({ outcome, origin: "user" })),
12124
+ ...project.entries.map((outcome) => ({
12125
+ outcome,
12126
+ origin: "project"
12127
+ }))
12128
+ ].flatMap(({ outcome, origin }) => outcome.kind === "dropped" ? [
12129
+ {
12130
+ status: "dropped invalid",
12131
+ name: outcome.label.startsWith('"') ? outcome.label.slice(1, -1) : outcome.label,
12132
+ origin,
12133
+ reason: outcome.reason,
12134
+ warnings: claim(outcome.warnings)
12135
+ }
12136
+ ] : []);
12137
+ const sources = [
12138
+ ...ordered.map((declared, index) => describe(declared, index < MAX_ACTIVE_SOURCES ? "checked" : "over source cap")),
12139
+ ...rejected.map((declared) => describe(declared, "not allowed")),
12140
+ ...droppedRows
12141
+ ];
12142
+ return {
12143
+ enabled: user.settings?.enabled !== false,
12144
+ allowProjectSources: allow,
12145
+ projectAllowed,
12146
+ projectRoot: checkoutRoot,
12147
+ userConfigUnreadable: user.unreadable,
12148
+ projectConfigUnreadable: project.unreadable,
12149
+ sources,
12150
+ builtIn: inspectBuiltInKinds(checkoutRoot),
12151
+ warnings: [...user.warnings, ...project.warnings].filter((warning) => !named.has(warning))
11418
12152
  };
11419
12153
  }
11420
12154
 
@@ -12454,4 +13188,4 @@ async function runExternalSearch(checked, options) {
12454
13188
  };
12455
13189
  }
12456
13190
 
12457
- export { parseFrontmatter, parse, parseTree, modify, applyEdits, CONFIG_PROTECTED_FIELD_PATHS, _isoDateTime, _isoDate, _isoTime, _isoDuration, string, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, number, boolean, array, object, union, discriminatedUnion, _enum, literal, loadUserLevelSearchSettings, AgentOverlaySchema, CategoryOverlaySchema, isRecord, isPermissionSetting, isAgentMode, extractString, toSourcedPiSubagentsOverlays, resolveRouting, loadConfig, loadConfigWithSources, isAgentDisabled, collectRoutingTargets, getConfigPaths, isDiscoverableMarkdown, findAgentsInDir, extractAgentFrontmatter, findCommandsInDir, extractCommandFrontmatter, findSkillsInDir, discoverSkills, resolveSearchRoot, SEARCH_TOOL_NAME, SEARCH_ARGS, MIN_LIMIT, MAX_LIMIT, KIND_SELECTOR_EXTERNAL, SEARCH_TOOL_DESCRIPTION, SEARCH_ARG_DESCRIPTIONS, SEARCH_NOTICES, SEARCH_CONFIG_UNREADABLE_NOTE, runSearch };
13191
+ export { parseFrontmatter, parse, parseTree, modify, applyEdits, CONFIG_PROTECTED_FIELD_PATHS, _isoDateTime, _isoDate, _isoTime, _isoDuration, string, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, number, boolean, array, object, union, discriminatedUnion, _enum, literal, displaySafe, MAX_PROJECT_CONFIG_BYTES, readTextBounded, loadUserLevelSearchSettings, AgentOverlaySchema, CategoryOverlaySchema, isRecord, isPermissionSetting, isAgentMode, extractString, toSourcedPiSubagentsOverlays, resolveRouting, loadConfig, loadConfigWithSources, isAgentDisabled, collectRoutingTargets, getConfigPaths, isDiscoverableMarkdown, findAgentsInDir, extractAgentFrontmatter, findCommandsInDir, extractCommandFrontmatter, findSkillsInDir, discoverSkills, inspectSearch, SEARCH_TOOL_NAME, SEARCH_ARGS, MIN_LIMIT, MAX_LIMIT, KIND_SELECTOR_EXTERNAL, SEARCH_TOOL_DESCRIPTION, SEARCH_ARG_DESCRIPTIONS, SEARCH_NOTICES, SEARCH_CONFIG_UNREADABLE_NOTE, runSearch };