diff --git a/config.example.toml b/config.example.toml index 443e5625a..1546ff086 100644 --- a/config.example.toml +++ b/config.example.toml @@ -23,6 +23,9 @@ class = "ollama" [web] # observability dashboard (read-only, no auth — keep it local/tailnet) listen = "127.0.0.1:8484" # "off" disables +[notify] # optional webhook for human-in-the-loop moments (n8n -> email) +# webhook = "https://n8n.catlow.cloud/webhook/archie" + [budgets] max_steps = 60 max_tokens = 400000 diff --git a/internal/config/config.go b/internal/config/config.go index 49cb09ea1..e1309f862 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -83,9 +83,17 @@ type Config struct { Budgets Budgets `toml:"budgets"` Web Web `toml:"web"` + Notify Notify `toml:"notify"` Repos []Repo `toml:"repos"` } +// Notify configures outbound notifications (n8n webhook → email etc.). +type Notify struct { + // Webhook receives JSON POSTs for events that need a human (e.g. + // feasibility PRDs awaiting go/no-go). Empty disables. + Webhook string `toml:"webhook"` +} + // Web configures the observability dashboard. type Web struct { // Listen is the dashboard address; empty disables the web UI. diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 52fd38622..e333b9232 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -6,11 +6,13 @@ package daemon import ( "context" + "fmt" "log/slog" "strings" "time" "github.com/google/go-github/v78/github" + "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" "github.com/samcharles93/archie-core/internal/config" @@ -73,11 +75,13 @@ func (d *Daemon) Run(ctx context.Context) error { } } -// Cycle is one poll-and-drain pass: enqueue new labelled issues, -// reconcile open PRs, then process every queued task sequentially. +// Cycle is one poll-and-drain pass: enqueue newly assigned issues, +// reconcile open PRs, act on human replies to waiting tasks, then +// process every queued task sequentially. func (d *Daemon) Cycle(ctx context.Context) { d.poll(ctx) d.reconcilePRs(ctx) + d.checkWaiting(ctx) for { if ctx.Err() != nil { return @@ -156,6 +160,104 @@ 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 { + replies, err := d.Forge.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 + } + _, _ = d.Forge.Comment(ctx, t.Owner, t.Repo, t.IssueNumber, + "**Go-ahead received — implementation is queued.** ("+reason+")") + 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) + _ = d.Forge.CloseIssue(ctx, t.Owner, t.Repo, t.IssueNumber, + "**Understood — closing without implementation.** ("+reason+")") + 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) { repo, ok := d.repoFor(task) if !ok { diff --git a/internal/forge/github.go b/internal/forge/github.go index ee39f3397..a91a944f4 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -66,11 +66,40 @@ func (c *Client) AssignedIssues(ctx context.Context, owner, repo, assignee strin return out, nil } -// Comment posts an issue (or PR) comment. -func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) error { - _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, +// Comment posts an issue (or PR) comment and returns its id, so a +// workflow can watch for replies that come after it. +func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) { + cm, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &github.IssueComment{Body: github.Ptr(body)}) - return err + if err != nil { + return 0, err + } + return cm.GetID(), nil +} + +// Reply is a human comment on a watched issue. +type Reply struct { + ID int64 + User string + Body string +} + +// RepliesAfter returns comments on the issue with id > afterID that were +// not written by exclude (the bot) — the human side of waiting_human. +func (c *Client) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]Reply, error) { + comments, _, err := c.gh.Issues.ListComments(ctx, owner, repo, number, + &github.IssueListCommentsOptions{ListOptions: github.ListOptions{PerPage: 50}}) + if err != nil { + return nil, err + } + var out []Reply + for _, cm := range comments { + if cm.GetID() <= afterID || cm.GetUser().GetLogin() == exclude { + continue + } + out = append(out, Reply{ID: cm.GetID(), User: cm.GetUser().GetLogin(), Body: cm.GetBody()}) + } + return out, nil } // CreatePR opens a pull request and returns its number. @@ -102,7 +131,7 @@ func (c *Client) PRState(ctx context.Context, owner, repo string, number int) (s // CloseIssue closes an issue with a final comment (feasibility "won't do"). func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { if comment != "" { - if err := c.Comment(ctx, owner, repo, number, comment); err != nil { + if _, err := c.Comment(ctx, owner, repo, number, comment); err != nil { return err } } diff --git a/internal/store/store.go b/internal/store/store.go index cc849e38b..1ef7bd33e 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -9,6 +9,7 @@ import ( "fmt" "os" "path/filepath" + "strings" _ "modernc.org/sqlite" ) @@ -45,6 +46,9 @@ type Task struct { Iterations int Attempt int ParkReason string + // WatchCommentID: replies to the issue after this comment are the + // human input a waiting_human task is blocked on. + WatchCommentID int64 } type Store struct{ db *sql.DB } @@ -62,6 +66,12 @@ func Open(path string) (*Store, error) { db.Close() return nil, fmt.Errorf("store: init schema: %w", err) } + // Additive migrations; "duplicate column" means already applied. + if _, err := db.Exec(`ALTER TABLE tasks ADD COLUMN watch_comment_id INTEGER NOT NULL DEFAULT 0`); err != nil && + !strings.Contains(err.Error(), "duplicate column") { + db.Close() + return nil, fmt.Errorf("store: migrate: %w", err) + } return &Store{db: db}, nil } @@ -160,10 +170,47 @@ func (s *Store) Update(ctx context.Context, t *Task) error { _, err := s.db.ExecContext(ctx, ` UPDATE tasks SET workflow=?, stage=?, branch=?, plan=?, notes=?, pr_number=?, tokens_used=?, iterations=?, park_reason=?, - updated_at=datetime('now') + watch_comment_id=?, updated_at=datetime('now') WHERE id=?`, t.Workflow, t.Stage, t.Branch, t.Plan, t.Notes, - t.PRNumber, t.TokensUsed, t.Iterations, clip(t.ParkReason, 4000), t.ID) + t.PRNumber, t.TokensUsed, t.Iterations, clip(t.ParkReason, 4000), + t.WatchCommentID, t.ID) + return err +} + +// WaitingTasks returns tasks blocked on human input. +func (s *Store) WaitingTasks(ctx context.Context) ([]Task, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT id, owner, repo, issue_number, title, body, plan, workflow, + watch_comment_id, status + FROM tasks WHERE status='waiting_human'`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Task + 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); err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} + +// Requeue puts a task back on the queue under a specific workflow — +// the waiting_human → approved → implement handoff. +func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE tasks SET status='queued', workflow=?, stage='', updated_at=datetime('now') + WHERE id=?`, workflow, taskID); err != nil { + return err + } + _, err := s.db.ExecContext(ctx, + `INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, 'queued', ?)`, + taskID, fromStatus, "requeued as "+workflow) return err } diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index ea34842bc..a32d8cc0a 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/archie-core/internal/config" ) @@ -34,6 +35,9 @@ type AgentStage struct { // an environmental constraint, not a prompt rule (TDD's fix stage // protects the committed repro tests). ProtectPaths func(path string) bool + // Extra adds stage-specific tools to the agent's toolset (e.g. + // feasibility's decide tool). + Extra func(*TaskContext) core.ToolSet // OnResult consumes a successful (passed) result. Parked and idle // results park the workflow before OnResult is called. OnResult func(*TaskContext, agentloop.Result) error @@ -66,6 +70,10 @@ func (a AgentStage) Stage() Stage { if a.Gate != nil { gate = a.Gate(tc) } + var extra core.ToolSet + if a.Extra != nil { + extra = a.Extra(tc) + } res, err := agentloop.Run(ctx, agentloop.Config{ Runtime: tc.Runtime, @@ -81,6 +89,7 @@ func (a AgentStage) Stage() Stage { Budget: budget, ReadOnly: a.ReadOnly, ProtectPaths: a.ProtectPaths, + Extra: extra, Logger: tc.Log.With("stage", a.Name, "model", modelRef), }) if err != nil { diff --git a/internal/workflow/feasibility.go b/internal/workflow/feasibility.go new file mode 100644 index 000000000..067a2ada1 --- /dev/null +++ b/internal/workflow/feasibility.go @@ -0,0 +1,168 @@ +package workflow + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "time" + + "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/ai-sdk/core" + + "github.com/samcharles93/archie-core/internal/store" +) + +// Feasibility is the feature-request workflow: assess the request +// against the project's direction, close it with reasons when it +// doesn't fit, otherwise produce a PRD, deliver it to Sam (issue +// comment + notify webhook), and hand the task to waiting_human. The +// daemon watches for Sam's reply and — LLM-judged, not keyword-matched — +// requeues approved features under the implement workflow or closes +// rejected ones. Routed via the "feature" label. +func Feasibility() Workflow { + return Workflow{ + Name: "feasibility", + Stages: []Stage{ + StagePrepareWorktree(), // read-only stages still need the checkout + + AgentStage{ + Name: "assess", + Role: "planner", + ReadOnly: true, + MaxSteps: 15, + Extra: decideToolSet, + Mission: func(tc *TaskContext) string { + return fmt.Sprintf( + "Assess whether this feature request fits the project %s.\n\n"+ + "\n# %s\n\n%s\n\n\n"+ + "Read the repository's AGENT.md, ROADMAP.md, and README (whichever exist) plus "+ + "enough code to judge scope and architectural fit. Then call the decide tool "+ + "EXACTLY ONCE with fit=true or fit=false and your reasons, and afterwards call "+ + "finish with status \"passed\" summarising the assessment.", + tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, + ) + }, + OnResult: func(tc *TaskContext, res agentloop.Result) error { + if tc.decision == nil { + return fmt.Errorf("assess stage finished without calling the decide tool") + } + if !tc.decision.Fit { + 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 { + return err + } + tc.Outcome = Outcome{Status: store.StatusClosedWontDo, Detail: tc.decision.Reasons} + } + return nil + }, + }.Stage(), + + AgentStage{ + Name: "prd", + Role: "planner", + ReadOnly: true, + MaxSteps: 20, + Mission: func(tc *TaskContext) string { + return fmt.Sprintf( + "Write a PRD for this accepted feature request on %s.\n\n"+ + "\n# %s\n\n%s\n\n\n\n%s\n\n\n"+ + "Explore the affected code surface, then call finish with status \"passed\" and the "+ + "PRD as the summary: problem, proposed solution, files/components affected, "+ + "acceptance criteria, explicit non-goals, and estimated diff size. It will be read "+ + "by a human deciding whether to green-light implementation.", + tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.decision.Reasons, + ) + }, + OnResult: func(tc *TaskContext, res agentloop.Result) error { + tc.Task.Plan = res.Summary + return nil + }, + }.Stage(), + + // Deliver the PRD and block on Sam: issue comment (the reply + // channel the daemon watches) plus the notify webhook (n8n → + // email). + {Name: "deliver", Run: func(ctx context.Context, tc *TaskContext) error { + 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 + }}, + }, + } +} + +// decision is the assess stage's structured verdict. +type decision struct { + Fit bool + Reasons string +} + +// decideToolSet gives the assess agent a decide tool that records its +// verdict on the TaskContext — structured output as a tool call, not +// parsed out of prose. +func decideToolSet(tc *TaskContext) core.ToolSet { + params := json.RawMessage(`{ + "type": "object", + "properties": { + "fit": {"type": "boolean", "description": "true: fits the project and is worth a PRD. false: close as won't-do."}, + "reasons": {"type": "string", "description": "The rationale, written for the human who filed the request."} + }, + "required": ["fit", "reasons"] + }`) + return core.ToolSet{ + "decide": core.NewTool("decide", + "Record the feasibility verdict. Call exactly once, before finish.", + params, + func(ctx context.Context, input string) (string, error) { + var args struct { + Fit bool `json:"fit"` + Reasons string `json:"reasons"` + } + if err := json.Unmarshal([]byte(input), &args); err != nil { + return "decide rejected: invalid arguments: " + err.Error(), nil + } + if args.Reasons == "" { + return "decide rejected: reasons are required", nil + } + tc.decision = &decision{Fit: args.Fit, Reasons: args.Reasons} + return fmt.Sprintf("verdict recorded: fit=%v", args.Fit), nil + }), + } +} + +// notify POSTs a JSON payload to the configured webhook (n8n turns it +// into an email). Best-effort: failures log, the issue comment is the +// authoritative channel. +func notify(ctx context.Context, tc *TaskContext, kind string) { + url := tc.Cfg.Notify.Webhook + if url == "" { + return + } + payload, _ := json.Marshal(map[string]any{ + "type": kind, "repo": tc.Repo.FullName(), "issue": tc.Task.IssueNumber, + "title": tc.Task.Title, "prd": tc.Task.Plan, + "issue_url": fmt.Sprintf("https://github.com/%s/issues/%d", tc.Repo.FullName(), tc.Task.IssueNumber), + }) + reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, url, bytes.NewReader(payload)) + if err != nil { + tc.Log.Warn("notify webhook request build failed", "err", err) + return + } + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + tc.Log.Warn("notify webhook failed", "err", err) + return + } + resp.Body.Close() +} diff --git a/internal/workflow/implement.go b/internal/workflow/implement.go index 50ce94fc9..aad81bdf0 100644 --- a/internal/workflow/implement.go +++ b/internal/workflow/implement.go @@ -45,8 +45,14 @@ func Implement() Workflow { ReadOnly: true, MaxSteps: 15, Mission: func(tc *TaskContext) string { + prd := "" + if tc.Task.Plan != "" { + // An approved feasibility PRD precedes this run; + // the plan refines it rather than starting cold. + prd = "\n\n" + tc.Task.Plan + "\n\n" + } return fmt.Sprintf( - "Produce a concrete implementation plan for this GitHub issue on the repository %s.\n\n"+ + "Produce a concrete implementation plan for this GitHub issue on the repository %s.\n"+prd+"\n"+ "\n# %s\n\n%s\n\n\n"+ "Explore the codebase with your read-only tools, then call finish with status "+ "\"passed\" and the plan as the summary: files to touch, the approach, acceptance "+ @@ -58,7 +64,7 @@ func Implement() Workflow { OnResult: func(tc *TaskContext, res agentloop.Result) error { tc.Task.Plan = res.Summary 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 { + 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 diff --git a/internal/workflow/tdd.go b/internal/workflow/tdd.go index 3575f4dcd..de11b3e82 100644 --- a/internal/workflow/tdd.go +++ b/internal/workflow/tdd.go @@ -131,7 +131,7 @@ func TDD() Workflow { } 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 { + 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) } } diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 7b0e9d83d..afc96bf88 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -43,6 +43,8 @@ type TaskContext struct { // ReproProof is the captured failing-test output from a TDD repro // stage, posted on the PR as evidence the bug was reproduced. ReproProof string + // decision is the feasibility assess stage's verdict. + decision *decision // Outcome describes where the task ended up; the engine applies it. Outcome Outcome } @@ -88,10 +90,15 @@ type Workflow struct { // Registry maps workflow names to definitions. type Registry map[string]Workflow -// Route picks the workflow for a task. Label-driven first; an LLM -// triage stage inside a workflow can still re-route by returning an -// Outcome that re-enqueues under a different workflow (later phase). +// Route picks the workflow for a task. A pre-assigned workflow wins +// (the waiting_human → approved handoff requeues under "implement"); +// otherwise labels decide, then the default. func Route(t *store.Task, reg Registry) Workflow { + if t.Workflow != "" { + if wf, ok := reg[t.Workflow]; ok { + return wf + } + } labels := strings.Split(t.Labels, ",") for _, l := range labels { switch strings.TrimSpace(l) { @@ -177,7 +184,7 @@ func park(ctx context.Context, tc *TaskContext, reason string) { tc.Emit(events.KindParked, t.Stage, reason, nil) 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 { + 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) } }