ceulen 0.15.2 → 0.16.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 (53) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -1
  3. package/extensions/lib/registry.ts +2 -1
  4. package/extensions/modules/classifier/index.ts +29 -12
  5. package/extensions/modules/classifier/lib/settings.ts +20 -3
  6. package/extensions/modules/classifier/test/classifier.test.ts +12 -4
  7. package/extensions/modules/config/defaultTools.ts +7 -3
  8. package/extensions/modules/config/test/defaultTools.test.ts +16 -0
  9. package/extensions/modules/gh/lib/ops.ts +22 -4
  10. package/extensions/modules/gh/test/gh.test.ts +64 -1
  11. package/extensions/modules/plan/index.ts +116 -4
  12. package/extensions/modules/plan/lib/settings.ts +5 -7
  13. package/extensions/modules/plan/test/module.test.ts +104 -1
  14. package/extensions/modules/plan/test/settings.test.ts +7 -0
  15. package/extensions/modules/repair/configPanel.ts +3 -1
  16. package/extensions/modules/repair/index.ts +21 -16
  17. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  18. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  19. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  20. package/extensions/modules/repair/test/readers.test.ts +11 -5
  21. package/extensions/modules/repair/test/settings.test.ts +7 -2
  22. package/extensions/modules/rtk/configPanel.ts +67 -0
  23. package/extensions/modules/rtk/index.ts +76 -9
  24. package/extensions/modules/rtk/lib/settings.ts +65 -0
  25. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  26. package/extensions/modules/rtk/test/index.test.js +120 -2
  27. package/extensions/modules/rules/index.ts +4 -1
  28. package/extensions/modules/rules/lib/rules.ts +6 -3
  29. package/extensions/modules/rules/test/lib.test.ts +24 -0
  30. package/extensions/modules/rules/test/module.test.ts +29 -0
  31. package/extensions/modules/shells/lib/sessions.ts +40 -12
  32. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  33. package/extensions/modules/steering/index.ts +12 -1
  34. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  35. package/extensions/modules/subagent/index.ts +19 -3
  36. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  37. package/extensions/modules/subagent/lib/runner.ts +88 -22
  38. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  39. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  40. package/extensions/modules/todo/index.ts +4 -0
  41. package/extensions/modules/todo/test/todo.test.ts +9 -0
  42. package/extensions/modules/web/index.ts +1 -1
  43. package/extensions/modules/web/lib/a11y.ts +30 -15
  44. package/extensions/modules/web/lib/cdp.ts +11 -2
  45. package/extensions/modules/web/lib/chrome.ts +12 -3
  46. package/extensions/modules/web/lib/content.ts +32 -9
  47. package/extensions/modules/web/lib/search.ts +111 -3
  48. package/extensions/modules/web/test/a11y.test.ts +100 -2
  49. package/extensions/modules/web/test/cdp.test.ts +48 -0
  50. package/extensions/modules/web/test/chrome.test.ts +32 -0
  51. package/extensions/modules/web/test/content.test.ts +92 -0
  52. package/extensions/modules/web/test/search.test.ts +75 -0
  53. package/package.json +1 -1
@@ -5,7 +5,8 @@
5
5
  // git version; on-disk effects use real temp dirs.
6
6
 
7
7
  import assert from "node:assert/strict";
8
- import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
8
+ import { chmod, mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
9
+ import { readdirSync } from "node:fs";
9
10
  import { tmpdir } from "node:os";
10
11
  import { join } from "node:path";
11
12
  import { after, describe, it } from "node:test";
@@ -125,6 +126,42 @@ describe("sweepStaleWorktrees", () => {
125
126
  assert.deepEqual(result, { removed: [], kept: 0 });
126
127
  assert.equal(exec.calls.length, 1);
127
128
  });
129
+
130
+ it("orphan marker (no matching dir) is reclaimed by the sweep", async () => {
131
+ const repo = await tempDir("wt-sweep-orphan-");
132
+ const base = join(repo, WORKTREE_DIR_NAME);
133
+ await mkdir(base, { recursive: true });
134
+ await writeFile(join(base, "orphan.owner.json"), JSON.stringify({ pid: process.pid, id: "orphan", createdAt: Date.now() }));
135
+ const exec = fakeExec([
136
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
137
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: "" },
138
+ ]);
139
+ const result = await sweepStaleWorktrees(repo, exec);
140
+ assert.deepEqual(result, { removed: [], kept: 0 });
141
+ await assert.rejects(stat(join(base, "orphan.owner.json")), "orphan marker must be dropped");
142
+ });
143
+
144
+ it("force: foreign live-pid sandbox removed, non-force keeps it, own pid stays protected", async () => {
145
+ const repo = await tempDir("wt-sweep-force-");
146
+ const base = join(repo, WORKTREE_DIR_NAME);
147
+ await mkdir(join(base, "foreign"), { recursive: true });
148
+ await mkdir(join(base, "mine"), { recursive: true });
149
+ await writeFile(join(base, "foreign.owner.json"), JSON.stringify({ pid: 1, id: "foreign", createdAt: Date.now() }));
150
+ await writeFile(join(base, "mine.owner.json"), JSON.stringify({ pid: process.pid, id: "mine", createdAt: Date.now() }));
151
+ const exec = fakeExec([
152
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
153
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: "" },
154
+ ]);
155
+ const plain = await sweepStaleWorktrees(repo, exec);
156
+ assert.equal(plain.kept, 2); // pid 1 (launchd/init) is alive — the false-KEEP
157
+ await stat(join(base, "foreign"));
158
+
159
+ const forced = await sweepStaleWorktrees(repo, exec, { force: true });
160
+ assert.deepEqual(forced.removed.map((r) => r.split("/").pop()), ["foreign"]);
161
+ assert.equal(forced.kept, 1);
162
+ await assert.rejects(stat(join(base, "foreign")));
163
+ await stat(join(base, "mine")); // this process's own live sandbox survives force
164
+ });
128
165
  });
