Files
archie/internal/domain/workflow/remediate.go
T
sam e0b6aa6105 feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00

313 lines
12 KiB
Go

package workflow
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/agentexec"
)
// ErrNoReviewPayload is returned when a remediate run starts on a task that
// carries no review unit to address. The daemon reaction consumer is the
// only producer of Task.ReviewPayload; a remediate task without one is a
// dispatch bug upstream, not a recoverable condition here.
var ErrNoReviewPayload = errors.New("remediate: task carries no review payload")
// ReviewUnitComment is one actionable review comment the builder must
// address, carried inside a ReviewUnit.
type ReviewUnitComment struct {
CommentID int64 `json:"comment_id"`
Path string `json:"path,omitempty"`
Line int `json:"line,omitempty"`
Body string `json:"body"`
}
// ReviewUnit is the remediate workflow's input contract: one review (or one
// standalone comment with no parent review) and every actionable comment
// grouped under it, per docs/prds/pr-review-remediation.md decision 5 ("a
// review is the unit of remediation, never an individual comment"). The
// daemon's reaction consumer builds and JSON-encodes this into
// Task.ReviewPayload before dispatch; this package only decodes and acts
// on it.
type ReviewUnit struct {
ReviewID int64 `json:"review_id,omitempty"`
Author string `json:"author,omitempty"`
State string `json:"state,omitempty"`
// Body is the review's own top-level summary (e.g. a "requested_changes"
// review's message), separate from any inline comment bodies.
Body string `json:"body,omitempty"`
Comments []ReviewUnitComment `json:"comments,omitempty"`
}
// DecodeReviewUnit parses a task's ReviewPayload. An empty payload is
// ErrNoReviewPayload, not a zero-value unit: a remediate task with nothing
// to address should never have been dispatched.
func DecodeReviewUnit(payload string) (ReviewUnit, error) {
if payload == "" {
return ReviewUnit{}, ErrNoReviewPayload
}
var u ReviewUnit
if err := json.Unmarshal([]byte(payload), &u); err != nil {
return ReviewUnit{}, fmt.Errorf("decode review payload: %w", err)
}
return u, nil
}
// EncodeReviewUnit renders a review unit for storage in Task.ReviewPayload.
func EncodeReviewUnit(u ReviewUnit) (string, error) {
data, err := json.Marshal(u)
if err != nil {
return "", fmt.Errorf("encode review payload: %w", err)
}
return string(data), nil
}
// replyTarget is the one comment ID a remediation run's reply threads onto,
// and whether one exists at all. A standalone review with no inline
// comments (a plain "requested changes" message) has nothing to thread a
// reply onto, so the reply falls back to a plain PR comment.
func (u ReviewUnit) replyTarget() (int64, bool) {
for _, c := range u.Comments {
if c.CommentID > 0 {
return c.CommentID, true
}
}
return 0, false
}
// renderReviewUnitMission formats a review unit as the builder's mission
// input: the review's own message, if any, followed by every actionable
// comment with its location.
func renderReviewUnitMission(u ReviewUnit) string {
var b strings.Builder
if u.Body != "" {
fmt.Fprintf(&b, "Review summary (%s): %s\n\n", orUnknown(u.State), u.Body)
}
if len(u.Comments) == 0 {
b.WriteString("No inline comments were attached; address the review summary above.")
return b.String()
}
b.WriteString("Comments:\n")
for _, c := range u.Comments {
loc := "(general)"
if c.Path != "" {
loc = c.Path
if c.Line > 0 {
loc = fmt.Sprintf("%s:%d", c.Path, c.Line)
}
}
fmt.Fprintf(&b, "- %s: %s\n", loc, c.Body)
}
return b.String()
}
func orUnknown(s string) string {
if s == "" {
return "unspecified"
}
return s
}
// remediationRoundCapBytes bounds the round-cap park detail, matching the
// other clipped park reasons in this package.
const remediationRoundCapBytes = 2000
// resumableTrees is the optional capability a Trees implementation offers
// for continuing work on an already-open PR branch instead of starting a
// fresh worktree. Deliberately NOT part of the exported Trees interface,
// for two reasons: Trees is projected into the Yaegi symbol table
// (wfextract) for repository-authored .archie/stages/*.go, and this
// capability must not become callable from there (mirrors changeStatsReader
// in steps.go); and Trees is already at golangci-lint's interfacebloat cap
// of 8 methods, which CLAUDE.md reserves for proto/gRPC surfaces, not
// growing Go interfaces further.
//
// *worktree.Manager (real git access) and the container-mode hybrid
// implementation both already satisfy this structurally; a Trees
// implementation that doesn't (a narrower test fake, say) simply cannot run
// the remediate workflow, which StageResumeWorktree reports plainly.
type resumableTrees interface {
Dir(owner, repo string, issue int) string
Resume(ctx context.Context, dir, branch string) error
}
// StageResumeWorktree re-syncs the task's already-prepared worktree onto
// its PR branch's remote tip, so the remediate workflow continues on the
// branch the implement run pushed instead of resetting to base the way
// StagePrepareWorktree's refresh would (docs/prds/pr-review-remediation.md
// decision 4). A remediate task always has a branch: it only ever runs
// against a PR archie itself opened.
func StageResumeWorktree() Stage {
return Stage{Name: "resume", Run: func(ctx context.Context, tc *TaskContext) error {
if tc.Task.Branch == "" {
return fmt.Errorf("remediate: task has no branch to resume")
}
rt, ok := tc.Trees.(resumableTrees)
if !ok {
return fmt.Errorf("remediate: this worktree implementation cannot resume a PR branch")
}
dir := rt.Dir(tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber)
if err := rt.Resume(ctx, dir, tc.Task.Branch); err != nil {
return fmt.Errorf("resume worktree onto %s: %w", tc.Task.Branch, err)
}
tc.Dir, tc.Branch = dir, tc.Task.Branch
return nil
}}
}
// StageRemediationRoundCap enforces the hard stop on an unbounded
// remediate/re-review exchange (decision 5, "bounding the exchange").
// Task.RetryCount doubles as the remediation round counter here: on the
// cap it parks the task and posts one comment explaining why, without
// running the builder; under the cap it counts this round and proceeds.
func StageRemediationRoundCap() Stage {
return Stage{Name: "round-cap", Run: func(ctx context.Context, tc *TaskContext) error {
maxRounds := tc.Repo.EffectiveMaxRetries(tc.Cfg.MaxRetries)
if maxRounds > 0 && tc.Task.RetryCount >= maxRounds {
detail := fmt.Sprintf("remediation round cap reached (%d/%d); stopping and parking for an operator", tc.Task.RetryCount, maxRounds)
postRemediationComment(ctx, tc, "Archie has stopped remediating this review: "+detail+".")
tc.Outcome = Outcome{Status: StatusParked, Detail: clip(detail, remediationRoundCapBytes)}
return nil
}
tc.Task.RetryCount++
return nil
}}
}
// postRemediationComment posts a plain PR comment, best-effort: a park or a
// reply failure on the messaging side must never mask the round-cap
// decision or the remediation outcome that already happened.
func postRemediationComment(ctx context.Context, tc *TaskContext, body string) {
if tc.Task.PRNumber <= 0 {
return
}
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, body); err != nil {
tc.Log.Warn("remediation comment not posted", "pr", tc.Task.PRNumber, "err", err)
}
}
// remediateMission builds the builder agent's mission from the task's
// decoded review unit, stashing it on tc.reviewUnit so later stages
// (commit-push, reply) don't re-decode the payload. StageCheckReviewPayload
// already guarantees the payload decodes before this stage runs.
func remediateMission(tc *TaskContext) string {
unit, _ := DecodeReviewUnit(tc.Task.ReviewPayload)
tc.reviewUnit = unit
return fmt.Sprintf(
"Address the review comments below on pull request #%d for %s with the smallest change that "+
"satisfies them, then run the gate.\n\n%s\n\n"+
"Do not run git -- the orchestrator commits and pushes for you. When done, call finish with "+
"status \"passed\" and a summary written for the human who will read your reply: what changed and "+
"why. If nothing here actually requires a code change, call finish with status \"passed\" and say "+
"so in the summary.",
tc.Task.PRNumber, tc.Repo.FullName(), renderReviewUnitMission(unit),
)
}
// remediateBuildStage runs the builder agent against the task's review
// unit. StageCheckReviewPayload runs first, so a decode failure parks the
// run before the builder ever sees an empty mission.
func remediateBuildStage() Stage {
return AgentStage{
Name: "remediate-build",
Role: "builder",
Gate: func(tc *TaskContext) agentexec.Gate {
return GateFromRepo(tc.Repo, tc.Cfg.Budgets)
},
Mission: remediateMission,
OnResult: func(tc *TaskContext, res agentexec.Result) error {
tc.BuildSummary = res.Summary
if res.Status == agentexec.StatusPassed && len(res.Changes) == 0 {
tc.BuildNoChanges = true
}
return nil
},
}.Stage()
}
// StageCheckReviewPayload fails the run before any worktree or agent work
// starts if the task's review payload cannot be decoded -- a dispatch bug
// upstream, not something a builder run can recover from.
func StageCheckReviewPayload() Stage {
return Stage{Name: "check-review-payload", Run: func(ctx context.Context, tc *TaskContext) error {
_, err := DecodeReviewUnit(tc.Task.ReviewPayload)
return err
}}
}
// StageRemediationCommitPush commits and pushes the remediation to the
// existing PR branch. Unlike StageCommitPush, no changes is a normal
// outcome, not an empty-tree error: a review can be satisfied by
// explanation alone, and there is no issue to close either way -- the PR
// this task owns stays open regardless.
func StageRemediationCommitPush() Stage {
return Stage{Name: "remediate-commit-push", Run: func(ctx context.Context, tc *TaskContext) error {
if tc.BuildNoChanges {
return nil
}
changed, err := tc.Trees.CommitAll(ctx, tc.Dir, remediationCommitMessage(tc))
if err != nil {
return err
}
if !changed {
return nil
}
if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil {
return err
}
tc.captureChanges(ctx, capturedAfterCommitPush)
return nil
}}
}
func remediationCommitMessage(tc *TaskContext) string {
return fmt.Sprintf("fix: address review feedback (archie)%s", commitIssueReference("Refs", tc.Task))
}
// StageRemediationReply replies to the review this run addressed, then
// returns the task to pr_open and clears the consumed review payload so a
// later crash-and-resume cannot reprocess it. It is the workflow's only
// terminal stage: it always sets Outcome, so it always ends the run.
func StageRemediationReply() Stage {
return Stage{Name: "remediate-reply", Run: func(ctx context.Context, tc *TaskContext) error {
summary := tc.BuildSummary
if tc.BuildNoChanges {
summary = "Reviewed -- no code change was required."
}
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", summary, tc.Task.RetryCount)
if id, ok := tc.reviewUnit.replyTarget(); ok {
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
tc.Log.Warn("remediation reply not posted", "pr", tc.Task.PRNumber, "comment", id, "err", err)
}
} else {
postRemediationComment(ctx, tc, reply)
}
tc.Task.ReviewPayload = ""
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RetryCount)}
return nil
}}
}
// Remediate runs one remediation round against an archie-owned, still-open
// pull request in response to a forge review reaction
// (docs/prds/pr-review-remediation.md decision 4). It reuses the task's
// existing worktree and branch rather than opening a new PR.
func Remediate() Workflow {
return Workflow{
Name: "remediate",
Stages: []Stage{
StageCheckReviewPayload(),
StageRemediationRoundCap(),
StageResumeWorktree(),
remediateBuildStage(),
StageRemediationCommitPush(),
StageRemediationReply(),
},
}
}