ceulen 0.13.0 → 0.14.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 (29) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/extensions/modules/a2a/lib/config.ts +15 -1
  3. package/extensions/modules/a2a/test/config.test.ts +27 -0
  4. package/extensions/modules/fff/index.ts +19 -0
  5. package/extensions/modules/fff/test/index.test.ts +31 -4
  6. package/extensions/modules/gh/configPanel.ts +9 -6
  7. package/extensions/modules/gh/test/gh.test.ts +61 -0
  8. package/extensions/modules/jfind/index.ts +10 -1
  9. package/extensions/modules/jfind/lib/cascade.ts +15 -1
  10. package/extensions/modules/jfind/lib/lexical.ts +18 -6
  11. package/extensions/modules/jfind/lib/tree.ts +34 -4
  12. package/extensions/modules/jfind/test/cascade.test.ts +56 -1
  13. package/extensions/modules/repair/configPanel.ts +11 -8
  14. package/extensions/modules/repair/index.ts +58 -25
  15. package/extensions/modules/repair/lib/auto-bg.ts +45 -2
  16. package/extensions/modules/repair/lib/auto-generated.ts +14 -4
  17. package/extensions/modules/repair/lib/read-archive.ts +14 -0
  18. package/extensions/modules/repair/lib/read-sqlite.ts +10 -4
  19. package/extensions/modules/repair/lib/settings.ts +19 -8
  20. package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
  21. package/extensions/modules/repair/test/hardening.test.ts +214 -0
  22. package/extensions/modules/repair/test/settings.test.ts +52 -13
  23. package/extensions/modules/shells/index.ts +31 -14
  24. package/extensions/modules/shells/lib/sessions.ts +76 -8
  25. package/extensions/modules/shells/test/output.test.ts +130 -0
  26. package/extensions/modules/shells/test/sessions.test.ts +127 -5
  27. package/extensions/modules/web/lib/pdf.ts +4 -2
  28. package/extensions/modules/web/test/pdf.test.ts +84 -0
  29. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0 — 2026-10-08
4
+
5
+ Review-wave hardening across 7 modules (round-3 findings), 8 new regression
6
+ suites, tests now 2792 (was 2750):
7
+
8
+ - **gh**: the `/config` run_watch row passed its working value BY VALUE — the
9
+ row setter rebound its parameter and every save wrote the original value
10
+ back with a false "Saved" notify (the module's only setting was silently
11
+ unwritable). Now the todo-module `{ value }` box pattern with a load-bearing
12
+ NaN guard (a garbage inline edit can no longer write JSON `null`);
13
+ round-trip tests drive row edit → save → settings.json.
14
+ - **fff**: in override mode a `guarded()` collision on `grep`/`find` (repair
15
+ owns the wrapped builtins) aborted the whole registration loop — override
16
+ mode lost resolve_file/fff_multi_grep/related_files along with the two
17
+ colliding names. Registration now degrades PER TOOL with one dim notify
18
+ naming the skipped tools; normal mode unchanged.
19
+ - **repair** (archive/sqlite/guard hardening): `pkg.tgz:src/x.ts:50-80` peels
20
+ the trailing lines-selector BEFORE the member lookup (member+range reads
21
+ were reporting "no member matching"); guard × archive-member reads resolve
22
+ the real target path; tar option-injection gate (member names starting with
23
+ `-` are refused); the auto-generated write guard handles relative paths
24
+ correctly; ascii rename-arrow target paths in read notices.
25
+ - **shells**: `since:"last"` cursors moved to LIFETIME line counts — a
26
+ ring-cap shrink could strand an index cursor and permanently black out
27
+ output; per-stream cursors (one shared offset duplicated stderr when stdout
28
+ was longer); `kill` refuses pid 0 (`kill(-0)` would SIGTERM pi's own
29
+ process group); session-name resolution prefers LIVE matches over lingering
30
+ exited ones; session_start clear via `store.clear()`.
31
+ - **jfind**: file reads respect `scanLimitBytes`/`maxBytes` byte caps with
32
+ truncation flags (a 3 MB file was read whole); a single-file scope that
33
+ lists zero eligible files surfaces the eligibility refusal instead of a
34
+ silent "no hits".
35
+ - **a2a**: `A2A_MAX_CONCURRENT` is now read from process env (declared env
36
+ parity) and a garbage/`0` value falls back to the default instead of
37
+ zeroing the admission pool (which would reject every inbound task).
38
+ - **web/read_pdf**: the lazy pdf.js engine import goes through `pathToFileURL`
39
+ — an unencoded `file://` string broke on spaces in the install path.
40
+ - Tests: +8 regression suites/files — gh config row round-trip, fff guarded-
41
+ collision degrade, repair hardening (A1/A2/A4/A6/A9), repair auto-bg +
42
+ settings, shells output/store wiring, web pdf pathToFileURL, a2a env parity,
43
+ jfind caps.
44
+
3
45
  ## 0.13.0 — 2026-10-08
