feat(daemon): wire the review-reaction consumer to remediate runs

The remediate workflow was registered but had no trigger: the reaction
stream was provisioned, the envelope, resolver and owned-PR lookup all
landed, yet nothing consumed the stream (pr-review-remediation.md's
sequencing left the consumer for this step). The daemon now drains the
reaction stream each cycle, before the task drain, so a reaction can be
claimed in the same pass that carried it.

Per decision 3, the store's owned-PR lookup is the authorization
boundary: an unmatched, merged or closed PR drops with a counter, and a
public reaction can never start an agent against a foreign repository.
Per decision 5, a review is the unit of remediation -- its comment
events are appended to the unit while it is queued and dropped once the
run is claimed (the round cap bounds the exchange); a standalone comment
is its own unit of one; approved reviews never remediate; and archie's
own comments, matched on the owning identity's bot user, are excluded so
its replies cannot retrigger it.

The guarded BeginRemediation/UpdateReviewPayload store methods are the
dedup: the pr_open -> queued transition carries the review unit in the
same write, so re-delivered reactions fail the status guard instead of
starting a second round. Both are new StateStoreService RPCs following
the Requeue shape, covered by the local/grpc conformance battery.
This commit is contained in:
sam committed 2026-09-23 12:08:44 +10:00
1 parent 2393ec6dae
commit 052e350bf1
13 files changed
+1662 -491

No files matched your search

