@cappa/cli 0.13.3 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -25,18 +25,341 @@ let _cappa_logger = require("@cappa/logger");
25
25
  let commander = require("commander");
26
26
  let _cappa_config = require("@cappa/config");
27
27
  let _cappa_core = require("@cappa/core");
28
- let node_path = require("node:path");
29
- node_path = __toESM(node_path);
30
28
  let chalk = require("chalk");
31
29
  chalk = __toESM(chalk);
30
+ let node_fs = require("node:fs");
31
+ node_fs = __toESM(node_fs);
32
+ let node_fs_promises = require("node:fs/promises");
33
+ node_fs_promises = __toESM(node_fs_promises);
34
+ let node_path = require("node:path");
35
+ node_path = __toESM(node_path);
32
36
  let zod = require("zod");
33
37
  let _cappa_client = require("@cappa/client");
34
38
  let _cappa_server = require("@cappa/server");
35
- let node_fs = require("node:fs");
36
- node_fs = __toESM(node_fs);
37
39
  let node_crypto = require("node:crypto");
38
40
  //#region package.json
39
- var version = "0.13.3";
41
+ var version = "0.15.0";
42
+ //#endregion
43
+ //#region src/utils/agentSkills.ts
44
+ /**
45
+ * Agent integrations `cappa agent init` can install, and the files each one
46
+ * gets.
47
+ *
48
+ * - `claude` — Claude Code: the skill in `.claude/skills/cappa` plus a
49
+ * `cappa-judge` subagent that judges screenshots in its own context.
50
+ * - `agents` — the vendor-neutral Agent Skills directory `.agents/skills`,
51
+ * read by Codex, OpenCode and other agents that adopted it.
52
+ * - `opencode` — OpenCode: the `.agents` skill plus slash commands that run
53
+ * the review flow and a sandboxed `cappa-judge` subagent that judges
54
+ * screenshots in its own context.
55
+ *
56
+ * Sources are relative to the package's `integrations/` directory; targets
57
+ * are relative to the project.
58
+ */
59
+ const SKILL = [
60
+ "skills/cappa/SKILL.md",
61
+ "skills/cappa/JUDGING.md",
62
+ "skills/cappa/MASKING.md"
63
+ ];
64
+ const skillInto = (dir) => SKILL.map((source) => ({
65
+ source,
66
+ target: node_path.default.join(dir, node_path.default.basename(source))
67
+ }));
68
+ const STACK_FILES = {
69
+ claude: [...skillInto(".claude/skills/cappa"), {
70
+ source: "claude/agents/cappa-judge.md",
71
+ target: node_path.default.join(".claude", "agents", "cappa-judge.md")
72
+ }],
73
+ agents: skillInto(".agents/skills/cappa"),
74
+ opencode: [...skillInto(".agents/skills/cappa"), ...[
75
+ "commands/cappa-review.md",
76
+ "commands/cappa-judge.md",
77
+ "commands/cappa-approve.md",
78
+ "agents/cappa-judge.md"
79
+ ].map((file) => ({
80
+ source: `opencode/${file}`,
81
+ target: node_path.default.join(".opencode", file)
82
+ }))]
83
+ };
84
+ const SKILL_STACK_NAMES = Object.keys(STACK_FILES);
85
+ /**
86
+ * Find the integration sources shipped with the package.
87
+ *
88
+ * They live in `integrations/` at the package root, which is one level above
89
+ * `dist/` when installed and two above `src/utils/` in development — so walk
90
+ * up instead of hard-coding either depth.
91
+ */
92
+ const findIntegrationsDir = (from = __dirname) => {
93
+ let current = from;
94
+ while (true) {
95
+ const candidate = node_path.default.join(current, "integrations");
96
+ if (node_fs.default.existsSync(node_path.default.join(candidate, "skills", "cappa", "SKILL.md"))) return candidate;
97
+ const parent = node_path.default.dirname(current);
98
+ if (parent === current) throw new Error("Could not locate the bundled cappa agent skill files");
99
+ current = parent;
100
+ }
101
+ };
102
+ /**
103
+ * Pick the stacks to install when none was named: whichever agents the
104
+ * project already shows signs of, falling back to Claude Code.
105
+ *
106
+ * OpenCode wins over plain `agents` — its stack already includes the
107
+ * `.agents` skill, and adds the commands on top.
108
+ */
109
+ const detectSkillStacks = (cwd) => {
110
+ const has = (entry) => node_fs.default.existsSync(node_path.default.join(cwd, entry));
111
+ const stacks = [];
112
+ if (has(".claude") || has("CLAUDE.md")) stacks.push("claude");
113
+ if (has(".opencode") || has("opencode.json") || has("opencode.jsonc")) stacks.push("opencode");
114
+ else if (has(".agents") || has("AGENTS.md")) stacks.push("agents");
115
+ return stacks.length > 0 ? stacks : ["claude"];
116
+ };
117
+ /**
118
+ * How the project runs its own `cappa` binary, from its lockfile.
119
+ *
120
+ * Written into the installed files because OpenCode commands run shell
121
+ * commands *before* the model sees anything, so a bare `cappa` that is not on
122
+ * `PATH` would inject an error instead of the review state; and agent
123
+ * permission rules match the command text literally.
124
+ */
125
+ const detectCappaRunner = (cwd) => {
126
+ const has = (entry) => node_fs.default.existsSync(node_path.default.join(cwd, entry));
127
+ if (has("pnpm-lock.yaml")) return "pnpm exec cappa";
128
+ if (has("yarn.lock")) return "yarn cappa";
129
+ if (has("bun.lock") || has("bun.lockb")) return "bunx cappa";
130
+ return "npx cappa";
131
+ };
132
+ /** Fill the `{{cappa}}` placeholder in a source file. */
133
+ const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}", runner);
134
+ /**
135
+ * Copy each stack's files into the project.
136
+ *
137
+ * A file that exists with different content is left alone unless `force` is
138
+ * set: users are expected to tailor these to their project, and an upgrade
139
+ * must not silently discard that. A target shared by two stacks (the
140
+ * `.agents` skill) is written once.
141
+ */
142
+ const installAgentSkills = async (options) => {
143
+ const sourceDir = options.sourceDir ?? findIntegrationsDir();
144
+ const runner = options.runner ?? detectCappaRunner(options.cwd);
145
+ const files = [];
146
+ const seen = /* @__PURE__ */ new Set();
147
+ for (const stack of options.stacks) for (const mapping of STACK_FILES[stack]) {
148
+ const target = node_path.default.resolve(options.cwd, mapping.target);
149
+ if (seen.has(target)) continue;
150
+ seen.add(target);
151
+ const source = renderIntegrationFile(await node_fs_promises.default.readFile(node_path.default.join(sourceDir, mapping.source), "utf8"), runner);
152
+ const existing = await node_fs_promises.default.readFile(target, "utf8").catch(() => void 0);
153
+ if (existing === source) {
154
+ files.push({
155
+ stack,
156
+ path: target,
157
+ status: "unchanged"
158
+ });
159
+ continue;
160
+ }
161
+ if (existing !== void 0 && !options.force) {
162
+ files.push({
163
+ stack,
164
+ path: target,
165
+ status: "skipped"
166
+ });
167
+ continue;
168
+ }
169
+ await node_fs_promises.default.mkdir(node_path.default.dirname(target), { recursive: true });
170
+ await node_fs_promises.default.writeFile(target, source, "utf8");
171
+ files.push({
172
+ stack,
173
+ path: target,
174
+ status: "written"
175
+ });
176
+ }
177
+ const warnings = [];
178
+ const claudeSkill = node_fs.default.existsSync(node_path.default.resolve(options.cwd, ".claude/skills/cappa/SKILL.md"));
179
+ if (options.stacks.includes("opencode") && claudeSkill) warnings.push("OpenCode reads .claude/skills too, and uses that copy of the cappa skill over the one in .agents/skills — keep the two in sync if you tailor them.");
180
+ return {
181
+ runner,
182
+ files,
183
+ warnings
184
+ };
185
+ };
186
+ //#endregion
187
+ //#region src/commands/agent.ts
188
+ const printJson = (value) => {
189
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
190
+ };
191
+ /** `CI=true`/`CI=1` — but not `CI=false`, which some tools set explicitly. */
192
+ const isCi = (env = process.env) => {
193
+ const value = env.CI?.trim().toLowerCase();
194
+ return !!value && value !== "false" && value !== "0";
195
+ };
196
+ /**
197
+ * Run `action`, reporting a failure as `{ error }` under `--json` instead of
198
+ * a log line an agent would have to find.
199
+ */
200
+ const run$1 = async (options, action) => {
201
+ try {
202
+ await action();
203
+ } catch (error) {
204
+ const message = error instanceof Error ? error.message : String(error);
205
+ if (options.json) printJson({ error: message });
206
+ else (0, _cappa_logger.getLogger)().error(message);
207
+ process.exitCode = 1;
208
+ }
209
+ };
210
+ const LABEL_COLORS = {
211
+ "regression-likely": chalk.default.red,
212
+ "intentional-likely": chalk.default.green,
213
+ "noise-likely": chalk.default.gray,
214
+ ambiguous: chalk.default.yellow
215
+ };
216
+ /** Human-readable lines for a report — what `--json` prints, for people. */
217
+ const describeAgentReport = (report) => {
218
+ const { totals } = report;
219
+ const lines = [`${totals.passed}/${totals.total} passed · ${totals.changed} changed · ${totals.new} new · ${totals.deleted} deleted`];
220
+ if (totals.pendingJudgments > 0) lines.push(chalk.default.yellow(`${totals.pendingJudgments} awaiting judgment in ${report.outputDir}/.cappa-agent/judgments`));
221
+ for (const entry of report.entries) {
222
+ if (entry.category !== "changed" || !entry.verdict) {
223
+ lines.push(`${chalk.default.bold(entry.name)} ${chalk.default.dim(entry.category)}`);
224
+ continue;
225
+ }
226
+ const { label, headline, source } = entry.verdict;
227
+ const tags = [source === "agent" ? "judged" : void 0, entry.pending ? "pending" : void 0].filter(Boolean);
228
+ lines.push(`${chalk.default.bold(entry.name)} ${LABEL_COLORS[label](label)} — ${headline}${tags.length > 0 ? chalk.default.dim(` (${tags.join(", ")})`) : ""}`);
229
+ if (entry.verdictError) lines.push(chalk.default.red(` verdict.json ignored: ${entry.verdictError}`));
230
+ }
231
+ return lines;
232
+ };
233
+ const agentCheck = (options) => run$1(options, async () => {
234
+ const config = await (0, _cappa_config.getConfig)();
235
+ const report = await (0, _cappa_core.runAgentCheck)({
236
+ outputDir: config.outputDir,
237
+ diff: config.diff,
238
+ judge: options.judge,
239
+ maxTileRegions: options.maxTileRegions
240
+ });
241
+ if (options.json) printJson((0, _cappa_core.toSlimAgentReport)(report));
242
+ else (0, _cappa_logger.getLogger)().box({
243
+ title: "Agent Review",
244
+ message: describeAgentReport(report).join("\n")
245
+ });
246
+ if (report.entries.length > 0) process.exitCode = 1;
247
+ });
248
+ const agentJudge = (names, options) => run$1(options, async () => {
249
+ const config = await (0, _cappa_config.getConfig)();
250
+ const written = [];
251
+ for (const name of names) {
252
+ const verdict = await (0, _cappa_core.writeAgentVerdict)(config.outputDir, name, {
253
+ label: options.label,
254
+ headline: options.headline,
255
+ rationale: options.rationale,
256
+ confidence: options.confidence
257
+ });
258
+ written.push({
259
+ name,
260
+ verdict
261
+ });
262
+ }
263
+ if (options.json) printJson({ written });
264
+ else (0, _cappa_logger.getLogger)().success(`Recorded ${options.label} for ${written.length} screenshot(s) — run \`cappa agent check\` to apply`);
265
+ });
266
+ const agentApprove = (names, options) => run$1(options, async () => {
267
+ if (isCi()) throw new Error("Refusing to approve in CI — baselines are only changed on developer machines.");
268
+ if (names.length === 0 && !options.label?.length) throw new Error("Name the screenshots to approve, or pass --label.");
269
+ const config = await (0, _cappa_config.getConfig)();
270
+ const screenshots = await (0, _cappa_core.collectScreenshots)(config.outputDir);
271
+ const byName = new Map(screenshots.map((s) => [s.name, s]));
272
+ const wanted = new Set(names);
273
+ const unknown = names.filter((name) => {
274
+ const screenshot = byName.get(name);
275
+ return !screenshot || screenshot.category === "passed";
276
+ });
277
+ if (unknown.length > 0) throw new Error(`Nothing to approve for: ${unknown.join(", ")} — names must match exactly (see \`cappa agent check --json\`).`);
278
+ const verdicts = /* @__PURE__ */ new Map();
279
+ if (!!options.label?.length || names.some((name) => byName.get(name)?.category === "changed")) {
280
+ const previous = await (0, _cappa_core.readAgentReport)(config.outputDir);
281
+ const report = await (0, _cappa_core.runAgentCheck)({
282
+ outputDir: config.outputDir,
283
+ diff: config.diff,
284
+ judge: previous?.judge ?? "ambiguous"
285
+ });
286
+ for (const entry of report.entries) if (entry.category === "changed" && entry.verdict) verdicts.set(entry.name, entry.verdict.label);
287
+ }
288
+ const labels = new Set(options.label);
289
+ for (const [name, label] of verdicts) if (labels.has(label)) wanted.add(name);
290
+ const toApprove = [...wanted].flatMap((name) => {
291
+ const screenshot = byName.get(name);
292
+ return screenshot && screenshot.category !== "passed" ? [screenshot] : [];
293
+ });
294
+ const regressions = toApprove.filter((s) => verdicts.get(s.name) === "regression-likely").map((s) => s.name);
295
+ if (regressions.length > 0 && !options.allowRegression) throw new Error(`Refusing to approve regression-likely: ${regressions.join(", ")} — if the change is intended, judge it (\`cappa agent check --judge all\`, then \`cappa agent judge <name> --label intentional-likely\`), or pass --allow-regression.`);
296
+ await new _cappa_core.ScreenshotFileSystem(config.outputDir).approveScreenshots(toApprove, config.diff);
297
+ await Promise.all(toApprove.map((screenshot) => (0, _cappa_core.clearJudgment)(config.outputDir, screenshot.name)));
298
+ const approved = toApprove.map((s) => ({
299
+ name: s.name,
300
+ category: s.category
301
+ }));
302
+ if (options.json) printJson({ approved });
303
+ else if (approved.length === 0) (0, _cappa_logger.getLogger)().warn("No screenshots matched");
304
+ else (0, _cappa_logger.getLogger)().success(`Approved ${approved.length} screenshot(s): ${approved.map((s) => s.name).join(", ")}`);
305
+ });
306
+ const agentInit = (options) => run$1(options, async () => {
307
+ const cwd = process.cwd();
308
+ const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(cwd);
309
+ const { runner, files, warnings } = await installAgentSkills({
310
+ cwd,
311
+ stacks,
312
+ force: options.force,
313
+ runner: options.runner
314
+ });
315
+ if (options.json) {
316
+ printJson({
317
+ stacks,
318
+ runner,
319
+ files,
320
+ warnings
321
+ });
322
+ return;
323
+ }
324
+ const logger = (0, _cappa_logger.getLogger)();
325
+ for (const file of files) {
326
+ const verb = {
327
+ written: chalk.default.green("wrote"),
328
+ unchanged: chalk.default.dim("unchanged"),
329
+ skipped: chalk.default.yellow("skipped (modified — use --force)")
330
+ }[file.status];
331
+ logger.log(`${verb} ${file.path}`);
332
+ }
333
+ logger.log(chalk.default.dim(`commands run as \`${runner}\` (--runner to change)`));
334
+ for (const warning of warnings) logger.warn(warning);
335
+ logger.success(stacks.includes("opencode") ? "Agent integration installed — run /cappa-review in OpenCode, or /cappa in Claude Code" : "Agent skill installed — ask your agent to run a visual review, or use /cappa in Claude Code");
336
+ });
337
+ const parseChoice = (choices, what) => (value) => {
338
+ if (!choices.includes(value)) throw new commander.InvalidArgumentError(`${what} must be one of: ${choices.join(", ")}`);
339
+ return value;
340
+ };
341
+ const parseLabel = (value) => {
342
+ if (!(0, _cappa_core.isJudgedLabel)(value)) throw new commander.InvalidArgumentError(`label must be one of: ${_cappa_core.JUDGED_LABELS.join(", ")}`);
343
+ return value;
344
+ };
345
+ const collectLabel = (value, previous = []) => [...previous, parseLabel(value)];
346
+ const parseConfidence = (value) => {
347
+ const parsed = Number(value);
348
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) throw new commander.InvalidArgumentError("confidence must be a number from 0 to 1");
349
+ return parsed;
350
+ };
351
+ const parsePositiveInt = (value) => {
352
+ const parsed = Number(value);
353
+ if (!Number.isInteger(parsed) || parsed < 1) throw new commander.InvalidArgumentError("must be a positive integer");
354
+ return parsed;
355
+ };
356
+ const registerAgentCommand = (program) => {
357
+ const agent = program.command("agent").description("Visual review for coding agents: label changes, hand ambiguous ones to an agent, approve");
358
+ agent.command("check").description("Label every changed screenshot and write judgment requests for an agent (does not capture)").option("--judge <mode>", `which changes get a judgment request: ${_cappa_core.JUDGE_MODES.join(", ")}`, parseChoice(_cappa_core.JUDGE_MODES, "--judge"), "ambiguous").option("--max-tile-regions <count>", "regions rendered into each regions.png", parsePositiveInt).option("--json", "print a JSON summary to stdout").action(agentCheck);
359
+ agent.command("judge").description("Record a verdict for screenshots with a judgment request").argument("<names...>", "screenshot names, exactly as reported").requiredOption("--label <label>", _cappa_core.JUDGED_LABELS.join(" | "), parseLabel).requiredOption("--headline <text>", "one line describing the change").option("--rationale <text...>", "reasons for the verdict").option("--confidence <number>", "0 to 1", parseConfidence).option("--json", "print a JSON summary to stdout").action(agentJudge);
360
+ agent.command("approve").description("Approve screenshots by exact name or by verdict label (refused in CI)").argument("[names...]", "screenshot names, exactly as reported").option("--label <label>", "also approve every changed screenshot with this verdict label (repeatable)", collectLabel).option("--allow-regression", "approve screenshots whose current verdict is regression-likely").option("--json", "print a JSON summary to stdout").action(agentApprove);
361
+ agent.command("init").description("Install the cappa skill for coding agents in this project").option("--stack <stack>", `${SKILL_STACK_NAMES.join(", ")} or all (default: detected)`, parseChoice([...SKILL_STACK_NAMES, "all"], "--stack")).option("--force", "overwrite skill files that were modified").option("--runner <command>", "how the project runs cappa, e.g. `pnpm exec cappa` (default: from the lockfile)").option("--json", "print a JSON summary to stdout").action(agentInit);
362
+ };
40
363
  //#endregion
