Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(witness): turn a visitor's bug report into a failing Playwright spec
nirholasefdef8f3665c
diff --git a/api/_lib/feedback/store.js b/api/_lib/feedback/store.jsindex d14f21b3b..0986be417 100644--- a/api/_lib/feedback/store.js+++ b/api/_lib/feedback/store.js@@ -35,8 +35,66 @@ function clampList(value, { max = 5, length = 400 } = {}) {.filter(Boolean);}+// A trace is machine-written, so it is validated by SHAPE rather than trusted+// by origin: anyone can POST to the report endpoint. Anything past these caps+// is a client that is broken or lying, and either way the row must stay small+// enough to read. Values a person typed are never in here by construction+// (packages/witness/src/redact.js), so there is nothing to strip, only to bound.+const MAX_TRACE_EVENTS = 80;+const TRACE_EVENT_TYPES = new Set([+ 'goto', 'navigate', 'click', 'fill', 'check', 'select', 'submit', 'key', 'xhr', 'error', 'rejection', 'resource',+]);++export function normalizeTrace(raw) {+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.events)) return null;+ const events = [];+ for (const event of raw.events.slice(0, MAX_TRACE_EVENTS)) {+ if (!event || typeof event !== 'object') continue;+ if (!TRACE_EVENT_TYPES.has(event.type)) continue;+ const out = { type: event.type };+ const detail = clampText(event.detail, 300);+ if (detail) out.detail = detail;+ if (Number.isInteger(event.count) && event.count > 1) out.count = Math.min(event.count, 9999);+ if (event.fatal === true) out.fatal = true;+ if (event.el && typeof event.el === 'object') {+ out.el = {+ tag: clampText(event.el.tag, 20),+ strategy: clampText(event.el.strategy, 20),+ value: clampText(event.el.value, 200),+ css: clampText(event.el.css, 300),+ role: clampText(event.el.role, 40),+ name: clampText(event.el.name, 120),+ attr: clampText(event.el.attr, 40),+ confidence: Number.isFinite(event.el.confidence) ? Math.max(0, Math.min(100, Math.round(event.el.confidence))) : null,+ };+ }+ events.push(out);+ }+ if (!events.length) return null;+ const env = raw.environment && typeof raw.environment === 'object' ? raw.environment : {};+ const viewport = env.viewport && typeof env.viewport === 'object' ? env.viewport : {};+ return {+ version: 1,+ environment: {+ url: clampText(env.url, 300),+ locale: clampText(env.locale, 40),+ userAgent: clampText(env.userAgent, 300),+ touch: env.touch === true,+ reducedMotion: env.reducedMotion === true,+ viewport: {+ width: Number.isFinite(viewport.width) ? Math.round(viewport.width) : null,+ height: Number.isFinite(viewport.height) ? Math.round(viewport.height) : null,+ dpr: Number.isFinite(viewport.dpr) ? Number(viewport.dpr.toFixed(2)) : null,+ },+ },+ recordedMs: Number.isFinite(raw.recordedMs) ? Math.max(0, Math.round(raw.recordedMs)) : 0,+ events,+ };+}+export function normalizeReport(input = {}) {return {+ trace: normalizeTrace(input.trace),body: clampText(input.body, 4000),transport: input.transport === 'voice' ? 'voice' : 'text',route: clampText(input.route, 300),@@ -50,20 +108,35 @@ export function normalizeReport(input = {}) {}export async function insertReport({ userId = null, clientKey = null, userAgent = null, report }) {+ // The two trace summaries are denormalized on write so the queue can rank by+ // "is this replayable" without opening every document.+ const summary = report.trace ? summarizeTrace(report.trace) : { steps: null, confidence: null };const [row] = await sql`insert into feedback_reports(user_id, client_key, body, transport, route, page_title, build_sha,- viewport, user_agent, locale, console_errors, failed_requests)+ viewport, user_agent, locale, console_errors, failed_requests,+ trace, trace_steps, replay_confidence)values (${userId}, ${clientKey}, ${report.body}, ${report.transport}, ${report.route},${report.page_title}, ${report.build_sha}, ${report.viewport},${clampText(userAgent, 400)}, ${report.locale},${JSON.stringify(report.console_errors)}::jsonb,- ${JSON.stringify(report.failed_requests)}::jsonb)+ ${JSON.stringify(report.failed_requests)}::jsonb,+ ${report.trace ? JSON.stringify(report.trace) : null}::jsonb,+ ${summary.steps}, ${summary.confidence})returning id, created_at`;return row || null;}+/** How many replayable steps a trace holds, and how well its weakest step is anchored. */+export function summarizeTrace(trace) {+ const events = trace?.events || [];+ const actions = events.filter((e) => ['click', 'fill', 'check', 'select', 'submit', 'key', 'navigate'].includes(e.type));+ const described = actions.filter((e) => e.el && Number.isFinite(e.el.confidence));+ const confidence = described.length ? Math.min(...described.map((e) => e.el.confidence)) : null;+ return { steps: Math.min(actions.length, 32767), confidence };+}+export async function untriagedReports(limit = 20) {return sql`select id, body, transport, route, page_title, build_sha, viewport, locale,@@ -118,6 +191,8 @@ export async function listClusters({ status = 'open', limit = 50 } = {}) {(array_agg(route order by created_at desc))[1] as route,(array_agg(build_sha order by created_at desc))[1] as build_sha,(array_agg(id order by created_at desc))[1] as latest_id,+ max(replay_confidence) as replay_confidence,+ count(*) filter (where trace is not null)::int as traced,count(distinct coalesce(user_id::text, client_key))::int as reportersfrom feedback_reportswhere true ${statusClause}@@ -138,6 +213,7 @@ export async function listReports({ clusterKey = null, limit = 50 } = {}) {select id, body, transport, route, page_title, build_sha, viewport, locale,console_errors, failed_requests, status, severity, kind, subsystem,summary, repro, cluster_key, resolution, created_at, triaged_at, resolved_at,+ trace, trace_steps, replay_confidence,user_id is not null as signed_infrom feedback_reportswhere true ${clusterClause}@@ -159,6 +235,16 @@ export function targetFromClusterKey(clusterKey) {return isUuid(id) ? { id } : {};}+/** One report with its full trace, for the repro compiler. */+export async function reportWithTrace(id) {+ const [row] = await sql`+ select id, body, summary, route, build_sha, trace, trace_steps, replay_confidence, created_at+ from feedback_reports+ where id = ${id}+ `;+ return row || null;+}+export async function setStatus({ id = null, clusterKey = null, status, resolution = null }) {if (!STATUSES.includes(status)) return 0;const closing = status === 'fixed' || status === 'dismissed';diff --git a/api/_lib/migrations/20260828190000_feedback_witness_trace.sql b/api/_lib/migrations/20260828190000_feedback_witness_trace.sqlnew file mode 100644index 000000000..d899b86a8--- /dev/null+++ b/api/_lib/migrations/20260828190000_feedback_witness_trace.sql@@ -0,0 +1,34 @@+begin;++-- The witness trace: what the person actually did, in order, before it broke.+--+-- Stored beside the report rather than in it, because the two have different+-- lifetimes and different sensitivities. The body is a sentence a human wrote;+-- the trace is a machine record that compiles into a runnable test+-- (packages/witness). Keeping it as jsonb means a maintainer can query across+-- traces ("every report whose trace contains a 500 from /api/export") without+-- parsing anything.+--+-- Values a person typed are never in here: the recorder counts characters and+-- keeps the shape, never the text (packages/witness/src/redact.js).++alter table feedback_reports+ add column if not exists trace jsonb,+ -- Denormalized from the trace so the queue can sort and filter on them+ -- without opening every document.+ add column if not exists trace_steps smallint,+ add column if not exists replay_confidence smallint;++-- Reports that carry a replayable trace are the ones worth reaching for first,+-- so the queue can find them without scanning.+create index if not exists feedback_reports_traced_idx+ on feedback_reports (replay_confidence desc nulls last, created_at desc)+ where trace is not null;++-- Cross-report search over the failures a trace recorded, which is what turns+-- "someone said export is broken" into "eleven sessions hit POST /api/export".+create index if not exists feedback_reports_trace_gin_idx+ on feedback_reports using gin (trace jsonb_path_ops)+ where trace is not null;++commit;diff --git a/api/_lib/oauth-scopes.js b/api/_lib/oauth-scopes.jsindex 386301d4f..fa1261509 100644--- a/api/_lib/oauth-scopes.js+++ b/api/_lib/oauth-scopes.js@@ -34,6 +34,12 @@ export const REGISTERABLE_SCOPES = Object.freeze([// On-chain agent identity MCP tools (register_agent / identity_check).'agents:read','agents:write',+ // Visitor feedback MCP tools (list_feedback / get_feedback_repro). Read-only+ // by design: the tools behind it compile a reported session into a failing+ // test and can change nothing (api/_mcp/tools/feedback.js). The handlers also+ // require an admin account, so granting this scope to a non-admin authorizes+ // nothing extra.+ 'feedback:read',// The wallet/services scopes gate the agent-wallet MCP server// (api/mcp-agent). They are registerable because the user approves each one// by name on the consent screen and every spend they authorize is stilldiff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.jsindex a7cbcd5c0..8c206d9f0 100644--- a/api/_mcp/catalog.js+++ b/api/_mcp/catalog.js@@ -17,6 +17,7 @@ import { toolDefs as tokenizeDefs } from './tools/tokenize.js';import { toolDefs as cryptoDataDefs } from './tools/crypto-data.js';import { toolDefs as garmentDefs } from './tools/garments.js';import { toolDefs as signDefs } from './tools/sign.js';+import { toolDefs as feedbackDefs } from './tools/feedback.js';const baseDefs = [...avatarDefs,@@ -33,6 +34,7 @@ const baseDefs = [...tokenizeDefs,...cryptoDataDefs,...garmentDefs,+ ...feedbackDefs,];// Free, public entry point — listed first so discovery clients see it up top.diff --git a/api/_mcp/tools/feedback.js b/api/_mcp/tools/feedback.jsnew file mode 100644index 000000000..5d9ecab5e--- /dev/null+++ b/api/_mcp/tools/feedback.js@@ -0,0 +1,149 @@+// MCP feedback tools: read the queue, and compile a report into a failing test.+//+// This is the agent-facing end of the loop that starts when a visitor tells the+// corner companion something is broken. An agent connected to /api/mcp can ask+// what is broken, then ask for the reproduction, and what comes back is not a+// description of the bug but a Playwright spec that fails while the bug exists.+// That is the difference between an agent that reads a bug report and an agent+// that can verify it fixed one.+//+// The boundary from docs/feedback.md holds here exactly as it does everywhere+// else: these tools are READ-ONLY. A feedback body is untrusted text typed by+// anyone on the internet, so nothing an agent reads through this surface can+// change a status, edit the product, or trigger any write. An agent that wants+// to act on a report opens a pull request a human merges.++import { sql } from '../../_lib/db.js';+import { isAdminUser } from '../../_lib/admin.js';+import { compileToPlaywright, narrate, replayConfidence } from '../../../packages/witness/src/compile.js';++const BASE_URL = process.env.WITNESS_REPRO_BASE_URL || 'https://three.ws';++// The queue exposes raw visitor text and internal route topology, so it is held+// to the same admin gate the /feedback page and the REST endpoints use. A+// pay-per-call x402 principal has no account at all and is refused here.+async function requireAdminAuth(auth) {+ if (!auth?.userId) return null;+ const [user] = await sql`select id, wallet_address, is_admin from users where id = ${auth.userId}`;+ if (!user) return null;+ return (await isAdminUser(user)) ? user : null;+}++function refusal() {+ return {+ content: [+ {+ type: 'text',+ text: 'The feedback queue is limited to platform admins. Connect with a three.ws admin account over OAuth.',+ },+ ],+ isError: true,+ };+}++function asText(value) {+ return { content: [{ type: 'text', text: value }] };+}++export const toolDefs = [+ {+ name: 'list_feedback',+ title: 'List feedback',+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ description:+ 'What visitors reported is broken, grouped into one row per distinct problem, loudest first. Each row carries the severity, the subsystem, how many people hit it, and whether a recorded session exists that can be compiled into a failing test with get_feedback_repro. Admin only.',+ inputSchema: {+ type: 'object',+ properties: {+ status: {+ type: 'string',+ enum: ['open', 'new', 'triaged', 'accepted', 'dismissed', 'fixed', 'all'],+ default: 'open',+ },+ replayable_only: {+ type: 'boolean',+ default: false,+ description: 'Only clusters that carry a recorded session, which are the ones an agent can verify a fix against.',+ },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },+ },+ additionalProperties: false,+ },+ scope: 'feedback:read',+ async handler(args, auth) {+ if (!(await requireAdminAuth(auth))) return refusal();+ const { listClusters } = await import('../../_lib/feedback/store.js');+ const clusters = await listClusters({ status: args.status || 'open', limit: args.limit || 20 });+ const rows = args.replayable_only ? clusters.filter((c) => c.traced > 0) : clusters;+ if (!rows.length) {+ return asText(+ args.replayable_only+ ? 'No open reports carry a recorded session yet.'+ : 'Nothing open. No unresolved feedback in the queue.',+ );+ }+ const lines = rows.map((c) => {+ const bits = [+ `severity ${c.severity ?? 0}`,+ `${c.reports} report(s) from ${c.reporters} person/people`,+ c.subsystem || 'unknown subsystem',+ c.route || '',+ c.traced > 0 ? `replayable (confidence ${c.replay_confidence ?? 0}/100, latest ${c.latest_id})` : 'no recorded session',+ ].filter(Boolean);+ return `- ${c.summary || '(no summary yet)'}\n ${bits.join(' | ')}\n cluster: ${c.cluster_key}`;+ });+ return asText(`${rows.length} cluster(s):\n\n${lines.join('\n\n')}`);+ },+ },+ {+ name: 'get_feedback_repro',+ title: 'Compile a feedback report into a failing test',+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ description:+ 'Compile one feedback report into a runnable Playwright spec from the session the visitor actually recorded. The spec asserts the reported failure is GONE, so it is red while the bug exists and green once it is fixed: use it to reproduce the bug before changing anything, and to prove the change worked. Returns the spec source, the narrated steps, and a replay-confidence score. Admin only, read-only.',+ inputSchema: {+ type: 'object',+ properties: {+ report_id: { type: 'string', format: 'uuid' },+ base_url: {+ type: 'string',+ description: 'Origin the replay runs against. Defaults to production; pass a local dev origin to run it against a working copy.',+ },+ },+ required: ['report_id'],+ additionalProperties: false,+ },+ scope: 'feedback:read',+ async handler(args, auth) {+ if (!(await requireAdminAuth(auth))) return refusal();+ const { reportWithTrace } = await import('../../_lib/feedback/store.js');+ const report = await reportWithTrace(args.report_id);+ if (!report) return asText(`No feedback report with id ${args.report_id}.`);+ if (!report.trace) {+ return asText(+ `Report ${args.report_id} has no recorded session, so there is nothing to replay. Reports filed before the recorder shipped, or from a browser that opted out, arrive without one. The written report still stands on its own.`,+ );+ }+ const compiled = compileToPlaywright(report.trace, {+ title: report.summary || report.body || 'reported issue',+ baseUrl: args.base_url || BASE_URL,+ reportId: report.id,+ });+ const confidence = replayConfidence(report.trace);+ const steps = narrate(report.trace);+ return asText(+ [+ `Reproduction for report ${report.id}`,+ `Replay confidence: ${confidence.score}/100. ${confidence.note}`,+ '',+ 'What the visitor did:',+ ...steps.map((s) => ` ${s}`),+ '',+ `Save as tests/repros/${compiled.filename} and run it. It is red until the bug is fixed.`,+ '',+ compiled.source,+ ].join('\n'),+ );+ },+ },+];diff --git a/api/feedback/report.js b/api/feedback/report.jsindex 691e57def..1dbabf137 100644--- a/api/feedback/report.js+++ b/api/feedback/report.js@@ -34,7 +34,10 @@ export default wrap(async (req, res) => {const rl = await limits.feedbackWrite(user?.id || clientKey || clientIp(req));if (!rl.success) return rateLimited(res, rl, 'You are sending feedback faster than we can read it. Try again shortly.');- const payload = await readJson(req, 16_000).catch(() => null);+ // A trace of 80 bounded events plus the environment fits comfortably here;+ // the store caps every field again on the way in, so this is only the outer+ // guard against a client that streams.+ const payload = await readJson(req, 96_000).catch(() => null);const report = normalizeReport(payload || {});if (!report.body) {return error(res, 400, 'empty_report', 'Tell us what happened and we will look into it.');@@ -47,7 +50,14 @@ export default wrap(async (req, res) => {userAgent: req.headers['user-agent'] || null,report,});- return json(res, 201, { ok: true, id: row?.id ?? null, received_at: row?.created_at ?? null });+ return json(res, 201, {+ ok: true,+ id: row?.id ?? null,+ received_at: row?.created_at ?? null,+ // Tell the page whether its session was replayable. The panel uses this+ // to say "we captured the steps" instead of a generic thank-you.+ replayable: !!report.trace,+ });} catch (err) {// A visitor took the trouble to report something. If our own store is the// thing that is down, say so plainly rather than swallowing it: the pagediff --git a/api/feedback/repro.js b/api/feedback/repro.jsnew file mode 100644index 000000000..d9237cfff--- /dev/null+++ b/api/feedback/repro.js@@ -0,0 +1,81 @@+/**+ * GET /api/feedback/repro?id=<report id>+ *+ * The report, as a runnable Playwright spec.+ *+ * This is the endpoint that changes what a bug report IS. A maintainer does not+ * read this output, they run it: it is red while the reported bug is present+ * and green once it is fixed, so "is it fixed" stops being a judgement call and+ * the report becomes a regression test the moment it was filed.+ *+ * curl -s 'https://three.ws/api/feedback/repro?id=<id>' \+ * -H "cookie: $SESSION" > tests/repros/export-does-nothing.spec.js+ * npx playwright test tests/repros/export-does-nothing.spec.js+ *+ * `?format=json` returns the spec alongside the narrated steps and the replay+ * confidence, which is what the /feedback queue renders.+ *+ * Admin-only: a trace names internal routes and the shape of a failure, and the+ * generated file is meant for the people who can act on it.+ */++import { cors, json, text, method, wrap, rateLimited, error } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { requireAdmin } from '../_lib/admin.js';+import { isUuid } from '../_lib/validate.js';+import { reportWithTrace } from '../_lib/feedback/store.js';+import { compileToPlaywright, narrate, replayConfidence } from '../../packages/witness/src/compile.js';++const BASE_URL = process.env.WITNESS_REPRO_BASE_URL || 'https://three.ws';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const admin = await requireAdmin(req, res);+ if (!admin) return;++ const rl = await limits.feedbackRead(admin.id || 'admin');+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://localhost');+ const id = url.searchParams.get('id') || '';+ if (!isUuid(id)) return error(res, 400, 'invalid_id', 'Pass the report id as ?id=<uuid>.');++ const report = await reportWithTrace(id);+ if (!report) return error(res, 404, 'not_found', 'No feedback report with that id.');+ if (!report.trace) {+ return error(+ res,+ 409,+ 'no_trace',+ 'That report has no recorded session, so there is nothing to replay. Reports filed before the recorder shipped, or from a browser that opted out, arrive without one.',+ );+ }++ const compiled = compileToPlaywright(report.trace, {+ title: report.summary || report.body || 'reported issue',+ baseUrl: url.searchParams.get('base') || BASE_URL,+ reportId: report.id,+ });++ if (url.searchParams.get('format') === 'json') {+ return json(res, 200, {+ ok: true,+ id: report.id,+ filename: compiled.filename,+ source: compiled.source,+ steps: narrate(report.trace),+ confidence: replayConfidence(report.trace),+ recorded_at: report.created_at,+ });+ }++ // Served as a file so `curl > tests/repros/<name>.spec.js` is the whole+ // workflow. text/plain rather than application/javascript keeps a browser+ // from trying to execute what is, to it, an untrusted script.+ return text(res, 200, compiled.source, {+ 'content-disposition': `inline; filename="${compiled.filename}"`,+ 'cache-control': 'private, no-store',+ });+});diff --git a/packages/witness/LICENSE b/packages/witness/LICENSEnew file mode 100644index 000000000..dff21b7f4--- /dev/null+++ b/packages/witness/LICENSE@@ -0,0 +1,20 @@+Copyright 2026 nirholas++All rights reserved.++This software is proprietary and may not be used, copied, modified, distributed,+translated, or made available to any third party without the express written+permission of the copyright owner.++No rights are granted by implication, estoppel, or otherwise. Use of this+software is subject to the terms of a separate license agreement with the+copyright owner.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.++IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/witness/README.md b/packages/witness/README.mdnew file mode 100644index 000000000..8108d4f86--- /dev/null+++ b/packages/witness/README.md@@ -0,0 +1,239 @@+# @three-ws/witness++**Turn a real user session into a runnable failing test.**++A bug report is a description of an experiment somebody else has to reconstruct.+This makes it the experiment.++```js+import { witness } from '@three-ws/witness';+witness.start();++// ...someone uses your site and something breaks...++import { compileToPlaywright } from '@three-ws/witness/compile';+const { source } = compileToPlaywright(witness.trace(), { title: 'Export does nothing' });+```++`source` is a Playwright spec. It is **red while the bug exists and green once it+is fixed**, so "can you reproduce it" and "is it actually fixed" stop being+conversations.++```js+// Generated by @three-ws/witness from a real user session.+// Report: Export does nothing+// Replay confidence: 80/100. Every step is anchored to a stable handle.+//+// This test asserts the FAILURE IS GONE, so it is red until the bug is fixed.+// What the visitor did:+// Open /avatar-studio+// Click the button [export]+// Type 11 characters into the field labelled "Model name"+// Click the button "Download"+// The request failed: POST /api/export -> 500++import { test, expect } from '@playwright/test';++test.describe('witness repro', () => {+ test.use({ viewport: { width: 390, height: 844 }, locale: 'en-GB', hasTouch: true, isMobile: true });+ test('Export does nothing', async ({ page }) => {+ const pageErrors = [];+ const failedRequests = [];+ page.on('pageerror', (err) => pageErrors.push(`${err.name}: ${err.message}`));+ page.on('response', (res) => {+ if (res.status() >= 400) failedRequests.push(`${res.request().method()} ${new URL(res.url()).pathname} -> ${res.status()}`);+ });++ await page.goto('/avatar-studio');+ await page.getByTestId("export").click();+ await page.getByLabel("Model name").fill('xxxxxxxxxxx'); // visitor typed 11 text character(s)+ await page.getByRole("button", { name: "Download" }).click();++ // The session saw these requests fail:+ // POST /api/export -> 500+ expect(failedRequests, `a request failed during the reported flow`).toEqual([]);+ });+});+```++## Why this is not session replay++Session replay records the DOM mutation stream, weighs megabytes per session,+costs real money to store, and gives you a video to watch. You still have to+reproduce the bug yourself afterwards.++Witness records **intent**, in about two kilobytes:++```+goto /avatar-studio+click the button "Export"+fill the field "Model name" (11 chars)+click the button "Download"+xhr POST /api/export -> 500+error TypeError: exportGLB is not a function (studio.js:412)+```++Because it is that small it can be always-on. Because it is always-on, the trace+**already exists at the moment somebody decides to complain**. Nobody can+reproduce a bug on request. Everybody has just done it.++## Install++```bash+npm install @three-ws/witness+```++```js+import { witness } from '@three-ws/witness';++witness.start();++// Ask at the moment of failure, which is the only moment the person still+// remembers what they were doing.+witness.onFailure(() => showYourFeedbackPrompt());+```++No dependencies. No build step. Works on any site, any framework, in about 6 KB.++## The selector ladder++A recorder that emits `div > div:nth-child(3) > button` produces tests that pass+review and break on the next refactor. Every element gets the strongest handle it+actually has, **verified unique against the live document** before it is+accepted, and demoted one rung at a time until something holds:++| Rung | Handle | Emits | Score |+| --- | --- | --- | --- |+| testid | `[data-testid]`, `[data-test]`, `[data-qa]`, `[data-cy]` | `getByTestId()` | 100 |+| id | `#id`, unless it looks framework-generated | `locator('#id')` | 95 |+| label | `[aria-label]` | `getByLabel()` | 85 |+| role | role + accessible name | `getByRole()` | 80 |+| text | visible text on buttons and links | `getByText()` | 70 |+| name | `[name]` on form controls | `locator()` | 65 |+| placeholder | `[placeholder]` | `getByPlaceholder()` | 60 |+| class | one stable-looking class token | `locator()` | 40 |+| path | `:nth-of-type` chain | `locator()` | 10 |++Framework-generated ids (`:r3a:`, `css-1x2y3z4`, `radix-abc123`) and utility+classes (`px-4`, `sm:text-lg`, `-mt-2`) are refused: a test hung off `.px-4` is a+test hung off a design decision.++Every trace carries a **replay confidence** equal to its weakest link, because+one fragile locator breaks the whole spec:++```js+import { replayConfidence } from '@three-ws/witness/compile';+replayConfidence(trace);+// { score: 40, weakest: {...}, note: 'A step is anchored to a class name, which a restyle can break.' }+```++That number is honest feedback about your own markup. A codebase that adds+`data-testid` to its primary actions watches it climb.++## Privacy is a property of what gets recorded++Not of what gets deleted afterwards. A recorder that captures everything and+scrubs later has already put the secret in memory, in a buffer, and one bug away+from a network call.++- **Typed values are never held.** A filled field records `text:11`, meaning+ eleven characters of ordinary text. The characters do not exist in the trace.+- **Password, hidden, email, tel, and date inputs record nothing at all**, and+ neither does any field whose name, id, `autocomplete`, label, or placeholder+ suggests it holds something personal.+- **URLs are stripped at capture.** Userinfo and the hash go entirely; the names+ of query parameters are kept, their values redacted when they look like+ credentials.+- **Free text is scanned** for the shapes secrets take: emails, JWTs, API keys,+ card numbers, wallet addresses, long base58 runs.+- **Opt out per subtree** with `data-witness="off"`. Nothing inside it is+ observed, not even that it was clicked.++```html+<section data-witness="off">+ <!-- nothing in here is ever recorded -->+</section>+```++## It never changes the page it watches++- Listeners are capture-phase and never call `preventDefault`.+- The `fetch` and `XMLHttpRequest` wrappers return the original object untouched+ on **every** path, including the throwing ones.+- Every handler is wrapped so a throw inside the recorder cannot surface as an+ error in your page.+- The buffer is bounded, so a tab left open for eight hours costs what one open+ for eight seconds costs.++Instrumentation that can change behaviour is a bug generator, not a bug reporter.++## The honest failure mode++When a session recorded **no exception and no failed request**, the visitor+judged the *result* wrong, and no recorder can see that. The compiler will not+invent an assertion to look useful. It emits the steps, then:++```js+// The browser recorded no exception or failed request for this report:+// the visitor judged the RESULT wrong, which no recorder can see.+// Replace this with the assertion that states what should have happened.+expect(pageErrors, 'no page errors during the reported flow').toEqual([]);+test.fail(true, 'Add the assertion this report is really about.');+```++You get the reproduction steps for free and write the one line only a human can.++## API++### `witness.start(options?)`++Begin recording. Idempotent. Returns the `Recorder`.++| Option | Default | Meaning |+| --- | --- | --- |+| `maxEvents` | `60` | Ring buffer size. The initial navigation is never evicted. |+| `coalesceMs` | `900` | Identical repeats inside this window become a count, not new events. |+| `captureNetwork` | `true` | Wrap `fetch`/XHR to notice failed requests. |+| `captureConsole` | `true` | Record uncaught errors and unhandled rejections. |+| `ignore` | none | `(path) => boolean`. Exclude your own reporting endpoint, or a noisy poller. |++### `witness.trace()`++The trace so far. Valid and empty before `start()`.++### `witness.hasFailure({ withinMs })` / `witness.onFailure(fn)`++Whether the session hit something the browser itself called a failure, and a+subscription for the moment it happens. This is the trigger for asking.++### `witness.stop()`++Stop and restore every patched global.++### `compileToPlaywright(trace, { title, baseUrl, reportId })`++Returns `{ filename, source, confidence, steps }`.++### `narrate(trace)`++The same sequence as plain English, for a dashboard or an issue body. The+narration and the spec come from one source, so they can never disagree.++### `describeElement(el)` / `toPlaywrightLocator(desc)`++The selector engine on its own, if you want stable locators for something else.++## Where this came from++three.ws puts a 3D agent in the corner of every page. When a page throws, the+agent turns around and asks what you were doing, and the answer arrives with the+session already attached. The maintainer's queue shows one row per problem with a+**Copy test** button.++The rest of that loop is documented at+[three.ws/docs/feedback](https://three.ws/docs/feedback). This package is the+part that does not depend on any of it.++## License++Apache-2.0diff --git a/packages/witness/package.json b/packages/witness/package.jsonnew file mode 100644index 000000000..07aa7d1a5--- /dev/null+++ b/packages/witness/package.json@@ -0,0 +1,66 @@+{+ "name": "@three-ws/witness",+ "version": "0.1.0",+ "description": "Turn a real user session into a runnable failing test. A tiny, privacy-first session recorder that captures intent (not pixels, not DOM mutations) and compiles it into a Playwright spec that stays red until the reported bug is fixed.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "exports": {+ ".": {+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./compile": {+ "import": "./src/compile.js",+ "default": "./src/compile.js"+ },+ "./selector": {+ "import": "./src/selector.js",+ "default": "./src/selector.js"+ },+ "./redact": {+ "import": "./src/redact.js",+ "default": "./src/redact.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "sideEffects": false,+ "scripts": {+ "test": "node --test test/*.test.js"+ },+ "keywords": [+ "bug-report",+ "session-replay",+ "playwright",+ "repro",+ "reproduction",+ "testing",+ "e2e",+ "feedback",+ "selector",+ "privacy",+ "three.ws"+ ],+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws/docs/witness",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/witness"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "publishConfig": {+ "access": "public"+ },+ "engines": {+ "node": ">=18"+ }+}diff --git a/packages/witness/src/compile.js b/packages/witness/src/compile.jsnew file mode 100644index 000000000..1d3713190--- /dev/null+++ b/packages/witness/src/compile.js@@ -0,0 +1,276 @@+// Compile a trace into a Playwright spec that FAILS on the reported bug.+//+// This is the part that changes what a bug report is. A normal report is prose+// a maintainer has to translate into an experiment. A compiled report IS the+// experiment: check it out, run it, watch it go red, fix the code, watch it go+// green. The report becomes a regression test the moment it is filed, and the+// definition of "fixed" stops being a judgement call.+//+// The critical design decision is that the generated test asserts the ABSENCE+// of the failure the visitor hit, not the presence of whatever the page did.+// A recorder that emits `expect(status).toBe(500)` has written a test that+// passes while the site is broken and fails once it is fixed, which is worse+// than no test at all. So the failure in the trace is inverted into the+// assertion:+//+// trace: POST /api/export -> 500 spec: expect(failures).toEqual([])+// trace: TypeError: x is not a fn spec: expect(pageErrors).toEqual([])+//+// Pure, DOM-free, and dependency-free so it runs identically in the browser,+// in the API, and in the CLI.++import { toPlaywrightLocator, describeForHuman } from './selector.js';++function quote(value) {+ return `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;+}++function commentSafe(value) {+ return String(value ?? '')+ .replace(/\*\//g, '*\\/')+ .replace(/[\r\n]+/g, ' ')+ .slice(0, 200);+}++function slug(value, max = 48) {+ return (+ String(value || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, max) || 'report'+ );+}++/** The events that describe intent, in order, with the noise dropped. */+function actionable(events) {+ return events.filter((e) => ['goto', 'navigate', 'click', 'fill', 'check', 'select', 'submit', 'key'].includes(e.type));+}++/** Every failure the session saw, split by kind so each gets the right assertion. */+export function failuresIn(trace) {+ const events = trace?.events || [];+ const network = [];+ const errors = [];+ const resources = [];+ for (const e of events) {+ if (e.type === 'xhr' && e.detail) network.push(e.detail);+ else if ((e.type === 'error' || e.type === 'rejection') && e.detail) errors.push(e.detail);+ else if (e.type === 'resource' && e.detail) resources.push(e.detail);+ }+ return { network, errors, resources, any: network.length + errors.length + resources.length > 0 };+}++/** The route the session started on, which is where the replay must start. */+export function entryRoute(trace) {+ const first = (trace?.events || []).find((e) => e.type === 'goto');+ return first?.detail || trace?.environment?.url || '/';+}++/**+ * One human-readable line per step. The same source of truth as the spec, so+ * the queue and the test can never describe different sequences.+ */+export function narrate(trace) {+ const steps = [];+ for (const e of actionable(trace?.events || [])) {+ const who = e.el ? describeForHuman(e.el) : null;+ const times = e.count > 1 ? ` (x${e.count})` : '';+ switch (e.type) {+ case 'goto':+ steps.push(`Open ${e.detail}`);+ break;+ case 'navigate':+ steps.push(`Go to ${e.detail}`);+ break;+ case 'click':+ steps.push(`Click ${who}${times}`);+ break;+ case 'fill': {+ const [shape, length] = String(e.detail || '').split(':');+ steps.push(+ shape === 'private'+ ? `Type into ${who}`+ : `Type ${length} character${length === '1' ? '' : 's'} into ${who}`,+ );+ break;+ }+ case 'check':+ steps.push(`${e.detail === 'on' ? 'Check' : 'Uncheck'} ${who}`);+ break;+ case 'select':+ steps.push(`Choose "${e.detail}" in ${who}`);+ break;+ case 'submit':+ steps.push(`Submit ${who}`);+ break;+ case 'key':+ steps.push(`Press ${e.detail}`);+ break;+ default:+ break;+ }+ }+ const { network, errors } = failuresIn(trace);+ for (const line of errors) steps.push(`The page threw: ${line}`);+ for (const line of network) steps.push(`The request failed: ${line}`);+ return steps;+}++/**+ * The confidence that this replays: the weakest link in the chain of selectors,+ * because one fragile locator breaks the whole spec.+ */+export function replayConfidence(trace) {+ const described = actionable(trace?.events || []).filter((e) => e.el);+ if (!described.length) return { score: 0, weakest: null, note: 'No interactions were recorded.' };+ let weakest = described[0].el;+ for (const e of described) if ((e.el.confidence ?? 0) < (weakest.confidence ?? 0)) weakest = e.el;+ const score = weakest.confidence ?? 0;+ const note =+ score >= 80+ ? 'Every step is anchored to a stable handle.'+ : score >= 60+ ? 'One or more steps rely on visible text, which moves when copy changes.'+ : score >= 40+ ? 'A step is anchored to a class name, which a restyle can break.'+ : 'A step falls back to a structural path and will not survive a refactor.';+ return { score, weakest, note };+}++function actionLine(event) {+ const locator = toPlaywrightLocator(event.el);+ switch (event.type) {+ case 'navigate':+ return `\tawait page.goto(${quote(event.detail)});`;+ case 'click':+ return `\tawait ${locator}.click();`;+ case 'submit':+ // Submitting through the form element is what actually happened, and it+ // exercises the same handler a click on the button would.+ return `\tawait ${locator}.evaluate((form) => form.requestSubmit());`;+ case 'check':+ return event.detail === 'on' ? `\tawait ${locator}.check();` : `\tawait ${locator}.uncheck();`;+ case 'select':+ return `\tawait ${locator}.selectOption({ label: ${quote(event.detail)} });`;+ case 'key':+ return `\tawait page.keyboard.press(${quote(event.detail)});`;+ case 'fill': {+ const [shape, length] = String(event.detail || '').split(':');+ if (shape === 'private') {+ return `\t// The visitor typed into this field. The value was never recorded\n\t// (see @three-ws/witness redact.js); supply a real one to replay.\n\tawait ${locator}.fill(process.env.WITNESS_INPUT || 'replace-me');`;+ }+ const sample =+ shape === 'digits'+ ? '1'.repeat(Math.min(Number(length) || 1, 12))+ : shape === 'email'+ ? '[email protected]'+ : shape === 'url'+ ? 'https://example.com'+ : 'x'.repeat(Math.min(Number(length) || 1, 40));+ return `\tawait ${locator}.fill(${quote(sample)}); // visitor typed ${length} ${shape} character(s)`;+ }+ default:+ return null;+ }+}++/**+ * Emit a runnable Playwright spec.+ *+ * @param {object} trace a trace from Recorder#trace()+ * @param {object} [options]+ * @param {string} [options.title] what the visitor reported, used as the test name+ * @param {string} [options.baseUrl] origin the replay runs against+ * @param {string} [options.reportId] the report this came from, linked in a comment+ * @returns {{ filename:string, source:string, confidence:object, steps:string[] }}+ */+export function compileToPlaywright(trace, options = {}) {+ const { title = 'reported issue', baseUrl = '', reportId = null } = options;+ const events = actionable(trace?.events || []);+ const failures = failuresIn(trace);+ const confidence = replayConfidence(trace);+ const steps = narrate(trace);+ const env = trace?.environment || {};+ const route = entryRoute(trace);+ const start = baseUrl ? `${String(baseUrl).replace(/\/+$/, '')}${route}` : route;++ const header = [+ '// Generated by @three-ws/witness from a real user session.',+ `// Report: ${commentSafe(title)}`,+ reportId ? `// Source: feedback report ${commentSafe(reportId)}` : null,+ env.userAgent ? `// Browser: ${commentSafe(env.userAgent)}` : null,+ `// Replay confidence: ${confidence.score}/100. ${confidence.note}`,+ '//',+ '// This test asserts the FAILURE IS GONE, so it is red until the bug is fixed.',+ '// What the visitor did:',+ ...steps.map((s) => `// ${commentSafe(s)}`),+ '',+ "import { test, expect } from '@playwright/test';",+ '',+ ]+ .filter((line) => line !== null)+ .join('\n');++ const viewport = env.viewport?.width+ ? `\ttest.use({ viewport: { width: ${env.viewport.width}, height: ${env.viewport.height} }${+ env.locale ? `, locale: ${quote(env.locale)}` : ''+ }${env.touch ? ', hasTouch: true, isMobile: true' : ''} });\n`+ : '';++ const body = [];+ body.push('\t// Collect the same classes of failure the visitor hit, so the assertions');+ body.push('\t// below fail for the reported reason and not for an unrelated one.');+ body.push('\tconst pageErrors = [];');+ body.push('\tconst failedRequests = [];');+ body.push("\tpage.on('pageerror', (err) => pageErrors.push(`${err.name}: ${err.message}`));");+ body.push("\tpage.on('response', (res) => {");+ body.push('\t\tif (res.status() >= 400) failedRequests.push(`${res.request().method()} ${new URL(res.url()).pathname} -> ${res.status()}`);');+ body.push('\t});');+ body.push('');+ body.push(`\tawait page.goto(${quote(start)});`);++ for (const event of events) {+ if (event.type === 'goto') continue;+ const line = actionLine(event);+ if (line) body.push(line);+ }++ body.push('');+ if (failures.errors.length) {+ body.push('\t// The session threw. The reported failure was:');+ for (const e of failures.errors) body.push(`\t// ${commentSafe(e)}`);+ body.push('\texpect(pageErrors, `the page threw during the reported flow`).toEqual([]);');+ }+ if (failures.network.length) {+ body.push('\t// The session saw these requests fail:');+ for (const n of failures.network) body.push(`\t// ${commentSafe(n)}`);+ body.push('\texpect(failedRequests, `a request failed during the reported flow`).toEqual([]);');+ }+ if (failures.resources.length) {+ body.push('\t// Assets the page could not load:');+ for (const r of failures.resources) body.push(`\t// ${commentSafe(r)}`);+ body.push('\texpect(failedRequests, `an asset failed to load`).toEqual([]);');+ }+ if (!failures.any) {+ // No machine-visible failure: the complaint is about behaviour a person+ // judged wrong. An assertion invented here would be fiction, so the spec+ // says plainly what a human must add, and does not pretend to be green.+ body.push('\t// The browser recorded no exception or failed request for this report:');+ body.push('\t// the visitor judged the RESULT wrong, which no recorder can see.');+ body.push('\t// Replace this with the assertion that states what should have happened.');+ body.push("\texpect(pageErrors, 'no page errors during the reported flow').toEqual([]);");+ body.push("\ttest.fail(true, 'Add the assertion this report is really about.');");+ }++ const source = `${header}test.describe('witness repro', () => {\n${viewport}\ttest(${quote(+ title.slice(0, 100),+ )}, async ({ page }) => {\n${body.join('\n')}\n\t});\n});\n`;++ return {+ filename: `${slug(reportId || title)}.spec.js`,+ source,+ confidence,+ steps,+ };+}diff --git a/packages/witness/src/index.js b/packages/witness/src/index.jsnew file mode 100644index 000000000..f95b4d572--- /dev/null+++ b/packages/witness/src/index.js@@ -0,0 +1,65 @@+// @three-ws/witness+//+// Turn a real user session into a runnable failing test.+//+// import { witness } from '@three-ws/witness';+// witness.start();+// // ... the person uses your site and something breaks ...+// const trace = witness.trace();+//+// import { compileToPlaywright } from '@three-ws/witness/compile';+// const { source } = compileToPlaywright(trace, { title: 'Export does nothing' });+// // `source` is a Playwright spec that is RED until the bug is fixed.+//+// The recorder is browser-only. Everything under compile/narrate is pure and+// runs anywhere, which is what lets the same trace produce the maintainer's+// English steps in a dashboard and the engineer's spec file on disk.++import { Recorder } from './recorder.js';++export { Recorder } from './recorder.js';+export { compileToPlaywright, narrate, failuresIn, entryRoute, replayConfidence } from './compile.js';+export { describeElement, toPlaywrightLocator, describeForHuman, accessibleName, roleOf, structuralPath } from './selector.js';+export { redactText, redactUrl, isSensitiveField, summarizeInput } from './redact.js';++let singleton = null;++/**+ * The default recorder. One per page: a second instance would double every+ * fetch wrapper and record each request twice.+ */+export const witness = {+ /**+ * Begin recording. Idempotent, so a page that calls it from two modules+ * still installs one recorder.+ * @param {object} [options] see Recorder's DEFAULTS+ */+ start(options = {}) {+ if (!singleton) singleton = new Recorder(options);+ if (!singleton.installed) singleton.install();+ return singleton;+ },+ /** The live recorder, or null when start() has not been called. */+ get current() {+ return singleton;+ },+ /** The trace so far. Empty and valid when nothing has been recorded. */+ trace() {+ return singleton ? singleton.trace() : { version: 1, recordedMs: 0, environment: {}, events: [] };+ },+ /** True when the session hit something the browser itself called a failure. */+ hasFailure(opts) {+ return singleton ? singleton.hasFailure(opts) : false;+ },+ /** Call back when a failure lands. The moment to ask "what were you doing?". */+ onFailure(fn) {+ return singleton ? singleton.onSignal(fn) : () => {};+ },+ /** Stop recording and restore every patched global. */+ stop() {+ singleton?.uninstall();+ singleton = null;+ },+};++export default witness;diff --git a/packages/witness/src/recorder.js b/packages/witness/src/recorder.jsnew file mode 100644index 000000000..e91e3eee3--- /dev/null+++ b/packages/witness/src/recorder.js@@ -0,0 +1,386 @@+// The recorder: a bounded, semantic trace of what a person did before it broke.+//+// This is deliberately NOT a session replay recorder. Those capture the DOM+// mutation stream, weigh megabytes, cost real money to store, and produce a+// video a maintainer has to watch. What actually fixes a bug is the sequence of+// intents plus the failure, and that fits in about two kilobytes:+//+// goto /avatar-studio+// click the button "Export"+// fill the field "Model name" (11 chars)+// click the button "Download"+// xhr POST /api/export -> 500+// error TypeError: exportGLB is not a function+//+// Because it is small it can be always-on, and because it is always-on the+// trace already exists at the moment the person decides to complain. That is+// the whole trick: nobody can reproduce a bug on request, but everybody has+// just done it.+//+// Design rules, all load-bearing:+// 1. Bounded. One ring buffer, a hard event cap, no growth over a long+// session. A page left open for eight hours costs the same as one open for+// eight seconds.+// 2. Passive. Listeners are capture-phase and never call preventDefault, and+// the fetch/XHR wrappers return the original object untouched on every+// path. Instrumentation that can change behaviour is a bug generator, not+// a bug reporter.+// 3. Silent on failure. Every handler is wrapped: a throw inside the recorder+// must never surface as an error in the page it is watching.+// 4. Values are never held (see redact.js).++import { describeElement } from './selector.js';+import { redactText, redactUrl, summarizeInput, isOptedOut } from './redact.js';++const DEFAULTS = {+ maxEvents: 60,+ // Two identical clicks a second apart are two facts. Fifty are one fact and+ // forty-nine of noise, so repeats collapse into a count.+ coalesceMs: 900,+ captureNetwork: true,+ captureConsole: true,+ sampleScrolls: false,+};++function now() {+ return Date.now();+}++export class Recorder {+ constructor(options = {}) {+ this.options = { ...DEFAULTS, ...options };+ this.events = [];+ this.startedAt = now();+ this.installed = false;+ this.listeners = new Set();+ this._teardown = [];+ this._seq = 0;+ }++ /** Subscribe to "something notable happened" (a failure, not every click). */+ onSignal(fn) {+ this.listeners.add(fn);+ return () => this.listeners.delete(fn);+ }++ _emit(event) {+ const last = this.events[this.events.length - 1];+ // Coalesce an identical repeat rather than spending buffer on it.+ if (+ last &&+ last.type === event.type &&+ last.target === event.target &&+ last.detail === event.detail &&+ event.at - last.at < this.options.coalesceMs+ ) {+ last.count = (last.count || 1) + 1;+ last.at = event.at;+ return last;+ }+ event.i = this._seq++;+ this.events.push(event);+ if (this.events.length > this.options.maxEvents) {+ // Drop from the front, but never drop the initial navigation: without+ // it the trace has no starting point and cannot be replayed at all.+ const first = this.events[0];+ if (first.type === 'goto' && this.events.length > 1) this.events.splice(1, 1);+ else this.events.shift();+ }+ if (event.fatal) {+ for (const fn of this.listeners) {+ try {+ fn(event);+ } catch {+ /* a subscriber must never break recording */+ }+ }+ }+ return event;+ }++ _safe(fn) {+ return (...args) => {+ try {+ fn(...args);+ } catch {+ /* the recorder never throws into the page it watches */+ }+ };+ }++ record(type, { target = null, detail = null, fatal = false, meta = null } = {}) {+ return this._emit({ type, target, detail, fatal, meta, at: now() });+ }++ /** Note the page we are on. Called on install and on every history change. */+ noteNavigation(kind = 'goto') {+ if (typeof location === 'undefined') return;+ this.record(kind, { detail: redactUrl(location.href, { origin: location.origin }) });+ }++ install() {+ if (this.installed || typeof window === 'undefined') return this;+ this.installed = true;+ this.noteNavigation('goto');++ const on = (target, type, handler, opts) => {+ const wrapped = this._safe(handler);+ target.addEventListener(type, wrapped, opts);+ this._teardown.push(() => target.removeEventListener(type, wrapped, opts));+ };++ // ── Intent ──────────────────────────────────────────────────────────────+ on(+ document,+ 'click',+ (e) => {+ const el = e.target?.closest?.(+ 'a,button,input,select,textarea,summary,label,[role],[onclick],[data-testid],[tabindex]',+ );+ if (!el || isOptedOut(el)) return;+ const desc = describeElement(el);+ if (!desc) return;+ this.record('click', { target: JSON.stringify(desc), detail: null, meta: desc });+ },+ true,+ );++ on(+ document,+ 'change',+ (e) => {+ const el = e.target;+ if (!el?.tagName || isOptedOut(el)) return;+ const tag = el.tagName;+ if (tag !== 'INPUT' && tag !== 'SELECT' && tag !== 'TEXTAREA') return;+ const desc = describeElement(el);+ if (!desc) return;+ const type = (el.getAttribute('type') || '').toLowerCase();+ if (type === 'checkbox' || type === 'radio') {+ this.record('check', { target: JSON.stringify(desc), detail: el.checked ? 'on' : 'off', meta: desc });+ return;+ }+ if (tag === 'SELECT') {+ // A select's chosen option is UI state a maintainer needs and is+ // not user-authored text, so the label itself is safe to keep.+ const label = redactText(el.selectedOptions?.[0]?.textContent || '', { max: 60 });+ this.record('select', { target: JSON.stringify(desc), detail: label, meta: desc });+ return;+ }+ const shape = summarizeInput(el, el.value);+ this.record('fill', {+ target: JSON.stringify(desc),+ detail: shape.length === null ? 'private' : `${shape.shape}:${shape.length}`,+ meta: desc,+ });+ },+ true,+ );++ on(+ document,+ 'submit',+ (e) => {+ const desc = describeElement(e.target);+ if (desc) this.record('submit', { target: JSON.stringify(desc), meta: desc });+ },+ true,+ );++ on(+ window,+ 'keydown',+ (e) => {+ // Only keys that are commands, never keys that are content. This is+ // the difference between recording a shortcut and keylogging.+ const isCommand = e.metaKey || e.ctrlKey || e.altKey;+ const named = ['Enter', 'Escape', 'Tab', 'Backspace', 'ArrowUp', 'ArrowDown'].includes(e.key);+ if (!isCommand && !named) return;+ const combo = [e.metaKey && 'Meta', e.ctrlKey && 'Control', e.altKey && 'Alt', e.shiftKey && 'Shift', e.key]+ .filter(Boolean)+ .join('+');+ this.record('key', { detail: combo });+ },+ true,+ );++ // ── Navigation ──────────────────────────────────────────────────────────+ on(window, 'popstate', () => this.noteNavigation('navigate'));+ on(window, 'hashchange', () => this.noteNavigation('navigate'));+ for (const method of ['pushState', 'replaceState']) {+ const native = history[method];+ if (typeof native !== 'function') continue;+ const self = this;+ history[method] = function patchedHistory(...args) {+ const result = native.apply(this, args);+ try {+ self.noteNavigation('navigate');+ } catch {+ /* never break a route change */+ }+ return result;+ };+ this._teardown.push(() => {+ history[method] = native;+ });+ }++ // ── Failure ─────────────────────────────────────────────────────────────+ if (this.options.captureConsole) {+ on(+ window,+ 'error',+ (e) => {+ if (e.target && e.target !== window && e.target.tagName) {+ const src = e.target.currentSrc || e.target.src || e.target.href;+ if (src) {+ this.record('resource', {+ detail: redactUrl(src, { origin: location.origin }),+ fatal: true,+ });+ }+ return;+ }+ const where = e.filename ? ` (${e.filename.split('/').pop()}:${e.lineno})` : '';+ this.record('error', {+ detail: `${redactText(e.error?.name ? `${e.error.name}: ${e.error.message}` : e.message)}${where}`,+ fatal: true,+ });+ },+ true,+ );+ on(window, 'unhandledrejection', (e) => {+ const reason = e.reason;+ const text = reason instanceof Error ? `${reason.name}: ${reason.message}` : String(reason?.message || reason);+ this.record('rejection', { detail: redactText(text), fatal: true });+ });+ }++ if (this.options.captureNetwork) this._installNetwork();++ return this;+ }++ _installNetwork() {+ const self = this;+ const origin = typeof location !== 'undefined' ? location.origin : null;++ const nativeFetch = window.fetch;+ if (typeof nativeFetch === 'function') {+ window.fetch = function witnessFetch(input, init) {+ const promise = nativeFetch.apply(this, arguments);+ try {+ const method = String(init?.method || input?.method || 'GET').toUpperCase();+ const raw = typeof input === 'string' ? input : input?.url || '';+ const path = redactUrl(raw, { origin });+ if (path && !self.options.ignore?.(path)) {+ promise.then(+ (res) => {+ if (res && !res.ok) {+ self.record('xhr', { detail: `${method} ${path} -> ${res.status}`, fatal: res.status >= 500 || res.status === 0 });+ }+ },+ (err) => {+ self.record('xhr', { detail: `${method} ${path} -> ${redactText(err?.message || 'network error', { max: 80 })}`, fatal: true });+ },+ );+ }+ } catch {+ /* instrumentation must never change a request */+ }+ return promise;+ };+ this._teardown.push(() => {+ window.fetch = nativeFetch;+ });+ }++ const XHR = window.XMLHttpRequest;+ if (typeof XHR === 'function' && XHR.prototype) {+ const nativeOpen = XHR.prototype.open;+ const nativeSend = XHR.prototype.send;+ XHR.prototype.open = function witnessOpen(method, url, ...rest) {+ try {+ this.__witness = { method: String(method || 'GET').toUpperCase(), url: redactUrl(url, { origin }) };+ } catch {+ /* keep the request working regardless */+ }+ return nativeOpen.call(this, method, url, ...rest);+ };+ XHR.prototype.send = function witnessSend(...args) {+ try {+ const meta = this.__witness;+ if (meta && !self.options.ignore?.(meta.url)) {+ this.addEventListener('loadend', () => {+ try {+ const status = this.status;+ if (status === 0 || status >= 400) {+ self.record('xhr', {+ detail: `${meta.method} ${meta.url} -> ${status || 'failed'}`,+ fatal: status === 0 || status >= 500,+ });+ }+ } catch {+ /* nothing to record */+ }+ });+ }+ } catch {+ /* never break a send */+ }+ return nativeSend.apply(this, args);+ };+ this._teardown.push(() => {+ XHR.prototype.open = nativeOpen;+ XHR.prototype.send = nativeSend;+ });+ }+ }++ /** The environment facts a replay needs to match the session it came from. */+ environment() {+ if (typeof window === 'undefined') return {};+ return {+ url: redactUrl(location.href, { origin: location.origin }),+ viewport: { width: window.innerWidth, height: window.innerHeight, dpr: window.devicePixelRatio || 1 },+ locale: navigator.language || null,+ userAgent: redactText(navigator.userAgent, { max: 200 }),+ touch: (navigator.maxTouchPoints || 0) > 0,+ reducedMotion: !!window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches,+ };+ }++ /** The trace as it stands. Safe to call at any time; does not stop recording. */+ trace() {+ return {+ version: 1,+ recordedMs: now() - this.startedAt,+ environment: this.environment(),+ // `target` is the coalescing key, not payload: when a descriptor exists+ // it is the same object serialized, so emitting both would double the+ // size of the one thing that has to stay small.+ events: this.events.map(({ meta, fatal, target, ...rest }) => ({+ ...rest,+ ...(meta ? { el: meta } : target ? { target } : {}),+ ...(fatal ? { fatal: true } : {}),+ })),+ };+ }++ /** True when the session contains a failure worth asking the visitor about. */+ hasFailure({ withinMs = 20_000 } = {}) {+ const cutoff = now() - withinMs;+ return this.events.some((e) => e.fatal && e.at >= cutoff);+ }++ uninstall() {+ for (const undo of this._teardown.splice(0)) {+ try {+ undo();+ } catch {+ /* best effort */+ }+ }+ this.installed = false;+ }+}diff --git a/packages/witness/src/redact.js b/packages/witness/src/redact.jsnew file mode 100644index 000000000..da01a796c--- /dev/null+++ b/packages/witness/src/redact.js@@ -0,0 +1,125 @@+// Privacy is a property of what we RECORD, not of what we delete later.+//+// A session recorder that captures everything and scrubs afterwards has already+// put the secret in memory, in a buffer, and one bug away from a network call.+// This module is applied at capture time, before a value is ever held: typed+// characters are counted, never kept; URLs are stripped of their credentials+// before the path is stored; text is scanned for the shapes that secrets take.+//+// The rules are conservative on purpose. A redaction that fires on something+// harmless costs a maintainer one word of context. A redaction that fails to+// fire puts a live token in a bug report.++const SECRET_PATTERNS = [+ [/\b[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[email]'],+ [/\bsk-[A-Za-z0-9_-]{16,}\b/g, '[api-key]'],+ [/\b(?:xox[baprs]|ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_-]{16,}\b/g, '[token]'],+ [/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[jwt]'],+ [/\b(?:[0-9]{4}[ -]?){3}[0-9]{3,4}\b/g, '[card]'],+ [/\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b/g, '[address]'],+ [/\b0x[a-fA-F0-9]{40}\b/g, '[address]'],+ // A long unbroken base58/base64 run is a key, a signature, or a mint. None+ // of them belong in a bug report, and none of them help a maintainer.+ [/\b[1-9A-HJ-NP-Za-km-z]{40,}\b/g, '[key]'],+];++// Query and hash parameters that carry credentials. Their presence is worth+// recording (the bug may BE the token); the value never is.+const SENSITIVE_PARAMS =+ /^(?:token|access_token|refresh_token|id_token|api_key|apikey|key|secret|password|passwd|pwd|auth|authorization|session|sid|code|state|signature|sig|otp|pin|email|phone)$/i;++// Includes the standard autocomplete tokens (`one-time-code`, `cc-number`,+// `current-password`) because that attribute is the most reliable declaration a+// page ever makes about what a field holds.+const SENSITIVE_FIELD =+ /(?:pass|pwd|secret|token|otp|one-time|verification|pin\b|cvv|cvc|cc-|ssn|social|card|iban|routing|seed|mnemonic|private|key|auth|email|phone|birthday|dob)/i;++/** Replace anything shaped like a secret. Never throws; returns a string. */+export function redactText(value, { max = 400 } = {}) {+ let text = String(value ?? '');+ if (!text) return '';+ for (const [pattern, replacement] of SECRET_PATTERNS) {+ text = text.replace(pattern, replacement);+ }+ text = text.replace(/\s+/g, ' ').trim();+ return text.length > max ? `${text.slice(0, max)}...` : text;+}++/**+ * A URL reduced to what a maintainer needs: origin-relative path, the NAMES of+ * the query parameters, and redacted values only for parameters that are+ * plainly not credentials. Userinfo and the hash go entirely.+ */+export function redactUrl(value, { origin = null } = {}) {+ const raw = String(value ?? '');+ if (!raw) return '';+ let url;+ try {+ url = new URL(raw, origin || 'http://local.invalid');+ } catch {+ return redactText(raw, { max: 120 });+ }+ const params = [];+ for (const [key] of url.searchParams) {+ if (SENSITIVE_PARAMS.test(key)) {+ params.push(`${key}=[redacted]`);+ } else {+ const value_ = url.searchParams.get(key) || '';+ params.push(`${key}=${redactText(value_, { max: 40 })}`);+ }+ }+ const sameOrigin = origin && url.origin === origin;+ const base = sameOrigin || url.origin === 'http://local.invalid' ? url.pathname : `${url.origin}${url.pathname}`;+ return params.length ? `${base}?${params.join('&')}` : base;+}++/**+ * Whether a field's CONTENT must never be observed at all: password inputs,+ * anything inside an opted-out subtree, and anything whose name, id, label, or+ * autocomplete hint says it holds something personal.+ */+export function isSensitiveField(el) {+ if (!el || el.nodeType !== 1) return true;+ const tag = el.tagName;+ if (tag === 'INPUT') {+ const type = (el.getAttribute('type') || 'text').toLowerCase();+ // The type attribute is a declaration about the content, so it is trusted+ // ahead of any name-based guessing below.+ if (['password', 'hidden', 'email', 'tel', 'date'].includes(type)) return true;+ }+ if (el.closest?.('[data-witness="off"], [data-witness-private]')) return true;+ const hints = [+ el.getAttribute?.('name'),+ el.getAttribute?.('id'),+ el.getAttribute?.('autocomplete'),+ el.getAttribute?.('aria-label'),+ el.getAttribute?.('placeholder'),+ ]+ .filter(Boolean)+ .join(' ');+ // A placeholder that is itself an example email or phone number says what+ // the field holds more clearly than its name ever does.+ if (/\S+@\S+\.\S+/.test(hints) || /\+?\d[\d\s().-]{7,}/.test(hints)) return true;+ return SENSITIVE_FIELD.test(hints);+}++/** True when this element sits inside a subtree the page asked us not to watch. */+export function isOptedOut(el) {+ return !!el?.closest?.('[data-witness="off"]');+}++/**+ * What we keep about something a person typed: that they typed, roughly how+ * much, and whether it looked like an email or a number. Never the characters.+ */+export function summarizeInput(el, value) {+ if (isSensitiveField(el)) return { length: null, shape: 'private' };+ const text = String(value ?? '');+ if (!text) return { length: 0, shape: 'empty' };+ let shape = 'text';+ if (/^\d+$/.test(text)) shape = 'digits';+ else if (/^\S+@\S+$/.test(text)) shape = 'email';+ else if (/^https?:\/\//i.test(text)) shape = 'url';+ else if (text.length > 120) shape = 'paragraph';+ return { length: text.length, shape };+}diff --git a/packages/witness/src/selector.js b/packages/witness/src/selector.jsnew file mode 100644index 000000000..06ebcc25e--- /dev/null+++ b/packages/witness/src/selector.js@@ -0,0 +1,360 @@+// Stable selector synthesis: the part that decides whether a generated test+// actually replays a year later.+//+// A recorder that writes `div > div:nth-child(3) > button` produces tests that+// pass review and break on the next refactor. So every element is described by+// the strongest handle it actually has, verified unique against the live+// document before it is accepted, and demoted one rung at a time until+// something holds. The ladder, strongest first:+//+// testid [data-testid] / [data-test] / [data-qa] the author's own contract+// id #id, unless it looks framework-generated+// label [aria-label]+// role role + accessible name (Playwright getByRole)+// text visible text, for buttons and links+// name [name], for form controls+// placeholder [placeholder], for inputs+// class one stable-looking class token+// path :nth-of-type chain, the honest last resort+//+// Each candidate carries a numeric confidence so the compiler can annotate a+// weak locator in the generated test instead of pretending it is solid. The+// caller sees exactly how fragile its own selector is.++export const STRATEGY_SCORE = {+ testid: 100,+ id: 95,+ label: 85,+ role: 80,+ text: 70,+ name: 65,+ placeholder: 60,+ class: 40,+ path: 10,+};++const TESTID_ATTRS = ['data-testid', 'data-test', 'data-qa', 'data-cy'];++// Ids and classes that a bundler or a CSS-in-JS runtime invented. Matching one+// means the handle will not survive the next build, so it is worth less than a+// structural path that at least describes the page.+const GENERATED = [+ /^[a-z]?[0-9a-f]{6,}$/i, // hash-like: a1b2c3d4+ /^(css|sc|jsx|emotion|mui|chakra|tw)-[a-z0-9]{4,}$/i, // styled-components and friends+ /^:r[0-9a-z]+:$/i, // React useId+ /^radix-[a-z0-9]+$/i,+ /^headlessui-/i,+ /^[0-9]/, // a leading digit is never a hand-written id+ /^(ember|ext-gen|yui)[0-9]+$/i,+ /[0-9]{4,}$/, // long numeric tails are almost always generated+];++// Utility-first class names (Tailwind and friends) describe appearance, not+// identity. A test hung off `.px-4` is a test hung off a design decision, and+// it breaks the first time somebody adjusts the padding. Matched as+// `[variant:]*root-`, which is the actual shape of the convention, so `px-4`,+// `sm:px-4`, `-mt-2`, and `hover:bg-blue-500` are all refused while a real+// class like `price-tag` is kept.+const UTILITY_ROOT = [+ 'p', 'px', 'py', 'pt', 'pb', 'pl', 'pr', 'ps', 'pe',+ 'm', 'mx', 'my', 'mt', 'mb', 'ml', 'mr', 'ms', 'me',+ 'w', 'h', 'min', 'max', 'size', 'top', 'left', 'right', 'bottom', 'inset', 'z',+ 'gap', 'flex', 'grid', 'col', 'row', 'basis', 'grow', 'shrink', 'order', 'place',+ 'text', 'bg', 'border', 'rounded', 'shadow', 'opacity', 'ring', 'outline', 'divide',+ 'translate', 'scale', 'rotate', 'skew', 'origin', 'transform',+ 'space', 'leading', 'tracking', 'font', 'align', 'whitespace', 'break', 'indent',+ 'items', 'justify', 'self', 'content', 'overflow', 'overscroll', 'cursor', 'select',+ 'transition', 'duration', 'ease', 'delay', 'animate', 'aspect', 'object', 'float',+ 'clear', 'list', 'placeholder', 'fill', 'stroke', 'filter', 'blur', 'backdrop', 'sr',+].join('|');+const UTILITY_CLASS = new RegExp(`^-?(?:[a-z0-9-]{1,12}:)*(?:${UTILITY_ROOT})-`, 'i');+// Single-word utilities carry no hyphen, so they need their own list.+const UTILITY_STANDALONE =+ /^(?:flex|grid|block|inline|inline-block|inline-flex|hidden|absolute|relative|fixed|sticky|static|truncate|italic|underline|uppercase|lowercase|capitalize|container|antialiased|isolate|contents|visible|invisible)$/i;++function looksUtility(token) {+ return UTILITY_STANDALONE.test(token) || UTILITY_CLASS.test(token) || token.includes('[');+}++const INTERACTIVE_ROLE = {+ A: 'link',+ BUTTON: 'button',+ SELECT: 'combobox',+ TEXTAREA: 'textbox',+ SUMMARY: 'button',+};++const INPUT_ROLE = {+ button: 'button',+ submit: 'button',+ reset: 'button',+ checkbox: 'checkbox',+ radio: 'radio',+ range: 'slider',+ search: 'searchbox',+ email: 'textbox',+ tel: 'textbox',+ text: 'textbox',+ url: 'textbox',+ number: 'spinbutton',+};++function looksGenerated(value) {+ const token = String(value || '');+ if (!token) return true;+ return GENERATED.some((re) => re.test(token));+}++function cssEscape(value) {+ const text = String(value);+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(text);+ return text.replace(/["\\\]]/g, '\\$&');+}++function quote(value) {+ return `"${String(value).replace(/["\\]/g, '\\$&')}"`;+}++/** Trim and collapse the way a screen reader would before comparing names. */+export function normalizeName(text) {+ return String(text || '')+ .replace(/\s+/g, ' ')+ .trim();+}++/**+ * The accessible name, computed over the subset of the spec that real pages+ * actually use: aria-label, aria-labelledby, a wrapping or associated <label>,+ * alt text, value on buttons, title, then the visible text.+ */+export function accessibleName(el) {+ if (!el || el.nodeType !== 1) return '';+ const aria = normalizeName(el.getAttribute?.('aria-label'));+ if (aria) return aria;++ const labelledBy = el.getAttribute?.('aria-labelledby');+ if (labelledBy) {+ const names = labelledBy+ .split(/\s+/)+ .map((id) => el.ownerDocument?.getElementById(id)?.textContent || '')+ .map(normalizeName)+ .filter(Boolean);+ if (names.length) return normalizeName(names.join(' '));+ }++ const tag = el.tagName;+ if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') {+ const id = el.getAttribute('id');+ if (id) {+ const label = el.ownerDocument?.querySelector(`label[for="${cssEscape(id)}"]`);+ const text = normalizeName(label?.textContent);+ if (text) return text;+ }+ const wrapping = el.closest?.('label');+ if (wrapping) {+ const text = normalizeName(wrapping.textContent);+ if (text) return text;+ }+ if (tag === 'INPUT') {+ const type = (el.getAttribute('type') || 'text').toLowerCase();+ if (type === 'button' || type === 'submit' || type === 'reset') {+ const value = normalizeName(el.getAttribute('value'));+ if (value) return value;+ }+ }+ }++ if (tag === 'IMG') {+ const alt = normalizeName(el.getAttribute('alt'));+ if (alt) return alt;+ }++ const title = normalizeName(el.getAttribute?.('title'));+ const text = normalizeName(el.textContent);+ // Text wins over title when both exist: it is what the person actually read.+ return text || title;+}++/** The ARIA role, explicit first, then the implicit role of the tag. */+export function roleOf(el) {+ if (!el || el.nodeType !== 1) return null;+ const explicit = normalizeName(el.getAttribute?.('role'));+ if (explicit) return explicit.split(/\s+/)[0];+ const tag = el.tagName;+ if (tag === 'INPUT') {+ const type = (el.getAttribute('type') || 'text').toLowerCase();+ return INPUT_ROLE[type] || null;+ }+ if (INTERACTIVE_ROLE[tag]) {+ // A bare anchor with no href is not a link to anyone, screen readers+ // included, so it does not get the link role here either.+ if (tag === 'A' && !el.getAttribute('href')) return null;+ return INTERACTIVE_ROLE[tag];+ }+ if (/^H[1-6]$/.test(tag)) return 'heading';+ return null;+}++function unique(doc, css) {+ try {+ return doc.querySelectorAll(css).length === 1;+ } catch {+ return false;+ }+}++/** Every element with this role whose accessible name matches, exactly as Playwright's getByRole resolves it. */+function roleMatchCount(doc, role, name) {+ let count = 0;+ const all = doc.querySelectorAll('*');+ for (const node of all) {+ if (roleOf(node) !== role) continue;+ if (normalizeName(accessibleName(node)) === name) count += 1;+ if (count > 1) return count;+ }+ return count;+}++function textMatchCount(doc, tag, text) {+ let count = 0;+ for (const node of doc.querySelectorAll(tag)) {+ if (normalizeName(node.textContent) === text) count += 1;+ if (count > 1) return count;+ }+ return count;+}++/** The :nth-of-type chain, capped so it stays readable, used only when nothing better exists. */+export function structuralPath(el, { maxDepth = 5 } = {}) {+ const parts = [];+ let node = el;+ let depth = 0;+ while (node && node.nodeType === 1 && node.tagName !== 'HTML' && depth < maxDepth) {+ const tag = node.tagName.toLowerCase();+ const parent = node.parentElement;+ if (!parent) {+ parts.unshift(tag);+ break;+ }+ const siblings = [...parent.children].filter((c) => c.tagName === node.tagName);+ parts.unshift(siblings.length > 1 ? `${tag}:nth-of-type(${siblings.indexOf(node) + 1})` : tag);+ if (parent.tagName === 'BODY') break;+ node = parent;+ depth += 1;+ }+ return parts.join(' > ');+}++/**+ * Describe an element as the strongest handle that uniquely identifies it.+ *+ * @param {Element} el+ * @returns {{strategy:string, value:string, css:string|null, role?:string, name?:string, confidence:number, tag:string}|null}+ */+export function describeElement(el) {+ if (!el || el.nodeType !== 1) return null;+ const doc = el.ownerDocument;+ const tag = el.tagName.toLowerCase();+ const base = { tag };++ for (const attr of TESTID_ATTRS) {+ const value = el.getAttribute(attr);+ if (value) {+ const css = `[${attr}="${cssEscape(value)}"]`;+ if (unique(doc, css)) {+ return { ...base, strategy: 'testid', value, css, attr, confidence: STRATEGY_SCORE.testid };+ }+ }+ }++ const id = el.getAttribute('id');+ if (id && !looksGenerated(id)) {+ const css = `#${cssEscape(id)}`;+ if (unique(doc, css)) return { ...base, strategy: 'id', value: id, css, confidence: STRATEGY_SCORE.id };+ }++ const label = normalizeName(el.getAttribute('aria-label'));+ if (label) {+ const css = `[aria-label="${cssEscape(label)}"]`;+ if (unique(doc, css)) return { ...base, strategy: 'label', value: label, css, confidence: STRATEGY_SCORE.label };+ }++ const role = roleOf(el);+ const name = normalizeName(accessibleName(el));+ // A name longer than this is a paragraph that happens to be clickable, and+ // matching on it is brittle for a different reason than a weak selector is.+ if (role && name && name.length <= 80 && roleMatchCount(doc, role, name) === 1) {+ return { ...base, strategy: 'role', value: name, role, name, css: null, confidence: STRATEGY_SCORE.role };+ }++ if (name && name.length <= 80 && (tag === 'button' || tag === 'a' || tag === 'summary')) {+ if (textMatchCount(doc, tag, name) === 1) {+ return { ...base, strategy: 'text', value: name, css: null, confidence: STRATEGY_SCORE.text };+ }+ }++ const nameAttr = el.getAttribute('name');+ if (nameAttr) {+ const css = `${tag}[name="${cssEscape(nameAttr)}"]`;+ if (unique(doc, css)) return { ...base, strategy: 'name', value: nameAttr, css, confidence: STRATEGY_SCORE.name };+ }++ const placeholder = el.getAttribute('placeholder');+ if (placeholder) {+ const css = `[placeholder="${cssEscape(placeholder)}"]`;+ if (unique(doc, css)) {+ return { ...base, strategy: 'placeholder', value: placeholder, css, confidence: STRATEGY_SCORE.placeholder };+ }+ }++ const classes = (el.getAttribute('class') || '')+ .split(/\s+/)+ .filter((c) => c && !looksGenerated(c) && !looksUtility(c));+ for (const cls of classes) {+ const css = `${tag}.${cssEscape(cls)}`;+ if (unique(doc, css)) return { ...base, strategy: 'class', value: cls, css, confidence: STRATEGY_SCORE.class };+ }++ const path = structuralPath(el);+ return { ...base, strategy: 'path', value: path, css: path, confidence: STRATEGY_SCORE.path };+}++/**+ * Render a description as Playwright locator source. Semantic strategies emit+ * the semantic locator (which is what a human would have written); everything+ * else emits a CSS locator.+ */+export function toPlaywrightLocator(desc) {+ if (!desc) return 'page.locator("body")';+ switch (desc.strategy) {+ case 'testid':+ // getByTestId only reads the configured attribute, so the default+ // data-testid uses it and the other spellings stay explicit CSS.+ return desc.attr === 'data-testid'+ ? `page.getByTestId(${quote(desc.value)})`+ : `page.locator(${quote(desc.css)})`;+ case 'label':+ return `page.getByLabel(${quote(desc.value)})`;+ case 'role':+ return `page.getByRole(${quote(desc.role)}, { name: ${quote(desc.name)} })`;+ case 'text':+ return `page.getByText(${quote(desc.value)}, { exact: true })`;+ case 'placeholder':+ return `page.getByPlaceholder(${quote(desc.value)})`;+ default:+ return `page.locator(${quote(desc.css || desc.value)})`;+ }+}++/** One short phrase naming the element for a human reading the steps. */+export function describeForHuman(desc) {+ if (!desc) return 'the page';+ const noun = desc.role || desc.tag || 'element';+ if (desc.strategy === 'role') return `the ${desc.role} "${desc.name}"`;+ if (desc.strategy === 'text') return `"${desc.value}"`;+ if (desc.strategy === 'label') return `the ${noun} labelled "${desc.value}"`;+ if (desc.strategy === 'placeholder') return `the field "${desc.value}"`;+ if (desc.strategy === 'testid') return `the ${noun} [${desc.value}]`;+ if (desc.strategy === 'id') return `the ${noun} #${desc.value}`;+ return `the ${noun} (${desc.value})`;+}diff --git a/packages/witness/test/compile.test.js b/packages/witness/test/compile.test.jsnew file mode 100644index 000000000..af484782c--- /dev/null+++ b/packages/witness/test/compile.test.js@@ -0,0 +1,135 @@+// The compiler's contract, and the one property that matters most: a generated+// test must be RED while the bug is present. A recorder that emits an assertion+// matching the broken behaviour has written a test that locks the bug in.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileToPlaywright, narrate, failuresIn, entryRoute, replayConfidence } from '../src/compile.js';++const el = (over = {}) => ({ tag: 'button', strategy: 'testid', value: 'export', attr: 'data-testid', confidence: 100, ...over });++const trace = (events, environment = {}) => ({ version: 1, recordedMs: 4200, environment, events });++const session = trace(+ [+ { i: 0, type: 'goto', detail: '/avatar-studio' },+ { i: 1, type: 'click', el: el(), at: 2 },+ { i: 2, type: 'fill', detail: 'text:11', el: el({ strategy: 'label', value: 'Model name', confidence: 85 }) },+ { i: 3, type: 'click', el: el({ strategy: 'role', role: 'button', name: 'Download', confidence: 80 }) },+ { i: 4, type: 'xhr', detail: 'POST /api/export -> 500', fatal: true },+ { i: 5, type: 'error', detail: 'TypeError: exportGLB is not a function (studio.js:412)', fatal: true },+ ],+ { viewport: { width: 390, height: 844, dpr: 3 }, locale: 'en-GB', touch: true, userAgent: 'iPhone' },+);++test('the generated spec asserts the failure is GONE, never that it happened', () => {+ const { source } = compileToPlaywright(session, { title: 'Export does nothing' });+ assert.match(source, /expect\(failedRequests[^)]*\)\.toEqual\(\[\]\)/);+ assert.match(source, /expect\(pageErrors[^)]*\)\.toEqual\(\[\]\)/);+ // The broken status must appear only as context, never as an expectation.+ assert.ok(!/expect\([^)]*\)\.toBe\(500\)/.test(source), 'must not assert the broken status');+ assert.ok(!/toContain\('TypeError/.test(source), 'must not assert the thrown error');+});++test('the spec is syntactically valid JavaScript', () => {+ // A generated file that does not parse is worse than no file at all, so the+ // output is compiled here. Imports are stripped because Function() bodies+ // cannot hold them; everything else is exactly what lands on disk.+ const { source } = compileToPlaywright(session, { title: "Export does nothing (it's broken)" });+ assert.doesNotThrow(() => new Function(`return async () => { ${source.replace(/^import .*$/gm, '')} }`));+});++test('semantic locators are emitted where the element had a semantic handle', () => {+ const { source } = compileToPlaywright(session, { title: 'x' });+ assert.match(source, /page\.getByTestId\('?"?export/);+ assert.match(source, /page\.getByLabel\("Model name"\)/);+ assert.match(source, /page\.getByRole\("button", \{ name: "Download" \}\)/);+});++test('the session viewport and locale are carried into the replay', () => {+ const { source } = compileToPlaywright(session, { title: 'x' });+ assert.match(source, /viewport: \{ width: 390, height: 844 \}/);+ assert.match(source, /locale: 'en-GB'/);+ assert.match(source, /hasTouch: true/);+});++test('a private field becomes an explicit placeholder, never an invented value', () => {+ const spec = compileToPlaywright(+ trace([+ { type: 'goto', detail: '/login' },+ { type: 'fill', detail: 'private', el: el({ strategy: 'label', value: 'Password', confidence: 85 }) },+ ]),+ { title: 'login' },+ );+ assert.match(spec.source, /WITNESS_INPUT \|\| 'replace-me'/);+ assert.ok(!spec.source.includes('hunter2'));+});++test('a report with no machine-visible failure refuses to look green', () => {+ const spec = compileToPlaywright(+ trace([+ { type: 'goto', detail: '/create' },+ { type: 'click', el: el() },+ ]),+ { title: 'the result looks wrong' },+ );+ assert.match(spec.source, /test\.fail\(true/);+ assert.match(spec.source, /Add the assertion this report is really about/);+});++test('the entry route drives the goto, and a base url is prefixed once', () => {+ assert.equal(entryRoute(session), '/avatar-studio');+ const { source } = compileToPlaywright(session, { title: 'x', baseUrl: 'https://three.ws/' });+ assert.match(source, /page\.goto\('https:\/\/three\.ws\/avatar-studio'\)/);+});++test('narration and the spec describe the same sequence', () => {+ const steps = narrate(session);+ assert.deepEqual(steps.slice(0, 4), [+ 'Open /avatar-studio',+ 'Click the button [export]',+ 'Type 11 characters into the button labelled "Model name"',+ 'Click the button "Download"',+ ]);+ assert.ok(steps.some((s) => s.startsWith('The page threw:')));+ assert.ok(steps.some((s) => s.startsWith('The request failed:')));+});++test('replay confidence reports the WEAKEST link, not the average', () => {+ const mixed = trace([+ { type: 'goto', detail: '/x' },+ { type: 'click', el: el() },+ { type: 'click', el: el({ strategy: 'path', value: 'div > button', confidence: 10 }) },+ ]);+ const { score, weakest } = replayConfidence(mixed);+ assert.equal(score, 10);+ assert.equal(weakest.strategy, 'path');+});++test('failuresIn separates the kinds so each gets its own assertion', () => {+ const found = failuresIn(session);+ assert.equal(found.network.length, 1);+ assert.equal(found.errors.length, 1);+ assert.equal(found.any, true);+ assert.equal(failuresIn(trace([{ type: 'click', el: el() }])).any, false);+});++test('a comment can never escape its own comment block', () => {+ const nasty = trace([+ { type: 'goto', detail: '/x' },+ { type: 'error', detail: 'Error: */ process.exit(1) /*', fatal: true },+ ]);+ const { source } = compileToPlaywright(nasty, { title: 'x' });+ assert.ok(!/^\/\/.*\*\/ process\.exit/m.test(source));+ assert.doesNotThrow(() => new Function(`return async () => { ${source.replace(/^import .*$/gm, '')} }`));+});++test('a repeated click is recorded once with its count, not replayed 50 times', () => {+ const spammed = trace([+ { type: 'goto', detail: '/x' },+ { type: 'click', el: el(), count: 47 },+ ]);+ const { source, steps } = compileToPlaywright(spammed, { title: 'x' });+ assert.equal((source.match(/\.click\(\)/g) || []).length, 1);+ assert.ok(steps.some((s) => s.includes('(x47)')));+});diff --git a/packages/witness/test/redact.test.js b/packages/witness/test/redact.test.jsnew file mode 100644index 000000000..ed1dde049--- /dev/null+++ b/packages/witness/test/redact.test.js@@ -0,0 +1,91 @@+// Privacy is enforced at capture time, so these are the tests that decide+// whether a live credential can end up in a bug report. Each one is a shape+// that has leaked out of a real logging pipeline at some company before.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { JSDOM } from 'jsdom';+import { redactText, redactUrl, isSensitiveField, summarizeInput } from '../src/redact.js';++function el(html) {+ return new JSDOM(`<!doctype html><body>${html}</body>`).window.document.body.firstElementChild;+}++test('secrets are replaced wherever they appear in free text', () => {+ const cases = [+ ['reach me at [email protected]', '[email]'],+ ['my key sk-abcdef0123456789abcdef', '[api-key]'],+ ['token ghp_abcdefghijklmnopqrstuvwxyz0123', '[token]'],+ ['eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N', '[jwt]'],+ ['card 4111 1111 1111 1111', '[card]'],+ ['wallet 0x71C7656EC7ab88b098defB751B7401B5f6d8976F', '[address]'],+ ];+ for (const [input, expected] of cases) {+ assert.match(redactText(input), new RegExp(expected.replace(/[[\]]/g, '\\$&')), input);+ }+});++test('a base58 run long enough to be a key never survives', () => {+ const mint = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ assert.equal(redactText(`the coin ${mint} broke`).includes(mint), false);+});++test('ordinary prose is left alone', () => {+ const plain = 'The download button does nothing on my phone.';+ assert.equal(redactText(plain), plain);+});++test('a url keeps its path and parameter names but never a credential value', () => {+ const out = redactUrl('https://three.ws/dashboard?token=supersecretvalue&tab=models', { origin: 'https://three.ws' });+ assert.equal(out, '/dashboard?token=[redacted]&tab=models');+ assert.ok(!out.includes('supersecretvalue'));+});++test('userinfo and the hash are dropped entirely', () => {+ const out = redactUrl('https://user:[email protected]/x#access_token=abc123', { origin: 'https://three.ws' });+ assert.ok(!out.includes('pw'));+ assert.ok(!out.includes('abc123'));+});++test('a cross-origin request keeps its origin so a third party is identifiable', () => {+ const out = redactUrl('https://api.stripe.com/v1/charges', { origin: 'https://three.ws' });+ assert.equal(out, 'https://api.stripe.com/v1/charges');+});++test('password and hidden inputs are always sensitive', () => {+ assert.equal(isSensitiveField(el('<input type="password">')), true);+ assert.equal(isSensitiveField(el('<input type="hidden" name="csrf">')), true);+});++test('a field is sensitive when any of its hints say so', () => {+ assert.equal(isSensitiveField(el('<input name="cardNumber">')), true);+ assert.equal(isSensitiveField(el('<input autocomplete="one-time-code">')), true);+ assert.equal(isSensitiveField(el('<input aria-label="Seed phrase">')), true);+ assert.equal(isSensitiveField(el('<input placeholder="[email protected]">')), true);+ assert.equal(isSensitiveField(el('<input name="modelName">')), false);+});++test('an opted-out subtree is never observed', () => {+ const form = el('<form data-witness="off"><input name="notes"></form>');+ assert.equal(isSensitiveField(form.querySelector('input')), true);+});++test('typed content is counted and shaped, never kept', () => {+ const input = el('<input name="modelName">');+ const summary = summarizeInput(input, 'Knight rider');+ assert.deepEqual(summary, { length: 12, shape: 'text' });+ assert.equal(JSON.stringify(summary).includes('Knight'), false);+});++test('a sensitive field yields no length at all, not even a hint', () => {+ assert.deepEqual(summarizeInput(el('<input type="password">'), 'hunter2'), { length: null, shape: 'private' });+});++test('shapes distinguish the cases a maintainer actually needs', () => {+ const field = el('<input name="q">');+ assert.equal(summarizeInput(field, '12345').shape, 'digits');+ assert.equal(summarizeInput(field, '[email protected]').shape, 'email');+ assert.equal(summarizeInput(field, 'https://x.dev').shape, 'url');+ assert.equal(summarizeInput(field, 'x'.repeat(200)).shape, 'paragraph');+ assert.equal(summarizeInput(field, '').shape, 'empty');+});diff --git a/packages/witness/test/selector.test.js b/packages/witness/test/selector.test.jsnew file mode 100644index 000000000..d6226fbcc--- /dev/null+++ b/packages/witness/test/selector.test.js@@ -0,0 +1,119 @@+// The selector ladder is what decides whether a generated test survives the+// next refactor, so every rung is pinned here, including the demotions.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { JSDOM } from 'jsdom';+import {+ describeElement,+ toPlaywrightLocator,+ describeForHuman,+ accessibleName,+ roleOf,+ structuralPath,+} from '../src/selector.js';++function dom(html) {+ const win = new JSDOM(`<!doctype html><body>${html}</body>`).window;+ // CSS.escape is not implemented by jsdom; the module falls back on its own+ // escaping when it is absent, which is exactly the path a real browser+ // without CSS.escape would take.+ globalThis.CSS = undefined;+ return win.document;+}++test('a test id wins over everything else on the element', () => {+ const doc = dom('<button data-testid="export" id="btn" aria-label="Export model">Export</button>');+ const desc = describeElement(doc.querySelector('button'));+ assert.equal(desc.strategy, 'testid');+ assert.equal(desc.value, 'export');+ assert.equal(toPlaywrightLocator(desc), 'page.getByTestId("export")');+});++test('a framework-generated id is refused in favour of the accessible name', () => {+ const doc = dom('<button id=":r3a:">Save changes</button>');+ const desc = describeElement(doc.querySelector('button'));+ assert.notEqual(desc.strategy, 'id');+ assert.equal(desc.strategy, 'role');+ assert.equal(toPlaywrightLocator(desc), 'page.getByRole("button", { name: "Save changes" })');+});++test('a hash-like class is refused, a hand-written one is kept', () => {+ const doc = dom('<div><span class="css-1x2y3z4 price-tag">$12</span></div>');+ const desc = describeElement(doc.querySelector('span'));+ assert.equal(desc.strategy, 'class');+ assert.equal(desc.value, 'price-tag');+});++test('utility classes never become selectors', () => {+ const doc = dom('<div><i class="px-4 py-2 text-sm rounded-lg"></i></div>');+ const desc = describeElement(doc.querySelector('i'));+ assert.equal(desc.strategy, 'path');+});++test('a duplicated role and name demotes rather than producing an ambiguous locator', () => {+ const doc = dom('<button>Delete</button><button>Delete</button>');+ const desc = describeElement(doc.querySelectorAll('button')[1]);+ assert.equal(desc.strategy, 'path');+ assert.match(desc.value, /nth-of-type\(2\)/);+});++test('an input is named by its label, and emits getByLabel only when aria-label is present', () => {+ const doc = dom('<label for="email-field">Email address</label><input id="email-field" name="email">');+ const input = doc.querySelector('input');+ assert.equal(accessibleName(input), 'Email address');+ // The id is hand-written, so it is the stronger handle and wins the ladder.+ const desc = describeElement(input);+ assert.equal(desc.strategy, 'id');+ assert.equal(toPlaywrightLocator(desc), 'page.locator("#email-field")');+});++test('aria-label produces a getByLabel locator', () => {+ const doc = dom('<div><button aria-label="Close dialog">x</button></div>');+ const desc = describeElement(doc.querySelector('button'));+ assert.equal(desc.strategy, 'label');+ assert.equal(toPlaywrightLocator(desc), 'page.getByLabel("Close dialog")');+});++test('aria-labelledby is resolved the way a screen reader resolves it', () => {+ const doc = dom('<h2 id="t">Billing</h2><section aria-labelledby="t"><p>x</p></section>');+ assert.equal(accessibleName(doc.querySelector('section')), 'Billing');+});++test('roles are implicit where the spec makes them implicit', () => {+ const doc = dom('<a href="/x">Go</a><a>Not a link</a><input type="checkbox"><h3>Title</h3>');+ assert.equal(roleOf(doc.querySelectorAll('a')[0]), 'link');+ assert.equal(roleOf(doc.querySelectorAll('a')[1]), null);+ assert.equal(roleOf(doc.querySelector('input')), 'checkbox');+ assert.equal(roleOf(doc.querySelector('h3')), 'heading');+});++test('a structural path is bounded so it stays readable', () => {+ const doc = dom('<div><div><div><div><div><div><span>deep</span></div></div></div></div></div></div>');+ const path = structuralPath(doc.querySelector('span'));+ assert.ok(path.split('>').length <= 5, path);+});++test('confidence falls as the ladder is descended', () => {+ const strong = describeElement(dom('<button data-testid="a">A</button>').querySelector('button'));+ const weak = describeElement(dom('<div><i></i></div>').querySelector('i'));+ assert.ok(strong.confidence > weak.confidence);+});++test('a human-readable description exists for every strategy', () => {+ const cases = [+ '<button data-testid="export">E</button>',+ '<button id="save-btn">S</button>',+ '<button aria-label="Close">x</button>',+ '<button>Unique text</button>',+ '<div><input placeholder="Search models"></div>',+ '<div><i class="thing-marker"></i></div>',+ '<div><em></em></div>',+ ];+ for (const html of cases) {+ const doc = dom(html);+ const el = doc.body.querySelector('button, input, i, em');+ const text = describeForHuman(describeElement(el));+ assert.ok(text && text.length > 2, `${html} -> ${text}`);+ }+});diff --git a/pages/feedback.html b/pages/feedback.htmlindex 6fb2610a8..7749c4192 100644--- a/pages/feedback.html+++ b/pages/feedback.html@@ -114,6 +114,45 @@.actions button[data-status='fixed']:hover { border-color: var(--green); color: var(--green); }.actions button[data-status='dismissed']:hover { border-color: var(--red); color: var(--red); }+ .repro-card {+ border: 1px solid rgba(59,130,246,.28); background: rgba(59,130,246,.05);+ border-radius: 10px; padding: 12px 14px; margin: 0 0 14px;+ }+ .repro-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }+ .repro-head > div:first-of-type { flex: 1; min-width: 180px; }+ .repro-head strong { display: block; font-size: 13.5px; }+ .repro-badge {+ display: grid; place-items: center; width: 38px; height: 38px; border-radius: 9px;+ font-weight: 700; font-size: 14px; font-variant-numeric: tabular-nums; flex: none;+ }+ .repro-badge[data-band='high'] { background: rgba(34,197,94,.16); color: var(--green); }+ .repro-badge[data-band='mid'] { background: rgba(245,158,11,.14); color: var(--amber); }+ .repro-badge[data-band='low'] { background: rgba(255,255,255,.05); color: var(--dim); }+ .repro-actions { display: flex; gap: 6px; flex-wrap: wrap; }+ .repro-actions button, .repro-actions a {+ background: transparent; border: 1px solid var(--line-2); color: var(--muted);+ border-radius: 7px; padding: 6px 11px; font: inherit; font-size: 12.5px; cursor: pointer;+ text-decoration: none; transition: background .15s ease, color .15s ease, border-color .15s ease;+ }+ .repro-actions button:hover, .repro-actions a:hover { color: var(--text); border-color: var(--blue); }+ .repro-actions button:focus-visible, .repro-actions a:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }+ .repro-actions button:disabled { opacity: .45; cursor: not-allowed; }+ .repro-steps {+ margin: 10px 0 0; padding: 0 0 0 20px; font-size: 12.5px; line-height: 1.6; color: var(--muted);+ }+ .repro-steps .repro-error { color: var(--amber); list-style: none; margin-left: -20px; }+ .repro-source {+ margin: 10px 0 0; padding: 12px; border-radius: 8px; background: rgba(0,0,0,.35);+ border: 1px solid var(--line); overflow-x: auto; max-height: 380px; overflow-y: auto;+ }+ .repro-source code {+ font: 11.5px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; color: #cfe0ff; white-space: pre;+ }+ .replay {+ border: 1px solid rgba(34,197,94,.4); color: var(--green); border-radius: 5px;+ padding: 0 6px; font-size: 11.5px;+ }+.skeleton { height: 68px; border-radius: 12px; background: var(--card); border: 1px solid var(--line); margin-bottom: 10px; position: relative; overflow: hidden; }.skeleton::after {content: ''; position: absolute; inset: 0; transform: translateX(-100%);@@ -144,8 +183,9 @@<p>What visitors told the corner companion. One row per distinct problem, loudest first,each carrying the route, the build it happened on, and the console errors the browser- captured at the time. Nothing here changes the product on its own: it is a list a- person reads and acts on.+ captured at the time. Where a session was recorded, the report compiles into a+ Playwright test that is red until the bug is fixed. Nothing here changes the product+ on its own: it is a list a person reads and acts on.</p></div>diff --git a/scripts/feedback-repro.mjs b/scripts/feedback-repro.mjsnew file mode 100644index 000000000..e54e8ee34--- /dev/null+++ b/scripts/feedback-repro.mjs@@ -0,0 +1,137 @@+#!/usr/bin/env node+/**+ * Turn a feedback report into a failing test in this repo.+ *+ * npm run feedback:repro -- <report-id>+ * npm run feedback:repro -- <report-id> --run+ * npm run feedback:repro -- --list+ *+ * This is the last mile of the loop that starts when a visitor tells the corner+ * companion something is broken. The session they recorded (packages/witness)+ * compiles into a Playwright spec written to tests/repros/, and the spec asserts+ * the FAILURE IS GONE, so it is red now and green when the bug is fixed. The+ * report stops being a description of a bug and becomes the test for it.+ *+ * Reads the database directly rather than the HTTP API, because the person+ * running this is already the maintainer and should not have to mint a session+ * to read their own queue. Needs DATABASE_URL (.env.local).+ */++import { mkdirSync, writeFileSync, existsSync } from 'node:fs';+import { join, relative } from 'node:path';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const ROOT = fileURLToPath(new URL('..', import.meta.url));+const OUT_DIR = join(ROOT, 'tests', 'repros');++const args = process.argv.slice(2);+const flags = new Set(args.filter((a) => a.startsWith('--')));+const positional = args.filter((a) => !a.startsWith('--'));++function usage(message) {+ if (message) console.error(`\n${message}\n`);+ console.error('Usage:');+ console.error(' npm run feedback:repro -- <report-id> write tests/repros/<slug>.spec.js');+ console.error(' npm run feedback:repro -- <report-id> --run write it, then run it');+ console.error(' npm run feedback:repro -- --list list reports that carry a recorded session');+ console.error(' npm run feedback:repro -- <id> --base <url> replay against a different origin');+ process.exit(message ? 1 : 0);+}++if (flags.has('--help') || flags.has('-h')) usage();++if (!process.env.DATABASE_URL) {+ console.error('DATABASE_URL is not set. Run with `node --env-file=.env.local` or export it first.');+ process.exit(2);+}++const { sql } = await import('../api/_lib/db.js');+const { compileToPlaywright, narrate, replayConfidence } = await import('../packages/witness/src/compile.js');++if (flags.has('--list')) {+ const rows = await sql`+ select id, coalesce(summary, left(body, 70)) as label, route, replay_confidence, trace_steps,+ status, created_at+ from feedback_reports+ where trace is not null+ order by created_at desc+ limit 30+ `;+ if (!rows.length) {+ console.log('No reports carry a recorded session yet.');+ console.log('One arrives as soon as somebody reports a problem from a page running the recorder.');+ process.exit(0);+ }+ console.log(`${rows.length} report(s) with a replayable session:\n`);+ for (const row of rows) {+ const score = row.replay_confidence ?? 0;+ console.log(+ ` ${row.id} ${String(score).padStart(3)}/100 ${String(row.trace_steps ?? 0).padStart(2)} steps ` ++ `${(row.route || '').padEnd(24).slice(0, 24)} ${row.label}`,+ );+ }+ console.log('\nCompile one: npm run feedback:repro -- <id>');+ process.exit(0);+}++const id = positional[0];+if (!id) usage('Pass a report id, or --list to see the ones that can be replayed.');++const [report] = await sql`+ select id, body, summary, route, build_sha, trace, trace_steps, replay_confidence, created_at+ from feedback_reports+ where id = ${id}+`;++if (!report) {+ console.error(`No feedback report with id ${id}. Try --list.`);+ process.exit(1);+}+if (!report.trace) {+ console.error(`Report ${id} has no recorded session, so there is nothing to replay.`);+ console.error('Reports filed before the recorder shipped, or from a browser that opted out, arrive without one.');+ process.exit(1);+}++const baseIdx = args.indexOf('--base');+const baseUrl = baseIdx >= 0 ? args[baseIdx + 1] : process.env.WITNESS_REPRO_BASE_URL || 'http://localhost:3000';++const compiled = compileToPlaywright(report.trace, {+ title: report.summary || report.body || 'reported issue',+ baseUrl,+ reportId: report.id,+});++mkdirSync(OUT_DIR, { recursive: true });+const outPath = join(OUT_DIR, compiled.filename);+const existed = existsSync(outPath);+writeFileSync(outPath, compiled.source);++const confidence = replayConfidence(report.trace);+const steps = narrate(report.trace);++console.log(`\n${existed ? 'Rewrote' : 'Wrote'} ${relative(ROOT, outPath)}`);+console.log(`Replay confidence ${confidence.score}/100. ${confidence.note}`);+console.log(`Replaying against ${baseUrl}\n`);+console.log('What the visitor did:');+for (const step of steps) console.log(` ${step}`);++if (flags.has('--run')) {+ console.log(`\nRunning it. It should FAIL while the reported bug is present.\n`);+ const result = spawnSync('npx', ['playwright', 'test', relative(ROOT, outPath)], {+ cwd: ROOT,+ stdio: 'inherit',+ });+ // A failing repro is the expected outcome, not an error in this script, so+ // the exit code is passed through for CI while the message stays honest.+ if (result.status !== 0) {+ console.log('\nThe reproduction failed, which means it reproduces. Fix the bug and run it again.');+ } else {+ console.log('\nThe reproduction passed. Either the bug is already fixed, or the session did not capture it.');+ }+ process.exit(result.status ?? 0);+}++console.log(`\nRun it: npx playwright test ${relative(ROOT, outPath)}`);+console.log('It is red until the bug is fixed.\n');diff --git a/src/feedback-page.js b/src/feedback-page.jsindex 5de7e4756..a70d1e987 100644--- a/src/feedback-page.js+++ b/src/feedback-page.js@@ -67,6 +67,9 @@ function clusterRow(c) {c.route ? `<code>${escape(c.route)}</code>` : '',c.build_sha ? `<code>${escape(c.build_sha)}</code>` : '',`<span>${ago(c.last_seen)}</span>`,+ // A cluster with a recorded session can be reproduced in one command, so+ // it is worth spotting from the collapsed row.+ c.traced ? `<span class="replay">replayable</span>` : '',].filter(Boolean).join('');@@ -106,6 +109,94 @@ function reportBlock(r) {`;}+function confidenceBand(score) {+ if (score >= 80) return 'high';+ if (score >= 40) return 'mid';+ return 'low';+}++// The reproduction panel. This is the part of the queue a maintainer actually+// acts on: the session compiles into a Playwright spec that is red until the+// bug is fixed, so "reproduce it" stops being the expensive first hour of the+// work and "is it fixed" stops being a judgement call.+function reproBlock(report) {+ const score = report.replay_confidence ?? 0;+ const steps = report.trace_steps ?? 0;+ return `+ <div class="repro-card" data-report="${escape(report.id)}">+ <div class="repro-head">+ <span class="repro-badge" data-band="${confidenceBand(score)}">${score}</span>+ <div>+ <strong>Recorded session</strong>+ <span class="meta">${steps} step${steps === 1 ? '' : 's'} captured · replay confidence ${score}/100</span>+ </div>+ <div class="repro-actions">+ <button type="button" class="repro-view">Show test</button>+ <button type="button" class="repro-copy">Copy test</button>+ <a class="repro-download" href="/api/feedback/repro?id=${encodeURIComponent(report.id)}" download>Download</a>+ </div>+ </div>+ <ol class="repro-steps"></ol>+ <pre class="repro-source" hidden><code></code></pre>+ </div>+ `;+}++async function wireRepro(holder, reportId) {+ const card = holder.querySelector('.repro-card');+ if (!card) return;+ const stepsEl = card.querySelector('.repro-steps');+ const sourceEl = card.querySelector('.repro-source');+ const codeEl = sourceEl.querySelector('code');+ const viewBtn = card.querySelector('.repro-view');+ const copyBtn = card.querySelector('.repro-copy');++ let compiled = null;+ async function load() {+ if (compiled) return compiled;+ const res = await fetch(`/api/feedback/repro?id=${encodeURIComponent(reportId)}&format=json`, {+ credentials: 'same-origin',+ });+ const data = await res.json();+ if (!res.ok) throw new Error(data?.message || 'Could not compile a reproduction.');+ compiled = data;+ return compiled;+ }++ try {+ const data = await load();+ stepsEl.innerHTML = data.steps.map((line) => `<li>${escape(line)}</li>`).join('');+ codeEl.textContent = data.source;+ } catch (err) {+ stepsEl.innerHTML = `<li class="repro-error">${escape(err.message)}</li>`;+ viewBtn.disabled = true;+ copyBtn.disabled = true;+ }++ viewBtn.addEventListener('click', () => {+ const open = !sourceEl.hidden;+ sourceEl.hidden = open;+ viewBtn.textContent = open ? 'Show test' : 'Hide test';+ });++ copyBtn.addEventListener('click', async () => {+ try {+ const data = await load();+ await navigator.clipboard.writeText(data.source);+ copyBtn.textContent = 'Copied';+ } catch {+ // Clipboard access can be denied outright. Reveal the source instead so+ // the maintainer can still select it by hand.+ sourceEl.hidden = false;+ viewBtn.textContent = 'Hide test';+ copyBtn.textContent = 'Select it above';+ }+ setTimeout(() => {+ copyBtn.textContent = 'Copy test';+ }, 2200);+ });+}+async function loadDetail(details) {const clusterKey = details.dataset.cluster;const holder = details.querySelector('.detail');@@ -116,8 +207,14 @@ async function loadDetail(details) {const data = await res.json();if (!res.ok) throw new Error(data?.message || 'Could not load the reports.');const repro = data.reports.find((r) => r.repro)?.repro;+ // The most replayable report in the cluster is the one worth compiling:+ // a spec is only as good as the selectors in the session it came from.+ const replayable = data.reports+ .filter((r) => r.trace)+ .sort((a, b) => (b.replay_confidence ?? 0) - (a.replay_confidence ?? 0))[0];holder.innerHTML = `${repro ? `<p class="repro"><strong>Repro guess:</strong> ${escape(repro)}</p>` : ''}+ ${replayable ? reproBlock(replayable) : ''}${data.reports.map(reportBlock).join('')}<div class="actions"><button type="button" data-status="accepted">Accept as real</button>@@ -128,6 +225,7 @@ async function loadDetail(details) {for (const btn of holder.querySelectorAll('.actions button')) {btn.addEventListener('click', () => updateStatus(clusterKey, btn.dataset.status, holder));}+ if (replayable) wireRepro(holder, replayable.id);} catch (err) {details.dataset.loaded = '';holder.innerHTML = `<p class="repro">${escape(err.message)} <button type="button" class="retry">Retry</button></p>`;