@fro.bot/systematic 3.27.2 → 3.28.1

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 +23 -10
  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 +15 -3
  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 +1169 -82
  27. package/package.json +5 -5
  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
package/dist/pi.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // src/pi.ts
2
- import path7 from "node:path";
2
+ import path9 from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { Type as Type3 } from "typebox";
5
5
 
6
6
  // src/lib/agent-resolver.ts
7
- import fs2 from "node:fs";
7
+ import fs3 from "node:fs";
8
8
 
9
9
  // node_modules/.bun/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
10
10
  function getDefaultExportFromCjs(x) {
@@ -3141,7 +3141,7 @@ var {
3141
3141
 
3142
3142
  // src/lib/frontmatter.ts
3143
3143
  function parseFrontmatter(content) {
3144
- const frontmatterRegex = /^---\r?\n([\s\S]*?)\r?\n?---\r?\n([\s\S]*)$/;
3144
+ const frontmatterRegex = /^---\r?\n((?:[\s\S]*?\r?\n)?)---\r?\n([\s\S]*)$/;
3145
3145
  const match = content.match(frontmatterRegex);
3146
3146
  if (!match) {
3147
3147
  return {
@@ -3239,13 +3239,902 @@ function findAgentsInDir(dir, maxDepth = 2) {
3239
3239
  }));
3240
3240
  }
3241
3241
 
3242
+ // src/lib/search-corpus.ts
3243
+ import fs2 from "node:fs";
3244
+ import path2 from "node:path";
3245
+ var MAX_FILE_BYTES = 256 * 1024;
3246
+ var MAX_FILES = 2000;
3247
+ var MAX_DEPTH = 6;
3248
+ var MAX_TOTAL_BYTES = 16 * 1024 * 1024;
3249
+ var MAX_DISCOVERED_FILES = MAX_FILES * 4;
3250
+ var MAX_WARNING_LENGTH = 200;
3251
+ var KIND_TABLE = {
3252
+ solution: {
3253
+ dir: "docs/solutions",
3254
+ excludedFiles: ["readme.md", "critical-patterns.md"],
3255
+ excludedDirs: ["_archived"],
3256
+ lifecycle: true
3257
+ }
3258
+ };
3259
+ function isDocumentKind(value) {
3260
+ return typeof value === "string" && Object.hasOwn(KIND_TABLE, value);
3261
+ }
3262
+ var ANSI_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
3263
+ var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
3264
+ function cleanForWarning(text) {
3265
+ const clean = text.replace(ANSI_SEQUENCE, "").replace(CONTROL_CHARACTERS, "");
3266
+ return clean.length > MAX_WARNING_LENGTH ? `${clean.slice(0, MAX_WARNING_LENGTH)}…` : clean;
3267
+ }
3268
+ function compareCodeUnits(a, b) {
3269
+ if (a < b)
3270
+ return -1;
3271
+ return a > b ? 1 : 0;
3272
+ }
3273
+ function safeLstat(target) {
3274
+ try {
3275
+ return fs2.lstatSync(target, { throwIfNoEntry: false }) ?? null;
3276
+ } catch {
3277
+ return null;
3278
+ }
3279
+ }
3280
+ function safeRealpath(target) {
3281
+ try {
3282
+ return fs2.realpathSync(target);
3283
+ } catch {
3284
+ return null;
3285
+ }
3286
+ }
3287
+ function isAbsence(error) {
3288
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
3289
+ return code === "ENOENT" || code === "ENOTDIR";
3290
+ }
3291
+ function probeRealpath(target) {
3292
+ try {
3293
+ return { kind: "ok", value: fs2.realpathSync(target) };
3294
+ } catch (error) {
3295
+ return { kind: isAbsence(error) ? "absent" : "failed" };
3296
+ }
3297
+ }
3298
+ function probeLstat(target) {
3299
+ try {
3300
+ const stat = fs2.lstatSync(target, { throwIfNoEntry: false });
3301
+ return stat === undefined ? { kind: "absent" } : { kind: "ok", value: stat };
3302
+ } catch (error) {
3303
+ return { kind: isAbsence(error) ? "absent" : "failed" };
3304
+ }
3305
+ }
3306
+ function safeReaddir(target) {
3307
+ try {
3308
+ return fs2.readdirSync(target);
3309
+ } catch {
3310
+ return null;
3311
+ }
3312
+ }
3313
+ function resolveSearchRoot(startDir) {
3314
+ const resolved = path2.resolve(startDir);
3315
+ const start = safeRealpath(resolved) ?? resolved;
3316
+ let current = start;
3317
+ while (true) {
3318
+ try {
3319
+ if (fs2.lstatSync(path2.join(current, ".git"), { throwIfNoEntry: false })) {
3320
+ return current;
3321
+ }
3322
+ } catch {
3323
+ return start;
3324
+ }
3325
+ const parent = path2.dirname(current);
3326
+ if (parent === current)
3327
+ return start;
3328
+ current = parent;
3329
+ }
3330
+ }
3331
+ function isInside(root, candidate) {
3332
+ const relative = path2.relative(root, candidate);
3333
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative);
3334
+ }
3335
+ function classifyEntry(spec, name, stat) {
3336
+ if (stat === null || stat.isSymbolicLink())
3337
+ return "ignored";
3338
+ if (stat.isDirectory()) {
3339
+ return spec.excludedDirs.includes(name) ? "ignored" : "directory";
3340
+ }
3341
+ if (!stat.isFile())
3342
+ return "ignored";
3343
+ const lower = name.toLowerCase();
3344
+ const indexable = lower.endsWith(".md") && !spec.excludedFiles.includes(lower);
3345
+ return indexable ? "file" : "ignored";
3346
+ }
3347
+ function discoverFiles(spec, directory, prefix, depth, found, warnings) {
3348
+ const names = safeReaddir(directory);
3349
+ if (names === null) {
3350
+ const shown = prefix === "" ? spec.dir : `${spec.dir}/${prefix.slice(0, -1)}`;
3351
+ warnings.push(cleanForWarning(`could not read directory ${shown}`));
3352
+ return;
3353
+ }
3354
+ names.sort(compareCodeUnits);
3355
+ for (const name of names) {
3356
+ if (found.truncated)
3357
+ return;
3358
+ const absolute = path2.join(directory, name);
3359
+ const stat = safeLstat(absolute);
3360
+ const entryKind = classifyEntry(spec, name, stat);
3361
+ if (entryKind === "directory" && depth + 1 <= MAX_DEPTH) {
3362
+ const child = `${prefix}${name}/`;
3363
+ discoverFiles(spec, absolute, child, depth + 1, found, warnings);
3364
+ } else if (entryKind === "file" && stat !== null) {
3365
+ if (found.candidates.length >= MAX_DISCOVERED_FILES) {
3366
+ found.truncated = true;
3367
+ return;
3368
+ }
3369
+ found.candidates.push({
3370
+ relative: `${prefix}${name}`,
3371
+ absolute,
3372
+ size: stat.size
3373
+ });
3374
+ }
3375
+ }
3376
+ }
3377
+ function narrowString(value) {
3378
+ return typeof value === "string" ? value : undefined;
3379
+ }
3380
+ function narrowStringList(value) {
3381
+ const items = Array.isArray(value) ? value : [value];
3382
+ const result = [];
3383
+ for (const item of items) {
3384
+ if (typeof item === "string")
3385
+ result.push(item);
3386
+ else if (typeof item === "number" && Number.isFinite(item))
3387
+ result.push(String(item));
3388
+ }
3389
+ return result;
3390
+ }
3391
+ function narrowSupersededBy(value) {
3392
+ if (value === undefined || value === null)
3393
+ return { state: "none" };
3394
+ if (typeof value === "string")
3395
+ return { state: "value", value };
3396
+ return { state: "invalid" };
3397
+ }
3398
+ function parseCorpusDocument(kind, relativePath, content) {
3399
+ let text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
3400
+ if (!text.endsWith(`
3401
+ `))
3402
+ text += `
3403
+ `;
3404
+ const parsed = parseFrontmatter(text);
3405
+ if (parsed.parseError)
3406
+ return { ok: false, reason: "invalid frontmatter" };
3407
+ if (parsed.hadFrontmatter && !isRecord(parsed.data)) {
3408
+ return { ok: false, reason: "frontmatter is not a mapping" };
3409
+ }
3410
+ const data = isRecord(parsed.data) ? parsed.data : {};
3411
+ const fileName = relativePath.slice(relativePath.lastIndexOf("/") + 1);
3412
+ const title = narrowString(data.title)?.trim();
3413
+ return {
3414
+ ok: true,
3415
+ document: {
3416
+ path: relativePath,
3417
+ kind,
3418
+ title: title ? title : fileName.replace(/\.md$/i, ""),
3419
+ tags: narrowStringList(data.tags),
3420
+ module: narrowString(data.module),
3421
+ component: narrowString(data.component),
3422
+ problemType: narrowString(data.problem_type),
3423
+ symptoms: narrowStringList(data.symptoms),
3424
+ appliesWhen: narrowStringList(data.applies_when),
3425
+ status: narrowString(data.status),
3426
+ supersededBy: narrowSupersededBy(data.superseded_by),
3427
+ staleReason: narrowString(data.stale_reason),
3428
+ body: parsed.body
3429
+ }
3430
+ };
3431
+ }
3432
+ function readCandidates(spec, kind, candidates, considered, warnings) {
3433
+ const documents = [];
3434
+ let totalBytes = 0;
3435
+ for (let index = 0;index < considered; index++) {
3436
+ const candidate = candidates[index];
3437
+ if (candidate === undefined)
3438
+ break;
3439
+ const logicalPath = `${spec.dir}/${candidate.relative}`;
3440
+ const display = cleanForWarning(logicalPath);
3441
+ if (candidate.size > MAX_FILE_BYTES) {
3442
+ warnings.push(`skipped ${display}: larger than ${MAX_FILE_BYTES} bytes`);
3443
+ continue;
3444
+ }
3445
+ if (totalBytes + candidate.size > MAX_TOTAL_BYTES) {
3446
+ return { documents, budgetSkipped: considered - index };
3447
+ }
3448
+ totalBytes += candidate.size;
3449
+ let bytes;
3450
+ try {
3451
+ bytes = fs2.readFileSync(candidate.absolute);
3452
+ } catch {
3453
+ warnings.push(`skipped ${display}: could not be read`);
3454
+ continue;
3455
+ }
3456
+ if (bytes.byteLength > MAX_FILE_BYTES) {
3457
+ warnings.push(`skipped ${display}: larger than ${MAX_FILE_BYTES} bytes`);
3458
+ continue;
3459
+ }
3460
+ const parsed = parseCorpusDocument(kind, logicalPath, bytes.toString("utf8"));
3461
+ if (parsed.ok)
3462
+ documents.push(parsed.document);
3463
+ else
3464
+ warnings.push(`skipped ${display}: ${parsed.reason}`);
3465
+ }
3466
+ return { documents, budgetSkipped: 0 };
3467
+ }
3468
+ function loadCorpus(root, kind = "solution") {
3469
+ const spec = KIND_TABLE[kind];
3470
+ const warnings = [];
3471
+ const none = { state: "none", documents: [], warnings };
3472
+ const unreadable = () => {
3473
+ warnings.push(`could not read ${spec.dir}; not loaded`);
3474
+ return none;
3475
+ };
3476
+ const rootProbe = probeRealpath(root);
3477
+ const directoryProbe = probeRealpath(path2.join(root, ...spec.dir.split("/")));
3478
+ if (rootProbe.kind === "failed" || directoryProbe.kind === "failed") {
3479
+ return unreadable();
3480
+ }
3481
+ if (rootProbe.kind !== "ok" || directoryProbe.kind !== "ok")
3482
+ return none;
3483
+ const rootReal = rootProbe.value;
3484
+ const directoryReal = directoryProbe.value;
3485
+ const statProbe = probeLstat(directoryReal);
3486
+ if (statProbe.kind === "failed")
3487
+ return unreadable();
3488
+ if (statProbe.kind !== "ok" || !statProbe.value.isDirectory())
3489
+ return none;
3490
+ if (!isInside(rootReal, directoryReal)) {
3491
+ warnings.push(`${spec.dir} resolves outside the project root; not loaded`);
3492
+ return none;
3493
+ }
3494
+ const found = { candidates: [], truncated: false };
3495
+ discoverFiles(spec, directoryReal, "", 0, found, warnings);
3496
+ const candidates = found.candidates.sort((a, b) => compareCodeUnits(a.relative, b.relative));
3497
+ const considered = Math.min(candidates.length, MAX_FILES);
3498
+ const { documents, budgetSkipped } = readCandidates(spec, kind, candidates, considered, warnings);
3499
+ const capSkipped = candidates.length - considered;
3500
+ if (capSkipped > 0) {
3501
+ const atLeast = found.truncated ? "at least " : "";
3502
+ warnings.push(`file limit of ${MAX_FILES} reached; skipped ${atLeast}${capSkipped} files`);
3503
+ }
3504
+ if (budgetSkipped > 0) {
3505
+ warnings.push(`text budget of ${MAX_TOTAL_BYTES} bytes reached; skipped ${budgetSkipped} files`);
3506
+ }
3507
+ return { state: "loaded", documents, warnings };
3508
+ }
3509
+
3510
+ // src/lib/search-lexical.ts
3511
+ var LEXICAL_FIELDS = [
3512
+ "title",
3513
+ "tags",
3514
+ "module",
3515
+ "symptoms",
3516
+ "applies_when",
3517
+ "component",
3518
+ "problem_type",
3519
+ "body"
3520
+ ];
3521
+ var BM25F_PARAMS = {
3522
+ k1: 1.2,
3523
+ fields: {
3524
+ title: { weight: 3, b: 0 },
3525
+ tags: { weight: 2.5, b: 0 },
3526
+ module: { weight: 2, b: 0 },
3527
+ symptoms: { weight: 3, b: 0 },
3528
+ applies_when: { weight: 2, b: 0 },
3529
+ component: { weight: 1.5, b: 0 },
3530
+ problem_type: { weight: 1.5, b: 0 },
3531
+ body: { weight: 1, b: 0.75 }
3532
+ }
3533
+ };
3534
+ var MAX_QUERY_TERMS = 64;
3535
+ var IDENTIFIER_RUN = /[a-z0-9]+(?:[_-]+[a-z0-9]+)*/g;
3536
+ var WORD = /[a-z0-9]+/g;
3537
+ function tokenize(text) {
3538
+ const tokens = [];
3539
+ for (const match of text.toLowerCase().matchAll(IDENTIFIER_RUN)) {
3540
+ const run = match[0];
3541
+ const words = run.match(WORD);
3542
+ if (words === null)
3543
+ continue;
3544
+ if (words.length === 1) {
3545
+ tokens.push(run);
3546
+ continue;
3547
+ }
3548
+ tokens.push(run, ...words);
3549
+ }
3550
+ return tokens;
3551
+ }
3552
+ function uniqueQueryTerms(query, max = MAX_QUERY_TERMS) {
3553
+ const seen = new Set;
3554
+ for (const token of tokenize(query))
3555
+ seen.add(token);
3556
+ const all = [...seen];
3557
+ const truncated = all.length > max;
3558
+ const terms = (truncated ? all.slice(0, max) : all).sort(compareCodeUnits2);
3559
+ return { terms, truncated };
3560
+ }
3561
+ function compareCodeUnits2(a, b) {
3562
+ if (a < b)
3563
+ return -1;
3564
+ if (a > b)
3565
+ return 1;
3566
+ return 0;
3567
+ }
3568
+ var LN2_HI = 0.6931471803691238;
3569
+ var LN2_LO = 0.00000000019082149292705877;
3570
+ var SQRT2 = Math.SQRT2;
3571
+ var SQRT_HALF = Math.SQRT1_2;
3572
+ function ln(x) {
3573
+ if (Number.isNaN(x) || x < 0)
3574
+ return Number.NaN;
3575
+ if (x === 0)
3576
+ return Number.NEGATIVE_INFINITY;
3577
+ if (x === Number.POSITIVE_INFINITY)
3578
+ return x;
3579
+ let m = x;
3580
+ let k = 0;
3581
+ while (m >= SQRT2) {
3582
+ m /= 2;
3583
+ k += 1;
3584
+ }
3585
+ while (m < SQRT_HALF) {
3586
+ m *= 2;
3587
+ k -= 1;
3588
+ }
3589
+ const s = (m - 1) / (m + 1);
3590
+ const s2 = s * s;
3591
+ let series = 1 / 25;
3592
+ for (let d = 23;d >= 1; d -= 2)
3593
+ series = series * s2 + 1 / d;
3594
+ const small = 2 * s * series;
3595
+ return k * LN2_HI + (k * LN2_LO + small);
3596
+ }
3597
+ function buildLexicalIndex(documents, params = BM25F_PARAMS) {
3598
+ const documentFrequency = new Map;
3599
+ const totals = LEXICAL_FIELDS.map(() => 0);
3600
+ const docs = [];
3601
+ for (const document of documents) {
3602
+ const seenInDocument = new Set;
3603
+ const fields = LEXICAL_FIELDS.map((field, fieldIndex) => {
3604
+ const tokens = tokenize(document.fields[field] ?? "");
3605
+ const tf = new Map;
3606
+ for (const token of tokens) {
3607
+ tf.set(token, (tf.get(token) ?? 0) + 1);
3608
+ seenInDocument.add(token);
3609
+ }
3610
+ totals[fieldIndex] = (totals[fieldIndex] ?? 0) + tokens.length;
3611
+ return { tf, length: tokens.length };
3612
+ });
3613
+ for (const term of seenInDocument) {
3614
+ documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
3615
+ }
3616
+ docs.push({ id: document.id, fields });
3617
+ }
3618
+ const count = docs.length;
3619
+ const averageLength = totals.map((total) => count === 0 ? 0 : total / count);
3620
+ return { params, docs, documentFrequency, averageLength };
3621
+ }
3622
+ function weightedFrequency(index, document, term) {
3623
+ let total = 0;
3624
+ for (let i = 0;i < LEXICAL_FIELDS.length; i++) {
3625
+ const field = LEXICAL_FIELDS[i];
3626
+ const stats = document.fields[i];
3627
+ const tf = stats?.tf.get(term);
3628
+ if (field === undefined || stats === undefined || tf === undefined)
3629
+ continue;
3630
+ const { weight, b } = index.params.fields[field];
3631
+ const average = index.averageLength[i] ?? 0;
3632
+ const normalisation = 1 - b + b * (stats.length / average);
3633
+ total += weight * tf / normalisation;
3634
+ }
3635
+ return total;
3636
+ }
3637
+ function searchLexical(index, terms) {
3638
+ const total = index.docs.length;
3639
+ const weighted = [];
3640
+ for (const term of [...new Set(terms)].sort(compareCodeUnits2)) {
3641
+ const df = index.documentFrequency.get(term);
3642
+ if (df === undefined)
3643
+ continue;
3644
+ weighted.push({ term, idf: ln(1 + (total - df + 0.5) / (df + 0.5)) });
3645
+ }
3646
+ const { k1 } = index.params;
3647
+ const hits = [];
3648
+ for (const document of index.docs) {
3649
+ let score = 0;
3650
+ for (const { term, idf } of weighted) {
3651
+ const wtf = weightedFrequency(index, document, term);
3652
+ if (wtf === 0)
3653
+ continue;
3654
+ score += idf * wtf / (k1 + wtf);
3655
+ }
3656
+ if (score > 0)
3657
+ hits.push({ id: document.id, score });
3658
+ }
3659
+ return hits.sort((a, b) => b.score - a.score || compareCodeUnits2(a.id, b.id));
3660
+ }
3661
+
3662
+ // src/lib/search-render.ts
3663
+ var MAX_OUTPUT_BYTES = 16 * 1024;
3664
+ var TRUNCATION_MARKER = "[Systematic: search output truncated at 16 KB]";
3665
+ var MAX_TITLE_CHARS = 160;
3666
+ var MAX_TAGS = 8;
3667
+ var MAX_SNIPPET_CHARS = 240;
3668
+ var MAX_WARNINGS = 5;
3669
+ var SUPERSEDES_LABEL = "Supersedes:";
3670
+ var MAX_TAG_CHARS = 64;
3671
+ var MAX_MODULE_CHARS = 120;
3672
+ var MAX_QUERY_ECHO_CHARS = 200;
3673
+ var MAX_WARNING_CHARS = 200;
3674
+ var MAX_NOTE_CHARS = 200;
3675
+ var MAX_LIFECYCLE_LINE_CHARS = 400;
3676
+ var MAX_PATH_CHARS = 400;
3677
+ var MAX_LABEL_CHARS = 40;
3678
+ var ELLIPSIS = "…";
3679
+ var ANSI_SEQUENCE2 = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
3680
+ var LINE_BREAKS = /[\t\n\r\u000b\u000c\u0085\u2028\u2029]+/g;
3681
+ var CONTROL_CHARACTERS2 = /[\u0000-\u001f\u007f-\u009f]/g;
3682
+ var INVISIBLE_FORMATTING = /[\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g;
3683
+ function isHighSurrogate(code) {
3684
+ return code >= 55296 && code <= 56319;
3685
+ }
3686
+ function isLowSurrogate(code) {
3687
+ return code >= 56320 && code <= 57343;
3688
+ }
3689
+ function clip(text, max) {
3690
+ if (text.length <= max)
3691
+ return text;
3692
+ let cut = Math.max(0, max - ELLIPSIS.length);
3693
+ if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1)))
3694
+ cut -= 1;
3695
+ return `${text.slice(0, cut)}${ELLIPSIS}`;
3696
+ }
3697
+ function sanitizeInline(text, max = Number.POSITIVE_INFINITY) {
3698
+ const clean = text.replace(ANSI_SEQUENCE2, "").replace(LINE_BREAKS, " ").replace(CONTROL_CHARACTERS2, "").replace(INVISIBLE_FORMATTING, "").replace(/ {2,}/g, " ").trim();
3699
+ return clip(clean, max);
3700
+ }
3701
+ function truncateUtf8(text, maxBytes, marker) {
3702
+ const encoder = new TextEncoder;
3703
+ const bytes = encoder.encode(text);
3704
+ if (bytes.byteLength <= maxBytes)
3705
+ return text;
3706
+ const tail = `
3707
+ ${marker}`;
3708
+ const budget = Math.max(0, maxBytes - encoder.encode(tail).byteLength);
3709
+ let cut = budget;
3710
+ while (cut > 0 && ((bytes[cut] ?? 0) & 192) === 128)
3711
+ cut -= 1;
3712
+ let kept = new TextDecoder("utf-8").decode(bytes.subarray(0, cut));
3713
+ const lastBreak = kept.lastIndexOf(`
3714
+ `);
3715
+ if (lastBreak > 0)
3716
+ kept = kept.slice(0, lastBreak);
3717
+ return `${kept}${tail}`;
3718
+ }
3719
+ var IDENTIFIER_RUN2 = /[a-z0-9]+(?:[_-]+[a-z0-9]+)*/gi;
3720
+ var WORD2 = /[a-z0-9]+/g;
3721
+ function matchedTerms(run, wanted) {
3722
+ const lower = run.toLowerCase();
3723
+ const matched = [];
3724
+ if (wanted.has(lower))
3725
+ matched.push(lower);
3726
+ if (lower.includes("_") || lower.includes("-")) {
3727
+ for (const part of lower.match(WORD2) ?? []) {
3728
+ if (wanted.has(part) && !matched.includes(part))
3729
+ matched.push(part);
3730
+ }
3731
+ }
3732
+ return matched;
3733
+ }
3734
+ function findOccurrences(text, wanted) {
3735
+ const found = [];
3736
+ for (const match of text.matchAll(IDENTIFIER_RUN2)) {
3737
+ const run = match[0];
3738
+ const terms = matchedTerms(run, wanted);
3739
+ if (terms.length === 0)
3740
+ continue;
3741
+ const start = match.index ?? 0;
3742
+ found.push({ start, end: start + run.length, terms });
3743
+ }
3744
+ return found;
3745
+ }
3746
+ function addTerms(counts, terms) {
3747
+ for (const term of terms)
3748
+ counts.set(term, (counts.get(term) ?? 0) + 1);
3749
+ }
3750
+ function removeTerms(counts, terms) {
3751
+ for (const term of terms) {
3752
+ const remaining = (counts.get(term) ?? 1) - 1;
3753
+ if (remaining <= 0)
3754
+ counts.delete(term);
3755
+ else
3756
+ counts.set(term, remaining);
3757
+ }
3758
+ }
3759
+ function densestWindow(occurrences, width) {
3760
+ const counts = new Map;
3761
+ let best;
3762
+ let bestDistinct = 0;
3763
+ let next = 0;
3764
+ for (let first = 0;first < occurrences.length; first++) {
3765
+ const head = occurrences[first];
3766
+ if (head === undefined)
3767
+ break;
3768
+ for (let candidate = occurrences[next];candidate !== undefined && candidate.end - head.start <= width; candidate = occurrences[next]) {
3769
+ addTerms(counts, candidate.terms);
3770
+ next += 1;
3771
+ }
3772
+ if (next === first) {
3773
+ next = first + 1;
3774
+ continue;
3775
+ }
3776
+ if (counts.size > bestDistinct) {
3777
+ bestDistinct = counts.size;
3778
+ best = { first, last: next - 1 };
3779
+ }
3780
+ removeTerms(counts, head.terms);
3781
+ }
3782
+ return best;
3783
+ }
3784
+ function cutAround(text, spanStart, spanEnd, inner) {
3785
+ const middle = Math.floor((spanStart + spanEnd) / 2);
3786
+ let begin = Math.max(0, middle - Math.floor(inner / 2));
3787
+ const end0 = Math.min(text.length, begin + inner);
3788
+ begin = Math.max(0, end0 - inner);
3789
+ let end = end0;
3790
+ if (begin > 0 && text.charAt(begin - 1) !== " ") {
3791
+ const space = text.indexOf(" ", begin);
3792
+ if (space !== -1 && space + 1 <= spanStart)
3793
+ begin = space + 1;
3794
+ }
3795
+ if (end < text.length && text.charAt(end) !== " ") {
3796
+ const space = text.lastIndexOf(" ", end);
3797
+ if (space >= spanEnd)
3798
+ end = space;
3799
+ }
3800
+ if (begin > 0 && isLowSurrogate(text.charCodeAt(begin)))
3801
+ begin += 1;
3802
+ if (end < text.length && isHighSurrogate(text.charCodeAt(end - 1)))
3803
+ end -= 1;
3804
+ const body = text.slice(begin, end).trim();
3805
+ return `${begin > 0 ? ELLIPSIS : ""}${body}${end < text.length ? ELLIPSIS : ""}`;
3806
+ }
3807
+ function bodySnippet(text, queryTerms) {
3808
+ if (text === "" || queryTerms.length === 0)
3809
+ return;
3810
+ const occurrences = findOccurrences(text, new Set(queryTerms));
3811
+ const head = occurrences[0];
3812
+ if (head === undefined)
3813
+ return;
3814
+ const inner = MAX_SNIPPET_CHARS - 2 * ELLIPSIS.length;
3815
+ const window = densestWindow(occurrences, inner);
3816
+ const first = window === undefined ? head : occurrences[window.first];
3817
+ const last = window === undefined ? head : occurrences[window.last];
3818
+ if (first === undefined || last === undefined)
3819
+ return;
3820
+ const snippet = window === undefined ? clip(text.slice(first.start), MAX_SNIPPET_CHARS) : cutAround(text, first.start, last.end, inner);
3821
+ return snippet === "" ? undefined : snippet;
3822
+ }
3823
+ function extractSnippet(document, queryTerms) {
3824
+ const fromBody = bodySnippet(sanitizeInline(document.body), queryTerms);
3825
+ if (fromBody !== undefined)
3826
+ return fromBody;
3827
+ const symptoms = sanitizeInline(document.symptoms.join("; "), MAX_SNIPPET_CHARS);
3828
+ if (symptoms !== "")
3829
+ return symptoms;
3830
+ return sanitizeInline(document.title, MAX_SNIPPET_CHARS);
3831
+ }
3832
+ function plural(count, singular) {
3833
+ return `${count} ${singular}${count === 1 ? "" : "s"}`;
3834
+ }
3835
+ function renderHeader(result) {
3836
+ const query = sanitizeInline(result.query, MAX_QUERY_ECHO_CHARS);
3837
+ const prefix = `Search "${query}":`;
3838
+ switch (result.corpus.state) {
3839
+ case "none":
3840
+ return `${prefix} corpus: none (no docs/solutions/ directory under the project root).`;
3841
+ case "empty":
3842
+ return `${prefix} corpus: empty (docs/solutions/ holds no indexable docs).`;
3843
+ case "docs":
3844
+ return `${prefix} ${plural(result.corpus.docCount, "doc")}, ${plural(result.hits.length, "hit")}. Corpus: docs/solutions.`;
3845
+ }
3846
+ }
3847
+ function renderLifecycleLine(line) {
3848
+ const prefix = `${SUPERSEDES_LABEL} `;
3849
+ if (!line.startsWith(prefix)) {
3850
+ return sanitizeInline(line, MAX_LIFECYCLE_LINE_CHARS);
3851
+ }
3852
+ const paths = line.slice(prefix.length).split(", ").map((path) => sanitizeInline(path, MAX_PATH_CHARS)).filter((path) => path !== "");
3853
+ return `${prefix}${paths.join(", ")}`;
3854
+ }
3855
+ function renderHit(hit, queryTerms) {
3856
+ const { document } = hit;
3857
+ const lines = [`${hit.rank}. ${sanitizeInline(document.path)}`];
3858
+ lines.push(` ${[
3859
+ `Title: ${sanitizeInline(document.title, MAX_TITLE_CHARS)}`,
3860
+ `Kind: ${sanitizeInline(document.kind, MAX_LABEL_CHARS)}`,
3861
+ `Status: ${sanitizeInline(hit.status, MAX_LABEL_CHARS)}`
3862
+ ].join(" | ")}`);
3863
+ const module = document.module === undefined ? "" : sanitizeInline(document.module, MAX_MODULE_CHARS);
3864
+ const tags = document.tags.map((tag) => sanitizeInline(tag, MAX_TAG_CHARS)).filter((tag) => tag !== "").slice(0, MAX_TAGS);
3865
+ const meta = [];
3866
+ if (module !== "")
3867
+ meta.push(`Module: ${module}`);
3868
+ if (tags.length > 0)
3869
+ meta.push(`Tags: ${tags.join(", ")}`);
3870
+ if (meta.length > 0)
3871
+ lines.push(` ${meta.join(" | ")}`);
3872
+ lines.push(` Snippet: ${extractSnippet(document, queryTerms)}`);
3873
+ for (const line of hit.lifecycle)
3874
+ lines.push(` ${renderLifecycleLine(line)}`);
3875
+ return lines;
3876
+ }
3877
+ function renderSearchResult(result) {
3878
+ const lines = [renderHeader(result)];
3879
+ if (result.notes.length > 0) {
3880
+ lines.push(`Notes: ${result.notes.map((note) => sanitizeInline(note, MAX_NOTE_CHARS)).join("; ")}`);
3881
+ }
3882
+ if (result.warnings.length > 0) {
3883
+ lines.push("Warnings:");
3884
+ for (const warning of result.warnings.slice(0, MAX_WARNINGS)) {
3885
+ lines.push(`- ${sanitizeInline(warning, MAX_WARNING_CHARS)}`);
3886
+ }
3887
+ const hidden = result.warnings.length - MAX_WARNINGS;
3888
+ if (hidden > 0)
3889
+ lines.push(`- +${hidden} more`);
3890
+ }
3891
+ for (const hit of result.hits) {
3892
+ lines.push("", ...renderHit(hit, result.queryTerms));
3893
+ }
3894
+ return truncateUtf8(lines.join(`
3895
+ `), MAX_OUTPUT_BYTES, TRUNCATION_MARKER);
3896
+ }
3897
+
3898
+ // src/lib/search-core.ts
3899
+ var SEARCH_TOOL_NAME = "systematic_search";
3900
+ var SEARCH_ARGS = {
3901
+ query: "query",
3902
+ kind: "kind",
3903
+ limit: "limit"
3904
+ };
3905
+ var DEFAULT_LIMIT = 8;
3906
+ var MIN_LIMIT = 1;
3907
+ var MAX_LIMIT = 20;
3908
+ var MAX_QUERY_CHARS = 2000;
3909
+ 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.";
3910
+ var SEARCH_ARG_DESCRIPTIONS = {
3911
+ query: `What to look for: a symptom, error message, module or topic, in plain words. At most ${MAX_QUERY_CHARS} characters.`,
3912
+ kind: 'Optional. The kind of durable output to search. Only "solution" (docs/solutions/) exists today, and it is the default.',
3913
+ limit: `Optional. How many hits to return, an integer from ${MIN_LIMIT} to ${MAX_LIMIT}. Defaults to ${DEFAULT_LIMIT}.`
3914
+ };
3915
+ var SEARCH_NOTICES = {
3916
+ failed: "Error: search failed.",
3917
+ noProject: "No project directory is available for this session, so there is nothing to search."
3918
+ };
3919
+ var SEARCH_CONFIG_UNREADABLE_NOTE = "config unreadable";
3920
+ var MAX_SUCCESSOR_HOPS = 5;
3921
+ var SUCCESSOR_PATH_PREFIX = `${KIND_TABLE.solution.dir}/`;
3922
+ var CAUTION_LABEL = "Caution:";
3923
+ var SUCCESSOR_UNRESOLVED_TEXT = "successor unresolved";
3924
+ var STALE_CAUTION_TEXT = "marked stale";
3925
+ var MAX_STALE_REASON_CHARS = 200;
3926
+ var SEARCH_ERRORS = {
3927
+ queryEmpty: "Error: query must be a non-empty string.",
3928
+ queryTooLong: `Error: query must be at most ${MAX_QUERY_CHARS} characters.`,
3929
+ kindUnknown: `Error: kind must be one of: ${Object.keys(KIND_TABLE).join(", ")}.`,
3930
+ limitInvalid: `Error: limit must be an integer from ${MIN_LIMIT} to ${MAX_LIMIT}.`
3931
+ };
3932
+ function isSuccessorPathForm(value) {
3933
+ if (!value.startsWith(SUCCESSOR_PATH_PREFIX))
3934
+ return false;
3935
+ if (!value.endsWith(".md"))
3936
+ return false;
3937
+ const segments = value.split("/");
3938
+ if (segments.includes(".."))
3939
+ return false;
3940
+ const name = segments[segments.length - 1]?.toLowerCase();
3941
+ if (name === "readme.md")
3942
+ return false;
3943
+ if (segments.includes("_archived"))
3944
+ return false;
3945
+ return true;
3946
+ }
3947
+ function resolveSuccessor(candidate, byPath) {
3948
+ const visited = new Set([candidate.path]);
3949
+ let current = candidate;
3950
+ for (let hop = 1;hop <= MAX_SUCCESSOR_HOPS; hop++) {
3951
+ const link = current.supersededBy;
3952
+ if (link.state !== "value" || !isSuccessorPathForm(link.value)) {
3953
+ return;
3954
+ }
3955
+ if (visited.has(link.value))
3956
+ return;
3957
+ const target = byPath.get(link.value);
3958
+ if (target === undefined)
3959
+ return;
3960
+ visited.add(target.path);
3961
+ if (target.status !== "superseded")
3962
+ return target;
3963
+ current = target;
3964
+ }
3965
+ return;
3966
+ }
3967
+ function compareCodeUnits3(a, b) {
3968
+ if (a < b)
3969
+ return -1;
3970
+ return a > b ? 1 : 0;
3971
+ }
3972
+ function resolveLifecycle(ranked, documents) {
3973
+ const byPath = new Map(documents.map((doc) => [doc.path, doc]));
3974
+ const order = [];
3975
+ const entries = new Map;
3976
+ for (const candidate of ranked) {
3977
+ let target = candidate;
3978
+ let replaces;
3979
+ let unresolved = false;
3980
+ if (candidate.status === "superseded") {
3981
+ const successor = resolveSuccessor(candidate, byPath);
3982
+ if (successor === undefined)
3983
+ unresolved = true;
3984
+ else {
3985
+ target = successor;
3986
+ replaces = candidate.path;
3987
+ }
3988
+ }
3989
+ let entry = entries.get(target.path);
3990
+ if (entry === undefined) {
3991
+ entry = { document: target, replaced: new Set, unresolved };
3992
+ entries.set(target.path, entry);
3993
+ order.push(target.path);
3994
+ }
3995
+ if (replaces !== undefined)
3996
+ entry.replaced.add(replaces);
3997
+ }
3998
+ return order.flatMap((path) => {
3999
+ const entry = entries.get(path);
4000
+ if (entry === undefined)
4001
+ return [];
4002
+ return [
4003
+ {
4004
+ document: entry.document,
4005
+ supersedes: [...entry.replaced].sort(compareCodeUnits3),
4006
+ unresolved: entry.unresolved
4007
+ }
4008
+ ];
4009
+ });
4010
+ }
4011
+ function entryStatus(entry) {
4012
+ if (entry.unresolved)
4013
+ return "superseded";
4014
+ return entry.document.status === "stale" ? "stale" : "active";
4015
+ }
4016
+ function lifecycleLines(entry) {
4017
+ const lines = [];
4018
+ if (entry.supersedes.length > 0) {
4019
+ lines.push(`${SUPERSEDES_LABEL} ${entry.supersedes.join(", ")}`);
4020
+ }
4021
+ if (entry.unresolved) {
4022
+ lines.push(`${CAUTION_LABEL} ${SUCCESSOR_UNRESOLVED_TEXT}`);
4023
+ } else if (entry.document.status === "stale") {
4024
+ const reason = sanitizeInline(entry.document.staleReason ?? "", MAX_STALE_REASON_CHARS);
4025
+ lines.push(reason === "" ? `${CAUTION_LABEL} ${STALE_CAUTION_TEXT}` : `${CAUTION_LABEL} ${STALE_CAUTION_TEXT}: ${reason}`);
4026
+ }
4027
+ return lines;
4028
+ }
4029
+ function toLexicalDocument(document) {
4030
+ return {
4031
+ id: document.path,
4032
+ fields: {
4033
+ title: document.title,
4034
+ tags: document.tags.join(" "),
4035
+ module: document.module ?? "",
4036
+ symptoms: document.symptoms.join(`
4037
+ `),
4038
+ applies_when: document.appliesWhen.join(`
4039
+ `),
4040
+ component: document.component ?? "",
4041
+ problem_type: document.problemType ?? "",
4042
+ body: document.body
4043
+ }
4044
+ };
4045
+ }
4046
+ function validate(request) {
4047
+ const { query } = request;
4048
+ if (typeof query !== "string" || query.trim() === "") {
4049
+ return { ok: false, error: SEARCH_ERRORS.queryEmpty };
4050
+ }
4051
+ if (query.length > MAX_QUERY_CHARS) {
4052
+ return { ok: false, error: SEARCH_ERRORS.queryTooLong };
4053
+ }
4054
+ let kind = "solution";
4055
+ if (request.kind !== undefined) {
4056
+ if (!isDocumentKind(request.kind)) {
4057
+ return { ok: false, error: SEARCH_ERRORS.kindUnknown };
4058
+ }
4059
+ kind = request.kind;
4060
+ }
4061
+ let limit = DEFAULT_LIMIT;
4062
+ if (request.limit !== undefined) {
4063
+ const value = request.limit;
4064
+ if (typeof value !== "number" || !Number.isInteger(value) || value < MIN_LIMIT || value > MAX_LIMIT) {
4065
+ return { ok: false, error: SEARCH_ERRORS.limitInvalid };
4066
+ }
4067
+ limit = value;
4068
+ }
4069
+ return { ok: true, query, kind, limit };
4070
+ }
4071
+ async function runSearch(request, options) {
4072
+ const checked = validate(request);
4073
+ if (!checked.ok)
4074
+ return { ok: false, text: checked.error };
4075
+ const { query, kind, limit } = checked;
4076
+ const root = resolveSearchRoot(options.startDir);
4077
+ const load = (options.corpusLoader ?? loadCorpus)(root, kind);
4078
+ const { terms, truncated } = uniqueQueryTerms(query);
4079
+ const base = {
4080
+ query,
4081
+ queryTerms: terms,
4082
+ warnings: load.warnings
4083
+ };
4084
+ const noteList = [...options.notes ?? []];
4085
+ if (truncated)
4086
+ noteList.push("query cut to its first 64 distinct terms");
4087
+ const finish = (result) => ({
4088
+ ok: true,
4089
+ text: renderSearchResult(result),
4090
+ result
4091
+ });
4092
+ if (load.state === "none") {
4093
+ return finish({
4094
+ ...base,
4095
+ corpus: { state: "none", docCount: 0 },
4096
+ hits: [],
4097
+ notes: noteList
4098
+ });
4099
+ }
4100
+ if (load.documents.length === 0) {
4101
+ return finish({
4102
+ ...base,
4103
+ corpus: { state: "empty", docCount: 0 },
4104
+ hits: [],
4105
+ notes: noteList
4106
+ });
4107
+ }
4108
+ const index = buildLexicalIndex(load.documents.map(toLexicalDocument), options.lexicalParams ?? BM25F_PARAMS);
4109
+ const lexical = searchLexical(index, terms);
4110
+ const byPath = new Map(load.documents.map((doc) => [doc.path, doc]));
4111
+ const candidates = [];
4112
+ for (const hit of lexical) {
4113
+ const document = byPath.get(hit.id);
4114
+ if (document !== undefined)
4115
+ candidates.push(document);
4116
+ }
4117
+ const hits = resolveLifecycle(candidates, load.documents).slice(0, limit).map((entry, position) => ({
4118
+ rank: position + 1,
4119
+ document: entry.document,
4120
+ status: entryStatus(entry),
4121
+ lifecycle: lifecycleLines(entry)
4122
+ }));
4123
+ return finish({
4124
+ ...base,
4125
+ corpus: { state: "docs", docCount: load.documents.length },
4126
+ hits,
4127
+ notes: noteList
4128
+ });
4129
+ }
4130
+
3242
4131
  // src/lib/agent-resolver.ts
