pkg/service/leaf_operations.go

package service

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"sync"
	"time"

	"git.cafe/ezterry/ez-agent/internal/incident"

	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/service/agent"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
	"git.cafe/ezterry/ez-agent/pkg/service/session"
)

// leafAgentDependencies are the capabilities used by a live Agent. Keeping
// these interfaces explicit lets leafOperations own Agent construction without
// acquiring a Server backpointer or connection-routing state.
type leafAgentDependencies struct {
	remoteProviders    *agent.RemoteProviders
	toolCaller         agent.ToolCaller
	toolResolver       agent.ToolResolver
	toolAborter        agent.ToolCallAborter
	pluginCaller       agent.PluginCaller
	pluginInfoResolver agent.PluginInfoResolver
	macroCaller        agent.MacroCaller
	macroInfoResolver  agent.MacroInfoResolver
	steerRouter        agent.SteerEventRouter
}

func leafRunTiming(started *time.Time) (string, *int64) {
	if started == nil {
		return "", nil
	}
	elapsed := time.Since(*started).Milliseconds()
	if elapsed < 0 {
		elapsed = 0
	}
	return started.UTC().Format(time.RFC3339Nano), &elapsed
}

func leafPresenceStateForWire(state string) string {
	if state == "closed" {
		return "unloaded"
	}
	return state
}

func leafUpdatedStateForWire(state string) string {
	if state == "closed" || state == "unloaded" {
		return "idle"
	}
	return state
}

// leafOperationRouter resolves recipients and enqueues immutable frames.
// leafOperations owns which notifications are required and their ordering.
type leafOperationRouter interface {
	SendToLeaf(leafID string, send func(*ezagentapi.Conn) error)
	enqueueLeafRewound(connID, leafID, oldTipTurnID, newTipTurnID string, replay bool, requestID string)
	enqueueLeafSnapshot(update protocol.LeafUpdated) bool
	enqueuePromptCompleted(completion agent.RunCompletion)
	shutdownSignal() <-chan struct{}
	enqueueToolSteerAccepted(connID, requestID string, accepted *protocol.SteerAccepted)
	enqueueToolSteerFailure(connID, requestID string, err error)
}

// leafOperations owns process-local coordination for durable leaves. Its mu is
// never held while entering Agent, storage, progress, or routing code.
type leafOperations struct {
	storage         *session.Storage
	runtimeMu       sync.Mutex
	runtimeUpdateMu sync.Mutex
	runtimeDirty    bool
	runtimeDone     chan struct{}
	runtimeErr      error
	audit           *serviceAudit
	deps            leafAgentDependencies
	router          leafOperationRouter

	mu                         sync.RWMutex
	agents                     map[string]*agent.Agent
	closing                    bool // guarded by mu; excludes registration after the shutdown snapshot
	admissions                 map[string]int
	pendingInputWorkers        sync.WaitGroup // Add under mu; drained after Agent close
	gates                      leafGateRegistry
	progress                   *progressRegistry
	questions                  pendingQuestionOwner
	background                 map[string]backgroundOwner // task ID -> owner; guarded by mu and leaf gates
	backgroundLost             map[string]bool
	backgroundCancelled        map[string]backgroundOwner
	backgroundInitial          map[string]*backgroundAdmission
	backgroundCallPending      func(string, string, string) (bool, string)
	backgroundInterpreter      map[string]string // nonempty for all command tasks, even unknown interpreters
	backgroundWakeConfigForCwd func(context.Context, string) (*config.Config, error)
	killBackground             func(backgroundOwner, string, string)

	activeToolCalls               func(leafID string) []protocol.ActiveToolCall
	claimToolInvocationsForLeaf   func(string) (int, func())
	cancelToolInvocationsForRoots func([]string)
	hasToolInvocations            func(string) bool
	// Test barrier after immutable abort capture while the leaf gate is held.
	beforeBackgroundAbortAdmission func()
	// Test barrier after a provider is marked lost, outside the owner mutex.
	afterBackgroundOwnerLost func()

	// Test barrier between preliminary validation and Agent.Prompt admission.
	afterPromptValidation func(requestID string)
	// Test barrier before lazy Agent registration, while activation is withheld.
	beforeAgentPublication func(leafID string, ag *agent.Agent)
	// Test barrier after the atomic shutdown registration boundary and snapshot.
	afterAgentShutdownSnapshot func()
	// Test barrier after no-Agent resolution, with the leaf gate held.
	beforeUnloadedVirtualRoot func(leafID string)
	// Test fault seam for authoritative sent-turn reads.
	resolveSentTurn func(leafID string) (string, error)
}

