Skip to content

Commit 4fc5af2

Browse files
committed
feat(review): add --path support for targeted folder/file reviews
Extends /opencode:review and /opencode:adversarial-review to accept --path <path> flags for reviewing specific directories or files instead of only git diff. Useful for reviewing specific subdirectories, fixed sets of files, or large untracked/imported code drops. Changes: - Add collectFolderContext() to fs.mjs with per-file and total size caps - Extend buildReviewPrompt() in prompts.mjs to accept paths option - Add normalizePathOption() helper and --path to valueOptions in companion - Update review.md and adversarial-review.md command documentation - Update README.md to document the new --path option Implements: #21
1 parent 87fbd97 commit 4fc5af2

6 files changed

Lines changed: 258 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,8 @@ To check your configured providers:
9797

9898
## Slash Commands
9999

100-
- `/opencode:review` -- Normal OpenCode code review (read-only). Supports `--base <ref>`, `--pr <number>`, `--model <provider/model>`, `--free`, `--wait`, and `--background`.
101-
- `/opencode:adversarial-review` -- Steerable review that challenges implementation and design decisions. Supports `--base <ref>`, `--pr <number>`, `--model <provider/model>`, `--free`, `--wait`, `--background`, and custom focus text.
100+
- `/opencode:review` -- Normal OpenCode code review (read-only). Supports `--base <ref>`, `--pr <number>`, `--path <path>`, `--model <provider/model>`, `--free`, `--wait`, and `--background`.
101+
- `/opencode:adversarial-review` -- Steerable review that challenges implementation and design decisions. Supports `--base <ref>`, `--pr <number>`, `--path <path>`, `--model <provider/model>`, `--free`, `--wait`, `--background`, and custom focus text.
102102
- `/opencode:rescue` -- Delegates a task to OpenCode via the `opencode:opencode-rescue` subagent. Supports `--model`, `--free`, `--agent`, `--resume`, `--fresh`, `--worktree`, `--wait`, and `--background`.
103103
- `/opencode:status` -- Shows running/recent OpenCode jobs for the current repo.
104104
- `/opencode:result` -- Shows final output for a finished job, including OpenCode session ID for resuming.

‎plugins/opencode/commands/adversarial-review.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
description: Run a steerable adversarial OpenCode review that challenges implementation and design decisions
3-
argument-hint: '[--wait|--background] [--base <ref>] [--model <id> | --free] [--pr <number>] [focus area or custom review instructions]'
3+
argument-hint: '[--wait|--background] [--base <ref>] [--model <id> | --free] [--pr <number>] [--path <path>] [--path <path2>] [focus area or custom review instructions]'
44
disable-model-invocation: true
55
allowed-tools: Read, Glob, Grep, Bash(node:*), Bash(git:*), Bash(gh:*), AskUserQuestion
66
---
@@ -40,6 +40,7 @@ Argument handling:
4040
- `--model <id>` overrides OpenCode's default model for this single review (e.g. `--model openrouter/anthropic/claude-opus-4-6`). Pass it through verbatim if the user supplied it.
4141
- `--free` tells the companion script to shell out to `opencode models`, filter for first-party `opencode/*` free-tier models (those ending in `:free` or `-free`), and pick one at random for this review. Restricted to the `opencode/*` provider because OpenRouter free-tier models have inconsistent tool-use support, and the review agent needs `read`/`grep`/`glob`/`list`. Pass it through verbatim if the user supplied it. `--free` and `--model` are mutually exclusive — the companion will error if both are given.
4242
- `--pr <number>` reviews a GitHub pull request via `gh pr diff` instead of the local working tree. The cwd must be a git repo whose remote points at the PR's repository, and `gh` must be installed and authenticated.
43+
- `--path <path>` reviews a specific file or directory instead of git diff. Can be specified multiple times (`--path src --path lib`). When `--path` is set, the review is assembled from the actual file contents at those paths rather than from `git diff`. This is useful for reviewing specific directories, fixed sets of files, or large untracked/imported code drops. Mutually exclusive with `--pr` (paths take precedence over PR mode).
4344

4445
PR reference extraction (REQUIRED — read this carefully):
4546
- If the user's input contains a PR reference like `PR #390`, `pr #390`, `PR 390`, or `pr 390`, you MUST extract the number yourself and pass it as `--pr 390`. Then strip the matched PR phrase from whatever you put in the focus text.

