package server import ( "context" "fmt" "log" "os" "path/filepath" "strings" "time" "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/stage" "git.a-wan.net/alan/pipelines/internal/turn" ) // Loop control: per-stage visit caps (raised by grants), the findings ledger, // mechanical findings gates and operator decisions on exhausted loops. const ( // maxStageVisits is the global per-stage visit cap before grants. maxStageVisits = 5 // maxRunSteps is the global step cap before grants. maxRunSteps = 30 // maxExtraVisits bounds one grant (a retry's --extra-visits). maxExtraVisits = 5 // maxRunStepsWithGrants is the absolute step cap however much is granted. maxRunStepsWithGrants = 120 ) func graphHasStage(g protocol.Graph, key string) bool { for _, s := range g.Stages { if s.Key == key { return true } } return false } // visitCaps returns a stage's effective max_visits and hard per-stage cap, // both raised by the extra visits granted to it. func (s *runState) visitCaps(selected protocol.Stage) (limit, hard int) { limit = maxStageVisits if selected.Limits != nil { limit = selected.Limits.MaxVisits } extra := s.grants[selected.Key] return limit + extra, maxStageVisits + extra } // stepLimit is the run's total step cap: 30 plus, for every granted visit, // room for one more pass through the graph, bounded. func (s *runState) stepLimit(graph protocol.Graph) int { total := maxRunSteps for _, extra := range s.grants { total += extra * max(len(graph.Stages), 1) } return min(total, maxRunStepsWithGrants) } // grant adds extra visits to each named stage. func (s *runState) grant(stages []string, extra int) { if s.grants == nil { s.grants = map[string]int{} } for _, key := range stages { s.grants[key] += extra } } // exhaustedContinuation turns the last step of a run that a visit cap stopped // into the checkpoint that continues its loop: the stage the routing was // heading to, with the stopped step's output as its input. ok is false when // the run did not stop on a cap. func exhaustedContinuation(last protocol.RunStep) (protocol.RunStep, bool) { if last.Status != "completed" { return last, false } target := last.Target if last.Control != nil && last.Control.LimitReached && last.Control.ModelTarget != "" { target = last.Control.ModelTarget } if target == "" || protocol.IsTerminal(target) { return last, false } input := last.Output if input == nil { input = map[string]any{} } return protocol.RunStep{Sequence: last.Sequence + 1, Stage: target, Status: "failed", Target: protocol.FailureEnd, Input: input}, true } // exhaustedStages are the non-human stages whose next visit their caps refuse, // plus next (the stage the run continues with) when nothing else is. func exhaustedStages(graph protocol.Graph, state *runState, next string) []string { var out []string for _, declared := range graph.Stages { if stage.EffectiveType(declared.Type) == stage.HumanType { continue } limit, hard := state.visitCaps(declared) if visits := state.visits[declared.Key]; visits > 0 && (visits >= limit || visits >= hard) { out = append(out, declared.Key) } } if len(out) == 0 && next != "" { out = append(out, next) } return out } // applyLimitOn applies a stage's limits.on on its last allowed visit: a listed // outcome is kept but routed to #failure, or, with on_exhausted=decide, keeps // its route and the caller parks the run on an operator decision (park true). func applyLimitOn(step *protocol.RunStep, selected protocol.Stage, visit, maxVisits int) (park bool) { if selected.Limits == nil || visit < maxVisits || step.Target == "" || protocol.IsTerminal(step.Target) { return false } for _, outcome := range selected.Limits.On { if outcome != step.Outcome { continue } step.Control.LimitReached = true step.Control.ModelTarget = step.Target if decidesOnExhaustion(selected) { return true } step.Target = protocol.FailureEnd step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", selected.Key, maxVisits, step.Outcome) return false } return false } // isExhaustionStep reports whether a recorded step is a runner-created // exhaustion decision rather than a stage visit. func isExhaustionStep(step protocol.RunStep) bool { return protocol.ExhaustedInfo(step.Output) != nil } func decidesOnExhaustion(s protocol.Stage) bool { return s.Limits != nil && s.Limits.OnExhausted == "decide" } // parkExhausted parks the run on an operator decision because stage selected // exhausted its visits: accept the work as it is (accept_to, default // #success), continue for one more round (continueTo, with one more visit // granted) or abort. It mirrors a human stage's wait: one waiting step and no // live goroutine; the decision resumes the run through decide. func (r *runner) parkExhausted(ctx context.Context, id int64, name, workspace string, state *runState, sequence int, selected protocol.Stage, visit, maxVisits int, continueTo string) error { accept := protocol.SuccessEnd if selected.Limits != nil && selected.Limits.AcceptTo != "" { accept = selected.Limits.AcceptTo } targets := map[string]any{protocol.ExhaustedAccept: accept, protocol.ExhaustedContinue: continueTo, protocol.ExhaustedAbort: protocol.FailureEnd} prompt := fmt.Sprintf("Stage %s used its %d allowed visits and the loop is not finished. Choose accept to take the work as it is (continues to %s), continue for one more round (one more visit; continues to %s), or abort to fail the run.", selected.Key, maxVisits, accept, continueTo) options := []string{protocol.ExhaustedAbort, protocol.ExhaustedAccept, protocol.ExhaustedContinue} evidence := protocol.NewWaitingEvidence(prompt, options) evidence[protocol.ExhaustedKey] = map[string]any{"stage": selected.Key, "visit": visit, "max_visits": maxVisits, "targets": targets} if err := r.store.BeginStep(ctx, id, sequence, selected.Key, state.input); err != nil { return err } state.nextSequence = sequence + 1 r.mu.Lock() if err := r.store.MarkWaiting(ctx, id, sequence, selected.Key, evidence); err != nil { r.mu.Unlock() return err } r.emitRun(protocol.RunEventFrame{ RunID: id, Workspace: workspace, Status: protocol.RunStatusWaiting, CurrentStage: selected.Key, CompletedSteps: state.completed, Step: &protocol.RunStepDelta{Sequence: sequence, Stage: selected.Key, Status: protocol.StepStatusWaiting}, }, false) delete(r.active, id) r.mu.Unlock() r.deliverRunNotificationBatch(time.Now(), 1) return nil } // grantForDecision records the extra visit a "continue" exhaustion decision // allows: one more visit for the exhausted stage and for the stage the loop // continues with. func (r *runner) grantForDecision(ctx context.Context, detail *protocol.RunDetail, step protocol.RunStep) { info := protocol.ExhaustedInfo(step.Output) if info == nil || step.Outcome != protocol.ExhaustedContinue { return } stages := []string{} if key, ok := info["stage"].(string); ok && key != "" { stages = append(stages, key) } if step.Target != "" && !protocol.IsTerminal(step.Target) && (len(stages) == 0 || stages[0] != step.Target) { stages = append(stages, step.Target) } for _, key := range stages { grants, err := r.store.AddRunVisitGrant(ctx, detail.ID, key, 1) if err != nil { log.Printf("run %d: grant a visit to %s: %v", detail.ID, key, err) continue } detail.VisitGrants = grants } } // recordFindings folds a completed visit's "# findings" section into the run's // ledger and persists it. A ledger write failure is logged, never fatal: the // stage's own output keeps the findings. func (r *runner) recordFindings(id int64, state *runState, step protocol.RunStep) { markdown, _ := step.Output["markdown"].(string) report := findings.Parse(markdown) if len(report.New) == 0 && len(report.Changes) == 0 { return } ledger, outcome := findings.Apply(state.findings, report, step.Stage, step.Sequence) state.findings = ledger if len(outcome.Ignored) > 0 { log.Printf("run %d stage %s #%d: findings ignored: %s", id, step.Stage, step.Sequence, strings.Join(outcome.Ignored, "; ")) } r.persistFindings(id, ledger) } func (r *runner) persistFindings(id int64, ledger []protocol.Finding) { save, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := r.store.SetRunFindings(save, id, ledger); err != nil { log.Printf("run %d: save findings ledger: %v", id, err) } } func (r *runner) persistGrants(id int64, grants map[string]int) { save, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := r.store.SetRunVisitGrants(save, id, grants); err != nil { log.Printf("run %d: save visit grants: %v", id, err) } } // findingsGateStep evaluates a findings stage against the ledger. func findingsGateStep(def stage.Definition, state *runState, sequence int) protocol.RunStep { gate, _ := stage.FindingsGate(def) matched := gate.Matching(state.findings) outcome := stage.FindingsClear reason := fmt.Sprintf("No open findings at %s or above (origin %s).", gate.MinSeverity, gate.Origin) ids := make([]string, 0, len(matched)) for _, item := range matched { ids = append(ids, item.ID) } if len(matched) > 0 { outcome = stage.FindingsOpen reason = fmt.Sprintf("%d open finding(s) at %s or above (origin %s): %s.", len(matched), gate.MinSeverity, gate.Origin, strings.Join(ids, ", ")) } return protocol.RunStep{ Sequence: sequence, Stage: def.Key, Status: "completed", Outcome: outcome, Output: stage.Values{"summary": reason, "findings": ids}, Target: def.Edges[outcome], Verdict: &protocol.StageVerdict{Reason: reason, ReasonSource: protocol.VerdictReasonFallback}, } } // writeFindingsFile writes the visit's findings.md (the whole ledger) next to // memory.md when the run has a ledger. func writeFindingsFile(paths turn.Paths, ledger []protocol.Finding) error { if len(ledger) == 0 { return nil } name := filepath.Join(paths.TurnDir, "findings.md") if err := os.WriteFile(name, []byte(findings.RenderFile(ledger)), 0o600); err != nil { return fmt.Errorf("write %s: %w", name, err) } return nil }