Skip to content

Commit 3616f9d

Browse files
terisukeclaude
andcommitted
fix(guardrails): translate the 2.x tool vocabulary for the 1.x guards; worker placement, permissions, launcher
Review round on #343 (code-reviewer agent + Codex route A, 2026-10-19): the bridge loaded and passed its tests, but most tool gates never fired on 2.x because 2.x renamed the built-in tools and their argument keys (packages/core/src/v1/config/migrate.ts normalizeAction: bash→shell, task→subagent, write/patch→edit; file tools take `path`, the subagent tool `agent`, the shell result `metadata.exit`) and the 1.x guards compare against the old names (a `shell` cat of the dotenv file, a `read {path}` of a secret file, `git push origin dev` all passed; with the 1.x shapes they blocked). - adapter: toV1Call / toV2Input translate every tool call to the 1.x shape before the hook and back afterwards (a native `patch` is judged as an edit of its first file); execute.after maps `metadata.exit` → `exitCode` and marks a tool error with a string, as guardrail-access.ts expects; the provider gate also runs on the compaction / generate / title hooks; model catalog misses are cached (TTL 60 s); `permission.asked` is handed to the 1.x event hook with permission/patterns; the event loop re-subscribes with backoff instead of dying with the stream - command.execute.before: 2.x expands a command into a plain prompt (core/src/config/plugin/command.ts), so the five packaged command templates end with `<!-- guardrails:command=NAME -->` and the prompt hook recognises the marker (literal `/name` text still works); workflow_phase and the state summary reach the model again - client: permission rules and the 1.x per-prompt `tools: { x: false }` list go through normalizeAction and become 2.x `permissions` (deny rules via session.update); a child created with parentID inherits the parent's location in 2.x, so the worker is moved to its isolated worktree with session.move; `noReply` notifications become a synthetic message with resume:false (no model run, no wait); a failed/interrupted execution is kept (events.ts) and surfaced to team.ts as an errored assistant row instead of a clean "done" - bin/opencode-guardrails: OPENCODE_CONFIG_DIR replaces the global config dir in 2.x, so the user's global opencode.json(c) is re-added through OPENCODE_CONFIG; extra plugins merge into an existing OPENCODE_CONFIG_CONTENT; no checkout candidate (bun install does not fetch the CLI binaries); PATH scan skips wrappers without reading large binaries; a `.cjs` shim target does not inherit OPENCODE_BIN_PATH (it would loop) - tool.ts: no additionalProperties:false (zod stripped unknown keys) - bun.lock: workspace entry for packages/guardrails (frozen installs failed without it) Verified: bun test profile/src profile/plugins 110 pass / 0 fail — new tests fire 2.x-shaped calls (shell cat of the dotenv file, `git push origin dev`, read {path} of a secret file, edit of the guardrail state) and expect the block, check exit code / error mapping, rule and tool-deny mapping, session.move, noReply → synthetic, failure row, marker detection, toV1Call/toV2Input round trip; live load with @opencode/cli 2.0.32 (scratch XDG, no key): 3 plugin directories, 0 failed loads, run starts as implement · glm-5.3. Agent-Lane: claude-code Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 454d01a commit 3616f9d

13 files changed

Lines changed: 414 additions & 110 deletions

File tree

‎bun.lock‎

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/guardrails/README.md‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,24 @@ unchanged); `profile/src/v2/` is the bridge:
5757
| `src/v2/background.ts` | local copy of the 19-line `Background` registry team.ts used from core |
5858
| `plugins/guardrail/index.ts`, `plugins/team/index.ts` | the directory entries listed in `profile/opencode.json` `plugins` |
5959

