From 15946dacfb032a45e6141848f2cdc5e54a953fed Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 2 Oct 2026 02:20:11 +1000 Subject: [PATCH] feat(taskactions): one approval path answers the review gate from every surface Decision 1 of docs/prds/pr-review-operator-response.md: the dashboard's POST /api/tasks/{id}/action is the authoritative surface, chat's /approve is a shortcut that posts every offered finding, and both reach the same Service.Apply so one operator intent cannot be recorded as two decisions. The action body now carries instructions (required by rereview) and the finding keys an approve posts. taskactions.Service answers an offer through the guarded RespondReviewGate write: approve records the selection on the offer, rereview records the instructions, increments the round and clears the offer, and a rereview with no instructions, with no offer, or at the cap is refused as a conflict with nothing written. Chat reaches the same service: chatTaskControllerAdapter.ApproveChatTask delegates to b.taskActions() instead of its own requeue, which is what removed the handler's hardcoded implement handoff -- feasibility's deliver stage now names implement on the task before it waits, the invariant the handler needs. The payload crosses every hop it must: the NATS action request, the gateway.v1 gRPC contract (regenerated), the LocalChatAdapter, and the webui handler, which answers 400 for a rereview without instructions and 409 for the cap. A rereview event kind names its actor the way the approval and rejection trios do. taskactions.Task gains review_gate and rereview_rounds, and the two surfaces' tests assert they agree. --- cmd/archie-ui/main_test.go | 4 +- internal/app/archied/gateway_runtime.go | 12 +- internal/app/archied/gateway_test.go | 4 +- internal/app/archied/main.go | 20 +- internal/app/archied/main_test.go | 50 +++- .../app/archied/task_action_adapter_test.go | 14 +- internal/app/archied/task_actions_test.go | 12 +- internal/app/archieui/run_test.go | 4 +- internal/channels/telegram/fake_test.go | 4 +- internal/contracts/gateway/v1/chat.pb.go | 54 +++- internal/domain/messaging/chat_contract.go | 12 +- .../domain/taskactions/cancel_path_test.go | 4 +- .../domain/taskactions/review_gate_test.go | 230 ++++++++++++++++++ internal/domain/taskactions/service.go | 143 ++++++++++- internal/domain/taskactions/service_test.go | 19 +- internal/domain/workflow/agent_test.go | 10 +- internal/domain/workflow/feasibility.go | 9 + internal/events/events.go | 9 + internal/gateway/chat_local.go | 8 +- internal/gateway/task_action_tool_test.go | 2 +- internal/gateway/task_tools.go | 7 +- internal/gateway/tasks.go | 15 +- internal/gateway/tasks_test.go | 3 +- internal/infrastructure/gatewayrpc/client.go | 21 +- .../gatewayrpc/conformance_test.go | 10 +- internal/infrastructure/gatewayrpc/server.go | 10 +- internal/infrastructure/taskactions/rpc.go | 22 +- .../infrastructure/taskactions/rpc_test.go | 11 +- internal/infrastructure/taskactions/store.go | 15 +- internal/taskstate/taskstate_test.go | 4 +- internal/webui/api_tasks.go | 45 +++- internal/webui/api_tasks_actions_test.go | 100 +++++++- internal/webui/api_tasks_test.go | 12 + proto/gateway/v1/chat.proto | 8 +- 34 files changed, 790 insertions(+), 117 deletions(-) create mode 100644 internal/domain/taskactions/review_gate_test.go diff --git a/cmd/archie-ui/main_test.go b/cmd/archie-ui/main_test.go index 0b305c318..adea31b27 100644 --- a/cmd/archie-ui/main_test.go +++ b/cmd/archie-ui/main_test.go @@ -131,11 +131,11 @@ func (f *fakeGateway) Cancel(context.Context, string) (messaging.ChatCancellatio func (f *fakeGateway) SetPersona(context.Context, string, string) (bool, error) { return false, nil } -func (f *fakeGateway) ApplyTaskAction(context.Context, string, int64, taskstate.Action) (messaging.TaskActionResult, error) { +func (f *fakeGateway) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ReviewResponse) (messaging.TaskActionResult, error) { return messaging.TaskActionResult{}, nil } -func (f *fakeGateway) ApplyOperatorTaskAction(_ context.Context, actor taskactions.Actor, id int64, action taskstate.Action) (messaging.TaskActionResult, error) { +func (f *fakeGateway) ApplyOperatorTaskAction(_ context.Context, actor taskactions.Actor, id int64, action taskstate.Action, _ taskactions.ReviewResponse) (messaging.TaskActionResult, error) { f.mu.Lock() defer f.mu.Unlock() f.actions = append(f.actions, fmt.Sprintf("%d:%s", id, action)) diff --git a/internal/app/archied/gateway_runtime.go b/internal/app/archied/gateway_runtime.go index 1e81495ef..0dc945880 100644 --- a/internal/app/archied/gateway_runtime.go +++ b/internal/app/archied/gateway_runtime.go @@ -9,7 +9,9 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/agent" "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/taskstate" "github.com/samcharles93/archie-core/internal/tools" ) @@ -63,8 +65,14 @@ func (b *boot) setupChatRuntime(ctx context.Context, cfg config.Config) error { canceller = ec } b.chatController = gateway.NewStoreTaskController(chatTaskControllerAdapter{ - taskByID: b.stateStore.TaskByID, - requeue: b.stateStore.Requeue, + taskByID: b.stateStore.TaskByID, + // Chat's /approve reaches the daemon's one task-action service rather + // 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 { + return b.taskActions().Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res) + }, cancelExecution: canceller.CancelExecution, }) b.updateService = makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)}) diff --git a/internal/app/archied/gateway_test.go b/internal/app/archied/gateway_test.go index 7558c3c57..70789df9e 100644 --- a/internal/app/archied/gateway_test.go +++ b/internal/app/archied/gateway_test.go @@ -89,11 +89,11 @@ func (stubGatewayContract) SetPersona(context.Context, string, string) (bool, er return false, nil } -func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action) (messaging.TaskActionResult, error) { +func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ReviewResponse) (messaging.TaskActionResult, error) { return messaging.TaskActionResult{}, nil } -func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (messaging.TaskActionResult, error) { +func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse) (messaging.TaskActionResult, error) { return messaging.TaskActionResult{}, nil } diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 38510281b..69c9ec9fc 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -560,7 +560,7 @@ func (a chatTaskWriterAdapter) EnqueueChatTask( type chatTaskControllerAdapter struct { taskByID func(context.Context, int64) (*workflow.Task, error) - requeue func(context.Context, int64, string, string) error + approve func(context.Context, *string, taskactions.Actor, int64, taskactions.ReviewResponse) error cancelExecution func(context.Context, int64, string, string) ([]int64, error) } @@ -578,8 +578,16 @@ func (a chatTaskControllerAdapter) ChatTaskStatus(ctx context.Context, taskID in return gateway.ChatTaskStatus{}, false, fmt.Errorf("task %d is not chat-originated", taskID) } -func (a chatTaskControllerAdapter) ApproveChatTask(ctx context.Context, taskID int64) error { - return a.requeue(ctx, taskID, workflow.StatusWaitingHuman, "implement") +func (a chatTaskControllerAdapter) ApproveChatTask(ctx context.Context, taskID int64, actor taskactions.Actor) error { + if a.approve == nil { + return fmt.Errorf("task approval is unavailable") + } + // The chat-bound identity is both the scope the task must belong to and + // the actor the record names: a chat command has no cross-identity + // 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{}) } func (a chatTaskControllerAdapter) CancelChatTask(ctx context.Context, taskID int64, reason string) error { @@ -684,15 +692,15 @@ type chatTaskActorAdapter struct { } func (a chatTaskActorAdapter) ApplyChatTaskAction( - ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, + ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse, ) (gateway.TaskActionResult, error) { if a.contract == nil { return gateway.TaskActionResult{}, gateway.ErrChatCapabilityUnavailable } if identity == nil { - return a.contract.ApplyOperatorTaskAction(ctx, actor, taskID, action) + return a.contract.ApplyOperatorTaskAction(ctx, actor, taskID, action, res) } - return a.contract.ApplyTaskAction(ctx, *identity, taskID, action) + return a.contract.ApplyTaskAction(ctx, *identity, taskID, action, res) } func chatTaskProfiles(cfg config.Config) ([]gateway.TaskProfile, string) { diff --git a/internal/app/archied/main_test.go b/internal/app/archied/main_test.go index 5423f6073..b267ce800 100644 --- a/internal/app/archied/main_test.go +++ b/internal/app/archied/main_test.go @@ -22,14 +22,17 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/forgerpc" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" + taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/taskstate" "github.com/samcharles93/archie-core/internal/taskstate/taskstatetest" "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/worktree" @@ -670,11 +673,19 @@ func TestChatTaskControllerAdapterRejectsForgeTask(t *testing.T) { func TestChatTaskControllerAdapterTransitions(t *testing.T) { task := &workflow.Task{ID: 42, Source: workflow.SourceChat, Status: workflow.StatusWaitingHuman} - var requeueFrom, requeueWorkflow, cancelReason, cancelTo string + var approveScope string + var approveActor taskactions.Actor + var approveRes taskactions.ReviewResponse + var cancelReason, cancelTo string adapter := chatTaskControllerAdapter{ taskByID: func(context.Context, int64) (*workflow.Task, error) { return task, nil }, - requeue: func(_ context.Context, _ int64, from, workflow string) error { - requeueFrom, requeueWorkflow = from, workflow + // 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 { + if scope != nil { + approveScope = *scope + } + approveActor, approveRes = actor, res return nil }, cancelExecution: func(_ context.Context, _ int64, reason, to string) ([]int64, error) { @@ -683,11 +694,17 @@ func TestChatTaskControllerAdapterTransitions(t *testing.T) { }, } - if err := adapter.ApproveChatTask(context.Background(), task.ID); err != nil { + if err := adapter.ApproveChatTask(context.Background(), task.ID, taskactions.ActorFromScope("archie")); err != nil { t.Fatalf("ApproveChatTask(): %v", err) } - if requeueFrom != workflow.StatusWaitingHuman || requeueWorkflow != "implement" { - t.Errorf("requeue = %q/%q, want waiting_human/implement", requeueFrom, requeueWorkflow) + // The scope is the chat-bound identity, and /approve carries no + // instruction or selection syntax, so the review-gate payload is empty + // (an absent selection means every offered finding). + if approveScope != "archie" || approveActor.Identity != "archie" { + t.Errorf("approve scope/actor = %q/%q, want the chat-bound identity", approveScope, approveActor.Identity) + } + if approveRes.Instructions != "" || len(approveRes.Findings) != 0 { + t.Errorf("approve payload = %+v, want the zero review response for chat", approveRes) } if err := adapter.CancelChatTask(context.Background(), task.ID, "cancelled by test"); err != nil { t.Fatalf("CancelChatTask(): %v", err) @@ -834,9 +851,15 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) { chatTaskWriterAdapter{enqueue: st.EnqueueChatTask}, profiles, ) + // Chat's /approve reaches the same task-action service the daemon wires + // (docs/prds/pr-review-operator-response.md, Decision 1), over the real + // store this test uses. + actions := taskactionstore.NewService(taskactionstore.Store{TaskStore: st}, nil, nil, nil, nil, nil, nil, nil) controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{ - taskByID: st.TaskByID, - requeue: st.Requeue, + taskByID: st.TaskByID, + approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ReviewResponse) error { + return actions.Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res) + }, cancelExecution: st.CancelExecution, }) router := gateway.NewRouter(st, nil, "test") @@ -862,6 +885,17 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) { t.Fatalf("spawned task = %+v", task) } + // Feasibility's deliver stage names implement on the task before it waits + // (docs/prds/pr-review-operator-response.md, Decision 1), so the wait the + // seed models carries that name; the approval resumes it. + waiting, err := st.TaskByID(ctx, taskID) + if err != nil || waiting == nil { + t.Fatalf("task before wait = (%+v, %v)", waiting, err) + } + waiting.Workflow = "implement" + if err := st.Update(ctx, waiting); err != nil { + t.Fatalf("name the resuming workflow: %v", err) + } taskstatetest.Seed(t.Context(), t, st, taskID, workflow.StatusQueued, workflow.StatusWaitingHuman, "await approval") task, err = st.TaskByID(ctx, taskID) if err != nil || task == nil || task.Status != workflow.StatusWaitingHuman { diff --git a/internal/app/archied/task_action_adapter_test.go b/internal/app/archied/task_action_adapter_test.go index 90dbdc477..36b397f52 100644 --- a/internal/app/archied/task_action_adapter_test.go +++ b/internal/app/archied/task_action_adapter_test.go @@ -24,9 +24,9 @@ import ( type testTaskActor struct{ b *boot } func (a testTaskActor) ApplyChatTaskAction( - ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, + ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse, ) (gateway.TaskActionResult, error) { - if err := a.b.taskActions().Apply(ctx, identity, actor, taskID, action); err != nil { + if err := a.b.taskActions().Apply(ctx, identity, actor, taskID, action, res); err != nil { return gateway.TaskActionResult{}, err } return gateway.TaskActionResult{ @@ -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) + _, err := adapter.ApplyChatTaskAction(ctx, &tc.actorIdentity, taskactions.Actor{}, task.ID, tc.action, taskactions.ReviewResponse{}) 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) + _, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.attemptAction, taskactions.ReviewResponse{}) 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) + _, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon, taskactions.ReviewResponse{}) 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) + result, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.action, taskactions.ReviewResponse{}) 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) + _, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 1, taskstate.ActionAbandon, taskactions.ReviewResponse{}) if err == nil { t.Fatal("expected error for nil contract, got nil") } diff --git a/internal/app/archied/task_actions_test.go b/internal/app/archied/task_actions_test.go index 27b371121..450fb338f 100644 --- a/internal/app/archied/task_actions_test.go +++ b/internal/app/archied/task_actions_test.go @@ -11,9 +11,12 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" + taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" + "github.com/samcharles93/archie-core/internal/taskstate" "github.com/samcharles93/archie-core/internal/taskstate/taskstatetest" "github.com/samcharles93/archie-core/internal/webui" ) @@ -80,9 +83,14 @@ func runChatAction(t *testing.T, ctx context.Context, st storecontract.TaskStore if !ok { t.Fatal("the task store cannot cancel executions") } + // Chat's /approve reaches the daemon's one task-action service + // (docs/prds/pr-review-operator-response.md, Decision 1). + actions := taskactionstore.NewService(taskactionstore.Store{TaskStore: st}, nil, nil, nil, nil, nil, nil, nil) controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{ - taskByID: st.TaskByID, - requeue: st.Requeue, + taskByID: st.TaskByID, + approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ReviewResponse) error { + return actions.Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res) + }, cancelExecution: canceller.CancelExecution, }) var err error diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go index 842a84199..1002f6dfe 100644 --- a/internal/app/archieui/run_test.go +++ b/internal/app/archieui/run_test.go @@ -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) (gateway.TaskActionResult, error) { +func (f *fakeChat) ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ReviewResponse) (gateway.TaskActionResult, error) { return gateway.TaskActionResult{}, nil } -func (f *fakeChat) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (gateway.TaskActionResult, error) { +func (f *fakeChat) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse) (gateway.TaskActionResult, error) { return gateway.TaskActionResult{}, nil } diff --git a/internal/channels/telegram/fake_test.go b/internal/channels/telegram/fake_test.go index 39ae67f64..f219cd721 100644 --- a/internal/channels/telegram/fake_test.go +++ b/internal/channels/telegram/fake_test.go @@ -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) (messaging.TaskActionResult, error) { +func (f *fakeChatContract) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse) (messaging.TaskActionResult, error) { return messaging.TaskActionResult{}, nil } -func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) { +func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse) (messaging.TaskActionResult, error) { return messaging.TaskActionResult{}, nil } diff --git a/internal/contracts/gateway/v1/chat.pb.go b/internal/contracts/gateway/v1/chat.pb.go index 9764320fa..d74b44727 100644 --- a/internal/contracts/gateway/v1/chat.pb.go +++ b/internal/contracts/gateway/v1/chat.pb.go @@ -1539,6 +1539,8 @@ type ApplyTaskActionRequest struct { Identity string `protobuf:"bytes,1,opt,name=identity,proto3" json:"identity,omitempty"` TaskId int64 `protobuf:"varint,2,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` Action string `protobuf:"bytes,3,opt,name=action,proto3" json:"action,omitempty"` + Instructions string `protobuf:"bytes,4,opt,name=instructions,proto3" json:"instructions,omitempty"` + Findings []string `protobuf:"bytes,5,rep,name=findings,proto3" json:"findings,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1594,6 +1596,20 @@ func (x *ApplyTaskActionRequest) GetAction() string { return "" } +func (x *ApplyTaskActionRequest) GetInstructions() string { + if x != nil { + return x.Instructions + } + return "" +} + +func (x *ApplyTaskActionRequest) GetFindings() []string { + if x != nil { + return x.Findings + } + return nil +} + type ApplyTaskActionResponse struct { state protoimpl.MessageState `protogen:"open.v1"` TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` @@ -1669,9 +1685,15 @@ type ApplyOperatorTaskActionRequest struct { // credited to the actor's own authority. All three are empty when the caller // has no verified identity, which is recorded as an unattributed action and // never as a human's. - ActorId string `protobuf:"bytes,3,opt,name=actor_id,json=actorId,proto3" json:"actor_id,omitempty"` - 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"` + ActorId string `protobuf:"bytes,3,opt,name=actor_id,json=actorId,proto3" json:"actor_id,omitempty"` + 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 + // 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"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1741,6 +1763,20 @@ func (x *ApplyOperatorTaskActionRequest) GetPrincipalId() string { return "" } +func (x *ApplyOperatorTaskActionRequest) GetInstructions() string { + if x != nil { + return x.Instructions + } + return "" +} + +func (x *ApplyOperatorTaskActionRequest) GetFindings() []string { + if x != nil { + return x.Findings + } + return nil +} + 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"` @@ -2961,22 +2997,26 @@ const file_gateway_v1_chat_proto_rawDesc = "" + "session_id\x18\x01 \x01(\tR\tsessionId\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\"*\n" + "\x12SetPersonaResponse\x12\x14\n" + - "\x05found\x18\x01 \x01(\bR\x05found\"e\n" + + "\x05found\x18\x01 \x01(\bR\x05found\"\xa5\x01\n" + "\x16ApplyTaskActionRequest\x12\x1a\n" + "\bidentity\x18\x01 \x01(\tR\bidentity\x12\x17\n" + "\atask_id\x18\x02 \x01(\x03R\x06taskId\x12\x16\n" + - "\x06action\x18\x03 \x01(\tR\x06action\"d\n" + + "\x06action\x18\x03 \x01(\tR\x06action\x12\"\n" + + "\finstructions\x18\x04 \x01(\tR\finstructions\x12\x1a\n" + + "\bfindings\x18\x05 \x03(\tR\bfindings\"d\n" + "\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\"\xae\x01\n" + + "\amessage\x18\x03 \x01(\tR\amessage\"\xee\x01\n" + "\x1eApplyOperatorTaskActionRequest\x12\x17\n" + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" + "\x06action\x18\x02 \x01(\tR\x06action\x12\x19\n" + "\bactor_id\x18\x03 \x01(\tR\aactorId\x12\x1d\n" + "\n" + "actor_kind\x18\x04 \x01(\tR\tactorKind\x12!\n" + - "\fprincipal_id\x18\x05 \x01(\tR\vprincipalId\"l\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" + "\x1fApplyOperatorTaskActionResponse\x12\x17\n" + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" + "\x06action\x18\x02 \x01(\tR\x06action\x12\x18\n" + diff --git a/internal/domain/messaging/chat_contract.go b/internal/domain/messaging/chat_contract.go index 63a2fa218..c973c3326 100644 --- a/internal/domain/messaging/chat_contract.go +++ b/internal/domain/messaging/chat_contract.go @@ -30,16 +30,20 @@ type ChatContract interface { //nolint:interfacebloat // wire contract intention // the Gateway. It is separate so read/turn consumers do not need to model it. type ChatTaskActionContract interface { // ApplyTaskAction applies an action on behalf of a chat identity, which - // may only act on its own tasks. - ApplyTaskAction(context.Context, string, int64, taskstate.Action) (TaskActionResult, error) + // 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) // 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 // nothing archie could verify -- which is recorded unattributed rather than // credited to a human. It is a separate method rather than an empty identity // because "" is a real identity in a single-identity deployment (see - // chatTaskProfiles in the daemon). - ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (TaskActionResult, error) + // 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) } // TaskActionResult is what task_action returns. diff --git a/internal/domain/taskactions/cancel_path_test.go b/internal/domain/taskactions/cancel_path_test.go index 21e8064d7..a45accb38 100644 --- a/internal/domain/taskactions/cancel_path_test.go +++ b/internal/domain/taskactions/cancel_path_test.go @@ -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); err != nil { + if err := service.Apply(context.Background(), nil, humanActor(), 7, tt.action, ReviewResponse{}); 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); err != nil { + if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionStop, ReviewResponse{}); err != nil { t.Fatalf("Apply(stop): %v", err) } if len(store.cancels) != 1 || store.cancels[0].to != taskstate.Parked { diff --git a/internal/domain/taskactions/review_gate_test.go b/internal/domain/taskactions/review_gate_test.go new file mode 100644 index 000000000..04a269191 --- /dev/null +++ b/internal/domain/taskactions/review_gate_test.go @@ -0,0 +1,230 @@ +package taskactions + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" + workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/taskstate" +) + +// gateStore is a fakeStore that records the review gate response write and +// the plain requeue separately, so a test can tell which path an approval +// took. +type gateStore struct { + fakeStore + + requeues []requeueCall + gateWrites []gateWrite + gateErr error +} + +type requeueCall struct { + taskID int64 + from, workflow string +} + +type gateWrite struct { + taskID int64 + from string + gate string + rereview bool + max int +} + +func (g *gateStore) Requeue(_ context.Context, taskID int64, from, workflow string) error { + g.requeues = append(g.requeues, requeueCall{taskID: taskID, from: from, workflow: workflow}) + return nil +} + +func (g *gateStore) RespondReviewGate(_ context.Context, taskID int64, from, gate string, rereview bool, maxRounds int) error { + if g.gateErr != nil { + return g.gateErr + } + g.gateWrites = append(g.gateWrites, gateWrite{taskID: taskID, from: from, gate: gate, rereview: rereview, max: maxRounds}) + return nil +} + +// offeredGate is a task waiting with the review gate offer recorded, which is +// what an operator's approve or re-review answers. +func offeredGate(findings ...prreview.ScoredFinding) *Task { + return &Task{ + ID: 7, Owner: "acme", Repo: "widgets", Status: taskstate.WaitingHuman, + ReviewGate: workflowtask.EncodeReviewGate(workflowtask.ReviewGate{ + Findings: gateDocuments(findings...), HeadSHA: "abc", Owner: "acme", Repo: "widgets", + PRNumber: 42, Workflow: "pr-review", + }), + } +} + +// gateDocuments renders scored findings the way the pipeline's gate stage +// does: the stable key an operator's selection names, beside the finding's +// own encoding. +func gateDocuments(findings ...prreview.ScoredFinding) []workflowtask.ReviewGateFinding { + out := make([]workflowtask.ReviewGateFinding, len(findings)) + for i, f := range findings { + out[i] = prreview.GateFinding(f) + } + return out +} + +func TestApproveOfAGateRecordsTheSelectionOnTheOffer(t *testing.T) { + findings := []prreview.ScoredFinding{ + {Title: "keep", File: "main.go", LineStart: 1, Body: "keep me"}, + {Title: "drop", File: "main.go", LineStart: 9, Body: "drop me"}, + } + store := &gateStore{fakeStore: fakeStore{task: offeredGate(findings...)}} + service := Service{Store: store} + + if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, + ReviewResponse{Findings: []string{findings[0].Key()}}); err != nil { + t.Fatalf("Apply(approve): %v", err) + } + if len(store.requeues) != 0 { + t.Fatalf("approve of a gate requeued plainly: %+v", store.requeues) + } + if len(store.gateWrites) != 1 { + t.Fatalf("gate writes = %+v, want exactly the one response write", store.gateWrites) + } + write := store.gateWrites[0] + if write.rereview || write.max != workflowtask.MaxRereviewRounds || write.from != taskstate.WaitingHuman { + t.Fatalf("write = %+v, want an approve, from waiting_human, at the domain cap", write) + } + gate, ok := workflowtask.DecodeReviewGate(write.gate) + if !ok || !gate.Approved() { + t.Fatalf("recorded gate = %q, want an approve", write.gate) + } + if len(gate.Selection) != 1 || gate.Selection[0] != findings[0].Key() { + t.Fatalf("recorded selection = %v, want exactly the selected key", gate.Selection) + } + if len(gate.Findings) != len(findings) { + t.Fatalf("recorded findings = %d, want the whole offer kept for the resume to post", len(gate.Findings)) + } + if got := store.last(); got.Kind != events.KindHumanApproved { + t.Fatalf("event kind = %q, want %q", got.Kind, events.KindHumanApproved) + } +} + +func TestApproveWithNoSelectionRecordsEveryOfferedFinding(t *testing.T) { + findings := []prreview.ScoredFinding{{Title: "only", File: "main.go", LineStart: 1, Body: "b"}} + store := &gateStore{fakeStore: fakeStore{task: offeredGate(findings...)}} + service := Service{Store: store} + + if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, ReviewResponse{}); err != nil { + t.Fatalf("Apply(approve): %v", err) + } + gate, _ := workflowtask.DecodeReviewGate(store.gateWrites[0].gate) + if len(gate.Selection) != 1 || gate.Selection[0] != findings[0].Key() { + t.Fatalf("selection = %v, want every offered finding's key", gate.Selection) + } +} + +func TestApproveRefusesANonOfferedFindingKey(t *testing.T) { + store := &gateStore{fakeStore: fakeStore{task: offeredGate(prreview.ScoredFinding{Title: "offered", File: "main.go", LineStart: 1})}} + service := Service{Store: store} + + err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionApprove, + ReviewResponse{Findings: []string{"main.go:99:stale"}}) + if !errors.Is(err, ErrConflict) { + t.Fatalf("Apply(approve with a stale key) = %v, want ErrConflict", err) + } + if len(store.gateWrites) != 0 { + t.Fatalf("refused approve wrote %+v", store.gateWrites) + } +} + +// TestApproveWithoutAGateKeepsTheTasksWorkflow is the feasibility handoff: +// no gate offer means there is no review to answer, and the approval releases +// waiting work under the workflow the wait recorded. It must not hardcode +// implement -- the PRD's Decision 1 -- which is why feasibility names +// implement itself before it waits. +func TestApproveWithoutAGateKeepsTheTasksWorkflow(t *testing.T) { + store := &gateStore{fakeStore: fakeStore{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 { + t.Fatalf("Apply(approve): %v", err) + } + if len(store.gateWrites) != 0 { + t.Fatalf("a task with no gate wrote %+v", store.gateWrites) + } + if len(store.requeues) != 1 || store.requeues[0].workflow != "" || store.requeues[0].from != taskstate.WaitingHuman { + t.Fatalf("requeues = %+v, want one waiting_human requeue that keeps the task's workflow", store.requeues) + } +} + +func TestRereviewRecordsInstructionsAndClearsTheOffer(t *testing.T) { + findings := []prreview.ScoredFinding{{Title: "old", File: "main.go", LineStart: 1}} + store := &gateStore{fakeStore: fakeStore{task: offeredGate(findings...)}} + service := Service{Store: store} + + if err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionRereview, + ReviewResponse{Instructions: "look at the migration ordering"}); err != nil { + t.Fatalf("Apply(rereview): %v", err) + } + write := store.gateWrites[0] + if !write.rereview { + t.Fatalf("write = %+v, want the rereview flag that increments the round count", write) + } + gate, _ := workflowtask.DecodeReviewGate(write.gate) + if gate.Outcome != workflowtask.GateRereview || gate.Instructions != "look at the migration ordering" { + t.Fatalf("recorded gate = %+v, want the re-review outcome and instructions", gate) + } + if len(gate.Findings) != 0 || len(gate.Selection) != 0 { + t.Fatalf("re-review kept the offer: %+v; the resumed run recomputes it", gate) + } + if got := store.last(); got.Kind != events.KindHumanRereviewed { + t.Fatalf("event kind = %q, want %q", got.Kind, events.KindHumanRereviewed) + } +} + +func TestRereviewRefusedWithoutInstructionsAndAtTheCap(t *testing.T) { + tests := []struct { + name string + task *Task + res ReviewResponse + want string + }{ + { + name: "no instructions", + task: offeredGate(prreview.ScoredFinding{Title: "f", File: "main.go", LineStart: 1}), + want: "instructions", + }, + { + name: "no gate offer", + task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: taskstate.WaitingHuman}, + res: ReviewResponse{Instructions: "look again"}, + want: "no review gate", + }, + { + name: "at the cap", + task: func() *Task { + task := offeredGate(prreview.ScoredFinding{Title: "f", File: "main.go", LineStart: 1}) + task.RereviewRounds = workflowtask.MaxRereviewRounds + return task + }(), + res: ReviewResponse{Instructions: "look again"}, + want: "re-reviews", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + store := &gateStore{fakeStore: fakeStore{task: tc.task}} + service := Service{Store: store} + err := service.Apply(context.Background(), nil, humanActor(), 7, taskstate.ActionRereview, tc.res) + if !errors.Is(err, ErrConflict) { + t.Fatalf("Apply(rereview) = %v, want ErrConflict", err) + } + if !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error = %q, want it to name %q", err, tc.want) + } + if len(store.gateWrites) != 0 || len(store.requeues) != 0 || len(store.events) != 0 { + t.Fatalf("a refused re-review wrote store state: gate=%+v requeues=%+v events=%+v", store.gateWrites, store.requeues, store.events) + } + }) + } +} diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index 90cc401f3..0c0b3bfcd 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/domain/identity" + workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -24,6 +25,15 @@ type Task struct { Owner, Repo, Identity, Status, ParkReason string IssueNumber, RetryCount int ForgeBacked bool + // 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 + // writes the answered document back. + ReviewGate string + // RereviewRounds is how many re-reviews this task's gate has granted. The + // service reads it to refuse a re-review at the cap before the guarded + // write, and the write itself re-checks it in the row. + RereviewRounds int // Attempt is the run the operator acted on. It is stamped onto the event // this action records so an intervention is attributable to the run it // changed course -- without it a retry or a stop is indistinguishable @@ -31,6 +41,19 @@ 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 { + // 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 +} + // Actor is the identity that performed an action, and the principal whose // authority permitted it. // @@ -117,11 +140,31 @@ func rejectedKind(actor Actor) string { } } +// rereviewedKind names a re-review's actor the way the approved and rejected +// trios do: the kind describes the ACTOR, so an agent asking for a re-review is +// never recorded as a person's, and an action with no verified actor is +// recorded as a task-level event that credits nobody. +func rereviewedKind(actor Actor) string { + switch { + case actor.Human(): + return events.KindHumanRereviewed + case actor.Attributed(): + return events.KindAgentRereviewed + default: + return events.KindTaskRereviewed + } +} + 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 + // 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 + // requeues, refusing a re-review past the cap with ErrRereviewCapReached. + RespondReviewGate(context.Context, int64, string, string, bool, int) error ArchiveTask(context.Context, int64, string, events.Event) (int64, error) InsertEvent(context.Context, events.Event) (int64, error) // CancelExecution is the one cancel path @@ -153,7 +196,13 @@ 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. -func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64, action taskstate.Action) error { +// +// 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 { task, err := s.Store.TaskByID(ctx, id) if err != nil { return err @@ -167,7 +216,7 @@ func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64 if err := taskstate.CheckAction(task.Status, action); err != nil { return fmt.Errorf("%w: %w", ErrConflict, err) } - mutation, err := s.apply(ctx, task, actor, action) + mutation, err := s.apply(ctx, task, actor, action, res) if err != nil { return err } @@ -194,13 +243,13 @@ 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) (outcome, error) { +func (s Service) apply(ctx context.Context, task *Task, actor Actor, action taskstate.Action, res ReviewResponse) (outcome, error) { o := outcome{event: s.attributed(task, actor)} switch action { case taskstate.ActionApprove: - err := s.Store.Requeue(ctx, task.ID, "waiting_human", "implement") - o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved") - return o, err + return s.applyApprove(ctx, task, actor, o, res) + case taskstate.ActionRereview: + return s.applyRereview(ctx, task, actor, o, res) case taskstate.ActionRetry: return s.applyRetry(ctx, task, actor, o) case taskstate.ActionStop: @@ -223,6 +272,88 @@ func (s Service) apply(ctx context.Context, task *Task, actor Actor, action task } } +// applyApprove is the one approval path, for both the review gate and the +// human-decision waits that predate it (feasibility's PRD handoff). +// +// A task carrying a gate offer gets the answer recorded on that offer in the +// guarded response write: the resumed run posts the recorded review filtered +// by the operator's selection, which is the only way "post the findings the +// operator selected" can mean the findings they saw. A task with no gate has +// no review to answer, so the approval is the plain release of waiting work; +// 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) { + o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved") + gate, ok := workflowtask.DecodeReviewGate(task.ReviewGate) + if !ok || !gate.Offered() { + return o, s.Store.Requeue(ctx, task.ID, task.Status, "") + } + selection, err := selectedFindingKeys(gate, res.Findings) + if err != nil { + return o, err + } + gate.Outcome = workflowtask.GateApprove + gate.Selection = selection + gate.Instructions = "" + if err := s.Store.RespondReviewGate(ctx, task.ID, task.Status, workflowtask.EncodeReviewGate(gate), false, workflowtask.MaxRereviewRounds); err != nil { + return o, err + } + o.event.Detail = fmt.Sprintf("%s (%d of %d finding(s) selected)", actor.describe("approved"), len(selection), len(gate.Findings)) + return o, nil +} + +// applyRereview records the operator's instructions and requeues the review +// phases. It is refused, as a conflict, for a task with no gate offer and for +// 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) { + 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) + } + if strings.TrimSpace(res.Instructions) == "" { + return o, fmt.Errorf("a re-review needs instructions: %w", ErrConflict) + } + if task.RereviewRounds >= workflowtask.MaxRereviewRounds { + return o, fmt.Errorf("task %d has used all %d re-reviews: %w", task.ID, workflowtask.MaxRereviewRounds, ErrConflict) + } + gate.Outcome = workflowtask.GateRereview + gate.Instructions = strings.TrimSpace(res.Instructions) + gate.Findings = nil + gate.Selection = nil + o.event.Kind, o.event.Detail = rereviewedKind(actor), actor.describe("requested a re-review") + if err := s.Store.RespondReviewGate(ctx, task.ID, task.Status, workflowtask.EncodeReviewGate(gate), true, workflowtask.MaxRereviewRounds); err != nil { + return o, err + } + return o, nil +} + +// selectedFindingKeys resolves an approve's selection against the offered +// findings. An absent selection means all of them; a selection naming a +// finding this offer does not hold is refused, because silently posting +// nothing is how an operator's answer turns into a review nobody sees. +func selectedFindingKeys(gate workflowtask.ReviewGate, requested []string) ([]string, error) { + offered := make(map[string]struct{}, len(gate.Findings)) + keys := make([]string, 0, len(gate.Findings)) + for _, f := range gate.Findings { + offered[f.Key] = struct{}{} + keys = append(keys, f.Key) + } + if len(requested) == 0 { + return keys, nil + } + selection := make([]string, 0, len(requested)) + for _, key := range requested { + if _, ok := offered[key]; !ok { + return nil, fmt.Errorf("finding %q is not part of this review offer: %w", key, ErrConflict) + } + selection = append(selection, key) + } + return selection, nil +} + // deliver cancels the in-memory context of a run the store has already // recorded as cancelled. It is the delivery mechanism, never a second store // write, and it follows the record -- the PRD's order, which the step rows diff --git a/internal/domain/taskactions/service_test.go b/internal/domain/taskactions/service_test.go index fbbd27556..3e8cc3b48 100644 --- a/internal/domain/taskactions/service_test.go +++ b/internal/domain/taskactions/service_test.go @@ -24,6 +24,11 @@ func (f *fakeStore) CancelExecution(context.Context, int64, string, string) ([]i } func (f *fakeStore) Requeue(context.Context, int64, string, string) error { return nil } + +func (f *fakeStore) RespondReviewGate(context.Context, int64, string, string, bool, int) error { + return nil +} + func (f *fakeStore) RetryTask(context.Context, int64, string, string) error { return nil } @@ -82,7 +87,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); err != nil { + if err := service.Apply(context.Background(), nil, tc.actor, 7, tc.action, ReviewResponse{}); err != nil { t.Fatalf("Apply() error = %v", err) } got := store.last() @@ -107,7 +112,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); err != nil { + if err := service.Apply(context.Background(), nil, actor, 7, taskstate.ActionApprove, ReviewResponse{}); err != nil { t.Fatalf("Apply() error = %v", err) } @@ -132,7 +137,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); err != nil { + if err := service.Apply(context.Background(), nil, Actor{}, 7, taskstate.ActionApprove, ReviewResponse{}); err != nil { t.Fatalf("Apply() error = %v", err) } @@ -167,7 +172,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); err != nil { + if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action, ReviewResponse{}); err != nil { t.Fatalf("Apply(%s) error = %v", tc.action, err) } got := store.last() @@ -186,14 +191,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); err == nil { + if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove, ReviewResponse{}); 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); err == nil { + if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove, ReviewResponse{}); err == nil { t.Fatal("Apply() allowed a scoped caller to act on a foreign task") } } @@ -233,7 +238,7 @@ func TestOnlyRejectAndCancelCloseTheIssue(t *testing.T) { closed = true return nil }} - if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action); err != nil { + if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action, ReviewResponse{}); err != nil { t.Fatalf("Apply(%s) error = %v", tc.action, err) } if closed != tc.closes { diff --git a/internal/domain/workflow/agent_test.go b/internal/domain/workflow/agent_test.go index e0f6ac970..268e906aa 100644 --- a/internal/domain/workflow/agent_test.go +++ b/internal/domain/workflow/agent_test.go @@ -240,7 +240,7 @@ func TestFeasibilityChatTaskAvoidsIssueOperations(t *testing.T) { } }) - t.Run("await approval", func(t *testing.T) { + t.Run("await approval names the workflow the wait resumes", func(t *testing.T) { forgeClient := &fakeForge{} tc := &TaskContext{ Task: &Task{ @@ -258,6 +258,14 @@ func TestFeasibilityChatTaskAvoidsIssueOperations(t *testing.T) { t.Fatalf("comments/watch/outcome = %d/%d/%q", len(forgeClient.commented), tc.Task.WatchCommentID, tc.Outcome.Status) } + // The approval handler requeues under the workflow the wait recorded, + // because a shared handler cannot hardcode implement without sending + // a pr-review gate wait back through implement + // (docs/prds/pr-review-operator-response.md, Decision 1). Feasibility + // owns the handoff by naming implement here. + if tc.Task.Workflow != "implement" { + t.Fatalf("workflow at the wait = %q, want %q: the approval resumes the workflow the wait names", tc.Task.Workflow, "implement") + } }) } diff --git a/internal/domain/workflow/feasibility.go b/internal/domain/workflow/feasibility.go index 4f21409a4..528fabf6d 100644 --- a/internal/domain/workflow/feasibility.go +++ b/internal/domain/workflow/feasibility.go @@ -96,6 +96,15 @@ func Feasibility() Workflow { // the decision surfaces; the forge issue is not a chat log. {Name: "deliver", Run: func(ctx context.Context, tc *TaskContext) error { notify(ctx, tc, "feasibility_prd") + // The approval handoff is a workflow change, not a payload + // the approve handler names: an approval requeues under the + // workflow the wait recorded (an empty name keeps the task's), + // so the task must name implement before it enters the wait. + // Hardcoding "implement" in the handler is how a gate wait on + // the standalone pr-review workflow would have re-run the + // implement workflow (docs/prds/pr-review-operator-response.md, + // Decision 1). + tc.Task.Workflow = "implement" tc.Outcome = Outcome{Status: StatusWaitingHuman, Detail: "PRD delivered, awaiting go/no-go"} return nil }}, diff --git a/internal/events/events.go b/internal/events/events.go index 2cf470309..78111279b 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -53,6 +53,15 @@ const ( // recorded as human_* and agent_* respectively. KindTaskApproved = "task_approved" KindTaskRejected = "task_rejected" + // KindHumanRereviewed, KindAgentRereviewed and KindTaskRereviewed record + // the operator asking the review gate for a re-review. The answer is + // neither an approval nor a rejection, and recording it as either would + // make the timeline claim a verdict the operator did not give. They follow + // the same actor/agent/task attribution split as the approved and rejected + // trios above. + KindHumanRereviewed = "human_rereviewed" + KindAgentRereviewed = "agent_rereviewed" + KindTaskRereviewed = "task_rereviewed" // KindTaskRetried records what the retry was escaping from. RetryTask // clears stage and park_reason in the same statement that increments the // count, so this event is the only place that context survives. diff --git a/internal/gateway/chat_local.go b/internal/gateway/chat_local.go index 99e5c7796..aed1a4d15 100644 --- a/internal/gateway/chat_local.go +++ b/internal/gateway/chat_local.go @@ -118,18 +118,18 @@ 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) (TaskActionResult, error) { +func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (TaskActionResult, error) { if a.TaskActor == nil { return TaskActionResult{}, ErrChatCapabilityUnavailable } - return a.TaskActor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, action) + 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) (TaskActionResult, error) { +func (a *LocalChatAdapter) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (TaskActionResult, error) { if a.TaskActor == nil { return TaskActionResult{}, ErrChatCapabilityUnavailable } - return a.TaskActor.ApplyChatTaskAction(ctx, nil, actor, taskID, action) + return a.TaskActor.ApplyChatTaskAction(ctx, nil, actor, taskID, action, res) } func (a *LocalChatAdapter) Stream(ctx context.Context, in Inbound) (<-chan ChatEvent, error) { diff --git a/internal/gateway/task_action_tool_test.go b/internal/gateway/task_action_tool_test.go index 0432e5b46..ab743038b 100644 --- a/internal/gateway/task_action_tool_test.go +++ b/internal/gateway/task_action_tool_test.go @@ -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) (TaskActionResult, error) { +func (f *fakeActor) ApplyChatTaskAction(_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse) (TaskActionResult, error) { if identity != nil { f.gotIdentity = *identity } diff --git a/internal/gateway/task_tools.go b/internal/gateway/task_tools.go index dcb0593e9..f9fb9ac82 100644 --- a/internal/gateway/task_tools.go +++ b/internal/gateway/task_tools.go @@ -77,8 +77,9 @@ type ChatTaskActor interface { // tasks. A nil identity is an authenticated dashboard operator, who acts // across identities -- the distinction internal/domain/taskactions draws, // and not the same as an empty name, which is a real identity in a - // single-identity deployment. - ApplyChatTaskAction(ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action) (TaskActionResult, error) + // 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) } // ChatTaskLogEntry is one log line as task_logs returns it. It mirrors @@ -330,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)) + result, err := actor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, taskstate.Action(actionStr), taskactions.ReviewResponse{}) if err != nil { return nil, fmt.Errorf("task_action: %w", err) } diff --git a/internal/gateway/tasks.go b/internal/gateway/tasks.go index df13dcfdd..ffa4c351c 100644 --- a/internal/gateway/tasks.go +++ b/internal/gateway/tasks.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -135,9 +136,15 @@ type chatTaskController interface { // ChatTaskStatus returns the task's status and owning identity, and // false if no task with that ID exists. ChatTaskStatus(ctx context.Context, taskID int64) (ChatTaskStatus, bool, error) - // ApproveChatTask requeues a waiting_human task. Callers must have - // already validated the current status is waiting_human. - ApproveChatTask(ctx context.Context, taskID int64) error + // ApproveChatTask releases a waiting_human task through the daemon's one + // task-action service, so chat and the dashboard cannot record different + // decisions for one operator intent (docs/prds/pr-review-operator- + // response.md, Decision 1). The caller has already validated the current + // status is waiting_human; the actor is the chat-bound identity, never an + // operator acting across identities. There is no review-gate payload: the + // chat surface has no instruction or selection syntax, so an approve posts + // every offered finding. + ApproveChatTask(ctx context.Context, taskID int64, actor taskactions.Actor) error // CancelChatTask transitions an active task to a rejected/terminal // state. Callers must have already validated the current status is // cancellable. @@ -184,7 +191,7 @@ func (c *StoreTaskController) Approve(ctx context.Context, taskID int64, identit if err := taskstate.CheckApprove(st.Status); err != nil { return err } - return c.store.ApproveChatTask(ctx, taskID) + return c.store.ApproveChatTask(ctx, taskID, taskactions.ActorFromScope(identity)) } func (c *StoreTaskController) Cancel(ctx context.Context, taskID int64, identity string) error { diff --git a/internal/gateway/tasks_test.go b/internal/gateway/tasks_test.go index 38cb79638..845c09e1b 100644 --- a/internal/gateway/tasks_test.go +++ b/internal/gateway/tasks_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -205,7 +206,7 @@ func (f *fakeChatTaskStore) ChatTaskStatus(ctx context.Context, taskID int64) (C return st, ok, nil } -func (f *fakeChatTaskStore) ApproveChatTask(ctx context.Context, taskID int64) error { +func (f *fakeChatTaskStore) ApproveChatTask(ctx context.Context, taskID int64, _ taskactions.Actor) error { f.approved = append(f.approved, taskID) return nil } diff --git a/internal/infrastructure/gatewayrpc/client.go b/internal/infrastructure/gatewayrpc/client.go index 8abfd4d55..a6401a724 100644 --- a/internal/infrastructure/gatewayrpc/client.go +++ b/internal/infrastructure/gatewayrpc/client.go @@ -82,21 +82,26 @@ 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) (messaging.TaskActionResult, error) { - v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{Identity: identity, TaskId: taskID, Action: string(action)}) +func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (messaging.TaskActionResult, error) { + v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{ + Identity: identity, TaskId: taskID, Action: string(action), + Instructions: res.Instructions, Findings: res.Findings, + }) if err != nil { return messaging.TaskActionResult{}, taskActionError(err) } 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) (messaging.TaskActionResult, error) { +func (c *Client) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, res taskactions.ReviewResponse) (messaging.TaskActionResult, error) { v, err := c.client.ApplyOperatorTaskAction(ctx, &pb.ApplyOperatorTaskActionRequest{ - TaskId: taskID, - Action: string(action), - ActorId: string(actor.Identity), - ActorKind: string(actor.Kind), - PrincipalId: string(actor.Principal), + TaskId: taskID, + Action: string(action), + ActorId: string(actor.Identity), + ActorKind: string(actor.Kind), + PrincipalId: string(actor.Principal), + Instructions: res.Instructions, + Findings: res.Findings, }) if err != nil { return messaging.TaskActionResult{}, taskActionError(err) diff --git a/internal/infrastructure/gatewayrpc/conformance_test.go b/internal/infrastructure/gatewayrpc/conformance_test.go index 4e135ece0..28b2c3670 100644 --- a/internal/infrastructure/gatewayrpc/conformance_test.go +++ b/internal/infrastructure/gatewayrpc/conformance_test.go @@ -145,7 +145,7 @@ type recordingTaskActor struct { } func (a *recordingTaskActor) ApplyChatTaskAction( - _ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, + _ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, _ taskactions.ReviewResponse, ) (gateway.TaskActionResult, error) { a.identity, a.taskID, a.action = identity, taskID, action return gateway.TaskActionResult{TaskID: taskID, Action: string(action), Message: "applied"}, nil @@ -169,7 +169,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) { chat = remoteChat(t, local) } - result, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 42, taskstate.ActionApprove) + result, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 42, taskstate.ActionApprove, taskactions.ReviewResponse{}) if err != nil { t.Fatalf("operator action: %v", err) } @@ -183,7 +183,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) { t.Fatalf("operator result = %+v, want the daemon's result", result) } - if _, err := chat.ApplyTaskAction(ctx, "scout", 7, taskstate.ActionRetry); err != nil { + if _, err := chat.ApplyTaskAction(ctx, "scout", 7, taskstate.ActionRetry, taskactions.ReviewResponse{}); err != nil { t.Fatalf("chat action: %v", err) } if actor.identity == nil || *actor.identity != "scout" { @@ -197,7 +197,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) { type failingTaskActor struct{ err error } func (a failingTaskActor) ApplyChatTaskAction( - context.Context, *string, taskactions.Actor, int64, taskstate.Action, + context.Context, *string, taskactions.Actor, int64, taskstate.Action, taskactions.ReviewResponse, ) (gateway.TaskActionResult, error) { return gateway.TaskActionResult{}, a.err } @@ -221,7 +221,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) + _, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 7, taskstate.ActionApprove, taskactions.ReviewResponse{}) if err == nil { t.Fatalf("ApplyOperatorTaskAction error = nil, want %v", tc.err) } diff --git a/internal/infrastructure/gatewayrpc/server.go b/internal/infrastructure/gatewayrpc/server.go index a8bcd7034..0627fc2bc 100644 --- a/internal/infrastructure/gatewayrpc/server.go +++ b/internal/infrastructure/gatewayrpc/server.go @@ -92,7 +92,10 @@ 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)) + v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action), taskactions.ReviewResponse{ + Instructions: r.Instructions, + Findings: r.Findings, + }) if err != nil { return nil, taskActionStatus(err) } @@ -105,7 +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)) + v, err := s.chat.ApplyOperatorTaskAction(ctx, actor, r.TaskId, taskstate.Action(r.Action), taskactions.ReviewResponse{ + Instructions: r.Instructions, + Findings: r.Findings, + }) if err != nil { return nil, taskActionStatus(err) } diff --git a/internal/infrastructure/taskactions/rpc.go b/internal/infrastructure/taskactions/rpc.go index 09d02caf5..ddb26ca33 100644 --- a/internal/infrastructure/taskactions/rpc.go +++ b/internal/infrastructure/taskactions/rpc.go @@ -36,6 +36,12 @@ type actionRequest struct { TaskID int64 `json:"task_id"` 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 + // approve and rereview, and for chat surfaces, which carry no selection + // syntax. + Instructions string `json:"instructions,omitempty"` + Findings []string `json:"findings,omitempty"` } type actorPayload struct { @@ -74,6 +80,7 @@ var actionErrorKinds = []struct { {kind: "not_found", err: taskactions.ErrNotFound}, {kind: "conflict", err: taskactions.ErrConflict}, {kind: "stale_transition", err: storecontract.ErrStaleTransition}, + {kind: "rereview_cap", err: storecontract.ErrRereviewCapReached}, {kind: "unavailable", err: taskactions.ErrUnavailable}, } @@ -120,7 +127,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) + err := service.Apply(context.Background(), req.Identity, req.Actor.actor(), req.TaskID, req.Action, taskactions.ReviewResponse{ + Instructions: req.Instructions, + Findings: req.Findings, + }) natsrpc.Respond(msg, log, "taskactions", actionResponse{ Envelope: natsrpc.NewEnvelope(err), Kind: actionErrorKind(err), @@ -142,14 +152,16 @@ 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) (gateway.TaskActionResult, error) { +func (c Client) ApplyChatTaskAction(ctx context.Context, scope *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ReviewResponse) (gateway.TaskActionResult, error) { if c.Conn == nil { return gateway.TaskActionResult{}, fmt.Errorf("task action connection is unavailable") } request := actionRequest{ - Identity: scope, - TaskID: id, - Action: action, + Identity: scope, + TaskID: id, + Action: action, + Instructions: res.Instructions, + Findings: res.Findings, Actor: &actorPayload{ ID: string(actor.Identity), Kind: string(actor.Kind), diff --git a/internal/infrastructure/taskactions/rpc_test.go b/internal/infrastructure/taskactions/rpc_test.go index d57c27fa6..2001ee624 100644 --- a/internal/infrastructure/taskactions/rpc_test.go +++ b/internal/infrastructure/taskactions/rpc_test.go @@ -45,7 +45,10 @@ func (s stubStore) Transition(context.Context, int64, string, string, string) er func (s stubStore) CancelExecution(context.Context, int64, string, string) ([]int64, error) { return nil, s.err } -func (s stubStore) Requeue(context.Context, int64, string, string) error { return s.err } +func (s stubStore) Requeue(context.Context, int64, string, string) error { return s.err } +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) ArchiveTask(context.Context, int64, string, events.Event) (int64, error) { @@ -108,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) + _, err = Client{Conn: nc}.ApplyChatTaskAction(t.Context(), nil, domain.Actor{}, 7, tc.action, domain.ReviewResponse{}) if err == nil { t.Fatalf("ApplyChatTaskAction(%s) error = nil, want %v", tc.action, tc.want) } @@ -116,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) + direct := service.Apply(t.Context(), nil, domain.Actor{}, 7, tc.action, domain.ReviewResponse{}) if direct == nil || err.Error() != direct.Error() { t.Fatalf("remote message = %q, want the daemon's own %v", err.Error(), direct) } @@ -155,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) + result, err := Client{Conn: nc}.ApplyChatTaskAction(t.Context(), tc.identity, domain.Actor{}, 7, taskstate.ActionAbandon, domain.ReviewResponse{}) if err != nil { t.Fatalf("apply: %v", err) } diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go index b182acd99..09534de61 100644 --- a/internal/infrastructure/taskactions/store.go +++ b/internal/infrastructure/taskactions/store.go @@ -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()}, 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, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil } // CancelExecution delegates to the store's one cancel path @@ -33,6 +33,19 @@ func (s Store) CancelExecution(ctx context.Context, taskID int64, reason, to str return canceller.CancelExecution(ctx, taskID, reason, to) } +// RespondReviewGate delegates to the store's guarded response write. Both +// adapters -- the PostgreSQL store and the remote gRPC client -- implement it +// (internal/domain/storecontract.ReviewGateResponder); the type assertion +// failing would be a composition bug, so it is named rather than panicked +// over, exactly like CancelExecution above. +func (s Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error { + responder, ok := s.TaskStore.(storecontract.ReviewGateResponder) + if !ok { + return fmt.Errorf("task store cannot record a review gate response") + } + return responder.RespondReviewGate(ctx, taskID, fromStatus, gate, rereview, maxRounds) +} + func MaxRetries(cfg *config.Holder) func(*taskactions.Task) int { return func(t *taskactions.Task) int { if cfg == nil { diff --git a/internal/taskstate/taskstate_test.go b/internal/taskstate/taskstate_test.go index 6b445bea3..7f7c3d8c9 100644 --- a/internal/taskstate/taskstate_test.go +++ b/internal/taskstate/taskstate_test.go @@ -17,7 +17,7 @@ func TestActionRules(t *testing.T) { }{ {status: Queued, decline: true, actions: []Action{ActionCancel, ActionReject}}, {status: Running, decline: true, actions: []Action{ActionStop, ActionReject}}, - {status: WaitingHuman, approve: true, decline: true, actions: []Action{ActionApprove, ActionReject}}, + {status: WaitingHuman, approve: true, decline: true, actions: []Action{ActionApprove, ActionReject, ActionRereview}}, {status: PROpen, decline: true, actions: []Action{ActionOpenPR, ActionOpenIssue, ActionReject}}, {status: Parked, retry: true, decline: true, actions: []Action{ActionRetry, ActionAbandon, ActionReject}}, {status: Merged, terminal: true, actions: []Action{ActionArchive}}, @@ -150,7 +150,7 @@ func TestPresentationCatalog(t *testing.T) { func TestActionsReturnsIndependentSlices(t *testing.T) { first := Actions(WaitingHuman) first[0] = ActionArchive - if got := Actions(WaitingHuman); !slices.Equal(got, []Action{ActionApprove, ActionReject}) { + if got := Actions(WaitingHuman); !slices.Equal(got, []Action{ActionApprove, ActionReject, ActionRereview}) { t.Fatalf("mutating returned actions changed lifecycle table: %v", got) } } diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 18c299730..fb4b12f50 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -189,6 +189,16 @@ func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) { type taskActionRequest struct { Action string `json:"action"` + // Instructions is the re-review's focus, required by the rereview action + // and ignored by every other one (docs/prds/pr-review-operator- + // response.md, Decision 1). The dashboard is the authoritative surface + // that carries operators' instructions; chat is a shortcut with no + // instruction syntax. + Instructions string `json:"instructions"` + // Findings are the keys of the offered findings an approve posts; an + // absent selection means all of them. It is ignored by every other + // action. + Findings []string `json:"findings"` } func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { @@ -200,15 +210,16 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { http.Error(w, "bad id", http.StatusBadRequest) return } - action, ok := decodeTaskAction(w, r) + action, res, ok := decodeTaskAction(w, r) if !ok { return } - if err := s.applyOperatorTaskAction(r.Context(), id, action); err != nil { + if err := s.applyOperatorTaskAction(r.Context(), id, action, res); err != nil { switch { case errors.Is(err, taskactions.ErrNotFound): http.Error(w, "task not found", http.StatusNotFound) - case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storecontract.ErrStaleTransition): + case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storecontract.ErrStaleTransition), + errors.Is(err, storecontract.ErrRereviewCapReached): http.Error(w, err.Error(), http.StatusConflict) case errors.Is(err, taskactions.ErrUnavailable): http.Error(w, err.Error(), http.StatusServiceUnavailable) @@ -221,7 +232,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, bool) { +func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, taskactions.ReviewResponse, bool) { r.Body = http.MaxBytesReader(w, r.Body, 4096) var req taskActionRequest decoder := json.NewDecoder(r.Body) @@ -229,28 +240,36 @@ 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 "", false + return "", taskactions.ReviewResponse{}, false } http.Error(w, "invalid action", http.StatusBadRequest) - return "", false + return "", taskactions.ReviewResponse{}, false } if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { http.Error(w, "invalid action", http.StatusBadRequest) - return "", false + return "", taskactions.ReviewResponse{}, false } action := taskstate.Action(req.Action) if !taskMutation(action) { http.Error(w, "unknown action", http.StatusBadRequest) - return "", false + return "", taskactions.ReviewResponse{}, false } - return action, true + // 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 + // than a round trip's conflict. The service re-checks it for the surfaces + // 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 action, taskactions.ReviewResponse{Instructions: req.Instructions, Findings: req.Findings}, true } func taskMutation(action taskstate.Action) bool { switch action { case taskstate.ActionCancel, taskstate.ActionStop, taskstate.ActionApprove, - taskstate.ActionReject, taskstate.ActionRetry, taskstate.ActionAbandon, - taskstate.ActionArchive: + taskstate.ActionReject, taskstate.ActionRereview, taskstate.ActionRetry, + taskstate.ActionAbandon, taskstate.ActionArchive: return true default: return false @@ -340,7 +359,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) error { +func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ReviewResponse) error { if s.Chat == nil || s.Chat.Contract == nil { return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable) } @@ -352,7 +371,7 @@ func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action t if value, ok := ActingIdentity(ctx); ok { actor = taskactions.ActorFor(value) } - _, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action) + _, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res) return err } diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 1b9ee2ca8..ac137fdcc 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -18,6 +18,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/domain/workflow" + workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" @@ -71,7 +72,7 @@ type daemonActions struct { } func (d *daemonActions) ApplyChatTaskAction( - ctx context.Context, identity *string, actor taskactions.Actor, id int64, action taskstate.Action, + ctx context.Context, identity *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ReviewResponse, ) (gateway.TaskActionResult, error) { d.scopes = append(d.scopes, identity) service := taskactionstore.NewService( @@ -84,7 +85,7 @@ func (d *daemonActions) ApplyChatTaskAction( d.publish(), d.srv.logf, ) - if err := service.Apply(ctx, identity, actor, id, action); err != nil { + if err := service.Apply(ctx, identity, actor, id, action, res); err != nil { return gateway.TaskActionResult{}, err } return gateway.TaskActionResult{TaskID: id, Action: string(action)}, nil @@ -472,6 +473,99 @@ func TestTaskActionErrorMapping(t *testing.T) { } } +// postActionBody posts one raw action body through the dashboard handler. +func postActionBody(t *testing.T, srv *Server, id int64, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, + "/api/tasks/"+strconv.FormatInt(id, 10)+"/action", bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Archie-CSRF", "1") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + return w +} + +// TestTaskActionRecordsTheReviewGateAnswer is the dashboard half of Decision +// 1: the action body carries instructions (required by rereview) and the +// finding keys approve posts, and the answer lands on the task's review_gate +// document through the same path chat uses. +func TestTaskActionRecordsTheReviewGateAnswer(t *testing.T) { + keep := workflowtask.ReviewGateFinding{Key: "main.go:1:keep", Finding: json.RawMessage(`{"file":"main.go","line_start":1,"title":"keep","body":"keep me"}`)} + drop := workflowtask.ReviewGateFinding{Key: "main.go:9:drop", Finding: json.RawMessage(`{"file":"main.go","line_start":9,"title":"drop","body":"drop me"}`)} + offer := workflowtask.EncodeReviewGate(workflowtask.ReviewGate{ + Findings: []workflowtask.ReviewGateFinding{keep, drop}, HeadSHA: "abc", Owner: "acme", Repo: "widget", + PRNumber: 42, Workflow: "pr-review", + }) + + t.Run("approve records the selection", func(t *testing.T) { + srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review") + if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Workflow: "pr-review", ReviewGate: offer}); err != nil { + t.Fatalf("seed the offer: %v", err) + } + w := postActionBody(t, srv, task.ID, fmt.Sprintf(`{"action":"approve","findings":[%q]}`, keep.Key)) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + updated, err := srv.Store.TaskByID(t.Context(), task.ID) + if err != nil || updated == nil { + t.Fatalf("TaskByID = (%+v, %v)", updated, err) + } + gate, ok := workflowtask.DecodeReviewGate(updated.ReviewGate) + if !ok || !gate.Approved() { + t.Fatalf("recorded gate = %q, want an approve", updated.ReviewGate) + } + if len(gate.Selection) != 1 || gate.Selection[0] != keep.Key { + t.Fatalf("recorded selection = %v, want only the posted key", gate.Selection) + } + if updated.Status != workflow.StatusQueued { + t.Fatalf("status = %q, want %q", updated.Status, workflow.StatusQueued) + } + }) + + t.Run("rereview records the instructions and clears the offer", func(t *testing.T) { + srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review") + if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Workflow: "pr-review", ReviewGate: offer}); err != nil { + t.Fatalf("seed the offer: %v", err) + } + w := postActionBody(t, srv, task.ID, `{"action":"rereview","instructions":"the migration ordering"}`) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + updated, err := srv.Store.TaskByID(t.Context(), task.ID) + if err != nil || updated == nil { + t.Fatalf("TaskByID = (%+v, %v)", updated, err) + } + gate, _ := workflowtask.DecodeReviewGate(updated.ReviewGate) + if gate.Outcome != workflowtask.GateRereview || gate.Instructions != "the migration ordering" { + t.Fatalf("recorded gate = %+v, want the re-review outcome and instructions", gate) + } + if len(gate.Findings) != 0 { + t.Fatalf("re-review kept the offer: %+v", gate.Findings) + } + if updated.RereviewRounds != 1 { + t.Fatalf("rereview rounds = %d, want 1 (the guarded write counts it)", updated.RereviewRounds) + } + }) + + t.Run("rereview without instructions is refused before any write", func(t *testing.T) { + srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review") + if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Workflow: "pr-review", ReviewGate: offer}); err != nil { + t.Fatalf("seed the offer: %v", err) + } + w := postActionBody(t, srv, task.ID, `{"action":"rereview"}`) + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", w.Code, w.Body) + } + updated, err := srv.Store.TaskByID(t.Context(), task.ID) + if err != nil || updated == nil { + t.Fatalf("TaskByID = (%+v, %v)", updated, err) + } + if updated.Status != workflow.StatusWaitingHuman || updated.RereviewRounds != 0 { + t.Fatalf("refused re-review changed the row: %+v", updated) + } + }) +} + // TestTaskActionIsUnscopedAndRemote covers what routing through the Gateway // contract has to preserve: the dashboard operator is authenticated and acts // across identities, so the action must arrive unscoped rather than claiming @@ -544,7 +638,7 @@ func TestTaskListExposesLifecycleActions(t *testing.T) { want := map[string][]string{ workflow.StatusQueued: {"cancel", "reject"}, workflow.StatusRunning: {"stop", "reject"}, - workflow.StatusWaitingHuman: {"approve", "reject"}, + workflow.StatusWaitingHuman: {"approve", "reject", "rereview"}, workflow.StatusParked: {"retry", "abandon", "reject"}, workflow.StatusPROpen: {"open_pr", "open_issue", "reject"}, workflow.StatusMerged: {"archive"}, diff --git a/internal/webui/api_tasks_test.go b/internal/webui/api_tasks_test.go index cb7e949a7..d4d0a7638 100644 --- a/internal/webui/api_tasks_test.go +++ b/internal/webui/api_tasks_test.go @@ -265,6 +265,18 @@ func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) { if err := srv.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "review"); err != nil { t.Fatal(err) } + // The wait names the workflow the approval resumes (feasibility's deliver + // stage sets implement before it waits); the handler keeps it rather than + // hardcoding one, so the approval runs the workflow the task carries + // (docs/prds/pr-review-operator-response.md, Decision 1). + waiting, err := srv.Store.TaskByID(ctx, task.ID) + if err != nil || waiting == nil { + t.Fatalf("TaskByID before approve = (%+v, %v)", waiting, err) + } + waiting.Workflow = "implement" + if err := srv.Store.Update(ctx, waiting); err != nil { + t.Fatalf("name the resuming workflow: %v", err) + } req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`)) req.Header.Set("Content-Type", "application/json") diff --git a/proto/gateway/v1/chat.proto b/proto/gateway/v1/chat.proto index da07b758f..2a8889f26 100644 --- a/proto/gateway/v1/chat.proto +++ b/proto/gateway/v1/chat.proto @@ -141,7 +141,7 @@ message CancelRequest { string session_id = 1; } message CancelResponse { bool cancelled = 1; int64 dropped = 2; } message SetPersonaRequest { string session_id = 1; string name = 2; } message SetPersonaResponse { bool found = 1; } -message ApplyTaskActionRequest { string identity = 1; int64 task_id = 2; string action = 3; } +message ApplyTaskActionRequest { string identity = 1; int64 task_id = 2; string action = 3; string instructions = 4; repeated string findings = 5; } message ApplyTaskActionResponse { int64 task_id = 1; string action = 2; string message = 3; } // An authenticated dashboard operator acts across identities, so this request // carries no identity to scope against -- the distinction the daemon's task @@ -160,6 +160,12 @@ message ApplyOperatorTaskActionRequest { string actor_id = 3; string actor_kind = 4; string principal_id = 5; + // instructions and findings are the review gate answer payload + // (taskactions.ReviewResponse): the instructions a rereview requires, and + // the finding keys an approve posts (empty means every offered finding). + // They are empty for every other action. + string instructions = 6; + repeated string findings = 7; } message ApplyOperatorTaskActionResponse { int64 task_id = 1; string action = 2; string message = 3; } message SaveSessionResponse {}