返回 DeepSeek-Reasonix
subagent_test.go
根目录 / internal / cli / subagent_test.go
1 package cli
2
3 import (
4 "context"
5 "os"
6 "path/filepath"
7 "strings"
8 "testing"
9
10 "reasonix/internal/config"
11 "reasonix/internal/control"
12 "reasonix/internal/event"
13 "reasonix/internal/pluginpkg"
14 "reasonix/internal/skill"
15 )
16
17 func TestSubagentProfileCLIManageRoundTrip(t *testing.T) {
18 isolateCLIConfigHome(t)
19 project := t.TempDir()
20 original, err := os.Getwd()
21 if err != nil {
22 t.Fatal(err)
23 }
24 if err := os.Chdir(project); err != nil {
25 t.Fatal(err)
26 }
27 t.Cleanup(func() { _ = os.Chdir(original) })
28
29 out := captureStdout(t, func() {
30 if rc := subagentCommand([]string{
31 "create", "helper", "--description", "Initial helper", "--prompt", "Initial prompt",
32 "--model", "provider/model", "--effort", "high", "--tools", "read_file,grep,read_file", "--color", "orange",
33 }); rc != 0 {
34 t.Fatalf("create rc = %d", rc)
35 }
36 })
37 if !strings.Contains(out, "created subagent profile") {
38 t.Fatalf("create output = %q", out)
39 }
40 store := newCLISubagentStore()
41 sk, ok := store.Read("helper")
42 if !ok {
43 t.Fatal("created profile was not discovered")
44 }
45 if sk.Scope != skill.ScopeProject || sk.RunAs != skill.RunSubagent || sk.Invocation != "manual" ||
46 sk.Description != "Initial helper" || sk.Body != "Initial prompt" || sk.Model != "provider/model" ||
47 sk.Effort != "high" || sk.Color != "orange" || strings.Join(sk.AllowedTools, ",") != "read_file,grep" {
48 t.Fatalf("created profile = %+v", sk)
49 }
50
51 if rc := subagentCommand([]string{
52 "edit", "helper", "--description", "Updated helper", "--prompt", "Updated prompt", "--model=", "--tools=",
53 }); rc != 0 {
54 t.Fatalf("edit rc = %d", rc)
55 }
56 sk, ok = store.Read("helper")
57 if !ok || sk.Description != "Updated helper" || sk.Body != "Updated prompt" || sk.Model != "" || len(sk.AllowedTools) != 0 {
58 t.Fatalf("updated profile = %+v, found=%v", sk, ok)
59 }
60
61 out = captureStdout(t, func() {
62 if rc := subagentCommand([]string{"list"}); rc != 0 {
63 t.Fatalf("list rc = %d", rc)
64 }
65 })
66 if !strings.Contains(out, "helper") || !strings.Contains(out, "project, manual") || !strings.Contains(out, "Updated helper") {
67 t.Fatalf("list output = %q", out)
68 }
69
70 errOut := captureStderr(t, func() {
71 if rc := subagentCommand([]string{"delete", "helper"}); rc != 2 {
72 t.Fatalf("unconfirmed delete rc = %d", rc)
73 }
74 })
75 if !strings.Contains(errOut, "--yes") {
76 t.Fatalf("unconfirmed delete output = %q", errOut)
77 }
78 if _, ok := store.Read("helper"); !ok {
79 t.Fatal("unconfirmed delete removed profile")
80 }
81 if rc := subagentCommand([]string{"delete", "helper", "--yes"}); rc != 0 {
82 t.Fatalf("delete rc = %d", rc)
83 }
84 if _, ok := store.Read("helper"); ok {
85 t.Fatal("confirmed delete left profile behind")
86 }
87 }
88
89 func TestSubagentListIncludesQualifiedPluginAgents(t *testing.T) {
90 home := t.TempDir()
91 t.Setenv("REASONIX_HOME", home)
92 project := t.TempDir()
93 t.Chdir(project)
94 root := filepath.Join(home, "plugins", "commercial-legal")
95 writePluginTestFile(t, filepath.Join(root, pluginpkg.ClaudeManifest), `{"name":"commercial-legal"}`)
96 writePluginTestFile(t, filepath.Join(root, "agents", "deal-debrief.md"), `---
97 description: Debrief a completed deal
98 model: sonnet
99 tools: ["Read", "Write", "mcp__*__search"]
100 ---
101 Debrief the deal.`)
102 if err := pluginpkg.Upsert(home, pluginpkg.InstalledPlugin{
103 Name: "commercial-legal", Root: "plugins/commercial-legal", ManifestKind: "claude", Enabled: true,
104 }); err != nil {
105 t.Fatal(err)
106 }
107
108 store := newCLISubagentStore()
109 sk, ok := store.ReadSlash("commercial-legal:agent:deal-debrief")
110 if !ok || sk.RunAs != skill.RunSubagent || sk.Invocation != "manual" || sk.Model != "" {
111 t.Fatalf("plugin agent = %+v, found=%v", sk, ok)
112 }
113 if got := strings.Join(sk.AllowedTools, ","); got != "read_file,write_file,mcp__*__search" {
114 t.Fatalf("allowed tools = %q", got)
115 }
116 out := captureStdout(t, func() {
117 if rc := subagentCommand([]string{"list"}); rc != 0 {
118 t.Fatalf("list rc = %d", rc)
119 }
120 })
121 if !strings.Contains(out, "commercial-legal:agent:deal-debrief") || !strings.Contains(out, "custom, manual") {
122 t.Fatalf("list output = %q", out)
123 }
124 }
125
126 func TestSubagentProfileCLIRejectsBuiltinCollisionAndRichSkillEdit(t *testing.T) {
127 isolateCLIConfigHome(t)
128 project := t.TempDir()
129 original, _ := os.Getwd()
130 if err := os.Chdir(project); err != nil {
131 t.Fatal(err)
132 }
133 t.Cleanup(func() { _ = os.Chdir(original) })
134
135 errOut := captureStderr(t, func() {
136 if rc := subagentCommand([]string{"create", "review", "--description", "d", "--prompt", "p"}); rc != 1 {
137 t.Fatalf("builtin collision rc = %d", rc)
138 }
139 })
140 if !strings.Contains(errOut, "already exists") {
141 t.Fatalf("builtin collision output = %q", errOut)
142 }
143
144 path := filepath.Join(project, ".reasonix", "skills", "rich", skill.SkillFile)
145 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
146 t.Fatal(err)
147 }
148 // read-only is now a managed profile field; use a still-unmanaged key so
149 // the editor refuse path remains covered.
150 if err := os.WriteFile(path, []byte("---\ndescription: rich\nrunAs: subagent\ninvocation: manual\ntriggers: [deploy]\n---\nbody"), 0o644); err != nil {
151 t.Fatal(err)
152 }
153 errOut = captureStderr(t, func() {
154 if rc := subagentCommand([]string{"edit", "rich", "--description", "changed"}); rc != 1 {
155 t.Fatalf("rich edit rc = %d", rc)
156 }
157 })
158 if !strings.Contains(errOut, "does not manage") {
159 t.Fatalf("rich edit output = %q", errOut)
160 }
161 // Positive: managed read-only frontmatter is editable and round-trips.
162 roPath := filepath.Join(project, ".reasonix", "skills", "readonly-agent", skill.SkillFile)
163 if err := os.MkdirAll(filepath.Dir(roPath), 0o755); err != nil {
164 t.Fatal(err)
165 }
166 if err := os.WriteFile(roPath, []byte("---\ndescription: ro\nrunAs: subagent\ninvocation: manual\nread-only: true\n---\nbody\n"), 0o644); err != nil {
167 t.Fatal(err)
168 }
169 if rc := subagentCommand([]string{"edit", "readonly-agent", "--description", "read only agent"}); rc != 0 {
170 t.Fatalf("managed read-only edit rc = %d", rc)
171 }
172 raw, err := os.ReadFile(roPath)
173 if err != nil {
174 t.Fatal(err)
175 }
176 if !strings.Contains(string(raw), "read-only: true") {
177 t.Fatalf("edit must preserve read-only frontmatter, got:\n%s", raw)
178 }
179 if !strings.Contains(string(raw), "read only agent") {
180 t.Fatalf("edit must update description, got:\n%s", raw)
181 }
182 }
183
184 func TestSubagentProfileCLIRejectsReservedAndCustomCommandNames(t *testing.T) {
185 isolateCLIConfigHome(t)
186 project := t.TempDir()
187 original, _ := os.Getwd()
188 if err := os.Chdir(project); err != nil {
189 t.Fatal(err)
190 }
191 t.Cleanup(func() { _ = os.Chdir(original) })
192 commandPath := filepath.Join(project, ".reasonix", "commands", "formatter.md")
193 if err := os.MkdirAll(filepath.Dir(commandPath), 0o755); err != nil {
194 t.Fatal(err)
195 }
196 if err := os.WriteFile(commandPath, []byte("---\ndescription: format\n---\nformat"), 0o644); err != nil {
197 t.Fatal(err)
198 }
199 for _, name := range []string{"clear", "mcp__server__prompt", "formatter"} {
200 errOut := captureStderr(t, func() {
201 if rc := subagentCommand([]string{"create", name, "--description", "d", "--prompt", "p"}); rc != 1 {
202 t.Fatalf("create %q rc = %d", name, rc)
203 }
204 })
205 if !strings.Contains(errOut, "slash command namespace") {
206 t.Fatalf("create %q output = %q", name, errOut)
207 }
208 }
209 }
210
211 func TestSubagentProfileCLIEditBuiltinModelOverride(t *testing.T) {
212 isolateCLIConfigHome(t)
213 cfg := config.Default()
214 cfg.DefaultModel = "offline/chat"
215 cfg.Providers = []config.ProviderEntry{{
216 Name: "offline",
217 Kind: "openai",
218 BaseURL: "https://offline.example.com",
219 Model: "chat",
220 APIKeyEnv: "REASONIX_SUBAGENT_OFFLINE_KEY",
221 SupportedEfforts: []string{"low", "high"},
222 DefaultEffort: "low",
223 }}
224 if err := cfg.SaveTo(config.UserConfigPath()); err != nil {
225 t.Fatal(err)
226 }
227 if rc := subagentCommand([]string{"edit", "review", "--model", "offline/chat", "--effort", "high"}); rc != 0 {
228 t.Fatalf("builtin edit rc = %d", rc)
229 }
230 loaded := config.LoadForEdit(config.UserConfigPath())
231 if got := subagentOverride(loaded.Agent.SubagentModels, "review"); got != "offline/chat" {
232 t.Fatalf("review model override = %q", got)
233 }
234 if got := subagentOverride(loaded.Agent.SubagentEfforts, "review"); got != "high" {
235 t.Fatalf("review effort override = %q", got)
236 }
237 out := captureStdout(t, func() {
238 if rc := subagentCommand([]string{"list"}); rc != 0 {
239 t.Fatalf("list rc = %d", rc)
240 }
241 })
242 if !strings.Contains(out, "review") || !strings.Contains(out, "model=offline/chat") || !strings.Contains(out, "effort=high") {
243 t.Fatalf("list did not show built-in override:\n%s", out)
244 }
245 if rc := subagentCommand([]string{"edit", "review", "--model="}); rc != 0 {
246 t.Fatalf("builtin clear rc = %d", rc)
247 }
248 loaded = config.LoadForEdit(config.UserConfigPath())
249 if got := subagentOverride(loaded.Agent.SubagentModels, "review"); got != "" {
250 t.Fatalf("review model override survived clear: %q", got)
251 }
252 }
253
254 func TestSubagentProfileCLIRunAndTrySelectIsolatedRunners(t *testing.T) {
255 previous := setupSubagentCommand
256 t.Cleanup(func() { setupSubagentCommand = previous })
257
258 var normalCalls, readOnlyCalls int
259 var normalTask, tryTask string
260 setupSubagentCommand = func(context.Context, string, int, bool, event.Sink, string) (*control.Controller, error) {
261 return control.New(control.Options{
262 Skills: []skill.Skill{{Name: "helper", RunAs: skill.RunSubagent, Invocation: "manual", Scope: skill.ScopeGlobal}},
263 SkillRunner: func(_ context.Context, _ skill.Skill, task string, opts skill.SubagentRunOptions) (string, error) {
264 normalCalls++
265 normalTask = task
266 if !opts.HostInitiated {
267 t.Fatal("run did not mark host-initiated invocation")
268 }
269 return "run answer", nil
270 },
271 ReadOnlySkillRunner: func(_ context.Context, _ skill.Skill, task string, opts skill.SubagentRunOptions) (string, error) {
272 readOnlyCalls++
273 tryTask = task
274 if !opts.HostInitiated {
275 t.Fatal("try did not mark host-initiated invocation")
276 }
277 return "try answer", nil
278 },
279 }), nil
280 }
281
282 out := captureStdout(t, func() {
283 if rc := subagentCommand([]string{"run", "helper", "inspect auth"}); rc != 0 {
284 t.Fatalf("run rc = %d", rc)
285 }
286 })
287 if strings.TrimSpace(out) != "run answer" || normalCalls != 1 || normalTask != "inspect auth" || readOnlyCalls != 0 {
288 t.Fatalf("run output=%q normal=%d task=%q readonly=%d", out, normalCalls, normalTask, readOnlyCalls)
289 }
290
291 out = captureStdout(t, func() {
292 if rc := subagentCommand([]string{"try", "helper", "inspect only"}); rc != 0 {
293 t.Fatalf("try rc = %d", rc)
294 }
295 })
296 if strings.TrimSpace(out) != "try answer" || readOnlyCalls != 1 || tryTask != "inspect only" {
297 t.Fatalf("try output=%q readonly=%d task=%q", out, readOnlyCalls, tryTask)
298 }
299 }
300
301 // TestSubagentRunTryDirPinsExplicitWorkspaceRoot reproduces the reported gap:
302 // a git repo at <repo>/.git with --dir pointing at a nested subdirectory must
303 // pin that subdirectory as the workspace root, not widen it to the repo root
304 // via git-root fallback. It drives the real chdirTo -> workspaceRootForDir ->
305 // setupSubagentCommand plumbing, not just the helpers in isolation.
306 func TestSubagentRunTryDirPinsExplicitWorkspaceRoot(t *testing.T) {
307 previous := setupSubagentCommand
308 t.Cleanup(func() { setupSubagentCommand = previous })
309 origWD, err := os.Getwd()
310 if err != nil {
311 t.Fatal(err)
312 }
313
314 repo := t.TempDir()
315 if err := os.Mkdir(filepath.Join(repo, ".git"), 0o755); err != nil {
316 t.Fatal(err)
317 }
318 sub := filepath.Join(repo, "a", "b")
319 if err := os.MkdirAll(sub, 0o755); err != nil {
320 t.Fatal(err)
321 }
322
323 // Register the cwd restore after repo's t.TempDir() cleanup so it runs
324 // first (LIFO): on Windows, RemoveAll fails while cwd sits inside repo.
325 t.Cleanup(func() { _ = os.Chdir(origWD) })
326 if err := os.Chdir(repo); err != nil {
327 t.Fatal(err)
328 }
329
330 var gotRoot string
331 setupSubagentCommand = func(_ context.Context, _ string, _ int, _ bool, _ event.Sink, workspaceRoot string) (*control.Controller, error) {
332 gotRoot = workspaceRoot
333 return control.New(control.Options{
334 Skills: []skill.Skill{{Name: "helper", RunAs: skill.RunSubagent, Invocation: "manual", Scope: skill.ScopeGlobal}},
335 SkillRunner: func(_ context.Context, _ skill.Skill, task string, opts skill.SubagentRunOptions) (string, error) {
336 return "run answer", nil
337 },
338 ReadOnlySkillRunner: func(_ context.Context, _ skill.Skill, task string, opts skill.SubagentRunOptions) (string, error) {
339 return "try answer", nil
340 },
341 }), nil
342 }
343
344 for _, verb := range []string{"run", "try"} {
345 gotRoot = ""
346 captureStdout(t, func() {
347 if rc := subagentCommand([]string{verb, "helper", "--dir", sub, "inspect"}); rc != 0 {
348 t.Fatalf("%s rc = %d", verb, rc)
349 }
350 })
351 want, err := filepath.EvalSymlinks(sub)
352 if err != nil {
353 t.Fatal(err)
354 }
355 got, err := filepath.EvalSymlinks(gotRoot)
356 if err != nil {
357 t.Fatalf("subagent %s --dir: setup seam got unusable workspace root %q: %v", verb, gotRoot, err)
358 }
359 if got != want {
360 t.Fatalf("subagent %s --dir %s: setup seam workspace root = %q, want explicit dir %q (must not widen to repo root)", verb, sub, gotRoot, sub)
361 }
362 }
363 }
364
365 func TestRootHelpListsSubagentCommand(t *testing.T) {
366 out := captureStdout(t, func() {
367 if rc := Run([]string{"help"}, "test"); rc != 0 {
368 t.Fatalf("help rc = %d", rc)
369 }
370 })
371 if !strings.Contains(out, "reasonix subagent <list|create|edit|delete|try|run>") {
372 t.Fatalf("help output missing subagent command:\n%s", out)
373 }
374 }
375
375 lines GO