60-
Known gaps of the bridge (documented, not hidden): the 1.x `command.execute.before` hook has no 2.x wrap point
61-
(`CommandEditor` only adds commands), so `/implement` `/review` `/ship` `/handoff` prompt augmentation is best-effort on
62-
slash-command text in the prompt hook; `body.tools` per-prompt tool allow-lists for workers are dropped (agents and
63-
permissions restrict workers instead); `dropKeylessCatalogLanes` cannot mutate the live 2.x config and only shapes the
64-
whitelist. The provider gate reads model cost/status from `ctx.model.list()`; a model missing from the catalog has
65-
unknown cost, which is not treated as free-tier.
60+
Tool vocabulary: 2.x renamed the built-in tools and their argument keys (`bash→shell`, `task→subagent`,
61+
`write/patch→edit`; file tools take `path`, the subagent tool `agent`, the shell result `metadata.exit` — the same table
62+
upstream applies to migrated v1 config in `packages/core/src/v1/config/migrate.ts`). The 1.x guards compare against the
63+
old names, so the adapter translates every tool call to the 1.x shape before the hook and back afterwards
64+
(`toV1Call` / `toV2Input`); a native `patch` is judged as an `edit` of its first file. Worker permission rules and the
65+
1.x per-prompt `tools: { x: false }` lists go through the same mapping as 2.x `permissions` (deny rules), and a worker
66+
created with `parentID` is moved to its isolated directory afterwards because the 2.x host lets a child inherit the
67+
parent's location.
68+
69+
Known gaps of the bridge (documented, not hidden): 2.x expands a command into a plain prompt and offers no wrap point
70+
(`CommandEditor` only adds commands), so the five packaged command templates end with a marker
71+
`<!-- guardrails:command=NAME -->` that the prompt hook recognises to run the 1.x `command.execute.before`
72+
(`workflow_phase`, state summary); a command without the marker is only recognised as literal `/name` text.
73+
`dropKeylessCatalogLanes` cannot mutate the live 2.x config and only shapes the whitelist. The provider gate runs on
74+
the `context`, `compaction`, `generate` and `title` hooks and reads model cost/status from `ctx.model.list()`
75+
(cached, misses included); a model missing from the catalog has unknown cost, which is not treated as free-tier.
76+
`session.status` / `session.idle` have no publisher in 2.x core; worker status is derived from the
77+
`session.execution.*` events and a failed execution is surfaced to team.ts as an errored assistant row.
6678

6779
Tests: `bun test profile/src profile/plugins` (from `packages/guardrails`). `src/v2/adapter.test.ts` drives the real v2
6880
entries with a recording 2.x ctx; `src/plugin-loads.test.ts` pins the three 2.x loader facts the entries rely on against

‎packages/guardrails/bin/opencode-guardrails‎