func newLeafOperations(storage *session.Storage, deps leafAgentDependencies, router leafOperationRouter) *leafOperations {
	o := &leafOperations{
		storage: storage, deps: deps, router: router,
		agents: make(map[string]*agent.Agent), admissions: make(map[string]int),
		progress:        newProgressRegistry(),
		questions:       emptyPendingQuestionOwner{},
		activeToolCalls: func(string) []protocol.ActiveToolCall { return nil },
	}
	return o
}

// SendToLeaf implements agent.EventRouter without exposing routing state to
// leafOperations. The server remains responsible for recipient lookup.
func (o *leafOperations) SendToLeaf(leafID string, send func(*ezagentapi.Conn) error) {
	if o.router != nil {
		o.router.SendToLeaf(leafID, send)
	}
}

// PublishLeafSnapshot implements agent.EventRouter. Agent lifecycle code names
// the state change; leafOperations captures and orders the canonical snapshot.
func (o *leafOperations) PublishLeafSnapshot(leafID, previousTipTurnID string) {
	o.publishLeafSnapshot(leafID, previousTipTurnID, func(update protocol.LeafUpdated) bool {
		if o.router == nil {
			return false
		}
		return o.router.enqueueLeafSnapshot(update)
	})
}

func (o *leafOperations) publishLeafSnapshot(leafID, previousTipTurnID string, publish func(protocol.LeafUpdated) bool) bool {
	gate, ok := o.acquireGate(leafID)
	if !ok {
		return false
	}
	var notify func()
	defer func() {
		o.releaseGate(leafID, gate)
		if notify != nil {
			notify()
		}
	}()
	if update, ok := o.buildSnapshotLocked(leafID, previousTipTurnID); ok {
		notify = o.selectLeafLifecycleLocked(leafID)
		if update.State == "aborting" {
			o.audit.emit("abort_publish", incident.Started, incident.Cancel, safeIDs(leafID, ""), false)
		}
		enqueued := publish(update)
		if update.State == "aborting" {
			outcome := incident.Continue
			if !enqueued {
				outcome = incident.Fail
			}
			o.audit.emit("abort_publish", incident.Completed, outcome, safeIDs(leafID, ""), false)
		}
		return enqueued
	}
	return false
}

func (o *leafOperations) resolvePendingQuestion(reply protocol.QuestionReply, committed func([]string), acknowledge func() error, reconciled func([]string), reject func(error) error) error {
	gate, ok := o.acquireGate(reply.LeafID)
	if !ok {
		return reject(ErrPendingQuestionNotFound)
	}
	affected, err := o.questions.ResolvePendingQuestion(reply)
	if err != nil {
		rejectErr := reject(err)
		if len(affected) != 0 {
			if update, ok := o.buildSnapshotLocked(reply.LeafID, ""); ok && o.router != nil {
				o.router.enqueueLeafSnapshot(update)
			}
		}
		o.releaseGate(reply.LeafID, gate)
		for _, leafID := range affected {
			if leafID != reply.LeafID {
				o.PublishLeafSnapshot(leafID, "")
			}
		}
		return rejectErr
	}
	committed(affected)
	ackErr := acknowledge()
	if update, ok := o.buildSnapshotLocked(reply.LeafID, ""); ok && o.router != nil {
		o.router.enqueueLeafSnapshot(update)
	}
	o.releaseGate(reply.LeafID, gate)
	// The replying leaf's gate is held until its acknowledgement and snapshot
	// are ordered, then released before any other leaf gate is acquired. Other
	// leaves receive independently captured complete snapshots after the shared
	// project decision is durable.
	for _, leafID := range affected {
		if leafID != reply.LeafID {
			o.PublishLeafSnapshot(leafID, "")
		}
	}
	reconciled(affected)
	return ackErr
}

