@fro.bot/systematic 3.27.2 → 3.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/ATTRIBUTIONS.md +2 -2
  2. package/HARNESSES.md +22 -9
  3. package/agents/research/learnings-researcher.md +49 -9
  4. package/dist/claude-code-search.d.ts +30 -0
  5. package/dist/claude-code-validator-bin.d.ts +17 -0
  6. package/dist/cli.d.ts +18 -0
  7. package/dist/cli.js +335 -108
  8. package/dist/{index-608preny.js → index-9chxhh5j.js} +1120 -72
  9. package/dist/index.js +117 -3
  10. package/dist/lib/agent-resolver.d.ts +8 -2
  11. package/dist/lib/config-protected-fields.d.ts +1 -1
  12. package/dist/lib/config-schema.d.ts +6 -0
  13. package/dist/lib/config.d.ts +13 -0
  14. package/dist/lib/main-module.d.ts +30 -0
  15. package/dist/lib/opencode-v2-skills.d.ts +12 -2
  16. package/dist/lib/opencode-v2.d.ts +1 -0
  17. package/dist/lib/pi-delegate-session.d.ts +3 -1
  18. package/dist/lib/pi-delegate-tool.d.ts +12 -1
  19. package/dist/lib/search-cli.d.ts +52 -0
  20. package/dist/lib/search-core.d.ts +128 -0
  21. package/dist/lib/search-corpus.d.ts +105 -0
  22. package/dist/lib/search-lexical.d.ts +136 -0
  23. package/dist/lib/search-render.d.ts +69 -0
  24. package/dist/lib/search-tool.d.ts +53 -0
  25. package/dist/lib/search-user-config.d.ts +96 -0
  26. package/dist/pi.js +1155 -77
  27. package/package.json +3 -3
  28. package/skills/ce-review/SKILL.md +1 -1
  29. package/skills/ce-review/references/review-output-template.md +1 -1
  30. package/skills/ce-review/scripts/validate-review.mjs +1 -3
  31. package/skills/using-systematic/references/claude-code-profile.md +1 -0
  32. package/skills/using-systematic/references/opencode-profile.md +1 -0
  33. package/skills/using-systematic/references/opencode-v2-profile.md +1 -0
  34. package/skills/using-systematic/references/pi-profile.md +1 -0
@@ -2,7 +2,7 @@
2
2
  // src/lib/frontmatter.ts
3
3
  import yaml from "js-yaml";