‎plugins/opencode/commands/review.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
description: Run an OpenCode code review against local git state or a GitHub PR
3-
argument-hint: '[--wait|--background] [--base <ref>] [--scope auto|working-tree|branch] [--model <id> | --free] [--pr <number>]'
3+
argument-hint: '[--wait|--background] [--base <ref>] [--scope auto|working-tree|branch] [--model <id> | --free] [--pr <number>] [--path <path>] [--path <path2>]'
44
disable-model-invocation: true
55
allowed-tools: Read, Glob, Grep, Bash(node:*), Bash(git:*), Bash(gh:*), AskUserQuestion
66
---
@@ -42,6 +42,7 @@ Argument handling:
4242
- `--model <id>` overrides OpenCode's default model for this single review (e.g. `--model openrouter/anthropic/claude-opus-4-6`). Pass it through verbatim if the user supplied it.
4343
- `--free` tells the companion script to shell out to `opencode models`, filter for first-party `opencode/*` free-tier models (those ending in `:free` or `-free`), and pick one at random for this review. Restricted to the `opencode/*` provider because OpenRouter free-tier models have inconsistent tool-use support, and the review agent needs `read`/`grep`/`glob`/`list`. Pass it through verbatim if the user supplied it. `--free` and `--model` are mutually exclusive — the companion will error if both are given.
4444
- `--pr <number>` reviews a GitHub pull request via `gh pr diff` instead of the local working tree. The cwd must be a git repo whose remote points at the PR's repository, and `gh` must be installed and authenticated. Pass it through verbatim if the user supplied it.
45+
- `--path <path>` reviews a specific file or directory instead of git diff. Can be specified multiple times (`--path src --path lib`). When `--path` is set, the review is assembled from the actual file contents at those paths rather than from `git diff`. This is useful for reviewing specific directories, fixed sets of files, or large untracked/imported code drops. Mutually exclusive with `--pr` (paths take precedence over PR mode).
4546
- **PR reference extraction (REQUIRED)**: if the user's input contains a PR reference like `PR #390`, `pr #390`, `PR 390`, or `pr 390` (e.g. `/opencode:review on PR #390`), you MUST extract the number yourself and pass it as `--pr 390`. Do not pass `PR #390` literally to bash — bash strips unquoted `#NNN` tokens as comments before they reach the companion script. Example: `node ... review --pr 390`, NOT `node ... review on PR #390`.
4647

4748
Foreground flow:

‎plugins/opencode/scripts/lib/fs.mjs‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,145 @@
33
import fs from "node:fs";
44
import path from "node:path";
55

