refactor: one definition of what approving or declining a task means

The dashboard and chat both let an operator approve or refuse work, and
they had drifted. Declining from the dashboard left the task
closed_wont_do; cancelling the same task from chat left it rejected. Two
operators looking at one queue saw different states for the same
decision, and "rejected" -- which reconcilePRs also uses for a pull
request closed without merging -- stopped meaning one thing.

internal/gateway deliberately does not import internal/store, so it kept
a hand-synced copy of the status strings with a comment asking future
editors to keep them aligned. That is the same defect one level down,
and it is how the drift happened.

internal/taskstate is a leaf package with no dependencies holding the
lifecycle vocabulary and the rules for operator actions. gateway, store
and the dashboard all import it, so gateway stays decoupled from store
without a copy, and CheckApprove/CheckRetry/CheckDecline have one
implementation. Declined is named for what it is -- a human said no --
and stays distinct from Rejected, which is something archie observed.

Chat cancel now records Declined. That is the behaviour change: same
decision, same state, whichever surface the operator used.

Rules were preserved rather than tidied while unifying. A parked task
still cannot be declined, which both surfaces already refused, even
though "not terminal" would have allowed it -- widening a rule under
cover of a refactor is how you ship a change nobody reviewed. The
comment says where to change it if that is ever wanted.

TestDashboardAndChatAgreeOnTerminalStates drives both real surfaces
against one store, so this cannot drift apart again without a red test.

Also removes a second rule for the dash-top-standalone class: renderSetup
already reconciles it from the data at the top of every call, and a later
branch cleared it again. Harmless, but it reads as two sources of truth
for one bit of layout state.
This commit is contained in:
sam committed 2026-08-05 04:15:39 +10:00
1 parent d6e00415fa
commit 1f2e7a42eb
10 files changed
+329 -46

No files matched your search

