xonecas.io
60255
Zn

Zoea-Nova / commit cac04bc

docs: add comprehensive goroutine cleanup fixes plan

- Phase 1: Fix event bus cleanup order (critical deadlock)
- Phase 2: Add WaitGroup for mysis goroutine tracking
- Phase 3: Add graceful shutdown timeout
- Phase 4: Close HTTP clients properly
- Phase 5: Close log file handle
- Phase 6: Remove redundant cleanup calls
- Phase 7: Add goroutine leak detection logging
- Phase 8: Testing and verification

Total: 8 phases, ~105 minutes estimated
Reference: GOROUTINE_CLEANUP_ANALYSIS.md

xonecas2026-02-06 cac04bc37d5d9233269f520ae5028ac8644f51e6 parent 046e107

1 file changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

documentation/plans/2026-02-06-goroutine-cleanup-fixes.md+1154−0
@@ -0,0 +1,1154 @@
1+# Goroutine Cleanup Fixes Implementation Plan
2+
3+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4+
5+**Goal:** Fix all goroutine cleanup issues to ensure clean application shutdown without hangs
6+
7+**Architecture:** Implement proper cleanup order with quit callbacks, close event bus before TUI exit, add WaitGroup tracking for myses, ensure all resources cleaned up gracefully
8+
9+**Tech Stack:** Go 1.22+, Bubble Tea TUI, context-based cancellation, sync.WaitGroup
10+
11+**Reference:** `GOROUTINE_CLEANUP_ANALYSIS.md` - Complete analysis of issues
12+
13+---
14+
15+## Phase 1: Fix Event Bus Cleanup Order (Critical)
16+
17+**Root Cause:** Event bus is closed AFTER program.Run() returns, but TUI event listener blocks on channel waiting for events. This creates a deadlock.
18+
19+**Solution:** Add onQuit callback to TUI that closes bus BEFORE tea.Quit is processed.
20+
21+---
22+
23+### Task 1.1: Verify onQuit callback already exists
24+
25+**Files:**
26+- Check: `internal/tui/app.go`
27+
28+**Step 1: Check if SetOnQuit already exists**
29+
30+Run: `grep -n "SetOnQuit\|onQuit" internal/tui/app.go`
31+Expected: Should find existing onQuit field and SetOnQuit method
32+
33+**Step 2: Check current usage in main.go**
34+
35+Run: `grep -n "SetOnQuit\|onQuit" cmd/zoea/main.go`
36+Expected: See if it's already being used
37+
38+**Step 3: Document findings**
39+
40+Note: Based on CLEANUP_ORDER_ANALYSIS.md, onQuit callback already exists at app.go:70 and SetOnQuit at app.go:116-118.
41+
42+---
43+
44+### Task 1.2: Update onQuit callback to close event bus
45+
46+**Files:**
47+- Modify: `cmd/zoea/main.go:145-155`
48+
49+**Step 1: Update model setup to set onQuit callback**
50+
51+**Current code (main.go:145-155):**
52+```go
53+eventCh := bus.Subscribe()
54+model := tui.New(commander, s, eventCh)
55+program := tea.NewProgram(model, tea.WithAltScreen())
56+
57+go func() {
58+ <-sigCh
59+ log.Info().Msg("Received shutdown signal")
60+ commander.StopAll()
61+ program.Quit()
62+}()
63+```
64+
65+**New code:**
66+```go
67+eventCh := bus.Subscribe()
68+model := tui.New(commander, s, eventCh)
69+
70+// Set quit callback to close bus before TUI exits
71+model.SetOnQuit(func() {
72+ bus.Close() // Unblocks event listener
73+})
74+
75+program := tea.NewProgram(model, tea.WithAltScreen())
76+
77+go func() {
78+ <-sigCh
79+ log.Info().Msg("Received shutdown signal")
80+ commander.StopAll()
81+ bus.Close() // Close bus to unblock TUI
82+ program.Quit()
83+}()
84+```
85+
86+**Step 2: Update cleanup after program.Run()**
87+
88+**Current code (main.go:166-172):**
89+```go
90+commander.StopAll()
91+
92+if err := s.ReleaseAllAccounts(); err != nil {
93+ log.Warn().Err(err).Msg("Failed to release accounts on shutdown")
94+}
95+
96+log.Info().Msg("Zoea Nova shutdown complete")
97+```
98+
99+**New code:**
100+```go
101+// Stop all myses (redundant but safe if signal handler didn't run)
102+commander.StopAll()
103+
104+// Close bus (idempotent if already closed by onQuit or signal handler)
105+bus.Close()
106+
107+// Release accounts
108+if err := s.ReleaseAllAccounts(); err != nil {
109+ log.Warn().Err(err).Msg("Failed to release accounts on shutdown")
110+}
111+
112+log.Info().Msg("Zoea Nova shutdown complete")
113+```
114+
115+**Step 3: Remove deferred bus.Close()**
116+
117+**Current code (main.go:81):**
118+```go
119+defer bus.Close()
120+defer s.Close()
121+```
122+
123+**New code:**
124+```go
125+// Event bus closed explicitly in shutdown sequence (onQuit callback or signal handler)
126+// Store closed last after all operations complete
127+defer s.Close()
128+```
129+
130+**Step 4: Build and verify**
131+
132+Run: `make build`
133+Expected: Clean build with no errors
134+
135+**Step 5: Test normal exit**
136+
137+Run: `./bin/zoea --offline` then press 'q'
138+Expected: Exits immediately (< 1 second)
139+
140+**Step 6: Test signal exit**
141+
142+Run: `./bin/zoea --offline` in background, then `pkill -TERM zoea`
143+Expected: Exits cleanly within 1 second
144+
145+**Step 7: Commit**
146+
147+```bash
148+git add cmd/zoea/main.go
149+git commit -m "fix: close event bus before TUI exit to prevent hang
150+
151+- Add onQuit callback that closes bus before tea.Quit processes
152+- Close bus in signal handler before calling program.Quit()
153+- Remove deferred bus.Close() (now explicit in shutdown sequence)
154+- Ensures listenForEvents() unblocks cleanly on exit
155+
156+Fixes deadlock where TUI event listener blocks on channel read
157+while waiting for bus.Close() that only runs after program.Run()
158+returns."
159+```
160+
161+---
162+
163+## Phase 2: Add WaitGroup for Mysis Goroutines
164+
165+**Root Cause:** No way to wait for all mysis goroutines to complete before proceeding with cleanup.
166+
167+**Solution:** Add sync.WaitGroup to Commander to track running myses.
168+
169+---
170+
171+### Task 2.1: Add WaitGroup to Commander
172+
173+**Files:**
174+- Modify: `internal/core/commander.go:18-30`
175+
176+**Step 1: Add WaitGroup field to Commander struct**
177+
178+**Current code (commander.go:18-30):**
179+```go
180+type Commander struct {
181+ store *store.Store
182+ mcpClient MCPClient
183+ toolRegistry *ToolRegistry
184+ providerFactory map[string]ProviderFactory
185+ eventBus *EventBus
186+ config *config.Config
187+
188+ mu sync.RWMutex
189+ myses map[string]*Mysis
190+
191+ aggregateTick atomic.Int64
192+}
193+```
194+
195+**New code:**
196+```go
197+type Commander struct {
198+ store *store.Store
199+ mcpClient MCPClient
200+ toolRegistry *ToolRegistry
201+ providerFactory map[string]ProviderFactory
202+ eventBus *EventBus
203+ config *config.Config
204+
205+ mu sync.RWMutex
206+ myses map[string]*Mysis
207+ wg sync.WaitGroup // Tracks running mysis goroutines
208+
209+ aggregateTick atomic.Int64
210+}
211+```
212+
213+**Step 2: Increment WaitGroup in StartMysis**
214+
215+**Location:** `internal/core/commander.go` (find StartMysis method)
216+
217+Run: `grep -n "func (c \*Commander) StartMysis" internal/core/commander.go`
218+
219+**Current code (commander.go:~120-140):**
220+```go
221+func (c *Commander) StartMysis(id string) error {
222+ // ...existing validation...
223+
224+ if err := mysis.Start(); err != nil {
225+ return fmt.Errorf("start mysis: %w", err)
226+ }
227+
228+ return nil
229+}
230+```
231+
232+**New code:**
233+```go
234+func (c *Commander) StartMysis(id string) error {
235+ // ...existing validation...
236+
237+ c.wg.Add(1) // Track this goroutine
238+ if err := mysis.Start(); err != nil {
239+ c.wg.Done() // Failed to start, don't track
240+ return fmt.Errorf("start mysis: %w", err)
241+ }
242+
243+ return nil
244+}
245+```
246+
247+**Step 3: Decrement WaitGroup in Mysis.run() when exiting**
248+
249+**Files:**
250+- Modify: `internal/core/mysis.go:913-944`
251+
252+**Current code:**
253+```go
254+func (m *Mysis) run(ctx context.Context) {
255+ a := m
256+ ticker := time.NewTicker(constants.IdleNudgeInterval)
257+ defer ticker.Stop()
258+
259+ for {
260+ select {
261+ case <-ctx.Done():
262+ return
263+ case <-ticker.C:
264+ // ...
265+ case <-a.nudgeCh:
266+ // ...
267+ }
268+ }
269+}
270+```
271+
272+**New code:**
273+```go
274+func (m *Mysis) run(ctx context.Context) {
275+ a := m
276+ defer a.commander.wg.Done() // Signal goroutine completion
277+
278+ ticker := time.NewTicker(constants.IdleNudgeInterval)
279+ defer ticker.Stop()
280+
281+ for {
282+ select {
283+ case <-ctx.Done():
284+ return
285+ case <-ticker.C:
286+ // ...
287+ case <-a.nudgeCh:
288+ // ...
289+ }
290+ }
291+}
292+```
293+
294+**Note:** Mysis needs reference to Commander. Check if it already exists.
295+
296+Run: `grep -n "commander.*Commander" internal/core/mysis.go | head -5`
297+
298+**Step 4: Add Commander reference to Mysis if missing**
299+
300+Check current Mysis struct:
301+
302+Run: `grep -A 30 "^type Mysis struct" internal/core/mysis.go`
303+
304+If commander field doesn't exist, add it:
305+
306+```go
307+type Mysis struct {
308+ // ...existing fields...
309+ commander *Commander // Reference to parent commander for WaitGroup
310+}
311+```
312+
313+Update NewMysis to accept commander parameter.
314+
315+**Step 5: Wait for all goroutines in StopAll**
316+
317+**Files:**
318+- Modify: `internal/core/commander.go:354-368`
319+
320+**Current code:**
321+```go
322+func (c *Commander) StopAll() {
323+ c.mu.RLock()
324+ myses := make([]*Mysis, 0)
325+ for _, m := range c.myses {
326+ myses = append(myses, m)
327+ }
328+ c.mu.RUnlock()
329+
330+ for _, m := range myses {
331+ if m.State() == MysisStateRunning {
332+ m.Stop()
333+ }
334+ }
335+}
336+```
337+
338+**New code:**
339+```go
340+func (c *Commander) StopAll() {
341+ c.mu.RLock()
342+ myses := make([]*Mysis, 0)
343+ for _, m := range c.myses {
344+ myses = append(myses, m)
345+ }
346+ c.mu.RUnlock()
347+
348+ // Stop all running myses
349+ for _, m := range myses {
350+ if m.State() == MysisStateRunning {
351+ m.Stop()
352+ }
353+ }
354+
355+ // Wait for all mysis goroutines to complete
356+ c.wg.Wait()
357+}
358+```
359+
360+**Step 6: Build and verify**
361+
362+Run: `make build`
363+Expected: Clean build
364+
365+**Step 7: Test with running myses**
366+
367+Run: `./bin/zoea --offline`
368+Steps: Create 2 myses, start them, wait 2 seconds, press 'q'
369+Expected: Exits cleanly within 2 seconds
370+
371+**Step 8: Commit**
372+
373+```bash
374+git add internal/core/commander.go internal/core/mysis.go
375+git commit -m "feat: add WaitGroup to track mysis goroutines
376+
377+- Add sync.WaitGroup to Commander struct
378+- Increment WaitGroup when starting mysis
379+- Decrement WaitGroup when mysis.run() exits
380+- Wait for all goroutines in StopAll()
381+
382+Ensures all mysis processing loops complete before cleanup
383+proceeds. Prevents race conditions during shutdown."
384+```
385+
386+---
387+
388+## Phase 3: Add Graceful Shutdown Timeout
389+
390+**Root Cause:** If a mysis hangs during Stop(), the entire shutdown hangs forever.
391+
392+**Solution:** Add timeout to StopAll() to force exit if myses don't stop in reasonable time.
393+
394+---
395+
396+### Task 3.1: Add timeout to StopAll
397+
398+**Files:**
399+- Modify: `internal/core/commander.go:354-368`
400+
401+**Step 1: Import time package if not already imported**
402+
403+Check: `grep "^import" -A 10 internal/core/commander.go | grep time`
404+
405+**Step 2: Implement timeout in StopAll**
406+
407+**Current code:**
408+```go
409+func (c *Commander) StopAll() {
410+ // ... stop all myses ...
411+ c.wg.Wait()
412+}
413+```
414+
415+**New code:**
416+```go
417+func (c *Commander) StopAll() {
418+ c.mu.RLock()
419+ myses := make([]*Mysis, 0)
420+ for _, m := range c.myses {
421+ myses = append(myses, m)
422+ }
423+ c.mu.RUnlock()
424+
425+ // Stop all running myses
426+ for _, m := range myses {
427+ if m.State() == MysisStateRunning {
428+ m.Stop()
429+ }
430+ }
431+
432+ // Wait for all mysis goroutines with timeout
433+ done := make(chan struct{})
434+ go func() {
435+ c.wg.Wait()
436+ close(done)
437+ }()
438+
439+ select {
440+ case <-done:
441+ // All goroutines completed
442+ log.Info().Int("count", len(myses)).Msg("All myses stopped")
443+ case <-time.After(5 * time.Second):
444+ // Timeout - force exit
445+ log.Warn().Int("count", len(myses)).Msg("StopAll timeout - forcing shutdown")
446+ }
447+}
448+```
449+
450+**Step 3: Add log import if needed**
451+
452+Check: `grep "github.com/rs/zerolog/log" internal/core/commander.go`
453+
454+If not found, add to imports:
455+```go
456+import (
457+ // ...existing imports...
458+ "github.com/rs/zerolog/log"
459+)
460+```
461+
462+**Step 4: Build and verify**
463+
464+Run: `make build`
465+Expected: Clean build
466+
467+**Step 5: Test normal shutdown**
468+
469+Run: `./bin/zoea --offline`, create myses, press 'q'
470+Expected: Log shows "All myses stopped" with count
471+
472+**Step 6: Commit**
473+
474+```bash
475+git add internal/core/commander.go
476+git commit -m "feat: add graceful shutdown timeout to StopAll
477+
478+- Add 5-second timeout for StopAll() to complete
479+- Log completion with mysis count
480+- Log warning if timeout occurs (force shutdown)
481+
482+Prevents infinite hang if a mysis fails to stop cleanly.
483+Application will exit after 5 seconds regardless of mysis state."
484+```
485+
486+---
487+
488+## Phase 4: Close HTTP Clients Properly
489+
490+**Root Cause:** Provider and MCP HTTP clients are never closed, leaving idle connections open.
491+
492+**Solution:** Add Close() methods and call them during shutdown.
493+
494+---
495+
496+### Task 4.1: Add Close() to Provider interface
497+
498+**Files:**
499+- Modify: `internal/provider/provider.go:42-55`
500+
501+**Step 1: Add Close() to Provider interface**
502+
503+**Current code:**
504+```go
505+type Provider interface {
506+ Name() string
507+ Chat(ctx context.Context, messages []Message) (string, error)
508+ ChatWithTools(ctx context.Context, messages []Message, tools []Tool) (*ChatResponse, error)
509+ Stream(ctx context.Context, messages []Message) (<-chan StreamChunk, error)
510+}
511+```
512+
513+**New code:**
514+```go
515+type Provider interface {
516+ Name() string
517+ Chat(ctx context.Context, messages []Message) (string, error)
518+ ChatWithTools(ctx context.Context, messages []Message, tools []Tool) (*ChatResponse, error)
519+ Stream(ctx context.Context, messages []Message) (<-chan StreamChunk, error)
520+ Close() error
521+}
522+```
523+
524+**Step 2: Verify implementations already have Close()**
525+
526+Check: Based on HTTP_CLIENT_CLEANUP_IMPLEMENTATION.md:
527+- `internal/provider/ollama.go:360-366` - Already has Close()
528+- `internal/provider/opencode.go:228-234` - Already has Close()
529+- `internal/provider/mock.go` - Check if needs Close()
530+
531+Run: `grep -n "func.*Close()" internal/provider/*.go`
532+
533+**Step 3: Add Close() to MockProvider if missing**
534+
535+**Files:**
536+- Modify: `internal/provider/mock.go`
537+
538+Check if Close exists:
539+Run: `grep -n "Close" internal/provider/mock.go`
540+
541+If missing, add:
542+```go
543+// Close is a no-op for mock provider (no resources to clean up)
544+func (p *MockProvider) Close() error {
545+ return nil
546+}
547+```
548+
549+**Step 4: Build and verify**
550+
551+Run: `make build`
552+Expected: Clean build
553+
554+**Step 5: Commit**
555+
556+```bash
557+git add internal/provider/
558+git commit -m "feat: add Close() to Provider interface
559+
560+- Add Close() method to Provider interface
561+- Ensures all providers implement cleanup
562+- MockProvider Close() is no-op (no resources)
563+
564+Enables polymorphic cleanup of provider HTTP clients."
565+```
566+
567+---
568+
569+### Task 4.2: Call provider.Close() in Mysis.Stop()
570+
571+**Files:**
572+- Modify: `internal/core/mysis.go:224-264`
573+
574+**Step 1: Add provider cleanup to Stop()**
575+
576+**Current code (mysis.go:~258-264):**
577+```go
578+func (m *Mysis) Stop() error {
579+ // ... existing stop logic ...
580+
581+ a.releaseCurrentAccount()
582+ return nil
583+}
584+```
585+
586+**New code:**
587+```go
588+func (m *Mysis) Stop() error {
589+ // ... existing stop logic ...
590+
591+ a.releaseCurrentAccount()
592+
593+ // Close provider HTTP client
594+ if a.provider != nil {
595+ if err := a.provider.Close(); err != nil {
596+ log.Warn().Err(err).Str("mysis", a.name).Msg("Failed to close provider")
597+ }
598+ }
599+
600+ return nil
601+}
602+```
603+
604+**Step 2: Add log import if needed**
605+
606+Check: `grep "github.com/rs/zerolog/log" internal/core/mysis.go`
607+
608+**Step 3: Build and verify**
609+
610+Run: `make build`
611+Expected: Clean build
612+
613+**Step 4: Test provider cleanup**
614+
615+Run: `./bin/zoea --offline`, create mysis, start it, stop it with 's'
616+Check logs for any errors
617+Expected: No errors, clean stop
618+
619+**Step 5: Commit**
620+
621+```bash
622+git add internal/core/mysis.go
623+git commit -m "feat: close provider HTTP client in Mysis.Stop()
624+
625+- Call provider.Close() after releasing account
626+- Log warning if close fails
627+- Prevents idle HTTP connection leaks
628+
629+Each mysis now properly cleans up its provider resources
630+when stopped."
631+```
632+
633+---
634+
635+### Task 4.3: Add Close() to MCP Client and call it
636+
637+**Files:**
638+- Verify: `internal/mcp/client.go:320-326` (already has Close() per HTTP_CLIENT_CLEANUP_IMPLEMENTATION.md)
639+- Modify: `cmd/zoea/main.go` cleanup sequence
640+
641+**Step 1: Verify MCP Client has Close()**
642+
643+Run: `grep -n "func.*Close" internal/mcp/client.go`
644+Expected: Should find Close() method at line ~320
645+
646+**Step 2: Add MCP client cleanup to main.go**
647+
648+**Location:** After `commander.StopAll()` in main.go
649+
650+**Current code (main.go:~166-172):**
651+```go
652+commander.StopAll()
653+bus.Close()
654+
655+if err := s.ReleaseAllAccounts(); err != nil {
656+ log.Warn().Err(err).Msg("Failed to release accounts on shutdown")
657+}
658+```
659+
660+**New code:**
661+```go
662+commander.StopAll()
663+bus.Close()
664+
665+// Close MCP client if initialized
666+if mcpProxy != nil {
667+ if client, ok := mcpProxy.Upstream().(*mcp.Client); ok {
668+ if err := client.Close(); err != nil {
669+ log.Warn().Err(err).Msg("Failed to close MCP client")
670+ }
671+ }
672+}
673+
674+if err := s.ReleaseAllAccounts(); err != nil {
675+ log.Warn().Err(err).Msg("Failed to release accounts on shutdown")
676+}
677+```
678+
679+**Note:** Check if mcpProxy.Upstream() method exists. May need to adjust based on actual API.
680+
681+Run: `grep -n "Upstream\|upstream" internal/mcp/proxy.go | head -10`
682+
683+**Step 3: Build and verify**
684+
685+Run: `make build`
686+Expected: Clean build (or error if Upstream() doesn't exist - adjust code)
687+
688+**Step 4: Commit**
689+
690+```bash
691+git add cmd/zoea/main.go
692+git commit -m "feat: close MCP client on shutdown
693+
694+- Call client.Close() after stopping myses
695+- Closes idle HTTP connections to SpaceMolt server
696+- Prevents connection leaks
697+
698+MCP client shared by all myses via proxy, so closed once
699+after all myses have stopped."
700+```
701+
702+---
703+
704+## Phase 5: Close Log File Handle
705+
706+**Root Cause:** Log file handle opened in initLogging() is never closed, risking buffered write loss.
707+
708+**Solution:** Track file handle and close it on exit.
709+
710+---
711+
712+### Task 5.1: Track and close log file handle
713+
714+**Files:**
715+- Modify: `cmd/zoea/main.go:183-210` (initLogging function)
716+- Modify: `cmd/zoea/main.go:60-90` (main function)
717+
718+**Step 1: Make logFile a package-level variable**
719+
720+**Current code (main.go:183):**
721+```go
722+func initLogging(debug bool) error {
723+ // ...
724+ logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
725+ // ...
726+}
727+```
728+
729+**Add at top of main.go (after package declaration):**
730+```go
731+package main
732+
733+import (
734+ // ...
735+)
736+
737+var logFile *os.File // Package-level to allow cleanup
738+```
739+
740+**Step 2: Update initLogging to use package variable**
741+
742+**New code:**
743+```go
744+func initLogging(debug bool) error {
745+ // ...
746+ var err error
747+ logFile, err = os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
748+ if err != nil {
749+ return fmt.Errorf("open log file: %w", err)
750+ }
751+
752+ log.Logger = zerolog.New(logFile).With().Timestamp().Logger()
753+ return nil
754+}
755+```
756+
757+**Step 3: Add deferred close in main()**
758+
759+**Current code (main.go:~76-81):**
760+```go
761+defer s.Close()
762+```
763+
764+**New code:**
765+```go
766+// Close log file last (after all logging complete)
767+defer func() {
768+ if logFile != nil {
769+ logFile.Close()
770+ }
771+}()
772+
773+defer s.Close()
774+```
775+
776+**Step 4: Build and verify**
777+
778+Run: `make build`
779+Expected: Clean build
780+
781+**Step 5: Test log file closes**
782+
783+Run: `./bin/zoea --offline`, press 'q' immediately
784+Check: `lsof | grep zoea.log` (should be empty after exit)
785+Expected: No open file handles to zoea.log
786+
787+**Step 6: Commit**
788+
789+```bash
790+git add cmd/zoea/main.go
791+git commit -m "fix: close log file handle on exit
792+
793+- Make logFile package-level variable
794+- Add deferred close in main()
795+- Ensures buffered writes flush on exit
796+
797+Prevents potential data loss from unclosed log file."
798+```
799+
800+---
801+
802+## Phase 6: Remove Redundant Cleanup Calls
803+
804+**Root Cause:** Multiple redundant StopAll() and bus.Close() calls create confusion.
805+
806+**Solution:** Clean up redundant calls now that proper sequence is established.
807+
808+---
809+
810+### Task 6.1: Remove redundant StopAll in signal handler
811+
812+**Files:**
813+- Modify: `cmd/zoea/main.go:152-158`
814+
815+**Step 1: Check current signal handler**
816+
817+Run: `grep -A 10 "go func()" cmd/zoea/main.go | grep -A 8 sigCh`
818+
819+**Current code:**
820+```go
821+go func() {
822+ <-sigCh
823+ log.Info().Msg("Received shutdown signal")
824+ commander.StopAll() // ← Will be called again after program.Run()
825+ bus.Close()
826+ program.Quit()
827+}()
828+```
829+
830+**New code:**
831+```go
832+go func() {
833+ <-sigCh
834+ log.Info().Msg("Received shutdown signal")
835+ // Don't call StopAll here - let main cleanup handle it
836+ // This avoids double-stop which wastes time
837+ bus.Close() // Close bus to unblock TUI
838+ program.Quit()
839+}()
840+```
841+
842+**Rationale:** StopAll() is called after program.Run() returns, so calling it in signal handler is redundant and wastes time waiting for myses to stop twice.
843+
844+**Step 2: Build and verify**
845+
846+Run: `make build`
847+Expected: Clean build
848+
849+**Step 3: Test signal exit**
850+
851+Run: `./bin/zoea --offline` with myses running, send SIGTERM
852+Expected: Exits cleanly, StopAll only called once (check logs)
853+
854+**Step 4: Commit**
855+
856+```bash
857+git add cmd/zoea/main.go
858+git commit -m "refactor: remove redundant StopAll in signal handler
859+
860+- StopAll already called after program.Run() returns
861+- Calling it in signal handler is wasteful (stops twice)
862+- Simplified signal handler to only close bus and quit TUI
863+
864+Improves shutdown speed by avoiding redundant mysis stops."
865+```
866+
867+---
868+
869+## Phase 7: Add Goroutine Leak Detection (Optional)
870+
871+**Root Cause:** No way to detect if goroutines are leaking during development/testing.
872+
873+**Solution:** Add runtime goroutine count logging at startup and shutdown.
874+
875+---
876+
877+### Task 7.1: Add goroutine count logging
878+
879+**Files:**
880+- Modify: `cmd/zoea/main.go` (main function)
881+
882+**Step 1: Log goroutine count at startup**
883+
884+**Location:** After all initialization (main.go:~145)
885+
886+**Add:**
887+```go
888+log.Info().Int("goroutines", runtime.NumGoroutine()).Msg("Application started")
889+```
890+
891+**Step 2: Log goroutine count at shutdown**
892+
893+**Location:** After StopAll completes (main.go:~169)
894+
895+**Add:**
896+```go
897+commander.StopAll()
898+bus.Close()
899+
900+// Log goroutine count for leak detection
901+log.Info().Int("goroutines", runtime.NumGoroutine()).Msg("Shutdown in progress")
902+
903+// ... rest of cleanup ...
904+
905+log.Info().Int("goroutines", runtime.NumGoroutine()).Msg("Zoea Nova shutdown complete")
906+```
907+
908+**Step 3: Add runtime import**
909+
910+Check: `grep "runtime" cmd/zoea/main.go`
911+
912+If not found, add to imports:
913+```go
914+import (
915+ // ...
916+ "runtime"
917+)
918+```
919+
920+**Step 4: Build and test**
921+
922+Run: `make build && ./bin/zoea --offline`
923+Create myses, start them, wait, then exit
924+Check logs: Compare goroutine counts at startup vs shutdown
925+Expected: Counts should be similar (within ~5 goroutines)
926+
927+**Step 5: Commit**
928+
929+```bash
930+git add cmd/zoea/main.go
931+git commit -m "feat: add goroutine leak detection logging
932+
933+- Log goroutine count at startup
934+- Log count during shutdown
935+- Log final count at exit
936+
937+Enables detection of goroutine leaks during development
938+and testing. Baseline count should be similar at start/end."
939+```
940+
941+---
942+
943+## Phase 8: Testing and Verification
944+
945+### Task 8.1: Create shutdown integration test
946+
947+**Files:**
948+- Create: `internal/integration/shutdown_test.go`
949+
950+**Step 1: Write shutdown test**
951+
952+```go
953+package integration
954+
955+import (
956+ "os"
957+ "os/exec"
958+ "syscall"
959+ "testing"
960+ "time"
961+)
962+
963+func TestGracefulShutdown(t *testing.T) {
964+ // Build binary
965+ buildCmd := exec.Command("go", "build", "-o", "/tmp/zoea-test", "./cmd/zoea")
966+ if err := buildCmd.Run(); err != nil {
967+ t.Fatalf("build failed: %v", err)
968+ }
969+ defer os.Remove("/tmp/zoea-test")
970+
971+ // Start application
972+ cmd := exec.Command("/tmp/zoea-test", "--offline")
973+ if err := cmd.Start(); err != nil {
974+ t.Fatalf("failed to start: %v", err)
975+ }
976+
977+ // Give it time to initialize
978+ time.Sleep(2 * time.Second)
979+
980+ // Send SIGTERM
981+ if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
982+ t.Fatalf("failed to send signal: %v", err)
983+ }
984+
985+ // Wait for exit with timeout
986+ done := make(chan error)
987+ go func() {
988+ done <- cmd.Wait()
989+ }()
990+
991+ select {
992+ case err := <-done:
993+ if err != nil {
994+ t.Logf("exit with error: %v (acceptable for SIGTERM)", err)
995+ }
996+ // Success - exited within timeout
997+ case <-time.After(10 * time.Second):
998+ cmd.Process.Kill()
999+ t.Fatal("shutdown timeout - process hung")
Cut short: this commit's diff is over 1000 lines.