// NotifyRunCompleted implements agent.RunNotifier.
func (o *leafOperations) NotifyRunCompleted(completion agent.RunCompletion) {
	if o.router != nil {
		o.router.enqueuePromptCompleted(completion)
	}
}

func (o *leafOperations) newAgent(leafID string, cfg *config.Config) *agent.Agent {
	ag := agent.NewAgent(
		leafID, o.storage, cfg,
		o.deps.toolCaller, o.deps.toolResolver, o.deps.toolAborter,
		o.deps.pluginCaller, o.deps.pluginInfoResolver,
		o.deps.macroCaller, o.deps.macroInfoResolver,
		o, o.deps.steerRouter, o,
	)
	ag.SetRemoteProviders(o.deps.remoteProviders)
	o.mu.RLock()
	closing := o.closing
	o.mu.RUnlock()
	if closing {
		ag.Close()
	}
	return ag
}

// registerAgent is used outside Agent lifecycle locks. Rejected provisional
// Agents must be closed before a caller can activate them.
func (o *leafOperations) registerAgent(leafID string, ag *agent.Agent) bool {
	if o.tryRegisterAgent(leafID, ag) {
		return true
	}
	ag.Close()
	return false
}

// tryRegisterAgent runs inside lazy resume's activation gate. It must not enter
// Agent code: a rejected resume returns to its caller for Close before launch.
func (o *leafOperations) tryRegisterAgent(leafID string, ag *agent.Agent) bool {
	o.mu.Lock()
	defer o.mu.Unlock()
	if o.closing {
		return false
	}
	o.agents[leafID] = ag
	o.LeafRuntimeChanged(leafID)
	return true
}

func (o *leafOperations) resolveAgent(leafID string) *agent.Agent {
	o.mu.RLock()
	ag := o.agents[leafID]
	o.mu.RUnlock()
	return ag
}

// resolveOpenAgent treats a closed reference as unloaded and removes it only
// if it is still the registered generation.
func (o *leafOperations) resolveOpenAgent(leafID string) *agent.Agent {
	ag := o.resolveAgent(leafID)
	if ag != nil && ag.State() == "closed" {
		// Closed is visible before its owned rotation finishes. Keep this
		// generation registered until ordinary Close has drained persistence.
		ag.Close()
		o.removeAgentIf(leafID, ag)
		return nil
	}
	return ag
}

func (o *leafOperations) removeAgentIf(leafID string, ag *agent.Agent) bool {
	o.mu.Lock()
	defer o.mu.Unlock()
	if o.agents[leafID] != ag {
		return false
	}
	delete(o.agents, leafID)
	o.LeafRuntimeChanged(leafID)
	return true
}

func (o *leafOperations) agentSnapshot() []*agent.Agent {
	o.mu.RLock()
	agents := make([]*agent.Agent, 0, len(o.agents))
	for _, ag := range o.agents {
		agents = append(agents, ag)
	}
	o.mu.RUnlock()
	return agents
}

func (o *leafOperations) closeAllAgents() {
	// Snapshot and close registration under one lock. A provisional generation
	// that loses this race must be rejected before it can start renewable work.
	o.mu.Lock()
	o.closing = true
	agents := make([]*agent.Agent, 0, len(o.agents))
	for _, ag := range o.agents {
		agents = append(agents, ag)
	}
	tasks := make(map[string]backgroundOwner, len(o.background))
	for id, owner := range o.background {
		tasks[id] = owner
		o.forgetBackgroundTaskLocked(id)
	}
	o.mu.Unlock()
	if o.afterAgentShutdownSnapshot != nil {
		o.afterAgentShutdownSnapshot()
	}
	for _, ag := range agents {
		ag.BeginClose()
	}
	o.cancelBackground(tasks, "shutdown")
	cancelAndDrainSubscriptionAgents(agents)
	o.pendingInputWorkers.Wait()
	if err := o.flushRuntime(); err != nil {
		slog.Error("drain leaf runtime", "error", err)
	}
}

