Files
pipelines/internal/opencode/chat_shell_snapshot.go
T
alan e9d902213e Preserve background shell visibility across readback races
Reconcile authoritative shell snapshots with bounded lifecycle journals so concurrent exits and creates cannot be overwritten, coalesce observation setup, and retain verified ownership across reconnects. Add deterministic reconciliation and cancellation regressions plus stable limited-visibility handling.\n\nChecked packaged templates and authoring skill references: none need updating. The task-owned docs note records the stale shared chat documentation for docs-fold; shared documentation was not edited.
2026-10-18 12:54:36 +01:00

73 lines
1.9 KiB
Go

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
}