pkg/service/progress.go

package service

import (
	"fmt"
	"slices"
	"sort"
	"sync"

	"git.cafe/ezterry/ez-agent/pkg/protocol"
)

type progressEntry struct {
	owner           string
	order           uint64
	title           string
	lines           []string
	visualizerMacro string
	visualizerType  string
}

type progressOrderKey struct {
	owner    string
	updateID string
}

type leafProgress struct {
	currentTurn string
	nextOrder   uint64
	items       map[string]progressEntry
	// Positive stream iterations are scoped to owner, leaf, turn, and item.
	// Retain only ordering, not old payloads, after clear or visible no-op.
	iterations map[progressOrderKey]int64
}

type progressRegistry struct {
	mu     sync.Mutex
	leaves map[string]*leafProgress
}

func newProgressRegistry() *progressRegistry {
	return &progressRegistry{leaves: make(map[string]*leafProgress)}
}

func (o *leafOperations) currentSentTurn(leafID string) (string, error) {
	if o.resolveSentTurn != nil {
		return o.resolveSentTurn(leafID)
	}
	return o.storage.CurrentSentTurnID(leafID)
}

func cloneProgressSnapshot(state *leafProgress, includeEmpty bool) *protocol.ProgressSnapshot {
	if state == nil || (!includeEmpty && len(state.items) == 0) {
		return nil
	}
	type ordered struct {
		id string
		progressEntry
	}
	entries := make([]ordered, 0, len(state.items))
	for id, entry := range state.items {
		entry.lines = append([]string(nil), entry.lines...)
		entries = append(entries, ordered{id: id, progressEntry: entry})
	}
	sort.Slice(entries, func(i, j int) bool { return entries[i].order < entries[j].order })
	items := make([]protocol.ProgressItem, 0, len(entries))
	for _, entry := range entries {
		items = append(items, protocol.ProgressItem{
			UpdateID: entry.id, Title: entry.title, Lines: entry.lines,
			VisualizerMacro: entry.visualizerMacro, VisualizerType: entry.visualizerType,
		})
	}
	return &protocol.ProgressSnapshot{TurnID: state.currentTurn, Items: items}
}

func (o *leafOperations) progressSnapshot(leafID string, includeEmpty bool) *protocol.ProgressSnapshot {
	if o.progress == nil {
		return nil
	}
	o.progress.mu.Lock()
	defer o.progress.mu.Unlock()
	return cloneProgressSnapshot(o.progress.leaves[leafID], includeEmpty)
}

// reportProgress owns turn derivation, mutation, and canonical snapshot
// publication. ownerCurrent checks exact connection identity under the routing
// lock; macroOwned checks capability ownership. Neither callback enters leaf
// state or performs transport work.
func (o *leafOperations) reportProgress(owner string, report protocol.ReportProgress, ownerCurrent func() bool, macroOwned func(string, string) bool) error {
	if err := protocol.ValidateReportProgress(report); err != nil {
		return err
	}
	gate, ok := o.acquireGate(report.LeafID)
	if !ok {
		return fmt.Errorf("leaf not found: %s", report.LeafID)
	}
	defer o.releaseGate(report.LeafID, gate)
	current, err := o.currentSentTurn(report.LeafID)
	if err != nil {
		return fmt.Errorf("resolve current sent turn: %w", err)
	}
	changed := false
	err = func() error {
		o.progress.mu.Lock()
		defer o.progress.mu.Unlock()
		// Check after the gate wait and before mutation. Cleanup removes routing
		// before taking this mutex, so a write finishes before cleanup or is rejected.
		if !ownerCurrent() {
			return nil
		}
		state := o.progress.leaves[report.LeafID]
		if state != nil && state.currentTurn != current {
			state.items = make(map[string]progressEntry)
			state.iterations = nil
			state.currentTurn = current
			// Publish the authoritative transition even if the triggering report
			// is stale, rejected, or an otherwise redundant clear.
			changed = true
		}
		if report.TurnID != current {
			return nil
		}
		if report.VisualizerMacro != "" && !macroOwned(report.VisualizerMacro, owner) {
			return fmt.Errorf("visualizer macro %q is not a live runtime macro owned by this connection", report.VisualizerMacro)
		}
		var entry progressEntry
		var exists bool
		if state != nil {
			entry, exists = state.items[report.UpdateID]
		}
		if exists && entry.owner != owner {
			return fmt.Errorf("progress item %q is owned by another connection", report.UpdateID)
		}
		// Validate live ownership before stale/no-op handling. Callbacks need
		// not arrive in stream order; even an absent clear or identical update
		// must prevent an older positive iteration from replacing it later.
		if report.Itr > 0 {
			key := progressOrderKey{owner: owner, updateID: report.UpdateID}
			if state != nil && report.Itr <= state.iterations[key] {
				return nil
			}
			if state == nil {
				state = &leafProgress{currentTurn: current, items: make(map[string]progressEntry)}
				o.progress.leaves[report.LeafID] = state
			}
			if state.iterations == nil {
				state.iterations = make(map[progressOrderKey]int64)
			}
			state.iterations[key] = report.Itr
		}
		// Unusable iterations keep arrival-order behavior without erasing the
		// positive high-water record.
		if !report.Enabled {
			if exists {
				delete(state.items, report.UpdateID)
				changed = true
			}
			return nil
		}
		if exists && entry.title == report.Title && slices.Equal(entry.lines, report.Lines) &&
			entry.visualizerMacro == report.VisualizerMacro && entry.visualizerType == report.VisualizerType {
			return nil
		}
		if state == nil {
			state = &leafProgress{currentTurn: current, items: make(map[string]progressEntry)}
			o.progress.leaves[report.LeafID] = state
		}
		if !exists {
			state.nextOrder++
			entry.owner = owner
			entry.order = state.nextOrder
		}
		entry.title = report.Title
		entry.lines = append([]string(nil), report.Lines...)
		entry.visualizerMacro = report.VisualizerMacro
		entry.visualizerType = report.VisualizerType
		state.items[report.UpdateID] = entry
		changed = true
		return nil
	}()
	if changed && o.router != nil {
		if update, ok := o.buildSnapshotLocked(report.LeafID, ""); ok {
			o.router.enqueueLeafSnapshot(update)
		}
	}
	return err
}

