From 4c3ab8c6601939e1d7abec2c60f1a242aa7dd5d4 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 10:56:43 +1300 Subject: [PATCH] Expose retained lane holds and parse additional-only reviews --- docs/mcp.md | 1 + docs/provider-observations.md | 2 + docs/review-lane-diagnostics.md | 19 + docs/review-scheduling.md | 2 + internal/cli/review_lane_diagnostic_test.go | 25 + internal/cli/review_scheduling.go | 19 +- internal/cli/review_scheduling_help.go | 8 +- internal/client/review_lane_diagnostic.go | 66 +++ .../client/review_lane_diagnostic_test.go | 71 +++ internal/mcpadapter/adapter_test.go | 1 + .../mcpadapter/review_lane_diagnostic_test.go | 47 ++ internal/mcpadapter/review_scheduling.go | 13 +- internal/mcpadapter/tools.go | 2 + internal/reviewexec/front_evaluator.go | 73 ++- internal/reviewexec/lane_diagnostic.go | 133 ++++++ internal/reviewexec/lane_diagnostic_http.go | 24 + internal/reviewexec/lane_diagnostic_test.go | 202 ++++++++ internal/reviewexec/scheduling_http.go | 1 + .../hosted_submitted_additional.go | 63 +++ .../hosted_submitted_additional_test.go | 439 ++++++++++++++++++ .../reviewprovider/hosted_submitted_review.go | 91 ++-- 21 files changed, 1235 insertions(+), 67 deletions(-) create mode 100644 docs/review-lane-diagnostics.md create mode 100644 internal/cli/review_lane_diagnostic_test.go create mode 100644 internal/client/review_lane_diagnostic.go create mode 100644 internal/client/review_lane_diagnostic_test.go create mode 100644 internal/mcpadapter/review_lane_diagnostic_test.go create mode 100644 internal/reviewexec/lane_diagnostic.go create mode 100644 internal/reviewexec/lane_diagnostic_http.go create mode 100644 internal/reviewexec/lane_diagnostic_test.go create mode 100644 internal/reviewprovider/hosted_submitted_additional.go create mode 100644 internal/reviewprovider/hosted_submitted_additional_test.go diff --git a/docs/mcp.md b/docs/mcp.md index 3cbf1cb1d..0198381cc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -93,6 +93,7 @@ Startup validates configuration without opening the credential or contacting the | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | | `wait_for_messages` | Required event cursor; optional limit 1–100 and wait_seconds 1–50, default 20/25. One new-message event page or quiet timeout over a call-owned persistent stream. | | `review_execution_read` | No fields; stored execution configuration and revision, without provider work. | +| `review_lane_diagnostic` | Required channel; provider-free [per-PR lane diagnostics](review-lane-diagnostics.md) with retained source timestamps/completeness, local holds and exact parent blockers. Not fresh admission or a dispatch promise. | | `review_scheduling_read` | No fields; stored project scheduling settings, revision and paused queued PRs, without provider work. | | `review_scheduling_configure` | Required idempotency_key/expected_revision/automatic_hosted; optional automatic_cli preserves its existing value when omitted. Project management capability configures [default-off automatic scheduling](review-scheduling.md), including authorization for later provider work within existing review limits. | | `review_pull_scheduling_read` | Required pull_number; reads the per-PR automatic scheduling pause and revision. | diff --git a/docs/provider-observations.md b/docs/provider-observations.md index 7806afb9e..2235da794 100644 --- a/docs/provider-observations.md +++ b/docs/provider-observations.md @@ -20,6 +20,8 @@ CI reads bind explicit source and selected commit identities, recheck passing ca CodeRabbit decoding recognizes closed generated envelopes and presentation variants while retaining original bodies and identities. Publication attribution, exact comparison, provider run identity, finished acknowledgment and counted finding inventory remain separate checks. Inline, outside-diff, duplicate and additional findings retain their own source references. Additional-only summaries support at most one bare `
` as the first visible, nonempty, non-Markdown-quoted line after each `
` inside balanced definition-list wrappers at the same details and HTML blockquote depths, and a standalone heading around exact Review info metadata. Repeated breaks, mid-body breaks and breaks outside the matching definition body remain unsupported; hidden or Markdown-quoted examples cannot supply wrapper boundaries or restart a body. Neither presentation form can hide unknown findings or supply comparison authority by itself. Supported count omission for positive and marked-empty publications follows the [native source contract](review-execution.md#hosted-source-adoption). Malformed or contradictory count metadata remains refused; omission by itself never establishes a clean review. Baseline-qualified historical annotation exclusion retains original comment/review identities, bodies and positions. Positive comparison proof requires an independently bound pre-POST baseline and authenticated current standing metadata; conflicting comparison metadata remains refused. Quoted prompts and examples cannot supply authoritative metadata. An authenticated foreign Bot report whose entire current body contains no case-insensitive `coderabbit` mention is not an inferred request authority merely because it was edited. This current-source policy does not prove its original body or require a pre-trigger copy; bot-looking prose or login names do not replace the source-owned actor kind. Visible competing review commands still close attribution regardless of author. Edited posting-actor, human and other actor-kind comments, and Bot comments with provider mentions even in quoted or hidden text, retain the conservative edit barrier. Baseline-qualified projections and old finding annotation proof preserve their separate source-binding checks without rewriting either capture. +A markerless submitted review may instead contain exactly one positive, counted Additional comments category followed directly by the existing `h6`-wrapped Review info and generated status footer. The complete provider collections must prove there are no attached inline roots or in-window orphan roots. The original submitted review, unique fresh run, configured provider actor, exact head, explicit full comparison, counted selected-file inventory and unique later finished acknowledgment retain their ordinary checks. Every additional finding must decode completely and name a selected file; category/group counts, source text and its unverified qualification remain intact. Actionable-count declarations, mixed or unknown categories, empty inventories, competing submissions or commands and ambiguous acknowledgments cannot use this path. This parser support preserves positive findings and does not itself finalize adjudication, change round accounting, or grant clean/taper credit. The existing runtime proof pipeline remains responsible for completion. + A closed unquoted Follow-up Comments envelope may carry positive outside-diff findings without a count header. Its generated badge, explicit matching title, severity, range, reviewed-head source location and fingerprint must agree. The source location establishes finding coordinates only; it never supplies base or effective-parent proof. Empty, ambiguous or unsupported envelopes remain incomplete. A generated Review info block can report files whose changes were unavailable. Retain that bounded limitation separately from finding-inventory completeness; a complete captured result does not imply every selected file was reviewed. Original findings and completion accounting remain unchanged. diff --git a/docs/review-lane-diagnostics.md b/docs/review-lane-diagnostics.md new file mode 100644 index 000000000..8681b859e --- /dev/null +++ b/docs/review-lane-diagnostics.md @@ -0,0 +1,19 @@ +# Review lane diagnostics + +The read-only lane diagnostic explains each configured PR's local evidence and dependency state using the latest retained source frame for the selected channel. It never starts or resumes selection, refreshes GitHub, contacts a review provider, changes allowance or adjudicates a result. + +Use `fc reviews scheduling diagnostics --channel cli` or `hosted`, MCP `review_lane_diagnostic` with the explicit `channel`, or `GET /api/v1/projects/{project_id}/reviews/lanes/{channel}/diagnostics`. Project read access suffices. The response contains at most the configured 100 PRs in queue order. It returns no provider bodies or credentials. + +## Reading the result + +The scope is always `retained_source_local_policy`. `evaluated_at` is the time of this local read; `source_checked_at`, each candidate's `source_observed_at`, and `source_configuration_revision` describe retained acquisition, not a fresh provider check. `source_complete` means that acquisition covered the configured queue with no global source error. It does not establish current GitHub heads or dispatch eligibility. Unknown suffixes remain `unknown` with `source_not_observed`; a changed configuration or repository invalidates the frame for all current candidates. Missing or damaged evidence never becomes an empty healthy lane. + +Each observed candidate has `local_state` and `local_reason`. `locally_ready` means only that the shared local evaluator found no evidence, source-obligation, route, PR-pause, round or actual-parent hold in that retained comparison. It is not a preview of the next automatic selection. Provider limits, active operations, automatic-intent suppression, authorization, current source and transactional admission still apply. `lane_reason` separately reports a configured project/channel pause, disabled channel or global storage/identity hold. + +A `predecessor_unfinished` row identifies `blocking_pull_number` and `blocking_reason`. An earlier PR's pending evidence does not hold an unrelated later PR. It does hold the earlier PR's real descendants until the existing channel-completion and fix-obligation rules are satisfied. The diagnostic shares this dependency evaluator with ordinary selection; it does not introduce a bypass. A local hold on the candidate itself remains its primary reason. + +For a lane audit, combine this diagnostic with current operation/scheduling/round reads and current published source observations. Do not use `locally_ready` to force a review or declare a lane healthy. A stale or incomplete frame means eligibility remains unestablished and calls for an authorized ordinary source/selection workflow, not a new review merely to obtain diagnostics. + +## Validation boundary + +Focused synthetic tests cover retained pending evidence, independent progression, actual-parent holds with exact blocker identity, incomplete/missing/configuration-changed/repository-changed source, malformed retained frames, revoked read access, strict bound client responses, read-only MCP discovery, CLI parsing and unchanged durable selection state. A 100-row shared completed-ancestor case passes the bounded read deadline normally and under the race detector. Each plan’s local facts are cached only inside the current read transaction, avoiding repeated ancestor SQL reads without changing admission. Local proof does not establish deployed service support, current live admission or provider throughput. diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 0cddb9626..bfd6b4e16 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -42,6 +42,8 @@ The existing queue and PR detail views show current round allowance, closure or ## CLI and MCP +The provider-free [lane diagnostic](review-lane-diagnostics.md) explains each configured PR against retained source and current local evidence/dependency facts, including exact parent blockers and unknown source suffixes. It does not authorize selection or claim fresh admission. + Read the current scheduling revision before changing settings. Keep the exact request and key after an uncertain mutation outcome; replaying the same key cannot enable or pause twice. ```sh diff --git a/internal/cli/review_lane_diagnostic_test.go b/internal/cli/review_lane_diagnostic_test.go new file mode 100644 index 000000000..19448421b --- /dev/null +++ b/internal/cli/review_lane_diagnostic_test.go @@ -0,0 +1,25 @@ +package cli + +import ( + "bytes" + "strings" + "testing" +) + +func TestLaneDiagnosticCLIReadSyntax(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + call, ok := parseInvocation([]string{"reviews", "scheduling", "diagnostics", "--channel", channel}) + if !ok || call.reviewScheduling == nil || call.reviewScheduling.action != "diagnostics" || call.reviewScheduling.channel != channel { + t.Fatal(call, ok) + } + } + for _, args := range [][]string{{}, {"--channel", "manual"}, {"--channel", "cli", "--key", "no"}, {"--channel", "cli", "--channel", "hosted"}, {"--channel", "cli", "--pr", "2"}} { + if _, ok := parseReviewScheduling(append([]string{"diagnostics"}, args...)); ok { + t.Fatal("invalid read accepted", args) + } + } + var out, diag bytes.Buffer + if code := RunContext(t.Context(), []string{"--profiles-file", "/missing", "reviews", "scheduling", "diagnostics", "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "not fresh admission") { + t.Fatal(code, out.String(), diag.String()) + } +} diff --git a/internal/cli/review_scheduling.go b/internal/cli/review_scheduling.go index 2f9fa0ac5..58636b71c 100644 --- a/internal/cli/review_scheduling.go +++ b/internal/cli/review_scheduling.go @@ -9,11 +9,12 @@ import ( ) type reviewSchedulingInvocation struct { - action string - pull int64 - key string - config client.ConfigureReviewSchedulingRequest - pause client.ConfigureReviewPullSchedulingRequest + action string + channel string + pull int64 + key string + config client.ConfigureReviewSchedulingRequest + pause client.ConfigureReviewPullSchedulingRequest } func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { @@ -24,6 +25,8 @@ func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { allowed := map[string]bool{"--pr": true} switch in.action { case "read": + case "diagnostics": + allowed = map[string]bool{"--channel": true} case "configure": allowed = map[string]bool{"--automatic-hosted": true, "--automatic-cli": true, "--expect-revision": true, "--key": true} case "pause", "resume": @@ -62,6 +65,10 @@ func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { } in.pull = n } + if in.action == "diagnostics" { + in.channel = values["--channel"] + return in, in.channel == "cli" || in.channel == "hosted" + } if in.action == "read" { return in, true } @@ -94,6 +101,8 @@ func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { func executeReviewScheduling(ctx context.Context, service *client.Client, in *reviewSchedulingInvocation) (any, error) { switch in.action { + case "diagnostics": + return service.ReviewLaneDiagnostic(ctx, in.channel) case "configure": return service.ConfigureReviewScheduling(ctx, in.key, in.config) case "pause", "resume": diff --git a/internal/cli/review_scheduling_help.go b/internal/cli/review_scheduling_help.go index 15042837d..2b37bc883 100644 --- a/internal/cli/review_scheduling_help.go +++ b/internal/cli/review_scheduling_help.go @@ -7,9 +7,15 @@ func operationHelp(operation string) (operationHelpResponse, bool) { case "reviews scheduling": out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause|resume --pr N --expect-revision N --key KEY [--reason TEXT]" out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)", "configure --automatic-hosted true|false (project manager; authorizes future automatic Hosted requests)", "pause|resume --pr N (writer; holds new/undispatched reviews without changing rounds)", "--reason TEXT (optional with pause, at most 256 UTF-8 bytes)"} - out.Optional = append(out.Optional, "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") + out.Optional = append(out.Optional, "reviews scheduling diagnostics --help", "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") out.Semantics = []string{"Automation defaults off. Enabling requires this connection's active bound worker and current project-management authority; CLI automation is separately opt-in via --automatic-cli; omission preserves its current value. Existing grants and taper remain unchanged.", "Pause can precede any intent. Existing provider review collection continues, and separate operation pauses remain in effect. Read the current revision; mutations require an explicit key and preserve original-key recovery.", "No live provider request is needed to read or change a PR pause. Enabling project automation authorizes later Hosted or CLI selection under all existing comparison, obligation, round and provider guards."} out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling diagnostics": + out.Usage = " reviews scheduling diagnostics --channel cli|hosted" + out.Required = []string{"--channel cli|hosted"} + out.Semantics = []string{"Read retained source time/completeness and current local evidence/dependency state for every configured PR. locally_ready is not fresh admission, automatic eligibility or a dispatch promise. No source/provider refresh, review request or mutation."} + out.Example = " reviews scheduling diagnostics --channel cli" + out.Documentation = "docs/review-lane-diagnostics.md" case "reviews scheduling read": out.Usage = " reviews scheduling read [--pr N]" out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)"} diff --git a/internal/client/review_lane_diagnostic.go b/internal/client/review_lane_diagnostic.go new file mode 100644 index 000000000..a00932281 --- /dev/null +++ b/internal/client/review_lane_diagnostic.go @@ -0,0 +1,66 @@ +package client + +import ( + "context" + "net/http" +) + +type ReviewLaneDiagnostic struct { + ProjectID string `json:"project_id"` + Channel string `json:"channel"` + ConfigurationRevision int64 `json:"configuration_revision"` + EvaluatedAt string `json:"evaluated_at"` + Scope string `json:"scope"` + SourceConfigurationRevision int64 `json:"source_configuration_revision"` + SourceCheckedAt string `json:"source_checked_at,omitempty"` + SourceComplete bool `json:"source_complete"` + SourceReason string `json:"source_reason"` + LaneReason string `json:"lane_reason"` + Candidates []ReviewLaneCandidateDiagnostic `json:"candidates"` +} + +type ReviewLaneCandidateDiagnostic struct { + PullNumber int64 `json:"pull_number"` + HeadSHA string `json:"head_sha,omitempty"` + SourceObservedAt string `json:"source_observed_at,omitempty"` + ParentPullNumber int64 `json:"parent_pull_number"` + LocalState string `json:"local_state"` + LocalReason string `json:"local_reason"` + BlockingPullNumber int64 `json:"blocking_pull_number"` + BlockingReason string `json:"blocking_reason"` +} + +func (c *Client) ReviewLaneDiagnostic(ctx context.Context, channel string) (ReviewLaneDiagnostic, error) { + if !oneReviewOf(channel, "cli", "hosted") { + return ReviewLaneDiagnostic{}, validation() + } + var out ReviewLaneDiagnostic + if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "lanes", channel, "diagnostics"), nil, true, "", nil, http.StatusOK, false, &out, 128<<10, decodeReviewResponse); err != nil { + return ReviewLaneDiagnostic{}, err + } + if out.ProjectID != c.identity.ProjectID || out.Channel != channel || out.Scope != "retained_source_local_policy" || out.ConfigurationRevision < 1 || !controlTime(out.EvaluatedAt) || out.SourceConfigurationRevision < 0 || out.Candidates == nil || len(out.Candidates) > 100 || out.SourceReason != "" && !safeCode(out.SourceReason) || out.LaneReason != "" && !safeCode(out.LaneReason) { + return ReviewLaneDiagnostic{}, invalidResponse() + } + if out.SourceConfigurationRevision == 0 { + if out.SourceCheckedAt != "" || out.SourceComplete || out.SourceReason != "source_unavailable" { + return ReviewLaneDiagnostic{}, invalidResponse() + } + } else if !controlTime(out.SourceCheckedAt) || out.SourceComplete && (out.SourceConfigurationRevision != out.ConfigurationRevision || out.SourceReason != "") { + return ReviewLaneDiagnostic{}, invalidResponse() + } + usableSource := out.SourceConfigurationRevision > 0 && out.SourceConfigurationRevision == out.ConfigurationRevision && out.SourceReason != "repository_changed" && out.SourceReason != "configuration_changed" + seen := map[int64]bool{} + for _, p := range out.Candidates { + if !validPullNumber(p.PullNumber) || seen[p.PullNumber] || !oneReviewOf(p.LocalState, "unknown", "held", "complete", "locally_ready") || p.LocalReason != "" && !safeCode(p.LocalReason) || p.BlockingReason != "" && !safeCode(p.BlockingReason) || p.ParentPullNumber != 0 && (!validPullNumber(p.ParentPullNumber) || p.ParentPullNumber == p.PullNumber) || p.BlockingPullNumber != 0 && !validPullNumber(p.BlockingPullNumber) { + return ReviewLaneDiagnostic{}, invalidResponse() + } + seen[p.PullNumber] = true + if !usableSource && p.HeadSHA != "" || out.SourceComplete && p.HeadSHA == "" || p.LocalState == "unknown" && p.LocalReason == "" || p.LocalState == "complete" && p.LocalReason != "" { + return ReviewLaneDiagnostic{}, invalidResponse() + } + if (p.HeadSHA == "") != (p.SourceObservedAt == "") || p.HeadSHA != "" && (!controlHex(p.HeadSHA, 40) || !controlTime(p.SourceObservedAt)) || p.HeadSHA == "" && (p.LocalState != "unknown" || p.ParentPullNumber != 0) || p.LocalState == "held" && p.LocalReason == "" || p.LocalState == "locally_ready" && p.LocalReason != "" || (p.BlockingPullNumber == 0) != (p.BlockingReason == "") || p.BlockingPullNumber != 0 && (p.LocalState != "held" || p.LocalReason != "predecessor_unfinished") { + return ReviewLaneDiagnostic{}, invalidResponse() + } + } + return out, nil +} diff --git a/internal/client/review_lane_diagnostic_test.go b/internal/client/review_lane_diagnostic_test.go new file mode 100644 index 000000000..1eb10f4d5 --- /dev/null +++ b/internal/client/review_lane_diagnostic_test.go @@ -0,0 +1,71 @@ +package client_test + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/client" +) + +func sampleLaneDiagnostic() client.ReviewLaneDiagnostic { + return client.ReviewLaneDiagnostic{ProjectID: "project-one", Channel: "cli", ConfigurationRevision: 1, EvaluatedAt: "2026-11-10T21:00:00Z", Scope: "retained_source_local_policy", SourceConfigurationRevision: 1, SourceCheckedAt: "2026-11-10T20:59:00Z", SourceComplete: true, Candidates: []client.ReviewLaneCandidateDiagnostic{{PullNumber: 2, HeadSHA: strings.Repeat("a", 40), SourceObservedAt: "2026-11-10T20:58:00Z", LocalState: "held", LocalReason: "review_evidence_pending"}, {PullNumber: 4, HeadSHA: strings.Repeat("b", 40), SourceObservedAt: "2026-11-10T20:58:00Z", ParentPullNumber: 2, LocalState: "held", LocalReason: "predecessor_unfinished", BlockingPullNumber: 2, BlockingReason: "review_evidence_pending"}}} +} +func TestReviewLaneDiagnosticBoundReadAndStrictResponses(t *testing.T) { + cases := map[string]func(*client.ReviewLaneDiagnostic){ + "valid": func(*client.ReviewLaneDiagnostic) {}, + "project": func(v *client.ReviewLaneDiagnostic) { v.ProjectID = "foreign" }, + "channel": func(v *client.ReviewLaneDiagnostic) { v.Channel = "hosted" }, + "duplicate": func(v *client.ReviewLaneDiagnostic) { v.Candidates[1].PullNumber = 2 }, + "false-freshness": func(v *client.ReviewLaneDiagnostic) { v.SourceConfigurationRevision = 2 }, + "changed-source-ready": func(v *client.ReviewLaneDiagnostic) { + v.SourceConfigurationRevision = 2 + v.SourceComplete = false + v.SourceReason = "configuration_changed" + }, + "no-source-ready": func(v *client.ReviewLaneDiagnostic) { + v.Candidates[0].HeadSHA = "" + v.Candidates[0].SourceObservedAt = "" + v.Candidates[0].LocalState = "locally_ready" + v.Candidates[0].LocalReason = "" + }, + "missing-blocker": func(v *client.ReviewLaneDiagnostic) { v.Candidates[1].BlockingPullNumber = 0 }, + "bad-time": func(v *client.ReviewLaneDiagnostic) { v.SourceCheckedAt = "yesterday" }, + "null-candidates": func(v *client.ReviewLaneDiagnostic) { v.Candidates = nil }, + } + for name, edit := range cases { + t.Run(name, func(t *testing.T) { + value := sampleLaneDiagnostic() + edit(&value) + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/instance") { + handshake(w) + return + } + calls++ + if r.Method != "GET" || r.URL.Path != "/api/v1/projects/project-one/reviews/lanes/cli/diagnostics" || r.URL.RawQuery != "" || r.Header.Get("Idempotency-Key") != "" { + t.Error("diagnostic changed method or binding") + } + write(w, 200, value) + })) + defer srv.Close() + c := newClient(t, srv) + got, err := c.ReviewLaneDiagnostic(t.Context(), "cli") + if calls != 1 { + t.Fatal("unexpected fanout", calls) + } + if name == "valid" { + if err != nil || got.Candidates[1].BlockingPullNumber != 2 { + t.Fatal(got, err) + } + } else { + checkError(t, err, "invalid_response") + } + if _, err = c.ReviewLaneDiagnostic(t.Context(), "manual"); err == nil || calls != 1 { + t.Fatal("invalid channel contacted service") + } + }) + } +} diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index 4ed4480d2..c70bcbf7b 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -211,6 +211,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_queue_edit"] = true expected["review_operation_control"] = true expected["review_scheduling_read"], expected["review_scheduling_configure"] = true, true + expected["review_lane_diagnostic"] = true expected["review_pull_scheduling_read"], expected["review_pull_scheduling_update"] = true, true expected["wait_for_ci"] = true expected["review_rounds_read"], expected["review_rounds_configure"] = true, true diff --git a/internal/mcpadapter/review_lane_diagnostic_test.go b/internal/mcpadapter/review_lane_diagnostic_test.go new file mode 100644 index 000000000..2705c563d --- /dev/null +++ b/internal/mcpadapter/review_lane_diagnostic_test.go @@ -0,0 +1,47 @@ +package mcpadapter_test + +import ( + "encoding/json" + "net/http/httptest" + "testing" + + "github.com/benhook1013/FireController/internal/client" +) + +func TestLaneDiagnosticSDKReadOnlyNoProviderWork(t *testing.T) { + f, handler, _ := reviewControlsFixture(t) + server := httptest.NewServer(handler) + defer server.Close() + session := reviewControlsStdio(t, reviewControlsProfile(t, f, server.URL), "chosen") + listed, err := allDiscoveredTools(t, session) + if err != nil { + t.Fatal(err) + } + found := false + for _, tool := range listed.Tools { + if tool.Name == "review_lane_diagnostic" { + found = true + a := tool.Annotations + if a == nil || !a.ReadOnlyHint || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint || a.OpenWorldHint == nil || *a.OpenWorldHint { + t.Fatal("incorrect read effects") + } + } + } + if !found { + t.Fatal("missing diagnostic tool") + } + before := f.providers.Load() + for _, channel := range []string{"cli", "hosted"} { + var out client.ReviewLaneDiagnostic + decodeResult(t, call(t, session, "review_lane_diagnostic", map[string]any{"channel": channel}), &out) + if out.Channel != channel || out.Scope != "retained_source_local_policy" || out.SourceComplete || out.SourceReason != "source_unavailable" { + t.Fatal(out) + } + } + for _, raw := range []string{`{}`, `null`, `{"channel":"manual"}`, `{"channel":"cli","refresh":true}`, `{"channel":"cli","channel":"hosted"}`, `{"channel":"cli","project_id":"foreign"}`} { + diagnosticResult(t, call(t, session, "review_lane_diagnostic", json.RawMessage(raw)), "invalid_arguments", false) + } + if f.providers.Load() != before { + t.Fatal("diagnostic contacted provider") + } +} diff --git a/internal/mcpadapter/review_scheduling.go b/internal/mcpadapter/review_scheduling.go index 91d984b57..5d8c64d22 100644 --- a/internal/mcpadapter/review_scheduling.go +++ b/internal/mcpadapter/review_scheduling.go @@ -14,7 +14,7 @@ func reviewSchedulingWrite(name string) bool { } func reviewSchedulingTool(name string) bool { - return reviewSchedulingWrite(name) || name == "review_scheduling_read" || name == "review_pull_scheduling_read" + return name == "review_lane_diagnostic" || reviewSchedulingWrite(name) || name == "review_scheduling_read" || name == "review_pull_scheduling_read" } func reviewSchedulingArguments(name string, raw json.RawMessage) (arguments, error) { @@ -26,6 +26,16 @@ func reviewSchedulingArguments(name string, raw json.RawMessage) (arguments, err if len(raw) > 4096 || len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' { return args, invalidArguments() } + if name == "review_lane_diagnostic" { + var wire struct { + Channel string `json:"channel"` + } + if strictjson.Decode(raw, &wire) != nil || (wire.Channel != "cli" && wire.Channel != "hosted") { + return args, invalidArguments() + } + args.roundChannel = wire.Channel + return args, nil + } if name == "review_scheduling_read" { var empty struct{} if strictjson.Decode(raw, &empty) != nil { @@ -100,6 +110,7 @@ func reviewSchedulingDefinitions() []definition { pull := map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647} key := map[string]any{"type": "string", "minLength": 1, "maxLength": 128, "description": "Explicit original idempotency key; retain with the exact request after unknown outcome."} return []definition{ + {"review_lane_diagnostic", "Read every configured PR in one channel against retained source facts and current local evidence/dependency policy. Includes source time/completeness and exact blocking parent. Provider-free and read-only; locally_ready is NOT fresh admission, automatic eligibility or a promise of dispatch. No new selection, retry, provider call, cap or control change.", object(map[string]any{"channel": map[string]any{"type": "string", "enum": []string{"cli", "hosted"}}}, "channel")}, {"review_scheduling_read", "Read this project's automatic Hosted and CLI settings and current queued PR pauses in one provider-free call. No settings, review or allowance changes. See docs/review-scheduling.md.", object(map[string]any{})}, {"review_scheduling_configure", "Project manager: explicitly enable or disable automatic future Hosted or CLI requests under existing source, obligation, round and provider guards. Both default off. Optional automatic_cli preserves the current CLI setting when omitted. Existing grants and taper apply; no automatic adjudication or grant increase. Enabling retains this connection's current credential and active bound worker; withdrawn authority stops new automatic actions. This setting can authorize asynchronous provider work. Current revision and explicit key required; no automatic mutation retry. See docs/review-scheduling.md.", object(map[string]any{"expected_revision": revision, "automatic_hosted": map[string]any{"type": "boolean"}, "automatic_cli": map[string]any{"type": "boolean", "description": "Optional CLI opt-in; omission preserves the current setting."}, "idempotency_key": key}, "expected_revision", "automatic_hosted", "idempotency_key")}, {"review_pull_scheduling_read", "Read one PR's temporary scheduling pause before or after an intent exists. Does not change Draft, grant, taper, closure or active provider work.", object(map[string]any{"pull_number": pull}, "pull_number")}, diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index 5d50dc1d9..6ab6483fc 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -207,6 +207,8 @@ func boundServer(binding profile.Binding) *mcp.Server { value, err = service.ReviewExecution(ctx) case "review_operations_list": value, err = service.ReviewOperations(ctx, args.reviewOperations) + case "review_lane_diagnostic": + value, err = service.ReviewLaneDiagnostic(ctx, args.roundChannel) case "review_scheduling_read": value, err = service.ReviewScheduling(ctx) case "review_scheduling_configure": diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 9a04970a8..7b2580dc5 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -10,8 +10,10 @@ import ( // evaluatedFront is shared with admission. A diagnostic hold retains the actual // blocking predecessor, whereas the legacy adapter intentionally returns zero. type evaluatedFront struct { - state, reason string - plan *SourcePlan + state, reason string + plan *SourcePlan + blockingPull int64 + blockingReason string } func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo int64, plan *SourcePlan) (evaluatedFront, error) { @@ -93,6 +95,50 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i return evaluatedFront{state: "ready", plan: plan}, nil } +// evaluateCandidatePlan shares actual-parent checks with the read-only lane +// diagnostic. A local hold never supplies completion for its real descendants. +func (e *Engine) evaluateCandidatePlan(ctx context.Context, q *sql.Tx, r Run, repo int64, plan *SourcePlan, byNumber map[int64]*SourcePlan) (evaluatedFront, error) { + return evaluateCandidateLocalState(plan, byNumber, func(p *SourcePlan) (evaluatedFront, error) { return e.evaluateFrontPlan(ctx, q, r, repo, p) }) +} + +func evaluateCandidateLocalState(plan *SourcePlan, byNumber map[int64]*SourcePlan, evaluate func(*SourcePlan) (evaluatedFront, error)) (evaluatedFront, error) { + result, err := evaluate(plan) + if err != nil || result.state != "ready" { + return result, err + } + seen := map[int64]bool{plan.Pull.Number: true} + parentNumber, parentSHA := plan.ParentPullNumber, plan.ParentSHA + for parentNumber != 0 { + parent := byNumber[parentNumber] + reason := "" + switch { + case seen[parentNumber]: + reason = "parent_cycle" + case parent == nil: + reason = "parent_source_unavailable" + case parent.Pull.HeadSHA != parentSHA: + reason = "parent_moved" + } + if reason != "" { + return evaluatedFront{state: "held", reason: "predecessor_unfinished", plan: plan, blockingPull: parentNumber, blockingReason: reason}, nil + } + seen[parentNumber] = true + parentState, err := evaluate(parent) + if err != nil { + return evaluatedFront{}, err + } + if parentState.state != "complete" { + reason := parentState.reason + if reason == "" { + reason = "review_rounds_pending" + } + return evaluatedFront{state: "held", reason: "predecessor_unfinished", plan: plan, blockingPull: parentNumber, blockingReason: reason}, nil + } + parentNumber, parentSHA = parent.ParentPullNumber, parent.ParentSHA + } + return result, nil +} + func (e *Engine) evaluateFront(ctx context.Context, q *sql.Tx, r Run, repo int64, prefix []SourcePlan, complete bool) (evaluatedFront, error) { byNumber := map[int64]*SourcePlan{} for i := range prefix { @@ -101,7 +147,7 @@ func (e *Engine) evaluateFront(ctx context.Context, q *sql.Tx, r Run, repo int64 var firstHeld *evaluatedFront for i := range prefix { plan := &prefix[i] - result, err := e.evaluateFrontPlan(ctx, q, r, repo, plan) + result, err := e.evaluateCandidatePlan(ctx, q, r, repo, plan, byNumber) if err != nil { return evaluatedFront{}, err } @@ -111,27 +157,6 @@ func (e *Engine) evaluateFront(ctx context.Context, q *sql.Tx, r Run, repo int64 if result.state == "complete" { continue } - if result.state == "ready" { - seen := map[int64]bool{plan.Pull.Number: true} - parentNumber, parentSHA := plan.ParentPullNumber, plan.ParentSHA - for parentNumber != 0 { - parent := byNumber[parentNumber] - if seen[parentNumber] || parent == nil || parent.Pull.HeadSHA != parentSHA { - result = evaluatedFront{state: "held", reason: "predecessor_unfinished", plan: plan} - break - } - seen[parentNumber] = true - parentState, err := e.evaluateFrontPlan(ctx, q, r, repo, parent) - if err != nil { - return evaluatedFront{}, err - } - if parentState.state != "complete" { - result = evaluatedFront{state: "held", reason: "predecessor_unfinished", plan: plan} - break - } - parentNumber, parentSHA = parent.ParentPullNumber, parent.ParentSHA - } - } if result.state == "ready" { return result, nil } diff --git a/internal/reviewexec/lane_diagnostic.go b/internal/reviewexec/lane_diagnostic.go new file mode 100644 index 000000000..3d723a757 --- /dev/null +++ b/internal/reviewexec/lane_diagnostic.go @@ -0,0 +1,133 @@ +package reviewexec + +import ( + "context" + "database/sql" + "slices" + + "github.com/benhook1013/FireController/internal/core" +) + +// LaneDiagnostic reports local policy against explicitly retained source facts. +// It is not an admission preview: source freshness, automatic-intent ownership, +// provider capacity and dispatch authorization still require normal selection. +type LaneDiagnostic struct { + ProjectID string `json:"project_id"` + Channel string `json:"channel"` + ConfigurationRevision int64 `json:"configuration_revision"` + EvaluatedAt string `json:"evaluated_at"` + Scope string `json:"scope"` + SourceConfigurationRevision int64 `json:"source_configuration_revision"` + SourceCheckedAt string `json:"source_checked_at,omitempty"` + SourceComplete bool `json:"source_complete"` + SourceReason string `json:"source_reason"` + LaneReason string `json:"lane_reason"` + Candidates []LaneCandidateDiagnostic `json:"candidates"` +} + +type LaneCandidateDiagnostic struct { + PullNumber int64 `json:"pull_number"` + HeadSHA string `json:"head_sha,omitempty"` + SourceObservedAt string `json:"source_observed_at,omitempty"` + ParentPullNumber int64 `json:"parent_pull_number"` + LocalState string `json:"local_state"` + LocalReason string `json:"local_reason"` + BlockingPullNumber int64 `json:"blocking_pull_number"` + BlockingReason string `json:"blocking_reason"` +} + +func (e *Engine) ReadLaneDiagnostic(ctx context.Context, scope core.Scope, channel string) (LaneDiagnostic, error) { + if !validChannel(channel) { + return LaneDiagnostic{}, invalid() + } + out := LaneDiagnostic{ProjectID: scope.ProjectID, Channel: channel, Scope: "retained_source_local_policy", Candidates: []LaneCandidateDiagnostic{}} + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + c, revision, err := readConfiguration(ctx, tx, scope.ProjectID) + if err != nil { + return err + } + out.ConfigurationRevision, out.EvaluatedAt = revision, stamp() + if c.Paused { + out.LaneReason = "reviews_paused" + } else if !slices.Contains(c.Channels, channel) { + out.LaneReason = "review_not_configured" + } + policy, err := readPolicy(ctx, tx, scope.ProjectID) + if err != nil { + return err + } + if slices.Contains(policy.Policy.PausedChannels, channel) { + out.LaneReason = "reviews_paused" + } + frame, found, err := readFrontFrame(ctx, tx, scope.ProjectID, channel) + if err != nil { + return err + } + var repository int64 + if err = tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, scope.ProjectID).Scan(&repository); err != nil { + return err + } + out.SourceReason = "source_unavailable" + if found { + out.SourceConfigurationRevision, out.SourceCheckedAt = frame.configuration, frame.checkedAt + out.SourceReason = frame.sourceReason + switch { + case frame.configuration != revision: + out.SourceReason = "configuration_changed" + case frame.repository != repository: + out.SourceReason = "repository_changed" + } + } + usable := found && frame.configuration == revision && frame.repository == repository + out.SourceComplete = usable && frame.complete + plans := frame.plans() + byNumber := map[int64]*SourcePlan{} + if usable { + for i := range plans { + byNumber[plans[i].Pull.Number] = &plans[i] + } + } + // An empty selection identity deliberately does not impersonate an automatic + // intent. This diagnostic describes local evidence/dependency facts only. + r := Run{ProjectID: scope.ProjectID, Channel: channel} + // Every local fact belongs to this same read transaction. Reuse ancestor + // evaluations so a full queue of siblings does not repeat thousands of SQL + // reads under the bounded Store.Read deadline. This cache never survives the + // request and is not used by selection or admission. + local := map[int64]evaluatedFront{} + evaluate := func(plan *SourcePlan) (evaluatedFront, error) { + if state, ok := local[plan.Pull.Number]; ok { + return state, nil + } + state, err := e.evaluateFrontPlan(ctx, tx, r, repository, plan) + if err == nil { + local[plan.Pull.Number] = state + } + return state, err + } + for _, number := range c.Queue { + item := LaneCandidateDiagnostic{PullNumber: number, LocalState: "unknown", LocalReason: "source_not_observed"} + if plan := byNumber[number]; plan != nil { + item.HeadSHA, item.SourceObservedAt, item.ParentPullNumber = plan.Pull.HeadSHA, plan.ObservedAt, plan.ParentPullNumber + state, err := evaluateCandidateLocalState(plan, byNumber, evaluate) + if err != nil { + return err + } + item.LocalState, item.LocalReason = state.state, state.reason + if globalFrontHold(state.reason) && out.LaneReason == "" { + out.LaneReason = state.reason + } + if item.LocalState == "ready" { + item.LocalState = "locally_ready" + } + item.BlockingPullNumber, item.BlockingReason = state.blockingPull, state.blockingReason + } + out.Candidates = append(out.Candidates, item) + } + return nil + }) + if err != nil { + return LaneDiagnostic{}, err + } + return out, nil +} diff --git a/internal/reviewexec/lane_diagnostic_http.go b/internal/reviewexec/lane_diagnostic_http.go new file mode 100644 index 000000000..acef3a477 --- /dev/null +++ b/internal/reviewexec/lane_diagnostic_http.go @@ -0,0 +1,24 @@ +package reviewexec + +import ( + "github.com/benhook1013/FireController/internal/core" + "net/http" +) + +func (e *Engine) readLaneDiagnosticHTTP(w http.ResponseWriter, r *http.Request) { + scope, err := e.store.Scope(r, "read") + if err != nil { + core.WriteError(w, err) + return + } + if _, err = core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + out, err := e.ReadLaneDiagnostic(r.Context(), scope, r.PathValue("channel")) + if err != nil { + core.WriteError(w, err) + return + } + core.WriteJSON(w, http.StatusOK, out) +} diff --git a/internal/reviewexec/lane_diagnostic_test.go b/internal/reviewexec/lane_diagnostic_test.go new file mode 100644 index 000000000..110e5a106 --- /dev/null +++ b/internal/reviewexec/lane_diagnostic_test.go @@ -0,0 +1,202 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func laneDiagnosticFrame(t *testing.T, f *attemptFixture, channel string, plans []SourcePlan) { + t.Helper() + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + c, rev, err := readConfiguration(ctx, tx, attemptProject) + if err != nil { + return err + } + return writeFrontFrame(ctx, tx, Run{ProjectID: attemptProject, Channel: channel, ConfigurationRevision: rev}, 801, c, runChoice{prefix: plans}) + }) + if err != nil { + t.Fatal(err) + } +} +func laneDiagnosticPlan(n int64) SourcePlan { + p := schedulingPull(n) + return SourcePlan{Repository: reviewprovider.Repository{ID: 801, FullName: "acme/repo", DefaultBranch: "main"}, Pull: p, ParentSHA: p.BaseSHA, ObservedAt: stamp()} +} +func TestLaneDiagnosticIndependentSkipAndDependentHold(t *testing.T) { + for _, dependent := range []bool{false, true} { + t.Run(map[bool]string{false: "independent", true: "dependent"}[dependent], func(t *testing.T) { + f := schedulingFixture(t) + // A genuine completed native CLI capture still awaiting adjudication holds + // its own PR, even after a later head or a closed allowance. + roundCapture(t, f, 1, false) + one := int64(1) + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "diagnostic-stack", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}}); err != nil { + t.Fatal(err) + } + p2, p4 := laneDiagnosticPlan(2), laneDiagnosticPlan(4) + if dependent { + p4.ParentPullNumber = 2 + p4.ParentSHA = p2.Pull.HeadSHA + p4.Pull.BaseSHA = p2.Pull.HeadSHA + p4.Pull.BaseRef = "branch-two" + } + laneDiagnosticFrame(t, f, "cli", []SourcePlan{p2, p4}) + before := selectionCounts(t, f) + out, err := f.e.ReadLaneDiagnostic(t.Context(), selectionScope(t, f, attemptProject, f.reader, "read"), "cli") + if err != nil || !out.SourceComplete || len(out.Candidates) != 2 { + t.Fatal(out, err) + } + if out.Candidates[0].LocalReason != "review_evidence_pending" { + t.Fatal(out) + } + later := out.Candidates[1] + if dependent { + if later.LocalReason != "predecessor_unfinished" || later.BlockingPullNumber != 2 || later.BlockingReason != "review_evidence_pending" { + t.Fatal(later) + } + } else if later.LocalState != "locally_ready" || later.BlockingPullNumber != 0 { + t.Fatal(later) + } + // The exact shared selector agrees, rather than a duplicated approximation. + err = f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + got, reason, err := f.e.runFront(ctx, tx, Run{ProjectID: attemptProject, Channel: "cli"}, 801, []SourcePlan{p2, p4}) + if err != nil { + return err + } + if dependent { + if got != 0 || reason != "review_evidence_pending" { + t.Fatal(got, reason) + } + } else if got != 4 || reason != "" { + t.Fatal(got, reason) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if selectionCounts(t, f) != before { + t.Fatal("read mutated selection, provider, event or receipt state") + } + }) + } +} +func TestLaneDiagnosticSourceBoundariesAndHTTP(t *testing.T) { + f := schedulingFixture(t) + scope := selectionScope(t, f, attemptProject, f.reader, "read") + before := selectionCounts(t, f) + out, err := f.e.ReadLaneDiagnostic(t.Context(), scope, "cli") + if err != nil || out.SourceComplete || out.SourceReason != "source_unavailable" || out.Candidates[1].LocalState != "unknown" { + t.Fatal(out, err) + } + laneDiagnosticFrame(t, f, "cli", []SourcePlan{laneDiagnosticPlan(2)}) + out, err = f.e.ReadLaneDiagnostic(t.Context(), scope, "cli") + if err != nil || out.SourceComplete || out.Candidates[1].LocalReason != "source_not_observed" { + t.Fatal(out, err) + } + mux := http.NewServeMux() + f.e.Register(mux) + w := runHTTPCall(t, f, mux, "GET", "/api/v1/projects/"+attemptProject+"/reviews/lanes/cli/diagnostics", "", "", "") + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || len(out.Candidates) != 2 { + t.Fatal(w.Code, w.Body.String()) + } + for _, suffix := range []string{"manual/diagnostics", "cli/diagnostics?refresh=true"} { + if w = runHTTPCall(t, f, mux, "GET", "/api/v1/projects/"+attemptProject+"/reviews/lanes/"+suffix, "", "", ""); w.Code != 400 { + t.Fatal(w.Code, w.Body.String()) + } + } + if selectionCounts(t, f) != before { + t.Fatal("diagnostic changed state") + } + one := int64(1) + if _, err = f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "changed-queue", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{4, 2}, Channels: []string{"cli", "hosted"}}); err != nil { + t.Fatal(err) + } + out, err = f.e.ReadLaneDiagnostic(t.Context(), scope, "cli") + if err != nil || out.SourceReason != "configuration_changed" || out.SourceComplete || out.Candidates[0].HeadSHA != "" { + t.Fatal(out, err) + } + // Source decode damage remains an error, never a healthy empty lane. + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json=?`, strings.Repeat("x", 128*1024+1)) + if _, err = f.e.ReadLaneDiagnostic(t.Context(), scope, "cli"); err == nil { + t.Fatal("damaged frame accepted") + } +} + +// Many ready siblings share one long completed ancestry. This exercises the +// advertised 100-row bound inside the real two-second Store.Read deadline. +func TestLaneDiagnosticMaximumSharedCompletedAncestry(t *testing.T) { + queue := make([]int64, 100) + for i := range queue { + queue[i] = int64(i + 1) + } + f := schedulingFixtureWithQueue(t, queue) + one := int64(1) + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "maximum-stack", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "stacked", Queue: queue, Channels: []string{"cli", "hosted"}}); err != nil { + t.Fatal(err) + } + plans := make([]SourcePlan, len(queue)) + zero := int64(0) + for i, n := range queue { + plans[i] = laneDiagnosticPlan(n) + if i > 0 { + parent := int64(i) + if i >= 50 { + parent = 50 + } + plans[i].ParentPullNumber = parent + plans[i].ParentSHA = strings.Repeat("a", 40) + plans[i].Pull.BaseSHA = plans[i].ParentSHA + plans[i].Pull.BaseRef = "ancestor" + } + if i < 50 { + if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "complete-"+strconv.FormatInt(n, 10), n, "cli", RoundControlRequest{ExpectedRevision: &zero, Action: "close"}); err != nil { + t.Fatal(err) + } + } + } + laneDiagnosticFrame(t, f, "cli", plans) + started := time.Now() + out, err := f.e.ReadLaneDiagnostic(t.Context(), selectionScope(t, f, attemptProject, f.reader, "read"), "cli") + t.Logf("100-row shared ancestry read: %s", time.Since(started)) + if err != nil || !out.SourceComplete || len(out.Candidates) != 100 { + t.Fatal(out, err) + } + for i, c := range out.Candidates { + want := "complete" + if i >= 50 { + want = "locally_ready" + } + if c.LocalState != want { + t.Fatal(i, c) + } + } +} + +func TestLaneDiagnosticRepositoryChangeAndRevokedRead(t *testing.T) { + f := schedulingFixture(t) + scope := selectionScope(t, f, attemptProject, f.reader, "read") + laneDiagnosticFrame(t, f, "cli", []SourcePlan{laneDiagnosticPlan(2), laneDiagnosticPlan(4)}) + admissionSQL(t, f, `UPDATE projects SET github_repository_id=999 WHERE id=?`, attemptProject) + out, err := f.e.ReadLaneDiagnostic(t.Context(), scope, "cli") + if err != nil || out.SourceReason != "repository_changed" || out.SourceComplete { + t.Fatal(out, err) + } + for _, c := range out.Candidates { + if c.LocalState != "unknown" || c.HeadSHA != "" { + t.Fatal(c) + } + } + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-reader-cred'`) + if _, err = f.e.ReadLaneDiagnostic(t.Context(), scope, "cli"); err == nil { + t.Fatal("retained read scope bypassed credential revocation") + } +} diff --git a/internal/reviewexec/scheduling_http.go b/internal/reviewexec/scheduling_http.go index b88e13e62..06306860f 100644 --- a/internal/reviewexec/scheduling_http.go +++ b/internal/reviewexec/scheduling_http.go @@ -8,6 +8,7 @@ import ( ) func (e *Engine) registerSchedulingHTTP(mux *http.ServeMux) { + mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/lanes/{channel}/diagnostics", e.readLaneDiagnosticHTTP) mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/scheduling", e.schedulingHTTP) mux.HandleFunc("POST /api/v1/projects/{project_id}/reviews/scheduling", e.schedulingHTTP) mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/pulls/{pull_number}/scheduling", e.pullSchedulingHTTP) diff --git a/internal/reviewprovider/hosted_submitted_additional.go b/internal/reviewprovider/hosted_submitted_additional.go new file mode 100644 index 000000000..2fa803bb7 --- /dev/null +++ b/internal/reviewprovider/hosted_submitted_additional.go @@ -0,0 +1,63 @@ +package reviewprovider + +import ( + "strconv" + "strings" +) + +// The observed markerless additional-only submission has one counted category, +// followed immediately by the existing h6-wrapped Review info. This recognizes +// its envelope only; it never supplies an inferred actionable count or inventory. +func (p *submittedReviewParser) additionalOnly() bool { + line, ok := p.next() + if !ok || line.hidden || line.quote != 0 || line.text != "
" { + return false + } + start := p.at + end, complete := findingBlock(p.lines, start, 0) + if !complete { + return false + } + p.at++ + header, ok := p.text() + match := findingAdditionalHeader.FindStringSubmatch(header) + if !ok || match == nil { + return false + } + count, err := strconv.Atoi(match[1]) + if err != nil || count < 1 || count > 200 { + return false + } + p.at = end + 1 + return true +} + +// Complete provider collections independently prove the absence of attached or +// in-window orphan roots before this check. The positive counted category must +// decode in full, and every additional finding must name a selected file. These +// are unverified additional findings, never a fabricated clean/zero result. +func submittedAdditionalInventory(review HostedReview, selected map[string]bool) bool { + lines, sound := findingLines(review.Body) + if !sound { + return false + } + // Category bodies are HTML blockquotes, not quoted examples. Do not let + // their visible count claims disappear behind publication metadata scopes. + for _, line := range lines { + if !line.hidden && strings.Contains(strings.ToLower(line.text), "actionable comments posted") { + return false + } + } + inventory := HostedFindingInventory{Complete: true, Findings: []HostedFinding{}} + decoder := findingDecoder{inventory: &inventory, seen: map[string]bool{}} + decoder.summary(review, true) + if !inventory.Complete || len(inventory.Findings) == 0 { + return false + } + for _, finding := range inventory.Findings { + if finding.Kind != "additional" || !selected[finding.Path] { + return false + } + } + return true +} diff --git a/internal/reviewprovider/hosted_submitted_additional_test.go b/internal/reviewprovider/hosted_submitted_additional_test.go new file mode 100644 index 000000000..136340edf --- /dev/null +++ b/internal/reviewprovider/hosted_submitted_additional_test.go @@ -0,0 +1,439 @@ +package reviewprovider + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +// Sanitized structural fixture from the public additional-only submission: +// https://github.com/benhook1013/FireController/pull/76#pullrequestreview-5849632157 +// https://github.com/benhook1013/FireController/pull/76#issuecomment-6779242468 +// Repository, branch, hashes, run/invocation IDs, paths, coordinates and finding +// prose are synthetic. Provider envelope, count 77, icons and layout are retained. +const submittedAdditionalBody = "\n" + + "\n" + + "\n" + + "\n" + + "
\n" + + "\"\" Additional comments: 1
\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "docs/example.md-24-24: 1
\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "`24-24`: **\"\" Trivial** · **Maintainability & Code Quality** · **Low value**\n" + + "\n" + + "\"\" **Unverified finding**\n" + + "Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.\n" + + "\n" + + "**Consider the optional example wording.**\n" + + "\n" + + "The synthetic example text may be clearer with an optional wording change. This observation remains unverified.\n" + + "\n" + + "_Source: Linters/SAST tools_\n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "
\n" + + "\"\" Review info\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "\"\" Run configuration\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "- **Source mode**: Auto\n" + + "- **Repository**: [example/project]()\n" + + "- **Branch**: [feature/example]()\n" + + "- **File**: [.coderabbit.yaml]()\n" + + "- **Commit**: [aaaaaaa]()\n" + + "- **Layers**: Repository YAML\n" + + "- **Review profile**: ASSERTIVE\n" + + "- **Plan**: Advanced\n" + + "- **Run ID**: `33333333-3333-4333-8333-333333333333`\n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "\"\" Commits\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "Reviewing files that changed from the base of the PR and between bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb and aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.\n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "\"\" Files selected for processing: 77\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "* `source/selected01.go`\n" + + "* `source/selected02.go`\n" + + "* `source/selected03.go`\n" + + "* `source/selected04.go`\n" + + "* `source/selected05.go`\n" + + "* `source/selected06.go`\n" + + "* `source/selected07.go`\n" + + "* `source/selected08.go`\n" + + "* `source/selected09.go`\n" + + "* `docs/example.md`\n" + + "* `source/selected10.go`\n" + + "* `source/selected11.go`\n" + + "* `source/selected12.go`\n" + + "* `source/selected13.go`\n" + + "* `source/selected14.go`\n" + + "* `source/selected15.go`\n" + + "* `source/selected16.go`\n" + + "* `source/selected17.go`\n" + + "* `source/selected18.go`\n" + + "* `source/selected19.go`\n" + + "* `source/selected20.go`\n" + + "* `source/selected21.go`\n" + + "* `source/selected22.go`\n" + + "* `source/selected23.go`\n" + + "* `source/selected24.go`\n" + + "* `source/selected25.go`\n" + + "* `source/selected26.go`\n" + + "* `source/selected27.go`\n" + + "* `source/selected28.go`\n" + + "* `source/selected29.go`\n" + + "* `source/selected30.go`\n" + + "* `source/selected31.go`\n" + + "* `source/selected32.go`\n" + + "* `source/selected33.go`\n" + + "* `source/selected34.go`\n" + + "* `source/selected35.go`\n" + + "* `source/selected36.go`\n" + + "* `source/selected37.go`\n" + + "* `source/selected38.go`\n" + + "* `source/selected39.go`\n" + + "* `source/selected40.go`\n" + + "* `source/selected41.go`\n" + + "* `source/selected42.go`\n" + + "* `source/selected43.go`\n" + + "* `source/selected44.go`\n" + + "* `source/selected45.go`\n" + + "* `source/selected46.go`\n" + + "* `source/selected47.go`\n" + + "* `source/selected48.go`\n" + + "* `source/selected49.go`\n" + + "* `source/selected50.go`\n" + + "* `source/selected51.go`\n" + + "* `source/selected52.go`\n" + + "* `source/selected53.go`\n" + + "* `source/selected54.go`\n" + + "* `source/selected55.go`\n" + + "* `source/selected56.go`\n" + + "* `source/selected57.go`\n" + + "* `source/selected58.go`\n" + + "* `source/selected59.go`\n" + + "* `source/selected60.go`\n" + + "* `source/selected61.go`\n" + + "* `source/selected62.go`\n" + + "* `source/selected63.go`\n" + + "* `source/selected64.go`\n" + + "* `source/selected65.go`\n" + + "* `source/selected66.go`\n" + + "* `source/selected67.go`\n" + + "* `source/selected68.go`\n" + + "* `source/selected69.go`\n" + + "* `source/selected70.go`\n" + + "* `source/selected71.go`\n" + + "* `source/selected72.go`\n" + + "* `source/selected73.go`\n" + + "* `source/selected74.go`\n" + + "* `source/selected75.go`\n" + + "* `source/selected76.go`\n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "**Included review availability:** This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.\n" + + "\n" + + "
\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "" + +const submittedAdditionalAck = "\n" + + "\n" + + "\n" + + "\n" + + "
\n" + + "Action performed\n" + + "
\n" + + "
\n" + + "
\n" + + "\n" + + "Full review finished.\n" + + "\n" + + "
\n" + + "
\n" + + "
" + +func submittedAdditionalFixture(t *testing.T) hfFixture { + t.Helper() + f := submittedTestFixture(t) + f.snapshot.Reviews[0].Body = submittedAdditionalBody + f.snapshot.ReviewComments = []ReviewComment{} + f.snapshot.IssueComments[1].Body = submittedAdditionalAck + return f +} + +func TestHostedSubmittedAdditionalOnlyPreservesPositiveInventory(t *testing.T) { + for _, crlf := range []bool{false, true} { + name := "LF" + if crlf { + name = "CRLF" + } + t.Run(name, func(t *testing.T) { + f := submittedAdditionalFixture(t) + if crlf { + f.snapshot.Reviews[0].Body = strings.ReplaceAll(f.snapshot.Reviews[0].Body, "\n", "\r\n") + } + before, _ := json.Marshal(f.snapshot) + got := f.extract(t) + p := got.Publication + if !got.Complete || got.Reason != "finding_inventory_complete" || p.State != "attributed" || p.SubmittedReview == nil || p.SubmittedReview.ProviderRunID != submittedTestRun || p.SubmittedReview.Acknowledgement != f.snapshot.IssueComments[1] || p.PublicationID != "" || p.ProviderAttemptID != "" || p.StandingZero != nil || len(p.Batches) != 1 || p.Batches[0].ID != 401 || len(p.Roots) != 0 || !p.FinishedAt.Equal(f.snapshot.IssueComments[1].UpdatedAt) || len(got.Findings) != 1 { + t.Fatalf("additional submission lost positive inventory or real provenance: %+v", got) + } + finding := got.Findings[0] + if finding.Kind != "additional" || finding.ReviewID != 401 || finding.CommentID != 0 || finding.Severity != "info" || finding.Path != "docs/example.md" || finding.StartLine == nil || *finding.StartLine != 24 || finding.EndLine == nil || *finding.EndLine != 24 || finding.Title != "Consider the optional example wording." || !strings.Contains(finding.Detail, "Unverified finding") || !strings.Contains(finding.Detail, "This observation remains unverified.") || !strings.HasPrefix(finding.SourceKey, "hosted-review:401:additional:") { + t.Fatal("additional finding lost its original identity, location or qualification", finding) + } + if !strings.Contains(p.Batches[0].Body, finding.Detail) || p.Batches[0].Body != f.snapshot.Reviews[0].Body { + t.Fatal("review source was rewritten") + } + after, _ := json.Marshal(f.snapshot) + if string(before) != string(after) { + t.Fatal("source snapshot changed") + } + if again := f.extract(t); len(again.Findings) != 1 || again.Findings[0].SourceKey != finding.SourceKey { + t.Fatal("exact replay changed source identity") + } + if base, ok := ResolveHostedComparison(p, f.intent.HeadSHA, strings.Repeat("b", 40), strings.Repeat("c", 40)); !ok || base != strings.Repeat("b", 40) { + t.Fatal("exact comparison was lost", base, ok) + } + if _, ok := ResolveHostedComparison(p, f.intent.HeadSHA, strings.Repeat("c", 40), strings.Repeat("d", 40)); ok { + t.Fatal("unrelated comparison credited") + } + }) + } +} + +func TestHostedSubmittedAdditionalOnlyRejectsUnprovenBody(t *testing.T) { + replace := func(old, next string) func(string) string { + return func(body string) string { return strings.Replace(body, old, next, 1) } + } + cases := map[string]func(string) string{ + "generated envelope missing": replace("", ""), + "unknown generated envelope": replace("coderabbit-ai-generated:v1", "coderabbit-ai-generated:v2"), + "zero category": replace("Additional comments: 1", "Additional comments: 0"), + "category count mismatch": replace("Additional comments: 1", "Additional comments: 2"), + "category overflow": replace("Additional comments: 1", "Additional comments: 9999999999999999999999999"), + "unknown category": replace("Additional comments: 1", "Other comments: 1"), + "group count mismatch": replace("docs/example.md-24-24: 1", "docs/example.md-24-24: 2"), + "group range mismatch": replace("docs/example.md-24-24: 1", "docs/example.md-25-25: 1"), + "zero location": replace("`24-24`:", "`0-24`:"), + "reversed location": replace("`24-24`:", "`25-24`:"), + "path not selected": replace("docs/example.md-24-24: 1", "docs/absent.md-24-24: 1"), + "unsafe path": replace("docs/example.md-24-24: 1", "../example.md-24-24: 1"), + "missing title": replace("**Consider the optional example wording.**", "Consider the optional example wording."), + "unbalanced wrappers": replace("
\n", "\n"), + "duplicate bare break": replace("
\n
", "
\n
\n
"), + "misplaced break": replace("_Source: Linters/SAST tools_", "_Source: Linters/SAST tools_\n
"), + "missing h6": replace("
\n", ""), + "unknown h6": replace("
\n", "
\n"), + "missing status footer": replace("", ""), + "unknown trailer": func(body string) string { return body + "\nUnknown findings: 1" }, + "unknown prefix": func(body string) string { return "Unknown results\n" + body }, + "quoted envelope": func(body string) string { return "> " + strings.ReplaceAll(body, "\n", "\n> ") }, + "fenced envelope": func(body string) string { return "```\n" + body + "\n```" }, + "additional block in prompt": replace("
\n", "
\n🤖 Prompt to fix review comments\n
\n"), + "positive actionable claim": replace("", "\n**Actionable comments posted: 1**"), + "zero actionable claim": replace("", "\n**Actionable comments posted: 0**"), + "invalid actionable claim": replace("", "\n**Actionable comments posted: unknown**"), + "additional actionable claim": replace("_Source: Linters/SAST tools_", "**Actionable comments posted: 1**\n_Source: Linters/SAST tools_"), + "empty additional": func(body string) string { + start := strings.Index(body, "
") + end := strings.Index(body, "
") + return body[:start] + "
\n🔇 Additional comments: 1
\n
\n
\n
\n
\n
\n\n" + body[end:] + }, + "duplicate category": func(body string) string { + start := strings.Index(body, "
") + end := strings.Index(body, "
") + return body[:end] + body[start:end] + body[end:] + }, + "mixed outside category": replace("
", hfOutsideCategory(1, hfOutside(9, "docs/example.md", "7", "Unproven mixed result."))+"\n
"), + "mixed duplicate category": replace("
", hfDuplicateCategory(1, hfDuplicateGroup("docs/example.md", 1, hfDuplicateItem(9, "7-7", "Duplicate observation.")))+"\n
"), + "missing run": replace("- **Run ID**: `"+submittedTestRun+"`", ""), + "malformed run": replace(submittedTestRun, "unknown"), + "duplicate run": replace("- **Run ID**: `"+submittedTestRun+"`", "- **Run ID**: `"+submittedTestRun+"`\n- **Run ID**: `"+submittedTestRun+"`"), + "quoted run": replace("- **Run ID**:", "> - **Run ID**:"), + "fenced run": replace("- **Run ID**: `"+submittedTestRun+"`", "```\n- **Run ID**: `"+submittedTestRun+"`\n```"), + "missing comparison": replace(hostedScopeDeclaration(strings.Repeat("b", 40), strings.Repeat("a", 40)), "No comparison declared."), + "partial comparison": replace("from the base of the PR", "in selected files"), + "wrong comparison head": replace("and "+strings.Repeat("a", 40)+".", "and "+strings.Repeat("c", 40)+"."), + "wrong configuration commit": replace("/commit/"+strings.Repeat("a", 40), "/commit/"+strings.Repeat("c", 40)), + "wrong configuration file head": replace("/blob/"+strings.Repeat("a", 40), "/blob/"+strings.Repeat("c", 40)), + "selected count mismatch": replace("processing: 77", "processing: 76"), + "duplicate selected path": replace("* `source/selected02.go`", "* `source/selected01.go`"), + "zero selected": replace("processing: 77", "processing: 0"), + "unknown metadata": replace("- **Layers**:", "- **Unknown field**:"), + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + f := submittedAdditionalFixture(t) + f.snapshot.Reviews[0].Body = mutate(f.snapshot.Reviews[0].Body) + if f.snapshot.Reviews[0].Body == submittedAdditionalBody { + t.Fatal("mutation did not alter fixture") + } + got := f.extract(t) + if got.Complete || got.Publication.State == "attributed" || got.Publication.SubmittedReview != nil || len(got.Findings) != 0 || !got.Publication.FinishedAt.IsZero() { + t.Fatalf("unproven body credited: state=%s reason=%s complete=%t findings=%d", got.Publication.State, got.Reason, got.Complete, len(got.Findings)) + } + }) + } +} + +func TestHostedSubmittedAdditionalOnlyKeepsAttributionBoundaries(t *testing.T) { + cases := map[string]func(*hfFixture){ + "incomplete source": func(f *hfFixture) { f.snapshot.Complete = false }, + "unknown root collection": func(f *hfFixture) { f.snapshot.ReviewComments = nil }, + "unknown issue collection": func(f *hfFixture) { f.snapshot.IssueComments = nil }, + "wrong provider actor": func(f *hfFixture) { f.snapshot.Reviews[0].Author.ID++ }, + "wrong provider kind": func(f *hfFixture) { f.snapshot.Reviews[0].Author.Kind = "User" }, + "wrong head": func(f *hfFixture) { f.snapshot.Reviews[0].HeadSHA = strings.Repeat("d", 40) }, + "pending review": func(f *hfFixture) { + f.snapshot.Reviews[0].State = "pending" + f.snapshot.Reviews[0].SubmittedAt = time.Time{} + }, + "equal trigger time": func(f *hfFixture) { f.snapshot.Reviews[0].SubmittedAt = f.snapshot.IssueComments[0].CreatedAt }, + "before trigger": func(f *hfFixture) { + f.snapshot.Reviews[0].SubmittedAt = f.snapshot.IssueComments[0].CreatedAt.Add(-time.Second) + }, + "competing review": func(f *hfFixture) { + other := f.snapshot.Reviews[0] + other.ID++ + f.snapshot.Reviews = append(f.snapshot.Reviews, other) + }, + "competing foreign head review": func(f *hfFixture) { + other := f.snapshot.Reviews[0] + other.ID++ + other.HeadSHA = strings.Repeat("d", 40) + f.snapshot.Reviews = append(f.snapshot.Reviews, other) + }, + "reused historical run": func(f *hfFixture) { + other := f.snapshot.Reviews[0] + other.ID++ + other.SubmittedAt = f.snapshot.IssueComments[0].CreatedAt.Add(-time.Hour) + f.snapshot.Reviews = append(f.snapshot.Reviews, other) + }, + "missing acknowledgement": func(f *hfFixture) { f.snapshot.IssueComments = f.snapshot.IssueComments[:1] }, + "foreign acknowledgement": func(f *hfFixture) { f.snapshot.IssueComments[1].Author.ID++ }, + "unknown acknowledgement": func(f *hfFixture) { f.snapshot.IssueComments[1].Body = "Full review finished." }, + "acknowledgement before trigger": func(f *hfFixture) { + f.snapshot.IssueComments[1].CreatedAt = f.snapshot.IssueComments[0].CreatedAt.Add(-time.Second) + }, + "acknowledgement at submission": func(f *hfFixture) { f.snapshot.IssueComments[1].UpdatedAt = f.snapshot.Reviews[0].SubmittedAt }, + "acknowledgement before submission": func(f *hfFixture) { + f.snapshot.IssueComments[1].UpdatedAt = f.snapshot.Reviews[0].SubmittedAt.Add(-time.Second) + }, + "duplicate acknowledgement": func(f *hfFixture) { + other := f.snapshot.IssueComments[1] + other.ID++ + f.snapshot.IssueComments = append(f.snapshot.IssueComments, other) + }, + "unknown provider reply": func(f *hfFixture) { + other := f.snapshot.IssueComments[1] + other.ID++ + other.Body = "Unknown output" + f.snapshot.IssueComments = append(f.snapshot.IssueComments, other) + }, + "competing trigger": func(f *hfFixture) { + other := f.snapshot.IssueComments[0] + other.ID = 303 + other.Body = "@coderabbitai full review" + other.CreatedAt = other.CreatedAt.Add(1500 * time.Millisecond) + other.UpdatedAt = other.CreatedAt + f.snapshot.IssueComments = append(f.snapshot.IssueComments, other) + }, + "attached root": func(f *hfFixture) { + other := submittedTestFixture(t) + f.snapshot.ReviewComments = other.snapshot.ReviewComments[:1] + }, + "orphan root": func(f *hfFixture) { + other := submittedTestFixture(t) + other.snapshot.ReviewComments[0].ReviewID = 999 + f.snapshot.ReviewComments = other.snapshot.ReviewComments[:1] + }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + f := submittedAdditionalFixture(t) + mutate(&f) + got := f.extract(t) + if got.Complete || got.Publication.State == "attributed" || got.Publication.SubmittedReview != nil || len(got.Findings) != 0 || !got.Publication.FinishedAt.IsZero() { + t.Fatalf("attribution boundary bypassed: state=%s reason=%s complete=%t findings=%d", got.Publication.State, got.Reason, got.Complete, len(got.Findings)) + } + }) + } +} + +func TestHostedSubmittedAdditionalUnknownSeverityRemainsUnknown(t *testing.T) { + f := submittedAdditionalFixture(t) + f.snapshot.Reviews[0].Body = strings.Replace(f.snapshot.Reviews[0].Body, "Trivial**", "Unknown**", 1) + got := f.extract(t) + if !got.Complete || len(got.Findings) != 1 || got.Findings[0].Severity != "unknown" || !strings.Contains(got.Findings[0].Detail, "Unknown**") || got.Publication.StandingZero != nil { + t.Fatal("unknown severity became a clean result or invented a severity", got.Reason) + } +} + +func TestHostedSubmittedAdditionalOnlyCountsEveryItem(t *testing.T) { + f := submittedAdditionalFixture(t) + start := strings.Index(f.snapshot.Reviews[0].Body, "`24-24`:") + end := strings.Index(f.snapshot.Reviews[0].Body[start:], "\n
") + start + item := f.snapshot.Reviews[0].Body[start:end] + second := strings.ReplaceAll(item, "`24-24`:", "`30-30`:") + second = strings.Replace(second, "Consider the optional example wording.", "Consider a second optional example.", 1) + f.snapshot.Reviews[0].Body = strings.Replace(f.snapshot.Reviews[0].Body, item, item+"\n"+second, 1) + f.snapshot.Reviews[0].Body = strings.Replace(f.snapshot.Reviews[0].Body, "Additional comments: 1", "Additional comments: 2", 1) + f.snapshot.Reviews[0].Body = strings.Replace(f.snapshot.Reviews[0].Body, "docs/example.md-24-24: 1", "docs/example.md-24-30: 2", 1) + got := f.extract(t) + if !got.Complete || len(got.Findings) != 2 || got.Findings[0].SourceKey == got.Findings[1].SourceKey || got.Findings[1].Title != "Consider a second optional example." { + t.Fatal("counted additional inventory lost an item", got.Reason, len(got.Findings)) + } + f.snapshot.Reviews[0].Body = strings.Replace(f.snapshot.Reviews[0].Body, second, item, 1) + got = f.extract(t) + if got.Complete || got.Publication.State == "attributed" || len(got.Findings) != 0 { + t.Fatal("duplicated additional item supplied a count", got.Reason) + } +} diff --git a/internal/reviewprovider/hosted_submitted_review.go b/internal/reviewprovider/hosted_submitted_review.go index ba6fd2e16..c34babd5c 100644 --- a/internal/reviewprovider/hosted_submitted_review.go +++ b/internal/reviewprovider/hosted_submitted_review.go @@ -139,6 +139,10 @@ func parseSubmittedReview(body, head string) (run string, count int, selected ma } func parseSubmittedReviewEnvelope(body, head string, current, marked bool) (run string, count int, selected map[string]bool, ok bool) { + return parseSubmittedReviewKind(body, head, current, marked, false) +} + +func parseSubmittedReviewKind(body, head string, current, marked, additionalOnly bool) (run string, count int, selected map[string]bool, ok bool) { if !validBody(body) { return } @@ -150,48 +154,54 @@ func parseSubmittedReviewEnvelope(body, head string, current, marked bool) (run if !p.take("", true) { return } - if line, _ := p.next(); !current || line.text != "---" { - claim, valid := p.text() - match := publicationActionable.FindStringSubmatch(claim) - if !valid || match == nil { - return - } - count, _ = strconv.Atoi(match[1]) - if count < 1 || count > 200 || !p.caution(body) { + if additionalOnly { + if !current || marked || !p.additionalOnly() || !p.take("
", false) { return } - } - if !p.take("---", false) { - return - } - if line, _ := p.next(); line.text == "" { - if count == 0 || !p.take(line.text, true) { - return + } else { + if line, _ := p.next(); !current || line.text != "---" { + claim, valid := p.text() + match := publicationActionable.FindStringSubmatch(claim) + if !valid || match == nil { + return + } + count, _ = strconv.Atoi(match[1]) + if count < 1 || count > 200 || !p.caution(body) { + return + } } - checkbox, found := p.next() - if !found || checkbox.quote != 0 || !checkbox.hidden || !submittedAutofix.MatchString(checkbox.text) { + if !p.take("---", false) { return } - p.at++ - if !p.take("", true) { - return - } - } - // The optional prompt is opaque. findingBlock retains visibility across - // fences/quotes, so examples cannot close the prompt and become metadata. - if current { - if !p.currentPrompt(body) || !p.take("
", false) { - return + if line, _ := p.next(); line.text == "" { + if count == 0 || !p.take(line.text, true) { + return + } + checkbox, found := p.next() + if !found || checkbox.quote != 0 || !checkbox.hidden || !submittedAutofix.MatchString(checkbox.text) { + return + } + p.at++ + if !p.take("", true) { + return + } } - } else if line, found := p.next(); found && !line.hidden && line.quote == 0 && line.text == "
" { - end, complete := findingBlock(lines, p.at, 0) - label := submittedReviewParser{lines: lines, at: p.at + 1} - header, visible := label.next() - if complete && visible && !header.hidden && header.quote == 0 && (header.text == "🤖 Prompt to fix review comments" || findingPromptIcon.MatchString(header.text)) { - p.at = end + 1 - if !p.take("---", false) { + // The optional prompt is opaque. findingBlock retains visibility across + // fences/quotes, so examples cannot close the prompt and become metadata. + if current { + if !p.currentPrompt(body) || !p.take("
", false) { return } + } else if line, found := p.next(); found && !line.hidden && line.quote == 0 && line.text == "
" { + end, complete := findingBlock(lines, p.at, 0) + label := submittedReviewParser{lines: lines, at: p.at + 1} + header, visible := label.next() + if complete && visible && !header.hidden && header.quote == 0 && (header.text == "🤖 Prompt to fix review comments" || findingPromptIcon.MatchString(header.text)) { + p.at = end + 1 + if !p.take("---", false) { + return + } + } } } if !p.block("ℹ️ Review info") { @@ -362,7 +372,12 @@ func resolveSubmittedReview(snapshot HostedPublicationSnapshot, result HostedPub if !valid { run, count, selected, valid = parseSubmittedReviewEnvelope(review.Body, intent.HeadSHA, true, false) } - if !valid || count == 0 { + additionalOnly := false + if !valid { + run, count, selected, valid = parseSubmittedReviewKind(review.Body, intent.HeadSHA, true, false, true) + additionalOnly = valid + } + if !valid || count == 0 && !additionalOnly { return result, false } inside := func(at time.Time) bool { @@ -426,7 +441,11 @@ func resolveSubmittedReview(snapshot HostedPublicationSnapshot, result HostedPub copy.OriginalStartLine = copyPublicationLine(comment.OriginalStartLine) roots = append(roots, copy) } - if !hostedInlineCountMatches(roots, count) { + if additionalOnly { + if snapshot.ReviewComments == nil || len(roots) != 0 || !publicationCountAbsent(result) || !submittedAdditionalInventory(review, selected) { + return result, false + } + } else if !hostedInlineCountMatches(roots, count) { return result, false } sort.Slice(roots, func(i, j int) bool { return roots[i].ID < roots[j].ID })