Merge lane-go: titles, verdicts, human stage, line result format, stale-client guard
Integrates nine commits of reviewed work from the lane-go branch after the automated resolver failed on this merge five times (each attempt dying on the malformed-result defect whose fix is contained in this same merge). Integration decisions: - Search: kept main's shipped design (Store.Search + SearchResponse.Results) and dropped lane-go's parallel, older attempt (an unused Message.Matches field, an absent runs.search, and two partial TUI plumbing blocks). lane-go itself did not compile: protocol.SearchMatch was undefined and model.go referenced searchNav, requestSearch and applyRunNav, which exist nowhere. Those partial TUI blocks are removed; the queued TUI omni-search item will implement the surface properly on main's design. - Both sides' additions are kept where they are independent: run titles and provenance, the human decision stage and its CLI/TUI surface, the derived stage verdict, the stale-client guard, the line-oriented result format, and main's search command. - The search key's help label is now "/ omni search"; the two tests asserting the old label are updated rather than the label reverted. - docs/cli.md and the packaged operations reference carry both sides' text. Verified: go build ./... , go vet ./... and the full go test ./... suite pass.
This commit is contained in:
@@ -0,0 +1,207 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
const humanSource = "# stage gate\n\n```output\nDecision evidence.\n```\n\n```prompt\nReview the screenshots and choose.\n```\n\n```edges\ndeploy -> worker\nrevise -> worker\nerror -> #failure\n```\n\n```configs\ntype=human\n```\n\n# stage worker\n\n```output\nWork result.\n```\n\n```prompt\nDo the work.\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=2\ntimeout=1h\n```\n\n"
|
||||
|
||||
func TestHumanStageAuthoringRoundTrip(t *testing.T) {
|
||||
graph, err := Parse(humanSource)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(graph.Stages) != 2 || graph.Stages[0].Type != "human" {
|
||||
t.Fatalf("human type not parsed: %+v", graph.Stages)
|
||||
}
|
||||
gate := graph.Stages[0]
|
||||
if strings.TrimSpace(gate.Prompt) == "" || gate.Edges["deploy"] != "worker" {
|
||||
t.Fatalf("human stage fields lost: %+v", gate)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "human.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "human", humanSource); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
definition, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if definition.Source != humanSource {
|
||||
t.Fatal("immutable source was rewritten")
|
||||
}
|
||||
if definition.Graph.Stages[0].Type != "human" {
|
||||
t.Fatalf("human type lost in stored graph: %+v", definition.Graph.Stages[0])
|
||||
}
|
||||
}
|
||||
|
||||
func humanRun(t *testing.T, ctx context.Context, store *Store) (int64, string) {
|
||||
t.Helper()
|
||||
if _, err := store.Submit(ctx, "humangate", humanSource); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
definition, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, _, err := store.CreateRun(ctx, definition, "humangate-run", "workspace", false, nil, map[string]any{"prompt": "task"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 1, "gate", map[string]any{"prompt": "task"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
evidence := protocol.NewWaitingEvidence("Review the screenshots and choose.", []string{"deploy", "revise"})
|
||||
if err := store.MarkWaiting(ctx, id, 1, "gate", evidence); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id, "gate"
|
||||
}
|
||||
|
||||
func TestMarkWaitingPersistsDurableWait(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "wait.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
id, _ := humanRun(t, ctx, store)
|
||||
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != protocol.RunStatusWaiting || detail.CurrentStage != "gate" || detail.FinishedAt != "" {
|
||||
t.Fatalf("run did not report waiting: %+v", detail.RunSummary)
|
||||
}
|
||||
if len(detail.Steps) != 1 || detail.Steps[0].Status != protocol.StepStatusWaiting || detail.Steps[0].FinishedAt != "" {
|
||||
t.Fatalf("step did not persist waiting: %+v", detail.Steps)
|
||||
}
|
||||
if prompt := protocol.WaitingPrompt(detail.Steps[0].Output); prompt == "" {
|
||||
t.Fatalf("waiting evidence lost its prompt: %+v", detail.Steps[0].Output)
|
||||
}
|
||||
if options := protocol.WaitingOptions(detail.Steps[0].Output); len(options) != 2 {
|
||||
t.Fatalf("waiting evidence lost its options: %+v", options)
|
||||
}
|
||||
|
||||
// Recovery from persisted rows must leave a waiting run and step untouched.
|
||||
if err := store.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovered, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recovered.Status != protocol.RunStatusWaiting || recovered.Steps[0].Status != protocol.StepStatusWaiting {
|
||||
t.Fatalf("RecoverRuns disturbed a waiting run: %+v", recovered.RunSummary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDecisionValidUnknownRepeatAndNotWaiting(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "decide.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
id, _ := humanRun(t, ctx, store)
|
||||
|
||||
if _, _, err := store.ResolveDecision(ctx, id, "", "launch", ""); err == nil || !strings.Contains(err.Error(), "valid options") || !strings.Contains(err.Error(), "deploy") {
|
||||
t.Fatalf("unknown option not refused with the valid list: %v", err)
|
||||
}
|
||||
|
||||
step, applied, err := store.ResolveDecision(ctx, id, "", "deploy", "looks good, ship it")
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("valid decision failed: %+v %v %v", step, applied, err)
|
||||
}
|
||||
if step.Outcome != "deploy" || step.Target != "worker" {
|
||||
t.Fatalf("decision did not route along the edge: %+v", step)
|
||||
}
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "running" || detail.Steps[0].Status != "completed" || detail.Steps[0].Outcome != "deploy" {
|
||||
t.Fatalf("decision not persisted: %+v", detail)
|
||||
}
|
||||
if detail.Steps[0].Diagnostic != "" {
|
||||
t.Fatalf("a deliberate decision must not be recorded as a stop: %+v", detail.Steps[0])
|
||||
}
|
||||
if detail.Steps[0].Output["option"] != "deploy" || detail.Steps[0].Output["feedback"] != "looks good, ship it" {
|
||||
t.Fatalf("feedback not recorded in the output: %+v", detail.Steps[0])
|
||||
}
|
||||
verdict := detail.Steps[0].Verdict
|
||||
if verdict == nil || verdict.Option != "deploy → worker" || verdict.Reason != "looks good, ship it" {
|
||||
t.Fatalf("derived verdict missing the choice or feedback: %+v", verdict)
|
||||
}
|
||||
|
||||
// A repeated decision for the already-decided visit must not double-apply.
|
||||
repeat, applied, err := store.ResolveDecision(ctx, id, "", "deploy", "second try")
|
||||
if err != nil || applied {
|
||||
t.Fatalf("repeat decision double-applied: applied=%v err=%v", applied, err)
|
||||
}
|
||||
if repeat.Sequence != step.Sequence {
|
||||
t.Fatalf("repeat decision pointed at another visit: %+v", repeat)
|
||||
}
|
||||
// A different option for the same decided visit is refused.
|
||||
if _, _, err := store.ResolveDecision(ctx, id, "", "revise", ""); err == nil || !strings.Contains(err.Error(), "not waiting") {
|
||||
t.Fatalf("deciding a decided visit with another option was accepted: %v", err)
|
||||
}
|
||||
// A run whose graph has no human stage cannot be decided.
|
||||
if _, err := store.Submit(ctx, "plain", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plainItems, _ := store.List(ctx)
|
||||
var plain protocol.PipelineSummary
|
||||
for _, p := range plainItems {
|
||||
if p.Name == "plain" {
|
||||
plain = p
|
||||
}
|
||||
}
|
||||
plainDef, err := store.Get(ctx, plain.ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plainRun, _, err := store.CreateRun(ctx, plainDef, "plain-run", "workspace", false, nil, map[string]any{"prompt": "task"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := store.ResolveDecision(ctx, plainRun, "", "success", ""); err == nil {
|
||||
t.Fatal("decision on a run with no human stage was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelWaitingRun(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "cancel.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
id, _ := humanRun(t, ctx, store)
|
||||
if err := store.CancelWaiting(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "canceled" || detail.Steps[0].Status != "canceled" {
|
||||
t.Fatalf("waiting run not canceled: %+v %+v", detail.RunSummary, detail.Steps)
|
||||
}
|
||||
if err := store.CancelWaiting(ctx, id); err == nil {
|
||||
t.Fatal("canceling an already-canceled run succeeded")
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func parseNotify(text string) (*protocol.NotificationPolicy, error) {
|
||||
return result, nil
|
||||
}
|
||||
var err error
|
||||
p.On, err = parse(values["on"], map[string]bool{"success": true, "failure": true})
|
||||
p.On, err = parse(values["on"], map[string]bool{"success": true, "failure": true, protocol.NotifyWaiting: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+286
-8
@@ -6,15 +6,18 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
)
|
||||
|
||||
func (s *Store) initRuns() error {
|
||||
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS pipeline_runs (
|
||||
id INTEGER PRIMARY KEY, pipeline_id INTEGER NOT NULL, version INTEGER NOT NULL,
|
||||
request_key TEXT NOT NULL UNIQUE, workspace TEXT NOT NULL, allow_tools INTEGER NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '', title_source TEXT NOT NULL DEFAULT '', title_model TEXT NOT NULL DEFAULT '',
|
||||
write_paths TEXT NOT NULL, input_json TEXT NOT NULL, output_json TEXT NOT NULL DEFAULT '{}',
|
||||
status TEXT NOT NULL DEFAULT 'queued', outcome TEXT NOT NULL DEFAULT '', current_stage TEXT NOT NULL DEFAULT '',
|
||||
diagnostic TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, finished_at TEXT,
|
||||
@@ -39,15 +42,73 @@ PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(
|
||||
CREATE TABLE IF NOT EXISTS step_artifacts (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, artifacts_json TEXT NOT NULL,
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
|
||||
CREATE TABLE IF NOT EXISTS step_verdicts (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, verdict_json TEXT NOT NULL,
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
|
||||
CREATE TABLE IF NOT EXISTS run_session_owners (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, backend TEXT NOT NULL, reference TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
|
||||
CREATE TABLE IF NOT EXISTS run_retries (
|
||||
run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id), original_run_id INTEGER NOT NULL REFERENCES pipeline_runs(id));`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateRunTitles()
|
||||
}
|
||||
|
||||
// migrateRunTitles adds the title columns to a database created before run
|
||||
// titles existed. Adding a column with a default leaves every existing row valid
|
||||
// and untouched, so old runs still list.
|
||||
func (s *Store) migrateRunTitles() error {
|
||||
for _, column := range [][2]string{
|
||||
{"title", "TEXT NOT NULL DEFAULT ''"},
|
||||
{"title_source", "TEXT NOT NULL DEFAULT ''"},
|
||||
{"title_model", "TEXT NOT NULL DEFAULT ''"},
|
||||
} {
|
||||
if err := s.addColumnIfMissing("pipeline_runs", column[0], column[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// addColumnIfMissing adds a column only when the table predates it, making an
|
||||
// upgrade idempotent across repeated Open calls without rewriting history.
|
||||
func (s *Store) addColumnIfMissing(table, column, definition string) error {
|
||||
rows, err := s.db.Query("PRAGMA table_info(" + table + ")")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var cid, notnull, pk int
|
||||
var name, ctype string
|
||||
var dflt sql.NullString
|
||||
if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil {
|
||||
return err
|
||||
}
|
||||
if name == column {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.Exec("ALTER TABLE " + table + " ADD COLUMN " + column + " " + definition)
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateRun inserts a run and derives its title from the prompt. It is the entry
|
||||
// point for callers with no generated title; the derived fallback is always
|
||||
// non-empty and never calls a model.
|
||||
func (s *Store) CreateRun(ctx context.Context, d *protocol.PipelineDetail, key, workspace string, tools bool, paths []string, input map[string]any, retryOf ...int64) (int64, bool, error) {
|
||||
return s.CreateRunTitled(ctx, d, key, workspace, tools, paths, input, summarise.Title{}, retryOf...)
|
||||
}
|
||||
|
||||
// CreateRunTitled inserts a run with the caller's title. A non-empty title (a
|
||||
// model generation) is stored verbatim; an empty one falls back to the
|
||||
// prompt-derived title, so a run never stores an empty title.
|
||||
func (s *Store) CreateRunTitled(ctx context.Context, d *protocol.PipelineDetail, key, workspace string, tools bool, paths []string, input map[string]any, title summarise.Title, retryOf ...int64) (int64, bool, error) {
|
||||
var parent int64
|
||||
if len(retryOf) > 0 {
|
||||
parent = retryOf[0]
|
||||
@@ -55,6 +116,7 @@ func (s *Store) CreateRun(ctx context.Context, d *protocol.PipelineDetail, key,
|
||||
if parent < 0 {
|
||||
return 0, false, fmt.Errorf("invalid retry parent")
|
||||
}
|
||||
title = resolveRunTitle(title, input)
|
||||
encoded, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
@@ -88,7 +150,7 @@ func (s *Store) CreateRun(ctx context.Context, d *protocol.PipelineDetail, key,
|
||||
return 0, false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
result, err := tx.ExecContext(ctx, "INSERT INTO pipeline_runs(pipeline_id,version,request_key,workspace,allow_tools,write_paths,input_json) VALUES (?,?,?,?,?,?,?)", d.ID, d.Version, key, workspace, tools, string(writes), string(encoded))
|
||||
result, err := tx.ExecContext(ctx, "INSERT INTO pipeline_runs(pipeline_id,version,request_key,workspace,allow_tools,write_paths,input_json,title,title_source,title_model) VALUES (?,?,?,?,?,?,?,?,?,?)", d.ID, d.Version, key, workspace, tools, string(writes), string(encoded), title.Text, title.Source, title.Model)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
@@ -115,15 +177,45 @@ const runFrom = `FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id`
|
||||
// and searchRuns instead of copied per query.
|
||||
const runStamps = `strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',r.finished_at),'')`
|
||||
|
||||
// resolveRunTitle guarantees a stored run title is never empty: a title supplied
|
||||
// by the caller (a model generation) is kept verbatim, and an absent one is
|
||||
// derived from the prompt's first line. The fallback is server-owned and never
|
||||
// calls a model, so it can never block or fail run creation.
|
||||
func resolveRunTitle(title summarise.Title, input map[string]any) summarise.Title {
|
||||
if strings.TrimSpace(title.Text) != "" {
|
||||
return title
|
||||
}
|
||||
prompt, _ := input["prompt"].(string)
|
||||
return summarise.Title{Text: summarise.DeriveTitle(prompt), Source: summarise.SourceFallback}
|
||||
}
|
||||
|
||||
// SetRunTitle replaces a run's operator-facing title and its provenance without
|
||||
// touching the run's input, steps or execution. It is how an operator renames a
|
||||
// run after the fact.
|
||||
func (s *Store) SetRunTitle(ctx context.Context, id int64, title summarise.Title) error {
|
||||
result, err := s.db.ExecContext(ctx, "UPDATE pipeline_runs SET title=?,title_source=?,title_model=? WHERE id=?", title.Text, title.Source, title.Model, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return fmt.Errorf("run not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const runSelect = `SELECT r.id,r.pipeline_id,p.name,r.version,v.content_hash,r.status,r.outcome,r.current_stage,
|
||||
` + runStamps + `,r.diagnostic,
|
||||
CASE WHEN r.status='succeeded' THEN r.output_json ELSE COALESCE((SELECT output_json FROM run_steps WHERE run_id=r.id AND status='completed' ORDER BY sequence DESC LIMIT 1),'{}') END,
|
||||
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed')
|
||||
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title
|
||||
` + runFrom + ` JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version`
|
||||
|
||||
func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error {
|
||||
var output string
|
||||
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps); err != nil {
|
||||
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title); err != nil {
|
||||
return err
|
||||
}
|
||||
var values map[string]any
|
||||
@@ -187,7 +279,7 @@ func (s *Store) GetRun(ctx context.Context, id int64) (*protocol.RunDetail, erro
|
||||
if err := json.Unmarshal([]byte(graphJSON), &r.Graph); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.QueryRowContext(ctx, "SELECT workspace,allow_tools,write_paths,input_json,output_json,COALESCE((SELECT original_run_id FROM run_retries WHERE run_id=pipeline_runs.id),0) FROM pipeline_runs WHERE id=?", id).Scan(&r.Workspace, &r.AllowTools, &paths, &input, &output, &r.RetryOf); err != nil {
|
||||
if err := tx.QueryRowContext(ctx, "SELECT workspace,allow_tools,write_paths,input_json,output_json,COALESCE((SELECT original_run_id FROM run_retries WHERE run_id=pipeline_runs.id),0),title_source,title_model FROM pipeline_runs WHERE id=?", id).Scan(&r.Workspace, &r.AllowTools, &paths, &input, &output, &r.RetryOf, &r.TitleSource, &r.TitleModel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := decodeValues(input, &r.Input); err != nil {
|
||||
@@ -203,6 +295,7 @@ func (s *Store) GetRun(ctx context.Context, id int64) (*protocol.RunDetail, erro
|
||||
COALESCE((SELECT receipts_json FROM step_notifications n WHERE n.run_id=run_steps.run_id AND n.sequence=run_steps.sequence),'[]'),
|
||||
COALESCE((SELECT changes_json FROM step_file_changes f WHERE f.run_id=run_steps.run_id AND f.sequence=run_steps.sequence),'null'),
|
||||
COALESCE((SELECT artifacts_json FROM step_artifacts a WHERE a.run_id=run_steps.run_id AND a.sequence=run_steps.sequence),'null'),
|
||||
COALESCE((SELECT verdict_json FROM step_verdicts v WHERE v.run_id=run_steps.run_id AND v.sequence=run_steps.sequence),''),
|
||||
strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',finished_at),'') FROM run_steps WHERE run_id=? ORDER BY sequence`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -211,8 +304,8 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
|
||||
for rows.Next() {
|
||||
var step protocol.RunStep
|
||||
var notifications string
|
||||
var fileChanges, artifacts string
|
||||
if err := rows.Scan(&step.Sequence, &step.Stage, &step.Status, &step.Outcome, &step.Target, &input, &output, &step.Diagnostic, &step.SessionID, &step.AgentActive, &step.Transcript, ¬ifications, &fileChanges, &artifacts, &step.StartedAt, &step.FinishedAt); err != nil {
|
||||
var fileChanges, artifacts, storedVerdict string
|
||||
if err := rows.Scan(&step.Sequence, &step.Stage, &step.Status, &step.Outcome, &step.Target, &input, &output, &step.Diagnostic, &step.SessionID, &step.AgentActive, &step.Transcript, ¬ifications, &fileChanges, &artifacts, &storedVerdict, &step.StartedAt, &step.FinishedAt); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
@@ -242,6 +335,18 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// The verdict is derived here - the one place that already holds both the
|
||||
// decoded output and the recorded artifacts - using the stored model line
|
||||
// when present and the bounded read-time fallback otherwise, so existing
|
||||
// runs need no backfill.
|
||||
var stored stageVerdictEvidence
|
||||
if storedVerdict != "" {
|
||||
if err := json.Unmarshal([]byte(storedVerdict), &stored); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
step.Verdict = protocol.NewStageVerdict(step.Outcome, step.Target, step.Output, step.Artifacts, stored.Reason, stored.Source)
|
||||
// Loaded below after the rows cursor closes to preserve SQLite connection use.
|
||||
r.Steps = append(r.Steps, step)
|
||||
}
|
||||
@@ -416,6 +521,16 @@ type stageArtifactsEvidence struct {
|
||||
Truncated int `json:"truncated,omitempty"`
|
||||
}
|
||||
|
||||
// stageVerdictEvidence is the generated one-line verdict reason plus its
|
||||
// provenance. Like the other step-scoped evidence it lives in its own table, so
|
||||
// run_steps needs no schema migration and an old database gains the empty table
|
||||
// on Open with no backfill. Only a model-generated line is ever stored; the
|
||||
// read-time fallback is always derived, so existing runs still show a verdict.
|
||||
type stageVerdictEvidence struct {
|
||||
Reason string `json:"reason"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
func (s *Store) FinishStep(ctx context.Context, id int64, step protocol.RunStep) error {
|
||||
output, err := json.Marshal(step.Output)
|
||||
if err != nil {
|
||||
@@ -461,6 +576,169 @@ WHERE run_id=? AND sequence=? AND status='running'`, step.Status, step.Outcome,
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Persist only a generated model line and its provenance; the read-time
|
||||
// fallback is always derived in GetRun, so old runs stay intact.
|
||||
if step.Verdict != nil && strings.TrimSpace(step.Verdict.Reason) != "" {
|
||||
data, err := json.Marshal(stageVerdictEvidence{Reason: step.Verdict.Reason, Source: step.Verdict.ReasonSource})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "INSERT INTO step_verdicts(run_id,sequence,verdict_json) VALUES(?,?,?) ON CONFLICT(run_id,sequence) DO UPDATE SET verdict_json=excluded.verdict_json", id, step.Sequence, string(data)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// MarkWaiting persists a human stage's pending state in one transaction: the
|
||||
// step becomes waiting with self-contained evidence (its operator instructions
|
||||
// and ordered options) and the run reports the same key it is waiting on. It
|
||||
// leaves finished_at NULL for both and adds no goroutine, timer or new column.
|
||||
func (s *Store) MarkWaiting(ctx context.Context, id int64, sequence int, key string, evidence map[string]any) error {
|
||||
data, err := json.Marshal(evidence)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := affected(tx.ExecContext(ctx, `UPDATE run_steps SET status=?,output_json=? WHERE run_id=? AND sequence=? AND status='running'`,
|
||||
protocol.StepStatusWaiting, string(data), id, sequence)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,current_stage=? WHERE id=? AND status IN ('queued','running')`,
|
||||
protocol.RunStatusWaiting, key, id)); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// ResolveDecision records an operator's choice for a waiting human stage and
|
||||
// routes the run along that option's edge, all in one short transaction. It
|
||||
// reads the pinned graph and the pending step from persisted rows, so it is
|
||||
// correct after a restart and needs no live goroutine. Validation is idempotent:
|
||||
// a repeated decision for an already-decided visit with the same option returns
|
||||
// applied=false and no error, an unknown option is refused with the valid list,
|
||||
// and a stage that is not waiting is refused with its current state.
|
||||
func (s *Store) ResolveDecision(ctx context.Context, id int64, stageKey, option, feedback string) (protocol.RunStep, bool, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var status, currentStage, graphJSON string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT r.status,r.current_stage,v.graph_json FROM pipeline_runs r
|
||||
JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&status, ¤tStage, &graphJSON); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return protocol.RunStep{}, false, fmt.Errorf("run not found")
|
||||
}
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
if stageKey == "" {
|
||||
stageKey = currentStage
|
||||
// Prefer the actual waiting step's stage; current_stage is normally the
|
||||
// waiting stage, but this keeps the decision correct if it ever drifts.
|
||||
var waitingKey string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT stage_key FROM run_steps WHERE run_id=? AND status=? ORDER BY sequence DESC LIMIT 1`, id, protocol.StepStatusWaiting).Scan(&waitingKey); err == nil {
|
||||
stageKey = waitingKey
|
||||
} else if err != sql.ErrNoRows {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
}
|
||||
var graph protocol.Graph
|
||||
if err := json.Unmarshal([]byte(graphJSON), &graph); err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
var edges map[string]string
|
||||
found := false
|
||||
for _, declared := range graph.Stages {
|
||||
if declared.Key == stageKey {
|
||||
edges = declared.Edges
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return protocol.RunStep{}, false, fmt.Errorf("stage %q is not part of this run", stageKey)
|
||||
}
|
||||
options := stage.HumanOptions(edges)
|
||||
valid := false
|
||||
for _, candidate := range options {
|
||||
if candidate == option {
|
||||
valid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
return protocol.RunStep{}, false, fmt.Errorf("unknown option %q for stage %s; valid options: %s", option, stageKey, strings.Join(options, ", "))
|
||||
}
|
||||
var sequence int
|
||||
var stepStatus, stepOutcome string
|
||||
err = tx.QueryRowContext(ctx, `SELECT sequence,status,outcome FROM run_steps WHERE run_id=? AND stage_key=? ORDER BY sequence DESC LIMIT 1`, id, stageKey).Scan(&sequence, &stepStatus, &stepOutcome)
|
||||
if err == sql.ErrNoRows {
|
||||
return protocol.RunStep{}, false, fmt.Errorf("stage %s is not waiting", stageKey)
|
||||
}
|
||||
if err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
if stepStatus != protocol.StepStatusWaiting {
|
||||
if stepStatus == "completed" && stepOutcome == option {
|
||||
return protocol.RunStep{Sequence: sequence, Stage: stageKey, Status: "completed", Outcome: stepOutcome, Target: edges[stepOutcome]}, false, nil
|
||||
}
|
||||
return protocol.RunStep{}, false, fmt.Errorf("stage %s is not waiting (state %s)", stageKey, stepStatus)
|
||||
}
|
||||
if status != protocol.RunStatusWaiting && status != protocol.RunStatusRunning {
|
||||
return protocol.RunStep{}, false, fmt.Errorf("run %d is not waiting (state %s)", id, status)
|
||||
}
|
||||
target := edges[option]
|
||||
// The operator's choice and feedback are the step's evidence. The feedback
|
||||
// stays in the output only - never the step diagnostic - so a deliberate,
|
||||
// successful decision is not presented as a stop or error; the derived
|
||||
// verdict reads the feedback as the step's reason.
|
||||
output := map[string]any{protocol.DecisionOptionKey: option, protocol.DecisionFeedbackKey: feedback}
|
||||
encoded, err := json.Marshal(output)
|
||||
if err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
if err := affected(tx.ExecContext(ctx, `UPDATE run_steps SET status='completed',outcome=?,target=?,output_json=?,finished_at=CURRENT_TIMESTAMP
|
||||
WHERE run_id=? AND sequence=? AND status=?`, option, target, string(encoded), id, sequence, protocol.StepStatusWaiting)); err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='running' WHERE id=? AND status IN (?,?)`, id, protocol.RunStatusWaiting, protocol.RunStatusRunning)); err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
return protocol.RunStep{Sequence: sequence, Stage: stageKey, Status: "completed", Outcome: option, Target: target, Output: output}, true, nil
|
||||
}
|
||||
|
||||
// CancelWaiting cancels a run that is waiting on a person without a live
|
||||
// goroutine. It is a single transaction that marks the run canceled and its
|
||||
// waiting step canceled; a run that is not waiting is reported, not silently
|
||||
// ignored.
|
||||
func (s *Store) CancelWaiting(ctx context.Context, id int64) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',finished_at=CURRENT_TIMESTAMP WHERE id=? AND status=?`, id, protocol.RunStatusWaiting)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return fmt.Errorf("run is not active or waiting")
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE run_steps SET status='canceled',diagnostic='Canceled while waiting for a decision',finished_at=CURRENT_TIMESTAMP WHERE run_id=? AND status=?`, id, protocol.StepStatusWaiting); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -499,10 +777,10 @@ func (s *Store) RecoverRuns(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET status='interrupted',agent_active=0,diagnostic='Server stopped; stage was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status='running' OR agent_active=1"); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET status='interrupted',agent_active=0,diagnostic='Server stopped; stage was not resumed',finished_at=CURRENT_TIMESTAMP WHERE (status='running' OR agent_active=1) AND status<>?", protocol.StepStatusWaiting); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic='Server stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running')"); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic='Server stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>?", protocol.RunStatusWaiting); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
|
||||
@@ -5,7 +5,10 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
)
|
||||
|
||||
func TestRunListIncludesHistoryBeyondFiftyForSearchAndPipelineScope(t *testing.T) {
|
||||
@@ -37,6 +40,126 @@ func TestRunListIncludesHistoryBeyondFiftyForSearchAndPipelineScope(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTitleStorageMigrationAndFallback proves the three title contracts: an
|
||||
// explicit title is kept verbatim, an absent one is derived bounded and
|
||||
// non-empty, and runs created before the title columns survive the migration and
|
||||
// still list.
|
||||
func TestRunTitleStorageMigrationAndFallback(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "titles.db")
|
||||
store, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Submit(ctx, "titled", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
definition, _ := store.Get(ctx, items[0].ID, 1)
|
||||
|
||||
explicit, _, err := store.CreateRunTitled(ctx, definition, "explicit", "workspace", false, nil,
|
||||
map[string]any{"prompt": "a prompt that must not become the title"},
|
||||
summarise.Title{Text: "Fix the flaky login test", Source: summarise.SourceModel, Model: "openai/gpt"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := store.GetRun(ctx, explicit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Title != "Fix the flaky login test" || got.TitleSource != summarise.SourceModel || got.TitleModel != "openai/gpt" {
|
||||
t.Fatalf("explicit title not kept verbatim with its provenance: %+v", got)
|
||||
}
|
||||
|
||||
derived, _, err := store.CreateRun(ctx, definition, "derived", "workspace", false, nil,
|
||||
map[string]any{"prompt": strings.Repeat("é", 500) + "\nsecond line is ignored"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = store.GetRun(ctx, derived)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Title == "" || got.TitleSource != summarise.SourceFallback || got.TitleModel != "" {
|
||||
t.Fatalf("derived title = %+v, want a non-empty fallback with no model", got)
|
||||
}
|
||||
if len([]rune(got.Title)) > summarise.TitleCap {
|
||||
t.Fatalf("derived title has %d runes, want <= %d", len([]rune(got.Title)), summarise.TitleCap)
|
||||
}
|
||||
|
||||
// Simulate a database created before run titles by removing the columns, then
|
||||
// reopen: existing rows must survive the re-add migration and still list.
|
||||
for _, column := range []string{"title", "title_source", "title_model"} {
|
||||
if _, err := store.db.ExecContext(ctx, "ALTER TABLE pipeline_runs DROP COLUMN "+column); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
runs, err := store.ListRuns(ctx)
|
||||
if err != nil {
|
||||
t.Fatal("legacy runs did not survive the title migration", err)
|
||||
}
|
||||
ids := map[int64]bool{}
|
||||
for _, run := range runs {
|
||||
ids[run.ID] = true
|
||||
}
|
||||
if !ids[explicit] || !ids[derived] {
|
||||
t.Fatalf("migrated run list lost history: %+v", runs)
|
||||
}
|
||||
migrated, err := store.GetRun(ctx, explicit)
|
||||
if err != nil || migrated.Title != "" || migrated.TitleSource != "" || migrated.TitleModel != "" {
|
||||
t.Fatalf("migrated row should keep a valid empty title: %+v %v", migrated, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetRunTitleRenamesWithoutTouchingInput proves an after-the-fact rename
|
||||
// replaces the stored title and its provenance and leaves the run's input,
|
||||
// status and steps untouched; an unknown run is reported, not silently ignored.
|
||||
func TestSetRunTitleRenamesWithoutTouchingInput(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "rename.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "rename", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
definition, _ := store.Get(ctx, items[0].ID, 1)
|
||||
id, _, err := store.CreateRun(ctx, definition, "rename-key", "workspace", false, nil, map[string]any{"prompt": "original derived prompt"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetRunTitle(ctx, id, summarise.Title{Text: "Investigate the regression", Source: summarise.SourceExplicit}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Title != "Investigate the regression" || after.TitleSource != summarise.SourceExplicit || after.TitleModel != "" {
|
||||
t.Fatalf("rename = %+v, want the explicit title and provenance", after)
|
||||
}
|
||||
if after.Status != before.Status || !reflect.DeepEqual(after.Input, before.Input) || len(after.Steps) != len(before.Steps) {
|
||||
t.Fatalf("rename changed run state: before %+v after %+v", before, after)
|
||||
}
|
||||
if err := store.SetRunTitle(ctx, id+999, summarise.Title{Text: "ghost", Source: summarise.SourceExplicit}); err == nil {
|
||||
t.Fatal("renaming an unknown run succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRecoveryAndVersionPinning(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "audit.db")
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// storeWithRun submits one pipeline and creates one run for verdict tests.
|
||||
func storeWithRun(t *testing.T, name string) (*Store, context.Context, int64) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), name+".db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Submit(ctx, name, Template([]string{"one", "two"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
definition, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, _, err := store.CreateRun(ctx, definition, name, "workspace", false, nil, map[string]any{"prompt": "task"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, ctx, id
|
||||
}
|
||||
|
||||
// TestStageVerdictStoredLineAndReadTimeFallback proves a model-generated line is
|
||||
// stored with its provenance and read back verbatim, while a step finished
|
||||
// without one gets a bounded reason derived at read time from its own output (the
|
||||
// existing-run/no-backfill path).
|
||||
func TestStageVerdictStoredLineAndReadTimeFallback(t *testing.T) {
|
||||
store, ctx, id := storeWithRun(t, "verdict")
|
||||
defer store.Close()
|
||||
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{
|
||||
Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two",
|
||||
Output: map[string]any{"summary": "read-time text must lose to the stored line"},
|
||||
Verdict: &protocol.StageVerdict{Reason: "the model line", ReasonSource: protocol.VerdictReasonModel},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 2, "two", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{
|
||||
Sequence: 2, Stage: "two", Status: "completed", Outcome: "success", Target: "#success",
|
||||
Output: map[string]any{"summary": "derived at read time"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(detail.Steps) != 2 {
|
||||
t.Fatalf("got %d steps", len(detail.Steps))
|
||||
}
|
||||
stored := detail.Steps[0].Verdict
|
||||
if stored == nil || stored.Reason != "the model line" || stored.ReasonSource != protocol.VerdictReasonModel ||
|
||||
stored.Option != "success → two" {
|
||||
t.Fatalf("stored verdict = %+v", stored)
|
||||
}
|
||||
fallback := detail.Steps[1].Verdict
|
||||
if fallback == nil || fallback.Reason != "derived at read time" ||
|
||||
fallback.ReasonSource != protocol.VerdictReasonFallback || fallback.Option != "success → success" {
|
||||
t.Fatalf("read-time verdict = %+v", fallback)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStageVerdictMatchingUsesRecordedArtifacts proves the store derives the
|
||||
// referenced artifacts from the artifacts it recorded for the same visit, by
|
||||
// reason text and by screenshots, and never exposes an unrecorded name.
|
||||
func TestStageVerdictMatchingUsesRecordedArtifacts(t *testing.T) {
|
||||
store, ctx, id := storeWithRun(t, "verdict-artifacts")
|
||||
defer store.Close()
|
||||
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{
|
||||
Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two",
|
||||
Output: map[string]any{"summary": "reviewed captures/shot.png and verified it"},
|
||||
Artifacts: []protocol.StageArtifact{{Name: "captures/shot.png"}, {Name: "unrelated.log"}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 2, "two", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{
|
||||
Sequence: 2, Stage: "two", Status: "completed", Outcome: "success", Target: "#success",
|
||||
Output: map[string]any{"summary": "no recorded name here", "screenshots": []any{"captures/shot.png"}},
|
||||
Artifacts: []protocol.StageArtifact{{Name: "captures/shot.png"}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := detail.Steps[0].Verdict.Artifacts; len(got) != 1 || got[0] != "captures/shot.png" {
|
||||
t.Fatalf("reason-referenced artifacts = %v, want only the recorded capture", got)
|
||||
}
|
||||
if got := detail.Steps[1].Verdict.Artifacts; len(got) != 1 || got[0] != "captures/shot.png" {
|
||||
t.Fatalf("screenshot-referenced artifacts = %v, want only the recorded capture", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStageVerdictAbsentAndNoArtifacts proves a running step has no verdict and a
|
||||
// completed step with no recorded artifacts keeps Option and Reason but an empty
|
||||
// artifact list.
|
||||
func TestStageVerdictAbsentAndNoArtifacts(t *testing.T) {
|
||||
store, ctx, id := storeWithRun(t, "verdict-absent")
|
||||
defer store.Close()
|
||||
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Still running: no outcome/target, so no verdict.
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Steps[0].Verdict != nil {
|
||||
t.Fatalf("running step verdict = %+v, want nil", detail.Steps[0].Verdict)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{
|
||||
Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "#success",
|
||||
Output: map[string]any{"summary": "done", "extra": "x"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err = store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verdict := detail.Steps[0].Verdict
|
||||
if verdict == nil || verdict.Reason != "done" || verdict.ReasonSource != protocol.VerdictReasonFallback || len(verdict.Artifacts) != 0 {
|
||||
t.Fatalf("no-artifact verdict = %+v", verdict)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStageVerdictStoreUpgrade proves a database created before step_verdicts
|
||||
// exists opens cleanly, gains the table on init, and still lists and loads runs
|
||||
// and steps.
|
||||
func TestStageVerdictStoreUpgrade(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "upgrade.db")
|
||||
store, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Submit(ctx, "upgrade", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
definition, _ := store.Get(ctx, items[0].ID, 1)
|
||||
id, _, err := store.CreateRun(ctx, definition, "upgrade", "workspace", false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{
|
||||
Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "#success",
|
||||
Output: map[string]any{"summary": "legacy output"},
|
||||
Verdict: &protocol.StageVerdict{Reason: "generated before the upgrade", ReasonSource: protocol.VerdictReasonModel},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Simulate a database created before step_verdicts existed.
|
||||
if _, err := store.db.ExecContext(ctx, "DROP TABLE step_verdicts"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal("a pre-verdict database did not open cleanly", err)
|
||||
}
|
||||
defer store.Close()
|
||||
runs, err := store.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 {
|
||||
t.Fatalf("legacy run list lost history: %v %v", runs, err)
|
||||
}
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil || len(detail.Steps) != 1 {
|
||||
t.Fatalf("legacy run/step did not load: %v %v", detail, err)
|
||||
}
|
||||
// The stored line is gone, so the verdict is derived at read time.
|
||||
if verdict := detail.Steps[0].Verdict; verdict == nil || verdict.Reason != "legacy output" || verdict.ReasonSource != protocol.VerdictReasonFallback {
|
||||
t.Fatalf("post-upgrade read-time verdict = %+v", verdict)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user