// Keep cancellation across leaves ahead of any owned renewal drain.
func cancelAndDrainSubscriptionAgents[T interface {
	BeginClose()
	WaitSubscriptionResolutions()
}](agents []T) {
	for _, ag := range agents {
		ag.BeginClose()
	}
	// Narrow drains run together so one stalled authorization reader cannot
	// multiply the watcher deadline by the number of leaves.
	var drains sync.WaitGroup
	for _, ag := range agents {
		drains.Add(1)
		go func(ag T) { defer drains.Done(); ag.WaitSubscriptionResolutions() }(ag)
	}
	drains.Wait()
}

func (o *leafOperations) invalidateToolCache(leafID string) {
	if ag := o.resolveAgent(leafID); ag != nil {
		ag.InvalidateToolCache()
	}
}

func (o *leafOperations) invalidateAllToolCaches() {
	for _, ag := range o.agentSnapshot() {
		ag.InvalidateToolCache()
	}
}

func (o *leafOperations) acquireGate(leafID string) (*leafGate, bool) {
	return o.gates.acquire(o.storage, leafID)
}

func (o *leafOperations) releaseGate(leafID string, gate *leafGate) {
	o.gates.release(leafID, gate)
}

// reserveAdmission bridges the interval before prompt-like work makes an Agent
// observably active. The reservation is established under the leaf gate.
func (o *leafOperations) reserveAdmission(leafID string) (func(), bool) {
	release, err := o.reserveAdmissionResult(leafID)
	return release, err == nil
}

func (o *leafOperations) reserveAdmissionResult(leafID string) (func(), error) {
	if o.storage == nil {
		return nil, leafValidationError{leafID, session.ErrLeafNotFound}
	}
	gate, err := o.gates.acquireResult(context.Background(), o.storage, leafID)
	if err != nil {
		return nil, err
	}
	release, err := o.reserveAdmissionLocked(leafID)
	o.releaseGate(leafID, gate)
	return release, err
}

func (o *leafOperations) reserveAdmissionLocked(leafID string) (func(), error) {
	err := o.mutateAdmissionReservationLocked(leafID, func() (bool, error) {
		o.mu.Lock()
		defer o.mu.Unlock()
		if o.closing {
			return false, agent.ErrAgentClosed
		}
		o.admissions[leafID]++
		return true, nil
	})
	if err != nil {
		return nil, err
	}
	o.selectLeafLifecycleLocked(leafID) // reservations clear idle age, not ownership

	var once sync.Once
	return func() {
		once.Do(func() {
			gate, ok := o.acquireGate(leafID)
			_ = o.mutateAdmissionReservationLocked(leafID, func() (bool, error) {
				o.mu.Lock()
				defer o.mu.Unlock()
				if o.admissions[leafID] <= 1 {
					delete(o.admissions, leafID)
				} else {
					o.admissions[leafID]--
				}
				return o.admissions[leafID] > 0, nil
			})
			if ok {
				notify := o.selectLeafLifecycleLocked(leafID)
				if update, exists := o.buildSnapshotLocked(leafID, ""); exists && o.router != nil {
					o.router.enqueueLeafSnapshot(update)
				}
				o.releaseGate(leafID, gate)
				if notify != nil {
					notify()
				}
			}
		})
	}, nil
}

