ceulen 0.15.2 → 0.17.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 (57) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/extensions/lib/registry.test.ts +5 -2
  4. package/extensions/lib/registry.ts +9 -3
  5. package/extensions/modules/classifier/index.ts +29 -12
  6. package/extensions/modules/classifier/lib/settings.ts +20 -3
  7. package/extensions/modules/classifier/test/classifier.test.ts +12 -4
  8. package/extensions/modules/config/defaultTools.ts +7 -3
  9. package/extensions/modules/config/test/defaultTools.test.ts +16 -0
  10. package/extensions/modules/gh/lib/ops.ts +22 -4
  11. package/extensions/modules/gh/test/gh.test.ts +64 -1
  12. package/extensions/modules/munin/index.ts +93 -6
  13. package/extensions/modules/munin/test/extension.test.ts +124 -0
  14. package/extensions/modules/plan/index.ts +116 -4
  15. package/extensions/modules/plan/lib/settings.ts +5 -7
  16. package/extensions/modules/plan/test/module.test.ts +104 -1
  17. package/extensions/modules/plan/test/settings.test.ts +7 -0
  18. package/extensions/modules/repair/configPanel.ts +3 -1
  19. package/extensions/modules/repair/index.ts +21 -16
  20. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  21. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  22. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  23. package/extensions/modules/repair/test/readers.test.ts +11 -5
  24. package/extensions/modules/repair/test/settings.test.ts +7 -2
  25. package/extensions/modules/rtk/configPanel.ts +67 -0
  26. package/extensions/modules/rtk/index.ts +76 -9
  27. package/extensions/modules/rtk/lib/settings.ts +65 -0
  28. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  29. package/extensions/modules/rtk/test/index.test.js +120 -2
  30. package/extensions/modules/rules/index.ts +4 -1
  31. package/extensions/modules/rules/lib/rules.ts +6 -3
  32. package/extensions/modules/rules/test/lib.test.ts +24 -0
  33. package/extensions/modules/rules/test/module.test.ts +29 -0
  34. package/extensions/modules/shells/lib/sessions.ts +40 -12
  35. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  36. package/extensions/modules/steering/index.ts +12 -1
  37. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  38. package/extensions/modules/subagent/index.ts +19 -3
  39. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  40. package/extensions/modules/subagent/lib/runner.ts +88 -22
  41. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  42. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  43. package/extensions/modules/todo/index.ts +4 -0
  44. package/extensions/modules/todo/test/todo.test.ts +9 -0
  45. package/extensions/modules/web/index.ts +1 -1
  46. package/extensions/modules/web/lib/a11y.ts +30 -15
  47. package/extensions/modules/web/lib/cdp.ts +11 -2
  48. package/extensions/modules/web/lib/chrome.ts +12 -3
  49. package/extensions/modules/web/lib/content.ts +32 -9
  50. package/extensions/modules/web/lib/search.ts +111 -3
  51. package/extensions/modules/web/test/a11y.test.ts +100 -2
  52. package/extensions/modules/web/test/cdp.test.ts +48 -0
  53. package/extensions/modules/web/test/chrome.test.ts +32 -0
  54. package/extensions/modules/web/test/content.test.ts +92 -0
  55. package/extensions/modules/web/test/search.test.ts +75 -0
  56. package/package.json +1 -1
  57. package/skills/munin/SKILL.md +1 -1
@@ -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
 
@@ -3,10 +3,10 @@
3
3
  // the fake websocket server (cdp.test.ts harness pattern).
4
4
 
5
5
  import assert from "node:assert/strict";
6
- import { mkdtempSync, rmSync, writeFileSync, chmodSync } from "node:fs";
6
+ import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import path from "node:path";
9
- import { after, before, describe, it } from "node:test";
9
+ import { after, before, afterEach, beforeEach, describe, it } from "node:test";
10
10
 
11
11
  import {
12
12
  axeSource,
@@ -185,6 +185,104 @@ describe("runner expression (via fake CDP server)", { skip: process.platform ===
185
185
  });
186
186
  });