41
364
  //#region src/commands/approve.ts
42
365
  const approve = async (options) => {
@@ -73,6 +396,75 @@ const filterScreenshots = (screenshots, filters) => {
73
396
  });
74
397
  };
75
398
  //#endregion
399
+ //#region src/utils/captureReport.ts
400
+ const errorMessage = (error) => {
401
+ if (typeof error === "string") return error;
402
+ if (error instanceof Error) return error.message;
403
+ if (typeof error === "object" && error !== null && typeof error.message === "string") return error.message;
404
+ return String(error);
405
+ };
406
+ /**
407
+ * A task failure that is a broken capture rather than a visual difference.
408
+ *
409
+ * A changed or new screenshot is reported as a failed task too; those are
410
+ * already in `results` with their category, so only the failures that never
411
+ * produced a comparable image belong here.
412
+ */
413
+ const toCaptureError = (failure) => {
414
+ const { result } = failure;
415
+ if (result.error !== void 0 && result.error !== null) return {
416
+ taskId: failure.taskId,
417
+ plugin: failure.pluginName,
418
+ error: errorMessage(result.error)
419
+ };
420
+ if (!result.filepath && result.skipped !== true) return {
421
+ taskId: failure.taskId,
422
+ plugin: failure.pluginName,
423
+ error: "no screenshot was produced"
424
+ };
425
+ };
426
+ const buildCaptureJsonReport = ({ detail, screenshots, durationMs }) => {
427
+ const failures = detail?.failures ?? [];
428
+ const deleted = detail?.deletedScreenshots ?? [];
429
+ const count = (category) => screenshots.filter((s) => s.category === category).length;
430
+ const results = screenshots.filter((s) => s.category !== "passed").map((s) => {
431
+ const origin = s;
432
+ return {
433
+ name: s.name,
434
+ category: s.category,
435
+ ...origin.taskId ? {
436
+ taskId: origin.taskId,
437
+ plugin: origin.plugin
438
+ } : {},
439
+ ...s.diffMeta?.percentDifference !== void 0 ? { percentDifference: s.diffMeta.percentDifference } : {}
440
+ };
441
+ });
442
+ const errors = failures.flatMap((failure) => {
443
+ const error = toCaptureError(failure);
444
+ return error ? [error] : [];
445
+ });
446
+ return {
447
+ ok: failures.length === 0 && deleted.length === 0,
448
+ ...detail ? { runId: detail.id } : {},
449
+ durationMs: Math.round(durationMs),
450
+ tasks: {
451
+ total: detail?.totalTasks ?? 0,
452
+ completed: detail?.completedTasks ?? 0,
453
+ failed: detail?.failedTasks ?? 0
454
+ },
455
+ screenshots: {
456
+ total: screenshots.length,
457
+ passed: count("passed"),
458
+ changed: count("changed"),
459
+ new: count("new"),
460
+ deleted: count("deleted")
461
+ },
462
+ errors,
463
+ results,
464
+ ...results.length > 0 ? { next: "cappa agent check --json" } : {}
465
+ };
466
+ };
467
+ //#endregion
76
468
  //#region src/utils/describeChanges.ts
