diff --git a/docs/superpowers/plans/2026-10-18-guardrails-a11y-split.md b/docs/superpowers/plans/2026-10-18-guardrails-a11y-split.md new file mode 100644 index 0000000..83b8c26 --- /dev/null +++ b/docs/superpowers/plans/2026-10-18-guardrails-a11y-split.md @@ -0,0 +1,2030 @@ +# Guardrails a11y split, injection and exposure domains — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Move accessibility out of `/guardrails` into a standalone `/a11y` skill sharing the scan engine, add the `injection` and `exposure` scanner domains, extend the read-only probe with an `exposure` block, and patch every citer. + +**Architecture:** `scan.py` is split into a parametrized engine (`scanner.py`, a `Catalogue` of domains, prefixes and marker) and two thin catalogue CLIs (guardrails, a11y). Two new check modules follow the `apis.py` pattern (regex constants, `applies`, `check`, private `_x(project)` lists, `project.found`). The probe gains one `probe_exposure` entry in `PROBES` plus two shared fixes to `fetch`. Doctrine, routing rows, profiles, locks and docs are patched in the same branch. + +**Tech Stack:** Python 3 stdlib (`python3 -B`), bash test suites run through `make test suite=`, shellcheck, gitflow lib. + +**Spec:** `docs/superpowers/specs/2026-10-18-guardrails-a11y-split-design.md` + +**Contract:** `.claude/tasks/contracts/2026-10-18-guardrails-a11y-split-inj-exp-2210.md` + +## Global Constraints + +- Scanner: read-only, stdlib only, never executes project code, severities FAIL / WARN / MANUAL only, exit 0 / 1 / 2. A clean scan means "no static finding". +- Probe: GET, HEAD, OPTIONS only plus the existing opt-in POST burst; `--authorized` required; same-host redirects only; shared budget 200; secrets from env only; never print a response value, only key names. +- Code style: max 25 logic lines per function, 80 columns, 5 params, 5 locals. One check module per domain exposing `DOMAIN`, `applies(project)`, `check(project)`. +- Tests: every rule has a mutant at its default severity; every known false-positive class has a `benign` lock; the clean fixtures report ` 0 FAIL, 0 WARN`. Portable shell: no `sed -i`, no `grep -P`, no `stat -c`. +- Git: work on `feature/a11y-split-inj-exp`; commit per task with `git add `; never `git add -A`; never stage `settings.json` or the pre-existing hunks of `mods/model-router/routing.json`; never push by hand (hooks push). +- Rule, heading and label citers are patched in the same task that changes them (BDR-100). +- Locked single-line strings in SKILL.md files (loops-light) must stay on one line. +- Fixture payloads are realistic, never canonical textbook examples; fixture names stay neutral. +- Run `make test suite=` for the suites a task touches; one full `make test` in Task 9. + +## Review Focus + +1. A tagged SQL template (`` sql`select * from notes where id = ${id}` ``) must stay silent: pinned by the `tagged-sql-template` benign lock in Task 2. +2. A console call in a server file (`src/pages/api/notes.ts`) must stay silent while the same call in `src/components/` warns: pinned by `console-server-file` in Task 3. +3. A `' + b'' + b'' + b'') + if path == "/app.js": + return self._send(200, b"console.log(1);\n//# sourceMappingURL=app.js.map\n") + if path == "/app.js.map": + return self._send(200, b'{"version":3,"sources":["src/app.ts"],"mappings":""}') + if path == "/clean.js": + return self._send(200, b"console.log(2);\n") + if path == "/boom": + return self._send(500, b"Traceback (most recent call last):\n" + b' File "app.py", line 12, in handler\n') + if path == "/api/me": + return self._send(200, b'{"id": 1, "email": "t@t.io", ' + b'"password_hash": "x", "profile": {"api_key": "y"}}', + {"Content-Type": "application/json"}) +``` + +And replace `do_OPTIONS` so header names are lowercase on `/lower`: + +```python + def do_OPTIONS(self): + origin = self.headers.get("Origin", "") + upper = ("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials") + names = tuple(n.lower() for n in upper) if self.path == "/lower" else upper + self._send(204, b"", {names[0]: origin, names[1]: "true"}) +``` + +Then add a test block before `echo "== JSON output"` (the inner heredocs use `EOF` exactly like the existing plan files in this suite): + +```bash +echo "== exposure probes" +cat > "$WORK/exposure.json" < "$WORK/badexp.json" +probe --authorized "$WORK/badexp.json" >/dev/null 2>&1 +check "an error route not starting with / exits 2" "$?" 2 +printf '{"base_url": "%s", "exposure": []}\n' "$BASE" > "$WORK/badexp2.json" +probe --authorized "$WORK/badexp2.json" >/dev/null 2>&1 +check "a non-object exposure block exits 2" "$?" 2 +cat > "$WORK/lower.json" <&1 | grep -c ' FAIL '` +Expected: at least 9 (the sourcemap, error-body and fields rows are absent; lowercase CORS reads CLOSED; the two exit-2 checks get 1). + +- [ ] **Step 3: Patch `probe.py`** + +Imports: add `import re` and change the parse import to `from urllib.parse import quote, urljoin, urlsplit`. + +Replace `_response_from` and `fetch`: + +```python +def _headers(message): + return {k.lower(): v for k, v in message.items()} + + +def _error_body(exc): + try: + return exc.read(BODY_CAP) + except (OSError, ValueError, AttributeError): + return b"" + + +def _response_from(resp): + return Response(resp.status, _headers(resp.headers), resp.read(BODY_CAP)) + + +def fetch(session, method, url, headers=None, body=None): + if session.budget <= 0: + return Response(None, {}, b"", "request budget exhausted") + session.budget -= 1 + req = urllib.request.Request( + url, data=body, method=method, headers=headers or {}) + try: + with session.opener.open(req, timeout=session.timeout) as resp: + return _response_from(resp) + except urllib.error.HTTPError as exc: + return Response(exc.code, _headers(exc.headers), _error_body(exc)) + except (urllib.error.URLError, OSError, ValueError) as exc: + return Response(None, {}, b"", str(exc)) +``` + +In `_cors_open`: `headers.get("access-control-allow-origin", "")` and `headers.get("access-control-allow-credentials", "")`. + +Add the constants after `BODY_CAP`: + +```python +SCRIPT_CAP = 10 +SCRIPT_SRC = re.compile(rb"]+src=[\"']([^\"']+)[\"']", re.I) +MAP_COMMENT = re.compile(rb"//[#@]\s*sourceMappingURL=(\S+)") +TRACE_MARKERS = re.compile( + rb"Traceback \(most recent call last\)|\bat [\w.$<> ]+ \([^)\n]*:\d+:\d+\)" + rb"|File \"[^\"\n]+\", line \d+|SQLSTATE\[|syntax error at or near" + rb"|node_modules/|/var/www/|Stack trace:|#\d+ /[\w/.-]+\.php\(\d+\)") +SENSITIVE_KEY = re.compile( + r"password|passwd|pwd|hash|salt|secret|token|api_?key|service_?role" + r"|private|ssn|iban|cvv|card_?number", re.I) +``` + +Add the probes before `PROBES = (…)` and append `probe_exposure` to the tuple: + +```python +def _same_host(context, url): + """Absolute url when it stays on context's host, else None.""" + text = url.decode("utf-8", "ignore") if isinstance(url, bytes) else url + full = urljoin(context, text) + return full if urlsplit(full).netloc == urlsplit(context).netloc else None + + +def _script_urls(session, base, cfg): + listed = cfg.get("scripts") + if listed is None: + page = fetch(session, "GET", base + "/") + listed = [m.group(1) for m in SCRIPT_SRC.finditer(page.body)] + urls = [u for u in (_same_host(base + "/", s) for s in listed) if u] + return list(dict.fromkeys(urls))[:SCRIPT_CAP] + + +def _map_candidates(script_url, resp): + urls = [script_url + ".map"] + header = resp.headers.get("sourcemap") or resp.headers.get("x-sourcemap") + if header: + urls.append(header) + comment = MAP_COMMENT.search(resp.body[-600:]) + if comment: + urls.append(comment.group(1)) + return [u for u in (_same_host(script_url, u) for u in urls) if u] + + +def _map_served(resp): + return resp.status == 200 and b'"sources"' in resp.body + + +def _sourcemap_probe(session, script_url): + pid = f"sourcemap:{urlsplit(script_url).path}" + resp = fetch(session, "GET", script_url) + if resp.error: + return Probe("exposure", pid, "ERROR", script_url, resp.error) + served = next((u for u in dict.fromkeys(_map_candidates(script_url, resp)) + if _map_served(fetch(session, "GET", u))), None) + if served: + return Probe("exposure", pid, "OPEN", served, + "source map served with its sources") + return Probe("exposure", pid, "CLOSED", script_url, + "no source map served for this script") + + +def _error_probe(session, base, path): + target = base + path + resp = fetch(session, "GET", target) + return _verdict( + ("exposure", f"error-body:{path}", target), resp, + bool(TRACE_MARKERS.search(resp.body)), + ("error body carries a stack trace or an internal path", + "error body carries no trace marker")) + + +def _error_paths(cfg): + random_path = "/guardrails-probe-" + os.urandom(6).hex() + return [random_path] + list(cfg.get("error_routes") or []) + + +def _keys(data, depth=0): + if depth > 4: + return [] + if isinstance(data, dict): + found = [k for k in data if isinstance(k, str)] + for value in data.values(): + found += _keys(value, depth + 1) + return found + if isinstance(data, list): + found = [] + for value in data[:5]: + found += _keys(value, depth + 1) + return found + return [] + + +def _sensitive_keys(body): + try: + data = json.loads(body or b"null") + except ValueError: + return [] + return sorted({k for k in _keys(data) if SENSITIVE_KEY.search(k)}) + + +def _bearer(): + token = os.environ.get("GUARDRAILS_JWT2") + return {"Authorization": f"Bearer {token}"} if token else None + + +def _fields_probe(session, base, route): + target = base + route["path"] + resp = fetch(session, "GET", target, _bearer()) + keys = _sensitive_keys(resp.body) if resp.status == 200 else [] + return _verdict( + ("exposure", f"fields:{route['path']}", target), resp, bool(keys), + ("response carries sensitive keys: " + ", ".join(keys), + "no sensitive key in the response")) + + +def probe_exposure(session, plan): + cfg = plan.get("exposure") + if cfg is None: + return [] + base = plan["base_url"].rstrip("/") + out = [_sourcemap_probe(session, u) + for u in _script_urls(session, base, cfg)] + out += [_error_probe(session, base, p) for p in _error_paths(cfg)] + out += [_fields_probe(session, base, r) for r in plan.get("routes", [])] + return out + + +PROBES = (probe_supabase, probe_cross_user, probe_routes, + probe_cors, probe_rate_limit, probe_exposure) +``` + +Extend plan validation: + +```python +def _exposure_error(cfg): + if cfg is None: + return "" + if not isinstance(cfg, dict): + return "exposure must be an object" + for key in ("scripts", "error_routes"): + items = cfg.get(key) or [] + if not all(isinstance(i, str) for i in items): + return f"exposure.{key} must be a list of strings" + if any(not r.startswith("/") for r in cfg.get("error_routes") or []): + return "exposure.error_routes entries must start with /" + return "" + + +def _plan_error(plan): + method = plan.get("rate_limit", {}).get("method", "GET").upper() + if method not in READ_METHODS and method != "POST": + return f"rate_limit method {method} is not a probe method" + return _exposure_error(plan.get("exposure")) +``` + +Module docstring: after the `GUARDRAILS_JWT2` line add ` (also sent as bearer by the fields probe when set)`; in the first paragraph add the sentence `With an exposure block in the plan it also reads what the page's scripts, error bodies and JSON responses give away.` + +- [ ] **Step 4: Run the suite** + +Run: `make test suite=lib/tests/guardrails-probe.test.sh` +Expected: `failed: 0`, including the untouched `json reports the open count` = 4 (`plan.json` has no `exposure` block) and `the burst is capped` = 25. + +- [ ] **Step 5: Commit** + +```bash +git add skills/guardrails/scripts/probe.py lib/tests/guardrails-probe.test.sh +git commit -m "feat(guardrails): exposure probe (source maps served, error bodies, sensitive keys); fetch keeps error bodies, headers lowercased" +``` + +--- + +### Task 6: The `/a11y` skill: SKILL.md, references, prompts, lazy rule, routing row, profiles, locks + +**Files:** +- Create: `skills/a11y/SKILL.md`, `skills/a11y/references/checks.md`, `skills/a11y/test-prompts.json`, `rules/a11y.md` +- Modify: `mods/model-router/routing.json` (one row), `lib/profiles/{audit,dev,web,web-full,full,max}.profile`, `lib/tests/model-routing.test.sh`, `lib/tests/loops-light.test.sh`, `lib/verify-secure-loop.md:1`, `lib/contract-interview.md:117`, `agents/bugfixer.md:3` +- Test: `make test suite='lib/tests/effort-routing.test.sh lib/tests/profile-census.test.sh lib/tests/model-routing.test.sh lib/tests/loops-light.test.sh lib/tests/skill-routing-census.test.sh'` + +**Interfaces:** +- Consumes: `skills/a11y/scripts/scan.py` (Task 4), `lib/contract-interview.md` (flow `a11y`), `lib/verify-secure-loop.md`, the `bugfixer` agent. +- Produces: the public `/a11y` command, report `.claude/audits/A11Y.md`, branch `bugfix/a11y-`, baseline `.claude/audits/.a11y-baseline.json`. + +- [ ] **Step 1: Write `skills/a11y/SKILL.md`** + +The description is one single-quoted line. The seven locked sentences (`lib/contract-interview.md`, `lib/verify-secure-loop.md`, `subagent_type="bugfixer"`, `EXPECT: A11Y-CLEAR`, `Positive control`, `Nothing is applied without the user's explicit acceptance`, `A11Y-NO-NEW`) and `lib/model-gate.md` must each sit on one line, as below. + +````markdown +--- +name: a11y +effort: high +description: 'Use when a web project needs its accessibility baseline checked and fixed: everything reachable by keyboard with a visible focus, an alt on every image, a label on every field. Runs a deterministic scanner (A11Y-* rules: img alt, field label, click without keyboard, focus outline removed, positive tabindex), judges each hit, walks the main flow with Tab only on --live (through /browse, else marked not done), writes .claude/audits/A11Y.md, then proposes fixes with the alt and label wording as visible choices, applies only the ones the user accepts (bugfixer executor, fresh verifier and security gates, the scanner as oracle) and re-scans to prove each one. Triggers: "a11y", "accessibilité", "accessibility basics", "clavier", "focus visible", "alt manquant", "label sur les champs", "tab order", "corrige l''accessibilité". Full WCAG conformance (axe, pa11y, W3C) → /web-validate; security guardrails → /guardrails.' +argument-hint: '[project path] [--exclude paths] [--live ] [--report-only]' +--- + +# /a11y + +Checks a project's accessibility baseline (`rules/a11y.md`), then fixes what +the user accepts and proves each fix. A scanner reads the tree as data and +finds what text can prove: a missing alt, an unlabeled field, a click with no +keyboard path, a focus outline removed, a positive tabindex. This skill judges +the hits, walks the main flow with the keyboard when a browser is available, +proposes fixes, applies the accepted ones and scans again until every accepted +fix is proven. + +The scanner proves absence of a baseline, never presence of accessibility. A +clean scan means "no static finding", and the report says exactly that. Full +WCAG conformance (contrast, structure, ARIA semantics, axe or pa11y runs) is +`/web-validate`'s job. + +## MODEL GATE (blocking, before any other step) + +Run `$HOME/.claude/lib/model-gate.md`. Judging hits and writing alt and label +text requires Fable or Opus. Verdict `small` → STOP: the gate prints the +remedy. ROUTING: follow `$HOME/.claude/lib/effort-shift.md` (phases via +`mcp__model-router__route`); each step below names its phase. + +## STEP 1: Scope + +Work in the project the user names, else the current directory. Say in one +line what you will scan. `--report-only` stops after STEP 5: audit, no fix. + +## STEP 2: Run the scanner + +``` +python3 -B "$HOME/.claude/skills/a11y/scripts/scan.py" +``` + +Add `--exclude a/b,c` to skip copies or vendored code, `--json` for machine +output. Exit 0 means no FAIL, 1 means at least one, 2 is a usage error. It +never executes project code. Severities: **FAIL**, the baseline is provably +missing; **WARN**, a pattern that is often wrong, judgment needed. + +## STEP 3: Judge every FAIL and WARN + +Read the file around each line. Label it CONFIRMED, FALSE POSITIVE (say why) +or ACCEPTED RISK (the user decides, never you). A decorative image with +`alt=""`, a field labeled through `aria-labelledby`, a click handler on a +`role="presentation"` overlay and an outline swapped for a visible border or +ring are the usual false positives; `references/checks.md` lists the blind +spots. Check them before calling a hit false. + +## STEP 4: Keyboard walk (on `--live`, read-only) + +With a dev server the user names, walk the main flow with Tab only through +`/browse`: every control reached in a sensible order, the focus visible at +each stop, Enter and Space working on what looks clickable, Escape closing +what opened. Record each stop that fails with the page and the element. +Without a browser tool, or without `--live`, the report marks the walk +"not done": a static scan cannot see a keyboard trap, a focus order or a +modal that loses focus. + +## STEP 5: Report + +Write `.claude/audits/A11Y.md`: one table with status PASS, FAIL, WARN or +N/A per rule, the evidence, the fix in one line, and the keyboard walk's +result (done, with its stops, or not done). PASS means "no static finding". +Keep it short; no filler sections. `--report-only`, or nothing CONFIRMED: +reply with counts, the FAILs with file:line and the walk's stops, then stop. + +## STEP 6: Propose fixes + +`mcp__model-router__route(phase="plan")`: wording is the deepest thinking in +this run, it goes to the plan row. + +One proposal per CONFIRMED finding, grouped by rule and file; merge pairs +that one change closes (one `:focus-visible` rule closes every outline +removal in a stylesheet). FALSE POSITIVE and ACCEPTED RISK get no proposal. +Each proposal: + +- **number, rule, file(s)**, and the problem in one line; +- **the fix**, concrete: file:line and the change. A missing alt gets a + description of what the image shows, or `alt=""` when it is decorative; an + unlabeled field gets a `label for`, a wrapping label or `aria-label`; a + clickable `div` becomes a `button`, or gains `role`, `tabindex` and a key + handler; a removed outline gets a `:focus-visible` style; +- **choices the user sees**: the alt text and the label wording, each with + your proposed value, named so the user can change it. These are content, + never invented silently: they ship only with the user's acceptance; +- **risk**: what it can break (`button` reset styles, a changed tab order). + `DECISION` when no wording is defensible (an image you cannot describe); +- **proof**: the scanner pairs that must disappear (`RULE:path`), and the + walk stop that must pass when `--live` ran. + +Save the proposals to `.claude/tasks/plans/-a11y-.md` and +append them to the report. In the reply, show them as a numbered list, one or +two lines each, DECISION marked. + +## STEP 7: Approval (gate, ends the turn) + +Nothing is applied without the user's explicit acceptance. Ask once, then +stop the turn: + +``` +Which fixes do I apply? "all" (every proposal except DECISION ones), +numbers ("1,3,5-7"), "none", or an amendment ("2 with the alt 'Team photo'"). +A DECISION proposal needs its number plus your wording. +``` + +On resume, `mcp__model-router__route(phase="reflect")`. "none" → stop, +proposals stay in the report. An amendment rewrites that proposal in the plan +file before anything else. Accepted set empty → stop. + +## STEP 8: Apply + +1. **Branch.** Not a git repository → stop: fixes need a diff to review. + On `main`/`develop`, `bash ~/.claude/lib/gitflow.sh start bugfix + a11y-`; on a working branch, stay. Never `finish`. +2. **Baseline**, before any edit: + `python3 -B --json > .claude/audits/.a11y-baseline.json`. + A derived file: never staged, never committed. +3. **Contract** per `$HOME/.claude/lib/contract-interview.md` (STEP 4 + template, `flow: a11y`). REQUEST = the user's acceptance verbatim plus the + accepted proposals. One criterion per accepted proposal, its oracle the + scanner itself: + ``` + 1. + CHECK: python3 -B "$HOME/.claude/skills/a11y/scripts/scan.py" '' --assert-absent 'RULE:path,RULE:path' + EXPECT: A11Y-CLEAR + EVIDENCE: pending + ``` + Add one criterion for the project suite when one exists + (`CHECK: && echo TESTS-GREEN`, `EXPECT: TESTS-GREEN`). The + keyboard walk is a criterion without CHECK: STEP 9 settles it. FILE SCOPE + = the files the accepted proposals name. Paths go in single quotes; a path + holding a single quote is named to the user, never written into a CHECK. +4. **Positive control.** Run each oracle once on the unfixed tree: it must + fail. An oracle that passes before the fix proves nothing; drop it, find + why, and say so. +5. **Dispatch the executor**, one fresh `bugfixer` for the accepted set + (batches of 8 proposals at most, one after the other on the same branch): + ``` + mcp__model-router__route(phase="orchestrate") # send with the Agent call + Agent(subagent_type="bugfixer") + prompt: "CONTRACT: + DIAGNOSIS: + FIX PLAN: + BRANCH: + Apply to the letter. No commit, no branch ops, no security dispatch. + Finish with the BUGFIX-EXEC REPORT." + ``` + `NEED-DECISION` routes per MID-RUN CLARIFICATION of the contract include: + a wording, visible or scope question goes to the user verbatim. + `BLOCKED` → surface it, stop. +6. **Gates** per `$HOME/.claude/lib/verify-secure-loop.md`, `CONTRACT` the + path above, `DIFF` the executor's working-tree diff, `TEST` the suite. + GATE 0 runs every scanner oracle (the per-fix proof), GATE 1 a fresh + verifier, GATE 2 a fresh security-auditor. Loop caps and escalation are + the include's; loop decisions stay in this main loop. + +## STEP 9: Re-pass (prove it all) + +`mcp__model-router__route(phase="reflect")`. The gates proved each accepted +fix on its own; this pass proves the whole tree. + +1. Full scan against the baseline: + ``` + python3 -B --baseline .claude/audits/.a11y-baseline.json + ``` + Every accepted pair must show `FIXED`, and the run must end on + `A11Y-NO-NEW` (exit 0). A `NEW` hit is a regression the fix made. +2. Live: when STEP 4 ran, walk the same flow again once the user has reloaded + the dev server and says go. Each stop a proposal named must now pass. +3. Add an "after" column to `.claude/audits/A11Y.md`: proposal, before, + after, evidence. + +Anything not fixed, or a NEW hit → one more round from STEP 6, limited to +those items. Two rounds at most: after the second, stop with the residuals +open and say so plainly. Never report a fix the re-pass did not prove. + +## STEP 10: Commit and hand over + +1. **Commit gate.** Show files, `git diff --stat` and the message, wait for + the user's go: + ``` + A11Y: READY TO COMMIT + FILES : + MESSAGE : fix(a11y): + ``` + Then `git add ` (never `-A`, never the baseline file) and + commit, project convention else 50 words at most. +2. `mcp__model-router__route(phase="apply")` for the tail. Reply with: fixed + and proven (proposal, rule, file), still open and why, the walk's result, + the branch name. Merge waits for the user's explicit signal. +3. Offer to capitalize a reusable lesson (a false-positive class, a fix + pattern), entry pre-filled, written only on approval. +```` + +Measure the description: `awk 'NR==4' skills/a11y/SKILL.md | sed 's/^description: //' | wc -c` must print 1024 or less. + +- [ ] **Step 2: Write `skills/a11y/references/checks.md`** + +```markdown +# Accessibility checks + +Rule ids the scanner emits, what each proves, and the fix. Severity is the +default; a judged hit can be a false positive. + +| Rule | Sev | Catches | Fix | +|---|---|---|---| +| A11Y-IMG-ALT | FAIL | `img` or `Image` without `alt` | describe it, or `alt=""` if decorative | +| A11Y-FIELD-LABEL | FAIL | native input, select, textarea with no label | `label for`, wrapping label or `aria-label` | +| A11Y-CLICK-NO-KEYBOARD | FAIL | click handler on a div or span lacking role, tabindex or key handler | use a `button` | +| A11Y-FOCUS-OUTLINE | FAIL / WARN | focus outline removed; WARN when a `:focus-visible` style exists elsewhere | style `:focus-visible` instead | +| A11Y-TABINDEX-POSITIVE | WARN | `tabindex` above 0 | use 0 or -1 and fix the DOM order | + +## Blind spots + +The scanner is regex over markup and styles. It cannot see: + +- keyboard traps, focus order, a modal that keeps or loses focus, color + contrast: the `--live` walk covers the first three, `/web-validate` the + fourth +- a label wired through `aria-labelledby` to an element in another file +- components whose markup is built at runtime, minified bundles, anything + over 1 MB +- `.astro` files for the click rule (never flagged) + +By design the scanner ignores: fields that are never rendered (`hidden`, +`display: none`), click handlers that only stop propagation or sit on +`role="presentation"`, focus styles that swap the outline for a border or +shadow, and `img` tags inside comments. + +## Fix loop: oracles and re-pass + +Every accepted fix is proven by the scanner itself, never by the executor's +word. Two check modes replace the report and its exit code: + +| Mode | Passes when | Marker | Used by | +|---|---|---|---| +| `--assert-absent RULE:path,...` | none of these FAIL/WARN pairs remains, the domain was scanned, the tree is not empty | `A11Y-CLEAR ` | a contract `CHECK:` run by `lib/gates.sh` (GATE 0) | +| `--baseline before.json` | no FAIL/WARN hit appeared since the earlier `--json` run | `A11Y-NO-NEW` | STEP 9 re-pass | + +Pairs match on rule and file, not line: a fix moves lines. An empty tree +fails the assertion, because absence there proves nothing. Run every oracle +once before the fix: it must fail. The baseline lists `FIXED` and `NEW` +pairs with their hit counts; a `NEW` hit after a fix is a regression. +``` + +- [ ] **Step 3: Write `skills/a11y/test-prompts.json`** + +```json +[ + {"id": 1, "prompt": "vérifie l'accessibilité de base de ~/Documents/faunosteo : clavier, alt, labels", "expected": "Runs the a11y scanner on the path, reads each A11Y FAIL and WARN in context, marks the keyboard walk not done (no --live), writes .claude/audits/A11Y.md, proposes fixes with alt and label wording as visible choices, stops for approval"}, + {"id": 2, "prompt": "il manque des alt sur les images du site, corrige", "expected": "Scans, confirms each A11Y-IMG-ALT hit, proposes one alt text per image (or alt=\"\" for decorative ones) as a named choice, applies only after acceptance on a bugfix branch with --assert-absent oracles, re-scans against the baseline"}, + {"id": 3, "prompt": "Walk my app at http://localhost:3000 with the keyboard only and tell me where focus gets lost", "expected": "Static scan first, then the Tab walk through /browse on the named localhost target, records each stop with no visible focus or unreachable control, reports them next to the static findings, fixes nothing without approval"}, + {"id": 4, "prompt": "est-ce que mon site passe les critères WCAG AA ?", "expected": "Routes to /web-validate for WCAG conformance; runs /a11y only if the user asks for the keyboard/alt/label baseline"}, + {"id": 5, "prompt": "a11y --report-only sur ce projet", "expected": "Scan and judgment only, report written, counts and file:line in the reply, no proposal, no branch, no edit"} +] +``` + +- [ ] **Step 4: Write `rules/a11y.md`** + +```markdown +--- +paths: ["**/*.tsx", "**/*.jsx", "**/*.vue", "**/*.svelte", "**/*.astro", "**/*.html", "**/*.css", "**/*.scss"] +--- + +# Accessibility baseline (audit and fix: `/a11y`) + +- Everything reachable and usable by keyboard, focus always visible. + `:focus-visible` styled, never `outline: none` without a replacement. +- Every image has an `alt` (empty when decorative). Every field has a label; + a placeholder is not a label. +``` + +- [ ] **Step 5: Add the routing row without sweeping the pre-existing hunks** + +```bash +git status --short mods/model-router/routing.json settings.json +``` + +If either file shows `M`, stash those two files first (and only them): + +```bash +git stash push -m "pre-existing: routing dialog decisions + settings env key" -- mods/model-router/routing.json settings.json +``` + +Then in `mods/model-router/routing.json`, in the `skills` block, add the line ` "a11y": "reflect",` right after ` "guardrails": "reflect",`. Validate: `python3 -I -c 'import json; json.load(open("mods/model-router/routing.json"))'`. + +```bash +git add mods/model-router/routing.json +git commit -m "chore(model-router): a11y skill row (reflect)" +git stash pop +git status --short mods/model-router/routing.json settings.json +``` + +The last status must show both files `M` again (the pre-existing diffs restored) and `git stash list` must be empty. A pop conflict means the a11y line sits next to a dialog hunk: keep both, `git add` nothing, continue. + +- [ ] **Step 6: Profiles, locks and flow enums** + +1. In `lib/profiles/audit.profile`, `dev.profile`, `web-full.profile`, `full.profile`, `max.profile`: add the line `a11y personal` right after the `guardrails …personal` line. In `lib/profiles/web.profile`: add it right after the `web-validate …personal` line. The name column is 34 characters wide: `a11y` plus 30 spaces. +2. `lib/tests/model-routing.test.sh`: add `a11y` at the end of the `for s in ship-feature … guardrails; do` list and change the comment to `# 1) gate wired in the 17 reflection skills (orchestrators, /analyze, /guardrails, /a11y)`. +3. `lib/tests/loops-light.test.sh`: find how `GSK` is defined near the top (`GSK="$R/skills/guardrails/SKILL.md"` or similar) and define `ASK` the same way for `skills/a11y/SKILL.md`. After the guardrails block add: + ```bash + echo "── skills/a11y/SKILL.md (fix loop reuses the bugfix circuit) ──" + tf "a11y contract include" "$ASK" "lib/contract-interview.md" + tf "a11y uses shared include" "$ASK" "lib/verify-secure-loop.md" + tf "a11y dispatches bugfixer" "$ASK" 'subagent_type="bugfixer"' + tf "a11y scanner is the oracle" "$ASK" "EXPECT: A11Y-CLEAR" + tf "a11y positive control" "$ASK" "Positive control" + tf "a11y approval gate" "$ASK" "Nothing is applied without the user's explicit acceptance" + tf "a11y re-pass baseline" "$ASK" "A11Y-NO-NEW" + ``` +4. `lib/verify-secure-loop.md` line 1: `(feat, bugfix, guardrails)` → `(feat, bugfix, guardrails, a11y)`. +5. `lib/contract-interview.md` line 117: `…|onboard|guardrails>` → `…|onboard|guardrails|a11y>`. +6. `agents/bugfixer.md` line 3: `dispatched by /bugfix (or /guardrails for accepted fixes)` → `dispatched by /bugfix (or /guardrails and /a11y for accepted fixes)`. + +- [ ] **Step 7: Run the censuses** + +Run: `make test suite='lib/tests/effort-routing.test.sh lib/tests/profile-census.test.sh lib/tests/model-routing.test.sh lib/tests/loops-light.test.sh lib/tests/skill-routing-census.test.sh'` +Expected: `all suites green`. A skill-routing WARN naming `a11y~web-validate` above 0.50 means the two descriptions still read alike: trim shared words from the a11y description (never from web-validate's, Task 8 handles that file) and re-measure. + +- [ ] **Step 8: Commit** + +```bash +git add skills/a11y/SKILL.md skills/a11y/references/checks.md skills/a11y/test-prompts.json rules/a11y.md lib/profiles/audit.profile lib/profiles/dev.profile lib/profiles/web.profile lib/profiles/web-full.profile lib/profiles/full.profile lib/profiles/max.profile lib/tests/model-routing.test.sh lib/tests/loops-light.test.sh lib/verify-secure-loop.md lib/contract-interview.md agents/bugfixer.md +git commit -m "feat(a11y): skill (scan, keyboard walk, report, fix loop on the bugfix circuit), lazy rules/a11y.md, profiles, locks" +``` + +--- + +### Task 7: `/guardrails` skill text, reference, prompts and the secure-by-default rule + +**Files:** +- Modify: `skills/guardrails/SKILL.md`, `skills/guardrails/references/checks.md`, `skills/guardrails/test-prompts.json`, `rules/secure-by-default.md` +- Test: `make test suite='lib/tests/loops-light.test.sh lib/tests/model-routing.test.sh lib/tests/skill-routing-census.test.sh lib/tests/doctrine-citers.test.sh'` + +- [ ] **Step 1: `skills/guardrails/SKILL.md` frontmatter** + +Replace the `description:` line with this single-quoted line (then measure it: `awk 'NR==4' skills/guardrails/SKILL.md | sed 's/^description: //' | wc -c` ≤ 1024): + +``` +description: 'Use when auditing a project against the baseline guardrails and fixing what fails: hosting (rate limit, CDN and firewall, spend cap), Supabase (RLS on every table, owner-scoped policies, no service_role key client-side), SMS and email (recorded consent, unsubscribe, STOP), cloud functions (no self-trigger, instance cap, budget stop), injection (SQL built from input, raw escapes, NoSQL operators, shell into DB tools), exposure (console data, source maps, hydrated state, error bodies, debug mode, wide responses), plus API hygiene (auth on every route, CORS, secrets, password storage). Deterministic scanner, judgment, .claude/audits/GUARDRAILS.md, then fixes applied only on acceptance (bugfixer, fresh verifier and security gates) and re-scanned to prove them; optional read-only live probe on a target the user owns. Triggers: "guardrails", "garde-fous", "RLS activée ?", "faille sql", "injection", "qu''est-ce qui fuit dans le navigateur", "plafond de dépense", "mots de passe en clair ?", "corrige les garde-fous", "sonde le projet en direct". Headers and TLS → /harden; secrets, CVE, dependencies → /cso; keyboard, alt, labels → /a11y.' +``` + +`argument-hint`: `'[project path] [--domain api,hosting,supabase,messaging,functions,injection,exposure] [--exclude paths] [--live ] [--report-only]'`. + +- [ ] **Step 2: `skills/guardrails/SKILL.md` body** + +1. STEP 1: `Domains: \`api\`, \`hosting\`, \`a11y\`, \`supabase\`, \`messaging\`, \`functions\`.` → `Domains: \`api\`, \`hosting\`, \`supabase\`, \`messaging\`, \`functions\`, \`injection\`, \`exposure\`.` +2. STEP 4: replace the `- **A11y**: …` bullet (two lines) with: + ``` + - **Injection**: for each INJ hit, trace the interpolated value to its + source. A constant, an allowlisted identifier or a value already cast to + a number is a FALSE POSITIVE; anything that can come from a request, + a file or another user's row is CONFIRMED. + - **Exposure**: open the main page in a browser and read what the console, + the network responses and the DOM carry: a token in a `data-*` + attribute, a user object logged, a full row in an API answer. With + `--live`, the probe answers for served source maps, error bodies and + sensitive keys; the rest is read by hand. + ``` +3. STEP 5.1: after `and a \`rate_limit\` route if the user wants that one burst.` add the sentence `Add an \`exposure\` block (\`{}\` for the defaults, \`error_routes\` for a route you own that answers an error to a malformed id, never a path you guess) so the probe reads source maps, error bodies and response keys.` +4. STEP 8 proposal examples: `the label text for a field.` → `the parameter binding for a query.`; `(label wording, CORS origins, owner column,\n rate-limit numbers)` → `(allowlisted filter fields, CORS origins, owner column,\n rate-limit numbers)`. +5. STEP 9 example: `("2 with the label 'Email'")` → `("2 with the fields ['id','status']")`. + +Every locked sentence from loops-light stays untouched and on one line. + +- [ ] **Step 3: `skills/guardrails/references/checks.md`** + +1. Delete the `## a11y` section (heading and table). +2. Add after the `## hosting` section: + ```markdown + ## injection + + | Rule | Sev | Catches | Fix | + |---|---|---|---| + | INJ-SQL-RAW-UNSAFE | FAIL | `$queryRawUnsafe`, `$executeRawUnsafe`, `knex.raw`, `.raw()`, `.extra()`, `sequelize.query`, `Sequelize.literal`, SQLAlchemy `text()` fed a variable; ActiveRecord `where("… #{}")` | bind the values, or the tagged `$queryRaw` | + | INJ-SQL-CONCAT | FAIL | a SQL statement string built with `${}`, `+`, an f-string, `%`, `.format`, PHP `$var`, Ruby `#{}`, `format!`, `Sprintf` | placeholders and a parameter list | + | INJ-SQL-DYNAMIC-EXEC | WARN | plpgsql `EXECUTE '…' \|\| x` | `format('… %I %L', …)` and `USING` | + | INJ-POSTGREST-FILTER | WARN | supabase-js `.or()`, `.filter()`, `.not()`, `.match()`, `.textSearch()` with an interpolated string | `.eq()` and friends, validated values | + | INJ-NOSQL-OPERATOR | WARN | Mongo `$where` with a string; a filter taken from `req.body`, `req.query` or `req.params` | allowlist the fields, cast to string, `sanitizeFilter` | + | INJ-SHELL-DB-TOOL | FAIL | a shell call naming psql, mysql, mysqldump, pg_dump, mongosh, redis-cli, sqlite3… with an interpolated argument | an argv array, no shell, validated input | + + ## exposure + + | Rule | Sev | Catches | Fix | + |---|---|---|---| + | EXP-CONSOLE-DATA | WARN | `console.log/info/debug/dir/table` in client-reachable code with a data argument (user, session, response, token, body…) | strip console calls in the production build, log server-side | + | EXP-SOURCEMAP-PUBLIC | FAIL / WARN | `productionBrowserSourceMaps: true`, vite `sourcemap: true`, `GENERATE_SOURCEMAP=true`, webpack `devtool` readable maps (FAIL in `webpack.prod*`, WARN elsewhere), a `.map` under `public/`; angular `sourceMap: true` (WARN) | off, or `hidden` and upload to the error tracker | + | EXP-HYDRATED-SENSITIVE | WARN | a token, secret, key, password or ssn-like key returned by `getServerSideProps`, `getStaticProps`, a Remix `loader`, a SvelteKit `load` or set on `window.__STATE__` | return only the fields the page renders | + | EXP-MARKUP-COMMENT | WARN | `` shipped to the browser (html, astro, php, ejs, hbs, twig, njk, liquid) with todo, fixme, debug, password, token, internal, staging, admin… | delete it, or move it to a code comment the build strips | + | EXP-DATA-ATTR-SENSITIVE | WARN | `data-*` attribute or hidden input named secret, api-key, password, jwt, private, credential (csrf excluded) | keep it server-side, send an opaque id | + | EXP-ERROR-STACK | FAIL | `err.stack`, the error object, `traceback.format_exc()` or `getTraceAsString()` in a response | generic message out, full error in the server log | + | EXP-ERROR-MESSAGE | WARN | `err.message`, `str(e)`, `$e->getMessage()` sent as is | map to a safe message; validation errors are fine, DB errors are not | + | EXP-DEBUG-ON | FAIL | `DEBUG = True`, `APP_DEBUG=true`, `FLASK_DEBUG=1`, `app.debug = True`, `consider_all_requests_local = true`, `errorhandler()` | env-driven, false in production | + | EXP-RESPONSE-WIDE | WARN | a route returning `select *` / `select('*')` / `findUnique` without `select` or `omit` on a users-like table | an explicit field list | + ``` +3. Blind spots list: replace `- keyboard traps, focus order, modal focus handling, color contrast` with + ``` + - a SQL string assembled across several lines, or passed through a + variable before the query call (trace it by hand) + - whether a template literal's tag parameterizes: tagged templates are + trusted + - built output (`dist/`, `.next/`) and runtime state such as + `__NEXT_DATA__`: only the live probe sees a served map or a hydrated + token + - what the console or an XHR carries once the page runs: a browser walk + ``` +4. "By design the scanner ignores" paragraph: remove `fields that are never rendered (\`hidden\`, \`display: none\`), click handlers that only stop propagation or sit on \`role="presentation"\`, focus styles that swap the outline for a border or shadow, ` and append `, tagged SQL templates, placeholders with a separate parameter list, an argv array handed to a DB tool, console calls in server code, \`sourcemap: 'hidden'\`, a debug flag read from the environment, and a hidden input named csrf, xsrf, authenticity or nonce` before the final period. +5. Live probe section: in the plan JSON example add, before the closing brace, `,\n "exposure": {"error_routes": ["/api/v1/notes/not-a-number"]}`; after the `Environment, from test keys only…` sentence add `The fields probe sends \`GUARDRAILS_JWT2\` as a bearer when it is set.`; add three rows to the probe table: + ``` + | sourcemap | `sourcemap: