ceulen 0.12.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 (50) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/extensions/lib/registry.ts +15 -1
  3. package/extensions/modules/a2a/lib/config.ts +15 -1
  4. package/extensions/modules/a2a/test/config.test.ts +27 -0
  5. package/extensions/modules/composer/test/module.test.ts +2 -2
  6. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  7. package/extensions/modules/fff/index.ts +19 -0
  8. package/extensions/modules/fff/test/index.test.ts +31 -4
  9. package/extensions/modules/gh/configPanel.ts +9 -6
  10. package/extensions/modules/gh/test/gh.test.ts +61 -0
  11. package/extensions/modules/jfind/index.ts +124 -0
  12. package/extensions/modules/jfind/lib/cascade.ts +391 -0
  13. package/extensions/modules/jfind/lib/format.ts +12 -0
  14. package/extensions/modules/jfind/lib/judge.ts +74 -0
  15. package/extensions/modules/jfind/lib/lexical.ts +244 -0
  16. package/extensions/modules/jfind/lib/questions.ts +178 -0
  17. package/extensions/modules/jfind/lib/tree.ts +404 -0
  18. package/extensions/modules/jfind/test/cascade.test.ts +360 -0
  19. package/extensions/modules/notify/index.ts +33 -0
  20. package/extensions/modules/notify/lib/notify.ts +99 -0
  21. package/extensions/modules/notify/test/notify.test.ts +95 -0
  22. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  23. package/extensions/modules/repair/configPanel.ts +18 -9
  24. package/extensions/modules/repair/index.ts +173 -9
  25. package/extensions/modules/repair/lib/auto-bg.ts +45 -2
  26. package/extensions/modules/repair/lib/auto-generated.ts +99 -0
  27. package/extensions/modules/repair/lib/read-archive.ts +115 -0
  28. package/extensions/modules/repair/lib/read-sqlite.ts +191 -0
  29. package/extensions/modules/repair/lib/settings.ts +23 -9
  30. package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
  31. package/extensions/modules/repair/test/hardening.test.ts +214 -0
  32. package/extensions/modules/repair/test/readers.test.ts +291 -0
  33. package/extensions/modules/repair/test/settings.test.ts +54 -14
  34. package/extensions/modules/sg/index.ts +129 -0
  35. package/extensions/modules/sg/lib/ops.ts +144 -0
  36. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  37. package/extensions/modules/sg/test/sg.test.ts +128 -0
  38. package/extensions/modules/shells/index.ts +227 -0
  39. package/extensions/modules/shells/lib/sessions.ts +412 -0
  40. package/extensions/modules/shells/test/output.test.ts +130 -0
  41. package/extensions/modules/shells/test/sessions.test.ts +397 -0
  42. package/extensions/modules/web/index.ts +34 -0
  43. package/extensions/modules/web/lib/pdf.ts +183 -0
  44. package/extensions/modules/web/test/extension.test.ts +2 -1
  45. package/extensions/modules/web/test/pdf.test.ts +84 -0
  46. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  47. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  48. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  49. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  50. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,96 @@
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
+
45
+ ## 0.13.0 — 2026-10-08
46
+
47
+ - **Tool-parity wave** (8h OMP/industry survey plan): 4 new modules + 4
48
+ read/write upgrades, all live-verified end-to-end (real spawns, real
49
+ classifier round-trips, real osascript):
50
+ - **shells** (new module): one `shell` tool — start/list/output/stdin/kill
51
+ over persistent background processes (dev servers, watchers, long
52
+ builds). Own process group per session (group kill via `kill(-pid)`),
53
+ 256 KB line rings (head+tail + truncation marker), 10 live/5 exited
54
+ caps, `since:"last"` output cursor, killAll on session_shutdown.
55
+ Plan-blocked.
56
+ - **read-sqlite** (repair): the wrapped read opens `db.sqlite` views —
57
+ table list, `:users` schema+rows, `:users:42` rowid, `:users:name=alice`
58
+ key lookup, `:?SELECT…` read-only query. `node:sqlite` READ-ONLY per
59
+ call; db is genuinely un-writable.
60
+ - **read-archive** (repair): `.tar`/`.tgz`/`.zip` member listing +
61
+ content through the read path; exact-then-unique-suffix member match,
62
+ 1 MB cap, binary refusal; `pkg.tgz:src/x.ts:50-80` slices the member.
63
+ - **auto-generated guard** (repair): writes/edits to lockfiles, minified
64
+ bundles, build dirs and snapshots are refused with a regenerate hint
65
+ (bash stays the deliberate override); `repair.autoGenGuard` setting,
66
+ default on, /config row on Tools → Repair.
67
+ - **read_pdf** (web, 13th tool): local PDF text via vendored pdf.js 4.10
68
+ (Apache-2.0, lazy import, workerless) — no external binaries; pages
69
+ grammar `"3"`, `"1-5"`, `"2,4,6-8"`, 10-page cap/call. Plan read-only.
70
+ - **sg** (new module): `ast_grep` (structural search, `$VAR`/`$$$ALL`
71
+ meta-variables, multi-pattern merge+dedupe) + `ast_edit` (pattern →
72
+ rewrite across files; DRY-RUN by default, staleness re-check after
73
+ apply warns on self-matching rewrites). Fail-open on a missing
74
+ ast-grep binary. Pattern-parse failures render a hint on ast-grep 0.4x
75
+ (exit 8 "Cannot parse query") as well as legacy sg. Plan read-only
76
+ search, blocked rewrite.
77
+ - **jfind** (new module): semantic code find — describe a behavior, get
78
+ files + line ranges, strongest first. OMP cascade port (lexical IDF
79
+ prior → filename judging → sketch routing → passage verification); the
80
+ judge routes through the router's System One classifier models. Plan
81
+ read-only.
82
+ - **notify** (new module): one `notify` tool — desktop notification via
83
+ osascript/notify-send, bell fallback, harmless by construction.
84
+ - Wiring: registry entries + per-tool kill-switches + plan-mode tiers, test
85
+ globs, /config tool-section count 16→20, composer disabled-list, AGENTS.md
86
+ sections, `@types/node` ^24 (node:sqlite types).
87
+ - Tests: 2750 (was 2661) — suites for shells sessions, readers, sg ops,
88
+ jfind cascade (fake-judge), notify.
89
+ - Live-verified (2026-10-08 round): shells ring/group-kill/stdin,
90
+ sqlite+archive views + guard refusal through real pi runs, pdf extraction,
91
+ sg dry-run/apply/staleness, jfind cascade vs the real classifier, notify
92
+ osascript delivery; one fix shipped (sg pattern-error detection, above).
93
+
3
94
  ## 0.12.0 — 2026-10-08
