ceulen 0.15.1 → 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 (55) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +2 -2
  3. package/extensions/lib/registry.test.ts +12 -0
  4. package/extensions/lib/registry.ts +20 -4
  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 +8 -5
  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 +4 -4
  13. package/extensions/modules/plan/index.ts +116 -4
  14. package/extensions/modules/plan/lib/settings.ts +5 -7
  15. package/extensions/modules/plan/test/module.test.ts +104 -1
  16. package/extensions/modules/plan/test/settings.test.ts +7 -0
  17. package/extensions/modules/repair/configPanel.ts +3 -1
  18. package/extensions/modules/repair/index.ts +21 -16
  19. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  20. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  21. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  22. package/extensions/modules/repair/test/readers.test.ts +11 -5
  23. package/extensions/modules/repair/test/settings.test.ts +7 -2
  24. package/extensions/modules/rtk/configPanel.ts +67 -0
  25. package/extensions/modules/rtk/index.ts +76 -9
  26. package/extensions/modules/rtk/lib/settings.ts +65 -0
  27. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  28. package/extensions/modules/rtk/test/index.test.js +120 -2
  29. package/extensions/modules/rules/index.ts +4 -1
  30. package/extensions/modules/rules/lib/rules.ts +6 -3
  31. package/extensions/modules/rules/test/lib.test.ts +24 -0
  32. package/extensions/modules/rules/test/module.test.ts +29 -0
  33. package/extensions/modules/shells/lib/sessions.ts +40 -12
  34. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  35. package/extensions/modules/steering/index.ts +12 -1
  36. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  37. package/extensions/modules/subagent/index.ts +19 -3
  38. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  39. package/extensions/modules/subagent/lib/runner.ts +88 -22
  40. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  41. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  42. package/extensions/modules/todo/index.ts +4 -0
  43. package/extensions/modules/todo/test/todo.test.ts +9 -0
  44. package/extensions/modules/web/index.ts +1 -1
  45. package/extensions/modules/web/lib/a11y.ts +30 -15
  46. package/extensions/modules/web/lib/cdp.ts +11 -2
  47. package/extensions/modules/web/lib/chrome.ts +12 -3
  48. package/extensions/modules/web/lib/content.ts +32 -9
  49. package/extensions/modules/web/lib/search.ts +111 -3
  50. package/extensions/modules/web/test/a11y.test.ts +100 -2
  51. package/extensions/modules/web/test/cdp.test.ts +48 -0
  52. package/extensions/modules/web/test/chrome.test.ts +32 -0
  53. package/extensions/modules/web/test/content.test.ts +92 -0
  54. package/extensions/modules/web/test/search.test.ts +75 -0
  55. package/package.json +1 -1
@@ -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
  });
