diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index 440ec1032..e04849c58 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -2,7 +2,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; // Export command functions export { chat } from "./chat.js"; -export { check } from "./check.js"; +export { review } from "./review.js"; export { login } from "./login.js"; export { logout } from "./logout.js"; export { listSessionsCommand } from "./ls.js"; diff --git a/extensions/cli/src/commands/check.ts b/extensions/cli/src/commands/review.ts similarity index 64% rename from extensions/cli/src/commands/check.ts rename to extensions/cli/src/commands/review.ts index da9d4bf59..44f4b0ca9 100644 --- a/extensions/cli/src/commands/check.ts +++ b/extensions/cli/src/commands/review.ts @@ -7,38 +7,38 @@ import { configureConsoleForHeadless } from "../init.js"; import { logger } from "../util/logger.js"; import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; -import type { CheckState } from "./check/CheckProgress.js"; -import { CheckProgress } from "./check/CheckProgress.js"; -import type { WorkerConfig, WorkerResult } from "./check/checkWorker.js"; -import type { DiffContext } from "./check/diffContext.js"; -import { computeDiffContext } from "./check/diffContext.js"; -import type { CheckResult } from "./check/renderReport.js"; -import { renderReport } from "./check/renderReport.js"; -import { resolveChecks } from "./check/resolveChecks.js"; -import { createWorktree, cleanupWorktree } from "./check/worktree.js"; +import type { ReviewState } from "./review/ReviewProgress.js"; +import { ReviewProgress } from "./review/ReviewProgress.js"; +import type { WorkerConfig, WorkerResult } from "./review/reviewWorker.js"; +import type { DiffContext } from "./review/diffContext.js"; +import { computeDiffContext } from "./review/diffContext.js"; +import type { ReviewResult } from "./review/renderReport.js"; +import { renderReport } from "./review/renderReport.js"; +import { resolveReviews } from "./review/resolveReviews.js"; +import { createWorktree, cleanupWorktree } from "./review/worktree.js"; -export interface CheckOptions extends ExtendedCommandOptions { +export interface ReviewOptions extends ExtendedCommandOptions { base?: string; format?: string; fix?: boolean; patch?: boolean; failFast?: boolean; - checkAgents?: string[]; + reviewAgents?: string[]; } /** - * Run a single check in a forked worker process. + * Run a single review in a forked worker process. */ -async function runCheckInWorker( +async function runReviewInWorker( agentSource: string, worktreePath: string, diffContext: DiffContext, - options: CheckOptions, + options: ReviewOptions, ): Promise { return new Promise((resolve, _reject) => { // Fork the current CLI entry point with the internal worker flag const workerPath = process.argv[1]; - const child = fork(workerPath, ["--internal-check-worker"], { + const child = fork(workerPath, ["--internal-review-worker"], { stdio: ["pipe", "pipe", "pipe", "ipc"], env: { ...process.env, @@ -58,7 +58,7 @@ async function runCheckInWorker( patch: "", agentOutput: "", duration: 0, - error: "Check timed out after 5 minutes", + error: "Review timed out after 5 minutes", }); } }, @@ -79,7 +79,7 @@ async function runCheckInWorker( verbose: options.verbose, }, }; - child.send({ type: "run-check", config }); + child.send({ type: "run-review", config }); } else if (msg.type === "result" && msg.result) { if (!settled) { settled = true; @@ -135,7 +135,7 @@ async function runCheckInWorker( /** * Apply patches to the real working tree (--fix mode). */ -function applyPatches(results: CheckResult[]): void { +function applyPatches(results: ReviewResult[]): void { const patchResults = results.filter( (r) => r.status === "fail" && r.patch.trim(), ); @@ -179,35 +179,37 @@ function applyPatches(results: CheckResult[]): void { } /** - * Mount the Ink live progress UI or fall back to static logs. + * Mutable props bag for the live Ink UI so we can update it progressively. + */ +interface LiveUIProps { + checks: ReviewState[]; + baseBranch?: string; + changedFileCount?: number; + loading?: boolean; +} + +/** + * Mount the Ink live progress UI or return a no-op for non-TTY / special modes. */ async function mountProgressUI( - checkStates: CheckState[], - diffContext: DiffContext, - options: CheckOptions, -): Promise<{ rerender?: () => void; unmount?: () => void }> { + props: LiveUIProps, + options: ReviewOptions, +): Promise<{ rerender: () => void; unmount: () => void }> { const useLiveUI = process.stdout.isTTY && !options.patch && options.format !== "json"; if (!useLiveUI) { - console.log( - chalk.dim( - `Running ${checkStates.length} check${checkStates.length > 1 ? "s" : ""}: ${checkStates.map((c) => c.name).join(", ")}`, - ), - ); - return {}; + return { + rerender: () => {}, + unmount: () => {}, + }; } const { render } = await import("ink"); - const props = { - checks: checkStates, - baseBranch: diffContext.baseBranch, - changedFileCount: diffContext.changedFiles.length, - }; - const instance = render(React.createElement(CheckProgress, props)); + const instance = render(React.createElement(ReviewProgress, props)); return { rerender: () => - instance.rerender(React.createElement(CheckProgress, props)), + instance.rerender(React.createElement(ReviewProgress, props)), unmount: () => instance.unmount(), }; } @@ -216,9 +218,9 @@ async function mountProgressUI( * Output results and exit with appropriate code. */ function outputResultsAndExit( - results: CheckResult[], + results: ReviewResult[], diffContext: DiffContext, - options: CheckOptions, + options: ReviewOptions, checksFromHub: boolean, ): void { const format = options.format === "json" ? "json" : "text"; @@ -254,20 +256,30 @@ function outputResultsAndExit( } /** - * Main check command handler. + * Main review command handler. */ -export async function check(options: CheckOptions = {}): Promise { +export async function review(options: ReviewOptions = {}): Promise { configureConsoleForHeadless(false); if (options.verbose) { logger.setLevel("debug"); } - // Step 1: Check for changes - console.log(chalk.dim("Computing diff...")); + // Mount the live UI immediately with a loading state + const uiProps: LiveUIProps = { + checks: [], + loading: true, + }; + const { rerender, unmount: unmountUI } = await mountProgressUI( + uiProps, + options, + ); + + // Step 1: Compute diff const diffContext = computeDiffContext(options.base); if (!diffContext.diff.trim() && diffContext.changedFiles.length === 0) { + unmountUI(); console.log( chalk.yellow( "No changes detected. Make some changes or specify a different base branch with --base.", @@ -276,64 +288,60 @@ export async function check(options: CheckOptions = {}): Promise { process.exit(0); } - console.log( - chalk.dim( - `Found ${diffContext.changedFiles.length} changed files against ${diffContext.baseBranch}`, - ), - ); + // Update UI with diff info (still loading reviews) + uiProps.baseBranch = diffContext.baseBranch; + uiProps.changedFileCount = diffContext.changedFiles.length; + rerender(); - // Step 2: Resolve checks - console.log(chalk.dim("Resolving checks...")); - const checks = await resolveChecks(options.checkAgents); + // Step 2: Resolve reviews + const reviews = await resolveReviews(options.reviewAgents); - if (checks.length === 0) { + if (reviews.length === 0) { + unmountUI(); console.log( - chalk.yellow("\nNo checks found. To add checks:\n") + + chalk.yellow("\nNo reviews found. To add reviews:\n") + chalk.dim( - " 1. Create .continue/agents/my-check.md with agent instructions\n", + " 1. Create .continue/agents/my-review.md with agent instructions\n", ) + chalk.dim( - " 2. Or specify an agent: cn check --agent org/agent-name\n", + " 2. Or specify an agent: cn review --review-agents org/agent-name\n", ) + - chalk.dim(" 3. Or configure checks on https://continue.dev\n"), + chalk.dim(" 3. Or configure reviews on https://continue.dev\n"), ); process.exit(0); } - const checksFromHub = checks.some((c) => c.sourceType === "hub"); + const checksFromHub = reviews.some((c) => c.sourceType === "hub"); - // Build mutable state for the live UI - const checkStates: CheckState[] = checks.map((c) => ({ + // Build mutable state for the live UI and stop loading + const reviewStates: ReviewState[] = reviews.map((c) => ({ name: c.name, status: "pending" as const, })); + uiProps.checks = reviewStates; + uiProps.loading = false; + rerender(); - const { rerender, unmount: unmountUI } = await mountProgressUI( - checkStates, - diffContext, - options, - ); + // Step 3: Create worktrees and run reviews + const results: ReviewResult[] = []; - // Step 3: Create worktrees and run checks - const results: CheckResult[] = []; - - const runSingleCheck = async ( - resolvedCheck: (typeof checks)[number], + const runSingleReview = async ( + resolvedReview: (typeof reviews)[number], i: number, - ): Promise => { + ): Promise => { const startTime = Date.now(); let worktreePath: string | null = null; try { // Mark as running - checkStates[i].status = "running"; - checkStates[i].startTime = Date.now(); - rerender?.(); + reviewStates[i].status = "running"; + reviewStates[i].startTime = Date.now(); + rerender(); worktreePath = await createWorktree(i); - const workerResult = await runCheckInWorker( - resolvedCheck.source, + const workerResult = await runReviewInWorker( + resolvedReview.source, worktreePath, diffContext, options, @@ -345,31 +353,33 @@ export async function check(options: CheckOptions = {}): Promise { ? ("fail" as const) : ("pass" as const); + const duration = (Date.now() - startTime) / 1000; + // Mark as complete - checkStates[i].status = status; - checkStates[i].duration = workerResult.duration; - rerender?.(); + reviewStates[i].status = status; + reviewStates[i].duration = duration; + rerender(); return { - agent: resolvedCheck.source, - name: resolvedCheck.name, + agent: resolvedReview.source, + name: resolvedReview.name, status, patch: workerResult.patch, output: workerResult.agentOutput, - duration: workerResult.duration, + duration, error: workerResult.error, }; } catch (e: any) { const duration = (Date.now() - startTime) / 1000; // Mark as error - checkStates[i].status = "error"; - checkStates[i].duration = duration; - rerender?.(); + reviewStates[i].status = "error"; + reviewStates[i].duration = duration; + rerender(); return { - agent: resolvedCheck.source, - name: resolvedCheck.name, + agent: resolvedReview.source, + name: resolvedReview.name, status: "error" as const, patch: "", output: "", @@ -384,8 +394,8 @@ export async function check(options: CheckOptions = {}): Promise { }; if (options.failFast) { - for (let i = 0; i < checks.length; i++) { - const result = await runSingleCheck(checks[i], i); + for (let i = 0; i < reviews.length; i++) { + const result = await runSingleReview(reviews[i], i); results.push(result); if (result.status === "fail" || result.status === "error") { break; @@ -393,7 +403,7 @@ export async function check(options: CheckOptions = {}): Promise { } } else { const settled = await Promise.allSettled( - checks.map((resolvedCheck, i) => runSingleCheck(resolvedCheck, i)), + reviews.map((resolvedReview, i) => runSingleReview(resolvedReview, i)), ); for (const result of settled) { if (result.status === "fulfilled") { @@ -402,6 +412,6 @@ export async function check(options: CheckOptions = {}): Promise { } } - unmountUI?.(); + unmountUI(); outputResultsAndExit(results, diffContext, options, checksFromHub); } diff --git a/extensions/cli/src/commands/check/CheckProgress.tsx b/extensions/cli/src/commands/review/ReviewProgress.tsx similarity index 59% rename from extensions/cli/src/commands/check/CheckProgress.tsx rename to extensions/cli/src/commands/review/ReviewProgress.tsx index 023deae83..97af65f8e 100644 --- a/extensions/cli/src/commands/check/CheckProgress.tsx +++ b/extensions/cli/src/commands/review/ReviewProgress.tsx @@ -3,20 +3,21 @@ import React, { useEffect, useState } from "react"; import { LoadingAnimation } from "../../ui/LoadingAnimation.js"; -export interface CheckState { +export interface ReviewState { name: string; status: "pending" | "running" | "pass" | "fail" | "error"; startTime?: number; duration?: number; } -interface CheckProgressProps { - checks: CheckState[]; - baseBranch: string; - changedFileCount: number; +interface ReviewProgressProps { + checks: ReviewState[]; + baseBranch?: string; + changedFileCount?: number; + loading?: boolean; } -function StatusIndicator({ status }: { status: CheckState["status"] }) { +function StatusIndicator({ status }: { status: ReviewState["status"] }) { switch (status) { case "pending": return {"◌ Pending"}; @@ -36,7 +37,7 @@ function StatusIndicator({ status }: { status: CheckState["status"] }) { } } -function ElapsedTime({ check }: { check: CheckState }) { +function ElapsedTime({ check }: { check: ReviewState }) { const [, setTick] = useState(0); useEffect(() => { @@ -62,31 +63,37 @@ function ElapsedTime({ check }: { check: CheckState }) { const COL_NAME = 22; const COL_STATUS = 16; -export const CheckProgress: React.FC = ({ +export const ReviewProgress: React.FC = ({ checks, baseBranch, changedFileCount, + loading, }) => { return ( - cn check - ─ - - {checks.length} check{checks.length === 1 ? "" : "s"} against{" "} - {baseBranch} - - ─ - - {changedFileCount} changed file{changedFileCount === 1 ? "" : "s"} - + cn review + {baseBranch ? ( + <> + ─ + + {checks.length} review{checks.length === 1 ? "" : "s"} against{" "} + {baseBranch} + + ─ + + {changedFileCount} changed file + {changedFileCount === 1 ? "" : "s"} + + + ) : null} - Check + Review @@ -101,17 +108,24 @@ export const CheckProgress: React.FC = ({ {"─".repeat(COL_NAME + COL_STATUS + 6)} - {checks.map((check, i) => ( - - - {check.name} - - - - - + {loading && checks.length === 0 ? ( + + + {" Loading reviews…"} - ))} + ) : ( + checks.map((check, i) => ( + + + {check.name} + + + + + + + )) + )} ); diff --git a/extensions/cli/src/commands/check/diffContext.ts b/extensions/cli/src/commands/review/diffContext.ts similarity index 100% rename from extensions/cli/src/commands/check/diffContext.ts rename to extensions/cli/src/commands/review/diffContext.ts diff --git a/extensions/cli/src/commands/check/renderReport.ts b/extensions/cli/src/commands/review/renderReport.ts similarity index 71% rename from extensions/cli/src/commands/check/renderReport.ts rename to extensions/cli/src/commands/review/renderReport.ts index 2a106f07a..093e7922d 100644 --- a/extensions/cli/src/commands/check/renderReport.ts +++ b/extensions/cli/src/commands/review/renderReport.ts @@ -1,6 +1,6 @@ import chalk from "chalk"; -export interface CheckResult { +export interface ReviewResult { /** Agent slug or local path */ agent: string; /** Display name */ @@ -25,10 +25,10 @@ export interface RenderOptions { } /** - * Render the check results report. + * Render the review results report. */ export function renderReport( - results: CheckResult[], + results: ReviewResult[], options: RenderOptions, ): string { if (options.format === "json") { @@ -38,7 +38,7 @@ export function renderReport( } function renderJsonReport( - results: CheckResult[], + results: ReviewResult[], _options: RenderOptions, ): string { const passed = results.filter((r) => r.status === "pass").length; @@ -47,7 +47,7 @@ function renderJsonReport( return JSON.stringify( { - checks: results.map((r) => ({ + reviews: results.map((r) => ({ agent: r.agent, name: r.name, status: r.status, @@ -69,29 +69,21 @@ function renderJsonReport( } function renderTextReport( - results: CheckResult[], + results: ReviewResult[], options: RenderOptions, ): string { const isTTY = process.stdout.isTTY; const lines: string[] = []; - lines.push(isTTY ? chalk.bold("# Check Results") : "# Check Results"); - lines.push(""); - lines.push( - `Checked against \`${options.baseBranch}...HEAD\` (${options.changedFileCount} files changed)`, + const failedResults = results.filter( + (r) => r.status === "fail" || r.status === "error", ); - lines.push(""); - for (const result of results) { + // Only output details for failures/errors — passes are already in the table + for (const result of failedResults) { const durationStr = `(${result.duration.toFixed(1)}s)`; - if (result.status === "pass") { - const header = isTTY - ? chalk.green(`## ✓ ${result.name}`) + " " + chalk.dim(durationStr) - : `## ✓ ${result.name} ${durationStr}`; - lines.push(header); - lines.push("No issues found."); - } else if (result.status === "error") { + if (result.status === "error") { const header = isTTY ? chalk.red(`## ✗ ${result.name}`) + " " + chalk.dim(durationStr) : `## ✗ ${result.name} ${durationStr}`; @@ -120,28 +112,19 @@ function renderTextReport( lines.push(""); } - // Summary - lines.push("---"); - const failed = results.filter( - (r) => r.status === "fail" || r.status === "error", - ).length; - const total = results.length; - - if (failed === 0) { - const summary = `**All ${total} checks passed.**`; - lines.push(isTTY ? chalk.green(summary) : summary); - } else { - const summary = `**${failed} of ${total} checks failed.**`; + if (failedResults.length > 0) { + lines.push("---"); + const summary = `**${failedResults.length} of ${results.length} reviews failed.**`; lines.push(isTTY ? chalk.red(summary) : summary); + lines.push(""); } // Migration nudge - lines.push(""); if (options.checksFromHub) { lines.push( isTTY - ? chalk.dim("These checks also run on your PRs via Continue CI.") - : "These checks also run on your PRs via Continue CI.", + ? chalk.dim("These reviews also run on your PRs via Continue CI.") + : "These reviews also run on your PRs via Continue CI.", ); } else { lines.push( diff --git a/extensions/cli/src/commands/check/resolveChecks.ts b/extensions/cli/src/commands/review/resolveReviews.ts similarity index 79% rename from extensions/cli/src/commands/check/resolveChecks.ts rename to extensions/cli/src/commands/review/resolveReviews.ts index bb2498c3e..1763b866d 100644 --- a/extensions/cli/src/commands/check/resolveChecks.ts +++ b/extensions/cli/src/commands/review/resolveReviews.ts @@ -6,8 +6,8 @@ import { loadAuthConfig, getAccessToken } from "../../auth/workos.js"; import { env } from "../../env.js"; import { logger } from "../../util/logger.js"; -export interface ResolvedCheck { - /** Display name for the check */ +export interface ResolvedReview { + /** Display name for the review */ name: string; /** Hub slug (org/agent) or local file path */ source: string; @@ -16,14 +16,14 @@ export interface ResolvedCheck { } /** - * Determine which checks to run, using three sources in order: + * Determine which reviews to run, using three sources in order: * 1. CLI --agent flags (highest priority) * 2. Hub API (if logged in and no --agent flags) * 3. Local .continue/agents/*.md (fallback) */ -export async function resolveChecks( +export async function resolveReviews( agentFlags?: string[], -): Promise { +): Promise { // Source 1: CLI --agent flags if (agentFlags && agentFlags.length > 0) { return agentFlags.map((agent) => ({ @@ -34,24 +34,24 @@ export async function resolveChecks( } // Source 2: Hub API (silent failure if not logged in) - const hubChecks = await resolveFromHub(); - if (hubChecks.length > 0) { - return hubChecks; + const hubReviews = await resolveFromHub(); + if (hubReviews.length > 0) { + return hubReviews; } // Source 3: Local .continue/agents/*.md - const localChecks = resolveFromLocal(); - if (localChecks.length > 0) { - return localChecks; + const localReviews = resolveFromLocal(); + if (localReviews.length > 0) { + return localReviews; } return []; } /** - * Try to resolve checks from the hub API based on the current repo. + * Try to resolve reviews from the hub API based on the current repo. */ -async function resolveFromHub(): Promise { +async function resolveFromHub(): Promise { try { const authConfig = loadAuthConfig(); if (!authConfig) { @@ -88,7 +88,7 @@ async function resolveFromHub(): Promise { }); if (!response.ok) { - logger.debug(`Hub check resolution returned ${response.status}`); + logger.debug(`Hub review resolution returned ${response.status}`); return []; } @@ -101,15 +101,15 @@ async function resolveFromHub(): Promise { sourceType: "hub" as const, })); } catch (e) { - logger.debug("Hub check resolution failed", { error: e }); + logger.debug("Hub review resolution failed", { error: e }); return []; } } /** - * Resolve checks from local .continue/agents/*.md files. + * Resolve reviews from local .continue/agents/*.md files. */ -function resolveFromLocal(): ResolvedCheck[] { +function resolveFromLocal(): ResolvedReview[] { const agentsDir = path.join(process.cwd(), ".continue", "agents"); if (!fs.existsSync(agentsDir)) { return []; diff --git a/extensions/cli/src/commands/check/checkWorker.ts b/extensions/cli/src/commands/review/reviewWorker.ts similarity index 72% rename from extensions/cli/src/commands/check/checkWorker.ts rename to extensions/cli/src/commands/review/reviewWorker.ts index 4b5bb1ed2..c16308702 100644 --- a/extensions/cli/src/commands/check/checkWorker.ts +++ b/extensions/cli/src/commands/review/reviewWorker.ts @@ -1,5 +1,5 @@ /** - * Check worker - runs in a forked process. + * Review worker - runs in a forked process. * * Receives configuration via IPC, initializes services, * runs the agent in the worktree, then captures the diff @@ -44,12 +44,18 @@ export interface WorkerResult { } /** - * Build the check prompt that gets prepended to the agent's own instructions. + * Build the review prompt that gets prepended to the agent's own instructions. */ -function buildCheckPrompt(diffContext: DiffContext): string { +function buildReviewPrompt(diffContext: DiffContext): string { const fileList = diffContext.changedFiles.map((f) => `- ${f}`).join("\n"); - let prompt = `You are running as a local code check. Review and fix the following changes. + let prompt = `You are a code review agent. Your job is to review ONLY the changed lines in the diff below and check them against your review rules. + +## Scope — READ THIS CAREFULLY +- You MUST only review the files and lines shown in the diff. +- Do NOT read, scan, or report on files outside the diff. +- Do NOT report pre-existing issues in unchanged code — even in files that appear in the diff, only the changed lines are in scope. +- If you need surrounding context to understand a change, you may read that file, but you must NOT flag issues in the unchanged parts. ## Changes (base: ${diffContext.baseBranch}) ### Changed files @@ -62,15 +68,16 @@ ${diffContext.diff || "(no diff available)"} `; if (diffContext.truncated) { - prompt += `\nNote: The diff was truncated due to size. Use Read and Search tools to inspect the full files.\n`; + prompt += `\nNote: The diff was truncated due to size. You may use Read tool to view the full content of the changed files listed above — but do NOT explore beyond them.\n`; } prompt += ` -## Context +## Rules - You are in a temporary worktree. Dependencies (node_modules, etc.) are not installed. -- Focus on source code analysis and edits. -- Make any edits you think are needed to fix issues. Your changes will be captured as suggestions. -- If there are no issues, simply say so and exit. +- ONLY flag issues that exist in the changed lines of the diff. +- ONLY make edits to files listed in the changed files above, and only to fix violations of your specific review rules in the changed code. +- Do NOT make general improvements, refactoring, documentation changes, or style fixes. +- If there are no violations in the changed code, do NOT edit any files. State that no issues were found and exit. `; return prompt; @@ -91,16 +98,16 @@ function loadLocalAgentInstructions(filePath: string): string { * Entry point for the forked worker process. * Listens for IPC messages from the orchestrator. */ -export async function runCheckWorker(): Promise { +export async function runReviewWorker(): Promise { if (typeof process.send !== "function") { console.error( - "Error: check worker must be run as a forked process (via cn check).", + "Error: review worker must be run as a forked process (via cn review).", ); process.exit(1); } process.on("message", async (msg: { type: string; config: WorkerConfig }) => { - if (msg.type !== "run-check") return; + if (msg.type !== "run-review") return; const { config } = msg; const startTime = Date.now(); @@ -131,8 +138,8 @@ export async function runCheckWorker(): Promise { throw new Error("Failed to initialize model service"); } - // Build the check prompt - const checkPrompt = buildCheckPrompt(config.diffContext); + // Build the review prompt + const reviewPrompt = buildReviewPrompt(config.diffContext); // Load agent-specific instructions if it's a local file let agentInstructions = ""; @@ -151,7 +158,7 @@ export async function runCheckWorker(): Promise { if (agentInstructions) { promptParts.push(`## Agent Instructions\n\n${agentInstructions}`); } - promptParts.push(checkPrompt); + promptParts.push(reviewPrompt); const userMessage = promptParts.join("\n\n"); chatHistorySvc.addUserMessage(userMessage); diff --git a/extensions/cli/src/commands/check/worktree.ts b/extensions/cli/src/commands/review/worktree.ts similarity index 69% rename from extensions/cli/src/commands/check/worktree.ts rename to extensions/cli/src/commands/review/worktree.ts index ff140b536..f312954d2 100644 --- a/extensions/cli/src/commands/check/worktree.ts +++ b/extensions/cli/src/commands/review/worktree.ts @@ -1,31 +1,32 @@ -import { execSync } from "child_process"; +import { exec, execSync } from "child_process"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { promisify } from "util"; import { logger } from "../../util/logger.js"; +const execAsync = promisify(exec); + /** * Create a git worktree that mirrors the user's current working tree state. * The worktree gets committed + staged + unstaged + untracked changes. */ export async function createWorktree(index: number): Promise { const tmpDir = os.tmpdir(); - const worktreePath = path.join(tmpDir, `cn-check-${Date.now()}-${index}`); + const worktreePath = path.join(tmpDir, `cn-review-${Date.now()}-${index}`); // Create the worktree at HEAD (detached) - execSync(`git worktree add "${worktreePath}" HEAD --detach`, { - stdio: ["pipe", "pipe", "pipe"], - }); + await execAsync(`git worktree add "${worktreePath}" HEAD --detach`); // Apply uncommitted changes (staged + unstaged) to the worktree try { - const diff = execSync("git diff HEAD", { - encoding: "utf-8", + const { stdout: diff } = await execAsync("git diff HEAD", { maxBuffer: 10 * 1024 * 1024, - stdio: ["pipe", "pipe", "pipe"], }); if (diff.trim()) { + // execAsync (promisified exec) doesn't support `input`, use execSync for apply. + // This is fine: the apply targets the isolated worktree, so it won't contend. execSync(`git -C "${worktreePath}" apply --allow-empty -`, { input: diff, stdio: ["pipe", "pipe", "pipe"], @@ -39,16 +40,12 @@ export async function createWorktree(index: number): Promise { // Copy untracked files to the worktree try { - const untrackedOutput = execSync( + const { stdout: untrackedOutput } = await execAsync( "git ls-files --others --exclude-standard", - { - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - }, - ).trim(); + ); - if (untrackedOutput) { - const untrackedFiles = untrackedOutput.split("\n"); + if (untrackedOutput.trim()) { + const untrackedFiles = untrackedOutput.trim().split("\n"); const cwd = process.cwd(); for (const file of untrackedFiles) { const srcPath = path.join(cwd, file); @@ -68,6 +65,12 @@ export async function createWorktree(index: number): Promise { logger.debug("Could not copy untracked files to worktree", { error: e }); } + // Commit the initial state so captureWorktreeDiff only captures agent changes + await execAsync(`git -C "${worktreePath}" add -A`); + await execAsync( + `git -C "${worktreePath}" commit -m "cn-review: user working tree state (staged + unstaged + untracked)" --allow-empty --no-verify`, + ); + return worktreePath; } @@ -96,9 +99,7 @@ export function captureWorktreeDiff(worktreePath: string): string { */ export async function cleanupWorktree(worktreePath: string): Promise { try { - execSync(`git worktree remove "${worktreePath}" --force`, { - stdio: ["pipe", "pipe", "pipe"], - }); + await execAsync(`git worktree remove "${worktreePath}" --force`); } catch (e) { logger.debug("Could not remove worktree, attempting manual cleanup", { worktreePath, @@ -107,10 +108,7 @@ export async function cleanupWorktree(worktreePath: string): Promise { // Manual cleanup as fallback try { fs.rmSync(worktreePath, { recursive: true, force: true }); - // Prune the worktree entry - execSync("git worktree prune", { - stdio: ["pipe", "pipe", "pipe"], - }); + await execAsync("git worktree prune"); } catch { // Best effort } diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 0c93a6e5c..83a221f03 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -6,7 +6,7 @@ import "./init.js"; import { Command } from "commander"; import { chat } from "./commands/chat.js"; -import { check } from "./commands/check.js"; +import { review } from "./commands/review.js"; import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; import { listSessionsCommand } from "./commands/ls.js"; @@ -420,20 +420,20 @@ program await remoteTest(prompt, options.url); }); -// Check subcommand +// Review subcommand program - .command("check") - .description("Run AI-powered checks on your changes") + .command("review") + .description("Run AI-powered reviews on your changes") .option("--base ", "Base git ref to diff against (default: auto-detect)") .option("--format ", "Output format") .option("--fix", "Automatically apply suggested fixes") .option("--patch", "Show patches") .option("--fail-fast", "Stop on first failure") - .option("--check-agents ", "Specific check agents to run") + .option("--review-agents ", "Specific review agents to run") .option("--verbose", "Enable verbose logging") .action(async (options) => { - await posthogService.capture("cliCommand", { command: "check" }); - await check(options); + await posthogService.capture("cliCommand", { command: "review" }); + await review(options); }); // Handle unknown commands @@ -444,10 +444,12 @@ program.on("command:*", () => { }); export async function runCli(): Promise { - // Handle internal worker subprocess for cn check - if (process.argv.includes("--internal-check-worker")) { - const { runCheckWorker } = await import("./commands/check/checkWorker.js"); - await runCheckWorker(); + // Handle internal worker subprocess for cn review + if (process.argv.includes("--internal-review-worker")) { + const { runReviewWorker } = await import( + "./commands/review/reviewWorker.js" + ); + await runReviewWorker(); return; }