129
166
 
130
167
  // ── Baseline capture: PURE READS on the parent ─────────────────────────────
@@ -227,4 +264,122 @@ describe("createWorktree", () => {
227
264
  assert.equal(result.ok, false);
228
265
  assert.match(result.error!, /not a git repo/);
229
266
  });
267
+
268
+ it("owner marker exists at the moment `worktree add` runs (git fallback path)", async () => {
269
+ const repo = await tempDir("wt-marker-add-");
270
+ await mkdir(join(repo, ".git"), { recursive: true });
271
+ const base = join(repo, WORKTREE_DIR_NAME);
272
+ let sawMarker: boolean | undefined;
273
+ const exec = fakeExec([
274
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
275
+ { match: (c) => c === "cp", code: 1, stderr: "cp failed" }, // force the git-worktree fallback
276
+ ]);
277
+ const wrapped: Exec = async (command, args, options) => {
278
+ if (command === "git" && args[0] === "worktree" && args[1] === "add") {
279
+ sawMarker = readdirSync(base).some((f) => f.endsWith(".owner.json"));
280
+ }
281
+ return exec(command, args, options);
282
+ };
283
+ const result = await createWorktree(repo, wrapped);
284
+ assert.equal(result.ok, true);
285
+ assert.equal(result.cow, false);
286
+ assert.equal(sawMarker, true, "marker must exist before the sandbox is registered");
287
+ });
288
+
289
+ it("marker-write failure → createWorktree fails; never ok without a marker", async () => {
290
+ if (typeof process.getuid === "function" && process.getuid() === 0) return; // root ignores dir perms
291
+ const repo = await tempDir("wt-marker-eacces-");
292
+ await mkdir(join(repo, ".git"), { recursive: true });
293
+ const base = join(repo, WORKTREE_DIR_NAME);
294
+ await mkdir(base, { recursive: true });
295
+ await writeFile(join(base, ".gitignore"), "*\n"); // the gitignore check passes; the MARKER write is what fails
296
+ await chmod(base, 0o500);
297
+ try {
298
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` }]);
299
+ const result = await createWorktree(repo, exec);
300
+ assert.equal(result.ok, false);
301
+ assert.match(result.error!, /marker/);
302
+ assert.ok(!exec.calls.some((c) => c.command === "git" && c.args[0] === "worktree"), "no sandbox registered");
303
+ } finally {
304
+ await chmod(base, 0o700);
305
+ }
306
+ });
307
+
308
+ it("a rejecting `worktree add` after the marker write → ok:false AND no orphan marker", async () => {
309
+ const repo = await tempDir("wt-add-throws-");
310
+ await mkdir(join(repo, ".git"), { recursive: true });
311
+ const base = join(repo, WORKTREE_DIR_NAME);
312
+ const exec = fakeExec([
313
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
314
+ { match: (c) => c === "cp", code: 1, stderr: "cp failed" }, // force the git-worktree fallback
315
+ ]);
316
+ const wrapped: Exec = async (command, args, options) => {
317
+ if (command === "git" && args[0] === "worktree" && args[1] === "add") throw new Error("worktree add exploded");
318
+ return exec(command, args, options);
319
+ };
320
+ const result = await createWorktree(repo, wrapped);
321
+ assert.equal(result.ok, false);
322
+ assert.match(result.error!, /exploded/);
323
+ const leftovers = (await readdir(base).catch(() => [] as string[])).filter((f) => f.endsWith(".owner.json"));
324
+ assert.deepEqual(leftovers, [], "no orphan marker may survive a failed creation");
325
+ });
326
+
327
+ it("CoW copies the live .git under the repo lock (no torn copy)", { skip: process.platform !== "darwin" }, async () => {
328
+ const repo = await tempDir("wt-cow-lock-");
329
+ await mkdir(join(repo, ".git"), { recursive: true });
330
+ await writeFile(join(repo, "file.txt"), "x");
331
+ const order: string[] = [];
332
+ let release!: () => void;
333
+ const gate = new Promise<void>((r) => { release = r; });
334
+ const holder = withRepoLock(repo, async () => { order.push("lock-start"); await gate; order.push("lock-end"); });
335
+ await new Promise((r) => setTimeout(r, 10));
336
+ assert.deepEqual(order, ["lock-start"], "holder acquired the lock first");
337
+ const exec = fakeExec([
338
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
339
+ { match: (c) => c === "cp" },
340
+ ]);
341
+ const wrapped: Exec = async (command, args, options) => {
342
+ if (command === "cp" && args[1]?.endsWith("/.git")) order.push("cow-git");
343
+ return exec(command, args, options);
344
+ };
345
+ const pending = createWorktree(repo, wrapped);
346
+ await new Promise((r) => setTimeout(r, 20));
347
+ assert.ok(!order.includes("cow-git"), "cp .git waits for the lock");
348
+ release();
349
+ await holder;
350
+ const result = await pending;
351
+ assert.ok(result.ok, result.error);
352
+ assert.equal(result.cow, undefined, "CoW path ran");
353
+ assert.deepEqual(order, ["lock-start", "lock-end", "cow-git"]);
354
+ });
355
+
356
+ it("base .gitignore as a DIRECTORY → createWorktree fails loudly", async () => {
357
+ const repo = await tempDir("wt-gitignore-dir-");
358
+ await mkdir(join(repo, ".git"), { recursive: true });
359
+ await mkdir(join(repo, WORKTREE_DIR_NAME, ".gitignore"), { recursive: true });
360
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` }]);
361
+ const result = await createWorktree(repo, exec);
362
+ assert.equal(result.ok, false);
363
+ assert.match(result.error!, /\.gitignore/);
364
+ assert.ok(!exec.calls.some((c) => c.command === "cp" || c.args[0] === "worktree"), "no sandbox materialized");
365
+ });
366
+ });
367
+
368
+ // ── Sweep: registry stays consistent when `worktree remove` fails ───────────
369
+
370
+ describe("sweepStaleWorktrees — prune fallback", () => {
371
+ it("a registered dir whose `worktree remove` exits 1 gets `worktree prune`", async () => {
372
+ const repo = await tempDir("wt-sweep-prune-");
373
+ const base = join(repo, WORKTREE_DIR_NAME);
374
+ await mkdir(join(base, "stuck"), { recursive: true });
375
+ const exec = fakeExec([
376
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
377
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: `worktree ${join(base, "stuck")}\n` },
378
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "remove", code: 1, stderr: "remove failed" },
379
+ ]);
380
+ const result = await sweepStaleWorktrees(repo, exec);
381
+ assert.deepEqual(result.removed.map((r) => r.split("/").pop()), ["stuck"]);
382
+ assert.ok(exec.calls.some((c) => c.args[0] === "worktree" && c.args[1] === "prune"), "prune issued after failed remove");
383
+ await assert.rejects(stat(join(base, "stuck"))); // the dir is still gone
384
+ });
230
385
  });
