Skip to content

Commit 1c61980

Browse files
committed
feat: throttle controls for stop-time review gate
Add --review-gate-max and --review-gate-cooldown flags to /opencode:setup so users can bound the review gate's spend: /opencode:setup --review-gate-max 5 /opencode:setup --review-gate-cooldown 10 /opencode:setup --review-gate-max off The stop hook now loads state before touching stdin, checks reviewGateMaxPerSession and reviewGateCooldownMinutes against the current session's reviewGateUsage entry, and allows the stop without running OpenCode when a limit would be exceeded. Usage entries older than 7 days are pruned on each successful run so state.json doesn't grow unbounded. renderSetup surfaces the configured limits. Closes #48. Port of openai/codex-plugin-cc#20.
1 parent a1019be commit 1c61980

4 files changed

Lines changed: 111 additions & 4 deletions

File tree

‎plugins/opencode/commands/setup.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
description: Check whether the local OpenCode CLI is ready and optionally toggle the stop-time review gate
3-
argument-hint: '[--enable-review-gate|--disable-review-gate]'
3+
argument-hint: '[--enable-review-gate|--disable-review-gate] [--review-gate-max <n|off>] [--review-gate-cooldown <minutes|off>]'
44
allowed-tools: Bash(node:*), Bash(npm:*), Bash(brew:*), Bash(curl:*), AskUserQuestion
55
---
66

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,14 @@ export function renderSetup(status) {
208208
lines.push(`- **Providers**: None configured. Run \`!opencode providers\` to set up.`);
209209
}
210210
if (status.reviewGate !== undefined) {
211-
lines.push(`- **Review Gate**: ${status.reviewGate ? "Enabled" : "Disabled"}`);
211+
const parts = [status.reviewGate ? "Enabled" : "Disabled"];
212+
if (status.reviewGateMaxPerSession != null) {
213+
parts.push(`limit ${status.reviewGateMaxPerSession}/session`);
214+
}
215+
if (status.reviewGateCooldownMinutes != null) {
216+
parts.push(`cooldown ${status.reviewGateCooldownMinutes} min`);
217+
}
218+
lines.push(`- **Review Gate**: ${parts.join(", ")}`);
212219
}
213220

214221
return lines.join("\n");