187
187
 
188
+ // ── F1/F2 regressions: bounded audit + awaited bootstrap (fake CDP server) ──
189
+
190
+ // launchCdp always spawns a real browser process (the wsFactory only fakes the
191
+ // WS protocol), so these need the stub-Chrome contract from cdp.test.ts.
192
+ describe("runA11yAudit liveness (fake CDP server)", { skip: process.platform === "linux" && !process.env.CHROME_PATH && "CI runners have no Chrome — launchCdp always spawns a real browser (the wsFactory only fakes the WS protocol)" }, () => {
193
+ let dir: string;
194
+ let originalChromePath: string | undefined;
195
+
196
+ beforeEach(() => {
197
+ dir = mkdtempSync(path.join(tmpdir(), "pi-web-a11y-live-"));
198
+ originalChromePath = process.env.CHROME_PATH; // Stub Chrome: publish DevToolsActivePort, record the profile dir, hang.
199
+ const stub = path.join(dir, "stub-chrome.sh");
200
+ const probe = path.join(dir, "profile-path");
201
+ process.env.A11Y_TEST_PROFILE_FILE = probe;
202
+ writeFileSync(
203
+ stub,
204
+ `#!/bin/sh\nfor a in "$@"; do case "$a" in --user-data-dir=*) prof="\${a#--user-data-dir=}" ;; esac; done\n` +
205
+ `mkdir -p "$prof"\nprintf '9222\\n/devtools/browser/fake' > "$prof/DevToolsActivePort"\n` +
206
+ `printf '%s' "$prof" > "$A11Y_TEST_PROFILE_FILE"\nsleep 30\n`,
207
+ );
208
+ chmodSync(stub, 0o755);
209
+ process.env.CHROME_PATH = stub;
210
+ });
211
+
212
+ afterEach(() => {
213
+ delete process.env.A11Y_TEST_PROFILE_FILE;
214
+ if (originalChromePath === undefined) delete process.env.CHROME_PATH;
215
+ else process.env.CHROME_PATH = originalChromePath;
216
+ rmSync(dir, { recursive: true, force: true });
217
+ });
218
+
219
+ const baseServer = (ws: FakeWs) => {
220
+ ws.onSend = (frame) => {
221
+ const { method, id, params } = frame;
222
+ if (method === "Target.createTarget") ws.reply(id, { targetId: "t1" });
223
+ else if (method === "Target.attachToTarget") ws.reply(id, { sessionId: "s1" });
224
+ else if (method === "Page.navigate") {
225
+ ws.reply(id, { frameId: "f1" });
226
+ ws.event("Page.loadEventFired", {}, "s1");
227
+ } else if (method === "Runtime.evaluate") {
228
+ if (String((params as { expression?: string }).expression ?? "").startsWith("/*! axe")) {
229
+ ws.reply(id, { result: { type: "object" } });
230
+ } else {
231
+ ws.reply(id, { result: { type: "string", value: JSON.stringify({ __axeOk: FIXTURE_RESULTS }) } });
232
+ }
233
+ } else ws.reply(id, {});
234
+ };
235
+ };
236
+
237
+ it("F1: a wedged runner evaluate rejects at the audit budget instead of hanging (cleanup runs)", { timeout: 10_000 }, async () => {
238
+ const ws = new FakeWs();
239
+ baseServer(ws);
240
+ const realOnSend = ws.onSend!;
241
+ ws.onSend = (frame) => {
242
+ // The runner evaluate is NEVER answered (wedged renderer).
243
+ if (frame.method === "Runtime.evaluate" && !String(frame.params?.expression ?? "").startsWith("/*! axe")) return;
244
+ realOnSend(frame);
245
+ };
246
+ const started = Date.now();
247
+ await assert.rejects(
248
+ runA11yAudit({ url: "http://localhost:8000/", timeoutMs: 400, wsFactory: () => ws }),
249
+ /timed out/,
250
+ );
251
+ assert.ok(Date.now() - started < 5_000, "rejected within the budget, not at the 30s stub lifetime");
252
+ // launchCdp cleanup observed: the browser temp profile is torn down.
253
+ const profile = readFileSync(path.join(dir, "profile-path"), "utf8");
254
+ await new Promise((r) => setTimeout(r, 1_000)); // cleanup rmSync runs 300ms after the rejection
255
+ assert.ok(!existsSync(profile), "browser cleanup removed the temp profile");
256
+ });
257
+
258
+ it("F2: a ws close during the awaited bootstrap rejects cleanly with zero unhandled rejections", { timeout: 10_000 }, async () => {
259
+ const ws = new FakeWs();
260
+ baseServer(ws);
261
+ const realOnSend = ws.onSend!;
262
+ ws.onSend = (frame) => {
263
+ if (frame.method === "Runtime.evaluate" && String(frame.params?.expression ?? "").startsWith("/*! axe")) {
264
+ ws.close(); // the transport dies exactly at the bootstrap evaluate
265
+ return;
266
+ }
267
+ realOnSend(frame);
268
+ };
269
+ const unhandled: unknown[] = [];
270
+ const onUnhandled = (e: unknown) => unhandled.push(e);
271
+ process.on("unhandledRejection", onUnhandled);
272
+ try {
273
+ await assert.rejects(
274
+ runA11yAudit({ url: "http://localhost:8000/", timeoutMs: 2_000, wsFactory: () => ws }),
275
+ /closed|timed out/,
276
+ );
277
+ // Give any orphaned rejection a tick to surface.
278
+ await new Promise((r) => setTimeout(r, 2_100));
279
+ assert.deepEqual(unhandled, [], "fire-and-forget bootstrap must not escape as an unhandled rejection");
280
+ } finally {
281
+ process.off("unhandledRejection", onUnhandled);
282
+ }
283
+ });
284
+ });
285
+
188
286
  // ── FakeWs (copied minimal from cdp.test.ts — same harness contract) ────────
