diff --git a/docs/browser-guide.md b/docs/browser-guide.md index 1cdcb70f3..9e84da0cc 100644 --- a/docs/browser-guide.md +++ b/docs/browser-guide.md @@ -18,6 +18,8 @@ Disconnect, expired or revoked access, an instance mismatch, or leaving the conn Routes are `/projects/{project_id}`, `/projects/{project_id}/jobs/{job_id}`, `/projects/{project_id}/workers`, `/projects/{project_id}/workers/{worker_id}`, `/projects/{project_id}/notes`, `/projects/{project_id}/notes/{note_id}`, `/projects/{project_id}/notes/{note_id}/history/{revision}`, `/projects/{project_id}/inbox` and `/projects/{project_id}/inbox/{conversation_id}`, `/projects/{project_id}/reviews`, `/projects/{project_id}/reviews/pulls/{number}`, `/projects/{project_id}/reviews/runs/{run_id}`, `/projects/{project_id}/map`, `/projects/{project_id}/map/entries/{entry_id}` and `/projects/{project_id}/map/entries/{entry_id}/history/{revision}`. Review drill-down links retain an optional `snapshot` query for historical consistency. Choose a worker to follow its incoming inbox. Worker changes cancel the prior view's requests and subscription and clear its cache; they do not alter credentials, assignments or server state. Project-scoped read access permits conversation reads within that project, as documented by the API. +Review queue pages and PR details also display explicitly current [round progress and accepted queue priority](review-scheduling.md#accepted-queue-priority), separate from their retained history snapshot. Only visible PRs are included in a bounded local read; project events refresh that current data. An earlier accepted Hosted request displays **Behind #PR** on later queued rows rather than implying they can start at their own cooldown deadline. Countdown text changes locally without polling. + Job detail reads the latest [checkpoint](job-checkpoints.md), including its captured revision, attribution, done/next/blocker and evidence. No-checkpoint state is explicit. The current brief and latest envelope are separate reads: a revision mismatch prompts refresh rather than implying an atomic combined snapshot. Checkpoint history loads only after opening it and remains cursor-paged; closing it stops that active view. Evidence is escaped plain text rather than an executable or automatically opened link. Native run details include an explicit **Assess captured comparison** panel for the current local review requirements. Opening it reads the [captured-comparison assessment](review-controls.md#captured-comparison-assessment); closing cancels its request, and reopening reads again. Imported history has no assessment control. The panel shows the returned captured target and observation time separately from policy evaluation; it does not verify current GitHub source, CI or merge readiness. Closed panels and ordinary queue reads perform no assessment request. diff --git a/docs/mcp.md b/docs/mcp.md index 93c4e4b2b..be9f79974 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -93,6 +93,7 @@ Startup validates configuration without opening the credential or contacting the | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | | `wait_for_messages` | Required event cursor; optional limit 1–100 and wait_seconds 1–50, default 20/25. One new-message event page or quiet timeout over a call-owned persistent stream. | | `review_execution_read` | No fields; stored execution configuration and revision, without provider work. | +| `review_lane_diagnostic` | Required channel; provider-free [per-PR lane diagnostics](review-lane-diagnostics.md) with retained source timestamps/completeness, local holds and exact parent blockers. Not fresh admission or a dispatch promise. | | `review_scheduling_read` | No fields; stored project scheduling settings, revision and paused queued PRs, without provider work. | | `review_scheduling_configure` | Required idempotency_key/expected_revision/automatic_hosted; optional automatic_cli preserves its existing value when omitted. Project management capability configures [default-off automatic scheduling](review-scheduling.md), including authorization for later provider work within existing review limits. | | `review_pull_scheduling_read` | Required pull_number; reads the per-PR pause for new and undispatched explicit and automatic reviews, and its revision. | diff --git a/docs/provider-observations.md b/docs/provider-observations.md index 7806afb9e..2235da794 100644 --- a/docs/provider-observations.md +++ b/docs/provider-observations.md @@ -20,6 +20,8 @@ CI reads bind explicit source and selected commit identities, recheck passing ca CodeRabbit decoding recognizes closed generated envelopes and presentation variants while retaining original bodies and identities. Publication attribution, exact comparison, provider run identity, finished acknowledgment and counted finding inventory remain separate checks. Inline, outside-diff, duplicate and additional findings retain their own source references. Additional-only summaries support at most one bare `
` as the first visible, nonempty, non-Markdown-quoted line after each `
` inside balanced definition-list wrappers at the same details and HTML blockquote depths, and a standalone heading around exact Review info metadata. Repeated breaks, mid-body breaks and breaks outside the matching definition body remain unsupported; hidden or Markdown-quoted examples cannot supply wrapper boundaries or restart a body. Neither presentation form can hide unknown findings or supply comparison authority by itself. Supported count omission for positive and marked-empty publications follows the [native source contract](review-execution.md#hosted-source-adoption). Malformed or contradictory count metadata remains refused; omission by itself never establishes a clean review. Baseline-qualified historical annotation exclusion retains original comment/review identities, bodies and positions. Positive comparison proof requires an independently bound pre-POST baseline and authenticated current standing metadata; conflicting comparison metadata remains refused. Quoted prompts and examples cannot supply authoritative metadata. An authenticated foreign Bot report whose entire current body contains no case-insensitive `coderabbit` mention is not an inferred request authority merely because it was edited. This current-source policy does not prove its original body or require a pre-trigger copy; bot-looking prose or login names do not replace the source-owned actor kind. Visible competing review commands still close attribution regardless of author. Edited posting-actor, human and other actor-kind comments, and Bot comments with provider mentions even in quoted or hidden text, retain the conservative edit barrier. Baseline-qualified projections and old finding annotation proof preserve their separate source-binding checks without rewriting either capture. +A markerless submitted review may instead contain exactly one positive, counted Additional comments category followed directly by the existing `h6`-wrapped Review info and generated status footer. The complete provider collections must prove there are no attached inline roots or in-window orphan roots. The original submitted review, unique fresh run, configured provider actor, exact head, explicit full comparison, counted selected-file inventory and unique later finished acknowledgment retain their ordinary checks. Every additional finding must decode completely and name a selected file; category/group counts, source text and its unverified qualification remain intact. Actionable-count declarations, mixed or unknown categories, empty inventories, competing submissions or commands and ambiguous acknowledgments cannot use this path. This parser support preserves positive findings and does not itself finalize adjudication, change round accounting, or grant clean/taper credit. The existing runtime proof pipeline remains responsible for completion. + A closed unquoted Follow-up Comments envelope may carry positive outside-diff findings without a count header. Its generated badge, explicit matching title, severity, range, reviewed-head source location and fingerprint must agree. The source location establishes finding coordinates only; it never supplies base or effective-parent proof. Empty, ambiguous or unsupported envelopes remain incomplete. A generated Review info block can report files whose changes were unavailable. Retain that bounded limitation separately from finding-inventory completeness; a complete captured result does not imply every selected file was reviewed. Original findings and completion accounting remain unchanged. diff --git a/docs/review-execution.md b/docs/review-execution.md index 1ad54c1b1..31a4a7e7e 100644 --- a/docs/review-execution.md +++ b/docs/review-execution.md @@ -124,7 +124,7 @@ The trusted one-pass recovery path reads the original admitted attempt and capab Hosted preflight must journal its fixed non-review allowance query separately from the eventual review trigger. The preparing attempt binds the original operation, capability, actors and exact source anchor before any query POST. Only the caller that newly creates that intent may make its one post; an existing or uncertain intent requires observation-based recovery and never permits blind reposting. Retain the exact returned or recovered query comment even if preparation later stops. A query grants no review admission or coverage. New query intents recheck current authorization, configuration, policy and source identity; retained query reads and response recording preserve already-issued work. Preparing may perform this journaled non-review metadata query, but may not post a review or spend its allowance before review admission. The query journal, one-pass query observer, immutable availability retention and final hosted guard are implemented components. The concrete hosted driver and configured daemon call them. -A separate pure allowance-query helper generates the fixed documented `@coderabbitai rate limit` command with an operation/attempt/head marker. Its resolver recognizes the observed availability and cooldown reply grammars in a complete, unambiguous comment window. Availability retains only the original query/response identities and times, without numeric capacity or billing proof. Cooldown retains a conservative retry-not-before time with one reported unit (second or minute) of rounding margin. Neither observation grants review permission or reserves provider quota. Edited competing comments close attribution even when their current bodies removed or hid the command. Unknown replies stay unproven. The pure resolver performs no I/O. A separate one-pass runtime component journals query intent before its one fixed metadata post and recovers an uncertain response without reposting. It saves and reference-checks immutable query source before interpretation. A trusted retention bridge records one proven available observation against the confirmed query and exact source, while preserving the original response time. Final hosted verification combines that record with authorization, policy, reservations, channel-specific target/predecessor evidence and the exact unposted review intent in one SQL snapshot; stale responses cannot become fresh merely because they were fetched again. The concrete driver and daemon compose bounded preflight observation, one-use dispatch and scheduled restart recovery. See CodeRabbit's [review commands](https://docs.coderabbit.ai/reference/review-commands). +A separate pure allowance-query helper generates the fixed documented `@coderabbitai rate limit` command with an operation/attempt/head marker. Its resolver recognizes the observed availability and cooldown reply grammars in a complete, unambiguous comment window. Availability retains only the original query/response identities and times, without numeric capacity or billing proof. Cooldown retains a conservative retry-not-before time with one reported unit (second or minute) of rounding margin. Neither observation grants review permission or reserves provider quota. Edited competing comments close attribution even when their current bodies removed or hid the command. Unknown replies stay unproven. The pure resolver performs no I/O. A separate one-pass runtime component journals query intent before its one fixed metadata post and recovers an uncertain response without reposting. It saves and reference-checks immutable query source before interpretation. A trusted retention bridge records one proven available observation against the confirmed query and exact source, while preserving the original response time. Final hosted verification combines that record with authorization, policy, reservations, channel-specific target evidence and exact predecessor source identity and the exact unposted review intent in one SQL snapshot; stale responses cannot become fresh merely because they were fetched again. The concrete driver and daemon compose bounded preflight observation, one-use dispatch and scheduled restart recovery. See CodeRabbit's [review commands](https://docs.coderabbit.ai/reference/review-commands). The operator explicitly selects `commit_status` or `check_run` for hosted progress. Commit statuses require the provider bot's stable numeric identity and the `CodeRabbit` context; check runs require the configured GitHub App ID, exact candidate and `CodeRabbit` check name. The complete selected collection shares a 15-second budget. Validate collection completeness, row identities and duplicates before selection; validate activity timestamps and lifecycle details only for the configured provider signal. Timestamps on another actor’s status or another App’s check cannot establish or block CodeRabbit activity. Selected provider signals retain strict timestamp and lifecycle validation. A trusted pending signal holds dispatch. Complete scoped absence means only that no activity was observed for that candidate; it allows a first review without fabricating a previous status. Unknown states, partial pages and conflicting identities remain unproven. A terminal status, including a successful “review skipped” status, establishes no review coverage. Check-run observation retains any trusted nonterminal run without guessing creation order from IDs or nullable timestamps. These observations do not establish account-wide or other-head idleness. See GitHub's [commit status](https://docs.github.com/en/rest/commits/statuses) and [check-run](https://docs.github.com/en/rest/checks/runs) APIs. @@ -224,7 +224,7 @@ Trusted initial publication builds a channel-specific native run from the retain A missing current PR projection leaves successfully retained CLI evidence in the authoritative ledger without changing a completed execution to uncertain or keeping its reservation. It does not recreate browser facts or finalize the source. Other publication failures remain recoverable failures; a failed retention never becomes a completed capture. -Hosted publication does not confer CLI comparison credit. The shared channel-explicit comparison check keeps current-comparison coverage separate from pending evidence. Each invocation selects `cli` or `hosted`; pending evidence and coverage never cross that channel boundary. Coverage requires a completed native attempt and complete finalized capture for the exact current repository, PR, candidate, base and effective parent, with every finding decided and accepted findings carrying fix proof. Pending completed native evidence is checked across all heads of the selected PR: missing captures, unfinished decisions/finalization and accepted findings without proof block another spend. A ready capture cannot hide another pending capture. The final local action guard repeats this check in its authorization snapshot. Imported history never becomes native execution credit. Repository renames preserve coverage when stable identity and Git objects still match. Hosted captures additionally require their retained command/trigger identity and complete publication metadata; they never fabricate a reviewed-file list. The indexed lookup examines at most 100 completed operations in the selected channel for the selected PR before loading evidence; excess history produces an explicit capacity hold instead of an unbounded scan or another provider spend. This predicate does not establish aggregate policy sufficiency, CI success or merge readiness. The concrete CLI driver supplies fresh source observations, selects only CLI comparison credit for its target and predecessors, and repeats local authorization before its one-use process action. Hosted comparison support alone enables no hosted dispatch. +Hosted publication does not confer CLI comparison credit. The shared channel-explicit comparison check keeps current-comparison coverage separate from pending evidence. Each invocation selects `cli` or `hosted`; pending evidence and coverage never cross that channel boundary. Coverage requires a completed native attempt and complete finalized capture for the exact current repository, PR, candidate, base and effective parent, with every finding decided and accepted findings carrying fix proof. Pending completed native evidence is checked across all heads of the selected PR: missing captures, unfinished decisions/finalization and accepted findings without proof block another spend. A ready capture cannot hide another pending capture. The final local action guard repeats this check in its authorization snapshot. Imported history never becomes native execution credit. Repository renames preserve coverage when stable identity and Git objects still match. Hosted captures additionally require their retained command/trigger identity and complete publication metadata; they never fabricate a reviewed-file list. The indexed `review_comparison` ledger supplies scoped pending and ready proof facts without a lifetime 100-operation ceiling. Dirty authority fails closed; installation and repair backfills independently validate the original records as described in [retained native channel completion](reviews.md#retained-native-channel-completion). This predicate does not establish aggregate policy sufficiency, CI success or merge readiness. The concrete CLI driver supplies fresh source observations, checks CLI comparison credit only for its target and verifies predecessor source identities without requiring their review completion, and repeats local authorization before its one-use process action. Hosted comparison support alone enables no hosted dispatch. New attempts, run evidence, findings, decisions, effective fix proofs and observation freshness are native durable records. Source finalization freezes source counts and identities. Adjudication/fix corrections append guarded evidence; they preserve earlier values and never replace finding text to reuse an old count. Public checkpoint publication is a separate recoverable external action. diff --git a/docs/review-lane-diagnostics.md b/docs/review-lane-diagnostics.md new file mode 100644 index 000000000..14c9dd03c --- /dev/null +++ b/docs/review-lane-diagnostics.md @@ -0,0 +1,19 @@ +# Review lane diagnostics + +The read-only lane diagnostic explains each configured PR's local evidence and dependency state using the latest retained source frame for the selected channel. It never starts or resumes selection, refreshes GitHub, contacts a review provider, changes allowance or adjudicates a result. + +Use `fc reviews scheduling diagnostics --channel cli` or `hosted`, MCP `review_lane_diagnostic` with the explicit `channel`, or `GET /api/v1/projects/{project_id}/reviews/lanes/{channel}/diagnostics`. Project read access suffices. The response contains at most the configured 100 PRs in queue order. It returns no provider bodies or credentials. + +## Reading the result + +The scope is always `retained_source_local_policy`. `evaluated_at` is the time of this local read; `source_checked_at`, each candidate's `source_observed_at`, and `source_configuration_revision` describe retained acquisition, not a fresh provider check. `source_complete` means that acquisition covered the configured queue with no global source error. It does not establish current GitHub heads or dispatch eligibility. Unknown suffixes remain `unknown` with `source_not_observed`; a changed configuration or repository invalidates the frame for all current candidates. Missing or damaged evidence never becomes an empty healthy lane. + +Each observed candidate has `local_state` and `local_reason`. `locally_ready` means only that the shared local evaluator found no evidence, source-obligation, route, PR-pause, round or actual-parent hold in that retained comparison. It is not a preview of the next automatic selection. Provider limits, active operations, automatic-intent suppression, authorization, current source and transactional admission still apply. `lane_reason` separately reports a configured project/channel pause, disabled channel or global storage/identity hold. + +A `predecessor_unfinished` row identifies `blocking_pull_number` and the concrete source-identity `blocking_reason`, such as a missing, moved, cyclic or unavailable parent. Ancestor findings, review rounds and PR pauses do not hold a child's review. The diagnostic shares the ordinary selector's source-chain checks and target-local obligation checks; it does not grant dispatch or merge permission. A local hold on the candidate itself remains its primary reason. + +For a lane audit, combine this diagnostic with current operation/scheduling/round reads and current published source observations. Do not use `locally_ready` to force a review or declare a lane healthy. A stale or incomplete frame means eligibility remains unestablished and calls for an authorized ordinary source/selection workflow, not a new review merely to obtain diagnostics. + +## Validation boundary + +Focused synthetic tests cover retained pending evidence, independent and stacked review progression, actual-parent source holds with exact blocker identity, incomplete/missing/configuration-changed/repository-changed source, malformed retained frames, revoked read access, strict bound client responses, read-only MCP discovery, CLI parsing and unchanged durable selection state. A 100-row shared completed-ancestor case passes the bounded read deadline normally and under the race detector. Each candidate's local facts stay within the current read transaction; ancestor traversal reads source identity rather than ancestor review sufficiency. Local proof does not establish deployed service support, current live admission or provider throughput. diff --git a/docs/review-round-controls.md b/docs/review-round-controls.md index f58246dfb..3777bbf44 100644 --- a/docs/review-round-controls.md +++ b/docs/review-round-controls.md @@ -14,7 +14,7 @@ Carried operational adoption is supported through independently guarded preview/ ## Operational controls -Hosted and CLI retain independent per-PR channel state. Each explicit start selects at most one eligible target in queue priority order, preserving actual-parent dependencies. A cooldown or active review in one channel does not hold the other channel. Automatic scheduling remains a separate consumer. Minimum and maximum count additional completed rounds. Equal values express an exact count; the CLI's `--exact` is only shorthand for those equal bounds. A maximum permits early taper once the minimum is satisfied. +Hosted and CLI retain independent per-PR channel state. Each explicit start selects at most one eligible target in queue priority order, preserving actual-parent source identity without requiring ancestor review completion. A cooldown or active review in one channel does not hold the other channel. Automatic scheduling remains a separate consumer. Minimum and maximum count additional completed rounds. Equal values express an exact count; the CLI's `--exact` is only shorthand for those equal bounds. A maximum permits early taper once the minimum is satisfied. New execution enrollment atomically initializes missing PR/channel controls using the selected [project defaults](#project-defaults): explicit policy `round_defaults` take precedence over product bounds, and new controls use taper two. A re-added pair with any retained native review operation is excluded from this initialization, so an older unconfigured pair remains unconfigured. Reordering, pausing or changing capability leaves existing enrolled pairs untouched. Existing grants and controls, including explicit controls installed before enrollment, are preserved. @@ -40,7 +40,7 @@ Work accepted while a PR/channel was unconfigured has no round grant binding. Th The first explicit conversion of a legacy rule reconstructs only its clean streak from immutable, already-counted current-epoch completions. This handles older rules that froze the displayed streak after taper: all-clean results preserve earned progress, and a recorded accepted result resets it. It adds no completion credit, changes no original capture/counts and leaves the previous history bytes intact. Backup replay validates the same evidenced transition. Older past epochs and imported history remain historical evidence, not new native completions. -Per-PR changes use their own revision and actor attribution rather than changing the project policy revision or holding unrelated PRs. Requests retain their original grant binding and recheck the current same-epoch limits, closure and obligations before preparation and provider dispatch. Both source preparation and final transactional admission allow another round after earned PR/channel completion only while the bound grant still requires discovery. They preserve pending-capture/finding obligations, source identity, current authority, provider limits and reservations. For ordinary stacked progression, an explicitly finished grant replaces the predecessor single-capture requirement; outstanding evidence/fix obligations still hold dependent work. Closure or exhausted allowance without validated native completion remains a separate readiness limitation and never manufactures earned credit; later Git movement alone does not create that limitation. +Per-PR changes use their own revision and actor attribution rather than changing the project policy revision or holding unrelated PRs. Requests retain their original grant binding and recheck the current same-epoch limits, closure and obligations before preparation and provider dispatch. Both source preparation and final transactional admission allow another round after earned PR/channel completion only while the bound grant still requires discovery. They preserve pending-capture/finding obligations, source identity, current authority, provider limits and reservations. For ordinary stacked review progression, each PR's grant and outstanding evidence/fix obligations govern that PR, not its descendants. Ancestor completion is not a review-dispatch prerequisite; the [review progression contract](reviews.md#admission-and-execution) preserves exact source identity and separate merge readiness. Closure or exhausted allowance without validated native completion remains a separate readiness limitation and never manufactures earned credit; later Git movement alone does not create that limitation. If a queued request’s target no longer matches its original comparison, preparation holds that request rather than rebinding it. Follow the [review-execution](review-execution.md) contract with a qualified current comparison and fresh authorized request/key; preserve retained rounds and known cooldowns instead of resetting grants. The recovery does not itself change configured PR queue order. @@ -100,7 +100,7 @@ See [refusals and recovery](adoption-obligations.md#refusals-and-recovery) for r ## One explicit channel-front run -`reviews start --channel cli --key KEY` accepts one durable selection before provider reads and authorizes at most one ordinary exact-head child operation. Hosted uses the same independent contract. The service considers configured queue priority while preserving actual published parent dependencies: a Draft, comparison-local refusal or pending earlier PR evidence does not block independent later work, but cannot be bypassed by its real dependent. These are PR-local holds; a queued, preparing, posting, active or uncertain native operation in the same channel holds new selection with `review_inflight`, even for independent later work. Incoming routes and retained source obligations remain guards even after round completion or captured coverage. Verified external Hosted results still awaiting native reconciliation hold that PR's Hosted channel; imported labels alone are not authority, and old-head obligations survive metadata movement. Fresh verified merged entries can be skipped. Closed, tapered or exhausted grants do not erase unfinished evidence or fix obligations. +`reviews start --channel cli --key KEY` accepts one durable selection before provider reads and authorizes at most one ordinary exact-head child operation. Hosted uses the same independent contract. The service considers configured queue priority while preserving actual published parent source identity. Pending earlier PR evidence and incomplete ancestor rounds do not block a later child's review. Source refusals such as missing, moved or draft parent comparisons remain explicit holds; they do not become review-completion requirements. These are PR-local holds; a queued, preparing, posting, active or uncertain native operation in the same channel holds new selection with `review_inflight`, even for independent later work. This guard applies to an explicit channel-front selection. Automatic selection has the bounded earlier-priority exception described in [review scheduling](review-scheduling.md): it may reconsider the prefix before the earliest queued request, while preparing, posting, active and uncertain operations still hold selection. The later queued operation retains its identity and cooldown. Incoming routes and retained source obligations remain guards even after round completion or captured coverage. Verified external Hosted results still awaiting native reconciliation hold that PR's Hosted channel; imported labels alone are not authority, and old-head obligations survive metadata movement. Fresh verified merged entries can be skipped. Closed, tapered or exhausted grants do not erase unfinished evidence or fix obligations. Acceptance binds the authenticated actor/worker and current configuration, policy and installed capability. `--expect-pr NUMBER` is an assertion, never forced selection. Optional `--expected-configuration-revision REVISION` asserts acceptance against a known configuration. Both assertions reject explicit null HTTP values. Paused execution returns `reviews_paused`; an unconfigured channel returns `review_not_configured` without storing a request or receipt. diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 130089270..c040c80ff 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -1,20 +1,16 @@ # Review scheduling -## Source-slice boundary - -This slice includes the scheduling engine, retained-state guards, HTTP API and CLI/MCP controls. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. - Projects can independently opt in to automatic new Hosted or CLI requests. Both default to off. Explicit CLI requests continue to work without enabling automatic selection; a proven quota refusal retains any accepted request through [durable CLI waiting](retained-review-quota-controls.md), without replacing that operation. Automatic GitHub observation and timer-backed retries of explicit requests are independent of this setting. Retries of automatically selected requests still require their channel to be continuously enabled. See [observation](github-observation.md) and [timer-backed waiting](retained-review-quota-controls.md). ## Automatic Hosted requests A project manager enables scheduling through CLI, MCP or the HTTP API. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. This project scheduling write requires bearer authentication and active project worker attribution. Browser sessions do not authorize this route. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected CLI intent crossing a scheduling revision additionally needs the same explicit, writer-owned CLI basis in every revision. An unrelated-channel edit can preserve that basis; a missing basis or an authorizer change followed by a change back cannot prove CLI continuity. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The acceptance event records whether a new selection is explicit or automatic. Automatic selections and their children require matching retained scheduling attribution before selection, recovery or dispatch. Missing or conflicting attribution holds those requests. For older selections, a caller-supplied PR pin, an exact retained explicit mutation receipt, or complete retained history showing acceptance before automatic scheduling for that channel can establish explicit origin. An ambiguous legacy selection stays held. Current explicit authorization still applies. -The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. +The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Exact source identity, target-local publication/findings/routes/imported obligations, round limits, taper and provider guards still apply. Both independent PRs and actual descendants can be reviewed while an earlier PR awaits fixes or more review rounds. This is review progression, not merge permission; the [review contract](reviews.md#admission-and-execution) owns that boundary. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. -Meaningful source, review or control changes can create another automatic intent. A waiting later PR does not prevent reconsideration of an earlier PR that becomes eligible; the earlier request can take priority while the later request retains its identity and cooldown. Existing queued work on a PR prevents a duplicate intent for that PR, and active provider work is not interrupted. Timer-backed requests retain their original operation and retry deadline. Ticks, restarts, observation timestamps and failed/cancelled operation transitions cannot recreate the same request. A clean CLI completion alone cannot restart a cancelled Hosted request. A dependent PR can become eligible when its actual predecessor completes at the same head. Cancellation stops that intent; use a PR pause to hold new reviews persistently. Planning and settlement use semantic facts from the eligible queue prefix. A waiting request fences off later siblings and their local basis checks. A candidate still requires proof of any source-owned dependency. The full-queue digest and selected PR digests retain their original format. Older pre-child holds have only opaque full-queue digests. While a waiting request shortens the queue, an older hold with the same execution configuration, policy and channel basis can prevent accepting an unproved replacement. The scheduler can compare the original digest once the full queue is eligible. Explicitly rearming that channel changes its basis and permits fresh selection under the normal guards. A setting change affecting only the other channel preserves this channel’s intent basis. Changing this channel’s setting or the authorizing principal, worker or credential changes its basis. Explicitly reasserting unchanged settings rearms only the supplied channels; an omitted CLI setting preserves its basis. The current scheduling event retains each channel’s basis revision independently of the shared authorization revision. Older events use their existing shared revision without rewriting any stored digests, so an upgrade alone cannot recreate cancelled work. +Meaningful source, review or control changes can create another automatic intent. A waiting later PR does not prevent reconsideration of an earlier PR that becomes eligible; the earlier request can take priority while the later request retains its identity and cooldown. Existing queued work on a PR prevents a duplicate intent for that PR, and active provider work is not interrupted. Timer-backed requests retain their original operation and retry deadline. Ticks, restarts, observation timestamps and failed/cancelled operation transitions cannot recreate the same request. A clean CLI completion alone cannot restart a cancelled Hosted request. An ancestor's review completion is not required for a child's eligibility; exact parent source identities still apply. Cancellation stops that intent; use a PR pause to hold new reviews persistently. Planning and settlement use semantic facts from the eligible queue prefix. A waiting request fences off later siblings and their local basis checks. A candidate still requires proof of any source-owned dependency. Selection uses the current source-identity digest. A previously cancelled child with a still-matching exact legacy digest remains suppressed across upgrade. Older pre-child holds have only opaque full-queue digests. While a waiting request shortens the queue, an older hold with the same execution configuration, policy and channel basis can prevent accepting an unproved replacement. The scheduler can compare the original digest once the full queue is eligible. Explicitly rearming that channel changes its basis and permits fresh selection under the normal guards. A setting change affecting only the other channel preserves this channel’s intent basis. Changing this channel’s setting or the authorizing principal, worker or credential changes its basis. Explicitly reasserting unchanged settings rearms only the supplied channels; an omitted CLI setting preserves its basis. The current scheduling event retains each channel’s basis revision independently of the shared authorization revision. Older events use their existing shared revision without rewriting any stored digests, so an upgrade alone cannot recreate cancelled work. -A pre-child automatic Hosted or CLI selection held only by `source_budget_exhausted`, `source_fetch_timeout`, `source_provider_unavailable` or `routed_findings_unavailable` can retry its source selection after at least thirty seconds. A route-related hold is retryable only after no configured pull retains a route invalidation and the ordinary retry guards pass. It reuses the original selection and accepted configuration, policy, capability and authorizer, with the exact scheduling revision still current for CLI and for legacy Hosted history. A completed, unselected Hosted retry can survive an unrelated-channel edit only when paired durable settings events prove the same scheduling-authorizer binding, uninterrupted Hosted enablement and the same Hosted lane basis. This is not a history of credential activation or grants; current authorization is checked independently. Changing the authorizer, withdrawing or rearming Hosted, or missing proof requires a new authorization under ordinary scheduling rules. Already-linked work keeps its established checks. At most two such delayed retries are permitted by a conservative durable transition budget; interrupted-selection recovery consumes that budget rather than resetting it. Existing recovery of an interrupted read remains separate from this bound on completed source holds. Restart and backup restore retain the budget and last-transition time. Restore/provider holds still prevent work. +A pre-child automatic Hosted or CLI selection held only by `source_budget_exhausted`, `source_fetch_timeout`, `source_provider_unavailable` or `routed_findings_unavailable` can retry its source selection after at least thirty seconds. A route-related hold is retryable only after no configured pull retains a route invalidation and the ordinary retry guards pass. It reuses the original selection and accepted configuration, policy, capability and authorizer only while the exact shared scheduling revision remains current. An edit to the other lane also changes this revision; a completed source hold cannot resume under it without a new ordinary selection. Current authorization is checked independently. Already-linked work keeps its established checks. At most two such delayed retries are permitted by a conservative durable transition budget; interrupted-selection recovery consumes that budget rather than resetting it. Existing recovery of an interrupted read remains separate from this bound on completed source holds. Restart and backup restore retain the budget and last-transition time. Restore/provider holds still prevent work. A later selection or direct operation in the same channel fences off this recovery, including a cancelled, failed or uncertain request. Explicit held selections, linked children, exhausted budgets, refusals, rate limits and invalid source responses are never reopened by it. The retry performs ordinary fresh source selection and normal admission; success may link at most one ordinary child operation under the original authority. It neither grants rounds nor bypasses any dispatch guard. A meaningful source or control change can still authorize a new automatic intent through the normal scheduler. @@ -24,7 +20,7 @@ Results still require normal adjudication, finalization and fix evidence. Automa A project manager can explicitly enable `automatic_cli` through CLI, MCP or the project scheduling API. A future browser editor must preserve the CLI setting when editing Hosted configuration. Both settings use the retained manager credential and active worker, with the same authorization rechecks before selection and dispatch. Changing either setting uses the shared scheduling revision. Older Hosted-only writes omit `automatic_cli` and preserve its current value; explicit `false` disables new CLI automation. Omission preserves the setting, not the shared authorizer: a successful write leaving either channel enabled records the acting manager credential and active worker for new automation, even if the write disables only the other channel. -Automatic CLI uses the ordinary durable channel-front selection and execution path, without out-of-order or file-limit overrides. Existing grants, maxima, taper, channel closure, exact current-head checks, source-owned predecessor dependencies, publication and adjudication requirements remain in force. No setting increases grants or adjudicates findings. A meaningful completed result or source/control change can authorize another selection; ticks, restart, failed attempts and cancellation alone cannot. CLI and Hosted results have separate intent digests, so a clean completion in the other channel does not recreate a cancelled request. +Automatic CLI uses the ordinary durable channel-front selection and execution path, without out-of-order or file-limit overrides. Existing grants, maxima, taper, channel closure, exact current-head checks, source-owned predecessor identities, and the selected target's publication and adjudication requirements remain in force. No setting increases grants or adjudicates findings. A meaningful completed result or source/control change can authorize another selection; ticks, restart, failed attempts and cancellation alone cannot. CLI and Hosted results have separate intent digests, so a clean completion in the other channel does not recreate a cancelled request. The current server policy fixes one repository preference in code; it is not a per-project setting. For competing CLI work on the same installed provider account, the repository `benhook1013/FireMUD` takes priority over other projects. The repository identity is case-insensitive; a project display name does not grant priority. Selection takes the oldest eligible account group first, then considers that repository first inside the group. The serialized attempt claim also yields to its eligible queued requests. Paused, invalid, draft-waiting or not-yet-due requests do not reserve the account. Other accounts remain independent and active reviews are never preempted. This preference does not relax dependencies or change retained quota deadlines. It has no fairness or maximum-deferral guarantee: other projects on that account may wait indefinitely while the preferred repository continues to have eligible work. @@ -48,6 +44,8 @@ The existing queue and PR detail views show current round allowance, closure or ## CLI and MCP +The provider-free [lane diagnostic](review-lane-diagnostics.md) explains each configured PR against retained source and current local evidence/dependency facts, including exact parent blockers and unknown source suffixes. It does not authorize selection or claim fresh admission. + Read the current scheduling revision before changing settings. Keep the exact request and key after an uncertain mutation outcome; replaying the same key cannot enable or pause twice. ```sh diff --git a/docs/reviews.md b/docs/reviews.md index c2ee9766f..19d12b452 100644 --- a/docs/reviews.md +++ b/docs/reviews.md @@ -34,7 +34,7 @@ Model attempts as prepared, posting/running, active, completed, failed, cancelle Hosted review and local CLI execution are separate adapters with independent review cycles and quota observations. A cooldown, exhausted allowance, or active attempt in one channel does not by itself prevent admission in the other. They may review the same immutable target concurrently when each adapter satisfies its own admission checks and neither requires an exclusive shared resource. Candidate or effective-parent movement requires fresh admission facts in either channel; separate cycles do not relax original capture identity or publication safety, and movement does not erase retained PR/channel completion. -For an ordered stack, select the earliest unfinished eligible target independently within each channel. A channel may advance after its configured sufficiency or stopping policy is met without waiting for the other channel to catch up; an upstream movement then requires reassessing current source and pending obligations. A genuine shared provider-account quota or exclusive executor resource constrains only the actions it covers. Record provider responses and next availability rather than infer one channel's limits from the other. +For an ordered stack, select the earliest eligible target independently within each channel. An ancestor's unfinished review rounds, pending findings, fix work, routes or adoption obligations do not prevent reviewing a child's exact published diff. Each target retains its own pending-evidence, routed-finding, adoption, pause, grant, taper and stopping guards. The actual parent chain must still establish the same repository, published branches and exact head/base identities; source movement requires fresh admission. Reviewing a child does not complete its ancestors, transfer review credit, resolve findings or establish merge readiness. A genuine shared provider-account quota or exclusive executor resource constrains only the actions it covers. Record provider responses and next availability rather than infer one channel's limits from the other. A local executor receives an explicit project, allowed workspace, immutable target, operation ID, and policy. The server never adopts a client's current working directory as a global setting. The initial executor runs on the server machine; remote executors are deferred until authentication, leasing, and artifact-transfer contracts are proven. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 541075ad9..f4107da8a 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -360,7 +360,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou if err != nil { return reportClientError(stderr, err, ctx) } - if call.reviewOperationControl != nil || call.reviewScheduling != nil && call.reviewScheduling.action != "read" { + if call.reviewOperationControl != nil || call.reviewScheduling != nil && call.reviewScheduling.isMutation() { encoded, err := json.Marshal(value) if err == nil { encoded = append(encoded, '\n') diff --git a/internal/cli/review_lane_diagnostic_output_test.go b/internal/cli/review_lane_diagnostic_output_test.go new file mode 100644 index 000000000..02c66d9f4 --- /dev/null +++ b/internal/cli/review_lane_diagnostic_output_test.go @@ -0,0 +1,44 @@ +package cli_test + +import ( + "bytes" + "encoding/json" + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestReviewLaneDiagnosticOutputFailureIsReadOnly(t *testing.T) { + f := setupServiceFixture(t) + project := f.project(t, "lane-diagnostic-output") + worker := f.worker(t, project, "Builder") + handler := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/v1/instance": + _ = json.NewEncoder(w).Encode(map[string]string{"instance_id": f.store.InstanceID()}) + case "/api/v1/projects/" + project + "/reviews/lanes/cli/diagnostics": + if r.Method != http.MethodGet || r.Header.Get("Idempotency-Key") != "" { + t.Error("diagnostic was not a keyless GET") + } + _ = json.NewEncoder(w).Encode(client.ReviewLaneDiagnostic{ + ProjectID: project, Channel: "cli", ConfigurationRevision: 1, + EvaluatedAt: "2026-11-22T01:00:00Z", Scope: "retained_source_local_policy", + SourceReason: "source_unavailable", Candidates: []client.ReviewLaneCandidateDiagnostic{}, + }) + default: + t.Error("unexpected diagnostic route", r.URL.Path) + http.NotFound(w, r) + } + })) + defer handler.Close() + path := mutationProfiles(t, f, handler.URL, map[string][2]string{"builder": {project, worker}}) + var stderr bytes.Buffer + code := cli.RunContext(t.Context(), []string{"--profiles-file", path, "--profile", "builder", "reviews", "scheduling", "diagnostics", "--channel", "cli"}, nil, selectionFailWriter{}, &stderr) + if code != cli.ExitConfig || !strings.Contains(stderr.String(), "Check the output destination before retrying.") || strings.Contains(stderr.String(), "outcome_unknown") || strings.Contains(stderr.String(), "same key") { + t.Fatal(code, stderr.String()) + } +} diff --git a/internal/cli/review_lane_diagnostic_test.go b/internal/cli/review_lane_diagnostic_test.go new file mode 100644 index 000000000..50f3dcc09 --- /dev/null +++ b/internal/cli/review_lane_diagnostic_test.go @@ -0,0 +1,36 @@ +package cli + +import ( + "bytes" + "strings" + "testing" +) + +func TestLaneDiagnosticCLIReadSyntax(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + call, ok := parseInvocation([]string{"reviews", "scheduling", "diagnostics", "--channel", channel}) + if !ok || call.reviewScheduling == nil || call.reviewScheduling.action != "diagnostics" || call.reviewScheduling.channel != channel { + t.Fatal(call, ok) + } + } + for _, args := range [][]string{{}, {"--channel", "manual"}, {"--channel", "cli", "--key", "no"}, {"--channel", "cli", "--channel", "hosted"}, {"--channel", "cli", "--pr", "2"}} { + if _, ok := parseReviewScheduling(append([]string{"diagnostics"}, args...)); ok { + t.Fatal("invalid read accepted", args) + } + } + var out, diag bytes.Buffer + if code := RunContext(t.Context(), []string{"--profiles-file", "/missing", "reviews", "scheduling", "diagnostics", "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "not fresh admission") { + t.Fatal(code, out.String(), diag.String()) + } +} + +func TestReviewSchedulingReceiptOnlyForMutations(t *testing.T) { + for action, want := range map[string]bool{ + "read": false, "diagnostics": false, "unknown": false, + "configure": true, "pause": true, "resume": true, + } { + if got := (&reviewSchedulingInvocation{action: action}).isMutation(); got != want { + t.Errorf("%s: receipt recovery = %v, want %v", action, got, want) + } + } +} diff --git a/internal/cli/review_scheduling.go b/internal/cli/review_scheduling.go index e23026326..414580c1f 100644 --- a/internal/cli/review_scheduling.go +++ b/internal/cli/review_scheduling.go @@ -9,11 +9,12 @@ import ( ) type reviewSchedulingInvocation struct { - action string - pull int64 - key string - config client.ConfigureReviewSchedulingRequest - pause client.ConfigureReviewPullSchedulingRequest + action string + channel string + pull int64 + key string + config client.ConfigureReviewSchedulingRequest + pause client.ConfigureReviewPullSchedulingRequest } func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { @@ -24,6 +25,8 @@ func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { allowed := map[string]bool{"--pr": true} switch in.action { case "read": + case "diagnostics": + allowed = map[string]bool{"--channel": true} case "configure": allowed = map[string]bool{"--automatic-hosted": true, "--automatic-cli": true, "--expect-revision": true, "--key": true} case "pause", "resume": @@ -67,6 +70,10 @@ func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { } in.pull = n } + if in.action == "diagnostics" { + in.channel = values["--channel"] + return in, in.channel == "cli" || in.channel == "hosted" + } if in.action == "read" { return in, true } @@ -99,6 +106,8 @@ func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { func executeReviewScheduling(ctx context.Context, service *client.Client, in *reviewSchedulingInvocation) (any, error) { switch in.action { + case "diagnostics": + return service.ReviewLaneDiagnostic(ctx, in.channel) case "configure": return service.ConfigureReviewScheduling(ctx, in.key, in.config) case "pause", "resume": @@ -110,3 +119,12 @@ func executeReviewScheduling(ctx context.Context, service *client.Client, in *re return service.ReviewScheduling(ctx) } } + +func (in *reviewSchedulingInvocation) isMutation() bool { + switch in.action { + case "configure", "pause", "resume": + return true + default: + return false + } +} diff --git a/internal/cli/review_scheduling_help.go b/internal/cli/review_scheduling_help.go index 041ed837f..2a78074ff 100644 --- a/internal/cli/review_scheduling_help.go +++ b/internal/cli/review_scheduling_help.go @@ -7,9 +7,15 @@ func operationHelp(operation string) (operationHelpResponse, bool) { case "reviews scheduling": out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause --pr N --expect-revision N --key KEY [--reason TEXT] | resume --pr N --expect-revision N --key KEY" out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)", "configure --automatic-hosted true|false (project manager; authorizes future automatic Hosted requests)", "pause|resume --pr N (writer; holds new/undispatched reviews without changing rounds)", "--reason TEXT (optional with pause, at most 256 UTF-8 bytes)"} - out.Optional = append(out.Optional, "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") + out.Optional = append(out.Optional, "reviews scheduling diagnostics --help", "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") out.Semantics = []string{"Automation defaults off. Enabling requires this connection's active bound worker and current project-management authority; CLI automation is separately opt-in via --automatic-cli; omission preserves its current value. Existing grants and taper remain unchanged.", "Pause can precede any intent. Existing provider review collection continues, and separate operation pauses remain in effect. Read the current revision; mutations require an explicit key and preserve original-key recovery.", "No live provider request is needed to read or change a PR pause. Enabling project automation authorizes later Hosted or CLI selection under all existing comparison, obligation, round and provider guards."} out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling diagnostics": + out.Usage = " reviews scheduling diagnostics --channel cli|hosted" + out.Required = []string{"--channel cli|hosted"} + out.Semantics = []string{"Read retained source time/completeness and current local evidence/dependency state for every configured PR. locally_ready is not fresh admission, automatic eligibility or a dispatch promise. No source/provider refresh, review request or mutation."} + out.Example = " reviews scheduling diagnostics --channel cli" + out.Documentation = "docs/review-lane-diagnostics.md" case "reviews scheduling read": out.Usage = " reviews scheduling read [--pr N]" out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)"} diff --git a/internal/client/review_lane_diagnostic.go b/internal/client/review_lane_diagnostic.go new file mode 100644 index 000000000..a00932281 --- /dev/null +++ b/internal/client/review_lane_diagnostic.go @@ -0,0 +1,66 @@ +package client + +import ( + "context" + "net/http" +) + +type ReviewLaneDiagnostic struct { + ProjectID string `json:"project_id"` + Channel string `json:"channel"` + ConfigurationRevision int64 `json:"configuration_revision"` + EvaluatedAt string `json:"evaluated_at"` + Scope string `json:"scope"` + SourceConfigurationRevision int64 `json:"source_configuration_revision"` + SourceCheckedAt string `json:"source_checked_at,omitempty"` + SourceComplete bool `json:"source_complete"` + SourceReason string `json:"source_reason"` + LaneReason string `json:"lane_reason"` + Candidates []ReviewLaneCandidateDiagnostic `json:"candidates"` +} + +type ReviewLaneCandidateDiagnostic struct { + PullNumber int64 `json:"pull_number"` + HeadSHA string `json:"head_sha,omitempty"` + SourceObservedAt string `json:"source_observed_at,omitempty"` + ParentPullNumber int64 `json:"parent_pull_number"` + LocalState string `json:"local_state"` + LocalReason string `json:"local_reason"` + BlockingPullNumber int64 `json:"blocking_pull_number"` + BlockingReason string `json:"blocking_reason"` +} + +func (c *Client) ReviewLaneDiagnostic(ctx context.Context, channel string) (ReviewLaneDiagnostic, error) { + if !oneReviewOf(channel, "cli", "hosted") { + return ReviewLaneDiagnostic{}, validation() + } + var out ReviewLaneDiagnostic + if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "lanes", channel, "diagnostics"), nil, true, "", nil, http.StatusOK, false, &out, 128<<10, decodeReviewResponse); err != nil { + return ReviewLaneDiagnostic{}, err + } + if out.ProjectID != c.identity.ProjectID || out.Channel != channel || out.Scope != "retained_source_local_policy" || out.ConfigurationRevision < 1 || !controlTime(out.EvaluatedAt) || out.SourceConfigurationRevision < 0 || out.Candidates == nil || len(out.Candidates) > 100 || out.SourceReason != "" && !safeCode(out.SourceReason) || out.LaneReason != "" && !safeCode(out.LaneReason) { + return ReviewLaneDiagnostic{}, invalidResponse() + } + if out.SourceConfigurationRevision == 0 { + if out.SourceCheckedAt != "" || out.SourceComplete || out.SourceReason != "source_unavailable" { + return ReviewLaneDiagnostic{}, invalidResponse() + } + } else if !controlTime(out.SourceCheckedAt) || out.SourceComplete && (out.SourceConfigurationRevision != out.ConfigurationRevision || out.SourceReason != "") { + return ReviewLaneDiagnostic{}, invalidResponse() + } + usableSource := out.SourceConfigurationRevision > 0 && out.SourceConfigurationRevision == out.ConfigurationRevision && out.SourceReason != "repository_changed" && out.SourceReason != "configuration_changed" + seen := map[int64]bool{} + for _, p := range out.Candidates { + if !validPullNumber(p.PullNumber) || seen[p.PullNumber] || !oneReviewOf(p.LocalState, "unknown", "held", "complete", "locally_ready") || p.LocalReason != "" && !safeCode(p.LocalReason) || p.BlockingReason != "" && !safeCode(p.BlockingReason) || p.ParentPullNumber != 0 && (!validPullNumber(p.ParentPullNumber) || p.ParentPullNumber == p.PullNumber) || p.BlockingPullNumber != 0 && !validPullNumber(p.BlockingPullNumber) { + return ReviewLaneDiagnostic{}, invalidResponse() + } + seen[p.PullNumber] = true + if !usableSource && p.HeadSHA != "" || out.SourceComplete && p.HeadSHA == "" || p.LocalState == "unknown" && p.LocalReason == "" || p.LocalState == "complete" && p.LocalReason != "" { + return ReviewLaneDiagnostic{}, invalidResponse() + } + if (p.HeadSHA == "") != (p.SourceObservedAt == "") || p.HeadSHA != "" && (!controlHex(p.HeadSHA, 40) || !controlTime(p.SourceObservedAt)) || p.HeadSHA == "" && (p.LocalState != "unknown" || p.ParentPullNumber != 0) || p.LocalState == "held" && p.LocalReason == "" || p.LocalState == "locally_ready" && p.LocalReason != "" || (p.BlockingPullNumber == 0) != (p.BlockingReason == "") || p.BlockingPullNumber != 0 && (p.LocalState != "held" || p.LocalReason != "predecessor_unfinished") { + return ReviewLaneDiagnostic{}, invalidResponse() + } + } + return out, nil +} diff --git a/internal/client/review_lane_diagnostic_test.go b/internal/client/review_lane_diagnostic_test.go new file mode 100644 index 000000000..1eb10f4d5 --- /dev/null +++ b/internal/client/review_lane_diagnostic_test.go @@ -0,0 +1,71 @@ +package client_test + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/client" +) + +func sampleLaneDiagnostic() client.ReviewLaneDiagnostic { + return client.ReviewLaneDiagnostic{ProjectID: "project-one", Channel: "cli", ConfigurationRevision: 1, EvaluatedAt: "2026-11-10T21:00:00Z", Scope: "retained_source_local_policy", SourceConfigurationRevision: 1, SourceCheckedAt: "2026-11-10T20:59:00Z", SourceComplete: true, Candidates: []client.ReviewLaneCandidateDiagnostic{{PullNumber: 2, HeadSHA: strings.Repeat("a", 40), SourceObservedAt: "2026-11-10T20:58:00Z", LocalState: "held", LocalReason: "review_evidence_pending"}, {PullNumber: 4, HeadSHA: strings.Repeat("b", 40), SourceObservedAt: "2026-11-10T20:58:00Z", ParentPullNumber: 2, LocalState: "held", LocalReason: "predecessor_unfinished", BlockingPullNumber: 2, BlockingReason: "review_evidence_pending"}}} +} +func TestReviewLaneDiagnosticBoundReadAndStrictResponses(t *testing.T) { + cases := map[string]func(*client.ReviewLaneDiagnostic){ + "valid": func(*client.ReviewLaneDiagnostic) {}, + "project": func(v *client.ReviewLaneDiagnostic) { v.ProjectID = "foreign" }, + "channel": func(v *client.ReviewLaneDiagnostic) { v.Channel = "hosted" }, + "duplicate": func(v *client.ReviewLaneDiagnostic) { v.Candidates[1].PullNumber = 2 }, + "false-freshness": func(v *client.ReviewLaneDiagnostic) { v.SourceConfigurationRevision = 2 }, + "changed-source-ready": func(v *client.ReviewLaneDiagnostic) { + v.SourceConfigurationRevision = 2 + v.SourceComplete = false + v.SourceReason = "configuration_changed" + }, + "no-source-ready": func(v *client.ReviewLaneDiagnostic) { + v.Candidates[0].HeadSHA = "" + v.Candidates[0].SourceObservedAt = "" + v.Candidates[0].LocalState = "locally_ready" + v.Candidates[0].LocalReason = "" + }, + "missing-blocker": func(v *client.ReviewLaneDiagnostic) { v.Candidates[1].BlockingPullNumber = 0 }, + "bad-time": func(v *client.ReviewLaneDiagnostic) { v.SourceCheckedAt = "yesterday" }, + "null-candidates": func(v *client.ReviewLaneDiagnostic) { v.Candidates = nil }, + } + for name, edit := range cases { + t.Run(name, func(t *testing.T) { + value := sampleLaneDiagnostic() + edit(&value) + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/instance") { + handshake(w) + return + } + calls++ + if r.Method != "GET" || r.URL.Path != "/api/v1/projects/project-one/reviews/lanes/cli/diagnostics" || r.URL.RawQuery != "" || r.Header.Get("Idempotency-Key") != "" { + t.Error("diagnostic changed method or binding") + } + write(w, 200, value) + })) + defer srv.Close() + c := newClient(t, srv) + got, err := c.ReviewLaneDiagnostic(t.Context(), "cli") + if calls != 1 { + t.Fatal("unexpected fanout", calls) + } + if name == "valid" { + if err != nil || got.Candidates[1].BlockingPullNumber != 2 { + t.Fatal(got, err) + } + } else { + checkError(t, err, "invalid_response") + } + if _, err = c.ReviewLaneDiagnostic(t.Context(), "manual"); err == nil || calls != 1 { + t.Fatal("invalid channel contacted service") + } + }) + } +} diff --git a/internal/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(``) -var findingPre = regexp.MustCompile(`(?i)]|$)`) var findingQuotedHTML = regexp.MustCompile(`(?i)]*)?>`) 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, " 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)]*|)$`) + +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 = true + } + } + return commentAt >= 0 && standingHasReleaseMarkerComment(line[commentAt:]) +} + +// Continued comments are never structural markers. Retain just enough visible +// wording to reject a reserved marker split across physical comment lines. +func (p *standingHistoricalParser) scanMarkerComment(tail, fragment string) string { + const marker = "release notes by coderabbit.ai" + text := strings.ToLower(strings.Join(strings.Fields(tail+" "+fragment), " ")) + if strings.Contains(text, marker) { + p.invalid = true + } + if len(text) > len(marker) { + text = text[len(text)-len(marker):] + } + return text +} + +func (p *standingHistoricalParser) line(line string, stack []string, index int, inRecent bool) { + if line == "" { + return + } + ancestry := strings.Join(stack, "/") + const releaseStart = "" + 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

\n", 1) +} + +func TestHostedStandingZeroHistoricalCheckpointNarrative(t *testing.T) { + s, intent, poster, bot, earliest := standingTestFixture(t) + s.IssueComments[1].Body = standingTestHistoricalCheckpoint(s.IssueComments[1].Body) + before := append([]IssueComment(nil), s.IssueComments...) + got, err := ExtractHostedFindings(s, intent, poster, bot, earliest) + if err != nil || !got.Complete || got.Findings == nil || len(got.Findings) != 0 || got.Publication.StandingZero == nil || got.Publication.Reason != "standing_zero_inventory_attributed" { + t.Fatalf("historical release-note prose prevented explicit current zero inventory: complete=%v reason=%s err=%v", got.Complete, got.Reason, err) + } + z := got.Publication.StandingZero + if z.ProviderRunID != standingTestRun || z.HeadSHA != intent.HeadSHA || z.BaseSHA != strings.Repeat("b", 40) || z.Summary != s.IssueComments[1] || z.Acknowledgement != s.IssueComments[2] || !reflect.DeepEqual(before, s.IssueComments) { + t.Fatal("narrative classification changed identity or raw source") + } +} + +func TestHostedStandingZeroHistoricalCheckpointBoundaries(t *testing.T) { + const releaseStart = "" + const releaseEnd = "" + changes := map[string]func(string) string{ + "no walkthrough start": func(b string) string { return strings.Replace(b, "", "", 1) }, + "no walkthrough end": func(b string) string { return strings.Replace(b, "", "", 1) }, + "duplicate walkthrough start": func(b string) string { + return strings.Replace(b, "", "\n", 1) + }, + "duplicate walkthrough end": func(b string) string { + return strings.Replace(b, "", "\n", 1) + }, + "nested walkthrough": func(b string) string { + return strings.Replace(b, releaseStart, "\n"+releaseStart, 1) + }, + "wrong summary label": func(b string) string { + return strings.Replace(b, "Summary", "Current findings", 1) + }, + "nested summary": func(b string) string { + return strings.Replace(strings.Replace(b, "", "
\n", 1), "", "\n
", 1) + }, + "hidden summary": func(b string) string { + return strings.Replace(b, "\n
", "\n