3243
4132
  function buildAgentCatalog(agentsDir) {
3244
4133
  const infos = findAgentsInDir(agentsDir);
3245
4134
  const byName = new Map;
3246
4135
  const entries = [];
3247
4136
  for (const info of infos) {
3248
- const content = fs2.readFileSync(info.file, "utf8");
4137
+ const content = fs3.readFileSync(info.file, "utf8");
3249
4138
  const parsed = parseValidatedAgentEntry(content, info.file);
3250
4139
  const category = info.category ?? "";
3251
4140
  const key = info.name;
@@ -3313,17 +4202,32 @@ function extractRawToolsSource(data, sourceFile) {
3313
4202
  }
3314
4203
  return trimmed;
3315
4204
  }
4205
+ var QUALIFIED_PERSONA_NAME = /^systematic:([^:]+):([^:]+)$/;
3316
4206
  function resolveAgent(catalog, name) {
3317
- return catalog.find((entry) => entry.name === name);
3318
- }
3319
- var DEFAULT_READONLY_TOOLS = ["read", "grep", "find", "ls"];
4207
+ const exact = catalog.find((entry) => entry.name === name);
4208
+ if (exact)
4209
+ return exact;
4210
+ const qualified = QUALIFIED_PERSONA_NAME.exec(name);
4211
+ if (!qualified)
4212
+ return;
4213
+ const [, category, flatName] = qualified;
4214
+ return catalog.find((entry) => entry.name === flatName && entry.category === category);
4215
+ }
4216
+ var DEFAULT_READONLY_TOOLS = [
4217
+ "read",
4218
+ "grep",
4219
+ "find",
4220
+ "ls",
4221
+ SEARCH_TOOL_NAME
4222
+ ];
3320
4223
  var OPENCODE_TO_PI_TOOL = {
3321
4224
  Read: "read",
3322
4225
  Grep: "grep",
3323
4226
  Glob: "find",
3324
4227
  Bash: "bash",
3325
4228
  Edit: "edit",
3326
- Write: "write"
4229
+ Write: "write",
4230
+ [SEARCH_TOOL_NAME]: SEARCH_TOOL_NAME
3327
4231
  };