189
287
 
190
288
  class FakeWs implements WsLike {
@@ -302,6 +302,54 @@ describe("CdpConnection over a fake websocket", () => {
302
302
  // Normal path intact: awaiting still throws (timeout still surfaces).
303
303
  assert.match(String(await rejectMsg(loaded)), /Navigation timed out after 0\.02s/);
304
304
  });
305
+
306
+ it("F3: a SIBLING exceptionDetails reaches unwrapEvaluate — step outcome ok:false with the error", async () => {
307
+ const ws = new FakeWs();
308
+ ws.onSend = (frame) => {
309
+ const { method, id } = frame;
310
+ if (method === "Target.createTarget") return ws.reply(id, { targetId: "t1" });
311
+ if (method === "Target.attachToTarget") return ws.reply(id, { sessionId: "s1" });
312
+ if (method === "Page.navigate") {
313
+ ws.reply(id, {});
314
+ ws.event("Page.loadEventFired", {}, "s1");
315
+ return;
316
+ }
317
+ if (method === "Runtime.evaluate") {
318
+ // Raw frame: exceptionDetails SIBLING to result (not the nested
319
+ // Runtime.evaluate shape unwrapEvaluate already handled).
320
+ return ws.emit("message", {
321
+ data: JSON.stringify({
322
+ id,
323
+ result: { result: { type: "object" } },
324
+ exceptionDetails: { exception: { description: "ReferenceError: boom" } },
325
+ }),
326
+ });
327
+ }
328
+ ws.reply(id, {});
329
+ };
330
+ const r = await runInteraction({ url: "http://localhost:3000/", steps: [{ evaluate: "1+1" }], wsFactory: () => ws });
331
+ assert.equal(r.outcomes[0]!.ok, false);
332
+ assert.match(String(r.outcomes[0]!.error), /boom/);
333
+ });
334
+
335
+ it("waitForLoad: orphaned timer rejection is pre-handled (pi-crash regression 2026-09-20)", async () => {
336
+ const ws = new FakeWs();
337
+ const conn = await CdpConnection.connect("ws://fake", () => ws);
338
+ const unhandled: unknown[] = [];
339
+ const onUnhandled = (e: unknown) => unhandled.push(e);
340
+ process.on("unhandledRejection", onUnhandled);
341
+ // Deliberately not awaited — simulates Page.navigate rejecting first so the
342
+ // caller skips `await loaded`; the 20ms timer then rejects with no consumer.
343
+ const loaded = waitForLoad(conn, "s1", 20);
344
+ try {
345
+ await new Promise((r) => setTimeout(r, 60));
346
+ assert.deepEqual(unhandled, []); // unpatched: contains the timeout Error
347
+ } finally {
348
+ process.off("unhandledRejection", onUnhandled);
349
+ }
350
+ // Normal path intact: awaiting still throws (timeout still surfaces).
351
+ assert.match(String(await rejectMsg(loaded)), /Navigation timed out after 0\.02s/);
352
+ });
305
353
  });