Lines changed: 67 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,20 @@
33
//
44
// 1.x resolved the CLI from the sibling `packages/opencode` package; upstream 2.x has no such package and the fork
55
// no longer ships a build of its own. The 2.x binary is resolved, in order, from:
6-
// 1. OPENCODE_BIN_PATH (the local wrapper under ~/.local/bin pins it explicitly)
7-
// 2. <repo>/packages/cli/bin/opencode.cjs (monorepo checkout with `bun install` done)
8-
// 3. an installed `opencode` on PATH that is not this launcher's own wrapper (e.g. ~/.opencode-2/pkg)
9-
// The packaged profile is applied through OPENCODE_CONFIG_DIR (2.x still honours it: packages/cli/src/index.ts).
10-
// Extra plugin directories (e.g. the AIDD H17 common control, ~/.config/opencode/plugins/aidd-cc-v2) are added with
11-
// OPENCODE_GUARDRAILS_EXTRA_PLUGINS (path list, ":" separated) through the OPENCODE_CONFIG_CONTENT layer, so the
12-
// profile file itself stays free of machine-specific paths.
6+
// 1. OPENCODE_BIN_PATH (the local wrapper under ~/.local/bin pins it explicitly)
7+
// 2. an installed `opencode` on PATH that is not a wrapper around this launcher (e.g. ~/.opencode-2/pkg/…/.bin)
8+
// A monorepo checkout is NOT a candidate: `bun install` does not fetch the @opencode/cli-* distribution binaries, so
9+
// packages/cli/bin/opencode.cjs exits with a missing-package error there.
10+
//
11+
// Config layering in 2.x: OPENCODE_CONFIG_DIR *replaces* the global config directory (1.x added it on top), so the
12+
// user's own global config file is handed back to the CLI through OPENCODE_CONFIG (the explicit-file layer) when that
13+
// variable is free. Extra plugin directories (e.g. the AIDD H17 common control, ~/.config/opencode/plugins/aidd-cc-v2)
14+
// are added with OPENCODE_GUARDRAILS_EXTRA_PLUGINS (path list, ":" separated) through the OPENCODE_CONFIG_CONTENT
15+
// layer — merged into an existing OPENCODE_CONFIG_CONTENT, never replacing it — so the profile file itself stays free
16+
// of machine-specific paths. Plugin lists of all layers are concatenated by the 2.x loader.
1317
import { spawnSync } from "node:child_process"
1418
import fs from "node:fs"
19+
import os from "node:os"
1520
import path from "node:path"
1621
import { fileURLToPath } from "node:url"
1722
import { parseEnv } from "node:util"
@@ -24,24 +29,37 @@ function fail(msg) {
2429
}
2530

2631
const here = path.dirname(fileURLToPath(import.meta.url))
27-
const repo = path.resolve(here, "..", "..", "..")
32+
33+
function isWrapper(file) {
34+
// a small text file that mentions this launcher would recurse into us; the real CLI is a large native binary
35+
try {
36+
const st = fs.statSync(file)
37+
if (!st.isFile()) return true
38+
if (st.size > 1024 * 1024) return false
39+
return fs.readFileSync(file, "utf8").includes("opencode-guardrails")
40+
} catch {
41+
return true
42+
}
43+
}
2844

2945
function bin() {
3046
if (process.env.OPENCODE_BIN_PATH) return process.env.OPENCODE_BIN_PATH
31-
const dev = path.join(repo, "packages", "cli", "bin", "opencode.cjs")
32-
if (fs.existsSync(dev) && fs.existsSync(path.join(repo, "node_modules"))) return dev
3347
const self = fs.realpathSync(process.argv[1])
3448
for (const dir of (process.env.PATH || "").split(path.delimiter)) {
49+
if (!dir) continue
3550
const candidate = path.join(dir, "opencode")
36-
if (!fs.existsSync(candidate)) continue
37-
const real = fs.realpathSync(candidate)
38-
if (real === self) continue
39-
if (fs.readFileSync(real, "utf8").includes("opencode-guardrails")) continue // a wrapper that would recurse into us
51+
let real
52+
try {
53+
real = fs.realpathSync(candidate)
54+
} catch {
55+
continue
56+
}
57+
if (real === self || isWrapper(real)) continue
4058
return candidate
4159
}
4260
fail(
4361
"opencode-guardrails: no 2.x CLI found. Set OPENCODE_BIN_PATH to an @opencode/cli binary " +
44-
"(e.g. ~/.opencode-2/pkg/node_modules/.bin/opencode) or run `bun install` in the repo for packages/cli.",
62+
"(e.g. ~/.opencode-2/pkg/node_modules/.bin/opencode).",
4563
)
4664
}
4765

@@ -65,26 +83,55 @@ function load(dir) {
6583
}
6684
}
6785

