ceulen 0.9.0 → 0.10.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 (33) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/extensions/lib/registry.ts +8 -2
  3. package/extensions/modules/composer/test/module.test.ts +2 -2
  4. package/extensions/modules/config/index.ts +1 -0
  5. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  6. package/extensions/modules/gh/configPanel.ts +82 -0
  7. package/extensions/modules/gh/index.ts +86 -0
  8. package/extensions/modules/gh/lib/gh-cli.ts +337 -0
  9. package/extensions/modules/gh/lib/ops.ts +771 -0
  10. package/extensions/modules/gh/test/gh.test.ts +280 -0
  11. package/extensions/modules/plan/lib/plan-tools.ts +8 -0
  12. package/extensions/modules/repair/index.ts +138 -0
  13. package/extensions/modules/repair/lib/guards.ts +1 -1
  14. package/extensions/modules/repair/lib/read-selector.ts +242 -0
  15. package/extensions/modules/repair/test/read-selector.test.ts +198 -0
  16. package/extensions/modules/steering/configPanel.ts +8 -0
  17. package/extensions/modules/steering/index.ts +6 -0
  18. package/extensions/modules/steering/lib/settings.ts +6 -2
  19. package/extensions/modules/steering/lib/think.ts +66 -0
  20. package/extensions/modules/steering/test/harness.ts +5 -0
  21. package/extensions/modules/steering/test/settings.test.ts +2 -0
  22. package/extensions/modules/steering/test/think.test.ts +77 -0
  23. package/extensions/modules/web/index.ts +37 -1
  24. package/extensions/modules/web/lib/a11y.ts +252 -0
  25. package/extensions/modules/web/test/a11y.test.ts +218 -0
  26. package/extensions/modules/web/test/extension.test.ts +2 -2
  27. package/extensions/modules/web/test/hook.test.ts +2 -2
  28. package/extensions/modules/web/vendor/axe/LICENSE +362 -0
  29. package/extensions/modules/web/vendor/axe/LICENSE-3RD-PARTY.txt +66 -0
  30. package/extensions/modules/web/vendor/axe/README.md +19 -0
  31. package/extensions/modules/web/vendor/axe/axe.min.js +12 -0
  32. package/package.json +2 -2
  33. package/skills/web/SKILL.md +1 -0
@@ -0,0 +1,77 @@
1
+ // think tool tests — definition shape, execute contract, collapsed rendering,
2
+ // the thinkTool gate on module load, and the kill-switch defaultActive.
3
+ //
4
+ // The agent dir is isolated for the WHOLE file (advisor catch: a test outside
5
+ // the gating describe would otherwise read the developer's real
6
+ // ~/.pi/agent/settings.json — a locally kill-switched `think` would fail it
7
+ // spuriously).
8
+
9
+ import assert from "node:assert/strict";
10
+ import { afterEach, beforeEach, describe, it } from "node:test";
11
+
12
+ import steeringModule from "../index.js";
13
+ import { THINK_MARKER, thinkTool } from "../lib/think.js";
14
+ import { createFakePi, isolateAgentDir, setSteeringSettings } from "./harness.js";
15
+
16
+ describe("think tool", () => {
17
+ let iso: { dir: string; restore: () => void };
18
+ beforeEach(() => { iso = isolateAgentDir("ceulen-think-test-"); });
19
+ afterEach(() => iso.restore());
20
+
21
+ describe("definition", () => {
22
+ it("has the OMP contract: private scratchpad, no promptSnippet", () => {
23
+ const def = thinkTool();
24
+ assert.equal(def.name, "think");
25
+ assert.equal(def.label, "Think");
26
+ assert.match(def.description, /scratchpad/i);
27
+ assert.equal((def as Record<string, unknown>).promptSnippet, undefined, "omitted from Available tools (OMP parity)");
28
+ assert.ok(Array.isArray(def.promptGuidelines) && def.promptGuidelines!.length > 0);
29
+ });
30
+
31
+ it("execute returns a minimal acknowledgment, never the thoughts", async () => {
32
+ const def = thinkTool();
33
+ const result = await def.execute();
34
+ assert.deepEqual(result, { content: [{ type: "text", text: "—" }] });
35
+ });
36
+
37
+ it("renderers return pi-tui Text components wrapping the dim marker", () => {
38
+ const def = thinkTool();
39
+ const theme = { fg: (token: string, text: string) => `<${token}>${text}</>` };
40
+ const call = def.renderCall({ thoughts: "abcd" }, theme);
41
+ const result = def.renderResult(undefined as never, undefined as never, theme);
42
+ // Regression (live 2026-10-05): a raw string here crashes the TUI with
43
+ // "this.child.render is not a function" — Box needs a real Component.
44
+ for (const c of [call, result]) {
45
+ assert.equal(typeof c, "object");
46
+ assert.equal(typeof (c as { render?: unknown }).render, "function", "must be a pi-tui Component");
47
+ const rendered = (c as { render(width?: number): string[] }).render(80);
48
+ assert.ok(Array.isArray(rendered) && rendered.every((l) => typeof l === "string"));
49
+ }
50
+ assert.match((call as unknown as { render(w: number): string[] }).render(80).join(""), /· think \(4 chars\)/);
51
+ assert.match((result as unknown as { render(w: number): string[] }).render(80).join(""), /·/);
52
+ // No theme → plain text (renderers must not crash on thin contexts).
53
+ const plain = def.renderCall({ thoughts: "x" });
54
+ assert.match((plain as unknown as { render(w: number): string[] }).render(80).join(""), /· think \(1 chars\)/);
55
+ });
56
+
57
+ it("defaultActive is true unless the kill-switch names think", () => {
58
+ assert.equal(thinkTool().defaultActive, true, "isolated dir has no ceulen.disabledTools");
59
+ });
60
+ });
61
+
62
+ describe("module gating", () => {
63
+ it("thinkTool: false (default) registers no think tool", () => {
64
+ setSteeringSettings(iso.dir, {});
65
+ const pi = createFakePi();
66
+ assert.equal(pi.tools.length, 0, "no tool when the gate is off");
67
+ });
68
+
69
+ it("thinkTool: true registers the think tool, active unless disabled", () => {
70
+ setSteeringSettings(iso.dir, { thinkTool: true });
71
+ const pi = createFakePi();
72
+ assert.equal(pi.tools.length, 1);
73
+ assert.equal(pi.tools[0]!.name, "think");
74
+ assert.equal(pi.tools[0]!.defaultActive, true);
75
+ });
76
+ });
77
+ });
@@ -1,5 +1,6 @@
1
1
  // ponytail: ported from @bacnh85/pi-web 0.17.8 extensions/index.ts — the 11