77
469
  /**
78
470
  * The interpretation fields this reporter actually reads.
@@ -104,23 +496,27 @@ const interpretationSchema = zod.z.object({
104
496
  regions: zod.z.array(regionSchema).catch([]).optional()
105
497
  });
106
498
  const severityColor = (severity) => {
107
- switch (severity) {
108
- case "High": return chalk.default.red;
109
- case "Medium": return chalk.default.yellow;
110
- case "Low": return chalk.default.green;
499
+ switch (severity.toLowerCase()) {
500
+ case "high": return chalk.default.red;
501
+ case "medium": return chalk.default.yellow;
502
+ case "low": return chalk.default.green;
111
503
  default: return chalk.default.gray;
112
504
  }
113
505
  };
114
- /** Human-readable labels for the `changeType` values reported by blazediff. */
506
+ /**
507
+ * Human-readable labels for the `changeType` values reported by blazediff,
508
+ * keyed by their normalised (kebab-case) form so both `color-change` and the
509
+ * older `ColorChange` resolve.
510
+ */
115
511
  const CHANGE_TYPE_LABELS = {
116
- Addition: "added",
117
- Deletion: "removed",
118
- ColorChange: "color",
119
- ContentChange: "content",
120
- Shift: "shifted",
121
- RenderingNoise: "noise"
122
- };
123
- const changeTypeLabel = (changeType) => CHANGE_TYPE_LABELS[changeType] ?? changeType;
512
+ addition: "added",
513
+ deletion: "removed",
514
+ "color-change": "color",
515
+ "content-change": "content",
516
+ shift: "shifted",
517
+ "rendering-noise": "noise"
518
+ };
519
+ const changeTypeLabel = (changeType) => CHANGE_TYPE_LABELS[(0, _cappa_core.normalizeChangeType)(changeType)] ?? changeType;
124
520
  /** `content at center · 0.90% · 360x200 at (420, 300)` */