@@ -233,6 +233,9 @@ export function applyTodo(current: readonly TodoPhase[], params: TodoParams): Ap
233
233
  for (const [i, p] of list.entries()) {
234
234
  const title = p.title.trim();
235
235
  if (!title) return fail("Every phase needs a title");
236
+ // Blocked is DERIVED from unmet blockedBy edges — a stored "blocked"
237
+ // status never clears (unblock touches blockedBy only), so refuse it.
238
+ if (p.status === "blocked") return fail(`"${title}": status "blocked" is derived from unmet blockedBy edges and is never stored — pass blockedBy: [ids] (or omit status)`);
236
239
  if (seenTitle.has(title)) return fail(`Duplicate phase title "${title}"`);
237
240
  seenTitle.add(title);
238
241
  const id = p.id?.trim() || autoId(i, taken);
@@ -255,6 +258,7 @@ export function applyTodo(current: readonly TodoPhase[], params: TodoParams): Ap
255
258
  const p = list[0];
256
259
  const title = p.title.trim();
257
260
  if (!title) return fail("Every phase needs a title");
261
+ if (p.status === "blocked") return fail(`"${title}": status "blocked" is derived from unmet blockedBy edges and is never stored — pass blockedBy: [ids] (or omit status)`);
258
262
  if (phases.some((x) => x.title === title)) return fail(`Phase "${title}" already exists`);
259
263
  const id = p.id?.trim() || autoId(phases.length, new Set(phases.map((x) => x.id)));
260
264
  if (byId.has(id)) return fail(`Phase id "${id}" already exists`);
@@ -110,6 +110,15 @@ describe("todo state machine", () => {
110
110
  assert.deepEqual(partial[1].blockedBy, ["p1"], "unblock drops only the named edge");
111
111
  });
112
112
 
113
+ it("init/append reject a stored status:\"blocked\" — blocked is derived from blockedBy", () => {
114
+ assert.match(fail([], { action: "init", phases: [{ title: "A", status: "blocked" }] })[0], /blockedBy/);
115
+ const seeded2 = run([], { action: "init", phases: [{ title: "A" }] });
116
+ assert.match(fail(seeded2, { action: "append", phases: [{ title: "B", status: "blocked" }] })[0], /blockedBy/);
117
+ // Normal flows unchanged: blocking goes through blockedBy edges.
118
+ const blocked = run(seeded(), { action: "block", id: "p1", blockedBy: ["p3"] });
119
+ assert.deepEqual(blocked[0].blockedBy, ["p3"]);
120
+ });
121
+
113
122
  it("append adds one phase with a fresh id and rejects duplicates", () => {
114
123
  const appended = run(seeded(), { action: "append", phases: [{ title: "Ship it" }] });
115
124
  assert.deepEqual(appended.map((p) => p.id), ["p1", "p2", "p3", "p4"]);
@@ -210,7 +210,7 @@ export default function piWebExtension(pi: ExtensionAPI) {
210
210
  _ctx: ctx,
211
211
  });
212
212
  const attempts = diagnostics.attempts.map((a) => `${a.backend}: ${a.status}${a.message ? ` (${a.message})` : ""}`).join("\n");
213
- const text = `${formatUnifiedSearchResults(diagnostics.results)}\n\n--- Search diagnostics ---\nSelected backend: ${diagnostics.selectedBackend}\n${attempts}`;
213
+ const text = `${formatUnifiedSearchResults(diagnostics.results)}\n\n--- Search diagnostics ---\nSelected backend: ${diagnostics.selectedBackend}\nRouter: ${diagnostics.router}\n${attempts}`;
214
214
  return { content: [{ type: "text" as const, text: truncateText(text) }], details: diagnostics };
215
215
  },
216
216
  });
