fix: close the duplicate-work loop and the dead paths around it

Applies the four-reviewer pass over the forge/dashboard-actions work.
The through-line is that several capabilities were wired but inert, and
one of them could cost real work.

DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of
LinkBranch, which is sidebar linkage on Gitea and a no-op stub on
GitHub -- neither closes anything, and nothing else did either. So a
merged task left its issue open, labelled and assigned; the next poll
re-enqueued it, and once the dashboard's Clear removed the task row that
became a second implementation and a second PR for work already merged.
reconcilePRs now closes the issue on merge, and a rejected task closes
its issue too. A PR closed without merging deliberately leaves the issue
open: that usually means "try again".

MAX RETRIES. Configured, defaulted and reported by /api/config, and
enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had
no callers, so the dashboard's retry incremented retry_count forever.
The retry action now retires a task to dead at the cap.

DEAD ON ARRIVAL. Tasks() never selected plan or source, so the
"Decision required" panel could not render and chat tasks -- whose issue
number is synthetic -- linked to forge issues that do not exist.

COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when
LinkBranch errored, so the pull request was never opened and the task
parked; a retry re-links the same branch, which Gitea answers with a
conflict, so every retry parked again. It is best-effort now.

INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing
else, so the timeline and activity stream never showed that a human had
intervened. They emit events now.

Also: store write failures answer 500 rather than 409; the dashboard
surfaces the server's actual reason instead of "409 Conflict"; action
buttons stop propagation (acting on a task no longer also expands it),
disable in flight, keep per-task errors instead of one shared string,
and confirm before rejecting.

Removed: the maybeRetryParked shim and markDead with their now-vacuous
tests, WaitingTasks (no consumers; its tests were rewritten to assert
the same routing through TaskByID), write-only Daemon.Runtime, and
dir/dirs response bloat from /api/skills. skillSource checked workDir
before sharedDir, mislabelling every shared skill when the two are equal.
DefaultRoots now dedupes roots differing only by a trailing separator.

The air build rule claiming to keep ui/dist current never ran -- it
required one file to satisfy include_dir and include_file together, and
ui/ is excluded from the walk. Deleted with the comment that promised it.
task test:ui joins task check and CI; it ran nowhere before, so the
dashboard suite could rot silently.

Docs corrected where they described behaviour that no longer exists:
parks no longer comment on the issue, state labels no longer drive
retries, and forgerpc's doc claimed four proxied methods while listing
three of five.
This commit is contained in:
sam committed 2026-08-05 03:54:25 +10:00
1 parent a751be66b3
commit 170fe0250b
60 files changed
+2081 -768

No files matched your search

