From 3491032516cf2fc4e0e686c3f934a13810d6c9d0 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 2 Feb 2026 00:18:04 -0800 Subject: [PATCH 1/3] Add cn-check skill for AI agent code checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a skill (skills.sh format) that teaches agents how to install and use `cn check` — the Continue CLI command for running AI agent checks locally against working tree changes. Co-Authored-By: Claude Opus 4.5 --- skills/cn-check.zip | Bin 0 -> 2735 bytes skills/cn-check/SKILL.md | 200 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+) create mode 100644 skills/cn-check.zip create mode 100644 skills/cn-check/SKILL.md diff --git a/skills/cn-check.zip b/skills/cn-check.zip new file mode 100644 index 0000000000000000000000000000000000000000..b4f30f3ef9ee52b7806c491d1c0ea2eb370ea099 GIT binary patch literal 2735 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 ixD!.md`: + +```markdown +# Security Review + +You are a security reviewer. Examine the code changes for: + +- SQL injection vulnerabilities +- XSS risks in user-facing output +- Hardcoded secrets or credentials +- Insecure use of eval() or similar + +If you find issues, edit the files to fix them. If everything looks good, say so and exit. +``` + +The agent receives: + +- The full diff against the base branch +- A list of changed files +- Access to read/edit files in a temporary worktree + +Any edits the agent makes are captured as a patch and reported as a "fail" with suggested changes. + +## How It Works + +1. **Diff** — Computes `git diff ...HEAD` to find changed files +2. **Resolve** — Discovers which checks to run (Hub, local, or `--agent` flags) +3. **Worktree** — Creates a temporary git worktree per check for isolation +4. **Run** — Forks a worker process per check; the agent runs with full tool access +5. **Capture** — After the agent finishes, captures `git diff` in the worktree as a patch +6. **Report** — Renders results: pass (no changes), fail (patch produced), or error + +Checks run in parallel by default. Use `--fail-fast` for sequential execution that stops on first failure. + +## Output + +### Interactive terminal (TTY) + +A live-updating table shows check progress: + +``` +cn check - 3 checks against main - 5 changed files + +Check Status Time +-------------------------------------------- +Security Review * Running 12s +Code Style Pass 8s +Documentation Pending - +``` + +When complete, a full report prints with pass/fail status, agent output, and suggested patches. + +### JSON output (`--format json`) + +```json +{ + "checks": [ + { + "agent": ".continue/agents/security.md", + "name": "security", + "status": "pass", + "patch": "", + "output": "No security issues found.", + "duration": 8.2 + } + ], + "summary": { + "total": 1, + "passed": 1, + "failed": 0, + "errored": 0 + } +} +``` + +## CLI Reference + +``` +cn check [options] + +Options: + --base Base branch for diff (default: auto-detect) + --format Output format: text or json (default: text) + --fix Apply suggested fixes to working tree + --patch Output unified patch (pipe to git apply) + --fail-fast Stop after first failing check + --agent Agent to run (hub slug or local path, repeatable) + --config Path to config file + --org Organization slug + --verbose Enable debug logging +``` + +## Troubleshooting + +| Problem | Solution | +| ---------------------------- | ------------------------------------------------------------------------------------- | +| "No changes detected" | Make sure you have uncommitted changes or specify `--base` | +| "No checks found" | Create `.continue/agents/*.md` files or run `cn login` for Hub checks | +| Check times out (5 min) | Reduce diff size or split into focused agents | +| "Worker exited with code 1" | Run with `--verbose` to see worker stderr | +| Patch conflicts with `--fix` | Apply patches manually: `cn check --patch > changes.patch && git apply changes.patch` | From 9b9297395696ef9acfcd6237f9cb8e24ab727b82 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 2 Feb 2026 00:27:40 -0800 Subject: [PATCH 2/3] Add `cn check` command with live progress UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the full `cn check` CLI command for running AI agent checks locally against working tree changes. Includes: - check.ts: Main orchestrator — resolves checks, forks workers, mounts live Ink progress UI, renders final report - CheckProgress.tsx: Ink component showing live table with status, braille loading animation, and elapsed timer per check - checkWorker.ts: Forked worker process that runs an agent in an isolated worktree and captures its diff as a patch - diffContext.ts: Computes git diff against base branch - resolveChecks.ts: Discovers checks from Hub API, --agent flags, or local .continue/agents/*.md files - worktree.ts: Creates/cleans up temporary git worktrees - renderReport.ts: Formats results as text or JSON Co-Authored-By: Claude Opus 4.5 --- extensions/cli/src/commands/check.ts | 397 ++++++++++++++++++ .../cli/src/commands/check/CheckProgress.tsx | 118 ++++++ .../cli/src/commands/check/checkWorker.ts | 219 ++++++++++ .../cli/src/commands/check/diffContext.ts | 116 +++++ .../cli/src/commands/check/renderReport.ts | 157 +++++++ .../cli/src/commands/check/resolveChecks.ts | 150 +++++++ extensions/cli/src/commands/check/worktree.ts | 118 ++++++ 7 files changed, 1275 insertions(+) create mode 100644 extensions/cli/src/commands/check.ts create mode 100644 extensions/cli/src/commands/check/CheckProgress.tsx create mode 100644 extensions/cli/src/commands/check/checkWorker.ts create mode 100644 extensions/cli/src/commands/check/diffContext.ts create mode 100644 extensions/cli/src/commands/check/renderReport.ts create mode 100644 extensions/cli/src/commands/check/resolveChecks.ts create mode 100644 extensions/cli/src/commands/check/worktree.ts diff --git a/extensions/cli/src/commands/check.ts b/extensions/cli/src/commands/check.ts new file mode 100644 index 000000000..112f27374 --- /dev/null +++ b/extensions/cli/src/commands/check.ts @@ -0,0 +1,397 @@ +import { execSync, fork } from "child_process"; + +import chalk from "chalk"; +import React from "react"; + +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 { 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 type { WorkerConfig, WorkerResult } from "./check/checkWorker.js"; +import { createWorktree, cleanupWorktree } from "./check/worktree.js"; + +export interface CheckOptions extends ExtendedCommandOptions { + base?: string; + format?: string; + fix?: boolean; + patch?: boolean; + failFast?: boolean; + checkAgents?: string[]; +} + +/** + * Run a single check in a forked worker process. + */ +async function runCheckInWorker( + agentSource: string, + worktreePath: string, + diffContext: DiffContext, + options: CheckOptions, +): 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"], { + stdio: ["pipe", "pipe", "pipe", "ipc"], + env: { + ...process.env, + // Ensure the worker can find its config + NODE_OPTIONS: process.env.NODE_OPTIONS || "", + }, + }); + + let settled = false; + + const timeout = setTimeout( + () => { + if (!settled) { + settled = true; + child.kill("SIGTERM"); + resolve({ + patch: "", + agentOutput: "", + duration: 0, + error: "Check timed out after 5 minutes", + }); + } + }, + 5 * 60 * 1000, + ); // 5 minute timeout + + child.on("message", (msg: { type: string; result?: WorkerResult }) => { + if (msg.type === "ready") { + // Worker is ready, send the config + const config: WorkerConfig = { + agentSource, + worktreePath, + diffContext, + options: { + config: options.config, + org: options.org, + rule: options.rule, + verbose: options.verbose, + }, + }; + child.send({ type: "run-check", config }); + } else if (msg.type === "result" && msg.result) { + if (!settled) { + settled = true; + clearTimeout(timeout); + resolve(msg.result); + } + } + }); + + child.on("error", (err) => { + if (!settled) { + settled = true; + clearTimeout(timeout); + resolve({ + patch: "", + agentOutput: "", + duration: 0, + error: err.message, + }); + } + }); + + child.on("exit", (code) => { + if (!settled) { + settled = true; + clearTimeout(timeout); + if (code !== 0) { + resolve({ + patch: "", + agentOutput: "", + duration: 0, + error: `Worker exited with code ${code}`, + }); + } + } + }); + + // Capture stderr for debugging + if (child.stderr) { + let stderr = ""; + child.stderr.on("data", (data: Buffer) => { + stderr += data.toString(); + }); + child.on("exit", () => { + if (stderr.trim()) { + logger.debug("Worker stderr:", { stderr: stderr.trim() }); + } + }); + } + }); +} + +/** + * Apply patches to the real working tree (--fix mode). + */ +function applyPatches(results: CheckResult[]): void { + const patchResults = results.filter( + (r) => r.status === "fail" && r.patch.trim(), + ); + + if (patchResults.length === 0) { + console.log(chalk.dim("No patches to apply.")); + return; + } + + let applied = 0; + let failed = 0; + + for (const result of patchResults) { + try { + // Dry-run first + execSync("git apply --check -", { + input: result.patch, + stdio: ["pipe", "pipe", "pipe"], + }); + // Actually apply + execSync("git apply -", { + input: result.patch, + stdio: ["pipe", "pipe", "pipe"], + }); + applied++; + console.log(chalk.green(` ✓ Applied patch from ${result.name}`)); + } catch { + failed++; + console.log( + chalk.red( + ` ✗ Could not apply patch from ${result.name} (conflict with working tree)`, + ), + ); + } + } + + console.log( + `\nApplied ${applied}/${patchResults.length} patches.` + + (failed > 0 ? ` ${failed} had conflicts (see above).` : ""), + ); +} + +/** + * Main check command handler. + */ +export async function check(options: CheckOptions = {}): Promise { + configureConsoleForHeadless(false); + + if (options.verbose) { + logger.setLevel("debug"); + } + + // Step 1: Check for changes + console.log(chalk.dim("Computing diff...")); + const diffContext = computeDiffContext(options.base); + + if (!diffContext.diff.trim() && diffContext.changedFiles.length === 0) { + console.log( + chalk.yellow( + "No changes detected. Make some changes or specify a different base branch with --base.", + ), + ); + process.exit(0); + } + + console.log( + chalk.dim( + `Found ${diffContext.changedFiles.length} changed files against ${diffContext.baseBranch}`, + ), + ); + + // Step 2: Resolve checks + console.log(chalk.dim("Resolving checks...")); + const checks = await resolveChecks(options.checkAgents); + + if (checks.length === 0) { + console.log( + chalk.yellow("\nNo checks found. To add checks:\n") + + chalk.dim( + " 1. Create .continue/agents/my-check.md with agent instructions\n", + ) + + chalk.dim( + " 2. Or specify an agent: cn check --agent org/agent-name\n", + ) + + chalk.dim(" 3. Or configure checks on https://hub.continue.dev\n"), + ); + process.exit(0); + } + + const checksFromHub = checks.some((c) => c.sourceType === "hub"); + + // Determine whether to show live Ink UI + const useLiveUI = + process.stdout.isTTY && !options.patch && options.format !== "json"; + + // Build mutable state for the live UI + const checkStates: CheckState[] = checks.map((c) => ({ + name: c.name, + status: "pending" as const, + })); + + // Mount the Ink live progress UI (or fall back to static logs) + let rerender: (() => void) | undefined; + let unmountUI: (() => void) | undefined; + + if (useLiveUI) { + const { render } = await import("ink"); + const instance = render( + React.createElement(CheckProgress, { + checks: checkStates, + baseBranch: diffContext.baseBranch, + changedFileCount: diffContext.changedFiles.length, + }), + ); + rerender = () => + instance.rerender( + React.createElement(CheckProgress, { + checks: checkStates, + baseBranch: diffContext.baseBranch, + changedFileCount: diffContext.changedFiles.length, + }), + ); + unmountUI = () => instance.unmount(); + } else { + console.log( + chalk.dim( + `Running ${checks.length} check${checks.length > 1 ? "s" : ""}: ${checks.map((c) => c.name).join(", ")}`, + ), + ); + } + + // Step 3: Create worktrees and run checks + const results: CheckResult[] = []; + + const runSingleCheck = async ( + resolvedCheck: (typeof checks)[number], + i: number, + ): Promise => { + const startTime = Date.now(); + let worktreePath: string | null = null; + + try { + // Mark as running + checkStates[i].status = "running"; + checkStates[i].startTime = Date.now(); + rerender?.(); + + worktreePath = await createWorktree(i); + + const workerResult = await runCheckInWorker( + resolvedCheck.source, + worktreePath, + diffContext, + options, + ); + + const status = workerResult.error + ? ("error" as const) + : workerResult.patch.trim() + ? ("fail" as const) + : ("pass" as const); + + // Mark as complete + checkStates[i].status = status; + checkStates[i].duration = workerResult.duration; + rerender?.(); + + return { + agent: resolvedCheck.source, + name: resolvedCheck.name, + status, + patch: workerResult.patch, + output: workerResult.agentOutput, + duration: workerResult.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?.(); + + return { + agent: resolvedCheck.source, + name: resolvedCheck.name, + status: "error" as const, + patch: "", + output: "", + duration, + error: e.message || String(e), + }; + } finally { + if (worktreePath) { + await cleanupWorktree(worktreePath); + } + } + }; + + if (options.failFast) { + // Run sequentially, stop on first failure + for (let i = 0; i < checks.length; i++) { + const result = await runSingleCheck(checks[i], i); + results.push(result); + if (result.status === "fail" || result.status === "error") { + break; + } + } + } else { + // Run all checks in parallel + const settled = await Promise.allSettled( + checks.map((resolvedCheck, i) => runSingleCheck(resolvedCheck, i)), + ); + for (const result of settled) { + if (result.status === "fulfilled") { + results.push(result.value); + } + } + } + + // Unmount the live UI before printing the final report + unmountUI?.(); + + // Step 4: Render report + const format = options.format === "json" ? "json" : "text"; + const report = renderReport(results, { + baseBranch: diffContext.baseBranch, + changedFileCount: diffContext.changedFiles.length, + format, + checksFromHub, + }); + + // For --patch mode, output just the patches + if (options.patch) { + const allPatches = results + .filter((r) => r.patch.trim()) + .map((r) => r.patch) + .join("\n"); + process.stdout.write(allPatches); + process.exit( + results.some((r) => r.status === "fail" || r.status === "error") ? 1 : 0, + ); + } + + console.log("\n" + report); + + // Step 5: Apply fixes if --fix + if (options.fix) { + console.log(chalk.dim("\nApplying fixes...")); + applyPatches(results); + } + + // Exit with appropriate code + const hasFailed = results.some( + (r) => r.status === "fail" || r.status === "error", + ); + process.exit(hasFailed ? 1 : 0); +} diff --git a/extensions/cli/src/commands/check/CheckProgress.tsx b/extensions/cli/src/commands/check/CheckProgress.tsx new file mode 100644 index 000000000..9a1cda291 --- /dev/null +++ b/extensions/cli/src/commands/check/CheckProgress.tsx @@ -0,0 +1,118 @@ +import { Box, Text } from "ink"; +import React, { useEffect, useState } from "react"; + +import { LoadingAnimation } from "../../ui/LoadingAnimation.js"; + +export interface CheckState { + name: string; + status: "pending" | "running" | "pass" | "fail" | "error"; + startTime?: number; + duration?: number; +} + +interface CheckProgressProps { + checks: CheckState[]; + baseBranch: string; + changedFileCount: number; +} + +function StatusIndicator({ status }: { status: CheckState["status"] }) { + switch (status) { + case "pending": + return {"◌ Pending"}; + case "running": + return ( + + + {" Running"} + + ); + case "pass": + return {"✓ Pass"}; + case "fail": + return {"✗ Fail"}; + case "error": + return {"✗ Error"}; + } +} + +function ElapsedTime({ check }: { check: CheckState }) { + const [, setTick] = useState(0); + + useEffect(() => { + if (check.status !== "running") return; + const interval = setInterval(() => setTick((t) => t + 1), 1000); + return () => clearInterval(interval); + }, [check.status]); + + if (check.status === "pending") { + return {"–"}; + } + + const seconds = + check.duration != null + ? Math.round(check.duration) + : check.startTime != null + ? Math.round((Date.now() - check.startTime) / 1000) + : 0; + + return {`${seconds}s`}; +} + +const COL_NAME = 22; +const COL_STATUS = 16; + +export const CheckProgress: React.FC = ({ + checks, + baseBranch, + changedFileCount, +}) => { + return ( + + + cn check + ─ + + {checks.length} check{checks.length !== 1 ? "s" : ""} against{" "} + {baseBranch} + + ─ + + {changedFileCount} changed file{changedFileCount !== 1 ? "s" : ""} + + + + + + + + Check + + + + + Status + + + + Time + + + + {"─".repeat(COL_NAME + COL_STATUS + 6)} + + {checks.map((check, i) => ( + + + {check.name} + + + + + + + ))} + + + ); +}; diff --git a/extensions/cli/src/commands/check/checkWorker.ts b/extensions/cli/src/commands/check/checkWorker.ts new file mode 100644 index 000000000..a634a2611 --- /dev/null +++ b/extensions/cli/src/commands/check/checkWorker.ts @@ -0,0 +1,219 @@ +/** + * Check worker - runs in a forked process. + * + * Receives configuration via IPC, initializes services, + * runs the agent in the worktree, then captures the diff + * and sends results back via IPC. + */ + +import * as fs from "fs"; +import type { ChatHistoryItem } from "core/index.js"; + +import { + initializeServices, + getService, + SERVICE_NAMES, +} from "../../services/index.js"; +import type { ModelServiceState } from "../../services/types.js"; +import { streamChatResponse } from "../../stream/streamChatResponse.js"; +import { constructSystemMessage } from "../../systemMessage.js"; + +import type { DiffContext } from "./diffContext.js"; +import type { CheckResult } from "./renderReport.js"; +import { captureWorktreeDiff } from "./worktree.js"; + +export interface WorkerConfig { + /** Hub slug or local file path for the agent */ + agentSource: string; + /** Path to the worktree */ + worktreePath: string; + /** Diff context for the prompt */ + diffContext: DiffContext; + /** CLI options passed through */ + options: { + config?: string; + org?: string; + rule?: string[]; + verbose?: boolean; + }; +} + +export interface WorkerResult { + patch: string; + agentOutput: string; + duration: number; + error?: string; +} + +/** + * Build the check prompt that gets prepended to the agent's own instructions. + */ +function buildCheckPrompt(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. + +## Changes (base: ${diffContext.baseBranch}) +### Changed files +${fileList || "(no files changed)"} + +### Diff +\`\`\`diff +${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 += ` +## Context +- 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. +`; + + return prompt; +} + +/** + * Load the agent's instructions from a local markdown file. + */ +function loadLocalAgentInstructions(filePath: string): string { + try { + return fs.readFileSync(filePath, "utf-8"); + } catch { + return ""; + } +} + +/** + * Entry point for the forked worker process. + * Listens for IPC messages from the orchestrator. + */ +export async function runCheckWorker(): Promise { + if (typeof process.send !== "function") { + console.error( + "Error: check worker must be run as a forked process (via cn check).", + ); + process.exit(1); + } + + process.on("message", async (msg: { type: string; config: WorkerConfig }) => { + if (msg.type !== "run-check") return; + + const { config } = msg; + const startTime = Date.now(); + + try { + // Change working directory to the worktree + process.chdir(config.worktreePath); + + // Initialize services in auto mode (full tool access) + await initializeServices({ + options: { + config: config.options.config, + org: config.options.org, + rule: config.options.rule, + }, + headless: true, + toolPermissionOverrides: { + mode: "auto", + }, + }); + + // Get model service + const modelState = await getService( + SERVICE_NAMES.MODEL, + ); + + if (!modelState.model || !modelState.llmApi) { + throw new Error("Failed to initialize model service"); + } + + // Build system message + const systemMessage = await constructSystemMessage( + "auto", + config.options.rule, + undefined, + true, // headless + ); + + // Build the check prompt + const checkPrompt = buildCheckPrompt(config.diffContext); + + // Load agent-specific instructions if it's a local file + let agentInstructions = ""; + if ( + config.agentSource.endsWith(".md") && + fs.existsSync(config.agentSource) + ) { + agentInstructions = loadLocalAgentInstructions(config.agentSource); + } + + // Construct initial chat history + const chatHistory: ChatHistoryItem[] = []; + + if (systemMessage) { + chatHistory.push({ + message: { role: "user", content: systemMessage }, + contextItems: [], + }); + } + + if (agentInstructions) { + chatHistory.push({ + message: { + role: "user", + content: `## Agent Instructions\n\n${agentInstructions}`, + }, + contextItems: [], + }); + } + + chatHistory.push({ + message: { role: "user", content: checkPrompt }, + contextItems: [], + }); + + // Collect agent text output + let agentOutput = ""; + + // Run the agent + const abortController = new AbortController(); + const response = await streamChatResponse( + chatHistory, + modelState.model, + modelState.llmApi, + abortController, + ); + + agentOutput = response || ""; + + // Capture the diff of changes the agent made + const patch = captureWorktreeDiff(config.worktreePath); + + const result: WorkerResult = { + patch, + agentOutput, + duration: (Date.now() - startTime) / 1000, + }; + + process.send!({ type: "result", result }); + } catch (e: any) { + const result: WorkerResult = { + patch: "", + agentOutput: "", + duration: (Date.now() - startTime) / 1000, + error: e.message || String(e), + }; + + process.send!({ type: "result", result }); + } + }); + + // Signal ready + process.send!({ type: "ready" }); +} diff --git a/extensions/cli/src/commands/check/diffContext.ts b/extensions/cli/src/commands/check/diffContext.ts new file mode 100644 index 000000000..389728950 --- /dev/null +++ b/extensions/cli/src/commands/check/diffContext.ts @@ -0,0 +1,116 @@ +import { execSync } from "child_process"; + +import { logger } from "../../util/logger.js"; + +const MAX_DIFF_SIZE = 50 * 1024; // 50KB + +export interface DiffContext { + baseBranch: string; + diff: string; + changedFiles: string[]; + stat: string; + truncated: boolean; +} + +/** + * Auto-detect the default branch (main/master) for the current repo. + */ +function detectDefaultBranch(): string { + try { + const ref = execSync("git symbolic-ref refs/remotes/origin/HEAD", { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + }).trim(); + // refs/remotes/origin/main -> main + return ref.replace("refs/remotes/origin/", ""); + } catch { + // Fallback: check if main or master exists + try { + execSync("git rev-parse --verify main", { + stdio: ["pipe", "pipe", "pipe"], + }); + return "main"; + } catch { + try { + execSync("git rev-parse --verify master", { + stdio: ["pipe", "pipe", "pipe"], + }); + return "master"; + } catch { + return "main"; // Default fallback + } + } + } +} + +/** + * Compute the diff context for the current working tree against a base branch. + * Includes both committed changes on the branch AND uncommitted changes. + */ +export function computeDiffContext(baseBranch?: string): DiffContext { + const base = baseBranch || detectDefaultBranch(); + + // Get the merge-base to handle diverged branches + let mergeBase: string; + try { + mergeBase = execSync(`git merge-base ${base} HEAD`, { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + }).trim(); + } catch { + logger.warn( + `Could not find merge-base with ${base}, falling back to direct diff`, + ); + mergeBase = base; + } + + // Get diff of committed changes + working tree changes against the base + let diff: string; + let truncated = false; + try { + // Use diff against merge-base to include all branch changes + working tree + diff = execSync(`git diff ${mergeBase}`, { + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, // 10MB buffer + stdio: ["pipe", "pipe", "pipe"], + }); + } catch { + diff = ""; + } + + if (diff.length > MAX_DIFF_SIZE) { + diff = diff.slice(0, MAX_DIFF_SIZE); + truncated = true; + } + + // Get changed file list + let changedFiles: string[] = []; + try { + const fileList = execSync(`git diff --name-only ${mergeBase}`, { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + }).trim(); + changedFiles = fileList ? fileList.split("\n") : []; + } catch { + changedFiles = []; + } + + // Get diff stat + let stat = ""; + try { + stat = execSync(`git diff --stat ${mergeBase}`, { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + }).trim(); + } catch { + stat = ""; + } + + return { + baseBranch: base, + diff, + changedFiles, + stat, + truncated, + }; +} diff --git a/extensions/cli/src/commands/check/renderReport.ts b/extensions/cli/src/commands/check/renderReport.ts new file mode 100644 index 000000000..0265bccfd --- /dev/null +++ b/extensions/cli/src/commands/check/renderReport.ts @@ -0,0 +1,157 @@ +import chalk from "chalk"; + +export interface CheckResult { + /** Agent slug or local path */ + agent: string; + /** Display name */ + name: string; + /** "pass" if no changes suggested, "fail" if changes suggested, "error" if agent errored */ + status: "pass" | "fail" | "error"; + /** Unified diff patch of agent's suggested changes */ + patch: string; + /** Agent's text output (explanation/rationale) */ + output: string; + /** Duration in seconds */ + duration: number; + /** Error message if status is "error" */ + error?: string; +} + +export interface RenderOptions { + baseBranch: string; + changedFileCount: number; + format: "text" | "json"; + checksFromHub: boolean; +} + +/** + * Render the check results report. + */ +export function renderReport( + results: CheckResult[], + options: RenderOptions, +): string { + if (options.format === "json") { + return renderJsonReport(results, options); + } + return renderTextReport(results, options); +} + +function renderJsonReport( + results: CheckResult[], + _options: RenderOptions, +): string { + const passed = results.filter((r) => r.status === "pass").length; + const failed = results.filter((r) => r.status === "fail").length; + const errored = results.filter((r) => r.status === "error").length; + + return JSON.stringify( + { + checks: results.map((r) => ({ + agent: r.agent, + name: r.name, + status: r.status, + patch: r.patch, + output: r.output, + duration: r.duration, + ...(r.error ? { error: r.error } : {}), + })), + summary: { + total: results.length, + passed, + failed, + errored, + }, + }, + null, + 2, + ); +} + +function renderTextReport( + results: CheckResult[], + 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)`, + ); + lines.push(""); + + for (const result of results) { + 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") { + const header = isTTY + ? chalk.red(`## ✗ ${result.name}`) + " " + chalk.dim(durationStr) + : `## ✗ ${result.name} ${durationStr}`; + lines.push(header); + lines.push(`Error: ${result.error || "Unknown error"}`); + } else { + const header = isTTY + ? chalk.red(`## ✗ ${result.name}`) + " " + chalk.dim(durationStr) + : `## ✗ ${result.name} ${durationStr}`; + lines.push(header); + lines.push(""); + + if (result.output.trim()) { + lines.push(result.output.trim()); + lines.push(""); + } + + if (result.patch.trim()) { + lines.push("### Suggested changes:"); + lines.push("```diff"); + lines.push(result.patch.trim()); + lines.push("```"); + } + } + + 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.**`; + lines.push(isTTY ? chalk.red(summary) : summary); + } + + // 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.", + ); + } else { + lines.push( + isTTY + ? chalk.dim( + "Tip: Run these automatically on every PR → https://hub.continue.dev", + ) + : "Tip: Run these automatically on every PR → https://hub.continue.dev", + ); + } + + return lines.join("\n"); +} diff --git a/extensions/cli/src/commands/check/resolveChecks.ts b/extensions/cli/src/commands/check/resolveChecks.ts new file mode 100644 index 000000000..bb2498c3e --- /dev/null +++ b/extensions/cli/src/commands/check/resolveChecks.ts @@ -0,0 +1,150 @@ +import { execSync } from "child_process"; +import * as fs from "fs"; +import * as path from "path"; + +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 */ + name: string; + /** Hub slug (org/agent) or local file path */ + source: string; + /** 'hub' | 'local' */ + sourceType: "hub" | "local"; +} + +/** + * Determine which checks 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( + agentFlags?: string[], +): Promise { + // Source 1: CLI --agent flags + if (agentFlags && agentFlags.length > 0) { + return agentFlags.map((agent) => ({ + name: agentDisplayName(agent), + source: agent, + sourceType: isLocalPath(agent) ? "local" : "hub", + })); + } + + // Source 2: Hub API (silent failure if not logged in) + const hubChecks = await resolveFromHub(); + if (hubChecks.length > 0) { + return hubChecks; + } + + // Source 3: Local .continue/agents/*.md + const localChecks = resolveFromLocal(); + if (localChecks.length > 0) { + return localChecks; + } + + return []; +} + +/** + * Try to resolve checks from the hub API based on the current repo. + */ +async function resolveFromHub(): Promise { + try { + const authConfig = loadAuthConfig(); + if (!authConfig) { + return []; + } + + const accessToken = getAccessToken(authConfig); + if (!accessToken) { + return []; + } + + // Get the repo URL from git + let repoUrl: string; + try { + repoUrl = execSync("git config --get remote.origin.url", { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + }).trim(); + } catch { + return []; + } + + if (!repoUrl) { + return []; + } + + const url = new URL("api/checks/resolve", env.apiBase); + url.searchParams.set("repoUrl", repoUrl); + + const response = await fetch(url.toString(), { + headers: { + Authorization: `Bearer ${accessToken}`, + }, + }); + + if (!response.ok) { + logger.debug(`Hub check resolution returned ${response.status}`); + return []; + } + + const data = (await response.json()) as { + checks: Array<{ slug: string; name: string }>; + }; + return (data.checks || []).map((c) => ({ + name: c.name, + source: c.slug, + sourceType: "hub" as const, + })); + } catch (e) { + logger.debug("Hub check resolution failed", { error: e }); + return []; + } +} + +/** + * Resolve checks from local .continue/agents/*.md files. + */ +function resolveFromLocal(): ResolvedCheck[] { + const agentsDir = path.join(process.cwd(), ".continue", "agents"); + if (!fs.existsSync(agentsDir)) { + return []; + } + + try { + const files = fs.readdirSync(agentsDir).filter((f) => f.endsWith(".md")); + return files.map((file) => ({ + name: path.basename(file, ".md").replace(/[-_]/g, " "), + source: path.join(agentsDir, file), + sourceType: "local" as const, + })); + } catch { + return []; + } +} + +function isLocalPath(agent: string): boolean { + return ( + agent.startsWith(".") || + agent.startsWith("/") || + agent.startsWith("~") || + agent.endsWith(".md") || + agent.endsWith(".yaml") || + agent.endsWith(".yml") || + // Windows absolute path (C:\...) + /^[A-Za-z]:[/\\]/.test(agent) + ); +} + +function agentDisplayName(agent: string): string { + if (isLocalPath(agent)) { + return path.basename(agent, path.extname(agent)).replace(/[-_]/g, " "); + } + // Hub slug: "org/agent-name" -> "agent-name" -> "agent name" + const parts = agent.split("/"); + return (parts[parts.length - 1] || agent).replace(/[-_]/g, " "); +} diff --git a/extensions/cli/src/commands/check/worktree.ts b/extensions/cli/src/commands/check/worktree.ts new file mode 100644 index 000000000..ff140b536 --- /dev/null +++ b/extensions/cli/src/commands/check/worktree.ts @@ -0,0 +1,118 @@ +import { execSync } from "child_process"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { logger } from "../../util/logger.js"; + +/** + * 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}`); + + // Create the worktree at HEAD (detached) + execSync(`git worktree add "${worktreePath}" HEAD --detach`, { + stdio: ["pipe", "pipe", "pipe"], + }); + + // Apply uncommitted changes (staged + unstaged) to the worktree + try { + const diff = execSync("git diff HEAD", { + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, + stdio: ["pipe", "pipe", "pipe"], + }); + if (diff.trim()) { + execSync(`git -C "${worktreePath}" apply --allow-empty -`, { + input: diff, + stdio: ["pipe", "pipe", "pipe"], + }); + } + } catch (e) { + logger.debug("Could not apply uncommitted changes to worktree", { + error: e, + }); + } + + // Copy untracked files to the worktree + try { + const untrackedOutput = execSync( + "git ls-files --others --exclude-standard", + { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + }, + ).trim(); + + if (untrackedOutput) { + const untrackedFiles = untrackedOutput.split("\n"); + const cwd = process.cwd(); + for (const file of untrackedFiles) { + const srcPath = path.join(cwd, file); + const destPath = path.join(worktreePath, file); + const destDir = path.dirname(destPath); + if (!fs.existsSync(destDir)) { + fs.mkdirSync(destDir, { recursive: true }); + } + try { + fs.copyFileSync(srcPath, destPath); + } catch { + // Skip files that can't be copied + } + } + } + } catch (e) { + logger.debug("Could not copy untracked files to worktree", { error: e }); + } + + return worktreePath; +} + +/** + * Capture the diff of changes the agent made in the worktree. + * Returns a unified diff patch string. + */ +export function captureWorktreeDiff(worktreePath: string): string { + try { + // Add all new files so they show up in the diff + execSync(`git -C "${worktreePath}" add -A`, { + stdio: ["pipe", "pipe", "pipe"], + }); + return execSync(`git -C "${worktreePath}" diff --cached`, { + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, + stdio: ["pipe", "pipe", "pipe"], + }); + } catch { + return ""; + } +} + +/** + * Remove a git worktree. + */ +export async function cleanupWorktree(worktreePath: string): Promise { + try { + execSync(`git worktree remove "${worktreePath}" --force`, { + stdio: ["pipe", "pipe", "pipe"], + }); + } catch (e) { + logger.debug("Could not remove worktree, attempting manual cleanup", { + worktreePath, + error: e, + }); + // Manual cleanup as fallback + try { + fs.rmSync(worktreePath, { recursive: true, force: true }); + // Prune the worktree entry + execSync("git worktree prune", { + stdio: ["pipe", "pipe", "pipe"], + }); + } catch { + // Best effort + } + } +} From 6c2dabe7de6ba83f9a458373802e9372013a7608 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 2 Feb 2026 00:38:25 -0800 Subject: [PATCH 3/3] Fix lint errors in cn check command - Reorder imports to satisfy import/order rule - Prefix unused `reject` param with underscore - Extract mountProgressUI and outputResultsAndExit to reduce check() complexity below threshold - Replace != with strict equality and remove negated conditions - Remove unused CheckResult import from checkWorker Co-Authored-By: Claude Opus 4.5 --- extensions/cli/src/commands/check.ts | 156 ++++++++++-------- .../cli/src/commands/check/CheckProgress.tsx | 14 +- .../cli/src/commands/check/checkWorker.ts | 2 +- 3 files changed, 91 insertions(+), 81 deletions(-) diff --git a/extensions/cli/src/commands/check.ts b/extensions/cli/src/commands/check.ts index 112f27374..f29d0443c 100644 --- a/extensions/cli/src/commands/check.ts +++ b/extensions/cli/src/commands/check.ts @@ -9,12 +9,12 @@ 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 type { WorkerConfig, WorkerResult } from "./check/checkWorker.js"; import { createWorktree, cleanupWorktree } from "./check/worktree.js"; export interface CheckOptions extends ExtendedCommandOptions { @@ -35,7 +35,7 @@ async function runCheckInWorker( diffContext: DiffContext, options: CheckOptions, ): Promise { - return new Promise((resolve, reject) => { + 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"], { @@ -178,6 +178,81 @@ function applyPatches(results: CheckResult[]): void { ); } +/** + * Mount the Ink live progress UI or fall back to static logs. + */ +async function mountProgressUI( + checkStates: CheckState[], + diffContext: DiffContext, + options: CheckOptions, +): 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 {}; + } + + const { render } = await import("ink"); + const props = { + checks: checkStates, + baseBranch: diffContext.baseBranch, + changedFileCount: diffContext.changedFiles.length, + }; + const instance = render(React.createElement(CheckProgress, props)); + return { + rerender: () => + instance.rerender(React.createElement(CheckProgress, props)), + unmount: () => instance.unmount(), + }; +} + +/** + * Output results and exit with appropriate code. + */ +function outputResultsAndExit( + results: CheckResult[], + diffContext: DiffContext, + options: CheckOptions, + checksFromHub: boolean, +): void { + const format = options.format === "json" ? "json" : "text"; + const report = renderReport(results, { + baseBranch: diffContext.baseBranch, + changedFileCount: diffContext.changedFiles.length, + format, + checksFromHub, + }); + + if (options.patch) { + const allPatches = results + .filter((r) => r.patch.trim()) + .map((r) => r.patch) + .join("\n"); + process.stdout.write(allPatches); + process.exit( + results.some((r) => r.status === "fail" || r.status === "error") ? 1 : 0, + ); + } + + console.log("\n" + report); + + if (options.fix) { + console.log(chalk.dim("\nApplying fixes...")); + applyPatches(results); + } + + const hasFailed = results.some( + (r) => r.status === "fail" || r.status === "error", + ); + process.exit(hasFailed ? 1 : 0); +} + /** * Main check command handler. */ @@ -227,45 +302,17 @@ export async function check(options: CheckOptions = {}): Promise { const checksFromHub = checks.some((c) => c.sourceType === "hub"); - // Determine whether to show live Ink UI - const useLiveUI = - process.stdout.isTTY && !options.patch && options.format !== "json"; - // Build mutable state for the live UI const checkStates: CheckState[] = checks.map((c) => ({ name: c.name, status: "pending" as const, })); - // Mount the Ink live progress UI (or fall back to static logs) - let rerender: (() => void) | undefined; - let unmountUI: (() => void) | undefined; - - if (useLiveUI) { - const { render } = await import("ink"); - const instance = render( - React.createElement(CheckProgress, { - checks: checkStates, - baseBranch: diffContext.baseBranch, - changedFileCount: diffContext.changedFiles.length, - }), - ); - rerender = () => - instance.rerender( - React.createElement(CheckProgress, { - checks: checkStates, - baseBranch: diffContext.baseBranch, - changedFileCount: diffContext.changedFiles.length, - }), - ); - unmountUI = () => instance.unmount(); - } else { - console.log( - chalk.dim( - `Running ${checks.length} check${checks.length > 1 ? "s" : ""}: ${checks.map((c) => c.name).join(", ")}`, - ), - ); - } + const { rerender, unmount: unmountUI } = await mountProgressUI( + checkStates, + diffContext, + options, + ); // Step 3: Create worktrees and run checks const results: CheckResult[] = []; @@ -337,7 +384,6 @@ export async function check(options: CheckOptions = {}): Promise { }; if (options.failFast) { - // Run sequentially, stop on first failure for (let i = 0; i < checks.length; i++) { const result = await runSingleCheck(checks[i], i); results.push(result); @@ -346,7 +392,6 @@ export async function check(options: CheckOptions = {}): Promise { } } } else { - // Run all checks in parallel const settled = await Promise.allSettled( checks.map((resolvedCheck, i) => runSingleCheck(resolvedCheck, i)), ); @@ -357,41 +402,6 @@ export async function check(options: CheckOptions = {}): Promise { } } - // Unmount the live UI before printing the final report unmountUI?.(); - - // Step 4: Render report - const format = options.format === "json" ? "json" : "text"; - const report = renderReport(results, { - baseBranch: diffContext.baseBranch, - changedFileCount: diffContext.changedFiles.length, - format, - checksFromHub, - }); - - // For --patch mode, output just the patches - if (options.patch) { - const allPatches = results - .filter((r) => r.patch.trim()) - .map((r) => r.patch) - .join("\n"); - process.stdout.write(allPatches); - process.exit( - results.some((r) => r.status === "fail" || r.status === "error") ? 1 : 0, - ); - } - - console.log("\n" + report); - - // Step 5: Apply fixes if --fix - if (options.fix) { - console.log(chalk.dim("\nApplying fixes...")); - applyPatches(results); - } - - // Exit with appropriate code - const hasFailed = results.some( - (r) => r.status === "fail" || r.status === "error", - ); - process.exit(hasFailed ? 1 : 0); + outputResultsAndExit(results, diffContext, options, checksFromHub); } diff --git a/extensions/cli/src/commands/check/CheckProgress.tsx b/extensions/cli/src/commands/check/CheckProgress.tsx index 9a1cda291..023deae83 100644 --- a/extensions/cli/src/commands/check/CheckProgress.tsx +++ b/extensions/cli/src/commands/check/CheckProgress.tsx @@ -50,11 +50,11 @@ function ElapsedTime({ check }: { check: CheckState }) { } const seconds = - check.duration != null - ? Math.round(check.duration) - : check.startTime != null - ? Math.round((Date.now() - check.startTime) / 1000) - : 0; + check.duration === undefined + ? check.startTime === undefined + ? 0 + : Math.round((Date.now() - check.startTime) / 1000) + : Math.round(check.duration); return {`${seconds}s`}; } @@ -73,12 +73,12 @@ export const CheckProgress: React.FC = ({ cn check ─ - {checks.length} check{checks.length !== 1 ? "s" : ""} against{" "} + {checks.length} check{checks.length === 1 ? "" : "s"} against{" "} {baseBranch} ─ - {changedFileCount} changed file{changedFileCount !== 1 ? "s" : ""} + {changedFileCount} changed file{changedFileCount === 1 ? "" : "s"} diff --git a/extensions/cli/src/commands/check/checkWorker.ts b/extensions/cli/src/commands/check/checkWorker.ts index a634a2611..4038246a0 100644 --- a/extensions/cli/src/commands/check/checkWorker.ts +++ b/extensions/cli/src/commands/check/checkWorker.ts @@ -7,6 +7,7 @@ */ import * as fs from "fs"; + import type { ChatHistoryItem } from "core/index.js"; import { @@ -19,7 +20,6 @@ import { streamChatResponse } from "../../stream/streamChatResponse.js"; import { constructSystemMessage } from "../../systemMessage.js"; import type { DiffContext } from "./diffContext.js"; -import type { CheckResult } from "./renderReport.js"; import { captureWorktreeDiff } from "./worktree.js"; export interface WorkerConfig {