3328
4232
  function unknownDeclaredToolError(toolName) {
3329
4233
  const error = new Error(`Unknown declared tool "${toolName}" in persona frontmatter; refusing to map ` + "to a Pi built-in (fail-closed). Known tools: " + `${Object.keys(OPENCODE_TO_PI_TOOL).join(", ")}.`);
@@ -3350,22 +4254,22 @@ function resolveToolAllowlist(toolsSource) {
3350
4254
  }
3351
4255
 
3352
4256
  // src/lib/bootstrap.ts
3353
- import fs3 from "node:fs";
4257
+ import fs4 from "node:fs";
3354
4258
  import os from "node:os";
3355
- import path2 from "node:path";
4259
+ import path3 from "node:path";
3356
4260
  function readHarnessProfile(bundledSkillsDir, name) {
3357
- const profilePath = path2.join(bundledSkillsDir, "using-systematic/references", `${name}-profile.md`);
4261
+ const profilePath = path3.join(bundledSkillsDir, "using-systematic/references", `${name}-profile.md`);
3358
4262
  try {
3359
- return fs3.readFileSync(profilePath, "utf8");
4263
+ return fs4.readFileSync(profilePath, "utf8");
3360
4264
  } catch (error) {
3361
4265
  console.error(`Failed to read harness profile ${profilePath}: ${error instanceof Error ? error.message : String(error)}`);
3362
4266
  return null;
3363
4267
  }
3364
4268
  }
3365
4269
  function readWorktreePlacementRule(bundledSkillsDir) {
3366
- const rulePath = path2.join(bundledSkillsDir, "using-systematic/references/worktree-placement.md");
4270
+ const rulePath = path3.join(bundledSkillsDir, "using-systematic/references/worktree-placement.md");
3367
4271
  try {
3368
- return fs3.readFileSync(rulePath, "utf8").trim();
4272
+ return fs4.readFileSync(rulePath, "utf8").trim();
3369
4273
  } catch (error) {
3370
4274
  console.error(`Failed to read worktree placement rule ${rulePath}: ${error instanceof Error ? error.message : String(error)}`);
3371
4275
  return null;
@@ -3422,15 +4326,15 @@ function getBootstrapContent(config, deps) {
3422
4326
  if (!config.bootstrap.enabled)
3423
4327
  return null;
3424
4328
  if (config.bootstrap.file) {
3425
- const customPath = config.bootstrap.file.startsWith("~/") ? path2.join(os.homedir(), config.bootstrap.file.slice(2)) : config.bootstrap.file;
3426
- if (fs3.existsSync(customPath)) {
3427
- return fs3.readFileSync(customPath, "utf8");
4329
+ const customPath = config.bootstrap.file.startsWith("~/") ? path3.join(os.homedir(), config.bootstrap.file.slice(2)) : config.bootstrap.file;
4330
+ if (fs4.existsSync(customPath)) {
4331
+ return fs4.readFileSync(customPath, "utf8");
3428
4332
  }
3429
4333
  }
3430
- const usingSystematicPath = path2.join(bundledSkillsDir, "using-systematic/SKILL.md");
3431
- if (!fs3.existsSync(usingSystematicPath))
4334
+ const usingSystematicPath = path3.join(bundledSkillsDir, "using-systematic/SKILL.md");
4335
+ if (!fs4.existsSync(usingSystematicPath))
3432
4336
  return null;
3433
- const fullContent = fs3.readFileSync(usingSystematicPath, "utf8");
4337
+ const fullContent = fs4.readFileSync(usingSystematicPath, "utf8");
3434
4338
  const { body } = parseFrontmatter(fullContent);
3435
4339
  const content = body.trim();
3436
4340
  const skillUsage = usageTemplate ?? getSkillUsageTemplate();
@@ -3452,12 +4356,11 @@ ${skillUsage}${ruleSection}${profileSection}
3452
4356
  }
3453
4357
 
3454
4358
  // src/lib/config.ts
3455
- import fs4 from "node:fs";
3456
- import os2 from "node:os";
3457
- import path3 from "node:path";
4359
+ import fs6 from "node:fs";
4360
+ import path5 from "node:path";
3458
4361
  import {
3459
- parse as parseJsonc,
3460
- printParseErrorCode
4362
+ parse as parseJsonc2,
4363
+ printParseErrorCode as printParseErrorCode2
3461
4364
  } from "jsonc-parser";
3462
4365
 
3463
4366
  // src/lib/bundled-names.ts
@@ -4434,7 +5337,7 @@ var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
4434
5337
  };
4435
5338
  var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
4436
5339
  var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
4437
- var validate = (schema, value, _ctx) => {
5340
+ var validate2 = (schema, value, _ctx) => {
4438
5341
  const validator = schema._zod.bag.validator;
4439
5342
  if (validator !== undefined) {
4440
5343
  if (validator(value) !== COMPILE_INVALID)
@@ -8620,7 +9523,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
8620
9523
  own(this, "spa", value);
8621
9524
  },
8622
9525
  validate(data, params) {
8623
- return validate(this, data, params);
9526
+ return validate2(this, data, params);
8624
9527
  },
8625
9528
  validateAsync(data, params) {
8626
9529
  return validateAsync(this, data, params);
@@ -9436,6 +10339,79 @@ var REMOVED_CONFIG_KEYS = [
9436
10339
  "workflow_guard"
9437
10340
  ];
9438
10341
 
10342
+ // src/lib/search-user-config.ts
10343
+ import fs5 from "node:fs";
10344
+ import os2 from "node:os";
10345
+ import path4 from "node:path";
10346
+ import {
10347
+ parse as parseJsonc,
10348
+ printParseErrorCode
10349
+ } from "jsonc-parser";
10350
+ var SearchSettingsSchema = object({
10351
+ enabled: boolean2().optional().meta({
10352
+ description: "Set to false to remove the search tool. Defaults to true when unset.",
10353
+ examples: [false]
10354
+ })
10355
+ }).strict().meta({
10356
+ 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.",
10357
+ examples: [{ enabled: false }]
10358
+ });
10359
+ function validateSearchBlock(value) {
10360
+ const parsed = SearchSettingsSchema.safeParse(value);
10361
+ if (parsed.success)
10362
+ return { ok: true, settings: parsed.data };
10363
+ const fields = [];
10364
+ for (const issue of parsed.error.issues) {
10365
+ const field = ["search", ...issue.path.map(String)].join(".");
10366
+ if (!fields.includes(field))
10367
+ fields.push(field);
10368
+ }
10369
+ return { ok: false, fields };
10370
+ }
10371
+ var MAX_WARNING_FIELDS = 5;
10372
+ var MAX_PATH_CHARS2 = 200;
10373
+ function displaySafe(text) {
10374
+ let out = "";
10375
+ for (const char of text) {
10376
+ if (out.length >= MAX_PATH_CHARS2)
10377
+ return `${out}…`;
10378
+ const code = char.codePointAt(0) ?? 0;
10379
+ const isControl = code <= 31 || code === 127 || code >= 128 && code <= 159 || code === 8232 || code === 8233;
10380
+ out += isControl ? `\\u${code.toString(16).padStart(4, "0")}` : char;
10381
+ }
10382
+ return out;
10383
+ }
10384
+ function formatSearchBlockWarning(sourcePath, fields) {
10385
+ const shown = fields.slice(0, MAX_WARNING_FIELDS).join(", ");
10386
+ const more = fields.length > MAX_WARNING_FIELDS ? ` and ${fields.length - MAX_WARNING_FIELDS} more` : "";
10387
+ 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.`;
10388
+ }
10389
+ function mergeSearchSettings(sources) {
10390
+ let enabled;
10391
+ let unreadable = false;
10392
+ for (const source of sources) {
10393
+ if (source.unreadable)
10394
+ unreadable = true;
10395
+ if (source.settings?.enabled !== undefined)
10396
+ enabled = source.settings.enabled;
10397
+ }
10398
+ if (enabled === undefined)
10399
+ return { settings: undefined, unreadable };
10400
+ return { settings: { enabled }, unreadable };
10401
+ }
10402
+ function selectConfigFile(dir, basename) {
10403
+ const jsoncPath = path4.join(dir, `${basename}.jsonc`);
10404
+ if (fs5.existsSync(jsoncPath))
10405
+ return jsoncPath;
10406
+ return path4.join(dir, `${basename}.json`);
10407
+ }
10408
+ function resolveUserLevelConfigDirs(options) {
10409
+ const homeDir = options?.homeDir ?? os2.homedir();
10410
+ const userConfigDir = options?.userConfigDir ?? path4.join(homeDir, ".config/opencode");
10411
+ const rawCustom = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
10412
+ return { homeDir, userConfigDir, customConfigDir: rawCustom || undefined };
10413
+ }
10414
+
9439
10415
  // src/lib/config-schema.ts
9440
10416
  var permissionSettingSchema = _enum(["ask", "allow", "deny"]);
9441
10417
  var permissionRuleSchema = union([
@@ -9725,6 +10701,7 @@ function createSystematicConfigSchema(opts) {
9725
10701
  description: "Allow a repository's project config to define its own `profiles` map. User-owned only — 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.",
9726
10702
  examples: [true, false]
9727
10703
  })).default(false),
10704
+ search: trustProtected(SearchSettingsSchema).optional(),
9728
10705
  disabled_skills: array(_enum([...skillNames, ...removedSkillNames])).default([]).meta({
9729
10706
  description: "Array of bundled skill names to disable globally. Unknown skill names are rejected at parse time.",
9730
10707
  examples: [["ce:plan", "ce:review"]]
@@ -10049,7 +11026,10 @@ var PROTECTED_OVERLAY_FIELD_PATHS = {
10049
11026
  pi: "categories.*.pi"
10050
11027
  }
10051
11028
  };
10052
- var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set(["allow_project_profiles"]);
11029
+ var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set([
11030
+ "allow_project_profiles",
11031
+ "search"
11032
+ ]);
10053
11033
  var MAX_DIAGNOSTIC_TEXT = 200;
10054
11034
  var MAX_STRIP_WARNINGS = 20;
10055
11035
  var DIAGNOSTIC_ELLIPSIS = "…";
@@ -10126,29 +11106,23 @@ function warnDroppedNames(dropped, field, warned, removalVersion, warningSink =
10126
11106
  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.`);
10127
11107
  }
10128
11108
  }
10129
- function resolveConfigPath(dir, basename) {
10130
- const jsoncPath = path3.join(dir, `${basename}.jsonc`);
10131
- if (fs4.existsSync(jsoncPath))
10132
- return jsoncPath;
10133
- return path3.join(dir, `${basename}.json`);
10134
- }
10135
11109
  function isErrorWithCode(error) {
10136
11110
  return error instanceof Error && "code" in error;
10137
11111
  }
10138
11112
  function loadJsoncFile(filePath) {
10139
11113
  let content;
10140
11114
  try {
10141
- content = fs4.readFileSync(filePath, "utf-8");
11115
+ content = fs6.readFileSync(filePath, "utf-8");
10142
11116
  } catch (error) {
10143
11117
  if (isErrorWithCode(error) && error.code === "ENOENT")
10144
11118
  return null;
10145
11119
  throw new Error(`Invalid Systematic config in ${filePath}: unable to read file`, { cause: error });
10146
11120
  }
10147
11121
  const errors = [];
10148
- const parsed = parseJsonc(content, errors);
11122
+ const parsed = parseJsonc2(content, errors);
10149
11123
  if (errors.length > 0) {
10150
11124
  const error = errors[0];
10151
- const message = error ? `${printParseErrorCode(error.error)} at offset ${error.offset}` : "unknown parse error";
11125
+ const message = error ? `${printParseErrorCode2(error.error)} at offset ${error.offset}` : "unknown parse error";
10152
11126
  throw new Error(`Invalid Systematic config in ${filePath}: JSONC parse error: ${message}`);
10153
11127
  }
10154
11128
  if (!isRecord2(parsed)) {
@@ -10254,19 +11228,21 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProj
10254
11228
  const protectedFields = collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles);
10255
11229
  const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig, allowProjectProfiles) : rawConfig;
10256
11230
  const config = trust === "project" ? stripProjectSecurityOverlayFields(topLevelStripped, filePath, warningSink) : topLevelStripped;
10257
- const result = SystematicConfigSchema.safeParse(config);
11231
+ const { config: configWithoutSearch, search } = splitSearchBlock(config, filePath, warningSink);
11232
+ const result = SystematicConfigSchema.safeParse(configWithoutSearch);
10258
11233
  if (!result.success) {
10259
- throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, config);
11234
+ throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, configWithoutSearch);
10260
11235
  }
10261
11236
  return {
10262
11237
  metadata: { kind: trust, presence: "present" },
10263
11238
  source: {
10264
11239
  kind: "file",
10265
11240
  canonicalPath: resolveConfigSourcePath(filePath),
10266
- config,
11241
+ config: configWithoutSearch,
10267
11242
  path: filePath,
10268
11243
  protectedFields,
10269
11244
  removedKeys: REMOVED_CONFIG_KEYS.filter((key) => Object.hasOwn(rawConfig, key)),
11245
+ ...search && { search },
10270
11246
  trust
10271
11247
  }
10272
11248
  };
@@ -10283,6 +11259,23 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProj
10283
11259
  };
10284
11260
  }