+24 -196
View File
@@ -10,14 +10,10 @@ import (
"fmt"
"log/slog"
"os"
"slices"
"strings"
"sync"
"time"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
@@ -53,7 +49,6 @@ type Daemon struct {
Store store.TaskStore
Forge forge.Forge
Trees *worktree.Manager
Runtime *runtime.Runtime
Agent agentexec.Runner
Bus *events.Bus
Workflows workflow.Registry
@@ -318,7 +313,6 @@ func (d *Daemon) Cycle(ctx context.Context) {
d.cleanupExpiredStorage(ctx)
d.poll(ctx)
d.reconcilePRs(ctx)
d.checkWaiting(ctx)
if d.Tasks != nil {
d.drainNATS(ctx)
} else {
@@ -509,19 +503,19 @@ func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, repo config.Rep
d.acknowledge(ctx, fg, repo, is)
return
}
d.maybeRetryParked(ctx, repo, is)
// Existing tasks are left untouched. Retry and approval are explicit
// operator actions in messaging or the Web UI, not forge-side label edits.
}
// pollNATS publishes discovered issues to NATS (new flow).
func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue, labels, identity string) {
// Read-only existence check -- needed for maybeRetryParked.
// Read-only existence check prevents rediscovering an existing task.
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
if err != nil {
d.Log.Error("task lookup failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
return
}
if existing != nil {
d.maybeRetryParked(ctx, repo, is)
return
}
// Classify and encode here: the envelope, its routing kind and its
@@ -558,7 +552,7 @@ func (d *Daemon) publishTask(ctx context.Context, task workintake.TaskEnvelope)
return d.Tasks.PublishUnique(ctx, task.Subject(), task.IdempotencyKey(), payload)
}
// acknowledge posts the pickup reaction, state label, and queued event
// acknowledge posts the pickup reaction and queued event
// using fg -- the forge client that owns repo (identity-scoped or root).
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue) {
d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
@@ -567,7 +561,6 @@ func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, repo config.Re
d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err)
}
}
fg.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
d.emit(events.Event{
Kind: events.KindTaskQueued, Repo: repo.FullName(),
Issue: is.Number, Detail: is.Title,
@@ -678,74 +671,20 @@ func (d *Daemon) pollEither(ctx context.Context, repo config.Repo) []forge.Issue
return out
}
// maybeRetryParked requeues a parked task whose state label a human has
// removed -- the forge-native retry trigger. When retry_count reaches the
// configured max_retries the task moves to dead instead of requeuing.
// The forge client is resolved from the task's own Identity via forgeFor
// (not passed in) since that's authoritative for which forge client owns it.
func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forge.Issue) {
if hasLabel(is.Labels, d.Cfg.Dispatch.StateLabel("parked")) {
// closeResolvedIssue closes the forge issue behind a finished task.
//
// A chat task's issue number is synthetic and matches no forge issue, so it
// is skipped. Failure is logged rather than returned: the task's own state is
// already correct, and the next reconcile pass will not retry, so a warning
// is the honest outcome -- the issue simply stays open.
func (d *Daemon) closeResolvedIssue(ctx context.Context, fg forge.Forge, task *store.Task, comment string) {
if !task.IsForgeBacked() {
return
}
task, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
if err != nil || task == nil || task.Status != store.StatusParked {
return
if err := fg.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
d.Log.Warn("closing resolved issue failed; it stays open and will be re-polled",
"repo", task.Owner+"/"+task.Repo, "issue", task.IssueNumber, "err", err)
}
fg := d.forgeFor(task)
maxRetries := repo.EffectiveMaxRetries(d.Cfg.MaxRetries)
if task.RetryCount >= maxRetries {
d.markDead(ctx, repo, task, maxRetries)
return
}
if err := d.Store.Requeue(ctx, task.ID, store.StatusParked, ""); err != nil {
d.Log.Error("label-triggered requeue failed", "issue", is.Number, "err", err)
return
}
if err := d.Store.IncrementRetryCount(ctx, task.ID); err != nil {
d.Log.Error("increment retry_count failed", "issue", is.Number, "err", err)
}
d.Log.Info("parked task requeued via label removal", "repo", repo.FullName(), "issue", is.Number, "retry_count", task.RetryCount+1, "max_retries", maxRetries)
fg.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
d.emit(events.Event{
Kind: "task_retried", TaskID: task.ID,
Repo: repo.FullName(), Issue: is.Number, Detail: "parked label removed",
})
}
// markDead permanently parks a task that has exhausted its max_retries.
func (d *Daemon) markDead(ctx context.Context, repo config.Repo, task *store.Task, maxRetries int) {
fg := d.forgeFor(task)
reason := fmt.Sprintf("max retries reached (%d/%d) -- task parked permanently", task.RetryCount, maxRetries)
if err := d.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
d.Log.Error("transition to dead failed", "task", task.ID, "err", err)
return
}
if task.IsForgeBacked() {
fg.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber,
d.Cfg.Dispatch.StateLabel("dead"), d.Cfg.Dispatch.LabelValues())
}
d.Log.Warn("task permanently parked after max retries",
"issue", task.IssueNumber, "retry_count", task.RetryCount, "max_retries", maxRetries)
if task.IsForgeBacked() {
body := fmt.Sprintf("**Max retries reached (%d/%d) -- task parked permanently.**\n\n"+
"The task failed %d times and has been moved to `dead` status. "+
"Manual intervention is required to recover this task.",
task.RetryCount, maxRetries, task.RetryCount)
if _, err := fg.Comment(ctx, task.Owner, task.Repo, task.IssueNumber, body); err != nil {
d.Log.Error("failed to post dead comment", "issue", task.IssueNumber, "err", err)
}
}
d.emit(events.Event{
Kind: events.KindTaskDead, TaskID: task.ID,
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
})
}
func hasLabel(labels []string, want string) bool {
return slices.Contains(labels, want)
}
// reconcilePRs moves pr_open tasks to merged/rejected from GitHub state
@@ -772,9 +711,15 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
case "merged":
_ = d.Store.Transition(ctx, t.ID, store.StatusPROpen, store.StatusMerged, "")
_ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber)
if t.IsForgeBacked() {
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
}
// Close the issue ourselves rather than relying on the forge
// noticing a "Closes #N" in the PR body. Nothing else closes it:
// LinkBranch is sidebar linkage on Gitea and a no-op on GitHub.
// Left open the issue stays labelled and assigned, the next poll
// re-enqueues it, and once the dashboard's Clear removes the task
// row that is a second implementation and a second PR for work
// already merged.
d.closeResolvedIssue(ctx, fg, &t, fmt.Sprintf(
"Closed by #%d, merged by archie.", t.PRNumber))
d.Log.Info("PR merged", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
d.emit(events.Event{
Kind: events.KindPRMerged, TaskID: t.ID,
@@ -784,9 +729,6 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
case "closed":
_ = d.Store.Transition(ctx, t.ID, store.StatusPROpen, store.StatusRejected, "PR closed without merge")
_ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber)
if t.IsForgeBacked() {
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
}
d.Log.Info("PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
d.emit(events.Event{
Kind: events.KindPRRejected, TaskID: t.ID,
@@ -797,113 +739,6 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
}
}
// checkWaiting looks for human replies on waiting_human tasks and asks
// an LLM -- not keyword matching -- whether the reply is a go-ahead.
// Approved tasks requeue under the implement workflow; rejections close
// the issue with the human's reasoning acknowledged.
func (d *Daemon) checkWaiting(ctx context.Context) {
tasks, err := d.Store.WaitingTasks(ctx)
if err != nil {
d.Log.Error("waiting query failed", "err", err)
return
}
for _, t := range tasks {
if !t.IsForgeBacked() {
// Chat-sourced waiting_human tasks resolve via /approve and
// /cancel, not forge issue replies -- there is no issue
// to poll.
continue
}
fg := d.forgeFor(&t)
replies, err := fg.RepliesAfter(ctx, t.Owner, t.Repo, t.IssueNumber, t.WatchCommentID, d.Cfg.BotUser)
if err != nil {
d.Log.Warn("reply check failed", "issue", t.IssueNumber, "err", err)
continue
}
if len(replies) == 0 {
continue
}
var sb strings.Builder
for _, r := range replies {
fmt.Fprintf(&sb, "%s: %s\n", r.User, r.Body)
}
verdict, reason, err := d.judgeReply(ctx, t.Plan, sb.String())
if err != nil {
d.Log.Error("reply judge failed", "issue", t.IssueNumber, "err", err)
continue
}
d.Log.Info("human reply judged", "issue", t.IssueNumber, "verdict", verdict)
switch verdict {
case "approve":
if err := d.Store.Requeue(ctx, t.ID, store.StatusWaitingHuman, "implement"); err != nil {
d.Log.Error("requeue failed", "issue", t.IssueNumber, "err", err)
continue
}
_, _ = fg.Comment(ctx, t.Owner, t.Repo, t.IssueNumber,
"**Go-ahead received -- implementation is queued.** ("+reason+")")
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
d.emit(events.Event{
Kind: "human_approved", TaskID: t.ID,
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Detail: reason,
})
case "reject":
_ = d.Store.Transition(ctx, t.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, reason)
_ = fg.CloseIssue(ctx, t.Owner, t.Repo, t.IssueNumber,
"**Understood -- closing without implementation.** ("+reason+")")
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
d.emit(events.Event{
Kind: "human_rejected", TaskID: t.ID,
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Detail: reason,
})
default:
// Unclear: keep waiting; the humans can be more explicit.
d.Log.Info("reply unclear -- still waiting", "issue", t.IssueNumber, "reason", reason)
}
}
}
// judgeReply classifies the human's response to a PRD as approve,
// reject, or unclear.
func (d *Daemon) judgeReply(ctx context.Context, prd, replies string) (verdict, reason string, err error) {
if d.Runtime == nil {
return "", "", fmt.Errorf("no LLM runtime configured")
}
model := d.Cfg.Models["triage"]
if model == "" {
model = d.Cfg.Models["planner"]
}
if model == "" {
return "", "", fmt.Errorf("no triage or planner model configured")
}
res, err := d.Runtime.Chat(ctx, model, core.GenerateOptions{
System: "You classify a project owner's reply to a proposed PRD. Answer with exactly one line: " +
"APPROVE, REJECT, or UNCLEAR, followed by ' - ' and a one-sentence justification. " +
"APPROVE only when the reply expresses a go-ahead (with or without caveats). " +
"REJECT when it declines or shelves the proposal. Anything ambiguous is UNCLEAR.",
Prompt: "PRD (abridged):\n" + clip(prd, 3000) + "\n\nOwner's reply:\n" + clip(replies, 2000),
})
if err != nil {
return "", "", err
}
line := strings.TrimSpace(res.Text)
word, rest, _ := strings.Cut(line, "-")
switch strings.ToUpper(strings.TrimSpace(strings.Trim(word, " :*"))) {
case "APPROVE":
return "approve", strings.TrimSpace(rest), nil
case "REJECT":
return "reject", strings.TrimSpace(rest), nil
default:
return "unclear", line, nil
}
}
func clip(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
func (d *Daemon) process(ctx context.Context, task *store.Task) {
// Register before any work starts so the task is stoppable for its
// whole life, including the slow setup -- clone, worktree prepare,
@@ -971,13 +806,6 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
defer d.ContainerPool.Release(ctx, ctr)
}
// Set the working label only after successful container setup (or when no
// container is needed). This prevents label/database divergence on failure.
// Chat-sourced tasks have no real forge issue to label.
if task.IsForgeBacked() {
fg.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues())
}
// Sandboxed path: hand the whole task to archie-agent in one NATS round
// trip instead of running the stage loop here. archie-agent proxies
// Store/Forge/worktree-push calls back to archied over storerpc/
+117 -206
View File
@@ -6,7 +6,6 @@ import (
"log/slog"
"os"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
@@ -530,24 +529,18 @@ func TestRunViaAgentSendsExpectedRequest(t *testing.T) {
}
}
func TestHasLabelUsesExactNames(t *testing.T) {
labels := []string{"bug", "archie:parked-old", "feature", "custom,label"}
if hasLabel(labels, "archie:parked") {
t.Fatal("hasLabel matched a label-name substring")
}
if !hasLabel(labels, "custom,label") {
t.Fatal("hasLabel did not preserve a label containing a comma")
}
labels = append(labels, "archie:parked")
if !hasLabel(labels, "archie:parked") {
t.Fatal("hasLabel did not match the exact label name")
}
}
// testForge implements forge.Forge for daemon tests.
type testForge struct {
comments []commentCall
stateLabels []stateLabelCall
comments []commentCall
stateLabels []stateLabelCall
closedIssues []closeIssueCall
prStates map[int]string
}
type closeIssueCall struct {
owner, repo string
number int
comment string
}
type commentCall struct {
@@ -589,12 +582,16 @@ func (f *testForge) CreatePR(context.Context, string, string, string, string, st
panic("unexpected call")
}
func (f *testForge) PRState(context.Context, string, string, int) (string, error) {
func (f *testForge) PRState(_ context.Context, _, _ string, number int) (string, error) {
if state, ok := f.prStates[number]; ok {
return state, nil
}
panic("unexpected call")
}
func (f *testForge) CloseIssue(context.Context, string, string, int, string) error {
panic("unexpected call")
func (f *testForge) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
f.closedIssues = append(f.closedIssues, closeIssueCall{owner, repo, number, comment})
return nil
}
func (f *testForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
@@ -627,114 +624,14 @@ func testDaemon(t *testing.T, maxRetries, _ int) (*Daemon, *store.Store, *testFo
Cfg: cfg,
Store: s,
Forge: fg,
// Reconcile paths call Trees.Cleanup, which dereferences the
// manager. A zero Manager is enough: cleanup of a worktree that was
// never created is a no-op.
Trees: &worktree.Manager{},
Log: log,
}, s, fg
}
func setupParkedTask(t *testing.T, s *store.Store, retryCount int) *store.Task {
t.Helper()
ctx := context.Background()
if _, err := s.EnqueueIssue(ctx, "acme", "todo", 1, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, err := s.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("claim = (%v, %v)", task, err)
}
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "parked"); err != nil {
t.Fatal(err)
}
for range retryCount {
if err := s.IncrementRetryCount(ctx, task.ID); err != nil {
t.Fatal(err)
}
}
task, err = s.TaskByIssue(ctx, "acme", "todo", 1)
if err != nil || task == nil {
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
}
return task
}
func TestMaybeRetryParkedUnderThreshold(t *testing.T) {
d, s, fg := testDaemon(t, 3, 0)
ctx := context.Background()
_ = setupParkedTask(t, s, 0)
is := forge.Issue{Number: 1, Labels: []string{}}
repo := config.Repo{Owner: "acme", Name: "todo"}
d.maybeRetryParked(ctx, repo, is)
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
if err != nil || task == nil {
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
}
if task.Status != store.StatusQueued {
t.Fatalf("expected status queued, got %s", task.Status)
}
if task.RetryCount != 1 {
t.Fatalf("expected retry_count=1, got %d", task.RetryCount)
}
if len(fg.stateLabels) != 1 || fg.stateLabels[0].label != "archie:queued" {
t.Fatalf("expected queued state label, got %+v", fg.stateLabels)
}
if len(fg.comments) != 0 {
t.Fatalf("expected no comments, got %d", len(fg.comments))
}
}
func TestMaybeRetryParkedAtThreshold(t *testing.T) {
d, s, fg := testDaemon(t, 3, 0)
ctx := context.Background()
_ = setupParkedTask(t, s, 3)
is := forge.Issue{Number: 1, Labels: []string{}}
repo := config.Repo{Owner: "acme", Name: "todo"}
d.maybeRetryParked(ctx, repo, is)
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
if err != nil || task == nil {
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
}
if task.Status != store.StatusDead {
t.Fatalf("expected status dead, got %s", task.Status)
}
if len(fg.stateLabels) != 1 || fg.stateLabels[0].label != "archie:dead" {
t.Fatalf("expected dead state label, got %+v", fg.stateLabels)
}
if len(fg.comments) != 1 || !strings.Contains(fg.comments[0].body, "Max retries reached") {
t.Fatalf("expected dead comment, got %+v", fg.comments)
}
}
func TestMaybeRetryParkedSkipsDead(t *testing.T) {
d, s, fg := testDaemon(t, 3, 0)
ctx := context.Background()
task := setupParkedTask(t, s, 0)
if err := s.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, "manual"); err != nil {
t.Fatal(err)
}
is := forge.Issue{Number: 1, Labels: []string{}}
repo := config.Repo{Owner: "acme", Name: "todo"}
d.maybeRetryParked(ctx, repo, is)
if len(fg.stateLabels) != 0 {
t.Fatalf("expected no state label calls, got %d", len(fg.stateLabels))
}
if len(fg.comments) != 0 {
t.Fatalf("expected no comments, got %d", len(fg.comments))
}
}
func TestNewIdentityRunnerPopulatesFromConfig(t *testing.T) {
// Identity names come from config, not hardcoded by the daemon.
tests := []struct {
@@ -843,40 +740,6 @@ func TestDaemonStoresIdentityRunners(t *testing.T) {
}
}
func TestMaybeRetryParkedStillParked(t *testing.T) {
d, _, fg := testDaemon(t, 3, 0)
ctx := context.Background()
is := forge.Issue{Number: 1, Labels: []string{"archie:parked", "bug"}}
repo := config.Repo{Owner: "acme", Name: "todo"}
d.maybeRetryParked(ctx, repo, is)
if len(fg.stateLabels) != 0 {
t.Fatalf("expected no state label calls, got %d", len(fg.stateLabels))
}
}
func TestMaybeRetryParkedRepoOverride(t *testing.T) {
d, s, _ := testDaemon(t, 3, 1)
ctx := context.Background()
_ = setupParkedTask(t, s, 1)
is := forge.Issue{Number: 1, Labels: []string{}}
repo := config.Repo{Owner: "acme", Name: "todo", MaxRetries: 1}
d.maybeRetryParked(ctx, repo, is)
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
if err != nil || task == nil {
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
}
if task.Status != store.StatusDead {
t.Fatalf("expected status dead with repo override, got %s", task.Status)
}
}
// ── Multi-identity isolation (archie-core-abg.37) ──────────────────────
//
// Two identities ("archie" and "winter") are both configured to work the
@@ -940,60 +803,14 @@ func TestAcknowledgeUsesOwningIdentityForgeNotRoot(t *testing.T) {
// archie's poll cycle acknowledges via its own forge client.
d.acknowledge(ctx, archieFg, repo, is)
if len(archieFg.stateLabels) != 1 {
t.Fatalf("archie forge got %d state label calls, want 1", len(archieFg.stateLabels))
if len(archieFg.stateLabels) != 0 {
t.Fatalf("archie forge got %d state label calls, want 0", len(archieFg.stateLabels))
}
if len(winterFg.stateLabels) != 0 || len(rootFg.stateLabels) != 0 {
t.Fatal("acknowledge leaked a state label call to winter's or root's forge client")
}
}
func TestMarkDeadResolvesForgeFromTaskIdentityNotCaller(t *testing.T) {
d, s, rootFg, archieFg, winterFg := twoIdentityDaemon(t)
ctx := context.Background()
// Two tasks for the SAME owner/repo, owned by different identities.
if _, err := s.EnqueueIssue(ctx, "acme", "shared", 1, "t1", "b", "", "archie"); err != nil {
t.Fatal(err)
}
if _, err := s.EnqueueIssue(ctx, "acme", "shared", 2, "t2", "b", "", "winter"); err != nil {
t.Fatal(err)
}
archieTask, err := s.TaskByIssue(ctx, "acme", "shared", 1)
if err != nil || archieTask == nil {
t.Fatalf("TaskByIssue(1) = (%+v, %v)", archieTask, err)
}
winterTask, err := s.TaskByIssue(ctx, "acme", "shared", 2)
if err != nil || winterTask == nil {
t.Fatalf("TaskByIssue(2) = (%+v, %v)", winterTask, err)
}
if err := s.Transition(ctx, archieTask.ID, store.StatusQueued, store.StatusParked, "test"); err != nil {
t.Fatal(err)
}
if err := s.Transition(ctx, winterTask.ID, store.StatusQueued, store.StatusParked, "test"); err != nil {
t.Fatal(err)
}
archieTask, _ = s.TaskByIssue(ctx, "acme", "shared", 1)
winterTask, _ = s.TaskByIssue(ctx, "acme", "shared", 2)
repo := config.Repo{Owner: "acme", Name: "shared"}
d.markDead(ctx, repo, archieTask, 0)
d.markDead(ctx, repo, winterTask, 0)
if len(archieFg.stateLabels) != 1 || archieFg.stateLabels[0].number != 1 {
t.Fatalf("archie forge state labels = %+v, want exactly issue 1", archieFg.stateLabels)
}
if len(winterFg.stateLabels) != 1 || winterFg.stateLabels[0].number != 2 {
t.Fatalf("winter forge state labels = %+v, want exactly issue 2", winterFg.stateLabels)
}
if len(rootFg.stateLabels) != 0 {
t.Fatal("markDead used the root forge client instead of the owning identity's")
}
if len(archieFg.comments) != 1 || len(winterFg.comments) != 1 {
t.Fatalf("expected one dead-comment per identity, got archie=%d winter=%d", len(archieFg.comments), len(winterFg.comments))
}
}
func TestRepoForPrefersOwningIdentityRepoList(t *testing.T) {
d, _, _, _, _ := twoIdentityDaemon(t)
@@ -1025,3 +842,97 @@ func mustCoreConn(t *testing.T, c *arnats.Client) *natsio.Conn {
}
return conn
}
// A merged PR must close the forge issue.
//
// "Closes #N" was removed from PR bodies in favour of LinkBranch, which is
// sidebar linkage on Gitea and a no-op stub on GitHub -- neither closes
// anything. So the issue stayed open, labelled and assigned, and the next
// poll re-enqueued it. Once the operator uses the dashboard's Clear, which
// deletes the task row, that is a second implementation and a second PR for
// work already merged.
func TestReconcilePRsClosesTheIssueOnMerge(t *testing.T) {
tests := []struct {
name string
prState string
wantClosed bool
}{
{name: "merged closes the issue", prState: "merged", wantClosed: true},
// A PR closed without merging usually means "try again", so the
// issue stays open deliberately.
{name: "closed without merge leaves it open", prState: "closed"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
d, s, fg := testDaemon(t, 3, 0)
ctx := context.Background()
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 42, "a task", "", "", ""); err != nil {
t.Fatal(err)
}
task, err := s.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
}
task.PRNumber = 7
if err := s.Update(ctx, task); err != nil {
t.Fatal(err)
}
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusPROpen, ""); err != nil {
t.Fatal(err)
}
fg.prStates = map[int]string{7: tc.prState}
d.reconcilePRs(ctx)
if tc.wantClosed {
if len(fg.closedIssues) != 1 {
t.Fatalf("CloseIssue calls = %d, want 1: the issue stays open "+
"and is re-polled, so the work is done twice", len(fg.closedIssues))
}
got := fg.closedIssues[0]
if got.owner != "acme" || got.repo != "widget" || got.number != 42 {
t.Errorf("closed %s/%s#%d, want acme/widget#42", got.owner, got.repo, got.number)
}
if got.comment == "" {
t.Error("closed with no comment")
}
return
}
if len(fg.closedIssues) != 0 {
t.Errorf("CloseIssue called %d times for a PR closed without merge",
len(fg.closedIssues))
}
})
}
}
// A chat task's issue number is synthetic, so closing it would close an
// unrelated issue or error.
func TestReconcilePRsSkipsChatTasks(t *testing.T) {
d, s, fg := testDaemon(t, 3, 0)
ctx := context.Background()
task, err := s.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", 900001)
if err != nil {
t.Fatal(err)
}
if _, err := s.ClaimNext(ctx); err != nil {
t.Fatal(err)
}
task.PRNumber = 8
if err := s.Update(ctx, task); err != nil {
t.Fatal(err)
}
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusPROpen, ""); err != nil {
t.Fatal(err)
}
fg.prStates = map[int]string{8: "merged"}
d.reconcilePRs(ctx)
if len(fg.closedIssues) != 0 {
t.Errorf("CloseIssue called for a chat task: issue number is synthetic")
}
}