2
- // unified web tools + the conditional WEB_ROUTING_GUIDANCE injection, wrapped
2
+ // unified web tools PLUS web_a11y (axe-core rendered-page audit, vendored
3
+ // under vendor/axe/), wrapped
3
4
  // in ceulen's module conventions: per-tool kill-switch (ceulen.disabledTools →
4
5
  // defaultActive:false, /config re-activates live), and the pi-web skill
5
6
  // contributed via resources_discover (kill-switch gated, NOT the package.json
@@ -16,6 +17,8 @@ import { Type } from "typebox";
16
17
 
17
18
  import { readDisabledTools } from "../../lib/tools.js";
18
19
 
20
+ import { formatA11ySummary, runA11yAudit } from "./lib/a11y";
21
+
19
22
  import {
20
23
  findEnvValue,
21
24
  cwdFromContext,
@@ -966,6 +969,39 @@ export default function piWebExtension(pi: ExtensionAPI) {
966
969
  },
967
970
  });
968
971
 
972
+ // ── web_a11y ─────────────────────────────────────────────────
973
+ pi.registerTool({
974
+ name: "web_a11y",
975
+ label: "Web Accessibility Audit",
976
+ description:
977
+ "Real rendered-page accessibility audit (axe-core 4.13) in local headless Chrome: contrast, accessible names, roles, keyboard/ARIA violations with node targets. For ANY http://, https://, or file:// URL the local machine can reach — the complement to ux_audit's static CSS checks in the UX loop. One call = one browser lifecycle; axe walks same-origin iframes in-page (cross-origin frames are not audited).",
978
+ promptSnippet: "Accessibility audit of a rendered page (axe-core)",
979
+ promptGuidelines: [
980
+ "Use to VERIFY your own UI builds: ux_audit checks the CSS text, web_a11y checks the RENDERED DOM — run both before declaring a screen done.",
981
+ "Local headless Chrome drives the audit (web_interact's engine); no daemon fallback.",
982
+ ],
983
+ parameters: Type.Object({
984
+ url: Type.String({ description: "Page to audit (http://, https://, or file://)." }),
985
+ tags: Type.Optional(Type.Array(Type.String(), { description: "Axe tag filter (wcag2a, wcag2aa, wcag21a, wcag21aa, best-practice…). Omit for axe's default tag set." })),
986
+ rules: Type.Optional(Type.Array(Type.String(), { description: "Restrict to these axe rule ids (enabled alongside the tag filter)." })),
987
+ selector: Type.Optional(Type.String({ description: "Audit only the subtree matching this CSS selector." })),
988
+ include_incomplete: Type.Optional(Type.Boolean({ default: false, description: "Include results that need manual review." })),
989
+ timeout_ms: Type.Optional(Type.Number({ default: 60000, description: "Budget for navigation + audit (default 60s)." })),
990
+ }),
991
+ async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal) {
992
+ const result = await runA11yAudit({
993
+ url: params.url as string,
994
+ tags: params.tags as string[] | undefined,
995
+ rules: params.rules as string[] | undefined,
996
+ selector: params.selector as string | undefined,
997
+ includeIncomplete: params.include_incomplete as boolean | undefined,
998
+ timeoutMs: params.timeout_ms as number | undefined,
999
+ signal,
1000
+ });
1001
+ return { content: [{ type: "text" as const, text: formatA11ySummary(result) }], details: result };
1002
+ },
1003
+ });
1004
+
969
1005
  // ── Always-on routing guidance ──────────────────────────────────────────
