Files
pipelines/internal/cli/inspect.go
T
alan ea858804b8 Merge main into the engine loop improvements
Keep both intents: check stages, allow_workspace_changes, outcome repair
counts and Claude stage re-adoption from main beside the findings gate,
resume_session, applyLimitOn and exhaustion decisions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:24:27 +00:00

298 lines
9.2 KiB
Go

package cli
import (
"encoding/json"
"fmt"
"sort"
"strings"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/turn"
)
// inspectHandoffCap bounds the final handoff the compact summary prints; the
// full text stays available with --step N or --json.
const inspectHandoffCap = 1500
// inspectSummary is the default, compact `pipelines inspect` view: a header,
// one line per step and the run's final handoff. It deliberately omits inputs,
// transcripts and full outputs, which --step N, --transcripts and --json show.
func inspectSummary(d *protocol.RunDetail) string {
var b strings.Builder
fmt.Fprintf(&b, "run %d · %s v%d · %s", d.ID, d.Name, d.Version, d.Status)
if outcome := strings.TrimSpace(d.Outcome); outcome != "" {
fmt.Fprintf(&b, " (%s)", outcome)
}
if elapsed := runElapsed(d.CreatedAt, d.FinishedAt); elapsed != "" {
b.WriteString(" · " + elapsed)
}
b.WriteString("\n")
if title := strings.TrimSpace(d.Title); title != "" && title != d.Name {
b.WriteString("title: " + title + "\n")
}
if d.Workspace != "" {
b.WriteString("workspace: " + d.Workspace + "\n")
}
if d.RetryOf > 0 {
fmt.Fprintf(&b, "retry of run %d (%s)\n", d.RetryOf, d.RetryMode)
}
if line := firstLine(d.Diagnostic); line != "" {
b.WriteString("diagnostic: " + line + "\n")
}
if len(d.Steps) > 0 {
b.WriteString("\nsteps:\n")
}
for _, step := range d.Steps {
b.WriteString(" " + stepLine(step) + "\n")
}
if next := waitingHint(d); next != "" {
b.WriteString("\n" + next + "\n")
}
b.WriteString(inspectFindings(d))
if len(d.VisitGrants) > 0 {
keys := make([]string, 0, len(d.VisitGrants))
for key := range d.VisitGrants {
keys = append(keys, key)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, key := range keys {
parts = append(parts, fmt.Sprintf("%s +%d", key, d.VisitGrants[key]))
}
b.WriteString("\nextra visits: " + strings.Join(parts, ", ") + "\n")
}
if handoff := finalHandoff(d); handoff != "" {
b.WriteString("\nhandoff:\n" + indent(handoff) + "\n")
} else if preview := strings.TrimSpace(d.ResultPreview); preview != "" {
b.WriteString("\nresult: " + preview + "\n")
}
b.WriteString(fmt.Sprintf("\nMore: pipelines inspect %d --step N | --transcripts | --json\n", d.ID))
return b.String()
}
// stepLine is one step of the compact summary: sequence, stage, status,
// outcome, duration and the first diagnostic line.
func stepLine(step protocol.RunStep) string {
line := fmt.Sprintf("#%d %s · %s", step.Sequence, step.Stage, step.Status)
if outcome := strings.TrimSpace(step.Outcome); outcome != "" {
line += " (" + outcome + ")"
}
if step.StartedAt != "" {
if elapsed := runElapsed(step.StartedAt, step.FinishedAt); elapsed != "" {
line += " · " + elapsed
}
}
if diagnostic := firstLine(step.Diagnostic); diagnostic != "" {
line += " · " + diagnostic
}
return line
}
// inspectStep renders one step in full except for its transcript, which only
// --transcripts adds.
func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string, error) {
step, ok := findStep(d, sequence)
if !ok {
return "", fmt.Errorf("run %d has no step %d; pipelines inspect %d lists them", d.ID, sequence, d.ID)
}
var b strings.Builder
b.WriteString(stepLine(step) + "\n")
if step.Target != "" {
b.WriteString("next: " + step.Target + "\n")
}
if step.Model != "" {
b.WriteString("model: " + step.Provider + "/" + step.Model + "\n")
}
if step.SessionID != "" {
b.WriteString("session: " + step.SessionID + "\n")
}
if step.Control != nil && step.Control.OutcomeRepairs > 0 {
fmt.Fprintf(&b, "outcome repair follow-ups: %d\n", step.Control.OutcomeRepairs)
}
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
}
if checks, ok := step.Output["checks"].([]any); ok && len(checks) > 0 {
b.WriteString("\nchecks:\n")
for _, entry := range checks {
check, _ := entry.(map[string]any)
command, _ := check["command"].(string)
status, _ := check["status"].(string)
exit, _ := check["exit_code"].(float64)
duration, _ := check["duration_ms"].(float64)
fmt.Fprintf(&b, " %-9s exit %-3d %6.1fs %s\n", status, int(exit), duration/1000, command)
}
}
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
} else if len(step.Output) > 0 {
data, _ := json.MarshalIndent(step.Output, "", " ")
b.WriteString("\noutput:\n" + indent(string(data)) + "\n")
}
if step.FileChanges != nil {
data, _ := json.Marshal(step.FileChanges)
b.WriteString("\nfile changes: " + string(data) + "\n")
}
for _, artifact := range step.Artifacts {
fmt.Fprintf(&b, "artifact: %s (%d bytes)\n", artifact.Name, artifact.SizeBytes)
}
if transcripts && strings.TrimSpace(step.Transcript) != "" {
b.WriteString("\ntranscript:\n" + indent(strings.TrimSpace(step.Transcript)) + "\n")
}
return b.String(), nil
}
// inspectTranscripts appends each step's transcript to the compact summary.
func inspectTranscripts(d *protocol.RunDetail) string {
var b strings.Builder
b.WriteString(inspectSummary(d))
for _, step := range d.Steps {
if transcript := strings.TrimSpace(step.Transcript); transcript != "" {
fmt.Fprintf(&b, "\ntranscript #%d %s:\n%s\n", step.Sequence, step.Stage, indent(transcript))
}
}
return b.String()
}
func findStep(d *protocol.RunDetail, sequence int) (protocol.RunStep, bool) {
for _, step := range d.Steps {
if step.Sequence == sequence {
return step, true
}
}
return protocol.RunStep{}, false
}
// finalHandoff is the bounded `# handoff` of the last step that wrote one.
func finalHandoff(d *protocol.RunDetail) string {
for i := len(d.Steps) - 1; i >= 0; i-- {
markdown, _ := d.Steps[i].Output["markdown"].(string)
if section, ok := turn.HandoffSection(markdown); ok {
return bounded(section, inspectHandoffCap)
}
}
return ""
}
// waitingHint tells an agent how to answer a run parked on a human stage.
func waitingHint(d *protocol.RunDetail) string {
if d.Status != protocol.RunStatusWaiting || d.ExportPendingSequence > 0 {
return ""
}
stage := strings.TrimSpace(d.CurrentStage)
var options []string
var prompt string
for i := len(d.Steps) - 1; i >= 0; i-- {
if d.Steps[i].Status == protocol.RunStatusWaiting || (stage != "" && d.Steps[i].Stage == stage) {
options = protocol.WaitingOptions(d.Steps[i].Output)
prompt = protocol.WaitingPrompt(d.Steps[i].Output)
if stage == "" {
stage = d.Steps[i].Stage
}
break
}
}
option := "KEY"
if len(options) > 0 {
option = strings.Join(options, "|")
}
line := fmt.Sprintf("run %d waiting at %s — answer with: pipelines decide %d --option %s [--feedback TEXT]", d.ID, stage, d.ID, option)
if prompt = firstLine(prompt); prompt != "" {
line += "\n question: " + prompt
}
return line
}
// failureDetail is the stage an unsuccessful run stopped at and the first line
// of its diagnostic; both are empty for a run that has not failed.
func failureDetail(d *protocol.RunDetail) (stage, diagnostic string) {
if d.Status != "failed" && d.Status != protocol.RunStatusCanceled && d.Status != "interrupted" {
return "", ""
}
for i := len(d.Steps) - 1; i >= 0; i-- {
if d.Steps[i].Status == "failed" || strings.TrimSpace(d.Steps[i].Diagnostic) != "" {
stage, diagnostic = d.Steps[i].Stage, firstLine(d.Steps[i].Diagnostic)
break
}
}
if stage == "" {
stage = strings.TrimSpace(d.CurrentStage)
}
if line := firstLine(d.Diagnostic); line != "" {
diagnostic = line
}
return stage, diagnostic
}
// failureNote names the failing stage and its first diagnostic line.
func failureNote(d *protocol.RunDetail) string {
stage, diagnostic := failureDetail(d)
switch {
case stage != "" && diagnostic != "":
return "failed at " + stage + ": " + diagnostic
case stage != "":
return "failed at " + stage
}
return diagnostic
}
func firstLine(text string) string {
for _, line := range strings.Split(text, "\n") {
if line = strings.TrimSpace(line); line != "" {
return bounded(line, 240)
}
}
return ""
}
func bounded(text string, limit int) string {
if len(text) <= limit {
return text
}
cut := limit
for cut > 0 && !utf8.RuneStart(text[cut]) {
cut--
}
return text[:cut] + "…"
}
func indent(text string) string {
return " " + strings.ReplaceAll(text, "\n", "\n ")
}
// inspect prints a run: the compact summary by default, one step with --step,
// transcripts with --transcripts and the full RunDetail with --json.
func (a App) inspect(d *protocol.RunDetail, o *options) error {
if o.step < 0 {
return fmt.Errorf("--step must be a positive step sequence")
}
if o.json {
if o.step > 0 {
step, ok := findStep(d, o.step)
if !ok {
return fmt.Errorf("run %d has no step %d", d.ID, o.step)
}
if !o.transcripts {
step.Transcript = ""
}
return a.output(step)
}
return a.output(d)
}
text := ""
switch {
case o.step > 0:
var err error
if text, err = inspectStep(d, o.step, o.transcripts); err != nil {
return err
}
case o.transcripts:
text = inspectTranscripts(d)
default:
text = inspectSummary(d)
}
_, err := fmt.Fprint(a.Out, text)
return err
}