@eduardo191labs/opencode-actions 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,180 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import { GitHub, repoFromEnv, tokenFromEnv } from "./github.js";
5
+ import { loadConfig, resolveSecretEnv, providerAuthPlan } from "./loader.js";
6
+ import { compileConfig, describeCapabilities } from "./compile.js";
7
+ import { createRenderer } from "./runner.js";
8
+ import { describePull, dispatch, handleComment, handleWorkflowFailure, mergePull, reviewPullRequest, } from "./actions.js";
9
+ import { helpText } from "./commands.js";
10
+ async function main() {
11
+ const options = parseArgs(process.argv.slice(2));
12
+ const workspace = options.workspace ?? process.env.GITHUB_WORKSPACE ?? process.cwd();
13
+ const token = tokenFromEnv();
14
+ const github = new GitHub({ token });
15
+ const repo = repoFromEnv();
16
+ const { config, sources } = await loadConfig({
17
+ workspace,
18
+ github,
19
+ configRepo: options.configRepo ?? process.env.OPENCODE_ACTIONS_CONFIG_REPO,
20
+ configRef: options.configRef ?? process.env.OPENCODE_ACTIONS_CONFIG_REF ?? "main",
21
+ inline: options.config,
22
+ });
23
+ const log = (message) => {
24
+ // Everything diagnostic goes to stderr so the workflow can capture stdout.
25
+ process.stderr.write(`[opencode-actions] ${message}\n`);
26
+ };
27
+ log(`config sources: ${sources.join(" → ")}`);
28
+ log(`repository: ${repo.owner}/${repo.repo}`);
29
+ const ctx = { github, repo, config, workspace, log };
30
+ // Provider credentials: export the mapped env and log in non-interactively.
31
+ const secretEnv = resolveSecretEnv(config);
32
+ for (const [key, value] of Object.entries(secretEnv))
33
+ process.env[key] = value;
34
+ for (const auth of providerAuthPlan(config)) {
35
+ log(`provider credentials available for ${auth.provider}`);
36
+ }
37
+ if (options.mode === "config") {
38
+ const compiled = compileConfig(config, { mode: "review" });
39
+ process.stdout.write(JSON.stringify({ config, compiled: compiled.content, sources, warnings: compiled.warnings }, null, 2));
40
+ return;
41
+ }
42
+ if (options.mode === "capabilities") {
43
+ process.stdout.write(describeCapabilities(config).join("\n") + "\n");
44
+ return;
45
+ }
46
+ if (options.mode === "detect") {
47
+ const { detect } = await import("./detect.js");
48
+ const found = await detect(github, repo);
49
+ process.stdout.write(JSON.stringify(found, null, 2) + "\n");
50
+ return;
51
+ }
52
+ if (options.mode === "plan") {
53
+ const { workflowTemplates, detect } = await import("./detect.js");
54
+ const found = await detect(github, repo);
55
+ process.stdout.write(JSON.stringify({ stack: found.stack, workflows: workflowTemplates({
56
+ configRepo: options.configRepo ?? process.env.OPENCODE_ACTIONS_CONFIG_REPO ?? "",
57
+ model: typeof config.opencode?.model === "string" ? config.opencode.model : undefined,
58
+ }) }, null, 2) + "\n");
59
+ return;
60
+ }
61
+ if (options.event === "run") {
62
+ process.stdout.write(helpText(config) + "\n");
63
+ return;
64
+ }
65
+ const payload = await readPayload(options.payload);
66
+ if (!payload) {
67
+ log("no event payload found; set GITHUB_EVENT_PATH or pass --payload");
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ log(`event: ${options.event} (action: ${payload.action ?? "n/a"})`);
72
+ const renderer = createRenderer("github");
73
+ renderer.banner([`opencode-actions · ${options.event}`, `repo ${repo.owner}/${repo.repo}`]);
74
+ if (options.dryRun) {
75
+ const compiled = compileConfig(config, { mode: "review" });
76
+ log("dry run: not contacting GitHub or running the agent");
77
+ process.stdout.write(JSON.stringify({ event: options.event, action: payload.action, compiled: compiled.content }, null, 2));
78
+ return;
79
+ }
80
+ const result = await dispatch(ctx, options.event, payload);
81
+ process.stdout.write(JSON.stringify(result ?? { ok: true }) + "\n");
82
+ }
83
+ async function readPayload(path) {
84
+ const file = path ?? process.env.GITHUB_EVENT_PATH;
85
+ if (!file || !existsSync(file))
86
+ return null;
87
+ return JSON.parse(await readFile(file, "utf8"));
88
+ }
89
+ function parseArgs(argv) {
90
+ const options = {
91
+ event: process.env.OPENCODE_ACTIONS_EVENT ?? "pull_request",
92
+ workspace: process.env.GITHUB_WORKSPACE ?? process.cwd(),
93
+ dryRun: false,
94
+ };
95
+ for (let index = 0; index < argv.length; index++) {
96
+ const arg = argv[index];
97
+ const next = () => argv[++index];
98
+ switch (arg) {
99
+ case "--event":
100
+ options.event = next();
101
+ break;
102
+ case "--payload":
103
+ options.payload = next();
104
+ break;
105
+ case "--config":
106
+ options.config = next();
107
+ break;
108
+ case "--config-file": {
109
+ const file = next();
110
+ options.config = file && existsSync(file) ? readFileSync(file, "utf8") : undefined;
111
+ break;
112
+ }
113
+ case "--config-repo":
114
+ options.configRepo = next();
115
+ break;
116
+ case "--config-ref":
117
+ options.configRef = next();
118
+ break;
119
+ case "--workspace":
120
+ options.workspace = next();
121
+ break;
122
+ case "--mode":
123
+ options.mode = next();
124
+ break;
125
+ case "--pr":
126
+ options.pr = Number(next());
127
+ break;
128
+ case "--issue":
129
+ options.issue = Number(next());
130
+ break;
131
+ case "--run-id":
132
+ options.runId = Number(next());
133
+ break;
134
+ case "--dry-run":
135
+ options.dryRun = true;
136
+ break;
137
+ case "--help":
138
+ case "-h":
139
+ process.stdout.write(usage());
140
+ process.exit(0);
141
+ break;
142
+ default:
143
+ if (arg.startsWith("--")) {
144
+ process.stderr.write(`Unknown flag ${arg}\n`);
145
+ process.exit(2);
146
+ }
147
+ }
148
+ }
149
+ return options;
150
+ }
151
+ function usage() {
152
+ return `opencode-actions — GitHub bot for OpenCode
153
+
154
+ Usage:
155
+ opencode-actions --event <event> [flags]
156
+
157
+ issue_comment | issue_comment | workflow_run | push | workflow_dispatch
158
+
159
+ Flags:
160
+ --payload <file> Event payload (default: $GITHUB_EVENT_PATH)
161
+ --config <json|yaml> Inline configuration
162
+ --config-repo <repo> Configuration repository, "owner/repo"
163
+ --config-ref <ref> Configuration repository ref (default: main)
164
+ --workspace <dir> Checkout directory (default: $GITHUB_WORKSPACE)
165
+ --mode <mode> config | capabilities | run
166
+ --dry-run Print the compiled config and exit
167
+
168
+ Environment:
169
+ GITHUB_TOKEN Required
170
+ GITHUB_REPOSITORY Required, "owner/repo"
171
+ GITHUB_EVENT_PATH Event payload path
172
+ OPENCODE_BOT_MODEL Override the model
173
+ `;
174
+ }
175
+ main().catch((error) => {
176
+ process.stderr.write(`\nopencode-actions failed: ${error.stack ?? error}\n`);
177
+ process.exit(1);
178
+ });
179
+ // Re-export the public surface so the package entry point stays one file.
180
+ export { reviewPullRequest, handleComment, handleWorkflowFailure, describePull, mergePull, dispatch };
@@ -0,0 +1,23 @@
1
+ import type { BotConfig, CommandInvocation } from "./config.js";
2
+ export declare const KNOWN_COMMANDS: readonly ["review", "fix", "explain", "test", "docs", "describe", "triage", "answer", "merge", "close", "reopen", "label", "assign", "implement", "help", "stop"];
3
+ export type KnownCommand = (typeof KNOWN_COMMANDS)[number];
4
+ export declare function parseCommand(body: string, config: BotConfig): CommandInvocation | null;
5
+ export declare function parseInvocation(body: string, config: BotConfig): CommandInvocation | null;
6
+ export interface ActorContext {
7
+ login: string;
8
+ permission: string | null;
9
+ teams: string[];
10
+ }
11
+ export declare function canRun(config: BotConfig, invocation: CommandInvocation, actor: ActorContext): {
12
+ ok: boolean;
13
+ reason?: string;
14
+ };
15
+ export declare function helpText(config: BotConfig): string;
16
+ /**
17
+ * Extract file/line references such as `src/app.ts:42` from free text so the
18
+ * agent can be pointed at the exact location a reviewer means.
19
+ */
20
+ export declare function extractReferences(body: string): {
21
+ path: string;
22
+ line?: number;
23
+ }[];
@@ -0,0 +1,120 @@
1
+ import { bot as botLayer } from "./config.js";
2
+ export const KNOWN_COMMANDS = [
3
+ "review",
4
+ "fix",
5
+ "explain",
6
+ "test",
7
+ "docs",
8
+ "describe",
9
+ "triage",
10
+ "answer",
11
+ "merge",
12
+ "close",
13
+ "reopen",
14
+ "label",
15
+ "assign",
16
+ "implement",
17
+ "help",
18
+ "stop",
19
+ ];
20
+ const COMMAND_HELP = {
21
+ review: "Review the pull request (or a diff) and post findings.",
22
+ fix: "Fix the reported problem and push a commit.",
23
+ explain: "Explain what a file, diff or error means.",
24
+ test: "Write or run tests for the change.",
25
+ docs: "Update documentation for the change.",
26
+ describe: "Rewrite the PR description from the actual diff.",
27
+ triage: "Classify an issue: labels, severity and a plan.",
28
+ answer: "Answer an issue question with repository context.",
29
+ merge: "Merge the pull request (respects the merge permission).",
30
+ close: "Close an issue or pull request.",
31
+ reopen: "Reopen an issue or pull request.",
32
+ label: "Add or remove labels: `label +bug -docs`.",
33
+ assign: "Assign users: `assign @user1 @user2`.",
34
+ implement: "Implement an issue from scratch and open a PR.",
35
+ help: "Show this command list.",
36
+ stop: "Cancel the current run.",
37
+ };
38
+ /** Strip a fenced code block so commands quoted inside diffs do not trigger. */
39
+ function stripFences(body) {
40
+ return body.replace(/```[\s\S]*?```/g, "");
41
+ }
42
+ export function parseCommand(body, config) {
43
+ return parseInvocation(body, config);
44
+ }
45
+ export function parseInvocation(body, config) {
46
+ if (!body)
47
+ return null;
48
+ const prefix = botLayer(config).commands?.prefix ?? "/bot";
49
+ const cleaned = stripFences(body);
50
+ const enabled = new Set(botLayer(config).commands?.enabled ?? KNOWN_COMMANDS);
51
+ for (const line of cleaned.split(/\r?\n/)) {
52
+ const trimmed = line.trim();
53
+ if (!trimmed.toLowerCase().startsWith(prefix.toLowerCase()))
54
+ continue;
55
+ const rest = trimmed.slice(prefix.length).trim();
56
+ if (!rest)
57
+ continue;
58
+ // Support "/bot review" and "@bot review" style invocations.
59
+ const [head = "", ...args] = rest.split(/\s+/);
60
+ const command = head.replace(/^@/, "").toLowerCase();
61
+ if (!enabled.has(command))
62
+ continue;
63
+ return {
64
+ command,
65
+ args,
66
+ raw: trimmed,
67
+ actor: "",
68
+ source: "issue_comment",
69
+ };
70
+ }
71
+ return null;
72
+ }
73
+ export function canRun(config, invocation, actor) {
74
+ const admins = botLayer(config).commands?.admins ?? [];
75
+ if (admins.includes(actor.login))
76
+ return { ok: true };
77
+ const allowUsers = botLayer(config).commands?.allow_users ?? [];
78
+ const allowTeams = botLayer(config).commands?.allow_teams ?? [];
79
+ if (allowUsers.length === 0 && allowTeams.length === 0) {
80
+ const min = botLayer(config).commands?.min_permission ?? "write";
81
+ const rank = { read: 0, triage: 1, write: 2, maintain: 3, admin: 4 };
82
+ const have = rank[actor.permission ?? "none"] ?? -1;
83
+ if (have >= (rank[min] ?? 2))
84
+ return { ok: true };
85
+ return { ok: false, reason: `\`${actor.login}\` needs \`${min}\` permission to use commands.` };
86
+ }
87
+ if (allowUsers.includes(actor.login))
88
+ return { ok: true };
89
+ if (allowTeams.some((team) => actor.teams.includes(team)))
90
+ return { ok: true };
91
+ return { ok: false, reason: `\`${actor.login}\` is not in \`commands.allow_users\` / \`allow_teams\`.` };
92
+ }
93
+ export function helpText(config) {
94
+ const prefix = botLayer(config).commands?.prefix ?? "/bot";
95
+ const enabled = new Set(botLayer(config).commands?.enabled ?? KNOWN_COMMANDS);
96
+ const lines = [`**Commands** — comment \`${prefix} <command>\` on an issue or PR.`, ""];
97
+ for (const command of KNOWN_COMMANDS) {
98
+ if (!enabled.has(command))
99
+ continue;
100
+ lines.push(`- \`${prefix} ${command}\` — ${COMMAND_HELP[command]}`);
101
+ }
102
+ return lines.join("\n");
103
+ }
104
+ /**
105
+ * Extract file/line references such as `src/app.ts:42` from free text so the
106
+ * agent can be pointed at the exact location a reviewer means.
107
+ */
108
+ export function extractReferences(body) {
109
+ const refs = [];
110
+ const pattern = /(?:^|\s)([\w./-]+\.\w{1,6})(?::(\d+))?/g;
111
+ for (const match of body.matchAll(pattern)) {
112
+ const path = match[1];
113
+ if (!path)
114
+ continue;
115
+ if (path.includes("/") || path.includes(".")) {
116
+ refs.push({ path, line: match[2] ? Number(match[2]) : undefined });
117
+ }
118
+ }
119
+ return refs;
120
+ }
@@ -0,0 +1,49 @@
1
+ import type { BotConfig } from "./config.js";
2
+ import { feature } from "./config.js";
3
+ import { REVIEW_SCHEMA } from "./prompts.js";
4
+ export interface CompiledConfig {
5
+ /** Object serialized into OPENCODE_CONFIG_CONTENT. */
6
+ content: Record<string, unknown>;
7
+ /** Warnings worth printing in the Actions log. */
8
+ warnings: string[];
9
+ /** Effective model. */
10
+ model?: string;
11
+ }
12
+ /**
13
+ * Turn the bot configuration into a real OpenCode configuration.
14
+ *
15
+ * The `opencode` block is forwarded verbatim (so every upstream field works).
16
+ * The `bot` block is then translated into concrete decisions:
17
+ *
18
+ * - GitHub permissions become OpenCode *tool permission rules*
19
+ * ({ action, resource, effect }), which is the shape OpenCode validates.
20
+ * - Unused tools are denied so the agent cannot wander outside the task.
21
+ * - The bot agent is created with an explicit, narrow ruleset.
22
+ * - Secrets, MCP servers and plugins are wired through.
23
+ */
24
+ export declare function compileConfig(config: BotConfig, options?: {
25
+ mode: TaskMode;
26
+ offline?: boolean;
27
+ }): CompiledConfig;
28
+ export type TaskMode = "review" | "issues" | "autofix" | "commands" | "describe" | "implement";
29
+ /**
30
+ * Map GitHub capabilities onto OpenCode tool rules.
31
+ *
32
+ * Order matters: OpenCode evaluates the ruleset in order and later rules win for
33
+ * matching resources, so a broad allow is written before a narrow deny.
34
+ */
35
+ export declare function buildPermissionRules(config: BotConfig, mode: TaskMode): {
36
+ action: string;
37
+ resource: string;
38
+ effect: "allow" | "deny" | "ask";
39
+ }[];
40
+ /** Human-readable summary of what the bot is allowed to do, for the run log. */
41
+ export declare function describeCapabilities(config: BotConfig): string[];
42
+ /**
43
+ * Produce a short description of repository facts the agent should not have to
44
+ * rediscover: languages, package manager, test command.
45
+ */
46
+ export declare function repoFacts(files: string[]): string;
47
+ /** True when the mode needs a writable checkout. */
48
+ export declare function needsWrite(mode: TaskMode): boolean;
49
+ export { REVIEW_SCHEMA, feature };
@@ -0,0 +1,217 @@
1
+ import { permission, feature } from "./config.js";
2
+ import { REVIEW_SCHEMA } from "./prompts.js";
3
+ /**
4
+ * Turn the bot configuration into a real OpenCode configuration.
5
+ *
6
+ * The `opencode` block is forwarded verbatim (so every upstream field works).
7
+ * The `bot` block is then translated into concrete decisions:
8
+ *
9
+ * - GitHub permissions become OpenCode *tool permission rules*
10
+ * ({ action, resource, effect }), which is the shape OpenCode validates.
11
+ * - Unused tools are denied so the agent cannot wander outside the task.
12
+ * - The bot agent is created with an explicit, narrow ruleset.
13
+ * - Secrets, MCP servers and plugins are wired through.
14
+ */
15
+ export function compileConfig(config, options = { mode: "review" }) {
16
+ const warnings = [];
17
+ const oc = structuredClone(config.opencode ?? {});
18
+ const botCfg = config.bot ?? {};
19
+ // ------------------------------------------------------------ model wiring
20
+ const taskModel = pickTaskModel(config, options.mode);
21
+ const model = taskModel ?? botCfg.model?.id;
22
+ if (model)
23
+ oc.model = model;
24
+ if (!model)
25
+ warnings.push("No model configured; OpenCode will use its default.");
26
+ // ------------------------------------------------------- permissions rules
27
+ const rules = buildPermissionRules(config, options.mode);
28
+ // Existing rules configured by the user come first so their denies win.
29
+ const existing = Array.isArray(oc.permissions) ? oc.permissions : [];
30
+ oc.permissions = [...existing, ...rules];
31
+ // ---------------------------------------------------------------- the agent
32
+ const agents = { ...(oc.agents ?? {}) };
33
+ const agentName = "opencode-bot";
34
+ const existingAgent = agents[agentName] ?? {};
35
+ agents[agentName] = {
36
+ description: "Autonomous GitHub Actions agent for opencode-actions.",
37
+ mode: "primary",
38
+ ...existingAgent,
39
+ permissions: [
40
+ ...(Array.isArray(existingAgent.permissions) ? existingAgent.permissions : []),
41
+ ...rules,
42
+ ],
43
+ };
44
+ oc.agents = agents;
45
+ oc.default_agent = agentName;
46
+ // ------------------------------------------------------------ MCP servers
47
+ if (oc.mcp && !isMcpShape(oc.mcp)) {
48
+ // Accept the friendlier { name: server } form and rewrite it to the real shape.
49
+ oc.mcp = { servers: oc.mcp };
50
+ warnings.push("mcp: wrapped flat server map into { servers: ... } to match the OpenCode schema.");
51
+ }
52
+ // ------------------------------------------------------------ CI hardening
53
+ oc.update = oc.update ?? "disable";
54
+ oc.share = oc.share ?? "disabled";
55
+ oc.automations = oc.automations ?? false;
56
+ if (options.offline)
57
+ oc.websearch = false;
58
+ // A CI run has nobody to answer a permission prompt; anything left as "ask"
59
+ // is a bug in the configuration, so make it explicit instead of hanging.
60
+ const asks = oc.permissions.filter((rule) => rule.effect === "ask");
61
+ for (const rule of asks) {
62
+ if (!isInteractiveCapable(rule))
63
+ warnings.push(`permission "${rule.action}" is "ask"; the run will reject it in CI.`);
64
+ }
65
+ return { content: oc, warnings, model };
66
+ }
67
+ function pickTaskModel(config, mode) {
68
+ const tasks = config.bot?.model?.tasks;
69
+ if (!tasks)
70
+ return undefined;
71
+ switch (mode) {
72
+ case "review":
73
+ return tasks.review;
74
+ case "issues":
75
+ return tasks.issues;
76
+ case "autofix":
77
+ return tasks.autofix;
78
+ case "commands":
79
+ return tasks.commands;
80
+ case "describe":
81
+ return tasks.describe;
82
+ case "implement":
83
+ return tasks.implement ?? tasks.issues;
84
+ }
85
+ }
86
+ function isMcpShape(value) {
87
+ if (typeof value !== "object" || value === null)
88
+ return false;
89
+ const record = value;
90
+ return "servers" in record || "timeout" in record;
91
+ }
92
+ function isInteractiveCapable(_rule) {
93
+ // In CI nothing can be asked; a run that hits "ask" is rejected by the runner.
94
+ return false;
95
+ }
96
+ /**
97
+ * Map GitHub capabilities onto OpenCode tool rules.
98
+ *
99
+ * Order matters: OpenCode evaluates the ruleset in order and later rules win for
100
+ * matching resources, so a broad allow is written before a narrow deny.
101
+ */
102
+ export function buildPermissionRules(config, mode) {
103
+ const rules = [];
104
+ const canWrite = config.bot?.write !== false;
105
+ const pushPr = permission(config, "push_pr_branch");
106
+ const pushDefault = permission(config, "push_default_branch");
107
+ const runCommands = permission(config, "run_commands");
108
+ const readSecrets = permission(config, "read_secrets");
109
+ const editWorkflows = permission(config, "edit_workflows");
110
+ // Deny by default, then re-allow the tools this task legitimately needs.
111
+ rules.push({ action: "*", resource: "*", effect: "deny" });
112
+ // Reading is always allowed: the agent cannot reason about code it cannot read.
113
+ rules.push({ action: "read", resource: "*", effect: "allow" });
114
+ rules.push({ action: "glob", resource: "*", effect: "allow" });
115
+ rules.push({ action: "grep", resource: "*", effect: "allow" });
116
+ rules.push({ action: "list", resource: "*", effect: "allow" });
117
+ rules.push({ action: "external_directory", resource: "*", effect: "allow" });
118
+ // Web access only when the task benefits from it.
119
+ if (mode === "review" || mode === "issues" || mode === "commands") {
120
+ rules.push({ action: "webfetch", resource: "*", effect: "allow" });
121
+ }
122
+ else {
123
+ rules.push({ action: "webfetch", resource: "*", effect: "deny" });
124
+ }
125
+ // Shell: needed to inspect git state and run tests.
126
+ if (runCommands === "allow") {
127
+ rules.push({ action: "shell", resource: "*", effect: "allow" });
128
+ rules.push({ action: "bash", resource: "*", effect: "allow" });
129
+ }
130
+ else if (runCommands === "ask") {
131
+ rules.push({ action: "shell", resource: "*", effect: "deny" });
132
+ }
133
+ else {
134
+ rules.push({ action: "shell", resource: "*", effect: "deny" });
135
+ }
136
+ // Editing: gated by GitHub permissions AND by whether this task writes at all.
137
+ // A review must never mutate the checkout, even when the bot may push to PR branches.
138
+ const writesInThisTask = mode === "autofix" || mode === "implement" || mode === "commands";
139
+ const mayEdit = canWrite && writesInThisTask && pushPr === "allow";
140
+ if (mayEdit) {
141
+ rules.push({ action: "edit", resource: "*", effect: "allow" });
142
+ rules.push({ action: "write", resource: "*", effect: "allow" });
143
+ rules.push({ action: "patch", resource: "*", effect: "allow" });
144
+ }
145
+ else {
146
+ rules.push({ action: "edit", resource: "*", effect: "deny" });
147
+ rules.push({ action: "write", resource: "*", effect: "deny" });
148
+ rules.push({ action: "patch", resource: "*", effect: "deny" });
149
+ }
150
+ // Workflow files: a separate gate, because they grant CI privileges.
151
+ if (editWorkflows === "allow") {
152
+ rules.push({ action: "edit", resource: "**/.github/workflows/**", effect: "allow" });
153
+ }
154
+ else {
155
+ rules.push({ action: "edit", resource: "**/.github/workflows/**", effect: "deny" });
156
+ rules.push({ action: "edit", resource: ".github/workflows/**", effect: "deny" });
157
+ }
158
+ // Secrets: never readable through the file tools.
159
+ if (readSecrets !== "allow") {
160
+ rules.push({ action: "read", resource: "**/*.env", effect: "deny" });
161
+ rules.push({ action: "read", resource: "**/*.env.*", effect: "deny" });
162
+ rules.push({ action: "read", resource: "**/*.pem", effect: "deny" });
163
+ rules.push({ action: "read", resource: "**/*.key", effect: "deny" });
164
+ rules.push({ action: "read", resource: "**/id_rsa*", effect: "deny" });
165
+ }
166
+ // The reviewer must not delegate to subagents (cost, and no context sharing).
167
+ if (mode === "review") {
168
+ rules.push({ action: "subagent", resource: "*", effect: "deny" });
169
+ }
170
+ return rules;
171
+ }
172
+ /** Human-readable summary of what the bot is allowed to do, for the run log. */
173
+ export function describeCapabilities(config) {
174
+ const lines = [];
175
+ const perms = config.bot?.permissions ?? {};
176
+ for (const [key, value] of Object.entries(perms)) {
177
+ const icon = value === "allow" ? "✓" : value === "ask" ? "?" : "✗";
178
+ lines.push(`${icon} ${key}: ${value}`);
179
+ }
180
+ return lines;
181
+ }
182
+ /**
183
+ * Produce a short description of repository facts the agent should not have to
184
+ * rediscover: languages, package manager, test command.
185
+ */
186
+ export function repoFacts(files) {
187
+ const facts = [];
188
+ const has = (name) => files.some((file) => file === name || file.endsWith(`/${name}`));
189
+ if (has("package.json"))
190
+ facts.push("Node.js project (package.json)");
191
+ if (has("bun.lockb") || has("bun.lock"))
192
+ facts.push("uses bun");
193
+ else if (has("pnpm-lock.yaml"))
194
+ facts.push("uses pnpm");
195
+ else if (has("yarn.lock"))
196
+ facts.push("uses yarn");
197
+ else if (has("package-lock.json"))
198
+ facts.push("uses npm");
199
+ if (has("Cargo.toml"))
200
+ facts.push("Rust project (Cargo.toml)");
201
+ if (has("go.mod"))
202
+ facts.push("Go module (go.mod)");
203
+ if (has("pyproject.toml"))
204
+ facts.push("Python project (pyproject.toml)");
205
+ if (has("requirements.txt"))
206
+ facts.push("Python project (requirements.txt)");
207
+ if (has("pom.xml"))
208
+ facts.push("Maven project (pom.xml)");
209
+ if (has("build.gradle") || has("build.gradle.kts"))
210
+ facts.push("Gradle project");
211
+ return facts.join("\n");
212
+ }
213
+ /** True when the mode needs a writable checkout. */
214
+ export function needsWrite(mode) {
215
+ return mode === "autofix" || mode === "implement" || mode === "commands";
216
+ }
217
+ export { REVIEW_SCHEMA, feature };