10285
11261
  }
11262
+ function splitSearchBlock(config, filePath, warningSink) {
11263
+ if (!Object.hasOwn(config, "search"))
11264
+ return { config, search: undefined };
11265
+ const { search: rawSearch, ...rest } = config;
11266
+ const validation = validateSearchBlock(rawSearch);
11267
+ if (validation.ok) {
11268
+ return {
11269
+ config: rest,
11270
+ search: { settings: validation.settings, unreadable: false }
11271
+ };
11272
+ }
11273
+ warningSink(formatSearchBlockWarning(filePath, validation.fields));
11274
+ return {
11275
+ config: rest,
11276
+ search: { unreadable: true }
11277
+ };
11278
+ }
10286
11279
  function classifyConfigSourceError(error) {
10287
11280
  if (isConfigSchemaError(error))
10288
11281
  return "schema-invalid";
@@ -10299,9 +11292,9 @@ function isConfigSchemaError(error) {
10299
11292
  }
10300
11293
  function resolveConfigSourcePath(filePath) {
10301
11294
  try {
10302
- return fs4.realpathSync(filePath);
11295
+ return fs6.realpathSync(filePath);
10303
11296
  } catch {
10304
- return path3.resolve(filePath);
11297
+ return path5.resolve(filePath);
10305
11298
  }
10306
11299
  }
10307
11300
  function emitTopLevelProtectedFieldWarning(projectSource, fieldPath, messageTemplate, sink) {
@@ -10329,6 +11322,13 @@ function collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles) {
10329
11322
  sourceKind: "project"
10330
11323
  }
10331
11324
  ] : [],