+5
View File
@@ -185,6 +185,9 @@ type boot struct {
lastReload func() config.ReloadStatus
natsClient *nats.Client
// reactionClient pulls the ARCHIE_REACTIONS fan-out stream; the daemon
// drains it each cycle to turn review reactions into remediate runs.
reactionClient *nats.Client
// natsURL is the endpoint the daemon's own client connected with at
// startup. For external mode it is cfg.NATS.URL; for embedded mode it is
// the embedded server's ClientURL(). Recorded so Daemon.ConnectedNATS
@@ -552,6 +555,7 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed
// is the deliverable. A future producer (bead archie-core-8li9.3) will
// need its own publisher surface, wired when that step lands.
b.addCleanup(func() { reactionClient.Close() })
b.reactionClient = reactionClient
log.Info("nats connected", "url", url, "task_stream", nats.DefaultStreamName, "reaction_stream", nats.DefaultReactionStreamName)
return nil
}
@@ -1289,6 +1293,7 @@ func (b *boot) buildDaemon() {
Storage: b.storeBackend,
Log: log,
Tasks: b.natsClient,
Reactions: b.reactionClient,
WorktreeGrants: b.worktreeGrants,
StateStoreGrants: b.stateStoreGrants,
ContainerPool: b.containerPool,
File diff suppressed because it is too large. Load diff
@@ -40,6 +40,8 @@ const (
StateStoreService_RecoverStale_FullMethodName = "/state.v1.StateStoreService/RecoverStale"
StateStoreService_ArchiveTask_FullMethodName = "/state.v1.StateStoreService/ArchiveTask"
StateStoreService_RetryTask_FullMethodName = "/state.v1.StateStoreService/RetryTask"
StateStoreService_BeginRemediation_FullMethodName = "/state.v1.StateStoreService/BeginRemediation"
StateStoreService_UpdateReviewPayload_FullMethodName = "/state.v1.StateStoreService/UpdateReviewPayload"
StateStoreService_TaskByIssue_FullMethodName = "/state.v1.StateStoreService/TaskByIssue"
StateStoreService_OpenTaskByPR_FullMethodName = "/state.v1.StateStoreService/OpenTaskByPR"
StateStoreService_TaskByID_FullMethodName = "/state.v1.StateStoreService/TaskByID"
@@ -124,6 +126,8 @@ type StateStoreServiceClient interface {
// Archive / Retry
ArchiveTask(ctx context.Context, in *ArchiveTaskRequest, opts ...grpc.CallOption) (*ArchiveTaskResponse, error)
RetryTask(ctx context.Context, in *RetryTaskRequest, opts ...grpc.CallOption) (*RetryTaskResponse, error)
BeginRemediation(ctx context.Context, in *BeginRemediationRequest, opts ...grpc.CallOption) (*BeginRemediationResponse, error)
UpdateReviewPayload(ctx context.Context, in *UpdateReviewPayloadRequest, opts ...grpc.CallOption) (*UpdateReviewPayloadResponse, error)
// Queries
TaskByIssue(ctx context.Context, in *TaskByIssueRequest, opts ...grpc.CallOption) (*TaskByIssueResponse, error)
OpenTaskByPR(ctx context.Context, in *OpenTaskByPRRequest, opts ...grpc.CallOption) (*OpenTaskByPRResponse, error)
@@ -432,6 +436,26 @@ func (c *stateStoreServiceClient) RetryTask(ctx context.Context, in *RetryTaskRe
return out, nil
}
func (c *stateStoreServiceClient) BeginRemediation(ctx context.Context, in *BeginRemediationRequest, opts ...grpc.CallOption) (*BeginRemediationResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BeginRemediationResponse)
err := c.cc.Invoke(ctx, StateStoreService_BeginRemediation_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) UpdateReviewPayload(ctx context.Context, in *UpdateReviewPayloadRequest, opts ...grpc.CallOption) (*UpdateReviewPayloadResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateReviewPayloadResponse)
err := c.cc.Invoke(ctx, StateStoreService_UpdateReviewPayload_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) TaskByIssue(ctx context.Context, in *TaskByIssueRequest, opts ...grpc.CallOption) (*TaskByIssueResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(TaskByIssueResponse)
@@ -921,6 +945,8 @@ type StateStoreServiceServer interface {
// Archive / Retry
ArchiveTask(context.Context, *ArchiveTaskRequest) (*ArchiveTaskResponse, error)
RetryTask(context.Context, *RetryTaskRequest) (*RetryTaskResponse, error)
BeginRemediation(context.Context, *BeginRemediationRequest) (*BeginRemediationResponse, error)
UpdateReviewPayload(context.Context, *UpdateReviewPayloadRequest) (*UpdateReviewPayloadResponse, error)
// Queries
TaskByIssue(context.Context, *TaskByIssueRequest) (*TaskByIssueResponse, error)
OpenTaskByPR(context.Context, *OpenTaskByPRRequest) (*OpenTaskByPRResponse, error)
@@ -1082,6 +1108,12 @@ func (UnimplementedStateStoreServiceServer) ArchiveTask(context.Context, *Archiv
func (UnimplementedStateStoreServiceServer) RetryTask(context.Context, *RetryTaskRequest) (*RetryTaskResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RetryTask not implemented")
}
func (UnimplementedStateStoreServiceServer) BeginRemediation(context.Context, *BeginRemediationRequest) (*BeginRemediationResponse, error) {
return nil, status.Error(codes.Unimplemented, "method BeginRemediation not implemented")
}
func (UnimplementedStateStoreServiceServer) UpdateReviewPayload(context.Context, *UpdateReviewPayloadRequest) (*UpdateReviewPayloadResponse, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateReviewPayload not implemented")
}
func (UnimplementedStateStoreServiceServer) TaskByIssue(context.Context, *TaskByIssueRequest) (*TaskByIssueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TaskByIssue not implemented")
}
@@ -1607,6 +1639,42 @@ func _StateStoreService_RetryTask_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_BeginRemediation_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BeginRemediationRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).BeginRemediation(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_BeginRemediation_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).BeginRemediation(ctx, req.(*BeginRemediationRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_UpdateReviewPayload_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateReviewPayloadRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).UpdateReviewPayload(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_UpdateReviewPayload_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).UpdateReviewPayload(ctx, req.(*UpdateReviewPayloadRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_TaskByIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TaskByIssueRequest)
if err := dec(in); err != nil {
@@ -2433,6 +2501,14 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "RetryTask",
Handler: _StateStoreService_RetryTask_Handler,
},
{
MethodName: "BeginRemediation",
Handler: _StateStoreService_BeginRemediation_Handler,
},
{
MethodName: "UpdateReviewPayload",
Handler: _StateStoreService_UpdateReviewPayload_Handler,
},
{
MethodName: "TaskByIssue",
Handler: _StateStoreService_TaskByIssue_Handler,
+48 -1
View File
@@ -25,6 +25,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
"github.com/samcharles93/archie-core/internal/events"
@@ -132,7 +133,17 @@ type Daemon struct {
// NATS startup is mandatory (there is no broker-off execution mode), so
// production composition always sets it. Nil appears only in tests and
// is handled fail-closed at the publish/run sites.
Tasks TaskBus
Tasks TaskBus
// reactionConsumer is built lazily by drainReactions and kept for its
// lifetime drop counter.
reactionConsumer *reactionConsumer
// Reactions pulls the review-reaction fan-out stream
// (docs/prds/pr-review-remediation.md). Each cycle it is drained into
// queued remediate runs before the task drain, so a reaction can be
// claimed in the same pass that carried it. Optional: nil disables the
// reaction consumer (tests, or a deployment without the reaction
// stream).
Reactions ReactionSource
WorktreeGrants WorktreeGrantIssuer
// StateStoreGrants issues per-task State Store credentials for container
// env (see containerEnv). Required whenever ConnectedStateStore.URL is
@@ -487,6 +498,7 @@ func (d *Daemon) maintainAndDrain(ctx context.Context) {
d.cleanupExpiredStorage(ctx)
d.reconcilePRs(ctx)
d.dispatchBindings(ctx)
d.drainReactions(ctx)
if d.Tasks != nil {
d.drainNATS(ctx)
}
@@ -561,6 +573,7 @@ func (d *Daemon) Cycle(ctx context.Context) {
d.poll(ctx)
d.reconcilePRs(ctx)
d.dispatchBindings(ctx)
d.drainReactions(ctx)
if d.Tasks != nil {
d.drainNATS(ctx)
}
@@ -778,6 +791,40 @@ func (d *Daemon) resolveBindingRepo(b binding.Binding) (string, string, bool) {
return "", "", false
}
// drainReactions turns available review reactions into queued remediate
// runs. It runs before the task drain so a reaction queued in this pass can
// be claimed by it; the consumer is built lazily once, so its drop counter
// spans the process lifetime.
func (d *Daemon) drainReactions(ctx context.Context) {
if d.Reactions == nil || d.Store == nil {
return
}
if d.reactionConsumer == nil {
d.reactionConsumer = newReactionConsumer(
// The store's owned-PR lookup is the authorization boundary: a
// reaction only ever causes work against a PR archie opened and
// still owns (pr-review-remediation.md decision 3).
d.Store,
d.Store,
d.botUserForTask,
d.Log,
)
}
if _, err := d.reactionConsumer.drain(ctx, d.Reactions, maxReactionsPerCycle); err != nil {
d.Log.Error("reaction drain failed", "err", err)
}
}
// botUserForTask resolves the bot login that owns task, so the reaction
// consumer can exclude Archie's own comments. Identity-derived for
// multi-identity deployments, the global forge bot user otherwise.
func (d *Daemon) botUserForTask(task *workflowtask.Task) string {
if runner := d.identityFor(task); runner != nil {
return runner.Cfg.BotUser
}
return d.Cfg.Get().BotUser
}
// drainNATS processes tasks from NATS, falling back to SQLite ClaimNext for
// requeued tasks (waiting_human approval, retry-parked) that didn't come
// through a NATS publish.
+234
View File
@@ -0,0 +1,234 @@
package daemon
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
)
// ReactionSource is the pull surface the reaction consumer needs: fetch one
// message from the reaction stream, or eventbus.ErrNoMessage when it is
// drained. Narrow on purpose -- the consumer never publishes and never
// subscribes.
type ReactionSource interface {
Fetch(ctx context.Context) (eventbus.Message, error)
}
// maxReactionsPerCycle bounds one drain pass. Reactions are row updates, not
// agent runs, but an unbounded drain could hold the dispatch loop hostage
// behind a burst; anything past the bound waits for the next cycle.
const maxReactionsPerCycle = 32
// remediableReviewStates are the review states a remediation unit addresses.
// approved is a decision-5 exclusion (recording, not remediating; merging
// stays an operator action) and dismissed is withdrawn feedback.
var remediableReviewStates = map[string]bool{
"requested_changes": true,
"commented": true,
}
// reactionConsumer turns forge review reactions on Archie-owned PRs into
// queued remediate runs. It implements the consumer half of
// docs/prds/pr-review-remediation.md decisions 3 and 5: resolve the PR to
// the task that owns it (the authorization boundary), never react to
// Archie's own comments, collect a review's comments into one unit while it
// is pending, and rely on the guarded store transition for dedup.
type reactionConsumer struct {
lookup workintake.ReviewTaskLookup
remediations storecontract.RemediationStarter
botUser func(*workflowtask.Task) string
log *slog.Logger
dropped int64
}
func newReactionConsumer(
lookup workintake.ReviewTaskLookup,
remediations storecontract.RemediationStarter,
botUser func(*workflowtask.Task) string,
log *slog.Logger,
) *reactionConsumer {
return &reactionConsumer{lookup: lookup, remediations: remediations, botUser: botUser, log: log}
}
// drain fetches and handles reactions until the stream is idle or the
// per-cycle bound is reached, returning how many messages it handled.
func (c *reactionConsumer) drain(ctx context.Context, src ReactionSource, limit int) (int, error) {
handled := 0
for handled < limit {
msg, err := src.Fetch(ctx)
if err != nil {
if errors.Is(err, eventbus.ErrNoMessage) {
return handled, nil
}
return handled, fmt.Errorf("fetch reaction: %w", err)
}
if ctx.Err() != nil {
return handled, ctx.Err()
}
c.handle(ctx, msg)
handled++
}
return handled, nil
}
// handle processes one reaction to a terminal outcome: Ack on every decided
// path (drop, dedup, or work queued), Nak only on a transient store failure
// the next delivery can succeed against.
func (c *reactionConsumer) handle(ctx context.Context, msg eventbus.Message) {
envelope, err := workintake.DecodeReviewComment(msg.Data())
if err != nil {
c.log.Error("review reaction decode failed", "subject", msg.Subject(), "err", err)
_ = msg.Ack() // it will never decode on redelivery
return
}
task, err := c.lookup.OpenTaskByPR(ctx, envelope.Owner, envelope.Repo, envelope.PRNumber)
if err != nil {
c.log.Error("review reaction lookup failed", "owner", envelope.Owner, "repo", envelope.Repo, "pr", envelope.PRNumber, "err", err)
_ = msg.Nak()
return
}
if task == nil {
// The resolver counts this: a reaction that does not resolve to a
// live task Archie owns is dropped, never work.
c.drop(msg, "no live task owns this PR")
return
}
if c.botUser(task) != "" && envelope.Author == c.botUser(task) {
// Decision 5: only Archie's own comments are excluded, so its
// ReplyToReview replies never retrigger it. Every other author --
// human or bot -- is actionable.
c.drop(msg, "reaction is archie's own comment")
return
}
switch envelope.Kind {
case workintake.ReviewReactionReview:
c.handleReview(ctx, msg, task, envelope)
case workintake.ReviewReactionComment:
c.handleComment(ctx, msg, task, envelope)
default:
c.drop(msg, "unknown reaction kind")
}
}
func (c *reactionConsumer) handleReview(ctx context.Context, msg eventbus.Message, task *workflowtask.Task, e workintake.ReviewCommentEnvelope) {
if !remediableReviewStates[e.State] {
// approved: no remediation, and never auto-merge (decision 5). The
// review state is visible on the forge itself.
c.drop(msg, fmt.Sprintf("review state %q does not trigger remediation", e.State))
return
}
unit := workflow.ReviewUnit{ReviewID: e.ReviewID, Author: e.Author, State: e.State, Body: e.Body}
payload, err := workflow.EncodeReviewUnit(unit)
if err != nil {
c.log.Error("review unit encode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if err := c.remediations.BeginRemediation(ctx, task.ID, payload); err != nil {
if errors.Is(err, storecontract.ErrStaleTransition) {
// Already queued or claimed: a re-delivered review, or a second
// reaction for a review whose unit is pending. The guarded
// transition is the dedup.
c.log.Debug("remediation already pending", "task", task.ID, "review", e.ReviewID)
_ = msg.Ack()
return
}
c.log.Error("BeginRemediation failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
c.log.Info("review reaction queued a remediation", "task", task.ID, "pr", fmt.Sprintf("%s/%s#%d", e.Owner, e.Repo, e.PRNumber), "review", e.ReviewID, "state", e.State)
_ = msg.Ack()
}
func (c *reactionConsumer) handleComment(ctx context.Context, msg eventbus.Message, task *workflowtask.Task, e workintake.ReviewCommentEnvelope) {
if e.ReviewID == 0 {
// Decision 5: a standalone comment with no parent review is its own
// unit of one.
unit := workflow.ReviewUnit{Comments: []workflow.ReviewUnitComment{{
CommentID: e.CommentID, Path: e.Path, Line: e.Line, Body: e.Body,
}}}
payload, err := workflow.EncodeReviewUnit(unit)
if err != nil {
c.log.Error("review unit encode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if err := c.remediations.BeginRemediation(ctx, task.ID, payload); err != nil {
if errors.Is(err, storecontract.ErrStaleTransition) {
_ = msg.Ack()
return
}
c.log.Error("BeginRemediation failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
_ = msg.Ack()
return
}
// A comment with a parent review is collected into that review's pending
// unit, never dispatched alone. Once the unit has been claimed, its input
// is frozen: a late comment is dropped, and the round cap bounds the
// exchange if the reviewer re-reviews.
if task.Status != workflow.StatusQueued || task.Workflow != "remediate" {
c.drop(msg, "parent review's unit is no longer pending")
return
}
unit, err := workflow.DecodeReviewUnit(task.ReviewPayload)
if err != nil {
if errors.Is(err, workflow.ErrNoReviewPayload) {
c.drop(msg, "queued remediation carries no review unit")
return
}
c.log.Error("review payload decode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if unit.ReviewID != e.ReviewID {
c.drop(msg, "comment's parent review is not the pending unit")
return
}
for _, existing := range unit.Comments {
if existing.CommentID == e.CommentID {
_ = msg.Ack() // re-delivery of an already-collected comment
return
}
}
unit.Comments = append(unit.Comments, workflow.ReviewUnitComment{
CommentID: e.CommentID, Path: e.Path, Line: e.Line, Body: e.Body,
})
payload, err := workflow.EncodeReviewUnit(unit)
if err != nil {
c.log.Error("review unit encode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if err := c.remediations.UpdateReviewPayload(ctx, task.ID, payload); err != nil {
if errors.Is(err, storecontract.ErrStaleTransition) {
// Claimed between the read and the write: the unit is frozen.
_ = msg.Ack()
return
}
c.log.Error("UpdateReviewPayload failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
_ = msg.Ack()
}
func (c *reactionConsumer) drop(msg eventbus.Message, reason string) {
c.dropped++
c.log.Info("review reaction dropped", "subject", msg.Subject(), "reason", reason)
_ = msg.Ack()
}
+367
View File
@@ -0,0 +1,367 @@
package daemon
import (
"context"
"errors"
"log/slog"
"sync"
"testing"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
)
// ---- fakes ----
type fakeReactionSource struct {
mu sync.Mutex
pending []eventbus.Message
fetchErr error
}
func (f *fakeReactionSource) Fetch(ctx context.Context) (eventbus.Message, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.fetchErr != nil {
return nil, f.fetchErr
}
if len(f.pending) == 0 {
return nil, eventbus.ErrNoMessage
}
m := f.pending[0]
f.pending = f.pending[1:]
return m, nil
}
type fakeReactionMessage struct {
data []byte
subject string
mu sync.Mutex
acked bool
nakked bool
}
func (m *fakeReactionMessage) Data() []byte { return m.data }
func (m *fakeReactionMessage) Subject() string { return m.subject }
func (m *fakeReactionMessage) Ack() error {
m.mu.Lock()
defer m.mu.Unlock()
m.acked = true
return nil
}
func (m *fakeReactionMessage) Nak() error {
m.mu.Lock()
defer m.mu.Unlock()
m.nakked = true
return nil
}
func (m *fakeReactionMessage) wasAcked() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.acked
}
func (m *fakeReactionMessage) wasNakked() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.nakked
}
type fakeRemediations struct {
begun []string // payloads handed to BeginRemediation, in order
updated []string
beginErr error
}
func (f *fakeRemediations) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
if f.beginErr != nil {
return f.beginErr
}
f.begun = append(f.begun, payload)
return nil
}
func (f *fakeRemediations) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
f.updated = append(f.updated, payload)
return nil
}
type fakeReviewLookup struct {
task *workflowtask.Task
err error
// sequence, when set, is consulted before task, so a test can model the
// store's fresh read per message (e.g. a unit that queued between two
// reactions).
sequence func(call int) (*workflowtask.Task, error)
calls int
}
func (f *fakeReviewLookup) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error) {
f.calls++
if f.sequence != nil {
return f.sequence(f.calls)
}
return f.task, f.err
}
// ---- helpers ----
func reviewEnvelopeJSON(kind string, reviewID, commentID int64, author, state, body string) []byte {
e := workintake.ReviewCommentEnvelope{
Owner: "acme", Repo: "widgets", PRNumber: 42,
Kind: workintake.ReviewReactionKind(kind),
ReviewID: reviewID, CommentID: commentID,
Author: author, State: state, Body: body,
}
data, err := e.Encode()
if err != nil {
panic(err)
}
return data
}
func ownedTask(status, workflowName, payload string) *workflowtask.Task {
t := &workflowtask.Task{
ID: 7, Owner: "acme", Repo: "widgets", PRNumber: 42,
Status: status, Workflow: workflowName, ReviewPayload: payload,
}
return t
}
func newConsumer(task *workflowtask.Task, remediations *fakeRemediations) *reactionConsumer {
return newReactionConsumer(
&fakeReviewLookup{task: task},
remediations,
func(*workflowtask.Task) string { return "archie-bot" },
slog.New(slog.DiscardHandler),
)
}
// ---- tests ----
func TestReactionConsumerReviewEventStartsARemediation(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "please fix x")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 1 {
t.Fatalf("BeginRemediation calls = %d, want 1", len(remediations.begun))
}
unit, err := workflow.DecodeReviewUnit(remediations.begun[0])
if err != nil {
t.Fatal(err)
}
if unit.ReviewID != 7 || unit.State != "requested_changes" || unit.Body != "please fix x" {
t.Errorf("unit = %+v, want the review's own coordinates", unit)
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerApprovedReviewDoesNotRemediate(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "approved", "lgtm")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 {
t.Errorf("BeginRemediation called for an approved review")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerOwnCommentNeverRetriggers(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 0, 9, "archie-bot", "", "my own reply")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 || len(remediations.updated) != 0 {
t.Errorf("own comment triggered work: begun=%d updated=%d", len(remediations.begun), len(remediations.updated))
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerCommentAppendsToThePendingUnitOfItsReview(t *testing.T) {
remediations := &fakeRemediations{}
pending := ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"state":"requested_changes"}`)
c := newConsumer(pending, remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "fix the loop")}
c.handle(context.Background(), msg)
if len(remediations.updated) != 1 {
t.Fatalf("UpdateReviewPayload calls = %d, want 1", len(remediations.updated))
}
unit, err := workflow.DecodeReviewUnit(remediations.updated[0])
if err != nil {
t.Fatal(err)
}
if unit.ReviewID != 7 || len(unit.Comments) != 1 || unit.Comments[0].CommentID != 9 {
t.Errorf("appended unit = %+v, want comment 9 under review 7", unit)
}
// The parent review's summary survives the append.
if unit.State != "requested_changes" {
t.Errorf("unit state = %q, want the parent review's state preserved", unit.State)
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerDuplicateCommentIsNotAppendedTwice(t *testing.T) {
remediations := &fakeRemediations{}
pending := ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"comments":[{"comment_id":9,"body":"fix the loop"}]}`)
c := newConsumer(pending, remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "fix the loop")}
c.handle(context.Background(), msg)
if len(remediations.updated) != 0 {
t.Errorf("UpdateReviewPayload called for a comment the unit already carries")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerLateCommentAfterDispatchIsDropped(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
// A comment carrying a parent review id, but the task is not a queued
// remediation for it: the unit already dispatched.
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "late comment")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 || len(remediations.updated) != 0 {
t.Errorf("late comment mutated store state: begun=%d updated=%d", len(remediations.begun), len(remediations.updated))
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerStandaloneCommentIsItsOwnUnit(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 0, 12, "alice", "", "nit: rename")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 1 {
t.Fatalf("BeginRemediation calls = %d, want 1", len(remediations.begun))
}
unit, err := workflow.DecodeReviewUnit(remediations.begun[0])
if err != nil {
t.Fatal(err)
}
if len(unit.Comments) != 1 || unit.Comments[0].CommentID != 12 {
t.Errorf("unit = %+v, want one standalone comment", unit)
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerUnresolvablePRIsDropped(t *testing.T) {
remediations := &fakeRemediations{}
// nil task: the PR does not belong to an archie-owned task.
c := newConsumer(nil, remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "unrelated")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 {
t.Errorf("reaction for a foreign PR started work")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerInvalidEnvelopeIsAckedNotRedelivered(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: []byte(`{"owner":"acme"}`)} // no kind, no ids
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 {
t.Errorf("invalid envelope started work")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerTransientStoreErrorNaks(t *testing.T) {
remediations := &fakeRemediations{beginErr: errors.New("db unavailable")}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "please fix x")}
c.handle(context.Background(), msg)
if !msg.wasNakked() {
t.Error("transient failure was not nakked for redelivery")
}
if msg.wasAcked() {
t.Error("transient failure was acked")
}
}
func TestReactionConsumerDrainsUntilIdle(t *testing.T) {
remediations := &fakeRemediations{}
// The lookup reads the row fresh per message: the review event queues the
// remediation, so the comment event resolves against the queued unit.
lookup := &fakeReviewLookup{sequence: func(call int) (*workflowtask.Task, error) {
if call == 1 {
return ownedTask(workflowtask.StatusPROpen, "implement", ""), nil
}
return ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"state":"requested_changes","body":"one"}`), nil
}}
c := newReactionConsumer(lookup, remediations, func(*workflowtask.Task) string { return "archie-bot" }, slog.New(slog.DiscardHandler))
src := &fakeReactionSource{pending: []eventbus.Message{
&fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "one")},
&fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 8, "alice", "", "one-a")},
}}
n, err := c.drain(context.Background(), src, 8)
if err != nil {
t.Fatal(err)
}
if n != 2 {
t.Errorf("handled = %d, want 2", n)
}
// The review queued the unit; the comment appended to it.
if len(remediations.begun) != 1 || len(remediations.updated) != 1 {
t.Errorf("begun=%d updated=%d, want 1/1", len(remediations.begun), len(remediations.updated))
}
unit, err := workflow.DecodeReviewUnit(remediations.updated[0])
if err != nil {
t.Fatal(err)
}
if len(unit.Comments) != 1 || unit.Comments[0].CommentID != 8 {
t.Errorf("appended unit = %+v, want comment 8 collected under review 7", unit)
}
}
// compile-time interface checks
var (
_ workintake.ReviewTaskLookup = (*fakeReviewLookup)(nil)
_ storecontract.RemediationStarter = (*fakeRemediations)(nil)
)
@@ -36,6 +36,7 @@ type TaskStore interface {
TaskQueries
TaskArchiver
TaskRetryer
RemediationStarter
}
// TaskLifecycle manages the core task state machine and enqueuing.
@@ -66,6 +67,17 @@ type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) error
}
// RemediationStarter queues a review-triggered remediation for an
// Archie-owned open-PR task: one guarded transition that carries the
// JSON-encoded review unit in the same write, so a claimed remediation
// always has its input. UpdateReviewPayload appends late-arriving comments
// to a still-queued unit. Both guards are the reaction consumer's dedup and
// are documented in docs/prds/pr-review-remediation.md decisions 3 and 5.
type RemediationStarter interface {
BeginRemediation(ctx context.Context, taskID int64, payload string) error
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
}
// TaskQueries groups read-only task accessors.
type TaskQueries interface {
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
@@ -134,6 +134,16 @@ func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf str
return unmapError(err)
}
func (c *Client) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
_, err := c.client.BeginRemediation(ctx, &pb.BeginRemediationRequest{TaskId: taskID, Payload: payload})
return unmapError(err)
}
func (c *Client) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
_, err := c.client.UpdateReviewPayload(ctx, &pb.UpdateReviewPayloadRequest{TaskId: taskID, Payload: payload})
return unmapError(err)
}
// Queries
func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) {
@@ -172,6 +172,35 @@ func TestStateStoreConformance(t *testing.T) {
t.Fatalf("Transition stale = %v, want ErrStaleTransition", err)
}
// Remediation starter: the guarded transition carries the review
// unit, and both guards are the wire contract (the sentinel must
// survive the hop for the reaction consumer's dedup to work).
if err := c.Transition(ctx, task.ID, "running", "pr_open", "PR opened"); err != nil {
t.Fatalf("Transition to pr_open: %v", err)
}
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); err != nil {
t.Fatalf("BeginRemediation: %v", err)
}
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); !errors.Is(err, store.ErrStaleTransition) {
t.Fatalf("BeginRemediation stale = %v, want ErrStaleTransition", err)
}
remediated, err := c.TaskByID(ctx, task.ID)
if err != nil || remediated == nil {
t.Fatalf("TaskByID after BeginRemediation: %+v %v", remediated, err)
}
if remediated.Status != "queued" || remediated.Workflow != "remediate" || remediated.ReviewPayload != `{"review_id":7}` {
t.Fatalf("BeginRemediation row = status:%q workflow:%q payload:%q", remediated.Status, remediated.Workflow, remediated.ReviewPayload)
}
if err := c.UpdateReviewPayload(ctx, task.ID, `{"review_id":7,"comments":[{"comment_id":9}]}`); err != nil {
t.Fatalf("UpdateReviewPayload: %v", err)
}
if err := c.Transition(ctx, task.ID, "queued", "running", "claimed"); err != nil {
t.Fatalf("claim: %v", err)
}
if err := c.UpdateReviewPayload(ctx, task.ID, `{}`); !errors.Is(err, store.ErrStaleTransition) {
t.Fatalf("UpdateReviewPayload stale = %v, want ErrStaleTransition", err)
}
// TaskQueries: found=false is not an error.
missing, err := c.TaskByID(ctx, task.ID+999999)
if err != nil || missing != nil {
@@ -202,6 +202,20 @@ func (s *server) RetryTask(ctx context.Context, r *pb.RetryTaskRequest) (*pb.Ret
return &pb.RetryTaskResponse{}, nil
}
func (s *server) BeginRemediation(ctx context.Context, r *pb.BeginRemediationRequest) (*pb.BeginRemediationResponse, error) {
if err := s.deps.Tasks.BeginRemediation(ctx, r.TaskId, r.Payload); err != nil {
return nil, s.logErr("BeginRemediation", err)
}
return &pb.BeginRemediationResponse{}, nil
}
func (s *server) UpdateReviewPayload(ctx context.Context, r *pb.UpdateReviewPayloadRequest) (*pb.UpdateReviewPayloadResponse, error) {
if err := s.deps.Tasks.UpdateReviewPayload(ctx, r.TaskId, r.Payload); err != nil {
return nil, s.logErr("UpdateReviewPayload", err)
}
return &pb.UpdateReviewPayloadResponse{}, nil
}
// Queries
func (s *server) TaskByIssue(ctx context.Context, r *pb.TaskByIssueRequest) (*pb.TaskByIssueResponse, error) {
+109
View File
@@ -0,0 +1,109 @@
package store
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// prOpenTask inserts a task and walks it to the state a reaction resolves
// against: the task opened its PR and is idle waiting for review.
func prOpenTask(t *testing.T, s *Store, owner, repo string, prNumber int) int64 {
t.Helper()
ok, err := s.EnqueueIssue(t.Context(), owner, repo, 1, "title", "body", "", "")
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("enqueue: task already tracked")
}
task, err := s.TaskByIssue(t.Context(), owner, repo, 1)
if err != nil || task == nil {
t.Fatalf("TaskByIssue = (%v, %v)", task, err)
}
task.PRNumber = prNumber
task.Status = workflow.StatusPROpen
if err := s.Transition(t.Context(), task.ID, workflow.StatusQueued, workflow.StatusPROpen, "PR opened"); err != nil {
t.Fatal(err)
}
if err := s.Update(t.Context(), task); err != nil {
t.Fatal(err)
}
return task.ID
}
func TestBeginRemediationMovesAnOpenPRTaskToQueuedRemediate(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); err != nil {
t.Fatalf("BeginRemediation: %v", err)
}
got, err := s.TaskByID(t.Context(), id)
if err != nil {
t.Fatal(err)
}
if got.Status != workflow.StatusQueued {
t.Errorf("status = %q, want queued", got.Status)
}
if got.Workflow != "remediate" {
t.Errorf("workflow = %q, want remediate", got.Workflow)
}
if got.ReviewPayload != `{"review_id":7}` {
t.Errorf("review_payload = %q, want the carried unit", got.ReviewPayload)
}
if got.ParkReason != "" || got.Stage != "" {
t.Errorf("park_reason/stage = %q/%q, want both empty", got.ParkReason, got.Stage)
}
}
func TestBeginRemediationRefusesAnAlreadyClaimedTask(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); err != nil {
t.Fatal(err)
}
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); !errors.Is(err, ErrStaleTransition) {
t.Errorf("second BeginRemediation err = %v, want ErrStaleTransition", err)
}
}
func TestBeginRemediationRefusesNonOpenPRStatuses(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.Transition(t.Context(), id, workflow.StatusPROpen, workflow.StatusParked, "gate failed"); err != nil {
t.Fatal(err)
}
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); !errors.Is(err, ErrStaleTransition) {
t.Errorf("BeginRemediation on parked err = %v, want ErrStaleTransition", err)
}
}
func TestUpdateReviewPayloadAppendsOnlyWhileARemediationIsQueued(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); err != nil {
t.Fatal(err)
}
if err := s.UpdateReviewPayload(t.Context(), id, `{"review_id":7,"comments":[{"comment_id":9}]}`); err != nil {
t.Fatalf("UpdateReviewPayload while queued: %v", err)
}
got, err := s.TaskByID(t.Context(), id)
if err != nil {
t.Fatal(err)
}
if got.ReviewPayload != `{"review_id":7,"comments":[{"comment_id":9}]}` {
t.Errorf("review_payload = %q, want the appended unit", got.ReviewPayload)
}
// Claim the task: the remediation is running, and a payload written under
// it would race the builder's input.
if _, err := s.ClaimNext(t.Context()); err != nil {
t.Fatal(err)
}
if err := s.UpdateReviewPayload(t.Context(), id, `{"review_id":7,"comments":[{"comment_id":10}]}`); !errors.Is(err, ErrStaleTransition) {
t.Errorf("UpdateReviewPayload while running err = %v, want ErrStaleTransition", err)
}
}
+60
View File
@@ -526,6 +526,66 @@ func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
return err
}
// BeginRemediation transitions an Archie-owned open-PR task into a queued
// remediate run carrying the JSON-encoded review unit. The guarded update is
// the reaction consumer's dedup: a re-delivered reaction, or a second
// consumer racing the first, fails the status guard instead of starting a
// second round. The unit is written in the same transaction, so a task can
// never be claimed into a remediate run whose payload has not landed.
func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?, workflow=?, stage='', park_reason='', review_payload=?,
updated_at=datetime('now')
WHERE id=? AND status=?`, workflow.StatusQueued, "remediate", clip(payload, 4000), taskID, workflow.StatusPROpen)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`,
taskID, workflow.StatusPROpen, workflow.StatusQueued, "review reaction queued remediation"); err != nil {
return err
}
return tx.Commit()
}
// UpdateReviewPayload replaces a queued remediation's review unit: the
// reaction consumer appends late-arriving comments of the same review while
// the unit is still pending. The guarded update is the boundary — once a
// run is claimed, its input is frozen; a late comment is dropped by the
// caller rather than racing the builder's mission.
func (s *Store) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
res, err := s.db.ExecContext(ctx, `
UPDATE tasks SET review_payload=?, updated_at=datetime('now')
WHERE id=? AND status=? AND workflow=?`,
clip(payload, 4000), taskID, workflow.StatusQueued, "remediate")
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
return nil
}
// TaskByIssue returns the task tracking an issue, or nil.
func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
+14
View File
@@ -41,6 +41,8 @@ service StateStoreService {
// Archive / Retry
rpc ArchiveTask(ArchiveTaskRequest) returns (ArchiveTaskResponse);
rpc RetryTask(RetryTaskRequest) returns (RetryTaskResponse);
rpc BeginRemediation(BeginRemediationRequest) returns (BeginRemediationResponse);
rpc UpdateReviewPayload(UpdateReviewPayloadRequest) returns (UpdateReviewPayloadResponse);
// Queries
rpc TaskByIssue(TaskByIssueRequest) returns (TaskByIssueResponse);
@@ -428,6 +430,18 @@ message RetryTaskRequest {
}
message RetryTaskResponse {}
message BeginRemediationRequest {
int64 task_id = 1;
string payload = 2;
}
message BeginRemediationResponse {}
message UpdateReviewPayloadRequest {
int64 task_id = 1;
string payload = 2;
}
message UpdateReviewPayloadResponse {}
message TaskByIssueRequest {
string owner = 1;
string repo = 2;