Merge pull request #10111 from continuedev/nate/cn-check-skill
Add cn-check skill for AI agent code checks
This commit is contained in:
commit
a230e224f0
9 changed files with 1485 additions and 0 deletions
407
extensions/cli/src/commands/check.ts
Normal file
407
extensions/cli/src/commands/check.ts
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
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 { 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";
|
||||
|
||||
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<WorkerResult> {
|
||||
return new Promise<WorkerResult>((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).` : ""),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export async function check(options: CheckOptions = {}): Promise<void> {
|
||||
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");
|
||||
|
||||
// Build mutable state for the live UI
|
||||
const checkStates: CheckState[] = checks.map((c) => ({
|
||||
name: c.name,
|
||||
status: "pending" as const,
|
||||
}));
|
||||
|
||||
const { rerender, unmount: unmountUI } = await mountProgressUI(
|
||||
checkStates,
|
||||
diffContext,
|
||||
options,
|
||||
);
|
||||
|
||||
// Step 3: Create worktrees and run checks
|
||||
const results: CheckResult[] = [];
|
||||
|
||||
const runSingleCheck = async (
|
||||
resolvedCheck: (typeof checks)[number],
|
||||
i: number,
|
||||
): Promise<CheckResult> => {
|
||||
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) {
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unmountUI?.();
|
||||
outputResultsAndExit(results, diffContext, options, checksFromHub);
|
||||
}
|
||||
118
extensions/cli/src/commands/check/CheckProgress.tsx
Normal file
118
extensions/cli/src/commands/check/CheckProgress.tsx
Normal file
|
|
@ -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 <Text dimColor>{"◌ Pending"}</Text>;
|
||||
case "running":
|
||||
return (
|
||||
<Box>
|
||||
<LoadingAnimation color="magenta" />
|
||||
<Text color="magenta">{" Running"}</Text>
|
||||
</Box>
|
||||
);
|
||||
case "pass":
|
||||
return <Text color="green">{"✓ Pass"}</Text>;
|
||||
case "fail":
|
||||
return <Text color="red">{"✗ Fail"}</Text>;
|
||||
case "error":
|
||||
return <Text color="red">{"✗ Error"}</Text>;
|
||||
}
|
||||
}
|
||||
|
||||
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 <Text dimColor>{"–"}</Text>;
|
||||
}
|
||||
|
||||
const seconds =
|
||||
check.duration === undefined
|
||||
? check.startTime === undefined
|
||||
? 0
|
||||
: Math.round((Date.now() - check.startTime) / 1000)
|
||||
: Math.round(check.duration);
|
||||
|
||||
return <Text dimColor>{`${seconds}s`}</Text>;
|
||||
}
|
||||
|
||||
const COL_NAME = 22;
|
||||
const COL_STATUS = 16;
|
||||
|
||||
export const CheckProgress: React.FC<CheckProgressProps> = ({
|
||||
checks,
|
||||
baseBranch,
|
||||
changedFileCount,
|
||||
}) => {
|
||||
return (
|
||||
<Box flexDirection="column" paddingTop={1} paddingBottom={1}>
|
||||
<Box gap={1}>
|
||||
<Text bold>cn check</Text>
|
||||
<Text dimColor>─</Text>
|
||||
<Text>
|
||||
{checks.length} check{checks.length === 1 ? "" : "s"} against{" "}
|
||||
{baseBranch}
|
||||
</Text>
|
||||
<Text dimColor>─</Text>
|
||||
<Text>
|
||||
{changedFileCount} changed file{changedFileCount === 1 ? "" : "s"}
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Box width={COL_NAME}>
|
||||
<Text bold dimColor>
|
||||
Check
|
||||
</Text>
|
||||
</Box>
|
||||
<Box width={COL_STATUS}>
|
||||
<Text bold dimColor>
|
||||
Status
|
||||
</Text>
|
||||
</Box>
|
||||
<Text bold dimColor>
|
||||
Time
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<Text dimColor>{"─".repeat(COL_NAME + COL_STATUS + 6)}</Text>
|
||||
|
||||
{checks.map((check, i) => (
|
||||
<Box key={i}>
|
||||
<Box width={COL_NAME}>
|
||||
<Text>{check.name}</Text>
|
||||
</Box>
|
||||
<Box width={COL_STATUS}>
|
||||
<StatusIndicator status={check.status} />
|
||||
</Box>
|
||||
<ElapsedTime check={check} />
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
219
extensions/cli/src/commands/check/checkWorker.ts
Normal file
219
extensions/cli/src/commands/check/checkWorker.ts
Normal file
|
|
@ -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 { 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<void> {
|
||||
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<ModelServiceState>(
|
||||
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" });
|
||||
}
|
||||
116
extensions/cli/src/commands/check/diffContext.ts
Normal file
116
extensions/cli/src/commands/check/diffContext.ts
Normal file
|
|
@ -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,
|
||||
};
|
||||
}
|
||||
157
extensions/cli/src/commands/check/renderReport.ts
Normal file
157
extensions/cli/src/commands/check/renderReport.ts
Normal file
|
|
@ -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");
|
||||
}
|
||||
150
extensions/cli/src/commands/check/resolveChecks.ts
Normal file
150
extensions/cli/src/commands/check/resolveChecks.ts
Normal file
|
|
@ -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<ResolvedCheck[]> {
|
||||
// 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<ResolvedCheck[]> {
|
||||
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, " ");
|
||||
}
|
||||
118
extensions/cli/src/commands/check/worktree.ts
Normal file
118
extensions/cli/src/commands/check/worktree.ts
Normal file
|
|
@ -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<string> {
|
||||
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<void> {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
skills/cn-check.zip
Normal file
BIN
skills/cn-check.zip
Normal file
Binary file not shown.
200
skills/cn-check/SKILL.md
Normal file
200
skills/cn-check/SKILL.md
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
---
|
||||
name: cn-check
|
||||
description: Install and run the Continue CLI (`cn`) to execute AI agent checks on local code changes. Use when asked to "run checks", "lint with AI", "review my changes with cn", or set up Continue CI locally.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: continuedev
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# cn check — Local AI Agent Checks
|
||||
|
||||
Run AI-powered code checks locally against your working tree changes using the Continue CLI. Each check is an agent (defined in markdown) that reviews your diff, identifies issues, and optionally suggests fixes as a patch.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks to run AI checks on their code changes
|
||||
- User wants to set up `cn check` in a project
|
||||
- User needs to create custom check agents
|
||||
- User wants to apply AI-suggested fixes locally
|
||||
- User asks about Continue CI or agent-based code review
|
||||
|
||||
## Installation
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- A git repository with uncommitted or branched changes
|
||||
|
||||
### Install the CLI
|
||||
|
||||
```bash
|
||||
npm install -g @continuedev/cli
|
||||
```
|
||||
|
||||
### Authenticate (required for Hub checks, optional for local-only)
|
||||
|
||||
```bash
|
||||
cn login
|
||||
```
|
||||
|
||||
This opens a browser for authentication. After login, Hub-configured checks are available automatically.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic: Run all discovered checks
|
||||
|
||||
```bash
|
||||
cn check
|
||||
```
|
||||
|
||||
This auto-detects checks from three sources (in priority order):
|
||||
|
||||
1. Hub API — checks configured for your repo on hub.continue.dev
|
||||
2. Local agents — markdown files in `.continue/agents/*.md`
|
||||
|
||||
### Specify agents explicitly
|
||||
|
||||
```bash
|
||||
# Run a single local agent
|
||||
cn check --agent .continue/agents/security-review.md
|
||||
|
||||
# Run a Hub-published agent
|
||||
cn check --agent myorg/code-style
|
||||
|
||||
# Run multiple agents
|
||||
cn check --agent .continue/agents/security.md --agent .continue/agents/docs.md
|
||||
```
|
||||
|
||||
### Compare against a specific base branch
|
||||
|
||||
```bash
|
||||
cn check --base develop
|
||||
```
|
||||
|
||||
Default: auto-detects `main` or `master`.
|
||||
|
||||
### Output formats
|
||||
|
||||
```bash
|
||||
# JSON output (for CI pipelines or scripting)
|
||||
cn check --format json
|
||||
|
||||
# Unified patch output (pipe to git apply)
|
||||
cn check --patch | git apply
|
||||
|
||||
# Stop on first failure
|
||||
cn check --fail-fast
|
||||
```
|
||||
|
||||
### Auto-fix mode
|
||||
|
||||
```bash
|
||||
cn check --fix
|
||||
```
|
||||
|
||||
Runs all checks, then applies any suggested patches directly to the working tree. Patches that conflict are reported but skipped.
|
||||
|
||||
## Creating a Check Agent
|
||||
|
||||
Create a markdown file at `.continue/agents/<name>.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 <base>...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 <branch> Base branch for diff (default: auto-detect)
|
||||
--format <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> Agent to run (hub slug or local path, repeatable)
|
||||
--config <path> Path to config file
|
||||
--org <slug> 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` |
|
||||
Loading…
Add table
Reference in a new issue