@@ -0,0 +1,92 @@
1
+ // content module tests — the fetchReadableContent SSRF guard (F5): local URLs
2
+ // refused before any fetch, redirect hops re-validated, public URLs unchanged.
3
+
4
+ import { describe, it, afterEach } from "node:test";
5
+ import assert from "node:assert/strict";
6
+
7
+ import { fetchReadableContent } from "../lib/content";
8
+
9
+ const ORIGINAL_FETCH = globalThis.fetch;
10
+
11
+ /** Track every fetch call; redirect: "manual" is asserted on the request init. */
12
+ function installMockFetch(handler: (url: string, init?: RequestInit) => Response | Promise<Response>): string[] {
13
+ const calls: string[] = [];
14
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
15
+ const url = String(input);
16
+ calls.push(url);
17
+ return handler(url, init);
18
+ }) as typeof fetch;
19
+ return calls;
20
+ }
21
+
22
+ afterEach(() => {
23
+ globalThis.fetch = ORIGINAL_FETCH;
24
+ });
25
+
26
+ describe("fetchReadableContent SSRF guard", () => {
27
+ it("rejects http://169.254.169.254/ before any fetch (metadata endpoint)", async () => {
28
+ const calls = installMockFetch(() => {
29
+ throw new Error("fetch must never be called for a guarded host");
30
+ });
31
+ await assert.rejects(
32
+ () => fetchReadableContent("http://169.254.169.254/latest/meta-data/"),
33
+ /SSRF-guarded/,
34
+ );
35
+ assert.deepEqual(calls, []);
36
+ });
37
+
38
+ it("rejects http://127.0.0.1/ before any fetch (loopback)", async () => {
39
+ const calls = installMockFetch(() => {
40
+ throw new Error("fetch must never be called for a guarded host");
41
+ });
42
+ await assert.rejects(() => fetchReadableContent("http://127.0.0.1:8080/"), /SSRF-guarded/);
43
+ assert.deepEqual(calls, []);
44
+ });
45
+
46
+ it("refuses a public→169.254.169.254 redirect hop", async () => {
47
+ const calls = installMockFetch((url) => {
48
+ if (url === "https://public.example/start") {
49
+ return new Response(null, { status: 302, headers: { location: "http://169.254.169.254/latest/meta-data/" } });
50
+ }
51
+ throw new Error(`fetch must never follow to ${url}`);
52
+ });
53
+ await assert.rejects(() => fetchReadableContent("https://public.example/start"), /SSRF-guarded/);
54
+ assert.deepEqual(calls, ["https://public.example/start"], "the redirect target is never fetched");
55
+ });
56
+
57
+ it("follows a public→public redirect and extracts the landed page", async () => {
58
+ installMockFetch((url) => {
59
+ if (url === "https://public.example/a") {
60
+ return new Response(null, { status: 301, headers: { location: "https://public.example/b" } });
61
+ }
62
+ if (url === "https://public.example/b") {
63
+ return new Response(
64
+ "<html><head><title>Moved</title></head><body><main><h1>Landed</h1><p>" +
65
+ "This public page carries plenty of readable content so the static extraction path returns it. ".repeat(2) +
66
+ "</p></main></body></html>",
67
+ { status: 200, headers: { "content-type": "text/html" } },
68
+ );
69
+ }
70
+ throw new Error(`unexpected fetch ${url}`);
71
+ });
72
+ const r = await fetchReadableContent("https://public.example/a");
73
+ assert.equal(r.title, "Moved");
74
+ assert.match(r.markdown, /Landed/);
75
+ });
76
+
77
+ it("still extracts a plain public URL (existing static path unchanged)", async () => {
78
+ installMockFetch((url) => {
79
+ if (url === "https://example.com/page") {
80
+ return new Response(
81
+ "<html><head><title>Plain</title></head><body><main><p>" +
82
+ "Ordinary public content, well above the readability floor, extracted through the untouched static path. ".repeat(2) +
83
+ "</p></main></body></html>",
84
+ { status: 200, headers: { "content-type": "text/html" } },
85
+ );
86
+ }
87
+ throw new Error(`unexpected fetch ${url}`);
88
+ });
89
+ const r = await fetchReadableContent("https://example.com/page");
90
+ assert.equal(r.title, "Plain");
91
+ });
92
+ });
@@ -207,4 +207,79 @@ describe("searchWithDiagnostics", () => {
207
207
  assert.equal(lengthOf(calls), 1);
208
208
  });
209
209
 