‎plugins/opencode/scripts/opencode-companion.mjs‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ handler(argv).catch((err) => {
101101

102102
async function handleSetup(argv) {
103103
const { options } = parseArgs(argv, {
104+
valueOptions: ["review-gate-max", "review-gate-cooldown"],
104105
booleanOptions: ["json", "enable-review-gate", "disable-review-gate"],
105106
});
106107

@@ -143,7 +144,45 @@ async function handleSetup(argv) {
143144
reviewGate = state.config?.reviewGate ?? false;
144145
}
145146

146-
const status = { installed, version, serverRunning, providers, reviewGate };
147+
if (options["review-gate-max"] != null) {
148+
const raw = options["review-gate-max"];
149+
const max = raw === "off" ? null : Number(raw);
150+
if (max !== null && (!Number.isInteger(max) || max < 1)) {
151+
console.error(`--review-gate-max must be a positive integer or "off".`);
152+
process.exit(1);
153+
}
154+
updateState(workspace, (state) => {
155+
state.config = state.config || {};
156+
state.config.reviewGateMaxPerSession = max;
157+
});
158+
}
159+
160+
if (options["review-gate-cooldown"] != null) {
161+
const raw = options["review-gate-cooldown"];
162+
const cooldown = raw === "off" ? null : Number(raw);
163+
if (cooldown !== null && (!Number.isInteger(cooldown) || cooldown < 1)) {
164+
console.error(`--review-gate-cooldown must be a positive integer (minutes) or "off".`);
165+
process.exit(1);
166+
}
167+
updateState(workspace, (state) => {
168+
state.config = state.config || {};
169+
state.config.reviewGateCooldownMinutes = cooldown;
170+
});
171+
}
172+
173+
const finalState = loadState(workspace);
174+
const reviewGateMaxPerSession = finalState.config?.reviewGateMaxPerSession ?? null;
175+
const reviewGateCooldownMinutes = finalState.config?.reviewGateCooldownMinutes ?? null;
176+
177+
const status = {
178+
installed,
179+
version,
180+
serverRunning,
181+
providers,
182+
reviewGate,
183+
reviewGateMaxPerSession,
184+
reviewGateCooldownMinutes,
185+
};
147186

148187
if (options.json) {
149188
console.log(JSON.stringify(status, null, 2));

‎plugins/opencode/scripts/stop-review-gate-hook.mjs‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,38 @@ import process from "node:process";
88
import fs from "node:fs";
99
import path from "node:path";
1010
import { resolveWorkspace } from "./lib/workspace.mjs";
11-
import { loadState } from "./lib/state.mjs";
11+
import { loadState, updateState } from "./lib/state.mjs";
1212
import { isServerRunning, connect } from "./lib/opencode-server.mjs";
1313
import { resolveReviewAgent } from "./lib/review-agent.mjs";
1414

1515
const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || path.resolve(import.meta.dirname, "..");
1616

17+
function currentSessionId() {
18+
return (
19+
process.env.OPENCODE_COMPANION_SESSION_ID ||
20+
process.env.CLAUDE_SESSION_ID ||
21+
null
22+
);
23+
}
24+
25+
/**
26+
* Prune review-gate usage entries older than 7 days so long-lived workspace
27+
* state doesn't grow unbounded across many Claude sessions.
28+
*/
29+
function pruneOldUsage(usage) {
30+
if (!usage || typeof usage !== "object") return {};
31+
const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
32+
const kept = {};
33+
for (const [sid, entry] of Object.entries(usage)) {
34+
if (!entry?.lastRunAt) continue;
35+
const ts = new Date(entry.lastRunAt).getTime();
36+
if (Number.isFinite(ts) && ts >= cutoff) {
37+
kept[sid] = entry;
38+
}
39+
}
40+
return kept;
41+
}
42+
1743
async function main() {
1844
const workspace = await resolveWorkspace();
1945

@@ -25,6 +51,27 @@ async function main() {
2551
return;
2652
}
2753

54+
// Throttle check — honor per-session cap and cooldown if configured.
55+
// Skipped when no session id is available (can't scope the limit safely).
56+
const sessionId = currentSessionId();
57+
if (sessionId) {
58+
const usage = state.reviewGateUsage?.[sessionId] ?? { count: 0, lastRunAt: null };
59+
const max = state.config.reviewGateMaxPerSession;
60+
if (Number.isFinite(max) && usage.count >= max) {
61+
console.log(`ALLOW: Review gate session cap (${max}) reached.`);
62+
return;
63+
}
64+
const cooldownMin = state.config.reviewGateCooldownMinutes;
65+
if (Number.isFinite(cooldownMin) && usage.lastRunAt) {
66+
const elapsedMs = Date.now() - new Date(usage.lastRunAt).getTime();
67+
if (Number.isFinite(elapsedMs) && elapsedMs < cooldownMin * 60 * 1000) {
68+
const remaining = Math.ceil((cooldownMin * 60 * 1000 - elapsedMs) / 1000);
69+
console.log(`ALLOW: Review gate cooldown (${remaining}s remaining).`);
70+
return;
71+
}
72+
}
73+
}
74+
2875
// Check if server is available
2976
if (!(await isServerRunning())) {
3077
console.log("ALLOW: OpenCode server not running.");
@@ -75,6 +122,20 @@ async function main() {
75122
const text = extractText(response);
76123
const firstLine = text.trim().split("\n")[0];
77124

125+
// Bump usage before returning a verdict so the count reflects work
126+
// actually done, even if the verdict BLOCKs.
127+
if (sessionId) {
128+
const nowIso = new Date().toISOString();
129+
updateState(workspace, (s) => {
130+
s.reviewGateUsage = pruneOldUsage(s.reviewGateUsage);
131+
const prior = s.reviewGateUsage[sessionId] ?? { count: 0, lastRunAt: null };
132+
s.reviewGateUsage[sessionId] = {
133+
count: prior.count + 1,
134+
lastRunAt: nowIso,
135+
};
136+
});
137+
}
138+
78139
if (firstLine.startsWith("BLOCK")) {
79140
// Output BLOCK to stderr so Claude Code sees it
80141
process.stderr.write(`OpenCode review gate: ${firstLine}\n`);

0 commit comments

Comments
 (0)