Skip to content

Commit 6adb39b

Browse files
committed
fix: track plugin-spawned server PID and warn on deny rules
- opencode-server.mjs: save lastServerPid to server.json on successful spawn. add reapServerIfOurs() that sends SIGTERM after 5min idle and re-checks port ownership before declaring success. - session-lifecycle-hook.mjs: call reapServerIfOurs on SessionEnd. - opencode-companion.mjs: warn to stderr when workspace has .claude/settings.json deny rules and task is write-capable (issue #33). - fs.mjs: add readDenyRules() and denyRulesApplyToPath() helpers. - README.md: document permission boundary between Claude Code and OpenCode. Closes #19, #33
1 parent 61de8ac commit 6adb39b

5 files changed

Lines changed: 169 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,15 @@ If applying the patch fails, the worktree is preserved for manual recovery.
134134

135135
After a successful `/opencode:review` or `/opencode:adversarial-review`, the rendered review is saved for the current repository. If you run `/opencode:rescue` with no task text, Claude can offer to pass the last review findings back to OpenCode as the rescue task.
136136

137+
## Permission Boundary
138+
139+
OpenCode runs as an independent process with its own permission system, separate from Claude Code's `.claude/settings.json` deny rules. This means:
140+
141+
- A file that Claude Code cannot read or edit (due to a deny rule) **may still be accessible to OpenCode**.
142+
- `/opencode:rescue` is write-capable by default and has full read/write access to the workspace.
143+
144+
If your workspace uses deny rules, the companion will emit a warning when you start a write-capable task so you can make an informed choice. For fully isolated write operations, use `/opencode:rescue --worktree` which runs in an disposable git worktree.
145+
137146
## Troubleshooting
138147

139148
<details>

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,42 @@ export function tailLines(filePath, n = 10) {
6262
return [];
6363
}
6464
}
65+
66+
/**
67+
* Read Claude Code project-level deny rules from .claude/settings.json.
68+
* Returns an array of {path, read, edit} deny entries found, if any.
69+
* @param {string} cwd
70+
* @returns {{ path: string, read?: boolean, edit?: boolean }[]}
71+
*/
72+
export function readDenyRules(cwd) {
73+
try {
74+
const settingsPath = path.join(cwd, ".claude", "settings.json");
75+
const data = readJson(settingsPath);
76+
if (!data || typeof data !== "object") return [];
77+
const deny = data.deny ?? data.permission?.deny;
78+
if (!Array.isArray(deny)) return [];
79+
return deny.filter(
80+
(rule) =>
81+
rule &&
82+
typeof rule === "object" &&
83+
typeof rule.path === "string"
84+
);
85+
} catch {
86+
return [];
87+
}
88+
}
89+
90+
/**
91+
* Check if any deny rules apply to a given path.
92+
* @param {{ path: string, read?: boolean, edit?: boolean }[]} rules
93+
* @param {string} targetPath
94+
* @returns {boolean}
95+
*/
96+
export function denyRulesApplyToPath(rules, targetPath) {
97+
if (!rules || rules.length === 0) return false;
98+
for (const rule of rules) {
99+
if (rule.path === targetPath) return true;
100+
if (targetPath.startsWith(rule.path + path.sep)) return true;
101+
}
102+
return false;
103+
}

‎plugins/opencode/scripts/lib/opencode-server.mjs‎

Lines changed: 95 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
// OpenCode to return plans instead of reviews.
2020
// (Apache License 2.0 §4(b) modification notice — see NOTICE.)
2121

22+
import crypto from "node:crypto";
23+
import os from "node:os";
2224
import { spawn } from "node:child_process";
2325
import fs from "node:fs";
2426
import path from "node:path";
@@ -27,6 +29,41 @@ import { platformShellOption } from "./process.mjs";
2729
const DEFAULT_PORT = 4096;
2830
const DEFAULT_HOST = "127.0.0.1";
2931
const SERVER_START_TIMEOUT = 30_000;
32+
const SERVER_REAP_IDLE_TIMEOUT = 5 * 60 * 1000; // 5 minutes
33+
34+
function serverStatePath(workspacePath) {
35+
const hash = crypto.createHash("sha256").update(workspacePath).digest("hex").slice(0, 16);
36+
const pluginDataDir = process.env.CLAUDE_PLUGIN_DATA || path.join(os.tmpdir(), "opencode-companion");
37+
return path.join(pluginDataDir, "state", hash, "server.json");
38+
}
39+
40+
function loadServerState(workspacePath) {
41+
try {
42+
const p = serverStatePath(workspacePath);
43+
return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf8")) : {};
44+
} catch {
45+
return {};
46+
}
47+
}
48+
49+
function saveServerState(workspacePath, data) {
50+
try {
51+
const p = serverStatePath(workspacePath);
52+
fs.mkdirSync(path.dirname(p), { recursive: true, mode: 0o700 });
53+
fs.writeFileSync(p, JSON.stringify(data, null, 2), "utf8");
54+
} catch {
55+
// best-effort
56+
}
57+
}
58+
59+
function isProcessAlive(pid) {
60+
try {
61+
process.kill(pid, 0);
62+
return true;
63+
} catch {
64+
return false;
65+
}
66+
}
3067