// The leaf gate excludes Agent replacement while its reservation mirror changes.
// Absent or closed Agents cannot retire model work, so their ledger can change
// directly; a later replacement reads it during lifecycle selection.
func (o *leafOperations) mutateAdmissionReservationLocked(leafID string, change func() (bool, error)) error {
	defer o.LeafRuntimeChanged(leafID)
	if ag := o.resolveAgent(leafID); ag != nil {
		if err := ag.MutateAdmissionReservation(change); !errors.Is(err, agent.ErrAgentClosed) {
			return err
		}
	}
	_, err := change()
	return err
}

// canDelete is called with the leaf gate held. Aborting remains active; a
// closed Agent is equivalent to an unloaded leaf and does not block deletion.
func (o *leafOperations) canDelete(leafID string) (bool, string) {
	o.mu.RLock()
	busyAdmission := o.admissions[leafID] > 0
	ag := o.agents[leafID]
	o.mu.RUnlock()
	if busyAdmission {
		return false, "leaf_busy"
	}
	if ag != nil {
		state := ag.State()
		if state == "running" || state == "aborting" {
			return false, "leaf_busy"
		}
	}
	return true, ""
}

func (o *leafOperations) cleanupAfterVacuum(prunedRootIDs []string) {
	if len(prunedRootIDs) == 0 {
		return
	}
	pruned := make(map[string]bool, len(prunedRootIDs))
	for _, id := range prunedRootIDs {
		pruned[id] = true
	}
	for leafID, ag := range o.agentEntries() {
		if !pruned[ag.RootID()] {
			continue
		}
		if ag.State() == "running" {
			slog.Warn("agent still running after root vacuumed", "leaf_id", leafID, "root_id", ag.RootID())
			continue
		}
		// Removal is generation-safe and must observe the same closed state
		// as other registry cleanup paths.
		tasks := o.retireBackgroundLocked(leafID)
		ag.Close()
		o.removeAgentIf(leafID, ag)
		o.cancelBackground(tasks, "leaf_deleted")
	}
}

func (o *leafOperations) agentEntries() map[string]*agent.Agent {
	o.mu.RLock()
	entries := make(map[string]*agent.Agent, len(o.agents))
	for id, ag := range o.agents {
		entries[id] = ag
	}
	o.mu.RUnlock()
	return entries
}

// evictIdle closes only an unchanged, still-idle Agent. Subscription ownership
// remains in routing and is queried without holding the leaf-operation lock.
func (o *leafOperations) evictIdle(now time.Time, idleFor time.Duration, hasSubscribers func(string) bool) int {
	var candidates []string
	for id, ag := range o.agentEntries() {
		if ag.State() != "idle" || hasSubscribers(id) {
			continue
		}
		since := ag.IdleSince()
		if since != nil && now.Sub(*since) >= idleFor {
			candidates = append(candidates, id)
		}
	}

	evicted := 0
	for _, id := range candidates {
		gate, ok := o.acquireGate(id)
		if !ok {
			continue
		}
		ag := o.resolveAgent(id)
		o.mu.RLock()
		reserved := o.admissions[id] > 0
		o.mu.RUnlock()
		var since *time.Time
		if ag != nil {
			since = ag.IdleSince()
		}
		liveTool := o.hasToolInvocations != nil && o.hasToolInvocations(id)
		if ag != nil && ag.State() == "idle" && !reserved && !hasSubscribers(id) && !liveTool && o.backgroundCount(id) == 0 && since != nil && now.Sub(*since) >= idleFor {
			ag.Close()
			if o.removeAgentIf(id, ag) {
				evicted++
			}
		}
		o.releaseGate(id, gate)
	}
	return evicted
}