+7 -1
View File
@@ -788,7 +788,13 @@ func (a chatTaskControllerAdapter) CancelChatTask(ctx context.Context, taskID in
if task.IsForgeBacked() {
return fmt.Errorf("task %d is not chat-originated", taskID)
}
return a.transition(ctx, taskID, task.Status, store.StatusRejected, reason)
// An operator declining work lands in the same state whichever surface
// they used. This used to record StatusRejected while the dashboard
// recorded StatusClosedWontDo, so the same decision showed up as two
// different states -- and StatusRejected, which the PR reconciler uses
// for "the pull request was closed without merging", stopped meaning one
// thing.
return a.transition(ctx, taskID, task.Status, store.StatusClosedWontDo, reason)
}
func chatTaskProfiles(cfg config.Config) ([]gateway.TaskProfile, string) {
+7 -2
View File
@@ -419,7 +419,11 @@ func TestChatTaskControllerAdapterTransitions(t *testing.T) {
if err := adapter.CancelChatTask(context.Background(), task.ID, "cancelled by test"); err != nil {
t.Fatalf("CancelChatTask(): %v", err)
}
if transitionFrom != store.StatusWaitingHuman || transitionTo != store.StatusRejected ||
// Declining from chat lands in the same state as declining from the
// dashboard. It used to record StatusRejected, which the PR reconciler
// also uses for "the pull request was closed without merging", so the
// state could not tell an operator's decision from a forge outcome.
if transitionFrom != store.StatusWaitingHuman || transitionTo != store.StatusClosedWontDo ||
transitionDetail != "cancelled by test" {
t.Errorf("transition = %q/%q/%q", transitionFrom, transitionTo, transitionDetail)
}
@@ -507,8 +511,9 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) {
if err != nil || !strings.Contains(reply, "cancelled") {
t.Fatalf("cancel = (%q, %v)", reply, err)
}
// Same terminal state as the dashboard's Reject: one decision, one state.
cancelled, err := st.TaskByID(ctx, cancelID)
if err != nil || cancelled == nil || cancelled.Status != store.StatusRejected {
if err != nil || cancelled == nil || cancelled.Status != store.StatusClosedWontDo {
t.Fatalf("cancelled task = (%+v, %v)", cancelled, err)
}
}
+97
View File
@@ -0,0 +1,97 @@
package main
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/nell"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webui"
)
// The dashboard and chat both let an operator approve or decline a task, and
// they had drifted: declining from the dashboard left the task
// closed_wont_do, cancelling the same task from chat left it rejected. Two
// operators looking at one queue saw different states for the same decision,
// and "rejected" -- which reconcilePRs uses for a pull request closed without
// merging -- no longer meant one thing.
//
// This drives both real surfaces against one store and asserts they agree.
// It lives in cmd/archied because that is the only place both are wired.
func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) {
tests := []struct {
name string
// viaChat runs the action through the chat router; otherwise it
// goes through the dashboard's HTTP handler.
viaChat bool
action string
want string
}{
{name: "dashboard reject", action: "reject", want: store.StatusClosedWontDo},
{name: "chat cancel", viaChat: true, action: "cancel", want: store.StatusClosedWontDo},
{name: "dashboard approve", action: "approve", want: store.StatusQueued},
{name: "chat approve", viaChat: true, action: "approve", want: store.StatusQueued},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
st, err := nell.OpenStore(filepath.Join(t.TempDir(), "tasks.db"), "test-node")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "decide on me", "", "", "reviewer", 900_001)
if err != nil {
t.Fatal(err)
}
if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusWaitingHuman, "await"); err != nil {
t.Fatal(err)
}
if tc.viaChat {
controller := gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: st.TaskByID,
requeue: st.Requeue,
transition: st.Transition,
})
var actErr error
if tc.action == "approve" {
actErr = controller.Approve(ctx, task.ID, "reviewer")
} else {
actErr = controller.Cancel(ctx, task.ID, "reviewer")
}
if actErr != nil {
t.Fatalf("chat %s: %v", tc.action, actErr)
}
} else {
srv := &webui.Server{Store: st, Cfg: &config.Config{MaxRetries: 3}}
req := httptest.NewRequestWithContext(ctx, http.MethodPost,
"/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action",
bytes.NewBufferString(`{"action":"`+tc.action+`"}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("dashboard %s: status %d, body %s", tc.action, w.Code, w.Body)
}
}
got, err := st.TaskByID(ctx, task.ID)
if err != nil || got == nil {
t.Fatalf("TaskByID = (%+v, %v)", got, err)
}
if got.Status != tc.want {
t.Errorf("status = %q, want %q: the two surfaces disagree about "+
"what this action means", got.Status, tc.want)
}
})
}
}
+16 -18
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"sync/atomic"
"time"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// StoreTaskCreator implements TaskCreator backed by a store interface.
@@ -135,19 +137,11 @@ func splitOwnerRepo(s string) (owner, repo string, ok bool) {
return "", "", false
}
// Task lifecycle status strings this controller reasons about. Kept as
// local constants (rather than importing internal/store) to preserve
// gateway's deliberate decoupling from the store package; must be kept
// in sync with store.StatusX by hand -- see StoreTaskController's doc.
const (
statusRunning = "running"
statusWaitingHuman = "waiting_human"
statusMerged = "merged"
statusParked = "parked"
statusRejected = "rejected"
statusDead = "dead"
statusClosedWontDo = "closed_wont_do"
)
// Task lifecycle statuses come from internal/taskstate, a leaf package with
// no dependencies, so gateway stays decoupled from internal/store without
// keeping a hand-synced copy of the strings. The copy that used to live here
// is how the dashboard and chat ended up recording different states for the
// same operator decision.
// ChatTaskStatus is the minimal task state StoreTaskController needs to
// authorize and validate /approve and /cancel.
@@ -211,8 +205,8 @@ func (c *StoreTaskController) Approve(ctx context.Context, taskID int64, identit
if err != nil {
return err
}
if st.Status != statusWaitingHuman {
return fmt.Errorf("task is %s, not waiting_human", st.Status)
if err := taskstate.CheckApprove(st.Status); err != nil {
return err
}
return c.store.ApproveChatTask(ctx, taskID)
}
@@ -222,10 +216,14 @@ func (c *StoreTaskController) Cancel(ctx context.Context, taskID int64, identity
if err != nil {
return err
}
if err := taskstate.CheckDecline(st.Status); err != nil {
return err
}
switch st.Status {
case statusMerged, statusParked, statusRejected, statusDead, statusClosedWontDo:
return fmt.Errorf("task is already %s", st.Status)
case statusRunning:
case taskstate.Parked:
// Parked is declinable -- taskstate allows it -- but there is
// nothing running to interrupt, so fall through to record it.
case taskstate.Running:
// Cancelling a running task used to be refused outright, which
// left the only case worth interrupting as the one case that
// could not be. Interrupt the work first, then record it: the
+10 -8
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// ── StoreTaskCreator ─────────────────────────────────────────────────
@@ -202,7 +204,7 @@ func (f *fakeChatTaskStore) CancelChatTask(ctx context.Context, taskID int64, re
}
func TestStoreTaskControllerApproveWaitingHuman(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusWaitingHuman}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.WaitingHuman}}}
c := NewStoreTaskController(store)
if err := c.Approve(context.Background(), 1, ""); err != nil {
t.Fatalf("Approve: %v", err)
@@ -235,7 +237,7 @@ func TestStoreTaskControllerApproveTaskNotFound(t *testing.T) {
}
func TestStoreTaskControllerApproveCrossIdentityRejected(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusWaitingHuman, Identity: "archie"}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.WaitingHuman, Identity: "archie"}}}
c := NewStoreTaskController(store)
err := c.Approve(context.Background(), 1, "winter")
if err == nil || !strings.Contains(err.Error(), "different identity") {
@@ -247,7 +249,7 @@ func TestStoreTaskControllerApproveCrossIdentityRejected(t *testing.T) {
}
func TestStoreTaskControllerApproveSameIdentityAllowed(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusWaitingHuman, Identity: "archie"}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.WaitingHuman, Identity: "archie"}}}
c := NewStoreTaskController(store)
if err := c.Approve(context.Background(), 1, "archie"); err != nil {
t.Fatalf("Approve: %v", err)
@@ -255,7 +257,7 @@ func TestStoreTaskControllerApproveSameIdentityAllowed(t *testing.T) {
}
func TestStoreTaskControllerRejectsCallerIdentityForLegacyTask(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusWaitingHuman}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.WaitingHuman}}}
c := NewStoreTaskController(store)
if err := c.Approve(context.Background(), 1, "anyone"); err == nil || !strings.Contains(err.Error(), "different identity") {
t.Fatalf("Approve error = %v, want cross-identity rejection", err)
@@ -297,7 +299,7 @@ func (f *fakeTaskRuntime) CancelRunningTasks(identity string) []int64 {
// to be refused. A running task is the only one worth interrupting, so
// cancelling it must reach the work and then record the outcome.
func TestStoreTaskControllerCancelInterruptsRunning(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusRunning}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.Running}}}
rt := &fakeTaskRuntime{running: true}
c := NewStoreTaskController(store).WithRuntime(rt)
@@ -316,7 +318,7 @@ func TestStoreTaskControllerCancelInterruptsRunning(t *testing.T) {
// calls running that nothing is executing -- a crashed or replaced daemon.
// Recording the terminal state is what unsticks it.
func TestStoreTaskControllerCancelRecordsStaleRunning(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusRunning}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.Running}}}
rt := &fakeTaskRuntime{running: false}
c := NewStoreTaskController(store).WithRuntime(rt)
@@ -332,7 +334,7 @@ func TestStoreTaskControllerCancelRecordsStaleRunning(t *testing.T) {
// refusal honest when nothing can interrupt the work: recording the task
// as cancelled while it carries on would be a lie.
func TestStoreTaskControllerCancelWithoutRuntimeRefusesRunning(t *testing.T) {
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusRunning}}}
store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: taskstate.Running}}}
c := NewStoreTaskController(store)
err := c.Cancel(context.Background(), 1, "")
@@ -404,5 +406,5 @@ func TestStoreTaskControllerLookupErrorPropagates(t *testing.T) {
}
// statusQueuedForTest avoids a naming collision with the package's own
// unexported statusRunning/statusWaitingHuman constants in test tables.
// unexported taskstate.Running/taskstate.WaitingHuman constants in test tables.
const statusQueuedForTest = "queued"
+14 -9
View File
@@ -14,20 +14,25 @@ import (
"unicode/utf8"
_ "modernc.org/sqlite"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// Task lifecycle statuses. Workflows move tasks between them; the
// daemon owns queued→running claims and crash recovery.
const (
StatusQueued = "queued"
StatusRunning = "running"
StatusWaitingHuman = "waiting_human"
StatusPROpen = "pr_open"
StatusMerged = "merged"
StatusParked = "parked"
StatusDead = "dead"
StatusRejected = "rejected"
StatusClosedWontDo = "closed_wont_do"
// Defined in internal/taskstate so the dashboard, chat and the store
// share one vocabulary. These names are kept as the store's public
// spelling; the values live in one place.
StatusQueued = taskstate.Queued
StatusRunning = taskstate.Running
StatusWaitingHuman = taskstate.WaitingHuman
StatusPROpen = taskstate.PROpen
StatusMerged = taskstate.Merged
StatusParked = taskstate.Parked
StatusDead = taskstate.Dead
StatusRejected = taskstate.Rejected
StatusClosedWontDo = taskstate.Declined
)
type Task struct {
+94
View File
@@ -0,0 +1,94 @@
// Package taskstate owns the task lifecycle vocabulary and the rules for
// operator-initiated actions on a task.
//
// It exists because those rules had two implementations. The dashboard and
// chat both offer approve and reject, and they had drifted: rejecting from
// the dashboard left a task ClosedWontDo, cancelling the same task from chat
// left it Rejected. Two operators looking at the same queue saw different
// states for the same decision, and Rejected -- which the PR reconciler uses
// for "the pull request was closed without merging" -- no longer meant one
// thing.
//
// internal/gateway deliberately does not import internal/store, so it kept a
// hand-synced copy of the status strings with a comment asking future editors
// to keep them aligned. That is the same defect one level down. This package
// has no dependencies, so both can import it and the copy can go.
package taskstate
import "fmt"
// Task lifecycle statuses. The store persists these strings, so they are
// part of the on-disk format: renaming one is a migration, not a rename.
const (
Queued = "queued"
Running = "running"
WaitingHuman = "waiting_human"
PROpen = "pr_open"
Merged = "merged"
Parked = "parked"
Dead = "dead"
// Rejected means the forge closed the pull request without merging it.
// It is an outcome archie observed, not a decision an operator made --
// use Declined for that.
Rejected = "rejected"
// Declined means an operator refused the work. Whether they said so from
// the dashboard or from chat, the task lands here.
Declined = "closed_wont_do"
)
// Terminal reports whether a status is an end state, from which no further
// work happens without an operator asking for it.
func Terminal(status string) bool {
switch status {
case Merged, Rejected, Dead, Declined:
return true
default:
return false
}
}
// CheckApprove reports whether a task in this status can be approved.
//
// Approval releases work that is waiting on a human decision, so it is only
// meaningful from WaitingHuman. Approving anything else would either restart
// finished work or race a task that is already running.
func CheckApprove(status string) error {
if status != WaitingHuman {
return fmt.Errorf("task is %s, not awaiting approval", status)
}
return nil
}
// CheckRetry reports whether a task in this status can be retried.
//
// Only a parked task can be retried: parking is how archie says "this failed
// in a way a human might fix". A dead task has spent its retries and needs
// the cap raised or the work re-filed, not another attempt.
func CheckRetry(status string) error {
if status != Parked {
return fmt.Errorf("task is %s, not parked", status)
}
return nil
}
// CheckDecline reports whether a task in this status can be declined.
//
// Work that is still progressing can be declined -- including a running task,
// which is the case most worth being able to stop. Callers that can interrupt
// running work should do so before recording the state, or the task may write
// its own outcome afterwards and win.
//
// Parked is refused along with the terminal states. A parked task is not
// progressing, so there is nothing to stop; it is retried, or left. Both the
// dashboard and chat already behaved this way and this package preserves it
// rather than widening the rule while unifying it. If declining a parked task
// is ever wanted, change it here and both paths get it at once -- which is
// the point.
func CheckDecline(status string) error {
if Terminal(status) || status == Parked {
return fmt.Errorf("task is already %s", status)
}
return nil
}
+70
View File
@@ -0,0 +1,70 @@
package taskstate
import "testing"
// The rules must be the same wherever an operator acts. These cases are the
// contract both the dashboard and chat are held to; a divergence between them
// is what this package exists to prevent.
func TestActionRules(t *testing.T) {
tests := []struct {
status string
approve, retry, decline bool
terminal bool
}{
{status: Queued, decline: true},
{status: Running, decline: true},
{status: WaitingHuman, approve: true, decline: true},
{status: PROpen, decline: true},
{status: Parked, retry: true},
{status: Merged, terminal: true},
{status: Rejected, terminal: true},
{status: Dead, terminal: true},
{status: Declined, terminal: true},
}
for _, tc := range tests {
t.Run(tc.status, func(t *testing.T) {
if got := CheckApprove(tc.status) == nil; got != tc.approve {
t.Errorf("CheckApprove allowed = %v, want %v", got, tc.approve)
}
if got := CheckRetry(tc.status) == nil; got != tc.retry {
t.Errorf("CheckRetry allowed = %v, want %v", got, tc.retry)
}
if got := CheckDecline(tc.status) == nil; got != tc.decline {
t.Errorf("CheckDecline allowed = %v, want %v", got, tc.decline)
}
if got := Terminal(tc.status); got != tc.terminal {
t.Errorf("Terminal = %v, want %v", got, tc.terminal)
}
})
}
}
// An unknown status must not be silently actionable: a typo or a status from
// a newer version should refuse rather than approve.
func TestUnknownStatusIsNotApprovable(t *testing.T) {
const unknown = "quantum_superposition"
if err := CheckApprove(unknown); err == nil {
t.Error("CheckApprove allowed an unknown status")
}
if err := CheckRetry(unknown); err == nil {
t.Error("CheckRetry allowed an unknown status")
}
// Declining is deliberately permissive: refusing work archie does not
// recognise is safer than being unable to stop it.
if err := CheckDecline(unknown); err != nil {
t.Errorf("CheckDecline refused an unknown status: %v", err)
}
}
// Rejected and Declined must stay distinct. Collapsing them would lose the
// difference between "the forge closed the PR" and "a human said no", which
// is the drift this package was created to end.
func TestRejectedAndDeclinedAreDistinct(t *testing.T) {
if Rejected == Declined {
t.Fatal("Rejected and Declined are the same string")
}
if !Terminal(Rejected) || !Terminal(Declined) {
t.Error("both must be terminal")
}
}
+10 -7
View File
@@ -9,6 +9,7 @@ import (
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
func (s *Server) handleSummary(w http.ResponseWriter, r *http.Request) {
@@ -143,8 +144,8 @@ func storeFailed(w http.ResponseWriter, err error) bool {
}
func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
if task.Status != store.StatusWaitingHuman {
http.Error(w, "task is not awaiting approval", http.StatusConflict)
if err := taskstate.CheckApprove(task.Status); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return nil
}
if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) {
@@ -160,8 +161,8 @@ func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *s
// every time could be retried without limit. At the cap the task belongs in
// dead, which is what the setting exists to say.
func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
if task.Status != store.StatusParked {
http.Error(w, "task is not parked", http.StatusConflict)
if err := taskstate.CheckRetry(task.Status); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return nil
}
if limit := s.maxRetriesFor(task); limit > 0 && task.RetryCount >= limit {
@@ -192,11 +193,13 @@ func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string
}
func (s *Server) rejectTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
if task.Status != store.StatusWaitingHuman {
http.Error(w, "task is not awaiting approval", http.StatusConflict)
// The dashboard only offers Reject on a waiting_human task, but the rule
// is the shared one so the two surfaces cannot drift apart again.
if err := taskstate.CheckApprove(task.Status); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return nil
}
err := s.Store.Transition(ctx, task.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, "rejected via Web UI")
err := s.Store.Transition(ctx, task.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, "declined from the dashboard")
if storeFailed(w, err) {
return nil
}
+4 -1
View File
@@ -213,6 +213,10 @@ export function dashboardPage() {
// Unknown setup (endpoint unreachable) or no checklist configured: omit
// the panel and let the gate pulse take the full row, so the Health row
// never shows an empty half beside the pulse.
// One place decides this class, reconciled from the data on every render.
// A second rule elsewhere in this function used to clear it again, which
// reads as two sources of truth for one bit of layout state even though
// the toggle above had already settled it.
const omit = !setup?.steps?.length;
topRow.classList.toggle("dash-top-standalone", omit);
if (omit) return mount(setupSlot);
@@ -240,7 +244,6 @@ export function dashboardPage() {
}
// Every step done: show completion so the row beside the gate pulse is
// not an empty hole on an otherwise healthy dashboard.
topRow.classList.remove("dash-top-standalone");
mount(
setupSlot,
el(