package main // What every node holds, heard as events (design 39 bus-and-switch §23, §46, B12): the agent module says // `holdings-changed` with its holdings report whole, at its start, on every change and when asked; the manager says // `holdings.asked` at every start, after its conditions are judged, and on its resync, and takes each report it hears as that // node's latest. import ( "encoding/json" "fmt" "sort" "sync" "time" ) // HoldingsChanged is the agent module's event saying what one node holds, which the manager consumes. const HoldingsChanged = "claude-code.holdings-changed" // HoldingsAsked is the manager's event asking every node to say what it holds again. const HoldingsAsked = "holdings.asked" // Heard is what every node last said it holds, by node. type Heard struct { mu sync.Mutex reports map[string]Holdings } // Take keeps one `holdings-changed` as its node's latest report. func (h *Heard) Take(body []byte) (Holdings, error) { var r Holdings if err := json.Unmarshal(body, &r); err != nil { return r, fmt.Errorf("%s is not a holdings report: %w", HoldingsChanged, err) } if r.Node == "" { return r, fmt.Errorf("%s names no node", HoldingsChanged) } h.mu.Lock() defer h.mu.Unlock() if h.reports == nil { h.reports = map[string]Holdings{} } h.reports[r.Node] = r return r, nil } // All is every node's latest report, by node's name. func (h *Heard) All() []Holdings { h.mu.Lock() all := make([]Holdings, 0, len(h.reports)) for _, r := range h.reports { all = append(all, r) } h.mu.Unlock() sort.Slice(all, func(i, j int) bool { return all[i].Node < all[j].Node }) return all } // Of is the generation node last reported applying. func (h *Heard) Of(node string) int64 { h.mu.Lock() defer h.mu.Unlock() return h.reports[node].Generation } // AskHoldings says `holdings.asked`, its time and who asks (§23). func (m *Manager) AskHoldings(by string) error { return m.Emit(HoldingsAsked, map[string]any{"at": m.Now().UTC().Format(time.RFC3339Nano), "by": by}) }