func (o *leafOperations) ensureAgent(leafID string, parentTurnID *string, cfg *config.Config) (*agent.Agent, error) {
	if o.storage == nil {
		return nil, fmt.Errorf("leaf_not_found: %w", leafValidationError{leafID, session.ErrLeafNotFound})
	}
	gate, err := o.gates.acquireResult(context.Background(), o.storage, leafID)
	if err != nil {
		return nil, fmt.Errorf("leaf_not_found: %w", err)
	}
	gateHeld := true
	releaseGate := func() {
		if gateHeld {
			o.releaseGate(leafID, gate)
			gateHeld = false
		}
	}
	defer releaseGate()

	if existingAgent := o.resolveOpenAgent(leafID); existingAgent != nil {
		releaseGate()
		if err := existingAgent.ValidateAndLock(parentTurnID); err != nil {
			if existingAgent.State() == "running" {
				return nil, expectedLeafRejection{fmt.Errorf("leaf_busy: %w", err)}
			}
			return nil, expectedLeafRejection{err}
		}
		return existingAgent, nil
	}

	tip, err := o.storage.GetLeafTip(leafID)
	if err != nil {
		return nil, fmt.Errorf("leaf_not_found: %w", err)
	}
	if parentTurnID != nil {
		if tip == nil || *tip != *parentTurnID {
			return nil, expectedLeafRejection{fmt.Errorf("turn_conflict: parent_turn_id does not match leaf tip")}
		}
	} else if tip != nil {
		return nil, expectedLeafRejection{fmt.Errorf("turn_conflict: parent_turn_id required for follow-up prompt on existing leaf")}
	}

	ag := o.newAgent(leafID, cfg)
	if err := ag.ResumeFromDBWithRegistration(leafID, func() bool {
		// State is initialized before publication. Releasing the gate lets the
		// resume snapshot and concurrent lazy admissions observe this Agent.
		if o.beforeAgentPublication != nil {
			o.beforeAgentPublication(leafID, ag)
		}
		if !o.tryRegisterAgent(leafID, ag) {
			return false
		}
		releaseGate()
		return true
	}); err != nil {
		ag.Close()
		return nil, fmt.Errorf("leaf_not_found: failed to resume leaf: %w", err)
	}
	slog.Info("agent created", "leaf_id", leafID)
	return ag, nil
}

type rewindLeafRequest struct {
	RequesterLive    func() bool
	LeafID           string
	CurrentTipTurnID string
	NewTipTurnID     string
	Replay           bool
	Origin           agent.Origin
	RequestID        string
	ResolveConfig    func(*session.Leaf) *config.Config
	// PublishFailure translates and enqueues a correlated error. Rewind calls
	// it before releasing an acquired gate; callers must provide it.
	PublishFailure func(error)
}

var errInvalidRewindModel = errors.New("invalid rewind model")
var errRewindAdmissionBusy = errors.New("rewind admission busy")
var errRequesterDisconnected = errors.New("requester disconnected")

type invalidRewindModelError struct{ err error }

func (e invalidRewindModelError) Error() string { return e.err.Error() }
func (e invalidRewindModelError) Unwrap() error { return errInvalidRewindModel }