4
95
 
5
96
  - **Secrets never land in settings.json** (user policy: URLs fine, credentials
@@ -50,6 +50,10 @@ import { attachmentsConfig } from "../modules/attachments/configPanel.ts";
50
50
  import cronModule from "../modules/cron/index.ts";
51
51
  import { cronConfig } from "../modules/cron/configPanel.ts";
52
52
  import permissionModule from "../modules/permission/index.ts";
53
+ import shellsModule from "../modules/shells/index.ts";
54
+ import sgModule from "../modules/sg/index.ts";
55
+ import jfindModule from "../modules/jfind/index.ts";
56
+ import notifyModule from "../modules/notify/index.ts";
53
57
  import configModule from "../modules/config/index.ts";
54
58
 
55
59
  /** A module's contribution to the central `/config` panel. */
@@ -156,11 +160,14 @@ export const MODULES: ModuleEntry[] = [
156
160
  { name: "fff", category: "Tools", describe: "FFF fuzzy file/content search (ffgrep, fffind) + @-mention completions.", load: fffModule, tools: [
157
161
  "ffgrep", "ffind", "fff_multi_grep", "resolve_file", "related_files",
158
162
  ] },
163
+ // jfind after fff: the semantic sibling of the lexical search pair (its
164
+ // judge resolves through the router's classifier models at execute time).
165
+ { name: "jfind", category: "Tools", describe: "Semantic code find: describe what code does, get files + line ranges (lexical prior + System One judge cascade).", load: jfindModule, tools: ["jfind"] },
159
166
  // Web after fff: same class of append-only before_agent_start guidance
160
167
  // (conditional on web_* tools being active) — no prompt-rewrite contract
161
168
  // beyond fff's shipped precedent.
162
169
  { name: "web", category: "Tools", describe: "Unified web tools: search (SearXNG/Brave/Firecrawl), extract & crawl (JSDOM/Firecrawl/Crawl4AI/agy), screenshot/PDF, CDP browser interaction, Gemini research, image generation, one-off chat.", load: webModule, config: webConfig, tools: [
163
- "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y",
170
+ "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y", "read_pdf",
164
171
  ] },
165
172
  { name: "rules", category: "Context", describe: "Sticky RULES.md constraints carried in every request + a rulebook of on-demand rules served by rule_get. Nearest-first project walk over user-level.", load: rulesModule, tools: ["rule_get"] },
166
173
  // Attachments: paste/drop files become real attachments. No tools/commands —
@@ -170,6 +177,10 @@ export const MODULES: ModuleEntry[] = [
170
177
  // gh binary (registers nothing until installed). Read-only ops only, so
171
178
  // plan mode auto-allows it (plan-tools.ts READ_ONLY_TOOLS).
172
179
  { name: "gh", category: "Tools", describe: "GitHub tool over the gh CLI: repo/file/PR views, PR diff, five search flavors, Actions run_watch. Read-only; mutating flows stay on bash gh.", load: ghModule, config: ghConfig, tools: ["github"] },
180
+ // sg after gh: the same external-binary fail-open shape, for ast-grep.
181
+ { name: "sg", category: "Tools", describe: "Structural search & rewrite via the ast-grep CLI: ast_grep search, ast_edit dry-run-default rewrites. Registers nothing until ast-grep/sg is installed.", load: sgModule, tools: ["ast_grep", "ast_edit"] },
182
+ // notify: harmless desktop ping (bell fallback), herdr multi-pane ergonomics.
183
+ { name: "notify", category: "Tools", describe: "Desktop notification tool: ping the user when long work settles or input is needed (osascript / notify-send / bell).", load: notifyModule, tools: ["notify"] },
173
184
  // rtk is a PROMPT REWRITER (its before_agent_start appends the RTK note), so
174
185
  // it must load BEFORE steering — during a ds-anchor bootstrap, steering's
175
186
  // minimal prompt replaces everything, including this note (byte-identity);
@@ -190,6 +201,9 @@ export const MODULES: ModuleEntry[] = [
190
201
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
191
202
  // exist; defers to plan mode via the shared plan-bridge flag (order-free).
192
203
  { name: "permission", category: "Shell", describe: "Persistent allow/ask/deny permission rules per tool (wildcards, external-directory boundary, doom-loop guard) — opt-in via the `permission` settings section; inert until configured.", load: permissionModule },
204
+ // Background shell sessions (the bash-escape-hatch tool is BLOCKED in plan
205
+ // mode via plan-tools.ts — keep that in sync when renaming).
206
+ { name: "shells", category: "Shell", describe: "Background shell sessions: start/list/output/stdin/kill over persistent processes (dev servers, watchers). Killed on session shutdown; blocked in plan mode.", load: shellsModule, tools: ["shell"] },
193
207
  // ── Plugins ────────────────────────────────────────────────────────────
194
208
  // Config last: it owns /config and reads the contrib map. CORE: the panel is
195
209
  // the only in-app way back from a misconfiguration — it can never be the
@@ -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 });
@@ -306,8 +306,8 @@ describe("core module contract", () => {
306
306
  it("nextDisabled excludes core modules; withEnableRow adds no row for them", async () => {
307
307
  const { nextDisabled, withEnableRow } = await import("../../config/index.js");
308
308
  // working = enabled set; nextDisabled lists the NOT-enabled non-core modules.
309
- assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "rules", "attachments", "gh", "rtk", "steering", "permission"]);
310
- assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "gh", "rules", "steering", "zai", "rtk", "config", "attachments", "permission"])), [], "all-on → nothing disabled");
309
+ assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "jfind", "web", "rules", "attachments", "gh", "sg", "notify", "rtk", "steering", "permission", "shells"]);
310
+ assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "jfind", "web", "gh", "sg", "notify", "rules", "steering", "zai", "rtk", "config", "attachments", "permission", "shells"])), [], "all-on → nothing disabled");
311
311
  for (const core of ["composer", "advisor", "router", "classifier", "usage", "ux", "config"]) {
312
312
  assert.ok(!nextDisabled(new Set()).includes(core), `core (${core}) is never disableable`);
313
313
  }