4
46
 
5
47
  - **Tool-parity wave** (8h OMP/industry survey plan): 4 new modules + 4
@@ -372,6 +372,13 @@ function num(v: any, fallback: number): number {
372
372
  return Number.isFinite(n) ? n : fallback;
373
373
  }
374
374
 
375
+ /** num() that refuses values < 1 — a zeroed admission pool would reject
376
+ * every inbound task, so garbage/0 falls back instead. */
377
+ function numPositive(v: any, fallback: number): number {
378
+ const n = num(v, fallback);
379
+ return n >= 1 ? n : fallback;
380
+ }
381
+
375
382
  function bool(v: any, fallback: boolean): boolean {
376
383
  if (typeof v === "boolean") return v;
377
384
  if (typeof v === "string") return /^(1|true|yes|on)$/i.test(v.trim());
@@ -428,7 +435,14 @@ export function loadConfig(opts: {
428
435
  cfg.server.portFallback = num(srv.portFallback ?? env.A2A_PORT_FALLBACK, DEFAULTS.server.portFallback);
429
436
  cfg.server.host = String(srv.host ?? env.A2A_HOST ?? DEFAULTS.server.host);
430
437
  cfg.server.workspace = String(srv.workspace ?? "");
431
- cfg.server.maxConcurrent = num(srv.maxConcurrent, DEFAULTS.server.maxConcurrent);
438
+ // Env parity with the siblings above (A2A_REPLY_TIMEOUT / A2A_ASYNC_TIMEOUT):
439
+ // SECURITY_ENV_KEYS + the panel row declare A2A_MAX_CONCURRENT, so the
440
+ // resolver must read it. numPositive keeps a garbage/"0" value from zeroing
441
+ // the admission pool.
442
+ cfg.server.maxConcurrent = numPositive(
443
+ srv.maxConcurrent ?? env.A2A_MAX_CONCURRENT,
444
+ DEFAULTS.server.maxConcurrent,
445
+ );
432
446
  cfg.server.replyTimeoutSec = num(srv.replyTimeoutSec ?? env.A2A_REPLY_TIMEOUT, DEFAULTS.server.replyTimeoutSec);
433
447
  cfg.server.asyncTimeoutSec = num(srv.asyncTimeoutSec ?? env.A2A_ASYNC_TIMEOUT, DEFAULTS.server.asyncTimeoutSec);
434
448
  cfg.server.agentName = String(srv.agentName ?? env.A2A_AGENT_NAME ?? "");
@@ -347,6 +347,33 @@ childTranscripts: false,
347
347
  });
348
348
  });
349
349
 
