@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.cjs CHANGED
@@ -38,7 +38,7 @@ let _cappa_client = require("@cappa/client");
38
38
  let _cappa_server = require("@cappa/server");
39
39
  let node_crypto = require("node:crypto");
40
40
  //#region package.json
41
- var version = "0.15.0";
41
+ var version = "0.16.0";
42
42
  //#endregion
43
43
  //#region src/utils/agentSkills.ts
44
44
  /**
@@ -114,6 +114,43 @@ const detectSkillStacks = (cwd) => {
114
114
  else if (has(".agents") || has("AGENTS.md")) stacks.push("agents");
115
115
  return stacks.length > 0 ? stacks : ["claude"];
116
116
  };
117
+ const LOCKFILES = {
118
+ "pnpm-lock.yaml": "pnpm",
119
+ "yarn.lock": "yarn",
120
+ "bun.lock": "bun",
121
+ "bun.lockb": "bun",
122
+ "package-lock.json": "npm"
123
+ };
124
+ const detectPackageManager = (dir) => {
125
+ for (const [lockfile, manager] of Object.entries(LOCKFILES)) if (node_fs.default.existsSync(node_path.default.join(dir, lockfile))) return manager;
126
+ };
127
+ /**
128
+ * The directory agents work from: the workspace root holding the lockfile.
129
+ *
130
+ * `cappa` is often installed in a single workspace package and run with
131
+ * `pnpm -F <pkg> exec cappa`, which puts `cwd` inside that package — but
132
+ * agents only read `.claude/` and `.agents/` from the root they were started
133
+ * in. Walk up to the nearest lockfile or `pnpm-workspace.yaml`, without
134
+ * leaving the git repository; `cwd` itself when there is neither.
135
+ */
136
+ const findProjectRoot = (cwd) => {
137
+ let current = node_path.default.resolve(cwd);
138
+ while (true) {
139
+ const has = (entry) => node_fs.default.existsSync(node_path.default.join(current, entry));
140
+ if (detectPackageManager(current) || has("pnpm-workspace.yaml")) return current;
141
+ const parent = node_path.default.dirname(current);
142
+ if (has(".git") || parent === current) return node_path.default.resolve(cwd);
143
+ current = parent;
144
+ }
145
+ };
146
+ const readPackageName = (dir) => {
147
+ try {
148
+ const { name } = JSON.parse(node_fs.default.readFileSync(node_path.default.join(dir, "package.json"), "utf8"));
149
+ return typeof name === "string" ? name : void 0;
150
+ } catch {
151
+ return;
152
+ }
153
+ };
117
154
  /**
118
155
  * How the project runs its own `cappa` binary, from its lockfile.
119
156
  *
@@ -121,18 +158,34 @@ const detectSkillStacks = (cwd) => {
121
158
  * commands *before* the model sees anything, so a bare `cappa` that is not on
122
159
  * `PATH` would inject an error instead of the review state; and agent
123
160
  * permission rules match the command text literally.
161
+ *
162
+ * When `cwd` is a package below `root`, the command switches into it: that is
163
+ * where `cappa` is installed and where `cappa.config.ts` lives, while agents
164
+ * run commands from the root.
124
165
  */
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";
166
+ const detectCappaRunner = (root, cwd = root) => {
167
+ const manager = detectPackageManager(root);
168
+ const dir = node_path.default.relative(root, cwd).split(node_path.default.sep).join("/");
169
+ if (!dir) return {
170
+ pnpm: "pnpm exec cappa",
171
+ yarn: "yarn cappa",
172
+ bun: "bunx cappa",
173
+ npm: "npx cappa"
174
+ }[manager ?? "npm"];
175
+ switch (manager) {
176
+ case "pnpm": return `pnpm -C ${dir} exec cappa`;
177
+ case "yarn": {
178
+ const name = readPackageName(cwd);
179
+ return name ? `yarn workspace ${name} cappa` : `yarn --cwd ${dir} cappa`;
180
+ }
181
+ case "bun": return `bun --cwd ${dir} x cappa`;
182
+ default: return `npm exec -w ${dir} -- cappa`;
183
+ }
131
184
  };
132
185
  /** Fill the `{{cappa}}` placeholder in a source file. */
133
186
  const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}", runner);
