diff --git a/internal/claude/chat.go b/internal/claude/chat.go index 7416a059..15b20d23 100644 --- a/internal/claude/chat.go +++ b/internal/claude/chat.go @@ -639,6 +639,9 @@ func (c *Chat) Shells(ctx context.Context, id string) ([]protocol.ChatShell, err s.enrichShellStarts() s.mu.Lock() defer s.mu.Unlock() + if p := s.proc; p != nil && p.link != nil && p.link.tasksIncomplete.Load() { + return nil, errors.New("Claude Code background task readback is incomplete: the legacy host trimmed replay without an authoritative task snapshot") + } result := []protocol.ChatShell{} for _, snapshot := range s.shells { if snapshot.shell.Status == protocol.ChatShellRunning { diff --git a/internal/claude/hosted.go b/internal/claude/hosted.go index 2052d3b2..b405c457 100644 --- a/internal/claude/hosted.go +++ b/internal/claude/hosted.go @@ -100,6 +100,8 @@ type hostLink struct { record claudehost.Record // Immutable capability of this attachment; old hosts cannot protect idle background tasks. tasksKnown bool + // A legacy host may have trimmed identities this client never observed. + tasksIncomplete atomic.Bool mu sync.Mutex conn *claudehost.Conn @@ -169,6 +171,7 @@ func (s *session) startHosted(ctx context.Context, args []string, mode string, e link := &hostLink{dir: c.hostDir, conn: conn, tasksKnown: status.Tasks != nil, record: claudehost.Record{ SessionID: s.id, HostPID: status.HostPID, ClaudePID: status.ClaudePID, Socket: paths.Socket, }} + link.tasksIncomplete.Store(status.Tasks == nil && status.Base > 0) p := newProcess(s, mode) p.link = link p.markReady() @@ -243,6 +246,7 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record) p.link = &hostLink{dir: c.hostDir, conn: conn, committed: status.Acked, tasksKnown: status.Tasks != nil, record: claudehost.Record{ SessionID: record.SessionID, HostPID: status.HostPID, ClaudePID: status.ClaudePID, Socket: record.Socket, }} + p.link.tasksIncomplete.Store(status.Tasks == nil && status.Base > 0) p.stderr.WriteString(status.Stderr) p.models, p.account, p.appliedModel = models, account, status.Model plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true, tasks: status.Tasks} @@ -346,6 +350,9 @@ func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) { catchUpReady := func() { if !tasksReconciled { s.reconcileHostTasks(plan.tasks) + if plan.tasks != nil { + p.link.tasksIncomplete.Store(false) + } tasksReconciled = true } p.markReady() @@ -501,6 +508,9 @@ func (p *process) hostLost(conn *claudehost.Conn, cause error) (*claudehost.Conn } next, status, err := claudehost.Attach(link.record.Socket, committed, hostAttachTimeout) if err == nil { + if status.Tasks == nil && status.Base > committed { + link.tasksIncomplete.Store(true) + } link.mu.Lock() link.conn = next link.mu.Unlock() diff --git a/internal/claude/hosted_completeness_test.go b/internal/claude/hosted_completeness_test.go new file mode 100644 index 00000000..9ab3e938 --- /dev/null +++ b/internal/claude/hosted_completeness_test.go @@ -0,0 +1,141 @@ +package claude + +import ( + "context" + "encoding/json" + "net" + "os" + "path/filepath" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/claudehost" +) + +func taskReadbackFixture(t *testing.T, serve func(net.Listener, <-chan struct{})) (*Chat, *process) { + t.Helper() + base, err := os.MkdirTemp("/tmp", "pcr") + if err != nil { + t.Fatal(err) + } + socket := filepath.Join(base, "host.sock") + listener, err := net.Listen("unix", socket) + if err != nil { + os.RemoveAll(base) + t.Fatal(err) + } + stop := make(chan struct{}) + done := make(chan struct{}) + go func() { defer close(done); serve(listener, stop) }() + chat := newChat(context.Background()) + p, conn, plan := chat.connectHost(claudehost.Record{SessionID: "completeness-session", Socket: socket}) + if p == nil { + close(stop) + listener.Close() + os.RemoveAll(base) + chat.Close() + t.Fatal("readback fixture did not attach") + } + s := p.session + s.mu.Lock() + s.proc = p + s.mu.Unlock() + go p.readHost(conn, plan) + t.Cleanup(func() { + p.detach() + close(stop) + listener.Close() + <-done + chat.Close() + os.RemoveAll(base) + }) + return chat, p +} + +func serveTaskReadback(conn net.Conn, base, end int64, tasks *[]claudehost.Task) error { + var attach claudehost.Frame + if err := json.NewDecoder(conn).Decode(&attach); err != nil { + return err + } + out := json.NewEncoder(conn) + if err := out.Encode(claudehost.Frame{Op: claudehost.OpStatus, Status: &claudehost.Status{SessionID: "completeness-session", Base: base, Acked: base, End: end, Init: json.RawMessage(`{"models":[{"value":"fixture"}]}`), Tasks: tasks}}); err != nil { + return err + } + return out.Encode(claudehost.Frame{Op: claudehost.OpOut, Offset: base, End: end, Data: json.RawMessage(`{"type":"system","subtype":"status"}`)}) +} + +func TestLegacyTaskReadbackDistinguishesTrimmedUnknownFromCompleteIdle(t *testing.T) { + empty := []claudehost.Task{} + for _, tc := range []struct { + name string + base int64 + tasks *[]claudehost.Task + unknown bool + }{ + {name: "trimmed legacy is unknown", base: 200, unknown: true}, + {name: "full legacy replay is complete", base: 0}, + {name: "new authoritative snapshot survives trim", base: 200, tasks: &empty}, + } { + t.Run(tc.name, func(t *testing.T) { + chat, _ := taskReadbackFixture(t, func(listener net.Listener, stop <-chan struct{}) { + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + if serveTaskReadback(conn, tc.base, tc.base+100, tc.tasks) != nil { + return + } + <-stop + }) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + shells, err := chat.Shells(ctx, "completeness-session") + if (err != nil) != tc.unknown || len(shells) != 0 { + t.Fatalf("incorrect authoritative-empty decision: tasks=%+v err=%v", shells, err) + } + }) + } +} + +func TestLegacyReconnectGapInvalidatesPreviouslyCompleteTaskReadback(t *testing.T) { + drop := make(chan struct{}) + chat, p := taskReadbackFixture(t, func(listener net.Listener, stop <-chan struct{}) { + first, err := listener.Accept() + if err != nil { + return + } + if serveTaskReadback(first, 0, 100, nil) != nil { + first.Close() + return + } + select { + case <-drop: + case <-stop: + first.Close() + return + } + first.Close() + second, err := listener.Accept() + if err != nil { + return + } + defer second.Close() + if serveTaskReadback(second, 300, 400, nil) != nil { + return + } + <-stop + }) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if shells, err := chat.Shells(ctx, "completeness-session"); err != nil || len(shells) != 0 { + t.Fatalf("initial full replay should be known idle: %+v %v", shells, err) + } + close(drop) + eventually(t, "legacy reconnect gap to make task readback incomplete", func() bool { + return p.link.tasksIncomplete.Load() + }) + if shells, err := chat.Shells(ctx, "completeness-session"); err == nil || len(shells) != 0 { + t.Fatalf("missing events became an authoritative empty task set: %+v %v", shells, err) + } +}