返回 DeepSeek-Reasonix
pluginpkg_test.go
根目录 / internal / pluginpkg / pluginpkg_test.go
1 package pluginpkg
2
3 import (
4 "encoding/json"
5 "os"
6 "path/filepath"
7 "reflect"
8 "strings"
9 "testing"
10
11 fileencoding "reasonix/internal/fileutil/encoding"
12 )
13
14 func TestParseCodexSuperpowersManifest(t *testing.T) {
15 root := t.TempDir()
16 writeTestFile(t, filepath.Join(root, CodexManifest), `{
17 "name": "superpowers",
18 "version": "6.1.0",
19 "description": "Planning workflows",
20 "skills": "./skills/"
21 }`)
22 writeTestFile(t, filepath.Join(root, "skills", "plan", "SKILL.md"), "---\ndescription: Plan work\n---\nbody")
23 writeTestFile(t, filepath.Join(root, "hooks", "session-start-codex"), "#!/usr/bin/env bash\n")
24
25 pkg, warnings, err := ParseDir(root)
26 if err != nil {
27 t.Fatalf("ParseDir: %v", err)
28 }
29 if len(warnings) != 0 {
30 t.Fatalf("warnings = %v, want none", warnings)
31 }
32 if pkg.ManifestKind != "codex" || pkg.Manifest.Name != "superpowers" || pkg.Manifest.Version != "6.1.0" {
33 t.Fatalf("pkg = %+v", pkg)
34 }
35 if got := pkg.SkillRoots(); len(got) != 1 || got[0] != filepath.Join(root, "skills") {
36 t.Fatalf("SkillRoots = %#v", got)
37 }
38 if hooks := pkg.Manifest.Hooks["SessionStart"]; len(hooks) != 1 || hooks[0].Command != filepath.Join(root, "hooks", "session-start-codex") {
39 t.Fatalf("SessionStart hooks = %+v", hooks)
40 }
41 inv := pkg.Inventory()
42 if len(inv.Skills) != 1 || inv.Skills[0].Name != "plan" || inv.Skills[0].Invocation != "/plan" {
43 t.Fatalf("Inventory().Skills = %+v", inv.Skills)
44 }
45 if skills, _, hooks, _ := pkg.CapabilityCounts(); skills != 1 || hooks != 1 {
46 t.Fatalf("CapabilityCounts skills=%d hooks=%d", skills, hooks)
47 }
48 }
49
50 func TestParseDirDecodesGB18030Manifest(t *testing.T) {
51 root := t.TempDir()
52 manifest := `{"name":"cn-plugin","version":"1.0.0","description":"中文插件"}`
53 path := filepath.Join(root, NativeManifest)
54 if err := os.WriteFile(path, fileencoding.Encode(manifest, fileencoding.GB18030), 0o644); err != nil {
55 t.Fatal(err)
56 }
57
58 pkg, warnings, err := ParseDir(root)
59 if err != nil {
60 t.Fatalf("ParseDir: %v", err)
61 }
62 if len(warnings) != 0 {
63 t.Fatalf("warnings = %v", warnings)
64 }
65 if pkg.Manifest.Description != "中文插件" {
66 t.Fatalf("decoded manifest = %+v", pkg.Manifest)
67 }
68 }
69
70 func TestParseCodexClaudeCompatibility(t *testing.T) {
71 root := t.TempDir()
72 writeTestFile(t, filepath.Join(root, CodexManifest), `{
73 "name": "claude-pack",
74 "version": "1.0.0",
75 "skills": "skills"
76 }`)
77 writeTestFile(t, filepath.Join(root, "CLAUDE.md"), "Always use the bundled workflow.")
78 writeTestFile(t, filepath.Join(root, ".claude", "settings.json"), `{
79 "hooks": {
80 "PostToolUse": [
81 {
82 "matcher": "bash|write_file",
83 "hooks": [
84 {
85 "type": "command",
86 "command": "node hooks/post-tool.js",
87 "description": "post tool check",
88 "timeout": 3,
89 "env": { "MODE": "check" }
90 },
91 { "type": "prompt", "command": "ignored" }
92 ]
93 }
94 ],
95 "UserPromptSubmit": [
96 {
97 "hooks": [
98 { "type": "command", "command": "node hooks/prompt.js" }
99 ]
100 }
101 ]
102 }
103 }`)
104
105 pkg, warnings, err := ParseDir(root)
106 if err != nil {
107 t.Fatalf("ParseDir: %v", err)
108 }
109 if len(warnings) != 1 || warnings[0] == "" {
110 t.Fatalf("warnings = %v, want unsupported hook warning", warnings)
111 }
112 if got := pkg.Manifest.Hooks["SessionStart"]; len(got) != 1 || got[0].ContextFile != "CLAUDE.md" {
113 t.Fatalf("SessionStart hooks = %+v, want CLAUDE.md context hook", got)
114 }
115 if got := pkg.Manifest.Hooks["PostToolUse"]; len(got) != 1 || got[0].Match != "bash|write_file" || got[0].Command != "node hooks/post-tool.js" || got[0].Timeout != 3000 || got[0].Env["MODE"] != "check" {
116 t.Fatalf("PostToolUse hooks = %+v", got)
117 }
118 if got := pkg.Manifest.Hooks["UserPromptSubmit"]; len(got) != 1 || got[0].Command != "node hooks/prompt.js" {
119 t.Fatalf("UserPromptSubmit hooks = %+v", got)
120 }
121 }
122
123 func TestParseClaudePluginManifest(t *testing.T) {
124 root := t.TempDir()
125 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{
126 "name": "ui-ux-pro-max",
127 "version": "2.6.2",
128 "description": "UI/UX design intelligence",
129 "skills": "./.claude/skills/"
130 }`)
131 writeTestFile(t, filepath.Join(root, ".claude", "skills", "ui-ux-pro-max", "SKILL.md"), "---\ndescription: UI design helper\n---\nbody")
132 writeTestFile(t, filepath.Join(root, "CLAUDE.md"), "Use the bundled UI workflow.")
133
134 pkg, warnings, err := ParseDir(root)
135 if err != nil {
136 t.Fatalf("ParseDir: %v", err)
137 }
138 if len(warnings) != 0 {
139 t.Fatalf("warnings = %v, want none", warnings)
140 }
141 if pkg.ManifestKind != "claude" || pkg.Manifest.Name != "ui-ux-pro-max" || pkg.Manifest.Version != "2.6.2" {
142 t.Fatalf("pkg = %+v", pkg)
143 }
144 if got := pkg.SkillRoots(); len(got) != 1 || got[0] != filepath.Join(root, ".claude", "skills") {
145 t.Fatalf("SkillRoots = %#v", got)
146 }
147 inv := pkg.Inventory()
148 if len(inv.Skills) != 1 || inv.Skills[0].Name != "ui-ux-pro-max" || inv.Skills[0].Invocation != "/ui-ux-pro-max" {
149 t.Fatalf("Inventory().Skills = %+v", inv.Skills)
150 }
151 if hooks := pkg.Manifest.Hooks["SessionStart"]; len(hooks) != 1 || hooks[0].ContextFile != "CLAUDE.md" {
152 t.Fatalf("SessionStart hooks = %+v, want CLAUDE.md context hook", hooks)
153 }
154 if ManifestPath(pkg.ManifestKind) != ClaudeManifest {
155 t.Fatalf("ManifestPath(%q) = %q, want %q", pkg.ManifestKind, ManifestPath(pkg.ManifestKind), ClaudeManifest)
156 }
157 }
158
159 func TestParseCodexWithoutSessionStartHookDoesNotWarn(t *testing.T) {
160 root := t.TempDir()
161 writeTestFile(t, filepath.Join(root, CodexManifest), `{
162 "name": "skills-only",
163 "skills": "skills"
164 }`)
165
166 _, warnings, err := ParseDir(root)
167 if err != nil {
168 t.Fatalf("ParseDir: %v", err)
169 }
170 if len(warnings) != 0 {
171 t.Fatalf("warnings = %v, want none", warnings)
172 }
173 }
174
175 func TestRejectsEscapingSkillPath(t *testing.T) {
176 root := t.TempDir()
177 writeTestFile(t, filepath.Join(root, NativeManifest), `{
178 "name": "bad",
179 "skills": "../skills"
180 }`)
181 if _, _, err := ParseDir(root); err == nil {
182 t.Fatal("ParseDir should reject escaping skill path")
183 }
184 }
185
186 func TestStateRoundTripSortsPlugins(t *testing.T) {
187 home := t.TempDir()
188 if err := Upsert(home, InstalledPlugin{Name: "zeta", Root: "plugins/zeta", Enabled: true}); err != nil {
189 t.Fatal(err)
190 }
191 if err := Upsert(home, InstalledPlugin{Name: "alpha", Root: "plugins/alpha", Enabled: false}); err != nil {
192 t.Fatal(err)
193 }
194 st, err := LoadState(home)
195 if err != nil {
196 t.Fatal(err)
197 }
198 if len(st.Plugins) != 2 || st.Plugins[0].Name != "alpha" || st.Plugins[1].Name != "zeta" {
199 t.Fatalf("state plugins = %+v", st.Plugins)
200 }
201 }
202
203 func TestInstalledTextDescribesUsageInventory(t *testing.T) {
204 home := t.TempDir()
205 root := filepath.Join(home, "plugins", "superpowers")
206 writeTestFile(t, filepath.Join(root, CodexManifest), `{
207 "name": "superpowers",
208 "version": "6.1.0",
209 "description": "Planning workflows",
210 "skills": "skills"
211 }`)
212 writeTestFile(t, filepath.Join(root, "skills", "plan", "SKILL.md"), "---\ndescription: Plan work\nrunAs: subagent\n---\nbody")
213 writeTestFile(t, filepath.Join(root, "hooks", "session-start-codex"), "#!/usr/bin/env bash\n")
214 if err := Upsert(home, InstalledPlugin{Name: "superpowers", Root: "plugins/superpowers", Version: "6.1.0", Description: "Planning workflows", ManifestKind: "codex", Enabled: true}); err != nil {
215 t.Fatal(err)
216 }
217 list, err := InstalledListText(home)
218 if err != nil {
219 t.Fatal(err)
220 }
221 for _, want := range []string{"plugins (1):", "superpowers [enabled]", "1 skills / 1 hooks", "/plugins show <name>"} {
222 if !strings.Contains(list, want) {
223 t.Fatalf("InstalledListText missing %q:\n%s", want, list)
224 }
225 }
226 details, err := InstalledShowText(home, "superpowers")
227 if err != nil {
228 t.Fatal(err)
229 }
230 for _, want := range []string{"plugin superpowers [enabled]", "usage: enabled plugins load into new sessions", "/superpowers:plan [subagent] - Plan work", "SessionStart"} {
231 if !strings.Contains(details, want) {
232 t.Fatalf("InstalledShowText missing %q:\n%s", want, details)
233 }
234 }
235 }
236
237 func writeTestFile(t *testing.T, path, body string) {
238 t.Helper()
239 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
240 t.Fatal(err)
241 }
242 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
243 t.Fatal(err)
244 }
245 }
246
247 // TestParseClaudePluginConventionSkillDirs pins the standard Claude plugin
248 // shape: plugin.json carries metadata only, and skills live in the
249 // conventional skills/ directory that Claude auto-discovers. Without the
250 // fallback such a package installed as zero capabilities with no warning.
251 func TestParseClaudePluginConventionSkillDirs(t *testing.T) {
252 root := t.TempDir()
253 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{
254 "name": "design-pack",
255 "version": "1.0.0",
256 "description": "metadata-only manifest"
257 }`)
258 writeTestFile(t, filepath.Join(root, "skills", "design-review", "SKILL.md"), "---\ndescription: review designs\n---\nbody")
259
260 pkg, warnings, err := ParseDir(root)
261 if err != nil {
262 t.Fatalf("ParseDir: %v", err)
263 }
264 if len(warnings) != 0 {
265 t.Fatalf("warnings = %v, want none", warnings)
266 }
267 if pkg.ManifestKind != "claude" {
268 t.Fatalf("kind = %q", pkg.ManifestKind)
269 }
270 if got := pkg.SkillRoots(); len(got) != 1 || got[0] != filepath.Join(root, "skills") {
271 t.Fatalf("SkillRoots = %#v, want conventional skills dir", got)
272 }
273 if inv := pkg.Inventory(); len(inv.Skills) != 1 || inv.Skills[0].Name != "design-review" {
274 t.Fatalf("Inventory().Skills = %+v", inv.Skills)
275 }
276 }
277
278 func TestParseClaudePluginDotClaudeConventionDir(t *testing.T) {
279 root := t.TempDir()
280 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "pack"}`)
281 writeTestFile(t, filepath.Join(root, ".claude", "skills", "helper", "SKILL.md"), "---\ndescription: helper\n---\nbody")
282
283 pkg, _, err := ParseDir(root)
284 if err != nil {
285 t.Fatalf("ParseDir: %v", err)
286 }
287 if got := pkg.SkillRoots(); len(got) != 1 || got[0] != filepath.Join(root, ".claude", "skills") {
288 t.Fatalf("SkillRoots = %#v, want .claude/skills", got)
289 }
290 }
291
292 func TestParseClaudePluginIgnoresEmptyConventionDirAndExplicitSkillsWin(t *testing.T) {
293 root := t.TempDir()
294 // Empty conventional dir (no SKILL.md inside) must not be adopted.
295 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "empty-pack"}`)
296 if err := os.MkdirAll(filepath.Join(root, "skills", "stub"), 0o755); err != nil {
297 t.Fatal(err)
298 }
299 pkg, _, err := ParseDir(root)
300 if err != nil {
301 t.Fatalf("ParseDir: %v", err)
302 }
303 if got := pkg.SkillRoots(); len(got) != 0 {
304 t.Fatalf("SkillRoots = %#v, want none for a skill-less conventional dir", got)
305 }
306
307 // Explicit skills declaration disables the fallback entirely.
308 root2 := t.TempDir()
309 writeTestFile(t, filepath.Join(root2, ClaudeManifest), `{"name": "explicit-pack", "skills": "./custom/"}`)
310 writeTestFile(t, filepath.Join(root2, "custom", "one", "SKILL.md"), "---\ndescription: one\n---\nbody")
311 writeTestFile(t, filepath.Join(root2, "skills", "two", "SKILL.md"), "---\ndescription: two\n---\nbody")
312 pkg2, _, err := ParseDir(root2)
313 if err != nil {
314 t.Fatalf("ParseDir explicit: %v", err)
315 }
316 if got := pkg2.SkillRoots(); len(got) != 1 || got[0] != filepath.Join(root2, "custom") {
317 t.Fatalf("SkillRoots = %#v, want only the declared custom dir", got)
318 }
319 }
320
321 func TestParseClaudeHooksKeepsDistinctEnvTimeoutAsyncCwd(t *testing.T) {
322 root := t.TempDir()
323 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "hook-pack"}`)
324 // Same event/matcher/command/args, but each block differs in exactly one
325 // of env, timeout, async, cwd — none should be dropped as a duplicate of
326 // another.
327 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"), `{
328 "hooks": {"PreToolUse": [
329 {"matcher": "bash", "hooks": [{"type":"command","command":"bin/guard","env":{"MODE":"a"}}]},
330 {"matcher": "bash", "hooks": [{"type":"command","command":"bin/guard","env":{"MODE":"b"}}]},
331 {"matcher": "bash", "hooks": [{"type":"command","command":"bin/guard","env":{"MODE":"b"},"timeout":5}]},
332 {"matcher": "bash", "hooks": [{"type":"command","command":"bin/guard","env":{"MODE":"b"},"timeout":5,"async":true}]},
333 {"matcher": "bash", "hooks": [{"type":"command","command":"bin/guard","env":{"MODE":"b"},"timeout":5,"async":true}]}
334 ]}
335 }`)
336
337 pkg, _, err := ParseDir(root)
338 if err != nil {
339 t.Fatalf("ParseDir: %v", err)
340 }
341 hooks := pkg.Manifest.Hooks["PreToolUse"]
342 // Four distinct configurations; the fifth block is an exact duplicate of
343 // the fourth (same env, timeout, and async) and must still be dropped.
344 if len(hooks) != 4 {
345 t.Fatalf("hooks = %#v, want 4 distinct configurations (dedup must not collapse different env/timeout/async)", hooks)
346 }
347 }
348
349 func TestParseClaudeHooksPreservesExecAndShellForms(t *testing.T) {
350 root := t.TempDir()
351 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "hook-contract-pack"}`)
352 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"), `{
353 "hooks": {"SessionStart": [
354 {"hooks": [
355 {"type":"command","command":"node","args":[],"shell":"powershell"},
356 {"type":"command","command":"tool","args":[""," spaced ","$HOME"]},
357 {"type":"command","command":"Write-Output \"a && b\"","shell":"powershell"}
358 ]}
359 ]}
360 }`)
361
362 pkg, warnings, err := ParseDir(root)
363 if err != nil {
364 t.Fatalf("ParseDir: %v", err)
365 }
366 if len(warnings) != 0 {
367 t.Fatalf("warnings = %v, want none", warnings)
368 }
369 hooks := pkg.Manifest.Hooks["SessionStart"]
370 if len(hooks) != 3 {
371 t.Fatalf("hooks = %#v, want 3", hooks)
372 }
373 if !hooks[0].ArgsSet || hooks[0].Args == nil || len(hooks[0].Args) != 0 || hooks[0].Shell != "" {
374 t.Fatalf("explicit empty args did not remain exec form (and ignore shell): %#v", hooks[0])
375 }
376 wantArgs := []string{"", " spaced ", "$HOME"}
377 if !hooks[1].ArgsSet || !reflect.DeepEqual(hooks[1].Args, wantArgs) {
378 t.Fatalf("literal exec args = %#v, want %#v", hooks[1].Args, wantArgs)
379 }
380 if hooks[2].ArgsSet || hooks[2].Shell != "powershell" || !hooks[2].ShellCommand {
381 t.Fatalf("PowerShell hook did not remain shell form: %#v", hooks[2])
382 }
383 }
384
385 func TestHookJSONPreservesExplicitEmptyArgs(t *testing.T) {
386 var hook Hook
387 if err := json.Unmarshal([]byte(`{"command":"bin/check","args":[]}`), &hook); err != nil {
388 t.Fatal(err)
389 }
390 if !hook.ArgsSet || hook.Args == nil || len(hook.Args) != 0 {
391 t.Fatalf("hook = %#v, want explicit empty exec-form args", hook)
392 }
393 }
394
395 func TestParseClaudeHooksWarnOnUnsupportedSemantics(t *testing.T) {
396 cases := []struct {
397 name string
398 hooksJSON string
399 wantSub string
400 }{
401 {
402 name: "conditional-if-runs-unconditionally",
403 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"bin/guard","if":"Bash(git *)"}]}]}}`,
404 wantSub: `does not evaluate`,
405 },
406 {
407 name: "asyncRewake-not-supported",
408 hooksJSON: `{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"bin/watch","asyncRewake":true}]}]}}`,
409 wantSub: `asyncRewake`,
410 },
411 {
412 name: "stop-cannot-block",
413 hooksJSON: `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"bin/gate"}]}]}}`,
414 wantSub: `cannot block the turn`,
415 },
416 {
417 name: "subagentstop-cannot-block",
418 hooksJSON: `{"hooks":{"SubagentStop":[{"hooks":[{"type":"command","command":"bin/gate"}]}]}}`,
419 wantSub: `cannot block the turn`,
420 },
421 {
422 name: "matcher-names-unsupported-tool",
423 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"WebSearch","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
424 wantSub: `will never fire`,
425 },
426 {
427 name: "matcher-alternation-all-unsupported",
428 hooksJSON: `{"hooks":{"PermissionRequest":[{"matcher":"ExitPlanMode|EnterPlanMode","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
429 wantSub: `will never fire`,
430 },
431 {
432 name: "webfetch-required-prompt-is-unavailable",
433 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"WebFetch","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
434 wantSub: `required "prompt"`,
435 },
436 {
437 name: "mixed-matcher-includes-webfetch",
438 hooksJSON: `{"hooks":{"PostToolUse":[{"matcher":"Bash|WebFetch","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
439 wantSub: `required "prompt"`,
440 },
441 {
442 name: "wildcard-matcher-includes-webfetch",
443 hooksJSON: `{"hooks":{"PermissionRequest":[{"matcher":"*","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
444 wantSub: `required "prompt"`,
445 },
446 {
447 name: "empty-matcher-includes-webfetch",
448 hooksJSON: `{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
449 wantSub: `required "prompt"`,
450 },
451 {
452 name: "regex-matcher-includes-webfetch",
453 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"Web(Fetch|Search)","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
454 wantSub: `required "prompt"`,
455 },
456 {
457 name: "notebook-cell-number-has-no-claude-equivalent",
458 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"NotebookEdit","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
459 wantSub: `cell_number`,
460 },
461 {
462 name: "task-output-may-cover-multiple-jobs",
463 hooksJSON: `{"hooks":{"PostToolUse":[{"matcher":"TaskOutput","hooks":[{"type":"command","command":"bin/watch"}]}]}}`,
464 wantSub: `multiple or all background jobs`,
465 },
466 {
467 name: "legacy-bash-output-may-cover-multiple-jobs",
468 hooksJSON: `{"hooks":{"PostToolUse":[{"matcher":"BashOutput","hooks":[{"type":"command","command":"bin/watch"}]}]}}`,
469 wantSub: `multiple or all background jobs`,
470 },
471 }
472 for _, c := range cases {
473 t.Run(c.name, func(t *testing.T) {
474 root := t.TempDir()
475 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "hook-pack"}`)
476 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"), c.hooksJSON)
477
478 pkg, warnings, err := ParseDir(root)
479 if err != nil {
480 t.Fatalf("ParseDir: %v", err)
481 }
482 if pkg.Compatibility.Status != "partial" {
483 t.Fatalf("compatibility status = %q, want partial (unsupported semantics must not claim full compatibility)", pkg.Compatibility.Status)
484 }
485 found := false
486 for _, w := range warnings {
487 if strings.Contains(w, c.wantSub) {
488 found = true
489 break
490 }
491 }
492 if !found {
493 t.Fatalf("warnings = %v, want one containing %q", warnings, c.wantSub)
494 }
495 // The hook is still imported best-effort — dropping it entirely
496 // could remove a plugin's only safety hook.
497 if pkg.Manifest.Hooks == nil {
498 t.Fatal("hook should still be imported despite the unsupported semantics")
499 }
500 })
501 }
502 }
503
504 func TestParseClaudeHooksSkipsUnsupportedShell(t *testing.T) {
505 root := t.TempDir()
506 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "hook-pack"}`)
507 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"),
508 `{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"echo ok","shell":"cmd"}]}]}}`)
509
510 pkg, warnings, err := ParseDir(root)
511 if err != nil {
512 t.Fatalf("ParseDir: %v", err)
513 }
514 if pkg.Compatibility.Status != "none" {
515 t.Fatalf("compatibility status = %q, want none", pkg.Compatibility.Status)
516 }
517 if len(pkg.Manifest.Hooks) != 0 {
518 t.Fatalf("unsupported shell hook was imported: %#v", pkg.Manifest.Hooks)
519 }
520 if len(warnings) != 1 || !strings.Contains(warnings[0], `unsupported shell "cmd"`) {
521 t.Fatalf("warnings = %v, want unsupported shell diagnostic", warnings)
522 }
523 }
524
525 // TestParseClaudeHooksReportsStructuralGapsOncePerFile pins the noise bound:
526 // a plugin with several wildcard hooks reports each structural input gap
527 // (WebFetch prompt, NotebookEdit cell_number, TaskOutput multi-job) once per
528 // hooks file, not once per hook item.
529 func TestParseClaudeHooksReportsStructuralGapsOncePerFile(t *testing.T) {
530 root := t.TempDir()
531 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "hook-pack"}`)
532 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"), `{"hooks":{
533 "PreToolUse":[{"matcher":"*","hooks":[{"type":"command","command":"bin/a"},{"type":"command","command":"bin/b"}]}],
534 "PostToolUse":[{"matcher":"*","hooks":[{"type":"command","command":"bin/c"}]}]
535 }}`)
536
537 pkg, warnings, err := ParseDir(root)
538 if err != nil {
539 t.Fatalf("ParseDir: %v", err)
540 }
541 if pkg.Compatibility.Status != "partial" {
542 t.Fatalf("compatibility status = %q, want partial", pkg.Compatibility.Status)
543 }
544 gapSubs := []string{`required "prompt"`, "cell_number", "multiple or all background jobs"}
545 for _, sub := range gapSubs {
546 warned := 0
547 for _, w := range warnings {
548 if strings.Contains(w, sub) {
549 warned++
550 }
551 }
552 if warned != 1 {
553 t.Errorf("warnings mentioning %q = %d, want exactly 1 per hooks file (got %v)", sub, warned, warnings)
554 }
555 skipped := 0
556 for _, issue := range pkg.Compatibility.Skipped {
557 if strings.Contains(issue.Reason, sub) {
558 skipped++
559 }
560 }
561 if skipped != 1 {
562 t.Errorf("compatibility issues mentioning %q = %d, want exactly 1 per hooks file", sub, skipped)
563 }
564 }
565 }
566
567 func TestParseClaudeHooksDoesNotWarnOnMatchersThatCanFire(t *testing.T) {
568 cases := []struct {
569 name string
570 hooksJSON string
571 }{
572 {
573 name: "supported-tool-name",
574 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
575 },
576 {
577 // A partly-unsupported alternation can still fire for Bash calls,
578 // so it must not be flagged as dead.
579 name: "mixed-alternation-still-fires",
580 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"Bash|WebSearch","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
581 },
582 {
583 // A regex beyond a plain "|" alternation isn't evaluated, to
584 // avoid guessing wrong and producing a false positive.
585 name: "complex-regex-not-evaluated",
586 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"WebSearch.*","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
587 },
588 {
589 // A previously-unmapped Reasonix tool the fix now supports.
590 name: "run-skill-now-mapped",
591 hooksJSON: `{"hooks":{"PreToolUse":[{"matcher":"Skill","hooks":[{"type":"command","command":"bin/guard"}]}]}}`,
592 },
593 }
594 for _, c := range cases {
595 t.Run(c.name, func(t *testing.T) {
596 root := t.TempDir()
597 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "hook-pack"}`)
598 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"), c.hooksJSON)
599
600 pkg, warnings, err := ParseDir(root)
601 if err != nil {
602 t.Fatalf("ParseDir: %v", err)
603 }
604 for _, w := range warnings {
605 if strings.Contains(w, "will never fire") {
606 t.Fatalf("warnings = %v, want no dead-matcher warning", warnings)
607 }
608 }
609 if pkg.Compatibility.Status != "full" {
610 t.Fatalf("compatibility status = %q, want full", pkg.Compatibility.Status)
611 }
612 })
613 }
614 }
615
616 func TestParseClaudePluginMapsConventionCapabilities(t *testing.T) {
617 root := t.TempDir()
618 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "big-pack"}`)
619 writeTestFile(t, filepath.Join(root, "skills", "s", "SKILL.md"), "---\ndescription: s\n---\nbody")
620 writeTestFile(t, filepath.Join(root, "commands", "deploy.md"), "run deploy")
621 writeTestFile(t, filepath.Join(root, "agents", "reviewer.md"), "---\nname: reviewer\ndescription: review changes\nmodel: sonnet\ntools: [Read, Grep]\n---\nReview carefully.")
622 writeTestFile(t, filepath.Join(root, "hooks", "hooks.json"), `{
623 "hooks": {"SessionStart": [{"hooks": [{"type":"command","command":"bin/start","args":["--hook"],"async":true}]}]}
624 }`)
625 writeTestFile(t, filepath.Join(root, ".mcp.json"), `{
626 "mcpServers": {"Google Drive": {"type":"local","command":"uvx","args":["drive-mcp"],"title":"Drive"}}
627 }`)
628
629 pkg, warnings, err := ParseDir(root)
630 if err != nil {
631 t.Fatalf("ParseDir: %v", err)
632 }
633 if len(warnings) != 0 {
634 t.Fatalf("warnings = %v, want fully mapped package", warnings)
635 }
636 if pkg.Compatibility.Status != "full" || pkg.AgentCount() != 1 {
637 t.Fatalf("compatibility = %+v agents=%d", pkg.Compatibility, pkg.AgentCount())
638 }
639 agent := pkg.Inventory().Agents[0]
640 if agent.Name != "reviewer" || agent.Model != "sonnet" || strings.Join(agent.AllowedTools, ",") != "Read,Grep" {
641 t.Fatalf("agent = %+v", agent)
642 }
643 hook := pkg.Manifest.Hooks["SessionStart"][0]
644 if !hook.Async || hook.PayloadFormat != "claude" || strings.Join(hook.Args, ",") != "--hook" {
645 t.Fatalf("hook = %+v", hook)
646 }
647 if len(pkg.Manifest.MCPServers) != 1 {
648 t.Fatalf("MCP servers = %+v", pkg.Manifest.MCPServers)
649 }
650 for name, server := range pkg.Manifest.MCPServers {
651 if !IsValidName(name) || server.Type != "stdio" || server.DisplayName != "Drive" || server.AutoStart == nil || *server.AutoStart {
652 t.Fatalf("MCP %q = %+v", name, server)
653 }
654 }
655 }
656
657 func TestClaudeMCPServerIDUsesConnectionIdentityAndPreservesValidNames(t *testing.T) {
658 identity := claudeMCPIdentity{Type: "http", URL: "https://open.feishu.cn/mcp"}
659 if got := claudeMCPServerID("yuandian", identity); got != "yuandian" {
660 t.Fatalf("valid MCP ID changed to %q", got)
661 }
662 first := claudeMCPServerID("飞书", identity)
663 second := claudeMCPServerID("飞书", identity)
664 if first != second || !IsValidName(first) {
665 t.Fatalf("stable MCP IDs = %q / %q", first, second)
666 }
667 different := claudeMCPServerID("飞书", claudeMCPIdentity{Type: "http", URL: "https://example.com/other"})
668 if different == first {
669 t.Fatalf("different endpoints shared MCP ID %q", first)
670 }
671 }
672
673 // TestParseClaudePluginMapsCommandsDir pins the commands mapping: a Claude
674 // plugin's conventional commands/ dir becomes a Manifest.Commands root — even
675 // when the manifest declares skills explicitly — and its flat <name>.md
676 // templates surface in the inventory as /<name> invocations.
677 func TestParseClaudePluginMapsCommandsDir(t *testing.T) {
678 root := t.TempDir()
679 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "pwf-pack"}`)
680 writeTestFile(t, filepath.Join(root, "skills", "planner", "SKILL.md"), "---\ndescription: planner skill\n---\nbody")
681 writeTestFile(t, filepath.Join(root, "commands", "plan.md"), "---\ndescription: \"Start planning\"\nargument-hint: \"[task]\"\n---\nPlan: $ARGUMENTS")
682 writeTestFile(t, filepath.Join(root, "commands", "status.md"), "Show status")
683
684 pkg, warnings, err := ParseDir(root)
685 if err != nil {
686 t.Fatalf("ParseDir: %v", err)
687 }
688 if len(warnings) != 0 {
689 t.Fatalf("warnings = %v, want none for a fully mapped plugin", warnings)
690 }
691 if got := pkg.CommandRoots(); len(got) != 1 || got[0] != filepath.Join(root, "commands") {
692 t.Fatalf("CommandRoots = %#v, want the conventional commands dir", got)
693 }
694 inv := pkg.Inventory()
695 if len(inv.Commands) != 2 {
696 t.Fatalf("inventory commands = %#v, want plan and status", inv.Commands)
697 }
698 byName := map[string]CommandRef{}
699 for _, c := range inv.Commands {
700 byName[c.Name] = c
701 }
702 plan, ok := byName["plan"]
703 if !ok || plan.Invocation != "/plan" || plan.Description != "Start planning" || plan.ArgHint != "[task]" {
704 t.Fatalf("plan command = %+v, want /plan with description and arg hint", plan)
705 }
706 if _, ok := byName["status"]; !ok {
707 t.Fatalf("inventory commands = %#v, want frontmatter-less status command included", inv.Commands)
708 }
709 skills, commands, hooks, mcp := pkg.CapabilityCounts()
710 if skills != 1 || commands != 2 || hooks != 0 || mcp != 0 {
711 t.Fatalf("CapabilityCounts = %d skills %d commands %d hooks %d mcp, want 1/2/0/0", skills, commands, hooks, mcp)
712 }
713
714 // Explicit skills declaration must not disable command adoption.
715 root2 := t.TempDir()
716 writeTestFile(t, filepath.Join(root2, ClaudeManifest), `{"name": "explicit-pack", "skills": "./custom/"}`)
717 writeTestFile(t, filepath.Join(root2, "custom", "one", "SKILL.md"), "---\ndescription: one\n---\nbody")
718 writeTestFile(t, filepath.Join(root2, "commands", "go.md"), "go")
719 pkg2, _, err := ParseDir(root2)
720 if err != nil {
721 t.Fatalf("ParseDir explicit: %v", err)
722 }
723 if got := pkg2.CommandRoots(); len(got) != 1 || got[0] != filepath.Join(root2, "commands") {
724 t.Fatalf("CommandRoots = %#v, want commands adopted alongside explicit skills", got)
725 }
726
727 // A docs-only commands dir (no installable <name>.md) is not adopted.
728 root3 := t.TempDir()
729 writeTestFile(t, filepath.Join(root3, ClaudeManifest), `{"name": "docs-pack"}`)
730 writeTestFile(t, filepath.Join(root3, "skills", "s", "SKILL.md"), "---\ndescription: s\n---\nbody")
731 writeTestFile(t, filepath.Join(root3, "commands", "notes.txt"), "not a command")
732 pkg3, _, err := ParseDir(root3)
733 if err != nil {
734 t.Fatalf("ParseDir docs-only: %v", err)
735 }
736 if got := pkg3.CommandRoots(); len(got) != 0 {
737 t.Fatalf("CommandRoots = %#v, want none for a commands dir without .md files", got)
738 }
739 }
740
741 // TestNativeManifestCommandsField pins the explicit "commands" declaration in
742 // reasonix-plugin.json, including path validation.
743 func TestNativeManifestCommandsField(t *testing.T) {
744 root := t.TempDir()
745 writeTestFile(t, filepath.Join(root, NativeManifest), `{"name": "native-pack", "commands": ["cmds"]}`)
746 writeTestFile(t, filepath.Join(root, "cmds", "ship.md"), "---\ndescription: ship it\n---\nShip $1")
747
748 pkg, _, err := ParseDir(root)
749 if err != nil {
750 t.Fatalf("ParseDir: %v", err)
751 }
752 if got := pkg.CommandRoots(); len(got) != 1 || got[0] != filepath.Join(root, "cmds") {
753 t.Fatalf("CommandRoots = %#v, want declared cmds dir", got)
754 }
755 inv := pkg.Inventory()
756 if len(inv.Commands) != 1 || inv.Commands[0].Name != "ship" {
757 t.Fatalf("inventory commands = %#v, want ship", inv.Commands)
758 }
759
760 rootBad := t.TempDir()
761 writeTestFile(t, filepath.Join(rootBad, NativeManifest), `{"name": "bad-pack", "commands": ["../escape"]}`)
762 if _, _, err := ParseDir(rootBad); err == nil {
763 t.Fatal("ParseDir must reject a commands path escaping the plugin root")
764 }
765 }
766
767 // TestParseClaudePluginDoesNotRegisterCodexSessionStartHook pins the security
768 // boundary of the includeCodexSessionStartHook flag: a claude-kind package
769 // shipping a hooks/session-start-codex file must NOT get it registered as an
770 // executable SessionStart hook (that convention belongs to codex manifests).
771 func TestParseClaudePluginDoesNotRegisterCodexSessionStartHook(t *testing.T) {
772 root := t.TempDir()
773 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "sneaky-pack"}`)
774 writeTestFile(t, filepath.Join(root, "skills", "s", "SKILL.md"), "---\ndescription: s\n---\nbody")
775 writeTestFile(t, filepath.Join(root, "hooks", "session-start-codex"), "#!/bin/sh\necho pwned\n")
776
777 pkg, _, err := ParseDir(root)
778 if err != nil {
779 t.Fatalf("ParseDir: %v", err)
780 }
781 for _, h := range pkg.Manifest.Hooks["SessionStart"] {
782 if h.Command != "" {
783 t.Fatalf("claude package registered executable SessionStart hook: %+v", h)
784 }
785 }
786 }
787
788 // TestParseCodexManifestNotAffectedByClaudeFallback: the convention-dir
789 // fallback is claude-only; a codex manifest without a skills field keeps its
790 // existing "no skills" behavior even when a skills/ directory exists.
791 func TestParseCodexManifestNotAffectedByClaudeFallback(t *testing.T) {
792 root := t.TempDir()
793 writeTestFile(t, filepath.Join(root, CodexManifest), `{"name": "codex-pack"}`)
794 writeTestFile(t, filepath.Join(root, "skills", "s", "SKILL.md"), "---\ndescription: s\n---\nbody")
795
796 pkg, _, err := ParseDir(root)
797 if err != nil {
798 t.Fatalf("ParseDir: %v", err)
799 }
800 if pkg.ManifestKind != "codex" {
801 t.Fatalf("kind = %q", pkg.ManifestKind)
802 }
803 if got := pkg.SkillRoots(); len(got) != 0 {
804 t.Fatalf("SkillRoots = %#v, codex parsing must not adopt convention dirs", got)
805 }
806 }
807
808 // TestParseClaudePluginAdoptsNestedCommands pins that namespace layouts like
809 // commands/git/commit.md — which the runtime loader walks — also gate command
810 // root adoption, and surface in the inventory under their namespaced name.
811 func TestParseClaudePluginAdoptsNestedCommands(t *testing.T) {
812 root := t.TempDir()
813 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "nested-pack"}`)
814 writeTestFile(t, filepath.Join(root, "skills", "s", "SKILL.md"), "---\ndescription: s\n---\nbody")
815 writeTestFile(t, filepath.Join(root, "commands", "git", "commit.md"), "---\ndescription: commit helper\n---\nCommit: $ARGUMENTS")
816
817 pkg, warnings, err := ParseDir(root)
818 if err != nil {
819 t.Fatalf("ParseDir: %v", err)
820 }
821 if len(warnings) != 0 {
822 t.Fatalf("warnings = %v, want none", warnings)
823 }
824 if got := pkg.CommandRoots(); len(got) != 1 || got[0] != filepath.Join(root, "commands") {
825 t.Fatalf("CommandRoots = %#v, want commands adopted for nested-only layout", got)
826 }
827 inv := pkg.Inventory()
828 if len(inv.Commands) != 1 || inv.Commands[0].Name != "git:commit" || inv.Commands[0].Invocation != "/git:commit" {
829 t.Fatalf("inventory commands = %#v, want namespaced git:commit", inv.Commands)
830 }
831 }
832
833 // TestInventoryTextCommandsOnly pins that a commands-only inventory does not
834 // also claim "no detailed inventory available".
835 func TestInventoryTextCommandsOnly(t *testing.T) {
836 var b strings.Builder
837 appendInventoryText(&b, "superpowers", Inventory{Commands: []CommandRef{{Name: "plan", Invocation: "/plan", Description: "plan things"}}})
838 out := b.String()
839 if !strings.Contains(out, "commands:") || !strings.Contains(out, "/superpowers:plan") {
840 t.Fatalf("output = %q, want the commands listing", out)
841 }
842 if strings.Contains(out, "no detailed inventory available") {
843 t.Fatalf("output = %q, must not claim an empty inventory after listing commands", out)
844 }
845 }
846
847 // TestParseClaudePluginAdoptsDeeplyNestedCommands pins that adoption gating
848 // shares the runtime loader's discovery semantics with no depth ceiling: a
849 // plugin whose only command sits six levels deep is still adopted.
850 func TestParseClaudePluginAdoptsDeeplyNestedCommands(t *testing.T) {
851 root := t.TempDir()
852 writeTestFile(t, filepath.Join(root, ClaudeManifest), `{"name": "deep-pack"}`)
853 writeTestFile(t, filepath.Join(root, "skills", "s", "SKILL.md"), "---\ndescription: s\n---\nbody")
854 writeTestFile(t, filepath.Join(root, "commands", "a", "b", "c", "d", "e", "commit.md"), "---\ndescription: deep commit\n---\nCommit")
855
856 pkg, _, err := ParseDir(root)
857 if err != nil {
858 t.Fatalf("ParseDir: %v", err)
859 }
860 if got := pkg.CommandRoots(); len(got) != 1 || got[0] != filepath.Join(root, "commands") {
861 t.Fatalf("CommandRoots = %#v, want commands adopted for the deeply nested layout", got)
862 }
863 inv := pkg.Inventory()
864 if len(inv.Commands) != 1 || inv.Commands[0].Name != "a:b:c:d:e:commit" {
865 t.Fatalf("inventory commands = %#v, want the namespaced deep command", inv.Commands)
866 }
867 }
868
868 lines GO