134
187
  /**
135
- * Copy each stack's files into the project.
188
+ * Copy each stack's files into the project root (see `findProjectRoot`).
136
189
  *
137
190
  * A file that exists with different content is left alone unless `force` is
138
191
  * set: users are expected to tailor these to their project, and an upgrade
@@ -141,11 +194,12 @@ const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}",
141
194
  */
142
195
  const installAgentSkills = async (options) => {
143
196
  const sourceDir = options.sourceDir ?? findIntegrationsDir();
144
- const runner = options.runner ?? detectCappaRunner(options.cwd);
197
+ const root = options.root ?? findProjectRoot(options.cwd);
198
+ const runner = options.runner ?? detectCappaRunner(root, options.cwd);
145
199
  const files = [];
146
200
  const seen = /* @__PURE__ */ new Set();
147
201
  for (const stack of options.stacks) for (const mapping of STACK_FILES[stack]) {
148
- const target = node_path.default.resolve(options.cwd, mapping.target);
202
+ const target = node_path.default.resolve(root, mapping.target);
149
203
  if (seen.has(target)) continue;
150
204
  seen.add(target);
151
205
  const source = renderIntegrationFile(await node_fs_promises.default.readFile(node_path.default.join(sourceDir, mapping.source), "utf8"), runner);
@@ -175,9 +229,10 @@ const installAgentSkills = async (options) => {
175
229
  });
176
230
  }
177
231
  const warnings = [];
178
- const claudeSkill = node_fs.default.existsSync(node_path.default.resolve(options.cwd, ".claude/skills/cappa/SKILL.md"));
232
+ const claudeSkill = node_fs.default.existsSync(node_path.default.resolve(root, ".claude/skills/cappa/SKILL.md"));
179
233
  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
234
  return {
235
+ root,
181
236
  runner,
182
237
  files,
183
238
  warnings
@@ -303,21 +358,47 @@ const agentApprove = (names, options) => run$1(options, async () => {
303
358
  else if (approved.length === 0) (0, _cappa_logger.getLogger)().warn("No screenshots matched");
304
359
  else (0, _cappa_logger.getLogger)().success(`Approved ${approved.length} screenshot(s): ${approved.map((s) => s.name).join(", ")}`);
305
360
  });
361
+ /**
362
+ * Advice about the config the skill will run against. Read-only: `agent init`
363
+ * installs skill files and never edits `cappa.config.ts`.
364
+ *
365
+ * Without a `webServer` the skill still works, but the agent has to get the
366
+ * app under test running by itself — which is exactly the project-specific
367
+ * guesswork `webServer` exists to remove.
368
+ */
369
+ const webServerHints = async (cwd) => {
370
+ let config;
371
+ try {
372
+ config = await (0, _cappa_config.getConfig)(void 0, {
373
+ cwd,
374
+ command: "agent"
375
+ });
376
+ } catch {
377
+ return [];
378
+ }
379
+ if (config.webServer.length > 0) return [];
380
+ 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\" }"];
381
+ };
306
382
  const agentInit = (options) => run$1(options, async () => {
307
383
  const cwd = process.cwd();
308
- const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(cwd);
384
+ const root = findProjectRoot(cwd);
385
+ const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(root);
309
386
  const { runner, files, warnings } = await installAgentSkills({
310
387
  cwd,
388
+ root,
311
389
  stacks,
312
390
  force: options.force,
313
391
  runner: options.runner
314
392
  });
393
+ const hints = await webServerHints(cwd);
315
394
  if (options.json) {
316
395
  printJson({
396
+ root,
317
397
  stacks,
318
398
  runner,
319
399
  files,
320
- warnings
400
+ warnings,
401
+ hints
321
402
  });
322
403
  return;
323
404
  }
@@ -332,6 +413,7 @@ const agentInit = (options) => run$1(options, async () => {
332
413
  }
333
414
  logger.log(chalk.default.dim(`commands run as \`${runner}\` (--runner to change)`));
334
415
  for (const warning of warnings) logger.warn(warning);
416
+ for (const hint of hints) logger.info(hint);
335
417
  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
418
  });
337
419
  const parseChoice = (choices, what) => (value) => {
@@ -423,6 +505,20 @@ const toCaptureError = (failure) => {
423
505
  error: "no screenshot was produced"
424
506
  };
425
507
  };
508
+ /**
509
+ * Fold errors with the same plugin and message into one, keeping the first
510
+ * task and counting the rest. Order follows each message's first occurrence.
511
+ */
512
+ const collapseIdenticalErrors = (errors) => {
513
+ const collapsed = /* @__PURE__ */ new Map();
514
+ for (const error of errors) {
515
+ const key = `${error.plugin}\u0000${error.error}`;
516
+ const existing = collapsed.get(key);
517
+ if (existing) existing.count = (existing.count ?? 1) + 1;
518
+ else collapsed.set(key, { ...error });
519
+ }
520
+ return [...collapsed.values()];
521
+ };
426
522
  const buildCaptureJsonReport = ({ detail, screenshots, durationMs }) => {
427
523
  const failures = detail?.failures ?? [];
428
524
  const deleted = detail?.deletedScreenshots ?? [];
@@ -439,10 +535,10 @@ const buildCaptureJsonReport = ({ detail, screenshots, durationMs }) => {
439
535
  ...s.diffMeta?.percentDifference !== void 0 ? { percentDifference: s.diffMeta.percentDifference } : {}
440
536
  };
441
537
  });
