@cappa/cli 0.18.0 → 0.20.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 +273 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +273 -26
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["path","fs","fsp","run","getConfig","runAgentCheck","toSlimAgentReport","writeAgentVerdict","collectScreenshots","ScreenshotFileSystem","clearJudgment","getLogger","InvalidArgumentError","isVerdictLabel","VERDICT_LABELS","getLogger","getConfig","ScreenshotFileSystem","groupScreenshots","z","normalizeChangeType","InvalidArgumentError","ProtocolMismatchError","createClient","getLogger","isLoopbackHost","LocalEngine","configToEngineOptions","createServer","path","getLogger","path","getConfig","LocalEngine","configToEngineOptions","getLogger","path","fs","defaultConfig","getLogger","getConfig","isLoopbackHost","randomBytes","getLogger","getConfig","isLoopbackHost","getLogger","getConfig","collectScreenshots","Command","initLogger"],"sources":["../package.json","../src/utils/agentSkills.ts","../src/utils/judgeGuard.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":["","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\n/**\n * A judge subagent's frontmatter takes a `model:`, in the agent's own format.\n * Without one the judge runs on the calling model — so a caller whose model\n * cannot read images gets a judge that cannot either.\n */\nexport type JudgeFormat = \"claude\" | \"opencode\";\n\ntype FileMapping = { source: string; target: string; judge?: JudgeFormat };\n\n/**\n * Both judges share one body; their own source files are only the\n * frontmatter each agent needs. The body points at the copy of `JUDGING.md`\n * the agent's caller reads — for OpenCode that is the `.claude` copy when\n * there is one, since OpenCode prefers it over `.agents` (see the warning in\n * `installAgentSkills`), and judge and caller must not follow two copies.\n */\nconst JUDGE_BODY = \"judge/cappa-judge.md\";\n\nconst CLAUDE_JUDGING = \".claude/skills/cappa/JUDGING.md\";\nconst AGENTS_JUDGING = \".agents/skills/cappa/JUDGING.md\";\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 judge: \"claude\",\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 ].map(\n (file): FileMapping => ({\n source: `opencode/${file}`,\n target: path.join(\".opencode\", file),\n }),\n ),\n {\n source: \"opencode/agents/cappa-judge.md\",\n target: path.join(\".opencode\", \"agents\", \"cappa-judge.md\"),\n judge: \"opencode\",\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\nconst LOCKFILES = {\n \"pnpm-lock.yaml\": \"pnpm\",\n \"yarn.lock\": \"yarn\",\n \"bun.lock\": \"bun\",\n \"bun.lockb\": \"bun\",\n \"package-lock.json\": \"npm\",\n} as const;\n\ntype PackageManager = (typeof LOCKFILES)[keyof typeof LOCKFILES];\n\nconst detectPackageManager = (dir: string): PackageManager | undefined => {\n for (const [lockfile, manager] of Object.entries(LOCKFILES)) {\n if (fs.existsSync(path.join(dir, lockfile))) return manager;\n }\n return undefined;\n};\n\n/**\n * The directory agents work from: the workspace root holding the lockfile.\n *\n * `cappa` is often installed in a single workspace package and run with\n * `pnpm -F <pkg> exec cappa`, which puts `cwd` inside that package — but\n * agents only read `.claude/` and `.agents/` from the root they were started\n * in. Walk up to the nearest lockfile or `pnpm-workspace.yaml`, without\n * leaving the git repository; `cwd` itself when there is neither.\n */\nexport const findProjectRoot = (cwd: string): string => {\n let current = path.resolve(cwd);\n while (true) {\n const has = (entry: string) => fs.existsSync(path.join(current, entry));\n if (detectPackageManager(current) || has(\"pnpm-workspace.yaml\")) {\n return current;\n }\n const parent = path.dirname(current);\n if (has(\".git\") || parent === current) return path.resolve(cwd);\n current = parent;\n }\n};\n\nconst readPackageName = (dir: string): string | undefined => {\n try {\n const { name } = JSON.parse(\n fs.readFileSync(path.join(dir, \"package.json\"), \"utf8\"),\n );\n return typeof name === \"string\" ? name : undefined;\n } catch {\n return undefined;\n }\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 *\n * When `cwd` is a package below `root`, the command switches into it: that is\n * where `cappa` is installed and where `cappa.config.ts` lives, while agents\n * run commands from the root.\n */\nexport const detectCappaRunner = (root: string, cwd: string = root): string => {\n const manager = detectPackageManager(root);\n const dir = path.relative(root, cwd).split(path.sep).join(\"/\");\n\n if (!dir) {\n return {\n pnpm: \"pnpm exec cappa\",\n yarn: \"yarn cappa\",\n bun: \"bunx cappa\",\n npm: \"npx cappa\",\n }[manager ?? \"npm\"];\n }\n\n switch (manager) {\n case \"pnpm\":\n return `pnpm -C ${dir} exec cappa`;\n case \"yarn\": {\n const name = readPackageName(cwd);\n return name ? `yarn workspace ${name} cappa` : `yarn --cwd ${dir} cappa`;\n }\n case \"bun\":\n return `bun --cwd ${dir} x cappa`;\n default:\n return `npm exec -w ${dir} -- cappa`;\n }\n};\n\n/** Fill the `{{cappa}}` placeholder in a source file. */\nexport const renderIntegrationFile = (source: string, runner: string) =>\n source.replaceAll(\"{{cappa}}\", runner);\n\n/**\n * Which judge a model id is for: OpenCode names models `provider/model`,\n * Claude Code takes an alias (`sonnet`) or a model id, neither with a slash.\n */\nexport const judgeFormatOf = (model: string): JudgeFormat =>\n model.includes(\"/\") ? \"opencode\" : \"claude\";\n\n/** Pin a judge's model: a `model:` line at the top of its frontmatter. */\nexport const withJudgeModel = (source: string, model: string) =>\n source.replace(/^---\\n/, `---\\nmodel: ${model}\\n`);\n\n/** The model pinned in an installed judge, if any. */\nconst readJudgeModel = (source: string) =>\n /^---\\nmodel: (.*)\\n/.exec(source)?.[1]?.trim() || undefined;\n\n/** A judge file without its `model:` line, to tell a re-pin from an edit. */\nconst withoutJudgeModel = (source: string) =>\n source.replace(/^(---\\n)model: .*\\n/, \"$1\");\n\nexport type SkillFileResult = {\n stack: SkillStack;\n path: string;\n status: \"written\" | \"unchanged\" | \"skipped\";\n};\n\nexport type InstallResult = {\n root: string;\n runner: string;\n /** The model pinned in each judge that was installed; absent = inherited. */\n judgeModels: Partial<Record<JudgeFormat, string>>;\n files: SkillFileResult[];\n warnings: string[];\n};\n\n/**\n * Copy each stack's files into the project root (see `findProjectRoot`).\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 *\n * `judgeModel` goes into the judge whose format it matches (see\n * `judgeFormatOf`). Without it, a judge keeps the model it was pinned to.\n * Changing only that model is not a modification: an installed judge that\n * differs from the new one by its `model:` line alone is rewritten without\n * `force`.\n */\nexport const installAgentSkills = async (options: {\n cwd: string;\n root?: string;\n stacks: readonly SkillStack[];\n force?: boolean;\n runner?: string;\n judgeModel?: string;\n sourceDir?: string;\n}): Promise<InstallResult> => {\n const sourceDir = options.sourceDir ?? findIntegrationsDir();\n const root = options.root ?? findProjectRoot(options.cwd);\n const runner = options.runner ?? detectCappaRunner(root, options.cwd);\n const judgeModel = options.judgeModel?.trim() || undefined;\n const judgeFormats = options.stacks.flatMap((stack) =>\n STACK_FILES[stack].flatMap((mapping) =>\n mapping.judge ? [mapping.judge] : [],\n ),\n );\n\n if (judgeModel && !judgeFormats.includes(judgeFormatOf(judgeModel))) {\n throw new Error(\n judgeFormatOf(judgeModel) === \"opencode\"\n ? `--judge-model \"${judgeModel}\" is an OpenCode model (provider/model), but no OpenCode judge is being installed — add --stack opencode`\n : `--judge-model \"${judgeModel}\" is a Claude Code model, but no Claude Code judge is being installed — OpenCode models are written provider/model, e.g. anthropic/claude-sonnet-5-5`,\n );\n }\n\n const judgeModels: InstallResult[\"judgeModels\"] = {};\n if (judgeModel) judgeModels[judgeFormatOf(judgeModel)] = judgeModel;\n\n const claudeSkillDir = path.resolve(root, \".claude/skills/cappa\");\n const hasClaudeSkill =\n options.stacks.includes(\"claude\") ||\n fs.existsSync(path.join(claudeSkillDir, \"SKILL.md\"));\n const judgingFor: Record<JudgeFormat, string> = {\n claude: CLAUDE_JUDGING,\n opencode: hasClaudeSkill ? CLAUDE_JUDGING : AGENTS_JUDGING,\n };\n\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(root, mapping.target);\n if (seen.has(target)) continue;\n seen.add(target);\n\n const read = (file: string) =>\n fsp.readFile(path.join(sourceDir, file), \"utf8\");\n let template = await read(mapping.source);\n if (mapping.judge) {\n template = `${template}\\n${await read(JUDGE_BODY)}`.replaceAll(\n \"{{judging}}\",\n judgingFor[mapping.judge],\n );\n }\n const rendered = renderIntegrationFile(template, runner);\n const existing = await fsp\n .readFile(target, \"utf8\")\n .catch(() => undefined);\n let source = rendered;\n if (mapping.judge) {\n const model =\n judgeModels[mapping.judge] ??\n (existing === undefined ? undefined : readJudgeModel(existing));\n if (model) {\n judgeModels[mapping.judge] = model;\n source = withJudgeModel(rendered, model);\n }\n }\n\n if (existing === source) {\n files.push({ stack, path: target, status: \"unchanged\" });\n continue;\n }\n const repinned =\n mapping.judge !== undefined &&\n existing !== undefined &&\n withoutJudgeModel(existing) === rendered;\n if (existing !== undefined && !options.force && !repinned) {\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 if (options.stacks.includes(\"opencode\") && hasClaudeSkill) {\n warnings.push(\n \"OpenCode reads .claude/skills too, and uses that copy of the cappa skill over the one in .agents/skills — so its cappa-judge follows .claude/skills/cappa/JUDGING.md. Tailor that copy; keep .agents/skills in sync for other agents.\",\n );\n }\n\n if (judgeFormats.includes(\"opencode\") && !judgeModels.opencode) {\n warnings.push(\n \"The OpenCode cappa-judge runs on the calling model, so it cannot judge if that model cannot read images. Pin a vision model: --judge-model <provider/model>\",\n );\n }\n\n return { root, runner, judgeModels, files, warnings };\n};\n","/**\n * The shell commands the `cappa-judge` subagent may run.\n *\n * OpenCode enforces this with the judge's `permission.bash` patterns. Claude\n * Code agent frontmatter cannot narrow Bash to commands, only run a\n * `PreToolUse` hook — which calls `cappa agent guard`, and that calls this.\n */\n\nconst GIT_READ_ONLY = [\"diff\", \"log\", \"show\", \"status\"] as const;\nconst CAPPA_ALLOWED = [\"check\", \"judge\"] as const;\n\n/**\n * Split a command the way a shell would, as far as the guard needs: words,\n * with quotes removed. Returns a reason instead when the command does\n * anything but run one program — chaining, pipes, redirects, substitution —\n * since a prefix check alone would let `git diff; rm -rf .` through.\n *\n * Quoted text is literal, so a headline like \"Price | Total misaligned\"\n * stays one argument; only `$(` and backticks are refused inside double\n * quotes, because the shell still expands those.\n */\nexport const splitCommand = (\n command: string,\n): { words: string[] } | { reason: string } => {\n const words: string[] = [];\n let word: string | undefined;\n let quote: \"'\" | '\"' | undefined;\n\n for (let i = 0; i < command.length; i++) {\n const char = command[i] as string;\n const next = command[i + 1];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = undefined;\n else word += char;\n continue;\n }\n if (quote === '\"') {\n if (char === '\"') quote = undefined;\n else if (char === \"`\" || (char === \"$\" && next === \"(\")) {\n return { reason: \"command substitution is not allowed\" };\n } else if (char === \"\\\\\" && next !== undefined) {\n word += next;\n i++;\n } else word += char;\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n word ??= \"\";\n } else if (char === \"\\\\\" && next === \"\\n\") {\n i++; // line continuation\n } else if (char === \"\\\\\" && next !== undefined) {\n word = (word ?? \"\") + next;\n i++;\n } else if (char === \" \" || char === \"\\t\") {\n if (word !== undefined) words.push(word);\n word = undefined;\n } else if (\";&|<>`\\n\".includes(char) || (char === \"$\" && next === \"(\")) {\n return {\n reason:\n \"run one command at a time — no chaining, pipes, redirects or substitution\",\n };\n } else {\n word = (word ?? \"\") + char;\n }\n }\n\n if (quote) return { reason: \"unterminated quote\" };\n if (word !== undefined) words.push(word);\n return { words };\n};\n\n/**\n * Why the judge may not run `command`, or `undefined` when it may.\n *\n * `runner` is how the project runs cappa (`pnpm exec cappa`); the judge's\n * cappa calls must start with exactly those words.\n */\nexport const judgeCommandRefusal = (\n command: string,\n runner: string,\n): string | undefined => {\n const split = splitCommand(command.trim());\n if (\"reason\" in split) return split.reason;\n\n const { words } = split;\n const prefix = runner.trim().split(/\\s+/);\n const allowed = `only \\`${runner} agent ${CAPPA_ALLOWED.join(\"|\")}\\` and \\`git ${GIT_READ_ONLY.join(\"|\")}\\``;\n\n if (words[0] === \"git\") {\n // Other global options (`-C <dir>`, `-c key=value`) are not needed by\n // the judge, and `-c` could point git at a program to run.\n const sub = words[1] === \"--no-pager\" ? words[2] : words[1];\n if ((GIT_READ_ONLY as readonly string[]).includes(sub ?? \"\")) {\n if (words.some((w) => w === \"--output\" || w.startsWith(\"--output=\"))) {\n return \"`--output` writes a file\";\n }\n return undefined;\n }\n return `the judge may run ${allowed}`;\n }\n\n const isCappa = prefix.every((w, i) => words[i] === w);\n const [agent, sub] = words.slice(prefix.length);\n if (\n isCappa &&\n agent === \"agent\" &&\n (CAPPA_ALLOWED as readonly string[]).includes(sub ?? \"\")\n ) {\n return undefined;\n }\n return `the judge may run ${allowed}`;\n};\n","import { getConfig } from \"@cappa/config\";\nimport {\n type AgentReport,\n clearJudgment,\n collectScreenshots,\n isVerdictLabel,\n runAgentCheck,\n ScreenshotFileSystem,\n toSlimAgentReport,\n VERDICT_LABELS,\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 findProjectRoot,\n installAgentSkills,\n SKILL_STACK_NAMES,\n type SkillStack,\n} from \"../utils/agentSkills\";\nimport { judgeCommandRefusal } from \"../utils/judgeGuard\";\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};\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\") {\n lines.push(`${chalk.bold(entry.name)} ${chalk.dim(entry.category)}`);\n continue;\n }\n if (entry.verdict) {\n const { label, headline } = entry.verdict;\n lines.push(\n `${chalk.bold(entry.name)} ${LABEL_COLORS[label](label)} — ${headline}`,\n );\n } else {\n lines.push(\n `${chalk.bold(entry.name)} ${chalk.yellow(\"awaiting judgment\")} — ${entry.change ?? \"changed\"}`,\n );\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 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 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: VerdictLabel;\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?: VerdictLabel[];\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 verdict\n // about images that have since been re-captured is exactly the mistake\n // to prevent, and a changed screenshot's current verdict is what the\n // regression guard 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 report = await runAgentCheck({\n outputDir: config.outputDir,\n diff: config.diff,\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 again (\\`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 judgeModel?: string;\n};\n\n/**\n * Advice about the config the skill will run against. Read-only: `agent init`\n * installs skill files and never edits `cappa.config.ts`.\n *\n * Without a `webServer` the skill still works, but the agent has to get the\n * app under test running by itself — which is exactly the project-specific\n * guesswork `webServer` exists to remove.\n */\nexport const webServerHints = async (cwd: string): Promise<string[]> => {\n let config: Awaited<ReturnType<typeof getConfig>>;\n try {\n config = await getConfig(undefined, { cwd, command: \"agent\" });\n } catch {\n // No config, or one that does not load: nothing to advise on here.\n return [];\n }\n\n if (config.webServer.length > 0) {\n return [];\n }\n\n return [\n \"cappa.config.ts has no `webServer`, so the agent has to start whatever the plugins point at itself. \" +\n 'Add one and `cappa capture` starts and stops it: webServer: { command: \"pnpm storybook --ci\", url: \"http://localhost:6006\" }',\n ];\n};\n\nexport const agentInit = (options: InitOptions) =>\n run(options, async () => {\n const cwd = process.cwd();\n const root = findProjectRoot(cwd);\n const stacks =\n options.stack === \"all\"\n ? SKILL_STACK_NAMES\n : options.stack\n ? [options.stack]\n : detectSkillStacks(root);\n\n const { runner, judgeModels, files, warnings } = await installAgentSkills({\n cwd,\n root,\n stacks,\n force: options.force,\n runner: options.runner,\n judgeModel: options.judgeModel,\n });\n\n const hints = await webServerHints(cwd);\n\n if (options.json) {\n printJson({ root, stacks, runner, judgeModels, files, warnings, hints });\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 [stack, model] of Object.entries(judgeModels)) {\n logger.log(chalk.dim(`${stack} cappa-judge runs on \\`${model}\\``));\n }\n for (const warning of warnings) {\n logger.warn(warning);\n }\n for (const hint of hints) {\n logger.info(hint);\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 readStdin = async (stream: NodeJS.ReadableStream = process.stdin) => {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\n/**\n * Decide a Claude Code `PreToolUse` hook call for the `cappa-judge`\n * subagent: `undefined` lets the Bash command run, a message blocks it.\n * Anything it cannot read is blocked too — a guard that fails open is no\n * guard.\n */\nexport const judgeGuardVerdict = (\n input: string,\n runner: string,\n): string | undefined => {\n let command: unknown;\n try {\n command = JSON.parse(input)?.tool_input?.command;\n } catch {\n return \"cappa-judge: could not read the hook input\";\n }\n if (typeof command !== \"string\") {\n return \"cappa-judge: could not read the hook input\";\n }\n const refusal = judgeCommandRefusal(command, runner);\n return refusal ? `cappa-judge: ${refusal}` : undefined;\n};\n\nexport const agentGuard = async (options: { runner: string }) => {\n const message = judgeGuardVerdict(await readStdin(), options.runner);\n if (message) {\n process.stderr.write(`${message}\\n`);\n // 2 is the exit code Claude Code reads as \"block this tool call\".\n process.exitCode = 2;\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): VerdictLabel => {\n if (!isVerdictLabel(value)) {\n throw new InvalidArgumentError(\n `label must be one of: ${VERDICT_LABELS.join(\", \")}`,\n );\n }\n return value;\n};\n\nconst collectLabel = (value: string, previous: VerdictLabel[] = []) => [\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: hand every change to a judge, record verdicts, approve\",\n );\n\n agent\n .command(\"check\")\n .description(\n \"Write a judgment request for every changed screenshot and apply verdicts already recorded (does not capture)\",\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>\", VERDICT_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(\n \"--judge-model <model>\",\n \"pin the cappa-judge subagent to a model that can read images: provider/model for OpenCode, an alias or model id for Claude Code (default: the calling model)\",\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentInit);\n\n // Called by the Claude Code judge's PreToolUse hook, not by people.\n agent\n .command(\"guard\", { hidden: true })\n .description(\"Allow or block a cappa-judge Bash call (Claude Code hook)\")\n .requiredOption(\"--runner <command>\", \"how the project runs cappa\")\n .action(agentGuard);\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 /**\n * Tasks that did not produce a comparable screenshot.\n *\n * Identical errors from one plugin collapse into one entry: `taskId` is the\n * first affected task and `count` how many there were. An unreachable\n * Storybook fails every story the same way, and 300 copies of one sentence\n * bury the fix rather than explain it.\n */\n errors: Array<{\n taskId: string;\n plugin: string;\n error: string;\n count?: number;\n }>;\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\ntype CaptureError = CaptureJsonReport[\"errors\"][number];\n\n/**\n * Fold errors with the same plugin and message into one, keeping the first\n * task and counting the rest. Order follows each message's first occurrence.\n */\nexport const collapseIdenticalErrors = (\n errors: readonly CaptureError[],\n): CaptureError[] => {\n const collapsed = new Map<string, CaptureError>();\n\n for (const error of errors) {\n const key = `${error.plugin}\\u0000${error.error}`;\n const existing = collapsed.get(key);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n } else {\n collapsed.set(key, { ...error });\n }\n }\n\n return [...collapsed.values()];\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 = collapseIdenticalErrors(\n failures.flatMap((failure) => {\n const error = toCaptureError(failure);\n return error ? [error] : [];\n }),\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\nconst errorMessageOf = (error: unknown): string | undefined => {\n if (!error) {\n return undefined;\n }\n if (typeof error === \"string\") {\n return error;\n }\n return error instanceof Error ? error.message : String(error);\n};\n\nexport function 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 // An unreachable app fails every task with the same sentence. Say it once,\n // with the tasks it covers, instead of once per task.\n const byError = new Map<string, TaskFailure[]>();\n for (const failed of failures) {\n const message = errorMessageOf(failed.result.error);\n if (message !== undefined) {\n byError.set(message, [...(byError.get(message) ?? []), failed]);\n }\n }\n\n for (const [message, shared] of byError) {\n if (shared.length < 2) {\n continue;\n }\n const shown = shared.slice(0, 3).map((failed) => failed.taskId);\n const more = shared.length - shown.length;\n lines.push(\n `\\n ${chalk.dim(\"Tasks:\")} ${shown.join(\", \")}${more > 0 ? ` and ${more} more` : \"\"}`,\n );\n lines.push(` ${chalk.red(\"Error:\")} ${message}`);\n }\n\n for (const failed of failures) {\n const errorMsg = errorMessageOf(failed.result.error);\n if (errorMsg !== undefined && (byError.get(errorMsg)?.length ?? 0) > 1) {\n continue;\n }\n\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 (errorMsg !== undefined) {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACmBA,MAAM,QAAQ;CACZ;CACA;CACA;AACF;;;;;;;;AAkBA,MAAM,aAAa;AAEnB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,MAAM,aAAa,QACjB,MAAM,KAAK,YAAY;CACrB;CACA,QAAQA,UAAAA,QAAK,KAAK,KAAKA,UAAAA,QAAK,SAAS,MAAM,CAAC;AAC9C,EAAE;AAEJ,MAAa,cAAc;CACzB,QAAQ,CACN,GAAG,UAAU,sBAAsB,GACnC;EACE,QAAQ;EACR,QAAQA,UAAAA,QAAK,KAAK,WAAW,UAAU,gBAAgB;EACvD,OAAO;CACT,CACF;CACA,QAAQ,UAAU,sBAAsB;CACxC,UAAU;EACR,GAAG,UAAU,sBAAsB;EACnC,GAAG;GACD;GACA;GACA;EACF,CAAC,CAAC,KACC,UAAuB;GACtB,QAAQ,YAAY;GACpB,QAAQA,UAAAA,QAAK,KAAK,aAAa,IAAI;EACrC,EACF;EACA;GACE,QAAQ;GACR,QAAQA,UAAAA,QAAK,KAAK,aAAa,UAAU,gBAAgB;GACzD,OAAO;EACT;CACF;AACF;AAIA,MAAa,oBAAoB,OAAO,KAAK,WAAW;;;;;;;;AASxD,MAAa,uBAAuB,OAAe,cAAsB;CACvE,IAAI,UAAU;CACd,OAAO,MAAM;EACX,MAAM,YAAYA,UAAAA,QAAK,KAAK,SAAS,cAAc;EACnD,IAAIC,QAAAA,QAAG,WAAWD,UAAAA,QAAK,KAAK,WAAW,UAAU,SAAS,UAAU,CAAC,GACnE,OAAO;EAET,MAAM,SAASA,UAAAA,QAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,sDAAsD;EAExE,UAAU;CACZ;AACF;;;;;;;;AASA,MAAa,qBAAqB,QAA8B;CAC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B,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.cjs","names":["path","fs","fsp","run","getConfig","runAgentCheck","toSlimAgentReport","writeAgentVerdict","collectScreenshots","ScreenshotFileSystem","clearJudgment","getLogger","InvalidArgumentError","isVerdictLabel","VERDICT_LABELS","getLogger","getConfig","ScreenshotFileSystem","groupScreenshots","getConfig","resolveContainerOptions","getLogger","removePlaywrightContainers","z","normalizeChangeType","describePixelRatioMismatch","InvalidArgumentError","ProtocolMismatchError","createClient","http","getLogger","LocalEngine","configToEngineOptions","createServer","path","getLogger","path","getConfig","LocalEngine","configToEngineOptions","getLogger","path","fs","defaultConfig","getLogger","getConfig","isLoopbackHost","randomBytes","getLogger","getConfig","isLoopbackHost","getLogger","getConfig","collectScreenshots","Command","initLogger"],"sources":["../package.json","../src/utils/agentSkills.ts","../src/utils/judgeGuard.ts","../src/commands/agent.ts","../src/commands/approve.ts","../src/commands/browser.ts","../src/utils/captureReport.ts","../src/utils/describeChanges.ts","../src/utils/parseMaxRegions.ts","../src/utils/remoteEngine.ts","../src/utils/loopback.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":["","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\n/**\n * A judge subagent's frontmatter takes a `model:`, in the agent's own format.\n * Without one the judge runs on the calling model — so a caller whose model\n * cannot read images gets a judge that cannot either.\n */\nexport type JudgeFormat = \"claude\" | \"opencode\";\n\ntype FileMapping = { source: string; target: string; judge?: JudgeFormat };\n\n/**\n * Both judges share one body; their own source files are only the\n * frontmatter each agent needs. The body points at the copy of `JUDGING.md`\n * the agent's caller reads — for OpenCode that is the `.claude` copy when\n * there is one, since OpenCode prefers it over `.agents` (see the warning in\n * `installAgentSkills`), and judge and caller must not follow two copies.\n */\nconst JUDGE_BODY = \"judge/cappa-judge.md\";\n\nconst CLAUDE_JUDGING = \".claude/skills/cappa/JUDGING.md\";\nconst AGENTS_JUDGING = \".agents/skills/cappa/JUDGING.md\";\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 judge: \"claude\",\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 ].map(\n (file): FileMapping => ({\n source: `opencode/${file}`,\n target: path.join(\".opencode\", file),\n }),\n ),\n {\n source: \"opencode/agents/cappa-judge.md\",\n target: path.join(\".opencode\", \"agents\", \"cappa-judge.md\"),\n judge: \"opencode\",\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\nconst LOCKFILES = {\n \"pnpm-lock.yaml\": \"pnpm\",\n \"yarn.lock\": \"yarn\",\n \"bun.lock\": \"bun\",\n \"bun.lockb\": \"bun\",\n \"package-lock.json\": \"npm\",\n} as const;\n\ntype PackageManager = (typeof LOCKFILES)[keyof typeof LOCKFILES];\n\nconst detectPackageManager = (dir: string): PackageManager | undefined => {\n for (const [lockfile, manager] of Object.entries(LOCKFILES)) {\n if (fs.existsSync(path.join(dir, lockfile))) return manager;\n }\n return undefined;\n};\n\n/**\n * The directory agents work from: the workspace root holding the lockfile.\n *\n * `cappa` is often installed in a single workspace package and run with\n * `pnpm -F <pkg> exec cappa`, which puts `cwd` inside that package — but\n * agents only read `.claude/` and `.agents/` from the root they were started\n * in. Walk up to the nearest lockfile or `pnpm-workspace.yaml`, without\n * leaving the git repository; `cwd` itself when there is neither.\n */\nexport const findProjectRoot = (cwd: string): string => {\n let current = path.resolve(cwd);\n while (true) {\n const has = (entry: string) => fs.existsSync(path.join(current, entry));\n if (detectPackageManager(current) || has(\"pnpm-workspace.yaml\")) {\n return current;\n }\n const parent = path.dirname(current);\n if (has(\".git\") || parent === current) return path.resolve(cwd);\n current = parent;\n }\n};\n\nconst readPackageName = (dir: string): string | undefined => {\n try {\n const { name } = JSON.parse(\n fs.readFileSync(path.join(dir, \"package.json\"), \"utf8\"),\n );\n return typeof name === \"string\" ? name : undefined;\n } catch {\n return undefined;\n }\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 *\n * When `cwd` is a package below `root`, the command switches into it: that is\n * where `cappa` is installed and where `cappa.config.ts` lives, while agents\n * run commands from the root.\n */\nexport const detectCappaRunner = (root: string, cwd: string = root): string => {\n const manager = detectPackageManager(root);\n const dir = path.relative(root, cwd).split(path.sep).join(\"/\");\n\n if (!dir) {\n return {\n pnpm: \"pnpm exec cappa\",\n yarn: \"yarn cappa\",\n bun: \"bunx cappa\",\n npm: \"npx cappa\",\n }[manager ?? \"npm\"];\n }\n\n switch (manager) {\n case \"pnpm\":\n return `pnpm -C ${dir} exec cappa`;\n case \"yarn\": {\n const name = readPackageName(cwd);\n return name ? `yarn workspace ${name} cappa` : `yarn --cwd ${dir} cappa`;\n }\n case \"bun\":\n return `bun --cwd ${dir} x cappa`;\n default:\n return `npm exec -w ${dir} -- cappa`;\n }\n};\n\n/** Fill the `{{cappa}}` placeholder in a source file. */\nexport const renderIntegrationFile = (source: string, runner: string) =>\n source.replaceAll(\"{{cappa}}\", runner);\n\n/**\n * Which judge a model id is for: OpenCode names models `provider/model`,\n * Claude Code takes an alias (`sonnet`) or a model id, neither with a slash.\n */\nexport const judgeFormatOf = (model: string): JudgeFormat =>\n model.includes(\"/\") ? \"opencode\" : \"claude\";\n\n/** Pin a judge's model: a `model:` line at the top of its frontmatter. */\nexport const withJudgeModel = (source: string, model: string) =>\n source.replace(/^---\\n/, `---\\nmodel: ${model}\\n`);\n\n/** The model pinned in an installed judge, if any. */\nconst readJudgeModel = (source: string) =>\n /^---\\nmodel: (.*)\\n/.exec(source)?.[1]?.trim() || undefined;\n\n/** A judge file without its `model:` line, to tell a re-pin from an edit. */\nconst withoutJudgeModel = (source: string) =>\n source.replace(/^(---\\n)model: .*\\n/, \"$1\");\n\nexport type SkillFileResult = {\n stack: SkillStack;\n path: string;\n status: \"written\" | \"unchanged\" | \"skipped\";\n};\n\nexport type InstallResult = {\n root: string;\n runner: string;\n /** The model pinned in each judge that was installed; absent = inherited. */\n judgeModels: Partial<Record<JudgeFormat, string>>;\n files: SkillFileResult[];\n warnings: string[];\n};\n\n/**\n * Copy each stack's files into the project root (see `findProjectRoot`).\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 *\n * `judgeModel` goes into the judge whose format it matches (see\n * `judgeFormatOf`). Without it, a judge keeps the model it was pinned to.\n * Changing only that model is not a modification: an installed judge that\n * differs from the new one by its `model:` line alone is rewritten without\n * `force`.\n */\nexport const installAgentSkills = async (options: {\n cwd: string;\n root?: string;\n stacks: readonly SkillStack[];\n force?: boolean;\n runner?: string;\n judgeModel?: string;\n sourceDir?: string;\n}): Promise<InstallResult> => {\n const sourceDir = options.sourceDir ?? findIntegrationsDir();\n const root = options.root ?? findProjectRoot(options.cwd);\n const runner = options.runner ?? detectCappaRunner(root, options.cwd);\n const judgeModel = options.judgeModel?.trim() || undefined;\n const judgeFormats = options.stacks.flatMap((stack) =>\n STACK_FILES[stack].flatMap((mapping) =>\n mapping.judge ? [mapping.judge] : [],\n ),\n );\n\n if (judgeModel && !judgeFormats.includes(judgeFormatOf(judgeModel))) {\n throw new Error(\n judgeFormatOf(judgeModel) === \"opencode\"\n ? `--judge-model \"${judgeModel}\" is an OpenCode model (provider/model), but no OpenCode judge is being installed — add --stack opencode`\n : `--judge-model \"${judgeModel}\" is a Claude Code model, but no Claude Code judge is being installed — OpenCode models are written provider/model, e.g. anthropic/claude-sonnet-5-5`,\n );\n }\n\n const judgeModels: InstallResult[\"judgeModels\"] = {};\n if (judgeModel) judgeModels[judgeFormatOf(judgeModel)] = judgeModel;\n\n const claudeSkillDir = path.resolve(root, \".claude/skills/cappa\");\n const hasClaudeSkill =\n options.stacks.includes(\"claude\") ||\n fs.existsSync(path.join(claudeSkillDir, \"SKILL.md\"));\n const judgingFor: Record<JudgeFormat, string> = {\n claude: CLAUDE_JUDGING,\n opencode: hasClaudeSkill ? CLAUDE_JUDGING : AGENTS_JUDGING,\n };\n\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(root, mapping.target);\n if (seen.has(target)) continue;\n seen.add(target);\n\n const read = (file: string) =>\n fsp.readFile(path.join(sourceDir, file), \"utf8\");\n let template = await read(mapping.source);\n if (mapping.judge) {\n template = `${template}\\n${await read(JUDGE_BODY)}`.replaceAll(\n \"{{judging}}\",\n judgingFor[mapping.judge],\n );\n }\n const rendered = renderIntegrationFile(template, runner);\n const existing = await fsp\n .readFile(target, \"utf8\")\n .catch(() => undefined);\n let source = rendered;\n if (mapping.judge) {\n const model =\n judgeModels[mapping.judge] ??\n (existing === undefined ? undefined : readJudgeModel(existing));\n if (model) {\n judgeModels[mapping.judge] = model;\n source = withJudgeModel(rendered, model);\n }\n }\n\n if (existing === source) {\n files.push({ stack, path: target, status: \"unchanged\" });\n continue;\n }\n const repinned =\n mapping.judge !== undefined &&\n existing !== undefined &&\n withoutJudgeModel(existing) === rendered;\n if (existing !== undefined && !options.force && !repinned) {\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 if (options.stacks.includes(\"opencode\") && hasClaudeSkill) {\n warnings.push(\n \"OpenCode reads .claude/skills too, and uses that copy of the cappa skill over the one in .agents/skills — so its cappa-judge follows .claude/skills/cappa/JUDGING.md. Tailor that copy; keep .agents/skills in sync for other agents.\",\n );\n }\n\n if (judgeFormats.includes(\"opencode\") && !judgeModels.opencode) {\n warnings.push(\n \"The OpenCode cappa-judge runs on the calling model, so it cannot judge if that model cannot read images. Pin a vision model: --judge-model <provider/model>\",\n );\n }\n\n return { root, runner, judgeModels, files, warnings };\n};\n","/**\n * The shell commands the `cappa-judge` subagent may run.\n *\n * OpenCode enforces this with the judge's `permission.bash` patterns. Claude\n * Code agent frontmatter cannot narrow Bash to commands, only run a\n * `PreToolUse` hook — which calls `cappa agent guard`, and that calls this.\n */\n\nconst GIT_READ_ONLY = [\"diff\", \"log\", \"show\", \"status\"] as const;\nconst CAPPA_ALLOWED = [\"check\", \"judge\"] as const;\n\n/**\n * Split a command the way a shell would, as far as the guard needs: words,\n * with quotes removed. Returns a reason instead when the command does\n * anything but run one program — chaining, pipes, redirects, substitution —\n * since a prefix check alone would let `git diff; rm -rf .` through.\n *\n * Quoted text is literal, so a headline like \"Price | Total misaligned\"\n * stays one argument; only `$(` and backticks are refused inside double\n * quotes, because the shell still expands those.\n */\nexport const splitCommand = (\n command: string,\n): { words: string[] } | { reason: string } => {\n const words: string[] = [];\n let word: string | undefined;\n let quote: \"'\" | '\"' | undefined;\n\n for (let i = 0; i < command.length; i++) {\n const char = command[i] as string;\n const next = command[i + 1];\n\n if (quote === \"'\") {\n if (char === \"'\") quote = undefined;\n else word += char;\n continue;\n }\n if (quote === '\"') {\n if (char === '\"') quote = undefined;\n else if (char === \"`\" || (char === \"$\" && next === \"(\")) {\n return { reason: \"command substitution is not allowed\" };\n } else if (char === \"\\\\\" && next !== undefined) {\n word += next;\n i++;\n } else word += char;\n continue;\n }\n\n if (char === \"'\" || char === '\"') {\n quote = char;\n word ??= \"\";\n } else if (char === \"\\\\\" && next === \"\\n\") {\n i++; // line continuation\n } else if (char === \"\\\\\" && next !== undefined) {\n word = (word ?? \"\") + next;\n i++;\n } else if (char === \" \" || char === \"\\t\") {\n if (word !== undefined) words.push(word);\n word = undefined;\n } else if (\";&|<>`\\n\".includes(char) || (char === \"$\" && next === \"(\")) {\n return {\n reason:\n \"run one command at a time — no chaining, pipes, redirects or substitution\",\n };\n } else {\n word = (word ?? \"\") + char;\n }\n }\n\n if (quote) return { reason: \"unterminated quote\" };\n if (word !== undefined) words.push(word);\n return { words };\n};\n\n/**\n * Why the judge may not run `command`, or `undefined` when it may.\n *\n * `runner` is how the project runs cappa (`pnpm exec cappa`); the judge's\n * cappa calls must start with exactly those words.\n */\nexport const judgeCommandRefusal = (\n command: string,\n runner: string,\n): string | undefined => {\n const split = splitCommand(command.trim());\n if (\"reason\" in split) return split.reason;\n\n const { words } = split;\n const prefix = runner.trim().split(/\\s+/);\n const allowed = `only \\`${runner} agent ${CAPPA_ALLOWED.join(\"|\")}\\` and \\`git ${GIT_READ_ONLY.join(\"|\")}\\``;\n\n if (words[0] === \"git\") {\n // Other global options (`-C <dir>`, `-c key=value`) are not needed by\n // the judge, and `-c` could point git at a program to run.\n const sub = words[1] === \"--no-pager\" ? words[2] : words[1];\n if ((GIT_READ_ONLY as readonly string[]).includes(sub ?? \"\")) {\n if (words.some((w) => w === \"--output\" || w.startsWith(\"--output=\"))) {\n return \"`--output` writes a file\";\n }\n return undefined;\n }\n return `the judge may run ${allowed}`;\n }\n\n const isCappa = prefix.every((w, i) => words[i] === w);\n const [agent, sub] = words.slice(prefix.length);\n if (\n isCappa &&\n agent === \"agent\" &&\n (CAPPA_ALLOWED as readonly string[]).includes(sub ?? \"\")\n ) {\n return undefined;\n }\n return `the judge may run ${allowed}`;\n};\n","import { getConfig } from \"@cappa/config\";\nimport {\n type AgentReport,\n clearJudgment,\n collectScreenshots,\n isVerdictLabel,\n runAgentCheck,\n ScreenshotFileSystem,\n toSlimAgentReport,\n VERDICT_LABELS,\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 findProjectRoot,\n installAgentSkills,\n SKILL_STACK_NAMES,\n type SkillStack,\n} from \"../utils/agentSkills\";\nimport { judgeCommandRefusal } from \"../utils/judgeGuard\";\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};\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\") {\n lines.push(`${chalk.bold(entry.name)} ${chalk.dim(entry.category)}`);\n continue;\n }\n if (entry.verdict) {\n const { label, headline } = entry.verdict;\n lines.push(\n `${chalk.bold(entry.name)} ${LABEL_COLORS[label](label)} — ${headline}`,\n );\n } else {\n lines.push(\n `${chalk.bold(entry.name)} ${chalk.yellow(\"awaiting judgment\")} — ${entry.change ?? \"changed\"}`,\n );\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 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 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: VerdictLabel;\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?: VerdictLabel[];\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 verdict\n // about images that have since been re-captured is exactly the mistake\n // to prevent, and a changed screenshot's current verdict is what the\n // regression guard 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 report = await runAgentCheck({\n outputDir: config.outputDir,\n diff: config.diff,\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 again (\\`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 judgeModel?: string;\n};\n\n/**\n * Advice about the config the skill will run against. Read-only: `agent init`\n * installs skill files and never edits `cappa.config.ts`.\n *\n * Without a `webServer` the skill still works, but the agent has to get the\n * app under test running by itself — which is exactly the project-specific\n * guesswork `webServer` exists to remove.\n */\nexport const webServerHints = async (cwd: string): Promise<string[]> => {\n let config: Awaited<ReturnType<typeof getConfig>>;\n try {\n config = await getConfig(undefined, { cwd, command: \"agent\" });\n } catch {\n // No config, or one that does not load: nothing to advise on here.\n return [];\n }\n\n if (config.webServer.length > 0) {\n return [];\n }\n\n return [\n \"cappa.config.ts has no `webServer`, so the agent has to start whatever the plugins point at itself. \" +\n 'Add one and `cappa capture` starts and stops it: webServer: { command: \"pnpm storybook --ci\", url: \"http://localhost:6006\" }',\n ];\n};\n\nexport const agentInit = (options: InitOptions) =>\n run(options, async () => {\n const cwd = process.cwd();\n const root = findProjectRoot(cwd);\n const stacks =\n options.stack === \"all\"\n ? SKILL_STACK_NAMES\n : options.stack\n ? [options.stack]\n : detectSkillStacks(root);\n\n const { runner, judgeModels, files, warnings } = await installAgentSkills({\n cwd,\n root,\n stacks,\n force: options.force,\n runner: options.runner,\n judgeModel: options.judgeModel,\n });\n\n const hints = await webServerHints(cwd);\n\n if (options.json) {\n printJson({ root, stacks, runner, judgeModels, files, warnings, hints });\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 [stack, model] of Object.entries(judgeModels)) {\n logger.log(chalk.dim(`${stack} cappa-judge runs on \\`${model}\\``));\n }\n for (const warning of warnings) {\n logger.warn(warning);\n }\n for (const hint of hints) {\n logger.info(hint);\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 readStdin = async (stream: NodeJS.ReadableStream = process.stdin) => {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\n/**\n * Decide a Claude Code `PreToolUse` hook call for the `cappa-judge`\n * subagent: `undefined` lets the Bash command run, a message blocks it.\n * Anything it cannot read is blocked too — a guard that fails open is no\n * guard.\n */\nexport const judgeGuardVerdict = (\n input: string,\n runner: string,\n): string | undefined => {\n let command: unknown;\n try {\n command = JSON.parse(input)?.tool_input?.command;\n } catch {\n return \"cappa-judge: could not read the hook input\";\n }\n if (typeof command !== \"string\") {\n return \"cappa-judge: could not read the hook input\";\n }\n const refusal = judgeCommandRefusal(command, runner);\n return refusal ? `cappa-judge: ${refusal}` : undefined;\n};\n\nexport const agentGuard = async (options: { runner: string }) => {\n const message = judgeGuardVerdict(await readStdin(), options.runner);\n if (message) {\n process.stderr.write(`${message}\\n`);\n // 2 is the exit code Claude Code reads as \"block this tool call\".\n process.exitCode = 2;\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): VerdictLabel => {\n if (!isVerdictLabel(value)) {\n throw new InvalidArgumentError(\n `label must be one of: ${VERDICT_LABELS.join(\", \")}`,\n );\n }\n return value;\n};\n\nconst collectLabel = (value: string, previous: VerdictLabel[] = []) => [\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: hand every change to a judge, record verdicts, approve\",\n );\n\n agent\n .command(\"check\")\n .description(\n \"Write a judgment request for every changed screenshot and apply verdicts already recorded (does not capture)\",\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>\", VERDICT_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(\n \"--judge-model <model>\",\n \"pin the cappa-judge subagent to a model that can read images: provider/model for OpenCode, an alias or model id for Claude Code (default: the calling model)\",\n )\n .option(\"--json\", \"print a JSON summary to stdout\")\n .action(agentInit);\n\n // Called by the Claude Code judge's PreToolUse hook, not by people.\n agent\n .command(\"guard\", { hidden: true })\n .description(\"Allow or block a cappa-judge Bash call (Claude Code hook)\")\n .requiredOption(\"--runner <command>\", \"how the project runs cappa\")\n .action(agentGuard);\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 { getConfig } from \"@cappa/config\";\nimport {\n removePlaywrightContainers,\n resolveContainerOptions,\n} from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport type { Command } from \"commander\";\n\ntype BrowserDownOptions = { cli?: string };\n\n/**\n * The container CLI to use: `--cli`, else the config's\n * `playwright({ container: { cli } })`, else `CAPPA_CONTAINER_CLI`, else\n * docker. A config that fails to load must not block cleanup.\n */\nconst resolveCli = async (cli: string | undefined): Promise<string> => {\n if (cli) return cli;\n let container: Parameters<typeof resolveContainerOptions>[0];\n try {\n container = (await getConfig()).browser?.provider?.options?.container;\n } catch (error) {\n getLogger().debug(\"Could not load the config:\", error);\n }\n return (\n resolveContainerOptions(container && container !== true ? container : true)\n ?.cli ?? \"docker\"\n );\n};\n\n/** `cappa browser down` — remove every Playwright container cappa started. */\nexport const browserDown = async (options: BrowserDownOptions = {}) => {\n const logger = getLogger();\n const cli = await resolveCli(options.cli);\n const removed = await removePlaywrightContainers({ cli });\n\n if (removed.length === 0) {\n logger.info(\"No Playwright containers to remove.\");\n return;\n }\n for (const name of removed) {\n logger.success(`Removed ${name}`);\n }\n};\n\nexport const registerBrowserCommand = (program: Command) => {\n const browser = program\n .command(\"browser\")\n .description(\n \"Manage the Playwright container (browser.provider container)\",\n );\n\n browser\n .command(\"down\")\n .description(\"Remove every Playwright container cappa started\")\n .option(\"--cli <cli>\", \"container CLI to use (docker, podman, nerdctl)\")\n .action(browserDown);\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 /**\n * Tasks that did not produce a comparable screenshot.\n *\n * Identical errors from one plugin collapse into one entry: `taskId` is the\n * first affected task and `count` how many there were. An unreachable\n * Storybook fails every story the same way, and 300 copies of one sentence\n * bury the fix rather than explain it.\n */\n errors: Array<{\n taskId: string;\n plugin: string;\n error: string;\n count?: number;\n }>;\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\ntype CaptureError = CaptureJsonReport[\"errors\"][number];\n\n/**\n * Fold errors with the same plugin and message into one, keeping the first\n * task and counting the rest. Order follows each message's first occurrence.\n */\nexport const collapseIdenticalErrors = (\n errors: readonly CaptureError[],\n): CaptureError[] => {\n const collapsed = new Map<string, CaptureError>();\n\n for (const error of errors) {\n const key = `${error.plugin}\\u0000${error.error}`;\n const existing = collapsed.get(key);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n } else {\n collapsed.set(key, { ...error });\n }\n }\n\n return [...collapsed.values()];\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 = collapseIdenticalErrors(\n failures.flatMap((failure) => {\n const error = toCaptureError(failure);\n return error ? [error] : [];\n }),\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 { describePixelRatioMismatch, 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 /** Absent means 1. */\n actualPixelRatio?: number;\n expectedPixelRatio?: number;\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 expectedRatio = screenshot.expectedPixelRatio ?? 1;\n const actualRatio = screenshot.actualPixelRatio ?? 1;\n const ratioChanged = expectedRatio !== actualRatio;\n\n const parts: string[] = [];\n if (ratioChanged) {\n parts.push(chalk.yellow(`${expectedRatio}× → ${actualRatio}×`));\n }\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 (ratioChanged) {\n lines.push(\n ` ${chalk.yellow(describePixelRatioMismatch(expectedRatio, actualRatio))}`,\n );\n }\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 http from \"node:http\";\n\nconst IPV4_LOOPBACK = \"127.0.0.1\";\nconst IPV6_LOOPBACK = \"::1\";\n\n/**\n * Binds printed as `localhost`, and the loopback addresses each one leaves\n * uncovered.\n *\n * `localhost` is not one address. Browsers try `::1` and `127.0.0.1` (RFC 6761,\n * happy eyeballs), so a URL saying `localhost:3000` reaches whichever answers\n * first — and if cappa holds only `127.0.0.1:3000` while a dev server holds\n * `[::1]:3000`, the user's click lands in the dev server. The companions are\n * the addresses cappa must also hold for the printed URL to mean cappa.\n *\n * `::` is dual-stack in Node (libuv clears `IPV6_V6ONLY`), so it covers both.\n */\nconst LOCALHOST_BINDS: Record<string, string[]> = {\n localhost: [IPV6_LOOPBACK],\n [IPV4_LOOPBACK]: [IPV6_LOOPBACK],\n [IPV6_LOOPBACK]: [IPV4_LOOPBACK],\n \"[::1]\": [IPV4_LOOPBACK],\n \"0.0.0.0\": [IPV6_LOOPBACK],\n \"::\": [],\n \"[::]\": [],\n};\n\n/** Loopback addresses `localhost` may reach that binding `host` does not. */\nexport const localhostCompanions = (host: string): string[] =>\n LOCALHOST_BINDS[host] ?? [];\n\n/**\n * The host to put in the URL a person is expected to click.\n *\n * `localhost` for every bind it reaches — loopback and wildcards, which no\n * browser will open (`http://0.0.0.0:4801` locked users out of their own UI).\n * Anything else is printed as given, with IPv6 literals bracketed. Note\n * `127.0.0.2` is loopback but is *not* `localhost`, which resolves to\n * `127.0.0.1` only.\n */\nexport const toDisplayHost = (host: string): string => {\n if (host in LOCALHOST_BINDS) {\n return \"localhost\";\n }\n return host.includes(\":\") && !host.startsWith(\"[\") ? `[${host}]` : host;\n};\n\n/**\n * The address to hand to `listen`.\n *\n * `localhost` becomes `127.0.0.1`: Fastify binds every address `localhost`\n * resolves to but silently drops the ones that fail, so a taken `[::1]:port`\n * would go unnoticed — exactly the conflict the companions exist to catch.\n * Brackets are URL syntax, not something `listen` resolves.\n */\nexport const toBindHost = (host: string): string => {\n if (host === \"localhost\") {\n return IPV4_LOOPBACK;\n }\n return host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n};\n\n/**\n * The loopback family does not exist on this machine — IPv6 disabled, say —\n * so nothing can be listening there and there is nothing to hold.\n */\nconst FAMILY_UNAVAILABLE = new Set([\"EAFNOSUPPORT\", \"EADDRNOTAVAIL\"]);\n\n/**\n * Listen on `host:port` and hand every request to `target`.\n *\n * What Fastify does itself for its secondary `localhost` addresses, minus the\n * swallowed errors: `EADDRINUSE` is thrown so the caller can move to another\n * port. Resolves to `null` when the address family is unavailable.\n */\nexport async function bindCompanion(\n target: http.Server,\n host: string,\n port: number,\n): Promise<http.Server | null> {\n const companion = http.createServer((req, res) => {\n target.emit(\"request\", req, res);\n });\n companion.on(\"upgrade\", (...args) => target.emit(\"upgrade\", ...args));\n // Same limits as the server it fronts, so a request behaves the same\n // whichever address it arrived on.\n companion.timeout = target.timeout;\n companion.keepAliveTimeout = target.keepAliveTimeout;\n companion.requestTimeout = target.requestTimeout;\n companion.headersTimeout = target.headersTimeout;\n\n try {\n await new Promise<void>((resolve, reject) => {\n companion.once(\"error\", reject);\n companion.listen({ host, port, ipv6Only: host.includes(\":\") }, () => {\n companion.off(\"error\", reject);\n resolve();\n });\n });\n } catch (error) {\n if (FAMILY_UNAVAILABLE.has((error as NodeJS.ErrnoException).code ?? \"\")) {\n return null;\n }\n throw error;\n }\n\n return companion;\n}\n\n/** Stop a companion and drop its open connections (SSE streams included). */\nexport const closeCompanion = (companion: http.Server) => {\n companion.close(() => {});\n companion.closeAllConnections();\n};\n","import type http from \"node:http\";\nimport path from \"node:path\";\nimport { configToEngineOptions, type ResolvedUserConfig } from \"@cappa/config\";\nimport { LocalEngine } from \"@cappa/core\";\nimport { getLogger } from \"@cappa/logger\";\nimport { createServer } from \"@cappa/server\";\nimport {\n bindCompanion,\n closeCompanion,\n localhostCompanions,\n toBindHost,\n toDisplayHost,\n} from \"./loopback\";\n\nexport { toDisplayHost };\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 /** Fail when `port` is taken instead of moving to the next free one. */\n strictPort?: 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 /** The port actually bound — `port + n` when the requested one was taken. */\n port: number;\n unregisterShutdownHandlers: () => void;\n};\n\n/** How many ports past the requested one to try before giving up. */\nexport const MAX_PORT_ATTEMPTS = 20;\n\ntype Listenable = {\n listen: (options: { port: number; host: string }) => Promise<unknown>;\n addresses?: () => Array<{ port: number }>;\n};\n\n/** No port in the range `listenWithFallback` tried was free. */\nexport class PortInUseError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"PortInUseError\";\n }\n}\n\nconst isAddressInUse = (error: unknown): boolean =>\n (error as { code?: unknown } | null)?.code === \"EADDRINUSE\";\n\n/** A bind that failed with `EADDRINUSE`, and where. */\nclass AddressTaken extends Error {\n constructor(\n readonly host: string,\n readonly error: unknown,\n ) {\n super(`${host} is in use`);\n }\n}\n\nexport type ListenWithFallbackOptions = {\n host: string;\n port: number;\n strictPort?: boolean;\n maxAttempts?: number;\n onPortInUse?: (port: number, host: string) => void;\n /**\n * Further addresses to hold on the same port, each forwarding to `target`.\n * A port counts as free only when all of them are — see `loopback.ts`.\n */\n companions?: { hosts: string[]; target: http.Server };\n};\n\nexport type ListenResult = {\n port: number;\n /** The companion addresses actually held (an absent IPv6 is skipped). */\n companions: string[];\n};\n\n/**\n * Listen on `port`, or the next free port above it.\n *\n * Retries the real `listen` on `EADDRINUSE` rather than probing first (what\n * `get-port`/`detect-port` do): a probe frees the port again before the server\n * binds it, so two cappa processes started together can both \"find\" the same\n * port and one of them still crashes. Binding is the only atomic check.\n *\n * Companions are bound before the server, because a Fastify instance cannot\n * listen again once it has been closed: a companion that turns out to be taken\n * costs nothing to give back, a bound server does.\n *\n * Only `EADDRINUSE` moves on. `EACCES` (a privileged port) or a bad host would\n * fail identically on every port, so they surface as-is.\n *\n * Returns the port actually bound, read back from the server so `port: 0`\n * (OS-assigned) reports the real number too.\n */\nexport async function listenWithFallback(\n server: Listenable,\n options: ListenWithFallbackOptions,\n): Promise<ListenResult> {\n const { host, port, strictPort = false, companions } = options;\n // Port 0 can never be \"in use\", and a strict port gets exactly one try.\n const attempts =\n strictPort || port === 0\n ? 1\n : Math.min(options.maxAttempts ?? MAX_PORT_ATTEMPTS, 65_536 - port);\n\n const companionHosts = companions?.hosts ?? [];\n const bind = async (address: string, candidate: number) => {\n if (!companions) return null;\n try {\n return await bindCompanion(companions.target, address, candidate);\n } catch (error) {\n throw isAddressInUse(error) ? new AddressTaken(address, error) : error;\n }\n };\n\n for (let i = 0; i < attempts; i++) {\n const candidate = port + i;\n const held: Array<{ host: string; server: http.Server }> = [];\n try {\n // With port 0 the number is not known until the server has it.\n if (candidate !== 0) {\n for (const address of companionHosts) {\n const companion = await bind(address, candidate);\n if (companion) held.push({ host: address, server: companion });\n }\n }\n\n try {\n await server.listen({ port: candidate, host });\n } catch (error) {\n throw isAddressInUse(error) ? new AddressTaken(host, error) : error;\n }\n const bound = server.addresses?.()[0]?.port ?? candidate;\n\n if (candidate === 0) {\n // Best effort: an OS-picked port taken on the other loopback is\n // vanishingly unlikely, and the server can no longer move.\n for (const address of companionHosts) {\n const companion = await bind(address, bound).catch(() => null);\n if (companion) held.push({ host: address, server: companion });\n }\n }\n\n if (companions && held.length > 0) {\n companions.target.once(\"close\", () => {\n for (const companion of held) closeCompanion(companion.server);\n });\n }\n\n return { port: bound, companions: held.map((c) => c.host) };\n } catch (error) {\n for (const companion of held) closeCompanion(companion.server);\n\n if (!(error instanceof AddressTaken)) {\n throw error;\n }\n options.onPortInUse?.(candidate, error.host);\n if (i === attempts - 1) {\n const where = attempts === 1 ? error.host : host;\n const tried =\n attempts === 1 ? `Port ${port}` : `Ports ${port}–${candidate}`;\n const fix = strictPort\n ? \"Drop --strict-port to use the next free one, or pass --port <port>.\"\n : \"Pass --port <port> to pick another.\";\n throw new PortInUseError(\n `${tried} on ${where} ${attempts === 1 ? \"is\" : \"are all\"} in use. ${fix}`,\n { cause: error.error },\n );\n }\n }\n }\n\n // Unreachable: the loop either returns or throws on its last attempt.\n throw new Error(`Could not listen on ${host}:${port}.`);\n}\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, strictPort } = 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 let boundPort: number;\n try {\n ({ port: boundPort } = await listenWithFallback(server, {\n host: toBindHost(host),\n port,\n strictPort,\n onPortInUse: (taken, on) =>\n logger.debug(`Port ${taken} is in use on ${on}.`),\n // Hold the other loopback too, or `localhost:<port>` in the printed URL\n // may reach someone else's server instead of this one.\n companions: server.server && {\n hosts: localhostCompanions(host),\n target: server.server,\n },\n }));\n } catch (error) {\n // The engine may already hold a browser and the signal handlers keep the\n // process alive; leave nothing behind for a server that never started.\n unregisterShutdownHandlers();\n await closeQuietly(\"server\", server);\n await closeQuietly(\"engine\", engine);\n throw error;\n }\n\n if (boundPort !== port && port !== 0) {\n logger.warn(`Port ${port} is in use, using ${boundPort} instead.`);\n }\n\n const displayHost = toDisplayHost(host);\n const query = token ? `?token=${token}` : \"\";\n\n return {\n server,\n engine,\n port: boundPort,\n url: `http://${displayHost}:${boundPort}${query}`,\n unregisterShutdownHandlers,\n };\n}\n\n/**\n * `startServer` for a CLI command: a taken port is a one-line error and exit\n * code 1, not a stack trace. Anything else is a bug and keeps its stack.\n */\nexport async function startServerOrExit(\n options: StartServerOptions,\n exitFn: (code: number) => void = process.exit,\n): Promise<RunningServer> {\n try {\n return await startServer(options);\n } catch (error) {\n if (error instanceof PortInUseError) {\n getLogger().error(error.message);\n exitFn(1);\n }\n throw error;\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\nconst errorMessageOf = (error: unknown): string | undefined => {\n if (!error) {\n return undefined;\n }\n if (typeof error === \"string\") {\n return error;\n }\n return error instanceof Error ? error.message : String(error);\n};\n\nexport function 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 // An unreachable app fails every task with the same sentence. Say it once,\n // with the tasks it covers, instead of once per task.\n const byError = new Map<string, TaskFailure[]>();\n for (const failed of failures) {\n const message = errorMessageOf(failed.result.error);\n if (message !== undefined) {\n byError.set(message, [...(byError.get(message) ?? []), failed]);\n }\n }\n\n for (const [message, shared] of byError) {\n if (shared.length < 2) {\n continue;\n }\n const shown = shared.slice(0, 3).map((failed) => failed.taskId);\n const more = shared.length - shown.length;\n lines.push(\n `\\n ${chalk.dim(\"Tasks:\")} ${shown.join(\", \")}${more > 0 ? ` and ${more} more` : \"\"}`,\n );\n lines.push(` ${chalk.red(\"Error:\")} ${message}`);\n }\n\n for (const failed of failures) {\n const errorMsg = errorMessageOf(failed.result.error);\n if (errorMsg !== undefined && (byError.get(errorMsg)?.length ?? 0) > 1) {\n continue;\n }\n\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 (errorMsg !== undefined) {\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, startServerOrExit } from \"../utils/server\";\n\nexport type ReviewOptions = {\n port?: number;\n host?: string;\n readOnly?: boolean;\n token?: string;\n /** Fail when the port is taken instead of moving to the next free one. */\n strictPort?: boolean;\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 startServerOrExit({\n config,\n host,\n port,\n readOnly,\n token,\n strictPort: options.strictPort ?? false,\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, startServerOrExit } from \"../utils/server\";\n\nexport type ServeOptions = {\n port?: number;\n host?: string;\n readOnly?: boolean;\n token?: string;\n /** Fail when the port is taken instead of moving to the next free one. */\n strictPort?: boolean;\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, port: boundPort } = await startServerOrExit({\n config,\n host,\n port,\n readOnly,\n token,\n strictPort: options.strictPort ?? false,\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=${boundPort} 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 { registerBrowserCommand } from \"./commands/browser\";\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(\n \"-p, --port <port>\",\n \"port to listen on (the next free one if it is taken)\",\n (v) => Number.parseInt(v, 10),\n )\n .option(\"--strict-port\", \"exit if the port is taken instead of moving on\")\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(\n \"-p, --port <port>\",\n \"port to listen on (the next free one if it is taken)\",\n (v) => Number.parseInt(v, 10),\n )\n .option(\"--strict-port\", \"exit if the port is taken instead of moving on\")\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\nregisterBrowserCommand(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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACmBA,MAAM,QAAQ;CACZ;CACA;CACA;AACF;;;;;;;;AAkBA,MAAM,aAAa;AAEnB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,MAAM,aAAa,QACjB,MAAM,KAAK,YAAY;CACrB;CACA,QAAQA,UAAAA,QAAK,KAAK,KAAKA,UAAAA,QAAK,SAAS,MAAM,CAAC;AAC9C,EAAE;AAEJ,MAAa,cAAc;CACzB,QAAQ,CACN,GAAG,UAAU,sBAAsB,GACnC;EACE,QAAQ;EACR,QAAQA,UAAAA,QAAK,KAAK,WAAW,UAAU,gBAAgB;EACvD,OAAO;CACT,CACF;CACA,QAAQ,UAAU,sBAAsB;CACxC,UAAU;EACR,GAAG,UAAU,sBAAsB;EACnC,GAAG;GACD;GACA;GACA;EACF,CAAC,CAAC,KACC,UAAuB;GACtB,QAAQ,YAAY;GACpB,QAAQA,UAAAA,QAAK,KAAK,aAAa,IAAI;EACrC,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