diff --git a/internal/domain/workflow/prreview/gate.go b/internal/domain/workflow/prreview/gate.go new file mode 100644 index 000000000..dd5e06d1f --- /dev/null +++ b/internal/domain/workflow/prreview/gate.go @@ -0,0 +1,54 @@ +package prreview + +import ( + "encoding/json" + "fmt" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" +) + +// Key is a scored finding's stable identity inside one gate document: file, +// line and title. Findings carry no ID, so this is what an operator's +// selection names and what filtering matches on. The document stores the key +// beside the finding (task.ReviewGateFinding), because the operator surface +// never sees this type. +func (f ScoredFinding) Key() string { + return fmt.Sprintf("%s:%d:%s", f.File, f.LineStart, f.Title) +} + +// GateFinding renders f as a document finding: the key an operator's +// selection names, beside the finding's own encoding. +func GateFinding(f ScoredFinding) task.ReviewGateFinding { + data, err := json.Marshal(f) + if err != nil { + // ScoredFinding holds only strings, numbers, bools and slices; a + // marshal failure would be a programming error. + return task.ReviewGateFinding{Key: f.Key()} + } + return task.ReviewGateFinding{Key: f.Key(), Finding: data} +} + +// GateFindings renders a whole scored review for the document. +func GateFindings(findings []ScoredFinding) []task.ReviewGateFinding { + out := make([]task.ReviewGateFinding, len(findings)) + for i, f := range findings { + out[i] = GateFinding(f) + } + return out +} + +// PostedFindings decodes the findings an approve posts back into the review +// type. An entry whose finding does not decode is skipped rather than failing +// the post: the document's keys were produced by this package, so a +// decode failure means the row was not written by this code. +func PostedFindings(entries []task.ReviewGateFinding) []ScoredFinding { + out := make([]ScoredFinding, 0, len(entries)) + for _, entry := range entries { + var f ScoredFinding + if err := json.Unmarshal(entry.Finding, &f); err != nil { + continue + } + out = append(out, f) + } + return out +} diff --git a/internal/domain/workflow/prreview_gate_test.go b/internal/domain/workflow/prreview_gate_test.go new file mode 100644 index 000000000..9a8d14500 --- /dev/null +++ b/internal/domain/workflow/prreview_gate_test.go @@ -0,0 +1,325 @@ +package workflow + +import ( + "context" + "encoding/json" + "slices" + "strings" + "sync" + "testing" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" + workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" +) + +// recordingPipelineRunner answers every full-pipeline agent call the way +// scriptedPRReviewPipeline does, and additionally records each call's mission +// by stage name so the instruction-threading tests can read what phase 3 and +// phase 4 were actually told. +type recordingPipelineRunner struct { + inner *concurrentAgentRunner + + mu sync.Mutex + missions map[string]string +} + +func newRecordingPipelineRunner(byStage func(stage string) (agentexec.Result, error)) *recordingPipelineRunner { + return &recordingPipelineRunner{ + inner: &concurrentAgentRunner{byStage: byStage}, + missions: map[string]string{}, + } +} + +func (r *recordingPipelineRunner) Run( + ctx context.Context, dir string, req agentexec.Request, reporter agentexec.ToolCallReporter, +) (agentexec.Result, error) { + r.mu.Lock() + r.missions[req.Stage] = req.Mission + r.mu.Unlock() + return r.inner.Run(ctx, dir, req, reporter) +} + +func (r *recordingPipelineRunner) mission(stage string) string { + r.mu.Lock() + defer r.mu.Unlock() + return r.missions[stage] +} + +// offerDocuments renders scored findings the way the gate stage does: the +// stable key an operator's selection names, beside the finding's own encoding. +func offerDocuments(findings ...prreview.ScoredFinding) []workflowtask.ReviewGateFinding { + out := make([]workflowtask.ReviewGateFinding, len(findings)) + for i, f := range findings { + out[i] = prreview.GateFinding(f) + } + return out +} + +// gateReviewFindings is a two-finding review the operator is offered: one to +// keep, one to drop, with distinct bodies so a posted comment proves which +// document won. +func gateReviewFindings() []prreview.ScoredFinding { + return []prreview.ScoredFinding{ + {Title: "keep me", File: "main.go", LineStart: 1, Body: "the selected finding", Severity: prreview.SeverityImportant}, + {Title: "drop me", File: "main.go", LineStart: 9, Body: "the unselected finding", Severity: prreview.SeverityNitpick}, + } +} + +// TestStagePROperatorApprovalWritesTheReviewOffer pins the recorded offer +// (docs/prds/pr-review-operator-response.md, "The review the operator +// answers"): the gate must persist the scored findings, the head SHA, the +// pull request's identity and the workflow the wait resumes before it ends +// the run in waiting_human, because the run that computed the findings cannot +// be resumed partway. +func TestStagePROperatorApprovalWritesTheReviewOffer(t *testing.T) { + tc := baseTaskContext(t) + tc.Cfg.Review.ApproveBeforePost = true + tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber = "acme", "widgets", 42 + findings := gateReviewFindings() + tc.prReview = &prReviewState{scored: findings, headSHA: "abc123"} + + if err := stagePROperatorApproval().Run(context.Background(), tc); err != nil { + t.Fatalf("operator-approval: %v", err) + } + if tc.Outcome.Status != StatusWaitingHuman { + t.Fatalf("outcome status = %q, want %q", tc.Outcome.Status, StatusWaitingHuman) + } + gate, ok := workflowtask.DecodeReviewGate(tc.Task.ReviewGate) + if !ok { + t.Fatalf("review_gate = %q, want the encoded offer", tc.Task.ReviewGate) + } + offered := prreview.PostedFindings(gate.Findings) + if len(offered) != len(findings) || offered[0].Title != findings[0].Title || offered[0].Body != findings[0].Body { + t.Fatalf("offer findings = %+v, want the scored review the operator was shown", offered) + } + if gate.Findings[0].Key != findings[0].Key() { + t.Fatalf("offer key = %q, want the finding's stable key %q", gate.Findings[0].Key, findings[0].Key()) + } + if gate.HeadSHA != "abc123" || gate.Owner != "acme" || gate.Repo != "widgets" || gate.PRNumber != 42 || gate.Workflow != tc.Task.Workflow { + t.Fatalf("offer provenance = %+v, want the head, PR identity and resuming workflow recorded", gate) + } + if gate.Outcome != "" || gate.Instructions != "" { + t.Fatalf("offer already carries an answer: %+v", gate) + } +} + +// TestStagePROperatorApprovalDoesNotWaitAgainOnAnApprovedGate is the other +// half of the resume: once the operator approved, the re-run must continue to +// the merge gate and output (which posts the recorded review) rather than +// waiting a second time and overwriting the answer. +func TestStagePROperatorApprovalDoesNotWaitAgainOnAnApprovedGate(t *testing.T) { + tc := baseTaskContext(t) + tc.Cfg.Review.ApproveBeforePost = true + tc.prReview = &prReviewState{scored: gateReviewFindings()} + tc.Task.ReviewGate = workflowtask.EncodeReviewGate(workflowtask.ReviewGate{ + Findings: offerDocuments(gateReviewFindings()...), Outcome: workflowtask.GateApprove, + }) + // Intake is the one restore point; this stage test calls it directly + // rather than scripting the whole pipeline. + restoreReviewGate(tc) + + if err := stagePROperatorApproval().Run(context.Background(), tc); err != nil { + t.Fatalf("operator-approval: %v", err) + } + if tc.Outcome.Status != "" { + t.Fatalf("outcome = %q, want empty: an answered gate must not park the run again", tc.Outcome.Status) + } +} + +// TestRereviewInstructionsReachLensAndReviewerMissions pins Decision 3: the +// restored instructions ride a labelled block in runLens's and runReviewer's +// missions only, and a first run -- no gate document, no instructions -- does +// not carry the block at all. +func TestRereviewInstructionsReachLensAndReviewerMissions(t *testing.T) { + const instructions = "concentrate on the SQL path and the migration ordering" + + run := func(t *testing.T, gate string) *recordingPipelineRunner { + t.Helper() + tc := baseTaskContext(t) + tc.PRSource = &fakePRSource{diff: smallDiff, files: map[string]string{"main.go": "package main\n"}} + tc.Task.ReviewGate = gate + runner := newRecordingPipelineRunner(func(stage string) (agentexec.Result, error) { + switch { + case stage == "intake-ai-score": + return captureResult("score_ai_generated", map[string]any{"confidence": 0.1}), nil + case strings.HasPrefix(stage, "lens-"): + return captureResult("propose_dimensions", map[string]any{"dimensions": []map[string]any{{ + "name": "defect", "prompt": "review main.go", "target_files": []string{"main.go"}, "priority": 1.0, + }}}), nil + case strings.HasPrefix(stage, "reviewer-"): + return captureResult("report_findings", map[string]any{"findings": []any{}}), nil + case stage == "consistency": + return captureResult("report_findings", map[string]any{"findings": []any{}}), nil + case stage == "adversary": + return passedResult("no findings to challenge"), nil + default: + return passedResult("phase complete"), nil + } + }) + tc.Agent = runner + Run(context.Background(), PRReview(), tc) + return runner + } + + answered := workflowtask.EncodeReviewGate(workflowtask.ReviewGate{ + Outcome: workflowtask.GateRereview, Instructions: instructions, + }) + reReview := run(t, answered) + for _, stage := range []string{"lens-behaviour", "lens-mechanics", "lens-fit", "reviewer-defect"} { + if mission := reReview.mission(stage); !strings.Contains(mission, instructions) { + t.Errorf("%s mission does not carry the operator's instructions:\n%s", stage, mission) + } + } + // Only phases 3 and 4 read them: no other phase's mission may carry them. + for _, stage := range []string{"intake-ai-score", "anatomy", "merge-gate"} { + if mission := reReview.mission(stage); strings.Contains(mission, instructions) { + t.Errorf("%s mission carries the re-review instructions; only phases 3 and 4 may", stage) + } + } + + firstRun := run(t, "") + for _, stage := range []string{"lens-behaviour", "reviewer-defect"} { + if mission := firstRun.mission(stage); strings.Contains(mission, "Operator instructions") { + t.Errorf("first-run %s mission carries an operator-instructions block:\n%s", stage, mission) + } + } +} + +// TestApproveResumePostsTheRecordedSelectionNotTheRecomputedFindings pins the +// PRD's first Verification bullet: an approve posts exactly the findings the +// operator selected, and no finding the resumed phases produced. The resumed +// pipeline recomputes its own (different) finding; only the recorded selection +// may reach the forge. +func TestApproveResumePostsTheRecordedSelectionNotTheRecomputedFindings(t *testing.T) { + tc := baseTaskContext(t) + tc.Cfg.Review.ApproveBeforePost = true + tc.PRSource = &fakePRSource{diff: smallDiff, files: map[string]string{"main.go": "package main\n"}} + forge := &fakeForger{} + tc.Forge = forge + + recorded := gateReviewFindings() + tc.Task.ReviewGate = workflowtask.EncodeReviewGate(workflowtask.ReviewGate{ + Findings: offerDocuments(recorded...), HeadSHA: "recorded-sha", Owner: "acme", Repo: "widgets", PRNumber: 42, + Workflow: "pr-review", Outcome: workflowtask.GateApprove, Selection: []string{recorded[0].Key()}, + }) + + tc.Agent = newRecordingPipelineRunner(func(stage string) (agentexec.Result, error) { + switch { + case stage == "intake-ai-score": + return captureResult("score_ai_generated", map[string]any{"confidence": 0.1}), nil + case strings.HasPrefix(stage, "lens-"): + return captureResult("propose_dimensions", map[string]any{"dimensions": []map[string]any{{ + "name": "defect", "prompt": "review main.go", "target_files": []string{"main.go"}, "priority": 1.0, + }}}), nil + case strings.HasPrefix(stage, "reviewer-"): + return captureResult("report_findings", map[string]any{"findings": []map[string]any{{ + "file": "main.go", "line_start": 3, "severity": "important", "title": "recomputed defect", + "body": "a finding the resumed phases produced", "evidence": "package main", "confidence": 0.9, + }}}), nil + case stage == "evidence-verifier": + return captureResult("verify_findings", map[string]any{"verdicts": []map[string]any{{"index": 0, "supported": true}}}), nil + case stage == "adversary": + return captureResult("adversary_verdicts", map[string]any{"verdicts": []map[string]any{{"index": 0, "verdict": "confirmed"}}}), nil + case stage == "consistency": + return captureResult("report_findings", map[string]any{"findings": []any{}}), nil + case stage == "merge-gate": + return captureResult("classify_blocking", map[string]any{"blocking": false}), nil + default: + return passedResult("phase complete"), nil + } + }) + + Run(context.Background(), PRReview(), tc) + + if tc.Outcome.Status != StatusCompleted { + t.Fatalf("outcome = %q, want %q: the approved review posts and the run completes", tc.Outcome.Status, StatusCompleted) + } + if len(forge.comments) != 1 { + t.Fatalf("posted comments = %+v, want exactly the one selected finding", forge.comments) + } + if body := forge.comments[0].Body; body != recorded[0].Body { + t.Fatalf("posted body = %q, want the recorded finding %q, not a recomputed one", body, recorded[0].Body) + } + for _, comment := range forge.comments { + if strings.Contains(comment.Body, "recomputed") { + t.Fatalf("posted comment %q is a finding the resumed phases produced", comment.Body) + } + } + if forge.reviewedHeadSHA != "recorded-sha" { + t.Fatalf("reviewed head = %q, want the recorded head SHA", forge.reviewedHeadSHA) + } +} + +// TestApproveResumeWithNoSelectionPostsEveryRecordedFinding is the PRD's +// "an absent selection means all of them": a chat /approve carries no +// selection syntax and must post the whole recorded review. +func TestApproveResumeWithNoSelectionPostsEveryRecordedFinding(t *testing.T) { + tc := baseTaskContext(t) + tc.Cfg.Review.ApproveBeforePost = true + tc.PRSource = &fakePRSource{diff: smallDiff, files: map[string]string{"main.go": "package main\n"}} + forge := &fakeForger{} + tc.Forge = forge + + recorded := gateReviewFindings() + tc.Task.ReviewGate = workflowtask.EncodeReviewGate(workflowtask.ReviewGate{ + Findings: offerDocuments(recorded...), HeadSHA: "recorded-sha", Owner: "acme", Repo: "widgets", PRNumber: 42, + Outcome: workflowtask.GateApprove, + }) + tc.Agent = newRecordingPipelineRunner(func(stage string) (agentexec.Result, error) { + switch { + case stage == "intake-ai-score": + return captureResult("score_ai_generated", map[string]any{"confidence": 0.1}), nil + case strings.HasPrefix(stage, "lens-"): + return captureResult("propose_dimensions", map[string]any{"dimensions": []map[string]any{{ + "name": "defect", "prompt": "review main.go", "target_files": []string{"main.go"}, "priority": 1.0, + }}}), nil + case strings.HasPrefix(stage, "reviewer-"): + return captureResult("report_findings", map[string]any{"findings": []any{}}), nil + case stage == "consistency": + return captureResult("report_findings", map[string]any{"findings": []any{}}), nil + default: + return passedResult("phase complete"), nil + } + }) + + Run(context.Background(), PRReview(), tc) + + if len(forge.comments) != len(recorded) { + t.Fatalf("posted comments = %d, want all %d recorded findings", len(forge.comments), len(recorded)) + } + bodies := make([]string, len(forge.comments)) + for i, c := range forge.comments { + bodies[i] = c.Body + } + if !slices.Contains(bodies, recorded[0].Body) || !slices.Contains(bodies, recorded[1].Body) { + t.Fatalf("posted bodies = %v, want both recorded findings", bodies) + } +} + +// TestReviewGateDocumentRoundTrip pins the encoding contract itself: the +// document is owned by this package, the store and the wire never parse it, +// and an empty or malformed value must not read as an offer. +func TestReviewGateDocumentRoundTrip(t *testing.T) { + gate := workflowtask.ReviewGate{ + Findings: offerDocuments(gateReviewFindings()...), HeadSHA: "sha", Owner: "acme", Repo: "widgets", + PRNumber: 3, Workflow: "pr-review", Outcome: workflowtask.GateApprove, + Selection: []string{"main.go:1:keep me"}, Instructions: "x", + } + decoded, ok := workflowtask.DecodeReviewGate(workflowtask.EncodeReviewGate(gate)) + if !ok { + t.Fatalf("round trip failed: %q", workflowtask.EncodeReviewGate(gate)) + } + if !decoded.Approved() || len(decoded.Findings) != 2 || decoded.Selection[0] != gate.Selection[0] { + t.Fatalf("decoded = %+v, want %+v", decoded, gate) + } + if _, ok := workflowtask.DecodeReviewGate(""); ok { + t.Fatal("an empty column decoded as a document") + } + if _, ok := workflowtask.DecodeReviewGate("not json"); ok { + t.Fatal("a malformed column decoded as a document") + } + if _, err := json.Marshal(gate); err != nil { + t.Fatalf("the document must be JSON-safe: %v", err) + } +} diff --git a/internal/domain/workflow/prreview_stages.go b/internal/domain/workflow/prreview_stages.go index ff46cc0ad..7bce421f4 100644 --- a/internal/domain/workflow/prreview_stages.go +++ b/internal/domain/workflow/prreview_stages.go @@ -74,6 +74,22 @@ type prReviewState struct { scored []prreview.ScoredFinding reviewerFailures atomic.Int64 + // operatorInstructions is the re-review's instructions, restored from the + // task's review_gate document at intake. Phase 3's lens missions and phase + // 4's reviewer missions append it as one labelled block + // (docs/prds/pr-review-operator-response.md, Decision 3); nothing else + // reads it, so a first run -- or any run the operator did not instruct -- + // leaves every other mission untouched. + operatorInstructions string + // approvedReview is the review the operator approved, restored from the + // task's review_gate document at intake. When set, this run IS the + // approve resume: the gate must not wait a second time, and phase 9 posts + // the recorded review filtered by the operator's selection rather than + // the review the resumed phases recomputed. The resumed pipeline has no + // partway resume, so the recomputed findings are unavoidable; not posting + // them is what makes "the findings the operator selected" true. + approvedReview *task.ReviewGate + // findingsMu guards findings during phase 6, where the coverage gate and // consistency verification append to it from two goroutines running in // parallel (docs/prds/pr-review-agent.md, phase 6). Every other phase @@ -265,6 +281,7 @@ func stagePRIntake() Stage { metadata: meta, diff: diff, files: files, stats: stats, depth: depth, runStart: time.Now(), } + restoreReviewGate(tc) aiGenerated, err := scoreAIGenerated(ctx, tc, meta) if err != nil { @@ -326,6 +343,35 @@ func scoreAIGenerated(ctx context.Context, tc *TaskContext, meta PRMetadata) (fl return captured.Confidence, nil } +// restoreReviewGate reads the task's review_gate document back into the +// run's scratch state at intake: the instructions a re-review must carry into +// phases 3 and 4, and the approved review an approve resume must post. Called +// once, where the review the run works on is established +// (docs/prds/pr-review-operator-response.md, Decision 3). +func restoreReviewGate(tc *TaskContext) { + gate, ok := task.DecodeReviewGate(tc.Task.ReviewGate) + if !ok { + return + } + tc.prReview.operatorInstructions = gate.Instructions + if gate.Approved() { + approved := gate + tc.prReview.approvedReview = &approved + } +} + +// operatorInstructionsBlock renders the re-review's operator instructions as +// the labelled block phase 3's and phase 4's missions carry. It is empty -- +// and therefore absent -- on a run the operator did not instruct, which is +// what keeps "a first run's do not" true. +func operatorInstructionsBlock(tc *TaskContext) string { + if tc.prReview == nil || tc.prReview.operatorInstructions == "" { + return "" + } + return "Operator instructions for this re-review, written by the operator who read the " + + "previous findings. Address them in your work:\n" + tc.prReview.operatorInstructions + "\n\n" +} + // stagePRAnatomy is pipeline phase 2: the read-only snapshot every later // phase reads from, the deterministic clustering and blast radius, and one // agent's narrative of the change. @@ -446,13 +492,14 @@ func runLens(ctx context.Context, tc *TaskContext, name, angle string) ([]prrevi }`) mission := fmt.Sprintf( "You are the %s lens over this pull request: %s.\n\n"+ - "Title: %s\n\nDescription:\n%s\n\nDiff:\n%s\n\n"+ + "Title: %s\n\nDescription:\n%s\n\nDiff:\n%s\n\n%s"+ "Propose the review dimensions this angle needs, each with a reviewer prompt "+ "written for this specific PR, its target files, any context files a reviewer "+ "should also read, and a priority (higher runs first when the depth caps how "+ "many dimensions survive). Call propose_dimensions exactly once, then call "+ "finish with status \"passed\".", name, angle, tc.prReview.metadata.Title, tc.prReview.metadata.Body, clip(tc.prReview.diff, 60000), + operatorInstructionsBlock(tc), ) res, err := runPRReviewAgent(ctx, tc, tc.prReview.snapshotDir, "lens-"+name, "review", mission, 15, []agentexec.CaptureTool{{ Name: "propose_dimensions", Description: "Record this lens's proposed review dimensions. Call exactly once, before finish.", @@ -522,12 +569,12 @@ func stagePRReview() Stage { // (not this slice) can tell "unreviewed" from "reviewed-clean" apart. func runReviewer(ctx context.Context, tc *TaskContext, dim prreview.Dimension) []prreview.Finding { mission := fmt.Sprintf( - "%s\n\nTarget files: %s\n\nRead the target files (and, if useful, the context "+ + "%s\n\nTarget files: %s\n\n%sRead the target files (and, if useful, the context "+ "files) in the snapshot and report every finding for this dimension. Quote the "+ "exact evidence for each finding; do not report anything you cannot point at in "+ "the code. Call report_findings exactly once (an empty array is a valid, "+ "complete report), then call finish with status \"passed\".", - dim.Prompt, strings.Join(dim.TargetFiles, ", "), + dim.Prompt, strings.Join(dim.TargetFiles, ", "), operatorInstructionsBlock(tc), ) name := "reviewer-" + dim.Name res, runErr := runReviewerAgent(ctx, tc, name, mission, []agentexec.CaptureTool{reportFindingsTool}) @@ -712,7 +759,16 @@ func stagePROutput() Stage { // a caller that must preserve its own outcome (archie's own PRs, which has // already set StatusPROpen by the time findings are ready to post) can run it // without stagePROutput's unconditional StatusCompleted assignment. +// +// An approve resume posts the recorded review the operator answered, not the +// one this run recomputed: the engine has no partway resume, so the resumed +// phases recompute every finding, and only the recorded document is the +// review the operator saw (docs/prds/pr-review-operator-response.md, "The +// review the operator answers"). func runPROutputPhase(ctx context.Context, tc *TaskContext) (string, error) { + if approved := tc.prReview.approvedReview; approved != nil { + return postApprovedReview(ctx, tc, *approved) + } if budgetExhausted(tc, "output") { skipPhase(tc, "output") } else { @@ -769,23 +825,47 @@ func polishFinding(ctx context.Context, tc *TaskContext, f prreview.ScoredFindin return f } -// postPRReview posts every line-anchored finding as one forge review. A -// finding with no line (LineStart <= 0) is dropped rather than posted -// anywhere -- docs/prds/inline-review.md's PR-body fallback list for +// postApprovedReview posts the review the operator approved, filtered by +// their selection, against the pull request and head the offer recorded. It +// polishes nothing: the wording the operator approved is the wording that +// posts. +func postApprovedReview(ctx context.Context, tc *TaskContext, gate task.ReviewGate) (string, error) { + posted := prreview.PostedFindings(gate.Posted()) + comments := reviewComments(posted) + if len(comments) == 0 { + return fmt.Sprintf("operator approved %d finding(s); none to post with a line anchor", len(posted)), nil + } + if err := tc.Forge.CreateReviewComments(ctx, gate.Owner, gate.Repo, gate.PRNumber, gate.HeadSHA, comments); err != nil { + return "", fmt.Errorf("post approved review: %w", err) + } + return fmt.Sprintf("posted %d finding(s) approved by the operator", len(comments)), nil +} + +// reviewComments renders every line-anchored finding as one forge review +// comment. A finding with no line (LineStart <= 0) is dropped rather than +// posted anywhere -- docs/prds/inline-review.md's PR-body fallback list for // whole-file findings, and REQUEST_CHANGES vs COMMENT event submission // (workflow.Forger.CreateReviewComments always posts a COMMENT-state // review; GitHub's implementation does not submit a review object at all, // only per-comment calls, so REQUEST_CHANGES needs a Forger/forge change, // not just a caller change here) are both real gaps this bead does not // close; see the follow-up bead this bead's commit files. -func postPRReview(ctx context.Context, tc *TaskContext) error { - comments := make([]ReviewComment, 0, len(tc.prReview.scored)) - for _, f := range tc.prReview.scored { +func reviewComments(findings []prreview.ScoredFinding) []ReviewComment { + comments := make([]ReviewComment, 0, len(findings)) + for _, f := range findings { if f.LineStart <= 0 { continue } comments = append(comments, ReviewComment{Path: f.File, Line: f.LineStart, Body: f.Body}) } + return comments +} + +// postPRReview posts every line-anchored finding as one forge review. A +// finding with no line (LineStart <= 0) is dropped rather than posted +// anywhere (see reviewComments). +func postPRReview(ctx context.Context, tc *TaskContext) error { + comments := reviewComments(tc.prReview.scored) if len(comments) == 0 { return nil } diff --git a/internal/domain/workflow/prreview_stages_verify.go b/internal/domain/workflow/prreview_stages_verify.go index 0c3d2dcd2..015536e01 100644 --- a/internal/domain/workflow/prreview_stages_verify.go +++ b/internal/domain/workflow/prreview_stages_verify.go @@ -10,6 +10,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) // stagePRVerification is pipeline phase 5, over the review findings phase 4 @@ -152,11 +153,34 @@ func runPrecisionGate(ctx context.Context, tc *TaskContext, findings []prreview. // docs/prds/execution-tree-state-machine.md's engine loop stops as soon as a // stage sets a non-empty Outcome.Status -- so the merge gate and output // stages never run until an operator's response requeues the task. +// +// Before it waits, the gate records the review it is holding on the task's +// review_gate column: the scored findings, the head SHA, the pull request's +// identity and the workflow the wait resumes. The recorded document is what +// makes the operator's answer mean the review they saw -- the engine cannot +// resume a run partway, so a resumed pipeline recomputes its findings with +// agent calls (docs/prds/pr-review-operator-response.md, "The review the +// operator answers"). +// +// An approve resume is the same run re-entered: its review_gate carries the +// answer already, so the gate must not wait a second time -- it continues to +// the merge gate and output, where the recorded review posts. func stagePROperatorApproval() Stage { return Stage{Name: "operator-approval", Run: func(_ context.Context, tc *TaskContext) error { if !tc.Cfg.Review.ApproveBeforePost || len(tc.prReview.scored) == 0 { return nil } + if tc.prReview.approvedReview != nil { + return nil + } + tc.Task.ReviewGate = task.EncodeReviewGate(task.ReviewGate{ + Findings: prreview.GateFindings(tc.prReview.scored), + HeadSHA: tc.prReview.headSHA, + Owner: tc.Task.Owner, + Repo: tc.Task.Repo, + PRNumber: tc.Task.PRNumber, + Workflow: tc.Task.Workflow, + }) tc.Outcome = Outcome{ Status: StatusWaitingHuman, Detail: fmt.Sprintf("%d finding(s) awaiting operator review before posting", len(tc.prReview.scored)), diff --git a/internal/domain/workflow/task/review_gate.go b/internal/domain/workflow/task/review_gate.go new file mode 100644 index 000000000..8df88c1b5 --- /dev/null +++ b/internal/domain/workflow/task/review_gate.go @@ -0,0 +1,155 @@ +package task + +import ( + "encoding/json" + + "github.com/samcharles93/archie-core/internal/taskstate" +) + +// ReviewGate is the operator-approval gate's whole conversation with the +// operator, encoded on the task's review_gate column +// (docs/prds/pr-review-operator-response.md). +// +// It lives with the task record it encodes, the way EncodeInputs does, for the +// same reason: the dashboard process renders and answers a gate, and it must +// not link the workflow engine that owns the finding type the pipeline reads. +// The findings therefore cross this document as opaque JSON beside the key an +// operator's selection names (ReviewGateFinding); only the pipeline decodes +// them. +// +// The offer half -- the findings, the head SHA, the pull request's identity +// and the workflow the wait resumes -- is written by the gate stage before it +// ends the run in waiting_human. The answer half -- the outcome, the finding +// keys an approve posts and the instructions a re-review carries -- is +// written back by the response path in the guarded requeue that clears the +// wait. +type ReviewGate struct { + // Findings is the review the operator is answering. An approve keeps it + // (the resumed run posts it, filtered by Selection); a re-review's + // response clears it, because the resumed run recomputes the review from + // scratch. + Findings []ReviewGateFinding `json:"findings,omitempty"` + // HeadSHA is the pull request head the findings were measured on, so the + // review the resume posts anchors to the commit the operator reviewed. + HeadSHA string `json:"head_sha,omitempty"` + // Owner, Repo and PRNumber are the pull request's identity. They ride in + // the document rather than being re-read from the task so the review the + // operator approved posts against exactly the pull request it named. + Owner string `json:"owner,omitempty"` + Repo string `json:"repo,omitempty"` + PRNumber int `json:"pr_number,omitempty"` + // Workflow is the workflow the wait resumes. It is recorded for the + // operator's benefit; the requeue keeps the task's own workflow, which + // this must agree with. + Workflow string `json:"workflow,omitempty"` + // Outcome is the operator's answer: GateApprove or GateRereview, empty + // while the gate is still waiting. + Outcome string `json:"outcome,omitempty"` + // Selection is the finding keys an approve posts. Empty means all of the + // offered findings. + Selection []string `json:"selection,omitempty"` + // Instructions is what the operator asked a re-review to focus on. The + // PRD requires it for a re-review; the lens and reviewer missions read it. + Instructions string `json:"instructions,omitempty"` +} + +// ReviewGateFinding is one offered finding: its stable key, which an +// operator's selection names and the response path validates against, beside +// the finding's own JSON. The key is part of the document rather than derived +// here so the operator surface never has to know the finding's type. +type ReviewGateFinding struct { + Key string `json:"key"` + Finding json.RawMessage `json:"finding"` +} + +// The gate's outcome values. They are the operator actions that answer a +// gate, spelled by the shared lifecycle vocabulary so a rename cannot leave +// the gate recording a decision no surface offers. +const ( + GateApprove = string(taskstate.ActionApprove) + GateRereview = string(taskstate.ActionRereview) +) + +// MaxRereviewRounds bounds how many operator re-reviews one review gate +// grants, per the PRD's Decision 2. It is a constant in the domain, not a +// config knob, and the guarded store write enforces it in the row so two +// simultaneous re-reviews cannot spend a round the cap forbids. +const MaxRereviewRounds = 2 + +// Approved reports whether the operator's answer was an approve. +func (g ReviewGate) Approved() bool { return g.Outcome == GateApprove } + +// Offered reports whether the document holds a review the operator was shown. +func (g ReviewGate) Offered() bool { return len(g.Findings) > 0 } + +// OfferedKeys returns the keys of every offered finding, in offer order. +func (g ReviewGate) OfferedKeys() []string { + keys := make([]string, len(g.Findings)) + for i, entry := range g.Findings { + keys[i] = entry.Key + } + return keys +} + +// Posted returns the offered findings an approve posts, filtered by the +// operator's selection. An absent selection means all of them, in the order +// the findings were offered. +func (g ReviewGate) Posted() []ReviewGateFinding { + if !g.Approved() { + return nil + } + if len(g.Selection) == 0 { + return g.Findings + } + selected := make(map[string]struct{}, len(g.Selection)) + for _, key := range g.Selection { + selected[key] = struct{}{} + } + out := make([]ReviewGateFinding, 0, len(g.Findings)) + for _, entry := range g.Findings { + if _, ok := selected[entry.Key]; ok { + out = append(out, entry) + } + } + return out +} + +// EncodeReviewGate renders the document for the review_gate column. The +// package that owns the column owns its encoding, so neither the store nor the +// wire parses it. Encoding the zero document yields "" rather than "{}": an +// empty column is the format for "this task never reached the gate". +func EncodeReviewGate(g ReviewGate) string { + if gateIsZero(g) { + return "" + } + data, err := json.Marshal(g) + if err != nil { + // ReviewGate holds only strings, ints and JSON already validated by + // encoding/json; a marshal failure would be a programming error, and + // the honest encoding of "there is no document" is empty. + return "" + } + return string(data) +} + +// gateIsZero reports whether the document carries nothing at all. The struct +// holds slices, so it cannot be compared with ==. +func gateIsZero(g ReviewGate) bool { + return g.Outcome == "" && g.Instructions == "" && g.Selection == nil && + g.HeadSHA == "" && g.Owner == "" && g.Repo == "" && g.PRNumber == 0 && + g.Workflow == "" && g.Findings == nil +} + +// DecodeReviewGate parses a stored review_gate document. An empty or +// unparseable value decodes to ok=false: a task that never reached the gate, +// or a row from before the column existed, must not be mistaken for an offer. +func DecodeReviewGate(stored string) (ReviewGate, bool) { + if stored == "" { + return ReviewGate{}, false + } + var g ReviewGate + if err := json.Unmarshal([]byte(stored), &g); err != nil { + return ReviewGate{}, false + } + return g, true +} diff --git a/internal/taskstate/taskstate.go b/internal/taskstate/taskstate.go index 84447278f..4890ae27b 100644 --- a/internal/taskstate/taskstate.go +++ b/internal/taskstate/taskstate.go @@ -31,6 +31,7 @@ const ( ActionStop Action = "stop" ActionApprove Action = "approve" ActionReject Action = "reject" + ActionRereview Action = "rereview" ActionRetry Action = "retry" ActionAbandon Action = "abandon" ActionOpenPR Action = "open_pr" @@ -89,7 +90,7 @@ func Actions(status string) []Action { case Running: actions = []Action{ActionStop, ActionReject} case WaitingHuman: - actions = []Action{ActionApprove, ActionReject} + actions = []Action{ActionApprove, ActionReject, ActionRereview} case Parked: actions = []Action{ActionRetry, ActionAbandon, ActionReject} case PROpen: @@ -104,7 +105,7 @@ func Actions(status string) []Action { // change no status (archive, and the forge links) report false. func ActionTarget(action Action) (string, bool) { switch action { - case ActionApprove, ActionRetry: + case ActionApprove, ActionRetry, ActionRereview: return Queued, true case ActionStop: return Parked, true @@ -206,6 +207,7 @@ func ActionCatalog() []ActionMeta { {ID: string(ActionCancel), Label: "Cancel", Kind: "quiet", Confirm: `Cancel "{title}"? This closes the forge issue.`}, {ID: string(ActionStop), Label: "Stop", Kind: "primary", Confirm: `Stop "{title}"? Recoverable work will remain parked.`}, {ID: string(ActionApprove), Label: "Approve", Kind: "primary"}, + {ID: string(ActionRereview), Label: "Re-review", Kind: "quiet"}, {ID: string(ActionReject), Label: "Reject", Kind: "quiet", Confirm: `Reject "{title}"? This closes the forge issue.`}, {ID: string(ActionRetry), Label: "Retry", Kind: "primary"}, {ID: string(ActionAbandon), Label: "Abandon", Kind: "quiet", Confirm: `Abandon "{title}"? Archie stops working on it; the forge issue stays open.`},