diff --git a/CHANGELOG.md b/CHANGELOG.md index a13eb3d..61a867c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ This changelog is automatically generated by AI when releases are published. ## [Unreleased] +## [3.14.0] - 2026-11-17 + +### Added + +- **`autter findings`** shows the Autter review findings of the pull request open for your branch, most severe first, on the lines of your working tree. Findings are anchored to the commit Autter reviewed; the command diffs that commit against your files and moves each line by the lines added or removed above it. A finding whose own line you have edited since the review is reported as changed, with no line, so nothing points at code the review never saw. A missing reviewed commit is fetched from the pull request's head without prompting for credentials (`--no-fetch` skips it); otherwise the findings are reported as unverified. `--branch` and `--pr` pick another pull request; `--json` adds a `local` placement to every finding. +- **`autter findings --write`** keeps `.autter/findings.md` up to date: a summary, location, next steps and dashboard link for every finding, grouped into findings in your code, on lines you have changed since the review, and about the change as a whole. `.autter/` is added to `.git/info/exclude`. The file only changes when the findings do. +- **`autter review`** reviews your changes before a pull request exists, with the core of Autter's PR review: secrets, static security, auth and permissions, race conditions, and deep correctness when your organization has it on. By default it reviews what a pull request from this branch would contain (since the merge base with the default branch, committed or not, untracked files included); `--uncommitted`, `--base ` and paths narrow it. Up to 60 files. The reviewed copy of each file is saved as a git blob, and the result in `.autter/local-review.json`; `autter findings` shows it for the branch it was made on, with lines that follow your edits the same way. +- **VS Code extension 0.2.0**: review findings in the editor, as squiggles, Problems entries and (by default) the title after the line (`autter.findings.display`: `inline`, `problems` or `off`). Quick fixes copy a fix prompt for your agent, open the finding in the dashboard, or dismiss it. **Autter: Review My Changes** runs `autter review`. The status bar shows the count, or **autter: Sign in**, which runs `autter login` in a terminal. Needs autter 3.14.0. + ## [3.13.0] - 2026-11-17 ### Added diff --git a/Cargo.lock b/Cargo.lock index c1792ab..2aa51ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -258,7 +258,7 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "autter" -version = "3.13.0" +version = "3.14.0" dependencies = [ "autter", "base64", diff --git a/Cargo.toml b/Cargo.toml index ba02a99..b33cd90 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "3" [package] name = "autter" -version = "3.13.0" +version = "3.14.0" edition = "2024" default-run = "autter" diff --git a/agent-support/vscode/CHANGELOG.md b/agent-support/vscode/CHANGELOG.md index a38d9c9..bf5f785 100644 --- a/agent-support/vscode/CHANGELOG.md +++ b/agent-support/vscode/CHANGELOG.md @@ -6,4 +6,13 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how ## [Unreleased] +## [0.2.0] - 2026-11-17 + +- Review findings in the editor: the findings of your branch's pull request appear as squiggles, Problems entries and (by default) the title after the line, on the lines of your working tree. Lines follow your edits; a finding whose line you have edited since the review is not shown in the code. Setting: `autter.findings.display` (`inline`, `problems`, `off`). +- Quick fixes: copy a fix prompt for your AI agent, open the finding in the Autter dashboard, or dismiss it. +- **Autter: Review My Changes** reviews your changes before a pull request exists (`autter review`); its findings show up the same way, labelled "local review". +- `.autter/findings.md` is kept up to date with every finding (`autter.findings.writeFile`). +- The status bar shows the count of findings, or **autter: Sign in** when you are signed out. +- Requires autter CLI 3.14.0 or later. + - Initial release \ No newline at end of file diff --git a/agent-support/vscode/README.md b/agent-support/vscode/README.md index dc0fb81..2921a82 100644 --- a/agent-support/vscode/README.md +++ b/agent-support/vscode/README.md @@ -26,6 +26,21 @@ You can enable toast messages from the extension when it calls checkpoints to ge "autter.enableCheckpointLogging": true ``` +### Review findings in the editor + +When the branch you have checked out has an open pull request that Autter reviewed, its findings show up next to the code: squiggles on the affected lines, entries in the Problems panel, and (by default) the finding's title after the line. Quick fixes on each finding copy a fix prompt for your AI agent, open the finding in the dashboard, or dismiss it. + +Findings are only shown on lines the review saw. Line numbers follow your edits: lines added or removed above a finding move it, and a finding whose own line you've edited since the review is no longer shown in the code (it's listed in the findings file as possibly fixed). + +The extension keeps `.autter/findings.md` up to date with every finding: a summary, its location, next steps, and a link. `.autter/` is added to `.git/info/exclude`, so it is never committed. + +**Before a pull request exists**, run *Autter: Review My Changes*. It saves your files and runs `autter review`, which reviews everything a pull request from this branch would contain (committed or not, new files included) with the core of Autter's PR review. Its findings show up the same way, labelled "local review", and follow your edits the same way. The result is kept until you review again on that branch. + +- **Sign in**: click **autter: Sign in** in the status bar. It runs `autter login` in a terminal. +- **Settings**: `autter.findings.display` (`inline`, `problems` or `off`; default `inline`) and `autter.findings.writeFile` (default `true`). +- **Commands**: *Autter: Review My Changes*, *Autter: Refresh Review Findings*, *Autter: Open Review Findings File*, *Autter: Show Dismissed Review Findings Again*. +- Requires an `autter` CLI with the `autter findings` and `autter review` commands. + ### AI tab tracking (experimental) Adds support for tracking AI tab-completion insertions diff --git a/agent-support/vscode/package-lock.json b/agent-support/vscode/package-lock.json index a37c204..d6be0d4 100644 --- a/agent-support/vscode/package-lock.json +++ b/agent-support/vscode/package-lock.json @@ -1,12 +1,13 @@ { "name": "autter-vscode", - "version": "0.1.25", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "autter-vscode", - "version": "0.1.25", + "version": "0.2.0", + "license": "Apache-2.0", "dependencies": { "posthog-node": "^5.35.14" }, @@ -1992,19 +1993,6 @@ "dev": true, "license": "BSD-2-Clause" }, - "node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, "node_modules/braces": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", @@ -3136,9 +3124,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-2.4.3.tgz", - "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { @@ -3275,17 +3263,17 @@ } }, "node_modules/form-data": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.6.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -3543,9 +3531,9 @@ } }, "node_modules/hasown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", - "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "dev": true, "license": "MIT", "dependencies": { @@ -3985,10 +3973,20 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "3.15.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -4460,6 +4458,19 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/minimatch/node_modules/brace-expansion": { + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, "node_modules/minimist": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", @@ -6380,9 +6391,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "6.27.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz", - "integrity": "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==", + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", "dev": true, "license": "MIT", "engines": { diff --git a/agent-support/vscode/package.json b/agent-support/vscode/package.json index 5c649b4..c9a213d 100644 --- a/agent-support/vscode/package.json +++ b/agent-support/vscode/package.json @@ -2,7 +2,7 @@ "name": "autter-vscode", "displayName": "autter", "description": "Keep track of code generated by AI.", - "version": "0.1.25", + "version": "0.2.0", "icon": "autter.png", "publisher": "autter", "repository": { @@ -65,6 +65,28 @@ "Show gutter decorations for all AI-authored lines in the file" ], "description": "Control how AI blame attribution is displayed in the editor gutter." + }, + "autter.findings.display": { + "type": "string", + "enum": [ + "inline", + "problems", + "off" + ], + "default": "inline", + "scope": "window", + "enumDescriptions": [ + "Squiggles and Problems entries, plus the finding's title after the affected line", + "Squiggles and Problems entries only", + "Don't show review findings in the editor" + ], + "description": "How Autter review findings for the current branch's pull request are shown in the editor. Findings are only shown on lines the review saw: a line you've edited since is left unmarked." + }, + "autter.findings.writeFile": { + "type": "boolean", + "default": true, + "scope": "window", + "description": "Keep .autter/findings.md up to date with the findings (summary, location, next steps and a link for each). It is excluded from git." } } }, @@ -73,6 +95,46 @@ "command": "autter.toggleAICode", "title": "Toggle Show AI Code", "category": "Autter" + }, + { + "command": "autter.findings.reviewChanges", + "title": "Review My Changes", + "category": "Autter" + }, + { + "command": "autter.findings.refresh", + "title": "Refresh Review Findings", + "category": "Autter" + }, + { + "command": "autter.findings.openFile", + "title": "Open Review Findings File", + "category": "Autter" + }, + { + "command": "autter.findings.signIn", + "title": "Sign In", + "category": "Autter" + }, + { + "command": "autter.findings.restoreDismissed", + "title": "Show Dismissed Review Findings Again", + "category": "Autter" + }, + { + "command": "autter.findings.copyFixPrompt", + "title": "Copy Fix Prompt", + "category": "Autter" + }, + { + "command": "autter.findings.openInDashboard", + "title": "Open Finding in Dashboard", + "category": "Autter" + }, + { + "command": "autter.findings.dismiss", + "title": "Dismiss Review Finding", + "category": "Autter" } ], "keybindings": [ @@ -82,7 +144,23 @@ "mac": "cmd+shift+a", "when": "editorTextFocus" } - ] + ], + "menus": { + "commandPalette": [ + { + "command": "autter.findings.copyFixPrompt", + "when": "false" + }, + { + "command": "autter.findings.openInDashboard", + "when": "false" + }, + { + "command": "autter.findings.dismiss", + "when": "false" + } + ] + } }, "scripts": { "vscode:prepublish": "npm run compile", diff --git a/agent-support/vscode/src/extension.ts b/agent-support/vscode/src/extension.ts index 59a9d09..f952769 100644 --- a/agent-support/vscode/src/extension.ts +++ b/agent-support/vscode/src/extension.ts @@ -11,6 +11,7 @@ import { BlameLensManager, registerBlameLensCommands } from "./blame-lens-manage import { initBinaryResolver } from "./utils/binary-path"; import { KnownHumanCheckpointManager } from "./known-human-checkpoint-manager"; import { checkNativeHooksHealth } from "./native-hooks-health"; +import { FindingsManager } from "./findings-manager"; function getDistinctId(): string { try { @@ -78,6 +79,13 @@ export function activate(context: vscode.ExtensionContext) { dispose: () => blameLensManager.dispose() }); + // Review findings of the branch's pull request, next to the code. + const findingsManager = new FindingsManager(context); + findingsManager.activate(); + context.subscriptions.push({ + dispose: () => findingsManager.dispose() + }); + if (Config.isAiTabTrackingEnabled()) { const aiTabEditManager = new AITabEditManager(context, ideHostCfg, aiEditManager); const aiTabTrackingEnabled = aiTabEditManager.enableIfSupported(); diff --git a/agent-support/vscode/src/findings-manager.ts b/agent-support/vscode/src/findings-manager.ts new file mode 100644 index 0000000..3cd2172 --- /dev/null +++ b/agent-support/vscode/src/findings-manager.ts @@ -0,0 +1,634 @@ +import { spawn } from "child_process"; +import * as path from "path"; +import * as vscode from "vscode"; +import { getAutterBinary, resolveAutterBinary } from "./utils/binary-path"; +import { Config } from "./utils/config"; +import { + applyEdit, + type CliFinding, + type CliFindingsResult, + diagnosticMessage, + type FindingsOutcome, + inlineText, + parseFindingsOutput, + type PlacedFinding, + placeFindings, + severityLabel, + statusSummary, +} from "./findings-model"; + +const SOURCE = "autter"; +const DISMISSED_KEY = "autter.findings.dismissed"; +const SAVE_DEBOUNCE_MS = 3_000; +const POLL_MS = 5 * 60_000; +const FOCUS_REFRESH_MIN_MS = 60_000; +const RUN_TIMEOUT_MS = 90_000; + +/** One git work tree we show findings for. */ +interface Root { + workdir: string; + result: CliFindingsResult | null; + /** Placed findings by repo-relative path, kept in step with edits. */ + placed: Map; + running: boolean; + rerun: boolean; + lastRun: number; +} + +/** + * Review findings of the branch's pull request, in the editor: squiggles and + * Problems entries, optional after-the-line annotations, quick fixes, and a + * status bar item that doubles as the sign-in button. Data comes from + * `autter findings --json --write`, which also keeps `.autter/findings.md`. + */ +export class FindingsManager implements vscode.CodeActionProvider { + private readonly diagnostics = vscode.languages.createDiagnosticCollection(SOURCE); + private readonly decoration = vscode.window.createTextEditorDecorationType({ + after: { + margin: "0 0 0 2em", + color: new vscode.ThemeColor("editorCodeLens.foreground"), + fontStyle: "italic", + }, + isWholeLine: true, + }); + private readonly statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 90); + private readonly roots = new Map(); + /** Folder → its work tree, once a run has told us. */ + private readonly folderWorkdir = new Map(); + private readonly disposables: vscode.Disposable[] = []; + private saveTimer: NodeJS.Timeout | undefined; + private pollTimer: NodeJS.Timeout | undefined; + private signedOut = false; + private lastError: string | null = null; + + constructor(private readonly context: vscode.ExtensionContext) {} + + activate(): void { + this.disposables.push( + this.diagnostics, + this.decoration, + this.statusBar, + vscode.languages.registerCodeActionsProvider({ scheme: "file" }, this, { + providedCodeActionKinds: [vscode.CodeActionKind.QuickFix], + }), + vscode.commands.registerCommand("autter.findings.refresh", () => this.refreshAll(true)), + vscode.commands.registerCommand("autter.findings.reviewChanges", () => this.reviewChanges()), + vscode.commands.registerCommand("autter.findings.signIn", () => this.signIn()), + vscode.commands.registerCommand("autter.findings.openFile", () => this.openFindingsFile()), + vscode.commands.registerCommand("autter.findings.copyFixPrompt", (f: CliFinding) => this.copyFixPrompt(f)), + vscode.commands.registerCommand("autter.findings.openInDashboard", (f: CliFinding) => this.openInDashboard(f)), + vscode.commands.registerCommand("autter.findings.dismiss", (f: CliFinding) => this.dismiss(f)), + vscode.commands.registerCommand("autter.findings.restoreDismissed", () => this.restoreDismissed()), + vscode.workspace.onDidSaveTextDocument(() => this.scheduleRefresh()), + vscode.workspace.onDidChangeTextDocument((e) => this.onEdit(e)), + vscode.workspace.onDidChangeWorkspaceFolders(() => this.refreshAll(true)), + vscode.window.onDidChangeVisibleTextEditors(() => this.renderDecorations()), + vscode.window.onDidChangeWindowState((state) => { + if (state.focused) { + this.refreshAll(false); + } + }), + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("autter.findings")) { + this.refreshAll(true); + } + }), + ); + this.watchHeads(); + this.pollTimer = setInterval(() => this.refreshAll(true), POLL_MS); + this.refreshAll(true); + } + + dispose(): void { + if (this.saveTimer) { + clearTimeout(this.saveTimer); + } + if (this.pollTimer) { + clearInterval(this.pollTimer); + } + for (const d of this.disposables) { + d.dispose(); + } + } + + // ── Refresh ────────────────────────────────────────────────────────────── + + /** A checkout or commit changes `.git/HEAD`: refresh for the new branch. */ + private watchHeads(): void { + const watcher = vscode.workspace.createFileSystemWatcher("**/.git/{HEAD,ORIG_HEAD}"); + const onHead = () => this.scheduleRefresh(); + this.disposables.push(watcher, watcher.onDidChange(onHead), watcher.onDidCreate(onHead)); + } + + private scheduleRefresh(): void { + if (this.saveTimer) { + clearTimeout(this.saveTimer); + } + this.saveTimer = setTimeout(() => this.refreshAll(true), SAVE_DEBOUNCE_MS); + } + + private refreshAll(force: boolean): void { + if (Config.getFindingsDisplay() === "off") { + this.clearAll(); + this.statusBar.hide(); + return; + } + const folders = vscode.workspace.workspaceFolders ?? []; + const seen = new Set(); + for (const folder of folders) { + const cwd = folder.uri.fsPath; + const key = this.folderWorkdir.get(cwd) ?? cwd; + if (seen.has(key)) { + continue; + } + seen.add(key); + void this.refresh(cwd, force); + } + } + + private rootFor(key: string): Root { + let root = this.roots.get(key); + if (!root) { + root = { workdir: key, result: null, placed: new Map(), running: false, rerun: false, lastRun: 0 }; + this.roots.set(key, root); + } + return root; + } + + private async refresh(cwd: string, force: boolean): Promise { + const root = this.rootFor(this.folderWorkdir.get(cwd) ?? cwd); + if (!force && Date.now() - root.lastRun < FOCUS_REFRESH_MIN_MS) { + return; + } + if (root.running) { + root.rerun = true; + return; + } + root.running = true; + root.lastRun = Date.now(); + try { + const outcome = await this.runCli(cwd); + this.apply(cwd, root, outcome); + } finally { + root.running = false; + if (root.rerun) { + root.rerun = false; + void this.refresh(cwd, true); + } + } + } + + private async runCli(cwd: string): Promise { + if (!(await resolveAutterBinary())) { + return { kind: "unavailable", message: "The autter CLI is not installed." }; + } + const args = ["findings", "--json"]; + if (Config.isFindingsFileEnabled()) { + args.push("--write"); + } + return new Promise((resolve) => { + let stdout = ""; + let settled = false; + const done = (outcome: FindingsOutcome) => { + if (!settled) { + settled = true; + resolve(outcome); + } + }; + const proc = spawn(getAutterBinary(), args, { cwd, timeout: RUN_TIMEOUT_MS }); + proc.stdout.on("data", (d) => { + stdout += d.toString(); + }); + proc.stderr.on("data", () => {}); + proc.on("error", (err) => done({ kind: "unavailable", message: `Could not run autter: ${err.message}` })); + proc.on("close", (code) => done(parseFindingsOutput(stdout, code))); + }); + } + + private apply(cwd: string, root: Root, outcome: FindingsOutcome): void { + switch (outcome.kind) { + case "ok": { + this.signedOut = false; + this.lastError = null; + const workdir = outcome.result.local?.workdir ? path.resolve(outcome.result.local.workdir) : root.workdir; + let target = root; + if (workdir !== root.workdir) { + // First run from this folder: key the root by its real work tree. + this.clearRoot(root); + this.roots.delete(root.workdir); + this.folderWorkdir.set(cwd, workdir); + target = this.rootFor(workdir); + target.lastRun = root.lastRun; + } + this.setResult(target, outcome.result); + break; + } + case "signed_out": + this.signedOut = true; + this.clearRoot(root); + break; + case "unavailable": + // Not a repo Autter knows (or no CLI): show nothing for it. + this.clearRoot(root); + root.result = null; + break; + case "error": + // Keep what is shown; a transient failure shouldn't blank the editor. + this.lastError = outcome.message; + break; + } + this.renderStatus(); + } + + private setResult(root: Root, result: CliFindingsResult): void { + const dismissed = new Set(this.context.workspaceState.get(DISMISSED_KEY, [])); + const fresh = placeFindings(result, dismissed); + // The CLI placed findings on the files on disk. An editor with unsaved + // changes no longer matches them, so keep that file's edit-tracked + // placement until it is saved. + for (const doc of vscode.workspace.textDocuments) { + if (!doc.isDirty || doc.uri.scheme !== "file") { + continue; + } + const rel = this.relativePath(root, doc.uri); + if (rel === null) { + continue; + } + const kept = root.placed.get(rel); + if (kept) { + fresh.set(rel, kept.filter((p) => !dismissed.has(p.finding.id))); + } else { + fresh.delete(rel); + } + } + this.clearRoot(root); + root.result = result; + root.placed = fresh; + for (const rel of fresh.keys()) { + this.publish(root, rel); + } + this.renderDecorations(); + } + + // ── Display ────────────────────────────────────────────────────────────── + + private relativePath(root: Root, uri: vscode.Uri): string | null { + const rel = path.relative(root.workdir, uri.fsPath); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) { + return null; + } + return rel.split(path.sep).join("/"); + } + + private rootForUri(uri: vscode.Uri): { root: Root; rel: string } | null { + for (const root of this.roots.values()) { + const rel = this.relativePath(root, uri); + if (rel !== null && root.placed.has(rel)) { + return { root, rel }; + } + } + return null; + } + + private publish(root: Root, rel: string): void { + const uri = vscode.Uri.file(path.join(root.workdir, ...rel.split("/"))); + const placed = root.placed.get(rel) ?? []; + this.diagnostics.set(uri, placed.map((p) => this.toDiagnostic(p))); + } + + private toDiagnostic(p: PlacedFinding): vscode.Diagnostic { + const range = new vscode.Range(p.line, 0, p.line, Number.MAX_SAFE_INTEGER); + const severity = + p.finding.severity === "critical" + ? vscode.DiagnosticSeverity.Error + : p.finding.severity === "warning" + ? vscode.DiagnosticSeverity.Warning + : vscode.DiagnosticSeverity.Information; + const diagnostic = new vscode.Diagnostic(range, diagnosticMessage(p.finding), severity); + diagnostic.source = SOURCE; + const label = + p.origin === "local" + ? `${severityLabel(p.finding.severity)}, local review` + : severityLabel(p.finding.severity); + diagnostic.code = p.finding.url ? { value: label, target: vscode.Uri.parse(p.finding.url) } : label; + return diagnostic; + } + + private renderDecorations(): void { + const inline = Config.getFindingsDisplay() === "inline"; + for (const editor of vscode.window.visibleTextEditors) { + if (!inline) { + editor.setDecorations(this.decoration, []); + continue; + } + const hit = this.rootForUri(editor.document.uri); + const placed = hit ? (hit.root.placed.get(hit.rel) ?? []) : []; + // One annotation per line: the most severe finding on it. + const byLine = new Map(); + for (const p of placed) { + if (!byLine.has(p.line)) { + byLine.set(p.line, p); + } + } + const options: vscode.DecorationOptions[] = []; + for (const [line, p] of byLine) { + if (line >= editor.document.lineCount) { + continue; + } + const more = placed.filter((q) => q.line === line).length - 1; + options.push({ + range: new vscode.Range(line, 0, line, 0), + renderOptions: { + after: { + contentText: + more > 0 + ? `${inlineText(p.finding, 90, p.origin)} (+${more} more)` + : inlineText(p.finding, 90, p.origin), + }, + }, + }); + } + editor.setDecorations(this.decoration, options); + } + } + + private renderStatus(): void { + if (this.signedOut) { + this.statusBar.text = "$(account) autter: Sign in"; + this.statusBar.tooltip = "Sign in to see Autter review findings next to your code."; + this.statusBar.command = "autter.findings.signIn"; + this.statusBar.show(); + return; + } + const withResult = [...this.roots.values()].filter((r) => r.result); + if (withResult.length === 0) { + if (this.lastError) { + this.statusBar.text = "$(warning) autter"; + this.statusBar.tooltip = `Could not load findings: ${this.lastError}\nClick to retry.`; + this.statusBar.command = "autter.findings.refresh"; + this.statusBar.show(); + } else { + this.statusBar.hide(); + } + return; + } + // Several repos open: summarise the first; the file and Problems list the rest. + const root = withResult[0]; + const result = root.result as CliFindingsResult; + const shown = [...root.placed.values()].reduce((n, list) => n + list.length, 0); + const summary = statusSummary(result, shown); + this.statusBar.text = summary.text; + this.statusBar.tooltip = this.lastError ? `${summary.tooltip}\n\nLast refresh failed: ${this.lastError}` : summary.tooltip; + this.statusBar.command = "autter.findings.openFile"; + this.statusBar.show(); + } + + private clearRoot(root: Root): void { + for (const rel of root.placed.keys()) { + this.diagnostics.delete(vscode.Uri.file(path.join(root.workdir, ...rel.split("/")))); + } + root.placed = new Map(); + this.renderDecorations(); + } + + private clearAll(): void { + for (const root of this.roots.values()) { + this.clearRoot(root); + } + } + + // ── Edits ──────────────────────────────────────────────────────────────── + + /** Keep findings on their lines while typing; drop ones whose line is edited. */ + private onEdit(event: vscode.TextDocumentChangeEvent): void { + if (event.contentChanges.length === 0) { + return; + } + const hit = this.rootForUri(event.document.uri); + if (!hit) { + return; + } + let placed = hit.root.placed.get(hit.rel) ?? []; + for (const change of event.contentChanges) { + placed = applyEdit(placed, { + startLine: change.range.start.line, + startCharacter: change.range.start.character, + endLine: change.range.end.line, + endCharacter: change.range.end.character, + text: change.text, + }); + } + hit.root.placed.set(hit.rel, placed); + this.publish(hit.root, hit.rel); + this.renderDecorations(); + } + + // ── Code actions and commands ──────────────────────────────────────────── + + provideCodeActions( + document: vscode.TextDocument, + _range: vscode.Range, + context: vscode.CodeActionContext, + ): vscode.CodeAction[] { + const actions: vscode.CodeAction[] = []; + const hit = this.rootForUri(document.uri); + const placed = hit ? (hit.root.placed.get(hit.rel) ?? []) : []; + for (const diagnostic of context.diagnostics) { + if (diagnostic.source !== SOURCE) { + continue; + } + // Diagnostics come back as copies: find the finding by line and text. + const finding = placed.find( + (p) => p.line === diagnostic.range.start.line && diagnosticMessage(p.finding) === diagnostic.message, + )?.finding; + if (!finding) { + continue; + } + const add = (title: string, command: string) => { + const action = new vscode.CodeAction(title, vscode.CodeActionKind.QuickFix); + action.diagnostics = [diagnostic]; + action.command = { title, command, arguments: [finding] }; + actions.push(action); + }; + if (finding.fixPrompt) { + add("autter: Copy fix prompt (paste into your AI agent)", "autter.findings.copyFixPrompt"); + } + if (finding.url) { + add("autter: Open finding in the dashboard", "autter.findings.openInDashboard"); + } + add("autter: Dismiss this finding", "autter.findings.dismiss"); + } + return actions; + } + + private async copyFixPrompt(finding: CliFinding): Promise { + const text = [ + `Fix this code review finding in ${finding.path}${finding.local?.line ? `:${finding.local.line}` : ""}: ${finding.title}`, + finding.body, + finding.fixPrompt ?? "", + ] + .filter((s) => s.trim()) + .join("\n\n"); + await vscode.env.clipboard.writeText(text); + void vscode.window.showInformationMessage("autter: Fix prompt copied."); + } + + private openInDashboard(finding: CliFinding): void { + if (finding.url) { + void vscode.env.openExternal(vscode.Uri.parse(finding.url)); + } + } + + private async dismiss(finding: CliFinding): Promise { + const dismissed = new Set(this.context.workspaceState.get(DISMISSED_KEY, [])); + dismissed.add(finding.id); + await this.context.workspaceState.update(DISMISSED_KEY, [...dismissed]); + for (const root of this.roots.values()) { + for (const [rel, list] of root.placed) { + const kept = list.filter((p) => p.finding.id !== finding.id); + if (kept.length !== list.length) { + root.placed.set(rel, kept); + this.publish(root, rel); + } + } + } + this.renderDecorations(); + this.renderStatus(); + } + + private async restoreDismissed(): Promise { + await this.context.workspaceState.update(DISMISSED_KEY, []); + this.refreshAll(true); + } + + private async openFindingsFile(): Promise { + const root = [...this.roots.values()].find((r) => r.result); + const file = root?.result?.local?.markdownPath; + if (file) { + const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(file)); + await vscode.window.showTextDocument(doc, { preview: true }); + return; + } + if (root?.result?.pullRequest?.url) { + void vscode.env.openExternal(vscode.Uri.parse(root.result.pullRequest.url)); + return; + } + await vscode.commands.executeCommand("workbench.actions.view.problems"); + } + + /** The work tree to review: the active editor's, else the first folder's. */ + private reviewFolder(): string | null { + const active = vscode.window.activeTextEditor?.document.uri; + const folder = + (active && vscode.workspace.getWorkspaceFolder(active)) ?? vscode.workspace.workspaceFolders?.[0]; + return folder?.uri.fsPath ?? null; + } + + /** + * `autter review`: review the branch's changes before a pull request, then + * show the findings like the PR's. Saves open files first: the review reads + * them from disk. + */ + private async reviewChanges(): Promise { + const cwd = this.reviewFolder(); + if (!cwd) { + void vscode.window.showWarningMessage("autter: Open a folder in a git repository to review your changes."); + return; + } + if (!(await resolveAutterBinary())) { + void vscode.window.showWarningMessage("autter: The autter CLI is not installed."); + return; + } + await vscode.workspace.saveAll(false); + const args = ["review", "--json"]; + if (Config.isFindingsFileEnabled()) { + args.push("--write"); + } + const outcome = await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: "autter: Reviewing your changes (a minute or two)…", + cancellable: true, + }, + (_progress, token) => + new Promise<{ stdout: string; code: number | null; cancelled: boolean }>((resolve) => { + let stdout = ""; + const proc = spawn(getAutterBinary(), args, { cwd, timeout: 11 * 60_000 }); + token.onCancellationRequested(() => { + proc.kill(); + resolve({ stdout: "", code: null, cancelled: true }); + }); + proc.stdout.on("data", (d) => { + stdout += d.toString(); + }); + proc.stderr.on("data", () => {}); + proc.on("error", () => resolve({ stdout: "", code: null, cancelled: false })); + proc.on("close", (code) => resolve({ stdout, code, cancelled: false })); + }), + ); + if (outcome.cancelled) { + return; + } + let parsed: { error?: string; message?: string; localReview?: { findings?: CliFinding[] } | null } | null = null; + try { + parsed = JSON.parse(outcome.stdout.trim() || "null"); + } catch { + parsed = null; + } + if (!parsed) { + void vscode.window.showErrorMessage("autter: The review failed. Is the autter CLI up to date?"); + return; + } + if (parsed.error) { + if (/autter login|HTTP 401/i.test(parsed.error)) { + const choice = await vscode.window.showWarningMessage(`autter: ${parsed.error}`, "Sign in"); + if (choice === "Sign in") { + await this.signIn(); + } + } else { + void vscode.window.showErrorMessage(`autter: ${parsed.error}`); + } + return; + } + if (!parsed.localReview) { + void vscode.window.showInformationMessage(`autter: ${parsed.message ?? "No changes to review."}`); + return; + } + const findings = parsed.localReview.findings ?? []; + const shown = findings.filter((f) => f.local?.status === "unchanged" || f.local?.status === "moved").length; + this.refreshAll(true); + const text = + findings.length === 0 + ? "autter: The review found nothing in your changes." + : `autter: The review found ${findings.length} issue${findings.length === 1 ? "" : "s"}${shown < findings.length ? ` (${shown} shown in the code)` : ""}.`; + const choice = await vscode.window.showInformationMessage(text, "Open findings"); + if (choice === "Open findings") { + await this.openFindingsFile(); + } + } + + /** Sign in with the CLI's device flow in a terminal, then refresh. */ + private async signIn(): Promise { + const binary = (await resolveAutterBinary()) ?? "autter"; + const terminal = vscode.window.createTerminal({ name: "autter login" }); + terminal.show(); + const quoted = /\s/.test(binary) ? `"${binary}"` : binary; + terminal.sendText(`${quoted} login`); + const sub = vscode.window.onDidCloseTerminal((closed) => { + if (closed === terminal) { + sub.dispose(); + this.refreshAll(true); + } + }); + this.disposables.push(sub); + // Most people leave the terminal open after signing in: also refresh + // when the window regains focus from the browser. + const focus = vscode.window.onDidChangeWindowState((state) => { + if (state.focused) { + focus.dispose(); + this.refreshAll(true); + } + }); + this.disposables.push(focus); + } +} diff --git a/agent-support/vscode/src/findings-model.ts b/agent-support/vscode/src/findings-model.ts new file mode 100644 index 0000000..81868d2 --- /dev/null +++ b/agent-support/vscode/src/findings-model.ts @@ -0,0 +1,237 @@ +/** + * Findings in the editor: the parts that don't need VS Code, so they can be + * unit-tested. Reads `autter findings --json` and keeps each finding on the + * right line while the user types. + * + * Rule: a finding is only ever shown on a line the review saw. The CLI drops + * findings whose line changed since the reviewed commit (`local.status: + * "changed"`); while typing, {@link applyEdit} drops a finding as soon as its + * own line is edited, and moves it when lines above it are added or removed. + */ + +export type FindingSeverity = "critical" | "warning" | "info"; + +export type PlacementStatus = + | "unchanged" + | "moved" + | "changed" + | "file_deleted" + | "unverified" + | "no_line"; + +export interface CliFinding { + id: string; + title: string; + body: string; + path: string; + /** 1-based line at the reviewed commit. */ + line: number; + severity: FindingSeverity; + category?: string; + fixPrompt: string | null; + url: string | null; + local?: { status: PlacementStatus; line: number | null }; +} + +export interface CliFindingsResult { + repository?: { name: string; fullName: string }; + pullRequest: { + number: number; + title: string | null; + url: string | null; + } | null; + review: { headSha: string; stale: boolean } | null; + findings: CliFinding[]; + /** The saved `autter review` for this branch, placed on the working tree. */ + localReview?: { + reviewId?: string; + reviewedAt?: string | null; + baseRef?: string | null; + findings: CliFinding[]; + } | null; + local?: { + workdir?: string; + branch?: string | null; + markdownPath?: string; + reviewedCommitAvailable?: boolean; + }; +} + +export type FindingsOutcome = + | { kind: "ok"; result: CliFindingsResult } + | { kind: "signed_out"; message: string } + /** Not a repo Autter can look up (no git repo, no remote, not connected). */ + | { kind: "unavailable"; message: string } + | { kind: "error"; message: string }; + +const SIGNED_OUT = /autter login|sign in|signed in|HTTP 401/i; +const UNAVAILABLE = + /inside a git repository|has no remote|detached|repo_not_found|not connected|ambiguous|Unknown repository|not found in this organization/i; + +/** Classify what `autter findings --json` printed (and its exit code). */ +export function parseFindingsOutput(stdout: string, exitCode: number | null): FindingsOutcome { + let parsed: unknown; + try { + parsed = JSON.parse(stdout.trim() || "null"); + } catch { + return { kind: "error", message: "autter findings printed something that isn't JSON. Update the autter CLI." }; + } + if (parsed && typeof parsed === "object" && typeof (parsed as { error?: unknown }).error === "string") { + const message = (parsed as { error: string }).error; + if (SIGNED_OUT.test(message)) { + return { kind: "signed_out", message }; + } + if (UNAVAILABLE.test(message)) { + return { kind: "unavailable", message }; + } + return { kind: "error", message }; + } + if (exitCode !== 0 || !parsed || typeof parsed !== "object" || !Array.isArray((parsed as { findings?: unknown }).findings)) { + return { kind: "error", message: "autter findings failed. Is the autter CLI up to date?" }; + } + return { kind: "ok", result: parsed as CliFindingsResult }; +} + +/** Where a finding comes from: the pull request's review, or `autter review` on this machine. */ +export type FindingOrigin = "pr" | "local"; + +/** A finding placed on a 0-based line of a file in the working tree. */ +export interface PlacedFinding { + finding: CliFinding; + origin: FindingOrigin; + /** Repo-relative path. */ + path: string; + /** 0-based line in the current document. */ + line: number; +} + +/** Findings that have a line in the working tree, grouped by repo-relative path. */ +export function placeFindings( + result: CliFindingsResult, + dismissed: ReadonlySet = new Set(), +): Map { + const byPath = new Map(); + const sources: Array<[FindingOrigin, CliFinding[]]> = [ + ["pr", result.findings], + ["local", result.localReview?.findings ?? []], + ]; + for (const [origin, findings] of sources) { + for (const finding of findings) { + if (dismissed.has(finding.id)) { + continue; + } + const status = finding.local?.status; + const line = finding.local?.line; + if ((status !== "unchanged" && status !== "moved") || typeof line !== "number" || line < 1) { + continue; + } + const list = byPath.get(finding.path) ?? []; + list.push({ finding, origin, path: finding.path, line: line - 1 }); + byPath.set(finding.path, list); + } + } + return byPath; +} + +/** One text change, in the document's lines before the change (0-based). */ +export interface LineEdit { + startLine: number; + startCharacter: number; + endLine: number; + endCharacter: number; + /** The inserted text. */ + text: string; +} + +/** + * Move findings through one edit. A finding on a line the edit touches is + * dropped (the review never saw the new code); one below it moves by the + * lines added or removed. Pressing Enter at the very start of a finding's + * line only pushes it down. + */ +export function applyEdit(placed: PlacedFinding[], edit: LineEdit): PlacedFinding[] { + const inserted = edit.text.split("\n").length - 1; + const delta = inserted - (edit.endLine - edit.startLine); + // Text ending in a newline inserted at column 0 leaves the line's own + // content as it was, one or more lines further down. + const pushesDown = + edit.startLine === edit.endLine && + edit.startCharacter === 0 && + edit.endCharacter === 0 && + edit.text.endsWith("\n"); + const out: PlacedFinding[] = []; + for (const p of placed) { + if (p.line < edit.startLine) { + out.push(p); + } else if (p.line > edit.endLine || (p.line === edit.startLine && pushesDown)) { + out.push({ ...p, line: p.line + delta }); + } + // Otherwise the edit touched the finding's line: drop it. + } + return out; +} + +const SEVERITY_LABEL: Record = { + critical: "Critical", + warning: "Warning", + info: "Info", +}; + +export function severityLabel(severity: FindingSeverity): string { + return SEVERITY_LABEL[severity] ?? "Info"; +} + +/** The diagnostic text: title, then the body, then the next step. */ +export function diagnosticMessage(finding: CliFinding): string { + const parts = [finding.title.trim()]; + if (finding.body.trim()) { + parts.push(finding.body.trim()); + } + if (finding.fixPrompt?.trim()) { + parts.push(`Next step: ${finding.fixPrompt.trim()}`); + } + return parts.join("\n\n"); +} + +/** The short text shown after the line when inline annotations are on. */ +export function inlineText(finding: CliFinding, max = 90, origin: FindingOrigin = "pr"): string { + const who = origin === "local" ? "autter review" : "autter"; + const text = `${who} ${severityLabel(finding.severity).toLowerCase()}: ${finding.title.replace(/\s+/g, " ").trim()}`; + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +} + +/** The status bar text for a result (`shown`: findings with a place in the code). */ +export function statusSummary(result: CliFindingsResult, shown: number): { text: string; tooltip: string } { + const local = result.localReview?.findings ?? []; + const pr = result.pullRequest && result.review ? result.findings : []; + const total = pr.length + local.length; + const lines: string[] = []; + if (!result.pullRequest) { + lines.push("No open pull request for this branch yet."); + } else if (!result.review) { + lines.push(`Autter has not reviewed PR #${result.pullRequest.number} yet.`); + } else { + lines.push( + `${pr.length} finding${pr.length === 1 ? "" : "s"} on PR #${result.pullRequest.number}${result.review.stale ? " (from an older push)" : ""}.`, + ); + } + if (result.localReview) { + lines.push(`${local.length} from your last local review (autter review).`); + } else { + lines.push("Run \"Autter: Review My Changes\" to review your changes before a PR."); + } + const elsewhere = total - shown; + if (elsewhere > 0) { + lines.push(`${elsewhere} not shown in the code: on lines you changed since the review, or about the change as a whole.`); + } + lines.push("Click to open .autter/findings.md."); + if (total === 0 && !result.pullRequest && !result.localReview) { + return { text: "$(shield) autter: no PR", tooltip: lines.join("\n") }; + } + if (total === 0 && result.pullRequest && !result.review && !result.localReview) { + return { text: `$(shield) autter: PR #${result.pullRequest.number} not reviewed`, tooltip: lines.join("\n") }; + } + const all = [...pr, ...local]; + const icon = all.some((f) => f.severity === "critical") ? "$(error)" : total > 0 ? "$(warning)" : "$(pass)"; + return { text: `${icon} autter: ${total}`, tooltip: lines.join("\n") }; +} diff --git a/agent-support/vscode/src/test/findings-model.test.ts b/agent-support/vscode/src/test/findings-model.test.ts new file mode 100644 index 0000000..bbe1ed9 --- /dev/null +++ b/agent-support/vscode/src/test/findings-model.test.ts @@ -0,0 +1,139 @@ +import * as assert from "assert"; +import { + applyEdit, + type CliFinding, + type CliFindingsResult, + diagnosticMessage, + inlineText, + parseFindingsOutput, + type PlacedFinding, + placeFindings, + statusSummary, +} from "../findings-model"; + +function finding(id: string, over: Partial = {}): CliFinding { + return { + id, + title: `Title ${id}`, + body: `Body ${id}`, + path: "src/a.ts", + line: 3, + severity: "warning", + fixPrompt: `Fix ${id}`, + url: `https://app.autter.dev/acme/repositories/web/pull/7?finding=${id}`, + local: { status: "unchanged", line: 3 }, + ...over, + }; +} + +function result(findings: CliFinding[]): CliFindingsResult { + return { + pullRequest: { number: 7, title: "Add thing", url: "https://app/pull/7" }, + review: { headSha: "abc", stale: false }, + findings, + }; +} + +function placed(line: number, id = "f"): PlacedFinding { + return { finding: finding(id), origin: "pr", path: "src/a.ts", line }; +} + +suite("Findings model", () => { + test("parses CLI output into outcomes", () => { + const ok = parseFindingsOutput(JSON.stringify(result([finding("a")])), 0); + assert.strictEqual(ok.kind, "ok"); + assert.strictEqual( + parseFindingsOutput('{"error":"Generic error: Sign in with `autter login` first."}', 1).kind, + "signed_out", + ); + assert.strictEqual( + parseFindingsOutput('{"error":"Run autter findings inside a git repository."}', 1).kind, + "unavailable", + ); + assert.strictEqual(parseFindingsOutput('{"error":"HTTP 500: boom"}', 1).kind, "error"); + assert.strictEqual(parseFindingsOutput("not json", 0).kind, "error"); + assert.strictEqual(parseFindingsOutput("{}", 0).kind, "error"); + }); + + test("places only findings that still sit on a line the review saw", () => { + const byPath = placeFindings( + result([ + finding("same"), + finding("moved", { local: { status: "moved", line: 9 } }), + finding("changed", { local: { status: "changed", line: null } }), + finding("unverified", { local: { status: "unverified", line: null } }), + finding("pr", { path: "", local: { status: "no_line", line: null } }), + finding("hidden"), + ]), + new Set(["hidden"]), + ); + const list = byPath.get("src/a.ts") ?? []; + assert.deepStrictEqual( + list.map((p) => [p.finding.id, p.line]), + [ + ["same", 2], + ["moved", 8], + ], + ); + assert.strictEqual(byPath.size, 1); + }); + + test("places the saved local review next to the PR's findings", () => { + const byPath = placeFindings({ + ...result([finding("pr")]), + localReview: { + findings: [ + finding("local-1", { local: { status: "moved", line: 7 } }), + finding("local-2", { local: { status: "changed", line: null } }), + ], + }, + }); + assert.deepStrictEqual( + (byPath.get("src/a.ts") ?? []).map((p) => [p.finding.id, p.origin, p.line]), + [ + ["pr", "pr", 2], + ["local-1", "local", 6], + ], + ); + assert.strictEqual(inlineText(finding("x"), 90, "local"), "autter review warning: Title x"); + }); + + test("an edit above a finding moves it; an edit on its line drops it", () => { + const list = [placed(2, "a"), placed(5, "b"), placed(9, "c")]; + // Two lines inserted at the end of line 0. + const moved = applyEdit(list, { startLine: 0, startCharacter: 4, endLine: 0, endCharacter: 4, text: "\nx\ny" }); + assert.deepStrictEqual(moved.map((p) => p.line), [4, 7, 11]); + // Typing on line 5 drops b. + const typed = applyEdit(list, { startLine: 5, startCharacter: 3, endLine: 5, endCharacter: 3, text: "z" }); + assert.deepStrictEqual(typed.map((p) => p.finding.id), ["a", "c"]); + // Deleting lines 4–6 (joining them) drops b and moves c up by 2. + const joined = applyEdit(list, { startLine: 4, startCharacter: 0, endLine: 6, endCharacter: 0, text: "" }); + assert.deepStrictEqual(joined.map((p) => [p.finding.id, p.line]), [["a", 2], ["c", 7]]); + }); + + test("Enter at the start of a finding's line pushes it down instead of dropping it", () => { + const list = [placed(5)]; + const out = applyEdit(list, { startLine: 5, startCharacter: 0, endLine: 5, endCharacter: 0, text: "\n" }); + assert.deepStrictEqual(out.map((p) => p.line), [6]); + // Replacing text at the start of the line is an edit of the line. + const replaced = applyEdit(list, { startLine: 5, startCharacter: 0, endLine: 5, endCharacter: 3, text: "x\n" }); + assert.strictEqual(replaced.length, 0); + }); + + test("formats diagnostic, inline and status text", () => { + assert.strictEqual(diagnosticMessage(finding("a")), "Title a\n\nBody a\n\nNext step: Fix a"); + assert.strictEqual(inlineText(finding("a")), "autter warning: Title a"); + assert.ok(inlineText(finding("a", { title: "x".repeat(200) })).endsWith("…")); + + const summary = statusSummary(result([finding("a", { severity: "critical" }), finding("b")]), 1); + assert.strictEqual(summary.text, "$(error) autter: 2"); + assert.ok(summary.tooltip.includes("1 not shown in the code")); + assert.strictEqual(statusSummary({ ...result([]), pullRequest: null }, 0).text, "$(shield) autter: no PR"); + const withLocal = statusSummary( + { ...result([]), pullRequest: null, review: null, localReview: { findings: [finding("l", { severity: "critical" })] } }, + 1, + ); + assert.strictEqual(withLocal.text, "$(error) autter: 1"); + assert.ok(withLocal.tooltip.includes("1 from your last local review")); + }); +}); diff --git a/agent-support/vscode/src/utils/config.ts b/agent-support/vscode/src/utils/config.ts index 0aa1e9f..19c9349 100644 --- a/agent-support/vscode/src/utils/config.ts +++ b/agent-support/vscode/src/utils/config.ts @@ -2,6 +2,8 @@ import * as vscode from "vscode"; export type BlameMode = 'off' | 'line' | 'all'; +export type FindingsDisplay = 'off' | 'problems' | 'inline'; + export class Config { private static getRoot(): vscode.WorkspaceConfiguration { return vscode.workspace.getConfiguration("autter"); @@ -29,6 +31,20 @@ export class Config { return 'line'; // default } + static getFindingsDisplay(): FindingsDisplay { + const mode = this.getRoot().get("findings.display"); + if (mode === 'off' || mode === 'problems' || mode === 'inline') { + return mode; + } + return 'inline'; // default + } + + static isFindingsFileEnabled(): boolean { + // Defaults to true when unset. + const value = this.getRoot().get("findings.writeFile"); + return value === undefined ? true : value; + } + static async setBlameMode(mode: BlameMode): Promise { await this.getRoot().update("blameMode", mode, vscode.ConfigurationTarget.Global); } diff --git a/changelog/findings-in-the-editor.md b/changelog/findings-in-the-editor.md new file mode 100644 index 0000000..8c9b84c --- /dev/null +++ b/changelog/findings-in-the-editor.md @@ -0,0 +1,15 @@ +# Review findings in the editor, and before the pull request + +## Summary + +`autter findings` shows the Autter review findings of the pull request open for your branch, on the lines of your working tree, and can keep them in `.autter/findings.md`. `autter review` runs the core of that review on your changes before a pull request exists. The VS Code extension shows both inline, so you no longer have to switch to the dashboard, or wait for a pull request, to see them. + +## Added + +- **`autter findings`** prints the findings of the current branch's open pull request: severity, `file:line` and title, most severe first. `--branch` and `--pr` pick another pull request; `--repo` and `--org` work as in `autter ask`. +- **Lines follow your edits.** Findings are anchored to the commit Autter reviewed. The command diffs that commit against your working tree and moves each line by the lines added or removed above it. A finding whose own line you have edited since the review is reported as changed, with no line, so nothing points at code the review never saw. If the reviewed commit is missing locally, the command fetches the pull request's head without prompting for credentials (`--no-fetch` skips this) and otherwise reports the findings as unverified. +- **`--write`** keeps `.autter/findings.md` up to date: a summary, location, next steps and dashboard link for every finding, grouped into findings in your code, findings on lines you have changed since the review, and findings about the pull request. `.autter/` is added to `.git/info/exclude`. The file only changes when the findings do. +- **`--json`** prints the response with a `local` placement (`status`, `line`) on every finding. +- **VS Code extension**: findings appear as squiggles and Problems entries, with the title after the line (`autter.findings.display`: `inline`, `problems` or `off`). Quick fixes copy a fix prompt for your agent, open the finding in the dashboard, or dismiss it. A finding is dropped as soon as you edit its line, and moves when you add or remove lines above it. The status bar shows the count and opens the findings file; when you are signed out it reads **autter: Sign in** and runs `autter login` in a terminal. +- **`autter review`** reviews what a pull request from this branch would contain (the diff from the merge base with the default branch, committed or not, untracked files included; or `--uncommitted`, `--base `, or paths) with the core of the PR review: secrets, static security, auth and permissions, race conditions, and deep correctness when the organization has it on. The organization's review settings apply. Up to 60 files. The reviewed copy of each file is saved as a git blob, so `autter findings` places the saved result on your working tree and marks lines you have edited since as changed. The result is kept in `.autter/local-review.json` and shown for the branch it was made on. +- **VS Code: Autter: Review My Changes** saves your files, runs `autter review` with a progress notification (cancellable), and shows its findings inline, labelled "local review". diff --git a/src/commands/arg_parser.rs b/src/commands/arg_parser.rs index 0537ca7..e47e83e 100644 --- a/src/commands/arg_parser.rs +++ b/src/commands/arg_parser.rs @@ -906,6 +906,70 @@ autter login [--token ] summary: "Search and read saved debugging investigations", body: "autter threads [search ] [--repo ] [--org ] [--offset ] [--json]\nautter threads show [--org ] [--json]\n\n Search your questions and answers across Dashboard and CLI. Lists 50 threads\n at a time. Continue an investigation with autter ask --thread .", }, + HelpEntry { + name: "findings", + aliases: &[], + summary: "Review findings for this branch's pull request, on your working tree's lines", + body: "\ +autter findings [--write] [--branch ] [--pr ] [--repo ] + [--org ] [--no-fetch] [--json] + + Prints the Autter review findings of the pull request open for the current + branch: severity, file:line and title, most severe first. + + Line numbers are moved to match your working tree: the command diffs the + commit Autter reviewed against your files. A finding whose line you have + edited since the review is listed as changed, with no line, because the + review never saw the new code. If the reviewed commit is missing locally, + the command fetches the pull request's head (never prompting for + credentials); --no-fetch skips that. + + --write Also write .autter/findings.md: a summary, location, next + steps and a dashboard link for every finding. .autter/ is + added to .git/info/exclude so it is never committed. + --branch Another branch's pull request + --pr A pull request by number, open or closed + --repo The repository, when the remote doesn't identify it + --org Another organization you belong to + --json The response as JSON, with a `local` placement per finding + + Uses your autter login. The autter VS Code extension shows the same + findings inline.", + }, + HelpEntry { + name: "review", + aliases: &[], + summary: "Review your changes before you open a pull request", + body: "\ +autter review [...] [--base | --uncommitted] [--write] [--repo ] + [--org ] [--json] + + Runs the core of Autter's pull request review on your changes, so you learn + about problems before a pull request exists: secrets, static security, + auth and permissions, race conditions, and (when your organization has it + on) the deep correctness pass. Your organization's review settings apply. + It takes a minute or two. + + By default it reviews what a pull request from this branch would contain: + everything since the merge base with the default branch (origin/HEAD, + else main or master), committed or not, untracked files included. Up to + 60 files; pass paths to review fewer. + + The result is kept in .autter/local-review.json. `autter findings` and the + VS Code extension show it next to the pull request's findings, with lines + moved to follow your edits; a finding whose line you have edited since is + listed as changed. + + ... Only changes under these files or directories + --base Compare with the merge base of this branch or commit + --uncommitted Only changes not committed yet (compared with HEAD) + --write Also write .autter/findings.md + --repo The repository, when the remote doesn't identify it + --org Another organization you belong to + --json The result as JSON, with a `local` placement per finding + + Uses your autter login. The files you review are sent to Autter.", + }, HelpEntry { name: "lineage", aliases: &[], diff --git a/src/commands/autter_handlers.rs b/src/commands/autter_handlers.rs index 8f2d3f7..5456c17 100644 --- a/src/commands/autter_handlers.rs +++ b/src/commands/autter_handlers.rs @@ -147,6 +147,8 @@ pub fn handle_autter(args: &[String]) { | "logout" | "whoami" | "ask" + | "findings" + | "review" | "logs" | "threads" | "badge" @@ -219,6 +221,8 @@ pub fn handle_autter(args: &[String]) { } None => commands::lineage::handle(&args[1..]), }, + "findings" => commands::findings::handle(&args[1..]), + "review" => commands::review::handle(&args[1..]), "memory" => commands::memory::handle(&args[1..]), "tests" => commands::generated_tests::handle(&args[1..]), "context" => commands::context::handle(&args[1..]), @@ -495,6 +499,7 @@ const AUTTER_COMMANDS: &[&str] = &[ "fetch-notes", "fetch_authorship_notes", "file-changes", + "findings", "flush-metrics-db", "git-hooks", "git-path", @@ -516,6 +521,7 @@ const AUTTER_COMMANDS: &[&str] = &[ "personal_dashboard", "push-authorship-notes", "push_authorship_notes", + "review", "setup", "show", "show-prompt", diff --git a/src/commands/findings.rs b/src/commands/findings.rs new file mode 100644 index 0000000..3cc09dc --- /dev/null +++ b/src/commands/findings.rs @@ -0,0 +1,1521 @@ +//! `autter findings`: the review findings of the pull request open for the +//! current branch, placed on the lines of your working tree. +//! +//! Reads `GET /api/cli/orgs//findings?repository=&branch=` +//! with the sign-in and organization choice of `autter ask`. Every finding's +//! line is a line of the file at the commit the review ran on +//! (`review.headSha`). The command diffs that commit against the working tree +//! (`git diff -U0 `) and moves each line by the lines added and +//! removed above it. A finding whose own line changed since the review is +//! marked `changed` and given no line: the editor must never point at code the +//! review did not see. +//! +//! `--write` also writes `.autter/findings.md` (summary, location, next steps +//! and a link for each finding) and keeps `.autter/` out of git through +//! `.git/info/exclude`. `--json` prints the response with a `local` object on +//! every finding; the VS Code extension reads it. +use crate::api::client::ApiContext; +use crate::commands::arg_parser::{self, ScanMode}; +use crate::commands::ask::{component, org_api_context}; +use crate::error::AutterError; +use crate::git::repository::{Repository, exec_git, exec_git_allow_nonzero}; +use serde_json::{Value, json}; +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +pub(crate) const TIMEOUT_SECS: u64 = 30; +/// A missing reviewed commit is fetched from the PR's ref at most this long. +const FETCH_TIMEOUT: Duration = Duration::from_secs(30); +pub(crate) const FINDINGS_DIR: &str = ".autter"; +pub(crate) const FINDINGS_FILE: &str = "findings.md"; + +const NOT_SIGNED_IN: &str = "Autter did not accept your sign-in for this organization (HTTP 401). Sign in with `autter login` first, or choose an organization with --org ."; + +#[derive(Debug, Default, PartialEq)] +pub(crate) struct Options { + branch: Option, + pr: Option, + repository: Option, + organization: Option, + write: bool, + no_fetch: bool, +} + +fn parse_options(args: &[String]) -> Result { + let mut options = Options::default(); + let mut index = 0; + while index < args.len() { + let arg = args[index].as_str(); + match arg { + "--write" => { + options.write = true; + index += 1; + continue; + } + "--no-fetch" => { + options.no_fetch = true; + index += 1; + continue; + } + "--branch" | "--pr" | "--repo" | "--org" => {} + _ => return Err(format!("unknown option for findings: {arg}")), + } + let value = args + .get(index + 1) + .map(|value| value.trim()) + .filter(|value| !value.starts_with("--") && !value.is_empty()) + .ok_or_else(|| format!("{arg} requires a value"))?; + match arg { + "--branch" => options.branch = Some(value.to_owned()), + "--pr" => { + let number = value.trim_start_matches('#').parse::().ok(); + options.pr = Some( + number + .filter(|n| *n > 0) + .ok_or("--pr takes a pull request number")?, + ); + } + "--repo" => options.repository = Some(value.to_owned()), + _ => options.organization = Some(value.to_owned()), + } + index += 2; + } + Ok(options) +} + +// --------------------------------------------------------------------------- +// Line mapping: reviewed commit → working tree +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq)] +struct Hunk { + old_start: u32, + old_count: u32, + new_count: u32, +} + +#[derive(Debug, Default, PartialEq)] +pub(crate) struct FileDiff { + deleted: bool, + /// A binary file that differs: no line can be trusted. + binary: bool, + hunks: Vec, +} + +/// Where a finding sits in the working tree. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) enum Placement { + /// Same line as in the review. + Unchanged(u32), + /// The line is untouched; lines above it were added or removed. + Moved(u32), + /// The line itself was edited or removed since the review. + Changed, + /// The file no longer exists. + FileDeleted, + /// The reviewed commit is not available locally, so the line can't be checked. + Unverified, + /// About the PR or a removed (base) line: no place in the working tree. + NoLine, +} + +impl Placement { + fn status(self) -> &'static str { + match self { + Placement::Unchanged(_) => "unchanged", + Placement::Moved(_) => "moved", + Placement::Changed => "changed", + Placement::FileDeleted => "file_deleted", + Placement::Unverified => "unverified", + Placement::NoLine => "no_line", + } + } + + fn line(self) -> Option { + match self { + Placement::Unchanged(line) | Placement::Moved(line) => Some(line), + _ => None, + } + } +} + +/// `-a,b` / `+c,d` of a hunk header; a missing count is 1. +fn parse_range(range: &str) -> Option<(u32, u32)> { + let (start, count) = match range.split_once(',') { + Some((start, count)) => (start, count.parse().ok()?), + None => (range, 1), + }; + Some((start.parse().ok()?, count)) +} + +fn parse_hunk_header(line: &str) -> Option { + let rest = line.strip_prefix("@@ -")?; + let (old, rest) = rest.split_once(" +")?; + let (new, _) = rest.split_once(" @@")?; + let (old_start, old_count) = parse_range(old)?; + let (_, new_count) = parse_range(new)?; + Some(Hunk { + old_start, + old_count, + new_count, + }) +} + +/// A path from a `---`/`+++` header: strip the `a/`/`b/` prefix, the tab git +/// adds after names with spaces, and C quoting. +fn header_path(raw: &str, prefix: &str) -> Option { + let raw = raw.trim_end_matches('\t'); + if raw == "/dev/null" { + return None; + } + let unquoted = if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') { + unquote_c(&raw[1..raw.len() - 1]) + } else { + raw.to_owned() + }; + Some( + unquoted + .strip_prefix(prefix) + .unwrap_or(&unquoted) + .to_owned(), + ) +} + +fn unquote_c(s: &str) -> String { + let mut bytes = Vec::with_capacity(s.len()); + let mut iter = s.bytes().peekable(); + while let Some(b) = iter.next() { + if b != b'\\' { + bytes.push(b); + continue; + } + match iter.next() { + Some(b'n') => bytes.push(b'\n'), + Some(b't') => bytes.push(b'\t'), + Some(b'"') => bytes.push(b'"'), + Some(b'\\') => bytes.push(b'\\'), + Some(d @ b'0'..=b'7') => { + let mut value = (d - b'0') as u32; + for _ in 0..2 { + match iter.peek() { + Some(n @ b'0'..=b'7') => { + value = value * 8 + (*n - b'0') as u32; + iter.next(); + } + _ => break, + } + } + bytes.push(value as u8); + } + Some(other) => { + bytes.push(b'\\'); + bytes.push(other); + } + None => bytes.push(b'\\'), + } + } + String::from_utf8_lossy(&bytes).into_owned() +} + +/// Parse `git diff -U0 --no-renames ` output into hunks per old path. +/// `---`/`+++` are read only in a file's header, so a removed line that +/// starts with `--` is never mistaken for one. +pub(crate) fn parse_diff(diff: &str) -> HashMap { + let mut files: HashMap = HashMap::new(); + let mut current: Option = None; + let mut in_header = false; + let mut pending_old: Option = None; + for line in diff.lines() { + if line.starts_with("diff --git ") { + in_header = true; + current = None; + pending_old = None; + continue; + } + if in_header { + if let Some(raw) = line.strip_prefix("--- ") { + pending_old = header_path(raw, "a/"); + continue; + } + if let Some(raw) = line.strip_prefix("+++ ") { + if let Some(old) = pending_old.take() { + let entry = files.entry(old.clone()).or_default(); + entry.deleted = header_path(raw, "b/").is_none(); + current = Some(old); + } + continue; + } + if line.starts_with("Binary files ") { + // `Binary files a/x and /dev/null differ` — the path is not + // reliably parseable; mark it by the preceding `diff --git`. + if let Some(path) = binary_path(line) { + let entry = files.entry(path).or_default(); + entry.binary = true; + entry.deleted = line.ends_with(" and /dev/null differ"); + } + continue; + } + } + if line.starts_with("@@ ") { + in_header = false; + if let (Some(path), Some(hunk)) = (current.as_ref(), parse_hunk_header(line)) + && let Some(entry) = files.get_mut(path) + { + entry.hunks.push(hunk); + } + } + } + for file in files.values_mut() { + file.hunks.sort_by_key(|h| h.old_start); + } + files +} + +fn binary_path(line: &str) -> Option { + let rest = line.strip_prefix("Binary files ")?; + let (old, _) = rest.split_once(" and ")?; + header_path(old, "a/") +} + +/// Where line `line` of the reviewed file is now, given that file's diff. +pub(crate) fn map_line(diff: Option<&FileDiff>, line: u32) -> Placement { + let Some(diff) = diff else { + return Placement::Unchanged(line); + }; + if diff.deleted { + return Placement::FileDeleted; + } + if diff.binary { + return Placement::Changed; + } + let mut delta: i64 = 0; + for hunk in &diff.hunks { + if hunk.old_count == 0 { + // Pure insertion after line `old_start`. + if hunk.old_start < line { + delta += hunk.new_count as i64; + continue; + } + break; + } + let end = hunk.old_start + hunk.old_count - 1; + if end < line { + delta += hunk.new_count as i64 - hunk.old_count as i64; + } else if hunk.old_start <= line { + return Placement::Changed; + } else { + break; + } + } + let moved = line as i64 + delta; + if moved < 1 { + return Placement::Changed; + } + if delta == 0 { + Placement::Unchanged(line) + } else { + Placement::Moved(moved as u32) + } +} + +pub(crate) fn finding_has_line(finding: &Value) -> bool { + finding["line"].as_u64().unwrap_or(0) > 0 + && finding["side"].as_str() != Some("LEFT") + && !finding["prScoped"].as_bool().unwrap_or(false) + && finding["path"].as_str().is_some_and(|p| !p.is_empty()) +} + +/// Place every finding (sets `finding.local = {status, line}`). +fn place_findings(findings: &mut [Value], diffs: Option<&HashMap>) { + for finding in findings.iter_mut() { + let placement = if !finding_has_line(finding) { + Placement::NoLine + } else if let Some(diffs) = diffs { + let path = finding["path"].as_str().unwrap_or_default(); + let line = finding["line"].as_u64().unwrap_or(0) as u32; + map_line(diffs.get(path), line) + } else { + Placement::Unverified + }; + finding["local"] = json!({ "status": placement.status(), "line": placement.line() }); + } +} + +// --------------------------------------------------------------------------- +// Git +// --------------------------------------------------------------------------- + +pub(crate) fn git_args(repo: &Repository, rest: &[&str]) -> Vec { + let mut args = repo.global_args_for_exec(); + args.extend(rest.iter().map(|s| (*s).to_owned())); + args +} + +fn has_commit(repo: &Repository, sha: &str) -> bool { + let spec = format!("{sha}^{{commit}}"); + exec_git_allow_nonzero(&git_args(repo, &["cat-file", "-e", &spec])) + .map(|out| out.status.success()) + .unwrap_or(false) +} + +/// Fetch `refs/pull//head` (GitHub keeps every pushed head there) so the +/// reviewed commit exists locally. Never prompts for credentials, gives up +/// after [`FETCH_TIMEOUT`], and writes no local ref (only FETCH_HEAD). +fn fetch_pull_head(repo: &Repository, pr: u64) -> bool { + let Ok(Some(remote)) = repo.get_default_remote() else { + return false; + }; + let refspec = format!("refs/pull/{pr}/head"); + let args = git_args( + repo, + &[ + "fetch", + "--quiet", + "--no-tags", + "--no-write-fetch-head", + &remote, + &refspec, + ], + ); + let mut command = std::process::Command::new(crate::config::Config::get().git_cmd()); + command + .args(&args) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GCM_INTERACTIVE", "never") + .env("GIT_ASKPASS", "") + .env("SSH_ASKPASS", "") + .env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + let Ok(mut child) = command.spawn() else { + return false; + }; + let started = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => return status.success(), + Ok(None) if started.elapsed() < FETCH_TIMEOUT => { + std::thread::sleep(Duration::from_millis(100)); + } + _ => { + let _ = child.kill(); + let _ = child.wait(); + return false; + } + } + } +} + +/// The diff from `sha` to the working tree for `paths`. +fn working_tree_diff( + repo: &Repository, + sha: &str, + paths: &BTreeSet, +) -> Result, AutterError> { + if paths.is_empty() { + return Ok(HashMap::new()); + } + let mut args = git_args( + repo, + &[ + "-c", + "core.quotePath=false", + "diff", + "-U0", + "--no-color", + "--no-renames", + "--no-ext-diff", + "--no-textconv", + sha, + "--", + ], + ); + args.extend(paths.iter().map(|p| format!(":(literal){p}"))); + let output = exec_git(&args)?; + Ok(parse_diff(&String::from_utf8_lossy(&output.stdout))) +} + +// --------------------------------------------------------------------------- +// Fetching +// --------------------------------------------------------------------------- + +fn findings_path(slug: &str, repository: &str, branch: Option<&str>, pr: Option) -> String { + let mut query = url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("repository", repository); + if let Some(branch) = branch { + query.append_pair("branch", branch); + } + if let Some(pr) = pr { + query.append_pair("pr", &pr.to_string()); + } + format!( + "/api/cli/orgs/{}/findings?{}", + component(slug), + query.finish() + ) +} + +fn response_value(code: u16, body: &str) -> Result { + let value: Option = serde_json::from_str(body).ok(); + if code == 200 + && let Some(value) = value + { + return Ok(value); + } + if code == 401 { + return Err(AutterError::Generic(NOT_SIGNED_IN.into())); + } + let message = value + .as_ref() + .and_then(|v| v["message"].as_str().or(v["error"].as_str())) + .map(str::to_owned); + Err(AutterError::Generic(match (code, message) { + (404, Some(message)) if message.contains("Unknown") || message.contains("not found") => { + message + } + (404, None) => "Findings API not found (HTTP 404). Update the API deployment if this command is unavailable.".into(), + (_, message) => format!( + "HTTP {code}: {}", + message.as_deref().unwrap_or("Findings request failed") + ), + })) +} + +/// Everything `run` needs from the local repository. +pub(crate) struct Local { + pub(crate) repo: Repository, + pub(crate) workdir: PathBuf, + pub(crate) repository: String, + pub(crate) branch: Option, +} + +/// The repository you are in, its remote (or `repository`) and branch (or `branch`). +pub(crate) fn local_context_for( + repository: Option, + branch: Option, +) -> Result { + let repo = crate::git::repository::find_repository(&Vec::::new()) + .map_err(|_| AutterError::Generic("Run this inside a git repository.".into()))?; + let workdir = repo.workdir()?; + let repository = match repository { + Some(repository) => repository, + None => crate::authorship::post_commit::current_repo_url(&repo).ok_or_else(|| { + AutterError::Generic("This repository has no remote. Pass --repo .".into()) + })?, + }; + let branch = match branch { + Some(branch) => Some(branch), + None => repo + .head() + .ok() + .and_then(|head| head.shorthand().ok()) + .filter(|name| !name.is_empty() && name != "HEAD"), + }; + Ok(Local { + repo, + workdir, + repository, + branch, + }) +} + +fn local_context(options: &Options) -> Result { + let local = local_context_for(options.repository.clone(), options.branch.clone())?; + if local.branch.is_none() && options.pr.is_none() { + return Err(AutterError::Generic( + "HEAD is detached. Check out a branch, or pass --branch or --pr ." + .into(), + )); + } + Ok(local) +} + +/// Fetch the findings and place them on the working tree. +fn collect(options: &Options, local: &Local) -> Result { + let (context, slug): (ApiContext, String) = + org_api_context(options.organization.as_deref(), TIMEOUT_SECS)?; + collect_with(&context, &slug, options, local) +} + +/// [`collect`] with a signed-in context, for `autter review --write`. +pub(crate) fn collect_for_branch( + context: &ApiContext, + slug: &str, + local: &Local, +) -> Result { + let options = Options { + no_fetch: true, + ..Options::default() + }; + collect_with(context, slug, &options, local) +} + +fn collect_with( + context: &ApiContext, + slug: &str, + options: &Options, + local: &Local, +) -> Result { + let branch = if options.pr.is_some() { + None + } else { + local.branch.as_deref() + }; + let mut result = if branch.is_none() && options.pr.is_none() { + json!({ "pullRequest": null, "review": null, "findings": [] }) + } else { + let path = findings_path(slug, &local.repository, branch, options.pr); + let response = context.clone().with_timeout(TIMEOUT_SECS).get(&path)?; + let body = response + .as_str() + .map_err(|error| AutterError::Generic(error.to_string()))?; + response_value(response.status_code, body)? + }; + + let reviewed = result["review"]["headSha"].as_str().map(str::to_owned); + let pr_number = result["pullRequest"]["number"].as_u64(); + let mut available = false; + let mut diffs = None; + if let Some(sha) = reviewed.as_deref() { + available = has_commit(&local.repo, sha); + if !available + && !options.no_fetch + && let Some(pr) = pr_number + { + available = fetch_pull_head(&local.repo, pr) && has_commit(&local.repo, sha); + } + if available { + let paths: BTreeSet = result["findings"] + .as_array() + .into_iter() + .flatten() + .filter(|f| finding_has_line(f)) + .filter_map(|f| f["path"].as_str().map(str::to_owned)) + .collect(); + diffs = Some(working_tree_diff(&local.repo, sha, &paths)?); + } + } + if let Some(findings) = result["findings"].as_array_mut() { + place_findings(findings, diffs.as_ref()); + } + result["local"] = json!({ + "branch": local.branch, + "repository": local.repository, + "workdir": local.workdir.to_string_lossy(), + "reviewedCommitAvailable": available, + "generatedAt": chrono::Utc::now().to_rfc3339(), + }); + attach_local_review(&mut result, local); + Ok(result) +} + +// --------------------------------------------------------------------------- +// The saved local review (`autter review`) +// --------------------------------------------------------------------------- + +pub(crate) const LOCAL_REVIEW_FILE: &str = "local-review.json"; + +pub(crate) fn local_review_path(local: &Local) -> PathBuf { + local.workdir.join(FINDINGS_DIR).join(LOCAL_REVIEW_FILE) +} + +/// Write each path's working-tree content into the object database and +/// return its blob id (`git hash-object -w --stdin-paths`). Missing files are +/// left out. +pub(crate) fn snapshot_blobs( + local: &Local, + paths: &[String], +) -> Result, AutterError> { + use std::io::Write; + let present: Vec<&String> = paths + .iter() + .filter(|p| local.workdir.join(p).is_file()) + .collect(); + if present.is_empty() { + return Ok(HashMap::new()); + } + let args = git_args(&local.repo, &["hash-object", "-w", "--stdin-paths"]); + let mut child = std::process::Command::new(crate::config::Config::get().git_cmd()) + .args(&args) + .current_dir(&local.workdir) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn()?; + { + let mut stdin = child + .stdin + .take() + .ok_or_else(|| AutterError::Generic("Could not write to git hash-object.".into()))?; + for path in &present { + writeln!(stdin, "{path}")?; + } + } + let output = child.wait_with_output()?; + if !output.status.success() { + return Err(AutterError::Generic( + "git hash-object failed while saving the reviewed files.".into(), + )); + } + let shas: Vec = String::from_utf8_lossy(&output.stdout) + .lines() + .map(str::to_owned) + .collect(); + Ok(present + .into_iter() + .cloned() + .zip(shas) + .collect::>()) +} + +/// Place a saved local review's findings on the working tree: each file is +/// compared with the copy the review saw (a blob saved at review time). +pub(crate) fn place_local_findings(local: &Local, saved: &Value) -> Vec { + let mut findings: Vec = saved["result"]["findings"] + .as_array() + .cloned() + .unwrap_or_default(); + let reviewed: HashMap = saved["files"] + .as_object() + .map(|files| { + files + .iter() + .filter_map(|(path, sha)| sha.as_str().map(|sha| (path.clone(), sha.to_owned()))) + .collect() + }) + .unwrap_or_default(); + let paths: Vec = findings + .iter() + .filter(|f| finding_has_line(f)) + .filter_map(|f| f["path"].as_str().map(str::to_owned)) + .collect::>() + .into_iter() + .collect(); + let current = snapshot_blobs(local, &paths).unwrap_or_default(); + // Diffs keyed by path: None when the file is gone, Some(empty) when unchanged. + let mut diffs: HashMap> = HashMap::new(); + for path in &paths { + let Some(before) = reviewed.get(path) else { + continue; + }; + let diff = match current.get(path) { + None => None, + Some(now) if now == before => Some(FileDiff::default()), + Some(now) => { + let args = git_args( + &local.repo, + &[ + "diff", + "-U0", + "--no-color", + "--no-ext-diff", + "--no-textconv", + before, + now, + ], + ); + match exec_git(&args) { + Ok(out) => parse_diff(&String::from_utf8_lossy(&out.stdout)) + .remove(before.as_str()) + .or(Some(FileDiff::default())), + Err(_) => continue, + } + } + }; + diffs.insert(path.clone(), diff); + } + for finding in findings.iter_mut() { + let placement = if !finding_has_line(finding) { + Placement::NoLine + } else { + let path = finding["path"].as_str().unwrap_or_default(); + let line = finding["line"].as_u64().unwrap_or(0) as u32; + match diffs.get(path) { + Some(Some(diff)) => map_line(Some(diff), line), + Some(None) => Placement::FileDeleted, + None => Placement::Unverified, + } + }; + finding["local"] = json!({ "status": placement.status(), "line": placement.line() }); + } + findings +} + +/// Add `localReview` (the saved `autter review` result, placed on the working +/// tree) when there is one for the branch you are on. +pub(crate) fn attach_local_review(result: &mut Value, local: &Local) { + let Ok(text) = std::fs::read_to_string(local_review_path(local)) else { + return; + }; + let Ok(saved) = serde_json::from_str::(&text) else { + return; + }; + if saved["branch"].as_str() != local.branch.as_deref() { + return; + } + let findings = place_local_findings(local, &saved); + result["localReview"] = json!({ + "reviewId": saved["result"]["review"]["reviewId"], + "reviewedAt": saved["reviewedAt"], + "base": saved["base"], + "baseRef": saved["baseRef"], + "files": saved["files"].as_object().map(|f| f.len()).unwrap_or(0), + "bundles": saved["result"]["review"]["bundles"], + "findings": findings, + }); +} + +// --------------------------------------------------------------------------- +// findings.md +// --------------------------------------------------------------------------- + +/// Text without control characters (keeps newlines and tabs). +fn printable(text: &str) -> String { + text.chars() + .filter(|c| !c.is_control() || *c == '\n' || *c == '\t') + .collect() +} + +pub(crate) fn one_line(text: &str) -> String { + printable(text) + .split_whitespace() + .collect::>() + .join(" ") +} + +pub(crate) fn short_sha(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +fn severity_label(finding: &Value) -> &'static str { + match finding["severity"].as_str() { + Some("critical") => "Critical", + Some("warning") => "Warning", + _ => "Info", + } +} + +fn location(finding: &Value) -> String { + let path = finding["path"].as_str().unwrap_or_default(); + match finding["local"]["line"].as_u64() { + Some(line) => format!("{path}:{line}"), + None if path.is_empty() => String::new(), + None => path.to_owned(), + } +} + +/// `2026-11-17T09:12:34.000Z` → `2026-11-17 09:12 UTC`. +fn when(at: &str) -> String { + format!("{} UTC", at.get(..16).unwrap_or(at).replace('T', " ")) +} + +/// Indent every line of a Markdown block so it stays inside a list item. +fn indented(text: &str) -> String { + printable(text.trim()) + .lines() + .map(|line| { + if line.is_empty() { + String::new() + } else { + format!(" {line}") + } + }) + .collect::>() + .join("\n") +} + +fn render_markdown_finding(out: &mut String, finding: &Value, number: usize) { + let title = one_line(finding["title"].as_str().unwrap_or("Finding")); + out.push_str(&format!( + "{number}. **{}: {title}**\n", + severity_label(finding) + )); + let loc = location(finding); + if !loc.is_empty() { + let note = match finding["local"]["status"].as_str() { + Some("moved") => format!( + " (line {} when reviewed)", + finding["line"].as_u64().unwrap_or(0) + ), + Some("changed") => format!( + ", line {} when reviewed; you have edited that line since", + finding["line"].as_u64().unwrap_or(0) + ), + Some("file_deleted") => ", deleted since the review".into(), + Some("unverified") => format!( + ", line {} when reviewed; the reviewed copy isn't available locally to check it", + finding["line"].as_u64().unwrap_or(0) + ), + _ => String::new(), + }; + out.push_str(&format!(" - Location: `{loc}`{note}\n")); + } + let body = finding["body"].as_str().unwrap_or_default(); + if !body.trim().is_empty() { + out.push_str(" - Summary:\n\n"); + out.push_str(&indented(body)); + out.push_str("\n\n"); + } + if let Some(next) = finding["fixPrompt"] + .as_str() + .filter(|s| !s.trim().is_empty()) + { + out.push_str(" - Next steps:\n\n"); + out.push_str(&indented(next)); + out.push_str("\n\n"); + } + if let Some(url) = finding["url"].as_str() { + out.push_str(&format!(" - Link: {url}\n")); + } + // One blank line between items. + while out.ends_with("\n\n") { + out.pop(); + } + out.push('\n'); +} + +fn status_of(finding: &Value) -> &str { + finding["local"]["status"].as_str().unwrap_or_default() +} + +/// The counts line and the findings grouped into in-your-code, changed since +/// the review, and about the change as a whole. +fn render_markdown_groups(out: &mut String, findings: &[Value], number: &mut usize, whole: &str) { + if findings.is_empty() { + out.push_str("No findings.\n\n"); + return; + } + let pick = |statuses: &[&str]| -> Vec<&Value> { + findings + .iter() + .filter(|f| statuses.contains(&status_of(f))) + .collect() + }; + let in_code = pick(&["unchanged", "moved", "unverified"]); + let changed = pick(&["changed", "file_deleted"]); + let general = pick(&["no_line"]); + let critical = findings + .iter() + .filter(|f| f["severity"].as_str() == Some("critical")) + .count(); + out.push_str(&format!( + "**{} finding{}** ({critical} critical): {} in your code, {} on lines you have changed since the review, {} about the {whole}.\n\n", + findings.len(), + if findings.len() == 1 { "" } else { "s" }, + in_code.len(), + changed.len(), + general.len(), + )); + let about = format!("About the {whole}"); + for (heading, list) in [ + ("In your code", &in_code), + ("Changed since the review (may be fixed)", &changed), + (about.as_str(), &general), + ] { + if list.is_empty() { + continue; + } + out.push_str(&format!("### {heading}\n\n")); + for finding in list.iter() { + *number += 1; + render_markdown_finding(out, finding, *number); + } + } +} + +fn findings_of(value: &Value) -> Vec { + value["findings"].as_array().cloned().unwrap_or_default() +} + +pub(crate) fn render_markdown(result: &Value) -> String { + let mut out = String::from("# Autter findings\n\n"); + out.push_str("\n\n"); + // No time of the run in here: the file only changes when the findings + // do, so an editor showing it doesn't reload on every refresh. + let branch = result["local"]["branch"].as_str().unwrap_or("this branch"); + let mut number = 0; + + out.push_str("## Pull request review\n\n"); + let pr = &result["pullRequest"]; + if pr.is_null() { + out.push_str(&format!( + "No open pull request for `{}` yet. Run `autter review` to review your changes before you open one.\n\n", + one_line(branch) + )); + } else { + let pr_number = pr["number"].as_u64().unwrap_or(0); + let title = one_line(pr["title"].as_str().unwrap_or_default()); + match pr["url"].as_str() { + Some(url) => out.push_str(&format!("Pull request [#{pr_number} {title}]({url})")), + None => out.push_str(&format!("Pull request #{pr_number} {title}")), + } + out.push_str(&format!(" on `{}`.\n\n", one_line(branch))); + let review = &result["review"]; + if review.is_null() { + out.push_str("Autter has not reviewed this pull request yet.\n\n"); + } else { + let sha = review["headSha"].as_str().unwrap_or_default(); + out.push_str(&format!("Reviewed commit `{}`", short_sha(sha))); + if let Some(at) = review["reviewedAt"].as_str() { + out.push_str(&format!(" at {}", when(at))); + } + if review["stale"].as_bool().unwrap_or(false) { + out.push_str(" (an older push: the newest one has not been reviewed yet)"); + } + out.push_str(".\n\n"); + render_markdown_groups(&mut out, &findings_of(result), &mut number, "pull request"); + } + } + + let local_review = &result["localReview"]; + if !local_review.is_null() { + out.push_str("## Local review\n\n"); + out.push_str("Your changes as `autter review` saw them"); + let base = match ( + local_review["baseRef"].as_str(), + local_review["base"].as_str(), + ) { + (Some(name), _) if name != "HEAD" => Some(one_line(name)), + (_, Some(sha)) => Some(short_sha(sha).to_owned()), + _ => None, + }; + if let Some(base) = base { + out.push_str(&format!(", compared with `{base}`")); + } + if let Some(at) = local_review["reviewedAt"].as_str() { + out.push_str(&format!(", at {}", when(at))); + } + out.push_str(". A local review runs the core checks before a pull request exists; its findings are not verified.\n\n"); + render_markdown_groups( + &mut out, + &findings_of(local_review), + &mut number, + "change as a whole", + ); + } + out +} + +/// `exclude` with `/.autter/` added, or `None` when it is already there. +fn with_exclude_entry(existing: &str) -> Option { + let entry = format!("/{FINDINGS_DIR}/"); + if existing.lines().any(|line| line.trim() == entry) { + return None; + } + let mut text = existing.to_owned(); + if !text.is_empty() && !text.ends_with('\n') { + text.push('\n'); + } + text.push_str(&format!( + "# autter findings (autter findings --write)\n{entry}\n" + )); + Some(text) +} + +/// Add `/.autter/` to `.git/info/exclude` (once) so the file never gets committed. +pub(crate) fn exclude_findings_dir(repo: &Repository) -> std::io::Result<()> { + let info = repo.common_dir().join("info"); + let exclude = info.join("exclude"); + let existing = std::fs::read_to_string(&exclude).unwrap_or_default(); + let Some(text) = with_exclude_entry(&existing) else { + return Ok(()); + }; + std::fs::create_dir_all(&info)?; + std::fs::write(exclude, text) +} + +pub(crate) fn write_markdown(local: &Local, markdown: &str) -> Result { + let dir = local.workdir.join(FINDINGS_DIR); + std::fs::create_dir_all(&dir)?; + let path = dir.join(FINDINGS_FILE); + write_if_changed(&path, markdown)?; + // Best effort: the file is still useful when info/exclude can't be written. + let _ = exclude_findings_dir(&local.repo); + Ok(path) +} + +/// Rewrite only when the text changed, so editors watching it don't reload for nothing. +pub(crate) fn write_if_changed(path: &Path, text: &str) -> std::io::Result<()> { + if std::fs::read_to_string(path).ok().as_deref() == Some(text) { + return Ok(()); + } + let mut tmp = path.as_os_str().to_owned(); + tmp.push(".tmp"); + let tmp = PathBuf::from(tmp); + std::fs::write(&tmp, text)?; + std::fs::rename(tmp, path) +} + +// --------------------------------------------------------------------------- +// Terminal output +// --------------------------------------------------------------------------- + +/// One line per finding with a place in the code (or about the change), then +/// how many are on lines changed since the review. +pub(crate) fn render_text_findings(out: &mut String, findings: &[Value]) { + if findings.is_empty() { + out.push_str("No findings.\n"); + return; + } + let mut changed = 0; + for finding in findings { + if matches!(status_of(finding), "changed" | "file_deleted") { + changed += 1; + continue; + } + let loc = location(finding); + out.push_str(&format!( + "{:<8} {}{}\n", + severity_label(finding).to_lowercase(), + if loc.is_empty() { + String::new() + } else { + format!("{loc} ") + }, + one_line(finding["title"].as_str().unwrap_or_default()) + )); + } + if changed > 0 { + out.push_str(&format!( + "\n{changed} finding{} on lines you have changed since the review (see --write or --json).\n", + if changed == 1 { " is" } else { "s are" } + )); + } +} + +fn render_text(result: &Value) -> String { + let mut out = String::new(); + let pr = &result["pullRequest"]; + let branch = result["local"]["branch"].as_str().unwrap_or("this branch"); + if pr.is_null() { + out.push_str(&format!( + "No open pull request for {} yet. Run `autter review` to review your changes before you open one.\n", + one_line(branch) + )); + } else { + out.push_str(&format!( + "PR #{} {}\n", + pr["number"].as_u64().unwrap_or(0), + one_line(pr["title"].as_str().unwrap_or_default()) + )); + if let Some(url) = pr["url"].as_str() { + out.push_str(&format!("{url}\n")); + } + let review = &result["review"]; + if review.is_null() { + out.push_str("Autter has not reviewed this pull request yet.\n"); + } else { + out.push_str(&format!( + "Reviewed {}{}\n\n", + short_sha(review["headSha"].as_str().unwrap_or_default()), + if review["stale"].as_bool().unwrap_or(false) { + " (an older push; the newest is not reviewed yet)" + } else { + "" + } + )); + render_text_findings(&mut out, &findings_of(result)); + if result["local"]["reviewedCommitAvailable"].as_bool() == Some(false) { + out.push_str( + "\nThe reviewed commit isn't available locally, so lines may have moved. Run `git fetch` and try again.\n", + ); + } + } + } + let local_review = &result["localReview"]; + if !local_review.is_null() { + out.push_str(&format!( + "\nLocal review{}\n\n", + local_review["reviewedAt"] + .as_str() + .map(|at| format!(" ({})", when(at))) + .unwrap_or_default() + )); + render_text_findings(&mut out, &findings_of(local_review)); + } + out +} + +fn run(options: Options) -> Result<(), AutterError> { + let local = local_context(&options)?; + let mut result = collect(&options, &local)?; + if options.write { + let path = write_markdown(&local, &render_markdown(&result))?; + result["local"]["markdownPath"] = json!(path.to_string_lossy()); + } + if arg_parser::json() { + println!("{}", serde_json::to_string_pretty(&result)?); + } else { + print!("{}", render_text(&result)); + if let Some(path) = result["local"]["markdownPath"].as_str() { + println!("\nWrote {path}"); + } + } + Ok(()) +} + +pub fn handle(args: &[String]) { + let parsed = arg_parser::pre_parse(args, ScanMode::Full, true).unwrap_or_else(|error| { + eprintln!("error: {error}"); + std::process::exit(2); + }); + arg_parser::merge_global_flags(&parsed.flags); + if parsed.flags.help { + arg_parser::print_command_help("findings"); + return; + } + if let Some(directory) = parsed.flags.change_dir + && let Err(error) = std::env::set_current_dir(directory) + { + eprintln!("error: {error}"); + std::process::exit(1); + } + let options = parse_options(&parsed.rest).unwrap_or_else(|error| { + eprintln!("error: {error}"); + std::process::exit(2); + }); + if let Err(error) = run(options) { + let message = match error { + AutterError::Generic(message) => message, + other => other.to_string(), + }; + if arg_parser::json() { + println!("{}", json!({ "error": message })); + } else { + eprintln!("error: {message}"); + } + std::process::exit(1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(args: &[&str]) -> Vec { + args.iter().map(|a| (*a).to_owned()).collect() + } + + #[test] + fn parses_options() { + assert_eq!( + parse_options(&s(&[ + "--write", + "--pr", + "#12", + "--org", + "acme", + "--no-fetch" + ])) + .unwrap(), + Options { + pr: Some(12), + organization: Some("acme".into()), + write: true, + no_fetch: true, + ..Options::default() + } + ); + assert!(parse_options(&s(&["--pr", "x"])).is_err()); + assert!(parse_options(&s(&["--branch"])).is_err()); + assert!(parse_options(&s(&["stray"])).is_err()); + } + + #[test] + fn builds_the_query() { + assert_eq!( + findings_path("acme co", "https://github.com/a/b", Some("feat/x"), None), + "/api/cli/orgs/acme+co/findings?repository=https%3A%2F%2Fgithub.com%2Fa%2Fb&branch=feat%2Fx" + ); + } + + const DIFF: &str = "\ +diff --git a/src/a.ts b/src/a.ts +index 111..222 100644 +--- a/src/a.ts ++++ b/src/a.ts +@@ -2,0 +3,2 @@ fn top ++added one ++added two +@@ -10 +12 @@ fn mid +-old ten ++new ten +@@ -20,3 +22,0 @@ +--- a removed SQL comment line +-x +-y +diff --git a/gone.ts b/gone.ts +deleted file mode 100644 +--- a/gone.ts ++++ /dev/null +@@ -1,3 +0,0 @@ +-a +-b +-c +diff --git \"a/sp\\303\\251cial \\\"q\\\".ts\" \"b/sp\\303\\251cial \\\"q\\\".ts\" +--- \"a/sp\\303\\251cial \\\"q\\\".ts\" ++++ \"b/sp\\303\\251cial \\\"q\\\".ts\" +@@ -1 +1 @@ +-a ++b +"; + + #[test] + fn parses_hunks_per_file() { + let files = parse_diff(DIFF); + let a = &files["src/a.ts"]; + assert!(!a.deleted); + assert_eq!(a.hunks.len(), 3); + assert_eq!( + a.hunks[2], + Hunk { + old_start: 20, + old_count: 3, + new_count: 0 + } + ); + assert!(files["gone.ts"].deleted); + assert!(files.contains_key("spécial \"q\".ts")); + // The removed `-- a removed…` line must not open a new file. + assert_eq!(files.len(), 3); + } + + #[test] + fn maps_lines_through_the_diff() { + let files = parse_diff(DIFF); + let a = files.get("src/a.ts"); + assert_eq!(map_line(a, 1), Placement::Unchanged(1)); + assert_eq!(map_line(a, 2), Placement::Unchanged(2)); + // Two lines inserted after line 2. + assert_eq!(map_line(a, 3), Placement::Moved(5)); + assert_eq!(map_line(a, 9), Placement::Moved(11)); + // Line 10 itself was edited. + assert_eq!(map_line(a, 10), Placement::Changed); + assert_eq!(map_line(a, 11), Placement::Moved(13)); + assert_eq!(map_line(a, 21), Placement::Changed); + // Three lines removed above. + assert_eq!(map_line(a, 30), Placement::Moved(29)); + assert_eq!(map_line(files.get("gone.ts"), 2), Placement::FileDeleted); + assert_eq!(map_line(None, 7), Placement::Unchanged(7)); + } + + #[test] + fn insertion_at_the_finding_line_does_not_move_it() { + // Inserted after line 5: line 5 stays, line 6 moves. + let diff = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -5,0 +6 @@\n+new\n"; + let files = parse_diff(diff); + assert_eq!(map_line(files.get("f"), 5), Placement::Unchanged(5)); + assert_eq!(map_line(files.get("f"), 6), Placement::Moved(7)); + // Inserted at the top of the file. + let diff = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -0,0 +1 @@\n+new\n"; + let files = parse_diff(diff); + assert_eq!(map_line(files.get("f"), 1), Placement::Moved(2)); + } + + fn finding(path: &str, line: u64) -> Value { + json!({ "id": "f", "title": "T", "body": "B", "path": path, "line": line, "side": "RIGHT", + "severity": "critical", "prScoped": false, "fixPrompt": "Do X.", "url": "https://x/pull/1" }) + } + + #[test] + fn places_findings_or_marks_them_unverified() { + let files = parse_diff(DIFF); + let mut list = vec![ + finding("src/a.ts", 10), + finding("src/a.ts", 3), + json!({ "path": "", "line": 0, "prScoped": true }), + ]; + place_findings(&mut list, Some(&files)); + assert_eq!( + list[0]["local"], + json!({ "status": "changed", "line": null }) + ); + assert_eq!(list[1]["local"], json!({ "status": "moved", "line": 5 })); + assert_eq!(list[2]["local"]["status"], "no_line"); + + let mut list = vec![finding("src/a.ts", 3)]; + place_findings(&mut list, None); + assert_eq!( + list[0]["local"], + json!({ "status": "unverified", "line": null }) + ); + } + + #[test] + fn renders_markdown_sections() { + let files = parse_diff(DIFF); + let mut findings = vec![finding("src/a.ts", 3), finding("src/a.ts", 10)]; + place_findings(&mut findings, Some(&files)); + let result = json!({ + "pullRequest": { "number": 7, "title": "Add thing", "url": "https://app/pull/7" }, + "review": { "headSha": "abcdef123456", "stale": false, "reviewedAt": "2026-11-17T09:12:34.000Z" }, + "findings": findings, + "local": { "branch": "feat", "generatedAt": "2026-11-17T00:00:00Z" }, + }); + let md = render_markdown(&result); + assert!(md.contains("[#7 Add thing](https://app/pull/7)")); + assert!(md.contains("Reviewed commit `abcdef1` at 2026-11-17 09:12 UTC.")); + assert!(!md.contains("2026-11-17T00:00:00Z"), "no run time: {md}"); + assert!(md.contains("## Pull request review")); + assert!(md.contains("### In your code")); + assert!(md.contains("Location: `src/a.ts:5` (line 3 when reviewed)")); + assert!(md.contains("### Changed since the review")); + assert!(!md.contains("## Local review")); + assert!(md.contains("Location: `src/a.ts`, line 10 when reviewed")); + assert!(md.contains(" - Next steps:\n\n Do X.")); + + let none = render_markdown(&json!({ "pullRequest": null, "local": { "branch": "feat" } })); + assert!(none.contains("No open pull request for `feat` yet")); + } + + #[test] + fn excludes_the_findings_dir_once() { + let once = with_exclude_entry("*.log").unwrap(); + assert_eq!( + once, + "*.log\n# autter findings (autter findings --write)\n/.autter/\n" + ); + assert_eq!(with_exclude_entry(&once), None); + assert!(with_exclude_entry("").unwrap().ends_with("/.autter/\n")); + } + + /// The parser against what git really prints, not a hand-written diff. + #[test] + fn maps_lines_through_a_real_git_diff() { + use std::process::Command; + let dir = tempfile::tempdir().unwrap(); + let git = |args: &[&str]| { + let out = Command::new("git") + .args([ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .current_dir(dir.path()) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).into_owned() + }; + git(&["init", "-q"]); + let original: String = (1..=12).map(|n| format!("line {n}\n")).collect(); + std::fs::write(dir.path().join("a b.ts"), &original).unwrap(); + git(&["add", "."]); + git(&["commit", "-q", "-m", "reviewed"]); + let reviewed = git(&["rev-parse", "HEAD"]).trim().to_owned(); + + // Two lines added at the top, line 5 edited, line 9 removed. + let edited = original + .replacen("line 1\n", "new a\nnew b\nline 1\n", 1) + .replace("line 5\n", "line five\n") + .replace("line 9\n", ""); + std::fs::write(dir.path().join("a b.ts"), edited).unwrap(); + + let diff = git(&[ + "-c", + "core.quotePath=false", + "diff", + "-U0", + "--no-color", + "--no-renames", + "--no-ext-diff", + &reviewed, + "--", + ":(literal)a b.ts", + ]); + let files = parse_diff(&diff); + let file = files.get("a b.ts"); + assert!(file.is_some(), "{diff}"); + assert_eq!(map_line(file, 1), Placement::Moved(3)); + assert_eq!(map_line(file, 4), Placement::Moved(6)); + assert_eq!(map_line(file, 5), Placement::Changed); + assert_eq!(map_line(file, 8), Placement::Moved(10)); + assert_eq!(map_line(file, 9), Placement::Changed); + assert_eq!(map_line(file, 10), Placement::Moved(11)); + assert_eq!(map_line(file, 12), Placement::Moved(13)); + } + + /// A saved local review is placed by diffing the reviewed blob against the file now. + #[test] + fn places_a_saved_local_review_on_the_working_tree() { + use std::process::Command; + let dir = tempfile::tempdir().unwrap(); + let run = |args: &[&str]| { + let out = Command::new("git") + .args(args) + .current_dir(dir.path()) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + }; + run(&["init", "-q"]); + let original: String = (1..=10).map(|n| format!("line {n}\n")).collect(); + std::fs::write(dir.path().join("a.ts"), &original).unwrap(); + std::fs::write(dir.path().join("b.ts"), "x\n").unwrap(); + + let repo = + crate::git::repository::find_repository_in_path(&dir.path().to_string_lossy()).unwrap(); + let local = Local { + workdir: repo.workdir().unwrap(), + repo, + repository: "acme/web".into(), + branch: Some("feat".into()), + }; + let blobs = snapshot_blobs(&local, &["a.ts".into(), "b.ts".into()]).unwrap(); + assert_eq!(blobs.len(), 2); + + // After the review: a line added at the top, line 6 edited, b.ts deleted. + let edited = format!("new\n{}", original.replace("line 6\n", "line six\n")); + std::fs::write(dir.path().join("a.ts"), edited).unwrap(); + std::fs::remove_file(dir.path().join("b.ts")).unwrap(); + + let saved = json!({ + "branch": "feat", + "files": blobs, + "result": { "findings": [ + finding("a.ts", 2), finding("a.ts", 6), finding("b.ts", 1), finding("c.ts", 1), + ] }, + }); + let placed = place_local_findings(&local, &saved); + let local_of = |i: usize| placed[i]["local"].clone(); + assert_eq!(local_of(0), json!({ "status": "moved", "line": 3 })); + assert_eq!(local_of(1), json!({ "status": "changed", "line": null })); + assert_eq!( + local_of(2), + json!({ "status": "file_deleted", "line": null }) + ); + // Not in the snapshot: can't be checked. + assert_eq!(local_of(3), json!({ "status": "unverified", "line": null })); + + // Shown only on the branch it was made on. + std::fs::create_dir_all(dir.path().join(FINDINGS_DIR)).unwrap(); + std::fs::write(local_review_path(&local), saved.to_string()).unwrap(); + let mut result = json!({}); + attach_local_review(&mut result, &local); + assert_eq!( + result["localReview"]["findings"].as_array().unwrap().len(), + 4 + ); + let other = Local { + branch: Some("main".into()), + ..local + }; + let mut result = json!({}); + attach_local_review(&mut result, &other); + assert!(result["localReview"].is_null()); + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 23104b2..65c9fa0 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -16,6 +16,7 @@ pub mod doctor; pub mod exchange_nonce; pub mod fetch_notes; pub mod file_changes; +pub mod findings; pub mod flush_metrics_db; pub mod generated_tests; pub mod git_handlers; @@ -37,6 +38,7 @@ pub mod notes_migrate; pub mod onboard; pub mod output; pub mod personal_dashboard; +pub mod review; pub mod setup_notices; pub mod show; pub mod show_prompt; diff --git a/src/commands/review.rs b/src/commands/review.rs new file mode 100644 index 0000000..3b57e19 --- /dev/null +++ b/src/commands/review.rs @@ -0,0 +1,743 @@ +//! `autter review`: review your changes before you open a pull request. +//! +//! Sends what a pull request from this branch would contain — the diff from +//! the merge base with the default branch to your working tree, untracked +//! files included — to `POST /api/cli/orgs//review`, which runs the core +//! of the PR review (secrets, static security, auth, race conditions and, when +//! the org has it on, deep correctness) and streams back JSON lines. +//! +//! Before sending, every reviewed file is saved as a git blob. The result and +//! those blob ids go to `.autter/local-review.json`; `autter findings` (and so +//! the VS Code extension) reads it and places each finding on your working +//! tree by diffing the reviewed blob against the file as it is now, the same +//! way PR findings follow your edits. `--write` also writes +//! `.autter/findings.md` with the pull request's findings and this review. +use crate::commands::arg_parser::{self, ScanMode}; +use crate::commands::ask::{component, org_api_context}; +use crate::commands::findings::{ + self, FINDINGS_DIR, Local, git_args, local_context_for, local_review_path, one_line, + place_local_findings, render_markdown, render_text_findings, short_sha, snapshot_blobs, + write_if_changed, write_markdown, +}; +use crate::error::AutterError; +use crate::git::repository::{exec_git, exec_git_allow_nonzero}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, HashMap}; + +/// A review takes a minute or two; the server streams while it runs. +const TIMEOUT_SECS: u64 = 600; +/// What the server takes (`LOCAL_REVIEW_MAX_FILES` / `_MAX_BYTES` in the backend). +const MAX_FILES: usize = 60; +const MAX_BYTES: usize = 3 * 1024 * 1024; +/// Files larger than this are sent as a patch only, without their content. +const MAX_CONTENT_BYTES: usize = 200 * 1024; + +const NOT_SIGNED_IN: &str = "Autter did not accept your sign-in for this organization (HTTP 401). Sign in with `autter login` first, or choose an organization with --org ."; + +#[derive(Debug, Default, PartialEq)] +struct Options { + paths: Vec, + base: Option, + uncommitted: bool, + repository: Option, + organization: Option, + write: bool, +} + +fn parse_options(args: &[String]) -> Result { + let mut options = Options::default(); + let mut index = 0; + while index < args.len() { + let arg = args[index].as_str(); + if arg == "--" { + options + .paths + .extend(args[index + 1..].iter().map(|p| p.trim().to_owned())); + break; + } + match arg { + "--write" => options.write = true, + "--uncommitted" => options.uncommitted = true, + "--base" | "--repo" | "--org" => { + let value = args + .get(index + 1) + .map(|v| v.trim()) + .filter(|v| !v.starts_with("--") && !v.is_empty()) + .ok_or_else(|| format!("{arg} requires a value"))?; + match arg { + "--base" => options.base = Some(value.to_owned()), + "--repo" => options.repository = Some(value.to_owned()), + _ => options.organization = Some(value.to_owned()), + } + index += 2; + continue; + } + _ if arg.starts_with('-') => return Err(format!("unknown option for review: {arg}")), + _ => options.paths.push(arg.trim().to_owned()), + } + index += 1; + } + if options.uncommitted && options.base.is_some() { + return Err("--uncommitted and --base can't be used together".into()); + } + options.paths.retain(|p| !p.is_empty()); + Ok(options) +} + +// --------------------------------------------------------------------------- +// What to review +// --------------------------------------------------------------------------- + +fn git_text(local: &Local, rest: &[&str]) -> Result { + let out = exec_git(&git_args(&local.repo, rest))?; + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +fn rev_parse(local: &Local, spec: &str) -> Option { + let spec = format!("{spec}^{{commit}}"); + let out = exec_git_allow_nonzero(&git_args( + &local.repo, + &["rev-parse", "--verify", "--quiet", &spec], + )) + .ok()?; + out.status + .success() + .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned()) + .filter(|s| !s.is_empty()) +} + +/// The commit to compare with and how to name it: the merge base of HEAD +/// with `--base` or the default branch (what a PR would be opened against), +/// or HEAD itself with `--uncommitted` or when there is no default branch. +fn resolve_base(local: &Local, options: &Options) -> Result<(String, String), AutterError> { + let head = rev_parse(local, "HEAD").ok_or_else(|| { + AutterError::Generic( + "This repository has no commits yet. Commit once, then run autter review.".into(), + ) + })?; + if options.uncommitted { + return Ok((head, "HEAD".into())); + } + let candidates: Vec = match options.base.clone() { + Some(base) => vec![base], + None => { + let mut list = Vec::new(); + if let Ok(Some(remote)) = local.repo.get_default_remote() { + if let Ok(head_ref) = local.repo.remote_head(&remote) + && !head_ref.is_empty() + { + list.push(head_ref); + } + list.push(format!("{remote}/main")); + list.push(format!("{remote}/master")); + } + list.push("main".into()); + list.push("master".into()); + list + } + }; + for candidate in &candidates { + let Some(sha) = rev_parse(local, candidate) else { + continue; + }; + if let Ok(Some(base)) = local.repo.merge_base(head.clone(), sha) { + return Ok((base, candidate.clone())); + } + } + if let Some(base) = options.base.as_deref() { + return Err(AutterError::Generic(format!( + "Could not find a common commit with {base}. Pass another --base, or --uncommitted." + ))); + } + Ok((head, "HEAD".into())) +} + +#[derive(Debug, Clone, PartialEq)] +struct Change { + path: String, + status: &'static str, +} + +/// `git diff --name-status -z` output → changes. +fn parse_name_status(text: &str) -> Vec { + let mut out = Vec::new(); + let mut parts = text.split('\0').filter(|s| !s.is_empty()); + while let Some(code) = parts.next() { + let Some(path) = parts.next() else { + break; + }; + let status = match code.chars().next() { + Some('A') => "added", + Some('D') => "removed", + _ => "modified", + }; + out.push(Change { + path: path.to_owned(), + status, + }); + } + out +} + +fn wanted(path: &str, filters: &[String]) -> bool { + if path == FINDINGS_DIR || path.starts_with(&format!("{FINDINGS_DIR}/")) { + return false; + } + filters.is_empty() + || filters.iter().any(|f| { + let f = f.trim_end_matches('/'); + f == "." || path == f || path.starts_with(&format!("{f}/")) + }) +} + +/// Paths given on the command line, relative to the repository root. +fn repo_relative_filters(local: &Local, paths: &[String]) -> Vec { + let cwd = std::env::current_dir().unwrap_or_else(|_| local.workdir.clone()); + paths + .iter() + .map(|p| { + let abs = cwd.join(p); + let abs = abs.canonicalize().unwrap_or(abs); + let root = local + .workdir + .canonicalize() + .unwrap_or_else(|_| local.workdir.clone()); + abs.strip_prefix(&root) + .map(|rel| crate::utils::normalize_to_posix(&rel.to_string_lossy())) + .unwrap_or_else(|_| p.clone()) + }) + .map(|p| if p.is_empty() { ".".into() } else { p }) + .collect() +} + +fn changed_files( + local: &Local, + base: &str, + filters: &[String], +) -> Result, AutterError> { + let tracked = git_text( + local, + &[ + "-c", + "core.quotePath=false", + "diff", + "--name-status", + "--no-renames", + "-z", + base, + ], + )?; + let mut changes = parse_name_status(&tracked); + let untracked = git_text(local, &["ls-files", "--others", "--exclude-standard", "-z"])?; + changes.extend( + untracked + .split('\0') + .filter(|p| !p.is_empty()) + .map(|path| Change { + path: path.to_owned(), + status: "added", + }), + ); + changes.retain(|c| wanted(&c.path, filters)); + changes.sort_by(|a, b| a.path.cmp(&b.path)); + changes.dedup_by(|a, b| a.path == b.path); + Ok(changes) +} + +/// Split `git diff` output into each file's hunks (from the first `@@`), as +/// GitHub sends a PR file's patch. Binary files get none. +fn split_patches(diff: &str) -> HashMap { + let mut out = HashMap::new(); + let mut path: Option = None; + let mut old: Option = None; + let mut body = String::new(); + let mut in_header = false; + let mut flush = |path: &mut Option, body: &mut String| { + if let Some(p) = path.take() + && !body.is_empty() + { + out.insert(p, std::mem::take(body)); + } + body.clear(); + }; + for line in diff.split_inclusive('\n') { + if line.starts_with("diff --git ") { + flush(&mut path, &mut body); + in_header = true; + old = None; + continue; + } + if in_header { + if let Some(raw) = line.strip_prefix("--- ") { + old = header_path(raw.trim_end_matches('\n'), "a/"); + continue; + } + if let Some(raw) = line.strip_prefix("+++ ") { + path = header_path(raw.trim_end_matches('\n'), "b/").or_else(|| old.clone()); + continue; + } + if !line.starts_with("@@ ") { + continue; + } + in_header = false; + } + if path.is_some() { + body.push_str(line); + } + } + flush(&mut path, &mut body); + out +} + +fn header_path(raw: &str, prefix: &str) -> Option { + let raw = raw.trim_end_matches('\t'); + if raw == "/dev/null" { + return None; + } + let raw = if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') { + // Quoted names are rare with core.quotePath=false (control characters only). + raw[1..raw.len() - 1] + .replace("\\\"", "\"") + .replace("\\\\", "\\") + } else { + raw.to_owned() + }; + Some(raw.strip_prefix(prefix).unwrap_or(&raw).to_owned()) +} + +/// The patch of a new, untracked file. +fn added_patch(content: &str) -> Option { + let lines: Vec<&str> = content.lines().collect(); + if lines.is_empty() { + return None; + } + let mut patch = format!("@@ -0,0 +1,{} @@\n", lines.len()); + for line in lines { + patch.push('+'); + patch.push_str(line); + patch.push('\n'); + } + Some(patch) +} + +fn blob_text(local: &Local, sha: &str) -> Option { + let out = exec_git(&git_args(&local.repo, &["cat-file", "blob", sha])).ok()?; + if out.stdout.len() > MAX_CONTENT_BYTES || out.stdout.contains(&0) { + return None; + } + String::from_utf8(out.stdout).ok() +} + +struct Prepared { + files: Vec, + /// path → blob id of the content the review saw. + snapshot: HashMap, +} + +fn prepare(local: &Local, base: &str, changes: &[Change]) -> Result { + let mut args: Vec = git_args( + &local.repo, + &[ + "-c", + "core.quotePath=false", + "diff", + "-U3", + "--no-color", + "--no-renames", + "--no-ext-diff", + "--no-textconv", + base, + "--", + ], + ); + // Untracked files match nothing here; they get a patch from their content below. + args.extend(changes.iter().map(|c| format!(":(literal){}", c.path))); + let patches = if changes.is_empty() { + HashMap::new() + } else { + split_patches(&String::from_utf8_lossy(&exec_git(&args)?.stdout)) + }; + + let present: Vec = changes + .iter() + .filter(|c| c.status != "removed") + .map(|c| c.path.clone()) + .collect(); + // Saved before the contents are read, so the review and the later line + // mapping see exactly the same bytes. + let snapshot = snapshot_blobs(local, &present)?; + + let mut files = Vec::new(); + let mut total = 0usize; + for change in changes { + let content = snapshot + .get(&change.path) + .and_then(|sha| blob_text(local, sha)); + let patch = match patches.get(&change.path) { + Some(patch) => Some(patch.clone()), + None if change.status == "added" => content.as_deref().and_then(added_patch), + None => None, + }; + if patch.is_none() && change.status != "removed" { + // Binary, empty, or mode-only: nothing to review. + continue; + } + total += patch.as_ref().map_or(0, String::len) + content.as_ref().map_or(0, String::len); + files.push(json!({ + "path": change.path, + "status": change.status, + "patch": patch, + "content": content, + })); + } + if files.len() > MAX_FILES { + return Err(AutterError::Generic(format!( + "{} changed files is more than a local review takes ({MAX_FILES}). Pass the paths to review, e.g. `autter review src/payments`.", + files.len() + ))); + } + if total > MAX_BYTES { + return Err(AutterError::Generic(format!( + "These changes are too large for one local review ({} KB of {} KB). Pass the paths to review.", + total / 1024, + MAX_BYTES / 1024 + ))); + } + Ok(Prepared { files, snapshot }) +} + +// --------------------------------------------------------------------------- +// The request +// --------------------------------------------------------------------------- + +/// The `result` (or `error`) line of the server's JSON-lines stream. +fn stream_result(code: u16, body: &str) -> Result { + if code == 401 { + return Err(AutterError::Generic(NOT_SIGNED_IN.into())); + } + if code != 200 { + let value: Option = serde_json::from_str(body).ok(); + let message = value + .as_ref() + .and_then(|v| v["message"].as_str().or(v["error"].as_str())) + .map(str::to_owned); + return Err(AutterError::Generic(match (code, message) { + (404, None) => "The review API isn't available (HTTP 404). Update the API deployment if this command is unavailable.".into(), + (_, Some(message)) => message, + (_, None) => format!("HTTP {code}: the review request failed"), + })); + } + let mut last_error = None; + for line in body.lines().filter(|l| !l.trim().is_empty()) { + let Ok(event) = serde_json::from_str::(line) else { + continue; + }; + match event["type"].as_str() { + Some("result") => return Ok(event), + Some("error") => last_error = event["message"].as_str().map(str::to_owned), + _ => {} + } + } + Err(AutterError::Generic(last_error.unwrap_or_else(|| { + "The review ended without a result. Try again.".into() + }))) +} + +fn run(options: Options) -> Result<(), AutterError> { + let local = local_context_for(options.repository.clone(), None)?; + let (base, base_label) = resolve_base(&local, &options)?; + let filters = repo_relative_filters(&local, &options.paths); + let changes = changed_files(&local, &base, &filters)?; + if changes.is_empty() { + let message = format!( + "No changes to review compared with {}.", + if base_label == "HEAD" { + "HEAD".to_owned() + } else { + base_label.clone() + } + ); + if arg_parser::json() { + println!("{}", json!({ "localReview": null, "message": message })); + } else { + println!("{message}"); + } + return Ok(()); + } + let prepared = prepare(&local, &base, &changes)?; + if prepared.files.is_empty() { + println!("Nothing reviewable in these changes (binary or empty files only)."); + return Ok(()); + } + + let (context, slug) = org_api_context(options.organization.as_deref(), TIMEOUT_SECS)?; + if !arg_parser::json() && !arg_parser::quiet() { + eprintln!( + "Reviewing {} file{} compared with {} ({}). This takes a minute or two…", + prepared.files.len(), + if prepared.files.len() == 1 { "" } else { "s" }, + base_label, + short_sha(&base) + ); + } + let title = git_text(&local, &["log", "-1", "--format=%s"]) + .ok() + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty() && base_label != "HEAD"); + let response = context.post_json( + &format!("/api/cli/orgs/{}/review", component(&slug)), + &json!({ + "repository": local.repository, + "branch": local.branch, + "title": title, + "files": prepared.files, + }), + )?; + let body = response + .as_str() + .map_err(|error| AutterError::Generic(error.to_string()))?; + let result = stream_result(response.status_code, body)?; + + // Saved for `autter findings` and the editor; then placed like any later read. + let files: BTreeMap<&String, &String> = prepared.snapshot.iter().collect(); + let saved = json!({ + "version": 1, + "branch": local.branch, + "base": base, + "baseRef": base_label, + "reviewedAt": result["review"]["reviewedAt"], + "files": files, + "result": result, + }); + let path = local_review_path(&local); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + write_if_changed(&path, &serde_json::to_string_pretty(&saved)?)?; + let _ = findings::exclude_findings_dir(&local.repo); + let placed = place_local_findings(&local, &saved); + + let mut markdown_path = None; + if options.write { + // The file has both reviews: the PR's findings (when there is one) and this one. + let mut combined = + findings::collect_for_branch(&context, &slug, &local).unwrap_or_else(|_| { + let mut stub = json!({ + "pullRequest": null, + "review": null, + "findings": [], + "local": { "branch": local.branch }, + }); + findings::attach_local_review(&mut stub, &local); + stub + }); + if combined["localReview"].is_null() { + findings::attach_local_review(&mut combined, &local); + } + markdown_path = Some(write_markdown(&local, &render_markdown(&combined))?); + } + + let output = json!({ + "localReview": { + "reviewId": result["review"]["reviewId"], + "reviewedAt": result["review"]["reviewedAt"], + "base": base, + "baseRef": base_label, + "files": prepared.files.len(), + "bundles": result["review"]["bundles"], + "ignoredPaths": result["review"]["ignoredPaths"], + "findings": placed, + }, + "local": { + "branch": local.branch, + "repository": local.repository, + "workdir": local.workdir.to_string_lossy(), + "markdownPath": markdown_path.as_ref().map(|p| p.to_string_lossy()), + }, + }); + if arg_parser::json() { + println!("{}", serde_json::to_string_pretty(&output)?); + return Ok(()); + } + let mut out = format!( + "Local review of {} file{} compared with {} ({})\n\n", + prepared.files.len(), + if prepared.files.len() == 1 { "" } else { "s" }, + one_line(&base_label), + short_sha(&base) + ); + render_text_findings(&mut out, &placed); + let failed: Vec = result["review"]["bundles"] + .as_array() + .into_iter() + .flatten() + .filter(|b| b["error"].is_string()) + .filter_map(|b| b["bundle"].as_str().map(str::to_owned)) + .collect(); + if !failed.is_empty() { + out.push_str(&format!( + "\nSome checks didn't finish ({}); run autter review again to retry them.\n", + failed.join(", ") + )); + } + print!("{out}"); + if let Some(path) = markdown_path { + println!("\nWrote {}", path.to_string_lossy()); + } + Ok(()) +} + +pub fn handle(args: &[String]) { + let parsed = arg_parser::pre_parse(args, ScanMode::Full, true).unwrap_or_else(|error| { + eprintln!("error: {error}"); + std::process::exit(2); + }); + arg_parser::merge_global_flags(&parsed.flags); + if parsed.flags.help { + arg_parser::print_command_help("review"); + return; + } + if let Some(directory) = parsed.flags.change_dir + && let Err(error) = std::env::set_current_dir(directory) + { + eprintln!("error: {error}"); + std::process::exit(1); + } + let options = parse_options(&parsed.rest).unwrap_or_else(|error| { + eprintln!("error: {error}"); + std::process::exit(2); + }); + if let Err(error) = run(options) { + let message = match error { + AutterError::Generic(message) => message, + other => other.to_string(), + }; + if arg_parser::json() { + println!("{}", json!({ "error": message })); + } else { + eprintln!("error: {message}"); + } + std::process::exit(1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(args: &[&str]) -> Vec { + args.iter().map(|a| (*a).to_owned()).collect() + } + + #[test] + fn parses_options() { + assert_eq!( + parse_options(&s(&[ + "src/a", + "--base", + "origin/dev", + "--write", + "--", + "--odd" + ])) + .unwrap(), + Options { + paths: vec!["src/a".into(), "--odd".into()], + base: Some("origin/dev".into()), + write: true, + ..Options::default() + } + ); + assert!(parse_options(&s(&["--uncommitted", "--base", "x"])).is_err()); + assert!(parse_options(&s(&["--nope"])).is_err()); + assert!(parse_options(&s(&["--base"])).is_err()); + } + + #[test] + fn parses_name_status() { + let out = parse_name_status("M\0src/a.ts\0A\0new file.ts\0D\0gone.ts\0T\0link\0"); + assert_eq!( + out.iter() + .map(|c| (c.path.as_str(), c.status)) + .collect::>(), + vec![ + ("src/a.ts", "modified"), + ("new file.ts", "added"), + ("gone.ts", "removed"), + ("link", "modified"), + ] + ); + } + + #[test] + fn filters_paths_and_skips_its_own_directory() { + assert!(!wanted(".autter/findings.md", &[])); + assert!(wanted("src/a.ts", &[])); + assert!(wanted("src/a.ts", &["src".into()])); + assert!(wanted("src/a.ts", &["src/".into()])); + assert!(!wanted("srcx/a.ts", &["src".into()])); + assert!(wanted("src/a.ts", &[".".into()])); + } + + #[test] + fn splits_a_diff_into_patches() { + let diff = "\ +diff --git a/src/a.ts b/src/a.ts +index 1..2 100644 +--- a/src/a.ts ++++ b/src/a.ts +@@ -1,2 +1,2 @@ + keep +--- removed sql comment ++added +diff --git a/gone.ts b/gone.ts +deleted file mode 100644 +--- a/gone.ts ++++ /dev/null +@@ -1 +0,0 @@ +-x +diff --git a/img.png b/img.png +Binary files a/img.png and b/img.png differ +"; + let patches = split_patches(diff); + assert_eq!( + patches["src/a.ts"], + "@@ -1,2 +1,2 @@\n keep\n--- removed sql comment\n+added\n" + ); + assert_eq!(patches["gone.ts"], "@@ -1 +0,0 @@\n-x\n"); + assert!(!patches.contains_key("img.png")); + } + + #[test] + fn builds_a_patch_for_a_new_file() { + assert_eq!(added_patch("a\nb\n").unwrap(), "@@ -0,0 +1,2 @@\n+a\n+b\n"); + assert_eq!(added_patch(""), None); + } + + #[test] + fn reads_the_result_line_of_the_stream() { + let body = "{\"type\":\"progress\",\"stage\":\"started\"}\n{\"type\":\"progress\",\"keepalive\":true}\n{\"type\":\"result\",\"findings\":[]}\n"; + assert_eq!(stream_result(200, body).unwrap()["type"], "result"); + let err = stream_result( + 200, + "{\"type\":\"error\",\"message\":\"The review failed.\"}\n", + ) + .unwrap_err() + .to_string(); + assert!(err.contains("The review failed."), "{err}"); + assert!(stream_result(200, "{\"type\":\"progress\"}\n").is_err()); + let err = stream_result( + 429, + "{\"error\":\"rate_limited\",\"message\":\"Rate limit exceeded\"}", + ) + .unwrap_err() + .to_string(); + assert!(err.contains("Rate limit exceeded"), "{err}"); + assert!( + stream_result(401, "") + .unwrap_err() + .to_string() + .contains("autter login") + ); + } +} diff --git a/src/commands/setup_notices.rs b/src/commands/setup_notices.rs index cc50195..916bae7 100644 --- a/src/commands/setup_notices.rs +++ b/src/commands/setup_notices.rs @@ -37,6 +37,8 @@ const NOTICE_COMMANDS: &[&str] = &[ "dashboard", "personal-dashboard", "ask", + "findings", + "review", "lineage", "logs", "threads", diff --git a/tests/integration/help_flag_safety.rs b/tests/integration/help_flag_safety.rs index ae7ecce..327d109 100644 --- a/tests/integration/help_flag_safety.rs +++ b/tests/integration/help_flag_safety.rs @@ -58,6 +58,9 @@ const HELP_INVOCATIONS: &[&[&str]] = &[ &["logout", "--help"], &["whoami", "--help"], &["ask", "--help"], + &["findings", "--help"], + &["review", "--help"], + &["review", "src", "--help"], &["lineage", "--help"], &["lineage", "src/main.rs:1", "--help"], &["logs", "--help"],