@cappa/cli 0.15.0 → 0.16.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.mjs CHANGED
@@ -12,7 +12,7 @@ import { ProtocolMismatchError, createClient } from "@cappa/client";
12
12
  import { createServer, isLoopbackHost } from "@cappa/server";
13
13
  import { randomBytes } from "node:crypto";
14
14
  //#region package.json
15
- var version = "0.15.0";
15
+ var version = "0.16.0";
16
16
  //#endregion
17
17
  //#region ../../node_modules/.pnpm/tsdown@0.23.0_@arethetypeswrong+core@0.18.5_oxc-resolver@11.24.2_tsx@4.23.1_typescript@7.0.2/node_modules/tsdown/esm-shims.js
18
18
  const getFilename = () => fileURLToPath(import.meta.url);
@@ -93,6 +93,43 @@ const detectSkillStacks = (cwd) => {
93
93
  else if (has(".agents") || has("AGENTS.md")) stacks.push("agents");
94
94
  return stacks.length > 0 ? stacks : ["claude"];
95
95
  };
96
+ const LOCKFILES = {
97
+ "pnpm-lock.yaml": "pnpm",
98
+ "yarn.lock": "yarn",
99
+ "bun.lock": "bun",
100
+ "bun.lockb": "bun",
101
+ "package-lock.json": "npm"
102
+ };
103
+ const detectPackageManager = (dir) => {
104
+ for (const [lockfile, manager] of Object.entries(LOCKFILES)) if (fs.existsSync(path.join(dir, lockfile))) return manager;
105
+ };
106
+ /**
107
+ * The directory agents work from: the workspace root holding the lockfile.
108
+ *
109
+ * `cappa` is often installed in a single workspace package and run with
110
+ * `pnpm -F <pkg> exec cappa`, which puts `cwd` inside that package — but
111
+ * agents only read `.claude/` and `.agents/` from the root they were started
112
+ * in. Walk up to the nearest lockfile or `pnpm-workspace.yaml`, without
113
+ * leaving the git repository; `cwd` itself when there is neither.
114
+ */
115
+ const findProjectRoot = (cwd) => {
116
+ let current = path.resolve(cwd);
117
+ while (true) {
118
+ const has = (entry) => fs.existsSync(path.join(current, entry));
119
+ if (detectPackageManager(current) || has("pnpm-workspace.yaml")) return current;
120
+ const parent = path.dirname(current);
121
+ if (has(".git") || parent === current) return path.resolve(cwd);
122
+ current = parent;
123
+ }
124
+ };
125
+ const readPackageName = (dir) => {
126
+ try {
127
+ const { name } = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
128
+ return typeof name === "string" ? name : void 0;
129
+ } catch {
130
+ return;
131
+ }
132
+ };
96
133
  /**
97
134
  * How the project runs its own `cappa` binary, from its lockfile.
98
135
  *
@@ -100,18 +137,34 @@ const detectSkillStacks = (cwd) => {
100
137
  * commands *before* the model sees anything, so a bare `cappa` that is not on
101
138
  * `PATH` would inject an error instead of the review state; and agent
102
139
  * permission rules match the command text literally.
140
+ *
141
+ * When `cwd` is a package below `root`, the command switches into it: that is
142
+ * where `cappa` is installed and where `cappa.config.ts` lives, while agents
143
+ * run commands from the root.
103
144
  */
104
- const detectCappaRunner = (cwd) => {
105
- const has = (entry) => fs.existsSync(path.join(cwd, entry));
106
- if (has("pnpm-lock.yaml")) return "pnpm exec cappa";
107
- if (has("yarn.lock")) return "yarn cappa";
108
- if (has("bun.lock") || has("bun.lockb")) return "bunx cappa";
109
- return "npx cappa";
145
+ const detectCappaRunner = (root, cwd = root) => {
146
+ const manager = detectPackageManager(root);
147
+ const dir = path.relative(root, cwd).split(path.sep).join("/");
148
+ if (!dir) return {
149
+ pnpm: "pnpm exec cappa",
150
+ yarn: "yarn cappa",
151
+ bun: "bunx cappa",
152
+ npm: "npx cappa"
153
+ }[manager ?? "npm"];
154
+ switch (manager) {
155
+ case "pnpm": return `pnpm -C ${dir} exec cappa`;
156
+ case "yarn": {
157
+ const name = readPackageName(cwd);
158
+ return name ? `yarn workspace ${name} cappa` : `yarn --cwd ${dir} cappa`;
159
+ }
160
+ case "bun": return `bun --cwd ${dir} x cappa`;
161
+ default: return `npm exec -w ${dir} -- cappa`;
162
+ }
110
163
  };
111
164
  /** Fill the `{{cappa}}` placeholder in a source file. */
112
165
  const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}", runner);
