package opencode import ( "fmt" "sort" "git.a-wan.net/alan/pipelines/internal/protocol" ) // ShellSnapshot records changes while an authoritative read is in flight. Its // owner serializes access. Unknown exits may be recorded, but can only remove an // id: they never establish ownership. Overflow rejects the snapshot, not events. type ShellSnapshot struct { changes map[string]protocol.ChatShell bytes int overflow bool } const chatShellIdentityLimit = 256 func (s *ShellSnapshot) Record(shell *protocol.ChatShell) { if s == nil || shell == nil || shell.ID == "" || s.overflow { return } if s.changes == nil { s.changes = make(map[string]protocol.ChatShell) } old := s.changes[shell.ID] n := s.bytes - len(old.ID) - len(old.Command) + len(shell.ID) + len(shell.Command) if n > MaxResponse || (old.ID == "" && len(s.changes) >= chatShellIdentityLimit) { s.overflow = true return } // A terminal event wins even if a duplicate create is delivered later. if old.ID != "" && old.Status != protocol.ChatShellRunning { return } s.changes[shell.ID] = *shell s.bytes = n } func (s *ShellSnapshot) Merge(shells []protocol.ChatShell) ([]protocol.ChatShell, error) { if s.overflow { return nil, fmt.Errorf("shell reconciliation capacity exceeded") } byID := make(map[string]protocol.ChatShell) for _, shell := range shells { if shell.ID != "" && shell.Status == protocol.ChatShellRunning { byID[shell.ID] = shell } } for id, shell := range s.changes { if shell.Status == protocol.ChatShellRunning { byID[id] = shell } else { delete(byID, id) } } if len(byID) > chatShellIdentityLimit { return nil, fmt.Errorf("shell reconciliation capacity exceeded") } ids := make([]string, 0, len(byID)) for id := range byID { ids = append(ids, id) } sort.Strings(ids) out := make([]protocol.ChatShell, 0, len(ids)) for _, id := range ids { out = append(out, byID[id]) } return out, nil }