Skip to content

Commit 93f28f4

Browse files
terisukeclaude
andcommitted
fix(guardrails): plugin を v1 形で export し、loader を通ることを検査する
#328 は gate-fires.test.ts をもって発火検証済みと読める書き方をしたが、 実 opencode run では guardrail.ts / team.ts とも loader で落ちており、 chat.params の block は全期間で 0 件だった。gate() は本番で一度も呼ばれていない。 根因は export の形。default が関数だと readV1Plugin (detect) に v1 と認識されず legacy 経路に落ち、module の全 named export を server(input, options) で呼ぶ。 ensureLocalOpencodeIgnored(worktree: string) に input オブジェクトが渡って path.join で落ち、team.ts は非関数の const export で "not a function"。 変更: guardrail.ts / team.ts default を { id, server } の v1 形へ(判定内容は不変。 guardrail.ts の非コメント差分は rename 1 行 + default 1 行) plugin-loads.test.ts 新規。loader の判定を複製し v1 認識 / legacy 再現 / chat.params 到達 / ソースとの pair を検査 gate-fires.test.ts ヘッダを「loader を迂回した単体検査」と明記 実測: 修正前 (dev) に新テストをかけると 5 pass / 4 fail、修正後 9 pass / 0 fail。 実 CLI で failed to load plugin が 2 -> 0。harness 45 pass、lint 5131/1 (不変)、typecheck 30/30。 未解決: 実在 preview モデルでの実セッションは init 後にストールし session.created に 到達しないため、chat.params の実発火はまだ観測できていない (別の起動時問題)。 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Et1J3J3Zi3V6zEzAod8QPD
1 parent 8d9c54b commit 93f28f4

4 files changed

Lines changed: 224 additions & 11 deletions

File tree

‎packages/guardrails/profile/plugins/gate-fires.test.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
11
/**
2-
* The guardrail must actually BLOCK, not merely be consistent.
2+
* gate() の判定ロジックを **loader を迂回して** 直接検査する。
33
*
4-
* 既存の 2 本(model-whitelist / team-permission)は**宣言の一致**を検査する。
5-
* 3 コピーの whitelist が揃っているか、権限表が矛盾していないか。
6-
* どちらも「実際に止まるか」は一度も確かめていない。
4+
* ## このテストが保証しないこと(2026-09-04 に実環境で反証された)
75
*
8-
* 宣言が揃っていても gate() が素通りすれば、ガードは無いのと同じである。
9-
* 2026-09-04 の upstream 取り込み(49 commit / 137 files)でこの穴に気づいた:
10-
* 取り込み後に harness テストは 30 pass だったが、**その 30 本は 1 度も
11-
* 発火経路を通っていなかった。**
6+
* 本テストは `createContext` を直接 import して `gate()` を呼ぶ。
7+
* **opencode の plugin loader は通らない。** したがって次は一切保証しない:
8+
* - profile の plugin が実 CLI でロードされること
9+
* - `chat.params` フックが登録されること
10+
* - 実セッションで gate() に到達すること
11+
*
12+
* 実測(2026-09-04、実 `opencode run`): 本テストが 6 pass の状態で
13+
* failed to load plugin .../guardrail.ts (paths[0] must be of type string, got object)
14+
* failed to load plugin .../team.ts (Plugin export is not a function)
15+
* が出ており、`chat.params` の block は events.jsonl に**全期間で 0 件**だった。
16+
* つまり **本テストが緑のまま、本番の強制経路は死んでいた。**
17+
*
18+
* 当初のヘッダは「The guardrail must actually BLOCK」と書き、発火検証済みと読めた。
19+
* それは過大だった。ロード経路の検査は plugin-loads.test.ts が担う。
20+
*
21+
* ## 本テストが保証すること
1222
*
13-
* 軸:
1423
* F1 発火 拒否すべき入力で gate() が理由文字列を返す
1524
* F2 統制 通すべき入力で gate() が undefined を返す
1625
* (F2 が無いと「全部拒否する壊れた gate」と区別できない)
1726
* F3 変異 拒否理由を 1 つずつ外すと、対応する入力だけが通るようになる
1827
*
28+
* これは「gate() が正しく判定するか」であって「gate() が呼ばれるか」ではない。
29+
*
1930
* Run: bun test packages/guardrails/profile/plugins/gate-fires.test.ts
2031
*/
2132
import { describe, expect, test } from "bun:test"

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

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export async function ensureLocalOpencodeIgnored(worktree: string) {
5050
return true
5151
}
5252

