diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl
index 00e0b330b..8ad356695 100644
--- a/.beads/issues.jsonl
+++ b/.beads/issues.jsonl
@@ -15,7 +15,7 @@
{"_type":"issue","id":"archie-core-t2db.5","title":"Security: an unauthenticated endpoint must not be able to run an agent","description":"P0 within this epic because the feature's own pitch is the threat model: a public intake surface whose output is an agent with tool access and a repo. Get this wrong and a webhook URL is remote code execution with extra steps.\n\nNon-negotiables to design:\n\n- Per-source authentication. A source registers with a secret (HMAC, as internal/channels/webhook already does per route) before its events can trigger anything. Capture-only for unknown senders is acceptable; triggering is not.\n- Human approval before a binding goes live. An operator authoring a binding is a deliberate act; an event arriving is not. Nothing should self-arm.\n- Rate and volume limits per source, so capture cannot be used to exhaust disk or drown the inspector.\n- Payload content is untrusted input flowing into an agent prompt. Treat prompt injection as expected, not exceptional -- the sender controls that text, and the agent has tools. Bound what a playbook-triggered workflow may do.\n- Captured payloads may contain secrets from the sending system. Decide retention, redaction and who can view them; internal/memory/scrubber may already have applicable prior art.\n\nArchie's own principle applies: environmental enforcement over prompt rules. 'The agent should ignore instructions in the payload' is not a control.","acceptance_criteria":"An event from an unauthenticated source can be captured but cannot trigger a workflow; a new binding requires explicit human approval before it arms; per-source rate limits exist; the blast radius of a playbook-triggered workflow is bounded by code rather than by prompt text; retention and visibility of captured payloads is decided and documented.","notes":"2026-08-22: security design decided and documented in docs/prds/webhook-intake-security.md, covering all five non-negotiables from this bead's description:\n1. Per-source auth reuses internal/channels/webhook's existing HMAC-SHA256 scheme; capture accepts unsigned events (visible, marked unauthenticated), only authenticated events can ever match a binding.\n2. Bindings gain a draft -\u003e pending_approval -\u003e armed state machine; any edit to an armed binding drops it back to pending_approval so approval can't be bypassed by editing. Modeled on telegram's existing dangerousAction/pendingApproval flow (dangerous.go/approval.go).\n3. Per-source token-bucket rate limiting (precedent: pairing/store.go's MaxPendingPerPlatform); limit-exceeded is an observable 429, not a silent drop.\n4. Blast radius bounded by the SAME code-level controls every task already gets -- gate, diff_cap_lines, sandboxed container, worktree isolation -- no new relaxation for playbook-triggered work, and payload text is ordinary untrusted prompt input, never a trusted instruction.\n5. 7-day configurable retention on captured payloads; best-effort redaction reusing gateway/stream.go's sensitiveParameterKey heuristic before persisting; visibility gated by the same dashboard auth as every other webui surface.\n\nThis bead's code-level acceptance criteria (capture-can't-trigger, rate limits exist, blast-radius bounded, approval gate) cannot be implemented yet: they constrain t2db.1 (capture), 7d5u.3 (intake family) and t2db.4 (binding), none of which have landed. This document is the contract those beads build against -- do not build any of them without satisfying it. Leaving this bead in_progress rather than closing it; it closes when t2db.1/7d5u.3/t2db.4 land and demonstrably satisfy points 1-5, not before.","status":"in_progress","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:46Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:01Z","started_at":"2026-08-21T14:51:26Z","external_ref":"https://github.com/samcharles93/archie-core/issues/536","dependencies":[{"issue_id":"archie-core-t2db.5","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-d66k","title":"P1: Update ARCHITECTURE.md Package Map with missing packages","description":"ARCHITECTURE.md's Package Map omits sizeable load-bearing packages:\n- internal/gateway: 18.7k LOC\n- internal/tools: 20.9k LOC\n- internal/memory: 7k LOC\n- secret/*\n- plugin/*\n- skill/*\n\nA contributor or agent reading the map would miss where most of the code actually lives.\n\nNeed to:\n- Audit ARCHITECTURE.md Package Map section\n- Add all missing packages with their responsibilities\n- Ensure consistency with actual package structure\n- Verify LOC counts are accurate\n\nBlocked by: nothing","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-28T13:42:10Z","created_by":"Sam Catlow","updated_at":"2026-08-31T10:10:50Z","closed_at":"2026-08-31T10:10:50Z","close_reason":"Added internal/gateway, internal/tools, internal/memory, internal/secret, internal/plugin, internal/skill to ARCHITECTURE.md Package Map with LOC and role descriptions","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-p3wt","title":"P1: Fix recvcheck - mixed pointer/value receivers","description":"recvcheck found mixed pointer/value receivers on:\n- Duration\n- TaskEnvelope\n- Provenance\n\nThis is a latent mutation-semantics bug - methods may not behave correctly if they expect to mutate the receiver.\n\nNeed to:\n- Audit all methods on Duration, TaskEnvelope, Provenance\n- Standardize to either all pointer receivers or all value receivers\n- Prefer pointer receivers for types that need mutation\n- Verify no behavior changes after fix\n\nBlocked by: nothing","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-28T13:42:07Z","created_by":"Sam Catlow","updated_at":"2026-08-31T10:09:59Z","closed_at":"2026-08-31T10:09:59Z","close_reason":"Duration and TaskEnvelope were already consistent by the time this was picked up; fixed the remaining recvcheck violation on Provenance (Paths/String moved to pointer receiver to match the mutating record() method). All Provenance uses are through addressable struct fields, so build/tests are unaffected. recvcheck now reports 0 issues.","dependency_count":0,"dependent_count":0,"comment_count":0}
-{"_type":"issue","id":"archie-core-agui","title":"P1: Fix 31 golangci-lint issues","description":"31 golangci-lint issues clustered as high cyclomatic/cognitive complexity in:\n- internal/tools/builtin/find.go\n- internal/tools/builtin/grep.go\n- internal/tools/builtin/shell.go\n- internal/gateway/go:dispatchLocal\n\nThese are real refactor candidates, not noise.\n\nNeed to:\n- Review each issue to understand the complexity\n- Refactor functions to reduce cyclomatic complexity\n- Break down large functions into smaller, focused ones\n- Re-run golangci-lint to verify fixes\n\nBlocked by: nothing","notes":"Fixed cyclop findings (applyEdits, grepFallback, grepDirFallback, serveReadContent, handleChatStream) and several gocognit/funlen findings (TDD, runFindGoFallback, makeGrepExecutor, makeShellExecutor). Remaining: richblocks.go markdownToBlocks/blocksToPlainText (gocognit), gateway.go dispatchLocal (gocyclo), agent.go Stage (gocognit 70), turn.go Run (gocognit 53), tomlwrite.go Apply (gocognit 82), cronstore store.go Update (gocognit) + nestif x2, toolset.go nestif. 22 of original 31 findings remain unaddressed -- keeping open.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-28T13:42:04Z","created_by":"Sam Catlow","updated_at":"2026-08-31T11:27:16Z","dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-agui","title":"P1: Fix 31 golangci-lint issues","description":"31 golangci-lint issues clustered as high cyclomatic/cognitive complexity in:\n- internal/tools/builtin/find.go\n- internal/tools/builtin/grep.go\n- internal/tools/builtin/shell.go\n- internal/gateway/go:dispatchLocal\n\nThese are real refactor candidates, not noise.\n\nNeed to:\n- Review each issue to understand the complexity\n- Refactor functions to reduce cyclomatic complexity\n- Break down large functions into smaller, focused ones\n- Re-run golangci-lint to verify fixes\n\nBlocked by: nothing","notes":"Fixed cyclop findings (applyEdits, grepFallback, grepDirFallback, serveReadContent, handleChatStream) and several gocognit/funlen findings (TDD, runFindGoFallback, makeGrepExecutor, makeShellExecutor). Remaining: richblocks.go markdownToBlocks/blocksToPlainText (gocognit), gateway.go dispatchLocal (gocyclo), agent.go Stage (gocognit 70), turn.go Run (gocognit 53), tomlwrite.go Apply (gocognit 82), cronstore store.go Update (gocognit) + nestif x2, toolset.go nestif. 22 of original 31 findings remain unaddressed -- keeping open.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-28T13:42:04Z","created_by":"Sam Catlow","updated_at":"2026-08-31T11:36:17Z","closed_at":"2026-08-31T11:36:17Z","close_reason":"All 31 original findings (5 cyclop, 9 gocognit, 1 gocyclo, 2 nestif, plus incidental funlen) resolved via targeted extraction across tools/builtin, gateway, workflow, webui, telegram, cronstore, tomlwrite, agentexec. Remaining 6 lint findings (containedctx/errorlint/noctx/staticcheck) were never part of this bead's scope.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-k7y7","title":"P1: Address coverage gaps in load-bearing packages","description":"Coverage gaps in critical packages:\n- domain/workintake: 14.3%\n- secret/enginehost: 0%\n- secret/secretextract: 10%\n- forge: 35.8%\n- natsrpc: 28.3%\n\nNeed to:\n- Analyze why coverage is low in these packages\n- Add tests for uncovered code paths\n- Prioritize based on risk/criticality\n- Aim for at least 60-70% coverage in load-bearing packages\n\nBlocked by: nothing","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-28T13:42:01Z","created_by":"Sam Catlow","updated_at":"2026-08-31T11:27:21Z","closed_at":"2026-08-31T11:27:21Z","close_reason":"Raised coverage: workintake 14.3%-\u003e94.6%, secret/enginehost 0%-\u003e100%, secret/secretextract 10%-\u003e100%, forge 36.1%-\u003e77.0%, natsrpc 28.3%-\u003e91.3%. Committed as bc5b355.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-zq4l","title":"P1: Tighten CI go-version pinning","description":"CI's go-version is set to '1.26' (floating) while go.mod has exact 1.26.5. This loose coupling means CI could use 1.26.0-1.26.5 or newer minor versions, potentially missing bugs or compatibility issues.\n\nNeed to:\n- Pin CI go-version to exact match go.mod (currently 1.26.5, will be 1.26.6+ after P0 bump)\n- Consider using same variable/source of truth for both\n- Update CI configuration files\n\nBlocked by: Go version bump (archie-core-1sjk) for consistency","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-28T13:41:58Z","created_by":"Sam Catlow","updated_at":"2026-08-31T10:05:31Z","closed_at":"2026-08-31T10:05:31Z","close_reason":"Switched CI to actions/setup-go go-version-file: go.mod so CI's Go version is always sourced from go.mod directly, eliminating drift","dependencies":[{"issue_id":"archie-core-zq4l","depends_on_id":"archie-core-1sjk","type":"blocks","created_at":"2026-08-28T13:42:31Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-0bvr","title":"P1: Add govulncheck step to CI/Taskfile","description":"The 6 stdlib CVEs went undetected through normal task check because there's no govulncheck step anywhere in CI or Taskfile.\n\nNeed to:\n- Add govulncheck to Taskfile.yml (e.g., task vuln)\n- Consider adding to CI pipeline\n- Decide: should vuln check be part of task check or separate?\n- Document the new task\n\nBlocked by: nothing","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-28T13:41:54Z","created_by":"Sam Catlow","updated_at":"2026-08-31T10:05:53Z","closed_at":"2026-08-31T10:05:53Z","close_reason":"Added 'task vuln' (govulncheck) to Taskfile, deliberately kept out of task check since it needs network access to the vuln DB; wired as a separate CI step in deploy.yml","dependency_count":0,"dependent_count":0,"comment_count":0}
diff --git a/internal/app/agentworker/review.go b/internal/app/agentworker/review.go
new file mode 100644
index 000000000..b5e77759e
--- /dev/null
+++ b/internal/app/agentworker/review.go
@@ -0,0 +1,209 @@
+package agentworker
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/samcharles93/ai-sdk/agent"
+ "github.com/samcharles93/ai-sdk/core"
+ "github.com/samcharles93/ai-sdk/runtime"
+ "github.com/samcharles93/ai-sdk/toolkit"
+
+ "github.com/samcharles93/archie-core/internal/agentexec"
+ "github.com/samcharles93/archie-core/internal/domain/workflow"
+ "github.com/samcharles93/archie-core/internal/taskrun"
+)
+
+// newReviewerFor builds the workflow.Reviewer for one task run, or nil
+// when the repo has not opted into review (Repo.ReviewEnabled == false)
+// or no providers are configured. Model resolution mirrors AgentStage's
+// own role->"builder" fallback (agent.go): Models["reviewer"], falling
+// back to Models["builder"].
+func newReviewerFor(req taskrun.Request) workflow.Reviewer {
+ if !req.Repo.ReviewEnabled {
+ return nil
+ }
+ modelRef := req.Cfg.Models["reviewer"]
+ if modelRef == "" {
+ modelRef = req.Cfg.Models["builder"]
+ }
+ if modelRef == "" {
+ return nil
+ }
+ rt := agentexec.NewRuntime(req.Providers)
+ if rt == nil {
+ return nil
+ }
+ return newSubagentReviewer(rt, modelRef)
+}
+
+// defaultReviewMaxSteps bounds the reviewer's tool loop when neither
+// ReviewRequest.MaxSteps nor the repo's configured budget set one.
+const defaultReviewMaxSteps = 10
+
+// subagentReviewer implements workflow.Reviewer using ai-sdk's
+// agent.Subagent: a nested, synchronous generation in this same worker
+// process, with its own model, system prompt, toolset, and step budget.
+//
+// Isolation is two-fold. Conversation isolation is structural: Subagent.Run
+// only ever sends a prompt string, never the implementer's message
+// history. Workspace isolation is built by the caller (StageReview via
+// workflow.Trees.Snapshot): reviewerToolSet is rooted at that snapshot
+// directory and holds only read-only tools -- never the worker's own
+// toolset, which carries the worktreerpc publication grant a reviewer must
+// not be able to reach.
+type subagentReviewer struct {
+ runtime *runtime.Runtime
+ modelRef string
+}
+
+// newSubagentReviewer constructs a Reviewer that runs on modelRef, resolved
+// through rt (the same provider runtime the worker's own agent runner
+// uses). rt must be non-nil.
+func newSubagentReviewer(rt *runtime.Runtime, modelRef string) *subagentReviewer {
+ return &subagentReviewer{runtime: rt, modelRef: modelRef}
+}
+
+var _ workflow.Reviewer = (*subagentReviewer)(nil)
+
+// Review runs one adversarial review. It never returns a Go error: every
+// failure mode (unresolvable model, a Subagent.Run error, a truncated
+// run) folds into the returned ReviewReport, per
+// docs/prds/adversarial-self-review.md section 4's fail-closed contract.
+func (s *subagentReviewer) Review(ctx context.Context, req workflow.ReviewRequest) workflow.ReviewReport {
+ if s.runtime == nil {
+ return workflow.NewNotRunReviewReport("no provider runtime configured for the reviewer")
+ }
+ provider, model, err := s.runtime.ChatProvider(ctx, s.modelRef)
+ if err != nil {
+ return workflow.NewNotRunReviewReport(fmt.Sprintf("resolve reviewer model %q: %v", s.modelRef, err))
+ }
+
+ var findings []workflow.ReviewFinding
+ tools := reviewerToolSet(req.SnapshotDir, &findings)
+
+ maxSteps := req.MaxSteps
+ if maxSteps <= 0 {
+ maxSteps = defaultReviewMaxSteps
+ }
+
+ sub := agent.Subagent{
+ Provider: provider,
+ Model: model,
+ System: reviewerSystemPrompt,
+ Tools: tools,
+ MaxSteps: maxSteps,
+ }
+
+ summary, runErr := sub.Run(ctx, reviewerPrompt(req))
+ if runErr != nil {
+ // A truncated or errored run still yields whatever the reviewer
+ // captured before it ran out of budget -- those findings are real
+ // and must not be discarded just because the run's own
+ // conclusion never arrived (docs/prds/adversarial-self-review.md
+ // section 1, "findings return through a closure"). Zero captured
+ // findings on error means the reviewer never got anywhere, which
+ // fail-closed treats as not having run at all.
+ if len(findings) == 0 {
+ return workflow.NewNotRunReviewReport(runErr.Error())
+ }
+ return workflow.NewCompletedReviewReport(findings, "")
+ }
+ return workflow.NewCompletedReviewReport(findings, summary)
+}
+
+// reviewerSystemPrompt instructs the reviewer per CLAUDE.md's own
+// adversarial-review discipline: assume every line is wrong until proven
+// correct, work the checklist, report only what a fresh reader can verify
+// from what it was given.
+const reviewerSystemPrompt = `You are a fresh adversarial code reviewer. You did not write this change and have no access to how or why it was written -- only what is given to you below.
+
+Assume every line is wrong until you have verified it is correct. Read whole files with your read tool, not just diff hunks, before concluding a call site or interface is satisfied. Use grep/find to check for other call sites a change affects.
+
+Check for: dead code, unchecked errors, hardcoded values that should be parameters, interface-satisfaction defects, nil-pointer risk, goroutine leaks, races and unsynchronized shared state.
+
+For every defect you find, call record_finding with: the file and line, a one-sentence defect statement, a concrete failure scenario (specific inputs or state that produce the wrong output or a crash -- not a hypothetical), a verdict, a level, and a category.
+
+Verdict is "confirmed" only when you have traced the actual failure -- read the code paths involved and can state exactly how it goes wrong. Verdict is "plausible" for a real worry you have not fully traced. Only a "confirmed" finding at level "error" blocks the pull request; do not inflate a plausible worry to confirmed/error to make it count -- an unjustified block is worse than a missed one, because it teaches the operator to stop trusting your reports.
+
+Level is "error" for a defect that blocks; "warn" for something worth knowing but not blocking.
+
+When you have finished checking, reply with a short summary of what you checked and what you found (or that you found nothing). If you find nothing, say so plainly -- reporting zero findings on properties you actually checked is a valid and expected outcome, not a failure to find something.`
+
+// reviewerPrompt renders the reviewer's mission: the diff and issue text.
+// The snapshot itself is not embedded here -- it reaches the reviewer only
+// through its read-only toolset, rooted at SnapshotDir, never as prompt
+// text the reviewer could mistake for something it already checked.
+func reviewerPrompt(req workflow.ReviewRequest) string {
+ var b strings.Builder
+ b.WriteString("Review the following change. The full file tree at the reviewed commit is available through your tools; ")
+ b.WriteString("start by reading the files the diff touches, not just the diff itself.\n\n")
+ b.WriteString("\n")
+ b.WriteString(req.IssueText)
+ b.WriteString("\n\n\n\n")
+ b.WriteString(req.Diff)
+ b.WriteString("\n\n")
+ return b.String()
+}
+
+// reviewerToolSet builds the reviewer's read-only toolset, rooted at
+// snapshotDir, plus the structured findings-capture tool that appends
+// directly to findings. This is a distinct toolset built fresh for each
+// review -- never the worker's own registry, which holds write/edit/shell
+// tools and the worktreerpc publication grant.
+func reviewerToolSet(snapshotDir string, findings *[]workflow.ReviewFinding) core.ToolSet {
+ reg := toolkit.NewRegistry()
+ readOnly := []toolkit.Tool{
+ toolkit.NewReadTool(snapshotDir, toolkit.NewReadTracker()),
+ toolkit.NewGrepTool(snapshotDir),
+ toolkit.NewFindTool(snapshotDir),
+ }
+ for _, tool := range readOnly {
+ _ = reg.Register(tool) // names are fixed and distinct; Register cannot fail here
+ }
+ set := reg.CoreToolSet(toolkit.NonInteractiveBridge{})
+ set["record_finding"] = recordFindingTool(findings)
+ return set
+}
+
+// findingInput is the reviewer-facing shape of workflow.ReviewFinding: the
+// model reports plain strings for Verdict/Level/Category, validated and
+// converted before being appended.
+type findingInput struct {
+ File string `json:"file" jsonschema:"description=Repo-relative file path where the defect is located."`
+ Line int `json:"line" jsonschema:"description=Line number where the defect is located."`
+ Defect string `json:"defect" jsonschema:"description=One-sentence statement of the defect."`
+ FailureScenario string `json:"failure_scenario" jsonschema:"description=Concrete inputs or state that produce the wrong output or a crash -- not a hypothetical."`
+ Verdict string `json:"verdict" jsonschema:"description=Only 'confirmed' may block. Use 'plausible' for a real worry you have not fully traced.,enum=confirmed|plausible"`
+ Level string `json:"level" jsonschema:"description=error blocks when confirmed; warn is advisory only.,enum=error|warn"`
+ Category string `json:"category" jsonschema:"enum=dead-code|unchecked-error|hardcoded-value|interface-satisfaction|nil-risk|goroutine-leak|race|other"`
+}
+
+// recordFindingTool builds the typed capture tool the reviewer must call
+// to report a defect. Rejecting an invalid finding with a plain-text
+// message (rather than a Go error) lets the model see what was wrong and
+// retry, the same environmental-enforcement pattern the rest of the
+// agent-loop tool contract uses.
+func recordFindingTool(findings *[]workflow.ReviewFinding) *core.Tool {
+ return core.NewTypedTool(
+ "record_finding",
+ "Report one defect found during review. Call this once per defect; do not summarize multiple defects into one call.",
+ func(_ context.Context, in findingInput) (string, error) {
+ finding := workflow.ReviewFinding{
+ File: in.File,
+ Line: in.Line,
+ Defect: in.Defect,
+ FailureScenario: in.FailureScenario,
+ Verdict: workflow.ReviewVerdict(in.Verdict),
+ Level: workflow.ReviewLevel(in.Level),
+ Category: workflow.ReviewCategory(in.Category),
+ }
+ if err := finding.Validate(); err != nil {
+ return "record_finding rejected: " + err.Error(), nil //nolint:nilerr // rejection feedback lets the model retry with a valid finding
+ }
+ *findings = append(*findings, finding)
+ return "finding recorded", nil
+ },
+ )
+}
diff --git a/internal/app/agentworker/review_test.go b/internal/app/agentworker/review_test.go
new file mode 100644
index 000000000..cb1cff1bd
--- /dev/null
+++ b/internal/app/agentworker/review_test.go
@@ -0,0 +1,201 @@
+package agentworker
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "github.com/samcharles93/ai-sdk/agent"
+ "github.com/samcharles93/ai-sdk/chat"
+
+ "github.com/samcharles93/archie-core/internal/domain/workflow"
+)
+
+// TestReviewerToolSetIsReadOnlyAndHasNoMutationPath asserts, as a
+// construction fact rather than a prompt claim, that the reviewer's
+// toolset carries no tool capable of writing, editing, or running a
+// shell command -- the class of tool that could reach the worktreerpc
+// publication grant or otherwise mutate anything. Read/grep/find plus the
+// findings-capture tool are the entire surface.
+func TestReviewerToolSetIsReadOnlyAndHasNoMutationPath(t *testing.T) {
+ var findings []workflow.ReviewFinding
+ set := reviewerToolSet(t.TempDir(), &findings)
+
+ names := make([]string, 0, len(set))
+ for name := range set {
+ names = append(names, name)
+ }
+ slices.Sort(names)
+
+ want := []string{"find", "grep", "read", "record_finding"}
+ slices.Sort(want)
+ if !slices.Equal(names, want) {
+ t.Fatalf("reviewer toolset = %v, want exactly %v (no write/edit/shell)", names, want)
+ }
+}
+
+// TestReviewerToolSetIsRootedAtTheGivenSnapshot asserts the read tool
+// cannot read outside the snapshot directory it was constructed with --
+// it has no path back to the implementer's actual worktree.
+func TestReviewerToolSetIsRootedAtTheGivenSnapshot(t *testing.T) {
+ snapshot := t.TempDir()
+ if err := os.WriteFile(filepath.Join(snapshot, "in-snapshot.txt"), []byte("ok\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ outside := t.TempDir()
+ if err := os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("nope\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ var findings []workflow.ReviewFinding
+ set := reviewerToolSet(snapshot, &findings)
+ readTool := set["read"]
+ if readTool == nil {
+ t.Fatal("reviewer toolset has no read tool")
+ }
+
+ out, err := readTool.Execute(t.Context(), `{"path":"in-snapshot.txt"}`)
+ if err != nil {
+ t.Fatalf("read in-snapshot file: %v", err)
+ }
+ if !containsSubstr(out, "ok") {
+ t.Errorf("read in-snapshot file = %q, want it to contain the file's content", out)
+ }
+
+ // Tool failures are encoded in-band in the returned content, not as a
+ // Go error (toolkit.Registry.CoreToolSet's own contract) -- an escape
+ // attempt must reject there, not succeed.
+ escapeOut, err := readTool.Execute(t.Context(), `{"path":"`+filepath.Join(outside, "secret.txt")+`"}`)
+ if err != nil {
+ t.Fatalf("read outside-snapshot path: %v", err)
+ }
+ if containsSubstr(escapeOut, "nope") {
+ t.Errorf("read tool returned content from outside the snapshot: %q", escapeOut)
+ }
+ if !containsSubstr(escapeOut, "escapes") {
+ t.Errorf("read tool output = %q, want a path-confinement rejection", escapeOut)
+ }
+}
+
+// TestRecordFindingToolAppendsToCapturedSlice asserts the capture-tool
+// contract: findings are recorded via the closure over the findings
+// slice, not returned from Subagent.Run's text.
+func TestRecordFindingToolAppendsToCapturedSlice(t *testing.T) {
+ var findings []workflow.ReviewFinding
+ tool := recordFindingTool(&findings)
+
+ input := `{"file":"main.go","line":10,"defect":"nil deref","failure_scenario":"calling Foo(nil) panics","verdict":"confirmed","level":"error","category":"nil-risk"}`
+ if _, err := tool.Execute(t.Context(), input); err != nil {
+ t.Fatalf("record_finding: %v", err)
+ }
+ if len(findings) != 1 {
+ t.Fatalf("captured %d findings, want 1", len(findings))
+ }
+ if !findings[0].Blocking() {
+ t.Error("captured finding is not blocking, want confirmed+error to block")
+ }
+}
+
+// TestRecordFindingToolRejectsInvalidVerdictWithoutError asserts an
+// invalid finding is rejected in-band (so the model can retry) rather
+// than surfacing as a hard tool error, and is not captured.
+func TestRecordFindingToolRejectsInvalidVerdictWithoutError(t *testing.T) {
+ var findings []workflow.ReviewFinding
+ tool := recordFindingTool(&findings)
+
+ input := `{"file":"main.go","line":1,"defect":"x","failure_scenario":"y","verdict":"maybe","level":"error","category":"other"}`
+ out, err := tool.Execute(t.Context(), input)
+ if err != nil {
+ t.Fatalf("record_finding returned a Go error for invalid input: %v", err)
+ }
+ if !containsSubstr(out, "rejected") {
+ t.Errorf("record_finding output = %q, want a rejection message", out)
+ }
+ if len(findings) != 0 {
+ t.Errorf("captured %d findings, want 0 for an invalid finding", len(findings))
+ }
+}
+
+// TestReviewSubagentConstructionNeverSendsConversationHistory asserts, at
+// the exact agent.Subagent construction Review performs, that only a
+// prompt string reaches the model. This exercises the same Subagent{}
+// shape subagentReviewer.Review builds (provider, model, system prompt,
+// reviewerToolSet, MaxSteps) directly against a fake chat.Provider, so it
+// proves the construction fact without needing a full *runtime.Runtime:
+// Subagent.Run populates GenerateOptions.Prompt and never Messages, so
+// there is no code path for the implementer's transcript to travel
+// through.
+func TestReviewSubagentConstructionNeverSendsConversationHistory(t *testing.T) {
+ captured := &capturingChatProvider{}
+ var findings []workflow.ReviewFinding
+ req := workflow.ReviewRequest{
+ SnapshotDir: t.TempDir(),
+ Diff: "diff --git a/x.go b/x.go\n",
+ IssueText: "some issue text",
+ }
+
+ sub := agent.Subagent{
+ Provider: captured,
+ Model: "fake-model",
+ System: reviewerSystemPrompt,
+ Tools: reviewerToolSet(req.SnapshotDir, &findings),
+ MaxSteps: defaultReviewMaxSteps,
+ }
+ prompt := reviewerPrompt(req)
+ if _, err := sub.Run(t.Context(), prompt); err != nil {
+ t.Fatalf("Subagent.Run() error = %v", err)
+ }
+
+ if captured.lastRequest == nil {
+ t.Fatal("chat provider was never called")
+ }
+ // The only non-system message the model ever sees is the one
+ // Subagent.Run derives from the prompt string -- there is no code
+ // path here for a second, implementer-authored message to arrive
+ // alongside it.
+ var userMessages int
+ for _, m := range captured.lastRequest.Messages {
+ if m.Role == chat.RoleUser {
+ userMessages++
+ if m.Content != prompt {
+ t.Errorf("user message content = %q, want the review prompt %q", m.Content, prompt)
+ }
+ }
+ }
+ if userMessages != 1 {
+ t.Errorf("chat.Request carried %d user messages, want exactly 1 (the review prompt, no implementer history)", userMessages)
+ }
+}
+
+func containsSubstr(s, substr string) bool {
+ return len(substr) == 0 ||
+ (len(s) >= len(substr) && func() bool {
+ for i := 0; i+len(substr) <= len(s); i++ {
+ if s[i:i+len(substr)] == substr {
+ return true
+ }
+ }
+ return false
+ }())
+}
+
+// capturingChatProvider is a minimal chat.Provider fake that records the
+// last chat.Request it received and returns a fixed, valid completion.
+type capturingChatProvider struct {
+ lastRequest *chat.Request
+}
+
+func (c *capturingChatProvider) Name() string { return "fake" }
+
+func (c *capturingChatProvider) Chat(_ context.Context, req chat.Request) (chat.Response, error) {
+ r := req
+ c.lastRequest = &r
+ return chat.Response{Content: "no findings", FinishReason: "stop"}, nil
+}
+
+func (c *capturingChatProvider) ChatStream(_ context.Context, req chat.Request) (chat.Stream, error) {
+ return nil, errors.New("not implemented")
+}
diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go
index 7ccdcc719..4ee9e8486 100644
--- a/internal/app/agentworker/task_execution.go
+++ b/internal/app/agentworker/task_execution.go
@@ -83,6 +83,10 @@ func (h *hybridTrees) ChangedFiles(ctx context.Context, dir, base string) ([]str
return h.local.ChangedFiles(ctx, dir, base)
}
+func (h *hybridTrees) Snapshot(ctx context.Context, dir, destDir string) error {
+ return h.local.Snapshot(ctx, dir, destDir)
+}
+
func (h *hybridTrees) ChangedLines(ctx context.Context, dir, base string) (int, error) {
return h.local.ChangedLines(ctx, dir, base)
}
@@ -205,6 +209,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
Store: dependencies.store,
Trees: trees,
Agent: agent,
+ Reviewer: newReviewerFor(req),
Bus: bus,
Log: log,
CustomStages: wfeval.Discover,
diff --git a/internal/config/config.go b/internal/config/config.go
index 11adcee38..c017dc180 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -96,6 +96,13 @@ type Repo struct {
// won't collide (e.g. different base branches or packages per
// task). Still bounded by [containers].max_concurrency globally.
AllowConcurrent bool `toml:"allow_concurrent" json:"allow_concurrent" yaml:"allow_concurrent"`
+ // ReviewEnabled opts this repo into the adversarial self-review stage
+ // (docs/prds/adversarial-self-review.md): a fresh reviewer agent, with
+ // no path to the implementer's context, runs after gates pass and
+ // before the PR opens. Default false -- an uncalibrated reviewer that
+ // cries wolf is worse than no review, so a repo opts in once it
+ // trusts the stage.
+ ReviewEnabled bool `toml:"review_enabled" json:"review_enabled" yaml:"review_enabled"`
}
// Protected reports whether path matches a protected suffix.
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index 0ca4bd1fa..6b7fd5ca2 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -204,6 +204,7 @@ func TestRepoJSONRoundTrip(t *testing.T) {
PersistentStorage: true,
MaxRetries: 4,
AllowConcurrent: true,
+ ReviewEnabled: true,
}
data, err := json.Marshal(repo)
@@ -223,6 +224,7 @@ func TestRepoJSONRoundTrip(t *testing.T) {
"persistent_storage",
"max_retries",
"allow_concurrent",
+ "review_enabled",
)
var got Repo
diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go
index fddf9d820..f73680b27 100644
--- a/internal/domain/workflow/implement.go
+++ b/internal/domain/workflow/implement.go
@@ -186,6 +186,7 @@ func Implement() Workflow {
}),
StageYaegiGate(),
StageDiffCap(),
+ StageReview(),
StageOpenPR(func(tc *TaskContext) string {
return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %d tokens*",
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
diff --git a/internal/domain/workflow/review.go b/internal/domain/workflow/review.go
new file mode 100644
index 000000000..1f386ce38
--- /dev/null
+++ b/internal/domain/workflow/review.go
@@ -0,0 +1,125 @@
+package workflow
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/samcharles93/archie-core/internal/store"
+)
+
+// Reviewer runs an adversarial review of a code snapshot in its own
+// isolated context and reports what it found. Implementations must give
+// the reviewer no path to the implementer's conversation, credentials, or
+// git history -- see docs/prds/adversarial-self-review.md. A reviewer that
+// errors, is truncated, or reaches no conclusion returns a ReviewReport
+// with Status == ReviewStatusNotRun rather than a Go error: the stage
+// always has a report to act on, and "did not run" is a first-class
+// outcome, not a special case.
+type Reviewer interface {
+ Review(ctx context.Context, req ReviewRequest) ReviewReport
+}
+
+// ReviewRequest is everything an adversarial reviewer is given: a
+// .git-free snapshot of the reviewed commit's tracked files, the diff that
+// produced it, and the originating issue text. Nothing else -- commit
+// messages, branch name, reflog, and the implementer's own transcript are
+// structurally excluded, not merely withheld by instruction.
+type ReviewRequest struct {
+ // SnapshotDir is a filesystem directory containing HEAD's tracked
+ // files with no .git present.
+ SnapshotDir string
+ Diff string
+ IssueText string
+ // MaxSteps bounds the reviewer's tool-loop iterations. 0 means the
+ // implementation's own default.
+ MaxSteps int
+}
+
+// reviewDetailBytes bounds how much of a park Detail the rendered review
+// findings occupy, matching the store's own park-reason cap headroom (see
+// baselineParkOutputBytes in implement.go).
+const reviewDetailBytes = 4000
+
+// StageReview runs the adversarial self-review stage. It is a no-op unless
+// Repo.ReviewEnabled is true. A surviving confirmed error-level finding, or
+// a review that failed to run at all, parks the task (store.StatusParked)
+// with the findings in Detail and stops the workflow before StageOpenPR;
+// a clean pass, or only warn/plausible findings, leaves Outcome unset so
+// the workflow proceeds.
+func StageReview() Stage {
+ return Stage{Name: "review", Run: func(ctx context.Context, tc *TaskContext) error {
+ if !tc.Repo.ReviewEnabled {
+ return nil
+ }
+ if tc.Reviewer == nil {
+ tc.Outcome = Outcome{
+ Status: store.StatusParked,
+ Detail: "adversarial review is enabled (review_enabled) but no reviewer is configured",
+ }
+ return nil
+ }
+
+ report, err := runReview(ctx, tc)
+ if err != nil {
+ return fmt.Errorf("review: %w", err)
+ }
+ if !report.Passed() {
+ tc.Outcome = Outcome{Status: store.StatusParked, Detail: renderReviewDetail(report)}
+ }
+ return nil
+ }}
+}
+
+// runReview builds the reviewer's isolated snapshot, diff and issue text,
+// invokes tc.Reviewer, and cleans up the snapshot regardless of outcome.
+func runReview(ctx context.Context, tc *TaskContext) (ReviewReport, error) {
+ diff, err := tc.Trees.Diff(ctx, tc.Dir, tc.Repo.BaseBranch())
+ if err != nil {
+ return ReviewReport{}, fmt.Errorf("compute diff: %w", err)
+ }
+
+ // Beside, not inside, the task worktree: a snapshot inside tc.Dir
+ // would itself be an untracked, .git-adjacent directory the next
+ // commit or gate run could pick up.
+ snapshotDir, err := os.MkdirTemp(filepath.Dir(tc.Dir), "review-snapshot-*")
+ if err != nil {
+ return ReviewReport{}, fmt.Errorf("create review snapshot directory: %w", err)
+ }
+ defer os.RemoveAll(snapshotDir)
+
+ if err := tc.Trees.Snapshot(ctx, tc.Dir, snapshotDir); err != nil {
+ return ReviewReport{}, fmt.Errorf("snapshot worktree for review: %w", err)
+ }
+
+ req := ReviewRequest{
+ SnapshotDir: snapshotDir,
+ Diff: diff,
+ IssueText: taskPromptBlock(tc.Task),
+ MaxSteps: tc.Cfg.Budgets.MaxSteps,
+ }
+ return tc.Reviewer.Review(ctx, req), nil
+}
+
+// renderReviewDetail formats a review report as a park Detail: why the
+// task stopped, and what a human (or a retry) needs to know.
+func renderReviewDetail(report ReviewReport) string {
+ if !report.Ran() {
+ reason := report.SkipReason
+ if reason == "" {
+ reason = "no reason given"
+ }
+ return clip("adversarial review did not run -- "+reason, reviewDetailBytes)
+ }
+ var b strings.Builder
+ b.WriteString("adversarial review found blocking defects:\n")
+ for _, f := range report.Findings {
+ if !f.Blocking() {
+ continue
+ }
+ fmt.Fprintf(&b, "- %s:%d %s (%s)\n", f.File, f.Line, f.Defect, f.FailureScenario)
+ }
+ return clip(b.String(), reviewDetailBytes)
+}
diff --git a/internal/domain/workflow/review_test.go b/internal/domain/workflow/review_test.go
new file mode 100644
index 000000000..74fefe057
--- /dev/null
+++ b/internal/domain/workflow/review_test.go
@@ -0,0 +1,204 @@
+package workflow
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/samcharles93/archie-core/internal/config"
+ "github.com/samcharles93/archie-core/internal/store"
+ "github.com/samcharles93/archie-core/internal/worktree"
+)
+
+// fakeReviewer records the request it was given and returns a canned
+// report, standing in for the app-layer agent.Subagent-backed Reviewer.
+//
+// It reads what it needs from req.SnapshotDir synchronously, inside
+// Review, because the stage cleans the snapshot up as soon as Review
+// returns -- a real Reviewer implementation faces the same constraint.
+type fakeReviewer struct {
+ gotRequest ReviewRequest
+ snapshotContent string
+ snapshotHadGit bool
+ called bool
+ report ReviewReport
+}
+
+func (f *fakeReviewer) Review(_ context.Context, req ReviewRequest) ReviewReport {
+ f.called = true
+ f.gotRequest = req
+ if content, err := os.ReadFile(filepath.Join(req.SnapshotDir, "feature.go")); err == nil {
+ f.snapshotContent = string(content)
+ }
+ if _, err := os.Stat(filepath.Join(req.SnapshotDir, ".git")); err == nil {
+ f.snapshotHadGit = true
+ }
+ return f.report
+}
+
+// reviewTaskContext builds a TaskContext over a real git repo with a
+// tracked, committed change against base, so StageReview's Diff/Snapshot
+// calls have real content to work with.
+func reviewTaskContext(t *testing.T, enabled bool) (*TaskContext, string) {
+ t.Helper()
+ dir := gitRepoWithOriginRef(t, "main")
+ if err := os.WriteFile(filepath.Join(dir, "feature.go"), []byte("package main\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ runGit(t, dir, "add", "-A")
+ runGit(t, dir, "commit", "-m", "feat: add feature.go")
+
+ tc := &TaskContext{
+ Task: &store.Task{ID: 1, Owner: "acme", Repo: "todo", IssueNumber: 42, Title: "Add feature", Body: "Please add it."},
+ Repo: config.Repo{Owner: "acme", Name: "todo", Base: "main", ReviewEnabled: enabled},
+ Cfg: config.Config{},
+ Trees: &worktree.Manager{WorkDir: t.TempDir()},
+ Dir: dir,
+ Log: slog.New(slog.DiscardHandler),
+ }
+ return tc, dir
+}
+
+func TestStageReviewIsInertUnlessEnabled(t *testing.T) {
+ tc, _ := reviewTaskContext(t, false)
+ reviewer := &fakeReviewer{}
+ tc.Reviewer = reviewer
+
+ if err := StageReview().Run(t.Context(), tc); err != nil {
+ t.Fatalf("StageReview().Run() error = %v", err)
+ }
+ if reviewer.called {
+ t.Error("StageReview called the reviewer despite Repo.ReviewEnabled == false")
+ }
+ if tc.Outcome.Status != "" {
+ t.Errorf("Outcome.Status = %q, want unset", tc.Outcome.Status)
+ }
+}
+
+func TestStageReviewParksWhenEnabledWithNoReviewerWired(t *testing.T) {
+ tc, _ := reviewTaskContext(t, true)
+ tc.Reviewer = nil
+
+ if err := StageReview().Run(t.Context(), tc); err != nil {
+ t.Fatalf("StageReview().Run() error = %v", err)
+ }
+ if tc.Outcome.Status != store.StatusParked {
+ t.Errorf("Outcome.Status = %q, want %q", tc.Outcome.Status, store.StatusParked)
+ }
+}
+
+func TestStageReviewParksFailClosedWhenReviewDidNotRun(t *testing.T) {
+ tc, _ := reviewTaskContext(t, true)
+ reviewer := &fakeReviewer{report: NewNotRunReviewReport("provider outage")}
+ tc.Reviewer = reviewer
+
+ if err := StageReview().Run(t.Context(), tc); err != nil {
+ t.Fatalf("StageReview().Run() error = %v", err)
+ }
+ if !reviewer.called {
+ t.Fatal("reviewer was not called")
+ }
+ if tc.Outcome.Status != store.StatusParked {
+ t.Errorf("Outcome.Status = %q, want %q", tc.Outcome.Status, store.StatusParked)
+ }
+ if got := tc.Outcome.Detail; !containsAll(got, "did not run", "provider outage") {
+ t.Errorf("Outcome.Detail = %q, want it to say the review did not run and why", got)
+ }
+}
+
+func TestStageReviewParksOnConfirmedErrorFinding(t *testing.T) {
+ tc, _ := reviewTaskContext(t, true)
+ blocking := ReviewFinding{
+ File: "feature.go", Line: 1, Defect: "nil deref",
+ FailureScenario: "calling Foo(nil) panics",
+ Verdict: ReviewVerdictConfirmed, Level: ReviewLevelError, Category: ReviewCategoryNilRisk,
+ }
+ reviewer := &fakeReviewer{report: NewCompletedReviewReport([]ReviewFinding{blocking}, "found one defect")}
+ tc.Reviewer = reviewer
+
+ if err := StageReview().Run(t.Context(), tc); err != nil {
+ t.Fatalf("StageReview().Run() error = %v", err)
+ }
+ if tc.Outcome.Status != store.StatusParked {
+ t.Errorf("Outcome.Status = %q, want %q", tc.Outcome.Status, store.StatusParked)
+ }
+ if got := tc.Outcome.Detail; !containsAll(got, "feature.go", "nil deref") {
+ t.Errorf("Outcome.Detail = %q, want the blocking finding rendered", got)
+ }
+}
+
+func TestStageReviewDoesNotBlockOnWarnOrPlausibleFindings(t *testing.T) {
+ tc, _ := reviewTaskContext(t, true)
+ findings := []ReviewFinding{
+ {
+ File: "feature.go", Line: 1, Defect: "could be tidier",
+ FailureScenario: "n/a", Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn,
+ Category: ReviewCategoryOther,
+ },
+ {
+ File: "feature.go", Line: 2, Defect: "maybe a race",
+ FailureScenario: "under heavy concurrency", Verdict: ReviewVerdictPlausible, Level: ReviewLevelError,
+ Category: ReviewCategoryRace,
+ },
+ }
+ reviewer := &fakeReviewer{report: NewCompletedReviewReport(findings, "found two non-blocking findings")}
+ tc.Reviewer = reviewer
+
+ if err := StageReview().Run(t.Context(), tc); err != nil {
+ t.Fatalf("StageReview().Run() error = %v", err)
+ }
+ if tc.Outcome.Status != "" {
+ t.Errorf("Outcome.Status = %q, want unset (non-blocking findings must not park)", tc.Outcome.Status)
+ }
+}
+
+func TestStageReviewGivesReviewerAnIsolatedSnapshotDiffAndIssueText(t *testing.T) {
+ tc, dir := reviewTaskContext(t, true)
+ reviewer := &fakeReviewer{report: NewCompletedReviewReport(nil, "clean")}
+ tc.Reviewer = reviewer
+
+ if err := StageReview().Run(t.Context(), tc); err != nil {
+ t.Fatalf("StageReview().Run() error = %v", err)
+ }
+ if !reviewer.called {
+ t.Fatal("reviewer was not called")
+ }
+ req := reviewer.gotRequest
+
+ if req.SnapshotDir == "" {
+ t.Fatal("ReviewRequest.SnapshotDir is empty")
+ }
+ if req.SnapshotDir == dir {
+ t.Errorf("ReviewRequest.SnapshotDir = %q reuses the task worktree; want a distinct snapshot", req.SnapshotDir)
+ }
+ if reviewer.snapshotContent != "package main\n" {
+ t.Errorf("snapshotted feature.go = %q, want %q", reviewer.snapshotContent, "package main\n")
+ }
+ if reviewer.snapshotHadGit {
+ t.Error("ReviewRequest.SnapshotDir contains .git, want it stripped")
+ }
+ if req.Diff == "" {
+ t.Error("ReviewRequest.Diff is empty, want the feature.go diff")
+ }
+ if !containsAll(req.IssueText, "Add feature", "Please add it.") {
+ t.Errorf("ReviewRequest.IssueText = %q, want it to contain the task title and body", req.IssueText)
+ }
+
+ // The snapshot is scratch, cleaned up once the stage returns -- it
+ // must not leak into the task worktree's directory tree permanently.
+ if _, err := os.Stat(req.SnapshotDir); !os.IsNotExist(err) {
+ t.Errorf("ReviewRequest.SnapshotDir %q still exists after the stage returned, want it cleaned up", req.SnapshotDir)
+ }
+}
+
+func containsAll(s string, substrs ...string) bool {
+ for _, sub := range substrs {
+ if !strings.Contains(s, sub) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go
index 84f202876..11fa7d0fa 100644
--- a/internal/domain/workflow/workflow.go
+++ b/internal/domain/workflow/workflow.go
@@ -42,6 +42,11 @@ type Trees interface {
Diff(ctx context.Context, dir, base string) (string, error)
ChangedFiles(ctx context.Context, dir, base string) ([]string, error)
ChangedLines(ctx context.Context, dir, base string) (int, error)
+ // Snapshot exports HEAD's tracked files into destDir with no .git
+ // directory -- no commit history, branch name, or reflog. Used to
+ // build the adversarial reviewer's isolated workspace (see
+ // docs/prds/adversarial-self-review.md).
+ Snapshot(ctx context.Context, dir, destDir string) error
}
// TaskContext carries everything a stage may need. Stages communicate
@@ -55,8 +60,13 @@ type TaskContext struct {
Store store.WorkflowStore
Trees Trees
Agent agentexec.Runner
- Bus *events.Bus // nil-safe via Emit
- Log *slog.Logger
+ // Reviewer runs the adversarial self-review stage (StageReview). Nil
+ // is only safe when Repo.ReviewEnabled is false; StageReview parks
+ // rather than silently skipping if it is enabled with no Reviewer
+ // wired.
+ Reviewer Reviewer
+ Bus *events.Bus // nil-safe via Emit
+ Log *slog.Logger
// CustomStages discovers a repo's per-repo custom stages (Yaegi-
// interpreted from .archie/stages/*.go in the given worktree
// directory), returning them in the order they should run. Application
diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go
index 35dfb719f..7d374c403 100644
--- a/internal/worktree/worktree.go
+++ b/internal/worktree/worktree.go
@@ -22,6 +22,7 @@ import (
"encoding/base64"
"errors"
"fmt"
+ "io"
"log/slog"
"os"
"path/filepath"
@@ -596,6 +597,74 @@ func (m *Manager) ChangedFiles(ctx context.Context, dir, base string) ([]string,
return files, nil
}
+// Snapshot exports HEAD's tracked files into a fresh, empty destDir with no
+// .git directory: file contents only, no commit history, branch name, or
+// reflog. Used to build the adversarial reviewer's isolated workspace
+// (docs/prds/adversarial-self-review.md section 1) -- stripping .git is
+// what makes the implementer's reasoning (commit messages, branch name,
+// history) structurally unreachable rather than merely undisclosed.
+func (m *Manager) Snapshot(ctx context.Context, dir, destDir string) error {
+ r, err := git.PlainOpen(dir)
+ if err != nil {
+ return fmt.Errorf("open worktree: %w", err)
+ }
+ head, err := r.Head()
+ if err != nil {
+ return fmt.Errorf("resolve HEAD: %w", err)
+ }
+ commit, err := r.CommitObject(head.Hash())
+ if err != nil {
+ return fmt.Errorf("load HEAD commit: %w", err)
+ }
+ tree, err := commit.Tree()
+ if err != nil {
+ return fmt.Errorf("load HEAD tree: %w", err)
+ }
+
+ if err := os.MkdirAll(destDir, 0o755); err != nil {
+ return fmt.Errorf("create snapshot directory: %w", err)
+ }
+
+ files := tree.Files()
+ defer files.Close()
+ for {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ file, iterErr := files.Next()
+ if errors.Is(iterErr, io.EOF) {
+ break
+ }
+ if iterErr != nil {
+ return fmt.Errorf("walk HEAD tree: %w", iterErr)
+ }
+ if err := writeSnapshotFile(destDir, file); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// writeSnapshotFile writes one tracked file's blob content to destDir,
+// preserving its relative path and creating parent directories as needed.
+func writeSnapshotFile(destDir string, file *object.File) error {
+ target := filepath.Join(destDir, filepath.FromSlash(file.Name))
+ if rel, relErr := filepath.Rel(destDir, target); relErr != nil || strings.HasPrefix(rel, "..") {
+ return fmt.Errorf("snapshot: tracked path %q escapes destination", file.Name)
+ }
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ return fmt.Errorf("create snapshot subdirectory for %s: %w", file.Name, err)
+ }
+ contents, err := file.Contents()
+ if err != nil {
+ return fmt.Errorf("read tracked file %s: %w", file.Name, err)
+ }
+ if err := os.WriteFile(target, []byte(contents), 0o644); err != nil {
+ return fmt.Errorf("write snapshot file %s: %w", file.Name, err)
+ }
+ return nil
+}
+
// Cleanup removes a task's worktree (merged/rejected); parked worktrees
// are kept for post-mortems.
func (m *Manager) Cleanup(owner, repo string, issue int) error {
diff --git a/internal/worktree/worktree_test.go b/internal/worktree/worktree_test.go
index 9a762b7c9..18ff79142 100644
--- a/internal/worktree/worktree_test.go
+++ b/internal/worktree/worktree_test.go
@@ -494,6 +494,42 @@ func TestOperationsOnNonRepository(t *testing.T) {
// The diff must be measured from the merge base, not from the remote tip.
// Otherwise commits landed on the base branch after the task started are
// attributed to the task and can trip the diff-size cap.
+func TestSnapshotExportsTrackedFilesWithoutGit(t *testing.T) {
+ ctx := context.Background()
+ host := newLocalRemote(t, "acme", "todo")
+ m := newManager(t, host)
+
+ dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "feat: snapshot me", "", "feature")
+ if err != nil {
+ t.Fatalf("Prepare() error = %v", err)
+ }
+ if err := os.MkdirAll(filepath.Join(dir, "pkg"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "pkg", "file.go"), []byte("package pkg\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := m.CommitAll(ctx, dir, "feat: add pkg/file.go"); err != nil {
+ t.Fatalf("CommitAll() error = %v", err)
+ }
+
+ dest := filepath.Join(t.TempDir(), "snapshot")
+ if err := m.Snapshot(ctx, dir, dest); err != nil {
+ t.Fatalf("Snapshot() error = %v", err)
+ }
+
+ content, err := os.ReadFile(filepath.Join(dest, "pkg", "file.go"))
+ if err != nil {
+ t.Fatalf("read snapshotted file: %v", err)
+ }
+ if string(content) != "package pkg\n" {
+ t.Errorf("snapshotted content = %q, want %q", content, "package pkg\n")
+ }
+ if _, err := os.Stat(filepath.Join(dest, ".git")); !os.IsNotExist(err) {
+ t.Errorf("Snapshot() destination contains .git, want it stripped (stat err = %v)", err)
+ }
+}
+
func TestDiffUsesMergeBaseNotRemoteTip(t *testing.T) {
ctx := context.Background()
host := newLocalRemote(t, "acme", "todo")