306
354
 
307
355
  // ── runInteraction end-to-end against the fake CDP server ────────────────
@@ -72,6 +72,12 @@ describe("isLocalUrl", () => {
72
72
  "http://[::ffff:7f00:1]:8080", // hex form — WHATWG URL canonicalization shape
73
73
  "http://[::ffff:169.254.169.254]/",
74
74
  "http://[::ffff:10.0.0.5]/",
75
+ "http://100.64.0.1/", // 100.64/10 CGNAT
76
+ "http://100.127.255.254/", // 100.64/10 upper edge
77
+ "http://198.18.0.1/", // 198.18/15 benchmarking
78
+ "http://198.19.255.254/", // 198.18/15 upper edge
79
+ "http://192.0.0.1/", // 192.0.0/24 IETF protocol assignments
80
+ "http://[fec0::1]/", // decommissioned IPv6 site-local
75
81
  "file:///Users/me/project/index.html",
76
82
  ];
77
83
  for (const url of local) {
@@ -86,6 +92,9 @@ describe("isLocalUrl", () => {
86
92
  "http://172.32.0.1/",
87
93
  "http://192.169.1.1/",
88
94
  "http://[2001:db8::1]/",
95
+ "http://100.128.0.1/", // just above 100.64/10
96
+ "http://198.20.0.1/", // just above 198.18/15
97
+ "http://192.0.1.1/", // just above 192.0.0/24
89
98
  "https://developer.chrome.com/blog",
90
99
  "not a url",
91
100
  ];
@@ -279,4 +288,27 @@ describe("runChrome via stub binary", () => {
279
288
  assert.ok(includes(err.message, "timed out"));
280
289
  }
281
290
  });
291
+
292
+ it("bounds the captured stderr to a ~1KB tail even after megabytes of noise (F7)", async () => {
293
+ // The stub floods STDERR (~15MB, 25000 × 600B lines), then exits 1 without
294
+ // writing the output file → the close handler builds the error message
295
+ // from the retained tail.
296
+ process.env.CHROME_PATH = writeStub(
297
+ `echo "ERROR-TAIL-MARKER: chrome exploded" >&2\n` +
298
+ `i=0\nwhile [ $i -lt 25000 ]; do\n` +
299
+ ` echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' >&2\n` +
300
+ ` i=$((i+1))\ndone\nexit 1\n`,
301
+ );
302
+ try {
303
+ await captureScreenshot({ url: "http://localhost:9/x", timeoutMs: 10_000 });
304
+ assert.fail("should have failed (no output file)");
305
+ } catch (err: any) {
306
+ assert.ok(includes(err.message, "Chrome exited with code 1"));
307
+ // Retained stderr (message after the code prefix) is bounded, and the
308
+ // newest bytes survived the clipping (tail, not head).
309
+ const tail = String(err.message).split("Chrome exited with code 1: ")[1] ?? "";
310
+ assert.ok(tail.length <= 1024, `stderr tail ${tail.length}B must be ≤ 1KB`);
311
+ assert.ok(tail.includes("xxxx"), "newest stderr bytes retained");
312
+ }
313
+ });
282
314
  });