6+
const DEFAULT_MAX_BYTES = 256 * 1024;
7+
const DEFAULT_MAX_FILES = 50;
8+
9+
function isGitignored(filePath, cwd) {
10+
try {
11+
const result = fs.statSync(filePath);
12+
if (!result.isFile()) return false;
13+
const dir = path.dirname(filePath);
14+
const gitignorePath = path.join(dir, ".gitignore");
15+
if (!fs.existsSync(gitignorePath)) {
16+
return isGitignored(dir, cwd);
17+
}
18+
const patterns = fs.readFileSync(gitignorePath, "utf8").split("\n");
19+
const relativePath = path.relative(cwd, filePath);
20+
for (const pattern of patterns) {
21+
const trimmed = pattern.trim();
22+
if (!trimmed || trimmed.startsWith("#")) continue;
23+
const glob = trimmed.replace(/\/$/, "");
24+
if (glob === relativePath || relativePath.startsWith(glob + "/")) {
25+
return true;
26+
}
27+
}
28+
return false;
29+
} catch {
30+
return false;
31+
}
32+
}
33+
34+
function isBinaryFile(filePath) {
35+
try {
36+
const buffer = Buffer.alloc(8192);
37+
const fd = fs.openSync(filePath, "r");
38+
const bytesRead = fs.readSync(fd, buffer, 0, 8192, 0);
39+
fs.closeSync(fd);
40+
for (let i = 0; i < bytesRead; i++) {
41+
if (buffer[i] === 0) return true;
42+
}
43+
return false;
44+
} catch {
45+
return false;
46+
}
47+
}
48+
49+
/**
50+
* Collect file contents for a set of paths within cwd.
51+
* Respects per-file and total size caps, skips binary files and broken symlinks.
52+
*
53+
* @param {string} cwd - Working directory
54+
* @param {string[]} targetPaths - Relative paths to include
55+
* @param {{ maxBytes?: number, maxFiles?: number }} opts
56+
* @returns {Promise<{ content: string, files: string[], totalBytes: number, overflowed: boolean }>}
57+
*/
58+
export async function collectFolderContext(cwd, targetPaths, opts = {}) {
59+
const maxBytes = Number.isFinite(opts.maxBytes) ? opts.maxBytes : DEFAULT_MAX_BYTES;
60+
const maxFiles = Number.isFinite(opts.maxFiles) ? opts.maxFiles : DEFAULT_MAX_FILES;
61+
62+
const result = {
63+
content: "",
64+
files: [],
65+
totalBytes: 0,
66+
overflowed: false,
67+
};
68+
69+
const visited = new Set();
70+
71+
for (const targetPath of targetPaths) {
72+
const resolvedPath = path.resolve(cwd, targetPath);
73+
74+
if (!resolvedPath.startsWith(path.resolve(cwd))) {
75+
continue;
76+
}
77+
78+
if (visited.has(resolvedPath)) continue;
79+
visited.add(resolvedPath);
80+
81+
try {
82+
const stat = fs.lstatSync(resolvedPath);
83+
84+
if (stat.isSymbolicLink()) {
85+
try {
86+
fs.statSync(resolvedPath);
87+
} catch {
88+
continue;
89+
}
90+
}
91+
92+
if (stat.isDirectory()) {
93+
const entries = fs.readdirSync(resolvedPath, { withFileTypes: true });
94+
for (const entry of entries) {
95+
if (result.files.length >= maxFiles) break;
96+
const entryPath = path.join(resolvedPath, entry.name);
97+
if (visited.has(entryPath)) continue;
98+
visited.add(entryPath);
99+
}
100+
} else if (stat.isFile()) {
101+
if (isBinaryFile(resolvedPath)) continue;
102+
103+
const relativePath = path.relative(cwd, resolvedPath);
104+
if (isGitignored(resolvedPath, cwd)) continue;
105+
106+
const content = fs.readFileSync(resolvedPath, "utf8");
107+
const fileBytes = Buffer.byteLength(content, "utf8");
108+
109+
if (result.totalBytes + fileBytes > maxBytes) {
110+
result.overflowed = true;
111+
const remaining = maxBytes - result.totalBytes;
112+
if (remaining > 0) {
113+
const truncated = truncateUtf8(content, remaining);
114+
result.content += `// File: ${relativePath} (truncated)\n${truncated}\n\n`;
115+
result.totalBytes += Buffer.byteLength(truncated, "utf8");
116+
}
117+
break;
118+
}
119+
120+
result.content += `// File: ${relativePath}\n${content}\n\n`;
121+
result.totalBytes += fileBytes;
122+
result.files.push(relativePath);
123+
124+
if (result.files.length >= maxFiles) {
125+
break;
126+
}
127+
}
128+
} catch (err) {
129+
if (err?.code !== "ENOENT") {
130+
// Skip files that don't exist
131+
}
132+
}
133+
}
134+
135+
return result;
136+
}
137+
138+
function truncateUtf8(text, maxBytes) {
139+
if (!text) return text;
140+
const buf = Buffer.from(text, "utf8");
141+
if (buf.length <= maxBytes) return text;
142+
return buf.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/, "");
143+
}
144+
6145
/**
7146
* Ensure a directory exists (recursive mkdir).
8147
* @param {string} dirPath

‎plugins/opencode/scripts/lib/prompts.mjs‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
getPrInfo,
1616
getPrDiff,
1717
} from "./git.mjs";
18+
import { collectFolderContext } from "./fs.mjs";
1819

1920
// Inline-diff thresholds. When a review exceeds either, we keep the prompt
2021
// bounded by including a diff excerpt instead of the full diff. The review
@@ -44,6 +45,7 @@ function truncateUtf8(text, maxBytes) {
4445
* @param {number} [opts.pr] - GitHub PR number to review (uses `gh pr diff`)
4546
* @param {boolean} [opts.adversarial] - use adversarial review prompt
4647
* @param {string} [opts.focus] - user-supplied focus text
48+
* @param {string[]} [opts.paths] - specific paths to review instead of git diff
4749
* @param {string} pluginRoot - CLAUDE_PLUGIN_ROOT for reading prompt templates
4850
* @returns {Promise<string>}
4951
*/
@@ -61,6 +63,50 @@ export async function buildReviewPrompt(cwd, opts, pluginRoot) {
6163
let prInfo = null;
6264
let diffStat = "";
6365
let overByteLimit = false;
66+
let folderContext = null;
67+
68+
// Step 1: When --path is specified, collect folder context instead of git diff
69+
if (opts.paths && opts.paths.length > 0 && !opts.pr) {
70+
folderContext = await collectFolderContext(cwd, opts.paths, {
71+
maxBytes,
72+
maxFiles,
73+
});
74+
changedFiles = folderContext.files;
75+
overByteLimit = folderContext.overflowed;
76+
const diffBytes = folderContext.totalBytes;
77+
const diffIsComplete = !folderContext.overflowed;
78+
const collectionGuidance = buildCollectionGuidance(diffIsComplete);
79+
80+
const targetLabel = `Review of ${opts.paths.join(", ")}`;
81+
82+
const reviewContext = buildFolderContext(folderContext, {
83+
diffIsComplete,
84+
originalDiffBytes: diffBytes,
85+
maxInlineDiffBytes: maxBytes,
86+
overFileLimit: changedFiles.length > maxFiles,
87+
overByteLimit: folderContext.overflowed,
88+
});
89+
90+
let systemPrompt;
91+
if (opts.adversarial) {
92+
const templatePath = path.join(pluginRoot, "prompts", "adversarial-review.md");
93+
systemPrompt = fs.readFileSync(templatePath, "utf8")
94+
.replace("{{TARGET_LABEL}}", targetLabel)
95+
.replace("{{USER_FOCUS}}", opts.focus || "General review")
96+
.replace("{{REVIEW_COLLECTION_GUIDANCE}}", collectionGuidance)
97+
.replace("{{REVIEW_INPUT}}", reviewContext);
98+
} else {
99+
systemPrompt = buildStandardReviewPrompt(folderContext.content, status, changedFiles, {
100+
...opts,
101+
targetLabel,
102+
prInfo,
103+
reviewContext,
104+
collectionGuidance,
105+
});
106+
}
107+
108+
return systemPrompt;
109+
}
64110

65111
// Step 1: cheap metadata. The status / changed-file list / shortstat
66112
// reads do not materialize the full diff and are safe on any size.
@@ -227,6 +273,44 @@ function buildReviewContext(diff, status, changedFiles, prInfo, opts = {}) {
227273
return sections.join("\n\n");
228274
}
229275

276+
/**
277+
* Build the repository context block for folder/path-based review prompts.
278+
* Uses <files> section instead of <diff> when context is collected from paths.
279+
*/
280+
function buildFolderContext(folderContext, opts = {}) {
281+
const sections = [];
282+
283+
if (folderContext.files.length > 0) {
284+
sections.push(`<files_reviewed>\n${folderContext.files.join("\n")}\n</files_reviewed>`);
285+
}
286+
287+
if (opts.overFileLimit || opts.overByteLimit) {
288+
const reasons = [];
289+
if (opts.overFileLimit) reasons.push(`file count ${folderContext.files.length}`);
290+
if (opts.overByteLimit) {
291+
reasons.push(`content size ${opts.originalDiffBytes} bytes`);
292+
}
293+
const budget = opts.overByteLimit && opts.maxInlineDiffBytes
294+
? `; excerpt budget ${opts.maxInlineDiffBytes} bytes`
295+
: "";
296+
const note = opts.diffIsComplete === false
297+
? "File content is bounded"
298+
: "Review spans multiple files, but all content is included";
299+
sections.push(
300+
`<content_note>\n` +
301+
`${note} (${reasons.join(", ")}${budget}). ` +
302+
`Findings must be supported by the file evidence below.\n` +
303+
`</content_note>`
304+
);
305+
}
306+
307+
if (folderContext.content) {
308+
sections.push(`<files>\n${folderContext.content}\n</files>`);
309+
}
310+
311+
return sections.join("\n\n");
312+
}
313+
230314
/**
231315
* Build a task prompt from user input.
232316
* @param {string} taskText

0 commit comments

Comments
 (0)