125
521
  const describeRegion = (region) => {
126
522
  const { bbox } = region;
@@ -633,11 +1029,24 @@ async function renderRunToCompletion(engine, runId, onEvent) {
633
1029
  unsubscribe?.();
634
1030
  }
635
1031
  }
1032
+ /**
1033
+ * Print a JSON document and wait until it is flushed: `process.exit` right
1034
+ * after a plain `write` can cut off output that is still queued for a pipe.
1035
+ */
1036
+ const writeJson = (value) => new Promise((resolve) => {
1037
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`, () => resolve());
1038
+ });
636
1039
  /** How long a `SIGINT` waits for a remote host to acknowledge cancellation. */
637
1040
  const REMOTE_CANCEL_TIMEOUT_MS = 5e3;
638
1041
  const runCapture = async (options = {}) => {
639
1042
  const logger = (0, _cappa_logger.getLogger)();
640
1043
  const captureStart = performance.now();
1044
+ if (options.json && options.watch) {
1045
+ logger.error("--json cannot be combined with --watch: watch never ends.");
1046
+ process.exit(1);
1047
+ return;
1048
+ }
1049
+ if (options.json) logger.level = Math.min(logger.level, 1);
641
1050
  if (options.watch && options.server) {
642
1051
  logger.error("--watch cannot be combined with --server: a remote host cannot see the files on this machine.");
643
1052
  process.exit(1);
@@ -698,7 +1107,7 @@ const runCapture = async (options = {}) => {
698
1107
  try {
699
1108
  run = await engine.startRun({
700
1109
  filter: options.filter,
701
- clearActual: true
1110
+ clearActual: !options.filter
702
1111
  });
703
1112
  } catch (error) {
704
1113
  if (isRunInProgress(error)) {
@@ -715,7 +1124,7 @@ const runCapture = async (options = {}) => {
715
1124
  detail = await engine.getRun(run.id);
716
1125
  const failedDuringRun = detail?.error !== void 0;
717
1126
  const hasFailure = (detail?.failures.length ?? 0) > 0 || (detail?.deletedScreenshots.length ?? 0) > 0;
718
- if (!failedDuringRun && (isCi || hasFailure)) try {
1127
+ if (!failedDuringRun && (isCi || hasFailure || options.json)) try {
719
1128
  groupedScreenshots = await engine.listScreenshots();
720
1129
  } catch (err) {
721
1130
  logger.warn("Could not collect screenshot results:", err);
@@ -724,11 +1133,32 @@ const runCapture = async (options = {}) => {
724
1133
  unregisterSignalHandlers();
725
1134
  if (!options.watch) await engine.close();
726
1135
  }
727
- if (detail?.error) throw toThrowable(detail.error);
1136
+ if (detail?.error) {
1137
+ if (options.json) {
1138
+ await writeJson({
1139
+ ok: false,
1140
+ runId: detail.id,
1141
+ error: detail.error.message
1142
+ });
1143
+ process.exit(1);
1144
+ return;
1145
+ }
1146
+ throw toThrowable(detail.error);
1147
+ }
728
1148
  const failures = detail?.failures ?? [];
729
1149
  const deletedScreenshots = detail?.deletedScreenshots ?? [];
730
1150
  const hasScreenshotFailure = failures.length > 0 || deletedScreenshots.length > 0;
731
1151
  if (isCi) await executeOnFailCallback(config, groupedScreenshots, { remote });
1152
+ if (options.json) {
1153
+ const report = buildCaptureJsonReport({
1154
+ detail,
1155
+ screenshots: groupedScreenshots,
1156
+ durationMs: performance.now() - captureStart
1157
+ });
1158
+ await writeJson(report);
1159
+ if (!report.ok) process.exit(1);
1160
+ return;
1161
+ }
732
1162
  const duration = formatDuration(performance.now() - captureStart);
733
1163
  if (hasScreenshotFailure) {
734
1164
  const reportMessage = generateFailureReportMessage(failures, deletedScreenshots);
@@ -758,7 +1188,7 @@ const runCapture = async (options = {}) => {
758
1188
  }
759
1189
  };
760
1190
  const registerCaptureCommand = (program) => {
761
- program.command("capture").description("Capture screenshots").option("--ci", "run capture in CI mode and execute onFail callback").option("-f, --filter <pattern>", "only capture tasks whose id matches the given glob pattern").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).option("--server <url>", "capture against a `cappa serve` host instead of a local browser").option("--token <token>", "access token for --server (falls back to CAPPA_TOKEN)").option("-w, --watch", "capture once, then re-capture affected tasks whenever files change").action(async (options) => {
1191
+ program.command("capture").description("Capture screenshots").option("--ci", "run capture in CI mode and execute onFail callback").option("--json", "print a JSON summary to stdout instead of progress and reports").option("-f, --filter <pattern>", "only capture tasks whose id matches the given glob pattern").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).option("--server <url>", "capture against a `cappa serve` host instead of a local browser").option("--token <token>", "access token for --server (falls back to CAPPA_TOKEN)").option("-w, --watch", "capture once, then re-capture affected tasks whenever files change").action(async (options) => {
762
1192
  await runCapture(options);
763
1193
  });
764
1194
  };
@@ -886,6 +1316,7 @@ program.command("review").description("Open the review and capture UI").option("
886
1316
  program.command("serve").description("Host a capture engine for a remote `cappa capture --server`").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").option("--no-ui", "serve the API only, without the review UI").action(serve);
887
1317
  program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
888
1318
  program.command("status").description("Get status of screenshots").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).action(status);
1319
+ registerAgentCommand(program);
889
1320
  program.command("init").description("Initialize Cappa in the current directory").action(init);
890
1321
  async function run() {
891
1322
  await program.parseAsync();