@@ -34,7 +34,7 @@ function toolGroups(): PanelGroup[] {
34
34
  describe("render smoke — ported modules' /config sections", () => {
35
35
  it("renders Enable + per-tool rows inside the boxed frame with zero overflow", () => {
36
36
  const groups = toolGroups();
37
- assert.equal(groups.length, 16, "serena + fff + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules + a2a + gh + cron + steering·think (rtk has no tools)");
37
+ assert.equal(groups.length, 20, "serena + fff + jfind + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules + a2a + gh + sg + notify + cron + shells + steering·think (rtk has no tools)");
38
38
  const m = new ConfigPanelModel(groups, theme, "Settings");
39
39
  m.getHeight = () => 40;
40
40
  for (const w of [110, 100, 80, 60]) {
@@ -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
+ });
@@ -0,0 +1,124 @@
1
+ // jfind — semantic code find: describe what code does, get files + line
2
+ // ranges. Ported from OMP's jfind cascade; the judge routes through pi's
3
+ // modelRegistry.classify (System One via the router provider).
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { existsSync, statSync } from "node:fs";
7
+ import { resolve as resolvePath } from "node:path";
8
+ import { Type } from "typebox";
9
+ import { readDisabledTools } from "../../lib/tools.js";
10
+ import { formatBytes } from "./lib/format.js";
11
+ import { runCascade, FIND_TIMEOUT_MS, type CascadeResult } from "./lib/cascade.js";
12
+ import { createJudge } from "./lib/judge.js";
13
+ import { rankedHeat } from "./lib/tree.js";
14
+
15
+ /** Line ranges shown per hit in the model-facing text, strongest first. */
16
+ const RANGES_SHOWN = 3;
17
+
18
+ function formatBytesCeulen(bytes: number): string {
19
+ return formatBytes(bytes);
20
+ }
21
+
22
+ export default function jfindModule(pi: ExtensionAPI): void {
23
+ const disabled = readDisabledTools();
24
+ pi.registerTool({
25
+ name: "jfind",
26
+ label: "Semantic Find",
27
+ defaultActive: !disabled.has("jfind"),
28
+ description:
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
+ "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). " +
32
+ "The `path` scope accepts a directory OR a single file (a deny-listed/binary/secret/empty file is refused with a reason).",
33
+ promptSnippet: "Semantic find: locate code by describing what it does",
34
+ promptGuidelines: [
35
+ "Describe the behavior, not the keywords: jfind judges passages semantically.",
36
+ 'Put must-have identifiers in quotes ("spawn", "writeStdin") — quoted phrases become hard lexical keywords.',
37
+ "No hits doesn't mean the code doesn't exist — fall back to ffgrep/fffind for literal patterns.",
38
+ ],
39
+ parameters: Type.Object({
40
+ query: Type.String({ description: 'What the code does, e.g. "parse cron expressions into next-fire times".' }),
41
+ keywords: Type.Optional(Type.Array(Type.String(), { description: "Extra literal keywords folded into the lexical prior." })),
42
+ path: Type.Optional(Type.String({ description: "Search scope: a directory (default the session cwd) or a single file." })),
43
+ }),
44
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
45
+ const query = (params.query as string).trim();
46
+ if (query.length === 0) throw new Error("`query` must be a non-empty description");
47
+ const cwd = ctx?.cwd || process.cwd();
48
+ const scopeInput = typeof params.path === "string" ? params.path.trim() : "";
49
+ let root = resolvePath(cwd);
50
+ if (scopeInput.length > 0) {
51
+ root = resolvePath(cwd, scopeInput);
52
+ if (!existsSync(root)) throw new Error(`Path not found: ${scopeInput}`);
53
+ if (!statSync(root).isFile() && !statSync(root).isDirectory()) {
54
+ throw new Error(`Path is neither a file nor a directory: ${scopeInput}`);
55
+ }
56
+ }
57
+ let judge;
58
+ try {
59
+ judge = createJudge(ctx);
60
+ } catch (err) {
61
+ return {
62
+ content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
63
+ isError: true as const,
64
+ details: { query },
65
+ };
66
+ }
67
+ const timeout = AbortSignal.timeout(FIND_TIMEOUT_MS);
68
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
69
+ let result: CascadeResult;
70
+ try {
71
+ result = await runCascade({
72
+ root,
73
+ query,
74
+ extraKeywords: (params.keywords as string[] | undefined) ?? [],
75
+ judge,
76
+ signal: combined,
77
+ onProgress: (message) => onUpdate?.({ content: [{ type: "text", text: message }], details: undefined }),
78
+ });
79
+ } catch (err) {
80
+ if (timeout.aborted && !signal?.aborted) {
81
+ throw new Error(`jfind timed out after ${Math.round(FIND_TIMEOUT_MS / 1000)}s — narrow the query or scope (path param)`);
82
+ }
83
+ throw err;
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
+ }
93
+ const { stats, threshold, keywords } = result;
94
+ const scope = scopeInput.length > 0 ? ` in ${scopeInput}` : "";
95
+ const out: string[] = [];
96
+ if (result.hits.length === 0) {
97
+ out.push(`no hits for "${query}"${scope} (τ ${threshold.toFixed(2)})`);
98
+ } else {
99
+ out.push(`${result.hits.length} hit(s) for "${query}"${scope} (τ ${threshold.toFixed(2)}), strongest first`, "");
100
+ for (const hit of result.hits) {
101
+ const coverage = hit.truncated ? `${hit.linesSeen} lines judged, partial` : `${hit.linesSeen} lines judged`;
102
+ out.push(`${hit.rel} ${hit.contentScore.toFixed(2)} ${coverage}`);
103
+ for (const range of rankedHeat(hit.ranges, RANGES_SHOWN)) {
104
+ const span = range.start === range.end ? String(range.start) : `${range.start}-${range.end}`;
105
+ out.push(` ${hit.rel}:${span} ${range.p.toFixed(2)} ${range.snippet}`);
106
+ }
107
+ }
108
+ }
109
+ out.push(
110
+ "",
111
+ `listed ${stats.listed} · judged ${stats.judged} · read ${stats.filesRead} files (${formatBytesCeulen(stats.fileBytes)}) · ${stats.requests} requests · ${stats.inputTokens + stats.outputTokens} tokens · keywords: ${keywords.join(", ")}`,
112
+ );
113
+ if (stats.failures.length > 0) {
114
+ out.push(`${stats.errors} of ${stats.requests} requests failed:`, ...stats.failures.map((f) => ` ${f}`));
115
+ }
116
+ const allFailed = stats.requests > 0 && stats.errors === stats.requests;
117
+ return {
118
+ content: [{ type: "text", text: out.join("\n") }],
119
+ isError: allFailed,
120
+ details: { query, keywords, threshold, hits: result.hits.length, stats },
121
+ };
122
+ },
123
+ });
124
+ }