1package subagents
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "os"
8 "path/filepath"
9 "runtime"
10 "strings"
11 "sync"
12 "sync/atomic"
13 "testing"
14 "time"
15)
16
17// TestSpawnWritesMetaJSON asserts the durability contract: every
18// successful Spawn leaves a meta.json on disk with the agent's
19// identity bits. Without this, Reload on the next zut launch can't
20// find the agent and the user loses access to the worktree.
21func TestSpawnWritesMetaJSON(t *testing.T) {
22 root := t.TempDir()
23 f := New(Config{
24 Root: root,
25 RepoRoot: root,
26 WebSearchPolicy: WebSearchAllow,
27 NewRunner: func(a *Agent) Runner {
28 return RunnerFunc(func(ctx context.Context, _ Sink) error {
29 <-ctx.Done()
30 return ctx.Err()
31 })
32 },
33 })
34 defer f.StopAll()
35
36 a, err := f.Spawn(context.Background(), "investigate widget")
37 if err != nil {
38 t.Fatalf("spawn: %v", err)
39 }
40
41 // Read meta.json straight off disk.
42 metaBytes, err := os.ReadFile(filepath.Join(root, "agents", a.ID, "meta.json"))
43 if err != nil {
44 t.Fatalf("read meta.json: %v", err)
45 }
46 var got agentMeta
47 if err := json.Unmarshal(metaBytes, &got); err != nil {
48 t.Fatalf("parse meta.json: %v", err)
49 }
50 if got.ID != a.ID {
51 t.Errorf("meta.ID = %q; want %q", got.ID, a.ID)
52 }
53 if got.Task != "investigate widget" {
54 t.Errorf("meta.Task = %q", got.Task)
55 }
56 if got.Dir != a.Dir {
57 t.Errorf("meta paths drifted: %+v vs agent %+v", got, a)
58 }
59 if got.InboxPath == "" || got.EventLogPath == "" || got.SessionPath == "" {
60 t.Errorf("meta paths empty: %+v", got)
61 }
62 if got.Started.IsZero() {
63 t.Error("meta.Started is zero")
64 }
65 if got.WebSearchPolicy != WebSearchAllow || a.WebSearchPolicy != WebSearchAllow {
66 t.Fatalf("web search policy persisted as meta=%v agent=%v, want allow", got.WebSearchPolicy, a.WebSearchPolicy)
67 }
68}
69
70// TestReloadRebuildsDetachedAgents simulates a zut restart by spawning
71// in one Supervisor, throwing it away, then opening a fresh Supervisor against
72// the same root and calling Reload. The user-visible state — id,
73// task, branch, dir — must come back, and status must be Detached so
74// the dashboard can offer resume.
75func TestReloadRebuildsDetachedAgents(t *testing.T) {
76 root := t.TempDir()
77
78 // First incarnation: spawn two agents, then drop the supervisor.
79 first := New(Config{
80 Root: root,
81 RepoRoot: root,
82 NewRunner: func(a *Agent) Runner {
83 return RunnerFunc(func(ctx context.Context, _ Sink) error {
84 <-ctx.Done()
85 return ctx.Err()
86 })
87 },
88 })
89 a1, err := first.Spawn(context.Background(), "alpha task")
90 if err != nil {
91 t.Fatalf("spawn a1: %v", err)
92 }
93 a2, err := first.Spawn(context.Background(), "beta task")
94 if err != nil {
95 t.Fatalf("spawn a2: %v", err)
96 }
97 first.StopAll()
98 // Wait briefly for the runner goroutines to settle so their
99 // stop event reaches the log before we move on. Reload itself
100 // doesn't need this; it makes the assertions below deterministic.
101 a1.Wait()
102 a2.Wait()
103
104 // Second incarnation against the same root.
105 second := New(Config{
106 Root: root,
107 RepoRoot: root,
108 })
109 loaded, errs := second.Reload()
110 if len(errs) > 0 {
111 t.Fatalf("reload errs: %v", errs)
112 }
113 if loaded != 2 {
114 t.Fatalf("loaded = %d; want 2", loaded)
115 }
116 snap := second.SnapshotAll()
117 if len(snap) != 2 {
118 t.Fatalf("snapshot len = %d; want 2", len(snap))
119 }
120 ids := map[string]AgentSnapshot{}
121 for _, s := range snap {
122 ids[s.ID] = s
123 }
124 if _, ok := ids[a1.ID]; !ok {
125 t.Errorf("reloaded set missing %s", a1.ID)
126 }
127 if _, ok := ids[a2.ID]; !ok {
128 t.Errorf("reloaded set missing %s", a2.ID)
129 }
130 for _, s := range snap {
131 if s.Status != StatusDetached {
132 t.Errorf("agent %s status = %q; want detached", s.ID, s.Status)
133 }
134 if s.Task == "" {
135 t.Errorf("agent %s lost its task", s.ID)
136 }
137 }
138}
139
140func TestResumePreservesPerAgentTimeout(t *testing.T) {
141 root := t.TempDir()
142 wantTimeout := 37 * time.Minute
143 first := New(Config{
144 Root: root, RepoRoot: root,
145 NewRunner: func(a *Agent) Runner {
146 return RunnerFunc(func(ctx context.Context, _ Sink) error {
147 <-ctx.Done()
148 return ctx.Err()
149 })
150 },
151 })
152 a, err := first.SpawnReq(context.Background(), SpawnRequest{Task: "timeout test", Timeout: wantTimeout})
153 if err != nil {
154 t.Fatal(err)
155 }
156 first.StopAll()
157 a.Wait()
158
159 observedCh := make(chan time.Duration, 1)
160 second := New(Config{
161 Root: root, RepoRoot: root,
162 Policy: SubagentPolicy{DefaultTimeout: time.Hour},
163 NewRunner: func(a *Agent) Runner {
164 observedCh <- a.Timeout
165 return RunnerFunc(func(ctx context.Context, _ Sink) error {
166 <-ctx.Done()
167 return ctx.Err()
168 })
169 },
170 })
171 if loaded, errs := second.Reload(); loaded != 1 || len(errs) != 0 {
172 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
173 }
174 resumed, err := second.ResumeSession(context.Background(), a.ID)
175 if err != nil {
176 t.Fatal(err)
177 }
178 var observed time.Duration
179 deadline := time.NewTimer(time.Second)
180 defer deadline.Stop()
181 select {
182 case observed = <-observedCh:
183 case <-deadline.C:
184 t.Fatal("timed out waiting for resumed runner to observe timeout")
185 }
186 if resumed.Timeout != wantTimeout || observed != wantTimeout {
187 t.Fatalf("resumed timeout = %s, runner observed %s; want %s", resumed.Timeout, observed, wantTimeout)
188 }
189 second.StopAll()
190 resumed.Wait()
191}
192
193func TestReloadRejectsMetadataPathsOutsideState(t *testing.T) {
194 root := t.TempDir()
195 outside := filepath.Join(t.TempDir(), "outside.json")
196 if err := os.WriteFile(outside, []byte("keep"), 0o600); err != nil {
197 t.Fatal(err)
198 }
199 stateDir := filepath.Join(root, "agents", "agent-1")
200 if err := os.MkdirAll(stateDir, 0o700); err != nil {
201 t.Fatal(err)
202 }
203 meta := agentMeta{
204 ID: "agent-1", Task: "malicious", Dir: root,
205 EventLogPath: outside, SessionPath: outside, InboxPath: outside,
206 }
207 data, err := json.Marshal(meta)
208 if err != nil {
209 t.Fatal(err)
210 }
211 if err := os.WriteFile(filepath.Join(stateDir, "meta.json"), data, 0o600); err != nil {
212 t.Fatal(err)
213 }
214 f := New(Config{Root: root, RepoRoot: root})
215 if loaded, errs := f.Reload(); loaded != 0 || len(errs) == 0 {
216 t.Fatalf("malicious metadata reload loaded=%d errs=%v", loaded, errs)
217 }
218 if got, err := os.ReadFile(outside); err != nil || string(got) != "keep" {
219 t.Fatalf("outside path was touched: data=%q err=%v", got, err)
220 }
221}
222
223// TestReloadIsIdempotent calls Reload twice in a row and asserts the
224// second call neither duplicates rows nor errors.
225func TestReloadIsIdempotent(t *testing.T) {
226 root := t.TempDir()
227 first := New(Config{
228 Root: root, RepoRoot: root,
229 NewRunner: func(a *Agent) Runner {
230 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
231 },
232 })
233 if _, err := first.Spawn(context.Background(), "only one"); err != nil {
234 t.Fatal(err)
235 }
236 first.StopAll()
237
238 second := New(Config{Root: root, RepoRoot: root})
239 loaded1, _ := second.Reload()
240 loaded2, errs := second.Reload()
241 if len(errs) > 0 {
242 t.Fatalf("errs on second reload: %v", errs)
243 }
244 if loaded1 != 1 || loaded2 != 0 {
245 t.Fatalf("loaded counts = (%d, %d); want (1, 0)", loaded1, loaded2)
246 }
247 if got := len(second.SnapshotAll()); got != 1 {
248 t.Fatalf("snapshot len = %d; want 1", got)
249 }
250}
251
252// TestReloadReplaysTranscriptFromEventLog drops a curated events.jsonl
253// next to a meta.json and checks that the transcript surfaces in the
254// reloaded agent. This is the user-facing payoff of Reload: opening
255// /subagents logs <id> after a restart shows what the agent said before.
256func TestReloadReplaysTranscriptFromEventLog(t *testing.T) {
257 root := t.TempDir()
258 id := "alpha-9"
259 stateDir := filepath.Join(root, "agents", id)
260 if err := os.MkdirAll(stateDir, 0o755); err != nil {
261 t.Fatal(err)
262 }
263 // meta.json
264 m := agentMeta{
265 ID: id, Task: "do thing",
266 Dir: root, Started: time.Now().Add(-time.Hour),
267 InboxPath: filepath.Join(stateDir, "in.sock"),
268 EventLogPath: filepath.Join(stateDir, "events.jsonl"),
269 SessionPath: filepath.Join(stateDir, "session.json"),
270 }
271 mb, _ := json.MarshalIndent(m, "", " ")
272 if err := os.WriteFile(filepath.Join(stateDir, "meta.json"), mb, 0o644); err != nil {
273 t.Fatal(err)
274 }
275 // Event log with one assistant turn and a graceful stop.
276 log, err := OpenEventLog(m.EventLogPath)
277 if err != nil {
278 t.Fatal(err)
279 }
280 _ = log.Append(NewEvent("assistant_message", map[string]any{
281 "content": []any{map[string]any{"type": "text", "text": "hello from the past"}},
282 }))
283 _ = log.Append(NewEvent("agent_stopped", map[string]any{"reason": "shutdown"}))
284 _ = log.Close()
285
286 f := New(Config{Root: root, RepoRoot: root})
287 loaded, errs := f.Reload()
288 if len(errs) > 0 || loaded != 1 {
289 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
290 }
291 a := f.Get(id)
292 if a == nil {
293 t.Fatal("reloaded agent not found")
294 }
295 // Legacy metadata has no persisted dashboard status, so startup keeps the
296 // agent detached until the user asks to inspect its durable history.
297 if a.Status() != StatusDetached {
298 t.Errorf("startup status = %q; want detached", a.Status())
299 }
300 got := a.Transcript()
301 if a.Status() != StatusDone {
302 t.Errorf("hydrated status = %q; want done (offline)", a.Status())
303 }
304 found := false
305 for _, line := range got {
306 if line == "hello from the past" {
307 found = true
308 }
309 }
310 if !found {
311 t.Errorf("transcript missing replayed line: %v", got)
312 }
313}
314
315// TestReloadUsesPersistedSummaryBeforeTranscriptHydration ensures startup
316// rebuilds the dashboard from compact metadata rather than replaying the
317// event log. Opening the transcript remains the explicit point that loads
318// durable history.
319func TestReloadUsesPersistedSummaryBeforeTranscriptHydration(t *testing.T) {
320 root := t.TempDir()
321 id := "summary-1"
322 stateDir := filepath.Join(root, "agents", id)
323 agent := &Agent{
324 ID: id,
325 Task: "persist summary",
326 OriginalTask: "persist summary",
327 Dir: root,
328 Started: time.Now().Add(-time.Hour),
329 EventLogPath: filepath.Join(stateDir, "events.jsonl"),
330 SessionPath: filepath.Join(stateDir, "session.json"),
331 status: StatusDone,
332 activity: "done",
333 finished: time.Now().Add(-time.Minute),
334 processState: ProcessExited,
335 turnState: TurnSucceeded,
336 currentTurnID: "turn-1",
337 done: make(chan struct{}),
338 }
339 if err := writeAgentMeta(stateDir, agent); err != nil {
340 t.Fatal(err)
341 }
342
343 log, err := OpenEventLog(agent.EventLogPath)
344 if err != nil {
345 t.Fatal(err)
346 }
347 if err := log.Append(NewEvent("assistant_message", map[string]any{
348 "content": []any{map[string]any{"type": "text", "text": "historical reply"}},
349 })); err != nil {
350 t.Fatal(err)
351 }
352 if err := log.Append(NewEvent("agent_stopped", map[string]any{"reason": "cancelled"})); err != nil {
353 t.Fatal(err)
354 }
355 if err := log.Close(); err != nil {
356 t.Fatal(err)
357 }
358
359 supervisor := New(Config{Root: root, RepoRoot: root})
360 if loaded, errs := supervisor.Reload(); loaded != 1 || len(errs) != 0 {
361 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
362 }
363 reloaded := supervisor.Get(id)
364 if reloaded == nil {
365 t.Fatal("reloaded agent missing")
366 }
367 before := reloaded.Snapshot()
368 if before.Status != StatusDetached || before.Activity != "done" || before.ProcessState != ProcessExited || before.TurnState != TurnSucceeded {
369 t.Fatalf("startup summary = (%q, %q, %q, %q), want (detached, done, exited, succeeded)", before.Status, before.Activity, before.ProcessState, before.TurnState)
370 }
371 if len(before.Lines) != 0 {
372 t.Fatalf("startup loaded transcript lines: %v", before.Lines)
373 }
374 lastActivity := before.LastActivity
375
376 lines := reloaded.Transcript()
377 if len(lines) != 1 || lines[0] != "historical reply" {
378 t.Fatalf("hydrated transcript = %v", lines)
379 }
380 after := reloaded.Snapshot()
381 if after.Status != StatusDetached || after.Activity != "done" {
382 t.Fatalf("hydration overwrote persisted summary: (%q, %q)", after.Status, after.Activity)
383 }
384 if !after.LastActivity.Equal(lastActivity) {
385 t.Fatalf("hydration changed last activity from %s to %s", lastActivity, after.LastActivity)
386 }
387}
388
389// TestReloadSkipsBareDirsAndCorruptMeta ensures one bad meta.json
390// doesn't blow up the whole reload. Directories with no meta.json
391// at all are silently ignored (Spawn that failed mid-way leaves
392// these); corrupt meta files are reported as errors but don't stop
393// the rest of the load.
394func TestReloadSkipsBareDirsAndCorruptMeta(t *testing.T) {
395 root := t.TempDir()
396 agentsDir := filepath.Join(root, "agents")
397 // Bare directory, no meta.json.
398 if err := os.MkdirAll(filepath.Join(agentsDir, "leftover"), 0o755); err != nil {
399 t.Fatal(err)
400 }
401 // Directory with garbage meta.json.
402 if err := os.MkdirAll(filepath.Join(agentsDir, "corrupt"), 0o755); err != nil {
403 t.Fatal(err)
404 }
405 if err := os.WriteFile(filepath.Join(agentsDir, "corrupt", "meta.json"), []byte("not json"), 0o644); err != nil {
406 t.Fatal(err)
407 }
408 // One good agent.
409 good := "good-1"
410 stateDir := filepath.Join(agentsDir, good)
411 _ = os.MkdirAll(stateDir, 0o755)
412 m := agentMeta{ID: good, Task: "x", Dir: "/tmp/x", Started: time.Now()}
413 mb, _ := json.MarshalIndent(m, "", " ")
414 _ = os.WriteFile(filepath.Join(stateDir, "meta.json"), mb, 0o644)
415
416 f := New(Config{Root: root, RepoRoot: root})
417 loaded, errs := f.Reload()
418 if loaded != 1 {
419 t.Errorf("loaded = %d; want 1", loaded)
420 }
421 if len(errs) != 1 {
422 t.Errorf("errs len = %d; want 1 (the corrupt entry): %v", len(errs), errs)
423 }
424}
425
426// TestResumeRestartsRunnerOnSameSession is the headline test. We:
427//
428// 1. Spawn an agent with a counting runner (records each Run call).
429// 2. Stop it.
430// 3. Resume it.
431// 4. Assert Run was called twice — once for spawn, once for resume —
432// against the same SessionPath / InboxPath / Dir.
433func TestResumeRestartsRunnerOnSameSession(t *testing.T) {
434 root := t.TempDir()
435 var (
436 mu sync.Mutex
437 runs []*Agent
438 runsDone int32
439 )
440 f := New(Config{
441 Root: root, RepoRoot: root,
442 NewRunner: func(a *Agent) Runner {
443 return RunnerFunc(func(ctx context.Context, sink Sink) error {
444 mu.Lock()
445 runs = append(runs, a)
446 mu.Unlock()
447 sink.Activity("ran")
448 atomic.AddInt32(&runsDone, 1)
449 <-ctx.Done()
450 return ctx.Err()
451 })
452 },
453 })
454 defer f.StopAll()
455
456 a, err := f.Spawn(context.Background(), "do thing")
457 if err != nil {
458 t.Fatalf("spawn: %v", err)
459 }
460 originalSession := a.SessionPath
461 originalDir := a.Dir
462 originalInbox := a.InboxPath
463
464 // Wait for the runner to record its presence, then stop the agent.
465 deadline := time.Now().Add(time.Second)
466 for atomic.LoadInt32(&runsDone) < 1 && time.Now().Before(deadline) {
467 time.Sleep(2 * time.Millisecond)
468 }
469 if err := f.Stop(a.ID); err != nil {
470 t.Fatalf("stop: %v", err)
471 }
472 a.Wait()
473 if a.Status() != StatusKilled {
474 t.Fatalf("post-stop status = %q; want killed", a.Status())
475 }
476 previousAttempt := a.Snapshot().Attempt
477
478 // Now resume.
479 a2, err := f.Resume(context.Background(), a.ID)
480 if err != nil {
481 t.Fatalf("resume: %v", err)
482 }
483 if a2.ID != a.ID {
484 t.Errorf("resume returned different id: %s vs %s", a2.ID, a.ID)
485 }
486 if a2.SessionPath != originalSession {
487 t.Errorf("resume changed session path: %s vs %s", a2.SessionPath, originalSession)
488 }
489 if a2.Dir != originalDir {
490 t.Errorf("resume changed dir: %s vs %s", a2.Dir, originalDir)
491 }
492 if a2.InboxPath != originalInbox {
493 t.Errorf("resume changed inbox path: %s vs %s", a2.InboxPath, originalInbox)
494 }
495 if got := a2.Snapshot().Attempt; got != previousAttempt+1 {
496 t.Errorf("resume attempt = %d; want %d", got, previousAttempt+1)
497 }
498 // Two runner invocations: spawn + resume.
499 deadline = time.Now().Add(time.Second)
500 for atomic.LoadInt32(&runsDone) < 2 && time.Now().Before(deadline) {
501 time.Sleep(2 * time.Millisecond)
502 }
503 mu.Lock()
504 defer mu.Unlock()
505 if len(runs) != 2 {
506 t.Fatalf("runner invocations = %d; want 2", len(runs))
507 }
508 if runs[1].ID != a.ID {
509 t.Errorf("second run had wrong id: %s", runs[1].ID)
510 }
511 if got := len(f.SnapshotAll()); got != 1 {
512 t.Errorf("snapshot len = %d; want 1 (in-place replace)", got)
513 }
514}
515
516func TestResumeRecalculatesInvalidStateInboxPath(t *testing.T) {
517 if runtime.GOOS == "windows" {
518 t.Skip("subagent inbox runtime relocation applies to Unix sockets")
519 }
520 root := t.TempDir()
521 f := New(Config{
522 Root: root, RepoRoot: root,
523 NewRunner: func(*Agent) Runner {
524 return RunnerFunc(func(context.Context, Sink) error { return nil })
525 },
526 })
527 a, err := f.Spawn(context.Background(), "invalid inbox")
528 if err != nil {
529 t.Fatal(err)
530 }
531 a.Wait()
532
533 invalidPath := filepath.Join(root, "agents", a.ID, "in.sock")
534 a.InboxPath = invalidPath
535 a2, err := f.Resume(context.Background(), a.ID)
536 if err != nil {
537 t.Fatalf("resume: %v", err)
538 }
539 a2.Wait()
540 if a2.InboxPath == invalidPath {
541 t.Fatalf("resume kept state-directory inbox path %q", invalidPath)
542 }
543 if strings.HasPrefix(a2.InboxPath, root+string(filepath.Separator)) {
544 t.Fatalf("resumed inbox %q remains below state root %q", a2.InboxPath, root)
545 }
546}
547
548// TestResumeSetsResumingFlag pins the contract execRunner relies on:
549// after Resume, the new Agent has Resuming == true; after a fresh
550// Spawn it's false. The runner branches on this to decide whether
551// to pass the original Task as a positional argv to the child, so
552// getting it wrong silently re-runs the initial task on every
553// resume and surfaces "agent busy; send 'cancel' first" between
554// assistant messages.
555func TestResumeSetsResumingFlag(t *testing.T) {
556 root := t.TempDir()
557 f := New(Config{
558 Root: root, RepoRoot: root,
559 NewRunner: func(a *Agent) Runner {
560 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
561 },
562 })
563 defer f.StopAll()
564
565 a, err := f.Spawn(context.Background(), "x")
566 if err != nil {
567 t.Fatal(err)
568 }
569 if a.Resuming {
570 t.Fatal("fresh Spawn produced Resuming==true; want false")
571 }
572 if err := f.Stop(a.ID); err != nil {
573 t.Fatal(err)
574 }
575 a.Wait()
576
577 a2, err := f.Resume(context.Background(), a.ID)
578 if err != nil {
579 t.Fatalf("resume: %v", err)
580 }
581 if !a2.Resuming {
582 t.Error("Resume produced Resuming==false; want true so the runner skips the duplicate initial-task argv")
583 }
584}
585
586// TestResumeRejectsRunningAgent prevents the user from double-running
587// an agent: two runners on the same session.json would race.
588func TestResumeRejectsRunningAgent(t *testing.T) {
589 root := t.TempDir()
590 f := New(Config{
591 Root: root, RepoRoot: root,
592 NewRunner: func(a *Agent) Runner {
593 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
594 },
595 })
596 defer f.StopAll()
597 a, err := f.Spawn(context.Background(), "x")
598 if err != nil {
599 t.Fatal(err)
600 }
601 // Wait for the runner to actually start.
602 deadline := time.Now().Add(time.Second)
603 for a.Status() != StatusRunning && time.Now().Before(deadline) {
604 time.Sleep(2 * time.Millisecond)
605 }
606 if _, err := f.Resume(context.Background(), a.ID); err == nil {
607 t.Fatal("resume on running agent did not error")
608 }
609}
610
611// TestResumeAfterReload exercises the full lifecycle the user cares
612// about: spawn in process A, exit A, start process B, Reload, Resume.
613// The resumed agent must keep its id and start producing new output
614// against the same on-disk state.
615//
616// Note on transcript persistence: in production the runner is
617// execRunner, which writes every event to events.jsonl, and Reload's
618// replayEventsIntoAgent rebuilds the transcript from there. The fake
619// RunnerFunc in this test calls sink.Transcript directly (which only
620// touches in-memory state), so the "first run" line is *expected* to
621// be lost across the restart — the in-memory Agent went away. We
622// have TestReloadReplaysTranscriptFromEventLog covering the
623// log-replay path with a curated events.jsonl.
624func TestResumeAfterReload(t *testing.T) {
625 root := t.TempDir()
626 // Process A
627 a := New(Config{
628 Root: root, RepoRoot: root,
629 NewRunner: func(ag *Agent) Runner {
630 return RunnerFunc(func(ctx context.Context, sink Sink) error {
631 sink.Transcript("first run for " + ag.ID)
632 <-ctx.Done()
633 return ctx.Err()
634 })
635 },
636 })
637 ag, err := a.Spawn(context.Background(), "x")
638 if err != nil {
639 t.Fatal(err)
640 }
641 // Let the runner record its transcript line before we tear it down.
642 deadline := time.Now().Add(time.Second)
643 for len(ag.Transcript()) == 0 && time.Now().Before(deadline) {
644 time.Sleep(2 * time.Millisecond)
645 }
646 id := ag.ID
647 a.StopAll()
648 ag.Wait()
649
650 // Process B: a new Supervisor against the same root.
651 resumed := make(chan struct{}, 1)
652 b := New(Config{
653 Root: root, RepoRoot: root,
654 NewRunner: func(ag *Agent) Runner {
655 return RunnerFunc(func(ctx context.Context, sink Sink) error {
656 sink.Transcript("second run for " + ag.ID)
657 select {
658 case resumed <- struct{}{}:
659 default:
660 }
661 <-ctx.Done()
662 return ctx.Err()
663 })
664 },
665 })
666 if loaded, errs := b.Reload(); loaded != 1 || len(errs) > 0 {
667 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
668 }
669 a2, err := b.Resume(context.Background(), id)
670 if err != nil {
671 t.Fatalf("resume: %v", err)
672 }
673 defer b.StopAll()
674
675 select {
676 case <-resumed:
677 case <-time.After(time.Second):
678 t.Fatal("resume runner did not start")
679 }
680 if a2.ID != id {
681 t.Errorf("resume id = %s; want %s", a2.ID, id)
682 }
683
684 // Wait for the new transcript line to land.
685 deadline = time.Now().Add(time.Second)
686 for time.Now().Before(deadline) {
687 for _, l := range a2.Transcript() {
688 if l == "second run for "+id {
689 return
690 }
691 }
692 time.Sleep(5 * time.Millisecond)
693 }
694 t.Fatalf("resumed transcript missing fresh line: %v", a2.Transcript())
695}
696
697func TestStopMustFinishBeforeResumeOrRemove(t *testing.T) {
698 root := t.TempDir()
699 started := make(chan struct{})
700 release := make(chan struct{})
701 f := New(Config{
702 Root: root, RepoRoot: root,
703 NewRunner: func(*Agent) Runner {
704 return RunnerFunc(func(context.Context, Sink) error {
705 close(started)
706 <-release
707 return nil
708 })
709 },
710 })
711 a, err := f.Spawn(context.Background(), "slow stop")
712 if err != nil {
713 t.Fatal(err)
714 }
715 <-started
716 if err := f.Stop(a.ID); err != nil {
717 t.Fatal(err)
718 }
719 if _, err := f.Resume(context.Background(), a.ID); err == nil || !strings.Contains(err.Error(), "finalizing") {
720 t.Fatalf("immediate resume error = %v, want finalizing", err)
721 }
722 if err := f.Remove(a.ID); err == nil || !strings.Contains(err.Error(), "finalizing") {
723 t.Fatalf("immediate remove error = %v, want finalizing", err)
724 }
725 close(release)
726 a.Wait()
727}
728
729func TestResumeFencesLiveReloadedWorker(t *testing.T) {
730 if runtime.GOOS == "windows" {
731 t.Skip("subagent inbox transport uses Unix-domain sockets")
732 }
733 root := t.TempDir()
734 first := New(Config{
735 Root: root, RepoRoot: root,
736 NewRunner: func(*Agent) Runner {
737 return RunnerFunc(func(context.Context, Sink) error { return nil })
738 },
739 })
740 a, err := first.Spawn(context.Background(), "live worker")
741 if err != nil {
742 t.Fatal(err)
743 }
744 a.Wait()
745 ln, err := Listen(a.InboxPath)
746 if err != nil {
747 t.Fatal(err)
748 }
749 defer ln.Close()
750
751 second := New(Config{Root: root, RepoRoot: root})
752 if loaded, errs := second.Reload(); loaded != 1 || len(errs) != 0 {
753 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
754 }
755 if got := second.Get(a.ID).ProcessState(); got != ProcessAlive {
756 t.Fatalf("reloaded process state = %s, want alive", got)
757 }
758 if _, err := second.Resume(context.Background(), a.ID); err == nil || !strings.Contains(err.Error(), "live worker") {
759 t.Fatalf("resume error = %v, want live-worker fence", err)
760 }
761}
762
763func TestSupervisorProviderSettingsPersistAcrossReloadAndResume(t *testing.T) {
764 root := t.TempDir()
765 newSupervisor := func(baseURL string, insecureTLS bool) *Supervisor {
766 return New(Config{
767 Root: root,
768 RepoRoot: root,
769 BaseURL: baseURL,
770 InsecureTLS: insecureTLS,
771 NewRunner: func(a *Agent) Runner {
772 return RunnerFunc(func(ctx context.Context, _ Sink) error {
773 <-ctx.Done()
774 return ctx.Err()
775 })
776 },
777 })
778 }
779
780 first := newSupervisor("https://parent.example.test/v1", true)
781 a, err := first.SpawnReq(context.Background(), SpawnRequest{Task: "x"})
782 if err != nil {
783 t.Fatalf("spawn: %v", err)
784 }
785 if a.BaseURL != "https://parent.example.test/v1" || !a.InsecureTLS {
786 t.Fatalf("spawned settings = (%q, %v), want inherited config", a.BaseURL, a.InsecureTLS)
787 }
788 if snap := a.Snapshot(); snap.BaseURL != a.BaseURL || snap.InsecureTLS != a.InsecureTLS {
789 t.Fatalf("snapshot settings = (%q, %v), want (%q, %v)", snap.BaseURL, snap.InsecureTLS, a.BaseURL, a.InsecureTLS)
790 }
791 if err := first.Stop(a.ID); err != nil {
792 t.Fatalf("stop: %v", err)
793 }
794 a.Wait()
795
796 metaBytes, err := os.ReadFile(filepath.Join(root, "agents", a.ID, "meta.json"))
797 if err != nil {
798 t.Fatalf("read meta.json: %v", err)
799 }
800 var meta agentMeta
801 if err := json.Unmarshal(metaBytes, &meta); err != nil {
802 t.Fatalf("decode meta.json: %v", err)
803 }
804 if meta.BaseURL != a.BaseURL || !meta.InsecureTLS {
805 t.Fatalf("metadata settings = (%q, %v), want (%q, %v)", meta.BaseURL, meta.InsecureTLS, a.BaseURL, a.InsecureTLS)
806 }
807 if strings.Contains(string(metaBytes), "api_key") || strings.Contains(string(metaBytes), "parent-secret") {
808 t.Fatalf("metadata contains credential material: %s", metaBytes)
809 }
810
811 second := newSupervisor("https://different.example.test/v1", false)
812 if loaded, errs := second.Reload(); loaded != 1 || len(errs) != 0 {
813 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
814 }
815 reloaded := second.Get(a.ID)
816 if reloaded == nil || reloaded.BaseURL != a.BaseURL || !reloaded.InsecureTLS {
817 t.Fatalf("reloaded settings = (%q, %v), want (%q, %v)", reloaded.BaseURL, reloaded.InsecureTLS, a.BaseURL, a.InsecureTLS)
818 }
819 resumed, err := second.Resume(context.Background(), a.ID)
820 if err != nil {
821 t.Fatalf("resume: %v", err)
822 }
823 if resumed.BaseURL != a.BaseURL || !resumed.InsecureTLS {
824 t.Fatalf("resumed settings = (%q, %v), want (%q, %v)", resumed.BaseURL, resumed.InsecureTLS, a.BaseURL, a.InsecureTLS)
825 }
826 if err := second.Stop(resumed.ID); err != nil {
827 t.Fatalf("stop resumed: %v", err)
828 }
829 resumed.Wait()
830}
831
832func TestExplicitChildProviderDoesNotInheritHostEndpoint(t *testing.T) {
833 f := New(Config{
834 Root: t.TempDir(), RepoRoot: t.TempDir(), Provider: "anthropic",
835 BaseURL: "https://host.example.test/v1", InsecureTLS: true,
836 NewRunner: func(*Agent) Runner {
837 return RunnerFunc(func(context.Context, Sink) error { return nil })
838 },
839 })
840 a, err := f.SpawnReq(context.Background(), SpawnRequest{Task: "x", Provider: "openai"})
841 if err != nil {
842 t.Fatal(err)
843 }
844 a.Wait()
845 if a.BaseURL != "" || a.InsecureTLS {
846 t.Fatalf("explicit provider inherited host settings: (%q, %v)", a.BaseURL, a.InsecureTLS)
847 }
848}
849
850func TestSpawnRequestProviderSettingsOverrideConfig(t *testing.T) {
851 root := t.TempDir()
852 f := New(Config{
853 Root: root,
854 RepoRoot: root,
855 BaseURL: "https://config.example.test/v1",
856 NewRunner: func(*Agent) Runner {
857 return RunnerFunc(func(context.Context, Sink) error { return nil })
858 },
859 })
860 a, err := f.SpawnReq(context.Background(), SpawnRequest{
861 Task: "x",
862 BaseURL: "https://request.example.test/v1",
863 InsecureTLS: true,
864 })
865 if err != nil {
866 t.Fatalf("spawn: %v", err)
867 }
868 a.Wait()
869 if a.BaseURL != "https://request.example.test/v1" || !a.InsecureTLS {
870 t.Fatalf("spawned settings = (%q, %v), want request override", a.BaseURL, a.InsecureTLS)
871 }
872}
873
874// TestSpawnReqPersistsModel confirms that the per-agent model
875// override is captured at Spawn time, surfaced via Snapshot, and
876// written to meta.json so a later Reload + Resume reuses it.
877func TestSpawnReqPersistsModel(t *testing.T) {
878 root := t.TempDir()
879 f := New(Config{
880 Root: root, RepoRoot: root,
881 NewRunner: func(a *Agent) Runner {
882 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
883 },
884 })
885 f.SetActiveSession("host-session")
886 a, err := f.SpawnReq(context.Background(), SpawnRequest{
887 Task: "x", Model: "claude-sonnet-4-5", Provider: "anthropic",
888 Reasoning: "high", Subagent: "reviewer",
889 })
890 if err != nil {
891 t.Fatalf("spawn: %v", err)
892 }
893 if a.Model != "claude-sonnet-4-5" || a.Provider != "anthropic" || a.Reasoning != "high" || a.Subagent != "reviewer" || a.SessionID != "host-session" {
894 t.Fatalf("agent fields = (%q,%q,%q,%q,%q); want model/provider/reasoning/profile/session", a.Model, a.Provider, a.Reasoning, a.Subagent, a.SessionID)
895 }
896 snap := a.Snapshot()
897 if snap.Model != "claude-sonnet-4-5" || snap.Provider != "anthropic" || snap.Reasoning != "high" || snap.Subagent != "reviewer" {
898 t.Fatalf("snapshot = (%q,%q,%q,%q); child fields not surfaced", snap.Model, snap.Provider, snap.Reasoning, snap.Subagent)
899 }
900
901 // Stop so we can read meta.json without racing the run loop.
902 if err := f.Stop(a.ID); err != nil {
903 t.Fatal(err)
904 }
905 a.Wait()
906
907 metaBytes, err := os.ReadFile(filepath.Join(root, "agents", a.ID, "meta.json"))
908 if err != nil {
909 t.Fatalf("read meta.json: %v", err)
910 }
911 var got agentMeta
912 if err := json.Unmarshal(metaBytes, &got); err != nil {
913 t.Fatal(err)
914 }
915 if got.Model != "claude-sonnet-4-5" || got.Provider != "anthropic" || got.Reasoning != "high" || got.Subagent != "reviewer" || got.SessionID != "host-session" {
916 t.Errorf("meta = (%q,%q,%q,%q,%q); want model/provider/reasoning/profile/session persisted", got.Model, got.Provider, got.Reasoning, got.Subagent, got.SessionID)
917 }
918
919 // Reload in a fresh Supervisor and confirm the detached agent still
920 // carries the model/provider so Resume can route the child
921 // subprocess back to the same model.
922 g := New(Config{
923 Root: root, RepoRoot: root,
924 NewRunner: func(a *Agent) Runner {
925 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
926 },
927 })
928 if loaded, errs := g.Reload(); loaded != 1 || len(errs) > 0 {
929 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
930 }
931 re := g.Get(a.ID)
932 if re == nil {
933 t.Fatal("reloaded agent missing")
934 }
935 if re.Model != "claude-sonnet-4-5" || re.Provider != "anthropic" || re.Reasoning != "high" || re.Subagent != "reviewer" || re.SessionID != "host-session" {
936 t.Errorf("reloaded fields = (%q,%q,%q,%q,%q); want preserved", re.Model, re.Provider, re.Reasoning, re.Subagent, re.SessionID)
937 }
938
939 resumed, err := g.Resume(context.Background(), re.ID)
940 if err != nil {
941 t.Fatalf("resume: %v", err)
942 }
943 if resumed.Reasoning != "high" || resumed.Subagent != "reviewer" || resumed.SessionID != "host-session" {
944 t.Errorf("resumed fields = (%q,%q,%q); want reasoning/profile/session preserved", resumed.Reasoning, resumed.Subagent, resumed.SessionID)
945 }
946 if err := g.Stop(resumed.ID); err != nil {
947 t.Fatalf("stop resumed agent: %v", err)
948 }
949 resumed.Wait()
950}
951
952// TestSubagentWorkerArgsIncludesModelFlags pins the argv contract that
953// connects the supervisor's per-agent model override to the child's
954// --model / --provider flag set. Adding a new path to argv without
955// updating this assertion is the failure mode this catches.
956func TestSubagentWorkerArgsIncludesModelFlags(t *testing.T) {
957 args := subagentWorkerArgs(subagentWorkerArgsOpts{
958 Exe: "/zut", Dir: "/wt", SessionPath: "/s.json", InboxPath: "/in.sock",
959 Task: "do x", Model: "gpt-5", Provider: "openai",
960 })
961 want := []string{"--model", "gpt-5", "--provider", "openai"}
962 for i := 0; i+1 < len(want); i += 2 {
963 flag, value := want[i], want[i+1]
964 found := false
965 for j := 0; j+1 < len(args); j++ {
966 if args[j] == flag && args[j+1] == value {
967 found = true
968 break
969 }
970 }
971 if !found {
972 t.Errorf("argv missing %s %s: %v", flag, value, args)
973 }
974 }
975 // And the task still ends up positional last.
976 if args[len(args)-1] != "do x" {
977 t.Errorf("task should be last positional; argv=%v", args)
978 }
979}
980
981// TestStopOnDetachedAgentIsNoopAndDoesNotPanic regression-tests the
982// segfault that hit when the user pressed 'k' on a reloaded
983// (detached) agent: Supervisor.Stop unconditionally called a.cancel(),
984// but buildDetachedAgent never assigns a cancel func because there's
985// no in-process runner to cancel. The fix is to short-circuit Stop
986// for StatusDetached and — belt-and-braces — nil-check a.cancel.
987func TestStopOnDetachedAgentIsNoopAndDoesNotPanic(t *testing.T) {
988 root := t.TempDir()
989 // Build a detached agent the same way Reload does: drop a
990 // meta.json on disk, then ask a fresh Supervisor to pick it up.
991 id := "alpha-1"
992 stateDir := filepath.Join(root, "agents", id)
993 if err := os.MkdirAll(stateDir, 0o755); err != nil {
994 t.Fatal(err)
995 }
996 m := agentMeta{
997 ID: id, Task: "t",
998 Dir: root,
999 Started: time.Now().Add(-time.Hour),
1000 InboxPath: filepath.Join(stateDir, "in.sock"),
1001 EventLogPath: filepath.Join(stateDir, "events.jsonl"),
1002 SessionPath: filepath.Join(stateDir, "session.json"),
1003 }
1004 mb, _ := json.MarshalIndent(m, "", " ")
1005 if err := os.WriteFile(filepath.Join(stateDir, "meta.json"), mb, 0o644); err != nil {
1006 t.Fatal(err)
1007 }
1008
1009 f := New(Config{Root: root, RepoRoot: root})
1010 if loaded, errs := f.Reload(); loaded != 1 || len(errs) > 0 {
1011 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
1012 }
1013 a := f.Get(id)
1014 if a == nil {
1015 t.Fatal("detached agent missing from subagent")
1016 }
1017 if a.Status() != StatusDetached {
1018 t.Fatalf("setup: agent status = %q; want detached", a.Status())
1019 }
1020
1021 // The real assertion: Stop returns cleanly without panicking.
1022 defer func() {
1023 if r := recover(); r != nil {
1024 t.Fatalf("Stop on detached agent panicked: %v", r)
1025 }
1026 }()
1027 if err := f.Stop(id); err != nil {
1028 t.Fatalf("Stop on detached agent: %v", err)
1029 }
1030 // Status must remain Detached (Stop is a no-op).
1031 if got := a.Status(); got != StatusDetached {
1032 t.Errorf("after Stop status = %q; want detached (no-op)", got)
1033 }
1034
1035 // StopAll, which the cli defers on exit, must also be safe.
1036 f.StopAll()
1037}
1038
1039// TestRemoveAlsoCleansStateDir ensures Remove deletes the on-disk
1040// state directory in addition to the worktree, so a removed agent
1041// doesn't reappear on the next Reload.
1042func TestRemoveAlsoCleansStateDir(t *testing.T) {
1043 root := t.TempDir()
1044 f := New(Config{
1045 Root: root, RepoRoot: root,
1046 NewRunner: func(a *Agent) Runner {
1047 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
1048 },
1049 })
1050 a, err := f.Spawn(context.Background(), "x")
1051 if err != nil {
1052 t.Fatal(err)
1053 }
1054 stateDir := filepath.Join(root, "agents", a.ID)
1055 if _, err := os.Stat(filepath.Join(stateDir, "meta.json")); err != nil {
1056 t.Fatalf("meta.json missing pre-remove: %v", err)
1057 }
1058 if err := f.Stop(a.ID); err != nil {
1059 t.Fatal(err)
1060 }
1061 a.Wait()
1062 if err := f.Remove(a.ID); err != nil {
1063 t.Fatal(err)
1064 }
1065 if _, err := os.Stat(stateDir); !errors.Is(err, os.ErrNotExist) {
1066 t.Fatalf("state dir should be gone after remove; got %v", err)
1067 }
1068
1069 // A fresh Supervisor + Reload should find nothing.
1070 g := New(Config{Root: root, RepoRoot: root})
1071 if loaded, _ := g.Reload(); loaded != 0 {
1072 t.Fatalf("reload after remove loaded=%d; want 0", loaded)
1073 }
1074}
1075
1076func TestRemoveReloadedAgentKeepsSiblingState(t *testing.T) {
1077 root := t.TempDir()
1078 first := New(Config{
1079 Root: root, RepoRoot: root,
1080 NewRunner: func(*Agent) Runner {
1081 return RunnerFunc(func(context.Context, Sink) error { return nil })
1082 },
1083 })
1084 a1, err := first.Spawn(context.Background(), "first")
1085 if err != nil {
1086 t.Fatal(err)
1087 }
1088 a2, err := first.Spawn(context.Background(), "second")
1089 if err != nil {
1090 t.Fatal(err)
1091 }
1092 a1.Wait()
1093 a2.Wait()
1094
1095 second := New(Config{Root: root, RepoRoot: root})
1096 if loaded, errs := second.Reload(); loaded != 2 || len(errs) != 0 {
1097 t.Fatalf("reload loaded=%d errs=%v", loaded, errs)
1098 }
1099 if err := second.Remove(a1.ID); err != nil {
1100 t.Fatal(err)
1101 }
1102 if _, err := os.Stat(filepath.Join(root, "agents", a2.ID, "meta.json")); err != nil {
1103 t.Fatalf("removing reloaded sibling deleted surviving metadata: %v", err)
1104 }
1105}
1106
1107// TestActiveSessionScopesSnapshotAll proves the session filter the
1108// user asked for: a single Supervisor with agents spawned under two
1109// different active sessions only surfaces the agents matching the
1110// currently-active session via SnapshotAll. Switching the active
1111// session re-narrows the view without touching agent state.
1112func TestActiveSessionScopesSnapshotAll(t *testing.T) {
1113 root := t.TempDir()
1114 f := New(Config{
1115 Root: root, RepoRoot: root,
1116 NewRunner: func(a *Agent) Runner {
1117 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
1118 },
1119 })
1120
1121 // Spawn one agent under session A and one under session B.
1122 f.SetActiveSession("sess-A")
1123 aA, err := f.Spawn(context.Background(), "task A")
1124 if err != nil {
1125 t.Fatal(err)
1126 }
1127 f.SetActiveSession("sess-B")
1128 aB, err := f.Spawn(context.Background(), "task B")
1129 if err != nil {
1130 t.Fatal(err)
1131 }
1132
1133 // Both agents must carry the session id they were spawned under,
1134 // regardless of any later SetActiveSession.
1135 if aA.SessionID != "sess-A" {
1136 t.Errorf("aA.SessionID = %q; want sess-A", aA.SessionID)
1137 }
1138 if aB.SessionID != "sess-B" {
1139 t.Errorf("aB.SessionID = %q; want sess-B", aB.SessionID)
1140 }
1141
1142 // Active session B → only aB visible.
1143 only := snapshotIDs(f.SnapshotAll())
1144 if len(only) != 1 || only[0] != aB.ID {
1145 t.Errorf("scoped to sess-B, snapshot ids = %v; want [%s]", only, aB.ID)
1146 }
1147
1148 // Switch back to A → only aA visible.
1149 f.SetActiveSession("sess-A")
1150 only = snapshotIDs(f.SnapshotAll())
1151 if len(only) != 1 || only[0] != aA.ID {
1152 t.Errorf("scoped to sess-A, snapshot ids = %v; want [%s]", only, aA.ID)
1153 }
1154
1155 // Clear the scope → both visible.
1156 f.SetActiveSession("")
1157 all := snapshotIDs(f.SnapshotAll())
1158 if len(all) != 2 {
1159 t.Errorf("unscoped snapshot ids = %v; want both agents", all)
1160 }
1161
1162 // Cleanup.
1163 _ = f.Stop(aA.ID)
1164 _ = f.Stop(aB.ID)
1165 aA.Wait()
1166 aB.Wait()
1167}
1168
1169// TestSessionIDPersistsAcrossReload confirms the SessionID field
1170// survives a Supervisor restart: an agent spawned under session A in one
1171// Supervisor instance is still SessionID="sess-A" after a fresh New +
1172// Reload reads it back from meta.json. Without persistence, the
1173// scope filter would forget which session owned each agent after
1174// a zut restart and the dashboard would leak everything again.
1175func TestSessionIDPersistsAcrossReload(t *testing.T) {
1176 root := t.TempDir()
1177 mkSupervisor := func() *Supervisor {
1178 return New(Config{
1179 Root: root, RepoRoot: root,
1180 NewRunner: func(a *Agent) Runner {
1181 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
1182 },
1183 })
1184 }
1185
1186 f := mkSupervisor()
1187 f.SetActiveSession("sess-keep")
1188 a, err := f.Spawn(context.Background(), "persist me")
1189 if err != nil {
1190 t.Fatal(err)
1191 }
1192 _ = f.Stop(a.ID)
1193 a.Wait()
1194
1195 // Fresh Supervisor, same root, reload from disk.
1196 g := mkSupervisor()
1197 if loaded, errs := g.Reload(); loaded != 1 || len(errs) > 0 {
1198 t.Fatalf("reload loaded=%d errs=%v; want 1 / no errs", loaded, errs)
1199 }
1200 g.SetActiveSession("sess-keep")
1201 got := snapshotIDs(g.SnapshotAll())
1202 if len(got) != 1 || got[0] != a.ID {
1203 t.Errorf("after reload + scope to sess-keep, ids = %v; want [%s]", got, a.ID)
1204 }
1205
1206 // A terminal persisted agent remains visible from another host session
1207 // so a normal restart does not hide durable recovery state.
1208 g.SetActiveSession("sess-other")
1209 if got := snapshotIDs(g.SnapshotAll()); len(got) != 1 || got[0] != a.ID {
1210 t.Errorf("scoped to other session, ids = %v; want [%s]", got, a.ID)
1211 }
1212}
1213
1214// TestEmptySessionIDIsVisibleFromAnyScope pins the unscoped-agent
1215// rule: agents whose meta.json predates the SessionID field (or who
1216// were spawned without an active session, e.g. via a test rig or
1217// scripted caller) carry SessionID == "" and remain visible from
1218// every scope. Otherwise the schema bump would orphan every
1219// pre-existing agent the moment a user upgraded zut.
1220func TestEmptySessionIDIsVisibleFromAnyScope(t *testing.T) {
1221 root := t.TempDir()
1222 f := New(Config{
1223 Root: root, RepoRoot: root,
1224 NewRunner: func(a *Agent) Runner {
1225 return RunnerFunc(func(ctx context.Context, _ Sink) error { <-ctx.Done(); return ctx.Err() })
1226 },
1227 })
1228 // No SetActiveSession call → agent spawned with empty SessionID.
1229 a, err := f.Spawn(context.Background(), "unscoped")
1230 if err != nil {
1231 t.Fatal(err)
1232 }
1233 if a.SessionID != "" {
1234 t.Fatalf("unscoped spawn produced SessionID %q; want empty", a.SessionID)
1235 }
1236
1237 for _, scope := range []string{"", "any-session", "some-other"} {
1238 f.SetActiveSession(scope)
1239 got := snapshotIDs(f.SnapshotAll())
1240 if len(got) != 1 || got[0] != a.ID {
1241 t.Errorf("scope=%q: ids = %v; want unscoped agent visible", scope, got)
1242 }
1243 }
1244
1245 _ = f.Stop(a.ID)
1246 a.Wait()
1247}
1248
1249func TestWebSearchPolicyPersistsThroughReloadResumeAndChildArgv(t *testing.T) {
1250 root := t.TempDir()
1251 newSupervisor := func(policy WebSearchPolicy) *Supervisor {
1252 return New(Config{
1253 Root: root,
1254 RepoRoot: root,
1255 WebSearchPolicy: policy,
1256 NewRunner: func(*Agent) Runner {
1257 return RunnerFunc(func(context.Context, Sink) error { return nil })
1258 },
1259 })
1260 }
1261
1262 first := newSupervisor(WebSearchAllow)
1263 t.Cleanup(first.StopAll)
1264 spawned, err := first.Spawn(context.Background(), "web policy")
1265 if err != nil {
1266 t.Fatalf("spawn: %v", err)
1267 }
1268 spawned.Wait()
1269 if spawned.WebSearchPolicy != WebSearchAllow {
1270 t.Fatalf("spawned policy = %v, want allow", spawned.WebSearchPolicy)
1271 }
1272
1273 metaBytes, err := os.ReadFile(filepath.Join(root, "agents", spawned.ID, "meta.json"))
1274 if err != nil {
1275 t.Fatalf("read metadata: %v", err)
1276 }
1277 var meta agentMeta
1278 if err := json.Unmarshal(metaBytes, &meta); err != nil {
1279 t.Fatalf("decode metadata: %v", err)
1280 }
1281 if meta.WebSearchPolicy != WebSearchAllow {
1282 t.Fatalf("metadata policy = %v, want allow", meta.WebSearchPolicy)
1283 }
1284
1285 second := newSupervisor(WebSearchDeny)
1286 t.Cleanup(second.StopAll)
1287 if loaded, errs := second.Reload(); loaded != 1 || len(errs) != 0 {
1288 t.Fatalf("reload loaded=%d errs=%v; want one clean load", loaded, errs)
1289 }
1290 reloaded := second.Get(spawned.ID)
1291 if reloaded == nil {
1292 t.Fatal("reloaded agent missing")
1293 }
1294 if reloaded.WebSearchPolicy != WebSearchAllow {
1295 t.Fatalf("reloaded policy = %v, want allow", reloaded.WebSearchPolicy)
1296 }
1297
1298 resumed, err := second.ResumeSession(context.Background(), spawned.ID)
1299 if err != nil {
1300 t.Fatalf("resume: %v", err)
1301 }
1302 if resumed.WebSearchPolicy != WebSearchAllow {
1303 t.Fatalf("resumed policy = %v, want allow", resumed.WebSearchPolicy)
1304 }
1305 args := defaultChildArgs("/zut", resumed, "/state/session.json", "/state/inbox.sock")
1306 idx := indexOf(args, "--web-search-policy")
1307 if idx < 0 || safeAt(args, idx+1) != "allow" {
1308 t.Fatalf("resumed child argv = %v, want explicit allow", args)
1309 }
1310 resumed.Wait()
1311}
1312
1313func snapshotIDs(ss []AgentSnapshot) []string {
1314 out := make([]string, len(ss))
1315 for i, s := range ss {
1316 out[i] = s.ID
1317 }
1318 return out
1319}