@@ -15,7 +15,7 @@ import { readFileSync } from "node:fs";
15
15
  import path from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
 
18
- import { launchCdp, unwrapEvaluate, waitForLoad, type WsFactory } from "./cdp";
18
+ import { launchCdp, raceBounded, unwrapEvaluate, waitForLoad, type WsFactory } from "./cdp";
19
19
 
20
20
  // ── OMP shapes (browser/a11y/audit.ts) ─────────────────────────────────────
21
21
 
@@ -198,9 +198,11 @@ function runnerExpression(options: BrowserA11yOptions): string {
198
198
  const r = await window.axe.run(context, opts);
199
199
  return JSON.stringify({ __axeOk: r });
200
200
  } catch (err) {
201
- // Error inside the page: the CDP connection layer resolves responses to
202
- // msg.result only, so a top-level exceptionDetails never reaches
203
- // unwrapEvaluate — carry the failure through the value instead.
201
+ // Belt and braces: unwrapEvaluate already surfaces exceptionDetails loudly
202
+ // (the connection layer preserves them, including Runtime.evaluate's
203
+ // nested shape), so an in-page throw would reject the evaluate promise —
204
+ // the in-page try/catch just carries a friendlier message through the
205
+ // {__axeError} value instead.
204
206
  return JSON.stringify({ __axeError: err instanceof Error ? err.message : String(err) });
205
207
  }
