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/core/event_project.go b/internal/core/event_project.go
index 6324bc2b4..275884ed7 100644
--- a/internal/core/event_project.go
+++ b/internal/core/event_project.go
@@ -18,7 +18,8 @@ var projectEventTypes = [...]string{
"job.workstream_changed", "job.created", "job.updated", "job.checkpointed", "job.update_appended", "job.checklist_replaced",
"workers.created", "workers.retired", "worker.pause_changed", "worker.primary_job_changed",
"note.created", "note.updated",
- "review.observed", "reviews.policy_configured", "reviews.rounds_configured",
+ "review.requested", "review.operation_updated",
+ "review.observed", "reviews.configured", "reviews.policy_configured", "reviews.rounds_configured",
"reviews.adoption_obligations_imported", "reviews.adoption_obligation_resolved", "reviews.adoption_obligation_retargeted",
"review.evidence.adjudicated", "review.evidence.finalized", "review.evidence.fix_recorded", "review.evidence.routed",
"review.route.routed", "review.route.superseded", "review.route.adjudicated", "review.route.fix_recorded",
diff --git a/internal/core/live_project_events_test.go b/internal/core/live_project_events_test.go
index b0093c8c4..c0eba734c 100644
--- a/internal/core/live_project_events_test.go
+++ b/internal/core/live_project_events_test.go
@@ -16,7 +16,7 @@ func TestLiveProjectReplayVisibleStateOnly(t *testing.T) {
"project.presentation_changed", "map.entry_created", "map.entry_updated",
"job.workstream_changed", "job.created", "job.updated", "job.checkpointed", "job.update_appended", "job.checklist_replaced",
"workers.created", "workers.retired", "worker.pause_changed", "worker.primary_job_changed", "note.created", "note.updated",
- "review.observed", "reviews.policy_configured",
+ "review.requested", "review.operation_updated", "review.observed", "reviews.configured", "reviews.policy_configured",
"review.evidence.adjudicated", "review.evidence.finalized", "review.evidence.fix_recorded", "review.evidence.routed",
"review.route.routed", "review.route.superseded", "review.route.adjudicated", "review.route.fix_recorded",
}
@@ -27,7 +27,7 @@ func TestLiveProjectReplayVisibleStateOnly(t *testing.T) {
// browser view. A future same-prefix event is not implicitly opted in.
for i, kind := range []string{
"message.sent", "message.seen", "message.acknowledged", "credentials.revoked",
- "reviews.configured", "review.requested", "review.captured", "review.capture_observed",
+ "review.captured", "review.capture_observed",
"review.source_refresh_requested", "review.source_refresh_updated", "reviews.checkpoint_publication",
"review.cli_preflight", "review.hosted_preflight", "review.hosted_query_started", "review.hosted_query_posted", "review.hosted_settled",
"job.future", "review.evidence.future", "review.route.future",
diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go
index f8fb898ba..c17d7a582 100644
--- a/internal/mcpadapter/adapter_test.go
+++ b/internal/mcpadapter/adapter_test.go
@@ -243,6 +243,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 8eb76a616..b32cef4e8 100644
--- a/internal/mcpadapter/review_scheduling.go
+++ b/internal/mcpadapter/review_scheduling.go
@@ -49,7 +49,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) {
@@ -61,6 +61,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 {
@@ -138,6 +148,7 @@ func reviewSchedulingDefinitions() []definition {
pullUpdate["if"] = map[string]any{"properties": map[string]any{"paused": map[string]any{"const": false}}}
pullUpdate["then"] = map[string]any{"not": map[string]any{"required": []string{"reason"}}}
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. If either channel stays enabled, this connection's current credential and active bound worker become the shared authorizer for new work, even when disabling only the other channel. Omission preserves the CLI setting, not the authorizer; 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 064f3cd2e..dfd5a91f1 100644
--- a/internal/mcpadapter/tools.go
+++ b/internal/mcpadapter/tools.go
@@ -205,6 +205,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/adoption_holds_integration_test.go b/internal/reviewexec/adoption_holds_integration_test.go
index 84a25474a..7d368df11 100644
--- a/internal/reviewexec/adoption_holds_integration_test.go
+++ b/internal/reviewexec/adoption_holds_integration_test.go
@@ -235,7 +235,7 @@ func integrationSelectionWorker(t *testing.T, f *attemptFixture) {
}
}
-func TestAdoptionHoldsIntegrationFinalPredecessorRecheck(t *testing.T) {
+func TestAdoptionHoldsIntegrationAncestorObligationsStayLocal(t *testing.T) {
for _, mode := range []string{"covered", "closed", "tapered", "merged"} {
t.Run(mode, func(t *testing.T) {
f, prior, id, predecessor := coverageFixture(t, 0, false)
@@ -289,7 +289,11 @@ func TestAdoptionHoldsIntegrationFinalPredecessorRecheck(t *testing.T) {
_, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "merged-source-still-held", Request{ExpectedConfigurationRevision: 2, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)})
integrationSourceHeld(t, err)
} else {
- integrationSourceHeld(t, f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, predecessors...))
+ if err := f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, predecessors...); err != nil {
+ t.Fatal("ancestor adoption work blocked child review", err)
+ }
+ _, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "ancestor-target-still-held", Request{ExpectedConfigurationRevision: 2, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)})
+ integrationSourceHeld(t, err)
}
if after := integrationHoldDetail(t, f, hold.ID); !reflect.DeepEqual(beforeHold, after) || after.Status != "open" {
t.Fatal("final guard changed the retained source hold", beforeHold, after)
@@ -600,9 +604,11 @@ func TestAdoptionHoldsIntegrationSelectionRechecksActualParent(t *testing.T) {
t.Fatal(worked, err)
}
got := selectionRead(t, f, r.ID)
- if !imported || got.State != "held" || got.Reason != "source_obligations_pending" || got.OperationID != "" || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 {
- t.Fatal("late actual-parent hold escaped transactional child admission", got)
+ if !imported || got.State != "selected" || got.OperationID == "" || roundOperation(t, f, got.OperationID).PullNumber != 4 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 {
+ t.Fatal("ancestor adoption work blocked exact child selection", got)
}
+ _, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "late-ancestor-target-still-held", Request{ExpectedConfigurationRevision: 2, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)})
+ integrationSourceHeld(t, err)
}
func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare(t *testing.T) {
diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go
index 3face4369..18995a479 100644
--- a/internal/reviewexec/front_evaluator.go
+++ b/internal/reviewexec/front_evaluator.go
@@ -10,9 +10,11 @@ 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
- localRefusal error
+ state, reason string
+ plan *SourcePlan
+ blockingPull int64
+ blockingReason string
+ localRefusal error
}
func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo int64, plan *SourcePlan) (evaluatedFront, error) {
@@ -104,6 +106,66 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i
return evaluatedFront{state: "ready", plan: plan}, nil
}
+// evaluateCandidatePlan shares source-identity checks with lane diagnostics.
+// Ancestor review sufficiency is not permission to review a child's pinned diff.
+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(parent int64) (string, error) { return pinnedParentSchedulingReason(ctx, q, r.ProjectID, parent) })
+}
+
+func evaluateCandidateLocalState(plan *SourcePlan, byNumber map[int64]*SourcePlan, evaluate func(*SourcePlan) (evaluatedFront, error), parentScheduling func(int64) (string, 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"
+ case parent.Repository.ID != plan.Repository.ID || !sameTarget(parent.Pull, plan.Repository.ID, parentNumber):
+ reason = "parent_identity_changed"
+ case parent.SourceReason != "":
+ reason = parent.SourceReason
+ case parent.Pull.State != "open" || parent.Pull.Merged:
+ reason = "parent_unavailable"
+ }
+ if reason == "" && parentScheduling != nil {
+ reason, err = parentScheduling(parentNumber)
+ if err != nil {
+ return evaluatedFront{}, err
+ }
+ }
+ if reason != "" {
+ return evaluatedFront{state: "held", reason: "predecessor_unfinished", plan: plan, blockingPull: parentNumber, blockingReason: reason}, nil
+ }
+ seen[parentNumber] = true
+ // The parent supplies source identity, not review completion or allowance.
+ // Its findings, rounds and PR pause remain obligations on that parent.
+ parentNumber, parentSHA = parent.ParentPullNumber, parent.ParentSHA
+ }
+ return result, nil
+}
+
+// A valid pause is not source invalidation. Unreadable retained scheduling
+// for this exact ancestor cannot support a dependent eligibility decision.
+func pinnedParentSchedulingReason(ctx context.Context, q *sql.Tx, project string, pull int64) (string, error) {
+ _, err := readPullScheduling(ctx, q, project, pull)
+ var state *pullSchedulingStateError
+ if errors.As(err, &state) && state.project == project && state.pull == pull {
+ return "automatic_scheduling_unavailable", nil
+ }
+ return "", err
+}
+
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 {
@@ -112,7 +174,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
}
@@ -122,27 +184,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/hosted_admission_test.go b/internal/reviewexec/hosted_admission_test.go
index dafb3aa90..17cef4902 100644
--- a/internal/reviewexec/hosted_admission_test.go
+++ b/internal/reviewexec/hosted_admission_test.go
@@ -150,13 +150,13 @@ func hostedAdmissionStack(t *testing.T, f *attemptFixture, open SourcePlan) (Att
return child, []SourcePlan{open}
}
-func TestHostedAdmissionStackRequiresHostedPredecessor(t *testing.T) {
+func TestHostedAdmissionStackDoesNotRequireAncestorReviewCoverage(t *testing.T) {
hostedAdmissionNoHTTP(t)
f, prior, id, open := coverageFixture(t, 0, false)
coverageFinalize(t, f, prior, id, 0)
child, plans := hostedAdmissionStack(t, f, open)
- // A complete native CLI predecessor cannot advance the hosted cycle.
- hostedAdmissionVerify(t, f, child, "review_held", "predecessor_unfinished", plans...)
+ // The ancestor needs no Hosted completion to review the child's exact diff.
+ hostedAdmissionVerify(t, f, child, "", "", plans...)
}
func TestHostedAdmissionStackChecksAllFreshPlansAndLateFixCorrection(t *testing.T) {
@@ -191,7 +191,7 @@ func TestHostedAdmissionStackChecksAllFreshPlansAndLateFixCorrection(t *testing.
moved[0].Pull.HeadSHA = strings.Repeat("9", 40)
hostedAdmissionVerify(t, f, child, "validation_failed", "", moved...)
adjudicationDecide(t, f, id, "hosted-stack-correct", 4, 0, "accepted")
- hostedAdmissionVerify(t, f, child, "review_held", "predecessor_unfinished", plans...)
+ hostedAdmissionVerify(t, f, child, "", "", plans...)
coverageFix(t, f, id, "hosted-stack-fix", 5, 0, "")
hostedAdmissionVerify(t, f, child, "", "", plans...)
admissionPolicy(t, f, 1, "hosted")
diff --git a/internal/reviewexec/lane_diagnostic.go b/internal/reviewexec/lane_diagnostic.go
new file mode 100644
index 000000000..1fb46ef82
--- /dev/null
+++ b/internal/reviewexec/lane_diagnostic.go
@@ -0,0 +1,150 @@
+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 {
+ if (frame.repository != repository || frame.sourceReason == "repository_changed") && out.LaneReason == "" {
+ out.LaneReason = "repository_changed"
+ }
+ 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"
+ }
+ }
+ // A partial observation can retain earlier candidates even when a
+ // later read detects a repository change. Those candidates are not
+ // usable diagnostics, even if the stored binding still matches.
+ usable := found && frame.configuration == revision && frame.repository == repository && frame.sourceReason != "repository_changed"
+ 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
+ }
+ parentScheduling := map[int64]string{}
+ verifyParent := func(pull int64) (string, error) {
+ if reason, ok := parentScheduling[pull]; ok {
+ return reason, nil
+ }
+ reason, err := pinnedParentSchedulingReason(ctx, tx, scope.ProjectID, pull)
+ if err == nil {
+ parentScheduling[pull] = reason
+ }
+ return reason, 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, verifyParent)
+ 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_repository_change_test.go b/internal/reviewexec/lane_diagnostic_repository_change_test.go
new file mode 100644
index 000000000..1169fe475
--- /dev/null
+++ b/internal/reviewexec/lane_diagnostic_repository_change_test.go
@@ -0,0 +1,34 @@
+package reviewexec
+
+import (
+ "context"
+ "database/sql"
+ "testing"
+)
+
+func TestLaneDiagnosticSuppressesRetainedPrefixAfterRepositoryChange(t *testing.T) {
+ f := schedulingFixture(t)
+ 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: "cli", ConfigurationRevision: rev}, 801, c, runChoice{prefix: []SourcePlan{laneDiagnosticPlan(2)}, sourceReason: "repository_changed"})
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ before := selectionCounts(t, f)
+ out, err := f.e.ReadLaneDiagnostic(t.Context(), selectionScope(t, f, attemptProject, f.reader, "read"), "cli")
+ if err != nil || out.SourceReason != "repository_changed" || out.SourceComplete || len(out.Candidates) != 2 {
+ t.Fatal(out, err)
+ }
+ for _, candidate := range out.Candidates {
+ if candidate.HeadSHA != "" || candidate.SourceObservedAt != "" || candidate.ParentPullNumber != 0 || candidate.LocalState != "unknown" || candidate.LocalReason != "source_not_observed" {
+ t.Fatal("repository change must invalidate the complete retained prefix", candidate)
+ }
+ }
+ if selectionCounts(t, f) != before {
+ t.Fatal("diagnostic changed selection state")
+ }
+}
diff --git a/internal/reviewexec/lane_diagnostic_test.go b/internal/reviewexec/lane_diagnostic_test.go
new file mode 100644
index 000000000..3a5d8cb3d
--- /dev/null
+++ b/internal/reviewexec/lane_diagnostic_test.go
@@ -0,0 +1,244 @@
+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 TestLaneDiagnosticIndependentAndStackedReviewProgress(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 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}, true)
+ if err != nil {
+ return err
+ }
+ 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.LaneReason != "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")
+ }
+}
+
+func TestStackReviewSourceIdentityRemainsRequired(t *testing.T) {
+ for _, cause := range []string{"parent_source_unavailable", "parent_moved", "parent_identity_changed", "pull_draft", "parent_unavailable", "parent_cycle"} {
+ t.Run(cause, func(t *testing.T) {
+ parent, child := laneDiagnosticPlan(2), laneDiagnosticPlan(4)
+ child.ParentPullNumber, child.ParentSHA, child.Pull.BaseSHA = 2, parent.Pull.HeadSHA, parent.Pull.HeadSHA
+ byNumber := map[int64]*SourcePlan{2: &parent, 4: &child}
+ switch cause {
+ case "parent_source_unavailable":
+ delete(byNumber, 2)
+ case "parent_moved":
+ parent.Pull.HeadSHA = strings.Repeat("f", 40)
+ case "parent_identity_changed":
+ parent.Repository.ID++
+ case "pull_draft":
+ parent.SourceReason = cause
+ case "parent_unavailable":
+ parent.Pull.State = "closed"
+ case "parent_cycle":
+ parent.ParentPullNumber, parent.ParentSHA = 4, child.Pull.HeadSHA
+ }
+ calls := 0
+ out, err := evaluateCandidateLocalState(&child, byNumber, func(p *SourcePlan) (evaluatedFront, error) {
+ calls++
+ if p.Pull.Number != 4 {
+ t.Fatal("ancestor review state was evaluated")
+ }
+ return evaluatedFront{state: "ready", plan: p}, nil
+ }, nil)
+ if err != nil || out.state != "held" || out.blockingReason != cause || calls != 1 {
+ t.Fatal("source identity was bypassed", out, calls, err)
+ }
+ })
+ }
+}
+
+func TestLaneDiagnosticRetainedRepositoryChangeReportsLaneHold(t *testing.T) {
+ f := schedulingFixture(t)
+ laneDiagnosticFrame(t, f, "cli", []SourcePlan{laneDiagnosticPlan(2), laneDiagnosticPlan(4)})
+ admissionSQL(t, f, `UPDATE review_front_frames SET complete=0,source_reason='repository_changed' WHERE project_id=? AND channel='cli'`, attemptProject)
+ out, err := f.e.ReadLaneDiagnostic(t.Context(), selectionScope(t, f, attemptProject, f.reader, "read"), "cli")
+ if err != nil || out.SourceReason != "repository_changed" || out.LaneReason != "repository_changed" || out.SourceComplete {
+ t.Fatal(out, err)
+ }
+ for _, candidate := range out.Candidates {
+ if candidate.LocalState != "unknown" || candidate.HeadSHA != "" {
+ t.Fatal(candidate)
+ }
+ }
+}
diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go
index b79916679..4c4113db1 100644
--- a/internal/reviewexec/policy_admission.go
+++ b/internal/reviewexec/policy_admission.go
@@ -324,16 +324,9 @@ func verifyPredecessors(ctx context.Context, tx *sql.Tx, project string, current
if err != nil || observed.IsZero() || plan.Repository.ID != current.RepositoryID || !repository.MatchString(plan.Repository.FullName) || plan.Repository.DefaultBranch == "" || !safeText(plan.Repository.DefaultBranch, 256) || !sameTarget(plan.Pull, current.RepositoryID, number) || !validCoverageSource(plan) || plan.Pull.Merged {
return invalid()
}
- if err := requireSourceObligationsClear(ctx, tx, project, number); err != nil {
- return err
- }
- state, err := channelProgress(ctx, tx, project, current.RepositoryID, number, current.Operation.Channel)
- if err != nil {
- return err
- }
- if state.Pending || state.RoundsConfigured && !state.RoundsComplete || !state.RoundsConfigured && !state.Covered {
- return sourceHold("predecessor_unfinished")
- }
+ // Ancestor findings, imported obligations and unfinished rounds do not
+ // invalidate this child's exact source comparison. Target-local obligations
+ // are rechecked separately in this same admission snapshot.
number, head, branch = plan.ParentPullNumber, plan.ParentSHA, plan.Pull.BaseRef
}
if number != 0 {
diff --git a/internal/reviewexec/policy_admission_test.go b/internal/reviewexec/policy_admission_test.go
index 704c1fad0..427d37c38 100644
--- a/internal/reviewexec/policy_admission_test.go
+++ b/internal/reviewexec/policy_admission_test.go
@@ -466,11 +466,13 @@ func TestVerifyActionStackedRequiresExactActualParentWitness(t *testing.T) {
if adjudicationState(t, f, child) != before {
t.Fatal("moved actual parent refusal changed retained state")
}
- // The proof was ready at preparation, but a real current correction now needs
- // a fix. The final guard must check predecessors and target in the same read.
+ // A late accepted ancestor finding does not change the child's pinned diff.
+ // The final guard preserves that obligation without making it a review gate.
adjudicationDecide(t, f, id, "late-predecessor-acceptance", 2, 0, "accepted")
afterCorrection := adjudicationState(t, f, child)
- attemptCode(t, f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, dependencies...), "review_held")
+ if err := f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, dependencies...); err != nil {
+ t.Fatal("ancestor fix work blocked child review", err)
+ }
if adjudicationState(t, f, child) != afterCorrection {
t.Fatal("late predecessor refusal mutated state")
}
diff --git a/internal/reviewexec/review636_probe_test.go b/internal/reviewexec/review636_probe_test.go
new file mode 100644
index 000000000..46e9047fa
--- /dev/null
+++ b/internal/reviewexec/review636_probe_test.go
@@ -0,0 +1,159 @@
+package reviewexec
+
+import (
+ "context"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/benhook1013/FireController/internal/reviewprovider"
+)
+
+func TestReview636AncestorHoldBeforeAllChildAdmission(t *testing.T) {
+ for _, mode := range []string{"covered", "closed", "tapered", "merged"} {
+ t.Run(mode, func(t *testing.T) {
+ f, prior, id, predecessor := coverageFixture(t, 0, false)
+ coverageFinalize(t, f, prior, id, 0)
+ if mode == "closed" {
+ zero := int64(0)
+ if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "close", 2, "cli", RoundControlRequest{ExpectedRevision: &zero, Action: "close"}); err != nil {
+ t.Fatal(err)
+ }
+ } else if mode == "tapered" {
+ if _, err := f.store.DB().Exec(`INSERT INTO workers(project_id,id,name) VALUES(?,'adoption-worker','Synthetic importer')`, attemptProject); err != nil {
+ t.Fatal(err)
+ }
+ p := adoptionPrepared()
+ p.Tapered, p.InitialDry = true, 3
+ adoptRound(t, f, p, "taper")
+ } else if mode == "merged" {
+ predecessor.Pull.State, predecessor.Pull.Merged = "closed", true
+ }
+ previous := int64(1)
+ if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "stack", Configuration{ExpectedRevision: &previous, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}}); err != nil {
+ t.Fatal(err)
+ }
+ _, _, hold := integrationImportHold(t, f, 2)
+ beforeHold := integrationHoldDetail(t, f, hold.ID)
+ operation := f.enqueue(t, attemptProject, "child", "cli", 4, 2)
+ child := f.start(t, attemptProject, operation)
+ if _, err := f.e.ExecutionContext(t.Context(), attemptProject, operation.ID); err != nil {
+ t.Fatal("preparation blocked by ancestor", err)
+ }
+ if _, err := f.e.RoundAdmission(t.Context(), attemptProject, operation.ID); err != nil {
+ t.Fatal("round admission blocked by ancestor", err)
+ }
+ anchor := attemptAnchor(attemptProject, 4)
+ anchor.ParentSHA = anchor.BaseSHA
+ var predecessors []SourcePlan
+ if mode != "merged" {
+ predecessor.Pull.HeadRef = "actual-parent"
+ anchor.ParentPullNumber, anchor.ParentSHA, anchor.BaseSHA, anchor.BaseRef = 2, predecessor.Pull.HeadSHA, predecessor.Pull.HeadSHA, "actual-parent"
+ predecessors = []SourcePlan{predecessor}
+ }
+ var err error
+ child, err = f.e.Admit(t.Context(), attemptProject, child.ID, child.Revision, anchor, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, predecessors...); err != nil {
+ t.Fatal("baseline predecessor failed", err)
+ }
+ before := attemptState(t, f, child)
+
+ if mode == "merged" {
+ // A merged former queue prefix is not an ancestor of a main-based
+ // target and cannot be supplied as its dependency witness.
+ attemptCode(t, f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, predecessor), "validation_failed")
+ if err := f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision); err != nil {
+ t.Fatal("unrelated merged hold blocked independent target", err)
+ }
+ _, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "merged-source-still-held", Request{ExpectedConfigurationRevision: 2, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)})
+ integrationSourceHeld(t, err)
+ } else {
+ if err := f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, predecessors...); err != nil {
+ t.Fatal("ancestor adoption work blocked child review", err)
+ }
+ _, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "ancestor-target-still-held", Request{ExpectedConfigurationRevision: 2, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)})
+ integrationSourceHeld(t, err)
+ }
+ if after := integrationHoldDetail(t, f, hold.ID); !reflect.DeepEqual(beforeHold, after) || after.Status != "open" {
+ t.Fatal("final guard changed the retained source hold", beforeHold, after)
+ }
+ if attemptState(t, f, child) != before {
+ t.Fatal("predecessor hold rewrote child work")
+ }
+ })
+ }
+}
+
+func TestReview636CompletedSourceRetryUsesCurrentSharedRevision(t *testing.T) {
+ f, stale := sourceRetryFixture(t)
+ ageSourceRetry(t, f, stale.ID)
+ stale = selectionRead(t, f, stale.ID)
+ one := int64(1)
+ on := true
+ _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "other-channel", SchedulingRequest{ExpectedRevision: &one, AutomaticHosted: &on, AutomaticCLI: &on})
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertRevision := func(selectionID string, acceptedWant, currentWant int64) {
+ t.Helper()
+ var accepted, current int64
+ err := f.store.DB().QueryRow(`SELECT a.scheduling_revision,s.revision FROM review_automatic_selections a
+ JOIN review_scheduling s ON s.project_id=a.project_id WHERE a.selection_id=? AND a.project_id=?`,
+ selectionID, attemptProject).Scan(&accepted, ¤t)
+ if err != nil || accepted != acceptedWant || current != currentWant {
+ t.Fatalf("retained selection revision=%d current=%d, want %d/%d: %v", accepted, current, acceptedWant, currentWant, err)
+ }
+ }
+ assertRevision(stale.ID, 1, 2)
+
+ // Changing only CLI leaves the Hosted intent basis unchanged, but must not
+ // requeue a completed hold under its superseded shared authorization.
+ reader := &refreshTestReader{}
+ worked, err := f.e.generateAutomaticHosted(t.Context(), map[string]TargetReader{"test-capability": reader})
+ if err != nil || worked || reader.calls.Load() != 0 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 {
+ t.Fatalf("stale retry performed work or replaced the held intent: worked=%t calls=%d err=%v", worked, reader.calls.Load(), err)
+ }
+ if got := selectionRead(t, f, stale.ID); got != stale {
+ t.Fatalf("stale held selection was rewritten: %+v", got)
+ }
+
+ // A deliberate Hosted rearm creates a distinct current-authority intent.
+ // When that fresh intent reaches a transient hold, its bounded retry must
+ // still work; the previous settings edit isn't a permanent veto.
+ schedulingEnable(t, f, 2, true)
+ schedulingGenerate(t, f, true)
+ fresh := schedulingLatest(t, f)
+ if fresh.ID == stale.ID || fresh.State != "queued" {
+ t.Fatalf("fresh revision did not obtain its own intent: %+v", fresh)
+ }
+ assertRevision(fresh.ID, 3, 3)
+ selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) {
+ return reviewprovider.Repository{}, context.DeadlineExceeded
+ }})
+ if got := selectionRead(t, f, fresh.ID); got.State != "held" || got.Reason != "source_fetch_timeout" || got.OperationID != "" {
+ t.Fatalf("fresh intent did not retain a transient hold: %+v", got)
+ }
+ ageSourceRetry(t, f, fresh.ID)
+ schedulingGenerate(t, f, true)
+ if got := selectionRead(t, f, fresh.ID); got.State != "queued" || got.OperationID != "" {
+ t.Fatalf("current held intent did not requeue: %+v", got)
+ }
+ reader = &refreshTestReader{}
+ selectionNext(t, f, reader)
+ got := selectionRead(t, f, fresh.ID)
+ if got.State != "selected" || got.OperationID == "" || reader.calls.Load() == 0 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 2 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 {
+ t.Fatalf("current retry did not create exactly one child without provider execution: %+v", got)
+ }
+ if old := selectionRead(t, f, stale.ID); old != stale {
+ t.Fatalf("fresh retry rewrote the old held intent: %+v", old)
+ }
+}
diff --git a/internal/reviewexec/round_controls_admission.go b/internal/reviewexec/round_controls_admission.go
index a5f6b3c47..fa03052b8 100644
--- a/internal/reviewexec/round_controls_admission.go
+++ b/internal/reviewexec/round_controls_admission.go
@@ -26,8 +26,9 @@ func (e *Engine) RoundAdmission(ctx context.Context, project, operationID string
return configured, err
}
-// DiscoveryComplete controls PR/channel progression. Later commits do not
-// reopen completed rounds; unresolved native evidence still holds progression.
+// DiscoveryComplete reports this PR/channel's retained discovery sufficiency.
+// Later commits do not reopen completed rounds. This is not an ancestor-review
+// prerequisite or authority to dispatch another review or merge a PR.
func (e *Engine) DiscoveryComplete(ctx context.Context, project string, current SourcePlan, channel string) (bool, error) {
state, err := e.Comparison(ctx, project, current, channel)
if err != nil {
diff --git a/internal/reviewexec/run_selection_actual_parent_test.go b/internal/reviewexec/run_selection_actual_parent_test.go
index 0d272c154..80949173d 100644
--- a/internal/reviewexec/run_selection_actual_parent_test.go
+++ b/internal/reviewexec/run_selection_actual_parent_test.go
@@ -86,20 +86,16 @@ func TestRunSelectionActualParentKeepsUnfinishedFindingLocal(t *testing.T) {
wantCalls := map[string]int{"repository:801": 1, "pull:2": 1, "pull:4": 2}
if dependent {
wantCalls["parent:agent-a"] = 1
- if got.State != "held" || got.OperationID != "" {
- t.Fatal("unfinished actual parent allowed dependent dispatch", got)
- }
- if count := attemptCount(t, f.store, `SELECT count(*) FROM review_operations`); count != 1 {
- t.Fatal("held dependency created another operation", count)
- }
- } else {
- if got.State != "selected" || got.OperationID == "" {
- t.Fatal("unrelated finding blocked independent work", got)
- }
- op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), got.OperationID)
- if err != nil || op.PullNumber != 4 || op.HeadSHA != reader.pulls[4].HeadSHA {
- t.Fatal("selected wrong independent source", op, err)
- }
+ }
+ if got.State != "selected" || got.OperationID == "" {
+ t.Fatal("ancestor finding blocked distinct review work", got)
+ }
+ op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), got.OperationID)
+ if err != nil || op.PullNumber != 4 || op.HeadSHA != reader.pulls[4].HeadSHA {
+ t.Fatal("selected wrong source comparison", op, err)
+ }
+ if count := attemptCount(t, f.store, `SELECT count(*) FROM review_operations`); count != 2 {
+ t.Fatal("selection did not create exactly one child", count)
}
gotCalls := map[string]int{}
for _, call := range reader.calls {
diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go
index 6e4961863..deb3c2228 100644
--- a/internal/reviewexec/scheduling_ancestor_memo_test.go
+++ b/internal/reviewexec/scheduling_ancestor_memo_test.go
@@ -23,15 +23,15 @@ func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) {
reads := 0
memo.load = func(p frontPull) ([]any, error) { reads++; return load(p) }
for pull := int64(10); pull < 60; pull++ {
- direct, err := newAutomaticDependencyRead(ctx, tx, attemptProject, "hosted", frame, true).forPull(pull)
+ direct, directLegacy, err := newAutomaticDependencyRead(ctx, tx, attemptProject, "hosted", frame, true).formatsForPull(pull)
if err != nil {
return err
}
- cached, err := memo.forPull(pull)
+ cached, cachedLegacy, err := memo.formatsForPull(pull)
if err != nil {
return err
}
- if encoded(direct) != encoded(cached) {
+ if encoded(direct) != encoded(cached) || encoded(directLegacy) != encoded(cachedLegacy) {
return fmt.Errorf("pull %d: planning facts changed: direct %v, memo %v", pull, direct, cached)
}
}
diff --git a/internal/reviewexec/scheduling_authority_retry_test.go b/internal/reviewexec/scheduling_authority_retry_test.go
index 980124958..ebf63ab82 100644
--- a/internal/reviewexec/scheduling_authority_retry_test.go
+++ b/internal/reviewexec/scheduling_authority_retry_test.go
@@ -5,7 +5,7 @@ import (
"time"
)
-func TestAutomaticHostedSourceRetryPreservesBindingAcrossUnrelatedEdit(t *testing.T) {
+func TestAutomaticHostedSourceRetryRequiresOriginalSchedulingRevision(t *testing.T) {
f, original := sourceRetryFixture(t)
scope := selectionScope(t, f, attemptProject, f.writer, "write")
revision, enabled := int64(1), true
@@ -16,18 +16,15 @@ func TestAutomaticHostedSourceRetryPreservesBindingAcrossUnrelatedEdit(t *testin
t.Fatal("settings edit shortened the original retry backoff")
}
ageSourceRetry(t, f, original.ID)
- schedulingGenerate(t, f, true)
- queued := schedulingLatest(t, f)
- if queued.ID != original.ID || queued.State != "queued" || queued.Revision != 4 || queued.ActorID != original.ActorID || queued.WorkerID != original.WorkerID {
- t.Fatal(queued)
+ if retrySourceDirect(t, f, original, time.Now()) {
+ t.Fatal("older completed retry passed the shared scheduling revision guard")
}
- selectionNext(t, f, &refreshTestReader{})
- selected := schedulingLatest(t, f)
- if selected.ID != original.ID || selected.State != "selected" || selected.OperationID == "" {
- t.Fatal(selected)
+ retained := selectionRead(t, f, original.ID)
+ if retained.State != original.State || retained.Revision != original.Revision || retained.OperationID != "" {
+ t.Fatal("refusal changed the original source hold", retained)
}
- if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 {
- t.Fatal("changed settings created replacement intent or started provider work")
+ if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 {
+ t.Fatal("refused older retry created an operation")
}
}
diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go
index b1caa7af6..77c9e2b4a 100644
--- a/internal/reviewexec/scheduling_automatic.go
+++ b/internal/reviewexec/scheduling_automatic.go
@@ -305,10 +305,16 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe
}
func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, shared automaticBasisRead) (string, error) {
+ basis, _, err := automaticPullBasisFormats(ctx, tx, project, pull, channel, shared)
+ return basis, err
+}
+
+func automaticPullBasisFormats(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, shared automaticBasisRead) (string, string, error) {
basisRevision := shared.revision
- h := sha256.New()
- h.Write(shared.prefix)
- appendRows := automaticBasisAppender(ctx, tx, h, channel, basisRevision)
+ h, legacy := sha256.New(), sha256.New()
+ prefix := io.MultiWriter(h, legacy)
+ prefix.Write(shared.prefix)
+ appendRows := automaticBasisAppender(ctx, tx, prefix, channel, basisRevision)
queries := []struct {
sql string
args []any
@@ -324,32 +330,33 @@ func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string,
if err := appendRows(q.sql, false, q.args...); err != nil {
var local *automaticPullAdjudicationUnavailable
if !errors.As(err, &local) {
- return "", err
+ return "", "", err
}
unavailable = err
}
}
if shared.workspace {
if err := appendRows(`SELECT p.state,p.head_sha,p.base_ref,p.base_sha,json_extract(p.metadata_json,'$.is_draft') FROM review_current_pulls c JOIN review_pull_memberships m ON m.project_id=c.project_id AND m.number=c.number AND m.start_revision=c.start_revision JOIN review_pull_versions p ON p.project_id=m.project_id AND p.number=m.number AND p.version_revision=m.version_revision WHERE c.project_id=? AND c.number=?`, false, project, pull); err != nil {
- return "", err
+ return "", "", err
}
if err := appendRows(strings.ReplaceAll(automaticCurrentRunsBasisQuery, "'hosted'", "'"+channel+"'"), true, project, pull); err != nil {
- return "", err
+ return "", "", err
}
if err := appendRows(automaticCurrentFindingsBasisQuery, true, project, pull); err != nil {
- return "", err
+ return "", "", err
}
}
- dependencies, err := shared.dependencies.forPull(pull)
+ dependencies, legacyDependencies, err := shared.dependencies.formatsForPull(pull)
if err != nil {
- return "", err
+ return "", "", err
}
if unavailable != nil {
- return "", unavailable
+ return "", "", unavailable
}
h.Write([]byte(encoded(dependencies)))
- return hex.EncodeToString(h.Sum(nil)), nil
+ legacy.Write([]byte(encoded(legacyDependencies)))
+ return hex.EncodeToString(h.Sum(nil)), hex.EncodeToString(legacy.Sum(nil)), nil
}
// Only a source-owned retained parent chain supplies dependency identity.
@@ -364,7 +371,12 @@ func automaticDependenciesChannel(ctx context.Context, tx *sql.Tx, project strin
if err != nil {
return nil, err
}
- return newAutomaticDependencyRead(ctx, tx, project, channel, frame, found).forPull(pull)
+ return automaticDependenciesWithFrame(ctx, tx, project, pull, channel, frame, found)
+}
+
+func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool) ([]any, error) {
+ current, _, err := newAutomaticDependencyRead(ctx, tx, project, channel, frame, found).formatsForPull(pull)
+ return current, err
}
// A dependency read owns one planning snapshot and one project's channel.
@@ -393,21 +405,22 @@ func newAutomaticDependencyRead(ctx context.Context, tx *sql.Tx, project, channe
return read
}
-func (r automaticDependencyRead) forPull(pull int64) ([]any, error) {
- out := []any{}
+func (r automaticDependencyRead) formatsForPull(pull int64) ([]any, []any, error) {
+ out, legacy := []any{}, []any{}
current, found := r.byNumber[pull]
if !found {
- return out, nil
+ return out, legacy, nil
}
seen := map[int64]bool{pull: true}
for parent := current.ParentPullNumber; parent != 0; {
if seen[parent] || len(seen) > 100 {
- return nil, errors.Join(errAutomaticParentCycle, schedulingUnavailable())
+ return nil, nil, errors.Join(errAutomaticParentCycle, schedulingUnavailable())
}
seen[parent] = true
p, exists := r.byNumber[parent]
if !exists {
out = append(out, []any{parent, "source_prefix_incomplete"})
+ legacy = append(legacy, []any{parent, "source_prefix_incomplete"})
break
}
facts, loaded := r.facts[parent]
@@ -415,14 +428,16 @@ func (r automaticDependencyRead) forPull(pull int64) ([]any, error) {
var err error
facts, err = r.load(p)
if err != nil {
- return nil, err
+ return nil, nil, err
}
r.facts[parent] = facts
}
- out = append(out, facts)
+ // Ancestor review facts must validate, but do not rearm the child.
+ out = append(out, []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA})
+ legacy = append(legacy, facts)
parent = p.ParentPullNumber
}
- return out, nil
+ return out, legacy, nil
}
func loadAutomaticDependencyFacts(ctx context.Context, tx *sql.Tx, project, channel string, repository int64, p frontPull) ([]any, error) {
@@ -490,7 +505,7 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st
degraded = true
continue
}
- basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared)
+ basis, legacyBasis, err := automaticPullBasisFormats(ctx, tx, project, pull, channel, shared)
if err != nil {
var unreadable *automaticPullAdjudicationUnavailable
if !errors.As(err, &unreadable) {
@@ -514,8 +529,8 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st
if pending {
continue
}
- var seen bool
- if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, project, ignoreSelection, pull, basis).Scan(&seen); err != nil {
+ seen, err := automaticPullPreviouslySelected(ctx, tx, project, ignoreSelection, pull, channel, basis, legacyBasis)
+ if err != nil {
return "", false, err
}
if !seen {
@@ -790,12 +805,30 @@ func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run,
if position := slices.Index(c.Queue, pull); position < 0 || position >= limit {
return true, nil
}
- basis, err := automaticPullBasisChannel(ctx, tx, r.ProjectID, pull, r.Channel)
+ shared, err := readAutomaticBasis(ctx, tx, r.ProjectID, r.Channel)
+ if err != nil {
+ return false, err
+ }
+ basis, legacyBasis, err := automaticPullBasisFormats(ctx, tx, r.ProjectID, pull, r.Channel, shared)
if err != nil {
return false, err
}
+ return automaticPullPreviouslySelected(ctx, tx, r.ProjectID, r.ID, pull, r.Channel, basis, legacyBasis)
+}
+
+// Match the old format only for a retained cancelled child with exact identity.
+// This retains existing same-input suppression without broadening it to a
+// different source, grant, channel, or already-changed legacy input.
+func automaticPullPreviouslySelected(ctx context.Context, tx *sql.Tx, project, ignoreSelection string, pull int64, channel, basis, legacyBasis string) (bool, error) {
var seen bool
- err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, r.ProjectID, r.ID, pull, basis).Scan(&seen)
+ err := tx.QueryRowContext(ctx, `SELECT EXISTS(
+ SELECT 1 FROM review_automatic_selections a
+ WHERE a.project_id=? AND a.selection_id<>? AND a.pull_number=?
+ AND (a.pull_basis_sha256=? OR (a.pull_basis_sha256=? AND EXISTS(
+ SELECT 1 FROM review_selections s JOIN review_operations o ON o.id=s.operation_id AND o.project_id=s.project_id
+ WHERE s.id=a.selection_id AND s.project_id=a.project_id AND s.channel=? AND o.channel=s.channel
+ AND o.pull_number=a.pull_number AND o.state='cancelled'
+ ))))`, project, ignoreSelection, pull, basis, legacyBasis, channel).Scan(&seen)
return seen, err
}
func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64, complete, acceptedOnly bool) error {
diff --git a/internal/reviewexec/scheduling_cli_test.go b/internal/reviewexec/scheduling_cli_test.go
index 8fb8e334e..d541a90fd 100644
--- a/internal/reviewexec/scheduling_cli_test.go
+++ b/internal/reviewexec/scheduling_cli_test.go
@@ -313,7 +313,7 @@ func TestSchedulingCLIPublicationAndAdjudicationRemainRequired(t *testing.T) {
}
}
-func TestSchedulingCLIActualParentStillBlocks(t *testing.T) {
+func TestSchedulingCLIActualParentPauseDoesNotBlockChild(t *testing.T) {
f := schedulingFixture(t)
one := int64(1)
_, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "stacked-cli", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}})
@@ -336,8 +336,12 @@ func TestSchedulingCLIActualParentStillBlocks(t *testing.T) {
reader.parents = map[string]reviewprovider.Pull{"branch-two": func() reviewprovider.Pull { p := schedulingPull(2); p.HeadRef = "branch-two"; return p }()}
selectionNext(t, f, reader)
r := schedulingLatest(t, f)
- if r.OperationID != "" || r.State != "held" {
- t.Fatal("actual predecessor bypassed", r)
+ if r.OperationID == "" || r.State != "selected" {
+ t.Fatal("ancestor pause blocked the child review", r)
+ }
+ op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), r.OperationID)
+ if err != nil || op.PullNumber != 4 {
+ t.Fatal(op, err)
}
}
diff --git a/internal/reviewexec/scheduling_dependency_snapshot_test.go b/internal/reviewexec/scheduling_dependency_snapshot_test.go
index 192163c26..834a1fffb 100644
--- a/internal/reviewexec/scheduling_dependency_snapshot_test.go
+++ b/internal/reviewexec/scheduling_dependency_snapshot_test.go
@@ -19,7 +19,7 @@ func TestAutomaticDependencyReadSharesParentsOnlyWithinSnapshot(t *testing.T) {
}
expect := func(read automaticDependencyRead, pull int64, want string) {
t.Helper()
- got, err := read.forPull(pull)
+ _, got, err := read.formatsForPull(pull)
if err != nil || encoded(got) != want {
t.Fatalf("pull %d: got %s, err=%v, want %s", pull, encoded(got), err, want)
}
diff --git a/internal/reviewexec/scheduling_http.go b/internal/reviewexec/scheduling_http.go
index 6435eaf49..1d0d68c9f 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/reviewexec/scheduling_legacy_basis_test.go b/internal/reviewexec/scheduling_legacy_basis_test.go
new file mode 100644
index 000000000..a62f4d6fa
--- /dev/null
+++ b/internal/reviewexec/scheduling_legacy_basis_test.go
@@ -0,0 +1,52 @@
+package reviewexec
+
+import (
+ "context"
+ "database/sql"
+ "testing"
+
+ _ "modernc.org/sqlite"
+)
+
+func TestAutomaticLegacyBasisKeepsOnlyMatchingCancelledChild(t *testing.T) {
+ ctx := context.Background()
+ db, err := sql.Open("sqlite", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ for _, statement := range []string{
+ "CREATE TABLE review_automatic_selections(project_id,selection_id,pull_number,pull_basis_sha256)",
+ "CREATE TABLE review_selections(project_id,id,channel,operation_id)",
+ "CREATE TABLE review_operations(project_id,id,pull_number,channel,state)",
+ "INSERT INTO review_automatic_selections VALUES ('project','old',7,'legacy')",
+ "INSERT INTO review_selections VALUES ('project','old','hosted','child')",
+ "INSERT INTO review_operations VALUES ('project','child',7,'hosted','cancelled')",
+ } {
+ if _, err := tx.ExecContext(ctx, statement); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, tc := range []struct {
+ name, ignore, channel, current, legacy string
+ want bool
+ }{
+ {"exact legacy cancellation", "", "hosted", "current", "legacy", true},
+ {"different channel", "", "cli", "current", "legacy", false},
+ {"changed source or grant", "", "hosted", "current", "changed", false},
+ {"excluded selection", "old", "hosted", "current", "legacy", false},
+ {"existing current format comparison", "", "hosted", "legacy", "changed", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := automaticPullPreviouslySelected(ctx, tx, "project", tc.ignore, 7, tc.channel, tc.current, tc.legacy)
+ if err != nil || got != tc.want {
+ t.Fatalf("matched legacy cancellation = %v, %v; want %v", got, err, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/reviewexec/scheduling_recovery0030_test.go b/internal/reviewexec/scheduling_recovery0030_test.go
index e3dac7355..656dd5fc7 100644
--- a/internal/reviewexec/scheduling_recovery0030_test.go
+++ b/internal/reviewexec/scheduling_recovery0030_test.go
@@ -79,42 +79,63 @@ func TestRecovery0030InterruptedInitialReadKeepsChannelContinuity(t *testing.T)
}
}
-func TestRecovery0030CompletedSourceHoldRetainsExactRevisionFence(t *testing.T) {
+func TestRecovery0030CompletedSourceHoldRequiresCurrentSchedulingRevision(t *testing.T) {
for _, channel := range []string{"hosted", "cli"} {
- for _, interrupted := range []bool{false, true} {
- t.Run(channel+"/"+map[bool]string{false: "queued", true: "interrupted"}[interrupted], func(t *testing.T) {
- var f *attemptFixture
- var original Run
- if channel == "hosted" {
- f, original = sourceRetryFixture(t)
- } else {
- f, original = cliSourceRetryFixture(t)
- }
- ageSourceRetry(t, f, original.ID)
- if channel == "hosted" {
- schedulingGenerate(t, f, true)
- } else {
- schedulingCLIGenerate(t, f, true)
+ for _, changeOtherChannel := range []bool{false, true} {
+ interruptionsToTest := []int{1}
+ if changeOtherChannel {
+ interruptionsToTest = []int{0, 1, 2, 4}
+ }
+ for _, interruptions := range interruptionsToTest {
+ revisionCase := "unchanged-revision"
+ if changeOtherChannel {
+ revisionCase = "changed-other-channel"
}
- if interrupted {
- recovery0030Claim(t, f, original.ID)
- if err := f.e.RecoverReviewRuns(t.Context()); err != nil {
- t.Fatal(err)
+ t.Run(channel+"/"+revisionCase+"/"+string(rune('0'+interruptions)), func(t *testing.T) {
+ var f *attemptFixture
+ var original Run
+ if channel == "hosted" {
+ f, original = sourceRetryFixture(t)
+ } else {
+ f, original = cliSourceRetryFixture(t)
}
- }
- if channel == "hosted" {
- // Explicitly rearm Hosted without editing the other lane.
- schedulingEnable(t, f, 1, true)
- } else {
- recovery0030EnableBoth(t, f)
- }
- reader := &refreshTestReader{}
- selectionNext(t, f, reader)
- got := selectionRead(t, f, original.ID)
- if got.State != "held" || got.Reason != "automation_authorization_changed" || got.OperationID != "" || reader.calls.Load() != 0 {
- t.Fatal("completed hold lost exact revision fence", got)
- }
- })
+ ageSourceRetry(t, f, original.ID)
+ if channel == "hosted" {
+ schedulingGenerate(t, f, true)
+ } else {
+ schedulingCLIGenerate(t, f, true)
+ }
+ for range interruptions {
+ recovery0030Claim(t, f, original.ID)
+ if err := f.e.RecoverReviewRuns(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if changeOtherChannel {
+ // Keep the selected channel on, but enable the other channel.
+ // Its distinct scheduling basis does not preserve the shared
+ // authorization revision of a completed source hold.
+ recovery0030EnableBoth(t, f)
+ }
+ reader := &refreshTestReader{}
+ selectionNext(t, f, reader)
+ got := selectionRead(t, f, original.ID)
+ if got.ID != original.ID || got.ActorID != original.ActorID || got.WorkerID != original.WorkerID ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 ||
+ attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 {
+ t.Fatal("retained selection changed, duplicated or attempted provider work", got)
+ }
+ operations := attemptCount(t, f.store, `SELECT count(*) FROM review_operations`)
+ if changeOtherChannel {
+ if got.State != "held" || got.Reason != "automation_authorization_changed" ||
+ got.OperationID != "" || operations != 0 || reader.calls.Load() != 0 {
+ t.Fatal("stale shared revision must stop before source read or child operation", got)
+ }
+ } else if got.State != "selected" || got.OperationID == "" || operations != 1 || reader.calls.Load() == 0 {
+ t.Fatal("current shared revision must resume the original bounded retry", got)
+ }
+ })
+ }
}
}
}
diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go
index 29867d109..4624bf659 100644
--- a/internal/reviewexec/scheduling_source_retry.go
+++ b/internal/reviewexec/scheduling_source_retry.go
@@ -3,7 +3,6 @@ package reviewexec
import (
"context"
"database/sql"
- "encoding/json"
"errors"
"time"
)
@@ -87,10 +86,7 @@ func (e *Engine) automaticSourceRetryCandidate(ctx context.Context, tx *sql.Tx,
return nil, schedulingUnavailable()
}
if accepted != schedulingRevision {
- generation, err := schedulingAuthorityContinuity(ctx, tx, project, r.ActorID, accepted, schedulingRevision, true)
- if err != nil || generation == 0 {
- return nil, err
- }
+ return nil, nil
}
if r.Reason == "routed_findings_unavailable" {
// A repaired projection can have the same source digest as before
@@ -112,8 +108,7 @@ func (e *Engine) automaticSourceRetryCandidate(ctx context.Context, tx *sql.Tx,
// Recheck recovery fences during every admission snapshot, including after
// source I/O. Interrupted initial reads retain ordinary authorization continuity.
// Both recovery paths respect newer intent. Completed source holds require the
-// exact accepted revision unless a pending Hosted retry proves unchanged
-// persisted authority and lane basis. Incomplete evidence remains conservative.
+// exact accepted shared scheduling revision, even for an other-channel edit.
func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (string, error) {
if !validChannel(r.Channel) || r.Revision < 4 {
return "", nil
@@ -151,23 +146,7 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin
return "selection_superseded", nil
}
} else if accepted != current.Revision {
- if r.Channel != "hosted" || r.State == "selected" || r.OperationID != "" || accepted >= current.Revision {
- return "automation_authorization_changed", nil
- }
- completed, err := verifiedCompletedAutomaticSourceHistory(ctx, tx, r)
- if err != nil {
- return "", err
- }
- if !completed {
- return "automation_authorization_changed", nil
- }
- generation, err := schedulingAuthorityContinuity(ctx, tx, r.ProjectID, r.ActorID, accepted, current.Revision, true)
- if err != nil {
- return "", err
- }
- if generation == 0 {
- return "automation_authorization_changed", nil
- }
+ return "automation_authorization_changed", nil
}
superseded, err := automaticSourceSuperseded(ctx, tx, r)
if err != nil {
@@ -179,77 +158,6 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin
return "", nil
}
-// Only a complete canonical source journal distinguishes a completed retry
-// from an unproved interrupted read. Settings authority cannot supply that proof.
-func verifiedCompletedAutomaticSourceHistory(ctx context.Context, tx *sql.Tx, r Run) (bool, error) {
- if r.Revision < 4 || r.Revision > 10000 {
- return false, nil
- }
- acceptance, err := readSelectionRequestedEvent(ctx, tx, r)
- if err != nil || acceptance.sequence == 0 || acceptance.Origin != selectionOriginAutomatic {
- return false, err
- }
- rows, err := tx.QueryContext(ctx, `SELECT revision,sequence,actor_id,typeof(event_type),
- CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END
- FROM events WHERE project_id=? AND resource_id=? AND (event_type='review.selection_updated'
- OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.selection_updated'))
- ORDER BY revision,sequence LIMIT ?`, r.ProjectID, r.ID, r.Revision+1)
- if err != nil {
- return false, err
- }
- defer rows.Close()
- previous, sequence, next, completed := "queued", acceptance.sequence, int64(2), false
- for rows.Next() {
- var revision, order, actor any
- var eventType string
- var body sql.NullString
- if err := rows.Scan(&revision, &order, &actor, &eventType, &body); err != nil {
- return false, err
- }
- ord, ok := order.(int64)
- if revision != next || next > r.Revision || !ok || ord <= sequence || actor != r.ActorID || eventType != "text" || !body.Valid {
- return false, nil
- }
- var event struct {
- Reason string `json:"reason"`
- State string `json:"state"`
- }
- if json.Unmarshal([]byte(body.String), &event) != nil || encoded(event) != body.String {
- return false, nil
- }
- switch event.State {
- case "selecting":
- if previous != "queued" || event.Reason != "" {
- return false, nil
- }
- case "queued":
- if (previous != "selecting" && previous != "held") || event.Reason != "" {
- return false, nil
- }
- case "held":
- if previous != "selecting" {
- return false, nil
- }
- switch event.Reason {
- case "source_budget_exhausted", "source_fetch_timeout", "source_provider_unavailable", "routed_findings_unavailable":
- completed = true
- default:
- return false, nil
- }
- default:
- return false, nil
- }
- if next == r.Revision && (event.State != r.State || event.Reason != r.Reason) {
- return false, nil
- }
- previous, sequence, next = event.State, ord, next+1
- }
- if err := rows.Err(); err != nil {
- return false, err
- }
- return completed && next == r.Revision+1, nil
-}
-
// An interrupted read can relax exact-revision continuity only when this
// selection durably recorded its automatic acceptance. The common decoder
// validates the unique revision-one event and binds its actor, worker and lane.
diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go
index b8f6d9308..6f14356c4 100644
--- a/internal/reviewexec/scheduling_test.go
+++ b/internal/reviewexec/scheduling_test.go
@@ -269,7 +269,7 @@ func TestSchedulingAutomaticAuthorizerWithdrawalAndRestoreHold(t *testing.T) {
t.Fatal("withdrawn manager claimed attempt", a, err)
}
}
-func TestSchedulingPausedFrontSkipsIndependentButNotDependency(t *testing.T) {
+func TestSchedulingPausedFrontSkipsIndependentAndStackedReviews(t *testing.T) {
f := schedulingFixture(t)
schedulingPause(t, f, 2, 0, true)
r, _ := selectionEnqueue(t, f, "independent-paused", "hosted", nil)
@@ -282,7 +282,7 @@ func TestSchedulingPausedFrontSkipsIndependentButNotDependency(t *testing.T) {
if err != nil || op.PullNumber != 4 {
t.Fatal(op, err)
}
- // The same evaluator cannot turn a paused parent into earned completion.
+ // The parent pause stays local; selecting the child grants no parent completion.
err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error {
base := strings.Repeat("b", 40)
head := strings.Repeat("a", 40)
@@ -295,8 +295,8 @@ func TestSchedulingPausedFrontSkipsIndependentButNotDependency(t *testing.T) {
if err != nil {
return err
}
- if front != 0 || reason != "pull_scheduling_paused" {
- t.Fatalf("dependent PR passed paused parent: %d %s", front, reason)
+ if front != 4 || reason != "" {
+ t.Fatalf("ancestor pause blocked child review: %d %s", front, reason)
}
return nil
})
@@ -486,18 +486,12 @@ func TestSchedulingAutomaticIndependentProgressAcrossRetainedEvidence(t *testing
}
selectionNext(t, f, reader)
r := schedulingLatest(t, f)
- if dependent {
- if r.State != "held" || r.OperationID != "" {
- t.Fatal("dependency bypassed", r)
- }
- } else {
- if r.State != "selected" {
- t.Fatal(r)
- }
- op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), r.OperationID)
- if err != nil || op.PullNumber != 4 {
- t.Fatal(op, err)
- }
+ if r.State != "selected" {
+ t.Fatal("ancestor evidence blocked a distinct review target", r)
+ }
+ op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), r.OperationID)
+ if err != nil || op.PullNumber != 4 {
+ t.Fatal(op, err)
}
schedulingGenerate(t, f, false)
})
@@ -710,7 +704,7 @@ func schedulingStackReader() *refreshTestReader {
r.parents = map[string]reviewprovider.Pull{"branch-two": func() reviewprovider.Pull { p := schedulingPull(2); p.HeadRef = "branch-two"; return p }()}
return r
}
-func TestSchedulingDependentHeldChildReleasesAfterParentTapersAtSameHead(t *testing.T) {
+func TestSchedulingAncestorRoundChangesKeepOriginalChild(t *testing.T) {
f := schedulingFixture(t)
schedulingCleanHosted(t, f, 1, 81)
one := int64(1)
@@ -751,38 +745,108 @@ func TestSchedulingDependentHeldChildReleasesAfterParentTapersAtSameHead(t *test
}
return verifyPredecessors(ctx, tx, attemptProject, current, anchor, []SourcePlan{parent})
})
- attemptCode(t, err, "review_held")
- var failure *core.Error
- if !errors.As(err, &failure) {
- t.Fatal(err)
+ if err != nil {
+ t.Fatal("ancestor round work stopped final child source verification", err)
}
- details, ok := failure.Details.(map[string]string)
- if !ok || details["reason"] != "predecessor_unfinished" {
- t.Fatal("not the genuine dependency hold", failure)
+ intent, err := reviewprovider.HostedTriggerBody(reviewprovider.HostedTriggerIntent{OperationID: a.OperationID, AttemptID: a.ID, HeadSHA: anchor.CandidateSHA})
+ if err != nil {
+ t.Fatal(err)
}
- if _, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "predecessor_unfinished", ""); err != nil {
+ a, err = f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, anchor, intent)
+ if err != nil {
t.Fatal(err)
}
- schedulingCleanHosted(t, f, 2, 82)
+ // Change parent progress after the child has an admitted operation/attempt.
control := roundRead(t, f, 2, "hosted")
- if !control.Tapered || control.Used != 1 {
- t.Fatal("parent did not actually taper", control)
+ if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "close-parent-during-child", 2, "hosted", RoundControlRequest{ExpectedRevision: &control.Revision, Action: "close"}); err != nil {
+ t.Fatal(err)
}
- schedulingGenerate(t, f, true)
- selectionNext(t, f, reader)
- next := schedulingLatest(t, f)
- if next.State != "selected" || next.OperationID == child.ID {
- t.Fatal("dependent child remained suppressed after genuine parent completion", next)
+ schedulingGenerate(t, f, false)
+ var children int
+ if err := f.store.DB().QueryRow(`SELECT count(*) FROM review_operations WHERE project_id=? AND pull_number=4 AND channel='hosted'`, attemptProject).Scan(&children); err != nil || children != 1 {
+ t.Fatal("ancestor progress created another child request", children, err)
}
- op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), next.OperationID)
- if err != nil || op.PullNumber != 4 || op.HeadSHA != child.HeadSHA || op.ConfigurationRevision != child.ConfigurationRevision {
- t.Fatal(op, err)
+ current, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), child.ID)
+ if err != nil || current.ID != child.ID || current.AttemptID != a.ID {
+ t.Fatal("ancestor progress replaced the child operation", current, err)
}
- old, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), child.ID)
- if err != nil || old.State != "held" || old.Reason != "predecessor_unfinished" {
- t.Fatal("old dependency hold was rewritten", old, err)
+ if err := f.e.VerifyAction(t.Context(), attemptProject, a.ID, a.Revision, parent); err != nil {
+ t.Fatal("ancestor progress blocked the original child at the final local dispatch guard", err)
}
+}
+func TestSchedulingCancelledChildIgnoresAncestorRoundProgress(t *testing.T) {
+ for _, change := range []string{"close", "grant-and-taper", "completed-review"} {
+ t.Run(change, func(t *testing.T) {
+ f := schedulingFixture(t)
+ schedulingCleanHosted(t, f, 1, 81)
+ one := int64(1)
+ _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "stack-for-cancelled-child", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ schedulingEnable(t, f, 0, true)
+ schedulingGenerate(t, f, true)
+ selectionNext(t, f, schedulingStackReader())
+ first := schedulingLatest(t, f)
+ scope := selectionScope(t, f, attemptProject, f.writer, "write")
+ child, err := f.e.ReadOperation(t.Context(), scope, first.OperationID)
+ if err != nil || child.PullNumber != 4 {
+ t.Fatal("dependent child not selected", child, err)
+ }
+ if _, err := f.e.ControlOperation(t.Context(), scope, "cancel-dependent-child", child.ID, OperationControl{ExpectedRevision: child.Revision, Action: "cancel"}); err != nil {
+ t.Fatal(err)
+ }
+ // Cancellation removes busy suppression; a changed ancestor digest
+ // would now create a replacement selection for this same child.
+ childBasis := func() string {
+ var basis string
+ if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error {
+ var err error
+ basis, err = automaticPullBasisChannel(ctx, tx, attemptProject, 4, "hosted")
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return basis
+ }
+ before := childBasis()
+ switch change {
+ case "close":
+ control := roundRead(t, f, 2, "hosted")
+ if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "close-parent-after-child", 2, "hosted", RoundControlRequest{ExpectedRevision: &control.Revision, Action: "close"}); err != nil {
+ t.Fatal(err)
+ }
+ case "grant-and-taper":
+ roundGrant(t, f, 2, "hosted", 0, 1, 2, "parent-reopened-after-child")
+ retainHistoricalRoundTaper(t, f, 2, "hosted")
+ case "completed-review":
+ roundGrant(t, f, 2, "hosted", 0, 1, 2, "parent-reopened-after-child")
+ schedulingCleanHosted(t, f, 2, 82)
+ control := roundRead(t, f, 2, "hosted")
+ if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "close-completed-parent", 2, "hosted", RoundControlRequest{ExpectedRevision: &control.Revision, Action: "close"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if after := childBasis(); after != before {
+ t.Fatal("ancestor progress changed terminal child's basis", before, after)
+ }
+ // The parent's own changed basis may justify a planning pass. Its
+ // source read must not recreate the cancelled child.
+ schedulingGenerate(t, f, true)
+ selectionNext(t, f, schedulingStackReader())
+ if count := attemptCount(t, f.store, `SELECT count(*) FROM review_operations WHERE pull_number=4 AND channel='hosted'`); count != 1 {
+ t.Fatal("ancestor progress recreated terminal child operation", count)
+ }
+ for range 3 {
+ schedulingGenerate(t, f, false)
+ }
+ current, err := f.e.ReadOperation(t.Context(), scope, child.ID)
+ if err != nil || current.State != "cancelled" {
+ t.Fatal("cancelled child identity changed", current, err)
+ }
+ })
+ }
}
func TestSchedulingPrepareControlRaceFinalVerificationKeepsSupervisorHealthy(t *testing.T) {
@@ -1490,6 +1554,18 @@ func TestValidateSchedulingSnapshotRejectsStaleProjectProjection(t *testing.T) {
t.Fatal(err)
}
schedulingEnable(t, f, 1, false)
+ // A newer, genuine event for a separate project must not advance this projection.
+ f.configure(t, otherAttemptProject, "test-capability", 0, false)
+ admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-other-cred' AND project_id=?`, otherAttemptProject)
+ otherScope := selectionScope(t, f, otherAttemptProject, f.other, "write")
+ for i, enabled := range []bool{true, false, true} {
+ revision := int64(i)
+ if _, err := f.e.ConfigureScheduling(t.Context(), otherScope, core.NewID("other-scheduling"), SchedulingRequest{
+ ExpectedRevision: &revision, AutomaticHosted: &enabled,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
if err := validateSchedulingSnapshotForTest(t, f); err != nil {
t.Fatalf("healthy rev-2 projection rejected: %v", err)
}
diff --git a/internal/reviewexec/selection_revision_five_test.go b/internal/reviewexec/selection_revision_five_test.go
new file mode 100644
index 000000000..e04fd7e73
--- /dev/null
+++ b/internal/reviewexec/selection_revision_five_test.go
@@ -0,0 +1,43 @@
+package reviewexec
+
+import (
+ "context"
+ "testing"
+
+ "github.com/benhook1013/FireController/internal/reviewprovider"
+)
+
+// An interruption before the first completed hold does not move the project's
+// scheduling revision. The original selection still owns its bounded retry.
+func TestSelectionRevisionFiveHoldKeepsExactSchedulingAuthority(t *testing.T) {
+ f := schedulingFixtureWithQueue(t, []int64{2})
+ schedulingEnable(t, f, 0, true)
+ schedulingGenerate(t, f, true)
+ original := schedulingLatest(t, f)
+ recovery0030Claim(t, f, original.ID)
+ if err := f.e.RecoverReviewRuns(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) {
+ return reviewprovider.Repository{}, context.DeadlineExceeded
+ }})
+ hold := selectionRead(t, f, original.ID)
+ if hold.Revision != 5 || hold.State != "held" || hold.Reason != "source_fetch_timeout" || hold.OperationID != "" {
+ t.Fatalf("expected original completed hold at selection revision 5: %+v", hold)
+ }
+
+ ageSourceRetry(t, f, original.ID)
+ schedulingGenerate(t, f, true)
+ after := selectionRead(t, f, original.ID)
+ if after.Revision != 6 || after.State != "queued" || after.OperationID != "" {
+ t.Fatalf("expected same original request to be queued: %+v", after)
+ }
+ selectionNext(t, f, &refreshTestReader{})
+ got := selectionRead(t, f, original.ID)
+ if got.State != "selected" || got.OperationID == "" || got.ActorID != original.ActorID || got.WorkerID != original.WorkerID ||
+ attemptCount(t, f.store, "SELECT count(*) FROM review_selections") != 1 ||
+ attemptCount(t, f.store, "SELECT count(*) FROM review_operations") != 1 ||
+ attemptCount(t, f.store, "SELECT count(*) FROM review_execution_attempts") != 0 {
+ t.Fatalf("original request not selected exactly once without provider dispatch: %+v", got)
+ }
+}
diff --git a/internal/reviewprovider/hosted_c7ab_lexical_test.go b/internal/reviewprovider/hosted_c7ab_lexical_test.go
new file mode 100644
index 000000000..6409efca9
--- /dev/null
+++ b/internal/reviewprovider/hosted_c7ab_lexical_test.go
@@ -0,0 +1,38 @@
+package reviewprovider
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestHostedPreLexerHonorsQuotedTagBoundaries(t *testing.T) {
+ body := `sample text
next
`
+ tags := submittedPreTags(body)
+ if len(tags) != 4 || tags[0][2] != 1 || tags[1][2] != -1 || tags[2][2] != 1 || tags[3][2] != -1 {
+ t.Fatalf("wrong pre tag sequence: %v", tags)
+ }
+ var projected []string
+ var count strings.Builder
+ if splitSubmittedPreCounts(body, &count, func(s string) bool { projected = append(projected, strings.TrimSpace(s)); return false }) {
+ t.Fatal("ordinary preformatted text cannot signal a count")
+ }
+ if len(projected) != 2 || projected[0] != "sample text" || projected[1] != "next" {
+ t.Fatalf("incorrect preformatted fragments: %q", projected)
+ }
+}
+func TestHostedPreLexerKeepsEditorialCommentInsideRawBlock(t *testing.T) {
+ body := "Demo\n\nText\n
\n\n Example -->"
+ if got := findingLastUnfencedCommentClose(body); got != strings.Index(body, "-->") {
+ t.Fatalf("unexpected comment delimiter offset: %d", got)
+ }
+}
+func TestHostedStandaloneCountLabelAndSummaryListOwnerGrammar(t *testing.T) {
+ if !hasBareSubmittedActionableLabel("* **Actionable comments posted**") || hasBareSubmittedActionableLabel("We discuss **Actionable comments posted** here.") {
+ t.Fatal("standalone list label and ordinary prose must be distinct")
+ }
+ owner := []string{"details", "dl", "dd", "p"}
+ if !standingImplicitSummaryClose(owner, "dd") || !standingImplicitSummaryClose(owner, "dt") || standingImplicitSummaryClose(owner, "em") ||
+ standingImplicitSummaryClose(append(owner, "dl", "dd"), "dd") {
+ t.Fatal("description item ownership changed")
+ }
+}
diff --git a/internal/reviewprovider/hosted_count_boundaries_test.go b/internal/reviewprovider/hosted_count_boundaries_test.go
new file mode 100644
index 000000000..3b1260547
--- /dev/null
+++ b/internal/reviewprovider/hosted_count_boundaries_test.go
@@ -0,0 +1,40 @@
+package reviewprovider
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSubmittedCountRenderingRespectsOrdinaryBoundaries(t *testing.T) {
+ if !hasSubmittedSoftWrappedCount("Actionable comments posted\n2") {
+ t.Fatal("ordinary label and numeric continuation were not recognized")
+ }
+ for _, text := range []string{"Release notes\n1. Read two documents.", "See the actionable comments posted\n* 2 examples appear below.", "The phrase __Actionable comments posted__ appears in this sentence."} {
+ if hasSubmittedSoftWrappedCount(text) {
+ t.Fatal("ordinary content was treated as a count declaration")
+ }
+ }
+ for _, text := range []string{"1. Read two documents.", "* 2 examples appear below."} {
+ if !submittedListInterrupt(findingLine{countText: text}) {
+ t.Fatal("list item must interrupt the paragraph")
+ }
+ }
+ var remaining strings.Builder
+ if splitSubmittedPreCounts("Findings:
2 releases remain.
", &remaining, func(text string) bool {
+ return standingFindingClaim.MatchString(submittedCountWhitespace(text))
+ }) {
+ t.Fatal("separate code examples were joined into one count")
+ }
+}
+
+func TestSubmittedCountProjectionNormalizesPunctuationSeparately(t *testing.T) {
+ if !hasBareSubmittedActionableLabel("__Actionable comments posted__") {
+ t.Fatal("formatted standalone label not recognized")
+ }
+ if got := normalizeSubmittedEscapedColon(`Example\: punctuation`); got != "Example: punctuation" {
+ t.Fatalf("punctuation escape not rendered: %q", got)
+ }
+ if got := normalizeSubmittedEscapedColon(`Example\\: punctuation`); got != `Example\: punctuation` {
+ t.Fatalf("literal backslash did not survive: %q", got)
+ }
+}
diff --git a/internal/reviewprovider/hosted_count_claim_boundary_test.go b/internal/reviewprovider/hosted_count_claim_boundary_test.go
new file mode 100644
index 000000000..0280f807d
--- /dev/null
+++ b/internal/reviewprovider/hosted_count_claim_boundary_test.go
@@ -0,0 +1,69 @@
+package reviewprovider
+
+import "testing"
+
+func TestHostedCountClaimsKeepWordBoundary(t *testing.T) {
+ for _, phrase := range []string{
+ "Nonactionable comments posted: 1",
+ "Preserve the **actionable comments posted** label.",
+ } {
+ if hasSubmittedActionableClaim(phrase) || hasBareSubmittedActionableLabel(phrase) {
+ t.Fatalf("ordinary prose classified as review metadata: %q", phrase)
+ }
+ }
+ if !hasSubmittedActionableClaim("**Actionable comments posted**: 1") {
+ t.Fatal("visible formatted count must remain a count")
+ }
+ if hasSubmittedLineActionableClaim("Preserve the actionable comments posted: check the label.") {
+ t.Fatal("a phrase inside prose is not a standalone publication declaration")
+ }
+ if !hasSubmittedLineActionableClaim("- **Actionable comments posted**: 1") {
+ t.Fatal("visible standalone count preceded by a list marker must remain a count")
+ }
+}
+
+func TestStandingCountTreatsFencedExamplesAsParagraphBreaks(t *testing.T) {
+ lines, sound := findingLines("Findings:\n```text\nsample releases\n```\n2 releases remain.")
+ if !sound || standingInventoryContradictsZero(lines, &standingHistoricalParser{}) {
+ t.Fatal("a fenced example cannot connect two separate prose paragraphs")
+ }
+}
+
+func TestHostedCountBoundariesRespectBlockAndHeadingMarkup(t *testing.T) {
+ lines, sound := findingLines("Findings:\n\nExample release data\n
\n2 releases remain.")
+ if !sound || standingInventoryContradictsZero(lines, &standingHistoricalParser{}) {
+ t.Fatal("unrelated prose on either side of an example was joined")
+ }
+ lines, sound = findingLines("\nFindings: 2\n
")
+ if !sound || !standingInventoryContradictsZero(lines, &standingHistoricalParser{}) {
+ t.Fatal("preformatted count stopped contributing refusal-only evidence")
+ }
+ if !hasSubmittedLineActionableClaim("### Actionable comments posted: 1") {
+ t.Fatal("visible counted heading is not ordinary prose")
+ }
+ if !hasBareSubmittedActionableLabel("## **Actionable comments posted**") {
+ t.Fatal("visible standalone heading label is not ordinary prose")
+ }
+ lines, sound = findingLines("Current findings: 2")
+ if !sound || !standingInventoryContradictsZero(lines, &standingHistoricalParser{}) {
+ t.Fatal("decorative markup obscured an explicit count")
+ }
+}
+
+func TestStandingMarkerScanContinuesAfterEditorialComment(t *testing.T) {
+ for _, tc := range []struct {
+ name, remainder string
+ wantInvalid bool
+ }{
+ {"editorial", "", false},
+ {"reserved wording", "", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ history := &standingHistoricalParser{}
+ standingSections(" "+tc.remainder, history)
+ if history.invalid != tc.wantInvalid {
+ t.Fatalf("marker invalid = %v, want %v", history.invalid, tc.wantInvalid)
+ }
+ })
+ }
+}
diff --git a/internal/reviewprovider/hosted_count_projection_test.go b/internal/reviewprovider/hosted_count_projection_test.go
new file mode 100644
index 000000000..f400284a1
--- /dev/null
+++ b/internal/reviewprovider/hosted_count_projection_test.go
@@ -0,0 +1,27 @@
+package reviewprovider
+
+import "testing"
+
+func TestPreformattedProjectionKeepsHiddenBoundaryMetadata(t *testing.T) {
+ lines, ok := findingLines("\nAlphaBeta\nGamma\n
\n")
+ if !ok || len(lines) != 5 {
+ t.Fatal("unexpected line framing", ok, len(lines))
+ }
+ if got := lines[1]; got.preCountText != "Alpha" || !got.preCommentContinues || !got.preCountContinues || !got.hidden {
+ t.Fatalf("unexpected first preformatted projection: %#v", got)
+ }
+ if got := lines[2]; got.preCountText != "Beta" || got.preCommentContinues || !got.preCountContinues || !got.hidden {
+ t.Fatalf("unexpected completed preformatted projection: %#v", got)
+ }
+ if got := lines[3]; got.preCountText != "Gamma" || got.preCommentContinues {
+ t.Fatalf("ordinary boundary was discarded: %#v", got)
+ }
+}
+
+func TestRefusalReferenceProjectionOnlyChangesTheLabelView(t *testing.T) {
+ raw := "See [release notes][guide] and [appendix][]."
+ visible := submittedCountMarkdownReference.ReplaceAllString(raw, "${1}")
+ if visible != "See release notes and appendix." || raw != "See [release notes][guide] and [appendix][]." {
+ t.Fatalf("unexpected reference projection: %q", visible)
+ }
+}
diff --git a/internal/reviewprovider/hosted_findings.go b/internal/reviewprovider/hosted_findings.go
index 6680f9330..49d2b7d6d 100644
--- a/internal/reviewprovider/hosted_findings.go
+++ b/internal/reviewprovider/hosted_findings.go
@@ -45,13 +45,18 @@ var findingRange = regexp.MustCompile("^`([0-9]+)-([0-9]+)`: (.+)$")
// Asterisks outside code and unbalanced delimiters cannot supply title metadata.
var findingTitle = regexp.MustCompile("^\\*\\*((?:[^*`\\r\\n]|`[^`\\r\\n]+`)+)\\*\\*$")
var findingHTML = regexp.MustCompile(`?(?:details|blockquote)>`)
-var findingPre = regexp.MustCompile(`(?i)?pre(?:[ \t/>]|$)`)
var findingQuotedHTML = regexp.MustCompile(`(?i)?blockquote(?:[ \t][^<>]*)?>`)
var findingConfirmation = regexp.MustCompile(`^✅ Confirmed as addressed by @[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$`)
type findingLine struct {
start, end, next, quote int
text string
+ countText string // Visible comment-excluded text for contradictory count checks only.
+ preCountText string // Visible HTML preformatted text, for refusal only.
+ preCountContinues bool
+ preCommentContinues bool // A comment hides this physical boundary in the preformatted projection.
+ countContinues bool // A comment hides this physical line boundary.
+ countBreak bool // Code and preformatted blocks separate visible paragraphs.
hidden bool
}
@@ -61,7 +66,17 @@ func findingLines(body string) ([]findingLine, bool) {
var lines []findingLine
var fence byte
fenceLength, fenceQuote, pre := 0, 0, 0
- comment := false
+ comment, preComment := false, false
+ // Keep the provider's exact terminal status footer separate from the
+ // preformatted count projection. Its delimiter cannot make a standalone
+ // literal opener in an example consume the review trailer.
+ const statusFooter = ""
+ preceding := body
+ if at := strings.LastIndex(body, statusFooter); at >= 0 && (at == 0 || body[at-1] == '\n') &&
+ strings.TrimSpace(body[at+len(statusFooter):]) == "" {
+ preceding = body[:at]
+ }
+ lastCommentClose := findingLastUnfencedCommentClose(preceding)
for offset := 0; offset < len(body); {
end := strings.IndexByte(body[offset:], '\n')
next := len(body)
@@ -84,10 +99,31 @@ func findingLines(body string) ([]findingLine, bool) {
l := findingLine{start: offset, end: end, next: next, quote: quote, text: strings.TrimSpace(text)}
trimmed := strings.TrimLeft(text, " ")
indent := len(text) - len(trimmed)
+ wasPre := pre > 0
+ visiblePre := false
+ if !comment && indent <= 3 && !strings.HasPrefix(trimmed, "\t") {
+ commentProbe := false
+ visiblePre = len(submittedPreTags(findingCommentVisible(trimmed, &commentProbe))) > 0
+ }
+ // Preformatted text stays hidden for retained markers and inventory.
+ // Capture only rendered text for the additional-only count check.
+ if quote <= 1 && fence == 0 && !comment && (wasPre || visiblePre) {
+ if wasPre && preComment && strings.EqualFold(strings.TrimSpace(trimmed), "") {
+ // An unmatched opener can be a literal preformatted example.
+ // Preserve the standalone closing tag only if there is no
+ // later matching close. HTML comments do not nest.
+ if lastCommentClose < next {
+ preComment = false
+ }
+ }
+ l.preCountText = findingCommentVisible(trimmed, &preComment)
+ l.preCommentContinues = preComment
+ }
if quote > 1 {
l.hidden = true
} else if fence != 0 {
l.hidden = true
+ l.countBreak = true
n := 0
for n < len(trimmed) && trimmed[n] == fence {
n++
@@ -95,27 +131,20 @@ func findingLines(body string) ([]findingLine, bool) {
if quote == fenceQuote && indent <= 3 && n >= fenceLength && strings.TrimSpace(trimmed[n:]) == "" {
fence = 0
}
- } else if indent > 3 || strings.HasPrefix(trimmed, "\t") {
- l.hidden = true
- } else if pre > 0 || findingPre.MatchString(trimmed) {
+ } else if wasPre || visiblePre {
l.hidden = true
- for _, tag := range findingPre.FindAllString(trimmed, -1) {
- if strings.HasPrefix(tag, "") {
- if pre > 0 {
- pre--
- }
- } else {
- pre++
- }
+ l.countBreak = true
+ for _, tag := range submittedPreTags(l.preCountText) {
+ pre = max(0, pre+tag[2])
}
+ } else if !comment && (indent > 3 || strings.HasPrefix(trimmed, "\t")) {
+ l.hidden = true
} else if comment {
l.hidden = true
- if strings.Contains(trimmed, "-->") {
- comment = false
- }
+ l.countText = findingCommentVisible(trimmed, &comment)
} else if strings.Contains(trimmed, "")
+ l.countText = findingCommentVisible(trimmed, &comment)
} else if len(trimmed) >= 3 && (trimmed[0] == '`' || trimmed[0] == '~') {
n := 0
for n < len(trimmed) && trimmed[n] == trimmed[0] {
@@ -124,14 +153,130 @@ func findingLines(body string) ([]findingLine, bool) {
if n >= 3 {
fence, fenceLength, fenceQuote = trimmed[0], n, quote
l.hidden = true
+ l.countBreak = true
}
}
+ if !l.hidden {
+ l.countText = l.text
+ }
+ l.preCountContinues = pre > 0
+ if !l.preCountContinues {
+ // A comment opened after the final rendered pre close belongs to
+ // the surrounding document, not to the completed code example.
+ if preComment && findingPreEndBeforeEditorialComment(trimmed) {
+ comment = true
+ }
+ preComment = false
+ }
+ l.countContinues = comment
lines = append(lines, l)
offset = next
}
return lines, fence == 0 && pre == 0 && !comment
}
+// This lookahead disambiguates a literal preformatted comment opener from
+// a real multiline comment. A delimiter in a separate Markdown example
+// cannot keep pre mode open. The raw body is never rewritten.
+func findingLastUnfencedCommentClose(body string) int {
+ last, offset := -1, 0
+ var fence byte
+ length, fenceQuote, pre := 0, 0, 0
+ comment := false
+ for rest := body; rest != ""; {
+ line, tail, hasNext := strings.Cut(rest, "\n")
+ consumed := len(line)
+ if hasNext {
+ consumed++
+ }
+ rest = tail
+ line = strings.TrimSuffix(line, "\r")
+ text, quote := line, 0
+ for {
+ trimmed := strings.TrimLeft(text, " ")
+ if len(text)-len(trimmed) > 3 || !strings.HasPrefix(trimmed, ">") {
+ break
+ }
+ quote++
+ text = strings.TrimPrefix(trimmed[1:], " ")
+ }
+ trimmed := strings.TrimLeft(text, " ")
+ indent := len(text) - len(trimmed)
+ if pre == 0 && !comment && quote <= 1 && indent <= 3 && (strings.HasPrefix(trimmed, "`") || strings.HasPrefix(trimmed, "~")) {
+ marker := trimmed[0]
+ n := 0
+ for n < len(trimmed) && trimmed[n] == marker {
+ n++
+ }
+ if n >= 3 {
+ if fence == 0 {
+ fence, length, fenceQuote = marker, n, quote
+ offset += consumed
+ continue
+ }
+ if marker == fence && quote == fenceQuote && n >= length && strings.TrimSpace(trimmed[n:]) == "" {
+ fence = 0
+ offset += consumed
+ continue
+ }
+ }
+ }
+ if fence == 0 && quote <= 1 && (pre > 0 || indent <= 3 && !strings.HasPrefix(trimmed, "\t")) {
+ if close := strings.LastIndex(line, "-->"); close >= 0 {
+ // Indentation inside an active raw pre comment does not stop
+ // its delimiter. Separate indented examples remain inert.
+ if indent <= 3 && !strings.HasPrefix(trimmed, "\t") || comment {
+ last = offset + close
+ }
+ }
+ for _, tag := range submittedPreTags(findingCommentVisible(trimmed, &comment)) {
+ pre = max(0, pre+tag[2])
+ }
+ }
+ offset += consumed
+ }
+ return last
+}
+
+func findingPreEndBeforeEditorialComment(text string) bool {
+ start := strings.LastIndex(text, "")
+ if end < 0 {
+ break
+ }
+ text, *comment = text[end+3:], false
+ continue
+ }
+ start := strings.Index(text, "\nOrdinary text")
+ if !sound || len(lines) != 3 || lines[0].preCountContinues || lines[2].countText != "Ordinary text" {
+ t.Fatalf("a tag mentioned in a note changed prose visibility: %#v", lines)
+ }
+ lines, sound = findingLines("\n\n
\nOrdinary text")
+ if !sound || len(lines) != 6 || !lines[2].preCountContinues || lines[5].countText != "Ordinary text" {
+ t.Fatalf("preformatted note changed block boundaries: %#v", lines)
+ }
+}
+
+func TestHostedParserOrderedParagraphBoundaries(t *testing.T) {
+ for _, tc := range []struct {
+ line string
+ interrupts bool
+ }{{"1. Read the notes", true}, {"1) Read the notes", true}, {"2. Read the notes", false}, {"1. ", false}, {"1st item", false}} {
+ if got := submittedOrderedParagraphInterrupt.MatchString(tc.line); got != tc.interrupts {
+ t.Errorf("%q interruption=%t, want %t", tc.line, got, tc.interrupts)
+ }
+ }
+}
diff --git a/internal/reviewprovider/hosted_rendering_ownership_test.go b/internal/reviewprovider/hosted_rendering_ownership_test.go
new file mode 100644
index 000000000..d4b344591
--- /dev/null
+++ b/internal/reviewprovider/hosted_rendering_ownership_test.go
@@ -0,0 +1,34 @@
+package reviewprovider
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestFindingPreformattedEditorialBoundaries(t *testing.T) {
+ body := "Example
\nVisible text."
+ lines, sound := findingLines(body)
+ if !sound || len(lines) != 4 || !lines[1].hidden || lines[1].countText != "" ||
+ lines[3].hidden || lines[3].countText != "Visible text." {
+ t.Fatal("editorial comment should end before ordinary visible text")
+ }
+ body = "Outside -->\n\n```plain\nExample delimiter -->\n```"
+ if got := findingLastUnfencedCommentClose(body); got != strings.Index(body, "-->") {
+ t.Fatalf("separate code example contributed a delimiter: %d", got)
+ }
+}
+
+func TestSubmittedProviderLabelIsSeparateFromProse(t *testing.T) {
+ if !hasSubmittedLabeledActionableCount("Review notes: Actionable comments posted: 2") {
+ t.Fatal("known provider label was not recognized")
+ }
+ if hasSubmittedLabeledActionableCount("The review notes refer to Actionable comments posted: 2 examples.") {
+ t.Fatal("ordinary prose was treated as an explicit provider label")
+ }
+ text := `A sentence
Another sentence.
`
+ edges := submittedCountParagraphEdges(text)
+ if len(edges) != 2 || edges[0][0] != strings.LastIndex(text, "") {
+ t.Fatalf("paragraph edge was confused with an attribute literal: %v", edges)
+ }
+}
diff --git a/internal/reviewprovider/hosted_standing_zero.go b/internal/reviewprovider/hosted_standing_zero.go
index 196ee3f10..9cf8fe2f2 100644
--- a/internal/reviewprovider/hosted_standing_zero.go
+++ b/internal/reviewprovider/hosted_standing_zero.go
@@ -138,21 +138,254 @@ func (p *standingRiskParser) line(line string, stack []string) (handled, ok bool
return false, true
}
+// Only this explicitly historical report is recognized as narrative. Counts
+// are bounded and must reconcile; the report supplies no current inventory or
+// comparison proof. Unknown wording, nonzero routes and current claims retain
+// the global finding guard.
+var standingHistoricalCheckpoint = regexp.MustCompile(`^The latest reported Hosted review checkpoint lists (0|[1-9][0-9]{0,2}) accepted findings: (0|[1-9][0-9]{0,2}) minor and (0|[1-9][0-9]{0,2}) trivial, with (0|[1-9][0-9]{0,2}) major and 0 routed\. Finding details and current review findings are not available\.$`)
+
+func standingHistoricalCheckpointLine(line string) bool {
+ counts := standingHistoricalCheckpoint.FindStringSubmatch(line)
+ if counts == nil {
+ return false
+ }
+ var values [4]int
+ for i := range values {
+ values[i], _ = strconv.Atoi(counts[i+1]) // The bounded decimal grammar cannot overflow.
+ }
+ return values[0] <= 100 && values[0] == values[1]+values[2]+values[3]
+}
+
+// This parser observes the existing visibility/HTML scanner; it never removes
+// or hides text. It recognizes one closed, root walkthrough Summary envelope
+// with one generated release-notes region. Only a complete envelope can exempt
+// its one standalone historical checkpoint line from the numeric-claim guard.
+// All other lines, including other claims in that same region, remain guarded.
+// Line-based ancestry cannot credit an owner across an unfinished HTML tag.
+var standingIncompleteOwnerTag = regexp.MustCompile(`(?i)?(?:dd|dl|details)(?:[ \t/][^>]*|)$`)
+
+type standingHistoricalParser struct {
+ phase, claimLine int
+ seen, invalid, bodyBreak bool
+}
+
+// Reserved release-note wording matters inside marker comments, not in ordinary
+// visible summary prose. The exact switch below still controls valid transitions.
+func standingHasReleaseMarkerComment(line string) bool {
+ for {
+ _, comment, found := strings.Cut(line, "")
+ if strings.Contains(strings.ToLower(body), "release notes by coderabbit.ai") {
+ return true
+ }
+ if !closed {
+ return false
+ }
+ line = rest
+ }
+}
+
+// A balanced preformatted example cannot reserve a release marker. Tags
+// inside HTML comments never change whether a marker is in preformatted text.
+func standingHasReleaseMarkerOutsidePre(line string) bool {
+ pre, commentAt := false, -1
+ for _, span := range hostedComparisonTokens.FindAllStringIndex(line, -1) {
+ token := line[span[0]:span[1]]
+ if commentAt >= 0 {
+ if token == "-->" {
+ if standingHasReleaseMarkerComment(line[commentAt:span[1]]) {
+ return true
+ }
+ commentAt = -1
+ }
+ continue
+ }
+ tag := hostedComparisonTag.FindStringSubmatch(token)
+ if pre {
+ if tag != nil && strings.EqualFold(tag[1], "pre") && strings.HasPrefix(token, "") {
+ pre = false
+ }
+ continue
+ }
+ if token == ""
+ const releaseEnd = ""
+ switch line {
+ case "":
+ if p.seen || inRecent || ancestry != "" {
+ p.invalid = true
+ }
+ p.seen, p.phase = true, 1
+ return
+ case "":
+ if p.phase != 10 || inRecent || ancestry != "" {
+ p.invalid = true
+ }
+ p.phase = 11
+ return
+ case releaseStart:
+ if p.phase != 5 || inRecent || ancestry != "details/dl/dd" {
+ p.invalid = true
+ }
+ p.phase = 6
+ return
+ case releaseEnd:
+ if p.phase != 6 || inRecent || ancestry != "details/dl/dd" {
+ p.invalid = true
+ }
+ p.phase = 7
+ return
+ }
+ if strings.Contains(line, "")
+ markerCommentTail = historical.scanMarkerComment(markerCommentTail, body)
+ if closed && standingHasReleaseMarkerComment(remainder) {
+ historical.invalid = true
+ }
+ }
+ }
if !comment && len(stack) == 0 {
switch {
case line == standingStatusStart:
@@ -233,7 +516,9 @@ func standingSections(body string) (recent []string, coverage string, statusZero
continue
}
}
- for _, token := range hostedComparisonTokens.FindAllString(line, -1) {
+ beganPreformatted := pre
+ for _, span := range hostedComparisonTokens.FindAllStringIndex(line, -1) {
+ token := line[span[0]:span[1]]
if comment {
if token == "-->" {
comment = false
@@ -246,6 +531,12 @@ func standingSections(body string) (recent []string, coverage string, statusZero
continue
}
if token == "")
+ historical.scanMarkerComment("", fragment)
+ }
comment = true
continue
}
@@ -267,11 +558,27 @@ func standingSections(body string) (recent []string, coverage string, statusZero
if len(stack) == 0 || stack[len(stack)-1] != tag {
return nil, "", false, false
}
+ if historical != nil {
+ historical.close(len(stack))
+ if len(stack) <= 3 {
+ rawHistoricalOwner, rawHTMLBlock = false, false
+ }
+ }
stack = stack[:len(stack)-1]
} else if !strings.HasSuffix(token, "/>") {
+ if rawHistoricalOwner && rawHTMLBlock && standingImplicitSummaryClose(stack, tag) {
+ historical.invalid = true
+ }
stack = append(stack, tag)
}
}
+ if historical != nil {
+ if !comment {
+ markerCommentTail = ""
+ } else if start := strings.LastIndex(line, "\n## Validation\n\n"+standingHistoricalCheckpointTest+"\n\nIndependent synthetic change description.\n