113
166
  /**
114
- * Copy each stack's files into the project.
167
+ * Copy each stack's files into the project root (see `findProjectRoot`).
115
168
  *
116
169
  * A file that exists with different content is left alone unless `force` is
117
170
  * set: users are expected to tailor these to their project, and an upgrade
@@ -120,11 +173,12 @@ const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}",
120
173
  */
121
174
  const installAgentSkills = async (options) => {
122
175
  const sourceDir = options.sourceDir ?? findIntegrationsDir();
123
- const runner = options.runner ?? detectCappaRunner(options.cwd);
176
+ const root = options.root ?? findProjectRoot(options.cwd);
177
+ const runner = options.runner ?? detectCappaRunner(root, options.cwd);
124
178
  const files = [];
125
179
  const seen = /* @__PURE__ */ new Set();
126
180
  for (const stack of options.stacks) for (const mapping of STACK_FILES[stack]) {
127
- const target = path.resolve(options.cwd, mapping.target);
181
+ const target = path.resolve(root, mapping.target);
128
182
  if (seen.has(target)) continue;
129
183
  seen.add(target);
130
184
  const source = renderIntegrationFile(await fsp.readFile(path.join(sourceDir, mapping.source), "utf8"), runner);
@@ -154,9 +208,10 @@ const installAgentSkills = async (options) => {
154
208
  });
155
209
  }
156
210
  const warnings = [];
157
- const claudeSkill = fs.existsSync(path.resolve(options.cwd, ".claude/skills/cappa/SKILL.md"));
211
+ const claudeSkill = fs.existsSync(path.resolve(root, ".claude/skills/cappa/SKILL.md"));
158
212
  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.");
