Skip to content

Commit 8612096

Browse files
committed
fix(guardrails): steer broad edits through team #29
1 parent 6393d95 commit 8612096

3 files changed

Lines changed: 142 additions & 52 deletions

File tree

‎packages/guardrails/profile/plugins/guardrail.ts‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -109,15 +109,17 @@ function ext(file: string) {
109109
function stash(file: string) {
110110
return Bun.file(file)
111111
.json()
112-
.catch(() => ({} as Record<string, unknown>))
112+
.catch(() => ({}) as Record<string, unknown>)
113113
}
114114

115115
async function save(file: string, data: Record<string, unknown>) {
116116
await Bun.write(file, JSON.stringify(data, null, 2) + "\n")
117117
}
118118

119119
async function line(file: string, data: Record<string, unknown>) {
120-
const prev = await Bun.file(file).text().catch(() => "")
120+
const prev = await Bun.file(file)
121+
.text()
122+
.catch(() => "")
121123
await Bun.write(file, prev + JSON.stringify(data) + "\n")
122124
}
123125

@@ -168,10 +170,7 @@ function free(data: {
168170
return !(ids && ids.has(str(data.id)))
169171
}
170172

171-
function preview(data: {
172-
id?: unknown
173-
status?: unknown
174-
}) {
173+
function preview(data: { id?: unknown; status?: unknown }) {
175174
const id = str(data.id)
176175
const status = str(data.status)
177176
if (status && status !== "active") return true
@@ -197,10 +196,13 @@ function cmp(left: string, right: string) {
197196
return a[2] - b[2]
198197
}
199198

200-
export default async function guardrail(input: {
201-
directory: string
202-
worktree: string
203-
}, opts?: Record<string, unknown>) {
199+
export default async function guardrail(
200+
input: {
201+
directory: string
202+
worktree: string
203+
},
204+
opts?: Record<string, unknown>,
205+
) {
204206
const mode = typeof opts?.mode === "string" ? opts.mode : "enforced"
205207
const evals = new Set<string>([])
206208
const evalAgent = "provider-eval"
@@ -322,7 +324,9 @@ export default async function guardrail(input: {
322324
return baseline(args.oldString, args.newString)
323325
}
324326
if (typeof args.content !== "string") return
325-
const prev = await Bun.file(file).text().catch(() => "")
327+
const prev = await Bun.file(file)
328+
.text()
329+
.catch(() => "")
326330
if (!prev) return
327331
return baseline(prev, args.content)
328332
}
@@ -368,9 +372,7 @@ export default async function guardrail(input: {
368372
}
369373

370374
return {
371-
config: async (cfg: {
372-
provider?: Record<string, { whitelist?: string[] }>
373-
}) => {
375+
config: async (cfg: { provider?: Record<string, { whitelist?: string[] }> }) => {
374376
for (const key of Object.keys(allow)) delete allow[key]
375377
for (const [key, val] of Object.entries(cfg.provider ?? {})) {
376378
const ids = list(val.whitelist)
@@ -415,10 +417,7 @@ export default async function guardrail(input: {
415417
})
416418
}
417419
},
418-
"tool.execute.before": async (
419-
item: { tool: string; args?: unknown },
420-
out: { args: Record<string, unknown> },
421-
) => {
420+
"tool.execute.before": async (item: { tool: string; args?: unknown }, out: { args: Record<string, unknown> }) => {
422421
const file = pick(out.args ?? item.args)
423422
if (file && (item.tool === "read" || item.tool === "edit" || item.tool === "write")) {
424423
const err = deny(file, item.tool === "read" ? "read" : "edit")
@@ -437,7 +436,7 @@ export default async function guardrail(input: {
437436
if ((item.tool === "edit" || item.tool === "write") && file && code(file)) {
438437
const count = await budget()
439438
if (count >= 4) {
440-
const err = `context budget exceeded after ${count} source reads; narrow scope or delegate before editing`
439+
const err = `context budget exceeded after ${count} source reads; narrow scope or delegate with the team tool before editing`
441440
await mark({ last_block: item.tool, last_file: rel(input.worktree, file), last_reason: err })
442441
throw new Error(text(err))
443442
}

‎packages/guardrails/profile/plugins/team.ts‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ type Stat = {
4242

4343
type Client = {
4444
session: {
45-
create(input: { body: { parentID: string; title: string }; query: { directory: string } }): Promise<{ data: { id: string } }>
45+
create(input: {
46+
body: { parentID: string; title: string }
47+
query: { directory: string }
48+
}): Promise<{ data: { id: string } }>
4649
promptAsync(input: {
4750
path: { id: string }
4851
query: { directory: string }
@@ -158,9 +161,10 @@ function big(text: string) {
158161
const data = text.trim()
159162
if (!data) return false
160163
const plan = (data.match(/^\s*([-*]|\d+\.)\s+/gm) ?? []).length
161-
const impl = /(implement|implementation|build|create|add|fix|refactor|rewrite|patch|parallel|subagent|team|background|worker|修正|実装|追加|改修|並列|サブエージェント|チーム)/i.test(
162-
data,
163-
)
164+
const impl =
165+
/(implement|implementation|build|create|add|fix|refactor|rewrite|patch|parallel|subagent|team|background|worker|修正|実装|追加|改修|並列|サブエージェント|チーム)/i.test(
166+
data,
167+
)
164168
const wide =
165169
data.length >= 500 ||
166170
plan >= 3 ||
@@ -237,19 +241,24 @@ async function save(dir: string, run: Run) {
237241
}
238242

239243
async function load(dir: string, id: string) {
240-
const data = await Bun.file(file(dir, id)).json().catch(() => undefined)
244+
const data = await Bun.file(file(dir, id))
245+
.json()
246+
.catch(() => undefined)
241247
return isRun(data) ? data : undefined
242248
}
243249

244250
async function scan(dir: string) {
245251
await mkdir(root(dir), { recursive: true })
246252
const list = await readdir(root(dir)).catch(() => [])
247-
return Promise.all(list.filter((item) => item.endsWith(".json")).map((item) => Bun.file(path.join(root(dir), item)).json().catch(() => undefined))).then(
248-
(list) =>
249-
list
250-
.filter(isRun)
251-
.toSorted((a, b) => String(b.updated_at).localeCompare(String(a.updated_at))),
252-
)
253+
return Promise.all(
254+
list
255+
.filter((item) => item.endsWith(".json"))
256+
.map((item) =>
257+
Bun.file(path.join(root(dir), item))
258+
.json()
259+
.catch(() => undefined),
260+
),
261+
).then((list) => list.filter(isRun).toSorted((a, b) => String(b.updated_at).localeCompare(String(a.updated_at))))
253262
}
254263

255264
async function yardadd(dir: string, id: string) {
@@ -365,11 +374,7 @@ async function stop(client: Client, run: Run) {
365374
).catch(() => undefined)
366375
}
367376

368-
export default async function team(input: {
369-
client: Client
370-
worktree: string
371-
directory: string
372-
}) {
377+
export default async function team(input: { client: Client; worktree: string; directory: string }) {
373378
const job = async (ctx: Ctx, run: Run, item: Step) => {
374379
const push = write(item.prompt, item.write)
375380
const box = push && item.worktree ? await yardadd(ctx.worktree, `${run.id}-${item.id}`) : ctx.directory
@@ -529,7 +534,9 @@ export default async function team(input: {
529534

530535
try {
531536
for (;;) {
532-
const ready = list.filter((item) => item.state === "pending" && item.depends.every((dep) => done.has(dep)) && !active.has(item.id))
537+
const ready = list.filter(
538+
(item) => item.state === "pending" && item.depends.every((dep) => done.has(dep)) && !active.has(item.id),
539+
)
533540

534541
if (args.strategy === "wave" && ready.length) {
535542
ready.forEach((item) => todo(run, item.id, { state: "queued" }))
@@ -676,7 +683,9 @@ export default async function team(input: {
676683
run_id: z.string().optional(),
677684
},
678685
async execute(args, ctx) {
679-
const list = args.run_id ? [live.get(args.run_id) ?? (await load(ctx.worktree, args.run_id))].filter(isRun) : await scan(ctx.worktree)
686+
const list = args.run_id
687+
? [live.get(args.run_id) ?? (await load(ctx.worktree, args.run_id))].filter(isRun)
688+
: await scan(ctx.worktree)
680689
if (!list.length) return "No team runs found."
681690
return list.map((item) => note(item)).join("\n\n")
682691
},
@@ -729,8 +738,7 @@ export default async function team(input: {
729738
sessionID: out.message.sessionID,
730739
messageID: out.message.id,
731740
type: "text",
732-
text:
733-
"Parallel implementation policy is active for this request. Before any edit, write, apply_patch, or mutating bash call, you MUST call the `team` tool and fan out at least two worker tasks. Mark tasks that should edit code with `write: true`; those tasks will be isolated in git worktrees and merged back when possible. Use `background` only for side work that should keep running after this turn.",
741+
text: "Parallel implementation policy is active for this request. Before any edit, write, apply_patch, or mutating bash call, you MUST call the `team` tool and fan out at least two worker tasks. Mark tasks that should edit code with `write: true`; those tasks will be isolated in git worktrees and merged back when possible. Use `background` only for side work that should keep running after this turn.",
734742
})
735743
},
736744
"tool.execute.before": async (
@@ -745,6 +753,12 @@ export default async function team(input: {
745753
const gate = need.get(item.sessionID)
746754
if (!gate || gate.done) return
747755
if (item.tool === "team") return
756+
if (item.tool === "background") {
757+
if (!write(String(out.args.prompt ?? ""), out.args.write === true)) return
758+
throw new Error(
759+
`Parallel implementation is enforced for this turn. Use the team tool with at least two tasks before starting write-capable background workers. Reason: ${gate.reason}`,
760+
)
761+
}
748762
if (item.tool !== "edit" && item.tool !== "write" && item.tool !== "apply_patch" && item.tool !== "bash") return
749763
if (item.tool === "bash" && !mut(String(out.args.command ?? ""))) return
750764
throw new Error(

‎packages/opencode/test/scenario/guardrails.test.ts‎

Lines changed: 90 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -408,14 +408,14 @@ test("guardrail profile enforces provider admission lanes", async () => {
408408
agent: "provider-eval",
409409
model: {
410410
...evalModel,
411-
id: "google/gemini-3-pro-preview" as typeof evalModel.id,
412-
cost: {
413-
...evalModel.cost,
414-
input: 0.1,
415-
output: 0.2,
416-
cache: { read: 0, write: 0 },
417-
},
411+
id: "google/gemini-3-pro-preview" as typeof evalModel.id,
412+
cost: {
413+
...evalModel.cost,
414+
input: 0.1,
415+
output: 0.2,
416+
cache: { read: 0, write: 0 },
418417
},
418+
},
419419
},
420420
{ temperature: undefined, topP: undefined, topK: undefined, options: {} },
421421
),
@@ -453,7 +453,11 @@ test("guardrail profile plugin injects shell env and blocks protected files", as
453453
)
454454
const vars = env.env as Record<string, string>
455455

456-
expect(cfg.plugin_origins?.some((item) => String(Array.isArray(item.spec) ? item.spec[0] : item.spec).includes("/plugins/guardrail.ts"))).toBe(true)
456+
expect(
457+
cfg.plugin_origins?.some((item) =>
458+
String(Array.isArray(item.spec) ? item.spec[0] : item.spec).includes("/plugins/guardrail.ts"),
459+
),
460+
).toBe(true)
457461
expect(vars.OPENCODE_GUARDRAIL_MODE).toBe("enforced")
458462
expect(vars.OPENCODE_GUARDRAIL_ROOT).toBe(files.root)
459463
expect(vars.OPENCODE_GUARDRAIL_STATE).toBe(files.state)
@@ -619,7 +623,77 @@ test("guardrail profile plugin enforces version baselines and context budget", a
619623
},
620624
},
621625
),
622-
).rejects.toThrow("context budget exceeded")
626+
).rejects.toThrow("delegate with the team tool")
627+
},
628+
})
629+
})
630+
})
631+
632+
test("guardrail profile blocks write-capable background workers until team runs", async () => {
633+
await withProfile(async () => {
634+
await using tmp = await tmpdir({ git: true })
635+
636+
await Instance.provide({
637+
directory: tmp.path,
638+
fn: async () => {
639+
const parts: { id?: string; sessionID?: string; messageID?: string; type?: string; text?: string }[] = [
640+
{
641+
type: "text",
642+
text:
643+
"Implement the following multi-file refactor across packages/a and packages/b.\n" +
644+
"1. Add a shared helper.\n" +
645+
"2. Update both packages.\n" +
646+
"3. Fix downstream imports.\n" +
647+
"This is a broad multi-file implementation.",
648+
},
649+
]
650+
651+
await Plugin.trigger(
652+
"chat.message",
653+
{
654+
sessionID: "session_team_gate",
655+
agent: "implement",
656+
},
657+
{
658+
message: {
659+
id: "msg_team_gate",
660+
sessionID: "session_team_gate",
661+
role: "user",
662+
},
663+
parts,
664+
},
665+
)
666+
667+
await expect(
668+
Plugin.trigger(
669+
"tool.execute.before",
670+
{ tool: "background", sessionID: "session_team_gate", callID: "call_bg_write" },
671+
{
672+
args: {
673+
prompt: "Edit src/a.ts to add the new helper",
674+
write: true,
675+
},
676+
},
677+
),
678+
).rejects.toThrow("Use the team tool with at least two tasks")
679+
680+
await expect(
681+
Plugin.trigger(
682+
"tool.execute.before",
683+
{ tool: "background", sessionID: "session_team_gate", callID: "call_bg_read" },
684+
{
685+
args: {
686+
prompt: "Inspect src/a.ts and summarize it",
687+
write: false,
688+
},
689+
},
690+
),
691+
).resolves.toEqual({
692+
args: {
693+
prompt: "Inspect src/a.ts and summarize it",
694+
write: false,
695+
},
696+
})
623697
},
624698
})
625699
})
@@ -766,9 +840,9 @@ test("guardrail profile plugin records lifecycle events and compaction context",
766840
{ context: [], prompt: undefined },
767841
)
768842

769-
expect(log).toContain("\"type\":\"session.created\"")
770-
expect(log).toContain("\"type\":\"permission.asked\"")
771-
expect(log).toContain("\"type\":\"session.idle\"")
843+
expect(log).toContain('"type":"session.created"')
844+
expect(log).toContain('"type":"permission.asked"')
845+
expect(log).toContain('"type":"session.idle"')
772846
expect(state.last_session).toBe("session_test")
773847
expect(state.read_count).toBe(0)
774848
expect(state.factchecked).toBe(false)
@@ -833,7 +907,10 @@ test("team plugin skips parallel enforcement on HEAD-less repos", async () => {
833907
expect(injected!.text).toContain("Parallel implementation policy is suspended")
834908

835909
const parallelInjected = parts.find(
836-
(item) => item.type === "text" && typeof item.text === "string" && item.text.includes("Parallel implementation policy is active"),
910+
(item) =>
911+
item.type === "text" &&
912+
typeof item.text === "string" &&
913+
item.text.includes("Parallel implementation policy is active"),
837914
)
838915
expect(parallelInjected).toBeUndefined()
839916

0 commit comments

Comments
 (0)