Files
archie/internal/app/archied/pr_review_test.go
T
sam 0e6c6fc6d1 feat(artifacts): publish the completed PR review to the collaborative editor
Implements docs/prds/artifact-sender.md (Approved). archie-core now sends
generated artifacts to the offloaded.dev collaborative editor, whose
POST /api/artifacts route, bearer service token, PocketBase-backed
versions and idempotency semantics are the receiving contract.

- [artifacts] config section: base_url + token SecretRef with a
  token_env fallback naming WORKSPACE_INGEST_TOKEN. An empty base_url
  disables the sender entirely; a base_url with an unresolvable token
  disables it with a warning, because a missing credential disables a
  capability rather than stopping the daemon.
- internal/infrastructure/artifactsync: one-method Publish seam in the
  Courier posture, full source per publish (versions of record are
  snapshots), 503 retried three times with backoff, 401/400 surfaced
  immediately with the field reason, deterministic request ids
  (artifact:pr-review:<owner>/<repo>#<n>).
- ReviewReport gains a pure markdown renderer in internal/domain/workflow:
  summary, one subsection per finding with the failure scenario and
  disposition when present, verified properties as a checked-clean list.
- The daemon's PR reviewer publishes after a completed review when the
  sender is configured, records the editor deep link on the result, and
  degrades a failed publish to a log line -- publishing never fails the
  producing work.
2026-09-23 03:15:27 +10:00

318 lines
11 KiB
Go

package archied
import (
"context"
"errors"
"log/slog"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/forge"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/artifactsync"
"github.com/samcharles93/archie-core/internal/tools"
"github.com/samcharles93/archie-core/internal/worktree"
)
func TestSplitOwnerRepo(t *testing.T) {
tests := []struct {
in string
owner string
repo string
wantErr bool
}{
{"acme/widget", "acme", "widget", false},
{"acme/widget/service", "acme", "widget/service", false},
{"acme", "", "", true},
{"/widget", "", "", true},
{"acme/", "", "", true},
{"", "", "", true},
}
for _, tt := range tests {
owner, repo, err := splitOwnerRepo(tt.in)
if tt.wantErr {
if err == nil {
t.Errorf("splitOwnerRepo(%q) error = nil, want error", tt.in)
}
continue
}
if err != nil {
t.Errorf("splitOwnerRepo(%q) error = %v", tt.in, err)
continue
}
if owner != tt.owner || repo != tt.repo {
t.Errorf("splitOwnerRepo(%q) = (%q, %q), want (%q, %q)", tt.in, owner, repo, tt.owner, tt.repo)
}
}
}
func TestPRIssueText(t *testing.T) {
tests := []struct {
name string
pr forge.PullRequest
want string
}{
{"title only", forge.PullRequest{Title: "Fix login"}, "Fix login"},
{"title and body", forge.PullRequest{Title: "Fix login", Body: "The form 500s."}, "Fix login\n\nThe form 500s."},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := prIssueText(tt.pr); got != tt.want {
t.Errorf("prIssueText = %q, want %q", got, tt.want)
}
})
}
}
func TestMapReviewResult(t *testing.T) {
report := workflow.ReviewReport{
Status: workflow.ReviewStatusCompleted,
Summary: "checked and cleared",
Findings: []workflow.ReviewFinding{
{File: "a.go", Line: 3, Defect: "nil deref", FailureScenario: "x", Verdict: workflow.ReviewVerdictConfirmed, Level: workflow.ReviewLevelError, Category: workflow.ReviewCategoryNilRisk},
{File: "b.go", Line: 0, Defect: "style", FailureScenario: "y", Verdict: workflow.ReviewVerdictPlausible, Level: workflow.ReviewLevelWarn, Category: workflow.ReviewCategoryOther},
},
}
got := mapReviewResult("acme/widget", 7, "openai/gpt-5", report)
if got.Repo != "acme/widget" || got.Number != 7 || got.Model != "openai/gpt-5" || got.Status != "completed" || got.Summary != "checked and cleared" {
t.Fatalf("result meta = %+v", got)
}
if len(got.Findings) != 2 {
t.Fatalf("findings = %d, want 2", len(got.Findings))
}
if !got.Findings[0].Blocking {
t.Error("confirmed error finding should be blocking")
}
if got.Findings[1].Blocking {
t.Error("plausible warn finding must not be blocking")
}
if got.Findings[0].Line != 3 {
t.Errorf("line = %d, want 3", got.Findings[0].Line)
}
}
func TestMapReviewResultNotRunPreservesReason(t *testing.T) {
report := workflow.NewNotRunReviewReport("no reviewer model configured")
got := mapReviewResult("acme/widget", 7, "", report)
if got.Status != "not_run" || got.Reason != "no reviewer model configured" {
t.Fatalf("not_run result = %+v, want status not_run and reason preserved", got)
}
}
func TestPrReviewerAuthorize(t *testing.T) {
r := &prReviewer{allowed: map[string]map[string]bool{
"": {"acme/widget": true, "acme/core": true},
"archie": {"acme/widget": true},
}}
archie := "archie"
other := "other"
tests := []struct {
name string
identity *string
owner string
repo string
wantErr bool
}{
{"identity own repo", &archie, "acme", "widget", false},
{"identity foreign repo", &archie, "acme", "core", true},
{"unknown identity", &other, "acme", "widget", true},
{"operator any configured", nil, "acme", "core", false},
{"operator unconfigured repo", nil, "acme", "other", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := r.authorize(tt.identity, tt.owner, tt.repo)
if tt.wantErr && err == nil {
t.Errorf("authorize(%v, %s/%s) error = nil, want error", tt.identity, tt.owner, tt.repo)
}
if !tt.wantErr && err != nil {
t.Errorf("authorize(%v, %s/%s) error = %v, want nil", tt.identity, tt.owner, tt.repo, err)
}
})
}
}
func TestPrReviewerSingleflight(t *testing.T) {
r := &prReviewer{}
key := "acme/widget#7"
if !r.begin(key) {
t.Fatal("first begin = false, want true")
}
if r.begin(key) {
t.Fatal("concurrent begin = true, want false (deterministic single-flight)")
}
r.end(key)
if !r.begin(key) {
t.Fatal("begin after end = false, want true")
}
}
func TestBuildReviewAllowlist(t *testing.T) {
cfg := config.Config{
Identities: []config.IdentityConfig{
{Name: "archie", Repos: []config.Repo{{Owner: "acme", Name: "widget"}}},
},
}
allowed := buildReviewAllowlist(cfg)
if !allowed["archie"]["acme/widget"] {
t.Errorf("allowlist missing acme/widget for identity archie: %+v", allowed)
}
if allowed["archie"]["acme/core"] {
t.Errorf("allowlist leaked acme/core to identity archie: %+v", allowed)
}
if _, ok := allowed["nobody"]; ok {
t.Errorf("allowlist contains unknown identity nobody: %+v", allowed)
}
}
// reviewCapableForge satisfies both forge.Forge (via embedding) and
// forge.PullRequestReader, so boot.prReviewer can be exercised in isolation.
type reviewCapableForge struct {
forge.Forge
}
func (reviewCapableForge) GetPullRequest(context.Context, string, string, int) (forge.PullRequest, error) {
return forge.PullRequest{}, nil
}
// TestPrReviewerIsMemoized pins the cross-channel single-flight fix: every
// gateway must share one prReviewer so a review of the same PR requested from
// two channels at once deduplicates instead of running twice. The boot must
// own a worktree manager: a reviewer without one can never run and must not be
// produced (see TestPrReviewerNilWithoutTrees).
func TestPrReviewerIsMemoized(t *testing.T) {
b := &boot{
forgeClient: reviewCapableForge{Forge: forge.NewNoop(slog.New(slog.DiscardHandler))},
trees: &worktree.Manager{},
}
first := b.prReviewer()
if first == nil {
t.Fatal("prReviewer() = nil, want a reviewer")
}
if second := b.prReviewer(); first != second {
t.Fatal("prReviewer() returned distinct instances; channels would not share the in-flight set")
}
}
// TestPrReviewerNilWithoutTrees pins the producer-side invariant: a PR-capable
// forge without a worktree manager must yield no reviewer. The standalone
// Gateway never builds trees, and the daemon used to capture b.trees before it
// was assigned, so both advertised a review_pr tool that always failed.
func TestPrReviewerNilWithoutTrees(t *testing.T) {
b := &boot{forgeClient: reviewCapableForge{Forge: forge.NewNoop(slog.New(slog.DiscardHandler))}}
if got := b.prReviewer(); got != nil {
t.Fatalf("prReviewer() with no worktree manager = %T, want nil", got)
}
}
// TestReviewPRToolRegisteredOnlyWithWorkingReviewer composes the real boot
// wiring (boot.prReviewer -> gateway.ReviewTools) and asserts review_pr is
// advertised only when the reviewer can actually run.
func TestReviewPRToolRegisteredOnlyWithWorkingReviewer(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
b := &boot{
forgeClient: reviewCapableForge{Forge: forge.NewNoop(logger)},
log: logger,
}
if hasReviewPRTool(gateway.ReviewTools(b.prReviewer(), "archie")) {
t.Fatal("review_pr advertised with no worktree manager: a tool that cannot run must not be offered")
}
b.trees = &worktree.Manager{}
if !hasReviewPRTool(gateway.ReviewTools(b.prReviewer(), "archie")) {
t.Fatal("review_pr not advertised with a worktree manager")
}
}
// hasReviewPRTool reports whether review_pr is offered. Presence is asserted by
// name rather than by entry count: the contract is that this one capability is
// offered only when it can run, so adding a sibling review tool must not turn
// this red.
func hasReviewPRTool(entries []tools.ToolEntry) bool {
for _, e := range entries {
if e.Name == "review_pr" {
return true
}
}
return false
}
type fakeArtifactSender struct {
calls int
url string
err error
last artifactsync.Artifact
}
func (f *fakeArtifactSender) Publish(_ context.Context, a artifactsync.Artifact) (string, error) {
f.calls++
f.last = a
if f.err != nil {
return "", f.err
}
return f.url, nil
}
func TestPrReviewerPublishesTheCompletedReview(t *testing.T) {
fake := &fakeArtifactSender{url: "https://offloaded.dev/collab?document=a_1"}
r := &prReviewer{artifacts: fake, log: slog.New(slog.DiscardHandler)}
report := workflow.NewCompletedReviewReport([]workflow.ReviewFinding{{
File: "handler.go", Line: 42, Defect: "nil deref",
FailureScenario: "empty payload crashes", Verdict: workflow.ReviewVerdictConfirmed,
Level: workflow.ReviewLevelError,
}}, "one finding")
report.Checked = []workflow.ReviewCheck{{Property: "p", Evidence: "e"}}
url := r.publishArtifact(context.Background(), "system:pr-reviewer", "acme", "widget", 7, report)
if url != fake.url {
t.Fatalf("publishArtifact = %q, want the sender's url %q", url, fake.url)
}
if fake.calls != 1 {
t.Fatalf("Publish called %d times, want 1", fake.calls)
}
got := fake.last
if got.Meta.Format != "markdown" || got.Meta.Category != "pr-review" {
t.Fatalf("format/category = %s/%s, want markdown/pr-review", got.Meta.Format, got.Meta.Category)
}
if got.Meta.Actor != "system:pr-reviewer" || got.Meta.Origin != "pr-review" {
t.Fatalf("attribution = %s/%s", got.Meta.Actor, got.Meta.Origin)
}
if got.Meta.Visibility != "account-only" || got.Meta.Egress != "none" {
t.Fatalf("visibility/egress = %s/%s", got.Meta.Visibility, got.Meta.Egress)
}
if got.Title != "Review of acme/widget#7" {
t.Fatalf("title = %q", got.Title)
}
if got.Meta.RequestID != "artifact:pr-review:acme/widget#7" {
t.Fatalf("requestId = %q, want the deterministic artifact key", got.Meta.RequestID)
}
if got.Meta.Task == nil || got.Meta.Task.Owner != "acme" || got.Meta.Task.Number != 7 {
t.Fatalf("task coordinates = %+v", got.Meta.Task)
}
if !strings.Contains(got.Source, "## Findings") {
t.Fatalf("source is not the rendered report:\n%s", got.Source)
}
}
func TestPrReviewerPublishDegradesOnSenderFailure(t *testing.T) {
r := &prReviewer{artifacts: &fakeArtifactSender{err: errors.New("503 exhausted")}, log: slog.New(slog.DiscardHandler)}
if url := r.publishArtifact(context.Background(), "system:pr-reviewer", "acme", "widget", 7, workflow.NewCompletedReviewReport(nil, "s")); url != "" {
t.Fatalf("url = %q, want empty on a failed publish", url)
}
}
func TestPrReviewerPublishIsANoOpWithoutASender(t *testing.T) {
r := &prReviewer{}
if url := r.publishArtifact(context.Background(), "system:pr-reviewer", "acme", "widget", 7, workflow.NewCompletedReviewReport(nil, "s")); url != "" {
t.Fatalf("url = %q, want empty when the sender is disabled", url)
}
}