// AdvanceSentTurn is called only after a turn has authoritatively become sent.
func (o *leafOperations) AdvanceSentTurn(leafID, turnID string) {
	if leafID == "" || turnID == "" {
		return
	}
	gate, ok := o.acquireGate(leafID)
	if !ok {
		return
	}
	defer o.releaseGate(leafID, gate)
	current, err := o.currentSentTurn(leafID)
	if err != nil || current != turnID {
		return
	}
	if !o.advanceProgressTurnLocked(leafID, turnID) {
		return
	}
	if o.router != nil {
		if update, ok := o.buildSnapshotLocked(leafID, ""); ok {
			o.router.enqueueLeafSnapshot(update)
		}
	}
}

// advanceProgressTurnLocked requires the leaf gate and a turn ID resolved from
// storage's current sent authority, not a queued draft or producer report. It
// changes only RAM state; the caller owns canonical snapshot publication. The
// empty ID is valid when a rewind leaves no sent turn.
func (o *leafOperations) advanceProgressTurnLocked(leafID, turnID string) bool {
	o.progress.mu.Lock()
	defer o.progress.mu.Unlock()
	state := o.progress.leaves[leafID]
	if state == nil {
		state = &leafProgress{items: make(map[string]progressEntry)}
		o.progress.leaves[leafID] = state
	}
	if state.currentTurn == turnID {
		return false
	}
	state.items = make(map[string]progressEntry)
	state.iterations = nil
	state.currentTurn = turnID
	return true
}

func (o *leafOperations) cleanupProgressOwner(owner string) {
	if o.progress == nil {
		return
	}
	var changed []string
	o.progress.mu.Lock()
	for leafID, state := range o.progress.leaves {
		removed := false
		for key := range state.iterations {
			if key.owner == owner {
				delete(state.iterations, key)
			}
		}
		for id, item := range state.items {
			if item.owner == owner {
				delete(state.items, id)
				removed = true
			}
		}
		if removed {
			changed = append(changed, leafID)
		}
	}
	o.progress.mu.Unlock()
	sort.Strings(changed)
	for _, id := range changed {
		o.PublishLeafSnapshot(id, "")
	}
}

func (o *leafOperations) dropProgressLeaf(leafID string) {
	if o.progress == nil {
		return
	}
	o.progress.mu.Lock()
	delete(o.progress.leaves, leafID)
	o.progress.mu.Unlock()
}

func (o *leafOperations) cleanupVacuumedProgress() {
	if o.progress == nil {
		return
	}
	o.progress.mu.Lock()
	ids := make([]string, 0, len(o.progress.leaves))
	for id := range o.progress.leaves {
		ids = append(ids, id)
	}
	o.progress.mu.Unlock()
	for _, id := range ids {
		if _, err := o.storage.GetLeaf(id); err != nil {
			o.dropProgressLeaf(id)
		}
	}
}

func (s *Server) handleReportProgress(c *Connection, report protocol.ReportProgress) error {
	return s.leaves.reportProgress(c.ID, report, func() bool {
		return s.isCurrentConnection(c)
	}, func(name, owner string) bool {
		return s.registry.RuntimeMacroInfo(name, owner) != nil
	})
}

// AdvanceSentTurn preserves the public SentTurnRouter API while leaf operations
// own progress transitions.
func (s *Server) AdvanceSentTurn(leafID, turnID string) {
	s.leaves.AdvanceSentTurn(leafID, turnID)
}