68-
/** OPENCODE_CONFIG_CONTENT layer with the extra plugin directories; merged with the profile by the 2.x config loader. */
86+
/** The user's global 2.x config file, re-added through OPENCODE_CONFIG since OPENCODE_CONFIG_DIR displaces its directory. */
87+
function keepGlobalConfig() {
88+
if (process.env.OPENCODE_CONFIG) return
89+
const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config")
90+
for (const name of ["opencode.jsonc", "opencode.json"]) {
91+
const file = path.join(base, "opencode", name)
92+
if (!fs.existsSync(file)) continue
93+
process.env.OPENCODE_CONFIG = file
94+
return
95+
}
96+
}
97+
98+
/** OPENCODE_CONFIG_CONTENT layer with the extra plugin directories, merged into any content already there. */
6999
function extraPlugins() {
70100
const dirs = (process.env.OPENCODE_GUARDRAILS_EXTRA_PLUGINS || "")
71101
.split(path.delimiter)
72102
.map((p) => p.trim())
73103
.filter((p) => p && fs.existsSync(p))
74-
if (!dirs.length || process.env.OPENCODE_CONFIG_CONTENT) return
75-
process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ plugins: dirs.map((p) => path.resolve(p)) })
104+
.map((p) => path.resolve(p))
105+
if (!dirs.length) return
106+
let current = {}
107+
if (process.env.OPENCODE_CONFIG_CONTENT) {
108+
try {
109+
current = JSON.parse(process.env.OPENCODE_CONFIG_CONTENT)
110+
} catch (error) {
111+
console.error(`opencode-guardrails: OPENCODE_CONFIG_CONTENT is not JSON (${error.message}); extra plugins not added`)
112+
return
113+
}
114+
}
115+
const plugins = Array.isArray(current.plugins) ? current.plugins : []
116+
process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ ...current, plugins: [...plugins, ...dirs.filter((d) => !plugins.includes(d))] })
76117
}
77118

78119
const dir = path.resolve(here, "..", "profile")
79120
load(process.cwd())
80121
process.env.OPENCODE_CONFIG_DIR ||= dir
122+
keepGlobalConfig()
81123
applyCorLocalDefaults()
82124
applyZaiAuthDefaults()
83125
extraPlugins()
84126

85-
const out = spawnSync(bin(), process.argv.slice(2), {
127+
const target = bin()
128+
const childEnv = { ...process.env }
129+
// the @opencode/cli `opencode.cjs` shim reads OPENCODE_BIN_PATH as *its* target; handing it its own path loops forever
130+
if (target.endsWith(".cjs")) delete childEnv.OPENCODE_BIN_PATH
131+
132+
const out = spawnSync(target, process.argv.slice(2), {
86133
stdio: "inherit",
87-
env: process.env,
134+
env: childEnv,
88135
})
89136

90137
if (out.error) fail(out.error.message)

‎packages/guardrails/profile/commands/auto.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@ Do NOT stop until all steps are complete or a hard blocker is encountered.
1717
Report blockers explicitly with evidence.
1818

1919
$ARGUMENTS
20+
21+
<!-- guardrails:command=auto -->

‎packages/guardrails/profile/commands/handoff.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@ Required sections:
1717
- Next steps
1818

1919
Include any pending approvals, denied operations, provider restrictions, or release gates that still block completion.
20+
21+
<!-- guardrails:command=handoff -->

‎packages/guardrails/profile/commands/implement.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,5 @@ Requirements:
1414
- for AI agent instrumentation or metric work, use source-level hooks only, add integration/smoke coverage, and include traceability from acceptance criteria to code paths
1515

1616
$ARGUMENTS
17+
18+
<!-- guardrails:command=implement -->

‎packages/guardrails/profile/commands/review.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,5 @@ Required sections:
1616
- Recommended next step
1717

1818
Default scope is the current uncommitted work unless `$ARGUMENTS` narrows it.
19+
20+
<!-- guardrails:command=review -->

‎packages/guardrails/profile/commands/ship.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,5 @@ Execute the ship workflow for the current work:
3434
Default scope is the current branch unless $ARGUMENTS specifies a PR number.
3535

3636
$ARGUMENTS
37+
38+
<!-- guardrails:command=ship -->

0 commit comments

Comments
 (0)