206
208
  })()`;
@@ -216,26 +218,39 @@ export async function runA11yAudit(opts: RunA11yOpts): Promise<BrowserA11yResult
216
218
  const browser = await launchCdp({ wsFactory: opts.wsFactory });
217
219
  const onAbort = () => browser.cleanup();
218
220
  opts.signal?.addEventListener("abort", onAbort, { once: true });
221
+ // timeoutError matcher for the tests (and readable tool errors).
222
+ const auditTimeoutError = (ms: number) =>
223
+ `audit timed out after ${Math.round(ms / 1000)}s — page/renderer likely wedged`;
219
224
  let sessionId: string | undefined;
225
+ const bounded = <T>(p: Promise<T>): Promise<T> =>
226
+ raceBounded(p, timeoutMs, auditTimeoutError(timeoutMs));
220
227
  try {
221
228
  const connection = browser.connection;
222
- const target = await connection.send("Target.createTarget", { url: "about:blank" });
229
+ // The whole post-launch CDP phase is bounded: a wedged renderer (hung
230
+ // navigate/evaluate) must reject at the documented budget instead of
231
+ // parking web_a11y forever. finally below tears Chrome down either way.
232
+ const target = await bounded(connection.send("Target.createTarget", { url: "about:blank" }));
223
233
  const targetId = target.targetId as string;
224
- sessionId = ((await connection.send("Target.attachToTarget", { targetId, flatten: true })) as { sessionId: string })
225
- .sessionId;
234
+ sessionId = ((await bounded(
235
+ connection.send("Target.attachToTarget", { targetId, flatten: true }),
236
+ )) as { sessionId: string }).sessionId;
226
237
  const send = (method: string, params?: Record<string, unknown>) => connection.send(method, params, sessionId);
227
- await send("Page.enable");
238
+ await bounded(send("Page.enable"));
228
239
  const loaded = waitForLoad(connection, sessionId);
229
- await send("Page.navigate", { url: opts.url });
230
- await loaded;
240
+ await bounded(send("Page.navigate", { url: opts.url }));
241
+ await bounded(loaded);
231
242
  const evaluate = async (expression: string, awaitPromise = false) =>
232
- unwrapEvaluate(await send("Runtime.evaluate", { expression, awaitPromise, returnByValue: true }));
233
- // Bootstrap: the UMD build defines window.axe in the page world.
234
- evaluate(axeSource());
243
+ unwrapEvaluate(await bounded(send("Runtime.evaluate", { expression, awaitPromise, returnByValue: true })));
244
+ // Bootstrap: the UMD build defines window.axe in the page world. Awaited —
245
+ // CDP serializes commands so ordering holds, and a failed bootstrap must
246
+ // fail the audit loudly rather than escape as an unhandled rejection
247
+ // (which kills pi; see cdp.ts incident 2026-09-20). The runner's
248
+ // window.axe check remains as backup for a silently swallowed failure.
249
+ await evaluate(axeSource());
235
250
  // Runner: axe.run is async and huge — awaitPromise + returnByValue, and
236
251
  // stringified (JSON survives returnByValue losslessly). In-page failures
237
- // ride back as {__axeError} because the connection layer drops top-level
238
- // exceptionDetails (see runnerExpression).
252
+ // ride back as {__axeError}; CDP-level exceptions surface via
253
+ // unwrapEvaluate (exceptionDetails preserved — see runnerExpression).
239
254
  const raw = String(await evaluate(runnerExpression(opts), true));
240
255
  let parsed: { __axeOk?: unknown; __axeError?: string };
241
256
  try {
@@ -39,6 +39,8 @@ export interface CdpFrame {
39
39
  params?: Record<string, unknown>;
40
40
  result?: Record<string, unknown>;
41
41
  error?: { message: string; data?: string };
42
+ /** Sibling-of-result protocol error report (e.g. Runtime domains): kept so unwrapEvaluate can fail loudly. */
43
+ exceptionDetails?: { text?: string; exception?: { description?: string; value?: unknown } };
42
44
  sessionId?: string;
43
45
  }
44
46
 
@@ -108,6 +110,13 @@ export class CdpConnection {
108
110
  this.pending.delete(msg.id);
109
111
  if (msg.error) {
110
112
  p.reject(new Error(`${msg.error.message}${msg.error.data ? `: ${msg.error.data}` : ""}`));
113
+ } else if (msg.exceptionDetails) {
114
+ // Shape-compatible: keep the result payload and surface the SIBLING
115
+ // exceptionDetails so unwrapEvaluate can fail loudly. (The nested
116
+ // Runtime.evaluate shape — exceptionDetails inside msg.result — was
117
+ // already preserved by the plain branch; this covers domains that
118
+ // report it beside result.)
119
+ p.resolve({ ...(msg.result ?? {}), exceptionDetails: msg.exceptionDetails });
111
120
  } else {
112
121
  p.resolve(msg.result ?? {});
113
122
  }
@@ -347,9 +356,9 @@ function stepLabel(step: InteractStep): string {
347
356
  * Bound any CDP await: a wedged renderer (hung evaluate, dialog race) must
348
357
  * fail loudly instead of hanging the call. Used for steps AND the post-loop
349
358
  * probe/auto-screenshot — without it a step timeout would still hang forever
350
- * on the unbounded probe that follows.
359
+ * on the unbounded probe that follows. Also bounds web_a11y's whole audit.
351
360
  */
352
- function raceBounded<T>(p: Promise<T>, ms: number, timeoutError: string): Promise<T> {
361
+ export function raceBounded<T>(p: Promise<T>, ms: number, timeoutError: string): Promise<T> {
353
362
  let timer: ReturnType<typeof setTimeout> | undefined;
354
363
  const timeout = new Promise<T>((_, reject) => {
355
364
  timer = setTimeout(() => reject(new Error(timeoutError)), ms);
@@ -94,8 +94,9 @@ export function isLocalUrl(raw: string): boolean {
94
94
  return isLocalUrl(`http://${(bits >>> 24) & 0xff}.${(bits >>> 16) & 0xff}.${(bits >>> 8) & 0xff}.${bits & 0xff}/`);
