420 lines
16 KiB
Go
420 lines
16 KiB
Go
package daemon
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"strings"
|
|
|
|
"github.com/samcharles93/archie-core/internal/config"
|
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
|
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
|
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
|
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
|
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
|
"github.com/samcharles93/archie-core/internal/events"
|
|
"github.com/samcharles93/archie-core/internal/forge"
|
|
"github.com/samcharles93/archie-core/internal/taskstate"
|
|
)
|
|
|
|
// ReactionPublisher delivers one reaction to the reaction stream. The
|
|
// composition root wires it to the task bus's PublishUnique against the
|
|
// reaction subject, so webhook and poll deliveries of the same record dedup
|
|
// on the envelope's source-independent key.
|
|
type ReactionPublisher func(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error
|
|
|
|
// botUserSource names the bot login that owns a task, so the reaction consumer
|
|
// can drop Archie's own comments.
|
|
type botUserSource interface {
|
|
botUserForTask(task *workflowtask.Task) string
|
|
}
|
|
|
|
// writerGate decides which review activity on one PR may reach agents: never
|
|
// the bot's own, and only from users with write access, which the forge is
|
|
// asked once per user for the lifetime of one scan.
|
|
type writerGate struct {
|
|
checker forge.WriteAccessChecker
|
|
log *slog.Logger
|
|
task *workflowtask.Task
|
|
botUser string
|
|
known map[string]bool
|
|
}
|
|
|
|
func (g *writerGate) admit(ctx context.Context, kind string, id int64, author string) (bool, error) {
|
|
if g.botUser != "" && author == g.botUser {
|
|
return false, nil
|
|
}
|
|
ok, seen := g.known[author]
|
|
if !seen {
|
|
var err error
|
|
ok, err = g.checker.HasWriteAccess(ctx, g.task.Owner, g.task.Repo, author)
|
|
if err != nil {
|
|
return false, fmt.Errorf("check write access for %s: %w", author, err)
|
|
}
|
|
g.known[author] = ok
|
|
}
|
|
if !ok {
|
|
g.log.WarnContext(ctx, "dropped forge activity from author without write access",
|
|
"repo", g.task.Owner+"/"+g.task.Repo, "pr", g.task.PRNumber, "kind", kind, "id", id, "author", author)
|
|
}
|
|
return ok, nil
|
|
}
|
|
|
|
// scanPRReviewReactions publishes review activity on one PR since the
|
|
// cursors and returns the advanced cursors. Activity from users without write
|
|
// access is dropped: agents act on what they read, so only collaborators may
|
|
// reach them. On a publish or access-check failure the caller keeps the old
|
|
// cursors.
|
|
func scanPRReviewReactions(
|
|
ctx context.Context,
|
|
log *slog.Logger,
|
|
reader forge.PullRequestReviewReader,
|
|
checker forge.WriteAccessChecker,
|
|
task *workflowtask.Task,
|
|
botUser string,
|
|
reviewCursor, commentCursor int64,
|
|
publish ReactionPublisher,
|
|
) (int64, int64, error) {
|
|
newReviewCursor, newCommentCursor := reviewCursor, commentCursor
|
|
gate := &writerGate{checker: checker, log: log, task: task, botUser: botUser, known: map[string]bool{}}
|
|
|
|
reviews, err := reader.ListReviews(ctx, task.Owner, task.Repo, task.PRNumber, reviewCursor)
|
|
if err != nil {
|
|
return reviewCursor, commentCursor, err
|
|
}
|
|
for _, r := range reviews {
|
|
if r.ID > newReviewCursor {
|
|
newReviewCursor = r.ID
|
|
}
|
|
if ok, err := gate.admit(ctx, "review", r.ID, r.Author); err != nil {
|
|
return reviewCursor, commentCursor, err
|
|
} else if !ok {
|
|
continue
|
|
}
|
|
reaction := workintake.ReviewCommentEnvelope{
|
|
Owner: task.Owner, Repo: task.Repo, PRNumber: task.PRNumber,
|
|
Kind: workintake.ReviewReactionReview,
|
|
ReviewID: r.ID, Author: r.Author, State: r.State, Body: r.Body,
|
|
Org: task.Org,
|
|
}
|
|
if err := publish(ctx, reaction); err != nil {
|
|
return reviewCursor, commentCursor, fmt.Errorf("publish review %d: %w", r.ID, err)
|
|
}
|
|
}
|
|
|
|
comments, err := reader.ListReviewComments(ctx, task.Owner, task.Repo, task.PRNumber, commentCursor)
|
|
if err != nil {
|
|
return reviewCursor, commentCursor, err
|
|
}
|
|
for _, cm := range comments {
|
|
if cm.ID > newCommentCursor {
|
|
newCommentCursor = cm.ID
|
|
}
|
|
if ok, err := gate.admit(ctx, "comment", cm.ID, cm.Author); err != nil {
|
|
return reviewCursor, commentCursor, err
|
|
} else if !ok {
|
|
continue
|
|
}
|
|
reaction := workintake.ReviewCommentEnvelope{
|
|
Owner: task.Owner, Repo: task.Repo, PRNumber: task.PRNumber,
|
|
Kind: workintake.ReviewReactionComment,
|
|
ReviewID: cm.ReviewID,
|
|
CommentID: cm.ID,
|
|
Author: cm.Author, Body: cm.Body, Path: cm.Path, Line: cm.Line,
|
|
Org: task.Org,
|
|
}
|
|
if err := publish(ctx, reaction); err != nil {
|
|
return reviewCursor, commentCursor, fmt.Errorf("publish comment %d: %w", cm.ID, err)
|
|
}
|
|
}
|
|
|
|
return newReviewCursor, newCommentCursor, nil
|
|
}
|
|
|
|
// RepositoryForgeResolver returns the forge client of owner/repo's bound
|
|
// connection in the org ctx carries. It is the daemon's own access, not a
|
|
// task identity's.
|
|
type RepositoryForgeResolver func(ctx context.Context, owner, repo string) (forge.Forge, error)
|
|
|
|
// ReviewScanner runs the pull request maintenance: it reconciles open PRs with
|
|
// forge state, scans their reviews into the reaction stream, and drains that
|
|
// stream into remediate runs.
|
|
type ReviewScanner struct {
|
|
store storecontract.TaskStore
|
|
reactions ReactionSource
|
|
publishTask func(ctx context.Context, subject, idempotencyKey string, payload []byte) error
|
|
bus *events.Bus
|
|
repos repoHub
|
|
orgs orgResolver
|
|
bots botUserSource
|
|
forges RepositoryForgeResolver
|
|
log *slog.Logger
|
|
consumer *reactionConsumer
|
|
publish ReactionPublisher
|
|
}
|
|
|
|
// NewReviewScanner wires the scanner to its dependencies. The reaction consumer
|
|
// and publisher are built here, so the consumer's drop counter spans the
|
|
// process lifetime.
|
|
func NewReviewScanner(
|
|
store storecontract.TaskStore,
|
|
reactions ReactionSource,
|
|
publishTask func(ctx context.Context, subject, idempotencyKey string, payload []byte) error,
|
|
bus *events.Bus,
|
|
repos repoHub,
|
|
orgs orgResolver,
|
|
bots botUserSource,
|
|
forges RepositoryForgeResolver,
|
|
log *slog.Logger,
|
|
) *ReviewScanner {
|
|
s := &ReviewScanner{
|
|
store: store, reactions: reactions, publishTask: publishTask, bus: bus,
|
|
repos: repos, orgs: orgs, bots: bots, forges: forges, log: log,
|
|
}
|
|
s.consumer = newReactionConsumer(store, store, store, bots.botUserForTask, log)
|
|
s.publish = s.PublishReaction
|
|
return s
|
|
}
|
|
|
|
// scanPRReviews scans every open PR task for review activity through its
|
|
// repository forge. Forges without review reading are skipped.
|
|
func (s *ReviewScanner) scanPRReviews(ctx context.Context) error {
|
|
tasks, err := s.store.OpenPRs(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("review scan query: %w", err)
|
|
}
|
|
var failed []string
|
|
for i := range tasks {
|
|
t := &tasks[i]
|
|
fg, ok := s.openPRForge(ctx, t, "review scan skipped: no forge for task")
|
|
if !ok {
|
|
continue
|
|
}
|
|
reader, ok := fg.(forge.PullRequestReviewReader)
|
|
if !ok {
|
|
continue // the noop forge and any forge without the capability
|
|
}
|
|
checker, ok := fg.(forge.WriteAccessChecker)
|
|
if !ok {
|
|
s.log.WarnContext(ctx, "review scan skipped: forge cannot verify write access", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
|
continue
|
|
}
|
|
if !s.scanOnePR(ctx, reader, checker, t) {
|
|
failed = append(failed, fmt.Sprintf("%s/%s#%d", t.Owner, t.Repo, t.PRNumber))
|
|
}
|
|
}
|
|
return passFailed("review scan", failed)
|
|
}
|
|
|
|
// scanOnePR reports false when the scan failed; the cause is logged here.
|
|
func (s *ReviewScanner) scanOnePR(ctx context.Context, reader forge.PullRequestReviewReader, checker forge.WriteAccessChecker, t *workflowtask.Task) bool {
|
|
// Resolve the org; on failure skip this task for now.
|
|
if t.Org == "" {
|
|
resolved, err := s.orgs.identityOrg(ctx, identity.IdentityID(t.Identity))
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "review scan org resolve failed", "task", t.ID, "err", err)
|
|
return false
|
|
}
|
|
t.Org = resolved
|
|
}
|
|
// A forge read failure skips the task for this scan with its cursors
|
|
// unchanged: the next scan re-fetches, and PublishUnique's dedup covers
|
|
// anything the previous scan already published.
|
|
reviewCursor, commentCursor, err := scanPRReviewReactions(
|
|
ctx, s.log, reader, checker, t, s.bots.botUserForTask(t),
|
|
t.ReviewCursor, t.WatchCommentID, s.publish)
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "review scan failed", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber, "err", err)
|
|
return false
|
|
}
|
|
if reviewCursor == t.ReviewCursor && commentCursor == t.WatchCommentID {
|
|
return true
|
|
}
|
|
if err := s.store.SetReviewCursors(ctx, t.ID, reviewCursor, commentCursor); err != nil {
|
|
// A stale guard here means the task was claimed between the scan and
|
|
// the write; the next scan re-reads and re-lists from the old cursor,
|
|
// and PublishUnique plus the consumer's dedup absorb the repeats.
|
|
s.log.WarnContext(ctx, "review cursor persist failed", "task", t.ID, "err", err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// drainReactions turns available review reactions into queued remediate
|
|
// runs. It runs before the task drain so a reaction queued in this pass can
|
|
// be claimed by it.
|
|
func (s *ReviewScanner) drainReactions(ctx context.Context) {
|
|
if _, err := s.consumer.drain(ctx, s.reactions, maxReactionsPerCycle); err != nil {
|
|
s.log.ErrorContext(ctx, "reaction drain failed", "err", err)
|
|
}
|
|
}
|
|
|
|
// PublishReaction stamps the org on a review reaction, defaulting to the
|
|
// root identity's, and publishes it.
|
|
func (s *ReviewScanner) PublishReaction(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error {
|
|
if reaction.Org == "" {
|
|
resolved, err := s.orgs.identityOrg(ctx, identity.SystemID)
|
|
if err != nil {
|
|
return fmt.Errorf("publish reaction %s: resolve org: %w", reaction.Ref(), err)
|
|
}
|
|
reaction.Org = resolved
|
|
}
|
|
payload, err := reaction.Encode()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.publishTask(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
|
|
}
|
|
|
|
// reconcilePRs moves pr_open tasks to merged/rejected from GitHub state
|
|
// and cleans up their worktrees.
|
|
func (s *ReviewScanner) reconcilePRs(ctx context.Context) error {
|
|
tasks, err := s.store.OpenPRs(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("reconcile query: %w", err)
|
|
}
|
|
var failed []string
|
|
for _, t := range tasks {
|
|
fg, ok := s.openPRForge(ctx, &t, "PR state check skipped: no forge for task")
|
|
if !ok {
|
|
continue
|
|
}
|
|
trees := s.repos.treesFor(&t)
|
|
// PRState/PR reconciliation is valid regardless of Source -- a
|
|
// chat-sourced task can still open a real PR against a real
|
|
// branch. Only the issue-label call (tied to the synthetic
|
|
// issue number) is forge-only.
|
|
state, err := fg.PRState(ctx, t.Owner, t.Repo, t.PRNumber)
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "PR state check failed", "pr", t.PRNumber, "err", err)
|
|
failed = append(failed, fmt.Sprintf("%s/%s#%d", t.Owner, t.Repo, t.PRNumber))
|
|
continue
|
|
}
|
|
attempt := t.Attempt
|
|
switch state {
|
|
case forge.PRStateMerged:
|
|
if err := s.store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusMerged, ""); err != nil {
|
|
s.log.ErrorContext(ctx, "PR merged but task transition failed", "task", t.ID, "pr", t.PRNumber, "err", err)
|
|
failed = append(failed, fmt.Sprintf("%s/%s#%d", t.Owner, t.Repo, t.PRNumber))
|
|
continue
|
|
}
|
|
if err := trees.Cleanup(t.Owner, t.Repo, t.IssueNumber); err != nil {
|
|
s.log.WarnContext(ctx, "worktree cleanup failed", "task", t.ID, "err", err)
|
|
}
|
|
// Close the issue explicitly; nothing else does.
|
|
s.closeResolvedIssue(ctx, &t, fmt.Sprintf(
|
|
"Closed by #%d, merged by archie.", t.PRNumber,
|
|
))
|
|
s.log.InfoContext(ctx, "PR merged", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
|
s.bus.Publish(ctx, events.Event{
|
|
Kind: events.KindPRMerged, TaskID: t.ID, Attempt: attempt,
|
|
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber,
|
|
Data: map[string]any{"pr": t.PRNumber},
|
|
})
|
|
case "closed":
|
|
if err := s.store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusRejected, "PR closed without merge"); err != nil {
|
|
s.log.ErrorContext(ctx, "PR rejected but task transition failed", "task", t.ID, "pr", t.PRNumber, "err", err)
|
|
failed = append(failed, fmt.Sprintf("%s/%s#%d", t.Owner, t.Repo, t.PRNumber))
|
|
continue
|
|
}
|
|
if err := trees.Cleanup(t.Owner, t.Repo, t.IssueNumber); err != nil {
|
|
s.log.WarnContext(ctx, "worktree cleanup failed", "task", t.ID, "err", err)
|
|
}
|
|
s.log.InfoContext(ctx, "PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
|
s.bus.Publish(ctx, events.Event{
|
|
Kind: events.KindPRRejected, TaskID: t.ID, Attempt: attempt,
|
|
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber,
|
|
Data: map[string]any{"pr": t.PRNumber},
|
|
})
|
|
}
|
|
}
|
|
return passFailed("PR reconcile", failed)
|
|
}
|
|
|
|
// reconcileForge is the forge for reading PR state and closing the issue. That
|
|
// is the daemon's own reconciliation, so it uses the repository's connection in
|
|
// the task's org rather than the task's execution identity, which may be an
|
|
// operator. A task without a repository keeps the identity-owned forge.
|
|
func (s *ReviewScanner) reconcileForge(ctx context.Context, task *workflow.Task) (forge.Forge, error) {
|
|
if !task.HasRepository() {
|
|
fg := s.repos.forgeFor(ctx, task)
|
|
if _, unavailable := fg.(*forge.NoopForge); unavailable {
|
|
return nil, errors.New("no forge for task")
|
|
}
|
|
return fg, nil
|
|
}
|
|
if s.forges == nil {
|
|
resolved, err := s.repos.Repository(ctx, task, config.OperationClone)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return resolved.Forge, nil
|
|
}
|
|
return s.forges(org.WithOrg(ctx, org.OrgID(task.OrgOrDefault())), task.Owner, task.Repo)
|
|
}
|
|
|
|
// permanentForgeFailure reports whether err from reconcileForge is permanent
|
|
// and names the park blocker if one applies.
|
|
func permanentForgeFailure(err error) (taskstate.Blocker, bool) {
|
|
if blocker := parkBlocker(err); blocker != "" {
|
|
return blocker, true
|
|
}
|
|
if failure, ok := errors.AsType[pinFailure](err); ok {
|
|
return "", failure.class != taskstate.ParkTransient
|
|
}
|
|
if failure, ok := errors.AsType[*pinFailure](err); ok && failure != nil {
|
|
return "", failure.class != taskstate.ParkTransient
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// openPRForge resolves the forge for an open PR task. Transient errors warn
|
|
// and skip; permanent errors park the task out of pr_open so it stops retrying
|
|
// on subsequent ticks.
|
|
func (s *ReviewScanner) openPRForge(ctx context.Context, t *workflow.Task, skipMsg string) (forge.Forge, bool) {
|
|
fg, err := s.reconcileForge(ctx, t)
|
|
if err == nil {
|
|
return fg, true
|
|
}
|
|
blocker, permanent := permanentForgeFailure(err)
|
|
if !permanent {
|
|
s.log.WarnContext(ctx, skipMsg, "task", t.ID, "pr", t.PRNumber, "err", err)
|
|
return nil, false
|
|
}
|
|
reason := err.Error()
|
|
if err := s.store.ParkTask(ctx, t.ID, workflow.StatusPROpen, reason, taskstate.ParkNeedsDecision, blocker); err != nil {
|
|
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
|
s.log.WarnContext(ctx, "park pr_open task failed", "task", t.ID, "pr", t.PRNumber, "reason", reason, "err", err)
|
|
}
|
|
return nil, false
|
|
}
|
|
s.log.WarnContext(ctx, "pr_open task parked: forge resolution failed", "task", t.ID, "pr", t.PRNumber, "blocker", blocker, "err", err)
|
|
if s.bus != nil {
|
|
s.bus.Publish(ctx, events.Event{
|
|
Kind: events.KindParked, TaskID: t.ID, Attempt: t.Attempt,
|
|
Repo: strings.Trim(t.Owner+"/"+t.Repo, "/"), Issue: t.IssueNumber, Workflow: t.Workflow,
|
|
Detail: reason, Data: map[string]any{"park_class": taskstate.ParkNeedsDecision},
|
|
})
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
// closeResolvedIssue closes a finished task's forge issue, skipping chat
|
|
// tasks. Failures are logged.
|
|
func (s *ReviewScanner) closeResolvedIssue(ctx context.Context, task *workflow.Task, comment string) {
|
|
if !task.IsForgeBacked() {
|
|
return
|
|
}
|
|
fg, err := s.reconcileForge(ctx, task)
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "issue closure skipped: no forge for task", "task", task.ID, "err", err)
|
|
return
|
|
}
|
|
if err := fg.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
|
|
s.log.WarnContext(ctx, "closing resolved issue failed; it stays open and will be re-polled",
|
|
"repo", task.Owner+"/"+task.Repo, "issue", task.IssueNumber, "err", err)
|
|
}
|
|
}
|