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:
1 parent
a751be66b3
commit
170fe0250b
60 files changed
+2081
-768
No files matched your search
+24
-196
@@ -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
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,14 @@ const (
|
||||
KindPRMerged = "pr_merged"
|
||||
KindPRRejected = "pr_rejected"
|
||||
KindTaskDead = "task_dead"
|
||||
KindLog = "log" // data: level, msg
|
||||
// Operator actions taken from the dashboard. Without these an
|
||||
// intervention is recorded in the tasks table but invisible on the
|
||||
// timeline and the activity stream -- the one kind of event most worth
|
||||
// seeing, because it explains why a task changed course.
|
||||
KindHumanApproved = "human_approved"
|
||||
KindHumanRejected = "human_rejected"
|
||||
KindTaskRetried = "task_retried"
|
||||
KindLog = "log" // data: level, msg
|
||||
)
|
||||
|
||||
// Event is the single wire type: task lifecycle, stage progress, agent
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
// Package forgerpc lets archie-agent call the four forge.Forge methods
|
||||
// workflow stages invoke mid-run (Comment, CloseIssue, CreatePR,
|
||||
// SetStateLabel) over core NATS request/reply, instead of the agent
|
||||
// container holding a live forge API token. archied remains the sole
|
||||
// holder of forge credentials and the sole caller of forge.Forge.
|
||||
// Package forgerpc lets archie-agent call the forge methods workflow stages
|
||||
// invoke mid-run -- CloseIssue, CreatePR and LinkBranch, the workflow.Forger
|
||||
// set -- over core NATS request/reply, instead of the agent container holding
|
||||
// a live forge API token. archied remains the sole holder of forge credentials
|
||||
// and the sole caller of forge.Forge.
|
||||
//
|
||||
// Only these four methods are proxied -- the rest of forge.Forge (issue
|
||||
// polling, invitations, reactions, PR-state reconciliation) is used
|
||||
// exclusively by the daemon's own poll/reconcile loops, never from inside
|
||||
// a workflow stage, so there's nothing for archie-agent to call.
|
||||
// The rest of forge.Forge (issue polling, invitations, reactions, PR-state
|
||||
// reconciliation) is used exclusively by the daemon's own poll/reconcile
|
||||
// loops, never from inside a workflow stage, so there is nothing for
|
||||
// archie-agent to call.
|
||||
//
|
||||
// The server also still answers Comment and SetStateLabel. No current agent
|
||||
// calls them; the handlers exist so an older archie-agent image keeps working
|
||||
// against a newer daemon. The compatibility is one-directional: a NEW agent
|
||||
// against an OLD daemon has no LinkBranch handler to reach, and the request
|
||||
// times out, so an image skew that way parks tasks. Note it in release notes
|
||||
// rather than assuming either side can lag.
|
||||
package forgerpc
|
||||
|
||||
import (
|
||||
@@ -27,6 +34,7 @@ const (
|
||||
SubjectComment = "archie.forge.comment"
|
||||
SubjectCloseIssue = "archie.forge.close_issue"
|
||||
SubjectCreatePR = "archie.forge.create_pr"
|
||||
SubjectLinkBranch = "archie.forge.link_branch"
|
||||
SubjectSetStateLabel = "archie.forge.set_state_label"
|
||||
)
|
||||
|
||||
@@ -56,6 +64,12 @@ type CreatePRResponse struct {
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
type LinkBranchRequest struct {
|
||||
Owner, Repo string
|
||||
IssueNumber int
|
||||
Branch string
|
||||
}
|
||||
|
||||
type SetStateLabelRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
@@ -74,13 +88,14 @@ type Server struct {
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// Register subscribes all four handlers on nc. The returned func
|
||||
// Register subscribes all handlers on nc. The returned func
|
||||
// unsubscribes all of them.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectComment, Handler: s.handleComment},
|
||||
{Subject: SubjectCloseIssue, Handler: s.handleCloseIssue},
|
||||
{Subject: SubjectCreatePR, Handler: s.handleCreatePR},
|
||||
{Subject: SubjectLinkBranch, Handler: s.handleLinkBranch},
|
||||
{Subject: SubjectSetStateLabel, Handler: s.handleSetStateLabel},
|
||||
})
|
||||
}
|
||||
@@ -115,13 +130,22 @@ func (s *Server) handleCreatePR(msg *nats.Msg) {
|
||||
s.respond(msg, CreatePRResponse{Number: num, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleLinkBranch(msg *nats.Msg) {
|
||||
var req LinkBranchRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode link_branch request: %w", err))})
|
||||
return
|
||||
}
|
||||
err := s.Forge.LinkBranch(context.Background(), req.Owner, req.Repo, req.IssueNumber, req.Branch)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
var req SetStateLabelRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode set_state_label request: %w", err))})
|
||||
return
|
||||
}
|
||||
// SetStateLabel has no error return in forge.Forge -- nothing to propagate.
|
||||
s.Forge.SetStateLabel(context.Background(), req.Owner, req.Repo, req.Number, req.Label, req.KnownLabels)
|
||||
s.respond(msg, Response{})
|
||||
}
|
||||
@@ -141,6 +165,11 @@ type Client struct {
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
// Comment and SetStateLabel are not in workflow.Forger, so no current agent
|
||||
// calls them. They stay as the client half of handlers kept for image skew
|
||||
// (see the package doc) -- and as the only way to exercise those handlers
|
||||
// end to end, which is why removing them would leave the compatibility path
|
||||
// untested rather than merely unused.
|
||||
func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
req := CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body}
|
||||
resp, err := natsrpc.Call[CommentResponse](ctx, c.rpc(), SubjectComment, req)
|
||||
@@ -174,9 +203,17 @@ func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, b
|
||||
return resp.Number, nil
|
||||
}
|
||||
|
||||
// SetStateLabel matches forge.Forge's signature (no error return). RPC or
|
||||
// server-side failures are logged by the server; the daemon still owns
|
||||
// SetStateLabel's fire-and-forget semantics.
|
||||
func (c *Client) LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error {
|
||||
req := LinkBranchRequest{Owner: owner, Repo: repo, IssueNumber: issueNumber, Branch: branch}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectLinkBranch, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// SetStateLabel remains available for RPC compatibility with older workers;
|
||||
// the current workflow deliberately never calls it.
|
||||
func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) {
|
||||
req := SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels}
|
||||
_, _ = natsrpc.Call[Response](ctx, c.rpc(), SubjectSetStateLabel, req)
|
||||
|
||||
@@ -39,6 +39,7 @@ type fakeForge struct {
|
||||
closes []closeCall
|
||||
prs []prCall
|
||||
stateLabels []stateLabelCall
|
||||
branches []branchCall
|
||||
|
||||
commentErr error
|
||||
closeErr error
|
||||
@@ -64,6 +65,10 @@ type stateLabelCall struct {
|
||||
label string
|
||||
knownLabels []string
|
||||
}
|
||||
type branchCall struct {
|
||||
owner, repo, branch string
|
||||
number int
|
||||
}
|
||||
|
||||
func (f *fakeForge) Comment(_ context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
f.comments = append(f.comments, commentCall{owner, repo, number, body})
|
||||
@@ -90,6 +95,11 @@ func (f *fakeForge) SetStateLabel(_ context.Context, owner, repo string, number
|
||||
f.stateLabels = append(f.stateLabels, stateLabelCall{owner, repo, number, label, knownLabels})
|
||||
}
|
||||
|
||||
func (f *fakeForge) LinkBranch(_ context.Context, owner, repo string, number int, branch string) error {
|
||||
f.branches = append(f.branches, branchCall{owner: owner, repo: repo, number: number, branch: branch})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
func (f *fakeForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
@@ -115,9 +125,6 @@ func (f *fakeForge) React(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) VerifyPush(context.Context, string, string) error { panic("unexpected call") }
|
||||
func (f *fakeForge) LinkBranch(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T) (*fakeForge, *Client) {
|
||||
t.Helper()
|
||||
@@ -179,6 +186,17 @@ func TestClientCreatePRPersistsViaServer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientLinkBranchPersistsViaServer(t *testing.T) {
|
||||
f, client := newTestServer(t)
|
||||
|
||||
if err := client.LinkBranch(context.Background(), "acme", "widget", 4, "fix/4-bug"); err != nil {
|
||||
t.Fatalf("LinkBranch: %v", err)
|
||||
}
|
||||
if len(f.branches) != 1 || f.branches[0] != (branchCall{owner: "acme", repo: "widget", number: 4, branch: "fix/4-bug"}) {
|
||||
t.Fatalf("branch link did not reach server, got %+v", f.branches)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSetStateLabelPersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
|
||||
@@ -376,26 +376,6 @@ func (a *Adapter) IncrementRetryCount(ctx context.Context, taskID int64) error {
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// WaitingTasks returns tasks in waiting_human state.
|
||||
func (a *Adapter) WaitingTasks(ctx context.Context) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []store.Task
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Status != store.StatusWaitingHuman {
|
||||
continue
|
||||
}
|
||||
out = append(out, *t)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// OpenPRs returns tasks in pr_open state.
|
||||
func (a *Adapter) OpenPRs(ctx context.Context) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
|
||||
@@ -100,13 +100,15 @@ func TestChatTaskLifecyclePreservesRouting(t *testing.T) {
|
||||
if err := s.Transition(ctx, task.ID, store.StatusQueued, store.StatusWaitingHuman, "await approval"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waiting, err := s.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// Routing metadata must survive a status transition: a chat task that
|
||||
// stops for approval still has to come back to the identity that owns it.
|
||||
waiting, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || waiting == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", waiting, err)
|
||||
}
|
||||
if len(waiting) != 1 || waiting[0].Source != store.SourceChat ||
|
||||
waiting[0].Identity != "reviewer" {
|
||||
t.Fatalf("WaitingTasks() = %+v, want chat/reviewer routing", waiting)
|
||||
if waiting.Status != store.StatusWaitingHuman || waiting.Source != store.SourceChat ||
|
||||
waiting.Identity != "reviewer" {
|
||||
t.Fatalf("waiting task = %+v, want waiting_human chat/reviewer routing", waiting)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,15 +284,6 @@ func TestEmptyStoreOperations(t *testing.T) {
|
||||
t.Errorf("Tasks on empty store should be empty, got %d", len(tasks))
|
||||
}
|
||||
|
||||
// WaitingTasks on empty store.
|
||||
waiting, err := s.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
t.Errorf("WaitingTasks on empty store: %v", err)
|
||||
}
|
||||
if len(waiting) != 0 {
|
||||
t.Errorf("WaitingTasks on empty store should be empty, got %d", len(waiting))
|
||||
}
|
||||
|
||||
// OpenPRs on empty store.
|
||||
prs, err := s.OpenPRs(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -75,6 +75,41 @@ func TestCatalogMissingDirReturnsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogRootsUsesPrecedenceAndTracksRoot(t *testing.T) {
|
||||
project := t.TempDir()
|
||||
global := t.TempDir()
|
||||
writeSkill := func(root, name, description string) {
|
||||
dir := filepath.Join(root, ".agents", "skills", name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content := "---\nname: " + name + "\ndescription: " + description + "\n---\nBody.\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
writeSkill(project, "shared-name", "project copy")
|
||||
writeSkill(project, "project-only", "project skill")
|
||||
writeSkill(global, "shared-name", "global copy")
|
||||
writeSkill(global, "global-only", "global skill")
|
||||
|
||||
entries, err := CatalogRoots(project, global)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("got %d catalog entries, want 3", len(entries))
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name == "shared-name" {
|
||||
if entry.Description != "project copy" || entry.Root != project {
|
||||
t.Fatalf("shared-name = %#v, want project entry", entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── archie-wf-* naming convention ────────────────────────────────────
|
||||
|
||||
func TestSkillsUseArchiewfNaming(t *testing.T) {
|
||||
|
||||
@@ -37,6 +37,7 @@ type CatalogEntry struct {
|
||||
Description string
|
||||
Workflow string // from metadata.archie.workflow -- which workflow this skill handles
|
||||
Dir string // skill directory name
|
||||
Root string // catalog root containing .agents/skills
|
||||
}
|
||||
|
||||
// Catalog scans dir/.agents/skills/*/SKILL.md and returns catalog entries
|
||||
@@ -83,11 +84,70 @@ func Catalog(dir string) ([]CatalogEntry, error) {
|
||||
Description: fm.Description,
|
||||
Workflow: wf,
|
||||
Dir: name,
|
||||
Root: dir,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CatalogRoots merges catalogues from roots in precedence order. The first
|
||||
// root containing a skill name wins, so callers can layer project skills over
|
||||
// shared and user-global skills deterministically.
|
||||
func CatalogRoots(roots ...string) ([]CatalogEntry, error) {
|
||||
seen := make(map[string]struct{})
|
||||
var out []CatalogEntry
|
||||
for _, root := range roots {
|
||||
entries, err := Catalog(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if _, ok := seen[entry.Name]; ok {
|
||||
continue
|
||||
}
|
||||
seen[entry.Name] = struct{}{}
|
||||
out = append(out, entry)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DefaultRoots returns the discovery roots for a daemon. Explicit project and
|
||||
// shared roots take precedence over the user's global skills directory.
|
||||
func DefaultRoots(workDir, sharedDir string) []string {
|
||||
var roots []string
|
||||
for _, root := range []string{workDir, sharedDir} {
|
||||
if root != "" && !containsRoot(roots, root) {
|
||||
roots = append(roots, root)
|
||||
}
|
||||
}
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" && !containsRoot(roots, home) {
|
||||
roots = append(roots, home)
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
// containsRoot compares roots after normalising trailing separators, so
|
||||
// "/srv/skills" and "/srv/skills/" are one root rather than two -- otherwise
|
||||
// the same directory is scanned twice and every skill in it appears twice.
|
||||
func containsRoot(roots []string, root string) bool {
|
||||
target := normaliseRoot(root)
|
||||
for _, existing := range roots {
|
||||
if normaliseRoot(existing) == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func normaliseRoot(root string) string {
|
||||
if root == "" {
|
||||
return root
|
||||
}
|
||||
return filepath.Clean(root)
|
||||
}
|
||||
|
||||
// SkillForWorkflow returns the catalog entry whose Workflow field matches
|
||||
// the given workflow name, or nil if no skill declares that workflow.
|
||||
// Replaces hardcoded workflow→skill lookup tables.
|
||||
|
||||
@@ -23,10 +23,14 @@ func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry {
|
||||
names := make([]any, len(catalog))
|
||||
descByName := make(map[string]string, len(catalog))
|
||||
dirByName := make(map[string]string, len(catalog))
|
||||
rootByName := make(map[string]string, len(catalog))
|
||||
for i, e := range catalog {
|
||||
names[i] = e.Name
|
||||
descByName[e.Name] = e.Description
|
||||
dirByName[e.Name] = e.Dir
|
||||
if e.Root != "" {
|
||||
rootByName[e.Name] = e.Root
|
||||
}
|
||||
}
|
||||
|
||||
return &tools.ToolEntry{
|
||||
@@ -53,7 +57,11 @@ func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry {
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("skill_activate: unknown skill %q", name)
|
||||
}
|
||||
body := LoadBody(dir, skillDir)
|
||||
root := dir
|
||||
if catalogRoot := rootByName[name]; catalogRoot != "" {
|
||||
root = catalogRoot
|
||||
}
|
||||
body := LoadBody(root, skillDir)
|
||||
if body == "" {
|
||||
return nil, fmt.Errorf("skill_activate: %q has no body (SKILL.md missing or empty)", name)
|
||||
}
|
||||
|
||||
@@ -81,6 +81,25 @@ func TestActivateToolHandlerReturnsFullBody(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivateToolHandlerLoadsFromCatalogEntryRoot(t *testing.T) {
|
||||
global := t.TempDir()
|
||||
writeSkill(t, global, "global-only", "global skill", "global body")
|
||||
|
||||
catalog, err := CatalogRoots(global)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := ActivateTool(t.TempDir(), catalog)
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{"name": "global-only"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "global body" {
|
||||
t.Errorf("body = %v, want global body", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivateToolHandlerRejectsUnknownSkill(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeSkill(t, dir, "alpha", "does alpha things", "alpha body")
|
||||
|
||||
@@ -101,7 +101,7 @@ func (s *Store) Tasks(ctx context.Context, limit int) (tasks []Task, retErr erro
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, owner, repo, issue_number, title, status, workflow, stage,
|
||||
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
|
||||
created_at, updated_at
|
||||
created_at, updated_at, plan, source
|
||||
FROM tasks ORDER BY updated_at DESC LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -111,10 +111,15 @@ func (s *Store) Tasks(ctx context.Context, limit int) (tasks []Task, retErr erro
|
||||
}()
|
||||
for rows.Next() {
|
||||
var t Task
|
||||
// Plan and Source are read by the dashboard: Plan gates the
|
||||
// "Decision required" panel on a waiting_human task, and Source
|
||||
// decides whether an issue link is rendered at all -- a chat task's
|
||||
// issue number is synthetic and links nowhere.
|
||||
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title,
|
||||
&t.Status, &t.Workflow, &t.Stage, &t.PRNumber, &t.TokensUsed,
|
||||
&t.Iterations, &t.Attempt, &t.ParkReason, &t.RetryCount,
|
||||
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt}); err != nil {
|
||||
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt},
|
||||
&t.Plan, &t.Source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
|
||||
@@ -35,7 +35,6 @@ type TaskLifecycle interface {
|
||||
type TaskQueries interface {
|
||||
TaskByIssue(ctx context.Context, owner, repo string, number int) (*Task, error)
|
||||
TaskByID(ctx context.Context, taskID int64) (*Task, error)
|
||||
WaitingTasks(ctx context.Context) ([]Task, error)
|
||||
OpenPRs(ctx context.Context) ([]Task, error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
Tasks(ctx context.Context, limit int) ([]Task, error)
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestTaskByIssue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitingTasksAndRequeue(t *testing.T) {
|
||||
func TestRequeueFromWaitingHuman(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -44,16 +44,12 @@ func TestWaitingTasksAndRequeue(t *testing.T) {
|
||||
t.Fatalf("claim = (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
if waiting, err := s.WaitingTasks(ctx); err != nil || len(waiting) != 0 {
|
||||
t.Fatalf("WaitingTasks before transition = (%+v, %v)", waiting, err)
|
||||
}
|
||||
|
||||
if err := s.Transition(ctx, task.ID, StatusRunning, StatusWaitingHuman, "needs input"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waiting, err := s.WaitingTasks(ctx)
|
||||
if err != nil || len(waiting) != 1 || waiting[0].ID != task.ID {
|
||||
t.Fatalf("WaitingTasks = (%+v, %v)", waiting, err)
|
||||
waiting, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || waiting == nil || waiting.Status != StatusWaitingHuman {
|
||||
t.Fatalf("after transition = (%+v, %v), want waiting_human", waiting, err)
|
||||
}
|
||||
|
||||
// Requeue with a workflow forces it (waiting_human -> approved -> implement).
|
||||
|
||||
+3
-26
@@ -169,8 +169,9 @@ func OpenTest(t interface{ TempDir() string }) *Store {
|
||||
return s
|
||||
}
|
||||
|
||||
// IncrementRetryCount atomically bumps retry_count by 1. Called after
|
||||
// a parked task is requeued by maybeRetryParked.
|
||||
// IncrementRetryCount atomically bumps retry_count by 1. Called when an
|
||||
// operator retries a parked task; the caller enforces max_retries against
|
||||
// the resulting count.
|
||||
func (s *Store) IncrementRetryCount(ctx context.Context, taskID int64) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`UPDATE tasks SET retry_count = retry_count + 1, updated_at = datetime('now') WHERE id = ?`, taskID)
|
||||
@@ -348,30 +349,6 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*Task, error) {
|
||||
return t, err
|
||||
}
|
||||
|
||||
// WaitingTasks returns tasks blocked on human input.
|
||||
func (s *Store) WaitingTasks(ctx context.Context) (tasks []Task, retErr error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, owner, repo, issue_number, title, body, plan, workflow,
|
||||
watch_comment_id, status, source, identity
|
||||
FROM tasks WHERE status='waiting_human'`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
retErr = errors.Join(retErr, rows.Close())
|
||||
}()
|
||||
for rows.Next() {
|
||||
var t Task
|
||||
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title,
|
||||
&t.Body, &t.Plan, &t.Workflow, &t.WatchCommentID, &t.Status,
|
||||
&t.Source, &t.Identity); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
}
|
||||
return tasks, rows.Err()
|
||||
}
|
||||
|
||||
// Requeue puts a task back on the queue. A non-empty workflow forces it
|
||||
// (the waiting_human → approved → implement handoff); empty keeps the
|
||||
// task's current workflow (retrying a parked task).
|
||||
|
||||
@@ -387,13 +387,15 @@ func TestLifecycleQueriesPreserveChatTaskRouting(t *testing.T) {
|
||||
if err := s.Transition(ctx, waiting.ID, StatusQueued, StatusWaitingHuman, "await approval"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitingTasks, err := s.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// Routing metadata must survive a status transition: a chat task that
|
||||
// stops for approval still has to come back to the identity that owns it.
|
||||
waitingTask, err := s.TaskByID(ctx, waiting.ID)
|
||||
if err != nil || waitingTask == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", waitingTask, err)
|
||||
}
|
||||
if len(waitingTasks) != 1 || waitingTasks[0].Source != SourceChat ||
|
||||
waitingTasks[0].Identity != "reviewer" {
|
||||
t.Fatalf("WaitingTasks() = %+v, want chat/reviewer routing", waitingTasks)
|
||||
if waitingTask.Status != StatusWaitingHuman || waitingTask.Source != SourceChat ||
|
||||
waitingTask.Identity != "reviewer" {
|
||||
t.Fatalf("waiting task = %+v, want waiting_human chat/reviewer routing", waitingTask)
|
||||
}
|
||||
|
||||
pr, err := s.EnqueueChatTask(ctx, "acme", "todo", "open PR", "", "implement", "builder", 999_002)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Tasks() is what the dashboard's task list is built from, and the UI reads
|
||||
// two fields the query never selected: Plan, which gates the "Decision
|
||||
// required" panel on a waiting_human task, and Source, which decides whether
|
||||
// to render a forge issue link at all.
|
||||
//
|
||||
// Both came back as the zero value, so the panel could never appear and a
|
||||
// chat-sourced task -- whose issue_number is synthetic -- rendered a link to
|
||||
// an issue that does not exist. Neither failed loudly; the features were
|
||||
// simply dead.
|
||||
func TestTasksSelectsFieldsTheUIReads(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := OpenTest(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "o", "r", 7, "forge task", "body", "", ""); err != nil {
|
||||
t.Fatalf("EnqueueIssue: %v", err)
|
||||
}
|
||||
forgeTaskRow, err := s.TaskByIssue(ctx, "o", "r", 7)
|
||||
if err != nil || forgeTaskRow == nil {
|
||||
t.Fatalf("TaskByIssue: %v", err)
|
||||
}
|
||||
forgeID := forgeTaskRow.ID
|
||||
|
||||
chatTaskRow, err := s.EnqueueChatTask(ctx, "o", "r", "chat task", "body", "", "", 900001)
|
||||
if err != nil {
|
||||
t.Fatalf("EnqueueChatTask: %v", err)
|
||||
}
|
||||
chatID := chatTaskRow.ID
|
||||
|
||||
// A plan is what an operator approves or rejects, so it has to survive
|
||||
// the read the approval UI is built on.
|
||||
const plan = "1. add the thing\n2. test the thing"
|
||||
forgeTaskRow.Plan = plan
|
||||
if err := s.Update(ctx, forgeTaskRow); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
|
||||
tasks, err := s.Tasks(ctx, 50)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
|
||||
byID := make(map[int64]Task, len(tasks))
|
||||
for _, task := range tasks {
|
||||
byID[task.ID] = task
|
||||
}
|
||||
|
||||
forgeTask, ok := byID[forgeID]
|
||||
if !ok {
|
||||
t.Fatalf("forge task %d missing from Tasks()", forgeID)
|
||||
}
|
||||
if forgeTask.Plan != plan {
|
||||
t.Errorf("Plan = %q, want %q: the approval panel is gated on this and "+
|
||||
"can never render while it is empty", forgeTask.Plan, plan)
|
||||
}
|
||||
if forgeTask.Source != SourceForge {
|
||||
t.Errorf("Source = %q, want %q", forgeTask.Source, SourceForge)
|
||||
}
|
||||
|
||||
chatTask, ok := byID[chatID]
|
||||
if !ok {
|
||||
t.Fatalf("chat task %d missing from Tasks()", chatID)
|
||||
}
|
||||
if chatTask.Source != SourceChat {
|
||||
t.Errorf("Source = %q, want %q: without it the UI links a synthetic "+
|
||||
"issue number to a forge issue that does not exist",
|
||||
chatTask.Source, SourceChat)
|
||||
}
|
||||
if chatTask.IsForgeBacked() {
|
||||
t.Error("IsForgeBacked() is true for a chat task read through Tasks()")
|
||||
}
|
||||
}
|
||||
@@ -19,26 +19,17 @@ type SkillView struct {
|
||||
// beyond what is in the source. It answers the same question a fresh
|
||||
// operator would ask by reading internal/skill/, without the reading.
|
||||
//
|
||||
// The catalogue is scanned from cfg.SkillsDir when configured (a shared
|
||||
// directory meant to be pointed at deliberately), falling back to
|
||||
// cfg.WorkDir's own .agents/skills/ otherwise. Both are legitimate --
|
||||
// skill.Catalog treats a missing directory as "no skills," not an error --
|
||||
// so an unconfigured deployment gets an empty, explained list rather than a
|
||||
// failure.
|
||||
// The catalogue layers project, explicitly shared, and user-global skills.
|
||||
// Earlier roots win when names collide. Missing roots are legitimate and
|
||||
// produce an empty or partial catalogue rather than a failed dashboard.
|
||||
func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Cfg == nil {
|
||||
writeJSON(w, map[string]any{"skills": []SkillView{}, "dir": ""})
|
||||
writeJSON(w, map[string]any{"skills": []SkillView{}})
|
||||
return
|
||||
}
|
||||
|
||||
dir := s.Cfg.SkillsDir
|
||||
source := "shared skills directory"
|
||||
if dir == "" {
|
||||
dir = s.Cfg.WorkDir
|
||||
source = "bundled with this project"
|
||||
}
|
||||
|
||||
catalog, err := skill.Catalog(dir)
|
||||
roots := skill.DefaultRoots(s.Cfg.WorkDir, s.Cfg.SkillsDir)
|
||||
catalog, err := skill.CatalogRoots(roots...)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read skill catalogue: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -50,9 +41,28 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) {
|
||||
Name: entry.Name,
|
||||
Description: entry.Description,
|
||||
Workflow: entry.Workflow,
|
||||
Source: source,
|
||||
Source: skillSource(entry.Root, s.Cfg.WorkDir, s.Cfg.SkillsDir),
|
||||
})
|
||||
}
|
||||
|
||||
writeJSON(w, map[string]any{"skills": views, "dir": dir})
|
||||
// Each skill already carries its own Source, which is what the page
|
||||
// renders. A top-level dir/dirs pair had no consumer and implied the
|
||||
// catalog came from one place when it is merged from several.
|
||||
writeJSON(w, map[string]any{"skills": views})
|
||||
}
|
||||
|
||||
// skillSource labels where a skill was loaded from.
|
||||
//
|
||||
// sharedDir is checked first: when it equals workDir the roots collapse to one
|
||||
// entry, and matching workDir first labelled every shared skill as a project
|
||||
// skill.
|
||||
func skillSource(root, workDir, sharedDir string) string {
|
||||
switch root {
|
||||
case sharedDir:
|
||||
return "shared skills"
|
||||
case workDir:
|
||||
return "project skills"
|
||||
default:
|
||||
return "user-global skills"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) handleSummary(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -64,3 +70,196 @@ func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, evs)
|
||||
}
|
||||
|
||||
type taskActionRequest struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var req taskActionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid action", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
task, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Each action reports the event to record, or writes its own error
|
||||
// response and returns nothing. Keeping the dispatch flat here and the
|
||||
// rules in one function each is what stops this growing back into a
|
||||
// single branch nobody can read.
|
||||
ctx := r.Context()
|
||||
var outcome *actionOutcome
|
||||
switch req.Action {
|
||||
case "approve":
|
||||
outcome = s.approveTask(ctx, w, task)
|
||||
case "retry":
|
||||
outcome = s.retryTask(ctx, w, task)
|
||||
case "reject":
|
||||
outcome = s.rejectTask(ctx, w, task)
|
||||
default:
|
||||
http.Error(w, "unknown action", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if outcome == nil {
|
||||
return
|
||||
}
|
||||
|
||||
s.emit(events.Event{
|
||||
Kind: outcome.kind, TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber,
|
||||
Detail: outcome.detail,
|
||||
})
|
||||
writeJSON(w, map[string]any{"ok": true, "action": req.Action, "task_id": id})
|
||||
}
|
||||
|
||||
// actionOutcome is what a completed operator action should record.
|
||||
type actionOutcome struct {
|
||||
kind string
|
||||
detail string
|
||||
}
|
||||
|
||||
// storeFailed writes the response for a failed store write and reports
|
||||
// whether it did. A store write that fails is not the caller's fault;
|
||||
// answering 409 made the UI say "conflict" for a broken database.
|
||||
func storeFailed(w http.ResponseWriter, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return true
|
||||
}
|
||||
|
||||
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)
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{events.KindHumanApproved, "approved via the dashboard"}
|
||||
}
|
||||
|
||||
// retryTask requeues a parked task, or retires it once max_retries is spent.
|
||||
//
|
||||
// max_retries was configured, defaulted and reported by /api/config while
|
||||
// nothing enforced it: retry_count climbed forever, so a task that fails
|
||||
// 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)
|
||||
return nil
|
||||
}
|
||||
if limit := s.maxRetriesFor(task); limit > 0 && task.RetryCount >= limit {
|
||||
s.retireTask(ctx, task, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit))
|
||||
http.Error(w, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit), http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusParked, "")) {
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.IncrementRetryCount(ctx, task.ID)) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{events.KindTaskRetried, "retried via the dashboard"}
|
||||
}
|
||||
|
||||
// retireTask moves a spent task to dead. Failure is logged, not returned:
|
||||
// the caller is already answering with the reason it refused the retry.
|
||||
func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string) {
|
||||
if err := s.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
|
||||
s.logf("transition to dead failed", "task", task.ID, "err", err)
|
||||
return
|
||||
}
|
||||
s.emit(events.Event{
|
||||
Kind: events.KindTaskDead, TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: reason,
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
return nil
|
||||
}
|
||||
err := s.Store.Transition(ctx, task.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, "rejected via Web UI")
|
||||
if storeFailed(w, err) {
|
||||
return nil
|
||||
}
|
||||
s.closeRejectedIssue(ctx, task)
|
||||
return &actionOutcome{events.KindHumanRejected, "rejected via the dashboard"}
|
||||
}
|
||||
|
||||
// maxRetriesFor resolves the retry cap for a task, honouring a per-repo
|
||||
// override. Zero means unlimited.
|
||||
func (s *Server) maxRetriesFor(task *store.Task) int {
|
||||
if s.Cfg == nil {
|
||||
return 0
|
||||
}
|
||||
for _, repo := range s.Cfg.Repos {
|
||||
if repo.Owner == task.Owner && repo.Name == task.Repo {
|
||||
return repo.EffectiveMaxRetries(s.Cfg.MaxRetries)
|
||||
}
|
||||
}
|
||||
return s.Cfg.MaxRetries
|
||||
}
|
||||
|
||||
// closeRejectedIssue closes the forge issue behind a task the operator has
|
||||
// declined.
|
||||
//
|
||||
// Without this the issue stays open, labelled and assigned, so the next poll
|
||||
// re-enqueues it -- and once the operator uses Clear, which deletes the task
|
||||
// row, that is a second implementation and a second PR for work already
|
||||
// refused. Approve and retry deliberately leave the issue open: the task is
|
||||
// going back to work.
|
||||
//
|
||||
// Failure is logged, not returned. The operator's decision is already
|
||||
// recorded, and reporting an error would invite them to click again.
|
||||
func (s *Server) closeRejectedIssue(ctx context.Context, task *store.Task) {
|
||||
if s.Issues == nil {
|
||||
s.logf("task rejected but no forge is wired; the issue stays open and will be re-polled",
|
||||
"task", task.ID, "issue", task.IssueNumber)
|
||||
return
|
||||
}
|
||||
// A chat task's issue number is synthetic and matches no forge issue.
|
||||
if !task.IsForgeBacked() {
|
||||
return
|
||||
}
|
||||
const comment = "Closing: this was rejected from the archie dashboard. " +
|
||||
"Reopen the issue to have archie pick it up again."
|
||||
if err := s.Issues.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
|
||||
s.logf("closing rejected issue failed; it stays open and will be re-polled",
|
||||
"task", task.ID, "issue", task.IssueNumber, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// emit publishes an operator action so it reaches the task timeline and the
|
||||
// live activity stream. A nil publisher is not an error: the action is still
|
||||
// recorded in the store.
|
||||
func (s *Server) emit(e events.Event) {
|
||||
if s.Events == nil || e.Kind == "" {
|
||||
return
|
||||
}
|
||||
s.Events.Publish(e)
|
||||
}
|
||||
|
||||
func (s *Server) logf(msg string, args ...any) {
|
||||
if s.Log == nil {
|
||||
return
|
||||
}
|
||||
s.Log.Warn(msg, args...)
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// recordingCloser captures the forge issue-closure calls an action makes.
|
||||
type recordingCloser struct {
|
||||
calls []closeCall
|
||||
err error
|
||||
}
|
||||
|
||||
type closeCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
comment string
|
||||
}
|
||||
|
||||
func (r *recordingCloser) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
|
||||
r.calls = append(r.calls, closeCall{owner, repo, number, comment})
|
||||
return r.err
|
||||
}
|
||||
|
||||
// actionServer builds a dashboard server with a task in the given state, plus
|
||||
// the collaborators the action path needs.
|
||||
func actionServer(t *testing.T, status, parkReason string) (*Server, *store.Task, *recordingCloser, *events.Bus, *events.Sub) {
|
||||
t.Helper()
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, status, parkReason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
closer := &recordingCloser{}
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(16)
|
||||
|
||||
srv.Issues = closer
|
||||
srv.Events = bus
|
||||
srv.Cfg = &config.Config{MaxRetries: 3}
|
||||
return srv, task, closer, bus, sub
|
||||
}
|
||||
|
||||
func postAction(t *testing.T, srv *Server, id int64, action string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action",
|
||||
bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// max_retries is configured, defaulted and shown in /api/config, but nothing
|
||||
// enforced it: the Web UI retry incremented retry_count with no cap, so a
|
||||
// task that fails every time could be retried forever. At the cap the task
|
||||
// belongs in dead, which is what the setting exists to express.
|
||||
func TestRetryEnforcesMaxRetries(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
priorCount int
|
||||
maxRetries int
|
||||
wantStatus int
|
||||
wantTask string
|
||||
}{
|
||||
{name: "under the cap", priorCount: 0, maxRetries: 3, wantStatus: http.StatusOK, wantTask: store.StatusQueued},
|
||||
{name: "one below the cap", priorCount: 2, maxRetries: 3, wantStatus: http.StatusOK, wantTask: store.StatusQueued},
|
||||
{name: "at the cap", priorCount: 3, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: store.StatusDead},
|
||||
{name: "past the cap", priorCount: 5, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: store.StatusDead},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, store.StatusParked, "it broke")
|
||||
srv.Cfg = &config.Config{MaxRetries: tc.maxRetries}
|
||||
ctx := t.Context()
|
||||
for range tc.priorCount {
|
||||
if err := srv.Store.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
w := postAction(t, srv, task.ID, "retry")
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body)
|
||||
}
|
||||
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != tc.wantTask {
|
||||
t.Errorf("status = %q, want %q", got.Status, tc.wantTask)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Rejecting a task must stop the forge issue coming back. It stays open,
|
||||
// labelled and assigned otherwise, so the next poll re-enqueues it -- and if
|
||||
// the operator has used the dashboard's Clear, which deletes the row, that is
|
||||
// a second implementation and a second PR for work already declined.
|
||||
func TestRejectClosesTheForgeIssue(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
if len(closer.calls) != 1 {
|
||||
t.Fatalf("CloseIssue calls = %d, want 1: the issue stays open and is "+
|
||||
"re-polled, so the work is done twice", len(closer.calls))
|
||||
}
|
||||
call := closer.calls[0]
|
||||
if call.owner != "acme" || call.repo != "widget" || call.number != 11 {
|
||||
t.Errorf("closed %s/%s#%d, want acme/widget#11", call.owner, call.repo, call.number)
|
||||
}
|
||||
if call.comment == "" {
|
||||
t.Error("closed with no comment: an issue that closes itself with no " +
|
||||
"explanation reads as archie losing the work")
|
||||
}
|
||||
}
|
||||
|
||||
// Approve and retry put the task back to work, so the issue must stay open.
|
||||
func TestApproveAndRetryDoNotCloseTheIssue(t *testing.T) {
|
||||
for _, tc := range []struct{ action, status, reason string }{
|
||||
{"approve", store.StatusWaitingHuman, "review"},
|
||||
{"retry", store.StatusParked, "it broke"},
|
||||
} {
|
||||
t.Run(tc.action, func(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, tc.status, tc.reason)
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called %d times for %s; the task is going "+
|
||||
"back to work", len(closer.calls), tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A chat-sourced task has a synthetic issue number that matches no forge
|
||||
// issue, so closing it would either error or close an unrelated issue.
|
||||
func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
closer := &recordingCloser{}
|
||||
srv.Issues = closer
|
||||
srv.Cfg = &config.Config{MaxRetries: 3}
|
||||
|
||||
task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", 900001)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := srv.Store.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called for a chat task: issue number %d is synthetic",
|
||||
task.IssueNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// A forge that cannot close the issue must not fail the action: the operator's
|
||||
// decision is already recorded in the store, and reporting failure would
|
||||
// invite them to click again.
|
||||
func TestRejectSurvivesAForgeFailure(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
closer.err = errors.New("forge unreachable")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, want 200: the store transition succeeded", w.Code)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusClosedWontDo {
|
||||
t.Errorf("status = %q, want %q", got.Status, store.StatusClosedWontDo)
|
||||
}
|
||||
}
|
||||
|
||||
// Actions wrote store rows and nothing else, so the activity stream and the
|
||||
// task timeline never showed that a human had intervened -- the one kind of
|
||||
// event most worth seeing.
|
||||
func TestActionsEmitEvents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
status string
|
||||
reason string
|
||||
wantMsg string
|
||||
}{
|
||||
{name: "approve", action: "approve", status: store.StatusWaitingHuman, reason: "review", wantMsg: "approve"},
|
||||
{name: "retry", action: "retry", status: store.StatusParked, reason: "it broke", wantMsg: "retry"},
|
||||
{name: "reject", action: "reject", status: store.StatusWaitingHuman, reason: "review", wantMsg: "reject"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, sub := actionServer(t, tc.status, tc.reason)
|
||||
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
select {
|
||||
case ev := <-sub.C:
|
||||
if ev.TaskID != task.ID {
|
||||
t.Errorf("event TaskID = %d, want %d", ev.TaskID, task.ID)
|
||||
}
|
||||
if ev.Kind == "" {
|
||||
t.Error("event Kind is empty")
|
||||
}
|
||||
default:
|
||||
t.Fatalf("%s emitted no event: the activity stream and timeline "+
|
||||
"never show that a human intervened", tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Error mapping. A store failure is not the client's fault, and returning 409
|
||||
// tells the UI to say "conflict" for what is actually a broken database.
|
||||
func TestTaskActionErrorMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
setup func(t *testing.T, srv *Server, id int64)
|
||||
id func(id int64) string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "unknown action",
|
||||
body: `{"action":"detonate"}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "malformed body",
|
||||
body: `not json`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "non-numeric id",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "banana" },
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "unknown task",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "424242" },
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "wrong state",
|
||||
body: `{"action":"retry"}`,
|
||||
// The task is waiting_human, not parked.
|
||||
wantStatus: http.StatusConflict,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
if tc.setup != nil {
|
||||
tc.setup(t, srv, task.ID)
|
||||
}
|
||||
path := strconv.FormatInt(task.ID, 10)
|
||||
if tc.id != nil {
|
||||
path = tc.id(task.ID)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+path+"/action", bytes.NewBufferString(tc.body))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A store write failure is a 500, not a 409.
|
||||
func TestTaskActionStoreFailureIs500(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := base.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := base.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := base.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")},
|
||||
Log: base.Log,
|
||||
Cfg: &config.Config{MaxRetries: 3},
|
||||
}
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500: a store failure is not a conflict", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package webui
|
||||
|
||||
// Tests for the task-timeline route. The dashboard's "Click a row for its
|
||||
// timeline" interaction depends on GET /api/tasks/{id} returning exactly that
|
||||
// task's events, ordered, and on the literal /api/tasks/clear route beating
|
||||
// the {id} wildcard.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Approve requeues from the task's own recorded state rather than anything
|
||||
// the caller supplies, so a stale dashboard cannot approve a task twice.
|
||||
func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "approve me", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("approve status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusQueued || got.Workflow != "implement" {
|
||||
t.Fatalf("approved task = %+v, want queued/implement", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskActionRetriesParkedTask(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "retry me", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "failed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"retry"}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("retry status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusQueued || got.RetryCount != 1 {
|
||||
t.Fatalf("retried task = %+v, want queued/retry_count=1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskIsolatesTasks returns the timeline for one task, and only
|
||||
// that task: another task's events must not leak into the response.
|
||||
func TestHandleTaskIsolatesTasks(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
for _, ev := range []events.Event{
|
||||
{TaskID: 7, Kind: "stage_start", Stage: "plan", Detail: "bootstrap"},
|
||||
{TaskID: 7, Kind: "stage_end", Stage: "plan"},
|
||||
{TaskID: 8, Kind: "stage_start", Stage: "implement"},
|
||||
} {
|
||||
if _, err := srv.Store.InsertEvent(ctx, ev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got []events.Event
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("timeline has %d events, want 2 (task 8 must not leak in)", len(got))
|
||||
}
|
||||
if got[0].Kind != "stage_start" || got[0].Stage != "plan" {
|
||||
t.Errorf("first event = %+v, want stage_start/plan", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskUnknownID returns an empty list, not an error, for a task id
|
||||
// that has no events yet -- the UI renders "No events yet" from that.
|
||||
func TestHandleTaskUnknownID(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/999", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if body := strings.TrimSpace(w.Body.String()); body != "null" && body != "[]" {
|
||||
t.Fatalf("body = %s, want an empty timeline", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskBadID is covered in webui_test.go (400 on a non-numeric id).
|
||||
|
||||
// TestHandleTaskStoreError proves a store failure surfaces as 500 -- the UI
|
||||
// shows its "Could not load timeline" state and offers a retry.
|
||||
func TestHandleTaskStoreError(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleClearTasksProvenance proves the literal /api/tasks/clear route is
|
||||
// not captured by the {id} wildcard (which would 400 on "clear").
|
||||
func TestHandleClearTasksProvenance(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/clear", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 — /api/tasks/clear was captured by {id}", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -39,10 +39,33 @@ type Server struct {
|
||||
// stay frictionless -- see IsLoopback.
|
||||
Token string
|
||||
|
||||
// Issues closes the forge issue behind a rejected task. Optional: the
|
||||
// action still records the operator's decision without it, and says so
|
||||
// in the log. Deliberately the narrowest interface that does the job
|
||||
// rather than the whole forge client -- the dashboard has no business
|
||||
// commenting, labelling or opening PRs.
|
||||
Issues IssueCloser
|
||||
|
||||
// Events publishes operator actions so they reach the task timeline and
|
||||
// the live activity stream. Optional: nil means the action is recorded
|
||||
// in the store but invisible to anyone watching.
|
||||
Events EventPublisher
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[chan events.Event]struct{}
|
||||
}
|
||||
|
||||
// IssueCloser closes the forge issue behind a task.
|
||||
type IssueCloser interface {
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
}
|
||||
|
||||
// EventPublisher accepts events for the store and the live stream. The bus
|
||||
// in cmd/archied satisfies it.
|
||||
type EventPublisher interface {
|
||||
Publish(events.Event)
|
||||
}
|
||||
|
||||
// Broadcast fans an (ID-stamped) event out to every connected SSE
|
||||
// client; stalled clients drop events rather than blocking the caller.
|
||||
func (s *Server) Broadcast(e events.Event) {
|
||||
@@ -61,6 +84,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/summary", s.handleSummary)
|
||||
mux.HandleFunc("GET /api/setup", s.handleSetup)
|
||||
mux.HandleFunc("GET /api/tasks", s.handleTasks)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/clear", s.handleClearTasks)
|
||||
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
|
||||
|
||||
@@ -49,6 +49,15 @@ type stubStore struct {
|
||||
stageStatsErr error
|
||||
tokensByDayErr error
|
||||
eventsSinceErr error
|
||||
taskEventsErr error
|
||||
requeueErr error
|
||||
}
|
||||
|
||||
func (s *stubStore) Requeue(ctx context.Context, id int64, from, workflow string) error {
|
||||
if s.requeueErr != nil {
|
||||
return s.requeueErr
|
||||
}
|
||||
return s.TaskStore.Requeue(ctx, id, from, workflow)
|
||||
}
|
||||
|
||||
func (s *stubStore) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error) {
|
||||
@@ -79,6 +88,13 @@ func (s *stubStore) EventsSince(ctx context.Context, sinceID int64, limit int) (
|
||||
return s.TaskStore.EventsSince(ctx, sinceID, limit)
|
||||
}
|
||||
|
||||
func (s *stubStore) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error) {
|
||||
if s.taskEventsErr != nil {
|
||||
return nil, s.taskEventsErr
|
||||
}
|
||||
return s.TaskStore.TaskEvents(ctx, taskID)
|
||||
}
|
||||
|
||||
func TestHandleSummary(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
|
||||
@@ -62,8 +62,7 @@ func Feasibility() Workflow {
|
||||
tc.decision = &decision{Fit: *captured.Fit, Reasons: captured.Reasons}
|
||||
if !tc.decision.Fit {
|
||||
if tc.Task.IsForgeBacked() {
|
||||
comment := fmt.Sprintf("**archie assessed this feature as not a fit -- closing as won't-do.**\n\n%s\n\n_Reopen and re-assign if you disagree._", tc.decision.Reasons)
|
||||
if err := tc.Forge.CloseIssue(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, comment); err != nil {
|
||||
if err := tc.Forge.CloseIssue(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -94,18 +93,9 @@ func Feasibility() Workflow {
|
||||
},
|
||||
}.Stage(),
|
||||
|
||||
// Deliver the PRD and block on Sam: issue comment (the reply
|
||||
// channel the daemon watches) plus the notify webhook (n8n →
|
||||
// email).
|
||||
// Persist the PRD and block on Sam. Messaging and the Web UI are
|
||||
// the decision surfaces; the forge issue is not a chat log.
|
||||
{Name: "deliver", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.Task.IsForgeBacked() {
|
||||
body := fmt.Sprintf("**archie's PRD -- awaiting your go/no-go.** Reply on this issue; I'll read your answer.\n\n%s", tc.Task.Plan)
|
||||
commentID, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tc.Task.WatchCommentID = commentID
|
||||
}
|
||||
notify(ctx, tc, "feasibility_prd")
|
||||
tc.Outcome = Outcome{Status: store.StatusWaitingHuman, Detail: "PRD delivered, awaiting go/no-go"}
|
||||
return nil
|
||||
|
||||
@@ -119,13 +119,6 @@ func Implement() Workflow {
|
||||
},
|
||||
OnResult: func(tc *TaskContext, res agentexec.Result) error {
|
||||
tc.Task.Plan = res.Summary
|
||||
if !tc.Task.IsForgeBacked() {
|
||||
return nil
|
||||
}
|
||||
body := fmt.Sprintf("**archie's plan** (review now if you want to veto -- building starts immediately):\n\n%s", res.Summary)
|
||||
if _, err := tc.Forge.Comment(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil {
|
||||
tc.Log.Warn("failed to post plan comment", "err", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}.Stage(),
|
||||
@@ -166,8 +159,7 @@ func Implement() Workflow {
|
||||
StageDiffCap(),
|
||||
StageOpenPR(func(tc *TaskContext) string {
|
||||
return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %d tokens*",
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed) +
|
||||
issueClosureReference(tc.Task)
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
@@ -13,6 +14,9 @@ import (
|
||||
type fakeForge struct {
|
||||
closed int
|
||||
commented []string
|
||||
calls []string
|
||||
linkErr error
|
||||
prNumber int
|
||||
}
|
||||
|
||||
func (f *fakeForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
@@ -40,7 +44,11 @@ func (f *fakeForge) IssuesWithLabel(ctx context.Context, owner, repo, label stri
|
||||
}
|
||||
|
||||
func (f *fakeForge) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
return 0, nil
|
||||
f.calls = append(f.calls, "pr:"+head)
|
||||
// A real forge never answers 0, and returning it let a test pass while
|
||||
// the PR number was never recorded.
|
||||
f.prNumber++
|
||||
return f.prNumber, nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) PRState(ctx context.Context, owner, repo string, number int) (string, error) {
|
||||
@@ -57,6 +65,11 @@ func (f *fakeForge) RepliesAfter(ctx context.Context, owner, repo string, number
|
||||
|
||||
func (f *fakeForge) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, known []string) {
|
||||
}
|
||||
|
||||
func (f *fakeForge) LinkBranch(ctx context.Context, owner, repo string, number int, branch string) error {
|
||||
f.calls = append(f.calls, "link:"+branch)
|
||||
return f.linkErr
|
||||
}
|
||||
func (f *fakeForge) VerifyPush(ctx context.Context, owner, repo string) error { return nil }
|
||||
|
||||
// TestStageCommitPushClosesIssueWhenBuildNoChanges verifies that
|
||||
@@ -94,15 +107,24 @@ func TestStageCommitPushClosesIssueWhenBuildNoChanges(t *testing.T) {
|
||||
t.Log("Outcome set to Merged (workflow stops)")
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, c := range f.commented {
|
||||
if strings.Contains(c, "no changes required") {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if len(f.commented) != 0 {
|
||||
t.Errorf("expected no forge comments, got %d", len(f.commented))
|
||||
}
|
||||
if !found {
|
||||
t.Error("expected a comment about no changes required")
|
||||
}
|
||||
|
||||
func TestOpenPRLinksSourceBranchBeforeCreatingPR(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := &TaskContext{
|
||||
Forge: f,
|
||||
Task: &store.Task{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 42, Title: "Fix bug"},
|
||||
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
|
||||
Branch: "fix/42-bug",
|
||||
}
|
||||
if err := OpenPR(context.Background(), tc, "summary"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(f.calls) != 2 || f.calls[0] != "link:fix/42-bug" || f.calls[1] != "pr:fix/42-bug" {
|
||||
t.Fatalf("forge calls = %v, want [link:fix/42-bug pr:fix/42-bug]", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,19 +155,43 @@ func TestStageCommitPushDoesNotUseSyntheticIssueForChatNoOp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueClosureReferenceOnlyForForgeTasks(t *testing.T) {
|
||||
// LinkBranch is cosmetic: it puts the branch in the issue's sidebar on Gitea
|
||||
// and does nothing at all on GitHub. Failing the stage on it meant the pull
|
||||
// request -- the entire point of the run -- was never opened, and the task
|
||||
// parked. Worse, a retry re-links the same branch, which Gitea answers with
|
||||
// a conflict, so every retry parked again.
|
||||
func TestOpenPRSurvivesALinkBranchFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
task *store.Task
|
||||
want string
|
||||
name string
|
||||
linkErr error
|
||||
}{
|
||||
{name: "forge", task: &store.Task{IssueNumber: 42}, want: "\n\nCloses #42"},
|
||||
{name: "chat", task: &store.Task{IssueNumber: 999_001, Source: store.SourceChat}, want: ""},
|
||||
{name: "already linked", linkErr: errors.New("409 Conflict: branch already linked")},
|
||||
{name: "endpoint unavailable", linkErr: errors.New("404 Not Found")},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := issueClosureReference(tt.task); got != tt.want {
|
||||
t.Errorf("issueClosureReference() = %q, want %q", got, tt.want)
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fakeForge{linkErr: tc.linkErr}
|
||||
taskCtx := &TaskContext{
|
||||
Forge: f,
|
||||
Task: &store.Task{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 42, Title: "Fix bug"},
|
||||
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
|
||||
Branch: "fix/42-bug",
|
||||
}
|
||||
|
||||
if err := OpenPR(context.Background(), taskCtx, "summary"); err != nil {
|
||||
t.Fatalf("OpenPR: %v\nthe PR is the load-bearing step; cosmetic "+
|
||||
"linkage must not stop it", err)
|
||||
}
|
||||
if taskCtx.Outcome.Status != store.StatusPROpen {
|
||||
t.Errorf("Outcome.Status = %q, want %q", taskCtx.Outcome.Status, store.StatusPROpen)
|
||||
}
|
||||
if taskCtx.Task.PRNumber == 0 {
|
||||
t.Error("PRNumber is 0: the pull request was never opened")
|
||||
}
|
||||
// The link is still attempted -- it is useful when it works.
|
||||
if len(f.calls) != 2 || f.calls[0] != "link:fix/42-bug" {
|
||||
t.Errorf("forge calls = %v, want the link attempted before the PR", f.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+16
-13
@@ -69,10 +69,6 @@ func closeNoChangesIssue(ctx context.Context, tc *TaskContext) error {
|
||||
tc.Outcome = Outcome{Status: store.StatusMerged, Detail: "completed -- no changes required"}
|
||||
return nil
|
||||
}
|
||||
body := fmt.Sprintf("**archie closed this issue -- no changes required.**\n\n%s", tc.BuildSummary)
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil {
|
||||
tc.Log.Warn("no-op close comment failed", "err", err)
|
||||
}
|
||||
if err := tc.Forge.CloseIssue(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -182,6 +178,21 @@ func StageYaegiGate() Stage {
|
||||
func OpenPR(ctx context.Context, tc *TaskContext, body string) error {
|
||||
t := tc.Task
|
||||
title := fmt.Sprintf("%s (archie)", t.Title)
|
||||
if t.IsForgeBacked() {
|
||||
// Best-effort. The link is cosmetic -- it puts the branch in the
|
||||
// issue's sidebar on Gitea and does nothing on GitHub -- so failing
|
||||
// the stage on it meant the pull request, the entire point of the
|
||||
// run, was never opened and the task parked. A retry then re-links
|
||||
// the same branch, which Gitea answers with a conflict, so every
|
||||
// retry parked again.
|
||||
if err := tc.Forge.LinkBranch(ctx, t.Owner, t.Repo, t.IssueNumber, tc.Branch); err != nil {
|
||||
if tc.Log != nil {
|
||||
tc.Log.Warn("link branch to issue failed; opening the PR anyway",
|
||||
"repo", t.Owner+"/"+t.Repo, "issue", t.IssueNumber,
|
||||
"branch", tc.Branch, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
num, err := tc.Forge.CreatePR(ctx, t.Owner, t.Repo, title, tc.Branch, tc.Repo.BaseBranch(), body)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -198,13 +209,6 @@ func StageOpenPR(body func(*TaskContext) string) Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
func issueClosureReference(task *store.Task) string {
|
||||
if !task.IsForgeBacked() {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("\n\nCloses #%d", task.IssueNumber)
|
||||
}
|
||||
|
||||
func taskPromptBlock(task *store.Task) string {
|
||||
if task.IsForgeBacked() {
|
||||
return fmt.Sprintf("<issue number=%d>\n# %s\n\n%s\n</issue>",
|
||||
@@ -250,8 +254,7 @@ func Bootstrap() Workflow {
|
||||
}),
|
||||
StageDiffCap(),
|
||||
StageOpenPR(func(tc *TaskContext) string {
|
||||
return "Deterministic bootstrap PR from archie's plumbing walk-through." +
|
||||
issueClosureReference(tc.Task)
|
||||
return "Deterministic bootstrap PR from archie's plumbing walk-through."
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -132,17 +132,10 @@ func TDD() Workflow {
|
||||
// evidence the bug was reproduced before the fix.
|
||||
{Name: "open-pr", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
body := fmt.Sprintf("%s\n\n---\n*workflow: tdd (failing repro committed first) · %d iterations · %d tokens*",
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed) +
|
||||
issueClosureReference(tc.Task)
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
|
||||
if err := OpenPR(ctx, tc, body); err != nil {
|
||||
return err
|
||||
}
|
||||
if tc.ReproProof != "" {
|
||||
proof := fmt.Sprintf("**Proof the repro tests failed before the fix** (commit 1 of this PR):\n\n```\n%s\n```", tc.ReproProof)
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, proof); err != nil {
|
||||
tc.Log.Warn("failed to post repro proof", "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
},
|
||||
|
||||
@@ -23,10 +23,9 @@ import (
|
||||
// forge.Forge (the daemon's real implementations) and forgerpc.Client
|
||||
// (archie-agent's NATS-backed proxy) both satisfy it.
|
||||
type Forger interface {
|
||||
Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error)
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error)
|
||||
SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string)
|
||||
LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error
|
||||
}
|
||||
|
||||
// Trees is the subset of *worktree.Manager that workflow stages call
|
||||
@@ -220,50 +219,16 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
}
|
||||
_ = tc.Store.Update(ctx, t)
|
||||
_ = tc.Store.Transition(ctx, t.ID, store.StatusRunning, tc.Outcome.Status, tc.Outcome.Detail)
|
||||
if t.IsForgeBacked() {
|
||||
tc.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, stateLabelFor(tc.Cfg.Dispatch, tc.Outcome.Status), tc.Cfg.Dispatch.LabelValues())
|
||||
}
|
||||
tc.Emit(events.KindOutcome, t.Stage, tc.Outcome.Detail, map[string]any{"status": tc.Outcome.Status})
|
||||
log.Info("workflow finished", "status", tc.Outcome.Status)
|
||||
}
|
||||
|
||||
// stateLabelFor maps a terminal workflow status to its forge label by
|
||||
// looking up the configured [dispatch.labels]; empty clears (done states
|
||||
//
|
||||
// -- the issue closes or the PR speaks).
|
||||
func stateLabelFor(d config.Dispatch, status string) string {
|
||||
switch status {
|
||||
case store.StatusPROpen:
|
||||
return d.StateLabel("pr")
|
||||
case store.StatusWaitingHuman:
|
||||
return d.StateLabel("waiting")
|
||||
case store.StatusParked:
|
||||
return d.StateLabel("parked")
|
||||
case store.StatusDead:
|
||||
return d.StateLabel("dead")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func park(ctx context.Context, tc *TaskContext, reason string) {
|
||||
t := tc.Task
|
||||
t.ParkReason = reason
|
||||
_ = tc.Store.Update(ctx, t)
|
||||
_ = tc.Store.Transition(ctx, t.ID, store.StatusRunning, store.StatusParked, reason)
|
||||
tc.Emit(events.KindParked, t.Stage, reason, nil)
|
||||
if !t.IsForgeBacked() {
|
||||
// Chat-sourced tasks have no real forge issue to label or
|
||||
// comment on; the park reason is visible via /status and the
|
||||
// task's ParkReason field instead.
|
||||
return
|
||||
}
|
||||
tc.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, tc.Cfg.Dispatch.StateLabel("parked"), tc.Cfg.Dispatch.LabelValues())
|
||||
body := fmt.Sprintf("**archie parked this task.**\n\n```\n%s\n```\n\nThe worktree is kept for inspection.",
|
||||
clip(reason, 3000))
|
||||
if _, err := tc.Forge.Comment(ctx, t.Owner, t.Repo, t.IssueNumber, body); err != nil {
|
||||
tc.Log.Error("failed to post park comment", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func clip(s string, n int) string {
|
||||
|
||||
Reference in new issue
Block a user