95
95
  }
96
96
  }
97
- // IPv6 ULA fc00::/7 and link-local fe80::/10 are private too.
98
- if (/^f[cd]/.test(host) || /^fe[89ab]/.test(host)) return true;
97
+ // IPv6 ULA fc00::/7, link-local fe80::/10, and the decommissioned
98
+ // site-local fec0::/10 are private too.
99
+ if (/^f[cd]/.test(host) || /^fe[89ab]/.test(host) || /^fe[c-f]/.test(host)) return true;
99
100
  return false;
100
101
  }
101
102
  const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
@@ -106,6 +107,12 @@ export function isLocalUrl(raw: string): boolean {
106
107
  if (a === 172 && b >= 16 && b <= 31) return true; // 172.16/12
107
108
  if (a === 192 && b === 168) return true;
108
109
  if (a === 169 && b === 254) return true; // link-local
110
+ // Reserved/special-use (RFC 2544 benchmarks, RFC 5737-adjacent docs, etc.):
111
+ // 100.64/10 (CGNAT), 198.18/15 (benchmarking), 192.0.0/24 (IETF protocol
112
+ // assignments). Unroutable from the public internet — treat as local.
113
+ if (a === 100 && b >= 64 && b <= 127) return true; // 100.64/10
114
+ if (a === 198 && (b === 18 || b === 19)) return true; // 198.18/15
115
+ if (a === 192 && b === 0 && Number(m[3]) === 0) return true; // 192.0.0/24
109
116
  }
110
117
  return false;
111
118
  }
@@ -206,7 +213,9 @@ function runChrome(
206
213
  }, timeoutMs);
207
214
  signal?.addEventListener("abort", onAbort, { once: true });
208
215
  child.stderr?.on("data", (d: Buffer) => {
209
- stderr += d.toString();
216
+ // Keep only the tail — Chrome is chatty (GCM/Freedom/DevTools noise); an
217
+ // unbounded accumulate over a 30s capture window can OOM the host.
218
+ stderr = (stderr + d.toString()).slice(-1024);
210
219
  });
211
220
  child.on("error", (err) => finish(err));