func (o *leafOperations) rewind(ctx context.Context, req rewindLeafRequest) (err error) {
	gate, valid := o.acquireGate(req.LeafID)
	gateHeld := valid
	releaseGate := func() {
		if gateHeld {
			o.releaseGate(req.LeafID, gate)
			gateHeld = false
		}
	}
	defer releaseGate()
	defer func() {
		if err != nil {
			req.PublishFailure(err)
		}
	}()
	if !valid {
		return fmt.Errorf("leaf not found: %s", req.LeafID)
	}

	if req.RequesterLive != nil && !req.RequesterLive() {
		return errRequesterDisconnected
	}
	o.mu.RLock()
	busyAdmission := o.admissions[req.LeafID] > 0
	o.mu.RUnlock()
	ag := o.resolveOpenAgent(req.LeafID)
	if busyAdmission {
		return errRewindAdmissionBusy
	}

	leaf, err := o.storage.GetLeaf(req.LeafID)
	if err != nil {
		return err
	}
	var cfg *config.Config
	if req.Replay {
		if req.ResolveConfig != nil {
			cfg = req.ResolveConfig(leaf)
		}
		if cfg == nil {
			return agent.ErrRunConfigRequired
		}
		if err := cfg.ValidateModel(leaf.Model); err != nil {
			return invalidRewindModelError{err: err}
		}
	}

	var oldTip, newTip string
	var replayRun *agent.ReplayRun
	if ag == nil && !req.Replay {
		oldTip, newTip, err = o.storage.RewindLeaf(req.LeafID, req.CurrentTipTurnID, req.NewTipTurnID)
	} else {
		var initialize *session.Leaf
		if ag == nil {
			ag = o.newAgent(leaf.ID, cfg)
			initialize = leaf
		}
		oldTip, newTip, replayRun, err = ag.Rewind(ctx, initialize, req.CurrentTipTurnID, req.NewTipTurnID, req.Replay, req.Origin, req.RequestID, cfg)
		if initialize != nil {
			if err == nil {
				if !o.registerAgent(req.LeafID, ag) {
					err = agent.ErrAgentClosed
				}
			} else {
				ag.Close()
			}
		}
	}
	if err != nil {
		return err
	}

	// Rewind may change the authoritative sent turn, including to no sent
	// turn. Reconcile progress under the existing leaf gate before capturing
	// the canonical snapshot; queued drafts are not authority.
	currentSent, sentErr := o.currentSentTurn(req.LeafID)
	if sentErr != nil {
		// The cut has already committed and may own a reserved replay. Do
		// not misreport it as rejected or abandon that execution. Old
		// statuses cannot survive the cut; drop the transient projection
		// and let the next successful authority read derive its turn.
		slog.Warn("resolve sent turn after committed rewind", "leaf_id", req.LeafID, "error", sentErr)
		o.dropProgressLeaf(req.LeafID)
	} else {
		o.advanceProgressTurnLocked(req.LeafID, currentSent)
	}

	// The operation owns this publication contract: accepted cut, canonical
	// subscriber snapshot, gate release, then replay lifecycle.
	if o.router != nil {
		o.router.enqueueLeafRewound(req.Origin.ConnID(), req.LeafID, oldTip, newTip, req.Replay, req.RequestID)
	}
	if update, ok := o.buildSnapshotLocked(req.LeafID, oldTip); ok {
		if o.router != nil {
			o.router.enqueueLeafSnapshot(update)
		}
	}
	releaseGate()
	if replayRun != nil {
		replayRun.Start()
	}
	return nil
}

// buildSnapshotLocked requires the leaf gate. It captures operation state; the
// router receives only an immutable value to fan out.
func (o *leafOperations) buildSnapshotLocked(leafID, previousTipTurnID string) (protocol.LeafUpdated, bool) {
	return o.buildSnapshotContextLocked(context.Background(), leafID, previousTipTurnID)
}

func (o *leafOperations) buildSnapshotContextLocked(ctx context.Context, leafID, previousTipTurnID string) (protocol.LeafUpdated, bool) {
	leaf, err := o.storage.GetLeafContext(ctx, leafID)
	if err != nil {
		return protocol.LeafUpdated{}, false
	}
	runtime := o.leafRuntimeContext(ctx, leaf)
	update := protocol.LeafUpdated{
		Type:              "leaf_updated",
		LeafID:            leaf.ID,
		TipTurnID:         leaf.TurnID,
		PreviousTipTurnID: previousTipTurnID,
		Model:             leaf.Model,
		ThinkingLevel:     leaf.ThinkingLevel,
		AccessSource:      runtime.AccessSource,
		Name:              leaf.Name,
		State:             leafUpdatedStateForWire(runtime.State),
		QueueCount:        runtime.QueueCount,
	}
	update.RunStartedAt, update.RunElapsedMS = leafRunTiming(runtime.RunStartedAt)
	update.Progress = o.progressSnapshot(leafID, false)
	questions := o.questions.PendingQuestions(leafID)
	update.PendingQuestions = make([]protocol.PendingQuestion, len(questions))
	for i, question := range questions {
		update.PendingQuestions[i] = question
		if question.ProjectConfigTrust != nil {
			value := *question.ProjectConfigTrust
			update.PendingQuestions[i].ProjectConfigTrust = &value
		}
	}
	return update, true
}