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