442
- const errors = failures.flatMap((failure) => {
538
+ const errors = collapseIdenticalErrors(failures.flatMap((failure) => {
443
539
  const error = toCaptureError(failure);
444
540
  return error ? [error] : [];
445
- });
541
+ }));
446
542
  return {
447
543
  ok: failures.length === 0 && deleted.length === 0,
448
544
  ...detail ? { runId: detail.id } : {},
@@ -761,6 +857,11 @@ function formatDuration(ms) {
761
857
  if (minutes > 0) return `${minutes}m ${remainingSeconds}s`;
762
858
  return `${(ms / 1e3).toFixed(2)}s`;
763
859
  }
860
+ const errorMessageOf = (error) => {
861
+ if (!error) return;
862
+ if (typeof error === "string") return error;
863
+ return error instanceof Error ? error.message : String(error);
864
+ };
764
865
  function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
765
866
  const total = failedScreenshots.length + deletedScreenshots.length;
766
867
  if (total === 0) return "";
@@ -774,14 +875,25 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
774
875
  }
775
876
  for (const [pluginName, failures] of byPlugin.entries()) {
776
877
  lines.push(`\n${chalk.default.bold(`Plugin: ${pluginName}`)}`);
878
+ const byError = /* @__PURE__ */ new Map();
777
879
  for (const failed of failures) {
880
+ const message = errorMessageOf(failed.result.error);
881
+ if (message !== void 0) byError.set(message, [...byError.get(message) ?? [], failed]);
882
+ }
883
+ for (const [message, shared] of byError) {
884
+ if (shared.length < 2) continue;
885
+ const shown = shared.slice(0, 3).map((failed) => failed.taskId);
886
+ const more = shared.length - shown.length;
887
+ lines.push(`\n ${chalk.default.dim("Tasks:")} ${shown.join(", ")}${more > 0 ? ` and ${more} more` : ""}`);
888
+ lines.push(` ${chalk.default.red("Error:")} ${message}`);
889
+ }
890
+ for (const failed of failures) {
891
+ const errorMsg = errorMessageOf(failed.result.error);
892
+ if (errorMsg !== void 0 && (byError.get(errorMsg)?.length ?? 0) > 1) continue;
778
893
  lines.push(`\n ${chalk.default.dim("Task ID:")} ${failed.taskId}`);
779
894
  const result = failed.result;
780
895
  if (result.storyName) lines.push(` ${chalk.default.dim("Story:")} ${result.storyName}`);
781
- if (result.error) {
782
- const errorMsg = typeof result.error === "string" ? result.error : result.error instanceof Error ? result.error.message : String(result.error);
783
- lines.push(` ${chalk.default.red("Error:")} ${errorMsg}`);
784
- }
896
+ if (errorMsg !== void 0) lines.push(` ${chalk.default.red("Error:")} ${errorMsg}`);
785
897
  if (result.success === false) {
786
898
  if (result.isNew) lines.push(` ${chalk.default.yellow("Status:")} New screenshot (no baseline — run 'cappa approve' to accept)`);
787
899
  else lines.push(` ${chalk.default.red("Status:")} Failed (comparison failed)`);