@cappa/cli 0.14.0 → 0.15.1

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.14.0";
15
+ var version = "0.15.1";
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);
@@ -24,7 +24,8 @@ const __dirname = /* @__PURE__ */ getDirname();
24
24
  * Agent integrations `cappa agent init` can install, and the files each one
25
25
  * gets.
26
26
  *
27
- * - `claude` — Claude Code: the skill in `.claude/skills/cappa`.
27
+ * - `claude` — Claude Code: the skill in `.claude/skills/cappa` plus a
28
+ * `cappa-judge` subagent that judges screenshots in its own context.
28
29
  * - `agents` — the vendor-neutral Agent Skills directory `.agents/skills`,
29
30
  * read by Codex, OpenCode and other agents that adopted it.
30
31
  * - `opencode` — OpenCode: the `.agents` skill plus slash commands that run
@@ -44,7 +45,10 @@ const skillInto = (dir) => SKILL.map((source) => ({
44
45
  target: path.join(dir, path.basename(source))
45
46
  }));
46
47
  const STACK_FILES = {
47
- claude: skillInto(".claude/skills/cappa"),
48
+ claude: [...skillInto(".claude/skills/cappa"), {
49
+ source: "claude/agents/cappa-judge.md",
50
+ target: path.join(".claude", "agents", "cappa-judge.md")
51
+ }],
48
52
  agents: skillInto(".agents/skills/cappa"),
49
53
  opencode: [...skillInto(".agents/skills/cappa"), ...[
50
54
  "commands/cappa-review.md",
@@ -89,6 +93,43 @@ const detectSkillStacks = (cwd) => {
89
93
  else if (has(".agents") || has("AGENTS.md")) stacks.push("agents");
90
94
  return stacks.length > 0 ? stacks : ["claude"];
91
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
+ };
92
133
  /**
93
134
  * How the project runs its own `cappa` binary, from its lockfile.
94
135
  *
@@ -96,18 +137,34 @@ const detectSkillStacks = (cwd) => {
96
137
  * commands *before* the model sees anything, so a bare `cappa` that is not on
97
138
  * `PATH` would inject an error instead of the review state; and agent
98
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.
99
144
  */
100
- const detectCappaRunner = (cwd) => {
101
- const has = (entry) => fs.existsSync(path.join(cwd, entry));
102
- if (has("pnpm-lock.yaml")) return "pnpm exec cappa";
103
- if (has("yarn.lock")) return "yarn cappa";
104
- if (has("bun.lock") || has("bun.lockb")) return "bunx cappa";
105
- 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
+ }
106
163
  };
107
164
  /** Fill the `{{cappa}}` placeholder in a source file. */
108
165
  const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}", runner);
109
166
  /**
110
- * Copy each stack's files into the project.
167
+ * Copy each stack's files into the project root (see `findProjectRoot`).
111
168
  *
112
169
  * A file that exists with different content is left alone unless `force` is
113
170
  * set: users are expected to tailor these to their project, and an upgrade
@@ -116,11 +173,12 @@ const renderIntegrationFile = (source, runner) => source.replaceAll("{{cappa}}",
116
173
  */
117
174
  const installAgentSkills = async (options) => {
118
175
  const sourceDir = options.sourceDir ?? findIntegrationsDir();
119
- const runner = options.runner ?? detectCappaRunner(options.cwd);
176
+ const root = options.root ?? findProjectRoot(options.cwd);
177
+ const runner = options.runner ?? detectCappaRunner(root, options.cwd);
120
178
  const files = [];
121
179
  const seen = /* @__PURE__ */ new Set();
122
180
  for (const stack of options.stacks) for (const mapping of STACK_FILES[stack]) {
123
- const target = path.resolve(options.cwd, mapping.target);
181
+ const target = path.resolve(root, mapping.target);
124
182
  if (seen.has(target)) continue;
125
183
  seen.add(target);
126
184
  const source = renderIntegrationFile(await fsp.readFile(path.join(sourceDir, mapping.source), "utf8"), runner);
@@ -150,9 +208,10 @@ const installAgentSkills = async (options) => {
150
208
  });
151
209
  }
152
210
  const warnings = [];
153
- 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"));
154
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.");
155
213
  return {
214
+ root,
156
215
  runner,
157
216
  files,
158
217
  warnings
@@ -250,20 +309,24 @@ const agentApprove = (names, options) => run$1(options, async () => {
250
309
  return !screenshot || screenshot.category === "passed";
251
310
  });
252
311
  if (unknown.length > 0) throw new Error(`Nothing to approve for: ${unknown.join(", ")} — names must match exactly (see \`cappa agent check --json\`).`);
253
- if (options.label?.length) {
312
+ const verdicts = /* @__PURE__ */ new Map();
313
+ if (!!options.label?.length || names.some((name) => byName.get(name)?.category === "changed")) {
254
314
  const previous = await readAgentReport(config.outputDir);
255
315
  const report = await runAgentCheck({
256
316
  outputDir: config.outputDir,
257
317
  diff: config.diff,
258
318
  judge: previous?.judge ?? "ambiguous"
259
319
  });
260
- const labels = new Set(options.label);
261
- for (const entry of report.entries) if (entry.category === "changed" && entry.verdict && labels.has(entry.verdict.label)) wanted.add(entry.name);
320
+ for (const entry of report.entries) if (entry.category === "changed" && entry.verdict) verdicts.set(entry.name, entry.verdict.label);
262
321
  }
322
+ const labels = new Set(options.label);
323
+ for (const [name, label] of verdicts) if (labels.has(label)) wanted.add(name);
263
324
  const toApprove = [...wanted].flatMap((name) => {
264
325
  const screenshot = byName.get(name);
265
326
  return screenshot && screenshot.category !== "passed" ? [screenshot] : [];
266
327
  });
328
+ const regressions = toApprove.filter((s) => verdicts.get(s.name) === "regression-likely").map((s) => s.name);
329
+ 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.`);
267
330
  await new ScreenshotFileSystem(config.outputDir).approveScreenshots(toApprove, config.diff);
268
331
  await Promise.all(toApprove.map((screenshot) => clearJudgment(config.outputDir, screenshot.name)));
269
332
  const approved = toApprove.map((s) => ({
@@ -276,15 +339,18 @@ const agentApprove = (names, options) => run$1(options, async () => {
276
339
  });
277
340
  const agentInit = (options) => run$1(options, async () => {
278
341
  const cwd = process.cwd();
279
- const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(cwd);
342
+ const root = findProjectRoot(cwd);
343
+ const stacks = options.stack === "all" ? SKILL_STACK_NAMES : options.stack ? [options.stack] : detectSkillStacks(root);
280
344
  const { runner, files, warnings } = await installAgentSkills({
281
345
  cwd,
346
+ root,
282
347
  stacks,
283
348
  force: options.force,
284
349
  runner: options.runner
285
350
  });
286
351
  if (options.json) {
287
352
  printJson({
353
+ root,
288
354
  stacks,
289
355
  runner,
290
356
  files,
@@ -328,7 +394,7 @@ const registerAgentCommand = (program) => {
328
394
  const agent = program.command("agent").description("Visual review for coding agents: label changes, hand ambiguous ones to an agent, approve");
329
395
  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: ${JUDGE_MODES.join(", ")}`, parseChoice(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);
330
396
  agent.command("judge").description("Record a verdict for screenshots with a judgment request").argument("<names...>", "screenshot names, exactly as reported").requiredOption("--label <label>", 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);
331
- 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);
397
+ 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);
332
398
  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);
333
399
  };
334
400
  //#endregion