212
221
  child.on("close", (code) => {
@@ -2,6 +2,7 @@
2
2
  // Readable content extraction using JSDOM + Readability + Turndown.
3
3
 
4
4
  import { createRequire } from "node:module";
5
+ import { isLocalUrl } from "./chrome";
5
6
  import { signalWithTimeout } from "./retry";
6
7
 
7
8
  const require = createRequire(import.meta.url);
@@ -52,15 +53,37 @@ export async function fetchReadableContent(
52
53
  timeoutMs = 15000,
53
54
  signal?: AbortSignal,
54
55
  ): Promise<{ title: string; markdown: string }> {
55
- const response = await fetch(url, {
56
- headers: {
57
- "User-Agent":
58
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120 Safari/537.36",
59
- Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
60
- "Accept-Language": "en-US,en;q=0.9",
61
- },
62
- signal: signalWithTimeout(timeoutMs, signal),
63
- });
56
+ // SSRF guard: model-supplied URLs must never reach loopback/metadata
57
+ // endpoints, and fetch follows redirects by default — follow manually and
58
+ // re-validate each hop (imageapi.ts downloadImage pattern).
59
+ let current = url;
60
+ for (let hop = 0; ; hop++) {
61
+ if (hop > 3) throw new Error("too many content redirects");
62
+ if (isLocalUrl(current)) throw new Error(`content host is private/loopback (SSRF-guarded): ${current}`);
63
+ const response = await fetch(current, {
64
+ headers: {
65
+ "User-Agent":
66
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120 Safari/537.36",
67
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
68
+ "Accept-Language": "en-US,en;q=0.9",
69
+ },
70
+ redirect: "manual",
71
+ signal: signalWithTimeout(timeoutMs, signal),
72
+ });
73
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
74
+ const loc = response.headers.get("location");
75
+ if (!loc) throw new Error(`content redirect ${response.status} without a location header`);
76
+ current = new URL(loc, current).toString();
77
+ continue;
78
+ }
79
+ return await readExtractResponse(response, current);
80
+ }
81
+ }
82
+
83
+ async function readExtractResponse(
84
+ response: Response,
85
+ url: string,
86
+ ): Promise<{ title: string; markdown: string }> {
64
87
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
65
88
  // Raw text/JSON payloads (raw.githubusercontent.com, JSON APIs) — Readability
66
89
  // shreds them to nothing. Pass through verbatim. text/html and text/xml keep
@@ -12,6 +12,7 @@ import { firecrawlRequest, type FirecrawlResult } from "./firecrawl";
12
12
  import { loadFirecrawlConfig, loadSearxngConfig, type FirecrawlConfig } from "./config";
13
13
  import { fetchReadableContent } from "./content";
14
14
  import { sanitizeSnippet, sanitizeError } from "./format";
15
+ import { askJev, getLastTask } from "../../classifier/index.js";
15
16
 
16
17
  export type SearchBackend = "searxng" | "brave" | "firecrawl";
17
18
  export type SearchAttemptStatus = "skipped" | "success" | "empty" | "error";
@@ -52,6 +53,9 @@ export interface SearchDiagnostics {
52
53
  attempts: SearchAttempt[];
53
54
  selectedBackend: SearchBackend | "";
54
55
  backendOrder: SearchBackend[];
56
+ /** How the backend order was picked: an explicit backend/engines param, the
57
+ * isPrecisionQuery heuristic, or the classifier's verdict. */
58
+ router: "explicit" | "heuristic" | "classifier:jev";
55
59
  }
56
60
 
57
61
  interface BackendConfig {
@@ -197,6 +201,110 @@ export function selectSearchBackendOrder(params: SearchParams): SearchBackend[]
197
201
  return ["searxng", "brave", "firecrawl"];
198
202
  }
199
203
 
204
+ // ── Classifier-routed order (auto mode only) ────────────────────────────────
205
+
206
+ const CLASSIFIER_ORDER_BUDGET_MS = 2_500; // ponytail: value of classifier's CLASSIFIER_HOOK_BUDGET_MS — module-private state is not imported
207
+ const CLASSIFIER_MIN_CONFIDENCE = 0.6;
208
+ const PRECISION_ORDER: SearchBackend[] = ["brave", "searxng", "firecrawl"];
209
+ const BROAD_ORDER: SearchBackend[] = ["searxng", "brave", "firecrawl"];
210
+
211
+ /** LRU over query fingerprints — repeated queries must not re-pay Jev.
212
+ * ponytail: insertion-order map, cap 200. Value: the resolved order. */
213
+ const orderCache = new Map<string, { order: SearchBackend[]; router: "classifier:jev" | "heuristic" }>();
214
+
215
+ function fingerprint(query: string): string {
216
+ return query.toLowerCase().replace(/\d+/g, "#").replace(/\s+/g, " ").trim();
217
+ }
218
+
219
+ /** Read a choice answer defensively: probabilities[choice], else confidence.
220
+ * Anything missing/out-of-range → NaN → the caller falls back. */
221
+ function choiceConfidence(answer: unknown): number {
222
+ const a = answer && typeof answer === "object" ? (answer as Record<string, unknown>) : {};
223
+ const p = a.probabilities && typeof a.probabilities === "object" ? (a.probabilities as Record<string, unknown>)[String(a.choice)] : undefined;
224
+ const v = typeof p === "number" ? p : a.confidence;
225
+ return typeof v === "number" && v >= 0 && v <= 1 ? v : NaN;
226
+ }
227
+
228
+ function readNoul(answer: unknown): number {
229
+ const a = answer && typeof answer === "object" ? (answer as Record<string, unknown>) : {};
230
+ const v = typeof a.probability === "number" ? a.probability : a.noul;
231
+ return typeof v === "number" && v >= 0 && v <= 1 ? v : NaN;
232
+ }
233
+
234
+ /** One Jev round-trip picks brave-first vs searxng-first; a wrong pick costs
235
+ * one probe + fallback, never a wrong answer. Low confidence, timeout, or
236
+ * any failure → the isPrecisionQuery heuristic, unchanged. */
237
+ async function classifyOrder(params: SearchParams): Promise<{ order: SearchBackend[]; router: "classifier:jev" | "heuristic" }> {
238
+ const fp = fingerprint(params.query);
239
+ const cached = orderCache.get(fp);
240
+ if (cached) {
241
+ orderCache.delete(fp);
242
+ orderCache.set(fp, cached);
243
+ return cached;
244
+ }
245
+ const ctx = params._ctx as Parameters<typeof askJev>[0] | undefined;
246
+ let resolved: { order: SearchBackend[]; router: "classifier:jev" | "heuristic" } | undefined;
247
+ try {
248
+ if (ctx && typeof ctx.modelRegistry?.classify === "function") {
249
+ const task = getLastTask();
250
+ const state: Record<string, unknown> = { query: params.query };
251
+ const questions: Record<string, unknown> = {
252
+ backend_preference: {
253
+ type: "choice",
254
+ instructions: "Which search backend should try this web query first?",
255
+ criteria: {
256
+ brave_first: "Precision lookup — site/docs/API/error-string search, freshness windows, or inline page content needed.",
257
+ searxng_first: "Broad multi-engine discovery, ambiguous topic exploration, or general browsing.",
258
+ },
259
+ },
260
+ ...(params.include_content === undefined
261
+ ? { include_content: { type: "bool", instructions: "Would answering this query benefit from fetching the full page content of results (vs snippets alone)?" } }
262
+ : {}),
263
+ ...(task ? { serves_task: { type: "bool", instructions: "Does this query plausibly serve the user's current task?", criteria: { yes: "A reasonable search toward the task.", no: "Unrelated to the task." } } } : {}),
264
+ };
265
+ const budget = AbortSignal.timeout(CLASSIFIER_ORDER_BUDGET_MS);
266
+ const answers = (await Promise.race([
267
+ askJev(ctx, state, questions, budget),
268
+ new Promise<never>((_, reject) => budget.addEventListener("abort", () => reject(new Error("classifier budget exceeded")), { once: true })),
269
+ ])) as Record<string, unknown>;
270
+ const pref = answers.backend_preference as Record<string, unknown> | undefined;
271
+ const choice = String(pref?.choice ?? "");
272
+ const confidence = choiceConfidence(pref);
273
+ const contentNeeded = params.include_content === undefined && Number.isFinite(readNoul(answers.include_content))
274
+ ? readNoul(answers.include_content) >= 0.5
275
+ : false;
276
+ const servesOk = !answers.serves_task || readNoul(answers.serves_task) >= 0.5;
277
+ if (servesOk && Number.isFinite(confidence) && confidence >= CLASSIFIER_MIN_CONFIDENCE && (choice === "brave_first" || choice === "searxng_first")) {
278
+ // include_content influences ORDER only — never turned into a fetch
279
+ // (a classifier guess must not trigger N page downloads).
280
+ const order = choice === "brave_first" || contentNeeded ? PRECISION_ORDER : BROAD_ORDER;
281
+ resolved = { order, router: "classifier:jev" };
282
+ }
283
+ }
284
+ } catch {
285
+ resolved = undefined; // fail open to the heuristic
286
+ }
287
+ if (!resolved) resolved = { order: selectSearchBackendOrder(params), router: "heuristic" };
288
+ orderCache.set(fp, resolved);
289
+ if (orderCache.size > 200) orderCache.delete(orderCache.keys().next().value!);
290
+ return resolved;
291
+ }
292
+
293
+ /** The order searchWithDiagnostics executes: explicit params keep the legacy
294
+ * sync path (router: explicit); auto mode asks the classifier when ≥2
295
+ * backends are configured and falls back to the heuristic otherwise. */
296
+ async function resolveBackendOrder(params: SearchParams, backends: BackendConfig): Promise<{ order: SearchBackend[]; router: SearchDiagnostics["router"] }> {
297
+ if ((params.backend && params.backend !== "auto") || params.engines) {
298
+ return { order: selectSearchBackendOrder(params), router: "explicit" };
299
+ }
300
+ const configured = (["searxng", "brave", "firecrawl"] as SearchBackend[]).filter((b) => isConfigured(b, backends)).length;
301
+ if (configured < 2) {
302
+ return { order: selectSearchBackendOrder(params), router: "heuristic" };
303
+ }
304
+ const classified = await classifyOrder(params);
305
+ return classified;
306
+ }
307
+
200
308
  function isConfigured(backend: SearchBackend, backends: BackendConfig): boolean {
201
309
  if (backend === "searxng") return backends.searxng.configured;
202
310
  if (backend === "brave") return backends.brave.configured;
@@ -211,7 +319,7 @@ async function runBackend(backend: SearchBackend, params: SearchParams, backends
211
319
 
212
320
  export async function searchWithDiagnostics(params: SearchParams): Promise<SearchDiagnostics> {
213
321
  const backends = probeBackends(params._ctx);
214
- const backendOrder = selectSearchBackendOrder(params);
322
+ const { order: backendOrder, router } = await resolveBackendOrder(params, backends);
215
323
  const attempts: SearchAttempt[] = [];
216
324
 
217
325
  for (const backend of backendOrder) {
@@ -223,7 +331,7 @@ export async function searchWithDiagnostics(params: SearchParams): Promise<Searc
223
331
  const results = await runBackend(backend, params, backends);
224
332
  if (results.length > 0) {
225
333
  attempts.push({ backend, status: "success", message: `Selected ${backend}`, resultCount: results.length });
226
- return { results, attempts, selectedBackend: backend, backendOrder };
334
+ return { results, attempts, selectedBackend: backend, backendOrder, router };
227
335
  }
228
336
  attempts.push({ backend, status: "empty", message: `${backend} returned 0 results`, resultCount: 0 });
229
337
  } catch (e) {
@@ -232,6 +340,6 @@ export async function searchWithDiagnostics(params: SearchParams): Promise<Searc
232
340
  }
233
341
  }
234
342
 
235
- return { results: [], attempts, selectedBackend: "" as const, backendOrder };
343
+ return { results: [], attempts, selectedBackend: "" as const, backendOrder, router };
236
344
  }
237
345