53-
export default async function guardrail(input: GuardrailInput, opts?: Record<string, unknown>) {
53+
async function guardrailServer(input: GuardrailInput, opts?: Record<string, unknown>) {
5454
const ctx = await createContext(input, opts)
5555
const access = createAccessHandlers(ctx)
5656
const gitHandlers = createGitHandlers(ctx)
@@ -727,3 +727,23 @@ export default async function guardrail(input: GuardrailInput, opts?: Record<str
727727
},
728728
}
729729
}
730+
731+
// ## なぜ v1 形(object with server)で export するか — 2026-09-04 実環境で反証された欠陥
732+
//
733+
// opencode の loader(packages/opencode/src/plugin/index.ts applyPlugin)は、まず
734+
// `readV1Plugin(mod, spec, "server", "detect")` で **default が object かつ
735+
// id/server/tui を持つか** を見る。持たなければ legacy 経路 `getLegacyPlugins` に落ち、
736+
// **module の全 export を plugin と見なして `server(input, options)` で呼ぶ。**
737+
//
738+
// 以前は `export default async function guardrail(...)` だった。関数なので v1 と
739+
// 認識されず legacy に落ち、named export の `ensureLocalOpencodeIgnored(worktree)` に
740+
// `input` オブジェクトが渡って `path.join(object)` で落ちた:
741+
// failed to load plugin .../guardrail.ts error="The \"paths[0]\" property must be of type string, got object"
742+
// その結果 `chat.params` は登録されず、gate() は**全期間で 0 回**しか呼ばれていなかった
743+
// (.opencode/guardrails/events.jsonl に chat.params の block が 1 件も無い)。
744+
// 一方で hygiene 系の副作用イベントは書かれるので、**台帳は動いて見えるのに強制は死んでいた。**
745+
//
746+
// v1 形なら loader は default object の `server` だけを呼び、named export には触れない。
747+
// 判定内容(gate / hooks の中身)は 1 バイトも変えていない。変えたのは export の形だけである。
748+
// 検出は plugin-loads.test.ts が担う(loader の判定を複製し、この形でなければ red)。
749+
export default { id: "aidd-guardrail", server: guardrailServer }
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/**
2+
* profile の plugin が **opencode の loader を通るか** を検査する。
3+
*
4+
* ## 起点(2026-09-04、実 `opencode run` で反証)
5+
*
6+
* gate-fires.test.ts が 6 pass の状態で、実 CLI は
7+
* failed to load plugin .../guardrail.ts (The "paths[0]" property must be of type string, got object)
8+
* failed to load plugin .../team.ts (Plugin export is not a function)
9+
* を出し、`chat.params` の block は events.jsonl に**全期間で 0 件**だった。
10+
* gate() の単体テストが緑でも、**gate() に到達する経路が死んでいれば強制は無い。**
11+
*
12+
* ## なぜ loader を直接 import せず判定を複製するか
13+
*
14+
* loader 本体(packages/opencode/src/plugin/shared.ts の readV1Plugin と
15+
* packages/opencode/src/plugin/index.ts の getLegacyPlugins)は `@/util/*` と
16+
* `@opencode-ai/core/npm` に依存し、guardrails の bun test からは解決できない。
17+
* そこで判定だけを忠実に複製し、**複製がソースからずれたら落ちる pair 検査**を付ける
18+
* (ソースの決定的な 2 条件を文字列で照合する)。複製だけだと「テストは緑だが loader は
19+
* 変わっていた」を通してしまう。
20+
*
21+
* ## 軸
22+
* F1 v1 判定 default が object で server() を持つ → loader は named export に触れない
23+
* F2 legacy 経路 default が関数の module(修正前の形)は legacy に落ち、named export を
24+
* server(input) で呼んで throw する — これが修正前の red の再現
25+
* F3 到達性 server(stubInput) が返す hooks に "chat.params" がある
26+
* PAIR 複製した判定条件がソースに実在する
27+
*
28+
* Run: bun test packages/guardrails/profile/plugins/plugin-loads.test.ts
29+
*/
30+
import { describe, expect, test } from "bun:test"
31+
import { existsSync, readFileSync } from "node:fs"
32+
import { join } from "node:path"
33+
import * as guardrailMod from "./guardrail"
34+
import * as teamMod from "./team"
35+
36+
// ---- loader の判定を複製(packages/opencode/src/plugin/{shared,index}.ts) ----
37+
type Mod = Record<string, unknown>
38+
type ServerFn = (input: unknown, opts?: unknown) => Promise<unknown>
39+
type V1 = { id?: unknown; server: ServerFn }
40+
41+
const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object"
42+
const isServerFn = (v: unknown): v is ServerFn => typeof v === "function"
43+
const isV1 = (v: unknown): v is V1 => isRecord(v) && isServerFn(v.server)
44+
45+
/** shared.ts readV1Plugin(mod, spec, "server", "detect") の判定部 */
46+
function readV1PluginDetect(mod: Mod): V1 | undefined {
47+
const value = mod.default
48+
if (!isRecord(value)) return undefined
49+
if (!("id" in value) && !("server" in value) && !("tui" in value)) return undefined
50+
if ("server" in value && value.server !== undefined && !isServerFn(value.server)) {
51+
throw new TypeError("invalid server export")
52+
}
53+
if (!isV1(value)) throw new TypeError("must default export an object with server()")
54+
return value
55+
}
56+
57+
/** index.ts getServerPlugin / getLegacyPlugins の判定部 */
58+
function getLegacyPlugins(mod: Mod): ServerFn[] {
59+
const seen = new Set<unknown>()
60+
const out: ServerFn[] = []
61+
for (const entry of Object.values(mod)) {
62+
if (seen.has(entry)) continue
63+
seen.add(entry)
64+
if (isServerFn(entry)) {
65+
out.push(entry)
66+
continue
67+
}
68+
if (isRecord(entry) && isServerFn(entry.server)) {
69+
out.push(entry.server)
70+
continue
71+
}
72+
throw new TypeError("Plugin export is not a function")
73+
}
74+
return out
75+
}
76+
77+
/** index.ts applyPlugin: v1 があればそれだけ、無ければ legacy で全 export を呼ぶ */
78+
async function applyPluginLike(mod: Mod, input: unknown): Promise<unknown[]> {
79+
const v1 = readV1PluginDetect(mod)
80+
// Promise.resolve で包む: 型ガード越しの戻り値を oxlint が thenable と確定できないため。
81+
// 実体は async 関数なので挙動は同じ。
82+
if (v1) return [await Promise.resolve(v1.server(input, {}))]
83+
const hooks: unknown[] = []
84+
for (const server of getLegacyPlugins(mod)) hooks.push(await Promise.resolve(server(input, {})))
85+
return hooks
86+
}
87+
88+
// ---- loader が実際に渡す入力に近い stub(client は触ったら落ちる Proxy) ----
89+
const dir = process.cwd()
90+
const stubInput = {
91+
client: new Proxy(
92+
{},
93+
{
94+
get(_t, p) {
95+
throw new Error(`plugin touched client.${String(p)} at load`)
96+
},
97+
},
98+
),
99+
project: { id: "test" },
100+
directory: dir,
101+
worktree: dir,
102+
serverUrl: new URL("http://localhost:0"),
103+
experimental_workspace: { register() {} },
104+
$: undefined,
105+
}
106+
107+
describe("profile plugin は opencode の loader を通る", () => {
108+
test("F1 guardrail: default は object で server() を持つ(v1 として認識される)", () => {
109+
const v1 = readV1PluginDetect(guardrailMod)
110+
expect(v1).toBeDefined()
111+
expect(v1?.id).toBe("aidd-guardrail")
112+
})
113+
114+
test("F1 team: default は object で server() を持つ", () => {
115+
const v1 = readV1PluginDetect(teamMod)
116+
expect(v1).toBeDefined()
117+
expect(v1?.id).toBe("aidd-team")
118+
})
119+
120+
test("F2 legacy 経路の再現: default が関数だと named export が server(input) で呼ばれて落ちる", async () => {
121+
// 修正前の guardrail.ts と同じ形を合成する: default は関数、named export に
122+
// 「string を要求する補助関数」がある。loader はこれを plugin と誤認して input を渡す。
123+
const legacyShaped: Mod = {
124+
default: async () => ({}),
125+
ensureLocalOpencodeIgnored: async (worktree: string) => join(worktree, ".gitignore"),
126+
}
127+
expect(readV1PluginDetect(legacyShaped)).toBeUndefined() // v1 とは認識されない
128+
// bun test は返した Promise を待つ。await にすると oxlint が expect(...).rejects を
129+
// thenable と確定できず await-thenable を出すので return にする。
130+
return expect(applyPluginLike(legacyShaped, stubInput)).rejects.toThrow(/paths\[0\]|must be of type string/)
131+
})
132+
133+
test("F2 legacy 経路の再現: 非関数の named export は 'Plugin export is not a function'", () => {
134+
const legacyShaped: Mod = { default: async () => ({}), DEFAULT_TIMEOUT_MS: 1000 }
135+
expect(() => getLegacyPlugins(legacyShaped)).toThrow("Plugin export is not a function")
136+
})
137+
138+
test("F3 到達性: guardrail.server(input) が返す hooks に chat.params がある", async () => {
139+
const [hooks] = await applyPluginLike(guardrailMod, stubInput)
140+
expect(isRecord(hooks)).toBe(true)
141+
if (!isRecord(hooks)) return
142+
expect(typeof hooks["chat.params"]).toBe("function")
143+
expect(typeof hooks["tool.execute.before"]).toBe("function")
144+
})
145+
146+
test("F3 統制: 現行の guardrail は named export を持つが、v1 なので loader はそれを呼ばない", async () => {
147+
// named export が残っていること自体は正しい(他の用途がある)。
148+
// v1 判定が効いていれば applyPluginLike は default.server だけを呼び、例外は出ない。
149+
const named = Object.keys(guardrailMod).filter((k) => k !== "default")
150+
expect(named.length).toBeGreaterThan(0)
151+
return expect(applyPluginLike(guardrailMod, stubInput)).resolves.toBeDefined()
152+
})
153+
})
154+
155+
describe("PAIR: 複製した loader 判定がソースに実在する(ずれたら落ちる)", () => {
156+
const root = join(import.meta.dir, "..", "..", "..", "opencode", "src", "plugin")
157+
const shared = join(root, "shared.ts")
158+
const index = join(root, "index.ts")
159+
160+
test("loader のソースが解決できる(無ければ pair は成立しない)", () => {
161+
expect(existsSync(shared)).toBe(true)
162+
expect(existsSync(index)).toBe(true)
163+
})
164+
165+
test("readV1Plugin: detect モードは id/server/tui の無い default を無視する", () => {
166+
const src = readFileSync(shared, "utf-8")
167+
expect(src).toContain(`if (mode === "detect" && !("id" in value) && !("server" in value) && !("tui" in value)) return`)
168+
})
169+
170+
test("getLegacyPlugins: 全 export を走査し、非関数なら throw する", () => {
171+
const src = readFileSync(index, "utf-8")
172+
expect(src).toContain("for (const entry of Object.values(mod))")
173+
expect(src).toContain(`throw new TypeError("Plugin export is not a function")`)
174+
})
175+
})

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1259,7 +1259,7 @@ async function stop(client: Client, run: Run) {
12591259
).catch(() => undefined)
12601260
}
12611261

1262-
export default async function team(input: { client: Client; worktree: string; directory: string }) {
1262+
async function teamServer(input: { client: Client; worktree: string; directory: string }) {
12631263
const inputRoot = projectRoot(input.directory, input.worktree)
12641264
void sweep(input.client, inputRoot)
12651265
const job = async (ctx: Ctx, run: Run, item: Step) => {
@@ -1781,3 +1781,10 @@ export default async function team(input: { client: Client; worktree: string; di
17811781
},
17821782
}
17831783
}
1784+
1785+
// v1 形で export する理由は guardrail.ts 末尾のコメントと同じ。
1786+
// 本ファイルは定数(DEFAULT_TEAM_*_TIMEOUT_MS)や補助関数を named export しており、
1787+
// legacy 経路では非関数の export に対して
1788+
// failed to load plugin .../team.ts error="Plugin export is not a function"
1789+
// で落ちていた(2026-09-04 実測)。default を object にすれば loader は server だけを呼ぶ。
1790+
export default { id: "aidd-team", server: teamServer }

0 commit comments

Comments
 (0)