4
4
  function parseFrontmatter(content) {
5
- const frontmatterRegex = /^---\r?\n([\s\S]*?)\r?\n?---\r?\n([\s\S]*)$/;
5
+ const frontmatterRegex = /^---\r?\n((?:[\s\S]*?\r?\n)?)---\r?\n([\s\S]*)$/;
6
6
  const match = content.match(frontmatterRegex);
7
7
  if (!match) {
8
8
  return {
@@ -23,9 +23,8 @@ function parseFrontmatter(content) {
23
23
  }
24
24
 
25
25
  // src/lib/config.ts
26
- import fs from "fs";
27
- import os from "os";
28
- import path from "path";
26
+ import fs2 from "fs";
27
+ import path2 from "path";
29
28
 
30
29
  // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
31
30
  function createScanner(text, ignoreTrivia = false) {
@@ -1507,6 +1506,7 @@ var BUNDLED_SKILL_NAMES = [
1507
1506
  var CONFIG_PROTECTED_FIELD_PATHS = [
1508
1507
  "profiles",
1509
1508
  "allow_project_profiles",
1509
+ "search",
1510
1510
  "agents.*.model",
1511
1511
  "agents.*.permission",
1512
1512
  "agents.*.skills",
@@ -7477,6 +7477,139 @@ var REMOVED_CONFIG_KEYS = [
7477
7477
  "workflow_guard"
7478
7478
  ];
7479
7479
 
7480
+ // src/lib/search-user-config.ts
7481
+ import fs from "fs";
7482
+ import os from "os";
7483
+ import path from "path";
7484
+ var SearchSettingsSchema = object({
7485
+ enabled: boolean().optional().meta({
7486
+ description: "Set to false to remove the search tool. Defaults to true when unset.",
7487
+ examples: [false]
7488
+ })
7489
+ }).strict().meta({
7490
+ description: "Durable-output search settings. Only user config and OPENCODE_CONFIG_DIR config may set this field; a project config that sets it has the whole field ignored with a warning, so a repository cannot switch search off. An invalid block is dropped with a warning; the rest of the file still loads.",
7491
+ examples: [{ enabled: false }]
7492
+ });
7493
+ function validateSearchBlock(value) {
7494
+ const parsed = SearchSettingsSchema.safeParse(value);
7495
+ if (parsed.success)
7496
+ return { ok: true, settings: parsed.data };
7497
+ const fields = [];
7498
+ for (const issue of parsed.error.issues) {
7499
+ const field = ["search", ...issue.path.map(String)].join(".");
7500
+ if (!fields.includes(field))
7501
+ fields.push(field);
7502
+ }
7503
+ return { ok: false, fields };
7504
+ }
7505
+ var MAX_WARNING_FIELDS = 5;
7506
+ var MAX_PATH_CHARS = 200;
7507
+ function displaySafe(text) {
7508
+ let out = "";
7509
+ for (const char of text) {
7510
+ if (out.length >= MAX_PATH_CHARS)
7511
+ return `${out}\u2026`;
7512
+ const code = char.codePointAt(0) ?? 0;
7513
+ const isControl = code <= 31 || code === 127 || code >= 128 && code <= 159 || code === 8232 || code === 8233;
7514
+ out += isControl ? `\\u${code.toString(16).padStart(4, "0")}` : char;
7515
+ }
7516
+ return out;
7517
+ }
7518
+ function formatSearchBlockWarning(sourcePath, fields) {
7519
+ const shown = fields.slice(0, MAX_WARNING_FIELDS).join(", ");
7520
+ const more = fields.length > MAX_WARNING_FIELDS ? ` and ${fields.length - MAX_WARNING_FIELDS} more` : "";
7521
+ return `[systematic] \`search\` in ${displaySafe(sourcePath)} is invalid (${shown}${more}) and has been ignored; search still runs and its results carry a \`config unreadable\` note. The rest of the file still loads.`;
7522
+ }
7523
+ function formatSearchFileWarning(sourcePath, reason) {
7524
+ 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.`;
7525
+ }
7526
+ function mergeSearchSettings(sources) {
7527
+ let enabled;
7528
+ let unreadable = false;
7529
+ for (const source of sources) {
7530
+ if (source.unreadable)
7531
+ unreadable = true;
7532
+ if (source.settings?.enabled !== undefined)
7533
+ enabled = source.settings.enabled;
7534
+ }
7535
+ if (enabled === undefined)
7536
+ return { settings: undefined, unreadable };
7537
+ return { settings: { enabled }, unreadable };
7538
+ }
7539
+ function selectConfigFile(dir, basename) {
7540
+ const jsoncPath = path.join(dir, `${basename}.jsonc`);
7541
+ if (fs.existsSync(jsoncPath))
7542
+ return jsoncPath;
7543
+ return path.join(dir, `${basename}.json`);
7544
+ }
7545
+ function resolveUserLevelConfigDirs(options) {
7546
+ const homeDir = options?.homeDir ?? os.homedir();
7547
+ const userConfigDir = options?.userConfigDir ?? path.join(homeDir, ".config/opencode");
7548
+ const rawCustom = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
7549
+ return { homeDir, userConfigDir, customConfigDir: rawCustom || undefined };
7550
+ }
7551
+ function isRecord2(value) {
7552
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7553
+ }
7554
+ function readSearchBlock(filePath) {
7555
+ let content;
7556
+ try {
7557
+ content = fs.readFileSync(filePath, "utf-8");
7558
+ } catch (error) {
7559
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
7560
+ if (code === "ENOENT")
7561
+ return { kind: "absent" };
7562
+ return { kind: "failed", reason: "unable to read file" };
7563
+ }
7564
+ const errors = [];
7565
+ const parsed = parse(content, errors);
7566
+ const firstError = errors[0];
7567
+ if (firstError) {
7568
+ return {
7569
+ kind: "failed",
7570
+ reason: `JSONC parse error: ${printParseErrorCode(firstError.error)}`
7571
+ };
7572
+ }
7573
+ if (!isRecord2(parsed)) {
7574
+ return { kind: "failed", reason: "root must be an object" };
7575
+ }
7576
+ return {
7577
+ kind: "read",
7578
+ has: Object.hasOwn(parsed, "search"),
7579
+ searchBlock: parsed.search
7580
+ };
7581
+ }
7582
+ function loadUserLevelSearchSettings(options) {
7583
+ const dirs = resolveUserLevelConfigDirs(options);
7584
+ const files = [
7585
+ selectConfigFile(dirs.userConfigDir, "systematic"),
7586
+ ...dirs.customConfigDir ? [selectConfigFile(dirs.customConfigDir, "systematic")] : []
7587
+ ];
7588
+ const warnings = [];
7589
+ const sources = [];
7590
+ for (const filePath of files) {
7591
+ const read = readSearchBlock(filePath);
7592
+ if (read.kind === "absent")
7593
+ continue;
7594
+ if (read.kind === "failed") {
7595
+ warnings.push(formatSearchFileWarning(filePath, read.reason));
7596
+ sources.push({ unreadable: true });
7597
+ continue;
7598
+ }
7599
+ if (!read.has)
7600
+ continue;
7601
+ const validation = validateSearchBlock(read.searchBlock);
7602
+ if (validation.ok) {
7603
+ sources.push({ settings: validation.settings, unreadable: false });
7604
+ } else {
7605
+ warnings.push(formatSearchBlockWarning(filePath, validation.fields));
7606
+ sources.push({ unreadable: true });
7607
+ }
7608
+ }
7609
+ const merged = mergeSearchSettings(sources);
7610
+ return { ...merged, warnings };
7611
+ }
7612
+
7480
7613
  // src/lib/config-schema.ts
7481
7614
  var permissionSettingSchema = _enum(["ask", "allow", "deny"]);
7482
7615
  var permissionRuleSchema = union([
@@ -7766,6 +7899,7 @@ function createSystematicConfigSchema(opts) {
7766
7899
  description: "Allow a repository's project config to define its own `profiles` map. User-owned only \u2014 only valid in user config or OPENCODE_CONFIG_DIR config; a project config setting this field has it ignored (a project cannot grant itself a permission it does not already have). Defaults to false.",
7767
7900
  examples: [true, false]
7768
7901
  })).default(false),
7902
+ search: trustProtected(SearchSettingsSchema).optional(),
7769
7903
  disabled_skills: array(_enum([...skillNames, ...removedSkillNames])).default([]).meta({
7770
7904
  description: "Array of bundled skill names to disable globally. Unknown skill names are rejected at parse time.",
7771
7905
  examples: [["ce:plan", "ce:review"]]
@@ -8198,7 +8332,10 @@ var PROTECTED_OVERLAY_FIELD_PATHS = {
8198
8332
  pi: "categories.*.pi"
8199
8333
  }
8200
8334
  };
8201
- var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set(["allow_project_profiles"]);
8335
+ var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set([
8336
+ "allow_project_profiles",
8337
+ "search"
8338
+ ]);
8202
8339
  var MAX_DIAGNOSTIC_TEXT = 200;
8203
8340
  var MAX_STRIP_WARNINGS = 20;
8204
8341
  var DIAGNOSTIC_ELLIPSIS = "\u2026";
@@ -8275,19 +8412,13 @@ function warnDroppedNames(dropped, field, warned, removalVersion, warningSink =
8275
8412
  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.`);
8276
8413
  }
8277
8414
  }
8278
- function resolveConfigPath(dir, basename) {
8279
- const jsoncPath = path.join(dir, `${basename}.jsonc`);
8280
- if (fs.existsSync(jsoncPath))
8281
- return jsoncPath;
8282
- return path.join(dir, `${basename}.json`);
8283
- }
8284
8415
  function isErrorWithCode(error) {
8285
8416
  return error instanceof Error && "code" in error;
8286
8417
  }
8287
8418
  function loadJsoncFile(filePath) {
8288
8419
  let content;
8289
8420
  try {
8290
- content = fs.readFileSync(filePath, "utf-8");
8421
+ content = fs2.readFileSync(filePath, "utf-8");
8291
8422
  } catch (error) {
8292
8423
  if (isErrorWithCode(error) && error.code === "ENOENT")
8293
8424
  return null;
@@ -8300,7 +8431,7 @@ function loadJsoncFile(filePath) {
8300
8431
  const message = error ? `${printParseErrorCode(error.error)} at offset ${error.offset}` : "unknown parse error";
8301
8432
  throw new Error(`Invalid Systematic config in ${filePath}: JSONC parse error: ${message}`);
8302
8433
  }
8303
- if (!isRecord2(parsed)) {
8434
+ if (!isRecord3(parsed)) {
8304
8435
  throw new Error(`Invalid Systematic config in ${filePath}: root must be an object`);
8305
8436
  }
8306
8437
  return parsed;
@@ -8353,9 +8484,9 @@ function enrichTopLevelTypedKeyIssue(issue, rawInput) {
8353
8484
  function enrichUnrecognizedKeyIssues(issues, rawInput) {
8354
8485
  return issues.map((issue) => enrichProfileAgentUnrecognizedKeysIssue(issue) ?? enrichTopLevelTypedKeyIssue(issue, rawInput) ?? issue);
8355
8486
  }
8356
- function resolveValueAtPath(root, path2) {
8487
+ function resolveValueAtPath(root, path) {
8357
8488
  let current = root;
8358
- for (const segment of path2) {
8489
+ for (const segment of path) {
8359
8490
  if (typeof segment === "symbol") {
8360
8491
  return;
8361
8492
  }
@@ -8364,7 +8495,7 @@ function resolveValueAtPath(root, path2) {
8364
8495
  return;
8365
8496
  current = current[segment];
8366
8497
  } else {
8367
- if (!isRecord2(current))
8498
+ if (!isRecord3(current))
8368
8499
  return;
8369
8500
  current = current[segment];
8370
8501
  }
@@ -8403,19 +8534,21 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProj
8403
8534
  const protectedFields = collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles);
8404
8535
  const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig, allowProjectProfiles) : rawConfig;
8405
8536
  const config = trust === "project" ? stripProjectSecurityOverlayFields(topLevelStripped, filePath, warningSink) : topLevelStripped;
8406
- const result = SystematicConfigSchema.safeParse(config);
8537
+ const { config: configWithoutSearch, search } = splitSearchBlock(config, filePath, warningSink);
8538
+ const result = SystematicConfigSchema.safeParse(configWithoutSearch);
8407
8539
  if (!result.success) {
8408
- throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, config);
8540
+ throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, configWithoutSearch);
8409
8541
  }
8410
8542
  return {
8411
8543
  metadata: { kind: trust, presence: "present" },
8412
8544
  source: {
8413
8545
  kind: "file",
8414
8546
  canonicalPath: resolveConfigSourcePath(filePath),
8415
- config,
8547
+ config: configWithoutSearch,
8416
8548
  path: filePath,
8417
8549
  protectedFields,
8418
8550
  removedKeys: REMOVED_CONFIG_KEYS.filter((key) => Object.hasOwn(rawConfig, key)),
8551
+ ...search && { search },
8419
8552
  trust
8420
8553
  }
8421
8554
  };
@@ -8432,6 +8565,23 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProj
8432
8565
  };
8433
8566
  }
8434
8567
  }
8568
+ function splitSearchBlock(config, filePath, warningSink) {
8569
+ if (!Object.hasOwn(config, "search"))
8570
+ return { config, search: undefined };
8571
+ const { search: rawSearch, ...rest } = config;
8572
+ const validation = validateSearchBlock(rawSearch);
8573
+ if (validation.ok) {
8574
+ return {
8575
+ config: rest,
8576
+ search: { settings: validation.settings, unreadable: false }
8577
+ };
8578
+ }
8579
+ warningSink(formatSearchBlockWarning(filePath, validation.fields));
8580
+ return {
8581
+ config: rest,
8582
+ search: { unreadable: true }
8583
+ };
8584
+ }
8435
8585
  function classifyConfigSourceError(error) {
8436
8586
  if (isConfigSchemaError(error))
8437
8587
  return "schema-invalid";
@@ -8444,13 +8594,13 @@ function classifyConfigSourceError(error) {
8444
8594
  return "source-invalid";
8445
8595
  }
8446
8596
  function isConfigSchemaError(error) {
8447
- return isRecord2(error) && error._tag === "ConfigSchemaError";
8597
+ return isRecord3(error) && error._tag === "ConfigSchemaError";
8448
8598
  }
8449
8599
  function resolveConfigSourcePath(filePath) {
8450
8600
  try {
8451
- return fs.realpathSync(filePath);
8601
+ return fs2.realpathSync(filePath);
8452
8602
  } catch {
8453
- return path.resolve(filePath);
8603
+ return path2.resolve(filePath);
8454
8604
  }
8455
8605
  }
8456
8606
  function emitTopLevelProtectedFieldWarning(projectSource, fieldPath, messageTemplate, sink) {
@@ -8478,14 +8628,21 @@ function collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles) {
8478
8628
  sourceKind: "project"
8479
8629
  }
8480
8630
  ] : [],
8631
+ ...Object.hasOwn(rawConfig, "search") ? [
8632
+ {
8633
+ fieldPath: "search",
8634
+ outcome: "blocked",
8635
+ sourceKind: "project"
8636
+ }
8637
+ ] : [],
8481
8638
  ...collectOverlayProtectedFields(rawConfig.agents, "agents"),
8482
8639
  ...collectOverlayProtectedFields(rawConfig.categories, "categories")
8483
8640
  ];
8484
8641
  }
8485
8642
  function collectOverlayProtectedFields(overlayMap, mapKey) {
8486
- if (!isRecord2(overlayMap))
8643
+ if (!isRecord3(overlayMap))
8487
8644
  return [];
8488
- return Object.values(overlayMap).flatMap((value) => isRecord2(value) ? collectProtectedOverlayValue(value, mapKey) : []);
8645
+ return Object.values(overlayMap).flatMap((value) => isRecord3(value) ? collectProtectedOverlayValue(value, mapKey) : []);
8489
8646
  }
8490
8647
  function collectProtectedOverlayValue(value, mapKey) {
8491
8648
  return [...SECURITY_OVERLAY_FIELDS].filter((field) => Object.hasOwn(value, field)).map((field) => ({
@@ -8518,12 +8675,12 @@ function stripProjectSecurityOverlayFields(rawConfig, filePath, warningSink) {
8518
8675
  return result;
8519
8676
  }
8520
8677
  function stripSecurityOverlayEntries(overlayMap, mapKey, filePath, warningSink) {
8521
- if (!isRecord2(overlayMap))
8678
+ if (!isRecord3(overlayMap))
8522
8679
  return overlayMap;
8523
8680
  let changed = false;
8524
8681
  const result = {};
8525
8682
  for (const [key, value] of Object.entries(overlayMap)) {
8526
- if (!isRecord2(value)) {
8683
+ if (!isRecord3(value)) {
8527
8684
  result[key] = value;
8528
8685
  continue;
8529
8686
  }
@@ -8539,7 +8696,7 @@ function stripSecurityOverlayEntries(overlayMap, mapKey, filePath, warningSink)
8539
8696
  }
8540
8697
  return changed ? result : overlayMap;
8541
8698
  }
8542
- function isRecord2(value) {
8699
+ function isRecord3(value) {
8543
8700
  return typeof value === "object" && value !== null && !Array.isArray(value);
8544
8701
  }
8545
8702
  function mergeArraysUnique(arr1, arr2) {
@@ -8744,6 +8901,7 @@ function loadConfigWithSources(projectDir, options) {
8744
8901
  const projectSource = project.source;
8745
8902
  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);
8746
8903
  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);
8904
+ emitTopLevelProtectedFieldWarning(projectSource, "search", `\`search\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`, boundedProjectStrip.sink);
8747
8905
  const suppressedStripCount = boundedProjectStrip.suppressedCount();
8748
8906
  if (suppressedStripCount > 0) {
8749
8907
  projectStrip.sink(`[systematic] ${suppressedStripCount} additional project-config protected-field warning(s) in (${sanitizeDiagnosticText(paths.projectConfig)}) were suppressed.`);
@@ -8769,6 +8927,7 @@ function loadConfigWithSources(projectDir, options) {
8769
8927
  const projectConfig = projectSource?.config;
8770
8928
  const customConfig = customSource?.config;
8771
8929
  const warned = new Set;
8930
+ const mergedSearch = mergeSearchSettings([userSource?.search, customSource?.search].filter((source) => source !== undefined));
8772
8931
  assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig);
8773
8932
  const profileSelection = resolveActiveProfile({
8774
8933
  userConfig,
@@ -8821,7 +8980,9 @@ function loadConfigWithSources(projectDir, options) {
8821
8980
  agents: overlayValues(mergedPiSubagentsOverlays.agents)
8822
8981
  },
8823
8982
  skills_as_commands: customConfig?.skills_as_commands ?? projectConfig?.skills_as_commands ?? userConfig?.skills_as_commands ?? DEFAULT_CONFIG.skills_as_commands,
8824
- allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles
8983
+ allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles,
8984
+ ...mergedSearch.settings && { search: mergedSearch.settings },
8985
+ ...mergedSearch.unreadable && { searchUnreadable: true }
8825
8986
  };
8826
8987
  const droppedSkills = computeDroppedNames(result.disabled_skills, CURRENT_SKILL_NAMES_SET);
8827
8988
  warnDroppedNames(droppedSkills, "disabled_skills", warned, undefined, warningSink);
@@ -8908,7 +9069,7 @@ function hasConfigField(config, fieldPath) {
8908
9069
  if (nested === undefined)
8909
9070
  return config[topLevel] !== undefined;
8910
9071
  const value = config[topLevel];
8911
- return isRecord2(value) && value[nested] !== undefined;
9072
+ return isRecord3(value) && value[nested] !== undefined;
8912
9073
  }
8913
9074
  function sortAuthorities(authorities) {
8914
9075
  return [...authorities].sort((left, right) => left.fieldPath === right.fieldPath ? left.sourceKind.localeCompare(right.sourceKind) : left.fieldPath.localeCompare(right.fieldPath));
@@ -8999,12 +9160,12 @@ function mergeOverlayMap(target, source, mapKey) {
8999
9160
  const overlayMap = source.config[mapKey];
9000
9161
  if (overlayMap === undefined)
9001
9162
  return;
9002
- if (!isRecord2(overlayMap)) {
9163
+ if (!isRecord3(overlayMap)) {
9003
9164
  throwInvalidOverlay(source.path, mapKey);
9004
9165
  }
9005
9166
  for (const [key, value] of Object.entries(overlayMap)) {
9006
9167
  const keyPath = source.kind === "profile-bundle" ? `profiles.${source.profileName}.${mapKey}.${key}` : `${mapKey}.${key}`;
9007
- if (!isRecord2(value)) {
9168
+ if (!isRecord3(value)) {
9008
9169
  throwInvalidOverlay(source.path, keyPath);
9009
9170
  }
9010
9171
  const previous = target[key];
@@ -9031,14 +9192,14 @@ function routingOriginsFromOwnFields(fragment, tag) {
9031
9192
  if (Object.hasOwn(fragment, "variant"))
9032
9193
  origins.variant = tag;
9033
9194
  const opencodeBlock = fragment.opencode;
9034
- if (isRecord2(opencodeBlock)) {
9195
+ if (isRecord3(opencodeBlock)) {
9035
9196
  if (Object.hasOwn(opencodeBlock, "model"))
9036
9197
  origins.opencodeModel = tag;
9037
9198
  if (Object.hasOwn(opencodeBlock, "variant"))
9038
9199
  origins.opencodeVariant = tag;
9039
9200
  }
9040
9201
  const piBlock = fragment.pi;
9041
- if (isRecord2(piBlock)) {
9202
+ if (isRecord3(piBlock)) {
9042
9203
  if (Object.hasOwn(piBlock, "model"))
9043
9204
  origins.piModel = tag;
9044
9205
  if (Object.hasOwn(piBlock, "thinking"))
@@ -9093,7 +9254,7 @@ function mergeProfileOverlayValue(previous, next) {
9093
9254
  for (const blockKey of HARNESS_BLOCK_KEYS) {
9094
9255
  const previousBlock = previous[blockKey];
9095
9256
  const nextBlock = next[blockKey];
9096
- if (isRecord2(previousBlock) && isRecord2(nextBlock)) {
9257
+ if (isRecord3(previousBlock) && isRecord3(nextBlock)) {
9097
9258
  result[blockKey] = { ...previousBlock, ...nextBlock };
9098
9259
  }
9099
9260
  }
@@ -9133,12 +9294,12 @@ function mergePiSubagentsOverlayMap(target, source, mapKey) {
9133
9294
  const overlayMap = source.config.pi_subagents?.[mapKey];
9134
9295
  if (overlayMap === undefined)
9135
9296
  return;
9136
- if (!isRecord2(overlayMap)) {
9297
+ if (!isRecord3(overlayMap)) {
9137
9298
  throwInvalidOverlay(source.path, `pi_subagents.${mapKey}`);
9138
9299
  }
9139
9300
  for (const [key, rawValue] of Object.entries(overlayMap)) {
9140
9301
  const keyPath = `pi_subagents.${mapKey}.${key}`;
9141
- if (!isRecord2(rawValue)) {
9302
+ if (!isRecord3(rawValue)) {
9142
9303
  throwInvalidOverlay(source.path, keyPath);
9143
9304
  }
9144
9305
  const previous = target[key];
@@ -9161,39 +9322,37 @@ function throwInvalidOverlay(sourcePath, keyPath) {
9161
9322
  throw new Error(`Invalid Systematic config in ${sourcePath}: ${keyPath} must be an object`);
9162
9323
  }
9163
9324
  function getConfigPaths(projectDir, options) {
9164
- const homeDir = options?.homeDir ?? os.homedir();
9165
- const userConfigDir = options?.userConfigDir ?? path.join(homeDir, ".config/opencode");
9166
- const customConfigDir = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
9325
+ const { homeDir, userConfigDir, customConfigDir } = resolveUserLevelConfigDirs(options);
9167
9326
  const result = {
9168
- userConfig: resolveConfigPath(userConfigDir, "systematic"),
9169
- projectConfig: resolveConfigPath(path.join(projectDir, ".opencode"), "systematic"),
9170
- userDir: path.join(homeDir, ".config/opencode/systematic"),
9171
- projectDir: path.join(projectDir, ".opencode/systematic"),
9327
+ userConfig: selectConfigFile(userConfigDir, "systematic"),
9328
+ projectConfig: selectConfigFile(path2.join(projectDir, ".opencode"), "systematic"),
9329
+ userDir: path2.join(homeDir, ".config/opencode/systematic"),
9330
+ projectDir: path2.join(projectDir, ".opencode/systematic"),
9172
9331
  ...customConfigDir && {
9173
- customConfig: resolveConfigPath(customConfigDir, "systematic"),
9174
- customDir: path.join(customConfigDir, "systematic")
9332
+ customConfig: selectConfigFile(customConfigDir, "systematic"),
9333
+ customDir: path2.join(customConfigDir, "systematic")
9175
9334
  }
9176
9335
  };
9177
9336
  return result;
9178
9337
  }
9179
9338
 
9180
9339
  // src/lib/walk-dir.ts
9181
- import fs2 from "fs";
9182
- import path2 from "path";
9340
+ import fs3 from "fs";
9341
+ import path3 from "path";
9183
9342
  function isDiscoverableMarkdown(fileName) {
9184
9343
  return fileName.endsWith(".md") && fileName.toLowerCase() !== "readme.md";
9185
9344
  }
9186
9345
  function walkDir(rootDir, options = {}) {
9187
9346
  const { maxDepth = 3, filter } = options;
9188
9347
  const results = [];
9189
- if (!fs2.existsSync(rootDir))
9348
+ if (!fs3.existsSync(rootDir))
9190
9349
  return results;
9191
9350
  function recurse(currentDir, depth, category) {
9192
9351
  if (depth > maxDepth)
9193
9352
  return;
9194
- const entries = fs2.readdirSync(currentDir, { withFileTypes: true });
9353
+ const entries = fs3.readdirSync(currentDir, { withFileTypes: true });
9195
9354
  for (const entry of entries) {
9196
- const fullPath = path2.join(currentDir, entry.name);
9355
+ const fullPath = path3.join(currentDir, entry.name);
9197
9356
  const walkEntry = {
9198
9357
  path: fullPath,
9199
9358
  name: entry.name,
@@ -9288,12 +9447,12 @@ function extractCommandFrontmatter(content) {
9288
9447
  }
9289
9448
 
9290
9449
  // src/lib/discovered-skills.ts
9291
- import fs4 from "fs";
9292
- import path4 from "path";
9450
+ import fs5 from "fs";
9451
+ import path5 from "path";
9293
9452
 
9294
9453
  // src/lib/skills.ts
9295
- import fs3 from "fs";
9296
- import path3 from "path";
9454
+ import fs4 from "fs";
9455
+ import path4 from "path";
9297
9456
  function parseMetadata(data) {
9298
9457
  const metadataRaw = data.metadata;
9299
9458
  if (!isRecord(metadataRaw)) {
@@ -9330,7 +9489,7 @@ function extractFrontmatterFromContent(content) {
9330
9489
  }
9331
9490
  function extractFrontmatter(filePath) {
9332
9491
  try {
9333
- const content = fs3.readFileSync(filePath, "utf8");
9492
+ const content = fs4.readFileSync(filePath, "utf8");
9334
9493
  return extractFrontmatterFromContent(content);
9335
9494
  } catch {
9336
9495
  return { name: "", description: "" };
@@ -9343,8 +9502,8 @@ function findSkillsInDir(dir, maxDepth = 3) {
9343
9502
  filter: (e) => e.isDirectory
9344
9503
  });
9345
9504
  for (const entry of entries) {
9346
- const skillFile = path3.join(entry.path, "SKILL.md");
9347
- if (fs3.existsSync(skillFile)) {
9505
+ const skillFile = path4.join(entry.path, "SKILL.md");
9506
+ if (fs4.existsSync(skillFile)) {
9348
9507
  const frontmatter = extractFrontmatter(skillFile);
9349
9508
  skills.push({
9350
9509
  path: entry.path,
@@ -9373,16 +9532,16 @@ function isValidSkillName(name) {
9373
9532
  return name.length >= 1 && name.length <= 64 && SKILL_NAME_REGEX.test(name);
9374
9533
  }
9375
9534
  function findGitWorktreeRoot(startDir) {
9376
- let current = path4.resolve(startDir);
9535
+ let current = path5.resolve(startDir);
9377
9536
  while (true) {
9378
9537
  try {
9379
- if (fs4.existsSync(path4.join(current, ".git"))) {
9538
+ if (fs5.existsSync(path5.join(current, ".git"))) {
9380
9539
  return current;
9381
9540
  }
9382
9541
  } catch {
9383
9542
  return null;
9384
9543
  }
9385
- const parent = path4.dirname(current);
9544
+ const parent = path5.dirname(current);
9386
9545
  if (parent === current)
9387
9546
  return null;
9388
9547
  current = parent;
@@ -9390,20 +9549,20 @@ function findGitWorktreeRoot(startDir) {
9390
9549
  }
9391
9550
  function upWalk(targets, start, stop) {
9392
9551
  const results = [];
9393
- let current = path4.resolve(start);
9394
- const resolvedStop = stop === undefined ? undefined : path4.resolve(stop);
9552
+ let current = path5.resolve(start);
9553
+ const resolvedStop = stop === undefined ? undefined : path5.resolve(stop);
9395
9554
  while (true) {
9396
9555
  for (const target of targets) {
9397
- const candidate = path4.join(current, target);
9556
+ const candidate = path5.join(current, target);
9398
9557
  try {
9399
- if (fs4.existsSync(candidate)) {
9558
+ if (fs5.existsSync(candidate)) {
9400
9559
  results.push(candidate);
9401
9560
  }
9402
9561
  } catch {}
9403
9562
  }
9404
9563
  if (resolvedStop !== undefined && current === resolvedStop)
9405
9564
  break;
9406
- const parent = path4.dirname(current);
9565
+ const parent = path5.dirname(current);
9407
9566
  if (parent === current)
9408
9567
  break;
9409
9568
  current = parent;
@@ -9425,9 +9584,9 @@ function buildOpencodeConfigDirs(startDir, homeDir, gitRoot, globalConfigDir, op
9425
9584
  function globSkillFiles(rootDir, subdirNames) {
9426
9585
  const results = [];
9427
9586
  for (const subdirName of subdirNames) {
9428
- const scanRoot = path4.join(rootDir, subdirName);
9587
+ const scanRoot = path5.join(rootDir, subdirName);
9429
9588
  try {
9430
- if (!fs4.existsSync(scanRoot))
9589
+ if (!fs5.existsSync(scanRoot))
9431
9590
  continue;
9432
9591
  const entries = walkDir(scanRoot, {
9433
9592
  maxDepth: 10,
@@ -9443,7 +9602,7 @@ function globSkillFiles(rootDir, subdirNames) {
9443
9602
  function toDiscoveredSkill(skillPath, rootId, onIssue) {
9444
9603
  let content;
9445
9604
  try {
9446
- content = fs4.readFileSync(skillPath, "utf8");
9605
+ content = fs5.readFileSync(skillPath, "utf8");
9447
9606
  } catch {
9448
9607
  onIssue?.("read-failed");
9449
9608
  return;
@@ -9469,7 +9628,7 @@ function toDiscoveredSkill(skillPath, rootId, onIssue) {
9469
9628
  }
9470
9629
  function discoverSkills(options) {
9471
9630
  const { startDir, homeDir, configDir, onIssue, opencodeConfigDirOverride } = options;
9472
- const globalConfigDir = configDir ?? path4.join(homeDir, ".config/opencode");
9631
+ const globalConfigDir = configDir ?? path5.join(homeDir, ".config/opencode");
9473
9632
  const gitRoot = findGitWorktreeRoot(startDir);
9474
9633
  const byName = new Map;
9475
9634
  function upsertAll(skillPaths, rootId) {
@@ -9483,8 +9642,8 @@ function discoverSkills(options) {
9483
9642
  upsertAll(globSkillFiles(homeDir, [".agents/skills"]), "global-agents");
9484
9643
  const externalLevels = upWalk([".claude", ".agents"], startDir, gitRoot ?? startDir);
9485
9644
  for (const levelDir of externalLevels) {
9486
- const isClaudeDir = path4.basename(levelDir) === ".claude";
9487
- const parentDir = path4.dirname(levelDir);
9645
+ const isClaudeDir = path5.basename(levelDir) === ".claude";
9646
+ const parentDir = path5.dirname(levelDir);
9488
9647
  const subdirGlob = isClaudeDir ? ".claude/skills" : ".agents/skills";
9489
9648
  const rootId = isClaudeDir ? "project-claude" : "project-agents";
9490
9649
  upsertAll(globSkillFiles(parentDir, [subdirGlob]), rootId);
@@ -9497,4 +9656,893 @@ function discoverSkills(options) {
9497
9656
  return Array.from(byName.values());
9498
9657
  }
9499
9658
 
9500
- 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, AgentOverlaySchema, CategoryOverlaySchema, isRecord, isPermissionSetting, isAgentMode, extractString, toSourcedPiSubagentsOverlays, resolveRouting, loadConfig, loadConfigWithSources, isAgentDisabled, collectRoutingTargets, getConfigPaths, isDiscoverableMarkdown, findAgentsInDir, extractAgentFrontmatter, findCommandsInDir, extractCommandFrontmatter, findSkillsInDir, discoverSkills };
9659
+ // src/lib/search-corpus.ts
9660
+ import fs6 from "fs";
9661
+ import path6 from "path";
9662
+ var MAX_FILE_BYTES = 256 * 1024;
9663
+ var MAX_FILES = 2000;
9664
+ var MAX_DEPTH = 6;
9665
+ var MAX_TOTAL_BYTES = 16 * 1024 * 1024;
9666
+ var MAX_DISCOVERED_FILES = MAX_FILES * 4;
9667
+ var MAX_WARNING_LENGTH = 200;
9668
+ var KIND_TABLE = {
9669
+ solution: {
9670
+ dir: "docs/solutions",
9671
+ excludedFiles: ["readme.md", "critical-patterns.md"],
9672
+ excludedDirs: ["_archived"],
9673
+ lifecycle: true
9674
+ }
9675
+ };
9676
+ function isDocumentKind(value) {
9677
+ return typeof value === "string" && Object.hasOwn(KIND_TABLE, value);
9678
+ }
9679
+ var ANSI_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
9680
+ var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
9681
+ function cleanForWarning(text) {
9682
+ const clean = text.replace(ANSI_SEQUENCE, "").replace(CONTROL_CHARACTERS, "");
9683
+ return clean.length > MAX_WARNING_LENGTH ? `${clean.slice(0, MAX_WARNING_LENGTH)}\u2026` : clean;
9684
+ }
9685
+ function compareCodeUnits(a, b) {
9686
+ if (a < b)
9687
+ return -1;
9688
+ return a > b ? 1 : 0;
9689
+ }
9690
+ function safeLstat(target) {
9691
+ try {
9692
+ return fs6.lstatSync(target, { throwIfNoEntry: false }) ?? null;
9693
+ } catch {
9694
+ return null;
9695
+ }
9696
+ }
9697
+ function safeRealpath(target) {
9698
+ try {
9699
+ return fs6.realpathSync(target);
9700
+ } catch {
9701
+ return null;
9702
+ }
9703
+ }
9704
+ function isAbsence(error) {
9705
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
9706
+ return code === "ENOENT" || code === "ENOTDIR";
9707
+ }
9708
+ function probeRealpath(target) {
9709
+ try {
9710
+ return { kind: "ok", value: fs6.realpathSync(target) };
9711
+ } catch (error) {
9712
+ return { kind: isAbsence(error) ? "absent" : "failed" };
9713
+ }
9714
+ }
9715
+ function probeLstat(target) {
9716
+ try {
9717
+ const stat = fs6.lstatSync(target, { throwIfNoEntry: false });
9718
+ return stat === undefined ? { kind: "absent" } : { kind: "ok", value: stat };
9719
+ } catch (error) {
9720
+ return { kind: isAbsence(error) ? "absent" : "failed" };
9721
+ }
9722
+ }
9723
+ function safeReaddir(target) {
9724
+ try {
9725
+ return fs6.readdirSync(target);
9726
+ } catch {
9727
+ return null;
9728
+ }
9729
+ }
9730
+ function resolveSearchRoot(startDir) {
9731
+ const resolved = path6.resolve(startDir);
9732
+ const start = safeRealpath(resolved) ?? resolved;
9733
+ let current = start;
9734
+ while (true) {
9735
+ try {
9736
+ if (fs6.lstatSync(path6.join(current, ".git"), { throwIfNoEntry: false })) {
9737
+ return current;
9738
+ }
9739
+ } catch {
9740
+ return start;
9741
+ }
9742
+ const parent = path6.dirname(current);
9743
+ if (parent === current)
9744
+ return start;
9745
+ current = parent;
9746
+ }
9747
+ }
9748
+ function isInside(root, candidate) {
9749
+ const relative = path6.relative(root, candidate);
9750
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relative);
9751
+ }
9752
+ function classifyEntry(spec, name, stat) {
9753
+ if (stat === null || stat.isSymbolicLink())
9754
+ return "ignored";
9755
+ if (stat.isDirectory()) {
9756
+ return spec.excludedDirs.includes(name) ? "ignored" : "directory";
9757
+ }
9758
+ if (!stat.isFile())
9759
+ return "ignored";
9760
+ const lower = name.toLowerCase();
9761
+ const indexable = lower.endsWith(".md") && !spec.excludedFiles.includes(lower);
9762
+ return indexable ? "file" : "ignored";
9763
+ }
9764
+ function discoverFiles(spec, directory, prefix, depth, found, warnings) {
9765
+ const names = safeReaddir(directory);
9766
+ if (names === null) {
9767
+ const shown = prefix === "" ? spec.dir : `${spec.dir}/${prefix.slice(0, -1)}`;
9768
+ warnings.push(cleanForWarning(`could not read directory ${shown}`));
9769
+ return;
9770
+ }
9771
+ names.sort(compareCodeUnits);
9772
+ for (const name of names) {
9773
+ if (found.truncated)
9774
+ return;
9775
+ const absolute = path6.join(directory, name);
9776
+ const stat = safeLstat(absolute);
9777
+ const entryKind = classifyEntry(spec, name, stat);
9778
+ if (entryKind === "directory" && depth + 1 <= MAX_DEPTH) {
9779
+ const child = `${prefix}${name}/`;
9780
+ discoverFiles(spec, absolute, child, depth + 1, found, warnings);
9781
+ } else if (entryKind === "file" && stat !== null) {
9782
+ if (found.candidates.length >= MAX_DISCOVERED_FILES) {
9783
+ found.truncated = true;
9784
+ return;
9785
+ }
9786
+ found.candidates.push({
9787
+ relative: `${prefix}${name}`,
9788
+ absolute,
9789
+ size: stat.size
9790
+ });
9791
+ }
9792
+ }
9793
+ }
9794
+ function narrowString(value) {
9795
+ return typeof value === "string" ? value : undefined;
9796
+ }
9797
+ function narrowStringList(value) {
9798
+ const items = Array.isArray(value) ? value : [value];
9799
+ const result = [];
9800
+ for (const item of items) {
9801
+ if (typeof item === "string")
9802
+ result.push(item);
9803
+ else if (typeof item === "number" && Number.isFinite(item))
9804
+ result.push(String(item));
9805
+ }
9806
+ return result;
9807
+ }
9808
+ function narrowSupersededBy(value) {
9809
+ if (value === undefined || value === null)
9810
+ return { state: "none" };
9811
+ if (typeof value === "string")
9812
+ return { state: "value", value };
9813
+ return { state: "invalid" };
9814
+ }
9815
+ function parseCorpusDocument(kind, relativePath, content) {
9816
+ let text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
9817
+ if (!text.endsWith(`
9818
+ `))
9819
+ text += `
9820
+ `;
9821
+ const parsed = parseFrontmatter(text);
9822
+ if (parsed.parseError)
9823
+ return { ok: false, reason: "invalid frontmatter" };
9824
+ if (parsed.hadFrontmatter && !isRecord(parsed.data)) {
9825
+ return { ok: false, reason: "frontmatter is not a mapping" };
9826
+ }
9827
+ const data = isRecord(parsed.data) ? parsed.data : {};
9828
+ const fileName = relativePath.slice(relativePath.lastIndexOf("/") + 1);
9829
+ const title = narrowString(data.title)?.trim();
9830
+ return {
9831
+ ok: true,
9832
+ document: {
9833
+ path: relativePath,
9834
+ kind,
9835
+ title: title ? title : fileName.replace(/\.md$/i, ""),
9836
+ tags: narrowStringList(data.tags),
9837
+ module: narrowString(data.module),
9838
+ component: narrowString(data.component),
9839
+ problemType: narrowString(data.problem_type),
9840
+ symptoms: narrowStringList(data.symptoms),
9841
+ appliesWhen: narrowStringList(data.applies_when),
9842
+ status: narrowString(data.status),
9843
+ supersededBy: narrowSupersededBy(data.superseded_by),
9844
+ staleReason: narrowString(data.stale_reason),
9845
+ body: parsed.body
9846
+ }
9847
+ };
9848
+ }
9849
+ function readCandidates(spec, kind, candidates, considered, warnings) {
9850
+ const documents = [];
9851
+ let totalBytes = 0;
9852
+ for (let index = 0;index < considered; index++) {
9853
+ const candidate = candidates[index];
9854
+ if (candidate === undefined)
9855
+ break;
9856
+ const logicalPath = `${spec.dir}/${candidate.relative}`;
9857
+ const display = cleanForWarning(logicalPath);
9858
+ if (candidate.size > MAX_FILE_BYTES) {
9859
+ warnings.push(`skipped ${display}: larger than ${MAX_FILE_BYTES} bytes`);
9860
+ continue;
9861
+ }
9862
+ if (totalBytes + candidate.size > MAX_TOTAL_BYTES) {
9863
+ return { documents, budgetSkipped: considered - index };
9864
+ }
9865
+ totalBytes += candidate.size;
9866
+ let bytes;
9867
+ try {
9868
+ bytes = fs6.readFileSync(candidate.absolute);
9869
+ } catch {
9870
+ warnings.push(`skipped ${display}: could not be read`);
9871
+ continue;
9872
+ }
9873
+ if (bytes.byteLength > MAX_FILE_BYTES) {
9874
+ warnings.push(`skipped ${display}: larger than ${MAX_FILE_BYTES} bytes`);
9875
+ continue;
9876
+ }
9877
+ const parsed = parseCorpusDocument(kind, logicalPath, bytes.toString("utf8"));
9878
+ if (parsed.ok)
9879
+ documents.push(parsed.document);
9880
+ else
9881
+ warnings.push(`skipped ${display}: ${parsed.reason}`);
9882
+ }
9883
+ return { documents, budgetSkipped: 0 };
9884
+ }
9885
+ function loadCorpus(root, kind = "solution") {
9886
+ const spec = KIND_TABLE[kind];
9887
+ const warnings = [];
9888
+ const none = { state: "none", documents: [], warnings };
9889
+ const unreadable = () => {
9890
+ warnings.push(`could not read ${spec.dir}; not loaded`);
9891
+ return none;
9892
+ };
9893
+ const rootProbe = probeRealpath(root);
9894
+ const directoryProbe = probeRealpath(path6.join(root, ...spec.dir.split("/")));
9895
+ if (rootProbe.kind === "failed" || directoryProbe.kind === "failed") {
9896
+ return unreadable();
9897
+ }
9898
+ if (rootProbe.kind !== "ok" || directoryProbe.kind !== "ok")
9899
+ return none;
9900
+ const rootReal = rootProbe.value;
9901
+ const directoryReal = directoryProbe.value;
9902
+ const statProbe = probeLstat(directoryReal);
9903
+ if (statProbe.kind === "failed")
9904
+ return unreadable();
9905
+ if (statProbe.kind !== "ok" || !statProbe.value.isDirectory())
9906
+ return none;
9907
+ if (!isInside(rootReal, directoryReal)) {
9908
+ warnings.push(`${spec.dir} resolves outside the project root; not loaded`);
9909
+ return none;
9910
+ }
9911
+ const found = { candidates: [], truncated: false };
9912
+ discoverFiles(spec, directoryReal, "", 0, found, warnings);
9913
+ const candidates = found.candidates.sort((a, b) => compareCodeUnits(a.relative, b.relative));
9914
+ const considered = Math.min(candidates.length, MAX_FILES);
9915
+ const { documents, budgetSkipped } = readCandidates(spec, kind, candidates, considered, warnings);
9916
+ const capSkipped = candidates.length - considered;
9917
+ if (capSkipped > 0) {
9918
+ const atLeast = found.truncated ? "at least " : "";
9919
+ warnings.push(`file limit of ${MAX_FILES} reached; skipped ${atLeast}${capSkipped} files`);
9920
+ }
9921
+ if (budgetSkipped > 0) {
9922
+ warnings.push(`text budget of ${MAX_TOTAL_BYTES} bytes reached; skipped ${budgetSkipped} files`);
9923
+ }
9924
+ return { state: "loaded", documents, warnings };
9925
+ }
9926
+
9927
+ // src/lib/search-lexical.ts
9928
+ var LEXICAL_FIELDS = [
9929
+ "title",
9930
+ "tags",
9931
+ "module",
9932
+ "symptoms",
9933
+ "applies_when",
9934
+ "component",
9935
+ "problem_type",
9936
+ "body"
9937
+ ];
9938
+ var BM25F_PARAMS = {
9939
+ k1: 1.2,
9940
+ fields: {
9941
+ title: { weight: 3, b: 0 },
9942
+ tags: { weight: 2.5, b: 0 },
9943
+ module: { weight: 2, b: 0 },
9944
+ symptoms: { weight: 3, b: 0 },
9945
+ applies_when: { weight: 2, b: 0 },
9946
+ component: { weight: 1.5, b: 0 },
9947
+ problem_type: { weight: 1.5, b: 0 },
9948
+ body: { weight: 1, b: 0.75 }
9949
+ }
9950
+ };
9951
+ var MAX_QUERY_TERMS = 64;
9952
+ var IDENTIFIER_RUN = /[a-z0-9]+(?:[_-]+[a-z0-9]+)*/g;
9953
+ var WORD = /[a-z0-9]+/g;
9954
+ function tokenize(text) {
9955
+ const tokens = [];
9956
+ for (const match of text.toLowerCase().matchAll(IDENTIFIER_RUN)) {
9957
+ const run = match[0];
9958
+ const words = run.match(WORD);
9959
+ if (words === null)
9960
+ continue;
9961
+ if (words.length === 1) {
9962
+ tokens.push(run);
9963
+ continue;
9964
+ }
9965
+ tokens.push(run, ...words);
9966
+ }
9967
+ return tokens;
9968
+ }
9969
+ function uniqueQueryTerms(query, max = MAX_QUERY_TERMS) {
9970
+ const seen = new Set;
9971
+ for (const token of tokenize(query))
9972
+ seen.add(token);
9973
+ const all = [...seen];
9974
+ const truncated = all.length > max;
9975
+ const terms = (truncated ? all.slice(0, max) : all).sort(compareCodeUnits2);
9976
+ return { terms, truncated };
9977
+ }
9978
+ function compareCodeUnits2(a, b) {
9979
+ if (a < b)
9980
+ return -1;
9981
+ if (a > b)
9982
+ return 1;
9983
+ return 0;
9984
+ }
9985
+ var LN2_HI = 0.6931471803691238;
9986
+ var LN2_LO = 0.00000000019082149292705877;
9987
+ var SQRT2 = Math.SQRT2;
9988
+ var SQRT_HALF = Math.SQRT1_2;
9989
+ function ln(x) {
9990
+ if (Number.isNaN(x) || x < 0)
9991
+ return Number.NaN;
9992
+ if (x === 0)
9993
+ return Number.NEGATIVE_INFINITY;
9994
+ if (x === Number.POSITIVE_INFINITY)
9995
+ return x;
9996
+ let m = x;
9997
+ let k = 0;
9998
+ while (m >= SQRT2) {
9999
+ m /= 2;
10000
+ k += 1;
10001
+ }
10002
+ while (m < SQRT_HALF) {
10003
+ m *= 2;
10004
+ k -= 1;
10005
+ }
10006
+ const s = (m - 1) / (m + 1);
10007
+ const s2 = s * s;
10008
+ let series = 1 / 25;
10009
+ for (let d = 23;d >= 1; d -= 2)
10010
+ series = series * s2 + 1 / d;
10011
+ const small = 2 * s * series;
10012
+ return k * LN2_HI + (k * LN2_LO + small);
10013
+ }
10014
+ function buildLexicalIndex(documents, params = BM25F_PARAMS) {
10015
+ const documentFrequency = new Map;
10016
+ const totals = LEXICAL_FIELDS.map(() => 0);
10017
+ const docs = [];
10018
+ for (const document of documents) {
10019
+ const seenInDocument = new Set;
10020
+ const fields = LEXICAL_FIELDS.map((field, fieldIndex) => {
10021
+ const tokens = tokenize(document.fields[field] ?? "");
10022
+ const tf = new Map;
10023
+ for (const token of tokens) {
10024
+ tf.set(token, (tf.get(token) ?? 0) + 1);
10025
+ seenInDocument.add(token);
10026
+ }
10027
+ totals[fieldIndex] = (totals[fieldIndex] ?? 0) + tokens.length;
10028
+ return { tf, length: tokens.length };
10029
+ });
10030
+ for (const term of seenInDocument) {
10031
+ documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
10032
+ }
10033
+ docs.push({ id: document.id, fields });
10034
+ }
10035
+ const count = docs.length;
10036
+ const averageLength = totals.map((total) => count === 0 ? 0 : total / count);
10037
+ return { params, docs, documentFrequency, averageLength };
10038
+ }
10039
+ function weightedFrequency(index, document, term) {
10040
+ let total = 0;
10041
+ for (let i = 0;i < LEXICAL_FIELDS.length; i++) {
10042
+ const field = LEXICAL_FIELDS[i];
10043
+ const stats = document.fields[i];
10044
+ const tf = stats?.tf.get(term);
10045
+ if (field === undefined || stats === undefined || tf === undefined)
10046
+ continue;
10047
+ const { weight, b } = index.params.fields[field];
10048
+ const average = index.averageLength[i] ?? 0;
10049
+ const normalisation = 1 - b + b * (stats.length / average);
10050
+ total += weight * tf / normalisation;
10051
+ }
10052
+ return total;
10053
+ }
10054
+ function searchLexical(index, terms) {
10055
+ const total = index.docs.length;
10056
+ const weighted = [];
10057
+ for (const term of [...new Set(terms)].sort(compareCodeUnits2)) {
10058
+ const df = index.documentFrequency.get(term);
10059
+ if (df === undefined)
10060
+ continue;
10061
+ weighted.push({ term, idf: ln(1 + (total - df + 0.5) / (df + 0.5)) });
10062
+ }
10063
+ const { k1 } = index.params;
10064
+ const hits = [];
10065
+ for (const document of index.docs) {
10066
+ let score = 0;
10067
+ for (const { term, idf } of weighted) {
10068
+ const wtf = weightedFrequency(index, document, term);
10069
+ if (wtf === 0)
10070
+ continue;
10071
+ score += idf * wtf / (k1 + wtf);
10072
+ }
10073
+ if (score > 0)
10074
+ hits.push({ id: document.id, score });
10075
+ }
10076
+ return hits.sort((a, b) => b.score - a.score || compareCodeUnits2(a.id, b.id));
10077
+ }
10078
+
10079
+ // src/lib/search-render.ts
10080
+ var MAX_OUTPUT_BYTES = 16 * 1024;
10081
+ var TRUNCATION_MARKER = "[Systematic: search output truncated at 16 KB]";
10082
+ var MAX_TITLE_CHARS = 160;
10083
+ var MAX_TAGS = 8;
10084
+ var MAX_SNIPPET_CHARS = 240;
10085
+ var MAX_WARNINGS = 5;
10086
+ var SUPERSEDES_LABEL = "Supersedes:";
10087
+ var MAX_TAG_CHARS = 64;
10088
+ var MAX_MODULE_CHARS = 120;
10089
+ var MAX_QUERY_ECHO_CHARS = 200;
10090
+ var MAX_WARNING_CHARS = 200;
10091
+ var MAX_NOTE_CHARS = 200;
10092
+ var MAX_LIFECYCLE_LINE_CHARS = 400;
10093
+ var MAX_PATH_CHARS2 = 400;
10094
+ var MAX_LABEL_CHARS = 40;
10095
+ var ELLIPSIS = "\u2026";
10096
+ var ANSI_SEQUENCE2 = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
10097
+ var LINE_BREAKS = /[\t\n\r\u000b\u000c\u0085\u2028\u2029]+/g;
10098
+ var CONTROL_CHARACTERS2 = /[\u0000-\u001f\u007f-\u009f]/g;
10099
+ var INVISIBLE_FORMATTING = /[\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g;
10100
+ function isHighSurrogate(code) {
10101
+ return code >= 55296 && code <= 56319;
10102
+ }
10103
+ function isLowSurrogate(code) {
10104
+ return code >= 56320 && code <= 57343;
10105
+ }
10106
+ function clip(text, max) {
10107
+ if (text.length <= max)
10108
+ return text;
10109
+ let cut = Math.max(0, max - ELLIPSIS.length);
10110
+ if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1)))
10111
+ cut -= 1;
10112
+ return `${text.slice(0, cut)}${ELLIPSIS}`;
10113
+ }
10114
+ function sanitizeInline(text, max = Number.POSITIVE_INFINITY) {
10115
+ const clean = text.replace(ANSI_SEQUENCE2, "").replace(LINE_BREAKS, " ").replace(CONTROL_CHARACTERS2, "").replace(INVISIBLE_FORMATTING, "").replace(/ {2,}/g, " ").trim();
10116
+ return clip(clean, max);
10117
+ }
10118
+ function truncateUtf8(text, maxBytes, marker) {
10119
+ const encoder = new TextEncoder;
10120
+ const bytes = encoder.encode(text);
10121
+ if (bytes.byteLength <= maxBytes)
10122
+ return text;
10123
+ const tail = `
10124
+ ${marker}`;
10125
+ const budget = Math.max(0, maxBytes - encoder.encode(tail).byteLength);
10126
+ let cut = budget;
10127
+ while (cut > 0 && ((bytes[cut] ?? 0) & 192) === 128)
10128
+ cut -= 1;
10129
+ let kept = new TextDecoder("utf-8").decode(bytes.subarray(0, cut));
10130
+ const lastBreak = kept.lastIndexOf(`
10131
+ `);
10132
+ if (lastBreak > 0)
10133
+ kept = kept.slice(0, lastBreak);
10134
+ return `${kept}${tail}`;
10135
+ }
10136
+ var IDENTIFIER_RUN2 = /[a-z0-9]+(?:[_-]+[a-z0-9]+)*/gi;
10137
+ var WORD2 = /[a-z0-9]+/g;
10138
+ function matchedTerms(run, wanted) {
10139
+ const lower = run.toLowerCase();
10140
+ const matched = [];
10141
+ if (wanted.has(lower))
10142
+ matched.push(lower);
10143
+ if (lower.includes("_") || lower.includes("-")) {
10144
+ for (const part of lower.match(WORD2) ?? []) {
10145
+ if (wanted.has(part) && !matched.includes(part))
10146
+ matched.push(part);
10147
+ }
10148
+ }
10149
+ return matched;
10150
+ }
10151
+ function findOccurrences(text, wanted) {
10152
+ const found = [];
10153
+ for (const match of text.matchAll(IDENTIFIER_RUN2)) {
10154
+ const run = match[0];
10155
+ const terms = matchedTerms(run, wanted);
10156
+ if (terms.length === 0)
10157
+ continue;
10158
+ const start = match.index ?? 0;
10159
+ found.push({ start, end: start + run.length, terms });
10160
+ }
10161
+ return found;
10162
+ }
10163
+ function addTerms(counts, terms) {
10164
+ for (const term of terms)
10165
+ counts.set(term, (counts.get(term) ?? 0) + 1);
10166
+ }
10167
+ function removeTerms(counts, terms) {
10168
+ for (const term of terms) {
10169
+ const remaining = (counts.get(term) ?? 1) - 1;
10170
+ if (remaining <= 0)
10171
+ counts.delete(term);
10172
+ else
10173
+ counts.set(term, remaining);
10174
+ }
10175
+ }
10176
+ function densestWindow(occurrences, width) {
10177
+ const counts = new Map;
10178
+ let best;
10179
+ let bestDistinct = 0;
10180
+ let next = 0;
10181
+ for (let first = 0;first < occurrences.length; first++) {
10182
+ const head = occurrences[first];
10183
+ if (head === undefined)
10184
+ break;
10185
+ for (let candidate = occurrences[next];candidate !== undefined && candidate.end - head.start <= width; candidate = occurrences[next]) {
10186
+ addTerms(counts, candidate.terms);
10187
+ next += 1;
10188
+ }
10189
+ if (next === first) {
10190
+ next = first + 1;
10191
+ continue;
10192
+ }
10193
+ if (counts.size > bestDistinct) {
10194
+ bestDistinct = counts.size;
10195
+ best = { first, last: next - 1 };
10196
+ }
10197
+ removeTerms(counts, head.terms);
10198
+ }
10199
+ return best;
10200
+ }
10201
+ function cutAround(text, spanStart, spanEnd, inner) {
10202
+ const middle = Math.floor((spanStart + spanEnd) / 2);
10203
+ let begin = Math.max(0, middle - Math.floor(inner / 2));
10204
+ const end0 = Math.min(text.length, begin + inner);
10205
+ begin = Math.max(0, end0 - inner);
10206
+ let end = end0;
10207
+ if (begin > 0 && text.charAt(begin - 1) !== " ") {
10208
+ const space = text.indexOf(" ", begin);
10209
+ if (space !== -1 && space + 1 <= spanStart)
10210
+ begin = space + 1;
10211
+ }
10212
+ if (end < text.length && text.charAt(end) !== " ") {
10213
+ const space = text.lastIndexOf(" ", end);
10214
+ if (space >= spanEnd)
10215
+ end = space;
10216
+ }
10217
+ if (begin > 0 && isLowSurrogate(text.charCodeAt(begin)))
10218
+ begin += 1;
10219
+ if (end < text.length && isHighSurrogate(text.charCodeAt(end - 1)))
10220
+ end -= 1;
10221
+ const body = text.slice(begin, end).trim();
10222
+ return `${begin > 0 ? ELLIPSIS : ""}${body}${end < text.length ? ELLIPSIS : ""}`;
10223
+ }
10224
+ function bodySnippet(text, queryTerms) {
10225
+ if (text === "" || queryTerms.length === 0)
10226
+ return;
10227
+ const occurrences = findOccurrences(text, new Set(queryTerms));
10228
+ const head = occurrences[0];
10229
+ if (head === undefined)
10230
+ return;
10231
+ const inner = MAX_SNIPPET_CHARS - 2 * ELLIPSIS.length;
10232
+ const window = densestWindow(occurrences, inner);
10233
+ const first = window === undefined ? head : occurrences[window.first];
10234
+ const last = window === undefined ? head : occurrences[window.last];
10235
+ if (first === undefined || last === undefined)
10236
+ return;
10237
+ const snippet = window === undefined ? clip(text.slice(first.start), MAX_SNIPPET_CHARS) : cutAround(text, first.start, last.end, inner);
10238
+ return snippet === "" ? undefined : snippet;
10239
+ }
10240
+ function extractSnippet(document, queryTerms) {
10241
+ const fromBody = bodySnippet(sanitizeInline(document.body), queryTerms);
10242
+ if (fromBody !== undefined)
10243
+ return fromBody;
10244
+ const symptoms = sanitizeInline(document.symptoms.join("; "), MAX_SNIPPET_CHARS);
10245
+ if (symptoms !== "")
10246
+ return symptoms;
10247
+ return sanitizeInline(document.title, MAX_SNIPPET_CHARS);
10248
+ }
10249
+ function plural(count, singular) {
10250
+ return `${count} ${singular}${count === 1 ? "" : "s"}`;
10251
+ }
10252
+ function renderHeader(result) {
10253
+ const query = sanitizeInline(result.query, MAX_QUERY_ECHO_CHARS);
10254
+ const prefix = `Search "${query}":`;
10255
+ switch (result.corpus.state) {
10256
+ case "none":
10257
+ return `${prefix} corpus: none (no docs/solutions/ directory under the project root).`;
10258
+ case "empty":
10259
+ return `${prefix} corpus: empty (docs/solutions/ holds no indexable docs).`;
10260
+ case "docs":
10261
+ return `${prefix} ${plural(result.corpus.docCount, "doc")}, ${plural(result.hits.length, "hit")}. Corpus: docs/solutions.`;
10262
+ }
10263
+ }
10264
+ function renderLifecycleLine(line) {
10265
+ const prefix = `${SUPERSEDES_LABEL} `;
10266
+ if (!line.startsWith(prefix)) {
10267
+ return sanitizeInline(line, MAX_LIFECYCLE_LINE_CHARS);
10268
+ }
10269
+ const paths = line.slice(prefix.length).split(", ").map((path) => sanitizeInline(path, MAX_PATH_CHARS2)).filter((path) => path !== "");
10270
+ return `${prefix}${paths.join(", ")}`;
10271
+ }
10272
+ function renderHit(hit, queryTerms) {
10273
+ const { document } = hit;
10274
+ const lines = [`${hit.rank}. ${sanitizeInline(document.path)}`];
10275
+ lines.push(` ${[
10276
+ `Title: ${sanitizeInline(document.title, MAX_TITLE_CHARS)}`,
10277
+ `Kind: ${sanitizeInline(document.kind, MAX_LABEL_CHARS)}`,
10278
+ `Status: ${sanitizeInline(hit.status, MAX_LABEL_CHARS)}`
10279
+ ].join(" | ")}`);
10280
+ const module = document.module === undefined ? "" : sanitizeInline(document.module, MAX_MODULE_CHARS);
10281
+ const tags = document.tags.map((tag) => sanitizeInline(tag, MAX_TAG_CHARS)).filter((tag) => tag !== "").slice(0, MAX_TAGS);
10282
+ const meta = [];
10283
+ if (module !== "")
10284
+ meta.push(`Module: ${module}`);
10285
+ if (tags.length > 0)
10286
+ meta.push(`Tags: ${tags.join(", ")}`);
10287
+ if (meta.length > 0)
10288
+ lines.push(` ${meta.join(" | ")}`);
10289
+ lines.push(` Snippet: ${extractSnippet(document, queryTerms)}`);
10290
+ for (const line of hit.lifecycle)
10291
+ lines.push(` ${renderLifecycleLine(line)}`);
10292
+ return lines;
10293
+ }
10294
+ function renderSearchResult(result) {
10295
+ const lines = [renderHeader(result)];
10296
+ if (result.notes.length > 0) {
10297
+ lines.push(`Notes: ${result.notes.map((note) => sanitizeInline(note, MAX_NOTE_CHARS)).join("; ")}`);
10298
+ }
10299
+ if (result.warnings.length > 0) {
10300
+ lines.push("Warnings:");
10301
+ for (const warning of result.warnings.slice(0, MAX_WARNINGS)) {
10302
+ lines.push(`- ${sanitizeInline(warning, MAX_WARNING_CHARS)}`);
10303
+ }
10304
+ const hidden = result.warnings.length - MAX_WARNINGS;
10305
+ if (hidden > 0)
10306
+ lines.push(`- +${hidden} more`);
10307
+ }
10308
+ for (const hit of result.hits) {
10309
+ lines.push("", ...renderHit(hit, result.queryTerms));
10310
+ }
10311
+ return truncateUtf8(lines.join(`
10312
+ `), MAX_OUTPUT_BYTES, TRUNCATION_MARKER);
10313
+ }
10314
+
10315
+ // src/lib/search-core.ts
10316
+ var SEARCH_TOOL_NAME = "systematic_search";
10317
+ var SEARCH_ARGS = {
10318
+ query: "query",
10319
+ kind: "kind",
10320
+ limit: "limit"
10321
+ };
10322
+ var DEFAULT_LIMIT = 8;
10323
+ var MIN_LIMIT = 1;
10324
+ var MAX_LIMIT = 20;
10325
+ var MAX_QUERY_CHARS = 2000;
10326
+ var SEARCH_TOOL_DESCRIPTION = "Search this project's durable outputs (the docs/solutions learnings) by symptom, error text, module or topic. Returns ranked hits with path, title, snippet, tags and status. A superseded learning is replaced by its successor, and a stale one carries a caution. Read a hit's path for the full text. Use it before debugging a failure or planning work a past learning may already cover.";
10327
+ var SEARCH_ARG_DESCRIPTIONS = {
10328
+ query: `What to look for: a symptom, error message, module or topic, in plain words. At most ${MAX_QUERY_CHARS} characters.`,
10329
+ kind: 'Optional. The kind of durable output to search. Only "solution" (docs/solutions/) exists today, and it is the default.',
10330
+ limit: `Optional. How many hits to return, an integer from ${MIN_LIMIT} to ${MAX_LIMIT}. Defaults to ${DEFAULT_LIMIT}.`
10331
+ };
10332
+ var SEARCH_NOTICES = {
10333
+ failed: "Error: search failed.",
10334
+ noProject: "No project directory is available for this session, so there is nothing to search."
10335
+ };
10336
+ var SEARCH_CONFIG_UNREADABLE_NOTE = "config unreadable";
10337
+ var MAX_SUCCESSOR_HOPS = 5;
10338
+ var SUCCESSOR_PATH_PREFIX = `${KIND_TABLE.solution.dir}/`;
10339
+ var CAUTION_LABEL = "Caution:";
10340
+ var SUCCESSOR_UNRESOLVED_TEXT = "successor unresolved";
10341
+ var STALE_CAUTION_TEXT = "marked stale";
10342
+ var MAX_STALE_REASON_CHARS = 200;
10343
+ var SEARCH_ERRORS = {
10344
+ queryEmpty: "Error: query must be a non-empty string.",
10345
+ queryTooLong: `Error: query must be at most ${MAX_QUERY_CHARS} characters.`,
10346
+ kindUnknown: `Error: kind must be one of: ${Object.keys(KIND_TABLE).join(", ")}.`,
10347
+ limitInvalid: `Error: limit must be an integer from ${MIN_LIMIT} to ${MAX_LIMIT}.`
10348
+ };
10349
+ function isSuccessorPathForm(value) {
10350
+ if (!value.startsWith(SUCCESSOR_PATH_PREFIX))
10351
+ return false;
10352
+ if (!value.endsWith(".md"))
10353
+ return false;
10354
+ const segments = value.split("/");
10355
+ if (segments.includes(".."))
10356
+ return false;
10357
+ const name = segments[segments.length - 1]?.toLowerCase();
10358
+ if (name === "readme.md")
10359
+ return false;
10360
+ if (segments.includes("_archived"))
10361
+ return false;
10362
+ return true;
10363
+ }
10364
+ function resolveSuccessor(candidate, byPath) {
10365
+ const visited = new Set([candidate.path]);
10366
+ let current = candidate;
10367
+ for (let hop = 1;hop <= MAX_SUCCESSOR_HOPS; hop++) {
10368
+ const link = current.supersededBy;
10369
+ if (link.state !== "value" || !isSuccessorPathForm(link.value)) {
10370
+ return;
10371
+ }
10372
+ if (visited.has(link.value))
10373
+ return;
10374
+ const target = byPath.get(link.value);
10375
+ if (target === undefined)
10376
+ return;
10377
+ visited.add(target.path);
10378
+ if (target.status !== "superseded")
10379
+ return target;
10380
+ current = target;
10381
+ }
10382
+ return;
10383
+ }
10384
+ function compareCodeUnits3(a, b) {
10385
+ if (a < b)
10386
+ return -1;
10387
+ return a > b ? 1 : 0;
10388
+ }
10389
+ function resolveLifecycle(ranked, documents) {
10390
+ const byPath = new Map(documents.map((doc) => [doc.path, doc]));
10391
+ const order = [];
10392
+ const entries = new Map;
10393
+ for (const candidate of ranked) {
10394
+ let target = candidate;
10395
+ let replaces;
10396
+ let unresolved = false;
10397
+ if (candidate.status === "superseded") {
10398
+ const successor = resolveSuccessor(candidate, byPath);
10399
+ if (successor === undefined)
10400
+ unresolved = true;
10401
+ else {
10402
+ target = successor;
10403
+ replaces = candidate.path;
10404
+ }
10405
+ }
10406
+ let entry = entries.get(target.path);
10407
+ if (entry === undefined) {
10408
+ entry = { document: target, replaced: new Set, unresolved };
10409
+ entries.set(target.path, entry);
10410
+ order.push(target.path);
10411
+ }
10412
+ if (replaces !== undefined)
10413
+ entry.replaced.add(replaces);
10414
+ }
10415
+ return order.flatMap((path) => {
10416
+ const entry = entries.get(path);
10417
+ if (entry === undefined)
10418
+ return [];
10419
+ return [
10420
+ {
10421
+ document: entry.document,
10422
+ supersedes: [...entry.replaced].sort(compareCodeUnits3),
10423
+ unresolved: entry.unresolved
10424
+ }
10425
+ ];
10426
+ });
10427
+ }
10428
+ function entryStatus(entry) {
10429
+ if (entry.unresolved)
10430
+ return "superseded";
10431
+ return entry.document.status === "stale" ? "stale" : "active";
10432
+ }
10433
+ function lifecycleLines(entry) {
10434
+ const lines = [];
10435
+ if (entry.supersedes.length > 0) {
10436
+ lines.push(`${SUPERSEDES_LABEL} ${entry.supersedes.join(", ")}`);
10437
+ }
10438
+ if (entry.unresolved) {
10439
+ lines.push(`${CAUTION_LABEL} ${SUCCESSOR_UNRESOLVED_TEXT}`);
10440
+ } else if (entry.document.status === "stale") {
10441
+ const reason = sanitizeInline(entry.document.staleReason ?? "", MAX_STALE_REASON_CHARS);
10442
+ lines.push(reason === "" ? `${CAUTION_LABEL} ${STALE_CAUTION_TEXT}` : `${CAUTION_LABEL} ${STALE_CAUTION_TEXT}: ${reason}`);
10443
+ }
10444
+ return lines;
10445
+ }
10446
+ function toLexicalDocument(document) {
10447
+ return {
10448
+ id: document.path,
10449
+ fields: {
10450
+ title: document.title,
10451
+ tags: document.tags.join(" "),
10452
+ module: document.module ?? "",
10453
+ symptoms: document.symptoms.join(`
10454
+ `),
10455
+ applies_when: document.appliesWhen.join(`
10456
+ `),
10457
+ component: document.component ?? "",
10458
+ problem_type: document.problemType ?? "",
10459
+ body: document.body
10460
+ }
10461
+ };
10462
+ }
10463
+ function validate2(request) {
10464
+ const { query } = request;
10465
+ if (typeof query !== "string" || query.trim() === "") {
10466
+ return { ok: false, error: SEARCH_ERRORS.queryEmpty };
10467
+ }
10468
+ if (query.length > MAX_QUERY_CHARS) {
10469
+ return { ok: false, error: SEARCH_ERRORS.queryTooLong };
10470
+ }
10471
+ let kind = "solution";
10472
+ if (request.kind !== undefined) {
10473
+ if (!isDocumentKind(request.kind)) {
10474
+ return { ok: false, error: SEARCH_ERRORS.kindUnknown };
10475
+ }
10476
+ kind = request.kind;
10477
+ }
10478
+ let limit = DEFAULT_LIMIT;
10479
+ if (request.limit !== undefined) {
10480
+ const value = request.limit;
10481
+ if (typeof value !== "number" || !Number.isInteger(value) || value < MIN_LIMIT || value > MAX_LIMIT) {
10482
+ return { ok: false, error: SEARCH_ERRORS.limitInvalid };
10483
+ }
10484
+ limit = value;
10485
+ }
10486
+ return { ok: true, query, kind, limit };
10487
+ }
10488
+ async function runSearch(request, options) {
10489
+ const checked = validate2(request);
10490
+ if (!checked.ok)
10491
+ return { ok: false, text: checked.error };
10492
+ const { query, kind, limit } = checked;
10493
+ const root = resolveSearchRoot(options.startDir);
10494
+ const load = (options.corpusLoader ?? loadCorpus)(root, kind);
10495
+ const { terms, truncated } = uniqueQueryTerms(query);
10496
+ const base = {
10497
+ query,
10498
+ queryTerms: terms,
10499
+ warnings: load.warnings
10500
+ };
10501
+ const noteList = [...options.notes ?? []];
10502
+ if (truncated)
10503
+ noteList.push("query cut to its first 64 distinct terms");
10504
+ const finish = (result) => ({
10505
+ ok: true,
10506
+ text: renderSearchResult(result),
10507
+ result
10508
+ });
10509
+ if (load.state === "none") {
10510
+ return finish({
10511
+ ...base,
10512
+ corpus: { state: "none", docCount: 0 },
10513
+ hits: [],
10514
+ notes: noteList
10515
+ });
10516
+ }
10517
+ if (load.documents.length === 0) {
10518
+ return finish({
10519
+ ...base,
10520
+ corpus: { state: "empty", docCount: 0 },
10521
+ hits: [],
10522
+ notes: noteList
10523
+ });
10524
+ }
10525
+ const index = buildLexicalIndex(load.documents.map(toLexicalDocument), options.lexicalParams ?? BM25F_PARAMS);
10526
+ const lexical = searchLexical(index, terms);
10527
+ const byPath = new Map(load.documents.map((doc) => [doc.path, doc]));
10528
+ const candidates = [];
10529
+ for (const hit of lexical) {
10530
+ const document = byPath.get(hit.id);
10531
+ if (document !== undefined)
10532
+ candidates.push(document);
10533
+ }
10534
+ const hits = resolveLifecycle(candidates, load.documents).slice(0, limit).map((entry, position) => ({
10535
+ rank: position + 1,
10536
+ document: entry.document,
10537
+ status: entryStatus(entry),
10538
+ lifecycle: lifecycleLines(entry)
10539
+ }));
10540
+ return finish({
10541
+ ...base,
10542
+ corpus: { state: "docs", docCount: load.documents.length },
10543
+ hits,
10544
+ notes: noteList
10545
+ });
10546
+ }
10547
+
10548
+ 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, SEARCH_TOOL_DESCRIPTION, SEARCH_ARG_DESCRIPTIONS, SEARCH_NOTICES, SEARCH_CONFIG_UNREADABLE_NOTE, runSearch };