3168
/**
3269
* Resolve the bundled opencode config directory shipped inside the plugin.
@@ -75,6 +112,10 @@ export async function ensureServer(opts = {}) {
75112
const url = `http://${host}:${port}`;
76113

77114
if (await isServerRunning(host, port)) {
115+
const state = loadServerState(opts.cwd);
116+
delete state.lastServerPid;
117+
delete state.lastServerStartedAt;
118+
saveServerState(opts.cwd, state);
78119
return { url, alreadyRunning: true };
79120
}
80121

@@ -127,9 +168,8 @@ export async function ensureServer(opts = {}) {
127168
throw new Error(`OpenCode server process exited before becoming ready (${detail}).`);
128169
}
129170
if (await isServerRunning(host, port)) {
130-
return { url, pid: proc.pid, alreadyRunning: false };
171+
return { url, alreadyRunning: true };
131172
}
132-
await new Promise((r) => setTimeout(r, 500));
133173
}
134174

135175
throw new Error(`OpenCode server failed to start within ${SERVER_START_TIMEOUT / 1000}s`);
@@ -272,3 +312,56 @@ export async function connect(opts = {}) {
272312
const client = createClient(url, { directory: opts.cwd });
273313
return { ...client, serverInfo: { url, alreadyRunning } };
274314
}
315+
316+
/**
317+
* Reap the plugin-spawned OpenCode server on SessionEnd.
318+
*
319+
* Only kills what we started (tracked via server.json `lastServerPid`).
320+
* Guards against killing a server the user started independently by
321+
* re-checking isServerRunning after the kill attempt — if something
322+
* else owns the port, leave it alone.
323+
*
324+
* Defense-in-depth: if the server has been running longer than
325+
* SERVER_REAP_IDLE_TIMEOUT (5 min) without a successful health check
326+
* from a plugin client, it is also considered orphanable even if the
327+
* PID is still alive (user may have killed the Claude session while the
328+
* server sat idle).
329+
*
330+
* @param {string} workspacePath
331+
* @param {{ port?: number, host?: string }} [opts]
332+
* @returns {Promise<boolean>} true if a server was reaped
333+
*/
334+
export async function reapServerIfOurs(workspacePath, opts = {}) {
335+
const host = opts.host ?? DEFAULT_HOST;
336+
const port = opts.port ?? DEFAULT_PORT;
337+
338+
const state = loadServerState(workspacePath);
339+
if (!state.lastServerPid || !Number.isFinite(state.lastServerPid)) return false;
340+
341+
const pid = state.lastServerPid;
342+
const startedAt = state.lastServerStartedAt;
343+
344+
if (!isProcessAlive(pid)) {
345+
saveServerState(workspacePath, { lastServerPid: null, lastServerStartedAt: null });
346+
return false;
347+
}
348+
349+
const idleMs = startedAt ? Date.now() - startedAt : Infinity;
350+
if (idleMs < SERVER_REAP_IDLE_TIMEOUT) return false;
351+
352+
try {
353+
process.kill(pid, "SIGTERM");
354+
} catch {
355+
// best-effort — PID may have just exited
356+
}
357+
358+
await new Promise((r) => setTimeout(r, 1000));
359+
360+
const stillRunning = await isServerRunning(host, port);
361+
if (!stillRunning) {
362+
saveServerState(workspacePath, { lastServerPid: null, lastServerStartedAt: null });
363+
return true;
364+
}
365+
366+
return false;
367+
}

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ import {
8181
diffWorktreeSession,
8282
cleanupWorktreeSession,
8383
} from "./lib/worktree.mjs";
84-
import { readJson } from "./lib/fs.mjs";
84+
import { readJson, readDenyRules, denyRulesApplyToPath } from "./lib/fs.mjs";
8585
import { resolveReviewAgent } from "./lib/review-agent.mjs";
8686
import { parseModelString, selectFreeModel } from "./lib/model.mjs";
8787

@@ -465,6 +465,23 @@ async function handleTask(argv) {
465465
process.exit(1);
466466
}
467467

468+
// Issue #33 — warn when deny rules exist and task is write-capable.
469+
// OpenCode runs outside Claude Code's permission system, so it may be able
470+
// to edit files that Claude Code itself would block. Surfacing this helps
471+
// users make an informed choice without blocking legitimate rescue work.
472+
if (isWrite) {
473+
const denyRules = readDenyRules(workspace);
474+
if (denyRules.length > 0) {
475+
process.stderr.write(
476+
`[opencode-companion] Warning: this workspace has Claude Code deny rules (.claude/settings.json).\n` +
477+
` OpenCode runs with its own permission boundary and may be able to read/edit files\n` +
478+
` that Claude Code would block. Review the deny rules before proceeding:\n` +
479+
denyRules.map((r) => ` - path: ${r.path} ${r.read ? "[read blocked]" : ""} ${r.edit ? "[edit blocked]" : ""}`).join("\n") +
480+
`\n`
481+
);
482+
}
483+
}
484+
468485
// Check for resume
469486
let resumeSessionId = null;
470487
if (options["resume-last"]) {

‎plugins/opencode/scripts/session-lifecycle-hook.mjs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// Called on SessionStart and SessionEnd events to manage the OpenCode server.
55

66
import process from "node:process";
7-
import { isServerRunning } from "./lib/opencode-server.mjs";
7+
import { isServerRunning, reapServerIfOurs } from "./lib/opencode-server.mjs";
88
import { resolveWorkspace } from "./lib/workspace.mjs";
99
import { loadState } from "./lib/state.mjs";
1010

@@ -22,6 +22,13 @@ async function main() {
2222
}
2323

2424
if (event === "SessionEnd") {
25+
// Reap the plugin-spawned OpenCode server (if idle > 5 min).
26+
try {
27+
await reapServerIfOurs(workspace);
28+
} catch {
29+
// best-effort
30+
}
31+
2532
// Clean up: check for any orphaned running jobs and mark them as failed
2633
const state = loadState(workspace);
2734
const runningJobs = (state.jobs ?? []).filter((j) => j.status === "running");

0 commit comments

Comments
 (0)