159
213
  return {
214
+ root,
160
215
  runner,
161
216
  files,
162
217
  warnings
@@ -282,21 +337,47 @@ const agentApprove = (names, options) => run$1(options, async () => {
282
337
  else if (approved.length === 0) getLogger().warn("No screenshots matched");
283
338
  else getLogger().success(`Approved ${approved.length} screenshot(s): ${approved.map((s) => s.name).join(", ")}`);
284
339
  });
340
+ /**
341
+ * Advice about the config the skill will run against. Read-only: `agent init`
342
+ * installs skill files and never edits `cappa.config.ts`.
343
+ *
344
+ * Without a `webServer` the skill still works, but the agent has to get the
345
+ * app under test running by itself — which is exactly the project-specific
346
+ * guesswork `webServer` exists to remove.
347
+ */
348
+ const webServerHints = async (cwd) => {
349
+ let config;
350
+ try {
351
+ config = await getConfig(void 0, {
352
+ cwd,
353
+ command: "agent"
354
+ });
355
+ } catch {
356
+ return [];
357
+ }
358
+ if (config.webServer.length > 0) return [];
359
+ return ["cappa.config.ts has no `webServer`, so the agent has to start whatever the plugins point at itself. Add one and `cappa capture` starts and stops it: webServer: { command: \"pnpm storybook --ci\", url: \"http://localhost:6006\" }"];
360
+ };
285
361
  const agentInit = (options) => run$1(options, async () => {
286
362
  const cwd = process.cwd();
287
- const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(cwd);
363
+ const root = findProjectRoot(cwd);
364
+ const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(root);
288
365
  const { runner, files, warnings } = await installAgentSkills({
289
366
  cwd,
367
+ root,
290
368
  stacks,
291
369
  force: options.force,
292
370
  runner: options.runner
293
371
  });
372
+ const hints = await webServerHints(cwd);
294
373
  if (options.json) {
295
374
  printJson({
375
+ root,
296
376
  stacks,
297
377
  runner,
298
378
  files,
299
- warnings
379
+ warnings,
380
+ hints
300
381
  });
301
382
  return;
302
383
  }
@@ -311,6 +392,7 @@ const agentInit = (options) => run$1(options, async () => {
311
392
  }
312
393
  logger.log(chalk.dim(`commands run as \`${runner}\` (--runner to change)`));
313
394
  for (const warning of warnings) logger.warn(warning);
395
+ for (const hint of hints) logger.info(hint);
314
396
  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");
315
397
  });
316
398
  const parseChoice = (choices, what) => (value) => {
@@ -402,6 +484,20 @@ const toCaptureError = (failure) => {
402
484
  error: "no screenshot was produced"
403
485
  };
404
486
  };
487
+ /**
488
+ * Fold errors with the same plugin and message into one, keeping the first
489
+ * task and counting the rest. Order follows each message's first occurrence.
490
+ */
491
+ const collapseIdenticalErrors = (errors) => {
492
+ const collapsed = /* @__PURE__ */ new Map();
493
+ for (const error of errors) {
494
+ const key = `${error.plugin}\u0000${error.error}`;
495
+ const existing = collapsed.get(key);
496
+ if (existing) existing.count = (existing.count ?? 1) + 1;
497
+ else collapsed.set(key, { ...error });
498
+ }
499
+ return [...collapsed.values()];
500
+ };
405
501
  const buildCaptureJsonReport = ({ detail, screenshots, durationMs }) => {
406
502
  const failures = detail?.failures ?? [];
407
503
  const deleted = detail?.deletedScreenshots ?? [];
@@ -418,10 +514,10 @@ const buildCaptureJsonReport = ({ detail, screenshots, durationMs }) => {
418
514
  ...s.diffMeta?.percentDifference !== void 0 ? { percentDifference: s.diffMeta.percentDifference } : {}
419
515
  };
420
516
  });
421
- const errors = failures.flatMap((failure) => {
517
+ const errors = collapseIdenticalErrors(failures.flatMap((failure) => {
422
518
  const error = toCaptureError(failure);
423
519
  return error ? [error] : [];
424
- });
520
+ }));
425
521
  return {
426
522
  ok: failures.length === 0 && deleted.length === 0,
427
523
  ...detail ? { runId: detail.id } : {},
@@ -740,6 +836,11 @@ function formatDuration(ms) {
740
836
  if (minutes > 0) return `${minutes}m ${remainingSeconds}s`;
741
837
  return `${(ms / 1e3).toFixed(2)}s`;
742
838
  }
839
+ const errorMessageOf = (error) => {
840
+ if (!error) return;
841
+ if (typeof error === "string") return error;
842
+ return error instanceof Error ? error.message : String(error);
843
+ };
743
844
  function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
744
845
  const total = failedScreenshots.length + deletedScreenshots.length;
745
846
  if (total === 0) return "";
@@ -753,14 +854,25 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
753
854
  }
754
855
  for (const [pluginName, failures] of byPlugin.entries()) {
755
856
  lines.push(`\n${chalk.bold(`Plugin: ${pluginName}`)}`);
857
+ const byError = /* @__PURE__ */ new Map();
756
858
  for (const failed of failures) {
859
+ const message = errorMessageOf(failed.result.error);
860
+ if (message !== void 0) byError.set(message, [...byError.get(message) ?? [], failed]);
861
+ }
862
+ for (const [message, shared] of byError) {
863
+ if (shared.length < 2) continue;
864
+ const shown = shared.slice(0, 3).map((failed) => failed.taskId);
865
+ const more = shared.length - shown.length;
866
+ lines.push(`\n ${chalk.dim("Tasks:")} ${shown.join(", ")}${more > 0 ? ` and ${more} more` : ""}`);
867
+ lines.push(` ${chalk.red("Error:")} ${message}`);
868
+ }
869
+ for (const failed of failures) {
870
+ const errorMsg = errorMessageOf(failed.result.error);
871
+ if (errorMsg !== void 0 && (byError.get(errorMsg)?.length ?? 0) > 1) continue;
757
872
  lines.push(`\n ${chalk.dim("Task ID:")} ${failed.taskId}`);
758
873
  const result = failed.result;
759
874
  if (result.storyName) lines.push(` ${chalk.dim("Story:")} ${result.storyName}`);
760
- if (result.error) {
761
- const errorMsg = typeof result.error === "string" ? result.error : result.error instanceof Error ? result.error.message : String(result.error);
762
- lines.push(` ${chalk.red("Error:")} ${errorMsg}`);
763
- }
875
+ if (errorMsg !== void 0) lines.push(` ${chalk.red("Error:")} ${errorMsg}`);
764
876
  if (result.success === false) {
765
877
  if (result.isNew) lines.push(` ${chalk.yellow("Status:")} New screenshot (no baseline — run 'cappa approve' to accept)`);
766
878
  else lines.push(` ${chalk.red("Status:")} Failed (comparison failed)`);