feat(webui): let the operator choose the retry worktree mode

A retry now carries the operator's worktree choice (refresh onto the base
branch or continue the work already pushed on the task branch) from the
dashboard through the task action to the daemon dispatch, and persists it
on the task row so it survives a reload. The daemon resolves the mode from
the task, never from the workflow; BeginRemediation records continue
explicitly so a remediation still resumes its pull request branch.
This commit is contained in:
sam committed 2026-10-02 10:53:21 +10:00
1 parent ef203ce30a
commit 19520a63e5
58 files changed
+977 -252

No files matched your search

+1 -1
View File
@@ -71,7 +71,7 @@ func (b *boot) setupChatRuntime(ctx context.Context, cfg config.Config) error {
// than its own requeue, so a chat approval and a dashboard approval
// cannot record different decisions for one operator intent
// (docs/prds/pr-review-operator-response.md, Decision 1).
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ReviewResponse) error {
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ActionPayload) error {
return b.taskActions().Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res)
},
cancelExecution: canceller.CancelExecution,
+2 -2
View File
@@ -94,11 +94,11 @@ func (stubGatewayContract) SetPersona(context.Context, string, string) (bool, er
return false, nil
}
func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ReviewResponse) (messaging.TaskActionResult, error) {
func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return messaging.TaskActionResult{}, nil
}
func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse) (messaging.TaskActionResult, error) {
func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return messaging.TaskActionResult{}, nil
}
+3 -3
View File
@@ -570,7 +570,7 @@ func (a chatTaskWriterAdapter) EnqueueChatTask(
type chatTaskControllerAdapter struct {
taskByID func(context.Context, int64) (*workflow.Task, error)
approve func(context.Context, *string, taskactions.Actor, int64, taskactions.ReviewResponse) error
approve func(context.Context, *string, taskactions.Actor, int64, taskactions.ActionPayload) error
cancelExecution func(context.Context, int64, string, string) ([]int64, error)
}
@@ -597,7 +597,7 @@ func (a chatTaskControllerAdapter) ApproveChatTask(ctx context.Context, taskID i
// authority, and /approve carries no selection syntax, so the review gate
// answer posts every offered finding.
scope := string(actor.Identity)
return a.approve(ctx, &scope, actor, taskID, taskactions.ReviewResponse{})
return a.approve(ctx, &scope, actor, taskID, taskactions.ActionPayload{})
}
func (a chatTaskControllerAdapter) CancelChatTask(ctx context.Context, taskID int64, reason string) error {
@@ -702,7 +702,7 @@ type chatTaskActorAdapter struct {
}
func (a chatTaskActorAdapter) ApplyChatTaskAction(
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse,
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ActionPayload,
) (gateway.TaskActionResult, error) {
if a.contract == nil {
return gateway.TaskActionResult{}, gateway.ErrChatCapabilityUnavailable
+3 -3
View File
@@ -734,13 +734,13 @@ func TestChatTaskControllerAdapterTransitions(t *testing.T) {
task := &workflow.Task{ID: 42, Source: workflow.SourceChat, Status: workflow.StatusWaitingHuman}
var approveScope string
var approveActor taskactions.Actor
var approveRes taskactions.ReviewResponse
var approveRes taskactions.ActionPayload
var cancelReason, cancelTo string
adapter := chatTaskControllerAdapter{
taskByID: func(context.Context, int64) (*workflow.Task, error) { return task, nil },
// Chat's approval reaches the daemon's one task-action service, not
// its own requeue: this records what the adapter hands it.
approve: func(_ context.Context, scope *string, actor taskactions.Actor, _ int64, res taskactions.ReviewResponse) error {
approve: func(_ context.Context, scope *string, actor taskactions.Actor, _ int64, res taskactions.ActionPayload) error {
if scope != nil {
approveScope = *scope
}
@@ -916,7 +916,7 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) {
actions := taskactionstore.NewService(taskactionstore.Store{TaskStore: st}, nil, nil, nil, nil, nil, nil, nil)
controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: st.TaskByID,
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ReviewResponse) error {
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ActionPayload) error {
return actions.Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res)
},
cancelExecution: st.CancelExecution,
@@ -24,7 +24,7 @@ import (
type testTaskActor struct{ b *boot }
func (a testTaskActor) ApplyChatTaskAction(
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse,
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ActionPayload,
) (gateway.TaskActionResult, error) {
if err := a.b.taskActions().Apply(ctx, identity, actor, taskID, action, res); err != nil {
return gateway.TaskActionResult{}, err
@@ -84,7 +84,7 @@ func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := adapter.ApplyChatTaskAction(ctx, &tc.actorIdentity, taskactions.Actor{}, task.ID, tc.action, taskactions.ReviewResponse{})
_, err := adapter.ApplyChatTaskAction(ctx, &tc.actorIdentity, taskactions.Actor{}, task.ID, tc.action, taskactions.ActionPayload{})
if err == nil {
t.Fatalf("ApplyChatTaskAction() allowed cross-identity action %s by %q on task owned by %q",
tc.action, tc.actorIdentity, task.Identity)
@@ -152,7 +152,7 @@ func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
}
taskstatetest.Seed(ctx, t, st, task.ID, workflow.StatusQueued, tc.initialStatus, "setup")
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.attemptAction, taskactions.ReviewResponse{})
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.attemptAction, taskactions.ActionPayload{})
if err == nil {
t.Fatalf("expected error attempting %s on %s task, got nil", tc.attemptAction, tc.initialStatus)
}
@@ -182,7 +182,7 @@ func TestChatTaskActorAdapterTaskNotFound(t *testing.T) {
adapter := newChatTaskActorForTest(t, st, config.Config{})
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon, taskactions.ReviewResponse{})
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon, taskactions.ActionPayload{})
if err == nil {
t.Fatal("expected error for non-existent task, got nil")
}
@@ -257,7 +257,7 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
}
taskstatetest.Seed(ctx, t, st, task.ID, workflow.StatusQueued, tc.initialStatus, "setup")
result, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.action, taskactions.ReviewResponse{})
result, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.action, taskactions.ActionPayload{})
if err != nil {
t.Fatalf("ApplyChatTaskAction(%s) error = %v", tc.action, err)
}
@@ -292,7 +292,7 @@ func TestChatTaskActorAdapterNilContract(t *testing.T) {
ctx := context.Background()
adapter := chatTaskActorAdapter{contract: nil}
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 1, taskstate.ActionAbandon, taskactions.ReviewResponse{})
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 1, taskstate.ActionAbandon, taskactions.ActionPayload{})
if err == nil {
t.Fatal("expected error for nil contract, got nil")
}
+1 -1
View File
@@ -88,7 +88,7 @@ func runChatAction(t *testing.T, ctx context.Context, st storecontract.TaskStore
actions := taskactionstore.NewService(taskactionstore.Store{TaskStore: st}, nil, nil, nil, nil, nil, nil, nil)
controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: st.TaskByID,
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ReviewResponse) error {
approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ActionPayload) error {
return actions.Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res)
},
cancelExecution: canceller.CancelExecution,
+2 -2
View File
@@ -72,11 +72,11 @@ func (f *fakeChat) Cancel(context.Context, string) (gateway.ChatCancellation, er
func (f *fakeChat) SetPersona(context.Context, string, string) (bool, error) { return false, nil }
func (f *fakeChat) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ReviewResponse) (gateway.TaskActionResult, error) {
func (f *fakeChat) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ActionPayload) (gateway.TaskActionResult, error) {
return gateway.TaskActionResult{}, nil
}
func (f *fakeChat) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse) (gateway.TaskActionResult, error) {
func (f *fakeChat) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload) (gateway.TaskActionResult, error) {
return gateway.TaskActionResult{}, nil
}
+2 -2
View File
@@ -82,10 +82,10 @@ func (f *fakeChatContract) SetPersona(ctx context.Context, id, name string) (boo
return true, nil
}
func (f *fakeChatContract) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse) (messaging.TaskActionResult, error) {
func (f *fakeChatContract) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, _ taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return messaging.TaskActionResult{}, nil
}
func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse) (messaging.TaskActionResult, error) {
func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return messaging.TaskActionResult{}, nil
}
+19 -5
View File
@@ -1703,11 +1703,16 @@ type ApplyOperatorTaskActionRequest struct {
ActorKind string `protobuf:"bytes,4,opt,name=actor_kind,json=actorKind,proto3" json:"actor_kind,omitempty"`
PrincipalId string `protobuf:"bytes,5,opt,name=principal_id,json=principalId,proto3" json:"principal_id,omitempty"`
// instructions and findings are the review gate answer payload
// (taskactions.ReviewResponse): the instructions a rereview requires, and
// (taskactions.ActionPayload): the instructions a rereview requires, and
// the finding keys an approve posts (empty means every offered finding).
// They are empty for every other action.
Instructions string `protobuf:"bytes,6,opt,name=instructions,proto3" json:"instructions,omitempty"`
Findings []string `protobuf:"bytes,7,rep,name=findings,proto3" json:"findings,omitempty"`
Instructions string `protobuf:"bytes,6,opt,name=instructions,proto3" json:"instructions,omitempty"`
Findings []string `protobuf:"bytes,7,rep,name=findings,proto3" json:"findings,omitempty"`
// retry_mode is the operator's worktree choice for a retry
// (taskstate.RetryMode): refresh onto the base branch or continue the work
// already pushed on the task's branch. It is empty for every other action,
// and chat carries no mode syntax -- an empty value means refresh_onto_base.
RetryMode string `protobuf:"bytes,8,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1791,6 +1796,13 @@ func (x *ApplyOperatorTaskActionRequest) GetFindings() []string {
return nil
}
func (x *ApplyOperatorTaskActionRequest) GetRetryMode() string {
if x != nil {
return x.RetryMode
}
return ""
}
type ApplyOperatorTaskActionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
@@ -3022,7 +3034,7 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
"\x17ApplyTaskActionResponse\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" +
"\x06action\x18\x02 \x01(\tR\x06action\x12\x18\n" +
"\amessage\x18\x03 \x01(\tR\amessage\"\xee\x01\n" +
"\amessage\x18\x03 \x01(\tR\amessage\"\x8d\x02\n" +
"\x1eApplyOperatorTaskActionRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" +
"\x06action\x18\x02 \x01(\tR\x06action\x12\x19\n" +
@@ -3031,7 +3043,9 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
"actor_kind\x18\x04 \x01(\tR\tactorKind\x12!\n" +
"\fprincipal_id\x18\x05 \x01(\tR\vprincipalId\x12\"\n" +
"\finstructions\x18\x06 \x01(\tR\finstructions\x12\x1a\n" +
"\bfindings\x18\a \x03(\tR\bfindings\"l\n" +
"\bfindings\x18\a \x03(\tR\bfindings\x12\x1d\n" +
"\n" +
"retry_mode\x18\b \x01(\tR\tretryMode\"l\n" +
"\x1fApplyOperatorTaskActionResponse\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" +
"\x06action\x18\x02 \x01(\tR\x06action\x12\x18\n" +
+37 -10
View File
@@ -1354,8 +1354,14 @@ type Task struct {
// from retry_count and remediation_rounds for the same reason those are
// separate from each other.
RereviewRounds int64 `protobuf:"varint,40,opt,name=rereview_rounds,json=rereviewRounds,proto3" json:"rereview_rounds,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// retry_mode is the operator's worktree choice for the next dispatch
// (taskstate.RetryMode: refresh_onto_base, continue_pushed_work). The retry
// action writes it and the daemon's prepareWorkspace reads it, so it must
// cross the wire for a retry to land on the source the operator chose. The
// empty string reads as refresh_onto_base.
RetryMode string `protobuf:"bytes,41,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Task) Reset() {
@@ -1669,6 +1675,13 @@ func (x *Task) GetRereviewRounds() int64 {
return 0
}
func (x *Task) GetRetryMode() string {
if x != nil {
return x.RetryMode
}
return ""
}
// 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.
@@ -4811,10 +4824,13 @@ func (x *ArchiveTaskResponse) GetEventId() int64 {
}
type RetryTaskRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
FromStatus string `protobuf:"bytes,2,opt,name=from_status,json=fromStatus,proto3" json:"from_status,omitempty"`
Workflow string `protobuf:"bytes,3,opt,name=workflow,proto3" json:"workflow,omitempty"`
state protoimpl.MessageState `protogen:"open.v1"`
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
FromStatus string `protobuf:"bytes,2,opt,name=from_status,json=fromStatus,proto3" json:"from_status,omitempty"`
Workflow string `protobuf:"bytes,3,opt,name=workflow,proto3" json:"workflow,omitempty"`
// retry_mode is the operator's worktree choice (taskstate.RetryMode) the
// requeue persists. Empty reads as refresh_onto_base.
RetryMode string `protobuf:"bytes,4,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -4870,6 +4886,13 @@ func (x *RetryTaskRequest) GetWorkflow() string {
return ""
}
func (x *RetryTaskRequest) GetRetryMode() string {
if x != nil {
return x.RetryMode
}
return ""
}
type RetryTaskResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -12108,7 +12131,7 @@ const file_state_v1_state_proto_rawDesc = "" +
"\asubject\x18\x03 \x01(\tR\asubject\x12-\n" +
"\x05audit\x18\x04 \x01(\v2\x17.state.v1.IdentityAuditR\x05audit\"M\n" +
"\x1bBindIdentitySubjectResponse\x12.\n" +
"\bidentity\x18\x01 \x01(\v2\x12.state.v1.IdentityR\bidentity\"\xcb\n" +
"\bidentity\x18\x01 \x01(\v2\x12.state.v1.IdentityR\bidentity\"\xea\n" +
"\n" +
"\x04Task\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" +
@@ -12163,7 +12186,9 @@ const file_state_v1_state_proto_rawDesc = "" +
"\foutputs_json\x18& \x01(\tR\voutputsJson\x12\x1f\n" +
"\vreview_gate\x18' \x01(\tR\n" +
"reviewGate\x12'\n" +
"\x0frereview_rounds\x18( \x01(\x03R\x0erereviewRounds\"\xf8\x02\n" +
"\x0frereview_rounds\x18( \x01(\x03R\x0erereviewRounds\x12\x1d\n" +
"\n" +
"retry_mode\x18) \x01(\tR\tretryMode\"\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" +
@@ -12418,12 +12443,14 @@ const file_state_v1_state_proto_rawDesc = "" +
"fromStatus\x12%\n" +
"\x05audit\x18\x03 \x01(\v2\x0f.state.v1.EventR\x05audit\"0\n" +
"\x13ArchiveTaskResponse\x12\x19\n" +
"\bevent_id\x18\x01 \x01(\x03R\aeventId\"h\n" +
"\bevent_id\x18\x01 \x01(\x03R\aeventId\"\x87\x01\n" +
"\x10RetryTaskRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1f\n" +
"\vfrom_status\x18\x02 \x01(\tR\n" +
"fromStatus\x12\x1a\n" +
"\bworkflow\x18\x03 \x01(\tR\bworkflow\"\x13\n" +
"\bworkflow\x18\x03 \x01(\tR\bworkflow\x12\x1d\n" +
"\n" +
"retry_mode\x18\x04 \x01(\tR\tretryMode\"\x13\n" +
"\x11RetryTaskResponse\"\x96\x01\n" +
"\x18RespondReviewGateRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1f\n" +
+12 -24
View File
@@ -1485,25 +1485,24 @@ func (d *Daemon) prepareWorkspace(ctx context.Context, task *workflow.Task, tree
}
return dir, true
}
// The retry path selects the worktree mode from the task row. A task that
// continues an already-open PR branch -- the remediate workflow -- resumes
// that branch's remote tip instead of resetting onto base: preparing one
// the ordinary way discarded the commits the implement run had already
// pushed, so the agent remediated a PR from a tree that no longer contained
// it. Every other task starts fresh on base. This runs before Acquire,
// The retry action writes the worktree mode onto the task row
// (taskstate.RetryMode): continue_pushed_work resumes the branch the task
// already pushed, refresh_onto_base resets onto base. The mode is never
// inferred here from the workflow -- the reaction consumer writes
// continue_pushed_work when it queues a remediation, so every path that
// needs a resume records that choice explicitly. This runs before Acquire,
// because the daemon holds the forge credential that fetches the branch and
// the container must find the PR's work already in place. It also runs on a
// the container must find the work already in place. It also runs on a
// retry whose local worktree is gone: Prepare clones a missing worktree for
// either target, which is how a resume reaches a task whose clone the
// terminal cleanup removed.
target := worktree.Fresh
if continuesOpenPRBranch(task) {
if taskstate.NormalizeRetryMode(task.RetryMode) == taskstate.RetryContinuePushedWork {
if task.Branch == "" {
// A remediation task is queued against the branch its implement
// run pushed, so an empty branch is a dispatch bug upstream and no
// retry can fix it.
d.Log.Error("remediate task has no persisted branch", "task", task.ID)
d.parkRunningTask(ctx, task.ID, "worktree resume failed: remediate task has no branch to resume", taskstate.ParkNeedsHuman)
// The action refuses this combination, so an empty branch here is a
// dispatch bug upstream and no retry can fix it.
d.Log.Error("task has no persisted branch to continue", "task", task.ID)
d.parkRunningTask(ctx, task.ID, "worktree resume failed: task has no branch to continue", taskstate.ParkNeedsHuman)
return "", false
}
target = worktree.Target(task.Branch)
@@ -1530,17 +1529,6 @@ func (d *Daemon) prepareWorkspace(ctx context.Context, task *workflow.Task, tree
return dir, true
}
// continuesOpenPRBranch reports whether the task must continue a branch archie
// already pushed rather than start from base. Only the remediate workflow does:
// it addresses review feedback on an open archie-owned PR and reuses that PR's
// branch (docs/prds/pr-review-remediation.md decision 4), while every other
// workflow starts fresh work. The workflow is read from the task row, where the
// reaction consumer wrote it before queueing the run -- a decision about this
// task that no later routing may overturn.
func continuesOpenPRBranch(task *workflow.Task) bool {
return task.Workflow == "remediate"
}
// cleanupTerminalTaskWorktree removes a task's worktree once its forge side is
// settled, unless the worktree still holds work no commit captured.
//
+66 -11
View File
@@ -13,6 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/worktree"
)
@@ -41,10 +42,10 @@ func pushedImplementRun(t *testing.T, trees *worktree.Manager, title string) (di
}
// claimedTask returns the running row a dispatch leaves behind, carrying the
// workflow and branch prepareWorkspace must route on. The row is read back from
// the store, so the test drives prepareWorkspace from persisted state rather
// than from a struct the test assembled.
func claimedTask(t *testing.T, st *pgstore.TaskDB, title, workflowName, branch string) *workflow.Task {
// workflow, branch and retry mode prepareWorkspace must route on. The row is
// read back from the store, so the test drives prepareWorkspace from persisted
// state rather than from a struct the test assembled.
func claimedTask(t *testing.T, st *pgstore.TaskDB, title, workflowName, branch string, retryMode taskstate.RetryMode) *workflow.Task {
t.Helper()
ctx := context.Background()
if _, err := st.EnqueueIssue(ctx, "acme", "widget", 7, title, "body", "bug", ""); err != nil {
@@ -55,6 +56,7 @@ func claimedTask(t *testing.T, st *pgstore.TaskDB, title, workflowName, branch s
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
}
task.Workflow, task.Branch = workflowName, branch
task.RetryMode = string(retryMode)
if err := st.Update(ctx, task); err != nil {
t.Fatalf("persist task fields: %v", err)
}
@@ -63,9 +65,9 @@ func claimedTask(t *testing.T, st *pgstore.TaskDB, title, workflowName, branch s
if err != nil {
t.Fatalf("TaskByID: %v", err)
}
if persisted.Workflow != workflowName || persisted.Branch != branch {
t.Fatalf("persisted row = (workflow %q, branch %q), want (%q, %q)",
persisted.Workflow, persisted.Branch, workflowName, branch)
if persisted.Workflow != workflowName || persisted.Branch != branch || persisted.RetryMode != string(retryMode) {
t.Fatalf("persisted row = (workflow %q, branch %q, retry mode %q), want (%q, %q, %q)",
persisted.Workflow, persisted.Branch, persisted.RetryMode, workflowName, branch, retryMode)
}
return persisted
}
@@ -99,7 +101,7 @@ func TestPrepareWorkspaceResumesThePersistedBranchForARemediation(t *testing.T)
d, st, _ := testDaemon(t, 3, 0)
// The issue was retitled since; the PR's branch is still the pushed one.
task := claimedTask(t, st, "fix: retitled issue", "remediate", branch)
task := claimedTask(t, st, "fix: retitled issue", "remediate", branch, taskstate.RetryContinuePushedWork)
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
if !ok {
@@ -135,7 +137,7 @@ func TestPrepareWorkspaceResumesAPRBranchAfterTheWorktreeWasRemoved(t *testing.T
}
d, st, _ := testDaemon(t, 3, 0)
task := claimedTask(t, st, "fix: original issue", "remediate", branch)
task := claimedTask(t, st, "fix: original issue", "remediate", branch, taskstate.RetryContinuePushedWork)
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
if !ok {
@@ -167,7 +169,7 @@ func TestPrepareWorkspaceFailsClosedWhenTheRemediationBranchIsGone(t *testing.T)
dir, _, tip := pushedImplementRun(t, trees, "fix: original issue")
d, st, _ := testDaemon(t, 3, 0)
task := claimedTask(t, st, "fix: original issue", "remediate", "fix/7-never-pushed")
task := claimedTask(t, st, "fix: original issue", "remediate", "fix/7-never-pushed", taskstate.RetryContinuePushedWork)
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
if ok {
@@ -203,7 +205,7 @@ func TestPrepareWorkspaceStartsBaseForANonRemediationTask(t *testing.T) {
_, pushedBranch, tip := pushedImplementRun(t, trees, "fix: original issue")
d, st, _ := testDaemon(t, 3, 0)
task := claimedTask(t, st, "fix: retitled issue", "implement", pushedBranch)
task := claimedTask(t, st, "fix: retitled issue", "implement", pushedBranch, taskstate.RetryRefreshOntoBase)
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
if !ok {
@@ -219,3 +221,56 @@ func TestPrepareWorkspaceStartsBaseForANonRemediationTask(t *testing.T) {
t.Errorf("task branch = %q, want the branch recomputed for fresh work rather than the persisted PR branch", task.Branch)
}
}
// TestPrepareWorkspaceContinuesPushedWorkWhenTheOperatorChoseIt is the
// operator-mode half of the retry routing: a task whose persisted retry_mode
// is continue_pushed_work resumes the branch it already pushed, even though
// its workflow -- implement -- is not one that resumes by default. The
// worktree must land on the pushed tip, not reset over it.
func TestPrepareWorkspaceContinuesPushedWorkWhenTheOperatorChoseIt(t *testing.T) {
ctx := context.Background()
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
dir, branch, tip := pushedImplementRun(t, trees, "fix: original issue")
d, st, _ := testDaemon(t, 3, 0)
task := claimedTask(t, st, "fix: retitled issue", "implement", branch, taskstate.RetryContinuePushedWork)
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
if !ok {
t.Fatal("prepareWorkspace() = false, want the retry prepared on the branch the operator chose to continue")
}
if gotDir != dir {
t.Errorf("prepareWorkspace() dir = %q, want the task's worktree %q", gotDir, dir)
}
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); err != nil {
t.Fatalf("widget.go missing after prepare: %v (the pushed work was discarded despite continue_pushed_work)", err)
}
if got := headOf(t, gotDir); got != tip {
t.Errorf("worktree HEAD = %s, want the pushed branch tip %s", got, tip)
}
}
// TestPrepareWorkspaceRefreshesOntoBaseWhenTheOperatorChoseIt pins that the
// persisted mode decides, not the workflow: a task whose workflow would resume
// (remediate) but whose retry_mode is refresh_onto_base must land on base. The
// daemon must not re-derive the choice from the workflow, which is the silent
// default this bead exists to remove.
func TestPrepareWorkspaceRefreshesOntoBaseWhenTheOperatorChoseIt(t *testing.T) {
ctx := context.Background()
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
_, branch, tip := pushedImplementRun(t, trees, "fix: original issue")
d, st, _ := testDaemon(t, 3, 0)
task := claimedTask(t, st, "fix: original issue", "remediate", branch, taskstate.RetryRefreshOntoBase)
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
if !ok {
t.Fatal("prepareWorkspace() = false, want a fresh base preparation for refresh_onto_base")
}
if got := headOf(t, gotDir); got == tip {
t.Errorf("worktree HEAD = %s, want base rather than the pushed branch tip: refresh_onto_base must win over the workflow", got)
}
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); !os.IsNotExist(err) {
t.Errorf("widget.go present after refresh_onto_base (stat err = %v), want a fresh base checkout", err)
}
}
+2 -2
View File
@@ -33,7 +33,7 @@ type ChatTaskActionContract interface {
// may only act on its own tasks. res carries the review gate answer
// payload; the chat surface has no instruction or selection syntax, so it
// is the zero value there.
ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ReviewResponse) (TaskActionResult, error)
ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ActionPayload) (TaskActionResult, error)
// ApplyOperatorTaskAction applies an action on behalf of an authenticated
// dashboard caller, who acts across identities. The actor is who the
// credential resolved to, or the zero Actor when the caller presented
@@ -43,7 +43,7 @@ type ChatTaskActionContract interface {
// chatTaskProfiles in the daemon). res carries the review gate answer
// payload: the operator's finding selection for approve, and the
// instructions a rereview requires.
ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse) (TaskActionResult, error)
ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload) (TaskActionResult, error)
}
// TaskActionResult is what task_action returns.
@@ -122,9 +122,11 @@ type TaskArchiver interface {
}
// TaskRetryer atomically requeues recoverable work and accounts for the new
// attempt so a partial write cannot evade the retry cap.
// attempt so a partial write cannot evade the retry cap. retryMode is the
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
// persisted on the row so the daemon reads it instead of inferring it.
type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) error
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string) error
}
// ReviewGateResponder is the operator's answer to the review gate
@@ -50,7 +50,7 @@ func TestOperatorActionsRouteThroughCancelExecution(t *testing.T) {
Store: store,
CancelTask: func(id int64) bool { deliveries = append(deliveries, id); return true },
}
if err := service.Apply(context.Background(), nil, humanActor(), 7, tt.action, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, humanActor(), 7, tt.action, ActionPayload{}); err != nil {
t.Fatalf("Apply(%s): %v", tt.action, err)
}
if len(store.cancels) != 1 {
@@ -81,7 +81,7 @@ func TestStopRecordsEvenWhenNothingWasExecuting(t *testing.T) {
Store: store,
CancelTask: func(int64) bool { return false },
}
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionStop, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionStop, ActionPayload{}); err != nil {
t.Fatalf("Apply(stop): %v", err)
}
if len(store.cancels) != 1 || store.cancels[0].to != taskstate.Parked {
@@ -81,7 +81,7 @@ func TestApproveOfAGateRecordsTheSelectionOnTheOffer(t *testing.T) {
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove,
ReviewResponse{Findings: []string{findings[0].Key()}}); err != nil {
ActionPayload{Findings: []string{findings[0].Key()}}); err != nil {
t.Fatalf("Apply(approve): %v", err)
}
if len(store.requeues) != 0 {
@@ -114,7 +114,7 @@ func TestApproveWithNoSelectionRecordsEveryOfferedFinding(t *testing.T) {
store := &gateStore{task: offeredGate(findings...)}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, ActionPayload{}); err != nil {
t.Fatalf("Apply(approve): %v", err)
}
gate, _ := workflowtask.DecodeReviewGate(store.gateWrites[0].gate)
@@ -128,7 +128,7 @@ func TestApproveRefusesANonOfferedFindingKey(t *testing.T) {
service := Service{Store: store}
err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove,
ReviewResponse{Findings: []string{"main.go:99:stale"}})
ActionPayload{Findings: []string{"main.go:99:stale"}})
if !errors.Is(err, ErrConflict) {
t.Fatalf("Apply(approve with a stale key) = %v, want ErrConflict", err)
}
@@ -146,7 +146,7 @@ func TestApproveWithoutAGateKeepsTheTasksWorkflow(t *testing.T) {
store := &gateStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: taskstate.WaitingHuman}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, ActionPayload{}); err != nil {
t.Fatalf("Apply(approve): %v", err)
}
if len(store.gateWrites) != 0 {
@@ -163,7 +163,7 @@ func TestRereviewRecordsInstructionsAndClearsTheOffer(t *testing.T) {
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionRereview,
ReviewResponse{Instructions: "look at the migration ordering"}); err != nil {
ActionPayload{Instructions: "look at the migration ordering"}); err != nil {
t.Fatalf("Apply(rereview): %v", err)
}
write := store.gateWrites[0]
@@ -186,7 +186,7 @@ func TestRereviewRefusedWithoutInstructionsAndAtTheCap(t *testing.T) {
tests := []struct {
name string
task *Task
res ReviewResponse
res ActionPayload
want string
}{
{
@@ -197,7 +197,7 @@ func TestRereviewRefusedWithoutInstructionsAndAtTheCap(t *testing.T) {
{
name: "no gate offer",
task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: taskstate.WaitingHuman},
res: ReviewResponse{Instructions: "look again"},
res: ActionPayload{Instructions: "look again"},
want: "no review gate",
},
{
@@ -207,7 +207,7 @@ func TestRereviewRefusedWithoutInstructionsAndAtTheCap(t *testing.T) {
task.RereviewRounds = workflowtask.MaxRereviewRounds
return task
}(),
res: ReviewResponse{Instructions: "look again"},
res: ActionPayload{Instructions: "look again"},
want: "re-reviews",
},
}
+51 -19
View File
@@ -25,6 +25,15 @@ type Task struct {
Owner, Repo, Identity, Status, ParkReason string
IssueNumber, RetryCount int
ForgeBacked bool
// Branch is the branch this task already pushed, if any. A retry that
// continues pushed work resumes it, so the service refuses that mode for a
// task with no branch rather than queueing a resume that cannot land.
Branch string
// RetryMode is the worktree mode already persisted for this task. A retry
// that carries no explicit mode (chat has no mode syntax) keeps this value
// rather than resetting it, so a chat retry of a remediation still
// continues the branch its queued run recorded.
RetryMode string
// ReviewGate is the operator-approval gate's document as the task carries
// it (workflowtask.EncodeReviewGate): the offer the gate wrote, and the answer
// the response path fills in. The response path reads the offer here and
@@ -41,17 +50,23 @@ type Task struct {
Attempt int
}
// ReviewResponse is the payload an operator's answer to the review gate
// carries (docs/prds/pr-review-operator-response.md, Decision 1). It is empty
// for every other action, and for chat's /approve, which has no instruction or
// selection syntax: an absent selection means every offered finding.
type ReviewResponse struct {
// ActionPayload is the per-action data an operator action carries: the
// review-gate answer for approve and rereview (docs/prds/pr-review-operator-
// response.md, Decision 1), and the worktree mode for retry. Every field is
// empty for the actions that do not use it, and for chat's /approve and
// /retry, which carry no instruction, selection or mode syntax.
type ActionPayload struct {
// Instructions are what a re-review must focus on. The response path
// requires them for ActionRereview and ignores them otherwise.
Instructions string
// Findings are the keys (prreview.ScoredFinding.Key) of the offered
// findings an approve posts. Empty means all of them.
Findings []string
// RetryMode is the worktree choice a retry carries (taskstate.RetryMode):
// refresh onto the base branch, or continue the work already pushed on the
// task's branch. It is empty -- the explicit default, refresh -- for every
// other action.
RetryMode taskstate.RetryMode
}
// Actor is the identity that performed an action, and the principal whose
@@ -159,7 +174,9 @@ type Store interface {
TaskByID(context.Context, int64) (*Task, error)
Transition(context.Context, int64, string, string, string) error
Requeue(context.Context, int64, string, string) error
RetryTask(context.Context, int64, string, string) error
// RetryTask requeues a parked task, records the operator's worktree mode
// for the next dispatch and increments retry_count in one guarded write.
RetryTask(context.Context, int64, string, string, string) error
// RespondReviewGate is the guarded review gate response write
// (internal/domain/storecontract.ReviewGateResponder): it records the
// answered document, and for a re-review increments rereview_rounds and
@@ -197,12 +214,12 @@ type Service struct {
// The actor is not derived from scope: scope is which tasks a caller may touch,
// actor is who touched one, and the two are only equal by coincidence.
//
// res is the review-gate answer payload: the operator's instruction and
// finding selection for approve and rereview, empty for every other action
// and for the chat surfaces that carry no selection syntax. Both the dashboard
// and chat reach the same apply, so one operator intent cannot be recorded as
// two different decisions.
func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64, action taskstate.Action, res ReviewResponse) error {
// res is the per-action payload (ActionPayload): the operator's instruction
// and finding selection for approve and rereview, the worktree mode for
// retry, and empty for every other action and for the chat surfaces that
// carry no such syntax. Both the dashboard and chat reach the same apply, so
// one operator intent cannot be recorded as two different decisions.
func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64, action taskstate.Action, res ActionPayload) error {
task, err := s.Store.TaskByID(ctx, id)
if err != nil {
return err
@@ -243,7 +260,7 @@ type outcome struct {
// record alongside it. Errors from the store are returned unwrapped: the
// caller maps them to a response, and the rules-level errors (ErrConflict)
// were already checked above.
func (s Service) apply(ctx context.Context, task *Task, actor Actor, action taskstate.Action, res ReviewResponse) (outcome, error) {
func (s Service) apply(ctx context.Context, task *Task, actor Actor, action taskstate.Action, res ActionPayload) (outcome, error) {
o := outcome{event: s.attributed(task, actor)}
switch action {
case taskstate.ActionApprove:
@@ -251,7 +268,7 @@ func (s Service) apply(ctx context.Context, task *Task, actor Actor, action task
case taskstate.ActionRereview:
return s.applyRereview(ctx, task, actor, o, res)
case taskstate.ActionRetry:
return s.applyRetry(ctx, task, actor, o)
return s.applyRetry(ctx, task, actor, o, res)
case taskstate.ActionStop:
return s.applyStop(ctx, task, actor, o)
case taskstate.ActionReject:
@@ -283,7 +300,7 @@ func (s Service) apply(ctx context.Context, task *Task, actor Actor, action task
// it requeues under the workflow the wait names -- which feasibility sets to
// implement before it waits (docs/prds/pr-review-operator-response.md,
// Decision 1) -- never a name this handler hardcodes.
func (s Service) applyApprove(ctx context.Context, task *Task, actor Actor, o outcome, res ReviewResponse) (outcome, error) {
func (s Service) applyApprove(ctx context.Context, task *Task, actor Actor, o outcome, res ActionPayload) (outcome, error) {
o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved")
gate, ok := workflowtask.DecodeReviewGate(task.ReviewGate)
if !ok || !gate.Offered() {
@@ -308,7 +325,7 @@ func (s Service) applyApprove(ctx context.Context, task *Task, actor Actor, o ou
// one at the cap: in both cases the task stays waiting and nothing is written.
// The offer's findings are cleared, because the resumed run recomputes them;
// the instructions are what reach the recomputation.
func (s Service) applyRereview(ctx context.Context, task *Task, actor Actor, o outcome, res ReviewResponse) (outcome, error) {
func (s Service) applyRereview(ctx context.Context, task *Task, actor Actor, o outcome, res ActionPayload) (outcome, error) {
gate, ok := workflowtask.DecodeReviewGate(task.ReviewGate)
if !ok || !gate.Offered() {
return o, fmt.Errorf("task %d has no review gate to re-review: %w", task.ID, ErrConflict)
@@ -380,7 +397,22 @@ func (s Service) attributed(task *Task, actor Actor) events.Event {
}
}
func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outcome, payload ActionPayload) (outcome, error) {
// An explicit mode always wins. When the action carries none -- chat has no
// mode syntax -- the task's persisted mode is kept rather than reset, so a
// chat retry of a remediation still continues its branch. An empty stored
// value reads as the explicit refresh default.
requested := payload.RetryMode
if requested == "" {
requested = taskstate.RetryMode(task.RetryMode)
}
mode, ok := taskstate.ResolveRetryMode(string(requested))
if !ok {
return o, fmt.Errorf("unknown retry mode %q: %w", requested, ErrConflict)
}
if mode == taskstate.RetryContinuePushedWork && strings.TrimSpace(task.Branch) == "" {
return o, fmt.Errorf("task %d has no pushed branch to continue: %w", task.ID, ErrConflict)
}
limit := 0
if s.MaxRetries != nil {
limit = s.MaxRetries(task)
@@ -395,9 +427,9 @@ func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outc
}
return o, fmt.Errorf("%w: %s", ErrConflict, reason)
}
err := s.Store.RetryTask(ctx, task.ID, "parked", "")
err := s.Store.RetryTask(ctx, task.ID, "parked", "", string(mode))
o.event.Kind, o.event.Detail = events.KindTaskRetried, actor.describe("retried")
o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_reason": task.ParkReason}
o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_reason": task.ParkReason, "retry_mode": string(mode)}
return o, err
}
+84 -10
View File
@@ -2,6 +2,7 @@ package taskactions
import (
"context"
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
@@ -10,8 +11,10 @@ import (
)
type fakeStore struct {
task *Task
events []events.Event
task *Task
events []events.Event
retryMode string
retried bool
}
func (f *fakeStore) TaskByID(context.Context, int64) (*Task, error) { return f.task, nil }
@@ -29,7 +32,9 @@ func (f *fakeStore) RespondReviewGate(context.Context, int64, string, string, bo
return nil
}
func (f *fakeStore) RetryTask(context.Context, int64, string, string) error {
func (f *fakeStore) RetryTask(_ context.Context, _ int64, _, _, retryMode string) error {
f.retryMode = retryMode
f.retried = true
return nil
}
@@ -87,7 +92,7 @@ func TestEventKindDescribesTheActor(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, tc.actor, 7, tc.action, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, tc.actor, 7, tc.action, ActionPayload{}); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
@@ -112,7 +117,7 @@ func TestActorAndPrincipalAreRecordedSeparately(t *testing.T) {
service := Service{Store: store}
actor := agentActor().AuthorisedBy(humanID)
if err := service.Apply(context.Background(), nil, actor, 7, taskstate.ActionApprove, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, actor, 7, taskstate.ActionApprove, ActionPayload{}); err != nil {
t.Fatalf("Apply() error = %v", err)
}
@@ -137,7 +142,7 @@ func TestUnattributedActionClaimsNoApprover(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, Actor{}, 7, taskstate.ActionApprove, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, Actor{}, 7, taskstate.ActionApprove, ActionPayload{}); err != nil {
t.Fatalf("Apply() error = %v", err)
}
@@ -172,7 +177,7 @@ func TestEveryActionCarriesItsAttribution(t *testing.T) {
Store: store,
CancelTask: func(int64) bool { return true },
}
if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action, ActionPayload{}); err != nil {
t.Fatalf("Apply(%s) error = %v", tc.action, err)
}
got := store.last()
@@ -191,14 +196,14 @@ func TestScopeStillLimitsATaskButIsNotTheActor(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human", Identity: "archie"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove, ReviewResponse{}); err == nil {
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove, ActionPayload{}); err == nil {
t.Fatal("Apply() allowed an identity to act on another identity's task")
}
if len(store.events) != 0 {
t.Fatalf("a refused action recorded %d events", len(store.events))
}
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove, ReviewResponse{}); err == nil {
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove, ActionPayload{}); err == nil {
t.Fatal("Apply() allowed a scoped caller to act on a foreign task")
}
}
@@ -238,7 +243,7 @@ func TestOnlyRejectAndCancelCloseTheIssue(t *testing.T) {
closed = true
return nil
}}
if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action, ReviewResponse{}); err != nil {
if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action, ActionPayload{}); err != nil {
t.Fatalf("Apply(%s) error = %v", tc.action, err)
}
if closed != tc.closes {
@@ -247,3 +252,72 @@ func TestOnlyRejectAndCancelCloseTheIssue(t *testing.T) {
})
}
}
// TestRetryPersistsTheOperatorsWorktreeMode pins the retry half of the
// operator surface: the mode the dashboard sent reaches the store write, so
// the daemon reads the operator's choice instead of inferring one. The event
// records the mode too, so the timeline says how the retry was dispatched.
func TestRetryPersistsTheOperatorsWorktreeMode(t *testing.T) {
tests := []struct {
name string
mode taskstate.RetryMode
persisted string
branch string
wantMode string
}{
{"continue pushed work", taskstate.RetryContinuePushedWork, "", "fix/7-thing", "continue_pushed_work"},
{"refresh onto base", taskstate.RetryRefreshOntoBase, "", "", "refresh_onto_base"},
{"an empty mode is the explicit refresh default", "", "", "", "refresh_onto_base"},
{"an empty mode keeps the persisted choice", "", string(taskstate.RetryContinuePushedWork), "fix/7-thing", "continue_pushed_work"},
{"an explicit mode overrides the persisted choice", taskstate.RetryRefreshOntoBase, string(taskstate.RetryContinuePushedWork), "fix/7-thing", "refresh_onto_base"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: taskstate.Parked, Branch: tc.branch, RetryMode: tc.persisted}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionRetry, ActionPayload{RetryMode: tc.mode}); err != nil {
t.Fatalf("Apply(retry) error = %v", err)
}
if !store.retried || store.retryMode != tc.wantMode {
t.Fatalf("RetryTask mode = %q (called %v), want %q", store.retryMode, store.retried, tc.wantMode)
}
if got := store.last().Data["retry_mode"]; got != tc.wantMode {
t.Errorf("retry event retry_mode = %v, want %q", got, tc.wantMode)
}
})
}
}
// TestRetryRefusesModesThatCannotLand keeps a refuse-from-the-operator rule at
// the service, where every surface reaches it: continuing work with no pushed
// branch would queue a resume that cannot land, and an unknown mode is a
// caller bug rather than a task to reset. Both are conflicts and neither
// writes.
func TestRetryRefusesModesThatCannotLand(t *testing.T) {
tests := []struct {
name string
mode taskstate.RetryMode
branch string
}{
{"continue with no pushed branch", taskstate.RetryContinuePushedWork, ""},
{"an unknown mode", taskstate.RetryMode("reset_to_branch_head"), "fix/7-thing"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: taskstate.Parked, Branch: tc.branch}}
service := Service{Store: store}
err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionRetry, ActionPayload{RetryMode: tc.mode})
if err == nil {
t.Fatal("Apply(retry) = nil error, want a conflict")
}
if !errors.Is(err, ErrConflict) {
t.Fatalf("Apply(retry) error = %v, want ErrConflict", err)
}
if store.retried {
t.Error("RetryTask was called, want the refusal to write nothing")
}
})
}
}
+8
View File
@@ -66,6 +66,14 @@ type Task struct {
// (parking-to-queued transitions). When it reaches the configured
// max_retries the daemon moves the task to StatusDead.
RetryCount int `json:"retry_count"`
// RetryMode is the operator's worktree choice for the next dispatch of this
// task (taskstate.RetryMode): refresh onto the base branch, or continue the
// work already pushed on Branch. The retry action writes it -- and the
// reaction consumer writes continue when it queues a remediation -- and the
// daemon's prepareWorkspace reads it to position the worktree. Empty reads
// as the explicit default, RefreshOntoBase; it is never inferred from the
// workflow at dispatch.
RetryMode string `json:"retry_mode"`
// 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
+2 -2
View File
@@ -118,14 +118,14 @@ func (a *LocalChatAdapter) SetPersona(ctx context.Context, id, name string) (boo
return a.Personas.SetActive(id, strings.ToLower(name)), nil
}
func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (TaskActionResult, error) {
func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ActionPayload) (TaskActionResult, error) {
if a.TaskActor == nil {
return TaskActionResult{}, ErrChatCapabilityUnavailable
}
return a.TaskActor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, action, res)
}
func (a *LocalChatAdapter) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (TaskActionResult, error) {
func (a *LocalChatAdapter) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ActionPayload) (TaskActionResult, error) {
if a.TaskActor == nil {
return TaskActionResult{}, ErrChatCapabilityUnavailable
}
+1 -1
View File
@@ -22,7 +22,7 @@ type fakeActor struct {
gotAction taskstate.Action
}
func (f *fakeActor) ApplyChatTaskAction(_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse) (TaskActionResult, error) {
func (f *fakeActor) ApplyChatTaskAction(_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ActionPayload) (TaskActionResult, error) {
if identity != nil {
f.gotIdentity = *identity
}
+2 -2
View File
@@ -79,7 +79,7 @@ type ChatTaskActor interface {
// and not the same as an empty name, which is a real identity in a
// single-identity deployment. res is the review gate answer payload; this
// tool has no instruction or selection syntax, so it is the zero value.
ApplyChatTaskAction(ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (TaskActionResult, error)
ApplyChatTaskAction(ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ActionPayload) (TaskActionResult, error)
}
// ChatTaskLogEntry is one log line as task_logs returns it. It mirrors
@@ -331,7 +331,7 @@ func taskActionTool(actor ChatTaskActor, identity string) tools.ToolEntry {
// actor is that same bound identity, because a bot acting on
// its own channel's task is exactly what happened -- and it is
// recorded as an agent's action, not a person's.
result, err := actor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, taskstate.Action(actionStr), taskactions.ReviewResponse{})
result, err := actor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, taskstate.Action(actionStr), taskactions.ActionPayload{})
if err != nil {
return nil, fmt.Errorf("task_action: %w", err)
}
+3 -2
View File
@@ -82,7 +82,7 @@ func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error)
return v.Found, nil
}
func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (messaging.TaskActionResult, error) {
func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ActionPayload) (messaging.TaskActionResult, error) {
v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{
Identity: identity, TaskId: taskID, Action: string(action),
Instructions: res.Instructions, Findings: res.Findings,
@@ -93,7 +93,7 @@ func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID in
return messaging.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil
}
func (c *Client) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (messaging.TaskActionResult, error) {
func (c *Client) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ActionPayload) (messaging.TaskActionResult, error) {
v, err := c.client.ApplyOperatorTaskAction(ctx, &pb.ApplyOperatorTaskActionRequest{
TaskId: taskID,
Action: string(action),
@@ -102,6 +102,7 @@ func (c *Client) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.
PrincipalId: string(actor.Principal),
Instructions: res.Instructions,
Findings: res.Findings,
RetryMode: string(res.RetryMode),
})
if err != nil {
return messaging.TaskActionResult{}, taskActionError(err)
@@ -142,12 +142,13 @@ type recordingTaskActor struct {
identity *string
taskID int64
action taskstate.Action
payload taskactions.ActionPayload
}
func (a *recordingTaskActor) ApplyChatTaskAction(
_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse,
_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, payload taskactions.ActionPayload,
) (gateway.TaskActionResult, error) {
a.identity, a.taskID, a.action = identity, taskID, action
a.identity, a.taskID, a.action, a.payload = identity, taskID, action, payload
return gateway.TaskActionResult{TaskID: taskID, Action: string(action), Message: "applied"}, nil
}
@@ -169,7 +170,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
chat = remoteChat(t, local)
}
result, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 42, taskstate.ActionApprove, taskactions.ReviewResponse{})
result, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 42, taskstate.ActionApprove, taskactions.ActionPayload{RetryMode: taskstate.RetryContinuePushedWork})
if err != nil {
t.Fatalf("operator action: %v", err)
}
@@ -179,11 +180,14 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
if actor.taskID != 42 || actor.action != taskstate.ActionApprove {
t.Fatalf("operator action = (%d, %q), want (42, %q)", actor.taskID, actor.action, taskstate.ActionApprove)
}
if actor.payload.RetryMode != taskstate.RetryContinuePushedWork {
t.Fatalf("operator action retry mode = %q, want %q: the choice must survive the hop", actor.payload.RetryMode, taskstate.RetryContinuePushedWork)
}
if result.TaskID != 42 || result.Action != string(taskstate.ActionApprove) || result.Message != "applied" {
t.Fatalf("operator result = %+v, want the daemon's result", result)
}
if _, err := chat.ApplyTaskAction(ctx, "scout", 7, taskstate.ActionRetry, taskactions.ReviewResponse{}); err != nil {
if _, err := chat.ApplyTaskAction(ctx, "scout", 7, taskstate.ActionRetry, taskactions.ActionPayload{}); err != nil {
t.Fatalf("chat action: %v", err)
}
if actor.identity == nil || *actor.identity != "scout" {
@@ -197,7 +201,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
type failingTaskActor struct{ err error }
func (a failingTaskActor) ApplyChatTaskAction(
context.Context, *string, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse,
context.Context, *string, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload,
) (gateway.TaskActionResult, error) {
return gateway.TaskActionResult{}, a.err
}
@@ -221,7 +225,7 @@ func TestTaskActionErrorsKeepTheirSentinelOverGRPC(t *testing.T) {
local := &gateway.LocalChatAdapter{TaskActor: failingTaskActor{err: tc.err}}
chat := remoteChat(t, local)
_, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 7, taskstate.ActionApprove, taskactions.ReviewResponse{})
_, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 7, taskstate.ActionApprove, taskactions.ActionPayload{})
if err == nil {
t.Fatalf("ApplyOperatorTaskAction error = nil, want %v", tc.err)
}
+3 -2
View File
@@ -92,7 +92,7 @@ func (s *server) SetPersona(ctx context.Context, r *pb.SetPersonaRequest) (*pb.S
}
func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionRequest) (*pb.ApplyTaskActionResponse, error) {
v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action), taskactions.ReviewResponse{
v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action), taskactions.ActionPayload{
Instructions: r.Instructions,
Findings: r.Findings,
})
@@ -108,9 +108,10 @@ func (s *server) ApplyOperatorTaskAction(ctx context.Context, r *pb.ApplyOperato
Kind: identity.Kind(r.ActorKind),
Principal: identity.IdentityID(r.PrincipalId),
}
v, err := s.chat.ApplyOperatorTaskAction(ctx, actor, r.TaskId, taskstate.Action(r.Action), taskactions.ReviewResponse{
v, err := s.chat.ApplyOperatorTaskAction(ctx, actor, r.TaskId, taskstate.Action(r.Action), taskactions.ActionPayload{
Instructions: r.Instructions,
Findings: r.Findings,
RetryMode: taskstate.RetryMode(r.RetryMode),
})
if err != nil {
return nil, taskActionStatus(err)
@@ -0,0 +1,20 @@
-- Operator-selected retry worktree mode
-- (archie-core-vrl5: "retry should let the operator choose refresh-onto-base
-- or continue-pushed-work").
--
-- tasks.retry_mode records how the next dispatch positions the worktree:
-- 'refresh_onto_base' resets it onto the base branch, 'continue_pushed_work'
-- resumes the branch the task already pushed. The retry action writes the
-- operator's choice; BeginRemediationTask writes 'continue_pushed_work' when
-- it queues a remediation, because a remediation must continue its PR branch.
-- The default is the explicit refresh mode, so every existing row reads as a
-- retry that starts from base and no dispatch path infers the mode from the
-- workflow.
-- +goose Up
ALTER TABLE tasks ADD COLUMN retry_mode text NOT NULL DEFAULT 'refresh_onto_base';
-- +goose Down
ALTER TABLE tasks DROP COLUMN retry_mode;
@@ -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 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 FROM tasks t WHERE t.id = $1 FOR UPDATE
)
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth)
SELECT
@@ -41,7 +41,7 @@ SELECT
caller.id, caller.call_depth + 1
FROM caller
WHERE caller.status = 'running' AND caller.call_depth + 1 <= $7::int
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
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
`
type EnqueueCallTaskParams struct {
@@ -115,6 +115,7 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
return i, err
}
@@ -395,6 +395,7 @@ type Task struct {
Outputs string
ReviewGate string
RereviewRounds int64
RetryMode string
}
type ToolCall struct {
@@ -28,7 +28,7 @@ func (q *Queries) ArchiveTaskDelete(ctx context.Context, arg ArchiveTaskDeletePa
}
const beginRemediationTask = `-- name: BeginRemediationTask :execrows
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, updated_at = now()
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', updated_at = now()
WHERE id = $1 AND status = 'pr_open'
`
@@ -37,6 +37,9 @@ type BeginRemediationTaskParams struct {
ReviewPayload string
}
// A remediation must continue the branch its pull request lives on, so it
// records that dispatch mode explicitly (taskstate.RetryContinuePushedWork)
// rather than leaving prepareWorkspace to infer it from the workflow.
func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediationTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, beginRemediationTask, arg.ID, arg.ReviewPayload)
if err != nil {
@@ -48,7 +51,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
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
`
type ClaimByIssueParams struct {
@@ -103,6 +106,7 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
return i, err
}
@@ -117,7 +121,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
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
`
// FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
@@ -170,6 +174,7 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) {
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
return i, err
}
@@ -280,7 +285,7 @@ VALUES (
),
$8
)
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
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
`
type InsertChatTaskParams struct {
@@ -354,6 +359,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams)
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
return i, err
}
@@ -647,18 +653,25 @@ func (q *Queries) RespondReviewGateTask(ctx context.Context, arg RespondReviewGa
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,
park_reason = '', park_class = 'needs_human', updated_at = now()
WHERE id = $2 AND status = $3
WHERE id = $3 AND status = $4
`
type RetryTaskParams struct {
Workflow string
RetryMode string
ID int64
FromStatus string
}
func (q *Queries) RetryTask(ctx context.Context, arg RetryTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, retryTask, arg.Workflow, arg.ID, arg.FromStatus)
result, err := q.db.Exec(ctx, retryTask,
arg.Workflow,
arg.RetryMode,
arg.ID,
arg.FromStatus,
)
if err != nil {
return 0, err
}
@@ -700,7 +713,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 FROM tasks WHERE id = $1
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 FROM tasks WHERE id = $1
`
func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
@@ -747,12 +760,13 @@ func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
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 FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
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 FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
`
type TaskByIssueParams struct {
@@ -805,12 +819,13 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task,
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
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 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 FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
`
type TaskByPRParams struct {
@@ -872,6 +887,7 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
)
return i, err
}
@@ -934,7 +950,7 @@ UPDATE tasks SET workflow = $2, branch = $3, plan = $4, notes = $5,
review_payload = $13, workflow_definition_version = $14,
workflow_definition_digest = $15, workflow_definition_yaml = $16,
outputs = $17, review_gate = $18, rereview_rounds = $19,
updated_at = now()
retry_mode = $20, updated_at = now()
WHERE id = $1
`
@@ -958,6 +974,7 @@ type UpdateTaskParams struct {
Outputs string
ReviewGate string
RereviewRounds int64
RetryMode string
}
func (q *Queries) UpdateTask(ctx context.Context, arg UpdateTaskParams) error {
@@ -981,6 +998,7 @@ func (q *Queries) UpdateTask(ctx context.Context, arg UpdateTaskParams) error {
arg.Outputs,
arg.ReviewGate,
arg.RereviewRounds,
arg.RetryMode,
)
return err
}
@@ -85,7 +85,7 @@ UPDATE tasks SET workflow = $2, branch = $3, plan = $4, notes = $5,
review_payload = $13, workflow_definition_version = $14,
workflow_definition_digest = $15, workflow_definition_yaml = $16,
outputs = $17, review_gate = $18, rereview_rounds = $19,
updated_at = now()
retry_mode = $20, updated_at = now()
WHERE id = $1;
-- name: RereviewRounds :one
@@ -152,7 +152,10 @@ WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued'
RETURNING *;
-- name: BeginRemediationTask :execrows
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, updated_at = now()
-- A remediation must continue the branch its pull request lives on, so it
-- records that dispatch mode explicitly (taskstate.RetryContinuePushedWork)
-- rather than leaving prepareWorkspace to infer it from the workflow.
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', updated_at = now()
WHERE id = $1 AND status = 'pr_open';
-- name: UpdateReviewPayloadTask :execrows
@@ -172,6 +175,7 @@ WHERE id = @id AND status = @from_status;
-- name: RetryTask :execrows
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,
park_reason = '', park_class = 'needs_human', updated_at = now()
WHERE id = @id AND status = @from_status;
+7 -3
View File
@@ -111,6 +111,7 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
Attempt: int(t.Attempt),
ParkReason: t.ParkReason,
RetryCount: int(t.RetryCount),
RetryMode: t.RetryMode,
WatchCommentID: t.WatchCommentID,
ReviewCursor: t.ReviewCursor,
Source: t.Source,
@@ -322,6 +323,7 @@ func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
ReviewPayload: t.ReviewPayload,
ReviewGate: t.ReviewGate,
RereviewRounds: int64(t.RereviewRounds),
RetryMode: t.RetryMode,
WorkflowDefinitionVersion: t.WorkflowDefinitionVersion,
WorkflowDefinitionDigest: t.WorkflowDefinitionDigest,
WorkflowDefinitionYaml: t.WorkflowDefinitionYAML,
@@ -401,11 +403,13 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, wf string
}
// RetryTask requeues a task and increments retry_count in the same guarded
// transaction, under the same table check Requeue applies.
func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf string) error {
// transaction, under the same table check Requeue applies. retryMode is the
// operator's worktree choice for the next dispatch; the store persists it
// unread so the daemon's prepareWorkspace reads the mode the operator set.
func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string) error {
return s.requeue(ctx, taskID, fromStatus, wf, "retried "+wf, func(q *postgresdb.Queries) (int64, error) {
return q.RetryTask(ctx, postgresdb.RetryTaskParams{
ID: taskID, Workflow: wf, FromStatus: fromStatus,
ID: taskID, Workflow: wf, FromStatus: fromStatus, RetryMode: retryMode,
})
})
}
@@ -105,7 +105,7 @@ func TestTaskOutputs(t *testing.T) {
if err := st.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, "needs a look"); err != nil {
t.Fatal(err)
}
if err := st.RetryTask(ctx, task.ID, workflow.StatusParked, ""); err != nil {
if err := st.RetryTask(ctx, task.ID, workflow.StatusParked, "", ""); err != nil {
t.Fatal(err)
}
second, err := st.ClaimNext(ctx)
@@ -51,10 +51,10 @@ func TestIllegalTransitionsAreRejected(t *testing.T) {
return s.Requeue(t.Context(), taskID, taskstate.Merged, "implement")
}},
{name: "retry from terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
return s.RetryTask(t.Context(), taskID, taskstate.Merged, "implement")
return s.RetryTask(t.Context(), taskID, taskstate.Merged, "implement", "")
}},
{name: "retry from queued self-pair", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
return s.RetryTask(t.Context(), taskID, taskstate.Queued, "implement")
return s.RetryTask(t.Context(), taskID, taskstate.Queued, "implement", "")
}},
}
for _, tt := range tests {
+2 -2
View File
@@ -207,8 +207,8 @@ func (c *Client) ArchiveTask(ctx context.Context, taskID int64, fromStatus strin
return r.EventId, nil
}
func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf string) error {
_, err := c.client.RetryTask(ctx, &pb.RetryTaskRequest{TaskId: taskID, FromStatus: fromStatus, Workflow: wf})
func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string) error {
_, err := c.client.RetryTask(ctx, &pb.RetryTaskRequest{TaskId: taskID, FromStatus: fromStatus, Workflow: wf, RetryMode: retryMode})
return unmapError(err)
}
@@ -408,10 +408,10 @@ func TestStateStoreConformance(t *testing.T) {
// edges, and each guard is the wire contract. The battery used to
// walk queued -> queued through RetryTask, a self-write the shared
// transition table refuses, so the retry runs from running instead.
if err := c.RetryTask(ctx, claimed.ID, "running", ""); err != nil {
if err := c.RetryTask(ctx, claimed.ID, "running", "", ""); err != nil {
t.Fatalf("RetryTask: %v", err)
}
if err := c.RetryTask(ctx, claimed.ID, "queued", ""); !errors.Is(err, storecontract.ErrIllegalTransition) {
if err := c.RetryTask(ctx, claimed.ID, "queued", "", ""); !errors.Is(err, storecontract.ErrIllegalTransition) {
t.Fatalf("RetryTask queued->queued = %v, want ErrIllegalTransition", err)
}
if err := c.Transition(ctx, claimed.ID, "queued", "running", "re-claimed"); err != nil {
+1 -1
View File
@@ -347,7 +347,7 @@ func (s *server) ArchiveTask(ctx context.Context, r *pb.ArchiveTaskRequest) (*pb
}
func (s *server) RetryTask(ctx context.Context, r *pb.RetryTaskRequest) (*pb.RetryTaskResponse, error) {
if err := s.deps.Tasks.RetryTask(ctx, r.TaskId, r.FromStatus, r.Workflow); err != nil {
if err := s.deps.Tasks.RetryTask(ctx, r.TaskId, r.FromStatus, r.Workflow, r.RetryMode); err != nil {
return nil, s.logErr("RetryTask", err)
}
return &pb.RetryTaskResponse{}, nil
@@ -71,6 +71,7 @@ func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-f
Workflow: t.Workflow, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes,
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,
WatchCommentId: t.WatchCommentID, Source: t.Source, Identity: t.Identity,
BindingId: t.BindingID, BindingVersion: int64(t.BindingVersion),
InputsJson: inputsJSON(t.Inputs),
@@ -101,6 +102,7 @@ func taskValue(t *pb.Task) *task.Task { //nolint:dupl // see taskProto above
Workflow: t.Workflow, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes,
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,
WatchCommentID: t.WatchCommentId, Source: t.Source, Identity: t.Identity,
BindingID: t.BindingId, BindingVersion: int(t.BindingVersion),
Inputs: inputsValue(t.InputsJson),
+10 -6
View File
@@ -37,11 +37,13 @@ type actionRequest struct {
Action taskstate.Action `json:"action"`
Actor *actorPayload `json:"actor,omitempty"`
// Instructions and Findings are the review gate answer payload
// (taskactions.ReviewResponse). They are empty for every action but
// (taskactions.ActionPayload). They are empty for every action but
// approve and rereview, and for chat surfaces, which carry no selection
// syntax.
Instructions string `json:"instructions,omitempty"`
Findings []string `json:"findings,omitempty"`
// syntax. RetryMode is the worktree choice a retry carries; empty means
// the explicit default, refresh_onto_base.
Instructions string `json:"instructions,omitempty"`
Findings []string `json:"findings,omitempty"`
RetryMode taskstate.RetryMode `json:"retry_mode,omitempty"`
}
type actorPayload struct {
@@ -127,9 +129,10 @@ func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (fun
natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
err := service.Apply(context.Background(), req.Identity, req.Actor.actor(), req.TaskID, req.Action, taskactions.ReviewResponse{
err := service.Apply(context.Background(), req.Identity, req.Actor.actor(), req.TaskID, req.Action, taskactions.ActionPayload{
Instructions: req.Instructions,
Findings: req.Findings,
RetryMode: req.RetryMode,
})
natsrpc.Respond(msg, log, "taskactions", actionResponse{
Envelope: natsrpc.NewEnvelope(err),
@@ -152,7 +155,7 @@ func (c Client) rpc() *natsrpc.Client {
// ApplyChatTaskAction sends an action to the daemon's responder, carrying the
// scope and the actor the caller resolved. A caller with no verified identity
// passes the zero actor, which the daemon records as unattributed.
func (c Client) ApplyChatTaskAction(ctx context.Context, scope *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ReviewResponse) (gateway.TaskActionResult, error) {
func (c Client) ApplyChatTaskAction(ctx context.Context, scope *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ActionPayload) (gateway.TaskActionResult, error) {
if c.Conn == nil {
return gateway.TaskActionResult{}, fmt.Errorf("task action connection is unavailable")
}
@@ -162,6 +165,7 @@ func (c Client) ApplyChatTaskAction(ctx context.Context, scope *string, actor ta
Action: action,
Instructions: res.Instructions,
Findings: res.Findings,
RetryMode: res.RetryMode,
Actor: &actorPayload{
ID: string(actor.Identity),
Kind: string(actor.Kind),
@@ -49,7 +49,7 @@ func (s stubStore) Requeue(context.Context, int64, string, string) error { retur
func (s stubStore) RespondReviewGate(context.Context, int64, string, string, bool, int) error {
return s.err
}
func (s stubStore) RetryTask(context.Context, int64, string, string) error { return s.err }
func (s stubStore) RetryTask(context.Context, int64, string, string, string) error { return s.err }
func (s stubStore) ArchiveTask(context.Context, int64, string, events.Event) (int64, error) {
return 0, s.err
@@ -111,7 +111,7 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
t.Fatalf("flush: %v", err)
}
_, err = Client{Conn: nc}.ApplyChatTaskAction(t.Context(), nil, domain.Actor{}, 7, tc.action, domain.ReviewResponse{})
_, err = Client{Conn: nc}.ApplyChatTaskAction(t.Context(), nil, domain.Actor{}, 7, tc.action, domain.ActionPayload{})
if err == nil {
t.Fatalf("ApplyChatTaskAction(%s) error = nil, want %v", tc.action, tc.want)
}
@@ -119,7 +119,7 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
t.Fatalf("error %v (%T) is not %v", err, err, tc.want)
}
// The wording the operator reads survives too, not just the class.
direct := service.Apply(t.Context(), nil, domain.Actor{}, 7, tc.action, domain.ReviewResponse{})
direct := service.Apply(t.Context(), nil, domain.Actor{}, 7, tc.action, domain.ActionPayload{})
if direct == nil || err.Error() != direct.Error() {
t.Fatalf("remote message = %q, want the daemon's own %v", err.Error(), direct)
}
@@ -158,7 +158,7 @@ func TestActionScopeCrossesNATS(t *testing.T) {
t.Fatalf("flush: %v", err)
}
result, err := Client{Conn: nc}.ApplyChatTaskAction(t.Context(), tc.identity, domain.Actor{}, 7, taskstate.ActionAbandon, domain.ReviewResponse{})
result, err := Client{Conn: nc}.ApplyChatTaskAction(t.Context(), tc.identity, domain.Actor{}, 7, taskstate.ActionAbandon, domain.ActionPayload{})
if err != nil {
t.Fatalf("apply: %v", err)
}
+1 -1
View File
@@ -17,7 +17,7 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error
if err != nil || t == nil {
return nil, err
}
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil
}
// CancelExecution delegates to the store's one cancel path
+68
View File
@@ -148,6 +148,74 @@ func CheckRetry(status string) error {
return nil
}
// RetryMode is the operator's worktree choice for the next dispatch of a
// retried task. It is a dispatch directive: the daemon resolves it to the
// commit the worktree is prepared at, never infers it from the workflow.
//
// The values are persisted on the task row (tasks.retry_mode) and cross the
// wire, so they are part of the on-disk format: renaming one is a migration.
type RetryMode string
const (
// RetryRefreshOntoBase starts the retry from the current base branch,
// discarding anything an earlier attempt committed on the task branch.
// It is the default for work that is not an open pull request.
RetryRefreshOntoBase RetryMode = "refresh_onto_base"
// RetryContinuePushedWork resumes the branch the task already pushed, so
// the retry continues the work an earlier attempt committed instead of
// resetting over it. It requires a branch to resume.
RetryContinuePushedWork RetryMode = "continue_pushed_work"
)
// NormalizeRetryMode maps a stored retry mode to the mode it means. Empty and
// unknown values fall back to RefreshOntoBase: a retry that carries no explicit
// choice resets onto base, which is the safe default for work that is not an
// open pull request.
func NormalizeRetryMode(mode string) RetryMode {
if RetryMode(mode) == RetryContinuePushedWork {
return RetryContinuePushedWork
}
return RetryRefreshOntoBase
}
// ResolveRetryMode validates a retry mode arriving from a caller. Unlike
// stored data, a wire value that names no mode is rejected rather than
// defaulted: silently reading a typo as "refresh onto base" would reset a task
// the operator asked to continue. The empty string is accepted and means the
// explicit default, RetryRefreshOntoBase.
func ResolveRetryMode(mode string) (RetryMode, bool) {
switch RetryMode(mode) {
case "", RetryRefreshOntoBase:
return RetryRefreshOntoBase, true
case RetryContinuePushedWork:
return RetryContinuePushedWork, true
default:
return "", false
}
}
// RetryModeMeta describes how to present a retry mode. The dashboard renders
// the operator's choice from this catalog rather than keeping its own copy.
type RetryModeMeta struct {
ID string `json:"id"`
Label string `json:"label"`
Description string `json:"description"`
Default bool `json:"default"`
// RequiresBranch reports that the mode can only land when the task has a
// branch to resume. The dashboard disables it otherwise; the action refuses
// the same combination, so the UI check is a convenience, not the rule.
RequiresBranch bool `json:"requires_branch"`
}
// RetryModes returns the presentation catalog for the retry modes, in display
// order. Callers receive a fresh slice.
func RetryModes() []RetryModeMeta {
return []RetryModeMeta{
{ID: string(RetryRefreshOntoBase), Label: "Refresh onto base", Description: "Start the retry from the current base branch, discarding work already pushed on this task's branch.", Default: true},
{ID: string(RetryContinuePushedWork), Label: "Continue pushed work", Description: "Resume the branch this task already pushed, keeping its commits.", RequiresBranch: true},
}
}
// CheckDecline reports whether a task in this status can be declined.
//
// The legacy chat command expresses cancel, stop, reject and abandon as one
+10 -7
View File
@@ -21,23 +21,26 @@ type changeStatusMeta struct {
// struct rather than an inline map so the wire shape is declared in one place
// and pinned against the dashboard's freeze-dried snapshot by a fixture test.
type taskMetaView struct {
Statuses []taskstate.StatusMeta `json:"statuses"`
Actions []taskstate.ActionMeta `json:"actions"`
ChangeStatuses []changeStatusMeta `json:"change_statuses"`
ConfigSchema string `json:"config_schema"`
Statuses []taskstate.StatusMeta `json:"statuses"`
Actions []taskstate.ActionMeta `json:"actions"`
RetryModes []taskstate.RetryModeMeta `json:"retry_modes"`
ChangeStatuses []changeStatusMeta `json:"change_statuses"`
ConfigSchema string `json:"config_schema"`
}
// buildTaskMeta derives the lifecycle presentation catalog: the status
// vocabulary (with label, pill severity, "needs you" grouping), the operator
// action controls (with label, button variant, confirm prompt), the
// action controls (with label, button variant, confirm prompt), the retry
// worktree modes (with label, description and which is the default), the
// changes_captured status labels and the schema stamp a config_captured
// payload carries. Everything the dashboard can present that also exists on
// the server is derived here, so the frontend never has to keep a hand-synced
// copy of the vocabulary or the control set.
func buildTaskMeta() taskMetaView {
return taskMetaView{
Statuses: taskstate.Statuses(),
Actions: taskstate.ActionCatalog(),
Statuses: taskstate.Statuses(),
Actions: taskstate.ActionCatalog(),
RetryModes: taskstate.RetryModes(),
ChangeStatuses: []changeStatusMeta{
{ID: task.ChangeAdded, Label: "Added"},
{ID: task.ChangeModified, Label: "Modified"},
+22
View File
@@ -35,6 +35,13 @@ func TestTaskMetaCatalog(t *testing.T) {
Kind string `json:"kind"`
Confirm string `json:"confirm"`
} `json:"actions"`
RetryModes []struct {
ID string `json:"id"`
Label string `json:"label"`
Description string `json:"description"`
Default bool `json:"default"`
RequiresBranch bool `json:"requires_branch"`
} `json:"retry_modes"`
ChangeStatuses []struct {
ID string `json:"id"`
Label string `json:"label"`
@@ -51,6 +58,21 @@ func TestTaskMetaCatalog(t *testing.T) {
if len(got.Actions) == 0 {
t.Error("actions empty")
}
if len(got.RetryModes) == 0 {
t.Error("retry_modes empty; the retry dialog would offer no mode")
}
defaults := 0
for _, m := range got.RetryModes {
if m.ID == "" || m.Label == "" || m.Description == "" {
t.Errorf("retry mode missing id/label/description: %+v", m)
}
if m.Default {
defaults++
}
}
if defaults != 1 {
t.Errorf("retry_modes has %d defaults, want exactly 1", defaults)
}
if len(got.ChangeStatuses) == 0 {
t.Error("change_statuses empty; the dashboard renders raw status codes without it")
}
+14 -8
View File
@@ -199,6 +199,12 @@ type taskActionRequest struct {
// absent selection means all of them. It is ignored by every other
// action.
Findings []string `json:"findings"`
// RetryMode is the operator's worktree choice for a retry
// (taskstate.RetryMode): refresh onto the base branch, or continue the
// work already pushed on the task's branch. The retry control sends one;
// an empty value means the explicit default, refresh_onto_base. It is
// ignored by every other action.
RetryMode string `json:"retry_mode"`
}
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
@@ -232,7 +238,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id})
}
func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, taskactions.ReviewResponse, bool) {
func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, taskactions.ActionPayload, bool) {
r.Body = http.MaxBytesReader(w, r.Body, 4096)
var req taskActionRequest
decoder := json.NewDecoder(r.Body)
@@ -240,19 +246,19 @@ func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action,
if err := decoder.Decode(&req); err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
http.Error(w, "action body too large", http.StatusRequestEntityTooLarge)
return "", taskactions.ReviewResponse{}, false
return "", taskactions.ActionPayload{}, false
}
http.Error(w, "invalid action", http.StatusBadRequest)
return "", taskactions.ReviewResponse{}, false
return "", taskactions.ActionPayload{}, false
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
http.Error(w, "invalid action", http.StatusBadRequest)
return "", taskactions.ReviewResponse{}, false
return "", taskactions.ActionPayload{}, false
}
action := taskstate.Action(req.Action)
if !taskMutation(action) {
http.Error(w, "unknown action", http.StatusBadRequest)
return "", taskactions.ReviewResponse{}, false
return "", taskactions.ActionPayload{}, false
}
// A re-review without instructions is not a request the gate can honour,
// and refusing it here keeps the refusal the operator's to read rather
@@ -260,9 +266,9 @@ func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action,
// that do not pass through this handler.
if action == taskstate.ActionRereview && strings.TrimSpace(req.Instructions) == "" {
http.Error(w, "a re-review needs instructions", http.StatusBadRequest)
return "", taskactions.ReviewResponse{}, false
return "", taskactions.ActionPayload{}, false
}
return action, taskactions.ReviewResponse{Instructions: req.Instructions, Findings: req.Findings}, true
return action, taskactions.ActionPayload{Instructions: req.Instructions, Findings: req.Findings, RetryMode: taskstate.RetryMode(req.RetryMode)}, true
}
func taskMutation(action taskstate.Action) bool {
@@ -359,7 +365,7 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
// timeline needs its event bus, and stopping running work needs the
// goroutine or container that is executing it. Composing a local service
// over the task store alone would silently drop all four.
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ReviewResponse) error {
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error {
if s.Chat == nil || s.Chat.Contract == nil {
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
}
+46 -2
View File
@@ -72,7 +72,7 @@ type daemonActions struct {
}
func (d *daemonActions) ApplyChatTaskAction(
ctx context.Context, identity *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ReviewResponse,
ctx context.Context, identity *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ActionPayload,
) (gateway.TaskActionResult, error) {
d.scopes = append(d.scopes, identity)
service := taskactionstore.NewService(
@@ -236,7 +236,7 @@ func TestRetryEnforcesMaxRetries(t *testing.T) {
// (RetryTask) rather than a raw counter bump, re-parking
// between retries so each call sees the fromStatus it needs.
for range tc.priorCount {
if err := srv.Store.RetryTask(ctx, task.ID, workflow.StatusParked, ""); err != nil {
if err := srv.Store.RetryTask(ctx, task.ID, workflow.StatusParked, "", ""); err != nil {
t.Fatal(err)
}
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, workflow.StatusParked, "re-parked for test fixture")
@@ -898,3 +898,47 @@ func TestTaskActionRequiresCSRFHeader(t *testing.T) {
t.Fatalf("status = %d, want 403 without CSRF header (body %s)", w.Code, w.Body)
}
}
// TestRetryCarriesTheWorktreeModeToTheStore is the dashboard half of the
// operator retry choice: the mode in the action body reaches the store write,
// so the daemon reads the operator's choice rather than inferring one. The
// refusal case pins that continuing with nothing pushed is a conflict, not a
// queued resume.
func TestRetryCarriesTheWorktreeModeToTheStore(t *testing.T) {
t.Run("continue pushed work persists the choice", func(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusParked, "it broke")
if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Branch: "fix/11-thing"}); err != nil {
t.Fatal(err)
}
w := postActionBody(t, srv, task.ID, `{"action":"retry","retry_mode":"continue_pushed_work"}`)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body %s)", w.Code, w.Body)
}
got, err := srv.Store.TaskByID(t.Context(), task.ID)
if err != nil || got == nil {
t.Fatalf("TaskByID = (%+v, %v)", got, err)
}
if got.RetryMode != string(taskstate.RetryContinuePushedWork) {
t.Errorf("retry_mode = %q, want %q", got.RetryMode, taskstate.RetryContinuePushedWork)
}
})
t.Run("continue with no branch is refused", func(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusParked, "it broke")
w := postActionBody(t, srv, task.ID, `{"action":"retry","retry_mode":"continue_pushed_work"}`)
if w.Code != http.StatusConflict {
t.Fatalf("status = %d, want 409 (body %s)", w.Code, w.Body)
}
got, err := srv.Store.TaskByID(t.Context(), task.ID)
if err != nil || got == nil {
t.Fatalf("TaskByID = (%+v, %v)", got, err)
}
if got.Status != workflow.StatusParked {
t.Errorf("status = %q, want the task left parked", got.Status)
}
})
}
+2 -2
View File
@@ -93,7 +93,7 @@ func twoAttemptTask(t *testing.T, srv *Server) *workflow.Task {
if err := srv.Store.Transition(ctx, first.ID, workflow.StatusRunning, workflow.StatusParked, "stage implement: builder exited 1"); err != nil {
t.Fatal(err)
}
if err := srv.Store.RetryTask(ctx, first.ID, workflow.StatusParked, ""); err != nil {
if err := srv.Store.RetryTask(ctx, first.ID, workflow.StatusParked, "", ""); err != nil {
t.Fatal(err)
}
second, err := srv.Store.ClaimNext(ctx)
@@ -328,7 +328,7 @@ func TestHandleTaskAttemptsRendersBothAttemptsOfARetry(t *testing.T) {
if err := srv.Store.Transition(ctx, claimed1.ID, workflow.StatusRunning, workflow.StatusParked, "stage implement: builder exited 1"); err != nil {
t.Fatal(err)
}
if err := srv.Store.RetryTask(ctx, claimed1.ID, workflow.StatusParked, ""); err != nil {
if err := srv.Store.RetryTask(ctx, claimed1.ID, workflow.StatusParked, "", ""); err != nil {
t.Fatal(err)
}
current, err := srv.Store.ClaimNext(ctx)