@cappa/cli 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +15 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +15 -7
- package/dist/index.mjs.map +1 -1
- package/integrations/claude/agents/cappa-judge.md +54 -0
- package/integrations/opencode/agents/cappa-judge.md +5 -2
- package/integrations/opencode/commands/cappa-approve.md +2 -0
- package/integrations/opencode/commands/cappa-review.md +7 -4
- package/integrations/skills/cappa/JUDGING.md +15 -2
- package/integrations/skills/cappa/SKILL.md +33 -8
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["run"],"sources":["../package.json","../../../node_modules/.pnpm/tsdown@0.23.0_@arethetypeswrong+core@0.18.5_oxc-resolver@11.24.2_tsx@4.23.1_typescript@7.0.2/node_modules/tsdown/esm-shims.js","../src/utils/agentSkills.ts","../src/commands/agent.ts","../src/commands/approve.ts","../src/utils/captureReport.ts","../src/utils/describeChanges.ts","../src/utils/parseMaxRegions.ts","../src/utils/remoteEngine.ts","../src/utils/server.ts","../src/commands/capture.ts","../src/commands/init.ts","../src/commands/review.ts","../src/commands/serve.ts","../src/commands/status.ts","../src/index.ts"],"sourcesContent":["","// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Agent integrations `cappa agent init` can install, and the files each one\n * gets.\n *\n * - `claude` — Claude Code: the skill in `.claude/skills/cappa`.\n * - `agents` — the vendor-neutral Agent Skills directory `.agents/skills`,\n * read by Codex, OpenCode and other agents that adopted it.\n * - `opencode` — OpenCode: the `.agents` skill plus slash commands that run\n * the review flow and a sandboxed `cappa-judge` subagent that judges\n * screenshots in its own context.\n *\n * Sources are relative to the package's `integrations/` directory; targets\n * are relative to the project.\n */\nconst SKILL = [\n \"skills/cappa/SKILL.md\",\n \"skills/cappa/JUDGING.md\",\n \"skills/cappa/MASKING.md\",\n] as const;\n\ntype FileMapping = { source: string; target: string };\n\nconst skillInto = (dir: string): FileMapping[] =>\n SKILL.map((source) => ({\n source,\n target: path.join(dir, path.basename(source)),\n }));\n\nexport const STACK_FILES = {\n claude: skillInto(\".claude/skills/cappa\"),\n agents: skillInto(\".agents/skills/cappa\"),\n opencode: [\n ...skillInto(\".agents/skills/cappa\"),\n ...[\n \"commands/cappa-review.md\",\n \"commands/cappa-judge.md\",\n \"commands/cappa-approve.md\",\n \"agents/cappa-judge.md\",\n ].map((file) => ({\n source: `opencode/${file}`,\n target: path.join(\".opencode\", file),\n })),\n ],\n} satisfies Record<string, FileMapping[]>;\n\nexport type SkillStack = keyof typeof STACK_FILES;\n\nexport const SKILL_STACK_NAMES = Object.keys(STACK_FILES) as SkillStack[];\n\n/**\n * Find the integration sources shipped with the package.\n *\n * They live in `integrations/` at the package root, which is one level above\n * `dist/` when installed and two above `src/utils/` in development — so walk\n * up instead of hard-coding either depth.\n */\nexport const findIntegrationsDir = (from: string = __dirname): string => {\n let current = from;\n while (true) {\n const candidate = path.join(current, \"integrations\");\n if (fs.existsSync(path.join(candidate, \"skills\", \"cappa\", \"SKILL.md\"))) {\n return candidate;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n throw new Error(\"Could not locate the bundled cappa agent skill files\");\n }\n current = parent;\n }\n};\n\n/**\n * Pick the stacks to install when none was named: whichever agents the\n * project already shows signs of, falling back to Claude Code.\n *\n * OpenCode wins over plain `agents` — its stack already includes the\n * `.agents` skill, and adds the commands on top.\n */\nexport const detectSkillStacks = (cwd: string): SkillStack[] => {\n const has = (entry: string) => fs.existsSync(path.join(cwd, entry));\n const stacks: SkillStack[] = [];\n if (has(\".claude\") || has(\"CLAUDE.md\")) stacks.push(\"claude\");\n if (has(\".opencode\") || has(\"opencode.json\") || has(\"opencode.jsonc\")) {\n stacks.push(\"opencode\");\n } else if (has(\".agents\") || has(\"AGENTS.md\")) {\n stacks.push(\"agents\");\n }\n return stacks.length > 0 ? stacks : [\"claude\"];\n};\n\n/**\n * How the project runs its own `cappa` binary, from its lockfile.\n *\n * Written into the installed files because OpenCode commands run shell\n * commands *before* the model sees anything, so a bare `cappa` that is not on\n * `PATH` would inject an error instead of the review state; and agent\n * permission rules match the command text literally.\n */\nexport const detectCappaRunner = (cwd: string): string => {\n const has = (entry: string) => fs.existsSync(path.join(cwd, entry));\n if (has(\"pnpm-lock.yaml\")) return \"pnpm exec cappa\";\n if (has(\"yarn.lock\")) return \"yarn cappa\";\n if (has(\"bun.lock\") || has(\"bun.lockb\")) return \"bunx cappa\";\n return \"npx cappa\";\n};\n\n/** Fill the `{{cappa}}` placeholder in a source file. */\nexport const renderIntegrationFile = (source: string, runner: string) =>\n source.replaceAll(\"{{cappa}}\", runner);\n\nexport type SkillFileResult = {\n stack: SkillStack;\n path: string;\n status: \"written\" | \"unchanged\" | \"skipped\";\n};\n\nexport type InstallResult = {\n runner: string;\n files: SkillFileResult[];\n warnings: string[];\n};\n\n/**\n * Copy each stack's files into the project.\n *\n * A file that exists with different content is left alone unless `force` is\n * set: users are expected to tailor these to their project, and an upgrade\n * must not silently discard that. A target shared by two stacks (the\n * `.agents` skill) is written once.\n */\nexport const installAgentSkills = async (options: {\n cwd: string;\n stacks: readonly SkillStack[];\n force?: boolean;\n runner?: string;\n sourceDir?: string;\n}): Promise<InstallResult> => {\n const sourceDir = options.sourceDir ?? findIntegrationsDir();\n const runner = options.runner ?? detectCappaRunner(options.cwd);\n const files: SkillFileResult[] = [];\n const seen = new Set<string>();\n\n for (const stack of options.stacks) {\n for (const mapping of STACK_FILES[stack]) {\n const target = path.resolve(options.cwd, mapping.target);\n if (seen.has(target)) continue;\n seen.add(target);\n\n const source = renderIntegrationFile(\n await fsp.readFile(path.join(sourceDir, mapping.source), \"utf8\"),\n runner,\n );\n const existing = await fsp\n .readFile(target, \"utf8\")\n .catch(() => undefined);\n\n if (existing === source) {\n files.push({ stack, path: target, status: \"unchanged\" });\n continue;\n }\n if (existing !== undefined && !options.force) {\n files.push({ stack, path: target, status: \"skipped\" });\n continue;\n }\n\n await fsp.mkdir(path.dirname(target), { recursive: true });\n await fsp.writeFile(target, source, \"utf8\");\n files.push({ stack, path: target, status: \"written\" });\n }\n }\n\n const warnings: string[] = [];\n const claudeSkill = fs.existsSync(\n path.resolve(options.cwd, \".claude/skills/cappa/SKILL.md\"),\n );\n if (options.stacks.includes(\"opencode\") && claudeSkill) {\n warnings.push(\n \"OpenCode reads .claude/skills too, and uses that copy of the cappa skill over the one in .agents/skills — keep the two in sync if you tailor them.\",\n );\n }\n\n return { runner, files, warnings };\n};\n","import { getConfig } from \"@cappa/config\";\nimport {\n type AgentReport,\n clearJudgment,\n collectScreenshots,\n isJudgedLabel,\n JUDGE_MODES,\n JUDGED_LABELS,\n type JudgedLabel,\n type JudgeMode,\n readAgentReport,\n runAgentCheck,\n ScreenshotFileSystem,\n toSlimAgentReport,\n type VerdictLabel,\n writeAgentVerdict,\n} from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport chalk from \"chalk\";\nimport { type Command, InvalidArgumentError } from \"commander\";\nimport {\n detectSkillStacks,\n installAgentSkills,\n SKILL_STACK_NAMES,\n type SkillStack,\n} from \"../utils/agentSkills\";\n\n/**\n * `cappa agent` — visual review for coding agents.\n *\n * Every subcommand takes `--json`, which prints exactly one JSON document to\n * stdout and nothing else, so an agent can parse it without scraping logs.\n */\n\ntype JsonOption = { json?: boolean };\n\nconst printJson = (value: unknown) => {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n};\n\n/** `CI=true`/`CI=1` — but not `CI=false`, which some tools set explicitly. */\nexport const isCi = (env: NodeJS.ProcessEnv = process.env): boolean => {\n const value = env.CI?.trim().toLowerCase();\n return !!value && value !== \"false\" && value !== \"0\";\n};\n\n/**\n * Run `action`, reporting a failure as `{ error }` under `--json` instead of\n * a log line an agent would have to find.\n */\nconst run = async (\n options: JsonOption,\n action: () => Promise<void>,\n): Promise<void> => {\n try {\n await action();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (options.json) {\n printJson({ error: message });\n } else {\n getLogger().error(message);\n }\n process.exitCode = 1;\n }\n};\n\nconst LABEL_COLORS: Record<VerdictLabel, (text: string) => string> = {\n \"regression-likely\": chalk.red,\n \"intentional-likely\": chalk.green,\n \"noise-likely\": chalk.gray,\n ambiguous: chalk.yellow,\n};\n\n/** Human-readable lines for a report — what `--json` prints, for people. */\nexport const describeAgentReport = (report: AgentReport): string[] => {\n const { totals } = report;\n const lines = [\n `${totals.passed}/${totals.total} passed · ${totals.changed} changed · ${totals.new} new · ${totals.deleted} deleted`,\n ];\n if (totals.pendingJudgments > 0) {\n lines.push(\n chalk.yellow(\n `${totals.pendingJudgments} awaiting judgment in ${report.outputDir}/.cappa-agent/judgments`,\n ),\n );\n }\n\n for (const entry of report.entries) {\n if (entry.category !== \"changed\" || !entry.verdict) {\n lines.push(`${chalk.bold(entry.name)} ${chalk.dim(entry.category)}`);\n continue;\n }\n const { label, headline, source } = entry.verdict;\n const tags = [\n source === \"agent\" ? \"judged\" : undefined,\n entry.pending ? \"pending\" : undefined,\n ].filter(Boolean);\n lines.push(\n `${chalk.bold(entry.name)} ${LABEL_COLORS[label](label)} — ${headline}${tags.length > 0 ? chalk.dim(` (${tags.join(\", \")})`) : \"\"}`,\n );\n if (entry.verdictError) {\n lines.push(chalk.red(` verdict.json ignored: ${entry.verdictError}`));\n }\n }\n\n return lines;\n};\n\ntype CheckOptions = JsonOption & {\n judge: JudgeMode;\n maxTileRegions?: number;\n};\n\nexport const agentCheck = (options: CheckOptions) =>\n run(options, async () => {\n const config = await getConfig();\n\n const report = await runAgentCheck({\n outputDir: config.outputDir,\n diff: config.diff,\n judge: options.judge,\n maxTileRegions: options.maxTileRegions,\n });\n\n if (options.json) {\n printJson(toSlimAgentReport(report));\n } else {\n getLogger().box({\n title: \"Agent Review\",\n message: describeAgentReport(report).join(\"\\n\"),\n });\n }\n\n if (report.entries.length > 0) {\n process.exitCode = 1;\n }\n });\n\ntype JudgeOptions = JsonOption & {\n label: JudgedLabel;\n headline: string;\n rationale?: string[];\n confidence?: number;\n};\n\nexport const agentJudge = (names: string[], options: JudgeOptions) =>\n run(options, async () => {\n const config = await getConfig();\n\n const written: Array<{ name: string; verdict: string }> = [];\n for (const name of names) {\n const verdict = await writeAgentVerdict(config.outputDir, name, {\n label: options.label,\n headline: options.headline,\n rationale: options.rationale,\n confidence: options.confidence,\n });\n written.push({ name, verdict });\n }\n\n if (options.json) {\n printJson({ written });\n } else {\n getLogger().success(\n `Recorded ${options.label} for ${written.length} screenshot(s) — run \\`cappa agent check\\` to apply`,\n );\n }\n });\n\ntype ApproveOptions = JsonOption & {\n label?: JudgedLabel[];\n};\n\nexport const agentApprove = (names: string[], options: ApproveOptions) =>\n run(options, async () => {\n if (isCi()) {\n throw new Error(\n \"Refusing to approve in CI — baselines are only changed on developer machines.\",\n );\n }\n if (names.length === 0 && !options.label?.length) {\n throw new Error(\"Name the screenshots to approve, or pass --label.\");\n }\n\n const config = await getConfig();\n const screenshots = await collectScreenshots(config.outputDir);\n const byName = new Map(screenshots.map((s) => [s.name, s]));\n\n const wanted = new Set(names);\n const unknown = names.filter((name) => {\n const screenshot = byName.get(name);\n return !screenshot || screenshot.category === \"passed\";\n });\n if (unknown.length > 0) {\n throw new Error(\n `Nothing to approve for: ${unknown.join(\", \")} — names must match exactly (see \\`cappa agent check --json\\`).`,\n );\n }\n\n if (options.label?.length) {\n // Re-check rather than trusting the last report: approving off a label\n // the screenshots no longer carry is exactly the mistake to prevent.\n const previous = await readAgentReport(config.outputDir);\n const report = await runAgentCheck({\n outputDir: config.outputDir,\n diff: config.diff,\n judge: previous?.judge ?? \"ambiguous\",\n });\n const labels = new Set<string>(options.label);\n for (const entry of report.entries) {\n if (\n entry.category === \"changed\" &&\n entry.verdict &&\n labels.has(entry.verdict.label)\n ) {\n wanted.add(entry.name);\n }\n }\n }\n\n const toApprove = [...wanted].flatMap((name) => {\n const screenshot = byName.get(name);\n return screenshot && screenshot.category !== \"passed\" ? [screenshot] : [];\n });\n\n const fileSystem = new ScreenshotFileSystem(config.outputDir);\n await fileSystem.approveScreenshots(toApprove, config.diff);\n await Promise.all(\n toApprove.map((screenshot) =>\n clearJudgment(config.outputDir, screenshot.name),\n ),\n );\n\n const approved = toApprove.map((s) => ({\n name: s.name,\n category: s.category,\n }));\n if (options.json) {\n printJson({ approved });\n } else if (approved.length === 0) {\n getLogger().warn(\"No screenshots matched\");\n } else {\n getLogger().success(\n `Approved ${approved.length} screenshot(s): ${approved.map((s) => s.name).join(\", \")}`,\n );\n }\n });\n\ntype InitOptions = JsonOption & {\n stack?: SkillStack | \"all\";\n force?: boolean;\n runner?: string;\n};\n\nexport const agentInit = (options: InitOptions) =>\n run(options, async () => {\n const cwd = process.cwd();\n const stacks =\n options.stack === \"all\"\n ? SKILL_STACK_NAMES\n : options.stack\n ? [options.stack]\n : detectSkillStacks(cwd);\n\n const { runner, files, warnings } = await installAgentSkills({\n cwd,\n stacks,\n force: options.force,\n runner: options.runner,\n });\n\n if (options.json) {\n printJson({ stacks, runner, files, warnings });\n return;\n }\n\n const logger = getLogger();\n for (const file of files) {\n const verb = {\n written: chalk.green(\"wrote\"),\n unchanged: chalk.dim(\"unchanged\"),\n skipped: chalk.yellow(\"skipped (modified — use --force)\"),\n }[file.status];\n logger.log(`${verb} ${file.path}`);\n }\n logger.log(chalk.dim(`commands run as \\`${runner}\\` (--runner to change)`));\n for (const warning of warnings) {\n logger.warn(warning);\n }\n logger.success(\n stacks.includes(\"opencode\")\n ? \"Agent integration installed — run /cappa-review in OpenCode, or /cappa in Claude Code\"\n : \"Agent skill installed — ask your agent to run a visual review, or use /cappa in Claude Code\",\n );\n });\n\nconst parseChoice =\n <T extends string>(choices: readonly T[], what: string) =>\n (value: string): T => {\n if (!(choices as readonly string[]).includes(value)) {\n throw new InvalidArgumentError(\n `${what} must be one of: ${choices.join(\", \")}`,\n );\n }\n return value as T;\n };\n\nconst parseLabel = (value: string): JudgedLabel => {\n if (!isJudgedLabel(value)) {\n throw new InvalidArgumentError(\n `label must be one of: ${JUDGED_LABELS.join(\", \")}`,\n );\n }\n return value;\n};\n\nconst collectLabel = (value: string, previous: JudgedLabel[] = []) => [\n ...previous,\n parseLabel(value),\n];\n\nconst parseConfidence = (value: string): number => {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {\n throw new InvalidArgumentError(\"confidence must be a number from 0 to 1\");\n }\n return parsed;\n};\n\nconst parsePositiveInt = (value: string): number => {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError(\"must be a positive integer\");\n }\n return parsed;\n};\n\nexport const registerAgentCommand = (program: Command): void => {\n const agent = program\n .command(\"agent\")\n .description(\n \"Visual review for coding agents: label changes, hand ambiguous ones to an agent, approve\",\n );\n\n agent\n .command(\"check\")\n .description(\n \"Label every changed screenshot and write judgment requests for an agent (does not capture)\",\n )\n .option(\n \"--judge <mode>\",\n `which changes get a judgment request: ${JUDGE_MODES.join(\", \")}`,\n parseChoice(JUDGE_MODES, \"--judge\"),\n \"ambiguous\",\n )\n .option(\n \"--max-tile-regions <count>\",\n \"regions rendered into each regions.png\",\n parsePositiveInt,\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentCheck);\n\n agent\n .command(\"judge\")\n .description(\"Record a verdict for screenshots with a judgment request\")\n .argument(\"<names...>\", \"screenshot names, exactly as reported\")\n .requiredOption(\"--label <label>\", JUDGED_LABELS.join(\" | \"), parseLabel)\n .requiredOption(\"--headline <text>\", \"one line describing the change\")\n .option(\"--rationale <text...>\", \"reasons for the verdict\")\n .option(\"--confidence <number>\", \"0 to 1\", parseConfidence)\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentJudge);\n\n agent\n .command(\"approve\")\n .description(\n \"Approve screenshots by exact name or by verdict label (refused in CI)\",\n )\n .argument(\"[names...]\", \"screenshot names, exactly as reported\")\n .option(\n \"--label <label>\",\n \"also approve every changed screenshot with this verdict label (repeatable)\",\n collectLabel,\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentApprove);\n\n agent\n .command(\"init\")\n .description(\"Install the cappa skill for coding agents in this project\")\n .option(\n \"--stack <stack>\",\n `${SKILL_STACK_NAMES.join(\", \")} or all (default: detected)`,\n parseChoice([...SKILL_STACK_NAMES, \"all\"] as const, \"--stack\"),\n )\n .option(\"--force\", \"overwrite skill files that were modified\")\n .option(\n \"--runner <command>\",\n \"how the project runs cappa, e.g. `pnpm exec cappa` (default: from the lockfile)\",\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentInit);\n};\n","import { getConfig } from \"@cappa/config\";\nimport type { Screenshot } from \"@cappa/core\";\nimport { groupScreenshots, ScreenshotFileSystem } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\n\nexport const approve = async (options: { filter?: string[] }) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n logger.start(\"Approving screenshots...\");\n\n const fileSystem = new ScreenshotFileSystem(config.outputDir);\n\n const [actualScreenshots, diffScreenshots, expectedScreenshots] =\n await Promise.all([\n fileSystem.getActualScreenshots(),\n fileSystem.getDiffScreenshots(),\n fileSystem.getExpectedScreenshots(),\n ]);\n\n let screenshotsToApprove = await groupScreenshots(\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n config.outputDir,\n );\n\n const filters =\n options.filter?.map((filter: string) => filter.toLowerCase()) ?? [];\n\n if (filters.length > 0) {\n logger.debug(\n `Filtering actual screenshots by filter: ${filters.join(\", \")}`,\n );\n\n screenshotsToApprove = filterScreenshots(screenshotsToApprove, filters);\n\n if (screenshotsToApprove.length === 0) {\n logger.warn(\"No screenshots matched the provided filter(s)\");\n return;\n }\n }\n\n await fileSystem.approveScreenshots(screenshotsToApprove, config.diff);\n\n if (filters.length > 0) {\n logger.success(\n `${screenshotsToApprove.length} screenshot(s) approved (filtered)`,\n );\n } else {\n logger.success(\"All screenshots approved\");\n }\n};\n\nexport const filterScreenshots = (\n screenshots: Screenshot[],\n filters: string[],\n) => {\n return screenshots.filter((screenshot) => {\n return filters.some((filter: string) => {\n const nameMatches = screenshot.name.toLowerCase().includes(filter);\n const pathMatches =\n \"actualPath\" in screenshot &&\n screenshot.actualPath?.toLowerCase().includes(filter);\n return nameMatches || pathMatches;\n });\n });\n};\n","import type { RunDetail, TaskFailure } from \"@cappa/core\";\nimport type { ReportableScreenshot } from \"./describeChanges\";\n\n/**\n * What `cappa capture --json` prints: one document an agent or a script can\n * act on, instead of a progress log and report boxes to scrape.\n *\n * It separates the two reasons a capture \"fails\", which the exit code alone\n * cannot: `errors` are tasks that broke (a story threw, a page timed out) and\n * need fixing before anything can be judged; `results` are screenshots that\n * captured fine but differ from their baseline and need reviewing.\n */\nexport type CaptureJsonReport = {\n /** Nothing failed and nothing differs. Mirrors the exit code. */\n ok: boolean;\n runId?: string;\n durationMs: number;\n tasks: { total: number; completed: number; failed: number };\n screenshots: {\n total: number;\n passed: number;\n changed: number;\n new: number;\n deleted: number;\n };\n /** Tasks that did not produce a comparable screenshot. */\n errors: Array<{ taskId: string; plugin: string; error: string }>;\n /** Every screenshot that is not `passed`. */\n results: Array<{\n name: string;\n category: string;\n taskId?: string;\n plugin?: string;\n percentDifference?: number;\n }>;\n /** The command that picks up from here, when there is something to review. */\n next?: string;\n};\n\nconst errorMessage = (error: unknown): string => {\n if (typeof error === \"string\") return error;\n if (error instanceof Error) return error.message;\n if (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as { message?: unknown }).message === \"string\"\n ) {\n return (error as { message: string }).message;\n }\n return String(error);\n};\n\n/**\n * A task failure that is a broken capture rather than a visual difference.\n *\n * A changed or new screenshot is reported as a failed task too; those are\n * already in `results` with their category, so only the failures that never\n * produced a comparable image belong here.\n */\nconst toCaptureError = (\n failure: TaskFailure,\n): CaptureJsonReport[\"errors\"][number] | undefined => {\n const { result } = failure;\n if (result.error !== undefined && result.error !== null) {\n return {\n taskId: failure.taskId,\n plugin: failure.pluginName,\n error: errorMessage(result.error),\n };\n }\n if (!result.filepath && result.skipped !== true) {\n return {\n taskId: failure.taskId,\n plugin: failure.pluginName,\n error: \"no screenshot was produced\",\n };\n }\n return undefined;\n};\n\nexport const buildCaptureJsonReport = ({\n detail,\n screenshots,\n durationMs,\n}: {\n detail: RunDetail | undefined;\n screenshots: readonly ReportableScreenshot[];\n durationMs: number;\n}): CaptureJsonReport => {\n const failures = detail?.failures ?? [];\n const deleted = detail?.deletedScreenshots ?? [];\n const count = (category: string) =>\n screenshots.filter((s) => s.category === category).length;\n\n const results = screenshots\n .filter((s) => s.category !== \"passed\")\n .map((s) => {\n const origin = s as ReportableScreenshot & {\n taskId?: string;\n plugin?: string;\n };\n return {\n name: s.name,\n category: s.category,\n ...(origin.taskId\n ? { taskId: origin.taskId, plugin: origin.plugin }\n : {}),\n ...(s.diffMeta?.percentDifference !== undefined\n ? { percentDifference: s.diffMeta.percentDifference }\n : {}),\n };\n });\n\n const errors = failures.flatMap((failure) => {\n const error = toCaptureError(failure);\n return error ? [error] : [];\n });\n\n return {\n ok: failures.length === 0 && deleted.length === 0,\n ...(detail ? { runId: detail.id } : {}),\n durationMs: Math.round(durationMs),\n tasks: {\n total: detail?.totalTasks ?? 0,\n completed: detail?.completedTasks ?? 0,\n failed: detail?.failedTasks ?? 0,\n },\n screenshots: {\n total: screenshots.length,\n passed: count(\"passed\"),\n changed: count(\"changed\"),\n new: count(\"new\"),\n deleted: count(\"deleted\"),\n },\n errors,\n results,\n ...(results.length > 0 ? { next: \"cappa agent check --json\" } : {}),\n };\n};\n","import { normalizeChangeType } from \"@cappa/core\";\nimport chalk from \"chalk\";\nimport { z } from \"zod\";\n\n/**\n * The interpretation fields this reporter actually reads.\n *\n * The protocol carries `diffMeta.interpretation` opaquely — its shape belongs\n * to `@blazediff/core-native` and pinning it in a versioned wire contract would\n * make every diff-engine upgrade a breaking protocol change. So a remote engine\n * hands this an `unknown`, and it narrows rather than trusts.\n *\n * Deliberately not the full `InterpretResult`: matching only what is rendered\n * means a diff engine that adds or reshapes a field the reporter ignores does\n * not silently cost the user their diff report.\n */\nconst regionSchema = z.object({\n bbox: z.object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n }),\n percentage: z.number(),\n position: z.string(),\n changeType: z.string(),\n});\n\ntype ParsedRegion = z.infer<typeof regionSchema>;\n\nconst interpretationSchema = z.object({\n severity: z.string(),\n totalRegions: z.number(),\n summary: z.string().optional(),\n // A region list that does not match is dropped rather than failing the whole\n // interpretation: severity and the region count still tell the user what\n // happened, which beats reporting nothing because one field moved.\n regions: z.array(regionSchema).catch([]).optional(),\n});\n\ntype ParsedInterpretation = z.infer<typeof interpretationSchema>;\n\n/**\n * A screenshot as far as this reporter is concerned.\n *\n * Looser than `@cappa/core`'s `Screenshot` in exactly one place — the\n * interpretation is `unknown` — so both a local and a remote engine's results\n * satisfy it.\n */\nexport type ReportableScreenshot = {\n name: string;\n category: string;\n diffMeta?: {\n percentDifference?: number;\n interpretation?: unknown;\n };\n};\n\n// Compared case-insensitively: `@blazediff/interpret-native` reports `high`\n// today and reported `High` before.\nconst severityColor = (severity: string) => {\n switch (severity.toLowerCase()) {\n case \"high\":\n return chalk.red;\n case \"medium\":\n return chalk.yellow;\n case \"low\":\n return chalk.green;\n default:\n return chalk.gray;\n }\n};\n\n/**\n * Human-readable labels for the `changeType` values reported by blazediff,\n * keyed by their normalised (kebab-case) form so both `color-change` and the\n * older `ColorChange` resolve.\n */\nconst CHANGE_TYPE_LABELS: Record<string, string> = {\n addition: \"added\",\n deletion: \"removed\",\n \"color-change\": \"color\",\n \"content-change\": \"content\",\n shift: \"shifted\",\n \"rendering-noise\": \"noise\",\n};\n\nconst changeTypeLabel = (changeType: string) =>\n CHANGE_TYPE_LABELS[normalizeChangeType(changeType)] ?? changeType;\n\n/** `content at center · 0.90% · 360x200 at (420, 300)` */\nconst describeRegion = (region: ParsedRegion): string => {\n const { bbox } = region;\n\n return [\n chalk.cyan(changeTypeLabel(region.changeType)),\n `at ${region.position}`,\n chalk.dim(\"·\"),\n `${region.percentage.toFixed(2)}%`,\n chalk.dim(\"·\"),\n chalk.dim(`${bbox.width}x${bbox.height} at (${bbox.x}, ${bbox.y})`),\n ].join(\" \");\n};\n\n/** Default number of regions listed per changed screenshot. */\nexport const DEFAULT_MAX_REGIONS = 5;\n\nexport type DescribeChangesOptions = {\n /**\n * Maximum number of interpreted regions listed per screenshot. The largest\n * regions are listed first; the remainder is collapsed into a\n * `… and N more region(s)` line. Set to `0` to omit the per-region\n * breakdown entirely.\n *\n * @default 5\n */\n maxRegions?: number;\n};\n\n/**\n * Build human-readable lines describing the changed screenshots, surfacing the\n * pixel-diff percentage and (when `diff.interpret` is enabled) the structured\n * interpretation: severity, region count, summary and the individual regions\n * with their position and bounding box.\n *\n * Returns an empty array when there are no changed screenshots.\n */\nexport const describeChanges = (\n screenshots: readonly ReportableScreenshot[],\n options: DescribeChangesOptions = {},\n): string[] => {\n const { maxRegions = DEFAULT_MAX_REGIONS } = options;\n\n const changed = screenshots.filter(\n (screenshot) => screenshot.category === \"changed\",\n );\n\n if (changed.length === 0) {\n return [];\n }\n\n const lines: string[] = [];\n\n for (const screenshot of changed) {\n const meta = screenshot.diffMeta;\n const parsed = interpretationSchema.safeParse(meta?.interpretation);\n const interpretation: ParsedInterpretation | undefined = parsed.success\n ? parsed.data\n : undefined;\n\n const parts: string[] = [];\n if (interpretation) {\n parts.push(\n severityColor(interpretation.severity)(\n interpretation.severity.toUpperCase(),\n ),\n );\n }\n if (meta?.percentDifference !== undefined) {\n parts.push(`${meta.percentDifference.toFixed(2)}%`);\n }\n if (interpretation) {\n const { totalRegions } = interpretation;\n parts.push(\n `${totalRegions} ${totalRegions === 1 ? \"region\" : \"regions\"}`,\n );\n }\n\n const suffix =\n parts.length > 0\n ? ` ${chalk.dim(\"·\")} ${parts.join(chalk.dim(\" · \"))}`\n : \"\";\n lines.push(`${chalk.bold(screenshot.name)}${suffix}`);\n\n if (interpretation?.summary) {\n lines.push(` ${chalk.dim(interpretation.summary)}`);\n }\n\n // Largest regions first, so truncating keeps the most significant ones.\n const regions = [...(interpretation?.regions ?? [])].sort(\n (a, b) => b.percentage - a.percentage,\n );\n if (maxRegions > 0 && regions.length > 0) {\n for (const region of regions.slice(0, maxRegions)) {\n lines.push(` ${chalk.dim(\"→\")} ${describeRegion(region)}`);\n }\n\n const remaining = regions.length - maxRegions;\n if (remaining > 0) {\n lines.push(\n chalk.dim(\n ` … and ${remaining} more ${remaining === 1 ? \"region\" : \"regions\"}`,\n ),\n );\n }\n }\n }\n\n return lines;\n};\n","import { InvalidArgumentError } from \"commander\";\nimport { DEFAULT_MAX_REGIONS } from \"./describeChanges\";\n\n/**\n * Parse the `--max-regions` option: a non-negative integer, where `0` disables\n * the per-region breakdown. Falls back to the default when omitted.\n */\nexport const parseMaxRegions = (value: string | undefined): number => {\n if (value === undefined) {\n return DEFAULT_MAX_REGIONS;\n }\n\n if (!/^\\d+$/.test(value.trim())) {\n throw new InvalidArgumentError(\n \"Expected a non-negative integer (0 disables the region breakdown).\",\n );\n }\n\n return Number(value.trim());\n};\n","import { createClient, ProtocolMismatchError } from \"@cappa/client\";\nimport type { CaptureEngine } from \"@cappa/core\";\nimport type { ReportableScreenshot } from \"./describeChanges\";\n\n/**\n * The engine `capture` drives.\n *\n * Identical to `CaptureEngine` except for `listScreenshots`, which is widened:\n * a remote engine carries `diffMeta.interpretation` opaquely, so the two\n * engines' screenshot types differ in exactly that one field. Everything\n * downstream narrows it rather than trusting it.\n */\nexport type CaptureCliEngine = Omit<CaptureEngine, \"listScreenshots\"> & {\n listScreenshots(): Promise<ReportableScreenshot[]>;\n};\n\n/** A pre-flight failure, already phrased for the user. */\nexport class RemoteServerError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RemoteServerError\";\n }\n}\n\n/**\n * The host already has a run in flight.\n *\n * Duck-typed rather than `instanceof`: `@cappa/client` ships dual ESM/CJS\n * builds, so the CLI can hold a different copy of the class than the one that\n * threw — the same hazard the client documents for its own 404 check.\n */\nexport const isRunInProgress = (\n error: unknown,\n): error is { activeRunId?: string } =>\n typeof error === \"object\" &&\n error !== null &&\n (error as { status?: number }).status === 409;\n\nconst isAuthFailure = (error: unknown): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n (error as { status?: number }).status === 401;\n\nconst isProtocolMismatch = (\n error: unknown,\n): error is { expected: number; actual: number } =>\n error instanceof ProtocolMismatchError ||\n (typeof error === \"object\" &&\n error !== null &&\n (error as { name?: string }).name === \"ProtocolMismatchError\");\n\nexport type ConnectOptions = {\n server: string;\n token?: string;\n};\n\n/**\n * Build a remote engine and prove the host is usable before capturing anything.\n *\n * One request to `/api/health` turns four different failures — unreachable\n * host, wrong token, protocol skew, and a host that cannot capture — into four\n * distinct messages, up front. The client performs the version handshake on its\n * first call anyway; doing it here is what makes the failure legible rather\n * than arriving mid-run with half a report already printed.\n */\nexport async function connectToServer(\n options: ConnectOptions,\n): Promise<CaptureCliEngine> {\n const engine = createClient({\n baseUrl: options.server,\n token: options.token,\n });\n\n let health: Awaited<ReturnType<typeof engine.health>>;\n\n try {\n health = await engine.health();\n } catch (error) {\n await engine.close();\n\n if (isAuthFailure(error)) {\n throw new RemoteServerError(\n `${options.server} rejected the access token. Pass --token <token>, or set CAPPA_TOKEN.`,\n );\n }\n\n if (isProtocolMismatch(error)) {\n throw new RemoteServerError(\n `${options.server} speaks protocol version ${error.actual}, this CLI expects ${error.expected}. Upgrade whichever is older.`,\n );\n }\n\n const reason = error instanceof Error ? error.message : String(error);\n throw new RemoteServerError(\n `Could not reach a cappa server at ${options.server}: ${reason}`,\n );\n }\n\n if (!health.capabilities.capture) {\n await engine.close();\n throw new RemoteServerError(\n `${options.server} is running read-only and cannot capture. Restart it without --read-only.`,\n );\n }\n\n return engine;\n}\n","import path from \"node:path\";\nimport { configToEngineOptions, type ResolvedUserConfig } from \"@cappa/config\";\nimport { LocalEngine } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport { createServer, isLoopbackHost } from \"@cappa/server\";\n\ntype Closeable = { close: () => Promise<unknown> };\n\nconst closeQuietly = async (name: string, closeable: Closeable) => {\n try {\n await closeable.close();\n } catch (error) {\n getLogger().debug(`Error closing ${name} during shutdown:`, error);\n }\n};\n\n/**\n * Shut a running server down cleanly on Ctrl-C or SIGTERM.\n *\n * Order matters: the HTTP server closes first so no new run can be started\n * mid-teardown, then the engine, which aborts an active run and closes the\n * browser. Without that last step a killed server can leave an orphaned\n * Chromium behind.\n *\n * The second signal exits immediately — if the first shutdown is wedged on a\n * capture that will not stop, the user should not have to reach for `kill -9`.\n */\nexport function registerShutdownHandlers(\n server: Closeable,\n engine: Closeable,\n exitFn: (code: number) => void = process.exit,\n): () => void {\n let shuttingDown = false;\n\n const handleSignal = async () => {\n if (shuttingDown) {\n exitFn(130);\n return;\n }\n shuttingDown = true;\n\n const logger = getLogger();\n logger.info(\"Shutting down…\");\n\n // Each close is independent: a server that fails to close must not stop\n // the engine from closing, or a failed shutdown leaks a browser process.\n await closeQuietly(\"server\", server);\n await closeQuietly(\"engine\", engine);\n\n exitFn(130);\n };\n\n // `on`, not `once`: a second Ctrl-C must reach the handler to force the exit.\n process.on(\"SIGINT\", handleSignal);\n process.on(\"SIGTERM\", handleSignal);\n\n return () => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n}\n\n/**\n * Read the access token from the flag, falling back to `CAPPA_TOKEN`.\n *\n * The environment fallback exists so a CI job does not have to put the token in\n * its process list, where anything on the box can read it.\n */\nexport const resolveToken = (token?: string): string | undefined =>\n token ?? process.env.CAPPA_TOKEN ?? undefined;\n\nexport type StartServerOptions = {\n config: ResolvedUserConfig;\n host: string;\n port: number;\n readOnly: boolean;\n token?: string;\n /** Serve the review UI alongside `/api/*`. */\n ui: boolean;\n};\n\nexport type RunningServer = {\n server: Awaited<ReturnType<typeof createServer>>;\n engine: LocalEngine;\n /** Where the server is actually reachable, with the token if there is one. */\n url: string;\n unregisterShutdownHandlers: () => void;\n};\n\n/** Wildcard binds: addresses to listen on, never addresses to open. */\nconst WILDCARD_HOSTS = new Set([\"0.0.0.0\", \"::\", \"[::]\"]);\n\n/**\n * The host to put in the URL a person is expected to click.\n *\n * A wildcard bind is the common way to expose the UI, and printing it verbatim\n * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,\n * handed to a user who then cannot reach their own review UI. `localhost` is\n * reachable on every interface the wildcard covers, so it is the right thing to\n * show; a specific host is printed as given, because that one is meaningful.\n */\nexport const toDisplayHost = (host: string): string =>\n isLoopbackHost(host) || WILDCARD_HOSTS.has(host) ? \"localhost\" : host;\n\n/**\n * Build an engine, wrap it in a server, and start listening.\n *\n * Shared by `review` and `serve`, which differ only in how they resolve a token\n * and what they print afterwards — everything from the engine to the bound\n * socket is the same, and was duplicated before `serve` existed.\n *\n * The token is taken as already-resolved: the two commands have deliberately\n * different policies (`review` generates one off loopback for the human reading\n * the URL it prints, `serve` refuses to start without one), and folding that\n * decision in here would hide it.\n */\nexport async function startServer(\n options: StartServerOptions,\n): Promise<RunningServer> {\n const logger = getLogger();\n const { config, host, port, readOnly, token, ui } = options;\n\n // The engine holds the config's live plugin objects, so it is built here — in\n // the process that evaluated cappa.config.ts — and injected into the server.\n const engine = new LocalEngine({\n ...configToEngineOptions(config),\n browserIdleTimeoutMs: config.review.browserIdleTimeout,\n });\n\n const server = await createServer({\n engine,\n isProd: true,\n ui,\n outputDir: path.resolve(config.outputDir),\n logger: logger.level >= 4,\n theme: config.review.theme,\n readOnly,\n token,\n });\n\n const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);\n\n await server.listen({ port, host });\n\n const displayHost = toDisplayHost(host);\n const query = token ? `?token=${token}` : \"\";\n\n return {\n server,\n engine,\n url: `http://${displayHost}:${port}${query}`,\n unregisterShutdownHandlers,\n };\n}\n","import path from \"node:path\";\nimport { configToEngineOptions, getConfig } from \"@cappa/config\";\nimport type {\n CaptureEngine,\n FailedScreenshot,\n RunDetail,\n RunEvent,\n Screenshot,\n SerializedError,\n TaskFailure,\n WatchEvent,\n} from \"@cappa/core\";\nimport { LocalEngine } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport { buildCaptureJsonReport } from \"../utils/captureReport\";\nimport {\n DEFAULT_MAX_REGIONS,\n describeChanges,\n type ReportableScreenshot,\n} from \"../utils/describeChanges\";\nimport { parseMaxRegions } from \"../utils/parseMaxRegions\";\nimport {\n type CaptureCliEngine,\n connectToServer,\n isRunInProgress,\n RemoteServerError,\n} from \"../utils/remoteEngine\";\nimport { resolveToken } from \"../utils/server\";\n\nasync function executeOnFailCallback(\n config: Awaited<ReturnType<typeof getConfig>>,\n groupedScreenshots: ReportableScreenshot[],\n { remote = false }: { remote?: boolean } = {},\n): Promise<void> {\n const logger = getLogger();\n\n if (!config.onFail) {\n return;\n }\n\n // The screenshots are on the host, not here, so resolving them against the\n // local `outputDir` would hand the callback paths to files that do not exist.\n // An upload of nothing is the one outcome worth ruling out, so the absolute\n // fields are left undefined and the callback is told why — once, not per\n // screenshot.\n if (remote && groupedScreenshots.length > 0) {\n logger.warn(\n \"Capturing against a remote server: onFail receives relative paths only, \" +\n \"because the screenshot files live on the host rather than this machine.\",\n );\n }\n\n const resolveLocal = (relative: string | undefined) =>\n !remote && relative ? path.resolve(config.outputDir, relative) : undefined;\n\n // `interpretation` arrives opaque from a remote host, and `FailedScreenshot`\n // types it as the diff engine's `InterpretResult`. The runtime shape is\n // whatever the host's diff engine produced either way; a consumer that reads\n // it should narrow, exactly as the changed-screenshot reporter does.\n const failingScreenshots = (groupedScreenshots as Screenshot[])\n .filter((screenshot) => screenshot.category !== \"passed\")\n .map(\n (screenshot): FailedScreenshot => ({\n ...screenshot,\n absoluteActualPath: resolveLocal(\n \"actualPath\" in screenshot ? screenshot.actualPath : undefined,\n ),\n absoluteExpectedPath: resolveLocal(\n \"expectedPath\" in screenshot ? screenshot.expectedPath : undefined,\n ),\n absoluteDiffPath: resolveLocal(\n \"diffPath\" in screenshot ? screenshot.diffPath : undefined,\n ),\n }),\n );\n\n if (failingScreenshots.length > 0) {\n logger.debug(\n `Executing onFail callback with ${failingScreenshots.length} failing screenshot(s)`,\n );\n\n try {\n await config.onFail(failingScreenshots);\n } catch (error) {\n logger.error(\"Error executing onFail callback:\", error);\n }\n }\n}\n\nexport function formatProgress(\n completed: number,\n total: number,\n taskId: string,\n): string {\n return `[${completed}/${total}] captured ${taskId}`;\n}\n\nexport function formatDuration(ms: number): string {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n\n if (minutes > 0) {\n return `${minutes}m ${remainingSeconds}s`;\n }\n return `${(ms / 1000).toFixed(2)}s`;\n}\n\nfunction generateFailureReportMessage(\n failedScreenshots: TaskFailure[],\n deletedScreenshots: string[],\n): string {\n const total = failedScreenshots.length + deletedScreenshots.length;\n if (total === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(`${chalk.red(`Total failures: ${total}`)}\\n`);\n\n // Group by plugin\n const byPlugin = new Map<string, TaskFailure[]>();\n for (const failed of failedScreenshots) {\n const pluginFailures = byPlugin.get(failed.pluginName);\n if (pluginFailures) {\n pluginFailures.push(failed);\n } else {\n byPlugin.set(failed.pluginName, [failed]);\n }\n }\n\n for (const [pluginName, failures] of byPlugin.entries()) {\n lines.push(`\\n${chalk.bold(`Plugin: ${pluginName}`)}`);\n\n for (const failed of failures) {\n lines.push(`\\n ${chalk.dim(\"Task ID:\")} ${failed.taskId}`);\n\n const result = failed.result;\n if (result.storyName) {\n lines.push(` ${chalk.dim(\"Story:\")} ${result.storyName}`);\n }\n if (result.error) {\n const errorMsg =\n typeof result.error === \"string\"\n ? result.error\n : result.error instanceof Error\n ? result.error.message\n : String(result.error);\n lines.push(` ${chalk.red(\"Error:\")} ${errorMsg}`);\n }\n if (result.success === false) {\n if (result.isNew) {\n lines.push(\n ` ${chalk.yellow(\"Status:\")} New screenshot (no baseline — run 'cappa approve' to accept)`,\n );\n } else {\n lines.push(` ${chalk.red(\"Status:\")} Failed (comparison failed)`);\n }\n }\n if (!result.filepath && result.skipped !== true) {\n lines.push(` ${chalk.red(\"Status:\")} Failed (no filepath generated)`);\n }\n }\n }\n\n if (deletedScreenshots.length > 0) {\n lines.push(`\\n${chalk.bold(\"Deleted baselines:\")}`);\n for (const screenshotPath of deletedScreenshots) {\n lines.push(\n ` ${chalk.dim(\"Name:\")} ${screenshotPath.replace(/\\.png$/, \"\")}`,\n );\n }\n }\n\n return lines.join(\"\\n\");\n}\n\ntype CaptureOptions = {\n ci?: boolean;\n json?: boolean;\n filter?: string;\n maxRegions?: number;\n server?: string;\n token?: string;\n watch?: boolean;\n};\n\n/**\n * An engine that can watch the filesystem.\n *\n * Feature-detected rather than assumed: the watch methods are optional on\n * `CaptureEngine` because only an engine that can see the files is able to\n * offer them, and `--watch` has to say so plainly instead of failing on an\n * undefined call.\n */\nexport type WatchCapableEngine = CaptureCliEngine &\n Required<Pick<CaptureEngine, \"startWatch\" | \"stopWatch\" | \"subscribeWatch\">>;\n\nexport const supportsWatch = (\n engine: CaptureCliEngine,\n): engine is WatchCapableEngine =>\n typeof engine.startWatch === \"function\" &&\n typeof engine.stopWatch === \"function\" &&\n typeof engine.subscribeWatch === \"function\";\n\n/**\n * Close `closeable` and exit 130 on SIGINT/SIGTERM.\n *\n * Typed structurally rather than against a concrete class so it can be handed\n * whatever owns the browser — that is the engine now, and a remote engine\n * later, neither of which the CLI should have to special-case here.\n */\nexport function registerSignalHandlers(\n closeable: { close(): Promise<void> },\n exitFn: (code: number) => void = process.exit,\n onSignal?: () => Promise<void>,\n): () => void {\n let handling = false;\n\n const handleSignal = async () => {\n // A second signal means the first teardown is taking too long — most likely\n // waiting on a remote run to acknowledge cancellation. Leave immediately\n // rather than making the user reach for `kill -9`, but say what that costs.\n if (handling) {\n getLogger().warn(\n \"Interrupted again — exiting now. The remote run may still be going.\",\n );\n exitFn(130);\n return;\n }\n handling = true;\n\n try {\n await onSignal?.();\n await closeable.close();\n } catch (error) {\n // Teardown that fails must not become an uncaught exception: the point of\n // the handler is to leave cleanly, and the user has already asked to go.\n getLogger().debug(\"Error during shutdown:\", error);\n }\n exitFn(130);\n };\n\n // `on`, not `once`: a second Ctrl-C must reach the handler to force the exit.\n process.on(\"SIGINT\", handleSignal);\n process.on(\"SIGTERM\", handleSignal);\n\n return () => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n}\n\n/**\n * Render a runner event to the terminal.\n *\n * All terminal presentation lives here — the runner itself is silent — so the\n * server can consume the exact same event stream without inheriting CLI output.\n */\nexport function renderRunEvent(event: RunEvent): void {\n const logger = getLogger();\n\n switch (event.type) {\n case \"log\":\n logger[event.level](event.message, ...event.args);\n break;\n\n case \"discover:plugin\":\n logger.info(`Found ${event.taskCount} tasks for ${event.plugin}`);\n break;\n\n case \"filter:applied\": {\n if (event.filter === undefined) {\n break;\n }\n\n logger.box({\n title: \"Filter Active\",\n message: `Only capturing tasks matching: ${chalk.cyan(event.filter)}`,\n });\n\n for (const entry of event.plugins) {\n logger.info(\n `${entry.plugin}: ${entry.after}/${entry.before} tasks match filter`,\n );\n }\n break;\n }\n\n case \"task:start\":\n logger.debug(`Executing task: ${event.taskId}`);\n break;\n\n case \"task:complete\":\n logger.info(formatProgress(event.completed, event.total, event.taskId));\n break;\n\n case \"plugin:complete\":\n if (event.failed) {\n logger.error(\n `Plugin ${event.plugin} completed with failures: ${event.resultCount} results`,\n );\n } else {\n logger.success(\n `Plugin ${event.plugin} completed: ${event.resultCount} results`,\n );\n }\n break;\n\n case \"run:error\":\n logger.error(\"Error during plugin execution:\", event.error.message);\n break;\n\n default:\n break;\n }\n}\n\n/**\n * One line for a settled batch of changes.\n *\n * Terse on purpose: this is the inner loop of somebody fixing a regression, and\n * a paragraph per save is noise. It still says *why* the iteration is the size\n * it is, because \"3 tasks\" and \"everything\" have very different causes.\n */\nexport function describeWatchChange(\n event: Extract<WatchEvent, { type: \"watch:change\" }>,\n): string {\n const files =\n event.files.length === 1\n ? (event.files[0] ?? \"\")\n : `${event.files.length} files`;\n\n const what = (() => {\n switch (event.scope) {\n case \"tasks\": {\n const count = event.taskIds?.length ?? 0;\n return `${count} task${count === 1 ? \"\" : \"s\"}`;\n }\n case \"plugins\":\n return \"every task of the affected plugin(s)\";\n case \"all\":\n return \"everything\";\n default:\n return \"nothing\";\n }\n })();\n\n return `${chalk.cyan(\"↻\")} ${what} · ${files} changed`;\n}\n\n/** The one-line result of a watch iteration. */\nexport function summarizeRunDetail(\n detail: RunDetail | undefined,\n duration: string,\n): string {\n if (!detail) {\n return `Run finished in ${duration}`;\n }\n\n const failures = detail.failures.length + detail.deletedScreenshots.length;\n const captured = `${detail.completedTasks}/${detail.totalTasks} captured`;\n\n if (failures > 0) {\n return chalk.yellow(`${captured}, ${failures} to review — ${duration}`);\n }\n\n return chalk.green(`${captured}, all passing — ${duration}`);\n}\n\n/**\n * A watch iteration's run output.\n *\n * Only what changed: a passing task in watch mode is the absence of news, and\n * printing every one of them buries the two lines that matter.\n */\nexport function renderWatchRunEvent(event: RunEvent): void {\n const logger = getLogger();\n\n switch (event.type) {\n case \"log\":\n if (event.level === \"warn\" || event.level === \"error\") {\n logger[event.level](event.message, ...event.args);\n }\n break;\n\n case \"task:complete\":\n if (event.status !== \"passed\" && event.status !== \"skipped\") {\n logger.info(` ${chalk.dim(event.status)} ${event.taskId}`);\n }\n break;\n\n case \"run:error\":\n logger.error(\"Error during plugin execution:\", event.error.message);\n break;\n\n default:\n break;\n }\n}\n\n/**\n * Stop watching and exit 0 on SIGINT/SIGTERM.\n *\n * Zero, not 130: quitting a watch session is how it is meant to end, and a\n * non-zero exit would make `cappa capture --watch` fail every shell script and\n * task runner that wraps it.\n */\nexport function registerWatchSignalHandlers(\n stop: () => Promise<void>,\n exitFn: (code: number) => void = process.exit,\n): () => void {\n let handling = false;\n\n const handleSignal = async () => {\n // A second signal while the first teardown is still going: leave now rather\n // than making the user reach for `kill -9`.\n if (handling) {\n exitFn(0);\n return;\n }\n handling = true;\n\n getLogger().info(\"Stopping watch…\");\n await stop();\n exitFn(0);\n };\n\n process.on(\"SIGINT\", handleSignal);\n process.on(\"SIGTERM\", handleSignal);\n\n return () => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n}\n\nexport type WatchCaptureOptions = {\n filter?: string;\n};\n\n/**\n * Watch for changes and re-capture, until interrupted.\n *\n * Resolves only when a signal stops the session, so the caller keeps the\n * process — and the warm browser — alive for as long as the user is editing.\n */\nexport async function watchCapture(\n engine: WatchCapableEngine,\n options: WatchCaptureOptions = {},\n exitFn: (code: number) => void = process.exit,\n): Promise<void> {\n const logger = getLogger();\n\n let release: (() => void) | undefined;\n const finished = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n const stop = async () => {\n try {\n await engine.stopWatch();\n await engine.close();\n } catch (error) {\n // Same reason as `registerSignalHandlers`: a browser that is already gone\n // is not a reason to exit with a stack trace.\n logger.debug(\"Error stopping the watch session:\", error);\n } finally {\n release?.();\n }\n };\n\n const unregisterSignalHandlers = registerWatchSignalHandlers(stop, exitFn);\n\n // Iterations are rendered one at a time: the session starts the next run only\n // after the previous one ends, and the output should read the same way.\n let rendering: Promise<void> = Promise.resolve();\n\n const unsubscribe = engine.subscribeWatch((event) => {\n switch (event.type) {\n case \"watch:start\":\n logger.info(\n `Watching ${event.paths.join(\", \")}${\n event.filter ? ` (filter: ${event.filter})` : \"\"\n } — press Ctrl-C to stop.`,\n );\n break;\n\n case \"watch:change\": {\n logger.info(describeWatchChange(event));\n\n if (event.error) {\n logger.warn(`Could not start a run: ${event.error}`);\n break;\n }\n\n const runId = event.runId;\n if (runId) {\n rendering = rendering.then(() =>\n renderWatchIteration(engine, runId).catch((error) => {\n logger.error(\"Error rendering the run:\", error);\n }),\n );\n }\n break;\n }\n\n default:\n break;\n }\n });\n\n try {\n await engine.startWatch({ filter: options.filter });\n await finished;\n } finally {\n unsubscribe();\n unregisterSignalHandlers();\n }\n}\n\nasync function renderWatchIteration(\n engine: WatchCapableEngine,\n runId: string,\n): Promise<void> {\n const logger = getLogger();\n const start = performance.now();\n\n await renderRunToCompletion(engine, runId, renderWatchRunEvent);\n\n const detail = await engine.getRun(runId);\n const duration = formatDuration(performance.now() - start);\n\n // A failing screenshot in watch mode is the thing being worked on, not a\n // reason to quit: it is reported and the session keeps going.\n logger.info(summarizeRunDetail(detail, duration));\n}\n\n/**\n * Rebuild a throwable error from the run's serialized one.\n *\n * The engine flattens the error a plugin threw so it can cross a network\n * boundary, but `capture` has always failed by letting that error escape — the\n * stack is the only debugging signal for a plugin that blew up. Reinstating\n * name, message and stack keeps that output intact.\n */\nfunction toThrowable(error: SerializedError): Error {\n const rebuilt = new Error(error.message);\n rebuilt.name = error.name;\n if (error.stack) {\n rebuilt.stack = error.stack;\n }\n return rebuilt;\n}\n\n/**\n * Subscribe to a run, render every event, and resolve when it terminates.\n *\n * Events buffered between `startRun` and this subscription are replayed\n * synchronously, so nothing emitted during start-up is lost.\n */\nasync function renderRunToCompletion(\n engine: CaptureCliEngine,\n runId: string,\n onEvent: (event: RunEvent) => void,\n): Promise<void> {\n let unsubscribe: (() => void) | undefined;\n\n try {\n await new Promise<void>((resolve) => {\n unsubscribe = engine.subscribeRun(runId, (event) => {\n onEvent(event);\n\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n resolve();\n }\n });\n });\n } finally {\n unsubscribe?.();\n }\n}\n\n/**\n * Print a JSON document and wait until it is flushed: `process.exit` right\n * after a plain `write` can cut off output that is still queued for a pipe.\n */\nconst writeJson = (value: unknown): Promise<void> =>\n new Promise((resolve) => {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`, () =>\n resolve(),\n );\n });\n\n/** How long a `SIGINT` waits for a remote host to acknowledge cancellation. */\nconst REMOTE_CANCEL_TIMEOUT_MS = 5000;\n\nexport const runCapture = async (\n options: CaptureOptions = {},\n): Promise<void> => {\n const logger = getLogger();\n const captureStart = performance.now();\n\n if (options.json && options.watch) {\n logger.error(\"--json cannot be combined with --watch: watch never ends.\");\n process.exit(1);\n return;\n }\n\n // stdout carries exactly one JSON document. Progress and report boxes are\n // info-level and muted; warnings and errors stay, and consola writes those\n // to stderr, so a failure is still explained without corrupting the output.\n if (options.json) {\n logger.level = Math.min(logger.level, 1);\n }\n\n // Checked before the config is even loaded: a conflicting invocation is a\n // mistake to name, not something to half-do.\n if (options.watch && options.server) {\n logger.error(\n \"--watch cannot be combined with --server: a remote host cannot see the files on this machine.\",\n );\n process.exit(1);\n return;\n }\n\n if (options.watch && options.ci) {\n logger.error(\n \"--watch cannot be combined with --ci: CI captures once and exits.\",\n );\n process.exit(1);\n return;\n }\n\n const config = await getConfig();\n\n const remote = options.server !== undefined;\n\n let engine: CaptureCliEngine;\n\n // `--token` authenticates against a host. Without one it does nothing, and\n // silently ignoring it is how a user ends up believing a capture was\n // authenticated when it was never remote in the first place.\n if (options.token && !options.server) {\n logger.error(\"--token only applies with --server.\");\n process.exit(1);\n return;\n }\n\n if (options.server) {\n // The host loads its own `cappa.config.ts`: plugins are live closures and\n // cannot be sent anywhere. Every capture setting in the local config —\n // plugins, outputDir, diff, concurrency — belongs to the host instead, and\n // a user who does not know that will wonder why theirs had no effect.\n logger.info(\n `Capturing on ${options.server}, which uses its own cappa.config.ts. Local capture settings do not apply.`,\n );\n\n try {\n engine = await connectToServer({\n server: options.server,\n token: resolveToken(options.token),\n });\n } catch (error) {\n if (error instanceof RemoteServerError) {\n logger.error(error.message);\n process.exit(1);\n return;\n }\n throw error;\n }\n } else {\n engine = new LocalEngine({\n ...configToEngineOptions(config),\n // A one-shot capture has no next run to keep a browser warm for, so hand\n // it back as soon as the run ends rather than leaving an idle Chromium\n // around for the rest of the process's life.\n //\n // Watch mode has the opposite need. Its session holds an eviction lease\n // once started, but the gap between the first run finishing and the\n // watcher starting is not covered by it — with a zero timeout the browser\n // would be gone before the first save, which is exactly the cost watch\n // mode exists to avoid.\n browserIdleTimeoutMs: options.watch\n ? config.review?.browserIdleTimeout\n : 0,\n });\n }\n\n const isCi = options.ci || process.env.CI === \"true\";\n\n let detail: RunDetail | undefined;\n // Read the diff metadata sidecars once and reuse them for both the onFail\n // callback and the changed-screenshot report below.\n let groupedScreenshots: ReportableScreenshot[] = [];\n let activeRunId: string | undefined;\n let runCompleted: Promise<void> | undefined;\n\n // Ctrl-C locally does not stop a run on another machine, so ask the host to\n // cancel and wait for it to say it has.\n //\n // Waiting for the *terminal event* rather than for `cancelRun` to return is\n // the point: closing the engine aborts the event stream, so returning early\n // would tear down the connection while the host is still winding the run\n // down — and the CLI would never learn whether it stopped. Bounded, because\n // a wedged host must not hold the terminal hostage; a second signal skips\n // the wait entirely.\n const cancelRemoteRun = async () => {\n if (!remote || !activeRunId) {\n return;\n }\n\n logger.info(\"Cancelling the remote run…\");\n\n try {\n await engine.cancelRun(activeRunId);\n\n await Promise.race([\n runCompleted?.catch(() => undefined) ?? Promise.resolve(),\n new Promise((resolve) => {\n setTimeout(resolve, REMOTE_CANCEL_TIMEOUT_MS).unref?.();\n }),\n ]);\n } catch (error) {\n logger.debug(\"Error cancelling the remote run:\", error);\n }\n };\n\n const unregisterSignalHandlers = registerSignalHandlers(\n engine,\n process.exit,\n cancelRemoteRun,\n );\n\n try {\n let run: Awaited<ReturnType<CaptureCliEngine[\"startRun\"]>>;\n\n try {\n run = await engine.startRun({\n filter: options.filter,\n // Only a full run starts from an empty `actual/`. A filtered run\n // captures a subset; clearing would leave every other screenshot with\n // a baseline and no capture — `deleted` — and approving that deletes\n // the baseline. Each captured screenshot replaces its own diff instead.\n clearActual: !options.filter,\n });\n } catch (error) {\n // One run at a time is the host's deliberate design, not a fault, so it\n // gets a sentence rather than a stack trace.\n if (isRunInProgress(error)) {\n const active = error.activeRunId ? ` (run ${error.activeRunId})` : \"\";\n logger.error(\n `${options.server} is already running a capture${active}. Wait for it to finish, or cancel it, and try again.`,\n );\n process.exit(1);\n return;\n }\n throw error;\n }\n\n activeRunId = run.id;\n\n runCompleted = renderRunToCompletion(engine, run.id, renderRunEvent);\n await runCompleted;\n\n detail = await engine.getRun(run.id);\n\n const failedDuringRun = detail?.error !== undefined;\n const hasFailure =\n (detail?.failures.length ?? 0) > 0 ||\n (detail?.deletedScreenshots.length ?? 0) > 0;\n\n if (!failedDuringRun && (isCi || hasFailure || options.json)) {\n try {\n groupedScreenshots = await engine.listScreenshots();\n } catch (err) {\n logger.warn(\"Could not collect screenshot results:\", err);\n }\n }\n } finally {\n unregisterSignalHandlers();\n // Watch mode keeps this engine — and its warm browser — for the rest of the\n // session; `watchCapture` closes it when the user stops.\n if (!options.watch) {\n await engine.close();\n }\n }\n\n // A plugin that threw has always escaped this command rather than being\n // summarised, and the browser is closed by the time it does.\n if (detail?.error) {\n if (options.json) {\n await writeJson({\n ok: false,\n runId: detail.id,\n error: detail.error.message,\n });\n process.exit(1);\n return;\n }\n throw toThrowable(detail.error);\n }\n\n const failures = detail?.failures ?? [];\n const deletedScreenshots = detail?.deletedScreenshots ?? [];\n const hasScreenshotFailure =\n failures.length > 0 || deletedScreenshots.length > 0;\n\n if (isCi) {\n await executeOnFailCallback(config, groupedScreenshots, { remote });\n }\n\n if (options.json) {\n const report = buildCaptureJsonReport({\n detail,\n screenshots: groupedScreenshots,\n durationMs: performance.now() - captureStart,\n });\n await writeJson(report);\n if (!report.ok) {\n process.exit(1);\n }\n return;\n }\n\n const duration = formatDuration(performance.now() - captureStart);\n\n if (hasScreenshotFailure) {\n const reportMessage = generateFailureReportMessage(\n failures,\n deletedScreenshots,\n );\n logger.box({\n title: \"Failed Screenshots\",\n message: reportMessage,\n });\n\n // Surface the diff stats and, when `diff.interpret` is enabled, what\n // changed and where — this is often the only debugging signal on CI.\n const changeLines = describeChanges(groupedScreenshots, {\n maxRegions: options.maxRegions,\n });\n if (changeLines.length > 0) {\n logger.box({\n title: \"Changed Screenshots\",\n message: changeLines.join(\"\\n\"),\n });\n }\n\n if (options.watch) {\n // Not an exit: a failing screenshot is what the user is here to fix.\n logger.warn(`One or more screenshots failed in ${duration}.`);\n } else {\n logger.error(\n `One or more screenshots failed in ${duration}. See report above for details.`,\n );\n process.exit(1);\n }\n } else {\n logger.success(`All plugins completed successfully in ${duration}`);\n }\n\n if (options.watch) {\n if (!supportsWatch(engine)) {\n logger.error(\"This engine cannot watch files.\");\n await engine.close();\n process.exit(1);\n return;\n }\n\n await watchCapture(engine, { filter: options.filter });\n }\n};\n\nexport const registerCaptureCommand = (program: Command): void => {\n program\n .command(\"capture\")\n .description(\"Capture screenshots\")\n .option(\"--ci\", \"run capture in CI mode and execute onFail callback\")\n .option(\n \"--json\",\n \"print a JSON summary to stdout instead of progress and reports\",\n )\n .option(\n \"-f, --filter <pattern>\",\n \"only capture tasks whose id matches the given glob pattern\",\n )\n .option(\n \"--max-regions <count>\",\n \"maximum number of interpreted diff regions listed per changed screenshot (0 to disable)\",\n parseMaxRegions,\n DEFAULT_MAX_REGIONS,\n )\n .option(\n \"--server <url>\",\n \"capture against a `cappa serve` host instead of a local browser\",\n )\n .option(\n \"--token <token>\",\n \"access token for --server (falls back to CAPPA_TOKEN)\",\n )\n .option(\n \"-w, --watch\",\n \"capture once, then re-capture affected tasks whenever files change\",\n )\n .action(async (options: CaptureOptions) => {\n await runCapture(options);\n });\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { defaultConfig } from \"@cappa/config\";\nimport { getLogger } from \"@cappa/logger\";\n\nexport const init = async () => {\n const logger = getLogger();\n\n const configPath = path.resolve(process.cwd(), \"cappa.config.ts\");\n const packageJsonPath = path.resolve(process.cwd(), \"package.json\");\n\n // Create cappa.config.ts\n if (fs.existsSync(configPath)) {\n logger.warn(\"cappa.config.ts already exists, skipping...\");\n } else {\n fs.writeFileSync(configPath, defaultConfig);\n logger.success(\"Created cappa.config.ts\");\n }\n\n // Add scripts to package.json\n if (fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n\n if (!packageJson.scripts) {\n packageJson.scripts = {};\n }\n\n if (packageJson.scripts.cappa) {\n logger.warn(\n \"'cappa' script already exists in package.json, skipping...\",\n );\n } else {\n packageJson.scripts.cappa = \"cappa capture\";\n }\n\n if (packageJson.scripts[\"cappa:review\"]) {\n logger.warn(\n \"'cappa:review' script already exists in package.json, skipping...\",\n );\n } else {\n packageJson.scripts[\"cappa:review\"] = \"cappa review\";\n }\n\n fs.writeFileSync(\n packageJsonPath,\n `${JSON.stringify(packageJson, null, 2)}\\n`,\n );\n logger.success(\"Added 'cappa' scripts to package.json\");\n } catch (error) {\n logger.error(\"Failed to update package.json:\", error);\n }\n } else {\n logger.warn(\"package.json not found, skipping script addition\");\n }\n\n logger.success(\"Cappa initialization complete!\");\n logger.warn(\n \"cappa relies on playwright to capture screenshots. Please install playwright and browsers before running cappa.\",\n );\n};\n","import { randomBytes } from \"node:crypto\";\nimport { getConfig } from \"@cappa/config\";\nimport { getLogger } from \"@cappa/logger\";\nimport { isLoopbackHost } from \"@cappa/server\";\nimport { resolveToken, startServer } from \"../utils/server\";\n\nexport type ReviewOptions = {\n port?: number;\n host?: string;\n readOnly?: boolean;\n token?: string;\n};\n\nexport const review = async (options: ReviewOptions = {}) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n const host = options.host ?? \"127.0.0.1\";\n const port = options.port ?? config.review.port;\n const readOnly = options.readOnly ?? false;\n\n // The engine drives a real browser and writes to disk. On loopback that is\n // the user's own machine; exposed to a network it is not, so a token is\n // mandatory there — generated when one was not supplied, and printed as part\n // of the URL so it is usable without extra steps.\n let token = resolveToken(options.token);\n let tokenWasGenerated = false;\n if (!token && !isLoopbackHost(host) && !readOnly) {\n token = randomBytes(24).toString(\"base64url\");\n tokenWasGenerated = true;\n logger.warn(\n `Binding to ${host} exposes capture control beyond this machine; requiring an access token.`,\n );\n }\n\n const { url } = await startServer({\n config,\n host,\n port,\n readOnly,\n token,\n ui: true,\n });\n\n logger.success(`Review UI available at ${url}`);\n\n // `success` is an info-level log, so it is suppressed below `-l 3`. A\n // generated token is the only way into the server — printing it somewhere the\n // user may not see would leave them locked out of their own review UI — so\n // repeat it at the same level as the warning that announced it.\n if (tokenWasGenerated && logger.level < 3) {\n logger.warn(`Review UI available at ${url}`);\n }\n\n if (readOnly) {\n logger.info(\"Running read-only: capture and approval are disabled.\");\n }\n};\n","import { getConfig } from \"@cappa/config\";\nimport { getLogger } from \"@cappa/logger\";\nimport { isLoopbackHost } from \"@cappa/server\";\nimport { resolveToken, startServer } from \"../utils/server\";\n\nexport type ServeOptions = {\n port?: number;\n host?: string;\n readOnly?: boolean;\n token?: string;\n /** Commander sets this to `false` for `--no-ui`. */\n ui?: boolean;\n};\n\n/**\n * Host a capture engine for a remote `cappa capture --server`.\n *\n * `review` minus the assumption that a person is about to open a browser. The\n * one deliberate divergence is the token: `review` generates one off loopback\n * because a human is reading the URL it prints, and `serve` has no such reader —\n * generating one here would produce a daemon nobody can authenticate against.\n * So off loopback it is required, and the command refuses to start without one.\n */\nexport const serve = async (options: ServeOptions = {}) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n const host = options.host ?? \"127.0.0.1\";\n const port = options.port ?? config.review.port;\n const readOnly = options.readOnly ?? false;\n const ui = options.ui ?? true;\n\n const token = resolveToken(options.token);\n\n if (!token && !isLoopbackHost(host) && !readOnly) {\n logger.error(\n `Binding to ${host} exposes capture control beyond this machine, so an access token is required. ` +\n \"Pass --token <token>, or set CAPPA_TOKEN to keep it out of the process list.\",\n );\n process.exit(1);\n return;\n }\n\n const { url } = await startServer({\n config,\n host,\n port,\n readOnly,\n token,\n ui,\n });\n\n // One structured line, then quiet: nothing is watching this the way a human\n // watches `review`, so the output exists to be greppable in a CI log.\n logger.log(\n `cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? \"yes\" : \"no\"}`,\n );\n\n if (ui) {\n logger.info(`Review UI available at ${url}`);\n }\n\n if (readOnly) {\n logger.info(\"Running read-only: capture and approval are disabled.\");\n }\n};\n","import { getConfig } from \"@cappa/config\";\nimport { collectScreenshots } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport chalk from \"chalk\";\n\nimport { describeChanges } from \"../utils/describeChanges\";\n\ntype StatusOptions = {\n maxRegions?: number;\n};\n\nexport const status = async (options: StatusOptions = {}) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n const groupedScreenshots = await collectScreenshots(config.outputDir);\n\n logger.debug(\n \"All screenshot information:\",\n JSON.stringify(groupedScreenshots, null, 2),\n );\n\n logger.box({\n title: \"Screenshot Status\",\n message: `${chalk.yellow(\"New screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"new\").length}\\n${chalk.red(\"Deleted screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"deleted\").length}\\n${chalk.green(\"Changed screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"changed\").length}\\n${chalk.blue(\"Passed screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"passed\").length}`,\n });\n\n const changeLines = describeChanges(groupedScreenshots, {\n maxRegions: options.maxRegions,\n });\n if (changeLines.length > 0) {\n logger.box({\n title: \"Changed Screenshots\",\n message: changeLines.join(\"\\n\"),\n });\n }\n\n if (\n groupedScreenshots.some((s) =>\n [\"new\", \"changed\", \"deleted\"].includes(s.category),\n )\n ) {\n process.exitCode = 1;\n }\n};\n","import { initLogger } from \"@cappa/logger\";\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { registerAgentCommand } from \"./commands/agent\";\nimport { approve } from \"./commands/approve\";\nimport { registerCaptureCommand } from \"./commands/capture\";\nimport { init } from \"./commands/init\";\nimport { review } from \"./commands/review\";\nimport { serve } from \"./commands/serve\";\nimport { status } from \"./commands/status\";\nimport { DEFAULT_MAX_REGIONS } from \"./utils/describeChanges\";\nimport { parseMaxRegions } from \"./utils/parseMaxRegions\";\n\nconst program = new Command();\n\nprogram\n .name(\"cappa\")\n .description(\"Cappa CLI\")\n .version(version)\n .option(\n \"-l, --log-level <level>\",\n \"set log level (0: fatal and error, 1: warn, 2: log, 3: info, 4: debug, 5: trace)\",\n \"3\",\n )\n .hook(\"preAction\", (thisCommand) => {\n const logLevel = parseInt(thisCommand.opts().logLevel, 10);\n const logger = initLogger(logLevel);\n logger?.debug(`Log level set to: ${logLevel}`);\n });\n\nregisterCaptureCommand(program);\n\nprogram\n .command(\"review\")\n .description(\"Open the review and capture UI\")\n .option(\"-p, --port <port>\", \"port to listen on\", (v) =>\n Number.parseInt(v, 10),\n )\n .option(\n \"--host <host>\",\n \"host to bind to (a non-loopback host requires an access token)\",\n )\n .option(\n \"--read-only\",\n \"serve the UI without capture, approval or any other mutation\",\n )\n .option(\n \"--token <token>\",\n \"require this access token on every API request (falls back to CAPPA_TOKEN)\",\n )\n .action(review);\n\nprogram\n .command(\"serve\")\n .description(\"Host a capture engine for a remote `cappa capture --server`\")\n .option(\"-p, --port <port>\", \"port to listen on\", (v) =>\n Number.parseInt(v, 10),\n )\n .option(\n \"--host <host>\",\n \"host to bind to (a non-loopback host requires an access token)\",\n )\n .option(\n \"--read-only\",\n \"serve without capture, approval or any other mutation\",\n )\n .option(\n \"--token <token>\",\n \"require this access token on every API request (falls back to CAPPA_TOKEN)\",\n )\n .option(\"--no-ui\", \"serve the API only, without the review UI\")\n .action(serve);\n\nprogram\n .command(\"approve\")\n .description(\"Approve screenshots\")\n .option(\n \"-f, --filter <filter...>\",\n \"only approve screenshots whose name includes the provided filter value(s)\",\n )\n .action(approve);\n\nprogram\n .command(\"status\")\n .description(\"Get status of screenshots\")\n .option(\n \"--max-regions <count>\",\n \"maximum number of interpreted diff regions listed per changed screenshot (0 to disable)\",\n parseMaxRegions,\n DEFAULT_MAX_REGIONS,\n )\n .action(status);\n\nregisterAgentCommand(program);\n\nprogram\n .command(\"init\")\n .description(\"Initialize Cappa in the current directory\")\n .action(init);\n\nexport async function run(): Promise<void> {\n await program.parseAsync();\n}\n"],"x_google_ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;ACIA,MAAM,oBAAoB,cAAc,YAAY,GAAG;AACvD,MAAM,mBAAmB,KAAK,QAAQ,YAAY,CAAC;AAEnD,MAAa,YAA4B,2BAAW;;;;;;;;;;;;;;;;;ACWpD,MAAM,QAAQ;CACZ;CACA;CACA;AACF;AAIA,MAAM,aAAa,QACjB,MAAM,KAAK,YAAY;CACrB;CACA,QAAQ,KAAK,KAAK,KAAK,KAAK,SAAS,MAAM,CAAC;AAC9C,EAAE;AAEJ,MAAa,cAAc;CACzB,QAAQ,UAAU,sBAAsB;CACxC,QAAQ,UAAU,sBAAsB;CACxC,UAAU,CACR,GAAG,UAAU,sBAAsB,GACnC,GAAG;EACD;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,UAAU;EACf,QAAQ,YAAY;EACpB,QAAQ,KAAK,KAAK,aAAa,IAAI;CACrC,EAAE,CACJ;AACF;AAIA,MAAa,oBAAoB,OAAO,KAAK,WAAW;;;;;;;;AASxD,MAAa,uBAAuB,OAAe,cAAsB;CACvE,IAAI,UAAU;CACd,OAAO,MAAM;EACX,MAAM,YAAY,KAAK,KAAK,SAAS,cAAc;EACnD,IAAI,GAAG,WAAW,KAAK,KAAK,WAAW,UAAU,SAAS,UAAU,CAAC,GACnE,OAAO;EAET,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,sDAAsD;EAExE,UAAU;CACZ;AACF;;;;;;;;AASA,MAAa,qBAAqB,QAA8B;CAC9D,MAAM,OAAO,UAAkB,GAAG,WAAW,KAAK,KAAK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CACb,YAAY,WAAW,CAAC,CACxB,QAAQ,OAAO,CAAC,CAChB,OACC,2BACA,oFACA,GACF,CAAC,CACA,KAAK,cAAc,gBAAgB;CAClC,MAAM,WAAW,SAAS,YAAY,KAAK,CAAC,CAAC,UAAU,EAAE;CAEzD,WAD0B,QACrB,CAAC,EAAE,MAAM,qBAAqB,UAAU;AAC/C,CAAC;AAEH,uBAAuB,OAAO;AAE9B,QACG,QAAQ,QAAQ,CAAC,CACjB,YAAY,gCAAgC,CAAC,CAC7C,OAAO,qBAAqB,sBAAsB,MACjD,OAAO,SAAS,GAAG,EAAE,CACvB,CAAC,CACA,OACC,iBACA,gEACF,CAAC,CACA,OACC,eACA,8DACF,CAAC,CACA,OACC,mBACA,4EACF,CAAC,CACA,OAAO,MAAM;AAEhB,QACG,QAAQ,OAAO,CAAC,CAChB,YAAY,6DAA6D,CAAC,CAC1E,OAAO,qBAAqB,sBAAsB,MACjD,OAAO,SAAS,GAAG,EAAE,CACvB,CAAC,CACA,OACC,iBACA,gEACF,CAAC,CACA,OACC,eACA,uDACF,CAAC,CACA,OACC,mBACA,4EACF,CAAC,CACA,OAAO,WAAW,2CAA2C,CAAC,CAC9D,OAAO,KAAK;AAEf,QACG,QAAQ,SAAS,CAAC,CAClB,YAAY,qBAAqB,CAAC,CAClC,OACC,4BACA,2EACF,CAAC,CACA,OAAO,OAAO;AAEjB,QACG,QAAQ,QAAQ,CAAC,CACjB,YAAY,2BAA2B,CAAC,CACxC,OACC,yBACA,2FACA,iBAAA,CAEF,CAAC,CACA,OAAO,MAAM;AAEhB,qBAAqB,OAAO;AAE5B,QACG,QAAQ,MAAM,CAAC,CACf,YAAY,2CAA2C,CAAC,CACxD,OAAO,IAAI;AAEd,eAAsB,MAAqB;CACzC,MAAM,QAAQ,WAAW;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["run"],"sources":["../package.json","../../../node_modules/.pnpm/tsdown@0.23.0_@arethetypeswrong+core@0.18.5_oxc-resolver@11.24.2_tsx@4.23.1_typescript@7.0.2/node_modules/tsdown/esm-shims.js","../src/utils/agentSkills.ts","../src/commands/agent.ts","../src/commands/approve.ts","../src/utils/captureReport.ts","../src/utils/describeChanges.ts","../src/utils/parseMaxRegions.ts","../src/utils/remoteEngine.ts","../src/utils/server.ts","../src/commands/capture.ts","../src/commands/init.ts","../src/commands/review.ts","../src/commands/serve.ts","../src/commands/status.ts","../src/index.ts"],"sourcesContent":["","// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Agent integrations `cappa agent init` can install, and the files each one\n * gets.\n *\n * - `claude` — Claude Code: the skill in `.claude/skills/cappa` plus a\n * `cappa-judge` subagent that judges screenshots in its own context.\n * - `agents` — the vendor-neutral Agent Skills directory `.agents/skills`,\n * read by Codex, OpenCode and other agents that adopted it.\n * - `opencode` — OpenCode: the `.agents` skill plus slash commands that run\n * the review flow and a sandboxed `cappa-judge` subagent that judges\n * screenshots in its own context.\n *\n * Sources are relative to the package's `integrations/` directory; targets\n * are relative to the project.\n */\nconst SKILL = [\n \"skills/cappa/SKILL.md\",\n \"skills/cappa/JUDGING.md\",\n \"skills/cappa/MASKING.md\",\n] as const;\n\ntype FileMapping = { source: string; target: string };\n\nconst skillInto = (dir: string): FileMapping[] =>\n SKILL.map((source) => ({\n source,\n target: path.join(dir, path.basename(source)),\n }));\n\nexport const STACK_FILES = {\n claude: [\n ...skillInto(\".claude/skills/cappa\"),\n {\n source: \"claude/agents/cappa-judge.md\",\n target: path.join(\".claude\", \"agents\", \"cappa-judge.md\"),\n },\n ],\n agents: skillInto(\".agents/skills/cappa\"),\n opencode: [\n ...skillInto(\".agents/skills/cappa\"),\n ...[\n \"commands/cappa-review.md\",\n \"commands/cappa-judge.md\",\n \"commands/cappa-approve.md\",\n \"agents/cappa-judge.md\",\n ].map((file) => ({\n source: `opencode/${file}`,\n target: path.join(\".opencode\", file),\n })),\n ],\n} satisfies Record<string, FileMapping[]>;\n\nexport type SkillStack = keyof typeof STACK_FILES;\n\nexport const SKILL_STACK_NAMES = Object.keys(STACK_FILES) as SkillStack[];\n\n/**\n * Find the integration sources shipped with the package.\n *\n * They live in `integrations/` at the package root, which is one level above\n * `dist/` when installed and two above `src/utils/` in development — so walk\n * up instead of hard-coding either depth.\n */\nexport const findIntegrationsDir = (from: string = __dirname): string => {\n let current = from;\n while (true) {\n const candidate = path.join(current, \"integrations\");\n if (fs.existsSync(path.join(candidate, \"skills\", \"cappa\", \"SKILL.md\"))) {\n return candidate;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n throw new Error(\"Could not locate the bundled cappa agent skill files\");\n }\n current = parent;\n }\n};\n\n/**\n * Pick the stacks to install when none was named: whichever agents the\n * project already shows signs of, falling back to Claude Code.\n *\n * OpenCode wins over plain `agents` — its stack already includes the\n * `.agents` skill, and adds the commands on top.\n */\nexport const detectSkillStacks = (cwd: string): SkillStack[] => {\n const has = (entry: string) => fs.existsSync(path.join(cwd, entry));\n const stacks: SkillStack[] = [];\n if (has(\".claude\") || has(\"CLAUDE.md\")) stacks.push(\"claude\");\n if (has(\".opencode\") || has(\"opencode.json\") || has(\"opencode.jsonc\")) {\n stacks.push(\"opencode\");\n } else if (has(\".agents\") || has(\"AGENTS.md\")) {\n stacks.push(\"agents\");\n }\n return stacks.length > 0 ? stacks : [\"claude\"];\n};\n\n/**\n * How the project runs its own `cappa` binary, from its lockfile.\n *\n * Written into the installed files because OpenCode commands run shell\n * commands *before* the model sees anything, so a bare `cappa` that is not on\n * `PATH` would inject an error instead of the review state; and agent\n * permission rules match the command text literally.\n */\nexport const detectCappaRunner = (cwd: string): string => {\n const has = (entry: string) => fs.existsSync(path.join(cwd, entry));\n if (has(\"pnpm-lock.yaml\")) return \"pnpm exec cappa\";\n if (has(\"yarn.lock\")) return \"yarn cappa\";\n if (has(\"bun.lock\") || has(\"bun.lockb\")) return \"bunx cappa\";\n return \"npx cappa\";\n};\n\n/** Fill the `{{cappa}}` placeholder in a source file. */\nexport const renderIntegrationFile = (source: string, runner: string) =>\n source.replaceAll(\"{{cappa}}\", runner);\n\nexport type SkillFileResult = {\n stack: SkillStack;\n path: string;\n status: \"written\" | \"unchanged\" | \"skipped\";\n};\n\nexport type InstallResult = {\n runner: string;\n files: SkillFileResult[];\n warnings: string[];\n};\n\n/**\n * Copy each stack's files into the project.\n *\n * A file that exists with different content is left alone unless `force` is\n * set: users are expected to tailor these to their project, and an upgrade\n * must not silently discard that. A target shared by two stacks (the\n * `.agents` skill) is written once.\n */\nexport const installAgentSkills = async (options: {\n cwd: string;\n stacks: readonly SkillStack[];\n force?: boolean;\n runner?: string;\n sourceDir?: string;\n}): Promise<InstallResult> => {\n const sourceDir = options.sourceDir ?? findIntegrationsDir();\n const runner = options.runner ?? detectCappaRunner(options.cwd);\n const files: SkillFileResult[] = [];\n const seen = new Set<string>();\n\n for (const stack of options.stacks) {\n for (const mapping of STACK_FILES[stack]) {\n const target = path.resolve(options.cwd, mapping.target);\n if (seen.has(target)) continue;\n seen.add(target);\n\n const source = renderIntegrationFile(\n await fsp.readFile(path.join(sourceDir, mapping.source), \"utf8\"),\n runner,\n );\n const existing = await fsp\n .readFile(target, \"utf8\")\n .catch(() => undefined);\n\n if (existing === source) {\n files.push({ stack, path: target, status: \"unchanged\" });\n continue;\n }\n if (existing !== undefined && !options.force) {\n files.push({ stack, path: target, status: \"skipped\" });\n continue;\n }\n\n await fsp.mkdir(path.dirname(target), { recursive: true });\n await fsp.writeFile(target, source, \"utf8\");\n files.push({ stack, path: target, status: \"written\" });\n }\n }\n\n const warnings: string[] = [];\n const claudeSkill = fs.existsSync(\n path.resolve(options.cwd, \".claude/skills/cappa/SKILL.md\"),\n );\n if (options.stacks.includes(\"opencode\") && claudeSkill) {\n warnings.push(\n \"OpenCode reads .claude/skills too, and uses that copy of the cappa skill over the one in .agents/skills — keep the two in sync if you tailor them.\",\n );\n }\n\n return { runner, files, warnings };\n};\n","import { getConfig } from \"@cappa/config\";\nimport {\n type AgentReport,\n clearJudgment,\n collectScreenshots,\n isJudgedLabel,\n JUDGE_MODES,\n JUDGED_LABELS,\n type JudgedLabel,\n type JudgeMode,\n readAgentReport,\n runAgentCheck,\n ScreenshotFileSystem,\n toSlimAgentReport,\n type VerdictLabel,\n writeAgentVerdict,\n} from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport chalk from \"chalk\";\nimport { type Command, InvalidArgumentError } from \"commander\";\nimport {\n detectSkillStacks,\n installAgentSkills,\n SKILL_STACK_NAMES,\n type SkillStack,\n} from \"../utils/agentSkills\";\n\n/**\n * `cappa agent` — visual review for coding agents.\n *\n * Every subcommand takes `--json`, which prints exactly one JSON document to\n * stdout and nothing else, so an agent can parse it without scraping logs.\n */\n\ntype JsonOption = { json?: boolean };\n\nconst printJson = (value: unknown) => {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n};\n\n/** `CI=true`/`CI=1` — but not `CI=false`, which some tools set explicitly. */\nexport const isCi = (env: NodeJS.ProcessEnv = process.env): boolean => {\n const value = env.CI?.trim().toLowerCase();\n return !!value && value !== \"false\" && value !== \"0\";\n};\n\n/**\n * Run `action`, reporting a failure as `{ error }` under `--json` instead of\n * a log line an agent would have to find.\n */\nconst run = async (\n options: JsonOption,\n action: () => Promise<void>,\n): Promise<void> => {\n try {\n await action();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (options.json) {\n printJson({ error: message });\n } else {\n getLogger().error(message);\n }\n process.exitCode = 1;\n }\n};\n\nconst LABEL_COLORS: Record<VerdictLabel, (text: string) => string> = {\n \"regression-likely\": chalk.red,\n \"intentional-likely\": chalk.green,\n \"noise-likely\": chalk.gray,\n ambiguous: chalk.yellow,\n};\n\n/** Human-readable lines for a report — what `--json` prints, for people. */\nexport const describeAgentReport = (report: AgentReport): string[] => {\n const { totals } = report;\n const lines = [\n `${totals.passed}/${totals.total} passed · ${totals.changed} changed · ${totals.new} new · ${totals.deleted} deleted`,\n ];\n if (totals.pendingJudgments > 0) {\n lines.push(\n chalk.yellow(\n `${totals.pendingJudgments} awaiting judgment in ${report.outputDir}/.cappa-agent/judgments`,\n ),\n );\n }\n\n for (const entry of report.entries) {\n if (entry.category !== \"changed\" || !entry.verdict) {\n lines.push(`${chalk.bold(entry.name)} ${chalk.dim(entry.category)}`);\n continue;\n }\n const { label, headline, source } = entry.verdict;\n const tags = [\n source === \"agent\" ? \"judged\" : undefined,\n entry.pending ? \"pending\" : undefined,\n ].filter(Boolean);\n lines.push(\n `${chalk.bold(entry.name)} ${LABEL_COLORS[label](label)} — ${headline}${tags.length > 0 ? chalk.dim(` (${tags.join(\", \")})`) : \"\"}`,\n );\n if (entry.verdictError) {\n lines.push(chalk.red(` verdict.json ignored: ${entry.verdictError}`));\n }\n }\n\n return lines;\n};\n\ntype CheckOptions = JsonOption & {\n judge: JudgeMode;\n maxTileRegions?: number;\n};\n\nexport const agentCheck = (options: CheckOptions) =>\n run(options, async () => {\n const config = await getConfig();\n\n const report = await runAgentCheck({\n outputDir: config.outputDir,\n diff: config.diff,\n judge: options.judge,\n maxTileRegions: options.maxTileRegions,\n });\n\n if (options.json) {\n printJson(toSlimAgentReport(report));\n } else {\n getLogger().box({\n title: \"Agent Review\",\n message: describeAgentReport(report).join(\"\\n\"),\n });\n }\n\n if (report.entries.length > 0) {\n process.exitCode = 1;\n }\n });\n\ntype JudgeOptions = JsonOption & {\n label: JudgedLabel;\n headline: string;\n rationale?: string[];\n confidence?: number;\n};\n\nexport const agentJudge = (names: string[], options: JudgeOptions) =>\n run(options, async () => {\n const config = await getConfig();\n\n const written: Array<{ name: string; verdict: string }> = [];\n for (const name of names) {\n const verdict = await writeAgentVerdict(config.outputDir, name, {\n label: options.label,\n headline: options.headline,\n rationale: options.rationale,\n confidence: options.confidence,\n });\n written.push({ name, verdict });\n }\n\n if (options.json) {\n printJson({ written });\n } else {\n getLogger().success(\n `Recorded ${options.label} for ${written.length} screenshot(s) — run \\`cappa agent check\\` to apply`,\n );\n }\n });\n\ntype ApproveOptions = JsonOption & {\n label?: JudgedLabel[];\n allowRegression?: boolean;\n};\n\nexport const agentApprove = (names: string[], options: ApproveOptions) =>\n run(options, async () => {\n if (isCi()) {\n throw new Error(\n \"Refusing to approve in CI — baselines are only changed on developer machines.\",\n );\n }\n if (names.length === 0 && !options.label?.length) {\n throw new Error(\"Name the screenshots to approve, or pass --label.\");\n }\n\n const config = await getConfig();\n const screenshots = await collectScreenshots(config.outputDir);\n const byName = new Map(screenshots.map((s) => [s.name, s]));\n\n const wanted = new Set(names);\n const unknown = names.filter((name) => {\n const screenshot = byName.get(name);\n return !screenshot || screenshot.category === \"passed\";\n });\n if (unknown.length > 0) {\n throw new Error(\n `Nothing to approve for: ${unknown.join(\", \")} — names must match exactly (see \\`cappa agent check --json\\`).`,\n );\n }\n\n // Re-check rather than trusting the last report: approving off a label\n // the screenshots no longer carry is exactly the mistake to prevent, and\n // a changed screenshot's current verdict is what the regression guard\n // below needs.\n const verdicts = new Map<string, VerdictLabel>();\n const needsCheck =\n !!options.label?.length ||\n names.some((name) => byName.get(name)?.category === \"changed\");\n if (needsCheck) {\n const previous = await readAgentReport(config.outputDir);\n const report = await runAgentCheck({\n outputDir: config.outputDir,\n diff: config.diff,\n judge: previous?.judge ?? \"ambiguous\",\n });\n for (const entry of report.entries) {\n if (entry.category === \"changed\" && entry.verdict) {\n verdicts.set(entry.name, entry.verdict.label);\n }\n }\n }\n\n const labels = new Set<string>(options.label);\n for (const [name, label] of verdicts) {\n if (labels.has(label)) wanted.add(name);\n }\n\n const toApprove = [...wanted].flatMap((name) => {\n const screenshot = byName.get(name);\n return screenshot && screenshot.category !== \"passed\" ? [screenshot] : [];\n });\n\n const regressions = toApprove\n .filter((s) => verdicts.get(s.name) === \"regression-likely\")\n .map((s) => s.name);\n if (regressions.length > 0 && !options.allowRegression) {\n throw new Error(\n `Refusing to approve regression-likely: ${regressions.join(\", \")} — if the change is intended, judge it (\\`cappa agent check --judge all\\`, then \\`cappa agent judge <name> --label intentional-likely\\`), or pass --allow-regression.`,\n );\n }\n\n const fileSystem = new ScreenshotFileSystem(config.outputDir);\n await fileSystem.approveScreenshots(toApprove, config.diff);\n await Promise.all(\n toApprove.map((screenshot) =>\n clearJudgment(config.outputDir, screenshot.name),\n ),\n );\n\n const approved = toApprove.map((s) => ({\n name: s.name,\n category: s.category,\n }));\n if (options.json) {\n printJson({ approved });\n } else if (approved.length === 0) {\n getLogger().warn(\"No screenshots matched\");\n } else {\n getLogger().success(\n `Approved ${approved.length} screenshot(s): ${approved.map((s) => s.name).join(\", \")}`,\n );\n }\n });\n\ntype InitOptions = JsonOption & {\n stack?: SkillStack | \"all\";\n force?: boolean;\n runner?: string;\n};\n\nexport const agentInit = (options: InitOptions) =>\n run(options, async () => {\n const cwd = process.cwd();\n const stacks =\n options.stack === \"all\"\n ? SKILL_STACK_NAMES\n : options.stack\n ? [options.stack]\n : detectSkillStacks(cwd);\n\n const { runner, files, warnings } = await installAgentSkills({\n cwd,\n stacks,\n force: options.force,\n runner: options.runner,\n });\n\n if (options.json) {\n printJson({ stacks, runner, files, warnings });\n return;\n }\n\n const logger = getLogger();\n for (const file of files) {\n const verb = {\n written: chalk.green(\"wrote\"),\n unchanged: chalk.dim(\"unchanged\"),\n skipped: chalk.yellow(\"skipped (modified — use --force)\"),\n }[file.status];\n logger.log(`${verb} ${file.path}`);\n }\n logger.log(chalk.dim(`commands run as \\`${runner}\\` (--runner to change)`));\n for (const warning of warnings) {\n logger.warn(warning);\n }\n logger.success(\n stacks.includes(\"opencode\")\n ? \"Agent integration installed — run /cappa-review in OpenCode, or /cappa in Claude Code\"\n : \"Agent skill installed — ask your agent to run a visual review, or use /cappa in Claude Code\",\n );\n });\n\nconst parseChoice =\n <T extends string>(choices: readonly T[], what: string) =>\n (value: string): T => {\n if (!(choices as readonly string[]).includes(value)) {\n throw new InvalidArgumentError(\n `${what} must be one of: ${choices.join(\", \")}`,\n );\n }\n return value as T;\n };\n\nconst parseLabel = (value: string): JudgedLabel => {\n if (!isJudgedLabel(value)) {\n throw new InvalidArgumentError(\n `label must be one of: ${JUDGED_LABELS.join(\", \")}`,\n );\n }\n return value;\n};\n\nconst collectLabel = (value: string, previous: JudgedLabel[] = []) => [\n ...previous,\n parseLabel(value),\n];\n\nconst parseConfidence = (value: string): number => {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {\n throw new InvalidArgumentError(\"confidence must be a number from 0 to 1\");\n }\n return parsed;\n};\n\nconst parsePositiveInt = (value: string): number => {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError(\"must be a positive integer\");\n }\n return parsed;\n};\n\nexport const registerAgentCommand = (program: Command): void => {\n const agent = program\n .command(\"agent\")\n .description(\n \"Visual review for coding agents: label changes, hand ambiguous ones to an agent, approve\",\n );\n\n agent\n .command(\"check\")\n .description(\n \"Label every changed screenshot and write judgment requests for an agent (does not capture)\",\n )\n .option(\n \"--judge <mode>\",\n `which changes get a judgment request: ${JUDGE_MODES.join(\", \")}`,\n parseChoice(JUDGE_MODES, \"--judge\"),\n \"ambiguous\",\n )\n .option(\n \"--max-tile-regions <count>\",\n \"regions rendered into each regions.png\",\n parsePositiveInt,\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentCheck);\n\n agent\n .command(\"judge\")\n .description(\"Record a verdict for screenshots with a judgment request\")\n .argument(\"<names...>\", \"screenshot names, exactly as reported\")\n .requiredOption(\"--label <label>\", JUDGED_LABELS.join(\" | \"), parseLabel)\n .requiredOption(\"--headline <text>\", \"one line describing the change\")\n .option(\"--rationale <text...>\", \"reasons for the verdict\")\n .option(\"--confidence <number>\", \"0 to 1\", parseConfidence)\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentJudge);\n\n agent\n .command(\"approve\")\n .description(\n \"Approve screenshots by exact name or by verdict label (refused in CI)\",\n )\n .argument(\"[names...]\", \"screenshot names, exactly as reported\")\n .option(\n \"--label <label>\",\n \"also approve every changed screenshot with this verdict label (repeatable)\",\n collectLabel,\n )\n .option(\n \"--allow-regression\",\n \"approve screenshots whose current verdict is regression-likely\",\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentApprove);\n\n agent\n .command(\"init\")\n .description(\"Install the cappa skill for coding agents in this project\")\n .option(\n \"--stack <stack>\",\n `${SKILL_STACK_NAMES.join(\", \")} or all (default: detected)`,\n parseChoice([...SKILL_STACK_NAMES, \"all\"] as const, \"--stack\"),\n )\n .option(\"--force\", \"overwrite skill files that were modified\")\n .option(\n \"--runner <command>\",\n \"how the project runs cappa, e.g. `pnpm exec cappa` (default: from the lockfile)\",\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentInit);\n};\n","import { getConfig } from \"@cappa/config\";\nimport type { Screenshot } from \"@cappa/core\";\nimport { groupScreenshots, ScreenshotFileSystem } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\n\nexport const approve = async (options: { filter?: string[] }) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n logger.start(\"Approving screenshots...\");\n\n const fileSystem = new ScreenshotFileSystem(config.outputDir);\n\n const [actualScreenshots, diffScreenshots, expectedScreenshots] =\n await Promise.all([\n fileSystem.getActualScreenshots(),\n fileSystem.getDiffScreenshots(),\n fileSystem.getExpectedScreenshots(),\n ]);\n\n let screenshotsToApprove = await groupScreenshots(\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n config.outputDir,\n );\n\n const filters =\n options.filter?.map((filter: string) => filter.toLowerCase()) ?? [];\n\n if (filters.length > 0) {\n logger.debug(\n `Filtering actual screenshots by filter: ${filters.join(\", \")}`,\n );\n\n screenshotsToApprove = filterScreenshots(screenshotsToApprove, filters);\n\n if (screenshotsToApprove.length === 0) {\n logger.warn(\"No screenshots matched the provided filter(s)\");\n return;\n }\n }\n\n await fileSystem.approveScreenshots(screenshotsToApprove, config.diff);\n\n if (filters.length > 0) {\n logger.success(\n `${screenshotsToApprove.length} screenshot(s) approved (filtered)`,\n );\n } else {\n logger.success(\"All screenshots approved\");\n }\n};\n\nexport const filterScreenshots = (\n screenshots: Screenshot[],\n filters: string[],\n) => {\n return screenshots.filter((screenshot) => {\n return filters.some((filter: string) => {\n const nameMatches = screenshot.name.toLowerCase().includes(filter);\n const pathMatches =\n \"actualPath\" in screenshot &&\n screenshot.actualPath?.toLowerCase().includes(filter);\n return nameMatches || pathMatches;\n });\n });\n};\n","import type { RunDetail, TaskFailure } from \"@cappa/core\";\nimport type { ReportableScreenshot } from \"./describeChanges\";\n\n/**\n * What `cappa capture --json` prints: one document an agent or a script can\n * act on, instead of a progress log and report boxes to scrape.\n *\n * It separates the two reasons a capture \"fails\", which the exit code alone\n * cannot: `errors` are tasks that broke (a story threw, a page timed out) and\n * need fixing before anything can be judged; `results` are screenshots that\n * captured fine but differ from their baseline and need reviewing.\n */\nexport type CaptureJsonReport = {\n /** Nothing failed and nothing differs. Mirrors the exit code. */\n ok: boolean;\n runId?: string;\n durationMs: number;\n tasks: { total: number; completed: number; failed: number };\n screenshots: {\n total: number;\n passed: number;\n changed: number;\n new: number;\n deleted: number;\n };\n /** Tasks that did not produce a comparable screenshot. */\n errors: Array<{ taskId: string; plugin: string; error: string }>;\n /** Every screenshot that is not `passed`. */\n results: Array<{\n name: string;\n category: string;\n taskId?: string;\n plugin?: string;\n percentDifference?: number;\n }>;\n /** The command that picks up from here, when there is something to review. */\n next?: string;\n};\n\nconst errorMessage = (error: unknown): string => {\n if (typeof error === \"string\") return error;\n if (error instanceof Error) return error.message;\n if (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as { message?: unknown }).message === \"string\"\n ) {\n return (error as { message: string }).message;\n }\n return String(error);\n};\n\n/**\n * A task failure that is a broken capture rather than a visual difference.\n *\n * A changed or new screenshot is reported as a failed task too; those are\n * already in `results` with their category, so only the failures that never\n * produced a comparable image belong here.\n */\nconst toCaptureError = (\n failure: TaskFailure,\n): CaptureJsonReport[\"errors\"][number] | undefined => {\n const { result } = failure;\n if (result.error !== undefined && result.error !== null) {\n return {\n taskId: failure.taskId,\n plugin: failure.pluginName,\n error: errorMessage(result.error),\n };\n }\n if (!result.filepath && result.skipped !== true) {\n return {\n taskId: failure.taskId,\n plugin: failure.pluginName,\n error: \"no screenshot was produced\",\n };\n }\n return undefined;\n};\n\nexport const buildCaptureJsonReport = ({\n detail,\n screenshots,\n durationMs,\n}: {\n detail: RunDetail | undefined;\n screenshots: readonly ReportableScreenshot[];\n durationMs: number;\n}): CaptureJsonReport => {\n const failures = detail?.failures ?? [];\n const deleted = detail?.deletedScreenshots ?? [];\n const count = (category: string) =>\n screenshots.filter((s) => s.category === category).length;\n\n const results = screenshots\n .filter((s) => s.category !== \"passed\")\n .map((s) => {\n const origin = s as ReportableScreenshot & {\n taskId?: string;\n plugin?: string;\n };\n return {\n name: s.name,\n category: s.category,\n ...(origin.taskId\n ? { taskId: origin.taskId, plugin: origin.plugin }\n : {}),\n ...(s.diffMeta?.percentDifference !== undefined\n ? { percentDifference: s.diffMeta.percentDifference }\n : {}),\n };\n });\n\n const errors = failures.flatMap((failure) => {\n const error = toCaptureError(failure);\n return error ? [error] : [];\n });\n\n return {\n ok: failures.length === 0 && deleted.length === 0,\n ...(detail ? { runId: detail.id } : {}),\n durationMs: Math.round(durationMs),\n tasks: {\n total: detail?.totalTasks ?? 0,\n completed: detail?.completedTasks ?? 0,\n failed: detail?.failedTasks ?? 0,\n },\n screenshots: {\n total: screenshots.length,\n passed: count(\"passed\"),\n changed: count(\"changed\"),\n new: count(\"new\"),\n deleted: count(\"deleted\"),\n },\n errors,\n results,\n ...(results.length > 0 ? { next: \"cappa agent check --json\" } : {}),\n };\n};\n","import { normalizeChangeType } from \"@cappa/core\";\nimport chalk from \"chalk\";\nimport { z } from \"zod\";\n\n/**\n * The interpretation fields this reporter actually reads.\n *\n * The protocol carries `diffMeta.interpretation` opaquely — its shape belongs\n * to `@blazediff/core-native` and pinning it in a versioned wire contract would\n * make every diff-engine upgrade a breaking protocol change. So a remote engine\n * hands this an `unknown`, and it narrows rather than trusts.\n *\n * Deliberately not the full `InterpretResult`: matching only what is rendered\n * means a diff engine that adds or reshapes a field the reporter ignores does\n * not silently cost the user their diff report.\n */\nconst regionSchema = z.object({\n bbox: z.object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n }),\n percentage: z.number(),\n position: z.string(),\n changeType: z.string(),\n});\n\ntype ParsedRegion = z.infer<typeof regionSchema>;\n\nconst interpretationSchema = z.object({\n severity: z.string(),\n totalRegions: z.number(),\n summary: z.string().optional(),\n // A region list that does not match is dropped rather than failing the whole\n // interpretation: severity and the region count still tell the user what\n // happened, which beats reporting nothing because one field moved.\n regions: z.array(regionSchema).catch([]).optional(),\n});\n\ntype ParsedInterpretation = z.infer<typeof interpretationSchema>;\n\n/**\n * A screenshot as far as this reporter is concerned.\n *\n * Looser than `@cappa/core`'s `Screenshot` in exactly one place — the\n * interpretation is `unknown` — so both a local and a remote engine's results\n * satisfy it.\n */\nexport type ReportableScreenshot = {\n name: string;\n category: string;\n diffMeta?: {\n percentDifference?: number;\n interpretation?: unknown;\n };\n};\n\n// Compared case-insensitively: `@blazediff/interpret-native` reports `high`\n// today and reported `High` before.\nconst severityColor = (severity: string) => {\n switch (severity.toLowerCase()) {\n case \"high\":\n return chalk.red;\n case \"medium\":\n return chalk.yellow;\n case \"low\":\n return chalk.green;\n default:\n return chalk.gray;\n }\n};\n\n/**\n * Human-readable labels for the `changeType` values reported by blazediff,\n * keyed by their normalised (kebab-case) form so both `color-change` and the\n * older `ColorChange` resolve.\n */\nconst CHANGE_TYPE_LABELS: Record<string, string> = {\n addition: \"added\",\n deletion: \"removed\",\n \"color-change\": \"color\",\n \"content-change\": \"content\",\n shift: \"shifted\",\n \"rendering-noise\": \"noise\",\n};\n\nconst changeTypeLabel = (changeType: string) =>\n CHANGE_TYPE_LABELS[normalizeChangeType(changeType)] ?? changeType;\n\n/** `content at center · 0.90% · 360x200 at (420, 300)` */\nconst describeRegion = (region: ParsedRegion): string => {\n const { bbox } = region;\n\n return [\n chalk.cyan(changeTypeLabel(region.changeType)),\n `at ${region.position}`,\n chalk.dim(\"·\"),\n `${region.percentage.toFixed(2)}%`,\n chalk.dim(\"·\"),\n chalk.dim(`${bbox.width}x${bbox.height} at (${bbox.x}, ${bbox.y})`),\n ].join(\" \");\n};\n\n/** Default number of regions listed per changed screenshot. */\nexport const DEFAULT_MAX_REGIONS = 5;\n\nexport type DescribeChangesOptions = {\n /**\n * Maximum number of interpreted regions listed per screenshot. The largest\n * regions are listed first; the remainder is collapsed into a\n * `… and N more region(s)` line. Set to `0` to omit the per-region\n * breakdown entirely.\n *\n * @default 5\n */\n maxRegions?: number;\n};\n\n/**\n * Build human-readable lines describing the changed screenshots, surfacing the\n * pixel-diff percentage and (when `diff.interpret` is enabled) the structured\n * interpretation: severity, region count, summary and the individual regions\n * with their position and bounding box.\n *\n * Returns an empty array when there are no changed screenshots.\n */\nexport const describeChanges = (\n screenshots: readonly ReportableScreenshot[],\n options: DescribeChangesOptions = {},\n): string[] => {\n const { maxRegions = DEFAULT_MAX_REGIONS } = options;\n\n const changed = screenshots.filter(\n (screenshot) => screenshot.category === \"changed\",\n );\n\n if (changed.length === 0) {\n return [];\n }\n\n const lines: string[] = [];\n\n for (const screenshot of changed) {\n const meta = screenshot.diffMeta;\n const parsed = interpretationSchema.safeParse(meta?.interpretation);\n const interpretation: ParsedInterpretation | undefined = parsed.success\n ? parsed.data\n : undefined;\n\n const parts: string[] = [];\n if (interpretation) {\n parts.push(\n severityColor(interpretation.severity)(\n interpretation.severity.toUpperCase(),\n ),\n );\n }\n if (meta?.percentDifference !== undefined) {\n parts.push(`${meta.percentDifference.toFixed(2)}%`);\n }\n if (interpretation) {\n const { totalRegions } = interpretation;\n parts.push(\n `${totalRegions} ${totalRegions === 1 ? \"region\" : \"regions\"}`,\n );\n }\n\n const suffix =\n parts.length > 0\n ? ` ${chalk.dim(\"·\")} ${parts.join(chalk.dim(\" · \"))}`\n : \"\";\n lines.push(`${chalk.bold(screenshot.name)}${suffix}`);\n\n if (interpretation?.summary) {\n lines.push(` ${chalk.dim(interpretation.summary)}`);\n }\n\n // Largest regions first, so truncating keeps the most significant ones.\n const regions = [...(interpretation?.regions ?? [])].sort(\n (a, b) => b.percentage - a.percentage,\n );\n if (maxRegions > 0 && regions.length > 0) {\n for (const region of regions.slice(0, maxRegions)) {\n lines.push(` ${chalk.dim(\"→\")} ${describeRegion(region)}`);\n }\n\n const remaining = regions.length - maxRegions;\n if (remaining > 0) {\n lines.push(\n chalk.dim(\n ` … and ${remaining} more ${remaining === 1 ? \"region\" : \"regions\"}`,\n ),\n );\n }\n }\n }\n\n return lines;\n};\n","import { InvalidArgumentError } from \"commander\";\nimport { DEFAULT_MAX_REGIONS } from \"./describeChanges\";\n\n/**\n * Parse the `--max-regions` option: a non-negative integer, where `0` disables\n * the per-region breakdown. Falls back to the default when omitted.\n */\nexport const parseMaxRegions = (value: string | undefined): number => {\n if (value === undefined) {\n return DEFAULT_MAX_REGIONS;\n }\n\n if (!/^\\d+$/.test(value.trim())) {\n throw new InvalidArgumentError(\n \"Expected a non-negative integer (0 disables the region breakdown).\",\n );\n }\n\n return Number(value.trim());\n};\n","import { createClient, ProtocolMismatchError } from \"@cappa/client\";\nimport type { CaptureEngine } from \"@cappa/core\";\nimport type { ReportableScreenshot } from \"./describeChanges\";\n\n/**\n * The engine `capture` drives.\n *\n * Identical to `CaptureEngine` except for `listScreenshots`, which is widened:\n * a remote engine carries `diffMeta.interpretation` opaquely, so the two\n * engines' screenshot types differ in exactly that one field. Everything\n * downstream narrows it rather than trusting it.\n */\nexport type CaptureCliEngine = Omit<CaptureEngine, \"listScreenshots\"> & {\n listScreenshots(): Promise<ReportableScreenshot[]>;\n};\n\n/** A pre-flight failure, already phrased for the user. */\nexport class RemoteServerError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RemoteServerError\";\n }\n}\n\n/**\n * The host already has a run in flight.\n *\n * Duck-typed rather than `instanceof`: `@cappa/client` ships dual ESM/CJS\n * builds, so the CLI can hold a different copy of the class than the one that\n * threw — the same hazard the client documents for its own 404 check.\n */\nexport const isRunInProgress = (\n error: unknown,\n): error is { activeRunId?: string } =>\n typeof error === \"object\" &&\n error !== null &&\n (error as { status?: number }).status === 409;\n\nconst isAuthFailure = (error: unknown): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n (error as { status?: number }).status === 401;\n\nconst isProtocolMismatch = (\n error: unknown,\n): error is { expected: number; actual: number } =>\n error instanceof ProtocolMismatchError ||\n (typeof error === \"object\" &&\n error !== null &&\n (error as { name?: string }).name === \"ProtocolMismatchError\");\n\nexport type ConnectOptions = {\n server: string;\n token?: string;\n};\n\n/**\n * Build a remote engine and prove the host is usable before capturing anything.\n *\n * One request to `/api/health` turns four different failures — unreachable\n * host, wrong token, protocol skew, and a host that cannot capture — into four\n * distinct messages, up front. The client performs the version handshake on its\n * first call anyway; doing it here is what makes the failure legible rather\n * than arriving mid-run with half a report already printed.\n */\nexport async function connectToServer(\n options: ConnectOptions,\n): Promise<CaptureCliEngine> {\n const engine = createClient({\n baseUrl: options.server,\n token: options.token,\n });\n\n let health: Awaited<ReturnType<typeof engine.health>>;\n\n try {\n health = await engine.health();\n } catch (error) {\n await engine.close();\n\n if (isAuthFailure(error)) {\n throw new RemoteServerError(\n `${options.server} rejected the access token. Pass --token <token>, or set CAPPA_TOKEN.`,\n );\n }\n\n if (isProtocolMismatch(error)) {\n throw new RemoteServerError(\n `${options.server} speaks protocol version ${error.actual}, this CLI expects ${error.expected}. Upgrade whichever is older.`,\n );\n }\n\n const reason = error instanceof Error ? error.message : String(error);\n throw new RemoteServerError(\n `Could not reach a cappa server at ${options.server}: ${reason}`,\n );\n }\n\n if (!health.capabilities.capture) {\n await engine.close();\n throw new RemoteServerError(\n `${options.server} is running read-only and cannot capture. Restart it without --read-only.`,\n );\n }\n\n return engine;\n}\n","import path from \"node:path\";\nimport { configToEngineOptions, type ResolvedUserConfig } from \"@cappa/config\";\nimport { LocalEngine } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport { createServer, isLoopbackHost } from \"@cappa/server\";\n\ntype Closeable = { close: () => Promise<unknown> };\n\nconst closeQuietly = async (name: string, closeable: Closeable) => {\n try {\n await closeable.close();\n } catch (error) {\n getLogger().debug(`Error closing ${name} during shutdown:`, error);\n }\n};\n\n/**\n * Shut a running server down cleanly on Ctrl-C or SIGTERM.\n *\n * Order matters: the HTTP server closes first so no new run can be started\n * mid-teardown, then the engine, which aborts an active run and closes the\n * browser. Without that last step a killed server can leave an orphaned\n * Chromium behind.\n *\n * The second signal exits immediately — if the first shutdown is wedged on a\n * capture that will not stop, the user should not have to reach for `kill -9`.\n */\nexport function registerShutdownHandlers(\n server: Closeable,\n engine: Closeable,\n exitFn: (code: number) => void = process.exit,\n): () => void {\n let shuttingDown = false;\n\n const handleSignal = async () => {\n if (shuttingDown) {\n exitFn(130);\n return;\n }\n shuttingDown = true;\n\n const logger = getLogger();\n logger.info(\"Shutting down…\");\n\n // Each close is independent: a server that fails to close must not stop\n // the engine from closing, or a failed shutdown leaks a browser process.\n await closeQuietly(\"server\", server);\n await closeQuietly(\"engine\", engine);\n\n exitFn(130);\n };\n\n // `on`, not `once`: a second Ctrl-C must reach the handler to force the exit.\n process.on(\"SIGINT\", handleSignal);\n process.on(\"SIGTERM\", handleSignal);\n\n return () => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n}\n\n/**\n * Read the access token from the flag, falling back to `CAPPA_TOKEN`.\n *\n * The environment fallback exists so a CI job does not have to put the token in\n * its process list, where anything on the box can read it.\n */\nexport const resolveToken = (token?: string): string | undefined =>\n token ?? process.env.CAPPA_TOKEN ?? undefined;\n\nexport type StartServerOptions = {\n config: ResolvedUserConfig;\n host: string;\n port: number;\n readOnly: boolean;\n token?: string;\n /** Serve the review UI alongside `/api/*`. */\n ui: boolean;\n};\n\nexport type RunningServer = {\n server: Awaited<ReturnType<typeof createServer>>;\n engine: LocalEngine;\n /** Where the server is actually reachable, with the token if there is one. */\n url: string;\n unregisterShutdownHandlers: () => void;\n};\n\n/** Wildcard binds: addresses to listen on, never addresses to open. */\nconst WILDCARD_HOSTS = new Set([\"0.0.0.0\", \"::\", \"[::]\"]);\n\n/**\n * The host to put in the URL a person is expected to click.\n *\n * A wildcard bind is the common way to expose the UI, and printing it verbatim\n * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,\n * handed to a user who then cannot reach their own review UI. `localhost` is\n * reachable on every interface the wildcard covers, so it is the right thing to\n * show; a specific host is printed as given, because that one is meaningful.\n */\nexport const toDisplayHost = (host: string): string =>\n isLoopbackHost(host) || WILDCARD_HOSTS.has(host) ? \"localhost\" : host;\n\n/**\n * Build an engine, wrap it in a server, and start listening.\n *\n * Shared by `review` and `serve`, which differ only in how they resolve a token\n * and what they print afterwards — everything from the engine to the bound\n * socket is the same, and was duplicated before `serve` existed.\n *\n * The token is taken as already-resolved: the two commands have deliberately\n * different policies (`review` generates one off loopback for the human reading\n * the URL it prints, `serve` refuses to start without one), and folding that\n * decision in here would hide it.\n */\nexport async function startServer(\n options: StartServerOptions,\n): Promise<RunningServer> {\n const logger = getLogger();\n const { config, host, port, readOnly, token, ui } = options;\n\n // The engine holds the config's live plugin objects, so it is built here — in\n // the process that evaluated cappa.config.ts — and injected into the server.\n const engine = new LocalEngine({\n ...configToEngineOptions(config),\n browserIdleTimeoutMs: config.review.browserIdleTimeout,\n });\n\n const server = await createServer({\n engine,\n isProd: true,\n ui,\n outputDir: path.resolve(config.outputDir),\n logger: logger.level >= 4,\n theme: config.review.theme,\n readOnly,\n token,\n });\n\n const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);\n\n await server.listen({ port, host });\n\n const displayHost = toDisplayHost(host);\n const query = token ? `?token=${token}` : \"\";\n\n return {\n server,\n engine,\n url: `http://${displayHost}:${port}${query}`,\n unregisterShutdownHandlers,\n };\n}\n","import path from \"node:path\";\nimport { configToEngineOptions, getConfig } from \"@cappa/config\";\nimport type {\n CaptureEngine,\n FailedScreenshot,\n RunDetail,\n RunEvent,\n Screenshot,\n SerializedError,\n TaskFailure,\n WatchEvent,\n} from \"@cappa/core\";\nimport { LocalEngine } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport chalk from \"chalk\";\nimport type { Command } from \"commander\";\nimport { buildCaptureJsonReport } from \"../utils/captureReport\";\nimport {\n DEFAULT_MAX_REGIONS,\n describeChanges,\n type ReportableScreenshot,\n} from \"../utils/describeChanges\";\nimport { parseMaxRegions } from \"../utils/parseMaxRegions\";\nimport {\n type CaptureCliEngine,\n connectToServer,\n isRunInProgress,\n RemoteServerError,\n} from \"../utils/remoteEngine\";\nimport { resolveToken } from \"../utils/server\";\n\nasync function executeOnFailCallback(\n config: Awaited<ReturnType<typeof getConfig>>,\n groupedScreenshots: ReportableScreenshot[],\n { remote = false }: { remote?: boolean } = {},\n): Promise<void> {\n const logger = getLogger();\n\n if (!config.onFail) {\n return;\n }\n\n // The screenshots are on the host, not here, so resolving them against the\n // local `outputDir` would hand the callback paths to files that do not exist.\n // An upload of nothing is the one outcome worth ruling out, so the absolute\n // fields are left undefined and the callback is told why — once, not per\n // screenshot.\n if (remote && groupedScreenshots.length > 0) {\n logger.warn(\n \"Capturing against a remote server: onFail receives relative paths only, \" +\n \"because the screenshot files live on the host rather than this machine.\",\n );\n }\n\n const resolveLocal = (relative: string | undefined) =>\n !remote && relative ? path.resolve(config.outputDir, relative) : undefined;\n\n // `interpretation` arrives opaque from a remote host, and `FailedScreenshot`\n // types it as the diff engine's `InterpretResult`. The runtime shape is\n // whatever the host's diff engine produced either way; a consumer that reads\n // it should narrow, exactly as the changed-screenshot reporter does.\n const failingScreenshots = (groupedScreenshots as Screenshot[])\n .filter((screenshot) => screenshot.category !== \"passed\")\n .map(\n (screenshot): FailedScreenshot => ({\n ...screenshot,\n absoluteActualPath: resolveLocal(\n \"actualPath\" in screenshot ? screenshot.actualPath : undefined,\n ),\n absoluteExpectedPath: resolveLocal(\n \"expectedPath\" in screenshot ? screenshot.expectedPath : undefined,\n ),\n absoluteDiffPath: resolveLocal(\n \"diffPath\" in screenshot ? screenshot.diffPath : undefined,\n ),\n }),\n );\n\n if (failingScreenshots.length > 0) {\n logger.debug(\n `Executing onFail callback with ${failingScreenshots.length} failing screenshot(s)`,\n );\n\n try {\n await config.onFail(failingScreenshots);\n } catch (error) {\n logger.error(\"Error executing onFail callback:\", error);\n }\n }\n}\n\nexport function formatProgress(\n completed: number,\n total: number,\n taskId: string,\n): string {\n return `[${completed}/${total}] captured ${taskId}`;\n}\n\nexport function formatDuration(ms: number): string {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n\n if (minutes > 0) {\n return `${minutes}m ${remainingSeconds}s`;\n }\n return `${(ms / 1000).toFixed(2)}s`;\n}\n\nfunction generateFailureReportMessage(\n failedScreenshots: TaskFailure[],\n deletedScreenshots: string[],\n): string {\n const total = failedScreenshots.length + deletedScreenshots.length;\n if (total === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(`${chalk.red(`Total failures: ${total}`)}\\n`);\n\n // Group by plugin\n const byPlugin = new Map<string, TaskFailure[]>();\n for (const failed of failedScreenshots) {\n const pluginFailures = byPlugin.get(failed.pluginName);\n if (pluginFailures) {\n pluginFailures.push(failed);\n } else {\n byPlugin.set(failed.pluginName, [failed]);\n }\n }\n\n for (const [pluginName, failures] of byPlugin.entries()) {\n lines.push(`\\n${chalk.bold(`Plugin: ${pluginName}`)}`);\n\n for (const failed of failures) {\n lines.push(`\\n ${chalk.dim(\"Task ID:\")} ${failed.taskId}`);\n\n const result = failed.result;\n if (result.storyName) {\n lines.push(` ${chalk.dim(\"Story:\")} ${result.storyName}`);\n }\n if (result.error) {\n const errorMsg =\n typeof result.error === \"string\"\n ? result.error\n : result.error instanceof Error\n ? result.error.message\n : String(result.error);\n lines.push(` ${chalk.red(\"Error:\")} ${errorMsg}`);\n }\n if (result.success === false) {\n if (result.isNew) {\n lines.push(\n ` ${chalk.yellow(\"Status:\")} New screenshot (no baseline — run 'cappa approve' to accept)`,\n );\n } else {\n lines.push(` ${chalk.red(\"Status:\")} Failed (comparison failed)`);\n }\n }\n if (!result.filepath && result.skipped !== true) {\n lines.push(` ${chalk.red(\"Status:\")} Failed (no filepath generated)`);\n }\n }\n }\n\n if (deletedScreenshots.length > 0) {\n lines.push(`\\n${chalk.bold(\"Deleted baselines:\")}`);\n for (const screenshotPath of deletedScreenshots) {\n lines.push(\n ` ${chalk.dim(\"Name:\")} ${screenshotPath.replace(/\\.png$/, \"\")}`,\n );\n }\n }\n\n return lines.join(\"\\n\");\n}\n\ntype CaptureOptions = {\n ci?: boolean;\n json?: boolean;\n filter?: string;\n maxRegions?: number;\n server?: string;\n token?: string;\n watch?: boolean;\n};\n\n/**\n * An engine that can watch the filesystem.\n *\n * Feature-detected rather than assumed: the watch methods are optional on\n * `CaptureEngine` because only an engine that can see the files is able to\n * offer them, and `--watch` has to say so plainly instead of failing on an\n * undefined call.\n */\nexport type WatchCapableEngine = CaptureCliEngine &\n Required<Pick<CaptureEngine, \"startWatch\" | \"stopWatch\" | \"subscribeWatch\">>;\n\nexport const supportsWatch = (\n engine: CaptureCliEngine,\n): engine is WatchCapableEngine =>\n typeof engine.startWatch === \"function\" &&\n typeof engine.stopWatch === \"function\" &&\n typeof engine.subscribeWatch === \"function\";\n\n/**\n * Close `closeable` and exit 130 on SIGINT/SIGTERM.\n *\n * Typed structurally rather than against a concrete class so it can be handed\n * whatever owns the browser — that is the engine now, and a remote engine\n * later, neither of which the CLI should have to special-case here.\n */\nexport function registerSignalHandlers(\n closeable: { close(): Promise<void> },\n exitFn: (code: number) => void = process.exit,\n onSignal?: () => Promise<void>,\n): () => void {\n let handling = false;\n\n const handleSignal = async () => {\n // A second signal means the first teardown is taking too long — most likely\n // waiting on a remote run to acknowledge cancellation. Leave immediately\n // rather than making the user reach for `kill -9`, but say what that costs.\n if (handling) {\n getLogger().warn(\n \"Interrupted again — exiting now. The remote run may still be going.\",\n );\n exitFn(130);\n return;\n }\n handling = true;\n\n try {\n await onSignal?.();\n await closeable.close();\n } catch (error) {\n // Teardown that fails must not become an uncaught exception: the point of\n // the handler is to leave cleanly, and the user has already asked to go.\n getLogger().debug(\"Error during shutdown:\", error);\n }\n exitFn(130);\n };\n\n // `on`, not `once`: a second Ctrl-C must reach the handler to force the exit.\n process.on(\"SIGINT\", handleSignal);\n process.on(\"SIGTERM\", handleSignal);\n\n return () => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n}\n\n/**\n * Render a runner event to the terminal.\n *\n * All terminal presentation lives here — the runner itself is silent — so the\n * server can consume the exact same event stream without inheriting CLI output.\n */\nexport function renderRunEvent(event: RunEvent): void {\n const logger = getLogger();\n\n switch (event.type) {\n case \"log\":\n logger[event.level](event.message, ...event.args);\n break;\n\n case \"discover:plugin\":\n logger.info(`Found ${event.taskCount} tasks for ${event.plugin}`);\n break;\n\n case \"filter:applied\": {\n if (event.filter === undefined) {\n break;\n }\n\n logger.box({\n title: \"Filter Active\",\n message: `Only capturing tasks matching: ${chalk.cyan(event.filter)}`,\n });\n\n for (const entry of event.plugins) {\n logger.info(\n `${entry.plugin}: ${entry.after}/${entry.before} tasks match filter`,\n );\n }\n break;\n }\n\n case \"task:start\":\n logger.debug(`Executing task: ${event.taskId}`);\n break;\n\n case \"task:complete\":\n logger.info(formatProgress(event.completed, event.total, event.taskId));\n break;\n\n case \"plugin:complete\":\n if (event.failed) {\n logger.error(\n `Plugin ${event.plugin} completed with failures: ${event.resultCount} results`,\n );\n } else {\n logger.success(\n `Plugin ${event.plugin} completed: ${event.resultCount} results`,\n );\n }\n break;\n\n case \"run:error\":\n logger.error(\"Error during plugin execution:\", event.error.message);\n break;\n\n default:\n break;\n }\n}\n\n/**\n * One line for a settled batch of changes.\n *\n * Terse on purpose: this is the inner loop of somebody fixing a regression, and\n * a paragraph per save is noise. It still says *why* the iteration is the size\n * it is, because \"3 tasks\" and \"everything\" have very different causes.\n */\nexport function describeWatchChange(\n event: Extract<WatchEvent, { type: \"watch:change\" }>,\n): string {\n const files =\n event.files.length === 1\n ? (event.files[0] ?? \"\")\n : `${event.files.length} files`;\n\n const what = (() => {\n switch (event.scope) {\n case \"tasks\": {\n const count = event.taskIds?.length ?? 0;\n return `${count} task${count === 1 ? \"\" : \"s\"}`;\n }\n case \"plugins\":\n return \"every task of the affected plugin(s)\";\n case \"all\":\n return \"everything\";\n default:\n return \"nothing\";\n }\n })();\n\n return `${chalk.cyan(\"↻\")} ${what} · ${files} changed`;\n}\n\n/** The one-line result of a watch iteration. */\nexport function summarizeRunDetail(\n detail: RunDetail | undefined,\n duration: string,\n): string {\n if (!detail) {\n return `Run finished in ${duration}`;\n }\n\n const failures = detail.failures.length + detail.deletedScreenshots.length;\n const captured = `${detail.completedTasks}/${detail.totalTasks} captured`;\n\n if (failures > 0) {\n return chalk.yellow(`${captured}, ${failures} to review — ${duration}`);\n }\n\n return chalk.green(`${captured}, all passing — ${duration}`);\n}\n\n/**\n * A watch iteration's run output.\n *\n * Only what changed: a passing task in watch mode is the absence of news, and\n * printing every one of them buries the two lines that matter.\n */\nexport function renderWatchRunEvent(event: RunEvent): void {\n const logger = getLogger();\n\n switch (event.type) {\n case \"log\":\n if (event.level === \"warn\" || event.level === \"error\") {\n logger[event.level](event.message, ...event.args);\n }\n break;\n\n case \"task:complete\":\n if (event.status !== \"passed\" && event.status !== \"skipped\") {\n logger.info(` ${chalk.dim(event.status)} ${event.taskId}`);\n }\n break;\n\n case \"run:error\":\n logger.error(\"Error during plugin execution:\", event.error.message);\n break;\n\n default:\n break;\n }\n}\n\n/**\n * Stop watching and exit 0 on SIGINT/SIGTERM.\n *\n * Zero, not 130: quitting a watch session is how it is meant to end, and a\n * non-zero exit would make `cappa capture --watch` fail every shell script and\n * task runner that wraps it.\n */\nexport function registerWatchSignalHandlers(\n stop: () => Promise<void>,\n exitFn: (code: number) => void = process.exit,\n): () => void {\n let handling = false;\n\n const handleSignal = async () => {\n // A second signal while the first teardown is still going: leave now rather\n // than making the user reach for `kill -9`.\n if (handling) {\n exitFn(0);\n return;\n }\n handling = true;\n\n getLogger().info(\"Stopping watch…\");\n await stop();\n exitFn(0);\n };\n\n process.on(\"SIGINT\", handleSignal);\n process.on(\"SIGTERM\", handleSignal);\n\n return () => {\n process.off(\"SIGINT\", handleSignal);\n process.off(\"SIGTERM\", handleSignal);\n };\n}\n\nexport type WatchCaptureOptions = {\n filter?: string;\n};\n\n/**\n * Watch for changes and re-capture, until interrupted.\n *\n * Resolves only when a signal stops the session, so the caller keeps the\n * process — and the warm browser — alive for as long as the user is editing.\n */\nexport async function watchCapture(\n engine: WatchCapableEngine,\n options: WatchCaptureOptions = {},\n exitFn: (code: number) => void = process.exit,\n): Promise<void> {\n const logger = getLogger();\n\n let release: (() => void) | undefined;\n const finished = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n const stop = async () => {\n try {\n await engine.stopWatch();\n await engine.close();\n } catch (error) {\n // Same reason as `registerSignalHandlers`: a browser that is already gone\n // is not a reason to exit with a stack trace.\n logger.debug(\"Error stopping the watch session:\", error);\n } finally {\n release?.();\n }\n };\n\n const unregisterSignalHandlers = registerWatchSignalHandlers(stop, exitFn);\n\n // Iterations are rendered one at a time: the session starts the next run only\n // after the previous one ends, and the output should read the same way.\n let rendering: Promise<void> = Promise.resolve();\n\n const unsubscribe = engine.subscribeWatch((event) => {\n switch (event.type) {\n case \"watch:start\":\n logger.info(\n `Watching ${event.paths.join(\", \")}${\n event.filter ? ` (filter: ${event.filter})` : \"\"\n } — press Ctrl-C to stop.`,\n );\n break;\n\n case \"watch:change\": {\n logger.info(describeWatchChange(event));\n\n if (event.error) {\n logger.warn(`Could not start a run: ${event.error}`);\n break;\n }\n\n const runId = event.runId;\n if (runId) {\n rendering = rendering.then(() =>\n renderWatchIteration(engine, runId).catch((error) => {\n logger.error(\"Error rendering the run:\", error);\n }),\n );\n }\n break;\n }\n\n default:\n break;\n }\n });\n\n try {\n await engine.startWatch({ filter: options.filter });\n await finished;\n } finally {\n unsubscribe();\n unregisterSignalHandlers();\n }\n}\n\nasync function renderWatchIteration(\n engine: WatchCapableEngine,\n runId: string,\n): Promise<void> {\n const logger = getLogger();\n const start = performance.now();\n\n await renderRunToCompletion(engine, runId, renderWatchRunEvent);\n\n const detail = await engine.getRun(runId);\n const duration = formatDuration(performance.now() - start);\n\n // A failing screenshot in watch mode is the thing being worked on, not a\n // reason to quit: it is reported and the session keeps going.\n logger.info(summarizeRunDetail(detail, duration));\n}\n\n/**\n * Rebuild a throwable error from the run's serialized one.\n *\n * The engine flattens the error a plugin threw so it can cross a network\n * boundary, but `capture` has always failed by letting that error escape — the\n * stack is the only debugging signal for a plugin that blew up. Reinstating\n * name, message and stack keeps that output intact.\n */\nfunction toThrowable(error: SerializedError): Error {\n const rebuilt = new Error(error.message);\n rebuilt.name = error.name;\n if (error.stack) {\n rebuilt.stack = error.stack;\n }\n return rebuilt;\n}\n\n/**\n * Subscribe to a run, render every event, and resolve when it terminates.\n *\n * Events buffered between `startRun` and this subscription are replayed\n * synchronously, so nothing emitted during start-up is lost.\n */\nasync function renderRunToCompletion(\n engine: CaptureCliEngine,\n runId: string,\n onEvent: (event: RunEvent) => void,\n): Promise<void> {\n let unsubscribe: (() => void) | undefined;\n\n try {\n await new Promise<void>((resolve) => {\n unsubscribe = engine.subscribeRun(runId, (event) => {\n onEvent(event);\n\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n resolve();\n }\n });\n });\n } finally {\n unsubscribe?.();\n }\n}\n\n/**\n * Print a JSON document and wait until it is flushed: `process.exit` right\n * after a plain `write` can cut off output that is still queued for a pipe.\n */\nconst writeJson = (value: unknown): Promise<void> =>\n new Promise((resolve) => {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`, () =>\n resolve(),\n );\n });\n\n/** How long a `SIGINT` waits for a remote host to acknowledge cancellation. */\nconst REMOTE_CANCEL_TIMEOUT_MS = 5000;\n\nexport const runCapture = async (\n options: CaptureOptions = {},\n): Promise<void> => {\n const logger = getLogger();\n const captureStart = performance.now();\n\n if (options.json && options.watch) {\n logger.error(\"--json cannot be combined with --watch: watch never ends.\");\n process.exit(1);\n return;\n }\n\n // stdout carries exactly one JSON document. Progress and report boxes are\n // info-level and muted; warnings and errors stay, and consola writes those\n // to stderr, so a failure is still explained without corrupting the output.\n if (options.json) {\n logger.level = Math.min(logger.level, 1);\n }\n\n // Checked before the config is even loaded: a conflicting invocation is a\n // mistake to name, not something to half-do.\n if (options.watch && options.server) {\n logger.error(\n \"--watch cannot be combined with --server: a remote host cannot see the files on this machine.\",\n );\n process.exit(1);\n return;\n }\n\n if (options.watch && options.ci) {\n logger.error(\n \"--watch cannot be combined with --ci: CI captures once and exits.\",\n );\n process.exit(1);\n return;\n }\n\n const config = await getConfig();\n\n const remote = options.server !== undefined;\n\n let engine: CaptureCliEngine;\n\n // `--token` authenticates against a host. Without one it does nothing, and\n // silently ignoring it is how a user ends up believing a capture was\n // authenticated when it was never remote in the first place.\n if (options.token && !options.server) {\n logger.error(\"--token only applies with --server.\");\n process.exit(1);\n return;\n }\n\n if (options.server) {\n // The host loads its own `cappa.config.ts`: plugins are live closures and\n // cannot be sent anywhere. Every capture setting in the local config —\n // plugins, outputDir, diff, concurrency — belongs to the host instead, and\n // a user who does not know that will wonder why theirs had no effect.\n logger.info(\n `Capturing on ${options.server}, which uses its own cappa.config.ts. Local capture settings do not apply.`,\n );\n\n try {\n engine = await connectToServer({\n server: options.server,\n token: resolveToken(options.token),\n });\n } catch (error) {\n if (error instanceof RemoteServerError) {\n logger.error(error.message);\n process.exit(1);\n return;\n }\n throw error;\n }\n } else {\n engine = new LocalEngine({\n ...configToEngineOptions(config),\n // A one-shot capture has no next run to keep a browser warm for, so hand\n // it back as soon as the run ends rather than leaving an idle Chromium\n // around for the rest of the process's life.\n //\n // Watch mode has the opposite need. Its session holds an eviction lease\n // once started, but the gap between the first run finishing and the\n // watcher starting is not covered by it — with a zero timeout the browser\n // would be gone before the first save, which is exactly the cost watch\n // mode exists to avoid.\n browserIdleTimeoutMs: options.watch\n ? config.review?.browserIdleTimeout\n : 0,\n });\n }\n\n const isCi = options.ci || process.env.CI === \"true\";\n\n let detail: RunDetail | undefined;\n // Read the diff metadata sidecars once and reuse them for both the onFail\n // callback and the changed-screenshot report below.\n let groupedScreenshots: ReportableScreenshot[] = [];\n let activeRunId: string | undefined;\n let runCompleted: Promise<void> | undefined;\n\n // Ctrl-C locally does not stop a run on another machine, so ask the host to\n // cancel and wait for it to say it has.\n //\n // Waiting for the *terminal event* rather than for `cancelRun` to return is\n // the point: closing the engine aborts the event stream, so returning early\n // would tear down the connection while the host is still winding the run\n // down — and the CLI would never learn whether it stopped. Bounded, because\n // a wedged host must not hold the terminal hostage; a second signal skips\n // the wait entirely.\n const cancelRemoteRun = async () => {\n if (!remote || !activeRunId) {\n return;\n }\n\n logger.info(\"Cancelling the remote run…\");\n\n try {\n await engine.cancelRun(activeRunId);\n\n await Promise.race([\n runCompleted?.catch(() => undefined) ?? Promise.resolve(),\n new Promise((resolve) => {\n setTimeout(resolve, REMOTE_CANCEL_TIMEOUT_MS).unref?.();\n }),\n ]);\n } catch (error) {\n logger.debug(\"Error cancelling the remote run:\", error);\n }\n };\n\n const unregisterSignalHandlers = registerSignalHandlers(\n engine,\n process.exit,\n cancelRemoteRun,\n );\n\n try {\n let run: Awaited<ReturnType<CaptureCliEngine[\"startRun\"]>>;\n\n try {\n run = await engine.startRun({\n filter: options.filter,\n // Only a full run starts from an empty `actual/`. A filtered run\n // captures a subset; clearing would leave every other screenshot with\n // a baseline and no capture — `deleted` — and approving that deletes\n // the baseline. Each captured screenshot replaces its own diff instead.\n clearActual: !options.filter,\n });\n } catch (error) {\n // One run at a time is the host's deliberate design, not a fault, so it\n // gets a sentence rather than a stack trace.\n if (isRunInProgress(error)) {\n const active = error.activeRunId ? ` (run ${error.activeRunId})` : \"\";\n logger.error(\n `${options.server} is already running a capture${active}. Wait for it to finish, or cancel it, and try again.`,\n );\n process.exit(1);\n return;\n }\n throw error;\n }\n\n activeRunId = run.id;\n\n runCompleted = renderRunToCompletion(engine, run.id, renderRunEvent);\n await runCompleted;\n\n detail = await engine.getRun(run.id);\n\n const failedDuringRun = detail?.error !== undefined;\n const hasFailure =\n (detail?.failures.length ?? 0) > 0 ||\n (detail?.deletedScreenshots.length ?? 0) > 0;\n\n if (!failedDuringRun && (isCi || hasFailure || options.json)) {\n try {\n groupedScreenshots = await engine.listScreenshots();\n } catch (err) {\n logger.warn(\"Could not collect screenshot results:\", err);\n }\n }\n } finally {\n unregisterSignalHandlers();\n // Watch mode keeps this engine — and its warm browser — for the rest of the\n // session; `watchCapture` closes it when the user stops.\n if (!options.watch) {\n await engine.close();\n }\n }\n\n // A plugin that threw has always escaped this command rather than being\n // summarised, and the browser is closed by the time it does.\n if (detail?.error) {\n if (options.json) {\n await writeJson({\n ok: false,\n runId: detail.id,\n error: detail.error.message,\n });\n process.exit(1);\n return;\n }\n throw toThrowable(detail.error);\n }\n\n const failures = detail?.failures ?? [];\n const deletedScreenshots = detail?.deletedScreenshots ?? [];\n const hasScreenshotFailure =\n failures.length > 0 || deletedScreenshots.length > 0;\n\n if (isCi) {\n await executeOnFailCallback(config, groupedScreenshots, { remote });\n }\n\n if (options.json) {\n const report = buildCaptureJsonReport({\n detail,\n screenshots: groupedScreenshots,\n durationMs: performance.now() - captureStart,\n });\n await writeJson(report);\n if (!report.ok) {\n process.exit(1);\n }\n return;\n }\n\n const duration = formatDuration(performance.now() - captureStart);\n\n if (hasScreenshotFailure) {\n const reportMessage = generateFailureReportMessage(\n failures,\n deletedScreenshots,\n );\n logger.box({\n title: \"Failed Screenshots\",\n message: reportMessage,\n });\n\n // Surface the diff stats and, when `diff.interpret` is enabled, what\n // changed and where — this is often the only debugging signal on CI.\n const changeLines = describeChanges(groupedScreenshots, {\n maxRegions: options.maxRegions,\n });\n if (changeLines.length > 0) {\n logger.box({\n title: \"Changed Screenshots\",\n message: changeLines.join(\"\\n\"),\n });\n }\n\n if (options.watch) {\n // Not an exit: a failing screenshot is what the user is here to fix.\n logger.warn(`One or more screenshots failed in ${duration}.`);\n } else {\n logger.error(\n `One or more screenshots failed in ${duration}. See report above for details.`,\n );\n process.exit(1);\n }\n } else {\n logger.success(`All plugins completed successfully in ${duration}`);\n }\n\n if (options.watch) {\n if (!supportsWatch(engine)) {\n logger.error(\"This engine cannot watch files.\");\n await engine.close();\n process.exit(1);\n return;\n }\n\n await watchCapture(engine, { filter: options.filter });\n }\n};\n\nexport const registerCaptureCommand = (program: Command): void => {\n program\n .command(\"capture\")\n .description(\"Capture screenshots\")\n .option(\"--ci\", \"run capture in CI mode and execute onFail callback\")\n .option(\n \"--json\",\n \"print a JSON summary to stdout instead of progress and reports\",\n )\n .option(\n \"-f, --filter <pattern>\",\n \"only capture tasks whose id matches the given glob pattern\",\n )\n .option(\n \"--max-regions <count>\",\n \"maximum number of interpreted diff regions listed per changed screenshot (0 to disable)\",\n parseMaxRegions,\n DEFAULT_MAX_REGIONS,\n )\n .option(\n \"--server <url>\",\n \"capture against a `cappa serve` host instead of a local browser\",\n )\n .option(\n \"--token <token>\",\n \"access token for --server (falls back to CAPPA_TOKEN)\",\n )\n .option(\n \"-w, --watch\",\n \"capture once, then re-capture affected tasks whenever files change\",\n )\n .action(async (options: CaptureOptions) => {\n await runCapture(options);\n });\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { defaultConfig } from \"@cappa/config\";\nimport { getLogger } from \"@cappa/logger\";\n\nexport const init = async () => {\n const logger = getLogger();\n\n const configPath = path.resolve(process.cwd(), \"cappa.config.ts\");\n const packageJsonPath = path.resolve(process.cwd(), \"package.json\");\n\n // Create cappa.config.ts\n if (fs.existsSync(configPath)) {\n logger.warn(\"cappa.config.ts already exists, skipping...\");\n } else {\n fs.writeFileSync(configPath, defaultConfig);\n logger.success(\"Created cappa.config.ts\");\n }\n\n // Add scripts to package.json\n if (fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n\n if (!packageJson.scripts) {\n packageJson.scripts = {};\n }\n\n if (packageJson.scripts.cappa) {\n logger.warn(\n \"'cappa' script already exists in package.json, skipping...\",\n );\n } else {\n packageJson.scripts.cappa = \"cappa capture\";\n }\n\n if (packageJson.scripts[\"cappa:review\"]) {\n logger.warn(\n \"'cappa:review' script already exists in package.json, skipping...\",\n );\n } else {\n packageJson.scripts[\"cappa:review\"] = \"cappa review\";\n }\n\n fs.writeFileSync(\n packageJsonPath,\n `${JSON.stringify(packageJson, null, 2)}\\n`,\n );\n logger.success(\"Added 'cappa' scripts to package.json\");\n } catch (error) {\n logger.error(\"Failed to update package.json:\", error);\n }\n } else {\n logger.warn(\"package.json not found, skipping script addition\");\n }\n\n logger.success(\"Cappa initialization complete!\");\n logger.warn(\n \"cappa relies on playwright to capture screenshots. Please install playwright and browsers before running cappa.\",\n );\n};\n","import { randomBytes } from \"node:crypto\";\nimport { getConfig } from \"@cappa/config\";\nimport { getLogger } from \"@cappa/logger\";\nimport { isLoopbackHost } from \"@cappa/server\";\nimport { resolveToken, startServer } from \"../utils/server\";\n\nexport type ReviewOptions = {\n port?: number;\n host?: string;\n readOnly?: boolean;\n token?: string;\n};\n\nexport const review = async (options: ReviewOptions = {}) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n const host = options.host ?? \"127.0.0.1\";\n const port = options.port ?? config.review.port;\n const readOnly = options.readOnly ?? false;\n\n // The engine drives a real browser and writes to disk. On loopback that is\n // the user's own machine; exposed to a network it is not, so a token is\n // mandatory there — generated when one was not supplied, and printed as part\n // of the URL so it is usable without extra steps.\n let token = resolveToken(options.token);\n let tokenWasGenerated = false;\n if (!token && !isLoopbackHost(host) && !readOnly) {\n token = randomBytes(24).toString(\"base64url\");\n tokenWasGenerated = true;\n logger.warn(\n `Binding to ${host} exposes capture control beyond this machine; requiring an access token.`,\n );\n }\n\n const { url } = await startServer({\n config,\n host,\n port,\n readOnly,\n token,\n ui: true,\n });\n\n logger.success(`Review UI available at ${url}`);\n\n // `success` is an info-level log, so it is suppressed below `-l 3`. A\n // generated token is the only way into the server — printing it somewhere the\n // user may not see would leave them locked out of their own review UI — so\n // repeat it at the same level as the warning that announced it.\n if (tokenWasGenerated && logger.level < 3) {\n logger.warn(`Review UI available at ${url}`);\n }\n\n if (readOnly) {\n logger.info(\"Running read-only: capture and approval are disabled.\");\n }\n};\n","import { getConfig } from \"@cappa/config\";\nimport { getLogger } from \"@cappa/logger\";\nimport { isLoopbackHost } from \"@cappa/server\";\nimport { resolveToken, startServer } from \"../utils/server\";\n\nexport type ServeOptions = {\n port?: number;\n host?: string;\n readOnly?: boolean;\n token?: string;\n /** Commander sets this to `false` for `--no-ui`. */\n ui?: boolean;\n};\n\n/**\n * Host a capture engine for a remote `cappa capture --server`.\n *\n * `review` minus the assumption that a person is about to open a browser. The\n * one deliberate divergence is the token: `review` generates one off loopback\n * because a human is reading the URL it prints, and `serve` has no such reader —\n * generating one here would produce a daemon nobody can authenticate against.\n * So off loopback it is required, and the command refuses to start without one.\n */\nexport const serve = async (options: ServeOptions = {}) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n const host = options.host ?? \"127.0.0.1\";\n const port = options.port ?? config.review.port;\n const readOnly = options.readOnly ?? false;\n const ui = options.ui ?? true;\n\n const token = resolveToken(options.token);\n\n if (!token && !isLoopbackHost(host) && !readOnly) {\n logger.error(\n `Binding to ${host} exposes capture control beyond this machine, so an access token is required. ` +\n \"Pass --token <token>, or set CAPPA_TOKEN to keep it out of the process list.\",\n );\n process.exit(1);\n return;\n }\n\n const { url } = await startServer({\n config,\n host,\n port,\n readOnly,\n token,\n ui,\n });\n\n // One structured line, then quiet: nothing is watching this the way a human\n // watches `review`, so the output exists to be greppable in a CI log.\n logger.log(\n `cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? \"yes\" : \"no\"}`,\n );\n\n if (ui) {\n logger.info(`Review UI available at ${url}`);\n }\n\n if (readOnly) {\n logger.info(\"Running read-only: capture and approval are disabled.\");\n }\n};\n","import { getConfig } from \"@cappa/config\";\nimport { collectScreenshots } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport chalk from \"chalk\";\n\nimport { describeChanges } from \"../utils/describeChanges\";\n\ntype StatusOptions = {\n maxRegions?: number;\n};\n\nexport const status = async (options: StatusOptions = {}) => {\n const logger = getLogger();\n\n const config = await getConfig();\n\n const groupedScreenshots = await collectScreenshots(config.outputDir);\n\n logger.debug(\n \"All screenshot information:\",\n JSON.stringify(groupedScreenshots, null, 2),\n );\n\n logger.box({\n title: \"Screenshot Status\",\n message: `${chalk.yellow(\"New screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"new\").length}\\n${chalk.red(\"Deleted screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"deleted\").length}\\n${chalk.green(\"Changed screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"changed\").length}\\n${chalk.blue(\"Passed screenshots:\")} ${groupedScreenshots.filter((r) => r.category === \"passed\").length}`,\n });\n\n const changeLines = describeChanges(groupedScreenshots, {\n maxRegions: options.maxRegions,\n });\n if (changeLines.length > 0) {\n logger.box({\n title: \"Changed Screenshots\",\n message: changeLines.join(\"\\n\"),\n });\n }\n\n if (\n groupedScreenshots.some((s) =>\n [\"new\", \"changed\", \"deleted\"].includes(s.category),\n )\n ) {\n process.exitCode = 1;\n }\n};\n","import { initLogger } from \"@cappa/logger\";\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { registerAgentCommand } from \"./commands/agent\";\nimport { approve } from \"./commands/approve\";\nimport { registerCaptureCommand } from \"./commands/capture\";\nimport { init } from \"./commands/init\";\nimport { review } from \"./commands/review\";\nimport { serve } from \"./commands/serve\";\nimport { status } from \"./commands/status\";\nimport { DEFAULT_MAX_REGIONS } from \"./utils/describeChanges\";\nimport { parseMaxRegions } from \"./utils/parseMaxRegions\";\n\nconst program = new Command();\n\nprogram\n .name(\"cappa\")\n .description(\"Cappa CLI\")\n .version(version)\n .option(\n \"-l, --log-level <level>\",\n \"set log level (0: fatal and error, 1: warn, 2: log, 3: info, 4: debug, 5: trace)\",\n \"3\",\n )\n .hook(\"preAction\", (thisCommand) => {\n const logLevel = parseInt(thisCommand.opts().logLevel, 10);\n const logger = initLogger(logLevel);\n logger?.debug(`Log level set to: ${logLevel}`);\n });\n\nregisterCaptureCommand(program);\n\nprogram\n .command(\"review\")\n .description(\"Open the review and capture UI\")\n .option(\"-p, --port <port>\", \"port to listen on\", (v) =>\n Number.parseInt(v, 10),\n )\n .option(\n \"--host <host>\",\n \"host to bind to (a non-loopback host requires an access token)\",\n )\n .option(\n \"--read-only\",\n \"serve the UI without capture, approval or any other mutation\",\n )\n .option(\n \"--token <token>\",\n \"require this access token on every API request (falls back to CAPPA_TOKEN)\",\n )\n .action(review);\n\nprogram\n .command(\"serve\")\n .description(\"Host a capture engine for a remote `cappa capture --server`\")\n .option(\"-p, --port <port>\", \"port to listen on\", (v) =>\n Number.parseInt(v, 10),\n )\n .option(\n \"--host <host>\",\n \"host to bind to (a non-loopback host requires an access token)\",\n )\n .option(\n \"--read-only\",\n \"serve without capture, approval or any other mutation\",\n )\n .option(\n \"--token <token>\",\n \"require this access token on every API request (falls back to CAPPA_TOKEN)\",\n )\n .option(\"--no-ui\", \"serve the API only, without the review UI\")\n .action(serve);\n\nprogram\n .command(\"approve\")\n .description(\"Approve screenshots\")\n .option(\n \"-f, --filter <filter...>\",\n \"only approve screenshots whose name includes the provided filter value(s)\",\n )\n .action(approve);\n\nprogram\n .command(\"status\")\n .description(\"Get status of screenshots\")\n .option(\n \"--max-regions <count>\",\n \"maximum number of interpreted diff regions listed per changed screenshot (0 to disable)\",\n parseMaxRegions,\n DEFAULT_MAX_REGIONS,\n )\n .action(status);\n\nregisterAgentCommand(program);\n\nprogram\n .command(\"init\")\n .description(\"Initialize Cappa in the current directory\")\n .action(init);\n\nexport async function run(): Promise<void> {\n await program.parseAsync();\n}\n"],"x_google_ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;ACIA,MAAM,oBAAoB,cAAc,YAAY,GAAG;AACvD,MAAM,mBAAmB,KAAK,QAAQ,YAAY,CAAC;AAEnD,MAAa,YAA4B,2BAAW;;;;;;;;;;;;;;;;;;ACYpD,MAAM,QAAQ;CACZ;CACA;CACA;AACF;AAIA,MAAM,aAAa,QACjB,MAAM,KAAK,YAAY;CACrB;CACA,QAAQ,KAAK,KAAK,KAAK,KAAK,SAAS,MAAM,CAAC;AAC9C,EAAE;AAEJ,MAAa,cAAc;CACzB,QAAQ,CACN,GAAG,UAAU,sBAAsB,GACnC;EACE,QAAQ;EACR,QAAQ,KAAK,KAAK,WAAW,UAAU,gBAAgB;CACzD,CACF;CACA,QAAQ,UAAU,sBAAsB;CACxC,UAAU,CACR,GAAG,UAAU,sBAAsB,GACnC,GAAG;EACD;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,UAAU;EACf,QAAQ,YAAY;EACpB,QAAQ,KAAK,KAAK,aAAa,IAAI;CACrC,EAAE,CACJ;AACF;AAIA,MAAa,oBAAoB,OAAO,KAAK,WAAW;;;;;;;;AASxD,MAAa,uBAAuB,OAAe,cAAsB;CACvE,IAAI,UAAU;CACd,OAAO,MAAM;EACX,MAAM,YAAY,KAAK,KAAK,SAAS,cAAc;EACnD,IAAI,GAAG,WAAW,KAAK,KAAK,WAAW,UAAU,SAAS,UAAU,CAAC,GACnE,OAAO;EAET,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,sDAAsD;EAExE,UAAU;CACZ;AACF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AA2C,CAAC,CAC9D,OAAO,KAAK;AAEf,QACG,QAAQ,SAAS,CAAC,CAClB,YAAY,qBAAqB,CAAC,CAClC,OACC,4BACA,2EACF,CAAC,CACA,OAAO,OAAO;AAEjB,QACG,QAAQ,QAAQ,CAAC,CACjB,YAAY,2BAA2B,CAAC,CACxC,OACC,yBACA,2FACA,iBAAA,CAEF,CAAC,CACA,OAAO,MAAM;AAEhB,qBAAqB,OAAO;AAE5B,QACG,QAAQ,MAAM,CAAC,CACf,YAAY,2CAA2C,CAAC,CACxD,OAAO,IAAI;AAEd,eAAsB,MAAqB;CACzC,MAAM,QAAQ,WAAW;AAC3B"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: cappa-judge
|
|
3
|
+
description: Judges changed Cappa screenshots from their region crops and records a verdict for each. Use for pending judgments from `cappa agent check`, and whenever the calling model cannot read images. Read-only except for recording verdicts.
|
|
4
|
+
tools: Read, Glob, Grep, Bash
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
You judge visual changes for Cappa. You look at evidence and record verdicts; you never fix code,
|
|
8
|
+
approve screenshots, capture, or edit files.
|
|
9
|
+
|
|
10
|
+
Run only these commands: `{{cappa}} agent check`, `{{cappa}} agent judge`, and read-only git
|
|
11
|
+
(`git diff`, `git log`, `git show`, `git status`). Pass `--json` to every cappa call. Never
|
|
12
|
+
hand-roll crops or pixel analysis — the crops Cappa wrote are the evidence.
|
|
13
|
+
|
|
14
|
+
## For every screenshot you are asked to judge
|
|
15
|
+
|
|
16
|
+
The judgment directory of each pending screenshot is in `results[].judgment` of
|
|
17
|
+
`{{cappa}} agent check --json`.
|
|
18
|
+
|
|
19
|
+
1. Read `request.json` in it: `regions[]` (largest first), `heuristic`, `summary`, `paths`.
|
|
20
|
+
2. Read `locator.png` and `regions.png` together, in one parallel batch — and batch across
|
|
21
|
+
screenshots too. `locator.png` is a thumbnail with every region outlined and numbered;
|
|
22
|
+
`regions.png` stacks one `#n expected | #n actual` row per region. When there is an
|
|
23
|
+
`overview.png` instead, the dimensions changed: read that.
|
|
24
|
+
3. Open the full-size `paths.expected` / `paths.actual` only if a change clearly continues outside
|
|
25
|
+
its crop.
|
|
26
|
+
4. Check intent against the code: `git diff`, `git log -p -- <path>` for the component or page
|
|
27
|
+
(the screenshot name and `taskId` usually point at it). A change that matches a code change is
|
|
28
|
+
evidence of intent; one with no code change behind it is noise or an unintended side effect.
|
|
29
|
+
This applies to the heuristic's label too: a heuristic `regression-likely` that lines up with
|
|
30
|
+
a deliberate code change is `intentional-likely`.
|
|
31
|
+
|
|
32
|
+
Before judging one by one, group screenshots whose `verdict.headline` is identical — they usually
|
|
33
|
+
share one cause (a footer date, a theme toggle). Confirm on one or two, then judge the group in a
|
|
34
|
+
single call.
|
|
35
|
+
|
|
36
|
+
## Labels
|
|
37
|
+
- `regression-likely` — broken, missing, clipped, overlapping, misaligned, wrong data, truncated
|
|
38
|
+
text, or an unintended side effect.
|
|
39
|
+
- `intentional-likely` — a deliberate content or style change consistent with the code.
|
|
40
|
+
- `noise-likely` — anti-aliasing, sub-pixel text rendering, non-deterministic content (clocks,
|
|
41
|
+
random data, animation). Say which element, so it can be masked.
|
|
42
|
+
|
|
43
|
+
## Record
|
|
44
|
+
```sh
|
|
45
|
+
{{cappa}} agent judge <name> [<name> ...] --label <label> --headline "<one line>" \
|
|
46
|
+
--rationale "<reason>" ["<reason>" ...] --confidence <0..1> --json
|
|
47
|
+
```
|
|
48
|
+
Then run `{{cappa}} agent check --json` once and make sure `pendingJudgments` is 0 and no result
|
|
49
|
+
carries a `verdictError`. (It exits 1 while anything differs — that is expected.)
|
|
50
|
+
|
|
51
|
+
## Reply
|
|
52
|
+
Only a summary, one line per screenshot: `<name>: <label> — <headline>`, followed by any element
|
|
53
|
+
you think should be masked. Do not describe the images at length; the caller reads verdicts from
|
|
54
|
+
the CLI.
|