350
+ it("reads A2A_MAX_CONCURRENT from process env (declared env parity)", () => {
351
+ withIsolatedPiDir((dir) => {
352
+ const cases: Array<[string | undefined, number]> = [
353
+ ["6", 6],
354
+ [undefined, DEFAULTS().server.maxConcurrent],
355
+ // num() parses "0" as the finite 0 — the admission pool must fall
356
+ // back to the default rather than zeroing (a 0 pool rejects every
357
+ // inbound task). Same spirit as the repo-injection guard: garbage
358
+ // never widens or disables the ceiling.
359
+ ["abc", DEFAULTS().server.maxConcurrent],
360
+ ["0", DEFAULTS().server.maxConcurrent],
361
+ ];
362
+ for (const [value, expected] of cases) {
363
+ const saved = process.env.A2A_MAX_CONCURRENT;
364
+ if (value === undefined) delete process.env.A2A_MAX_CONCURRENT;
365
+ else process.env.A2A_MAX_CONCURRENT = value;
366
+ try {
367
+ const cfg = loadConfig({ cwd: dir });
368
+ assert.equal(cfg.server.maxConcurrent, expected, `A2A_MAX_CONCURRENT=${value}`);
369
+ } finally {
370
+ if (saved === undefined) delete process.env.A2A_MAX_CONCURRENT;
371
+ else process.env.A2A_MAX_CONCURRENT = saved;
372
+ }
373
+ }
374
+ });
375
+ });
376
+
350
377
  it("reads settings.json a2a key", () => {
351
378
  withIsolatedPiDir((dir) => {
352
379
  fs.mkdirSync(path.join(dir, ".pi"), { recursive: true });
@@ -427,6 +427,10 @@ export default function fffExtension(pi: ExtensionAPI) {
427
427
  let toolsRegistered = false;
428
428
  let autocompleteRegistered = false;
429
429
  let disabledTools: Set<string> = new Set();
430
+ // Names registerBoundedTool could not claim this session (another
431
+ // extension's guarded() owns them). One dim note after the loop instead of
432
+ // a first-throw unwind — a single collision must not cost the whole toolset.
433
+ let skippedTools: string[] = [];
430
434
 
431
435
  function resolveRuntimeConfig() {
432
436
  // Pi populates extension flag values only after loading extension factories.
@@ -977,6 +981,9 @@ export default function fffExtension(pi: ExtensionAPI) {
977
981
  activeCwd = ctx.cwd;
978
982
  resolveRuntimeConfig();
979
983
  registerTools();
984
+ if (skippedTools.length > 0) {
985
+ ctx.ui.notify(`FFF: skipped ${skippedTools.join(", ")} — name already claimed by another extension.`, "info");
986
+ }
980
987
  if (currentMode === "override") {
981
988
  const available = new Set(pi.getAllTools().map((tool) => tool.name));
982
989
  const active = pi.getActiveTools();
@@ -1003,6 +1010,7 @@ export default function fffExtension(pi: ExtensionAPI) {
1003
1010
  if (toolsRegistered) return;
1004
1011
  toolsRegistered = true;
1005
1012
  disabledTools = readDisabledTools();
1013
+ skippedTools = [];
1006
1014
 
1007
1015
  // --- Shared render helpers ---
1008
1016
 
@@ -1034,6 +1042,17 @@ export default function fffExtension(pi: ExtensionAPI) {
1034
1042
  };
1035
1043
 
1036
1044
  const registerBoundedTool = (tool: any) => {
1045
+ const name = tool.name as string;
1046
+ try {
1047
+ registerOneBoundedTool(tool);
1048
+ } catch {
1049
+ // Collision (usually repair's guarded() owning the builtin name in
1050
+ // override mode): skip THIS tool, keep registering the rest.
1051
+ skippedTools.push(name);
1052
+ }
1053
+ };
1054
+
1055
+ const registerOneBoundedTool = (tool: any) => {
1037
1056
  const execute = tool.execute;
1038
1057
  // Per-tool kill-switch (ceulen.disabledTools): rows use canonical names
1039
1058
  // (ffgrep/fffind); override mode registers grep/find, so map before the
@@ -67,7 +67,7 @@ function harness(
67
67
  finder: any,
68
68
  mode?: string,
69
69
  extraFlags: Record<string, unknown> = {},
70
- options: { cwd?: string; create?: (params: any) => any; excludedTools?: string[] } = {},
70
+ options: { cwd?: string; create?: (params: any) => any; excludedTools?: string[]; throwOnTool?: string } = {},
71
71
  ) {
72
72
  (FileFinder as any).create = (params: any) => ({
73
73
  ok: true,
@@ -77,13 +77,17 @@ function harness(
77
77
  const commands = new Map<string, any>();
78
78
  const events = new Map<string, Function[]>();
79
79
  const flags = new Map<string, unknown>(Object.entries(extraFlags));
80
+ const notifies: string[] = [];
80
81
  let activeTools = ["read", "bash", "edit", "write"];
81
82
  if (mode) flags.set("fff-mode", mode);
82
83
  let flagsReady = false;
83
84
  const pi = {
84
85
  getFlag: (name: string) => flagsReady ? flags.get(name) : undefined,
85
86
  registerFlag: () => {},
86
- registerTool: (tool: any) => tools.set(tool.name, tool),
87
+ registerTool: (tool: any) => {
88
+ if (tool.name === options.throwOnTool) throw new Error(`ceulen: tool "${tool.name}" already owned by another module`);
89
+ tools.set(tool.name, tool);
90
+ },
87
91
  registerCommand: (name: string, command: any) => commands.set(name, command),
88
92
  on: (name: string, handler: Function) => events.set(name, [...(events.get(name) ?? []), handler]),
89
93
  getAllTools: () => [...tools.values()]
@@ -94,9 +98,9 @@ function harness(
94
98
  };
95
99
  fffExtension(pi as any);
96
100
  flagsReady = true;
97
- const ctx = { cwd: options.cwd ?? process.cwd(), ui: { notify: () => {}, addAutocompleteProvider: () => {} } };
101
+ const ctx = { cwd: options.cwd ?? process.cwd(), ui: { notify: (m: string) => notifies.push(m), addAutocompleteProvider: () => {} } };
98
102
  const started = events.get("session_start")?.[0]({}, ctx);
99
- return { tools, commands, events, flags, started, setActiveTools: (names: string[]) => { activeTools = [...names]; }, get activeTools() { return activeTools; } };
103
+ return { tools, commands, events, flags, started, notifies, setActiveTools: (names: string[]) => { activeTools = [...names]; }, get activeTools() { return activeTools; } };
100
104
  }
101
105
 
102
106
  async function run(tool: any, params: any) {
@@ -572,6 +576,29 @@ describe("pi-fff tools", () => {
572
576
  assert.ok((text(result)).includes("[Output truncated:"));
573
577
  assert.ok(result.details.truncation.outputLines <= 2000);
574
578
  });
579
+
580
+ it("override mode degrades per tool when a name is already claimed (guarded collision)", async () => {
581
+ // registerTool throwing on "grep" simulates the bundle guarded() map:
582
+ // repair wrapped the builtin first. The throw must cost ONLY grep —
583
+ // resolve_file / fff_multi_grep / related_files still register and the
584
+ // session_start handler settles without an init failure.
585
+ const { tools, started, notifies } = harness(fakeFinder(), "override", {}, { throwOnTool: "grep" });
586
+ await started;
587
+ assert.ok(!tools.has("grep"));
588
+ for (const name of ["find", "resolve_file", "fff_multi_grep", "related_files"]) {
589
+ assert.ok(tools.has(name), `expected ${name} to register despite the grep collision`);
590
+ }
591
+ assert.ok(notifies.some((m) => m.includes("skipped") && m.includes("grep")));
592
+ assert.ok(!notifies.some((m) => m.includes("init failed")));
593
+ });
594
+
595
+ it("normal mode registers everything and never emits a skipped note", async () => {
596
+ const { tools, notifies } = harness(fakeFinder());
597
+ for (const name of ["ffgrep", "fffind", "resolve_file", "fff_multi_grep", "related_files"]) {
598
+ assert.ok(tools.has(name), `expected ${name} to register`);
599
+ }
600
+ assert.ok(!notifies.some((m) => m.includes("skipped")));
601
+ });
575
602
  });
576
603
 
577
604
  describe("before_agent_start search guidance", () => {
@@ -49,7 +49,7 @@ function writeRunWatchTimeoutSecs(secs: number): string {
49
49
  return file;
50
50
  }
51
51
 
52
- export function buildGhGroups(runWatchTimeoutSecs: number): PanelGroup[] {
52
+ export function buildGhGroups(working: { value: number }): PanelGroup[] {
53
53
  return [
54
54
  {
55
55
  key: "gh",
@@ -57,8 +57,11 @@ export function buildGhGroups(runWatchTimeoutSecs: number): PanelGroup[] {
57
57
  tab: "Tools",
58
58
  icon: "🐙",
59
59
  rows: [
60
- row("gh.runWatchTimeoutSecs", "run_watch budget", "number", runWatchTimeoutSecs, (v) => {
61
- runWatchTimeoutSecs = Math.max(10, Math.floor(Number(v)));
60
+ row("gh.runWatchTimeoutSecs", "run_watch budget", "number", working.value, (v) => {
61
+ // NaN guard is load-bearing: a garbage inline edit must not write
62
+ // NaN (JSON null) — leave the working value untouched instead.
63
+ const n = Math.floor(Number(v));
64
+ if (Number.isFinite(n)) working.value = Math.max(10, n);
62
65
  }, {
63
66
  defaultValue: DEFAULT_RUN_WATCH_TIMEOUT_SECS,
64
67
  description: "Seconds run_watch keeps polling a workflow run before reporting in-progress (capped at gh's 5-min command deadline).",
@@ -70,13 +73,13 @@ export function buildGhGroups(runWatchTimeoutSecs: number): PanelGroup[] {
70
73
 
71
74
  /** gh's ModuleConfig for the central /config panel. */
72
75
  export function ghConfig(_pi: ExtensionAPI): ModuleConfig {
73
- let working = readRunWatchTimeoutSecs();
76
+ const working = { value: readRunWatchTimeoutSecs() };
74
77
  return {
75
78
  groups: () => buildGhGroups(working),
76
79
  save: async (edited, ctx: ExtensionContext) => {
77
80
  if (![...edited].some((k) => k.startsWith("gh."))) return;
78
- const file = writeRunWatchTimeoutSecs(working);
79
- ctx.ui.notify(`Saved gh.runWatchTimeoutSecs=${working} to ${file} (applies to the next run_watch call).`, "info");
81
+ const file = writeRunWatchTimeoutSecs(working.value);
82
+ ctx.ui.notify(`Saved gh.runWatchTimeoutSecs=${working.value} to ${file} (applies to the next run_watch call).`, "info");
80
83
  },
81
84
  };
82
85
  }
@@ -4,6 +4,9 @@
4
4
 
5
5
  import assert from "node:assert/strict";
6
6
  import { describe, it } from "node:test";
7
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
7
10
  import {
8
11
  formatGhFailure,
9
12
  ghAvailable,
@@ -278,3 +281,61 @@ describe("dispatcher + availability", () => {
278
281
  );
279
282
  });
280
283
  });
284
+
285
+ describe("/config row (run_watch budget)", () => {
286
+ // Round-trip: the row setter mutates a SHARED { value } object (the
287
+ // todo-module pattern) so the save path persists what was edited — a
288
+ // by-value parameter made the setting silently unwritable (round-3 P2).
289
+ it("row.set writes through to the working copy; garbage input keeps it", async () => {
290
+ const { buildGhGroups } = await import("../configPanel.ts");
291
+ const working = { value: 600 };
292
+ const row0 = buildGhGroups(working)[0]!.rows[0]!;
293
+ assert.equal(row0.key, "gh.runWatchTimeoutSecs");
294
+ assert.equal(row0.value, 600);
295
+
296
+ row0.set("900");
297
+ assert.equal(working.value, 900);
298
+ row0.set(1200);
299
+ assert.equal(working.value, 1200);
300
+
301
+ // NaN guard: a garbage inline edit leaves the working value untouched
302
+ // (a NaN would JSON-serialize to null and silently reset the setting).
303
+ row0.set("garbage");
304
+ assert.equal(working.value, 1200);
305
+ // Floor: sub-10 values clamp to 10.
306
+ row0.set(5);
307
+ assert.equal(working.value, 10);
308
+ });
309
+
310
+ it("save() persists the edited working value and notifies; no owned key = no-op", async () => {
311
+ const { ghConfig } = await import("../configPanel.ts");
312
+ const home = process.env.PI_CODING_AGENT_DIR;
313
+ const dir = mkdtempSync(join(tmpdir(), "gh-config-"));
314
+ process.env.PI_CODING_AGENT_DIR = dir;
315
+ try {
316
+ const cfg = ghConfig({} as never);
317
+ // Drive the row the panel drives it: build groups, edit, save.
318
+ const row0 = cfg.groups()[0]!.rows[0]!;
319
+ row0.set("900");
320
+
321
+ const notes: string[] = [];
322
+ await cfg.save(new Set(["gh.runWatchTimeoutSecs"]), {
323
+ ui: { notify: (m: string) => notes.push(m) },
324
+ } as never);
325
+ const persisted = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"));
326
+ assert.equal(persisted.gh.runWatchTimeoutSecs, 900);
327
+ assert.match(notes[0] ?? "", /runWatchTimeoutSecs=900/);
328
+
329
+ // No owned edited key → no write.
330
+ await cfg.save(new Set(["other.key"]), {
331
+ ui: { notify: (m: string) => notes.push(m) },
332
+ } as never);
333
+ assert.equal(JSON.parse(readFileSync(join(dir, "settings.json"), "utf8")).gh.runWatchTimeoutSecs, 900);
334
+ assert.equal(notes.length, 1);
335
+ } finally {
336
+ if (home === undefined) delete process.env.PI_CODING_AGENT_DIR;
337
+ else process.env.PI_CODING_AGENT_DIR = home;
338
+ rmSync(dir, { recursive: true, force: true });
339
+ }
340
+ });
341
+ });
@@ -28,7 +28,8 @@ export default function jfindModule(pi: ExtensionAPI): void {
28
28
  description:
29
29
  "Semantic code find: describe a BEHAVIOR (\"where do we parse CLI flags\", \"retry with backoff around provider calls\") and get the files and line ranges that implement it, strongest first. " +
30
30
  "A lexical keyword scan ranks candidates, then a System One judge (the router's classifier models) ranks filenames, passage sketches, and full passages in three waves. " +
31
- "Use when grep/ffgrep can't phrase the search as a literal pattern; needs a classifier model to be configured (router catalog). Slower than grep (a few seconds of judging).",
31
+ "Use when grep/ffgrep can't phrase the search as a literal pattern; needs a classifier model to be configured (router catalog). Slower than grep (a few seconds of judging). " +
32
+ "The `path` scope accepts a directory OR a single file (a deny-listed/binary/secret/empty file is refused with a reason).",
32
33
  promptSnippet: "Semantic find: locate code by describing what it does",
33
34
  promptGuidelines: [
34
35
  "Describe the behavior, not the keywords: jfind judges passages semantically.",
@@ -81,6 +82,14 @@ export default function jfindModule(pi: ExtensionAPI): void {
81
82
  }
82
83
  throw err;
83
84
  }
85
+ // A single-file scope that lists zero eligible files used to fall through
86
+ // to a silent "no hits" — surface the eligibility refusal instead.
87
+ if (result.stats.listed === 0 && scopeInput.length > 0 && statSync(root).isFile()) {
88
+ return {
89
+ content: [{ type: "text", text: `not searchable: ${scopeInput} (deny-listed, binary, secret, or empty by jfind's eligibility rules)` }],
90
+ details: { query },
91
+ };
92
+ }
84
93
  const { stats, threshold, keywords } = result;
85
94
  const scope = scopeInput.length > 0 ? ` in ${scopeInput}` : "";
86
95
  const out: string[] = [];
@@ -6,6 +6,7 @@
6
6
  // budgets, and constants.
7
7
 
8
8
  import { basename } from "node:path";
9
+ import { statSync } from "node:fs";
9
10
  import {
10
11
  fileScore,
11
12
  grepIndex,
@@ -24,6 +25,7 @@ import {
24
25
  type SketchCard,
25
26
  } from "./questions.js";
26
27
  import {
28
+ eligibleFile,
27
29
  listFiles,
28
30
  mergeHeat,
29
31
  plainContent,
@@ -197,7 +199,7 @@ class Cascade {
197
199
  const keywords = deriveKeywords(query, this.#options.extraKeywords);
198
200
 
199
201
  onProgress?.("lexical scan");
200
- const entries = listFiles(root);
202
+ const entries = scopeFiles(root);
201
203
  const fileMap = new Map(entries.map((e) => [e.rel, e.path]));
202
204
  const index: GrepIndex = await grepIndex(root, keywords, { files: fileMap, signal });
203
205
  this.stats.listed = entries.length;
@@ -369,6 +371,18 @@ class Cascade {
369
371
  }
370
372
  }
371
373
 
374
+ /** The lexical/judging cascade runs over a file LIST; a single-file `path`
375
+ * scope used to list zero files and report "no hits" silently. Wrap it as a
376
+ * one-entry walk so the documented scope works. Exported for tests. */
377
+ export function scopeFiles(root: string): FileEntry[] {
378
+ const st = statSync(root);
379
+ if (!st.isDirectory()) {
380
+ const rel = basename(root);
381
+ return eligibleFile(rel, st.size, rel.startsWith(".")) ? [{ path: root, rel, size: st.size }] : [];
382
+ }
383
+ return listFiles(root);
384
+ }
385
+
372
386
  /** One cascade search. Judge failures degrade coverage and land in
373
387
  * `stats.failures` — never thrown. */
374
388
  export function runCascade(options: CascadeOptions): Promise<CascadeResult> {
@@ -157,16 +157,21 @@ export interface GrepIndexOptions {
157
157
  }
158
158
 
159
159
  const SCAN_LIMIT_DEFAULT = 512 * 1024;
160
+ /** ponytail: hard read cap per file — a multi-GB log must not buffer whole.
161
+ * The scan only needs counts, not completeness. */
162
+ const SCAN_READ_CAP = 2 * 1024 * 1024;
160
163
 
161
164
  /**
162
165
  * Count keyword occurrences (case-insensitive) per file by scanning each
163
- * eligible file's first `scanLimitBytes`. ponytail: plain read + regex over
164
- * matching lines (no native grep) — the cascade's ranking only needs counts,
165
- * and the walk is already eligibility-bounded. Exported for tests.
166
+ * eligible file's first `scanLimitBytes`, read as a BOUNDED prefix (open +
167
+ * read at most SCAN_READ_CAP bytes; a multi-GB log never buffers whole).
168
+ * ponytail: plain read + regex over matching lines (no native grep) — the
169
+ * cascade's ranking only needs counts, and the walk is already
170
+ * eligibility-bounded. Exported for tests.
166
171
  */
167
172
  export async function grepIndex(rootAbs: string, rawKeywords: readonly string[], options: GrepIndexOptions): Promise<GrepIndex> {
168
173
  void rootAbs;
169
- const { readFile } = await import("node:fs/promises");
174
+ const { open } = await import("node:fs/promises");
170
175
  const keywordsLower = rawKeywords.map((k) => k.toLowerCase()).filter((k) => k.length > 0);
171
176
  const index: GrepIndex = { keywords: keywordsLower, perFileKw: new Map(), filesScanned: 0 };
172
177
  if (keywordsLower.length === 0) return index;
@@ -176,8 +181,15 @@ export async function grepIndex(rootAbs: string, rawKeywords: readonly string[],
176
181
  index.filesScanned++;
177
182
  let text: string;
178
183
  try {
179
- const buf = await readFile(abs);
180
- text = buf.subarray(0, options.scanLimitBytes ?? SCAN_LIMIT_DEFAULT).toString("utf8");
184
+ const cap = Math.min(options.scanLimitBytes ?? SCAN_LIMIT_DEFAULT, SCAN_READ_CAP);
185
+ const fh = await open(abs, "r");
186
+ try {
187
+ const buf = Buffer.alloc(cap);
188
+ const { bytesRead } = await fh.read(buf, 0, cap, 0);
189
+ text = buf.subarray(0, bytesRead).toString("utf8");
190
+ } finally {
191
+ await fh.close();
192
+ }
181
193
  } catch {
182
194
  continue; // unreadable — just unranked
183
195
  }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { lines, clipBytes, countOccurrences } from "./lexical.js";
7
7
  import { execFileSync } from "node:child_process";
8
- import { readdirSync, readFileSync, statSync } from "node:fs";
8
+ import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
 
11
11
  // ── eligibility deny-lists (tree.ts, verbatim) ──────────────────────────────
@@ -327,13 +327,33 @@ export interface ReadText {
327
327
  }
328
328
 
329
329
  const BINARY_PROBE_BYTES = 8192;
330
+ /** ponytail: open + read at most this many bytes — a multi-GB file must not
331
+ * buffer whole before the maxBytes slice (the binary probe sits inside it). */
332
+ const READ_OPEN_CAP = 4 * 1024 * 1024;
330
333
 
331
- /** Read up to `maxBytes` of a text file; rejects binaries and blank files. */
334
+ /** Read up to `maxBytes` of a text file; rejects binaries and blank files.
335
+ * The underlying read is capped at READ_OPEN_CAP bytes regardless of maxBytes
336
+ * (beyond-cap callers already ask for ≤ READ_LIMIT, so only the OOM case
337
+ * changes); a short read at the cap flags `truncated`. */
332
338
  export function readTextFile(absPath: string, maxBytes: number): ReadText {
333
- let buf = readFileSync(absPath);
339
+ const want = Math.min(maxBytes, READ_OPEN_CAP);
340
+ const fd = openSync(absPath, "r");
341
+ let buf: Buffer;
342
+ let total = 0;
343
+ try {
344
+ buf = Buffer.alloc(want);
345
+ while (total < want) {
346
+ const n = readSync(fd, buf, total, want - total, total);
347
+ if (n === 0) break;
348
+ total += n;
349
+ }
350
+ buf = buf.subarray(0, total);
351
+ } finally {
352
+ closeSync(fd);
353
+ }
334
354
  const probe = buf.subarray(0, Math.min(buf.length, BINARY_PROBE_BYTES));
335
355
  if (probe.includes(0)) throw new Error("binary");
336
- const truncated = buf.length > maxBytes;
356
+ const truncated = total >= want && (maxBytes > want || readSizeExceeds(absPath, want));
337
357
  if (truncated) {
338
358
  buf = buf.subarray(0, maxBytes);
339
359
  const newline = buf.lastIndexOf(0x0a);
@@ -344,6 +364,16 @@ export function readTextFile(absPath: string, maxBytes: number): ReadText {
344
364
  return { text, truncated };
345
365
  }
346
366
 
367
+ /** Size check for the exact-cap edge (read filled `want` — is there more?).
368
+ * Only consulted when maxBytes === the read cap. */
369
+ function readSizeExceeds(absPath: string, cap: number): boolean {
370
+ try {
371
+ return statSync(absPath).size > cap;
372
+ } catch {
373
+ return false;
374
+ }
375
+ }
376
+
347
377
  /**
348
378
  * Union the judged-positive spans; never bridge an unjudged gap. A merged
349
379
  * span keeps the max probability. Strongest first, then earliest.
@@ -14,12 +14,13 @@ import {
14
14
  mergeHeat,
15
15
  plainContent,
16
16
  rankedHeat,
17
+ readTextFile,
17
18
  selectWindows,
18
19
  sketch,
19
20
  windows,
20
21
  } from "../lib/tree.js";
21
22
  import { entryKey, passageKey, nameBatch, sketchBatch, passageBatch, type Judge, type Request } from "../lib/questions.js";
22
- import { runCascade, type CascadeOptions } from "../lib/cascade.js";
23
+ import { runCascade, scopeFiles, type CascadeOptions } from "../lib/cascade.js";
23
24
 
24
25
  const dir = mkdtempSync(path.join(tmpdir(), "ceulen-jfind-"));
25
26
  after(() => rmSync(dir, { recursive: true, force: true }));
@@ -302,4 +303,58 @@ describe("cascade", () => {
302
303
  /aborted/,
303
304
  );
304
305
  });
306
+
307
+ it("a SINGLE-FILE path scope judges that file (B10 — was a silent no-hits)", async () => {
308
+ const judge = fakeJudge("src/spawn.ts");
309
+ const result = await runCascade({
310
+ root: path.join(proj, "src", "spawn.ts"),
311
+ query: "spawn a child process",
312
+ extraKeywords: [],
313
+ judge,
314
+ });
315
+ assert.equal(result.stats.listed, 1, "the file itself is the one entry");
316
+ assert.ok(result.hits.length >= 1, `hits: ${JSON.stringify(result.hits)}`);
317
+ assert.equal(result.hits[0]!.rel, "spawn.ts");
318
+ });
319
+
320
+ it("an ineligible single-file scope lists zero files", () => {
321
+ writeFileSync(path.join(proj, "logo.png"), "not text");
322
+ assert.deepEqual(scopeFiles(path.join(proj, "logo.png")), []);
323
+ const one = scopeFiles(path.join(proj, "src", "spawn.ts"));
324
+ assert.equal(one.length, 1);
325
+ assert.equal(one[0]!.rel, "spawn.ts");
326
+ });
327
+
328
+ it("grepIndex reads a BOUNDED prefix, not the whole file (B11)", async () => {
329
+ // 3 MB file: needle within the 2 MB SCAN_READ_CAP, and one beyond it when
330
+ // the caller raises scanLimitBytes above the cap.
331
+ const big = path.join(dir, "scan-big.log");
332
+ const head = Buffer.from("spawn early\n");
333
+ const filler = Buffer.alloc(1024 * 1024, 0x78); // 'x'
334
+ writeFileSync(big, Buffer.concat([head, filler, Buffer.from("spawn late\n")]));
335
+ const files = new Map([["scan-big.log", big]]);
336
+ // scanLimitBytes 3 MB > the 2 MB read cap: the cap wins, the 2 MB+ hit is NOT counted.
337
+ const capped = await grepIndex(dir, ["spawn"], { files, scanLimitBytes: 3 * 1024 * 1024 });
338
+ const counts = capped.perFileKw.get("scan-big.log");
339
+ assert.ok(counts, "within-cap hit counted");
340
+ assert.ok(counts![0]! >= 1, "the early spawn counted");
341
+ assert.equal(capped.filesScanned, 1);
342
+ // Default 512 KB scan limit on the same file: works, no whole-file read.
343
+ const small = await grepIndex(dir, ["spawn"], { files });
344
+ assert.ok(small.perFileKw.get("scan-big.log")![0]! >= 1);
345
+ });
346
+
347
+ it("readTextFile caps its read even when maxBytes is huge (B11)", () => {
348
+ const big = path.join(dir, "read-big.txt");
349
+ writeFileSync(big, Buffer.concat([Buffer.from("head\n"), Buffer.alloc(5 * 1024 * 1024, 0x61)]));
350
+ // maxBytes far above the 4 MB READ_OPEN_CAP: the read is capped and flagged truncated.
351
+ const huge = readTextFile(big, 8 * 1024 * 1024);
352
+ assert.equal(huge.truncated, true, "beyond-cap read flags truncation");
353
+ assert.ok(Buffer.byteLength(huge.text) <= 4 * 1024 * 1024, "text stays within the open cap");
354
+ assert.match(huge.text, /^head\n/);
355
+ // Normal path unchanged: 1 KB slice of the same file.
356
+ const sliced = readTextFile(big, 1024);
357
+ assert.equal(sliced.truncated, true);
358
+ assert.ok(Buffer.byteLength(sliced.text) <= 1024 + 8, "slice ends on a line boundary");
359
+ });
305
360
  });
@@ -1,12 +1,15 @@
1
1
  // repair's /config contribution — Tools tab, Repair section.
2
2
  //
3
- // The working copy is the EFFECTIVE settings (global agent-dir file, trusted
4
- // project file over it); saving writes the `repair` section back to the
5
- // GLOBAL settings.json. The three tool-call-time toggles apply to the next
6
- // turn (settings are read per tool call); the two bash keys bind at module
7
- // load, hence the "next session" warning. The config module AUTO-prepends the
8
- // Enable row and appends the per-tool toggle rows (apply_patch /
9
- // str_replace_editor from the registry entry) — none of those are declared here.
3
+ // The working copy mirrors the GLOBAL settings.json `repair` section (the
4
+ // file this panel writes); readRepairSettings() without a cwd is exactly the
5
+ // global layer. The trusted-project layer stays visible: the save notify
6
+ // discloses when a project file shadows the global save (projectShadow), the
7
+ // same contract as the other global-writing panels (advisor, subagent, a2a).
8
+ // The three tool-call-time toggles apply to the next turn (settings are read
9
+ // per tool call); the two bash keys bind at module load, hence the "next
10
+ // session" warning. The config module AUTO-prepends the Enable row and
11
+ // appends the per-tool toggle rows (apply_patch / str_replace_editor from the
12
+ // registry entry) — none of those are declared here.
10
13
 
11
14
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
15
  import { row, type PanelGroup } from "../../lib/panel.js";
@@ -95,7 +98,7 @@ export function repairConfig(_pi: ExtensionAPI): ModuleConfig {
95
98
  notes.push("The bash description + auto-background mechanics bind at session start — that change applies to the next session.");
96
99
  }
97
100
  const shadowed = projectShadow(ctx.cwd, ctx.isProjectTrusted?.() === true);
98
- if (shadowed) notes.push(`This project's .pi/settings.json sets "repair" — the project layer overrides this save.`);
101
+ if (shadowed) notes.push(`This project's .pi/settings.json sets "repair" — the project layer overrides this save (project values stay authoritative at runtime).`);
99
102
  ctx.ui.notify(notes.join(" "), shadowed ? "warning" : "info");
100
103
  },
101
104
  };