210
+ it("auto + >=2 backends routes through the classifier when a model resolves", async () => {
211
+ // A fake registry whose classify() always answers brave_first with high
212
+ // confidence — the order flips to precision regardless of the heuristic.
213
+ const registry = {
214
+ findOfType: () => ({ id: "combo/jev", provider: "router" }),
215
+ getModelsOfType: () => [{ id: "combo/jev", provider: "router" }],
216
+ getAvailableOfType: async () => [{ id: "combo/jev", provider: "router" }],
217
+ refresh: async () => {},
218
+ classify: async () => ({
219
+ stopReason: "stop",
220
+ answers: {
221
+ backend_preference: { choice: "brave_first", probabilities: { brave_first: 0.9, searxng_first: 0.1 }, confidence: 0.9 },
222
+ },
223
+ }),
224
+ };
225
+ const calls = installMockFetch((url) => {
226
+ if (url.startsWith("https://api.search.brave.com/")) {
227
+ return jsonResponse({ web: { results: [{ title: "Brave", url: "https://example.com", description: "S" }] } });
228
+ }
229
+ throw new Error(`unexpected fetch ${url}`);
230
+ });
231
+ // A broad query the heuristic would send to searxng first (unique string:
232
+ // the verdict LRU is keyed by query fingerprint and earlier tests run
233
+ // the same broad query without a ctx, which caches the heuristic order).
234
+ const result = await searchWithDiagnostics({ query: "homelab ansible ideas 2026", _ctx: { modelRegistry: registry } });
235
+ assert.equal(result.router, "classifier:jev");
236
+ assert.equal(result.backendOrder[0], "brave");
237
+ assert.equal(result.selectedBackend, "brave");
238
+ assert.ok(lengthOf(calls) >= 1);
239
+ });
240
+
241
+ it("classifier low confidence falls back to the heuristic", async () => {
242
+ const registry = {
243
+ findOfType: () => ({ id: "combo/jev", provider: "router" }),
244
+ getModelsOfType: () => [{ id: "combo/jev", provider: "router" }],
245
+ getAvailableOfType: async () => [{ id: "combo/jev", provider: "router" }],
246
+ refresh: async () => {},
247
+ classify: async () => ({
248
+ stopReason: "stop",
249
+ answers: { backend_preference: { choice: "searxng_first", probabilities: { searxng_first: 0.3, brave_first: 0.2 }, confidence: 0.3 } },
250
+ }),
251
+ };
252
+ const calls = installMockFetch((url) => {
253
+ if (url.startsWith("http://searxng.test/search")) {
254
+ return jsonResponse({ results: [{ title: "SearXNG", url: "https://example.com", content: "Snippet" }] });
255
+ }
256
+ throw new Error(`unexpected fetch ${url}`);
257
+ });
258
+ const result = await searchWithDiagnostics({ query: "homelab ansible ideas", _ctx: { modelRegistry: registry } });
259
+ assert.equal(result.router, "heuristic", "0.3 confidence < 0.6 → heuristic");
260
+ assert.equal(result.backendOrder[0], "searxng");
261
+ assert.ok(includes(calls[0], "searxng.test"));
262
+ });
263
+
264
+ it("explicit backend/engines params report router: explicit and never ask Jev", async () => {
265
+ let classifyCalls = 0;
266
+ const registry = {
267
+ findOfType: () => ({ id: "combo/jev", provider: "router" }),
268
+ getAvailableOfType: async () => [{ id: "combo/jev", provider: "router" }],
269
+ refresh: async () => {},
270
+ classify: async () => { classifyCalls++; throw new Error("must not be called"); },
271
+ };
272
+ installMockFetch((url) => {
273
+ if (url.startsWith("http://searxng.test/search")) {
274
+ return jsonResponse({ results: [{ title: "SearXNG", url: "https://example.com", content: "Snippet" }] });
275
+ }
276
+ throw new Error(`unexpected fetch ${url}`);
277
+ });
278
+ const explicit = await searchWithDiagnostics({ query: "homelab ansible", backend: "searxng", _ctx: { modelRegistry: registry } });
279
+ assert.equal(explicit.router, "explicit");
280
+ const engines = await searchWithDiagnostics({ query: "homelab ansible", engines: "google,github", _ctx: { modelRegistry: registry } });
281
+ assert.equal(engines.router, "explicit");
282
+ assert.equal(classifyCalls, 0);
283
+ });
284
+
210
285
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.15.1",
3
+ "version": "0.16.1",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",