From dc2c3b983f7e8e96ba474831b51a8cdd4b6b3275 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 9 Nov 2026 12:44:01 +1100 Subject: [PATCH] feat(workflow): a budget continuation resumes at the stopped step with its conversation (#1832) --- internal/agentexec/modelloop/history.go | 45 +++++++++++++++ internal/agentexec/modelloop/loop_runner.go | 2 +- internal/contracts/state/v1/types.pb.go | 19 +++++-- internal/domain/agentrun/history.go | 57 +++++++++++++++++++ internal/domain/agentrun/history_test.go | 46 +++++++++++++++ internal/domain/agentrun/protocol.go | 3 + internal/domain/workflow/agent.go | 42 ++++++++++++-- .../workflow/agent_budget_continue_test.go | 35 +++++++++++- internal/domain/workflow/task/task.go | 3 + internal/domain/workflow/workflow.go | 24 ++++++++ .../migrations/0070_resume_history.sql | 10 ++++ .../postgres/postgresdb/call_tasks.sql.go | 5 +- .../postgres/postgresdb/models.go | 1 + .../postgres/postgresdb/tasks.sql.go | 40 +++++++++---- .../infrastructure/postgres/queries/tasks.sql | 5 +- internal/infrastructure/postgres/store.go | 12 ++++ internal/infrastructure/staterpc/values.go | 4 +- proto/state/v1/types.proto | 3 + 18 files changed, 326 insertions(+), 30 deletions(-) create mode 100644 internal/agentexec/modelloop/history.go create mode 100644 internal/domain/agentrun/history.go create mode 100644 internal/domain/agentrun/history_test.go create mode 100644 internal/infrastructure/postgres/migrations/0070_resume_history.sql diff --git a/internal/agentexec/modelloop/history.go b/internal/agentexec/modelloop/history.go new file mode 100644 index 000000000..b7b10f52d --- /dev/null +++ b/internal/agentexec/modelloop/history.go @@ -0,0 +1,45 @@ +package modelloop + +import ( + "fmt" + "strings" + + "github.com/samcharles93/archie-core/internal/domain/agentrun" +) + +// missionWithHistory puts the conversation of an earlier run of the stage +// ahead of the mission, cut to fit the model's context window. agentloop has no +// field for prior messages, so the conversation goes in the first user message +// as text. +func missionWithHistory(req agentrun.Request) string { + entries := agentrun.BoundHistory(req.History, agentrun.HistoryBytes(req.ContextWindow)) + if len(entries) == 0 { + return req.Mission + } + var b strings.Builder + b.WriteString("\nAn earlier run of this stage stopped at its step budget and was approved to continue. " + + "Its conversation follows and its edits are already in the worktree. Continue from where it stopped; do not start over.\n\n") + for _, e := range entries { + switch e.Kind { + case agentrun.TranscriptModel: + if e.Text != "" { + fmt.Fprintf(&b, "[you] %s\n", e.Text) + } + for _, call := range e.ToolCalls { + fmt.Fprintf(&b, "[you called %s] %s\n", call.Name, call.Args) + } + case agentrun.TranscriptTool: + if e.Error != "" { + fmt.Fprintf(&b, "[%s failed] %s\n", e.Tool, e.Error) + } else { + fmt.Fprintf(&b, "[%s returned] %s\n", e.Tool, e.Output) + } + case agentrun.TranscriptUser: + fmt.Fprintf(&b, "[feedback] %s\n", e.Text) + case agentrun.TranscriptCompaction: + fmt.Fprintf(&b, "[summary of earlier steps] %s\n", e.Text) + } + } + b.WriteString("\n\n") + return b.String() + req.Mission +} diff --git a/internal/agentexec/modelloop/loop_runner.go b/internal/agentexec/modelloop/loop_runner.go index 4eaecb4fa..227ae5feb 100644 --- a/internal/agentexec/modelloop/loop_runner.go +++ b/internal/agentexec/modelloop/loop_runner.go @@ -85,7 +85,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req WorkDir: workspace, MaxParallelToolCalls: MaxParallelToolCalls, - Mission: req.Mission, + Mission: missionWithHistory(req), ExtraRules: agentexec.ProjectScopedRules(workspace, req.ExtraRules), Notes: notes, Gate: toAgentGate(req.Gate), diff --git a/internal/contracts/state/v1/types.pb.go b/internal/contracts/state/v1/types.pb.go index a1fb43b99..0fe0962d8 100644 --- a/internal/contracts/state/v1/types.pb.go +++ b/internal/contracts/state/v1/types.pb.go @@ -234,8 +234,11 @@ type Task struct { HandoffFromTaskId int64 `protobuf:"varint,51,opt,name=handoff_from_task_id,json=handoffFromTaskId,proto3" json:"handoff_from_task_id,omitempty"` // handoff_to_task_id is the run this one handed off to; 0 when none. HandoffToTaskId int64 `protobuf:"varint,52,opt,name=handoff_to_task_id,json=handoffToTaskId,proto3" json:"handoff_to_task_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // resume_history is the conversation (JSON) of a stage that stopped on its + // step budget, which the continuation starts from. + ResumeHistory []byte `protobuf:"bytes,53,opt,name=resume_history,json=resumeHistory,proto3" json:"resume_history,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Task) Reset() { @@ -626,6 +629,13 @@ func (x *Task) GetHandoffToTaskId() int64 { return 0 } +func (x *Task) GetResumeHistory() []byte { + if x != nil { + return x.ResumeHistory + } + return nil +} + // Event mirrors internal/events.Event. Data is carried as a JSON object // string (matching the store's own on-disk representation) rather than // google.protobuf.Struct, to stay a direct mirror of the existing column. @@ -802,7 +812,7 @@ const file_state_v1_types_proto_rawDesc = "" + "\n" + "created_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" + "\n" + - "updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\xef\r\n" + + "updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\x96\x0e\n" + "\x04Task\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" + "\x05owner\x18\x02 \x01(\tR\x05owner\x12\x12\n" + @@ -869,7 +879,8 @@ const file_state_v1_types_proto_rawDesc = "" + "\fpark_blocker\x180 \x01(\tR\vparkBlocker\x12#\n" + "\rplan_document\x182 \x01(\tR\fplanDocument\x12/\n" + "\x14handoff_from_task_id\x183 \x01(\x03R\x11handoffFromTaskId\x12+\n" + - "\x12handoff_to_task_id\x184 \x01(\x03R\x0fhandoffToTaskIdJ\x04\b1\x102R\tplan_view\"\xf8\x02\n" + + "\x12handoff_to_task_id\x184 \x01(\x03R\x0fhandoffToTaskId\x12%\n" + + "\x0eresume_history\x185 \x01(\fR\rresumeHistoryJ\x04\b1\x102R\tplan_view\"\xf8\x02\n" + "\x05Event\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" + "\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" + diff --git a/internal/domain/agentrun/history.go b/internal/domain/agentrun/history.go new file mode 100644 index 000000000..6dcdc13ac --- /dev/null +++ b/internal/domain/agentrun/history.go @@ -0,0 +1,57 @@ +package agentrun + +// droppedOutput replaces a tool output cut to fit a history bound. +const droppedOutput = "[output dropped to fit the context window]" + +// historySize is what an entry contributes to a history's size, in bytes. +func historySize(e TranscriptEntry) int { + n := len(e.Text) + len(e.Output) + len(e.Error) + len(e.Args) + for _, call := range e.ToolCalls { + n += len(call.Name) + len(call.Args) + } + return n +} + +// BoundHistory returns entries cut to at most maxBytes: the system prompt and +// the run's first user message are left out because a continuation sends its +// own, then the oldest tool outputs are dropped, then the oldest entries. The +// input is not modified. +func BoundHistory(entries []TranscriptEntry, maxBytes int) []TranscriptEntry { + out := make([]TranscriptEntry, 0, len(entries)) + seenUser := false + total := 0 + for _, e := range entries { + switch { + case e.Kind == TranscriptSystem: + continue + case e.Kind == TranscriptUser && !seenUser: + seenUser = true + continue + } + out = append(out, e) + total += historySize(e) + } + for i := 0; i < len(out) && total > maxBytes; i++ { + if out[i].Kind != TranscriptTool || len(out[i].Output) <= len(droppedOutput) { + continue + } + total -= len(out[i].Output) - len(droppedOutput) + out[i].Output = droppedOutput + } + drop := 0 + for drop < len(out) && total > maxBytes { + total -= historySize(out[drop]) + drop++ + } + return out[drop:] +} + +// HistoryBytes is the size budget for a history sent to a model with the given +// context window in tokens: a third of the window at about four bytes a token. +// A zero window is the persistence bound. +func HistoryBytes(contextWindow int) int { + if contextWindow <= 0 { + return 256 << 10 + } + return contextWindow * 4 / 3 +} diff --git a/internal/domain/agentrun/history_test.go b/internal/domain/agentrun/history_test.go new file mode 100644 index 000000000..10440a6a0 --- /dev/null +++ b/internal/domain/agentrun/history_test.go @@ -0,0 +1,46 @@ +package agentrun + +import ( + "strings" + "testing" +) + +func TestBoundHistory(t *testing.T) { + entries := []TranscriptEntry{ + {Kind: TranscriptSystem, Text: "system"}, + {Kind: TranscriptUser, Text: "mission"}, + {Kind: TranscriptTool, Tool: "read", Output: strings.Repeat("a", 1000)}, + {Kind: TranscriptTool, Tool: "read", Output: strings.Repeat("b", 1000)}, + {Kind: TranscriptModel, Text: "newest"}, + } + tests := []struct { + name string + max int + wantTools []string + wantLen int + }{ + {name: "fits", max: 1 << 20, wantTools: []string{strings.Repeat("a", 1000), strings.Repeat("b", 1000)}, wantLen: 3}, + {name: "oldest output dropped first", max: 1100, wantTools: []string{droppedOutput, strings.Repeat("b", 1000)}, wantLen: 3}, + {name: "then oldest entries", max: 10, wantLen: 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := BoundHistory(entries, tt.max) + if len(got) != tt.wantLen || got[len(got)-1].Text != "newest" { + t.Fatalf("got %d entries %+v, want %d ending in the newest", len(got), got, tt.wantLen) + } + var tools []string + for _, e := range got { + if e.Kind == TranscriptTool { + tools = append(tools, e.Output) + } + } + if strings.Join(tools, "|") != strings.Join(tt.wantTools, "|") { + t.Errorf("tool outputs = %v, want %v", tools, tt.wantTools) + } + }) + } + if entries[2].Output != strings.Repeat("a", 1000) { + t.Error("input was modified") + } +} diff --git a/internal/domain/agentrun/protocol.go b/internal/domain/agentrun/protocol.go index b7603e60b..f6b1ff20e 100644 --- a/internal/domain/agentrun/protocol.go +++ b/internal/domain/agentrun/protocol.go @@ -78,6 +78,9 @@ type Request struct { Protection Protection `json:"protection"` Notes string `json:"notes,omitempty"` CaptureTools []CaptureTool `json:"capture_tools,omitempty"` + // History is the conversation of an earlier run of this stage that stopped + // on its step budget; the run continues from it. + History []TranscriptEntry `json:"history,omitempty"` // Harness, when set, runs the stage on an external coding-agent CLI // instead of the built-in loop. The worker in a Kit container is the // daemon's own archie-agent build, so it always understands this field. diff --git a/internal/domain/workflow/agent.go b/internal/domain/workflow/agent.go index 150de32c7..bc4344998 100644 --- a/internal/domain/workflow/agent.go +++ b/internal/domain/workflow/agent.go @@ -2,9 +2,11 @@ package workflow import ( "context" + "encoding/json" "fmt" "os" "path/filepath" + "slices" "strings" "github.com/samcharles93/archie-core/internal/config" @@ -74,8 +76,16 @@ func (a AgentStage) Stage() Stage { } // The agent call is a child of the stage's recorded step: the store // says what the stage's runtime did, not just what the stage did. + req.History = tc.takeHistory(a.Name) + tc.transcript = slices.Clone(req.History) res, runErr := tc.RunAgentChild(ctx, a.Name, a.Model, modelRef, func() (agentrun.Result, error) { - return tc.Agent.Run(ctx, tc.Dir, req, tc.reporter(ctx, a.Name)) + report := tc.reporter(ctx, a.Name) + persist := report.Transcript + report.Transcript = func(entry agentrun.TranscriptEntry) { + tc.transcript = append(tc.transcript, entry) + persist(entry) + } + return tc.Agent.Run(ctx, tc.Dir, req, report) }) return a.handleResult(ctx, tc, req, res, runErr, modelRef) }} @@ -261,9 +271,9 @@ func budgetStopOutcome(stage string, res agentrun.Result) Outcome { } // awaitBudgetApproval waits for a decision on running the stage again. The -// worktree is kept as it stands and the stage's findings and changed files go -// to the next run as task notes, which stand in for the transcript: the run -// resumes from what is on disk, not from the model's message history. +// worktree is kept as it stands, the stage's findings and changed files go to +// the next run as task notes, and its conversation is kept for the run to +// continue from. The run loop records where the workflow resumes. func awaitBudgetApproval(tc *TaskContext, stage string, res agentrun.Result) { note := fmt.Sprintf("Stage %s stopped on its step budget and was approved to continue. The worktree holds its work so far; carry on from it.", stage) if summary := strings.TrimSpace(res.Summary); summary != "" { @@ -274,6 +284,7 @@ func awaitBudgetApproval(tc *TaskContext, stage string, res agentrun.Result) { } tc.Task.Notes += "- " + note + "\n" tc.Task.RetryMode = string(taskstate.RetryKeepWorktree) + tc.Task.ResumeHistory = encodeHistory(stage, agentrun.BoundHistory(tc.transcript, agentrun.HistoryBytes(0))) detail := budgetStopOutcome(stage, res).Detail tc.Outcome = Outcome{Status: StatusWaitingApproval, Detail: clip(detail+"\n\nApprove to continue with another full step budget, or reject to stop.", 4000)} } @@ -394,3 +405,26 @@ func loadSkillBody(tc *TaskContext) string { body = strings.TrimSpace(body) return body } + +// stageHistory is the conversation a budget-stopped stage leaves for its +// continuation, as persisted on the task. +type stageHistory struct { + Stage string `json:"stage"` + Entries []agentrun.TranscriptEntry `json:"entries"` +} + +func encodeHistory(stage string, entries []agentrun.TranscriptEntry) json.RawMessage { + // Transcript entries hold strings and numbers, which always marshal. + encoded, _ := json.Marshal(stageHistory{Stage: stage, Entries: entries}) + return encoded +} + +// takeHistory hands the stage the conversation its earlier run left, once. +func (tc *TaskContext) takeHistory(stage string) []agentrun.TranscriptEntry { + if tc.resumeHistory.Stage != stage { + return nil + } + entries := tc.resumeHistory.Entries + tc.resumeHistory = stageHistory{} + return entries +} diff --git a/internal/domain/workflow/agent_budget_continue_test.go b/internal/domain/workflow/agent_budget_continue_test.go index ebeef9b24..80fa1dda4 100644 --- a/internal/domain/workflow/agent_budget_continue_test.go +++ b/internal/domain/workflow/agent_budget_continue_test.go @@ -2,6 +2,7 @@ package workflow import ( "context" + "fmt" "log/slog" "strings" "testing" @@ -12,10 +13,17 @@ import ( "github.com/samcharles93/archie-core/internal/taskstate" ) -// sequenceRunner answers each agent run with the next result. -type sequenceRunner struct{ results []agentrun.Result } +// sequenceRunner answers each agent run with the next result, after the +// conversation entries it reports, and keeps the requests it was given. +type sequenceRunner struct { + results []agentrun.Result + requests []agentrun.Request +} -func (s *sequenceRunner) Run(context.Context, string, agentrun.Request, agentrun.Reporter) (agentrun.Result, error) { +func (s *sequenceRunner) Run(_ context.Context, _ string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) { + s.requests = append(s.requests, req) + report.ReportTranscript(agentrun.TranscriptEntry{Kind: agentrun.TranscriptUser, Text: "the mission"}) + report.ReportTranscript(agentrun.TranscriptEntry{Kind: agentrun.TranscriptTool, Tool: "read", Output: fmt.Sprintf("run %d output", len(s.requests))}) res := s.results[0] s.results = s.results[1:] return res, nil @@ -54,7 +62,9 @@ func TestBudgetStopAsksToContinue(t *testing.T) { Cfg: config.Config{Models: map[string]string{"default": "test/model"}}, } } + setups := 0 wf := Workflow{Name: "implement", Stages: []Stage{ + {Name: "setup", Run: func(context.Context, *TaskContext) error { setups++; return nil }}, AgentStage{Name: "build", ApproveBudget: tt.approve, Mission: func(*TaskContext) string { return "do it" }}.Stage(), }} @@ -70,6 +80,9 @@ func TestBudgetStopAsksToContinue(t *testing.T) { if !tt.wantKeep { return } + if tk.ResumeFrom != "build" { + t.Errorf("resume point = %q, want the stopped step", tk.ResumeFrom) + } if kind := taskstate.ApprovalKind(StatusWaitingApproval, "", tk.RetryMode); kind != taskstate.ApprovalBudget { t.Errorf("approval kind = %q, want %q", kind, taskstate.ApprovalBudget) } @@ -84,6 +97,22 @@ func TestBudgetStopAsksToContinue(t *testing.T) { if tc.Outcome.Status != StatusCompleted { t.Errorf("continued outcome = %q, want %q", tc.Outcome.Status, StatusCompleted) } + if setups != 1 { + t.Errorf("setup ran %d times, want once: the continuation skips completed steps", setups) + } + if tk.ResumeFrom != "" || len(tk.ResumeHistory) != 0 { + t.Errorf("resume point %q and history survive the continuation", tk.ResumeFrom) + } + if len(runner.requests) != 2 { + t.Fatalf("agent ran %d times, want 2", len(runner.requests)) + } + if first := runner.requests[0].History; len(first) != 0 { + t.Errorf("first run got history %v", first) + } + history := runner.requests[1].History + if len(history) != 1 || history[0].Output != "run 1 output" { + t.Errorf("continued run history = %+v, want the stopped run's tool output without its mission", history) + } }) } } diff --git a/internal/domain/workflow/task/task.go b/internal/domain/workflow/task/task.go index c4960cbf8..a8401925f 100644 --- a/internal/domain/workflow/task/task.go +++ b/internal/domain/workflow/task/task.go @@ -71,6 +71,9 @@ type Task struct { // with, so steps it skips still answer their references. ResumeFrom string `json:"resume_from,omitempty"` ResumeResults json.RawMessage `json:"resume_results,omitempty"` + // ResumeHistory is the conversation of the stage that stopped on its step + // budget (JSON); the continuation of that stage starts from it. + ResumeHistory json.RawMessage `json:"resume_history,omitempty"` // WatchCommentID is the poll backstop's high-water mark over forge // review-comment IDs for this task (pr-review-remediation.md decision // 2's persisted per-task cursor; the comment-watch design it was diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 30ad80c2f..41e5594e0 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -89,6 +89,10 @@ type TaskContext struct { // stepResults holds each finished step's, by step id. stepResult StepResult stepResults map[string]StepResult + // transcript is the conversation of the agent run in progress, and + // resumeHistory the one a budget stop left for the stage it continues. + transcript []agentrun.TranscriptEntry + resumeHistory stageHistory // skippedWhen is the when condition that skipped the stage whose body just // ran; empty when the stage ran. wrapStep sets it and the engine reads it // to record the step as skipped. It is per-attempt scratch state, reset by @@ -475,6 +479,9 @@ func (tc *TaskContext) resumeStages(stages []Stage) ([]Stage, error) { if from == "" { return stages, nil } + // The point is consumed: a run that stops again records its own, and a + // plain requeue after this one starts from the first step. + defer func() { tc.Task.ResumeFrom, tc.Task.ResumeResults, tc.Task.ResumeHistory = "", nil, nil }() at := slices.IndexFunc(stages, func(s Stage) bool { return s.Name == from }) if at < 0 { return nil, fmt.Errorf("resume point %q is not a step of this workflow", from) @@ -484,6 +491,11 @@ func (tc *TaskContext) resumeStages(stages []Stage) ([]Stage, error) { return nil, fmt.Errorf("resume results: %w", err) } } + if len(tc.Task.ResumeHistory) > 0 { + if err := json.Unmarshal(tc.Task.ResumeHistory, &tc.resumeHistory); err != nil { + return nil, fmt.Errorf("resume history: %w", err) + } + } tc.Log.Info("resuming", "from", from, "skipped", at) return stages[at:], nil } @@ -503,12 +515,24 @@ func endsRun(ctx context.Context, tc *TaskContext, stage Stage, err error, log, return true } if tc.Outcome.Status != "" { + tc.recordBudgetResume(stage) finish(ctx, tc, log) return true } return false } +// recordBudgetResume marks the stage a budget stop is waiting on approval to +// run again as the resume point, with the results of the steps before it. +func (tc *TaskContext) recordBudgetResume(stage Stage) { + if tc.Outcome.Status != StatusWaitingApproval || taskstate.NormalizeRetryMode(tc.Task.RetryMode) != taskstate.RetryKeepWorktree { + return + } + // StepResult holds strings and decoded JSON values, which always marshal. + results, _ := json.Marshal(tc.stepResults) + tc.Task.ResumeFrom, tc.Task.ResumeResults = stage.Name, results +} + // publishEvent puts an already-persisted event on the run's bus after its // write committed: the assigned ID is what the daemon's event sink reads to // skip the second insert, the same convention EmitDurable established. diff --git a/internal/infrastructure/postgres/migrations/0070_resume_history.sql b/internal/infrastructure/postgres/migrations/0070_resume_history.sql new file mode 100644 index 000000000..4ef406cbf --- /dev/null +++ b/internal/infrastructure/postgres/migrations/0070_resume_history.sql @@ -0,0 +1,10 @@ +-- tasks.resume_history is the conversation of a stage that stopped on its step +-- budget, kept so the continuation after approval starts from it. + +-- +goose Up + +ALTER TABLE tasks ADD COLUMN resume_history jsonb NOT NULL DEFAULT 'null'; + +-- +goose Down + +ALTER TABLE tasks DROP COLUMN resume_history; diff --git a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go index 1fb643d6a..12a71a357 100644 --- a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go @@ -24,7 +24,7 @@ func (q *Queries) CallStatusDetail(ctx context.Context, taskID int64) (string, e const enqueueCallTask = `-- name: EnqueueCallTask :one WITH caller AS ( - SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin, t.call_key, t.binding_signature, t.binding_addr, t.park_blocker, t.outcome_posted_status, t.plan_document, t.handoff_from_task_id, t.handoff_to_task_id FROM tasks t WHERE t.id = $1 FOR UPDATE + SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin, t.call_key, t.binding_signature, t.binding_addr, t.park_blocker, t.outcome_posted_status, t.plan_document, t.handoff_from_task_id, t.handoff_to_task_id, t.resume_history FROM tasks t WHERE t.id = $1 FOR UPDATE ), number AS ( INSERT INTO chat_issue_numbers (owner, repo, last_number) SELECT caller.owner, caller.repo, $9::bigint + 1 FROM caller @@ -43,7 +43,7 @@ SELECT FROM caller, number WHERE caller.status = 'running' AND caller.call_depth + 1 <= $8::int ON CONFLICT (call_parent_task_id, call_key) WHERE call_key <> '' AND status NOT IN ('dead', 'closed_wont_do') DO UPDATE SET call_key = EXCLUDED.call_key -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history ` type EnqueueCallTaskParams struct { @@ -139,6 +139,7 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } diff --git a/internal/infrastructure/postgres/postgresdb/models.go b/internal/infrastructure/postgres/postgresdb/models.go index bbf5708d3..5742c2d9c 100644 --- a/internal/infrastructure/postgres/postgresdb/models.go +++ b/internal/infrastructure/postgres/postgresdb/models.go @@ -586,6 +586,7 @@ type Task struct { PlanDocument string HandoffFromTaskID pgtype.Int8 HandoffToTaskID pgtype.Int8 + ResumeHistory []byte } type ToolCall struct { diff --git a/internal/infrastructure/postgres/postgresdb/tasks.sql.go b/internal/infrastructure/postgres/postgresdb/tasks.sql.go index 2cc95a2c3..d2e9dbc02 100644 --- a/internal/infrastructure/postgres/postgresdb/tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/tasks.sql.go @@ -13,7 +13,7 @@ import ( ) const activeTasksByOrigin = `-- name: ActiveTasksByOrigin :many -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history FROM tasks WHERE origin = $1 AND origin <> '' AND status IN ('queued', 'running') AND ($2::text IS NULL OR org_id = $2) ORDER BY id ` @@ -87,6 +87,7 @@ func (q *Queries) ActiveTasksByOrigin(ctx context.Context, arg ActiveTasksByOrig &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ); err != nil { return nil, err } @@ -166,7 +167,7 @@ func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediation const claimByIssue = `-- name: ClaimByIssue :one UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now() WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued' -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history ` type ClaimByIssueParams struct { @@ -234,6 +235,7 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } @@ -248,7 +250,7 @@ WHERE id = ( FOR UPDATE SKIP LOCKED LIMIT 1 ) -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history ` // FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two @@ -314,6 +316,7 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) { &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } @@ -433,7 +436,7 @@ FROM number, (SELECT COALESCE( 'org-sys' ) AS id) AS owner_org WHERE $11::text IS NULL OR owner_org.id = $11 -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history ` type InsertChatTaskParams struct { @@ -533,6 +536,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } @@ -545,7 +549,7 @@ SELECT $1, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, $2, t.sou t.org_id, t.workspace_id, t.inputs, t.plan, t.plan_document, t.binding_id, t.binding_version, t.binding_signature, t.binding_addr, t.origin, t.call_parent_task_id, t.call_depth, t.id FROM tasks t WHERE t.id = $3 -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history ` type InsertHandoffTaskParams struct { @@ -613,6 +617,7 @@ func (q *Queries) InsertHandoffTask(ctx context.Context, arg InsertHandoffTaskPa &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } @@ -1040,7 +1045,7 @@ const retryTask = `-- name: RetryTask :execrows UPDATE tasks SET status = 'queued', retry_count = retry_count + 1, workflow = CASE WHEN $1::text = '' THEN workflow ELSE $1::text END, retry_mode = $2::text, - resume_from = $3::text, resume_results = $4::jsonb, + resume_from = $3::text, resume_results = $4::jsonb, resume_history = 'null', workflow_definition_yaml = CASE WHEN $5::bool THEN '' ELSE workflow_definition_yaml END, workflow_definition_digest = CASE WHEN $5::bool THEN '' ELSE workflow_definition_digest END, workflow_definition_version = CASE WHEN $5::bool THEN 0 ELSE workflow_definition_version END, @@ -1137,7 +1142,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara } const taskByID = `-- name: TaskByID :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks WHERE id = $1 AND ($2::text IS NULL OR org_id = $2) +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history FROM tasks WHERE id = $1 AND ($2::text IS NULL OR org_id = $2) ` type TaskByIDParams struct { @@ -1202,12 +1207,13 @@ func (q *Queries) TaskByID(ctx context.Context, arg TaskByIDParams) (Task, error &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } const taskByIssue = `-- name: TaskByIssue :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND handoff_to_task_id IS NULL +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND handoff_to_task_id IS NULL AND ($4::text IS NULL OR org_id = $4) ` @@ -1280,12 +1286,13 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } const taskByPR = `-- name: TaskByPR :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 AND ($5::text IS NULL OR org_id = $5) ` @@ -1363,6 +1370,7 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ) return i, err } @@ -1415,7 +1423,7 @@ func (q *Queries) TransitionTask(ctx context.Context, arg TransitionTaskParams) } const unpostedOutcomes = `-- name: UnpostedOutcomes :many -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id FROM tasks +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history FROM tasks WHERE origin <> '' AND outcome_posted_status <> status AND status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed', 'waiting_approval', 'pr_open') AND handoff_to_task_id IS NULL @@ -1489,6 +1497,7 @@ func (q *Queries) UnpostedOutcomes(ctx context.Context, scopeOrg pgtype.Text) ([ &i.PlanDocument, &i.HandoffFromTaskID, &i.HandoffToTaskID, + &i.ResumeHistory, ); err != nil { return nil, err } @@ -1509,8 +1518,9 @@ UPDATE tasks SET workflow = $1, branch = $2, plan = $3, plan_document = $4, note workflow_definition_digest = CASE WHEN $14::text = '' THEN workflow_definition_digest ELSE $16 END, workflow_definition_yaml = CASE WHEN $14::text = '' THEN workflow_definition_yaml ELSE $14::text END, outputs = $17, review_gate = $18, rereview_rounds = $19, - retry_mode = $20, updated_at = now() -WHERE id = $21 + retry_mode = $20, resume_from = $21::text, resume_results = $22::jsonb, + resume_history = $23::jsonb, updated_at = now() +WHERE id = $24 ` type UpdateTaskParams struct { @@ -1534,6 +1544,9 @@ type UpdateTaskParams struct { ReviewGate string RereviewRounds int64 RetryMode string + ResumeFrom string + ResumeResults []byte + ResumeHistory []byte ID int64 } @@ -1561,6 +1574,9 @@ func (q *Queries) UpdateTask(ctx context.Context, arg UpdateTaskParams) error { arg.ReviewGate, arg.RereviewRounds, arg.RetryMode, + arg.ResumeFrom, + arg.ResumeResults, + arg.ResumeHistory, arg.ID, ) return err diff --git a/internal/infrastructure/postgres/queries/tasks.sql b/internal/infrastructure/postgres/queries/tasks.sql index 8a6c38583..bb85c1768 100644 --- a/internal/infrastructure/postgres/queries/tasks.sql +++ b/internal/infrastructure/postgres/queries/tasks.sql @@ -141,7 +141,8 @@ UPDATE tasks SET workflow = @workflow, branch = @branch, plan = @plan, plan_docu workflow_definition_digest = CASE WHEN @workflow_definition_yaml::text = '' THEN workflow_definition_digest ELSE @workflow_definition_digest END, workflow_definition_yaml = CASE WHEN @workflow_definition_yaml::text = '' THEN workflow_definition_yaml ELSE @workflow_definition_yaml::text END, outputs = @outputs, review_gate = @review_gate, rereview_rounds = @rereview_rounds, - retry_mode = @retry_mode, updated_at = now() + retry_mode = @retry_mode, resume_from = @resume_from::text, resume_results = @resume_results::jsonb, + resume_history = @resume_history::jsonb, updated_at = now() WHERE id = @id; -- name: RereviewRounds :one @@ -271,7 +272,7 @@ WHERE id = @id AND status = @from_status; UPDATE tasks SET status = 'queued', retry_count = retry_count + 1, workflow = CASE WHEN @workflow::text = '' THEN workflow ELSE @workflow::text END, retry_mode = @retry_mode::text, - resume_from = @resume_from::text, resume_results = @resume_results::jsonb, + resume_from = @resume_from::text, resume_results = @resume_results::jsonb, resume_history = 'null', workflow_definition_yaml = CASE WHEN @current_definition::bool THEN '' ELSE workflow_definition_yaml END, workflow_definition_digest = CASE WHEN @current_definition::bool THEN '' ELSE workflow_definition_digest END, workflow_definition_version = CASE WHEN @current_definition::bool THEN 0 ELSE workflow_definition_version END, diff --git a/internal/infrastructure/postgres/store.go b/internal/infrastructure/postgres/store.go index 7487e9375..ae308d223 100644 --- a/internal/infrastructure/postgres/store.go +++ b/internal/infrastructure/postgres/store.go @@ -105,6 +105,7 @@ func taskFromRow(t postgresdb.Task) *workflow.Task { RetryMode: t.RetryMode, ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults, + ResumeHistory: t.ResumeHistory, WatchCommentID: t.WatchCommentID, ReviewCursor: t.ReviewCursor, Source: t.Source, @@ -394,6 +395,9 @@ func (s *Store) Update(ctx context.Context, t *workflow.Task) error { ReviewGate: t.ReviewGate, RereviewRounds: int64(t.RereviewRounds), RetryMode: t.RetryMode, + ResumeFrom: t.ResumeFrom, + ResumeResults: jsonOr(t.ResumeResults, "{}"), + ResumeHistory: jsonOr(t.ResumeHistory, "null"), WorkflowDefinitionVersion: t.WorkflowDefinitionVersion, WorkflowDefinitionDigest: t.WorkflowDefinitionDigest, WorkflowDefinitionYaml: t.WorkflowDefinitionYAML, @@ -401,6 +405,14 @@ func (s *Store) Update(ctx context.Context, t *workflow.Task) error { }) } +// jsonOr is raw, or fallback when raw is empty: a jsonb column is never NULL. +func jsonOr(raw []byte, fallback string) []byte { + if len(raw) == 0 { + return []byte(fallback) + } + return raw +} + // BeginRemediation queues a remediate run carrying the review unit in the same // guarded write, so a claimed remediation always has its input. When a // remediation already owns the task, the unit is queued behind the run in diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 5932d0dee..1e8e320e7 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -66,7 +66,7 @@ func taskProto(t *task.Task) *pb.Task { // mirror-image field-by-field proto<->d PrNumber: int64(t.PRNumber), TokensUsed: int64(t.TokensUsed), Iterations: int64(t.Iterations), Attempt: int64(t.Attempt), ParkReason: t.ParkReason, RetryCount: int64(t.RetryCount), RetryMode: t.RetryMode, - ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults, + ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults, ResumeHistory: t.ResumeHistory, WatchCommentId: t.WatchCommentID, Source: t.Source, Identity: t.Identity, BindingId: t.BindingID, BindingVersion: int64(t.BindingVersion), InputsJson: inputsJSON(t.Inputs), @@ -105,7 +105,7 @@ func taskValue(t *pb.Task) *task.Task { // see taskProto above PRNumber: int(t.PrNumber), TokensUsed: int(t.TokensUsed), Iterations: int(t.Iterations), Attempt: int(t.Attempt), ParkReason: t.ParkReason, RetryCount: int(t.RetryCount), RetryMode: t.RetryMode, - ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults, + ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults, ResumeHistory: t.ResumeHistory, WatchCommentID: t.WatchCommentId, Source: t.Source, Identity: t.Identity, BindingID: t.BindingId, BindingVersion: int(t.BindingVersion), Inputs: inputsValue(t.InputsJson), diff --git a/proto/state/v1/types.proto b/proto/state/v1/types.proto index 0451b1fdc..e48def7c1 100644 --- a/proto/state/v1/types.proto +++ b/proto/state/v1/types.proto @@ -132,6 +132,9 @@ message Task { int64 handoff_from_task_id = 51; // handoff_to_task_id is the run this one handed off to; 0 when none. int64 handoff_to_task_id = 52; + // resume_history is the conversation (JSON) of a stage that stopped on its + // step budget, which the continuation starts from. + bytes resume_history = 53; } // Event mirrors internal/events.Event. Data is carried as a JSON object // string (matching the store's own on-disk representation) rather than