970
1006
  // Inject the backend-selection protocol only when a web_* tool is actually
971
1007
  // active, so recon agents / sessions without pi-web carry zero overhead.
@@ -0,0 +1,252 @@
1
+ // web_a11y — real rendered-page accessibility audits via axe-core.
2
+ //
3
+ // ponytail: ported from oh-my-pi packages/coding-agent/src/tools/browser/
4
+ // a11y/audit.ts (the normalize/trim/format half, verbatim shapes) onto the web
5
+ // module's own CDP client. OMP's puppeteer frame-walk is NOT ported: the audit
6
+ // runs once in the main document and axe walks same-origin iframes in-page
7
+ // itself; cross-origin frames are the documented ceiling (vendor/axe/README).
8
+ //
9
+ // Flow: launchCdp (the web_interact lifecycle) → navigate → wait load →
10
+ // Runtime.evaluate the vendored axe.min.js (defines window.axe; CDP evaluation
11
+ // is CSP-exempt, same as web_interact's evaluate steps) → Runtime.evaluate a
12
+ // runner IIFE calling axe.run → normalize → formatA11ySummary.
13
+
14
+ import { readFileSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ import { launchCdp, unwrapEvaluate, waitForLoad, type WsFactory } from "./cdp";
19
+
20
+ // ── OMP shapes (browser/a11y/audit.ts) ─────────────────────────────────────
21
+
22
+ /** Options accepted by the browser accessibility audit helper. */
23
+ export interface BrowserA11yOptions {
24
+ /** Restrict the audit to rules carrying at least one of these axe tags. */
25
+ tags?: string[];
26
+ /** Restrict the audit to these axe rule ids. */
27
+ rules?: string[];
28
+ /** Audit only the subtree matching this CSS selector. */
29
+ selector?: string;
30
+ /** Include results that require manual review in the returned report. */
31
+ includeIncomplete?: boolean;
32
+ }
33
+
34
+ /** One failing DOM node reported by axe-core. */
35
+ export interface BrowserA11yNode {
36
+ /** Selector path; nested arrays preserve shadow-root boundaries. */
37
+ target: string[] | string[][];
38
+ /** Truncated outer HTML for the failing node. */
39
+ html: string;
40
+ /** Axe's explanation of why the node failed. */
41
+ failureSummary: string;
42
+ }
43
+
44
+ /** One axe-core rule result. */
45
+ export interface BrowserA11yViolation {
46
+ id: string;
47
+ impact: string | null;
48
+ help: string;
49
+ helpUrl: string;
50
+ tags: string[];
51
+ /** Total number of failing nodes before the displayed-node limit. */
52
+ nodeCount: number;
53
+ /** At most ten representative failing nodes. */
54
+ nodes: BrowserA11yNode[];
55
+ }
56
+
57
+ /** Structured result returned by a browser accessibility audit. */
58
+ export interface BrowserA11yResult {
59
+ url: string;
60
+ engine: { name: "axe-core"; version: string };
61
+ counts: { violations: number; incomplete: number; passes: number };
62
+ violations: BrowserA11yViolation[];
63
+ incomplete: BrowserA11yViolation[];
64
+ }
65
+
66
+ const MAX_RESULT_NODES = 10;
67
+ const MAX_HTML_LENGTH = 300;
68
+
69
+ interface AxeNodeResult {
70
+ target: string[] | string[][];
71
+ html?: string;
72
+ failureSummary?: string;
73
+ }
74
+
75
+ interface AxeRuleResult {
76
+ id?: string;
77
+ impact?: string | null;
78
+ help?: string;
79
+ helpUrl?: string;
80
+ tags?: string[];
81
+ nodes?: AxeNodeResult[];
82
+ }
83
+
84
+ interface AxeResults {
85
+ url?: string;
86
+ testEngine?: { name?: string; version?: string };
87
+ violations?: AxeRuleResult[];
88
+ incomplete?: AxeRuleResult[];
89
+ passes?: AxeRuleResult[];
90
+ }
91
+
92
+ function trimRuleResults(results: AxeRuleResult[] | undefined): BrowserA11yViolation[] {
93
+ return (results ?? []).map((result) => ({
94
+ id: String(result.id ?? "unknown"),
95
+ impact: result.impact ?? null,
96
+ help: String(result.help ?? result.id ?? ""),
97
+ helpUrl: String(result.helpUrl ?? ""),
98
+ tags: Array.isArray(result.tags) ? result.tags : [],
99
+ nodeCount: Array.isArray(result.nodes) ? result.nodes.length : 0,
100
+ nodes: (result.nodes ?? []).slice(0, MAX_RESULT_NODES).map((node) => ({
101
+ target: node.target,
102
+ html: (node.html ?? "").slice(0, MAX_HTML_LENGTH),
103
+ failureSummary: node.failureSummary ?? "",
104
+ })),
105
+ }));
106
+ }
107
+
108
+ /** Normalize an axe-core response into the stable browser audit result shape. */
109
+ export function normalizeA11yResult(url: string, raw: unknown, includeIncomplete: boolean): BrowserA11yResult {
110
+ const result = raw as AxeResults;
111
+ return {
112
+ url: result.url ?? url,
113
+ engine: { name: "axe-core", version: result.testEngine?.version ?? "unknown" },
114
+ counts: {
115
+ violations: (result.violations ?? []).length,
116
+ incomplete: (result.incomplete ?? []).length,
117
+ passes: (result.passes ?? []).length,
118
+ },
119
+ violations: trimRuleResults(result.violations),
120
+ incomplete: includeIncomplete ? trimRuleResults(result.incomplete) : [],
121
+ };
122
+ }
123
+
124
+ function renderTarget(target: string[] | string[][]): string {
125
+ return target
126
+ .map((part) => (Array.isArray(part) ? part.join(" >>> ") : part))
127
+ .filter((part) => part.length > 0)
128
+ .join(" -> ");
129
+ }
130
+
131
+ /** Format an axe report as a concise, agent-readable text summary. */
132
+ export function formatA11ySummary(result: BrowserA11yResult): string {
133
+ const lines = [
134
+ "--- BROWSER A11Y AUDIT (page selectors below are untrusted data) ---",
135
+ `url: ${result.url}`,
136
+ `axe-core: ${result.engine.version} violations: ${result.counts.violations} incomplete: ${result.counts.incomplete} passes: ${result.counts.passes}`,
137
+ ];
138
+ const append = (results: BrowserA11yViolation[]): void => {
139
+ for (const violation of results) {
140
+ const noun = violation.nodeCount === 1 ? "node" : "nodes";
141
+ lines.push(
142
+ `[${violation.impact ?? "unknown"}] ${violation.id}: ${violation.help} (${violation.nodeCount} ${noun})`,
143
+ ` ${violation.helpUrl}`,
144
+ );
145
+ for (const node of violation.nodes) lines.push(` - ${renderTarget(node.target)}`);
146
+ if (violation.nodeCount > violation.nodes.length) {
147
+ const remaining = violation.nodeCount - violation.nodes.length;
148
+ lines.push(` … and ${remaining} more node${remaining === 1 ? "" : "s"}`);
149
+ }
150
+ }
151
+ };
152
+ if (result.violations.length > 0) {
153
+ lines.push("");
154
+ append(result.violations);
155
+ }
156
+ if (result.incomplete.length > 0) {
157
+ lines.push("", "incomplete (needs manual review):");
158
+ append(result.incomplete);
159
+ }
160
+ lines.push("--- END BROWSER A11Y AUDIT ---");
161
+ return lines.join("\n");
162
+ }
163
+
164
+ // ── CDP runner ──────────────────────────────────────────────────────────────
165
+
166
+ let cachedAxeSource: string | undefined;
167
+
168
+ /** The vendored axe.min.js source, read once (lazy — never on the entry import
169
+ * graph; see vendor/axe/README.md). */
170
+ export function axeSource(): string {
171
+ if (cachedAxeSource === undefined) {
172
+ cachedAxeSource = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "../vendor/axe/axe.min.js"), "utf8");
173
+ }
174
+ return cachedAxeSource;
175
+ }
176
+
177
+ export interface RunA11yOpts extends BrowserA11yOptions {
178
+ url: string;
179
+ timeoutMs?: number;
180
+ /** Abort → browser torn down at once. */
181
+ signal?: AbortSignal;
182
+ /** Test seam — fake websocket factory (cdp.test.ts pattern). */
183
+ wsFactory?: WsFactory;
184
+ }
185
+
186
+ function runnerExpression(options: BrowserA11yOptions): string {
187
+ // rules → {id:{enabled:true}}; runOnly only when tags are set (axe's own
188
+ // default tag set otherwise). JSON-injected — options are tool-validated.
189
+ const rules = Object.fromEntries((options.rules ?? []).map((id) => [id, { enabled: true }]));
190
+ const runOnly = options.tags && options.tags.length > 0 ? { runOnly: { type: "tag", values: options.tags } } : {};
191
+ const axeOpts = JSON.stringify({ ...runOnly, rules, resultTypes: ["violations", "incomplete", "passes"] });
192
+ const selector = options.selector ? JSON.stringify(options.selector) : null;
193
+ return `(async () => {
194
+ try {
195
+ if (!window.axe) throw new Error("axe bootstrap missing");
196
+ const opts = ${axeOpts};
197
+ const context = ${selector === null ? "document" : `{ include: [${selector}] }`};
198
+ const r = await window.axe.run(context, opts);
199
+ return JSON.stringify({ __axeOk: r });
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.
204
+ return JSON.stringify({ __axeError: err instanceof Error ? err.message : String(err) });
205
+ }
206
+ })()`;
207
+ }
208
+
209
+ /**
210
+ * One call = one browser lifecycle: launch local headless Chrome, navigate,
211
+ * inject axe, run, normalize, teardown. Same-origin iframes are covered by
212
+ * axe in-page; cross-origin frames are out of scope (ceiling note above).
213
+ */
214
+ export async function runA11yAudit(opts: RunA11yOpts): Promise<BrowserA11yResult> {
215
+ const timeoutMs = opts.timeoutMs ?? 60_000;
216
+ const browser = await launchCdp({ wsFactory: opts.wsFactory });
217
+ const onAbort = () => browser.cleanup();
218
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
219
+ let sessionId: string | undefined;
220
+ try {
221
+ const connection = browser.connection;
222
+ const target = await connection.send("Target.createTarget", { url: "about:blank" });
223
+ const targetId = target.targetId as string;
224
+ sessionId = ((await connection.send("Target.attachToTarget", { targetId, flatten: true })) as { sessionId: string })
225
+ .sessionId;
226
+ const send = (method: string, params?: Record<string, unknown>) => connection.send(method, params, sessionId);
227
+ await send("Page.enable");
228
+ const loaded = waitForLoad(connection, sessionId);
229
+ await send("Page.navigate", { url: opts.url });
230
+ await loaded;
231
+ 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());
235
+ // Runner: axe.run is async and huge — awaitPromise + returnByValue, and
236
+ // stringified (JSON survives returnByValue losslessly). In-page failures
237
+ // ride back as {__axeError} because the connection layer drops top-level
238
+ // exceptionDetails (see runnerExpression).
239
+ const raw = String(await evaluate(runnerExpression(opts), true));
240
+ let parsed: { __axeOk?: unknown; __axeError?: string };
241
+ try {
242
+ parsed = JSON.parse(raw);
243
+ } catch {
244
+ throw new Error(`axe runner returned non-JSON (${raw.slice(0, 120)})`);
245
+ }
246
+ if (parsed.__axeError) throw new Error(`axe audit failed: ${parsed.__axeError}`);
247
+ return normalizeA11yResult(opts.url, parsed.__axeOk, opts.includeIncomplete === true);
248
+ } finally {
249
+ opts.signal?.removeEventListener("abort", onAbort);
250
+ browser.cleanup();
251
+ }
252
+ }
@@ -0,0 +1,218 @@
1
+ // web_a11y tests — the ported OMP normalize/trim/format half (pure), the lazy
2
+ // vendored axe source, the runner expression builder, and the CDP flow against
3
+ // the fake websocket server (cdp.test.ts harness pattern).
4
+
5
+ import assert from "node:assert/strict";
6
+ import { mkdtempSync, rmSync, writeFileSync, chmodSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import path from "node:path";
9
+ import { after, before, describe, it } from "node:test";
10
+
11
+ import {
12
+ axeSource,
13
+ formatA11ySummary,
14
+ normalizeA11yResult,
15
+ runA11yAudit,
16
+ } from "../lib/a11y";
17
+ import type { WsLike } from "../lib/cdp";
18
+
19
+ // ── normalizeA11yResult ─────────────────────────────────────────────────────
20
+
21
+ const FIXTURE_VIOLATION = {
22
+ id: "color-contrast",
23
+ impact: "serious",
24
+ help: "Elements must have sufficient color contrast",
25
+ helpUrl: "https://dequeuniversity.com/rules/axe/4.13/color-contrast",
26
+ tags: ["cat.color", "wcag2aa"],
27
+ nodes: Array.from({ length: 12 }, (_, i) => ({
28
+ target: [`#row-${i}`],
29
+ html: `<div id="row-${i}">x</div>`,
30
+ failureSummary: "Fix any of the following...",
31
+ })),
32
+ };
33
+
34
+ const FIXTURE_RESULTS = {
35
+ url: "http://localhost:8000/",
36
+ testEngine: { name: "axe-core", version: "4.13.0" },
37
+ violations: [FIXTURE_VIOLATION],
38
+ incomplete: [{ id: "region", help: "page regions", helpUrl: "x", tags: [], nodes: [{ target: ["body"], html: "<body>", failureSummary: "" }] }],
39
+ passes: [{ id: "html-lang", nodes: [{ target: ["html"], html: "<html>", failureSummary: "" }] }],
40
+ };
41
+
42
+ describe("normalizeA11yResult", () => {
43
+ it("normalizes counts, engine, violations; caps nodes at 10 with real nodeCount", () => {
44
+ const r = normalizeA11yResult("http://localhost:8000/", FIXTURE_RESULTS, false);
45
+ assert.equal(r.url, "http://localhost:8000/");
46
+ assert.deepEqual(r.engine, { name: "axe-core", version: "4.13.0" });
47
+ assert.deepEqual(r.counts, { violations: 1, incomplete: 1, passes: 1 });
48
+ assert.equal(r.violations.length, 1);
49
+ const v = r.violations[0]!;
50
+ assert.equal(v.id, "color-contrast");
51
+ assert.equal(v.impact, "serious");
52
+ assert.equal(v.nodeCount, 12, "true failing-node count");
53
+ assert.equal(v.nodes.length, 10, "capped display");
54
+ assert.equal(v.nodes[0]!.html.length, "<div id=\"row-0\">x</div>".length);
55
+ });
56
+
57
+ it("gates incomplete results behind includeIncomplete", () => {
58
+ assert.equal(normalizeA11yResult("u", FIXTURE_RESULTS, false).incomplete.length, 0);
59
+ assert.equal(normalizeA11yResult("u", FIXTURE_RESULTS, true).incomplete.length, 1);
60
+ });
61
+
62
+ it("tolerates partial/garbage axe payloads (defensive on optional fields)", () => {
63
+ const r = normalizeA11yResult("http://x/", { violations: [{ id: "z" }] }, false);
64
+ assert.equal(r.violations[0]!.id, "z");
65
+ assert.equal(r.violations[0]!.impact, null);
66
+ assert.equal(r.violations[0]!.nodeCount, 0);
67
+ assert.equal(r.engine.version, "unknown");
68
+ assert.equal(r.url, "http://x/");
69
+ });
70
+ });
71
+
72
+ describe("formatA11ySummary", () => {
73
+ it("renders the OMP summary: header, counts, per-violation lines, node targets, … more tail", () => {
74
+ const text = formatA11ySummary(normalizeA11yResult("http://localhost:8000/", FIXTURE_RESULTS, false));
75
+ assert.match(text, /--- BROWSER A11Y AUDIT/);
76
+ assert.match(text, /url: http:\/\/localhost:8000\//);
77
+ assert.match(text, /axe-core: 4\.13\.0 violations: 1 incomplete: 1 passes: 1/, "counts are raw even when the incomplete list is gated");
78
+ assert.match(text, /\[serious\] color-contrast: Elements must have sufficient color contrast \(12 nodes\)/);
79
+ assert.match(text, /- #row-0$/m);
80
+ assert.match(text, /… and 2 more nodes/);
81
+ assert.match(text, /--- END BROWSER A11Y AUDIT ---/);
82
+ assert.doesNotMatch(text, /incomplete \(needs manual review\)/, "gated off");
83
+ });
84
+
85
+ it("lists incomplete results when included", () => {
86
+ const text = formatA11ySummary(normalizeA11yResult("u", FIXTURE_RESULTS, true));
87
+ assert.match(text, /incomplete \(needs manual review\):/);
88
+ assert.match(text, /\[unknown\] region: page regions \(1 node\)/);
89
+ assert.doesNotMatch(formatA11ySummary(normalizeA11yResult("u", FIXTURE_RESULTS, false)), /incomplete \(needs manual review\):/, "gated off");
90
+ });
91
+
92
+ it("shadow-root targets render with the >>> boundary", () => {
93
+ const r = normalizeA11yResult("u", { violations: [{ id: "x", nodes: [{ target: [["#shadow-host", "#inner"]] }] }] }, false);
94
+ assert.match(formatA11ySummary(r), /- #shadow-host >>> #inner/);
95
+ });
96
+ });
97
+
98
+ // ── vendored source + runner expression ────────────────────────────────────
99
+
100
+ describe("axeSource", () => {
101
+ it("reads the vendored 4.13.0 build lazily", () => {
102
+ const src = axeSource();
103
+ assert.ok(src.length > 500_000, "vendored axe.min.js loaded");
104
+ assert.match(src, /axe v4\.13\.0/);
105
+ });
106
+ });
107
+
108
+ describe("runner expression (via fake CDP server)", () => {
109
+ it("bootstraps axe then runs it, returning the normalized report", async () => {
110
+ const evals: string[] = [];
111
+ const ws = new FakeWs();
112
+ ws.onSend = (frame) => {
113
+ const { method, id, params } = frame;
114
+ if (method === "Target.createTarget") ws.reply(id, { targetId: "t1" });
115
+ else if (method === "Target.attachToTarget") ws.reply(id, { sessionId: "s1" });
116
+ else if (method === "Page.navigate") {
117
+ ws.reply(id, { frameId: "f1" });
118
+ ws.event("Page.loadEventFired", {}, "s1");
119
+ } else if (method === "Runtime.evaluate") {
120
+ const expr = String((params as { expression?: string }).expression ?? "");
121
+ evals.push(expr.slice(0, 40));
122
+ if (expr.startsWith("/*! axe")) ws.reply(id, { result: { type: "object", value: undefined } });
123
+ else ws.reply(id, { result: { type: "string", value: JSON.stringify({ __axeOk: FIXTURE_RESULTS }) } });
124
+ } else ws.reply(id, {});
125
+ };
126
+ const r = await runA11yAudit({ url: "http://localhost:8000/", wsFactory: () => ws, signal: undefined });
127
+ assert.equal(evals.length, 2, "bootstrap + runner evaluate");
128
+ assert.equal(r.violations[0]!.id, "color-contrast");
129
+ // The runner carried the options: default = no runOnly (axe defaults).
130
+ assert.ok(!evals[1]!.includes("runOnly"), "no tags → axe default tag set");
131
+ });
132
+
133
+ it("tags/selector flow into the runner expression", async () => {
134
+ let runner = "";
135
+ const ws = new FakeWs();
136
+ ws.onSend = (frame) => {
137
+ const { method, id, params } = frame;
138
+ if (method === "Target.createTarget") ws.reply(id, { targetId: "t1" });
139
+ else if (method === "Target.attachToTarget") ws.reply(id, { sessionId: "s1" });
140
+ else if (method === "Page.navigate") {
141
+ ws.reply(id, { frameId: "f1" });
142
+ ws.event("Page.loadEventFired", {}, "s1");
143
+ } else if (method === "Runtime.evaluate") {
144
+ const expr = String((params as { expression?: string }).expression ?? "");
145
+ if (expr.startsWith("/*! axe")) ws.reply(id, { result: { type: "object" } });
146
+ else {
147
+ runner = expr;
148
+ ws.reply(id, { result: { type: "string", value: JSON.stringify({ __axeOk: FIXTURE_RESULTS }) } });
149
+ }
150
+ } else ws.reply(id, {});
151
+ };
152
+ await runA11yAudit({
153
+ url: "http://localhost:8000/",
154
+ tags: ["wcag2a", "wcag2aa"],
155
+ rules: ["color-contrast"],
156
+ selector: "main",
157
+ wsFactory: () => ws,
158
+ });
159
+ assert.match(runner, /"runOnly":\{"type":"tag","values":\["wcag2a","wcag2aa"\]\}/);
160
+ assert.match(runner, /"color-contrast":\{"enabled":true\}/);
161
+ assert.match(runner, /include: \["main"\]/);
162
+ });
163
+
164
+ it("a rejected axe.run surfaces as a tool error (unwrapEvaluate path)", async () => {
165
+ const ws = new FakeWs();
166
+ ws.onSend = (frame) => {
167
+ const { method, id, params } = frame;
168
+ if (method === "Target.createTarget") ws.reply(id, { targetId: "t1" });
169
+ else if (method === "Target.attachToTarget") ws.reply(id, { sessionId: "s1" });
170
+ else if (method === "Page.navigate") {
171
+ ws.reply(id, { frameId: "f1" });
172
+ ws.event("Page.loadEventFired", {}, "s1");
173
+ } else if (method === "Runtime.evaluate") {
174
+ const expr = String((params as { expression?: string }).expression ?? "");
175
+ if (expr.startsWith("/*! axe")) ws.reply(id, { result: { type: "object" } });
176
+ else {
177
+ ws.reply(id, { result: { type: "string", value: JSON.stringify({ __axeError: "axe bootstrap missing" }) } });
178
+ }
179
+ } else ws.reply(id, {});
180
+ };
181
+ await assert.rejects(
182
+ runA11yAudit({ url: "http://localhost:8000/", wsFactory: () => ws }),
183
+ /axe bootstrap missing/,
184
+ );
185
+ });
186
+ });
187
+
188
+ // ── FakeWs (copied minimal from cdp.test.ts — same harness contract) ────────
189
+
190
+ class FakeWs implements WsLike {
191
+ onSend: ((frame: Record<string, any>) => void) | null = null;
192
+ private listeners = new Map<string, Array<(ev?: { data?: unknown }) => void>>();
193
+
194
+ addEventListener(type: string, fn: (ev?: { data?: unknown }) => void) {
195
+ if (!this.listeners.has(type)) this.listeners.set(type, []);
196
+ this.listeners.get(type)!.push(fn);
197
+ if (type === "open") queueMicrotask(() => this.emit("open"));
198
+ }
199
+ removeEventListener(type: string, fn: (ev?: { data?: unknown }) => void) {
200
+ this.listeners.set(type, (this.listeners.get(type) ?? []).filter((f) => f !== fn));
201
+ }
202
+ send(data: string) {
203
+ const frame = JSON.parse(data);
204
+ if (this.onSend) queueMicrotask(() => this.onSend!(frame));
205
+ }
206
+ close() {
207
+ this.emit("close");
208
+ }
209
+ emit(type: string, ev?: { data?: unknown }) {
210
+ for (const fn of this.listeners.get(type) ?? []) fn(ev);
211
+ }
212
+ reply(id: number, result: Record<string, unknown>) {
213
+ this.emit("message", { data: JSON.stringify({ id, result }) });
214
+ }
215
+ event(method: string, params: Record<string, unknown>, sessionId?: string) {
216
+ this.emit("message", { data: JSON.stringify({ method, params, sessionId }) });
217
+ }
218
+ }
@@ -12,7 +12,7 @@ import webExtension from "../index";
12
12
 
13
13
  const ALL_TOOLS = [
14
14
  "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf",
15
- "web_interact", "web_research", "web_image", "web_chat", "web_status",
15
+ "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y",
16
16
  ];
17
17
 
18
18
  function harness(opts: { disabledTools?: string[]; activeTools?: string[] } = {}) {
@@ -71,7 +71,7 @@ describe("web module ceulen contract", () => {
71
71
  else process.env.PI_CODING_AGENT_DIR = oldAgentDir;
72
72
  });
73
73
 
74
- it("registers exactly the eleven web_* tools", () => {
74
+ it("registers exactly the twelve web_* tools", () => {
75
75
  const { tools } = harness();
76
76
  assert.deepEqual(Object.keys(tools).sort(), [...ALL_TOOLS].sort());
77
77
  });
@@ -66,10 +66,10 @@ function callHook(handlers: Record<string, Function[]>, selectedTools: string[]
66
66
  }
67
67
 
68
68
  describe("pi-web before_agent_start routing guidance", () => {
69
- it("registers eleven web_* tools", () => {
69
+ it("registers twelve web_* tools", () => {
70
70
  const { tools } = harness();
71
71
  const webTools = Object.keys(tools).filter((n) => n.startsWith("web_"));
72
- assert.equal(lengthOf(webTools), 11);
72
+ assert.equal(lengthOf(webTools), 12);
73
73
  });
74
74
 
75
75
  it("injects routing guidance when a web_* tool is active", async () => {