11325
+ ...Object.hasOwn(rawConfig, "search") ? [
11326
+ {
11327
+ fieldPath: "search",
11328
+ outcome: "blocked",
11329
+ sourceKind: "project"
11330
+ }
11331
+ ] : [],
10332
11332
  ...collectOverlayProtectedFields(rawConfig.agents, "agents"),
10333
11333
  ...collectOverlayProtectedFields(rawConfig.categories, "categories")
10334
11334
  ];
@@ -10592,6 +11592,7 @@ function loadConfigWithSources(projectDir, options) {
10592
11592
  const projectSource = project.source;
10593
11593
  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);
10594
11594
  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);
11595
+ 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);
10595
11596
  const suppressedStripCount = boundedProjectStrip.suppressedCount();
10596
11597
  if (suppressedStripCount > 0) {
10597
11598
  projectStrip.sink(`[systematic] ${suppressedStripCount} additional project-config protected-field warning(s) in (${sanitizeDiagnosticText(paths.projectConfig)}) were suppressed.`);
@@ -10617,6 +11618,7 @@ function loadConfigWithSources(projectDir, options) {
10617
11618
  const projectConfig = projectSource?.config;
10618
11619
  const customConfig = customSource?.config;
10619
11620
  const warned = new Set;
11621
+ const mergedSearch = mergeSearchSettings([userSource?.search, customSource?.search].filter((source) => source !== undefined));
10620
11622
  assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig);
10621
11623
  const profileSelection = resolveActiveProfile({
10622
11624
  userConfig,
@@ -10669,7 +11671,9 @@ function loadConfigWithSources(projectDir, options) {
10669
11671
  agents: overlayValues(mergedPiSubagentsOverlays.agents)
10670
11672
  },
10671
11673
  skills_as_commands: customConfig?.skills_as_commands ?? projectConfig?.skills_as_commands ?? userConfig?.skills_as_commands ?? DEFAULT_CONFIG.skills_as_commands,
10672
- allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles
11674
+ allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles,
11675
+ ...mergedSearch.settings && { search: mergedSearch.settings },
11676
+ ...mergedSearch.unreadable && { searchUnreadable: true }
10673
11677
  };
10674
11678
  const droppedSkills = computeDroppedNames(result.disabled_skills, CURRENT_SKILL_NAMES_SET);
10675
11679
  warnDroppedNames(droppedSkills, "disabled_skills", warned, undefined, warningSink);
@@ -11009,17 +12013,15 @@ function throwInvalidOverlay(sourcePath, keyPath) {
11009
12013
  throw new Error(`Invalid Systematic config in ${sourcePath}: ${keyPath} must be an object`);
11010
12014
  }
11011
12015
  function getConfigPaths(projectDir, options) {
11012
- const homeDir = options?.homeDir ?? os2.homedir();
11013
- const userConfigDir = options?.userConfigDir ?? path3.join(homeDir, ".config/opencode");
11014
- const customConfigDir = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
12016
+ const { homeDir, userConfigDir, customConfigDir } = resolveUserLevelConfigDirs(options);
11015
12017
  const result = {
11016
- userConfig: resolveConfigPath(userConfigDir, "systematic"),
11017
- projectConfig: resolveConfigPath(path3.join(projectDir, ".opencode"), "systematic"),
11018
- userDir: path3.join(homeDir, ".config/opencode/systematic"),
11019
- projectDir: path3.join(projectDir, ".opencode/systematic"),
12018
+ userConfig: selectConfigFile(userConfigDir, "systematic"),
12019
+ projectConfig: selectConfigFile(path5.join(projectDir, ".opencode"), "systematic"),
12020
+ userDir: path5.join(homeDir, ".config/opencode/systematic"),
12021
+ projectDir: path5.join(projectDir, ".opencode/systematic"),
11020
12022
  ...customConfigDir && {
11021
- customConfig: resolveConfigPath(customConfigDir, "systematic"),
11022
- customDir: path3.join(customConfigDir, "systematic")
12023
+ customConfig: selectConfigFile(customConfigDir, "systematic"),
12024
+ customDir: path5.join(customConfigDir, "systematic")
11023
12025
  }
11024
12026
  };
11025
12027
  return result;
@@ -11098,7 +12100,7 @@ function renderDelegateCatalogCompact(catalog, budget) {
11098
12100
  `);
11099
12101
  }
11100
12102
  function createPiDelegateTool(deps) {
11101
- const { catalog, createDelegateSession } = deps;
12103
+ const { catalog, createDelegateSession, customTools } = deps;
11102
12104
  const routing = {
11103
12105
  overlays: deps.overlays ?? EMPTY_ROUTING_OVERLAYS,
11104
12106
  piSubagentsOverlays: toSourcedPiSubagentsOverlays(deps.piSubagentsOverlays),
@@ -11113,7 +12115,7 @@ function createPiDelegateTool(deps) {
11113
12115
  parameters: buildDelegateParametersSchema(catalog),
11114
12116
  executionMode: DELEGATE_EXECUTION_MODE,
11115
12117
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
11116
- return runDelegateTool({ catalog, createDelegateSession }, routing, params, signal, ctx);
12118
+ return runDelegateTool({ catalog, createDelegateSession, customTools }, routing, params, signal, ctx);
11117
12119
  }
11118
12120
  };
11119
12121
  }
@@ -11227,11 +12229,12 @@ function resolvePersonaRouting(persona, agentName, ctx, routing) {
11227
12229
  return { model: resolvedModel, thinkingLevel, notice, commitNotice };
11228
12230
  }
11229
12231
  function validateDelegateRequest(catalog, params, ctx, routing) {
11230
- const { agent: agentName, task } = params;
11231
- const persona = resolveAgent(catalog, agentName);
12232
+ const { agent: requestedName, task } = params;
12233
+ const persona = resolveAgent(catalog, requestedName);
11232
12234
  if (!persona) {
11233
- throw new Error(`Unknown persona "${agentName}". Available personas: ${catalog.map((e) => e.name).join(", ")}`);
12235
+ throw new Error(`Unknown persona "${requestedName}". Available personas: ${catalog.map((e) => e.name).join(", ")}`);
11234
12236
  }
12237
+ const agentName = persona.name;
11235
12238
  const { model, thinkingLevel, notice, commitNotice } = resolvePersonaRouting(persona, agentName, ctx, routing);
11236
12239
  let allowedToolNames;
11237
12240
  try {
@@ -11296,7 +12299,7 @@ function cleanUpLateSession(session) {
11296
12299
  } catch {}
11297
12300
  });
11298
12301
  }
11299
- async function runValidatedDelegateSession(createDelegateSession, request, signal, cwd) {
12302
+ async function runValidatedDelegateSession(createDelegateSession, request, signal, cwd, customTools) {
11300
12303
  const {
11301
12304
  agentName,
11302
12305
  task,
@@ -11326,7 +12329,8 @@ async function runValidatedDelegateSession(createDelegateSession, request, signa
11326
12329
  thinkingLevel,
11327
12330
  cwd,
11328
12331
  systemPromptOverride: personaBody,
11329
- allowedToolNames
12332
+ allowedToolNames,
12333
+ ...customTools !== undefined && { customTools }
11330
12334
  });
11331
12335
  sessionPromise.then((session) => {
11332
12336
  if (signal?.aborted || state.abortReason !== undefined) {
@@ -11385,7 +12389,7 @@ async function runValidatedDelegateSession(createDelegateSession, request, signa
11385
12389
  }
11386
12390
  async function runDelegateTool(deps, routing, params, signal, ctx) {
11387
12391
  const request = validateDelegateRequest(deps.catalog, params, ctx, routing);
11388
- return runValidatedDelegateSession(deps.createDelegateSession, request, signal, ctx.cwd);
12392
+ return runValidatedDelegateSession(deps.createDelegateSession, request, signal, ctx.cwd, deps.customTools);
11389
12393
  }
11390
12394
 
11391
12395
  // src/lib/pi-delegate-session.ts
@@ -11416,6 +12420,7 @@ function buildDelegateAgentSessionOptions(options) {
11416
12420
  model,
11417
12421
  thinkingLevel,
11418
12422
  allowedToolNames,
12423
+ customTools,
11419
12424
  resourceLoader,
11420
12425
  sessionManager
11421
12426
  } = options;
@@ -11425,7 +12430,7 @@ function buildDelegateAgentSessionOptions(options) {
11425
12430
  model,
11426
12431
  ...thinkingLevel !== undefined && { thinkingLevel },
11427
12432
  tools: allowedToolNames,
11428
- customTools: [],
12433
+ customTools,
11429
12434
  resourceLoader,
11430
12435
  sessionManager
11431
12436
  };
@@ -11437,11 +12442,15 @@ function createDelegateSessionWith(runtime) {
11437
12442
  thinkingLevel,
11438
12443
  cwd,
11439
12444
  systemPromptOverride,
11440
- allowedToolNames
12445
+ allowedToolNames,
12446
+ customTools = []
11441
12447
  } = options;
11442
12448
  if (allowedToolNames.includes(DELEGATE_TOOL_NAME)) {
11443
12449
  throw new Error(`Refusing to construct delegate child session: allowedToolNames included ${DELEGATE_TOOL_NAME} (fail-closed re-entry guard).`);
11444
12450
  }
12451
+ if (customTools.some((tool) => tool.name === DELEGATE_TOOL_NAME)) {
12452
+ throw new Error(`Refusing to construct delegate child session: customTools included ${DELEGATE_TOOL_NAME} (fail-closed re-entry guard).`);
12453
+ }
11445
12454
  const agentDir = runtime.getAgentDir();
11446
12455
  const resourceLoader = runtime.createResourceLoader(buildDelegateResourceLoaderOptions({
11447
12456
  cwd,
@@ -11456,6 +12465,7 @@ function createDelegateSessionWith(runtime) {
11456
12465
  model,
11457
12466
  thinkingLevel,
11458
12467
  allowedToolNames,
12468
+ customTools,
11459
12469
  resourceLoader,
11460
12470
  sessionManager
11461
12471
  }));
@@ -11596,14 +12606,83 @@ function parseSourceCategoryAndKey(sourceRelPath) {
11596
12606
  return { category: undefined, agentKey: fileName.replace(/\.md$/, "") };
11597
12607
  }
11598
12608
 
12609
+ // src/lib/search-tool.ts
12610
+ function isSearchEnabled(settings) {
12611
+ return settings?.enabled !== false;
12612
+ }
12613
+ async function executeSearch(args, startDir, settings, unreadable) {
12614
+ try {
12615
+ if (startDir === undefined)
12616
+ return SEARCH_NOTICES.noProject;
12617
+ const record = isRecord(args) ? args : {};
12618
+ const response = await runSearch({
12619
+ query: record[SEARCH_ARGS.query],
12620
+ kind: record[SEARCH_ARGS.kind],
12621
+ limit: record[SEARCH_ARGS.limit]
12622
+ }, {
12623
+ startDir,
12624
+ settings,
12625
+ ...unreadable === true && { notes: [SEARCH_CONFIG_UNREADABLE_NOTE] }
12626
+ });
12627
+ return response.text;
12628
+ } catch {
12629
+ return SEARCH_NOTICES.failed;
12630
+ }
12631
+ }
12632
+ function usableDirectory(value) {
12633
+ return typeof value === "string" && value.length > 0 ? value : undefined;
12634
+ }
12635
+ var V2_INPUT_SCHEMA = {
12636
+ type: "object",
12637
+ properties: {
12638
+ [SEARCH_ARGS.query]: {
12639
+ type: "string",
12640
+ description: SEARCH_ARG_DESCRIPTIONS.query
12641
+ },
12642
+ [SEARCH_ARGS.kind]: {
12643
+ type: "string",
12644
+ description: SEARCH_ARG_DESCRIPTIONS.kind
12645
+ },
12646
+ [SEARCH_ARGS.limit]: {
12647
+ type: "integer",
12648
+ description: SEARCH_ARG_DESCRIPTIONS.limit
12649
+ }
12650
+ },
12651
+ required: [SEARCH_ARGS.query],
12652
+ additionalProperties: false
12653
+ };
12654
+ function buildPiParameters(Type) {
12655
+ return Type.Object({
12656
+ [SEARCH_ARGS.query]: Type.String({
12657
+ description: SEARCH_ARG_DESCRIPTIONS.query
12658
+ }),
12659
+ [SEARCH_ARGS.kind]: Type.Optional(Type.String({ description: SEARCH_ARG_DESCRIPTIONS.kind })),
12660
+ [SEARCH_ARGS.limit]: Type.Optional(Type.Integer({ description: SEARCH_ARG_DESCRIPTIONS.limit }))
12661
+ });
12662
+ }
12663
+ function createPiSearchTool(options) {
12664
+ const { settings, unreadable, Type } = options;
12665
+ return {
12666
+ name: SEARCH_TOOL_NAME,
12667
+ label: "Systematic Search",
12668
+ description: SEARCH_TOOL_DESCRIPTION,
12669
+ promptSnippet: "Use `systematic_search` to find past learnings in docs/solutions.",
12670
+ parameters: buildPiParameters(Type),
12671
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
12672
+ const text = await executeSearch(params, usableDirectory(ctx.cwd), settings, unreadable);
12673
+ return { content: [{ type: "text", text }], details: undefined };
12674
+ }
12675
+ };
12676
+ }
12677
+
11599
12678
  // src/lib/skill-resolver.ts
11600
- import fs7 from "node:fs";
11601
- import path6 from "node:path";
12679
+ import fs9 from "node:fs";
12680
+ import path8 from "node:path";
11602
12681
  import { pathToFileURL } from "node:url";
11603
12682
 
11604
12683
  // src/lib/skill-loader.ts
11605
- import fs5 from "node:fs";
11606
- import path4 from "node:path";
12684
+ import fs7 from "node:fs";
12685
+ import path6 from "node:path";
11607
12686
  var SKILL_PREFIX = "systematic:";
11608
12687
  var SKILL_DESCRIPTION_PREFIX = "(Systematic) ";
11609
12688
  function formatSkillCommandName(name) {
@@ -11620,7 +12699,7 @@ function formatSkillDescription(description, fallbackName) {
11620
12699
  return `${SKILL_DESCRIPTION_PREFIX}${desc}`;
11621
12700
  }
11622
12701
  function wrapSkillTemplate(skillPath, body) {
11623
- const skillDir = path4.dirname(skillPath);
12702
+ const skillDir = path6.dirname(skillPath);
11624
12703
  return `<skill-instruction>
11625
12704
  Base directory for this skill: ${skillDir}/
11626
12705
  File references (@path) in this skill are relative to this directory.
@@ -11639,7 +12718,7 @@ function extractSkillBody(wrappedTemplate) {
11639
12718
  }
11640
12719
  function loadSkill(skillInfo) {
11641
12720
  try {
11642
- const content = fs5.readFileSync(skillInfo.skillFile, "utf8");
12721
+ const content = fs7.readFileSync(skillInfo.skillFile, "utf8");
11643
12722
  const { body } = parseFrontmatter(content);
11644
12723
  const wrappedTemplate = wrapSkillTemplate(skillInfo.skillFile, body);
11645
12724
  return {
@@ -11662,8 +12741,8 @@ function loadSkill(skillInfo) {
11662
12741
  }
11663
12742
 
11664
12743
  // src/lib/skills.ts
11665
- import fs6 from "node:fs";
11666
- import path5 from "node:path";
12744
+ import fs8 from "node:fs";
12745
+ import path7 from "node:path";
11667
12746
  function parseMetadata(data) {
11668
12747
  const metadataRaw = data.metadata;
11669
12748
  if (!isRecord(metadataRaw)) {
@@ -11700,7 +12779,7 @@ function extractFrontmatterFromContent(content) {
11700
12779
  }
11701
12780
  function extractFrontmatter(filePath) {
11702
12781
  try {
11703
- const content = fs6.readFileSync(filePath, "utf8");
12782
+ const content = fs8.readFileSync(filePath, "utf8");
11704
12783
  return extractFrontmatterFromContent(content);
11705
12784
  } catch {
11706
12785
  return { name: "", description: "" };
@@ -11713,8 +12792,8 @@ function findSkillsInDir(dir, maxDepth = 3) {
11713
12792
  filter: (e) => e.isDirectory
11714
12793
  });
11715
12794
  for (const entry of entries) {
11716
- const skillFile = path5.join(entry.path, "SKILL.md");
11717
- if (fs6.existsSync(skillFile)) {
12795
+ const skillFile = path7.join(entry.path, "SKILL.md");
12796
+ if (fs8.existsSync(skillFile)) {
11718
12797
  const frontmatter = extractFrontmatter(skillFile);
11719
12798
  skills.push({
11720
12799
  path: entry.path,
@@ -11828,7 +12907,7 @@ ${raw}`;
11828
12907
  function buildSkillContentOutput(matchedSkill, argument) {
11829
12908
  const trimmedBody = extractSkillBody(matchedSkill.wrappedTemplate).trim();
11830
12909
  const body = argument === undefined ? trimmedBody : substituteSkillArguments(trimmedBody, argument);
11831
- const dir = path6.dirname(matchedSkill.skillFile);
12910
+ const dir = path8.dirname(matchedSkill.skillFile);
11832
12911
  const base = pathToFileURL(dir).href;
11833
12912
  const files = discoverSkillFiles(dir);
11834
12913
  const lines = [
@@ -11859,17 +12938,17 @@ function discoverSkillFiles(dir, limit = 10) {
11859
12938
  function handleEntry(entry, currentDir) {
11860
12939
  if (entry.isDirectory()) {
11861
12940
  if (!shouldSkipDirectory(entry.name)) {
11862
- recurse(path6.resolve(currentDir, entry.name));
12941
+ recurse(path8.resolve(currentDir, entry.name));
11863
12942
  }
11864
12943
  } else if (shouldIncludeFile(entry.name)) {
11865
- files.push(path6.resolve(currentDir, entry.name));
12944
+ files.push(path8.resolve(currentDir, entry.name));
11866
12945
  }
11867
12946
  }
11868
12947
  function recurse(currentDir) {
11869
12948
  if (files.length >= limit)
11870
12949
  return;
11871
12950
  try {
11872
- const entries = fs7.readdirSync(currentDir, { withFileTypes: true });
12951
+ const entries = fs9.readdirSync(currentDir, { withFileTypes: true });
11873
12952
  for (const entry of entries) {
11874
12953
  if (files.length >= limit)
11875
12954
  break;
@@ -11883,10 +12962,10 @@ function discoverSkillFiles(dir, limit = 10) {
11883
12962
  }
11884
12963
 
11885
12964
  // src/pi.ts
11886
- var __dirname2 = path7.dirname(fileURLToPath(import.meta.url));
11887
- var packageRoot = path7.resolve(__dirname2, "..");
11888
- var bundledSkillsDir = path7.join(packageRoot, "skills");
11889
- var bundledAgentsDir = path7.join(packageRoot, "agents");
12965
+ var __dirname2 = path9.dirname(fileURLToPath(import.meta.url));
12966
+ var packageRoot = path9.resolve(__dirname2, "..");
12967
+ var bundledSkillsDir = path9.join(packageRoot, "skills");
12968
+ var bundledAgentsDir = path9.join(packageRoot, "agents");
11890
12969
  var PI_BOOTSTRAP_USAGE_TEMPLATE = `**Skills usage:**
11891
12970
  - Use \`systematic_skill\` for Systematic skills.
11892
12971
  - For non-Systematic skills, follow Pi's native skill instructions and read the listed SKILL.md path.`;
@@ -11984,6 +13063,13 @@ async function systematicPiExtension(pi, deps = defaultPiExtensionDependencies)
11984
13063
  };
11985
13064
  }
11986
13065
  });
13066
+ const searchTool = isSearchEnabled(piConfig.search) ? createPiSearchTool({
13067
+ settings: piConfig.search,
13068
+ unreadable: piConfig.searchUnreadable,
13069
+ Type: Type3
13070
+ }) : undefined;
13071
+ if (searchTool !== undefined)
13072
+ pi.registerTool(searchTool);
11987
13073
  try {
11988
13074
  const disabledAgents = new Set(piConfig.disabled_agents);
11989
13075
  const catalog = buildAgentCatalogFn(bundledAgentsDir).filter((entry) => !isAgentDisabled(disabledAgents, piRoutingOverlays.agents, entry.category, entry.key));
@@ -11992,7 +13078,8 @@ async function systematicPiExtension(pi, deps = defaultPiExtensionDependencies)
11992
13078
  createDelegateSession: createRealPiDelegateSession,
11993
13079
  overlays: piRoutingOverlays,
11994
13080
  piSubagentsOverlays: piConfig.pi_subagents,
11995
- activeProfile: piConfigMetadata.activeProfile
13081
+ activeProfile: piConfigMetadata.activeProfile,
13082
+ ...searchTool !== undefined && { customTools: [searchTool] }
11996
13083
  }));
11997
13084
  } catch (error) {
11998
13085
  reportPiDelegateCatalogFailure(error);