From 027dbb86df733e322ca72a86839173c8f376a09c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 14:56:48 +1300 Subject: [PATCH 01/21] Carry retained review quota controls and Hosted repairs onto CI wait client --- cmd/fcd/main_test.go | 11 +- cmd/fcd/restore_activation_test.go | 2 +- cmd/fcd/schema_migration_test.go | 4 +- docs/retained-review-quota-controls.md | 82 ++ docs/reviews.md | 2 +- internal/backup/comparison_inventory_test.go | 45 +- internal/backup/history_scan_context_test.go | 8 +- internal/backup/inventory.go | 76 +- internal/backup/inventory_test.go | 49 +- internal/backup/operation_list_index_test.go | 12 +- .../backup/reservation_scope_inventory.go | 149 +++ .../reservation_scope_inventory_test.go | 144 +++ internal/backup/review_order_inventory.go | 50 + internal/backup/review_selection_test.go | 2 +- internal/reviewexec/allowance_observation.go | 271 +++++ .../reviewexec/allowance_observation_test.go | 748 ++++++++++++ internal/reviewexec/attempt_projection.go | 51 +- internal/reviewexec/attempts.go | 119 +- internal/reviewexec/attempts_test.go | 240 +++- internal/reviewexec/capability_test.go | 3 +- internal/reviewexec/cli_draft_cursor_test.go | 107 ++ internal/reviewexec/cli_draft_wait.go | 243 ++++ internal/reviewexec/cli_draft_wait_test.go | 798 +++++++++++++ internal/reviewexec/cli_preflight.go | 53 +- internal/reviewexec/cli_preflight_test.go | 3 +- internal/reviewexec/cli_wait.go | 187 +++ internal/reviewexec/cli_wait_estimate_test.go | 57 + internal/reviewexec/cli_wait_test.go | 1006 +++++++++++++++++ .../reviewexec/comparison_authority_test.go | 52 + .../reviewexec/comparison_migration_test.go | 35 + internal/reviewexec/comparison_schema.go | 53 +- .../reviewexec/configuration_compatibility.go | 70 ++ .../configuration_compatibility_test.go | 355 ++++++ .../cooldown_projection_fallback_test.go | 65 ++ .../current_parent_enrollment_test.go | 49 + .../execution_comparison_upgrade_test.go | 50 + internal/reviewexec/hosted_comparison_test.go | 10 +- ...sted_observation_historical_replay_test.go | 43 + internal/reviewexec/hosted_observations.go | 12 +- internal/reviewexec/hosted_preflight.go | 55 +- internal/reviewexec/hosted_priority.go | 125 ++ internal/reviewexec/hosted_priority_test.go | 297 +++++ internal/reviewexec/hosted_query.go | 11 +- internal/reviewexec/hosted_query_test.go | 3 +- internal/reviewexec/hosted_settlement.go | 3 + internal/reviewexec/hosted_wait.go | 426 +++++++ .../reviewexec/hosted_wait_isolation_test.go | 87 ++ internal/reviewexec/hosted_wait_test.go | 995 ++++++++++++++++ internal/reviewexec/hosted_wait_validation.go | 181 +++ internal/reviewexec/http.go | 44 + .../reviewexec/operation_list_index_test.go | 5 +- internal/reviewexec/operation_status.go | 38 +- internal/reviewexec/operation_status_test.go | 5 +- internal/reviewexec/operation_wait_test.go | 6 +- internal/reviewexec/policy_admission.go | 22 +- internal/reviewexec/policy_admission_test.go | 5 +- internal/reviewexec/preparation_recovery.go | 66 ++ .../reviewexec/quota_test_helpers_test.go | 19 + internal/reviewexec/requests.go | 50 +- internal/reviewexec/resolve.go | 16 + internal/reviewexec/restored_provider_work.go | 20 +- .../reviewexec/restored_provider_work_test.go | 2 +- internal/reviewexec/round_progress.go | 131 +++ internal/reviewexec/round_progress_http.go | 69 ++ .../reviewexec/round_progress_stages_test.go | 111 ++ internal/reviewexec/round_progress_test.go | 535 +++++++++ internal/reviewexec/schema.go | 95 +- internal/reviewexec/source_refresh.go | 16 +- internal/reviewexec/supervisor.go | 203 +++- internal/reviewexec/supervisor_cooldown.go | 132 +++ internal/reviewexec/supervisor_test.go | 235 +++- internal/reviewexec/types.go | 26 + internal/reviewexec/wait_deadline.go | 79 ++ .../reviewexec/wait_deadline_runtime_test.go | 235 ++++ internal/reviewexec/workspace_retention.go | 45 + .../reviewexec/workspace_retention_test.go | 93 ++ internal/reviewprocess/process.go | 6 +- internal/reviewprocess/process_test.go | 17 +- internal/reviewruntime/cli_driver.go | 18 + .../cli_preparation_reason_test.go | 50 +- .../reviewruntime/cli_quota_retry_test.go | 116 ++ .../reviewruntime/draft_admission_test.go | 182 +++ .../hosted_cooldown_retry_test.go | 453 ++++++++ internal/reviewruntime/hosted_driver.go | 19 + internal/reviewruntime/hosted_driver_test.go | 12 +- internal/reviewruntime/hosted_preflight.go | 116 +- internal/reviewruntime/retry_comparison.go | 12 + internal/reviews/channel_run_counts_test.go | 78 +- 88 files changed, 10705 insertions(+), 176 deletions(-) create mode 100644 docs/retained-review-quota-controls.md create mode 100644 internal/backup/reservation_scope_inventory.go create mode 100644 internal/backup/reservation_scope_inventory_test.go create mode 100644 internal/backup/review_order_inventory.go create mode 100644 internal/reviewexec/allowance_observation.go create mode 100644 internal/reviewexec/allowance_observation_test.go create mode 100644 internal/reviewexec/cli_draft_cursor_test.go create mode 100644 internal/reviewexec/cli_draft_wait.go create mode 100644 internal/reviewexec/cli_draft_wait_test.go create mode 100644 internal/reviewexec/cli_wait.go create mode 100644 internal/reviewexec/cli_wait_estimate_test.go create mode 100644 internal/reviewexec/cli_wait_test.go create mode 100644 internal/reviewexec/comparison_authority_test.go create mode 100644 internal/reviewexec/configuration_compatibility.go create mode 100644 internal/reviewexec/configuration_compatibility_test.go create mode 100644 internal/reviewexec/cooldown_projection_fallback_test.go create mode 100644 internal/reviewexec/current_parent_enrollment_test.go create mode 100644 internal/reviewexec/execution_comparison_upgrade_test.go create mode 100644 internal/reviewexec/hosted_observation_historical_replay_test.go create mode 100644 internal/reviewexec/hosted_priority.go create mode 100644 internal/reviewexec/hosted_priority_test.go create mode 100644 internal/reviewexec/hosted_wait.go create mode 100644 internal/reviewexec/hosted_wait_isolation_test.go create mode 100644 internal/reviewexec/hosted_wait_test.go create mode 100644 internal/reviewexec/hosted_wait_validation.go create mode 100644 internal/reviewexec/preparation_recovery.go create mode 100644 internal/reviewexec/quota_test_helpers_test.go create mode 100644 internal/reviewexec/round_progress.go create mode 100644 internal/reviewexec/round_progress_http.go create mode 100644 internal/reviewexec/round_progress_stages_test.go create mode 100644 internal/reviewexec/round_progress_test.go create mode 100644 internal/reviewexec/supervisor_cooldown.go create mode 100644 internal/reviewexec/wait_deadline.go create mode 100644 internal/reviewexec/wait_deadline_runtime_test.go create mode 100644 internal/reviewexec/workspace_retention.go create mode 100644 internal/reviewexec/workspace_retention_test.go create mode 100644 internal/reviewruntime/cli_quota_retry_test.go create mode 100644 internal/reviewruntime/draft_admission_test.go create mode 100644 internal/reviewruntime/hosted_cooldown_retry_test.go create mode 100644 internal/reviewruntime/retry_comparison.go diff --git a/cmd/fcd/main_test.go b/cmd/fcd/main_test.go index 847a521a0..84cd194f6 100644 --- a/cmd/fcd/main_test.go +++ b/cmd/fcd/main_test.go @@ -370,7 +370,9 @@ func TestHTTPShutdownDetachesLongReviewWaitsAndKeepsAcceptedWork(t *testing.T) { }() project := "failed" - postPath := "/api/v1/projects/failed/reviews/requests" + // Independent projects allow both waits to be admitted while preserving + // the one-unfinished-request guard for each project/PR/channel. + postPath := "/api/v1/projects/sibling/reviews/requests" getReceipt, err := engine.Enqueue(t.Context(), f.scope(t, project), "shutdown-get-seed", reviewexec.Request{ExpectedConfigurationRevision: 1, PullNumber: 1, Channel: "hosted", HeadSHA: strings.Repeat("a", 40)}) if err != nil { t.Fatal(err) @@ -379,7 +381,7 @@ func TestHTTPShutdownDetachesLongReviewWaitsAndKeepsAcceptedWork(t *testing.T) { if json.Unmarshal(getReceipt, &getOperation) != nil { t.Fatal("GET wait fixture receipt is invalid") } - getPath := postPath[:len(postPath)-len("requests")] + "operations/" + getOperation.ID + getPath := "/api/v1/projects/" + project + "/reviews/operations/" + getOperation.ID body, err := json.Marshal(reviewexec.Request{ExpectedConfigurationRevision: 1, PullNumber: 1, Channel: "hosted", HeadSHA: strings.Repeat("b", 40)}) if err != nil { t.Fatal(err) @@ -471,10 +473,13 @@ func TestHTTPShutdownDetachesLongReviewWaitsAndKeepsAcceptedWork(t *testing.T) { if err = <-serveDone; !errors.Is(err, http.ErrServerClosed) { t.Fatal("server did not finish graceful shutdown", err) } - var queued, receipts int + var queued, receipts, queuedProjects int if err = f.store.DB().QueryRow(`SELECT count(*) FROM review_operations WHERE state='queued'`).Scan(&queued); err != nil || queued != 2 { t.Fatal("shutdown changed accepted operations", queued, err) } + if err = f.store.DB().QueryRow(`SELECT count(DISTINCT project_id) FROM review_operations WHERE state='queued' AND project_id IN ('failed','sibling')`).Scan(&queuedProjects); err != nil || queuedProjects != 2 { + t.Fatal("shutdown changed the independent accepted project scopes", queuedProjects, err) + } if err = f.store.DB().QueryRow(`SELECT count(*) FROM receipts WHERE operation='reviews.request'`).Scan(&receipts); err != nil || receipts != 2 { t.Fatal("shutdown changed accepted receipts", receipts, err) } diff --git a/cmd/fcd/restore_activation_test.go b/cmd/fcd/restore_activation_test.go index de4456c3a..d2ff2f59f 100644 --- a/cmd/fcd/restore_activation_test.go +++ b/cmd/fcd/restore_activation_test.go @@ -181,11 +181,11 @@ func newActivationCommandFixture(t *testing.T) activationCommandFixture { if _, err = e.EnqueueSourceRefresh(t.Context(), scope, "activation-source", reviewexec.SourceRefreshRequest{ExpectedConfigurationRevision: 1, PullNumber: 5, HeadSHA: strings.Repeat("a", 40)}); err != nil { t.Fatal(err) } - _ = enqueue(1, "cli") preparing := enqueue(2, "cli") if _, err = e.StartAttempt(t.Context(), project, preparing.ID); err != nil { t.Fatal(err) } + _ = enqueue(1, "cli") // A second retained account permits a separate uncertain action while the // original account still owns its preparing reservation. if _, err = e.Configure(t.Context(), scope, "activation-config-next", reviewexec.Configuration{ExpectedRevision: &one, CapabilityID: "activation-cap-next", Mode: "independent", Queue: []int64{1, 2, 3, 4, 5}, Channels: []string{"cli", "hosted"}}); err != nil { diff --git a/cmd/fcd/schema_migration_test.go b/cmd/fcd/schema_migration_test.go index e5b5daf01..948bac6f3 100644 --- a/cmd/fcd/schema_migration_test.go +++ b/cmd/fcd/schema_migration_test.go @@ -65,7 +65,7 @@ func TestDaemonSchemaMigrationFailurePrecedesListen(t *testing.T) { } // The additive comparison schema is reached after earlier domain schemas. // Refuse a newer retained version rather than modify or discard it. - if _, err := store.DB().Exec(`INSERT INTO metadata(key,value) VALUES('schema:review_comparison','2')`); err != nil { + if _, err := store.DB().Exec(`INSERT INTO metadata(key,value) VALUES('schema:review_comparison','3')`); err != nil { t.Fatal(err) } if err := store.Close(); err != nil { @@ -92,7 +92,7 @@ func TestDaemonSchemaMigrationFailurePrecedesListen(t *testing.T) { } defer store.Close() var version string - if err := store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_comparison'`).Scan(&version); err != nil || version != "2" { + if err := store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_comparison'`).Scan(&version); err != nil || version != "3" { t.Fatal("startup changed refused schema authority", version, err) } var count int diff --git a/docs/retained-review-quota-controls.md b/docs/retained-review-quota-controls.md new file mode 100644 index 000000000..71c1e5e9a --- /dev/null +++ b/docs/retained-review-quota-controls.md @@ -0,0 +1,82 @@ +# Retained review quota waits + +This slice follows native CI observation and keeps an authorized review request +alive when its provider has no available allowance. It does not discover new +reviews, increase grants, adjudicate findings, or merge pull requests. This slice delivers the server HTTP contract; bound client, CLI and MCP controls and wait diagnostics follow in a separate dependent slice. + +## One request, multiple unused preparations + +An observed Hosted cooldown with a future deadline that advances any previous retry floor, or proven zero CLI allowance, releases the unused preparation reservation and retains the original operation with a retry floor. +The supervisor rechecks authority, configuration, grants and source before +preparing again. The first comparison remains immutable. A changed head, parent, +base, merge base or patch cannot silently become the retry target. +Runtime reads verify that the stored retry deadline matches the latest retained, proven cooldown. The first comparison and allowance estimate remain bound to the original baseline. A syntactically valid but contradictory timer is damaged waiting history, not permission to prepare early. CLI account guards also derive live retry floors from retained exhaustion transitions, so shortening the cached timer cannot hide an active account backoff. + +During normal preparation, an elapsed or non-advancing Hosted cooldown instead leaves the operation `held` with reason `hosted_allowance_cooldown`. A missing or malformed retained Hosted allowance record also holds only that operation, without inventing a retry timer or stopping unrelated work. Actual storage failures retain their normal fatal behavior. It does not retry automatically, and the queued-only pause, resume and cancel controls cannot resume it. Inspect the retained operation and allowance facts, resolve the hold's cause, then submit a fresh authorized [review request](review-execution.md#bound-execution-tools) with a new explicit key and the qualified current comparison. The held history remains unchanged; the new request still passes authority, configuration, grant, source, finding, provider and known-cooldown guards. Recover an unknown original request outcome with its original key before considering a new request. + +Startup recovery of a still-preparing Hosted attempt revalidates the retained cooldown and restores a queued wait only when its deadline remains future and advances the prior retry floor. An elapsed or non-advancing deadline instead cancels that unused preparation with reason `supervisor_interrupted` and releases its reservation, preserving the original allowance facts and attempt history. A still-preparing CLI attempt with a valid retained zero-allowance record instead re-arms its account backoff from the recovery transition time; it does not apply the Hosted future-deadline or advancing-floor checks. An operation already held before restart remains held; startup recovery does not reopen it or issue another review. + +CLI backoff belongs to the shared provider account, including after cancellation +of one request. Hosted reservations are scoped to a repository on the account. +Within a project, an eligible earlier queued intent retains priority while its +timer waits. Neither a timer nor a fresh allowance query counts as a completed +review round. + +Damaged live CLI wait history suppresses candidates only on its provider account. Other accounts and Hosted work remain schedulable. Damaged retained Hosted waits suppress the affected candidate and later queued intents in its project/channel that depend on that unproven predecessor; other projects and channels remain schedulable. Typed retained wait failures in either channel emit a bounded candidate diagnostic using the same 30-second, 256-entry diagnostic budget; actual database and context errors still propagate. The retained request and evidence are not changed, and expiry removes only the account timer, not audit validation. + +Malformed or missing intermediate configuration history keeps the affected request queued without acquiring capacity or preparing a provider action. It also prevents later requests from bypassing that unproven predecessor, but does not stop other projects. A bounded diagnostic identifies the affected candidate and project without exposing stored content, at most once per candidate per 30 seconds within a 256-entry diagnostic bound. General database and context failures retain their normal error behavior. + +Pause, resume and cancel apply only to an undispatched queued operation and use +an expected revision plus an idempotency key. They cannot cancel an issued +provider review or reopen terminal history. Explicit CLI requests made while a +PR is draft remain queued until a bounded fresh source check observes readiness. A failed repository or pull probe leaves the request queued and emits a diagnostic with the operation ID, failed read and safe provider error code, at most once per operation per 30-second probe interval; provider bodies and credentials are excluded. An unknown Draft field uses the same bounded diagnostic with reason `draft_state_unknown`, without treating the PR as ready. + +Only one of the two supervisor workers probes retained Draft waits. Its scheduling pass selects at most one eligible probe and advances its rotation cursor at selection, so a local validation failure before probe claim cannot starve later waits; the other worker excludes Draft waits before applying the candidate limit, so slow probes do not hide ready work in other projects. Both workers retain the same authority, queue-priority, account and reservation guards. + +## Reading state + +Operation and round-progress reads expose waiting state only when requested with `X-FC-Operation-Wait`; round-progress reads also require the `view=stages` query parameter. Version 1 preserves the original Hosted shape; version 2 +also understands CLI baselines. Version 3 adds retained provider allowance +estimates. A full-capacity estimate is not the next retry time or a guarantee +that a review can start. Older clients continue receiving their existing shapes. Version 3 exposes `wait.cli_allowance` for a queued CLI baseline, held-operation `allowance` facts, and the compact held Hosted `retry_not_before` deadline. The existing bound clients retain their earlier response contract; version 3 client support follows in the dependent slice. Legacy responses without these optional facts remain readable; absence does not imply zero allowance or a provider reset. + +The public control endpoint is +`POST /api/v1/projects/{project_id}/reviews/operations/{operation_id}/control`. +The body contains `expected_revision` and `action` (`pause`, `resume`, `cancel`). +Any credential with write permission in this project may control an undispatched queued request, including another worker's request, while retaining its own authenticated identity. The idempotency header is required. + +- `review_conflict` refuses a stale `expected_revision` or an operation whose revision has reached the maximum `int64` value. Read the current operation before deciding whether a new action is appropriate; rereading cannot resolve revision exhaustion. +- `review_operation_started` refuses preparing, posting, active, uncertain or terminal operations; the control cannot stop issued provider work. +- `idempotency_key_required` refuses a missing or invalid `Idempotency-Key`; supply a valid explicit key before submitting the intended request. +- `idempotency_conflict` refuses reuse of the same key for a different action or request. +- `forbidden` refuses a credential without write permission in this project; use an authorized project-write credential before retrying the intended action. +- `not_found` refuses an operation that is not visible in this project; verify the selected project and operation ID. Do not retry with another key or guess another project's identity. +- `validation_failed` refuses a malformed operation ID or request body, an `expected_revision` below 1, or an action other than `pause`, `resume` or `cancel`; correct the invalid fields before submitting the intended control. +- `storage_unavailable` refuses a control when retained wait data is damaged or unavailable; retain the original request and idempotency key and inspect the retained state before attempting recovery. Do not submit a new key to bypass the failure. + +Request submission can separately fail with `review_inflight`. It refuses a new-key request while another operation for the same project, PR and channel is queued, preparing, posting, active or uncertain. Its `operation_id` detail names the existing request. Read and retain that operation; the queued-only HTTP control may cancel it when cancellation is intended, while issued work must finish or follow its original recovery path. Do not submit another key to bypass the pending request. + +After an unknown outcome, recover with the same authenticated principal, project, worker, exact request body, operation ID and idempotency key. Do not invent a new key or assume that the action failed. + +Held-operation `allowance` facts and the compact held Hosted `retry_not_before` field require `X-FC-Operation-Wait: 3`, including terminal replies to request submission. Missing, older or unsupported versions omit these fields; engine-level retained facts and exact-key recovery remain unchanged. + +Reads distinguish missing or malformed required waiting dependencies from operational lookup failures. Required dependency damage remains `storage_unavailable`; cancellation, deadlines and transient storage errors retain their original classification. An absent optional held allowance observation remains absent rather than becoming a broken wait. + +## Recovery and scope + +Restart recovery only requeues preparations with retained proof that no review +was issued. Ambiguous dispatch remains uncertain. Historical allowance captures, +attempts and evidence stay readable after a preparation detaches. Backup +validation checks the schema, timer ownership and retained allowance facts. + +Schema versions 7 and 8 reserve the integrated request-flag columns so later +slices use the same migration history; this slice does not expose new override +options. Its HTTP operation responses omit both reserved flags for every supported wait version while retaining their stored values. Automatic review selection, wider notification changes and automatic +workspace pruning are separate work. The workspace eligibility helper alone +does not delete checkouts. + +### Retention failure recovery + +A Hosted cooldown retention storage failure leaves the original attempt preparing after bounded local retries. Before interrupted-attempt recovery, the configured Hosted adapter reconciles the retained allowance-query capture against the same operation, query, attempt and pinned workspace, with no provider call. Successful replay writes the same idempotent cooldown facts and normal recovery restores a future queued wait. An ongoing storage failure blocks startup without changing the attempt. Missing, malformed or non-cooldown private source, or a changed workspace, grants no cooldown and follows normal interrupted preparation cancellation. This replay never obtains fresh allowance or dispatches a review. + +CLI account retry queries use indexed live deadline and exhaustion-time ranges; their capped prior-transition count uses the owning attempt index. Expired retained history remains auditable without being scanned as current quota proof. Actual database and context failures still propagate and stop the supervisor rather than admitting an account whose live guard was not established. diff --git a/docs/reviews.md b/docs/reviews.md index 18c9d3d7b..e44de8989 100644 --- a/docs/reviews.md +++ b/docs/reviews.md @@ -76,4 +76,4 @@ Completed native PR/channel progress remains earned when the candidate, base, pu An unresolved completed native operation on any retained head remains pending, including missing captures, incomplete results, unfinalized decisions, accepted findings without fix proof and unresolved receiving routes. Pending dominates usable completion even when another native capture is ready. Current policy and execution pauses retain their existing authority; this boundary does not add round budgets, adoption, retained applicability or automatic scheduling. -The `review_comparison` ledger derives compact pending/ready proof facts from original operation, attempt, capture, adjudication and route authority. Mutations invalidate affected facts and rederive them in the same transaction. Ordinary channel reads use scoped indexes and fail closed on dirty authority, without a lifetime 100-operation ceiling. Installation-time backfill and [backup validation](backups.md) independently rederive the canonical facts rather than trusting cached state. Backfill runs only when the comparison schema is installed, inside one exclusive startup transaction under the [operator-configurable per-domain migration budget](hosting.md#startup-schema-migrations). Invalid retained authority or a deadline failure rolls back the domain installation and prevents the daemon from serving any requests; it does not discard records or grant partial completion. A valid large retained completed history can exceed the default budget; the timeout alone is not a corruption signal. Preserve the installation and diagnostics for investigation. After diagnosis, an explicit longer-budget retry can complete valid retained history while preserving full validation and atomic rollback. Every retry starts the failed domain from the beginning, so restarting with the same insufficient budget or restoring identical over-budget data can repeat the failure; there is no resumable backfill. After installation, a dirty proof makes reads for its PR/channel fail closed with `storage_unavailable` (HTTP 500). Supported completion, adjudication and route mutations rederive their affected proofs transactionally; this slice has no generic dirty-proof repair or repository-rebinding command. For persistent malformed-authority failures, inspect a known-good bundle and follow the [inactive restore and activation procedure](backups.md). A bundle containing the same malformed authority is not a recovery source. Do not clear dirty markers, rewrite captures or bypass validation to restart; provider reconciliation remains required before resuming restored work. Receiving-route counts have their separate [indexed obligation owner](review-routes.md). +The `review_comparison` ledger derives compact pending/ready proof facts from original operation, attempt, capture, adjudication and route authority. Mutations invalidate affected facts and rederive them in the same transaction. Ordinary channel reads use scoped indexes and fail closed on dirty authority, without a lifetime 100-operation ceiling. Installation-time backfill and [backup validation](backups.md) independently rederive the canonical facts rather than trusting cached state. Backfill runs when the comparison schema is installed or its versioned repair is applied, inside one exclusive startup transaction under the [operator-configurable per-domain migration budget](hosting.md#startup-schema-migrations). Invalid retained authority or a deadline failure rolls back the domain installation and prevents the daemon from serving any requests; it does not discard records or grant partial completion. A valid large retained completed history can exceed the default budget; the timeout alone is not a corruption signal. Preserve the installation and diagnostics for investigation. After diagnosis, an explicit longer-budget retry can complete valid retained history while preserving full validation and atomic rollback. Every retry starts the failed domain from the beginning, so restarting with the same insufficient budget or restoring identical over-budget data can repeat the failure; there is no resumable backfill. Comparison schema version two restores the three attempt-table invalidation triggers lost when execution migration nine rebuilt that table, including stores already at execution version ten. The same guarded backfill rederives retained proofs before serving requests. After installation, a dirty proof makes reads for its PR/channel fail closed with `storage_unavailable` (HTTP 500). Supported completion, adjudication and route mutations rederive their affected proofs transactionally; this slice has no generic dirty-proof repair or repository-rebinding command. For persistent malformed-authority failures, inspect a known-good bundle and follow the [inactive restore and activation procedure](backups.md). A bundle containing the same malformed authority is not a recovery source. Do not clear dirty markers, rewrite captures or bypass validation to restart; provider reconciliation remains required before resuming restored work. Receiving-route counts have their separate [indexed obligation owner](review-routes.md). diff --git a/internal/backup/comparison_inventory_test.go b/internal/backup/comparison_inventory_test.go index eed528e0f..6d9eead06 100644 --- a/internal/backup/comparison_inventory_test.go +++ b/internal/backup/comparison_inventory_test.go @@ -144,7 +144,7 @@ func TestComparisonInventoryCanonicalSchemaAndInvalidationTriggersRequired(t *te {"wrong-trigger", `DROP TRIGGER review_comparison_repository_changed; CREATE TRIGGER review_comparison_repository_changed AFTER UPDATE ON projects BEGIN SELECT 1; END`}, {"unknown-trigger", `CREATE TRIGGER unexpected_comparison BEFORE INSERT ON review_comparison_proofs BEGIN SELECT 1; END`}, {"extra-column", `ALTER TABLE review_comparison_proofs ADD COLUMN fabricated_credit INTEGER`}, - {"wrong-domain-version", `UPDATE metadata SET value='2' WHERE key='schema:review_comparison'`}, + {"wrong-domain-version", `UPDATE metadata SET value='3' WHERE key='schema:review_comparison'`}, } var table, retain, stateIndex, anchorIndex string for _, statement := range reviewexec.ComparisonSchemaSQL() { @@ -336,16 +336,17 @@ func TestComparisonInventoryAbsentOptionalDomainRemainsSupported(t *testing.T) { func TestNativeInventoryVersionOneSchemaDefinitionsPinned(t *testing.T) { for _, tc := range []struct { domain string + version int statements []string counts map[string]int digest string }{ - {"review_comparison", reviewexec.ComparisonSchemaSQL(), map[string]int{"TABLE": 1, "INDEX": 2, "TRIGGER": 20}, "584a984a5981c377eda89cafdfb48f4893eb969cd5e006af52651f29f422d69f"}, - {"review_route_policy", reviewexec.RoutePolicySchemaSQL(), map[string]int{"TABLE": 2, "INDEX": 2, "TRIGGER": 7}, "529de94322105c8d76dde3159a47700a21baaa00eb4daae14bc59d7d3ea75889"}, + {"review_comparison", 2, reviewexec.ComparisonSchemaSQL(), map[string]int{"TABLE": 1, "INDEX": 2, "TRIGGER": 20}, "584a984a5981c377eda89cafdfb48f4893eb969cd5e006af52651f29f422d69f"}, + {"review_route_policy", 1, reviewexec.RoutePolicySchemaSQL(), map[string]int{"TABLE": 2, "INDEX": 2, "TRIGGER": 7}, "529de94322105c8d76dde3159a47700a21baaa00eb4daae14bc59d7d3ea75889"}, } { t.Run(tc.domain, func(t *testing.T) { - if got := supportedDomains[tc.domain]; got != 1 { - t.Fatalf("supported version = %d; retain v1 fixtures and add explicit versioned inventory coverage", got) + if got := supportedDomains[tc.domain]; got != tc.version { + t.Fatalf("supported version = %d, want %d; retain the pinned v1 physical definitions", got, tc.version) } counts := map[string]int{} seen := map[string]bool{} @@ -377,3 +378,37 @@ func TestNativeInventoryVersionOneSchemaDefinitionsPinned(t *testing.T) { }) } } + +// Version two repairs missing attempt invalidation triggers without changing +// physical definitions. Both retained versions keep the same pinned inventory. +func TestComparisonInventoryRepairPreservesVersionOneBundles(t *testing.T) { + for _, version := range []string{"1", "2"} { + t.Run(version, func(t *testing.T) { + f := newRestoreFixture(t) + if _, err := f.store.DB().Exec(`UPDATE metadata SET value=? WHERE key='schema:review_comparison'`, version); err != nil { + t.Fatal(err) + } + before := backupRows(t, f.store.DB()) + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + destination := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var retained string + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_comparison'`).Scan(&retained); err != nil || retained != version { + t.Fatal("restore migrated comparison marker", retained, err) + } + if !reflect.DeepEqual(before, backupRows(t, f.store.DB())) { + t.Fatal("inspection mutated source") + } + }) + } +} diff --git a/internal/backup/history_scan_context_test.go b/internal/backup/history_scan_context_test.go index 770bff769..0be987c9a 100644 --- a/internal/backup/history_scan_context_test.go +++ b/internal/backup/history_scan_context_test.go @@ -32,16 +32,17 @@ func (c *historyScanCancellation) Done() <-chan struct{} { var pcs [40]uintptr n := runtime.Callers(2, pcs[:]) frames := runtime.CallersFrames(pcs[:n]) - selected, sqlCall := false, false + selected, sqlCall, nestedPhysical := false, false, false for { frame, more := frames.Next() selected = selected || frame.Function == c.phase + nestedPhysical = nestedPhysical || strings.HasSuffix(frame.Function, "backup.validateHistoryPhysicalSchema") || strings.HasSuffix(frame.Function, "backup.validateDomainPhysicalSchema") sqlCall = sqlCall || strings.HasPrefix(frame.Function, "database/sql.") if !more { break } } - if selected && sqlCall { + if selected && sqlCall && !(strings.HasSuffix(c.phase, "validatePhysicalSchemaObjects") && nestedPhysical) { c.fired.Store(true) c.cancel() } @@ -57,6 +58,9 @@ func TestHistoryScanCancellationIsUnavailableAndReadOnly(t *testing.T) { bundle := restoreBundle(t, f) before := restoreTree(t, bundle.Path) for _, phase := range []string{ + "backup.validateReservationScopeSchema", + "backup.validateReviewOrderPhysicalSchema", + "backup.validatePhysicalSchemaObjects", "reviews.ValidateHistoryReferences", "reviews.ValidateCurrentSummaries", "reviews.ValidateCurrentRunOrder", diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index 3c7975bf1..0c0173d44 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -221,8 +221,9 @@ type tableVersion struct { // Fixed application schema bounds are intentionally independent of migration // execution. Inspection never opens a Store or installs/rewrites a schema. -var supportedDomains = map[string]int{"review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 1, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 6, "review_execution_indexes": 2, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 3, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} var tables = map[string]tableVersion{ + "review_operation_waits": {"review_execution", 9, "operation_id baseline_attempt_id retry_not_before paused"}, "review_selections": {"review_selection", 1, "id project_id actor_id worker_id channel configuration_revision policy_revision capability_fingerprint expected_pull_number state reason revision operation_id created_at updated_at"}, "review_hosted_discovery_state": {"reviews", 11, "project_id repository_id pull_number cutoff_at initialized_at"}, "review_pull_versions": {"reviews", 4, "project_id number version_revision title state head_sha base_ref base_sha ci_state mergeability complete run_count attempt_count recent_runs_json latest_attempts_json"}, @@ -594,6 +595,26 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, err } } + if versions["review_execution"] >= 9 { + // Schema nine owns durable wait identity and paired retry state even + // when the bundle has no wait rows to exercise these constraints. + const definition = `CREATE TABLE review_operation_waits(operation_id TEXT PRIMARY KEY REFERENCES review_operations(id),baseline_attempt_id TEXT REFERENCES review_execution_attempts(id),retry_not_before TEXT NOT NULL DEFAULT '',paused INTEGER NOT NULL DEFAULT 0 CHECK(paused IN(0,1)),CHECK((baseline_attempt_id IS NULL AND retry_not_before='') OR (baseline_attempt_id IS NOT NULL AND retry_not_before<>'')))` + objects := map[string]physicalSchemaObject{"review_operation_waits": {"table", historyDefinitionSQL(definition)}} + names := []string{"review_operation_waits"} + if versions["review_execution_indexes"] >= 3 { + objects["review_waits_live_retry"] = physicalSchemaObject{"index", historyDefinitionSQL(`CREATE INDEX review_waits_live_retry ON review_operation_waits(rtrim(retry_not_before,'Z') DESC,operation_id,baseline_attempt_id) WHERE retry_not_before<>''`)} + objects["review_execution_transitions"] = physicalSchemaObject{"table", historyDefinitionSQL(`CREATE TABLE review_execution_transitions(attempt_id TEXT NOT NULL REFERENCES review_execution_attempts(id),revision INTEGER NOT NULL,state TEXT NOT NULL,reason TEXT NOT NULL,external_id TEXT NOT NULL,created_at TEXT NOT NULL,PRIMARY KEY(attempt_id,revision))`)} + objects["review_transitions_exhaustion_time"] = physicalSchemaObject{"index", historyDefinitionSQL(`CREATE INDEX review_transitions_exhaustion_time ON review_execution_transitions(rtrim(created_at,'Z') DESC,attempt_id,revision) WHERE state='held' AND reason='allowance_exhausted'`)} + objects["review_transitions_exhaustion_attempt"] = physicalSchemaObject{"index", historyDefinitionSQL(`CREATE INDEX review_transitions_exhaustion_attempt ON review_execution_transitions(attempt_id,rtrim(created_at,'Z')) WHERE state='held' AND reason='allowance_exhausted'`)} + names = append(names, "review_execution_transitions") + } + if err = validatePhysicalSchemaObjects(ctx, db, objects, names); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } + } for name := range actual { if _, ok := tables[name]; !ok { return nil, invalid() @@ -647,6 +668,12 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ if versions[spec.domain] >= 3 { columns += " policy_revision" } + if versions[spec.domain] >= 7 { + columns += " allow_out_of_order" + } + if versions[spec.domain] >= 8 { + columns += " override_file_limit" + } } if name == "review_runs" && versions[spec.domain] >= 2 { columns += " snapshot_revision" @@ -707,6 +734,10 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ columnRows.Close() return nil, invalid() } + if name == "review_operations" && (col == "allow_out_of_order" || col == "override_file_limit") && !reviewOrderColumn(kind, notnull, pk, defaultValue) { + columnRows.Close() + return nil, invalid() + } present[col] = true } e = columnRows.Err() @@ -736,6 +767,24 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, err } } + if name == "review_execution_attempts" && versions[spec.domain] >= 9 { + if err = validateAttemptIndexSchema(ctx, db); err != nil { + return nil, err + } + } + if name == "review_execution_reservations" && versions[spec.domain] >= 10 { + if err = validateReservationScopeSchema(ctx, db); err != nil { + return nil, err + } + } + if name == "review_operations" && versions[spec.domain] >= 7 { + if err = validateReviewOrderPhysicalSchema(ctx, db, versions[spec.domain]); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } + } } if version == 2 { var empty int @@ -898,6 +947,30 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al return invalid() } } + if versions["review_execution"] >= 4 { + if err := reviewexec.ValidateAllowanceSnapshot(ctx, tx, versions["review_execution"]); err != nil { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } + if versions["review_execution"] >= 9 { + if err := reviewexec.ValidateOperationWaitsSnapshot(ctx, tx); err != nil { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } + if versions["review_execution"] >= 7 { + if err := validateReviewOrderRows(ctx, tx, versions["review_execution"]); err != nil { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } refs := map[string]Artifact{} for _, a := range m.Artifacts { refs[a.Path] = a @@ -1126,6 +1199,7 @@ func canonicalFK(table, from, to, onDelete string) foreignKey { } var canonicalForeignKeys = map[string][]foreignKey{ + "review_operation_waits": {canonicalFK("review_operations", "operation_id", "id", "NO ACTION"), canonicalFK("review_execution_attempts", "baseline_attempt_id", "id", "NO ACTION")}, "review_selections": {canonicalFK("projects", "project_id", "id", "NO ACTION"), canonicalFK("review_operations", "operation_id", "id", "NO ACTION"), canonicalFK("review_execution_config", "project_id,configuration_revision", "project_id,revision", "NO ACTION"), canonicalFK("review_policy_config", "project_id,policy_revision", "project_id,revision", "NO ACTION")}, "review_hosted_discovery_state": {canonicalFK("projects", "project_id", "id", "CASCADE")}, "review_pull_versions": {canonicalFK("review_snapshots", "project_id,version_revision", "project_id,revision", "NO ACTION")}, diff --git a/internal/backup/inventory_test.go b/internal/backup/inventory_test.go index ad6f64b98..abf757be4 100644 --- a/internal/backup/inventory_test.go +++ b/internal/backup/inventory_test.go @@ -439,6 +439,7 @@ func TestInventoryCanonicalForeignKeysRemainSupportedAcrossOlderSchemas(t *testi {"jobs", 1}, {"jobs", 2}, {"jobs", 3}, {"jobs", 4}, {"jobs", 5}, {"reviews", 1}, {"reviews", 2}, {"review_execution", 1}, {"review_execution", 2}, {"review_execution", 3}, {"review_execution", 4}, {"review_execution", 5}, + {"review_execution", 6}, {"review_execution", 7}, {"review_execution", 8}, {"review_execution", 9}, {"review_evidence", 1}, {"review_evidence", 2}, {"review_adjudication", 1}, {"review_source_refresh", 1}, {"review_source_refresh", 2}, } @@ -480,7 +481,53 @@ func TestInventoryCanonicalForeignKeysRemainSupportedAcrossOlderSchemas(t *testi // The independent original physical schema is already installed. case "review_execution": - statements = []string{`DROP TABLE review_hosted_allowance_queries`, `DROP TABLE review_hosted_preflight`} + + conn, err := store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + legacy := []string{`PRAGMA foreign_keys=OFF`} + if test.version < 9 { + legacy = append(legacy, + `DROP TABLE review_operation_waits`, + `CREATE TABLE review_execution_attempts_next(id TEXT PRIMARY KEY,operation_id TEXT NOT NULL UNIQUE REFERENCES review_operations(id),project_id TEXT NOT NULL REFERENCES projects(id),provider TEXT NOT NULL,account TEXT NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL,anchor_json TEXT NOT NULL,intent TEXT NOT NULL,external_id TEXT NOT NULL)`, + `INSERT INTO review_execution_attempts_next SELECT id,operation_id,project_id,provider,account,state,revision,anchor_json,intent,external_id FROM review_execution_attempts`, + `DROP TABLE review_execution_attempts`, + `ALTER TABLE review_execution_attempts_next RENAME TO review_execution_attempts`, + ) + } + legacy = append(legacy, + `CREATE TABLE review_execution_reservations_next(provider TEXT NOT NULL,repository_id INTEGER NOT NULL,pull_number INTEGER NOT NULL,action_class TEXT NOT NULL,account TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),PRIMARY KEY(provider,repository_id,pull_number,action_class),UNIQUE(provider,account,action_class))`, + `INSERT INTO review_execution_reservations_next SELECT provider,repository_id,pull_number,action_class,account,attempt_id FROM review_execution_reservations`, + `DROP TABLE review_execution_reservations`, + `ALTER TABLE review_execution_reservations_next RENAME TO review_execution_reservations`, + ) + if test.version < 7 { + legacy = append(legacy, `ALTER TABLE review_operations DROP COLUMN allow_out_of_order`) + } + if test.version < 8 { + legacy = append(legacy, `ALTER TABLE review_operations DROP COLUMN override_file_limit`) + } + legacy = append(legacy, `PRAGMA foreign_keys=ON`) + for _, statement := range legacy { + if _, err := conn.ExecContext(t.Context(), statement); err != nil { + t.Fatal(statement, err) + } + } + conn.Close() + // DROP TABLE removed its derived-proof triggers. Preserve the + // independently current comparison domain on this predecessor. + for _, statement := range reviewexec.ComparisonSchemaSQL() { + if strings.HasPrefix(statement, "CREATE TRIGGER ") { + if _, err := store.DB().Exec(strings.Replace(statement, "CREATE TRIGGER ", "CREATE TRIGGER IF NOT EXISTS ", 1)); err != nil { + t.Fatal(err) + } + } + } + statements = nil + if test.version < 6 { + statements = append(statements, `DROP TABLE review_hosted_allowance_queries`, `DROP TABLE review_hosted_preflight`) + } if test.version < 4 { statements = append(statements, `DROP TABLE review_cli_preflight`) } diff --git a/internal/backup/operation_list_index_test.go b/internal/backup/operation_list_index_test.go index 3f2ab6f6a..62a807559 100644 --- a/internal/backup/operation_list_index_test.go +++ b/internal/backup/operation_list_index_test.go @@ -11,12 +11,22 @@ import ( ) func TestOperationListIndexBackupVersionsRemainReadOnly(t *testing.T) { - for _, version := range []string{"1", "2"} { + for _, version := range []string{"1", "2", "3"} { t.Run(version, func(t *testing.T) { store, dir := historyInventoryFixture(t) if err := reviewexec.EnsureSchema(t.Context(), store); err != nil { t.Fatal(err) } + if version != "3" { + for _, index := range []string{"review_waits_live_retry", "review_transitions_exhaustion_time", "review_transitions_exhaustion_attempt"} { + if _, err := store.DB().Exec("DROP INDEX " + index); err != nil { + t.Fatal(err) + } + } + if _, err := store.DB().Exec(`UPDATE metadata SET value=? WHERE key='schema:review_execution_indexes'`, version); err != nil { + t.Fatal(err) + } + } if version == "1" { if err := store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { if _, err := tx.ExecContext(ctx, `DROP INDEX review_operations_listing`); err != nil { diff --git a/internal/backup/reservation_scope_inventory.go b/internal/backup/reservation_scope_inventory.go new file mode 100644 index 000000000..a785a13f9 --- /dev/null +++ b/internal/backup/reservation_scope_inventory.go @@ -0,0 +1,149 @@ +package backup + +import ( + "context" + "database/sql" + "strings" +) + +// These guards preserve the reservation policy through backup and inactive +// restore. Uniqueness must remain account-wide for CLI and repository-scoped +// for Hosted, alongside the exact-target and attempt identities. +func validateReservationScopeSchema(ctx context.Context, db sqlReader) error { + readError := func() error { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + type index struct { + name, origin string + partial int + } + rows, err := db.QueryContext(ctx, `SELECT name,origin,partial FROM pragma_index_list('review_execution_reservations') WHERE "unique"=1`) + if err != nil { + return readError() + } + var indexes []index + for rows.Next() { + var x index + if err = rows.Scan(&x.name, &x.origin, &x.partial); err != nil { + rows.Close() + return readError() + } + indexes = append(indexes, x) + } + err = rows.Err() + rows.Close() + if err != nil { + return readError() + } + if len(indexes) != 4 { + return invalid() + } + seen := map[string]bool{} + for _, x := range indexes { + var want, identity string + switch { + case x.origin == "pk" && x.partial == 0: + want, identity = "provider repository_id pull_number action_class", "target" + case x.origin == "u" && x.partial == 0: + want, identity = "attempt_id", "attempt" + case x.origin == "c" && x.partial == 1 && x.name == "review_reservations_cli_account": + want, identity = "provider account action_class", "cli" + case x.origin == "c" && x.partial == 1 && x.name == "review_reservations_hosted_account_repository": + want, identity = "provider account repository_id action_class", "hosted" + default: + return invalid() + } + if seen[identity] { + return invalid() + } + seen[identity] = true + columns, err := db.QueryContext(ctx, `SELECT name,coll,cid FROM pragma_index_xinfo(?) WHERE key=1 ORDER BY seqno`, x.name) + if err != nil { + return readError() + } + var names []string + for columns.Next() { + var name, coll sql.NullString + var cid int + if err = columns.Scan(&name, &coll, &cid); err != nil { + columns.Close() + return readError() + } + if !name.Valid || !coll.Valid || coll.String != "BINARY" || cid < 0 { + columns.Close() + return invalid() + } + names = append(names, name.String) + } + err = columns.Err() + columns.Close() + if err != nil { + return readError() + } + if strings.Join(names, " ") != want { + return invalid() + } + if x.partial == 1 { + var definition sql.NullString + if err = db.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(sql AS BLOB))<=4096 THEN sql END FROM sqlite_schema WHERE type='index' AND name=? AND tbl_name='review_execution_reservations'`, x.name).Scan(&definition); err != nil { + return readError() + } + expected := "CREATE UNIQUE INDEX " + x.name + " ON review_execution_reservations(" + strings.ReplaceAll(want, " ", ",") + ") WHERE action_class='" + identity + "'" + if !definition.Valid || strings.Join(strings.Fields(definition.String), " ") != expected { + return invalid() + } + } + } + return nil +} + +// Schema nine replaces the one-attempt-per-operation table constraint with +// historical attempts and a partial guard for live work. Both indexes must +// survive backup and inactive restore, even when existing rows are consistent. +func validateAttemptIndexSchema(ctx context.Context, db sqlReader) error { + readError := func() error { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + var uniqueCount int + if err := db.QueryRowContext(ctx, `SELECT count(*) FROM pragma_index_list('review_execution_attempts') WHERE "unique"=1`).Scan(&uniqueCount); err != nil { + return readError() + } + // Schema nine has only the primary key on id and the partial live-operation + // guard. A leftover operation_id UNIQUE constraint would still prevent + // historical attempts even when both named indexes below are canonical. + if uniqueCount != 2 { + return invalid() + } + for _, index := range []struct { + name, definition string + unique, partial int + }{ + {"review_attempts_operation", "CREATE INDEX review_attempts_operation ON review_execution_attempts(operation_id,id)", 0, 0}, + {"review_attempts_live_operation", "CREATE UNIQUE INDEX review_attempts_live_operation ON review_execution_attempts(operation_id) WHERE state IN ('preparing','posting','active','uncertain')", 1, 1}, + } { + var origin string + var unique, partial int + if err := db.QueryRowContext(ctx, `SELECT origin,"unique",partial FROM pragma_index_list('review_execution_attempts') WHERE name=?`, index.name).Scan(&origin, &unique, &partial); err != nil { + return readError() + } + if origin != "c" || unique != index.unique || partial != index.partial { + return invalid() + } + var definition sql.NullString + if err := db.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(sql AS BLOB))<=4096 THEN sql END FROM sqlite_schema WHERE type='index' AND name=? AND tbl_name='review_execution_attempts'`, index.name).Scan(&definition); err != nil { + return readError() + } + // As with the reservation guards, require the canonical definition. This + // also rejects changed column order, expressions, collations or predicates. + if !definition.Valid || strings.Join(strings.Fields(definition.String), " ") != index.definition { + return invalid() + } + } + return nil +} diff --git a/internal/backup/reservation_scope_inventory_test.go b/internal/backup/reservation_scope_inventory_test.go new file mode 100644 index 000000000..ed5ab9bee --- /dev/null +++ b/internal/backup/reservation_scope_inventory_test.go @@ -0,0 +1,144 @@ +package backup + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +func TestReservationScopeBackupRestoreAndPhysicalGuards(t *testing.T) { + f := newRestoreFixture(t) + var version int + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != 10 { + t.Fatalf("reservation schema not current: %d %v", version, err) + } + before := backupRows(t, f.store.DB()) + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("canonical scoped reservation refused", err) + } + destination := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + after := backupRows(t, db) + for _, table := range []string{"review_execution_reservations", "review_execution_attempts", "review_operations", "review_execution_transitions", "review_hosted_allowance_queries", "receipts"} { + if before[table] != after[table] { + t.Fatal("inactive restore changed native identity", table) + } + } + for name, statement := range map[string]string{ + "missing cli guard": `DROP INDEX review_reservations_cli_account`, + "missing hosted guard": `DROP INDEX review_reservations_hosted_account_repository`, + "global hosted guard": `DROP INDEX review_reservations_hosted_account_repository; CREATE UNIQUE INDEX review_reservations_hosted_account_repository ON review_execution_reservations(provider,account,action_class) WHERE action_class='hosted'`, + "disabled hosted guard": `DROP INDEX review_reservations_hosted_account_repository; CREATE UNIQUE INDEX review_reservations_hosted_account_repository ON review_execution_reservations(provider,account,repository_id,action_class) WHERE action_class='unused'`, + "widened cli guard": `DROP INDEX review_reservations_cli_account; CREATE UNIQUE INDEX review_reservations_cli_account ON review_execution_reservations(provider,account,repository_id,action_class) WHERE action_class='cli'`, + "extra unique index": `CREATE UNIQUE INDEX unexpected_reservation_account ON review_execution_reservations(account)`, + "changed primary key target": `PRAGMA foreign_keys=OFF; CREATE TABLE altered_reservations(provider TEXT NOT NULL,repository_id INTEGER NOT NULL,pull_number INTEGER NOT NULL,action_class TEXT NOT NULL,account TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),PRIMARY KEY(provider,account,repository_id,pull_number,action_class)); INSERT INTO altered_reservations SELECT provider,repository_id,pull_number,action_class,account,attempt_id FROM review_execution_reservations; DROP TABLE review_execution_reservations; ALTER TABLE altered_reservations RENAME TO review_execution_reservations; CREATE UNIQUE INDEX review_reservations_cli_account ON review_execution_reservations(provider,account,action_class) WHERE action_class='cli'; CREATE UNIQUE INDEX review_reservations_hosted_account_repository ON review_execution_reservations(provider,account,repository_id,action_class) WHERE action_class='hosted'`, + } { + t.Run(name, func(t *testing.T) { + damaged := restoreModifiedBundle(t, bundle, statement) + before := restoreTree(t, damaged) + if _, err := Inspect(t.Context(), damaged); err == nil { + t.Fatal("rehashed bundle lost reservation safety") + } + destination := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), damaged, destination); err == nil { + t.Fatal("Restore accepted damaged reservation guards") + } + if _, err := os.Lstat(destination); !os.IsNotExist(err) { + t.Fatal("rejected restore created a destination", err) + } + if !reflect.DeepEqual(before, restoreTree(t, damaged)) { + t.Fatal("rejection changed retained bundle data") + } + }) + } +} + +func TestAttemptIndexPhysicalGuardsRejectRehashedBundles(t *testing.T) { + f := newRestoreFixture(t) + bundle := restoreBundle(t, f) + for name, statement := range map[string]string{ + "missing-live": `DROP INDEX review_attempts_live_operation`, + "missing-lookup": `DROP INDEX review_attempts_operation`, + "nonunique-live": `DROP INDEX review_attempts_live_operation; CREATE INDEX review_attempts_live_operation ON review_execution_attempts(operation_id) WHERE state IN ('preparing','posting','active','uncertain')`, + "wrong-live-column": `DROP INDEX review_attempts_live_operation; CREATE UNIQUE INDEX review_attempts_live_operation ON review_execution_attempts(id) WHERE state IN ('preparing','posting','active','uncertain')`, + "missing-uncertain": `DROP INDEX review_attempts_live_operation; CREATE UNIQUE INDEX review_attempts_live_operation ON review_execution_attempts(operation_id) WHERE state IN ('preparing','posting','active')`, + "full-live": `DROP INDEX review_attempts_live_operation; CREATE UNIQUE INDEX review_attempts_live_operation ON review_execution_attempts(operation_id)`, + "wrong-lookup-order": `DROP INDEX review_attempts_operation; CREATE INDEX review_attempts_operation ON review_execution_attempts(id,operation_id)`, + "unique-lookup": `DROP INDEX review_attempts_operation; CREATE UNIQUE INDEX review_attempts_operation ON review_execution_attempts(operation_id,id)`, + "unique-operation-constraint": `CREATE UNIQUE INDEX legacy_attempt_operation_unique ON review_execution_attempts(operation_id)`, + "partial-lookup": `DROP INDEX review_attempts_operation; CREATE INDEX review_attempts_operation ON review_execution_attempts(operation_id,id) WHERE state='active'`, + "collation-lookup": `DROP INDEX review_attempts_operation; CREATE INDEX review_attempts_operation ON review_execution_attempts(operation_id COLLATE NOCASE,id)`, + } { + t.Run(name, func(t *testing.T) { + damaged := restoreModifiedBundle(t, bundle, statement) + if _, err := Inspect(t.Context(), damaged); err == nil { + t.Error("Inspect accepted damaged attempt indexes") + } + destination := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), damaged, destination); err == nil { + t.Error("Restore accepted damaged attempt indexes") + } + if _, err := os.Stat(destination); !os.IsNotExist(err) { + t.Fatal("rejected restore created a destination", err) + } + }) + } +} + +func TestWaitPhysicalGuardsRejectRehashedBundles(t *testing.T) { + f := newRestoreFixture(t) + bundle := restoreBundle(t, f) + var canonical string + if err := f.store.DB().QueryRow(`SELECT sql FROM sqlite_schema WHERE name='review_operation_waits'`).Scan(&canonical); err != nil { + t.Fatal(err) + } + for name, mutation := range map[string][2]string{ + "missing primary key": {"operation_id TEXT PRIMARY KEY", "operation_id TEXT"}, + "changed operation type": {"operation_id TEXT", "operation_id INTEGER"}, + "changed baseline type": {"baseline_attempt_id TEXT", "baseline_attempt_id INTEGER"}, + "changed retry type": {"retry_not_before TEXT", "retry_not_before INTEGER"}, + "changed paused type": {"paused INTEGER", "paused TEXT"}, + "nullable retry": {"retry_not_before TEXT NOT NULL", "retry_not_before TEXT"}, + "nullable paused": {"paused INTEGER NOT NULL", "paused INTEGER"}, + "missing retry default": {"DEFAULT ''", ""}, + "changed retry default": {"DEFAULT ''", "DEFAULT 'later'"}, + "missing paused default": {"DEFAULT 0", ""}, + "changed paused default": {"DEFAULT 0", "DEFAULT 1"}, + "missing paused check": {"CHECK(paused IN(0,1))", ""}, + "weakened paused check": {"CHECK(paused IN(0,1))", "CHECK(paused IN(0,1,2))"}, + "missing paired check": {",CHECK((baseline_attempt_id IS NULL AND retry_not_before='') OR (baseline_attempt_id IS NOT NULL AND retry_not_before<>''))", ""}, + "weakened paired check": {"baseline_attempt_id IS NULL AND retry_not_before=''", "baseline_attempt_id IS NULL"}, + } { + t.Run(name, func(t *testing.T) { + altered := strings.Replace(canonical, mutation[0], mutation[1], 1) + if altered == canonical { + t.Fatal("mutation did not change canonical schema") + } + damaged := restoreModifiedBundle(t, bundle, "DROP TABLE review_operation_waits; "+altered) + before := restoreTree(t, damaged) + if _, err := Inspect(t.Context(), damaged); err == nil { + t.Error("Inspect accepted damaged wait constraints") + } + destination := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), damaged, destination); err == nil { + t.Error("Restore accepted damaged wait constraints") + } + if _, err := os.Stat(destination); !os.IsNotExist(err) { + t.Fatal("rejected restore created a destination", err) + } + if !reflect.DeepEqual(before, restoreTree(t, damaged)) { + t.Fatal("rejection changed retained bundle data") + } + }) + } +} diff --git a/internal/backup/review_order_inventory.go b/internal/backup/review_order_inventory.go new file mode 100644 index 000000000..37029afc3 --- /dev/null +++ b/internal/backup/review_order_inventory.go @@ -0,0 +1,50 @@ +package backup + +import ( + "context" + "database/sql" + "strings" +) + +const reviewFileLimitDDL = "override_file_limit INTEGER NOT NULL DEFAULT 0 CHECK(override_file_limit IN (0,1))" + +const reviewOrderDDL = "allow_out_of_order INTEGER NOT NULL DEFAULT 0 CHECK(allow_out_of_order IN (0,1))" + +func reviewOrderColumn(kind string, notnull, pk int, defaultValue any) bool { + value, ok := defaultValue.(string) + return kind == "INTEGER" && notnull == 1 && pk == 0 && ok && value == "0" +} + +// Bind the explicit request flags appended in migrations seven and eight, +// without duplicating the predecessor execution schema authority. +func validateReviewOrderPhysicalSchema(ctx context.Context, db sqlReader, version int) error { + var definition sql.NullString + if db.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(sql AS BLOB))<=16384 THEN sql END FROM sqlite_schema WHERE type='table' AND name='review_operations'`).Scan(&definition) != nil || !definition.Valid { + return invalid() + } + normalized := strings.Join(strings.Fields(definition.String), " ") + clause := ", " + reviewOrderDDL + ",FOREIGN KEY(project_id,configuration_revision)" + if version >= 8 { + clause = ", " + reviewOrderDDL + ", " + reviewFileLimitDDL + ",FOREIGN KEY(project_id,configuration_revision)" + if strings.Count(normalized, reviewFileLimitDDL) != 1 { + return invalid() + } + } + if strings.Count(normalized, reviewOrderDDL) != 1 || !strings.Contains(normalized, clause) { + return invalid() + } + return nil +} + +func validateReviewOrderRows(ctx context.Context, db sqlReader, version int) error { + var damaged bool + if db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE typeof(allow_out_of_order)!='integer' OR allow_out_of_order NOT IN (0,1) LIMIT 1)`).Scan(&damaged) != nil || damaged { + return invalid() + } + if version >= 8 { + if db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE typeof(override_file_limit)!='integer' OR override_file_limit NOT IN (0,1) LIMIT 1)`).Scan(&damaged) != nil || damaged { + return invalid() + } + } + return nil +} diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index d6af6a39f..4fc00271b 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -246,7 +246,7 @@ func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testin before := backupRows(t, db) schema := restoreRows(t, db, `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name`) metadata := restoreRows(t, db, `SELECT key,value FROM metadata ORDER BY key`) - for domain, version := range map[string]string{"reviews": "11", "review_execution": "6", "review_policy": "1", "review_rounds": "5"} { + for domain, version := range map[string]string{"reviews": "11", "review_execution": "10", "review_policy": "1", "review_rounds": "5"} { var got string if err := db.QueryRow(`SELECT value FROM metadata WHERE key=?`, "schema:"+domain).Scan(&got); err != nil || got != version { t.Fatal("parent domain changed", domain, got, err) diff --git a/internal/reviewexec/allowance_observation.go b/internal/reviewexec/allowance_observation.go new file mode 100644 index 000000000..dcfacfefc --- /dev/null +++ b/internal/reviewexec/allowance_observation.go @@ -0,0 +1,271 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "fmt" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/strictjson" +) + +// errAllowanceObservationAbsent marks only the missing top-level preflight +// record. It still wraps sql.ErrNoRows for older preparation/recovery paths +// that intentionally treat an absent observation as a normal no-op. +var errAllowanceObservationAbsent = fmt.Errorf("allowance observation absent: %w", sql.ErrNoRows) + +// These private classifications describe unusable retained evidence. Keep the +// public storage error unchanged while separating it from actual lookup errors. +type storedUnavailableKind uint8 + +const ( + storedWaitingIntent storedUnavailableKind = iota + 1 + storedAllowanceObservation + storedHostedQuery + storedHostedObservation + storedReviewAdmission + storedConfigurationHistory +) + +type storedUnavailableError struct { + kind storedUnavailableKind + cause *core.Error +} + +func (e *storedUnavailableError) Error() string { return e.cause.Error() } +func (e *storedUnavailableError) Unwrap() error { return e.cause } + +func newStoredUnavailable(kind storedUnavailableKind, message string) error { + return &storedUnavailableError{kind: kind, cause: &core.Error{Code: "storage_unavailable", Message: message, Status: 500}} +} + +func isStoredUnavailable(err error, kind storedUnavailableKind) bool { + var unavailable *storedUnavailableError + return errors.As(err, &unavailable) && unavailable.kind == kind +} + +func allowanceUnavailable() error { + return newStoredUnavailable(storedAllowanceObservation, "Stored allowance observation is unavailable.") +} + +func validAllowanceOwners(o Operation, a Attempt) bool { + return hostedObservationID(o.ID, "review_operation_") && hostedObservationID(a.ID, "review_attempt_") && identifier.MatchString(o.ProjectID) && identifier.MatchString(o.ActorID) && (o.WorkerID == "" || identifier.MatchString(o.WorkerID)) && identifier.MatchString(a.Provider) && identifier.MatchString(a.Account) && o.ConfigurationRevision > 0 && o.PolicyRevision > 0 && o.Revision > 0 && a.Revision > 0 && o.AttemptID == a.ID && a.OperationID == o.ID && a.ProjectID == o.ProjectID && (o.Channel == "cli" || o.Channel == "hosted") +} + +func readCLIAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (cliAllowanceRecord, error) { + var record cliAllowanceRecord + var project, attempt string + var body sql.NullString + err := q.QueryRowContext(ctx, `SELECT project_id,attempt_id,CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=8192 THEN body_json END FROM review_cli_preflight WHERE attempt_id=?`, a.ID).Scan(&project, &attempt, &body) + if errors.Is(err, sql.ErrNoRows) { + return record, errAllowanceObservationAbsent + } + if err != nil { + return record, err + } + if !body.Valid { + return record, allowanceUnavailable() + } + if o.AttemptID != a.ID { + var err error + o, err = historicalCLIExhaustionOperation(ctx, q, o, a) + if err != nil { + return record, allowanceDependencyError(err) + } + } + if !validAllowanceOwners(o, a) { + return record, allowanceUnavailable() + } + if strictjson.Decode([]byte(body.String), &record) != nil || encoded(record) != body.String || !validCLIAllowanceObservation(record.Observation) || project != o.ProjectID || attempt != a.ID || record.ProjectID != project || record.AttemptID != attempt || record.OperationID != o.ID || a.OperationID != o.ID || a.ProjectID != project || o.AttemptID != a.ID || o.Channel != "cli" || record.ActorID != o.ActorID || record.WorkerID != o.WorkerID || record.ConfigurationRevision != o.ConfigurationRevision || record.PolicyRevision != o.PolicyRevision || record.CapabilityFingerprint != o.CapabilityFingerprint || !hash.MatchString(record.CapabilityFingerprint) || record.Provider != a.Provider || record.Account != a.Account || !identifier.MatchString(record.Provider) || !identifier.MatchString(record.Account) || record.AttemptRevision != 1 || record.AttemptRevision > a.Revision || record.Observation.Anchor.PullNumber != o.PullNumber || record.Observation.Anchor.CandidateSHA != o.HeadSHA { + return record, allowanceUnavailable() + } + var repo int64 + if err := q.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repo); err != nil { + return record, allowanceDependencyError(err) + } + if record.Observation.Anchor.RepositoryID != repo { + return record, allowanceUnavailable() + } + return record, nil +} + +func readHostedAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (hostedAllowanceRecord, error) { + var project, attempt string + var body sql.NullString + err := q.QueryRowContext(ctx, `SELECT project_id,attempt_id,CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=16384 THEN body_json END FROM review_hosted_preflight WHERE attempt_id=?`, a.ID).Scan(&project, &attempt, &body) + if errors.Is(err, sql.ErrNoRows) { + return hostedAllowanceRecord{}, errAllowanceObservationAbsent + } + if err != nil { + return hostedAllowanceRecord{}, err + } + if !body.Valid { + return hostedAllowanceRecord{}, allowanceUnavailable() + } + if o.AttemptID != a.ID { + var err error + o, err = historicalCooldownOperation(ctx, q, o, a) + if err != nil { + return hostedAllowanceRecord{}, allowanceDependencyError(err) + } + } + if !validAllowanceOwners(o, a) { + return hostedAllowanceRecord{}, allowanceUnavailable() + } + record, err := decodeHostedAllowance(body.String, project, attempt) + if err != nil { + return record, err + } + query, err := readHostedQuery(ctx, q, a, o) + if err != nil { + return record, allowanceDependencyError(err) + } + if project != o.ProjectID || attempt != a.ID || !hostedAllowanceBinding(record, a, o, query) { + return record, allowanceUnavailable() + } + if record.Input.Observation.State == "cooldown_observed" { + if err := validateCooldownReference(ctx, q, a, o, query, record.Input); err != nil { + return record, err + } + } + return record, nil +} + +// A retained allowance depends on its related domain rows. A missing row or +// an unavailable/missing hosted query is corrupt retained evidence, while +// other database and context errors must retain their original classification. +func allowanceDependencyError(err error) error { + if errors.Is(err, sql.ErrNoRows) { + return allowanceUnavailable() + } + var failure *core.Error + if errors.As(err, &failure) && (failure.Code == "not_found" || isStoredUnavailable(err, storedHostedQuery)) { + return allowanceUnavailable() + } + return err +} + +func storedAllowanceUnavailable(err error) bool { + return isStoredUnavailable(err, storedAllowanceObservation) +} + +func validateCooldownReference(ctx context.Context, q EvidenceQuery, a Attempt, o Operation, query HostedAllowanceQuery, in HostedAllowanceInput) error { + var id, project, attempt, operation, checksum string + var body sql.NullString + var position, size int64 + err := q.QueryRowContext(ctx, `SELECT id,project_id,attempt_id,operation_id,position,capture_sha256,capture_bytes,CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=24576 THEN body_json END FROM review_hosted_observations WHERE attempt_id=? AND capture_sha256=?`, a.ID, in.CaptureSHA256).Scan(&id, &project, &attempt, &operation, &position, &checksum, &size, &body) + if err != nil { + return allowanceDependencyError(err) + } + if !body.Valid { + return allowanceUnavailable() + } + observation, err := decodeHostedObservation(body.String, id, project, attempt, operation, position, checksum, size, a, o) + if err != nil { + // The optional capture is unusable; lookup failures above still retain + // their database or context classification. + return allowanceUnavailable() + } + source := observation.Input + if project != o.ProjectID || attempt != a.ID || operation != o.ID || source.Kind != "allowance_query" || source.CaptureID != in.CaptureID || source.CaptureBytes != in.CaptureBytes || source.CaptureSHA256 != in.CaptureSHA256 || source.ObservedAt != in.ObservedAt || source.ExpectedAnchor != query.Anchor || source.Intent != query.Intent { + return allowanceUnavailable() + } + return nil +} + +// readHeldAllowance projects only original held observations, never current +// account capacity. All queries use the caller's authorized read transaction. +func readHeldAllowance(ctx context.Context, q EvidenceQuery, o Operation) (*AllowanceObservation, error) { + if o.State != "held" || o.AttemptID == "" || !(o.Channel == "cli" && o.Reason == "allowance_exhausted" || o.Channel == "hosted" && o.Reason == "hosted_allowance_cooldown") { + return nil, nil + } + a, err := readAttempt(ctx, q, o.ProjectID, o.AttemptID) + if err != nil { + return nil, allowanceDependencyError(err) + } + if a.OperationID != o.ID || a.State != o.State { + return nil, allowanceUnavailable() + } + if o.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, q, o, a) + if errors.Is(err, errAllowanceObservationAbsent) { + return nil, nil + } + if err != nil { + return nil, err + } + in := record.Observation + if in.Remaining != 0 { + return nil, nil + } + return &AllowanceObservation{Kind: "cli_exhausted", ObservedAt: in.ObservedAt, Remaining: &in.Remaining, Limit: &in.Limit, FullCapacityInMS: &in.FullCapacityInMS, RollingWindowMS: &in.RollingWindowMS}, nil + } + record, err := readHostedAllowanceRecord(ctx, q, o, a) + if errors.Is(err, errAllowanceObservationAbsent) { + return nil, nil + } + if err != nil { + if isStoredUnavailable(err, storedHostedObservation) { + return nil, allowanceUnavailable() + } + return nil, err + } + if record.Input.Observation.State != "cooldown_observed" { + return nil, nil + } + return &AllowanceObservation{Kind: "hosted_cooldown", ObservedAt: record.Input.ObservedAt, RetryNotBefore: record.Input.Observation.RetryNotBefore.Format("2006-01-02T15:04:05.999999999Z07:00")}, nil +} + +// ValidateAllowanceSnapshot checks retained facts without applying ingestion +// freshness. It opens no connection, filesystem artifact or provider request. +func ValidateAllowanceSnapshot(ctx context.Context, q EvidenceQuery, executionVersion int) error { + tables := []string{} + if executionVersion >= 4 { + tables = append(tables, "review_cli_preflight") + } + if executionVersion >= 6 { + tables = append(tables, "review_hosted_preflight") + } + for _, table := range tables { + rows, err := q.QueryContext(ctx, `SELECT project_id,attempt_id FROM `+table) + if err != nil { + return err + } + var owners [][2]string + for rows.Next() { + var owner [2]string + if err := rows.Scan(&owner[0], &owner[1]); err != nil { + rows.Close() + return err + } + owners = append(owners, owner) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + // Finish the scan before further queries: snapshot readers can have a + // single connection, while transaction readers share their connection. + for _, owner := range owners { + a, err := readAttempt(ctx, q, owner[0], owner[1]) + if err != nil { + return err + } + o, err := readOperationBase(ctx, q, owner[0], a.OperationID) + if err != nil { + return err + } + if table == "review_cli_preflight" { + _, err = readCLIAllowanceRecord(ctx, q, o, a) + } else { + _, err = readHostedAllowanceRecord(ctx, q, o, a) + } + if err != nil { + return err + } + } + } + return nil +} diff --git a/internal/reviewexec/allowance_observation_test.go b/internal/reviewexec/allowance_observation_test.go new file mode 100644 index 000000000..f5bd371a4 --- /dev/null +++ b/internal/reviewexec/allowance_observation_test.go @@ -0,0 +1,748 @@ +package reviewexec + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" + "github.com/benhook1013/FireController/internal/reviews" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" +) + +func cooldownObservationFixture(t *testing.T) (*attemptFixture, Attempt, HostedAllowanceInput) { + t.Helper() + f, a, q, in := hostedAllowanceFixture(t) + in.Observation.State, in.Observation.Reason = "cooldown_observed", "provider_cooldown_observed" + in.Observation.RetryNotBefore = in.Observation.ResponseCreatedAt.Add(3 * time.Minute) + observed, _ := time.Parse(time.RFC3339Nano, in.ObservedAt) + start, _ := time.Parse(time.RFC3339Nano, q.EarliestPosting) + _, err := f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, HostedObservationInput{Kind: "allowance_query", CaptureID: in.CaptureID, CaptureSHA256: in.CaptureSHA256, CaptureBytes: in.CaptureBytes, StartedAt: start.Truncate(time.Second).Format(time.RFC3339Nano), FinishedAt: in.ObservedAt, ObservedAt: observed.Format(time.RFC3339Nano), ExpectedAnchor: q.Anchor, Intent: q.Intent}) + if err != nil { + t.Fatal(err) + } + return f, a, in +} + +func TestHeldAllowanceSQLReadHTTPReplayAndValidation(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var err error + reason := "allowance_exhausted" + var input CLIAllowanceObservation + var hosted HostedAllowanceInput + if channel == "cli" { + f, a, input = cliAllowanceFixture(t) + input.Remaining, input.FullCapacityInMS = 0, 0 + if err = f.e.RecordCLIAllowance(t.Context(), attemptProject, a.ID, 1, input); err == nil { + t.Fatal("zero observation accepted as positive preflight") + } + err = f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 1, input) + } else { + f, a, hosted = cooldownObservationFixture(t) + reason = "hosted_allowance_cooldown" + if err = f.e.RecordHostedAllowance(t.Context(), attemptProject, a.ID, 1, hosted); err == nil { + t.Fatal("cooldown accepted as positive preflight") + } + err = f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, hosted) + } + if err != nil { + t.Fatal(err) + } + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + if err != nil { + t.Fatal(err) + } + original := attemptState(t, f, a) + var before string + table := "review_cli_preflight" + if channel == "hosted" { + table = "review_hosted_preflight" + } + if err := f.store.DB().QueryRow(`SELECT body_json FROM `+table+` WHERE attempt_id=?`, a.ID).Scan(&before); err != nil { + t.Fatal(err) + } + r := httptest.NewRequest("GET", "/api/v1/projects/"+attemptProject+"/reviews/operations/"+a.OperationID, nil) + r.Header.Set("Authorization", "Bearer "+f.reader) + r.Header.Set(operationWaitHeader, "3") + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code != http.StatusOK { + t.Fatal("held HTTP read", w.Code, w.Body.String()) + } + var op Operation + if err = json.Unmarshal(w.Body.Bytes(), &op); err != nil { + t.Fatal(err) + } + if op.Allowance == nil || op.State != "held" || op.Reason != reason { + t.Fatal("missing held observation", op) + } + if channel == "cli" { + v := op.Allowance + if v.Kind != "cli_exhausted" || v.Remaining == nil || *v.Remaining != 0 || v.Limit == nil || *v.Limit != input.Limit || v.FullCapacityInMS == nil || *v.FullCapacityInMS != 0 || v.RollingWindowMS == nil || v.RetryNotBefore != "" || !bytes.Contains(w.Body.Bytes(), []byte(`"full_capacity_in_ms":0`)) { + t.Fatal("lost known zeros or fabricated retry", v) + } + err = f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 1, input) + } else { + v := op.Allowance + if v.Kind != "hosted_cooldown" || v.RetryNotBefore != hosted.Observation.RetryNotBefore.Format(time.RFC3339Nano) || v.Remaining != nil || v.Limit != nil || v.FullCapacityInMS != nil || v.RollingWindowMS != nil { + t.Fatal("wrong cooldown projection", v) + } + err = f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, hosted) + if _, err := f.e.ReadHostedAllowance(t.Context(), attemptProject, a.ID); err == nil { + t.Fatal("cooldown returned as positive allowance proof") + } + } + compactHTTP := statusHTTP(t, f, a.OperationID, "", "wait=0", "3") + var compact OperationStatus + if compactHTTP.Code != 200 || json.Unmarshal(compactHTTP.Body.Bytes(), &compact) != nil || compact.State != "held" || compact.Reason != reason || len(compactHTTP.Body.Bytes()) > 1024 { + t.Fatal("compact held status unavailable or expanded", compactHTTP.Code, compactHTTP.Body.String()) + } + wantRetry := "" + if channel == "hosted" { + wantRetry = op.Allowance.RetryNotBefore + } + if compact.RetryNotBefore != wantRetry || strings.Contains(compactHTTP.Body.String(), `"allowance"`) || strings.Contains(compactHTTP.Body.String(), `"remaining"`) { + t.Fatal("compact cooldown lost deadline or loaded full allowance output", compactHTTP.Body.String()) + } + if err != nil { + t.Fatal("immutable held replay", err) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 6); err != nil { + t.Fatal("typed retained snapshot", err) + } + cliAllowanceReopen(t, f) + read, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), a.OperationID) + if err != nil || !reflect.DeepEqual(read.Allowance, op.Allowance) { + t.Fatal("restart lost allowance", read, err) + } + var after string + if err := f.store.DB().QueryRow(`SELECT body_json FROM `+table+` WHERE attempt_id=?`, a.ID).Scan(&after); err != nil { + t.Fatal(err) + } + if after != before || attemptState(t, f, a) != original { + t.Fatal("read/replay/restart rewrote source") + } + if w := f.request("GET", "/api/v1/projects/"+otherAttemptProject+"/reviews/operations/"+a.OperationID, f.other, "", ""); w.Code == 200 { + t.Fatal("foreign project exposed observation") + } + if _, err := f.store.DB().Exec(`UPDATE `+table+` SET body_json=body_json||' ' WHERE attempt_id=?`, a.ID); err != nil { + t.Fatal(err) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 6); err == nil { + t.Fatal("noncanonical retained body accepted") + } + if _, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), a.OperationID); err == nil { + t.Fatal("corrupt optional fact silently accepted") + } + if channel == "hosted" && statusHTTP(t, f, a.OperationID, "", "").Code != 500 { + t.Fatal("compact read exposed an unvalidated deadline") + } + }) + } +} + +func TestHeldAllowanceLegacyMissingAndPositiveBytes(t *testing.T) { + f, a, in := cliAllowanceFixture(t) + if err := f.e.RecordCLIAllowance(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + var body string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_cli_preflight WHERE attempt_id=?`, a.ID).Scan(&body); err != nil { + t.Fatal(err) + } + var record cliAllowanceRecord + if json.Unmarshal([]byte(body), &record) != nil || encoded(record) != body { + t.Fatal("legacy positive encoding") + } + op, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), a.OperationID) + if err != nil || op.Allowance != nil { + t.Fatal("positive preparing observation leaked as held facts", op, err) + } + // Historical validation is structural, not an ingestion freshness test. + record.Observation.ObservedAt = time.Now().UTC().Add(-time.Hour).Format(time.RFC3339Nano) + record.Observation.Anchor.ObservedAt = record.Observation.ObservedAt + if _, err := f.store.DB().Exec(`UPDATE review_cli_preflight SET body_json=? WHERE attempt_id=?`, encoded(record), a.ID); err != nil { + t.Fatal(err) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 6); err != nil { + t.Fatal("historical positive observation rejected as stale", err) + } + f2 := newAttemptFixture(t) + f2.configure(t, attemptProject, "test-capability", 0, false) + b := f2.start(t, attemptProject, f2.enqueue(t, attemptProject, "legacy-no-facts", "cli", 2, 1)) + if _, err := f2.e.Advance(t.Context(), attemptProject, b.ID, 1, "held", "allowance_exhausted", ""); err != nil { + t.Fatal(err) + } + old, err := f2.e.ReadOperation(context.Background(), f2.scope(t, attemptProject, f2.writer, false), b.OperationID) + if err != nil || old.Allowance != nil { + t.Fatal("missing legacy observation became zero", old, err) + } +} + +func TestHeldAllowanceOnlyMissingPreflightIsCompatible(t *testing.T) { + ctx := context.Background() + f0, a0, _ := cliAllowanceFixture(t) + if _, err := f0.e.Advance(ctx, attemptProject, a0.ID, a0.Revision, "held", "allowance_exhausted", ""); err != nil { + t.Fatal(err) + } + op0, err := readOperationBase(ctx, f0.store.DB(), attemptProject, a0.OperationID) + if err != nil { + t.Fatal(err) + } + if _, err := readCLIAllowanceRecord(ctx, f0.store.DB(), op0, a0); !errors.Is(err, errAllowanceObservationAbsent) || !errors.Is(err, sql.ErrNoRows) { + t.Fatal("absent top-level preflight lost its compatibility sentinel", err) + } + if allowance, err := readHeldAllowance(ctx, f0.store.DB(), op0); err != nil || allowance != nil { + t.Fatal("absent preflight was not treated as legacy no-facts", allowance, err) + } + + f, a, input := cliAllowanceFixture(t) + input.Remaining = 0 + if err := f.e.RecordCLIExhaustion(ctx, attemptProject, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(ctx, attemptProject, a.ID, a.Revision, "held", "allowance_exhausted", ""); err != nil { + t.Fatal(err) + } + op, err := readOperationBase(ctx, f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + deleteRelatedRowWithoutForeignKeys(t, f.store.DB(), "projects", "id", attemptProject) + if _, err := readHeldAllowance(ctx, f.store.DB(), op); err == nil { + t.Fatal("missing related project row was hidden as no allowance") + } else { + attemptCode(t, err, "storage_unavailable") + } + if err := ValidateAllowanceSnapshot(ctx, f.store.DB(), 10); err == nil { + t.Fatal("snapshot validation accepted missing related project") + } else { + attemptCode(t, err, "storage_unavailable") + } +} + +func TestHeldHostedAllowanceMissingQueryIsUnavailable(t *testing.T) { + ctx := context.Background() + f, a, input := cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(ctx, attemptProject, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(ctx, attemptProject, a.ID, a.Revision, "held", "hosted_allowance_cooldown", ""); err != nil { + t.Fatal(err) + } + op, err := readOperationBase(ctx, f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + deleteRelatedRowWithoutForeignKeys(t, f.store.DB(), "review_hosted_allowance_queries", "attempt_id", a.ID) + if _, err := readHeldAllowance(ctx, f.store.DB(), op); err == nil { + t.Fatal("missing hosted query was hidden as no allowance") + } else { + attemptCode(t, err, "storage_unavailable") + } + if err := ValidateAllowanceSnapshot(ctx, f.store.DB(), 10); err == nil { + t.Fatal("snapshot validation accepted missing hosted query") + } else { + attemptCode(t, err, "storage_unavailable") + } +} + +func deleteRelatedRowWithoutForeignKeys(t *testing.T, db *sql.DB, table, column, key string) { + t.Helper() + conn, err := db.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if _, err := conn.ExecContext(context.Background(), `PRAGMA foreign_keys=OFF`); err != nil { + t.Fatal(err) + } + if _, err := conn.ExecContext(context.Background(), `DELETE FROM `+table+` WHERE `+column+`=?`, key); err != nil { + t.Fatal("delete related fixture row", table, err) + } + if _, err := conn.ExecContext(context.Background(), `PRAGMA foreign_keys=ON`); err != nil { + t.Fatal(err) + } +} + +func TestCooldownCannotAuthorizeActionAndRequiresRetainedQueryReference(t *testing.T) { + f, a, in := cooldownObservationFixture(t) + if _, err := f.store.DB().Exec(`DELETE FROM review_hosted_observations WHERE attempt_id=?`, a.ID); err != nil { + t.Fatal(err) + } + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err == nil { + t.Fatal("cooldown without raw-source journal accepted") + } + f, a, in = cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + intent, err := reviewprovider.HostedTriggerBody(reviewprovider.HostedTriggerIntent{OperationID: a.OperationID, AttemptID: a.ID, HeadSHA: in.Anchor.CandidateSHA}) + if err != nil { + t.Fatal(err) + } + a, err = f.e.Admit(t.Context(), attemptProject, a.ID, 1, in.Anchor, intent) + if err != nil { + t.Fatal(err) + } + source := hostedActionSource(a) + if err := f.e.VerifyHostedAction(t.Context(), attemptProject, a.ID, a.Revision, source); err == nil { + t.Fatal("cooldown became a positive action grant") + } +} + +func TestHeldAllowancePreparingRevisionProvenance(t *testing.T) { + f, a, in := cliAllowanceFixture(t) + in.Remaining = 0 + if err := f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 2, in); err == nil { + t.Fatal("noninitial preparing revision accepted") + } + if err := f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, 1, "held", "allowance_exhausted", ""); err != nil { + t.Fatal(err) + } + // Re-encode canonically, so the provenance check, not whitespace, rejects it. + var body string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_cli_preflight WHERE attempt_id=?`, a.ID).Scan(&body); err != nil { + t.Fatal(err) + } + var record cliAllowanceRecord + if json.Unmarshal([]byte(body), &record) != nil { + t.Fatal("record") + } + record.AttemptRevision = 2 + if _, err := f.store.DB().Exec(`UPDATE review_cli_preflight SET body_json=? WHERE attempt_id=?`, encoded(record), a.ID); err != nil { + t.Fatal(err) + } + if _, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), a.OperationID); err == nil { + t.Fatal("held revision masqueraded as preparing observation") + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 6); err == nil { + t.Fatal("backup accepted wrong preparing revision") + } +} + +func TestHeldAllowanceNegativeWriteEventFailureRollsBack(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var input CLIAllowanceObservation + var hosted HostedAllowanceInput + if channel == "cli" { + f, a, input = cliAllowanceFixture(t) + input.Remaining = 0 + } else { + f, a, hosted = cooldownObservationFixture(t) + } + admissionSQL(t, f, `CREATE TRIGGER reject_negative_preflight BEFORE INSERT ON events WHEN NEW.event_type='review.`+channel+`_preflight' BEGIN SELECT RAISE(ABORT,'synthetic private diagnostic'); END`) + before := attemptState(t, f, a) + var err error + if channel == "cli" { + err = f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 1, input) + } else { + err = f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, hosted) + } + if err == nil || strings.Contains(err.Error(), "synthetic") || attemptState(t, f, a) != before || attemptCount(t, f.store, `SELECT count(*) FROM review_`+channel+`_preflight`) != 0 { + t.Fatal("negative observation/event did not roll back safely", err) + } + }) + } +} + +func TestHeldAllowancePositiveObservationRemainsReadable(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var replay func() error + reason, table, key := "allowance_exhausted", "review_cli_preflight", "allowance-request" + if channel == "cli" { + var in CLIAllowanceObservation + f, a, in = cliAllowanceFixture(t) + replay = func() error { return f.e.RecordCLIAllowance(t.Context(), attemptProject, a.ID, 1, in) } + } else { + var in HostedAllowanceInput + f, a, _, in = hostedAllowanceFixture(t) + replay = func() error { return f.e.RecordHostedAllowance(t.Context(), attemptProject, a.ID, 1, in) } + reason, table, key = "hosted_allowance_cooldown", "review_hosted_preflight", "query-request" + } + if err := replay(); err != nil { + t.Fatal(err) + } + if err := reviews.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + bindPublisher := func() { + var err error + f.e, err = New(f.store, attemptCapabilities, WithNativeProjection()) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + f.e.Register(mux) + reviews.Register(mux, f.store) + f.handler = mux + } + bindPublisher() + metadata := projectionPull(2) + if _, err := f.e.PublishAttempt(t.Context(), attemptProject, a.ID, &metadata); err != nil { + t.Fatal("initial native publication", err) + } + var body string + if err := f.store.DB().QueryRow(`SELECT body_json FROM `+table+` WHERE attempt_id=?`, a.ID).Scan(&body); err != nil { + t.Fatal(err) + } + var err error + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + if err != nil { + t.Fatal("valid positive observation prevented held transition/publication", err) + } + _, projected := projectedAttempt(t, f, a) + if projected.State != "held" || projected.Reason != reason { + t.Fatal("native transition projection lost hold", projected) + } + before := attemptState(t, f, a) + policyState(t, f) + path := "/api/v1/projects/" + attemptProject + "/reviews/operations/" + a.OperationID + var original []byte + for phase := 0; phase < 2; phase++ { + if phase == 1 { + cliAllowanceReopen(t, f) + bindPublisher() + } + read := f.request("GET", path, f.reader, "", "") + var op Operation + if read.Code != http.StatusOK || json.Unmarshal(read.Body.Bytes(), &op) != nil || op.State != "held" || op.Reason != reason || op.Allowance != nil || bytes.Contains(read.Body.Bytes(), []byte(`"allowance":`)) { + t.Fatal("positive observation became unreadable or negative timing", phase, read.Code, read.Body.String()) + } + if phase == 0 { + original = bytes.Clone(read.Body.Bytes()) + } else if !bytes.Equal(original, read.Body.Bytes()) { + t.Fatal("reopen changed held operation") + } + if err := replay(); err != nil { + t.Fatal("original positive replay after hold", err) + } + request := httptest.NewRequest("POST", "/api/v1/projects/"+attemptProject+"/reviews/requests", bytes.NewBufferString(encoded(Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: channel, HeadSHA: op.HeadSHA}))) + request.Header.Set("Authorization", "Bearer "+f.writer) + request.Header.Set("Idempotency-Key", key) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Prefer", "wait=2") + result := httptest.NewRecorder() + f.handler.ServeHTTP(result, request) + if result.Code != http.StatusOK || !bytes.Equal(result.Body.Bytes(), read.Body.Bytes()) { + t.Fatal("exact request replay lost held result", phase, result.Code) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 7); err != nil { + t.Fatal("valid retained positive snapshot", err) + } + var after string + if err := f.store.DB().QueryRow(`SELECT body_json FROM `+table+` WHERE attempt_id=?`, a.ID).Scan(&after); err != nil || after != body || attemptState(t, f, a)+policyState(t, f) != before { + t.Fatal("read/replay/reopen changed original facts", err) + } + } + // Positive facts still undergo canonical and cross-owner validation + // before the optional negative projection is omitted. + for _, damage := range []string{"canonical", "actor"} { + bad := body + " " + if damage == "actor" { + if channel == "cli" { + var record cliAllowanceRecord + if json.Unmarshal([]byte(body), &record) != nil { + t.Fatal("fixture CLI record") + } + record.ActorID = "different-actor" + bad = encoded(record) + } else { + var record hostedAllowanceRecord + if json.Unmarshal([]byte(body), &record) != nil { + t.Fatal("fixture Hosted record") + } + record.ActorID = "different-actor" + bad = encoded(record) + } + } + if _, err := f.store.DB().Exec(`UPDATE `+table+` SET body_json=? WHERE attempt_id=?`, bad, a.ID); err != nil { + t.Fatal(err) + } + read := f.request("GET", path, f.reader, "", "") + if read.Code != http.StatusInternalServerError || !bytes.Contains(read.Body.Bytes(), []byte(`"code":"storage_unavailable"`)) || ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 7) == nil { + t.Fatal("damaged positive observation bypassed validation", damage, read.Code) + } + } + }) + } +} + +func TestHeldAllowanceLegacyPolicyZeroWithoutFacts(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + a := f.start(t, attemptProject, f.enqueue(t, attemptProject, "pre-policy-no-facts", channel, 2, 1)) + reason := "allowance_exhausted" + table := "review_cli_preflight" + if channel == "hosted" { + reason, table = "hosted_allowance_cooldown", "review_hosted_preflight" + } + var err error + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + if err != nil { + t.Fatal(err) + } + // Execution schema v3 adds this column with default zero to older rows. + if _, err := f.store.DB().Exec(`UPDATE review_operations SET policy_revision=0 WHERE id=?`, a.OperationID); err != nil { + t.Fatal(err) + } + before := attemptState(t, f, a) + check := func() { + t.Helper() + w := f.request("GET", "/api/v1/projects/"+attemptProject+"/reviews/operations/"+a.OperationID, f.reader, "", "") + var o Operation + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &o) != nil || o.PolicyRevision != 0 || o.State != "held" || o.Reason != reason || o.Allowance != nil { + t.Fatal("legacy operation without optional facts became unreadable", w.Code, w.Body.String()) + } + if attemptState(t, f, a) != before { + t.Fatal("legacy read rewrote retained history") + } + } + check() + cliAllowanceReopen(t, f) + mux := http.NewServeMux() + f.e.Register(mux) + f.handler = mux + check() + // Absence is compatible; a present malformed record must still fail closed. + if _, err := f.store.DB().Exec(`INSERT INTO `+table+`(project_id,attempt_id,body_json) VALUES(?,?,?)`, attemptProject, a.ID, `{}`); err != nil { + t.Fatal(err) + } + if w := f.request("GET", "/api/v1/projects/"+attemptProject+"/reviews/operations/"+a.OperationID, f.reader, "", ""); w.Code != 500 { + t.Fatal("present invalid facts were hidden", w.Code, w.Body.String()) + } + }) + } +} + +func TestHeldAllowanceHTTPNegotiationPreservesLegacyShapes(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var err error + reason, key := "allowance_exhausted", "allowance-request" + if channel == "cli" { + var in CLIAllowanceObservation + f, a, in = cliAllowanceFixture(t) + in.Remaining = 0 + err = f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 1, in) + } else { + var in HostedAllowanceInput + f, a, in = cooldownObservationFixture(t) + reason, key = "hosted_allowance_cooldown", "query-request" + err = f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in) + } + if err != nil { + t.Fatal(err) + } + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + if err != nil { + t.Fatal(err) + } + before := attemptState(t, f, a) + counts := attemptCount(t, f.store, "SELECT count(*) FROM receipts") + body, err := json.Marshal(Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: channel, HeadSHA: strings.Repeat("a", 40)}) + if err != nil { + t.Fatal(err) + } + for _, version := range []string{"", "1", "2", "3", "4", "unknown"} { + for _, kind := range []string{"full", "status", "enqueue-replay"} { + t.Run(version+"/"+kind, func(t *testing.T) { + path := "/api/v1/projects/" + attemptProject + "/reviews/operations/" + a.OperationID + method, token, payload := "GET", f.reader, "" + if kind == "status" { + path += "/status" + } + if kind == "enqueue-replay" { + method, token, payload, path = "POST", f.writer, string(body), "/api/v1/projects/"+attemptProject+"/reviews/requests" + } + r := httptest.NewRequest(method, path, strings.NewReader(payload)) + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("Prefer", "wait=1") + if version != "" { + r.Header.Set(operationWaitHeader, version) + } + if method == "POST" { + r.Header.Set("Idempotency-Key", key) + } + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + var fields map[string]json.RawMessage + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &fields) != nil { + t.Fatal("held response", w.Code, w.Body.String()) + } + _, allowance := fields["allowance"] + _, retry := fields["retry_not_before"] + wantAllowance := version == "3" && kind != "status" + wantRetry := version == "3" && kind == "status" && channel == "hosted" + if allowance != wantAllowance || retry != wantRetry { + t.Fatal("unnegotiated held fields or missing version3 facts", version, kind, w.Body.String()) + } + if !strings.Contains(w.Header().Get("Vary"), operationWaitHeader) && !strings.Contains(strings.Join(w.Header().Values("Vary"), ","), operationWaitHeader) { + t.Fatal("missing negotiation cache boundary") + } + }) + } + } + o, err := f.e.ReadOperation(t.Context(), operationReadScope(t, f), a.OperationID) + if err != nil || o.Allowance == nil || before != attemptState(t, f, a) || counts != attemptCount(t, f.store, "SELECT count(*) FROM receipts") { + t.Fatal("HTTP negotiation changed engine facts or replayed mutations", o, err) + } + }) + } +} + +func TestStoredUnavailableClassificationPreservesPublicErrors(t *testing.T) { + for _, tc := range []struct { + name string + makeError func() error + kind storedUnavailableKind + }{ + {"waiting intent", waitUnavailable, storedWaitingIntent}, + {"allowance", allowanceUnavailable, storedAllowanceObservation}, + {"hosted query", hostedQueryUnavailable, storedHostedQuery}, + {"hosted observation", hostedAllowanceUnavailable, storedHostedObservation}, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.makeError() + wrapped := fmt.Errorf("retained evidence: %w", err) + if !isStoredUnavailable(wrapped, tc.kind) || isStoredUnavailable(wrapped, tc.kind+1) { + t.Fatal("typed classification lost through wrapping", wrapped) + } + var failure *core.Error + if !errors.As(wrapped, &failure) || failure.Code != "storage_unavailable" || failure.Status != 500 || failure.Message != err.Error() { + t.Fatal("public error contract changed", failure) + } + recorder := httptest.NewRecorder() + core.WriteError(recorder, wrapped) + var body struct { + Error struct{ Code, Message string } + } + if recorder.Code != 500 || json.Unmarshal(recorder.Body.Bytes(), &body) != nil || body.Error.Code != failure.Code || body.Error.Message != failure.Message { + t.Fatal("typed classification escaped the public response", recorder.Code, recorder.Body.String()) + } + // Human-facing wording is deliberately not classification authority. + failure.Message = "Reworded retained evidence diagnostic." + if !isStoredUnavailable(wrapped, tc.kind) { + t.Fatal("wording edit changed classification") + } + lookalike := core.Fail("storage_unavailable", failure.Message, 500) + if isStoredUnavailable(lookalike, tc.kind) || interruptedAllowanceUnavailable(lookalike) { + t.Fatal("actual storage error acquired retained-evidence classification") + } + }) + } +} + +func TestStoredUnavailableDependencyAndRecoveryClassification(t *testing.T) { + query := fmt.Errorf("lookup: %w", newStoredUnavailable(storedHostedQuery, "Reworded query diagnostic.")) + if !storedAllowanceUnavailable(allowanceDependencyError(query)) { + t.Fatal("typed missing query did not become unusable allowance") + } + storage := core.Fail("storage_unavailable", "Stored hosted allowance query is unavailable.", 500) + if allowanceDependencyError(storage) != storage || storedAllowanceUnavailable(storage) { + t.Fatal("storage lookup failure was reclassified by wording") + } + for _, err := range []error{context.Canceled, context.DeadlineExceeded, errors.New("database failed")} { + if allowanceDependencyError(err) != err || interruptedAllowanceUnavailable(err) { + t.Fatal("real lookup failure was suppressed", err) + } + } + for _, err := range []error{allowanceUnavailable(), newStoredUnavailable(storedHostedObservation, "Reworded hosted observation diagnostic.")} { + if !interruptedAllowanceUnavailable(fmt.Errorf("recovery: %w", err)) { + t.Fatal("unusable optional evidence did not allow safe cancellation", err) + } + } + if !isWaitUnavailable(fmt.Errorf("history: %w", newStoredUnavailable(storedWaitingIntent, "Reworded history diagnostic."))) || isWaitUnavailable(core.Fail("storage_unavailable", "Stored review waiting intent is unavailable.", 500)) { + t.Fatal("history classification still depends on message text") + } +} + +func TestHeldAllowancePreservesLookupErrors(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var err error + reason := "allowance_exhausted" + if channel == "cli" { + var in CLIAllowanceObservation + f, a, in = cliAllowanceFixture(t) + in.Remaining = 0 + err = f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, a.Revision, in) + } else { + var in HostedAllowanceInput + f, a, in = cooldownObservationFixture(t) + reason = "hosted_allowance_cooldown" + err = f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision, in) + } + if err != nil { + t.Fatal(err) + } + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + if err != nil { + t.Fatal(err) + } + o, err := readOperation(t.Context(), f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + matches := []string{"FROM review_execution_attempts", "FROM review_" + channel + "_preflight", "FROM projects"} + if channel == "hosted" { + matches = []string{"FROM review_execution_attempts", "FROM review_hosted_preflight", "FROM review_hosted_allowance_queries", "FROM review_hosted_observations"} + } + for _, match := range matches { + for _, canceled := range []bool{false, true} { + q := cliRetryFailureQuery{EvidenceQuery: f.store.DB(), match: match, cancel: canceled} + allowance, err := readHeldAllowance(t.Context(), q, o) + if allowance != nil || err == nil || storedAllowanceUnavailable(err) || canceled && !errors.Is(err, context.Canceled) || !canceled && !strings.Contains(err.Error(), "missing_cli_retry_history") { + t.Errorf("held lookup reclassified: %s canceled=%t allowance=%v err=%v", match, canceled, allowance, err) + } + } + } + missing := o + missing.AttemptID = "review_attempt_" + strings.Repeat("f", 32) + if allowance, err := readHeldAllowance(t.Context(), f.store.DB(), missing); allowance != nil || !storedAllowanceUnavailable(err) { + t.Error("missing held attempt was not classified as damaged allowance evidence", allowance, err) + } + }) + } +} + +func TestWaitDependencyErrorsPreserveOperationalClassification(t *testing.T) { + for _, original := range []error{context.Canceled, context.DeadlineExceeded, sql.ErrTxDone, errors.New("database fault"), core.Fail("storage_unavailable", "Stored review admission is unavailable.", 500), core.Fail("overloaded", "Local overload", 503)} { + for _, err := range []error{original, fmt.Errorf("wrapped: %w", original)} { + if waitDependencyError(err) != err { + t.Errorf("real lookup failure changed: %v", err) + } + } + } + for _, err := range []error{sql.ErrNoRows, core.Fail("not_found", "missing", 404), newStoredUnavailable(storedReviewAdmission, "invalid anchor"), allowanceUnavailable(), hostedAllowanceUnavailable()} { + if !isWaitUnavailable(waitDependencyError(fmt.Errorf("wrapped: %w", err))) { + t.Errorf("broken retained dependency not classified: %v", err) + } + } +} diff --git a/internal/reviewexec/attempt_projection.go b/internal/reviewexec/attempt_projection.go index 61f1f4c4b..70ed64a1a 100644 --- a/internal/reviewexec/attempt_projection.go +++ b/internal/reviewexec/attempt_projection.go @@ -10,7 +10,7 @@ import ( "github.com/benhook1013/FireController/internal/reviews" ) -func probeAttemptProjection(ctx context.Context, tx *sql.Tx, operation Operation) error { +func validateAttemptProjection(ctx context.Context, tx *sql.Tx, operation Operation) error { _, err := currentReviewPull(ctx, tx, operation.ProjectID, operation.PullNumber) if err != nil && !missingCurrentPull(err) { return err @@ -61,10 +61,57 @@ func (e *Engine) PublishAttempt(ctx context.Context, project, attemptID string, } func publishJournalAttempt(ctx context.Context, tx *sql.Tx, attempt Attempt, metadata *reviews.PullInput, allowMissing bool) (reviews.Receipt, error) { - operation, err := readOperation(ctx, tx, attempt.ProjectID, attempt.OperationID) + // Publication needs journal ownership, not optional allowance presentation. + // Damaged allowance evidence must not roll back a safe local hold. + operation, err := readOperationBase(ctx, tx, attempt.ProjectID, attempt.OperationID) if err != nil { return reviews.Receipt{}, err } + if operation.AttemptID != attempt.ID { + // History may retain an unused preparation that detached before dispatch. + original, draft, err := historicalCLIDraftOperation(ctx, tx, operation, attempt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return reviews.Receipt{}, publicationConflict() + } + return reviews.Receipt{}, err + } + if !draft { + original, err = historicalCooldownOperation(ctx, tx, operation, attempt) + if err != nil { + // The helper returns this error only for a missing or mismatched + // historical cooldown. Its storage lookup failures pass through. + if isWaitUnavailable(err) { + return reviews.Receipt{}, publicationConflict() + } + return reviews.Receipt{}, err + } + if operation.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, tx, original, attempt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return reviews.Receipt{}, publicationConflict() + } + return reviews.Receipt{}, err + } + if record.Observation.Remaining != 0 { + return reviews.Receipt{}, publicationConflict() + } + } else { + record, err := readHostedAllowanceRecord(ctx, tx, original, attempt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return reviews.Receipt{}, publicationConflict() + } + return reviews.Receipt{}, err + } + if record.Input.Observation.State != "cooldown_observed" { + return reviews.Receipt{}, publicationConflict() + } + } + } + operation = original + } if operation.AttemptID != attempt.ID || operation.State != attempt.State || !validChannel(operation.Channel) || !sha.MatchString(operation.HeadSHA) { return reviews.Receipt{}, publicationConflict() } diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 2b59b5693..42f574850 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -72,6 +72,10 @@ func attemptRecordingStamp(ctx context.Context, tx *sql.Tx, o Operation, a *Atte // StartAttempt reserves both the external target and the provider account. // It does no provider work; preparing has not authorized an external action. func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, error) { + return e.startAttempt(ctx, project, id, 0) +} + +func (e *Engine) startAttempt(ctx context.Context, project, id string, draftReadyRevision int64) (Attempt, error) { var result Attempt err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { o, err := readOperation(ctx, tx, project, id) @@ -81,6 +85,12 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, if o.State != "queued" { return conflict() } + now := e.sampleExecutionTime() + // A retained quota timer is scheduling state, not permission to create + // another provider attempt before its recorded retry floor. + if o.Wait != nil && (o.Wait.Paused || o.Wait.RetryNotBefore != "" && now.Before(mustWaitTime(o.Wait.RetryNotBefore))) { + return nil + } at, err := attemptRecordingStamp(ctx, tx, o, nil, e.sampleAttemptTime()) if err != nil { return err @@ -89,7 +99,14 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, if err != nil { return err } - if c.Paused || revision != o.ConfigurationRevision { + if c.Paused { + return nil + } + compatible, err := compatibleQueuedConfiguration(ctx, tx, o, c, revision) + if err != nil { + return err + } + if !compatible { return holdOperation(ctx, tx, o, "configuration_changed", at) } capability, ok := e.capabilities[c.CapabilityID] @@ -99,6 +116,15 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, if o.CapabilityFingerprint != capability.Fingerprint { return holdOperation(ctx, tx, o, "capability_changed", at) } + if o.Channel == "cli" { + due, err := cliAccountRetryDeadline(ctx, tx, capability, now) + if err != nil { + return err + } + if now.Before(due) { + return nil + } + } allowed, err := actorAllowed(ctx, tx, project, o.ActorID, o.WorkerID) if err != nil { return err @@ -121,16 +147,24 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, return err } var repositoryID int64 + if earlier, err := e.earlierQueuedReviewIntent(ctx, tx, o, c, revision); err != nil { + return err + } else if earlier != nil { + return nil + } + if o.Reason == cliDraftWait && o.Revision != draftReadyRevision { + return nil + } if err = tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, project).Scan(&repositoryID); err != nil { return err } if e.publishAttempt != nil { - if err := probeAttemptProjection(ctx, tx, o); err != nil { + if err := validateAttemptProjection(ctx, tx, o); err != nil { return err } } var busy int - if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_execution_reservations WHERE provider=? AND action_class=? AND (account=? OR (repository_id=? AND pull_number=?))`, capability.Provider, o.Channel, capability.Account, repositoryID, o.PullNumber).Scan(&busy); err != nil { + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_execution_reservations WHERE provider=? AND action_class=? AND ((account=? AND (action_class='cli' OR repository_id=?)) OR (repository_id=? AND pull_number=?))`, capability.Provider, o.Channel, capability.Account, repositoryID, repositoryID, o.PullNumber).Scan(&busy); err != nil { return err } if busy != 0 { @@ -144,10 +178,13 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, if _, err = tx.ExecContext(ctx, `INSERT INTO review_execution_reservations(provider,repository_id,pull_number,action_class,account,attempt_id) VALUES(?,?,?,?,?,?)`, result.Provider, repositoryID, o.PullNumber, o.Channel, result.Account, result.ID); err != nil { return err } - if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state='preparing',attempt_id=?,revision=revision+1,updated_at=? WHERE id=?`, result.ID, at, o.ID); err != nil { + if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state='preparing',reason='',attempt_id=?,revision=revision+1,updated_at=? WHERE id=?`, result.ID, at, o.ID); err != nil { return err } - return e.transitionRow(ctx, tx, result, "preparing", at) + if err = e.transitionRow(ctx, tx, result, "preparing", at); err != nil { + return err + } + return core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}) }) if err == nil { e.notifyOperation(id) @@ -157,7 +194,10 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, func holdOperation(ctx context.Context, tx *sql.Tx, o Operation, reason, at string) error { _, err := tx.ExecContext(ctx, `UPDATE review_operations SET state='held',reason=?,revision=revision+1,updated_at=? WHERE id=?`, reason, at, o.ID) - return err + if err != nil { + return err + } + return core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}) } func readAttempt(ctx context.Context, tx EvidenceQuery, project, id string) (Attempt, error) { @@ -168,7 +208,7 @@ func readAttempt(ctx context.Context, tx EvidenceQuery, project, id string) (Att return a, core.Fail("not_found", "The review attempt is unavailable in this project.", 404) } if err == nil && json.Unmarshal([]byte(anchor), &a.Anchor) != nil { - return a, core.Fail("storage_unavailable", "Stored review admission is unavailable.", 500) + return a, newStoredUnavailable(storedReviewAdmission, "Stored review admission is unavailable.") } return a, err } @@ -214,7 +254,11 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision if err != nil { return err } - if !allowed || c.Paused || revision != o.ConfigurationRevision { + compatible, err := compatibleQueuedConfiguration(ctx, tx, o, c, revision) + if err != nil { + return err + } + if !allowed || !compatible { return conflict() } capability, ok := e.capabilities[c.CapabilityID] @@ -257,6 +301,9 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision if err = e.transitionRow(ctx, tx, a, "admitted", at); err != nil { return err } + if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { + return err + } result = a return nil }) @@ -323,7 +370,11 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi if _, err = tx.ExecContext(ctx, `UPDATE review_execution_attempts SET state=?,revision=?,external_id=? WHERE id=?`, state, a.Revision, a.ExternalID, a.ID); err != nil { return err } - if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,updated_at=? WHERE id=?`, state, reason, at, a.OperationID); err != nil { + operationState, operationAttempt := state, o.AttemptID + if o.Channel == "cli" && reason == cliDraftWait && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { + operationState, operationAttempt = "queued", "" + } + if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,attempt_id=?,updated_at=? WHERE id=?`, operationState, reason, operationAttempt, at, a.OperationID); err != nil { return err } if state != "posting" && state != "active" && state != "uncertain" { @@ -334,6 +385,9 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi if err = e.transitionRow(ctx, tx, a, reason, at); err != nil { return err } + if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { + return err + } if state == "completed" { if err = refreshComparisonProof(ctx, tx, project, a.OperationID); err != nil { return err @@ -365,6 +419,16 @@ func allowedTransition(from, to string) bool { return false } +// Optional allowance evidence can preserve a proven unused wait, but corrupt +// evidence must not prevent safe cancellation of undispatched preparation. +// Actual database and context failures still abort the recovery transaction. +func interruptedAllowanceUnavailable(err error) bool { + if errors.Is(err, sql.ErrNoRows) || storedAllowanceUnavailable(err) { + return true + } + return isStoredUnavailable(err, storedHostedObservation) +} + // RecoverInterrupted runs once before a new supervisor accepts work. It never // restarts a possibly dispatched action. Hosted recovery uses its retained // marker; interrupted CLI work remains uncertain until evidence settles it. @@ -403,6 +467,36 @@ func (e *Engine) RecoverInterrupted(ctx context.Context) error { if err != nil { return err } + if a.State == "preparing" && o.Channel == "hosted" { + record, readErr := readHostedAllowanceRecord(ctx, tx, o, a) + if readErr != nil && !interruptedAllowanceUnavailable(readErr) { + return readErr + } + if readErr == nil && record.Input.Observation.State == "cooldown_observed" && record.Input.Observation.RetryNotBefore.After(e.sampleExecutionTime()) { + _, scheduleErr := e.scheduleHostedCooldown(ctx, tx, x.project, x.id, a.Revision) + if scheduleErr == nil { + changed = append(changed, a.OperationID) + continue + } + var refusal *core.Error + if !errors.As(scheduleErr, &refusal) || refusal.Code != "review_cooldown_elapsed" { + return scheduleErr + } + } + } + if a.State == "preparing" && o.Channel == "cli" { + record, readErr := readCLIAllowanceRecord(ctx, tx, o, a) + if readErr != nil && !interruptedAllowanceUnavailable(readErr) { + return readErr + } + if readErr == nil && record.Observation.Remaining == 0 { + if _, err := e.scheduleCLICooldown(ctx, tx, x.project, x.id, a.Revision); err != nil { + return err + } + changed = append(changed, a.OperationID) + continue + } + } at, err := attemptRecordingStamp(ctx, tx, o, &a, now) if err != nil { return err @@ -427,6 +521,9 @@ func (e *Engine) RecoverInterrupted(ctx context.Context) error { if err = e.transitionRow(ctx, tx, a, "supervisor_interrupted", at); err != nil { return err } + if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { + return err + } changed = append(changed, a.OperationID) } return nil @@ -438,3 +535,7 @@ func (e *Engine) RecoverInterrupted(ctx context.Context) error { } return err } + +func (e *Engine) holdOperation(ctx context.Context, tx *sql.Tx, o Operation, reason, at string) error { + return holdOperation(ctx, tx, o, reason, at) +} diff --git a/internal/reviewexec/attempts_test.go b/internal/reviewexec/attempts_test.go index a9551ad64..5b599294e 100644 --- a/internal/reviewexec/attempts_test.go +++ b/internal/reviewexec/attempts_test.go @@ -212,8 +212,12 @@ func TestAttemptReservationsSerializeAccountAndExactTarget(t *testing.T) { f.configure(t, attemptProject, "test-capability", 0, false) f.configure(t, otherAttemptProject, "test-capability", 0, false) first := f.start(t, attemptProject, f.enqueue(t, attemptProject, "first", "cli", 2, 1)) + var queued Receipt for _, project := range []string{attemptProject, otherAttemptProject} { r := f.enqueue(t, project, "account-busy-"+project, "cli", 4, 1) + if project == attemptProject { + queued = r + } _, err := f.e.StartAttempt(context.Background(), project, r.ID) attemptCode(t, err, "review_busy") if strings.Contains(err.Error(), first.ID) || strings.Contains(err.Error(), first.ProjectID) { @@ -228,14 +232,23 @@ func TestAttemptReservationsSerializeAccountAndExactTarget(t *testing.T) { if _, err := f.e.Admit(context.Background(), attemptProject, first.ID, 1, attemptAnchor(attemptProject, 2), ""); err != nil { t.Fatal(err) } - // Changing configured accounts does not bypass an already occupied target. + // Enqueue rejects a live same-target intent even after changing accounts. f.configure(t, attemptProject, "other-account", 1, false) - r := f.enqueue(t, attemptProject, "same-target-other-account", "cli", 2, 2) - _, err := f.e.StartAttempt(context.Background(), attemptProject, r.ID) - attemptCode(t, err, "review_busy") + _, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "same-target-other-account", Request{ExpectedConfigurationRevision: 2, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)}) + attemptCode(t, err, "review_inflight") if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 2 { t.Fatal("busy calls created attempts") } + // Settle the existing queued request against its changed capability before + // authorizing another request for that same target. + held, err := f.e.StartAttempt(t.Context(), attemptProject, queued.ID) + if err != nil || held.ID != "" { + t.Fatal(held, err) + } + operation, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), queued.ID) + if err != nil || operation.State != "held" || operation.Reason != "configuration_changed" { + t.Fatal(operation, err) + } // A different target with the new account is independent. f.start(t, attemptProject, f.enqueue(t, attemptProject, "different-target-other-account", "cli", 4, 2)) } @@ -285,9 +298,14 @@ func TestAttemptStartHoldsChangedConfigurationOrAuthorization(t *testing.T) { if err != nil || a.ID != "" { t.Fatal("hold must not authorize an attempt", err) } + wantState, wantRevision := "held", 2 + if change == "paused" { + // A pause retains the original intent for later resumption. + wantState, wantReason, wantRevision = "queued", "", 1 + } var state, reason string var revision int - if err := f.store.DB().QueryRow(`SELECT state,reason,revision FROM review_operations WHERE id=?`, receipt.ID).Scan(&state, &reason, &revision); err != nil || state != "held" || reason != wantReason || revision != 2 { + if err := f.store.DB().QueryRow(`SELECT state,reason,revision FROM review_operations WHERE id=?`, receipt.ID).Scan(&state, &reason, &revision); err != nil || state != wantState || reason != wantReason || revision != wantRevision { t.Fatalf("held projection %s %s %d: %v", state, reason, revision, err) } if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`)+attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { @@ -585,3 +603,215 @@ func TestAttemptTerminalStatesReleaseWithoutManufacturingCoverage(t *testing.T) }) } } + +func TestAttemptExactTargetReservationRejectsDirectQueuedFixture(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + first := f.start(t, attemptProject, f.enqueue(t, attemptProject, "reserved-target", "cli", 2, 1)) + f.configure(t, attemptProject, "other-account", 1, false) + // Bypass Enqueue's review_inflight guard: a queued persisted operation + // on another account must still be stopped by StartAttempt's target lock. + id := core.NewID("review_operation") + admissionSQL(t, f, `INSERT INTO review_operations(id,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision) SELECT ?,project_id,actor_id,worker_id,2,pull_number,channel,head_sha,'queued',1,'','',created_at,updated_at,?,policy_revision FROM review_operations WHERE id=?`, id, f.e.capabilities["other-account"].Fingerprint, first.OperationID) + before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations") + _, err := f.e.StartAttempt(t.Context(), attemptProject, id) + attemptCode(t, err, "review_busy") + if after := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations"); after != before { + t.Fatal("busy target changed retained work") + } +} + +func TestAttemptRecoveryCancelsCorruptOptionalAllowance(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, corruption := range []string{"malformed", "binding", "oversized", "blob"} { + t.Run(channel+"/"+corruption, func(t *testing.T) { + f, a := interruptedAllowanceFixture(t, channel) + table := "review_" + channel + "_preflight" + switch corruption { + case "malformed": + admissionSQL(t, f, `UPDATE `+table+` SET body_json='{' WHERE attempt_id=?`, a.ID) + case "binding": + admissionSQL(t, f, `UPDATE `+table+` SET body_json=replace(body_json,'exec-project-one','exec-project-two') WHERE attempt_id=?`, a.ID) + case "oversized": + limit := 8192 + if channel == "hosted" { + limit = 16384 + } + admissionSQL(t, f, `UPDATE `+table+` SET body_json=? WHERE attempt_id=?`, strings.Repeat("x", limit+1), a.ID) + case "blob": + admissionSQL(t, f, `UPDATE `+table+` SET body_json=CAST(body_json AS BLOB) WHERE attempt_id=?`, a.ID) + } + o := cliWaitRead(t, f, a.OperationID) + var err error + if channel == "cli" { + _, err = readCLIAllowanceRecord(t.Context(), f.store.DB(), o, a) + } else { + _, err = readHostedAllowanceRecord(t.Context(), f.store.DB(), o, a) + } + if !interruptedAllowanceUnavailable(err) || (corruption == "oversized" || corruption == "blob") && !storedAllowanceUnavailable(err) { + t.Fatal("unusable retained body lost recovery classification", err) + } + assertCorruptAllowanceRecovery(t, f, a) + }) + } + } +} + +func assertCorruptAllowanceRecovery(t *testing.T, f *attemptFixture, a Attempt) { + t.Helper() + retained := func() string { + var state string + for _, table := range []string{"review_cli_preflight", "review_hosted_preflight", "review_hosted_allowance_queries", "review_hosted_observations", "review_execution_evidence", "review_round_controls", "review_round_changes", "review_round_operation_bindings", "review_round_completions"} { + state += snapshotTable(t, f, table) + } + return state + } + before := retained() + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal("corrupt optional evidence blocked recovery", err) + } + o := cliWaitRead(t, f, a.OperationID) + recovered, err := readAttempt(t.Context(), f.store.DB(), attemptProject, a.ID) + if err != nil || o.State != "cancelled" || o.Reason != "supervisor_interrupted" || o.Wait != nil || o.AttemptID != a.ID || recovered.State != "cancelled" || recovered.Revision != a.Revision+1 || recovered.Anchor != nil || recovered.Intent != "" || recovered.ExternalID != "" { + t.Fatal("corrupt optional evidence did not safely cancel unused preparation", o, recovered, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_operation_waits`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_round_completions`) != 0 { + t.Fatal("recovery created an attempt, retry, reservation, evidence or review credit") + } + if before != retained() { + t.Fatal("recovery rewrote evidence or review progress") + } + settledState := func() string { + return retained() + snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_transitions") + snapshotTable(t, f, "review_execution_reservations") + snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "events") + snapshotTable(t, f, "receipts") + } + settled := settledState() + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal("repeated recovery", err) + } + intent := "" + if o.Channel == "hosted" { + intent = "synthetic-intent-" + a.ID + } + _, err = f.e.Admit(t.Context(), attemptProject, a.ID, recovered.Revision, attemptAnchor(attemptProject, o.PullNumber), intent) + attemptCode(t, err, "review_conflict") + driver := &controlledDriver{} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal("post-recovery supervisor pass", err) + } + if driver.prepares.Load() != 0 || driver.calls.Load() != 0 || settled != settledState() { + t.Fatal("repeated recovery or supervisor pass changed settled work or contacted provider") + } +} + +func interruptedAllowanceFixture(t *testing.T, channel string) (*attemptFixture, Attempt) { + t.Helper() + if channel == "cli" { + f, a, _, _ := cliWaitFixture(t) + return f, a + } + f, a, in := cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + return f, a +} + +func TestAttemptRecoveryPreservesAllowanceStorageAndContextFailures(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, failure := range []string{"storage", "context"} { + t.Run(channel+"/"+failure, func(t *testing.T) { + f, a := interruptedAllowanceFixture(t, channel) + o := cliWaitRead(t, f, a.OperationID) + before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations") + ctx := t.Context() + if failure == "storage" { + admissionSQL(t, f, `ALTER TABLE review_`+channel+`_preflight RENAME TO unavailable_preflight`) + } else { + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + cancel() + } + var readErr error + if channel == "cli" { + _, readErr = readCLIAllowanceRecord(ctx, f.store.DB(), o, a) + } else { + _, readErr = readHostedAllowanceRecord(ctx, f.store.DB(), o, a) + } + if readErr == nil || interruptedAllowanceUnavailable(readErr) || failure == "context" && !errors.Is(readErr, context.Canceled) { + t.Fatal("allowance reader suppressed or reclassified query failure", readErr) + } + err := f.e.RecoverInterrupted(ctx) + if err == nil || interruptedAllowanceUnavailable(err) { + t.Fatal("failure was suppressed", err) + } + if failure == "context" { + attemptCode(t, err, "overloaded") + } + if after := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations"); after != before { + t.Fatal("failed recovery changed work") + } + }) + } + } +} + +func TestAttemptRecoveryPreservesCooldownReferenceStorageFailure(t *testing.T) { + f, a := interruptedAllowanceFixture(t, "hosted") + admissionSQL(t, f, `ALTER TABLE review_hosted_observations RENAME TO unavailable_observations`) + before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations") + if err := f.e.RecoverInterrupted(t.Context()); err == nil || interruptedAllowanceUnavailable(err) { + t.Fatal("reference storage failure suppressed", err) + } + if after := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations"); after != before { + t.Fatal("failed recovery changed work", a.ID) + } +} + +func TestCooldownReferencePreservesContextFailureAndClassifiesMissingEvidence(t *testing.T) { + f, a, in := cooldownObservationFixture(t) + o := cliWaitRead(t, f, a.OperationID) + query, err := readHostedQuery(t.Context(), f.store.DB(), a, o) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := validateCooldownReference(ctx, f.store.DB(), a, o, query, in); !errors.Is(err, context.Canceled) { + t.Fatal("reference lost cancellation", err) + } + admissionSQL(t, f, `DELETE FROM review_hosted_observations WHERE attempt_id=?`, a.ID) + if err := validateCooldownReference(t.Context(), f.store.DB(), a, o, query, in); !storedAllowanceUnavailable(err) { + t.Fatal("missing reference lost unavailable classification", err) + } +} + +func TestAttemptRecoveryCancelsCorruptCooldownReference(t *testing.T) { + for _, corruption := range []string{"malformed", "binding", "oversized", "blob"} { + t.Run(corruption, func(t *testing.T) { + f, a := interruptedAllowanceFixture(t, "hosted") + o := cliWaitRead(t, f, a.OperationID) + record, err := readHostedAllowanceRecord(t.Context(), f.store.DB(), o, a) + if err != nil { + t.Fatal(err) + } + query, err := readHostedQuery(t.Context(), f.store.DB(), a, o) + if err != nil { + t.Fatal(err) + } + switch corruption { + case "malformed": + admissionSQL(t, f, `UPDATE review_hosted_observations SET body_json='{' WHERE attempt_id=?`, a.ID) + case "binding": + admissionSQL(t, f, `UPDATE review_hosted_observations SET capture_bytes=capture_bytes+1 WHERE attempt_id=?`, a.ID) + case "oversized": + admissionSQL(t, f, `UPDATE review_hosted_observations SET body_json=? WHERE attempt_id=?`, strings.Repeat("x", 24577), a.ID) + case "blob": + admissionSQL(t, f, `UPDATE review_hosted_observations SET body_json=CAST(body_json AS BLOB) WHERE attempt_id=?`, a.ID) + } + if err := validateCooldownReference(t.Context(), f.store.DB(), a, o, query, record.Input); !storedAllowanceUnavailable(err) { + t.Fatal("unusable reference body lost allowance classification", err) + } + assertCorruptAllowanceRecovery(t, f, a) + }) + } +} diff --git a/internal/reviewexec/capability_test.go b/internal/reviewexec/capability_test.go index fbb99afa2..1f27d365a 100644 --- a/internal/reviewexec/capability_test.go +++ b/internal/reviewexec/capability_test.go @@ -204,6 +204,7 @@ func TestCapabilitySchemaUpgradeRetainsUnboundOperationsAndReplay(t *testing.T) before := bindingOperation(t, f, scope, oldReceipt.ID) instance := f.store.InstanceID() // Reconstruct the actual version1 table shape only in this owned fixture. + restorePreSelectionExecutionSchema(t, f) if _, err := f.store.DB().Exec(`DROP TABLE review_hosted_preflight`); err != nil { t.Fatal(err) } @@ -253,7 +254,7 @@ func TestCapabilitySchemaUpgradeRetainsUnboundOperationsAndReplay(t *testing.T) } bindEngine(t, f, bindingCapability()) var version, title, brief, worker string - if err := reopened.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "6" { + if err := reopened.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "10" { t.Fatal("migration did not advance only the domain version", err) } if err := reopened.DB().QueryRow(`SELECT title,brief,worker_id FROM jobs WHERE id='retained-job'`).Scan(&title, &brief, &worker); err != nil || title != "Retained title" || brief != "Retained exact brief" || worker != "retained-worker" { diff --git a/internal/reviewexec/cli_draft_cursor_test.go b/internal/reviewexec/cli_draft_cursor_test.go new file mode 100644 index 000000000..6e0343a77 --- /dev/null +++ b/internal/reviewexec/cli_draft_cursor_test.go @@ -0,0 +1,107 @@ +package reviewexec + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestCLIDraftProbeSelectionRotatesBeforeClaim(t *testing.T) { + now := time.Now() + e := &Engine{schedulingNow: func() time.Time { return now }} + operations := []Operation{ + {ID: "review_operation_c", Channel: "cli", Reason: cliDraftWait}, + {ID: "review_operation_a", Channel: "cli", Reason: cliDraftWait}, + {ID: "review_operation_b", Channel: "cli", Reason: cliDraftWait}, + {ID: "review_operation_0", Channel: "hosted", Reason: cliDraftWait}, + {ID: "review_operation_1", Channel: "cli"}, + } + for _, want := range []string{"review_operation_a", "review_operation_b", "review_operation_c", "review_operation_a"} { + if got := e.nextDraftProbe(operations); got != want { + t.Fatalf("selection without claim did not rotate: got %q, want %q", got, want) + } + if len(e.draftProbeNext) != 0 { + t.Fatal("selection acquired a read throttle") + } + } + e.draftProbeNext = map[string]time.Time{"review_operation_b": now.Add(cliDraftProbeInterval)} + if got := e.nextDraftProbe(operations); got != "review_operation_c" { + t.Fatal("selection ignored an existing throttle", got) + } + cursor := e.draftProbeCursor + if got := e.nextDraftProbe(nil); got != "" || e.draftProbeCursor != cursor { + t.Fatal("empty selection changed rotation", got, e.draftProbeCursor) + } +} + +func TestCLIDraftProbeDamagedWaitDoesNotStarveOtherProject(t *testing.T) { + for _, damage := range []string{"revision gap", "malformed history"} { + t.Run(damage, func(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + first := f.enqueue(t, attemptProject, "draft-cursor-first", "cli", 2, 1) + second := f.enqueue(t, otherAttemptProject, "draft-cursor-second", "cli", 2, 1) + for _, owner := range [][2]string{{attemptProject, first.ID}, {otherAttemptProject, second.ID}} { + o, err := readOperation(t.Context(), f.store.DB(), owner[0], owner[1]) + if err != nil { + t.Fatal(err) + } + if err := f.e.recordCLIDraftDecision(t.Context(), o, cliDraftWait); err != nil { + t.Fatal(err) + } + } + badID, healthyID, badProject := first.ID, second.ID, attemptProject + if second.ID < first.ID { + badID, healthyID, badProject = second.ID, first.ID, otherAttemptProject + } + for revision := int64(1); revision <= 2; revision++ { + c := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 4, 6}, Channels: []string{"cli", "hosted"}} + if revision == 2 { + c.Queue = append(c.Queue, 8) + } + if _, err := f.e.Configure(t.Context(), f.scope(t, badProject, f.admin, true), fmt.Sprintf("cursor-suffix-%d", revision), c); err != nil { + t.Fatal(err) + } + } + if damage == "revision gap" { + admissionSQL(t, f, `DELETE FROM review_execution_config WHERE project_id=? AND revision=2`, badProject) + } else { + admissionSQL(t, f, `UPDATE review_execution_config SET body_json='{' WHERE project_id=? AND revision=2`, badProject) + } + reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, errors.New("source unavailable") + }} + driver := &draftWaitDriver{reader: reader} + drivers := map[string]Driver{"test-capability": driver} + tables := []string{"review_operations", "review_execution_config", "review_execution_attempts", "review_operation_waits", "review_execution_transitions", "review_execution_reservations", "events", "receipts"} + before := make(map[string]string) + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal("damaged first wait stopped the pass", err) + } + if reader.calls.Load() != 0 || draftProbeClaimed(f.e, badID) { + t.Fatal("damaged wait reached a provider probe") + } + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal("later healthy wait stopped the pass", err) + } + if reader.calls.Load() != 1 || !draftProbeClaimed(f.e, healthyID) || draftProbeClaimed(f.e, badID) { + t.Fatal("pre-claim damage starved another project's Draft probe", reader.calls.Load()) + } + if driver.prepares.Load() != 0 || driver.calls.Load() != 0 { + t.Fatal("Draft selection authorized preparation or dispatch") + } + for _, table := range tables { + if before[table] != snapshotTable(t, f, table) { + t.Fatal("probe rotation changed retained history", table) + } + } + }) + } +} diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go new file mode 100644 index 000000000..f35930500 --- /dev/null +++ b/internal/reviewexec/cli_draft_wait.go @@ -0,0 +1,243 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "log/slog" + "math" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +const cliDraftWait = "cli_draft_wait" +const cliDraftProbeInterval = 30 * time.Second +const cliDraftProbeCapacity = 256 + +// The wait itself is durable. Only the read throttle is process-local, so a +// restart can observe readiness again without creating a new review request. +func (e *Engine) claimDraftProbe(id string) bool { + now := e.sampleExecutionTime() + e.draftProbeMu.Lock() + defer e.draftProbeMu.Unlock() + if e.draftProbeNext[id].After(now) { + return false + } + for key, next := range e.draftProbeNext { + if !next.After(now) { + delete(e.draftProbeNext, key) + } + } + if len(e.draftProbeNext) >= cliDraftProbeCapacity { + return false + } + if e.draftProbeNext == nil { + e.draftProbeNext = make(map[string]time.Time) + } + e.draftProbeNext[id] = now.Add(cliDraftProbeInterval) + e.draftProbeCursor = id + return true +} + +// Pick one eligible wait per scheduling pass, rotating even when an earlier +// probe's throttle has already expired. The cursor grants no readiness and +// holds no capacity; claimDraftProbe still serializes the actual read throttle. +func (e *Engine) nextDraftProbe(operations []Operation) string { + now := e.sampleExecutionTime() + e.draftProbeMu.Lock() + defer e.draftProbeMu.Unlock() + var first, next string + for _, o := range operations { + if o.Channel != "cli" || o.Reason != cliDraftWait || e.draftProbeNext[o.ID].After(now) { + continue + } + if first == "" || o.ID < first { + first = o.ID + } + if o.ID > e.draftProbeCursor && (next == "" || o.ID < next) { + next = o.ID + } + } + selected := first + if next != "" { + selected = next + } + if selected != "" { + // Selection must rotate even if local validation fails before claim. + e.draftProbeCursor = selected + } + return selected +} + +// This check only decides whether the same explicit request may reach normal +// preparation. It does not establish an anchor, allowance or permission to +// dispatch. Runtime preparation and final admission still make fresh checks. +func (e *Engine) checkCLIDraft(ctx context.Context, o Operation, drivers map[string]Driver) (proceed, ready, explicit bool, err error) { + waiting := o.Reason == cliDraftWait + if o.Channel != "cli" { + return true, false, false, nil + } + var execution ExecutionContext + var selected bool + err = e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + current, err := readOperationBase(ctx, tx, o.ProjectID, o.ID) + if err != nil { + return err + } + if current.State != "queued" || current.Revision != o.Revision { + return conflict() + } + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections WHERE project_id=? AND operation_id=?)`, o.ProjectID, o.ID).Scan(&selected); err != nil || selected { + return err + } + execution, err = e.currentExecutionContext(ctx, tx, current) + return err + }) + if err != nil { + var refusal *core.Error + if errors.As(err, &refusal) { + if refusal.Code == "overloaded" { + return false, false, false, nil + } + if refusal.Status >= 400 && refusal.Status < 500 { + // Let the normal claim settle a local refusal. A draft wait + // cannot acquire a reservation without a positive source check. + return true, false, false, nil + } + } + return false, false, false, err + } + if selected { + return true, false, false, nil + } + registered := drivers[execution.Configuration.CapabilityID] + if registered == nil { + if waiting { + // A missing driver cannot establish Draft readiness. Settle the + // local capability hold without inventing readiness or an attempt. + return false, false, false, e.recordCLIDraftDecision(ctx, o, "capability_unavailable") + } + return true, false, false, nil + } + driver, ok := registered.(interface{ SourceReader() TargetReader }) + var reader TargetReader + if ok { + reader = driver.SourceReader() + } + if reader == nil { + // Reuse the bounded probe throttle for diagnostics without attempting + // a provider read or changing the retained request's identity. + if waiting && e.claimDraftProbe(o.ID) { + slog.WarnContext(ctx, "CLI draft source probe failed", "operation_id", o.ID, "provider_operation", "source_reader", "reason", "source_reader_unavailable") + } + return !waiting, false, false, nil + } + if !waiting { + // Ordinary preparation already refreshes this exact source and retains + // pull_draft as a wait. Do not duplicate those provider reads or spend + // a draft-wait probe slot before the preparation path gets its turn. + return true, false, true, nil + } + if !e.claimDraftProbe(o.ID) { + return false, false, true, nil + } + readCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + repo, err := reader.Repository(readCtx, execution.RepositoryID) + if err != nil { + // claimDraftProbe bounds these diagnostics to one probe per operation + // every 30 seconds. Never log provider bodies or credential details. + slog.WarnContext(readCtx, "CLI draft source probe failed", "operation_id", o.ID, "provider_operation", "repository", "reason", lifecycleErrorCode(err)) + return false, false, true, nil + } + if repo.ID != execution.RepositoryID || !repository.MatchString(repo.FullName) { + return false, false, true, e.recordCLIDraftDecision(ctx, o, "repository_changed") + } + pull, err := reader.Pull(readCtx, repo.FullName, o.PullNumber) + if err != nil { + slog.WarnContext(readCtx, "CLI draft source probe failed", "operation_id", o.ID, "provider_operation", "pull", "reason", lifecycleErrorCode(err)) + return false, false, true, nil + } + if !sameTarget(pull, execution.RepositoryID, o.PullNumber) || pull.HeadSHA != o.HeadSHA || pull.State != "open" || pull.Merged { + reason := "target_changed" + if obsolete := obsoleteTargetReason(pull, execution.RepositoryID, o.PullNumber, o.HeadSHA); obsolete != "" { + reason = obsolete + } + return false, false, true, e.recordCLIDraftDecision(ctx, o, reason) + } + if pull.IsDraft == nil { + slog.WarnContext(readCtx, "CLI draft source probe failed", "operation_id", o.ID, "provider_operation", "pull", "reason", "draft_state_unknown") + return false, false, true, nil + } + if *pull.IsDraft { + return false, false, false, nil + } + return true, true, true, nil +} + +func (e *Engine) recordCLIDraftDecision(ctx context.Context, o Operation, reason string) error { + changed := false + err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + current, err := readOperationBase(ctx, tx, o.ProjectID, o.ID) + if err != nil || current.State != "queued" || current.Revision != o.Revision { + return err + } + if current.Channel != "cli" || current.AttemptID != "" || current.Revision == math.MaxInt64 { + return conflict() + } + at, err := attemptRecordingStamp(ctx, tx, current, nil, e.sampleAttemptTime()) + if err != nil { + return err + } + if reason != cliDraftWait { + changed = true + return e.holdOperation(ctx, tx, current, reason, at) + } + if _, err := tx.ExecContext(ctx, `UPDATE review_operations SET reason=?,revision=revision+1,updated_at=? WHERE id=?`, reason, at, o.ID); err != nil { + return err + } + changed = true + return core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}) + }) + if err == nil && changed { + e.notifyOperation(o.ID) + } + return err +} + +// historicalCLIDraftOperation identifies an unused preparation detached when +// GitHub returned the PR to Draft. It supplies attribution for history only. +func historicalCLIDraftOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (Operation, bool, error) { + var reason string + if err := q.QueryRowContext(ctx, `SELECT reason FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&reason); err != nil { + return Operation{}, false, err + } + if reason != cliDraftWait { + return Operation{}, false, nil + } + if o.Channel != "cli" || a.OperationID != o.ID || a.ProjectID != o.ProjectID || a.ID == o.AttemptID || a.State != "held" || a.Revision != 2 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + return Operation{}, false, waitUnavailable() + } + var startedAt, heldAt string + var occupied bool + err := q.QueryRowContext(ctx, `SELECT first.created_at, last.created_at, + EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=first.attempt_id AND revision NOT IN (1,2)) + OR EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=first.attempt_id) + OR EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=first.attempt_id) + OR EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=first.attempt_id) + FROM review_execution_transitions first + JOIN review_execution_transitions last ON last.attempt_id=first.attempt_id AND last.revision=2 + WHERE first.attempt_id=? AND first.revision=1 AND first.state='preparing' AND first.reason='preparing' + AND last.state='held' AND first.external_id='' AND last.external_id=''`, a.ID).Scan(&startedAt, &heldAt, &occupied) + if err != nil { + return Operation{}, false, err + } + started, validStart := attemptRecordedTime(startedAt) + held, validHold := attemptRecordedTime(heldAt) + if occupied || !validStart || !validHold || held.Before(started) { + return Operation{}, false, waitUnavailable() + } + o.AttemptID, o.State, o.Reason, o.Wait = a.ID, "held", cliDraftWait, nil + return o, true, nil +} diff --git a/internal/reviewexec/cli_draft_wait_test.go b/internal/reviewexec/cli_draft_wait_test.go new file mode 100644 index 000000000..4536b87a7 --- /dev/null +++ b/internal/reviewexec/cli_draft_wait_test.go @@ -0,0 +1,798 @@ +package reviewexec + +import ( + "bytes" + "context" + "database/sql" + "errors" + "fmt" + "log/slog" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +type draftWaitDriver struct { + controlledDriver + reader TargetReader +} + +func (d *draftWaitDriver) SourceReader() TargetReader { return d.reader } + +func markCLIDraftWait(t *testing.T, f *attemptFixture, operationID string) { + t.Helper() + o := cliWaitRead(t, f, operationID) + if err := f.e.recordCLIDraftDecision(t.Context(), o, cliDraftWait); err != nil { + t.Fatal(err) + } +} + +func draftProbeClaimed(e *Engine, operationID string) bool { + e.draftProbeMu.Lock() + defer e.draftProbeMu.Unlock() + _, claimed := e.draftProbeNext[operationID] + return claimed +} + +func TestSlowCLIDraftProbesLeaveOtherProjectSchedulable(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + seed := f.enqueue(t, attemptProject, "slow-draft-prefix", "cli", 2, 1) + for i := range 31 { + schedulerQueuedCopy(t, f, seed.ID, fmt.Sprintf("review_operation_slowdraft%03d", i)) + } + admissionSQL(t, f, `UPDATE review_operations SET reason=? WHERE project_id=?`, cliDraftWait, attemptProject) + entered := make(chan struct{}, 2) + var active, peak atomic.Int32 + reader := &refreshTestReader{repository: func(ctx context.Context, _ int64) (reviewprovider.Repository, error) { + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 10*time.Second { + t.Error("draft probe has no finite provider deadline") + } + n := active.Add(1) + defer active.Add(-1) + for old := peak.Load(); n > old && !peak.CompareAndSwap(old, n); old = peak.Load() { + } + entered <- struct{}{} + <-ctx.Done() + return reviewprovider.Repository{}, ctx.Err() + }} + d := &draftWaitDriver{reader: reader} + stop := runSupervisor(t, f, d) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("draft probe never started") + } + healthy := f.enqueue(t, otherAttemptProject, "ready-during-slow-probe", "cli", 2, 1) + waitOperationState(t, f, healthy.ID, "completed") + if d.prepares.Load() != 1 || d.calls.Load() != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts WHERE project_id=?`, attemptProject) != 0 { + t.Fatal("draft probe consumed an attempt or ready request dispatched twice") + } + stop() + if peak.Load() != 1 || active.Load() != 0 { + t.Fatal("both dispatch workers probed Drafts or shutdown leaked a probe", peak.Load(), active.Load()) + } +} + +func TestCLIDraftProbePassIsBoundedAndRotatesAfterTimeout(t *testing.T) { + f := supervisorFixture(t) + seed := f.enqueue(t, attemptProject, "rotating-draft-probes", "cli", 2, 1) + for i := range 2 { + schedulerQueuedCopy(t, f, seed.ID, fmt.Sprintf("review_operation_rotate%03d", i)) + } + admissionSQL(t, f, `UPDATE review_operations SET reason=?`, cliDraftWait) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + reader := &refreshTestReader{repository: func(ctx context.Context, _ int64) (reviewprovider.Repository, error) { + short, cancel := context.WithTimeout(ctx, time.Millisecond) + defer cancel() + <-short.Done() + return reviewprovider.Repository{}, short.Err() + }} + d := &draftWaitDriver{reader: reader} + seen := map[string]bool{} + for pass := range 3 { + before := reader.calls.Load() + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": d}); err != nil { + t.Fatal(err) + } + if reader.calls.Load()-before != 1 { + t.Fatal("one scheduling pass performed multiple Draft probes", pass, reader.calls.Load()-before) + } + f.e.draftProbeMu.Lock() + for id, next := range f.e.draftProbeNext { + if next.After(now) { + if seen[id] { + t.Error("expired early probe starved a later wait", id) + } + seen[id] = true + } + } + f.e.draftProbeMu.Unlock() + now = now.Add(cliDraftProbeInterval) + } + if len(seen) != 3 || d.prepares.Load() != 0 || d.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 { + t.Fatal("probe rotation skipped a wait or acquired review capacity", seen) + } +} + +func TestSupervisorNonDraftSelectionSkipsDraftPrefix(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + seed := f.enqueue(t, attemptProject, "draft-candidate-prefix", "cli", 2, 1) + healthy := f.enqueue(t, otherAttemptProject, "ready-after-draft-prefix", "cli", 2, 1) + // Legacy imported rows can exceed ordinary admission's smaller capacity. + // The non-probing worker must exclude them before its 256-row window. + for i := range 299 { + schedulerQueuedCopy(t, f, seed.ID, fmt.Sprintf("review_operation_prefix%03d", i)) + } + admissionSQL(t, f, `UPDATE review_operations SET reason=? WHERE project_id=?`, cliDraftWait, attemptProject) + operations, err := f.e.pendingForWorker(t.Context(), false) + if err != nil || len(operations) != 1 || operations[0].ID != healthy.ID { + t.Fatal("draft prefix hid independent ready operation", len(operations), err) + } + d := &draftWaitDriver{reader: &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + t.Error("non-probing worker attempted a Draft provider read") + return reviewprovider.Repository{}, context.DeadlineExceeded + }}} + if err := f.e.processNextForWorker(t.Context(), map[string]Driver{"test-capability": d, "other-account": d}, false); err != nil { + t.Fatal(err) + } + if supervisorOperationState(t, f, healthy.ID) != "completed" || d.prepares.Load() != 1 || d.calls.Load() != 1 { + t.Fatal("independent ready work did not dispatch exactly once") + } +} + +func TestOrdinaryCLIRequestUsesPreparationWithoutDraftProbe(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "ordinary-cli-no-draft-probe", "cli", 2, 1) + reader := &refreshTestReader{} + d := &draftWaitDriver{reader: reader} + d.prepare = func(ctx context.Context, o Operation, c Configuration, _ Attempt) (Preparation, error) { + _, err := ResolveSource(ctx, reader, 801, c, Request{PullNumber: o.PullNumber, Channel: o.Channel, HeadSHA: o.HeadSHA}) + if err != nil { + return Preparation{}, err + } + return Preparation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber)}, nil + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": d}); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.State != "completed" || d.prepares.Load() != 1 || d.calls.Load() != 1 { + t.Fatal("ordinary CLI request did not use normal preparation", got, d.prepares.Load(), d.calls.Load()) + } + if reader.calls.Load() != 2 { + t.Fatalf("ordinary request made %d provider reads, want only the repository and pull reads from preparation", reader.calls.Load()) + } + if draftProbeClaimed(f.e, request.ID) { + t.Fatal("ordinary preparation consumed a draft-probe slot") + } +} + +func TestOrdinaryCLIPreparationRetainsFirstDraftDiscovery(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "ordinary-cli-discovers-draft", "cli", 2, 1) + draft := true + reader := &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }} + d := &draftWaitDriver{reader: reader} + d.prepare = func(ctx context.Context, o Operation, c Configuration, _ Attempt) (Preparation, error) { + _, err := ResolveSource(ctx, reader, 801, c, Request{PullNumber: o.PullNumber, Channel: o.Channel, HeadSHA: o.HeadSHA}) + return Preparation{}, err + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": d}); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.State != "queued" || got.Reason != cliDraftWait || got.AttemptID != "" || d.prepares.Load() != 1 || d.calls.Load() != 0 { + t.Fatal("first draft discovery did not retain the explicit request through preparation", got, d.prepares.Load(), d.calls.Load()) + } + if reader.calls.Load() != 2 || draftProbeClaimed(f.e, request.ID) { + t.Fatalf("first discovery used %d source reads or consumed a wait-probe slot", reader.calls.Load()) + } + if attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("draft discovered during preparation retained an unused reservation") + } +} + +func TestSourceLessOrdinaryCLIDraftRefusalIsNotRetainedAsWait(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "ordinary-cli-source-less-draft", "cli", 2, 1) + d := &controlledDriver{prepare: func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + return Preparation{}, sourceHold("pull_draft") + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": d}); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.State != "held" || got.Reason != "pull_draft" || got.Reason == cliDraftWait || d.prepares.Load() != 1 || d.calls.Load() != 0 { + t.Fatal("source-less preparation gained an unprobeable retained Draft wait", got, d.prepares.Load(), d.calls.Load()) + } +} + +func TestExplicitCLIDraftWaitReusesIntentAndLeavesIndependentWorkEligible(t *testing.T) { + f := supervisorFixture(t) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + draft := true + reader := &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + isDraft := number == 2 && draft + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &isDraft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }} + d := &draftWaitDriver{reader: reader} + drivers := map[string]Driver{"test-capability": d} + request := f.enqueue(t, attemptProject, "cli-wait-original", "cli", 2, 1) + run := func() { + t.Helper() + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + } + read := func(id string) Operation { + t.Helper() + op, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), id) + if err != nil { + t.Fatal(err) + } + return op + } + markCLIDraftWait(t, f, request.ID) + run() + waiting := read(request.ID) + if waiting.State != "queued" || waiting.Reason != cliDraftWait || waiting.AttemptID != "" || waiting.Wait != nil || d.prepares.Load() != 0 || reader.calls.Load() != 2 || !draftProbeClaimed(f.e, request.ID) || attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("Draft consumed preparation or quota", waiting) + } + if replay := f.enqueue(t, attemptProject, "cli-wait-original", "cli", 2, 1); replay.ID != request.ID { + t.Fatal("same key created another operation", replay) + } + other := f.enqueue(t, attemptProject, "cli-wait-independent", "cli", 4, 1) + now = now.Add(cliDraftProbeInterval) + run() + if read(other.ID).State != "completed" || read(request.ID).Revision != waiting.Revision || d.calls.Load() != 1 { + t.Fatal("waiting Draft blocked independent work or churned its state") + } + + control := func(action string) { + t.Helper() + _, err := f.e.ControlOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), "cli-wait-"+action, request.ID, OperationControl{ExpectedRevision: read(request.ID).Revision, Action: action}) + if err != nil { + t.Fatal(err) + } + } + control("pause") + draft = false + now = now.Add(cliDraftProbeInterval) + run() + if read(request.ID).State != "queued" || d.calls.Load() != 1 { + t.Fatal("ready PR bypassed queued pause") + } + control("resume") + // A new engine has no in-process readiness cache and sees the durable + // queued request through the same recovery entry point used at startup. + fresh, err := New(f.store, attemptCapabilities, WithExecutionClock(func() time.Time { return now })) + if err != nil { + t.Fatal(err) + } + f.e = fresh + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + var workers sync.WaitGroup + for range 2 { + workers.Go(func() { + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Error(err) + } + }) + } + workers.Wait() + if got := read(request.ID); got.State != "completed" || got.AttemptID == "" || d.calls.Load() != 2 || d.prepares.Load() != 2 { + t.Fatal("original intent did not dispatch exactly once after restart", got, d.calls.Load(), d.prepares.Load()) + } +} + +func TestExplicitCLIDraftWaitRefusesMovedHeadAndLeavesOldTerminalHold(t *testing.T) { + f := supervisorFixture(t) + old := f.enqueue(t, attemptProject, "old-terminal-draft", "cli", 2, 1) + a := f.start(t, attemptProject, old) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "pull_draft", ""); err != nil { + t.Fatal(err) + } + request := f.enqueue(t, attemptProject, "new-draft-pinned", "cli", 2, 1) + markCLIDraftWait(t, f, request.ID) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + draft := true + head := strings.Repeat("a", 40) + d := &draftWaitDriver{reader: &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: head, BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}} + drivers := map[string]Driver{"test-capability": d} + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + draft = false + head = strings.Repeat("f", 40) + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + for id, reason := range map[string]string{old.ID: "pull_draft", request.ID: "target_superseded"} { + got, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), id) + if err != nil || got.State != "held" || got.Reason != reason { + t.Fatal("terminal hold changed or moved request became eligible", got, err) + } + } + if d.calls.Load() != 0 || d.prepares.Load() != 0 { + t.Fatal("moved or historical intent reached preparation") + } +} + +func TestExplicitCLIDraftWaitRechecksLocalAuthorityBeforeClaim(t *testing.T) { + for _, change := range []string{"revoked", "configuration", "redrafted"} { + t.Run(change, func(t *testing.T) { + f := supervisorFixture(t) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + draft := change != "redrafted" + d := &draftWaitDriver{reader: &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}} + if change == "redrafted" { + d.prepare = func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + return Preparation{}, sourceHold("pull_draft") + } + } + drivers := map[string]Driver{"test-capability": d} + request := f.enqueue(t, attemptProject, "draft-local-guard", "cli", 2, 1) + if change != "redrafted" { + markCLIDraftWait(t, f, request.ID) + } + process := func() { + t.Helper() + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + } + read := func() Operation { + t.Helper() + o, err := f.e.ReadOperation(t.Context(), evidenceReadScope(t, f, attemptProject, f.reader), request.ID) + if err != nil { + t.Fatal(err) + } + return o + } + process() + if got := read(); got.State != "queued" || got.Reason != cliDraftWait || got.AttemptID != "" { + t.Fatal("draft intent was not retained", got) + } + if attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 || d.calls.Load() != 0 { + t.Fatal("Draft reached dispatch or retained its unused reservation") + } + draft = false + now = now.Add(cliDraftProbeInterval) + want := "authorization_changed" + switch change { + case "revoked": + if _, err := f.store.DB().Exec(`UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`); err != nil { + t.Fatal(err) + } + case "configuration": + f.configure(t, attemptProject, "other-account", 1, false) + want = "configuration_changed" + case "redrafted": + d.prepare = nil + process() + if got := read(); got.State != "completed" || d.calls.Load() != 1 || d.prepares.Load() != 2 { + t.Fatal("a second readiness transition duplicated or dropped the intent", got) + } + return + } + process() + if got := read(); got.State != "held" || got.Reason != want || d.prepares.Load() != 0 { + t.Fatal("changed local authority did not stop the original request", got) + } + }) + } +} + +func TestExplicitCLIDraftWaitUsesRealQuotaBaselineOnlyAfterReadiness(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "cli", 0, 1, 3, "draft-wait-quota-rounds") + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + draft := true + d := &draftWaitDriver{reader: &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}} + d.prepare = func(ctx context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + if d.prepares.Load() == 1 { + return Preparation{}, sourceHold("pull_draft") + } + in := CLIAllowanceObservation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber), ObservedAt: stamp(), Remaining: 0, Limit: 3, FullCapacityInMS: 86400000, RollingWindowMS: 86400000, ChangedFiles: 2} + if err := f.e.RecordCLIExhaustion(ctx, o.ProjectID, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + return Preparation{}, sourceHold("allowance_exhausted") + } + drivers := map[string]Driver{"test-capability": d} + request := f.enqueue(t, attemptProject, "draft-wait-before-quota", "cli", 2, 1) + markCLIDraftWait(t, f, request.ID) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.Reason != cliDraftWait || got.Wait != nil || d.prepares.Load() != 0 { + t.Fatal("Draft wait fabricated allowance state", got) + } + draft = false + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + waiting := cliWaitRead(t, f, request.ID) + if waiting.Reason != cliDraftWait || waiting.AttemptID != "" || waiting.Wait != nil { + t.Fatal("redraft did not detach before quota", waiting) + } + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + quota := cliWaitRead(t, f, request.ID) + cliWaitDue(t, quota) + if quota.Reason != "" || d.prepares.Load() != 2 || d.calls.Load() != 0 { + t.Fatal("ready request bypassed genuine quota refusal", quota) + } + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) +} + +func TestExplicitCLIRedraftProjectsUnusedAttemptAndPreservesRestore(t *testing.T) { + for _, action := range []string{"ready", "restore", "cancel"} { + t.Run(action, func(t *testing.T) { + f := attemptProjectionFixture(t, true) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + d := &draftWaitDriver{reader: &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + draft := false + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}} + var unused Attempt + d.prepare = func(_ context.Context, _ Operation, _ Configuration, a Attempt) (Preparation, error) { + unused = a + return Preparation{}, sourceHold("pull_draft") + } + drivers := map[string]Driver{"test-capability": d} + request := f.enqueue(t, attemptProject, "draft-project-detached", "cli", 2, 1) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.State != "queued" || got.Reason != cliDraftWait || got.AttemptID != "" || got.Wait != nil { + t.Fatal("production projection did not retain queued intent", got) + } + _, projected := projectedAttempt(t, f, unused) + if projected.State != "held" || projected.Reason != cliDraftWait || attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("unused preparation did not project or retained its reservation", projected) + } + assertCLIWaitSnapshot(t, f) + control := func(action string) { + t.Helper() + op := cliWaitRead(t, f, request.ID) + if _, err := f.e.ControlOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), "redraft-"+action, op.ID, OperationControl{ExpectedRevision: op.Revision, Action: action}); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + } + switch action { + case "restore": + var summary RestoredWorkSummary + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return abandonRestoredAttempts(ctx, tx, now, &summary) + }); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.State != "held" || got.Reason != "restore_reconciled" || summary.QueuedOperations != 1 || d.calls.Load() != 0 { + t.Fatal("restore did not settle the queued intent without provider work", got, summary) + } + case "cancel": + control("cancel") + if got := cliWaitRead(t, f, request.ID); got.State != "cancelled" || d.calls.Load() != 0 { + t.Fatal("cancel did not settle the queued intent without provider work", got) + } + case "ready": + control("pause") + control("resume") + d.prepare = nil + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, request.ID); got.State != "completed" || got.AttemptID == unused.ID || d.calls.Load() != 1 { + t.Fatal("original intent did not dispatch once after redraft", got) + } + } + assertCLIWaitSnapshot(t, f) + }) + } +} + +func TestCLIDraftProbeThrottleOnlyBlocksWaitingRequests(t *testing.T) { + for _, cause := range []string{"recent", "capacity"} { + for _, waiting := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/waiting=%t", cause, waiting), func(t *testing.T) { + f := supervisorFixture(t) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + request := f.enqueue(t, attemptProject, "probe-throttled", "cli", 2, 1) + if waiting { + o, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), request.ID) + if err != nil { + t.Fatal(err) + } + if err := f.e.recordCLIDraftDecision(t.Context(), o, cliDraftWait); err != nil { + t.Fatal(err) + } + } + f.e.draftProbeNext = map[string]time.Time{} + if cause == "recent" { + f.e.draftProbeNext[request.ID] = now.Add(cliDraftProbeInterval) + } else { + for i := range cliDraftProbeCapacity { + f.e.draftProbeNext[fmt.Sprintf("other-%d", i)] = now.Add(cliDraftProbeInterval) + } + } + d := &draftWaitDriver{reader: &refreshTestReader{pull: func(context.Context, string, int64) (reviewprovider.Pull, error) { + t.Error("throttled probe still read the provider") + return reviewprovider.Pull{}, nil + }}} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": d}); err != nil { + t.Fatal(err) + } + o, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), request.ID) + if err != nil { + t.Fatal(err) + } + if waiting { + if o.State != "queued" || o.Reason != cliDraftWait || o.AttemptID != "" || d.prepares.Load() != 0 { + t.Fatal("waiting request bypassed probe throttle", o) + } + } else if o.State != "completed" || d.prepares.Load() != 1 || d.calls.Load() != 1 { + t.Fatal("ordinary request was delayed by draft probe throttle", o, d.prepares.Load(), d.calls.Load()) + } + }) + } + } +} + +func TestCLIDraftAfterThrottledProbeRetainsExplicitIntent(t *testing.T) { + for _, cause := range []string{"recent", "capacity"} { + t.Run(cause, func(t *testing.T) { + f := supervisorFixture(t) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + r := f.enqueue(t, attemptProject, "throttled-then-draft", "cli", 2, 1) + markCLIDraftWait(t, f, r.ID) + f.e.draftProbeNext = map[string]time.Time{} + if cause == "recent" { + f.e.draftProbeNext[r.ID] = now.Add(cliDraftProbeInterval) + } else { + for i := range cliDraftProbeCapacity { + f.e.draftProbeNext[fmt.Sprintf("occupied-%d", i)] = now.Add(cliDraftProbeInterval) + } + } + d := &draftWaitDriver{reader: &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + draft := false + return reviewprovider.Pull{Number: number, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}} + d.prepare = func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + return Preparation{}, sourceHold("pull_draft") + } + drivers := map[string]Driver{"test-capability": d} + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + throttled := cliWaitRead(t, f, r.ID) + if throttled.State != "queued" || throttled.Reason != cliDraftWait || throttled.AttemptID != "" || d.prepares.Load() != 0 || d.calls.Load() != 0 { + t.Fatal("throttled wait changed the explicit intent or reached preparation", throttled) + } + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + o, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), r.ID) + if err != nil || o.State != "queued" || o.Reason != cliDraftWait || o.AttemptID != "" || d.calls.Load() != 0 || d.prepares.Load() != 1 || attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("throttled probe lost explicit intent after Draft refusal", o, err) + } + now = now.Add(cliDraftProbeInterval) + d.prepare = nil + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + o, err = f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), r.ID) + if err != nil || o.ID != r.ID || o.State != "completed" || d.calls.Load() != 1 || d.prepares.Load() != 2 { + t.Fatal("retained intent did not resume once after readiness", o, err) + } + }) + } +} + +func TestCLIDraftWaitMissingDriverSettlesOriginalIntent(t *testing.T) { + for _, kind := range []string{"missing", "nil", "without-source-interface", "nil-source-reader"} { + t.Run(kind, func(t *testing.T) { + f := supervisorFixture(t) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil))) + defer slog.SetDefault(previous) + request := f.enqueue(t, attemptProject, "draft-driver-original", "cli", 2, 1) + original := cliWaitRead(t, f, request.ID) + if err := f.e.recordCLIDraftDecision(t.Context(), original, cliDraftWait); err != nil { + t.Fatal(err) + } + drivers := map[string]Driver{} + switch kind { + case "nil": + drivers["test-capability"] = nil + case "without-source-interface": + drivers["test-capability"] = &controlledDriver{} + case "nil-source-reader": + drivers["test-capability"] = &draftWaitDriver{} + } + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + got := cliWaitRead(t, f, request.ID) + missing := kind == "missing" || kind == "nil" + if missing { + if got.State != "held" || got.Reason != "capability_unavailable" || got.AttemptID != "" || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 { + t.Fatal("missing driver stranded Draft intent", got) + } + // The terminal original no longer blocks another authorized exact request. + if next := f.enqueue(t, attemptProject, "draft-driver-next", "cli", 2, 1); next.ID == request.ID { + t.Fatal("new key adopted old intent") + } + } else if got.State != "queued" || got.Reason != cliDraftWait || got.AttemptID != "" || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 { + t.Fatal("registered source-less driver changed Draft wait", got) + } + if !missing { + for range 2 { + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + } + text := output.String() + if strings.Count(text, "CLI draft source probe failed") != 1 || !strings.Contains(text, request.ID) || !strings.Contains(text, `"reason":"source_reader_unavailable"`) || !strings.Contains(text, `"provider_operation":"source_reader"`) { + t.Fatal("source-less wait diagnostic was silent or unbounded", text) + } + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + if strings.Count(output.String(), "CLI draft source probe failed") != 2 { + t.Fatal("next bounded source-less diagnostic was not observable") + } + after := cliWaitRead(t, f, request.ID) + if after.ID != got.ID || after.Revision != got.Revision || after.State != got.State || after.Reason != got.Reason || after.AttemptID != "" { + t.Fatal("source-less diagnostics changed retained intent", after) + } + } + if replay := f.enqueue(t, attemptProject, "draft-driver-original", "cli", 2, 1); replay.ID != request.ID { + t.Fatal("original request identity lost") + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("missing or source-less driver retained capacity") + } + }) + } +} + +func TestCLIDraftProbeReadFailuresAreBoundedAndSafe(t *testing.T) { + for _, stage := range []string{"repository", "pull", "unknown-draft"} { + t.Run(stage, func(t *testing.T) { + f := supervisorFixture(t) + now := time.Now() + f.e.schedulingNow = func() time.Time { return now } + r := f.enqueue(t, attemptProject, "draft-probe-failure", "cli", 2, 1) + markCLIDraftWait(t, f, r.ID) + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil))) + defer slog.SetDefault(previous) + reader := &refreshTestReader{} + failure := &reviewprovider.Error{Code: "provider_unavailable", Message: "PRIVATE_PROVIDER_BODY"} + if stage == "repository" { + reader.repository = func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, failure + } + } else if stage == "pull" { + reader.pull = func(context.Context, string, int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{}, failure + } + } else { + reader.pull = func(context.Context, string, int64) (reviewprovider.Pull, error) { + p := lifecyclePull(2) + p.IsDraft = nil + return p, nil + } + } + d := &draftWaitDriver{reader: reader} + drivers := map[string]Driver{"test-capability": d} + for range 2 { + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + } + text := output.String() + providerStage := stage + if stage == "unknown-draft" { + providerStage = "pull" + if !strings.Contains(text, `"reason":"draft_state_unknown"`) { + t.Fatal("missing unknown Draft reason", text) + } + } + if strings.Count(text, "CLI draft source probe failed") != 1 || !strings.Contains(text, r.ID) || !strings.Contains(text, `"provider_operation":"`+providerStage+`"`) || strings.Contains(text, "PRIVATE_PROVIDER_BODY") { + t.Fatal("probe failure was silent, unbounded or exposed a provider body", text) + } + now = now.Add(cliDraftProbeInterval) + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + if strings.Count(output.String(), "CLI draft source probe failed") != 2 { + t.Fatal("next bounded probe failure was not observable") + } + if got := cliWaitRead(t, f, r.ID); got.State != "queued" || got.Reason != cliDraftWait || got.AttemptID != "" || d.prepares.Load() != 0 || d.calls.Load() != 0 { + t.Fatal("provider failure changed intent or reached provider review", got) + } + }) + } +} + +type draftHistoryQuery struct { + EvidenceQuery + second string + calls int +} + +func (q *draftHistoryQuery) QueryRowContext(ctx context.Context, _ string, _ ...any) *sql.Row { + q.calls++ + if q.calls == 1 { + return q.EvidenceQuery.QueryRowContext(ctx, `SELECT 'cli_draft_wait'`) + } + return q.EvidenceQuery.QueryRowContext(ctx, q.second) +} + +func TestHistoricalCLIDraftSeparatesLookupFailureFromInvalidHistory(t *testing.T) { + f := supervisorFixture(t) + o := Operation{ID: "operation", ProjectID: attemptProject, Channel: "cli"} + a := Attempt{ID: "attempt", OperationID: o.ID, ProjectID: o.ProjectID, State: "held", Revision: 2} + for _, tc := range []struct { + name, query string + noRows, invalid bool + }{ + {"missing", `SELECT 1 WHERE 0`, true, false}, + {"storage", `SELECT * FROM nonexistent_draft_history`, false, false}, + {"invalid-time", `SELECT 'invalid', 'invalid', 0`, false, true}, + {"occupied", `SELECT '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 1`, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + q := &draftHistoryQuery{EvidenceQuery: f.store.DB(), second: tc.query} + _, draft, err := historicalCLIDraftOperation(t.Context(), q, o, a) + if draft || err == nil { + t.Fatal("invalid lookup became retained history", draft, err) + } + if tc.noRows && !errors.Is(err, sql.ErrNoRows) { + t.Fatal("missing-row identity was lost", err) + } + if tc.invalid && err.Error() != waitUnavailable().Error() { + t.Fatal("invalid history lost its classification", err) + } + if tc.name == "storage" && !strings.Contains(err.Error(), "nonexistent_draft_history") { + t.Fatal("storage error was rewritten as invalid history", err) + } + }) + } +} diff --git a/internal/reviewexec/cli_preflight.go b/internal/reviewexec/cli_preflight.go index a3c9bccbe..f35fbac16 100644 --- a/internal/reviewexec/cli_preflight.go +++ b/internal/reviewexec/cli_preflight.go @@ -38,12 +38,16 @@ type cliAllowanceRecord struct { } func validCLIAllowance(input CLIAllowanceObservation) bool { + return validCLIAllowanceObservation(input) && input.Remaining > 0 +} + +func validCLIAllowanceObservation(input CLIAllowanceObservation) bool { if len(input.ObservedAt) > 64 || len(input.Anchor.ObservedAt) > 64 { return false } observed, err := time.Parse(time.RFC3339Nano, input.ObservedAt) - return err == nil && !observed.IsZero() && input.ObservedAt == observed.UTC().Format(time.RFC3339Nano) && validEvidenceAnchor(input.Anchor) && - input.Remaining >= 1 && input.Limit >= 1 && input.Limit <= 10000 && input.Remaining <= input.Limit && input.FullCapacityInMS >= 0 && input.FullCapacityInMS <= 86400000 && input.RollingWindowMS >= 1 && input.RollingWindowMS <= 86400000 && input.ChangedFiles >= 1 && input.ChangedFiles <= 100000 + return err == nil && !observed.IsZero() && observed.Year() >= 1 && observed.Year() <= 9999 && input.ObservedAt == observed.UTC().Format(time.RFC3339Nano) && validEvidenceAnchor(input.Anchor) && + input.Remaining >= 0 && input.Limit >= 1 && input.Limit <= 10000 && input.Remaining <= input.Limit && input.FullCapacityInMS >= 0 && input.FullCapacityInMS <= 86400000 && input.RollingWindowMS >= 1 && input.RollingWindowMS <= 86400000 && input.ChangedFiles >= 1 && input.ChangedFiles <= 100000 } func freshAllowanceObservation(value string, now time.Time) bool { @@ -55,15 +59,33 @@ func freshAllowanceObservation(value string, now time.Time) bool { // a local transaction. Exact replay precedes current admission and freshness // checks; it never authorizes another provider action or refreshes old facts. func (e *Engine) RecordCLIAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input CLIAllowanceObservation) error { - if !identifier.MatchString(project) || !identifier.MatchString(attemptID) || expectedRevision < 1 || !validCLIAllowance(input) { + if !validCLIAllowance(input) { + return invalid() + } + return e.recordCLIAllowance(ctx, project, attemptID, expectedRevision, input) +} + +// RecordCLIExhaustion retains observed zero capacity without a review permit. +func (e *Engine) RecordCLIExhaustion(ctx context.Context, project, attemptID string, expectedRevision int64, input CLIAllowanceObservation) error { + if input.Remaining != 0 { + return invalid() + } + return e.recordCLIAllowance(ctx, project, attemptID, expectedRevision, input) +} + +func (e *Engine) recordCLIAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input CLIAllowanceObservation) error { + if !identifier.MatchString(project) || !identifier.MatchString(attemptID) || expectedRevision < 1 || !validCLIAllowanceObservation(input) { return invalid() } + if expectedRevision != 1 { + return conflict() + } return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { var body string err := tx.QueryRowContext(ctx, `SELECT body_json FROM review_cli_preflight WHERE project_id=? AND attempt_id=?`, project, attemptID).Scan(&body) if err == nil { var retained cliAllowanceRecord - if len(body) > 8192 || strictjson.Decode([]byte(body), &retained) != nil || retained.ProjectID != project || retained.AttemptID != attemptID || !identifier.MatchString(retained.OperationID) || !identifier.MatchString(retained.ActorID) || retained.WorkerID != "" && !identifier.MatchString(retained.WorkerID) || retained.AttemptRevision < 1 || retained.ConfigurationRevision < 1 || retained.PolicyRevision < 1 || !hash.MatchString(retained.CapabilityFingerprint) || !identifier.MatchString(retained.Provider) || !identifier.MatchString(retained.Account) || !validCLIAllowance(retained.Observation) { + if len(body) > 8192 || strictjson.Decode([]byte(body), &retained) != nil || retained.ProjectID != project || retained.AttemptID != attemptID || !identifier.MatchString(retained.OperationID) || !identifier.MatchString(retained.ActorID) || retained.WorkerID != "" && !identifier.MatchString(retained.WorkerID) || retained.AttemptRevision != 1 || retained.ConfigurationRevision < 1 || retained.PolicyRevision < 1 || !hash.MatchString(retained.CapabilityFingerprint) || !identifier.MatchString(retained.Provider) || !identifier.MatchString(retained.Account) || !validCLIAllowanceObservation(retained.Observation) { return core.Fail("storage_unavailable", "Stored CLI allowance observation is unavailable.", 500) } if retained.AttemptRevision != expectedRevision || retained.Observation != input { @@ -88,7 +110,26 @@ func (e *Engine) RecordCLIAllowance(ctx context.Context, project, attemptID stri if operation.AttemptID != attempt.ID || operation.State != "preparing" || operation.Channel != "cli" || !identifier.MatchString(operation.ActorID) || operation.WorkerID != "" && !identifier.MatchString(operation.WorkerID) || input.Anchor.PullNumber != operation.PullNumber || input.Anchor.CandidateSHA != operation.HeadSHA { return conflict() } - current, err := e.currentExecutionContext(ctx, tx, operation) + checked := operation + if input.Remaining == 0 { + // A negative observation grants no permit. Neighbor enrollment or + // ordering changes must not discard its already observed quota facts. + // Keep the record bound to the original operation/configuration, and + // still check current target membership, access, policy and controls. + configuration, revision, err := readConfiguration(ctx, tx, project) + if err != nil { + return err + } + original, err := sourceConfiguration(ctx, tx, project, operation.ConfigurationRevision) + if err != nil { + return err + } + if configuration.CapabilityID != original.CapabilityID || configuration.Mode != original.Mode { + return conflict() + } + checked.ConfigurationRevision = revision + } + current, err := e.currentExecutionContext(ctx, tx, checked) if err != nil { return err } @@ -100,7 +141,7 @@ func (e *Engine) RecordCLIAllowance(ctx context.Context, project, attemptID stri if !freshAllowanceObservation(input.ObservedAt, now) || !freshAllowanceObservation(input.Anchor.ObservedAt, now) { return invalid() } - if ceiling := current.Policy.Policy.MaxReviewFiles; ceiling > 0 && input.ChangedFiles > ceiling { + if ceiling := current.Policy.Policy.MaxReviewFiles; !current.Operation.OverrideFileLimit && ceiling > 0 && input.ChangedFiles > ceiling { return sourceHold("project_file_limit") } record := cliAllowanceRecord{ProjectID: project, AttemptID: attempt.ID, AttemptRevision: expectedRevision, OperationID: operation.ID, ActorID: operation.ActorID, WorkerID: operation.WorkerID, ConfigurationRevision: operation.ConfigurationRevision, PolicyRevision: operation.PolicyRevision, CapabilityFingerprint: operation.CapabilityFingerprint, Provider: attempt.Provider, Account: attempt.Account, Observation: input} diff --git a/internal/reviewexec/cli_preflight_test.go b/internal/reviewexec/cli_preflight_test.go index 42ff27dda..2d6269fa2 100644 --- a/internal/reviewexec/cli_preflight_test.go +++ b/internal/reviewexec/cli_preflight_test.go @@ -74,6 +74,7 @@ func cliAllowanceReopen(t *testing.T, f *attemptFixture) { func TestCLIAllowanceVersionThreeMigrationRetainsFactsAndReplayAcrossRestart(t *testing.T) { f, a, input := cliAllowanceFixture(t) journal := attemptState(t, f, a) + restorePreSelectionExecutionSchema(t, f) admissionSQL(t, f, `DROP TABLE review_cli_preflight`) admissionSQL(t, f, `DROP TABLE review_hosted_preflight`) admissionSQL(t, f, `DROP TABLE review_hosted_allowance_queries`) @@ -81,7 +82,7 @@ func TestCLIAllowanceVersionThreeMigrationRetainsFactsAndReplayAcrossRestart(t * admissionSQL(t, f, `UPDATE metadata SET value='3' WHERE key='schema:review_execution'`) cliAllowanceReopen(t, f) var version string - if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "6" || attemptState(t, f, a) != journal { + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "10" || attemptState(t, f, a) != journal { t.Fatal("migration changed retained journal", version, err) } receipts := attemptCount(t, f.store, `SELECT count(*) FROM receipts`) diff --git a/internal/reviewexec/cli_wait.go b/internal/reviewexec/cli_wait.go new file mode 100644 index 000000000..7e84d36aa --- /dev/null +++ b/internal/reviewexec/cli_wait.go @@ -0,0 +1,187 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "math" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +// CLI quota waits retain explicit requests, not a promise about provider reset. +// The account-wide backoff avoids probing once per queued PR or project. +func cliRetryDelay(previous int64) time.Duration { + if previous > 3 { + previous = 3 + } + return min(time.Minute*time.Duration(1<'' + AND rtrim(w.retry_not_before,'Z')>rtrim(?,'Z') + ORDER BY rtrim(w.retry_not_before,'Z') DESC LIMIT 1`, capability.Provider, capability.Account, now.UTC().Format(time.RFC3339Nano)).Scan(&project, &id) + } else { + err = q.QueryRowContext(ctx, `SELECT o.project_id,o.id FROM review_execution_transitions t INDEXED BY review_transitions_exhaustion_time + CROSS JOIN review_execution_attempts a ON a.id=t.attempt_id AND a.revision=t.revision + CROSS JOIN review_operations o ON o.id=a.operation_id + CROSS JOIN review_operation_waits w ON w.operation_id=o.id + WHERE o.channel='cli' AND a.provider=? AND a.account=? AND a.id<>o.attempt_id + AND t.state='held' AND t.reason='allowance_exhausted' + AND rtrim(t.created_at,'Z')>rtrim(?,'Z') + AND (SELECT count(*) FROM (SELECT 1 FROM review_execution_attempts prior + CROSS JOIN review_execution_transitions earlier INDEXED BY review_transitions_exhaustion_attempt ON earlier.attempt_id=prior.id + WHERE prior.operation_id=o.id AND earlier.state='held' AND earlier.reason='allowance_exhausted' + AND rtrim(earlier.created_at,'Z') 61*time.Second { + t.Fatal("first backoff must be local 60 seconds, not full-capacity time", delta) + } + if o.Wait.BaselineAttemptID != a.ID || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("wait lost original pin or retained capacity", o) + } + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) + priorityPending(t, f) + if early, err := f.e.StartAttempt(t.Context(), attemptProject, o.ID); err != nil || early.ID != "" { + t.Fatal("early direct claim bypassed backoff", early, err) + } + cliAllowanceReopen(t, f) + f.e.schedulingNow = func() time.Time { return *now } + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + if after := cliWaitRead(t, f, o.ID); !reflect.DeepEqual(o, after) { + t.Fatal("restart changed queued intent", after) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 10); err != nil { + t.Fatal("detached exhaustion invalidates backup validation", err) + } + *now = due + priorityPending(t, f, o.ID) + next := f.start(t, attemptProject, Receipt{ID: o.ID}) + if next.ID == a.ID || next.OperationID != a.OperationID { + t.Fatal("retry did not retain operation identity", next) + } + baseline, err := f.e.RetryBaseline(t.Context(), attemptProject, o.ID) + if err != nil || baseline == nil || *baseline != in.Anchor { + t.Fatal("retry lost original comparison pin", baseline, err) + } + if disposable, err := f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, due.Add(time.Hour)); err != nil || !disposable { + t.Fatal("detached unused workspace cannot be reclaimed", disposable, err) + } + if original != snapshotTable(t, f, "review_cli_preflight") { + t.Fatal("retry rewrote exhaustion evidence") + } + if err := f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal("exact original evidence replay failed after detachment", err) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 10); err != nil { + t.Fatal("historical allowance invalid after next attempt", err) + } + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) +} + +func TestCLIWaitBackoffIsBoundedAndFirstComparisonIsRetained(t *testing.T) { + f, a, in, now := cliWaitFixture(t) + first := a.ID + firstAnchor := in.Anchor + for i, delay := range []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 5 * time.Minute, 5 * time.Minute} { + if i > 0 { + in.ObservedAt = stamp() + in.Anchor.ObservedAt = stamp() + if err := f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal("later exhaustion observation", err) + } + } + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal("schedule exhausted attempt", i, err) + } + o := cliWaitRead(t, f, a.OperationID) + due := cliWaitDue(t, o) + if delta := due.Sub(*now); delta < delay-time.Second || delta > delay+time.Second || o.Wait.BaselineAttemptID != first { + t.Fatal("incorrect bounded backoff or baseline", i, delta, o.Wait) + } + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 10); err != nil { + t.Fatal("detached historical allowance validation", i, err) + } + baseline, err := f.e.RetryBaseline(t.Context(), attemptProject, o.ID) + if err != nil || baseline == nil || *baseline != firstAnchor { + t.Fatal("later exhaustion replaced the originally authorized comparison", i, baseline, err) + } + *now = due + a = f.start(t, attemptProject, Receipt{ID: o.ID}) + } + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) +} + +func TestCLIWaitPauseResumeCancelNeverDispatchesOrReopensHistory(t *testing.T) { + for _, action := range []string{"pause", "cancel"} { + t.Run(action, func(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + o := cliWaitRead(t, f, a.OperationID) + due := cliWaitDue(t, o) + timerControl(t, f, o.ID, action, "cli-wait-"+action) + *now = due.Add(time.Minute) + priorityPending(t, f) + claim, err := f.e.StartAttempt(t.Context(), attemptProject, o.ID) + if action == "cancel" { + attemptCode(t, err, "review_conflict") + if after := cliWaitRead(t, f, o.ID); after.State != "cancelled" || currentOperationWait(after) != nil || after.Wait == nil { + t.Fatal("cancel did not stop original intent", after) + } + cliAllowanceReopen(t, f) + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + if after := cliWaitRead(t, f, o.ID); after.State != "cancelled" { + t.Fatal("restart reopened cancelled request", after) + } + } else { + if err != nil || claim.ID != "" { + t.Fatal("paused direct claim", claim, err) + } + timerControl(t, f, o.ID, "resume", "cli-wait-resume") + resumed := cliWaitRead(t, f, o.ID) + if resumed.Wait == nil || resumed.Wait.RetryNotBefore != o.Wait.RetryNotBefore || resumed.Wait.BaselineAttemptID != a.ID { + t.Fatal("resume changed retained timer/pin", resumed) + } + priorityPending(t, f, o.ID) + } + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) + }) + } +} + +func TestCLIWaitSharedAccountBackoffSurvivesCancelWithoutBlockingOtherChannels(t *testing.T) { + for _, sameAccount := range []bool{true, false} { + t.Run(map[bool]string{true: "same-account", false: "different-account"}[sameAccount], func(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + capability := "other-account" + if sameAccount { + capability = "test-capability" + } + f.configure(t, otherAttemptProject, capability, 0, false) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + due := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + other := f.enqueue(t, otherAttemptProject, "other-explicit-cli", "cli", 2, 1) + hosted := f.enqueue(t, otherAttemptProject, "other-explicit-hosted", "hosted", 4, 1) + // Cancelling the exhausted request must not erase the shared account's + // recently observed exhaustion or let every queued PR requery at once. + timerControl(t, f, a.OperationID, "cancel", "cancel-cli-donor") + if sameAccount { + priorityPending(t, f, hosted.ID) + if early, err := f.e.StartAttempt(t.Context(), otherAttemptProject, other.ID); err != nil || early.ID != "" { + t.Fatal("direct cross-project claim bypassed account backoff", early, err) + } + } else { + priorityPending(t, f, other.ID, hosted.ID) + } + *now = due + priorityPending(t, f, other.ID, hosted.ID) + f.start(t, otherAttemptProject, other) + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) + }) + } +} + +func TestCLIWaitRequestsRespectCurrentPRRankWithoutAutomaticDiscovery(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + later := f.enqueue(t, attemptProject, "later-cli-first", "cli", 4, 1) + head := f.enqueue(t, attemptProject, "earlier-cli-second", "cli", 2, 1) + hosted := f.enqueue(t, attemptProject, "independent-hosted", "hosted", 4, 1) + priorityPending(t, f, head.ID, hosted.ID) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, later.ID); err != nil || a.ID != "" { + t.Fatal("oldest CLI request bypassed current PR order", a, err) + } + timerControl(t, f, head.ID, "pause", "pause-priority-head") + priorityPending(t, f, later.ID, hosted.ID) + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 3 { + t.Fatal("priority or waiting generated unsolicited requests") + } +} + +func TestCLIWaitRecoveryRequiresProvenUnusedExhaustion(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + cliAllowanceReopen(t, f) + f.e.schedulingNow = func() time.Time { return *now } + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + o := cliWaitRead(t, f, a.OperationID) + cliWaitDue(t, o) + assertCLIWaitNoCredit(t, f) + assertCLIWaitSnapshot(t, f) + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 10); err != nil { + t.Fatal("recovery lost retained exhaustion evidence", err) + } +} + +func TestCLIWaitDoesNotReopenTerminalQuotaHold(t *testing.T) { + f, a, _, _ := cliWaitFixture(t) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "allowance_exhausted", ""); err != nil { + t.Fatal(err) + } + before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision+1); err == nil { + t.Fatal("old terminal quota hold reopened without a new authorized request") + } + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + if after := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts"); before != after { + t.Fatal("terminal quota history changed") + } + assertCLIWaitNoCredit(t, f) +} + +func TestCLIWaitRecoveryDoesNotRetryPositiveUnusedPermit(t *testing.T) { + f, a, in := cliAllowanceFixture(t) + if err := f.e.RecordCLIAllowance(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + cliAllowanceReopen(t, f) + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + if o := cliWaitRead(t, f, a.OperationID); o.State != "cancelled" || o.Wait != nil { + t.Fatal("startup reused a positive old permit", o) + } +} + +func TestCLIWaitRejectsDuplicateNewKeyButReplaysOriginalRequest(t *testing.T) { + f, a, _, _ := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + scope := f.scope(t, attemptProject, f.writer, false) + request := Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)} + before := attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) + if _, err := f.e.Enqueue(t.Context(), scope, "duplicate-cli-new-key", request); err == nil { + t.Fatal("a new key purchased a second pending CLI round") + } else { + attemptCode(t, err, "review_inflight") + } + replayed, err := f.e.Enqueue(t.Context(), scope, "cli-wait-request", request) + if err != nil { + t.Fatal("original request receipt stopped replaying while queued", err) + } + var receipt Receipt + if err := json.Unmarshal(replayed, &receipt); err != nil || receipt.ID != a.OperationID || receipt.State != "queued" { + t.Fatal("replay manufactured a different request", receipt, err) + } + if after := attemptCount(t, f.store, `SELECT count(*) FROM review_operations`); after != before { + t.Fatal("duplicate/replay changed operation count", before, after) + } + assertCLIWaitNoCredit(t, f) +} + +func TestCLIWaitConcurrentAccountClaimsStartOnlyOneAttempt(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + otherRequest := f.enqueue(t, otherAttemptProject, "competing-account-cli", "cli", 2, 1) + *now = cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + otherEngine, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + otherEngine.schedulingNow = f.e.schedulingNow + type result struct { + attempt Attempt + err error + } + results := make(chan result, 2) + start := make(chan struct{}) + var workers sync.WaitGroup + for _, claim := range []struct { + engine *Engine + project string + id string + }{{f.e, attemptProject, a.OperationID}, {otherEngine, otherAttemptProject, otherRequest.ID}} { + workers.Add(1) + go func() { + defer workers.Done() + <-start + attempt, err := claim.engine.StartAttempt(t.Context(), claim.project, claim.id) + results <- result{attempt, err} + }() + } + close(start) + workers.Wait() + close(results) + claimed := 0 + for result := range results { + if result.err != nil { + attemptCode(t, result.err, "review_busy") + } + if result.attempt.ID != "" { + claimed++ + } + } + if claimed != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 { + t.Fatal("quota expiry allowed concurrent shared-account attempts", claimed) + } + assertCLIWaitNoCredit(t, f) +} + +func TestOperationWaitReadsLaterExecutionSchemaWithoutLosingPause(t *testing.T) { + f := roundFixture(t) + receipt := f.enqueue(t, attemptProject, "paused-future-schema", "cli", 2, 1) + admissionSQL(t, f, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,NULL,'',1)`, receipt.ID) + admissionSQL(t, f, `UPDATE review_operations SET allow_out_of_order=1,override_file_limit=1 WHERE id=?`, receipt.ID) + scope := f.scope(t, attemptProject, f.writer, false) + before, err := f.e.ReadOperation(t.Context(), scope, receipt.ID) + if err != nil || before.Wait == nil || !before.Wait.Paused || !before.AllowOutOfOrder || !before.OverrideFileLimit { + t.Fatal("invalid paused operation baseline", before, err) + } + for _, version := range []string{"9", "10", "11", "12", "100"} { + t.Run(version, func(t *testing.T) { + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_execution'`, version) + after, err := f.e.ReadOperation(t.Context(), scope, receipt.ID) + if err != nil || !reflect.DeepEqual(before, after) { + t.Fatal("later execution schema changed retained operation", before, after, err) + } + status, err := f.e.ReadOperationStatus(t.Context(), scope, receipt.ID) + if err != nil || status.ID != receipt.ID || !reflect.DeepEqual(before.Wait, status.Wait) { + t.Fatal("compact status dropped retained pause", status, err) + } + }) + } +} + +func TestOperationReadsSchemaFlagBoundaries(t *testing.T) { + f := roundFixture(t) + receipt := f.enqueue(t, attemptProject, "schema-flag-boundaries", "cli", 2, 1) + admissionSQL(t, f, `UPDATE review_operations SET allow_out_of_order=1,override_file_limit=1 WHERE id=?`, receipt.ID) + scope := f.scope(t, attemptProject, f.writer, false) + for _, tc := range []struct { + version string + order, limit bool + }{{"1", false, false}, {"6", false, false}, {"7", true, false}, {"8", true, true}} { + t.Run(tc.version, func(t *testing.T) { + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_execution'`, tc.version) + o, err := f.e.ReadOperation(t.Context(), scope, receipt.ID) + if err != nil || o.ID != receipt.ID || o.AllowOutOfOrder != tc.order || o.OverrideFileLimit != tc.limit || o.Wait != nil { + t.Fatal("incorrect legacy flags", o, err) + } + }) + } +} + +func TestOperationReadsRejectMalformedExecutionSchema(t *testing.T) { + f := roundFixture(t) + receipt := f.enqueue(t, attemptProject, "malformed-execution-schema", "cli", 2, 1) + scope := f.scope(t, attemptProject, f.writer, false) + for _, version := range []string{"", "0", "-1", "+11", "011", " 11", "11 ", "11\n", "1.1", "eleven", "999999999999999999999999999999"} { + t.Run(version, func(t *testing.T) { + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_execution'`, version) + o, err := f.e.ReadOperation(t.Context(), scope, receipt.ID) + if err == nil || !reflect.DeepEqual(o, Operation{}) { + t.Fatal("malformed schema returned operation", o, err) + } + attemptCode(t, err, "storage_unavailable") + status, err := f.e.ReadOperationStatus(t.Context(), scope, receipt.ID) + if err == nil || !reflect.DeepEqual(status, OperationStatus{}) { + t.Fatal("malformed schema returned compact status", status, err) + } + attemptCode(t, err, "storage_unavailable") + }) + } +} + +func TestCLISharedQuotaHTTPDiagnostics(t *testing.T) { + for _, mode := range []string{"shared", "cancelled-origin", "expired", "other-account", "changed-binding", "changed-fingerprint"} { + t.Run(mode, func(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + capability := "test-capability" + if mode == "other-account" { + capability = "other-account" + } + f.configure(t, otherAttemptProject, capability, 0, false) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + other := f.enqueue(t, otherAttemptProject, "diagnostic-cli", "cli", 2, 1) + if mode == "cancelled-origin" { + timerControl(t, f, a.OperationID, "cancel", "cancel-diagnostic-origin") + } + if mode == "expired" { + *now = cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + } + if mode == "changed-binding" { + f.configure(t, otherAttemptProject, "other-account", 1, false) + } + if mode == "changed-fingerprint" { + changed := f.e.capabilities[capability] + changed.Fingerprint = strings.Repeat("f", 64) + f.e.capabilities[capability] = changed + } + mux := http.NewServeMux() + f.e.Register(mux) + tables := []string{"review_operations", "review_execution_attempts", "review_operation_waits", "review_cli_preflight", "review_execution_reservations", "events", "receipts"} + before := make(map[string]string) + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + for _, suffix := range []string{"", "/status"} { + for _, version := range []string{"", "1", "2", "3"} { + req := httptest.NewRequest("GET", "/api/v1/projects/"+otherAttemptProject+"/reviews/operations/"+other.ID+suffix, nil) + req.Header.Set("Authorization", "Bearer "+f.other) + req.Header.Set(operationWaitHeader, version) + w := httptest.NewRecorder() + mux.ServeHTTP(w, req) + want := "" + if mode == "shared" || mode == "cancelled-origin" { + want = "cli_quota_wait" + } + if w.Code != http.StatusOK || w.Header().Get("X-FC-Review-Queued") != want { + t.Fatalf("%s schema %q: %d %v %s", suffix, version, w.Code, w.Header(), w.Body.String()) + } + var body map[string]any + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["state"] != "queued" || body["wait"] != nil || body["allowance"] != nil { + t.Fatal("diagnostic fabricated operation facts", body) + } + req = httptest.NewRequest("GET", "/api/v1/projects/"+attemptProject+"/reviews/operations/"+other.ID+suffix, nil) + req.Header.Set("Authorization", "Bearer "+f.writer) + w = httptest.NewRecorder() + mux.ServeHTTP(w, req) + if w.Code == http.StatusOK || w.Header().Get("X-FC-Review-Queued") != "" { + t.Fatal("cross-project diagnostic leaked", w.Code, w.Header()) + } + } + } + for _, table := range tables { + if before[table] != snapshotTable(t, f, table) { + t.Fatal("read changed state", table) + } + } + }) + } +} + +// Retained audit history can be invalid without remaining a live account timer. +// The same sampled instant governs candidate selection and the admission guard. +func TestCLIAccountRetryDeadlineFutureHistory(t *testing.T) { + for _, tc := range []struct { + name string + offset time.Duration + corrupt, otherAccount bool + }{ + {"before", -time.Nanosecond, false, false}, + {"exact", 0, false, false}, + {"after", time.Nanosecond, false, false}, + {"corrupt-before", -time.Nanosecond, true, false}, + {"corrupt-exact", 0, true, false}, + {"corrupt-after", time.Nanosecond, true, false}, + {"other-account-corrupt-before", -time.Nanosecond, true, true}, + {"other-account-corrupt-after", time.Nanosecond, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + capability := "test-capability" + if tc.otherAccount { + capability = "other-account" + } + f.configure(t, otherAttemptProject, capability, 0, false) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + due := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + other := f.enqueue(t, otherAttemptProject, "future-history-cli", "cli", 2, 1) + timerControl(t, f, a.OperationID, "cancel", "cancel-future-history") + if tc.corrupt { + admissionSQL(t, f, `UPDATE review_cli_preflight SET body_json='{}' WHERE attempt_id=?`, a.ID) + } + *now = due.Add(tc.offset) + live := tc.offset < 0 && !tc.otherAccount + invalid := live && tc.corrupt + tables := []string{"review_operations", "review_execution_attempts", "review_execution_transitions", "review_operation_waits", "review_cli_preflight", "review_execution_reservations", "events", "receipts"} + before := make(map[string]string) + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + got, err := cliAccountRetryDeadline(t.Context(), f.store.DB(), f.e.capabilities[capability], *now) + if invalid { + if !isWaitUnavailable(err) || !got.IsZero() { + t.Error("invalid live history was accepted", got, err) + } + } else if err != nil || live && !got.Equal(due) || !live && !got.IsZero() { + t.Error("deadline does not describe only future account history", got, due, err) + } + pending, err := f.e.pending(t.Context()) + if invalid { + if err != nil || len(pending) != 0 { + t.Error("pending did not isolate invalid live history", pending, err) + } + } else if err != nil || live && len(pending) != 0 || !live && (len(pending) != 1 || pending[0].ID != other.ID) { + t.Error("pending used expired or unrelated account history", pending, err) + } + scope := f.scope(t, otherAttemptProject, f.other, false) + if got := f.e.sharedCLIQuotaWait(t.Context(), scope, other.ID); got != (live && !invalid) { + t.Error("shared quota diagnostic differs from live validated deadline", got) + } + for _, table := range tables { + if before[table] != snapshotTable(t, f, table) { + t.Fatal("lookup changed retained history", table) + } + } + claim, err := f.e.StartAttempt(t.Context(), otherAttemptProject, other.ID) + if invalid { + if !isWaitUnavailable(err) || claim.ID != "" { + t.Error("claim accepted invalid live history", claim, err) + } + } else if err != nil || live && claim.ID != "" || !live && claim.ID == "" { + t.Error("claim used expired or unrelated account history", claim, err) + } + for _, table := range []string{"review_operation_waits", "review_cli_preflight"} { + if before[table] != snapshotTable(t, f, table) { + t.Fatal("admission changed retained cooldown history", table) + } + } + if tc.corrupt { + if _, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, a.OperationID); !isWaitUnavailable(err) { + t.Fatal("historical read stopped validating the corrupt audit record", err) + } + } else { + assertCLIWaitSnapshot(t, f) + } + assertCLIWaitNoCredit(t, f) + }) + } +} + +func TestCLIAccountRetryDeadlineLatestWithinSameMillisecond(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + // Leave room above creation times for two real retained exhaustion records. + *now = now.Add(10 * time.Second).Truncate(time.Second) + firstEnded := *now + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + firstDue := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + timerControl(t, f, a.OperationID, "cancel", "cancel-first-deadline") + *now = firstDue + b := f.start(t, otherAttemptProject, f.enqueue(t, otherAttemptProject, "second-deadline", "cli", 2, 1)) + in := CLIAllowanceObservation{Anchor: attemptAnchor(otherAttemptProject, 2), ObservedAt: stamp(), Remaining: 0, Limit: 3, FullCapacityInMS: 86400000, RollingWindowMS: 86400000, ChangedFiles: 2} + if err := f.e.RecordCLIExhaustion(t.Context(), otherAttemptProject, b.ID, b.Revision, in); err != nil { + t.Fatal(err) + } + *now = firstEnded.Add(time.Nanosecond) + if _, err := f.e.ScheduleCLICooldown(t.Context(), otherAttemptProject, b.ID, b.Revision); err != nil { + t.Fatal(err) + } + second, err := readOperation(t.Context(), f.store.DB(), otherAttemptProject, b.OperationID) + if err != nil { + t.Fatal(err) + } + secondDue := cliWaitDue(t, second) + if !secondDue.Equal(firstDue.Add(time.Nanosecond)) { + t.Fatal("fixture did not retain adjacent deadlines", firstDue, secondDue) + } + assertCLIWaitSnapshot(t, f) + for _, at := range []time.Time{firstDue.Add(-time.Nanosecond), firstDue, secondDue, secondDue.Add(time.Nanosecond)} { + got, err := cliAccountRetryDeadline(t.Context(), f.store.DB(), f.e.capabilities["test-capability"], at) + if err != nil || at.Before(secondDue) && !got.Equal(secondDue) || !at.Before(secondDue) && !got.IsZero() { + t.Error("same-millisecond ordering lost the latest live deadline", at, got, err) + } + } +} + +type cliRetryFailureQuery struct { + EvidenceQuery + match string + cancel bool +} + +func (q cliRetryFailureQuery) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + if strings.Contains(query, q.match) { + if q.cancel { + canceled, cancel := context.WithCancel(ctx) + cancel() + return q.EvidenceQuery.QueryRowContext(canceled, query, args...) + } + return q.EvidenceQuery.QueryRowContext(ctx, `SELECT * FROM missing_cli_retry_history`) + } + return q.EvidenceQuery.QueryRowContext(ctx, query, args...) +} + +type cliExhaustionCountQuery struct { + EvidenceQuery + t *testing.T + previous int64 +} + +func (q *cliExhaustionCountQuery) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + if strings.Contains(query, "SELECT count(*)") { + if err := q.EvidenceQuery.QueryRowContext(ctx, query, args...).Scan(&q.previous); err != nil { + q.t.Fatal(err) + } + } + return q.EvidenceQuery.QueryRowContext(ctx, query, args...) +} + +func TestCLIExhaustionDeadlineBoundsHistoryCount(t *testing.T) { + f, a, _, _ := cliWaitFixture(t) + a, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision) + if err != nil { + t.Fatal(err) + } + var heldAt string + if err := f.store.DB().QueryRow(`SELECT created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&heldAt); err != nil { + t.Fatal(err) + } + held := mustWaitTime(heldAt) + // Seed earlier, unrelated and future transitions in one rollback-only + // transaction. The actual SQL must count at most the three prior matches + // needed for the delay cap, not all retained history. + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + insert := func(revision int, state, reason string, at time.Time) { + t.Helper() + if _, err := tx.Exec(`INSERT INTO review_execution_transitions(attempt_id,revision,state,reason,external_id,created_at) VALUES(?,?,?,?,'',?)`, a.ID, revision, state, reason, at.Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + } + insert(100, "held", "allowance_exhausted", held.Add(time.Hour)) + insert(101, "held", "different_reason", held.Add(-time.Hour)) + insert(102, "cancelled", "allowance_exhausted", held.Add(-time.Hour)) + for previous := 0; previous <= 12; previous++ { + if previous > 0 { + insert(200+previous, "held", "allowance_exhausted", held.Add(-time.Duration(previous)*time.Minute)) + } + q := &cliExhaustionCountQuery{EvidenceQuery: tx, t: t, previous: -1} + due, err := cliExhaustionDeadline(t.Context(), q, a) + if err != nil || q.previous != int64(min(previous, 3)) || !due.Equal(held.Add(cliRetryDelay(int64(previous)))) { + t.Fatalf("prior=%d count=%d due=%v err=%v", previous, q.previous, due, err) + } + } +} + +func TestCLIAccountRetryDeadlinePreservesLookupErrors(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + for _, match := range []string{"SELECT o.project_id,o.id", "FROM metadata"} { + for _, canceled := range []bool{false, true} { + q := cliRetryFailureQuery{EvidenceQuery: f.store.DB(), match: match, cancel: canceled} + got, err := cliAccountRetryDeadline(t.Context(), q, f.e.capabilities["test-capability"], *now) + if !got.IsZero() || err == nil || isWaitUnavailable(err) || canceled && !errors.Is(err, context.Canceled) || !canceled && !strings.Contains(err.Error(), "missing_cli_retry_history") { + t.Error("account lookup concealed a real query failure", match, canceled, got, err) + } + } + } +} + +func TestCLIExhaustionDeadlinePreservesLookupErrors(t *testing.T) { + f, a, _, _ := cliWaitFixture(t) + a, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision) + if err != nil { + t.Fatal(err) + } + canceled, cancel := context.WithCancel(t.Context()) + cancel() + expired, cancelDeadline := context.WithDeadline(t.Context(), time.Now().Add(-time.Second)) + defer cancelDeadline() + closed, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + if err := closed.Rollback(); err != nil { + t.Fatal(err) + } + for _, test := range []struct { + name string + ctx context.Context + q EvidenceQuery + want error + }{ + {"cancelled", canceled, f.store.DB(), context.Canceled}, + {"deadline", expired, f.store.DB(), context.DeadlineExceeded}, + {"transaction closed", t.Context(), closed, sql.ErrTxDone}, + {"database", t.Context(), cliRetryFailureQuery{EvidenceQuery: f.store.DB(), match: "SELECT created_at"}, nil}, + } { + t.Run(test.name, func(t *testing.T) { + due, err := cliExhaustionDeadline(test.ctx, test.q, a) + if !due.IsZero() || err == nil || isWaitUnavailable(err) || test.want != nil && !errors.Is(err, test.want) || test.want == nil && !strings.Contains(err.Error(), "missing_cli_retry_history") { + t.Error("exhaustion transition lookup changed operational failure", due, err) + } + }) + } + a.Revision++ + if due, err := cliExhaustionDeadline(t.Context(), f.store.DB(), a); !due.IsZero() || !isWaitUnavailable(err) { + t.Error("missing exhaustion transition was not classified as damaged waiting intent", due, err) + } +} + +func TestCLIAccountRetryDeadlineRejectsNoncanonicalFuture(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + future := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)).Add(time.Hour).Truncate(time.Second) + for _, invalid := range []string{ + future.Format("2006-01-02T15:04:05-07:00"), // UTC offset is not canonical Z. + future.Format("2006-01-02T15:04:05.000000000Z"), // Redundant fractional zeros. + future.Format(time.RFC3339Nano) + "Z", // Invalid timestamp, not an expiry. + } { + admissionSQL(t, f, `UPDATE review_operation_waits SET retry_not_before=? WHERE operation_id=?`, invalid, a.OperationID) + before := snapshotTable(t, f, "review_operation_waits") + got, err := cliAccountRetryDeadline(t.Context(), f.store.DB(), f.e.capabilities["test-capability"], *now) + if !got.IsZero() || !isWaitUnavailable(err) { + t.Error("noncanonical future wait escaped retained validation", invalid, got, err) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + err = ValidateOperationWaitsSnapshot(t.Context(), tx) + tx.Rollback() + if !isWaitUnavailable(err) { + t.Error("backup accepted noncanonical retained wait", invalid, err) + } + if before != snapshotTable(t, f, "review_operation_waits") { + t.Fatal("validation rewrote invalid history") + } + } +} + +func TestCLIWaitHistoryIsolatesAccountAndChannel(t *testing.T) { + for _, cancelled := range []bool{false, true} { + t.Run(fmt.Sprint(cancelled), func(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + due := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + if cancelled { + timerControl(t, f, a.OperationID, "cancel", "isolation-cancel") + } + bad := f.enqueue(t, attemptProject, "same-account", "cli", 4, 1) + hosted := f.enqueue(t, attemptProject, "same-account-hosted", "hosted", 2, 1) + healthy := f.enqueue(t, otherAttemptProject, "other-account-cli", "cli", 2, 1) + admissionSQL(t, f, `UPDATE review_cli_preflight SET body_json='{}' WHERE attempt_id=?`, a.ID) + *now = due.Add(-time.Second) + tables := []string{"review_operations", "review_execution_attempts", "review_operation_waits", "review_cli_preflight", "review_execution_reservations", "events"} + before := map[string]string{} + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + for range 2 { + pending, err := f.e.pending(t.Context()) + if err != nil { + t.Fatal(err) + } + got := map[string]bool{} + for _, o := range pending { + got[o.ID] = true + } + if got[bad.ID] || got[a.OperationID] || !got[hosted.ID] || !got[healthy.ID] || len(got) != 2 { + t.Fatal("account/channel isolation failed", got) + } + } + for _, table := range tables { + if before[table] != snapshotTable(t, f, table) { + t.Fatal("pending mutated history", table) + } + } + if got, err := f.e.StartAttempt(t.Context(), attemptProject, bad.ID); got.ID != "" || !isWaitUnavailable(err) { + t.Fatal("corrupt account admitted", got, err) + } + f.start(t, attemptProject, hosted) + f.start(t, otherAttemptProject, healthy) + *now = due + pending, err := f.e.pending(t.Context()) + if err != nil || cancelled && (len(pending) != 1 || pending[0].ID != bad.ID) || !cancelled && len(pending) != 0 { + t.Fatal("expiry did not preserve account and predecessor boundaries", pending, err) + } + assertCLIWaitNoCredit(t, f) + }) + } +} + +func TestWaitIsolationIsTypedAndBounded(t *testing.T) { + now := time.Now() + e := &Engine{schedulingNow: func() time.Time { return now }} + o := Operation{ProjectID: "project", Channel: "cli"} + for _, channel := range []string{"cli", "hosted"} { + o.Channel = channel + for _, err := range []error{context.Canceled, context.DeadlineExceeded, sql.ErrTxDone, errors.New("database failure"), core.Fail("storage_unavailable", "Stored review waiting intent is unavailable.", 500)} { + if e.skipUnavailableWait(t.Context(), o, err) { + t.Fatal("operational error suppressed", err) + } + } + } + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil))) + defer slog.SetDefault(previous) + for i := range 300 { + o.Channel = []string{"cli", "hosted"}[i%2] + o.ID = fmt.Sprintf("review_operation_%d", i) + for range 2 { + if !e.skipUnavailableWait(t.Context(), o, fmt.Errorf("private data: %w", waitUnavailable())) { + t.Fatal("typed refusal escaped") + } + } + } + if len(e.configurationFailureNext) != 256 || strings.Count(output.String(), "\n") != 256 || strings.Contains(output.String(), "private data") { + t.Fatal("unbounded diagnostic") + } + now = now.Add(30 * time.Second) + if !e.skipUnavailableWait(t.Context(), o, waitUnavailable()) || len(e.configurationFailureNext) != 1 { + t.Fatal("diagnostic did not expire") + } + o.Channel = "invalid" + if e.skipUnavailableWait(t.Context(), o, waitUnavailable()) { + t.Fatal("invalid channel suppressed") + } +} + +func TestPausedExpiredCLIWaitDoesNotReportQuotaHeader(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + timerControl(t, f, a.OperationID, "pause", "pause-quota-diagnostic") + due := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + mux := http.NewServeMux() + f.e.Register(mux) + for _, live := range []bool{true, false} { + *now = due + if live { + *now = due.Add(-time.Nanosecond) + } + for _, suffix := range []string{"", "/status"} { + for _, version := range []string{"", "1", "2", "3"} { + req := httptest.NewRequest("GET", "/api/v1/projects/"+attemptProject+"/reviews/operations/"+a.OperationID+suffix, nil) + req.Header.Set("Authorization", "Bearer "+f.writer) + req.Header.Set(operationWaitHeader, version) + w := httptest.NewRecorder() + mux.ServeHTTP(w, req) + want := "" + if live { + want = "cli_quota_wait" + } + if w.Code != http.StatusOK || w.Header().Get("X-FC-Review-Queued") != want { + t.Fatal(live, suffix, version, w.Code, w.Header(), w.Body.String()) + } + } + } + } +} + +type cliRetryPlanQuery struct { + EvidenceQuery + t *testing.T + queries int +} + +func (q *cliRetryPlanQuery) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + if strings.Contains(query, "SELECT o.project_id,o.id") { + q.queries++ + rows, err := q.EvidenceQuery.QueryContext(ctx, "EXPLAIN QUERY PLAN "+query, args...) + if err != nil { + q.t.Fatal(err) + } + var plan string + for rows.Next() { + var id, parent, unused int + var detail string + if err := rows.Scan(&id, &parent, &unused, &detail); err != nil { + q.t.Fatal(err) + } + plan += detail + "\n" + } + if err := rows.Err(); err != nil { + q.t.Fatal(err) + } + rows.Close() + if strings.Contains(query, "INDEXED BY review_waits_live_retry") { + if !strings.Contains(plan, "SEARCH w USING INDEX review_waits_live_retry") { + q.t.Fatal("live deadline lacks indexed range", plan) + } + } else { + if !strings.Contains(plan, "SEARCH t USING INDEX review_transitions_exhaustion_time") || !strings.Contains(plan, "review_transitions_exhaustion_attempt") { + q.t.Fatal("tier history lacks indexed ranges", plan) + } + } + q.t.Log(plan) + } + return q.EvidenceQuery.QueryRowContext(ctx, query, args...) +} +func TestCLIAccountRetryLookupUsesLiveRangesWithRetainedHistory(t *testing.T) { + f, a, _, now := cliWaitFixture(t) + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + // History has no lifetime ceiling. This 10,000-row sample verifies actual + // query plans, not a timing promise or a new retention limit. + if _, err := tx.Exec(`WITH RECURSIVE n(x) AS (SELECT 1000 UNION ALL SELECT x+1 FROM n WHERE x<10999) + INSERT INTO review_execution_transitions(attempt_id,revision,state,reason,external_id,created_at) + SELECT ?,x,'held','allowance_exhausted','','2020-01-01T00:00:00Z' FROM n`, a.ID); err != nil { + t.Fatal(err) + } + q := &cliRetryPlanQuery{EvidenceQuery: tx, t: t} + due, err := cliAccountRetryDeadline(t.Context(), q, f.e.capabilities["test-capability"], *now) + if err != nil || !due.IsZero() || q.queries != 5 { + t.Fatal("expired history changed live account result", due, err, q.queries) + } +} diff --git a/internal/reviewexec/comparison_authority_test.go b/internal/reviewexec/comparison_authority_test.go new file mode 100644 index 000000000..262bdf3b1 --- /dev/null +++ b/internal/reviewexec/comparison_authority_test.go @@ -0,0 +1,52 @@ +package reviewexec + +import ( + "errors" + "reflect" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func TestExecutionUpgradeRefusesComparisonAuthorityBeforeMutation(t *testing.T) { + for _, version := range []string{"3", "02", "0", "invalid"} { + t.Run(version, func(t *testing.T) { + f, _, _, _ := coverageFixture(t, 0, false) + restorePreCooldownAttemptSchema(t, f) + admissionSQL(t, f, `UPDATE metadata SET value='8' WHERE key='schema:review_execution'`) + for _, statement := range comparisonAttemptTriggerRepairSQL() { + admissionSQL(t, f, statement) + } + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_comparison'`, version) + before := snapshotTable(t, f, "sqlite_master") + snapshotTable(t, f, "metadata") + snapshotTable(t, f, "review_comparison_proofs") + source := comparisonSourceRows(t, f) + err := EnsureSchema(t.Context(), f.store) + var typed *core.Error + code := "schema_invalid" + if version == "3" { + code = "schema_unsupported" + } + if !errors.As(err, &typed) || typed.Code != code { + t.Fatalf("unexpected refusal: %v", err) + } + if after := snapshotTable(t, f, "sqlite_master") + snapshotTable(t, f, "metadata") + snapshotTable(t, f, "review_comparison_proofs"); before != after || !reflect.DeepEqual(source, comparisonSourceRows(t, f)) { + t.Fatal("refused comparison authority changed schema or retained rows") + } + }) + } +} + +func TestExecutionUpgradeRefusesMissingComparisonTable(t *testing.T) { + f, _, _, _ := coverageFixture(t, 0, false) + comparisonPreDomain(t, f) + admissionSQL(t, f, `INSERT INTO metadata(key,value) VALUES('schema:review_comparison','2')`) + before := snapshotTable(t, f, "sqlite_master") + snapshotTable(t, f, "metadata") + err := EnsureSchema(t.Context(), f.store) + var typed *core.Error + if !errors.As(err, &typed) || typed.Code != "schema_invalid" { + t.Fatalf("missing retained comparison table was not refused: %v", err) + } + if after := snapshotTable(t, f, "sqlite_master") + snapshotTable(t, f, "metadata"); before != after { + t.Fatal("missing comparison table refusal changed retained schema") + } +} diff --git a/internal/reviewexec/comparison_migration_test.go b/internal/reviewexec/comparison_migration_test.go index 91d59d582..00106727e 100644 --- a/internal/reviewexec/comparison_migration_test.go +++ b/internal/reviewexec/comparison_migration_test.go @@ -474,3 +474,38 @@ func TestComparisonMigrationRetainedHistoryLongerBudgetAndRollback(t *testing.T) assertSource() // Corruption is retained for diagnosis, never repaired. }) } + +func TestAttemptRebuildRepairRestoresInvalidationAndProofs(t *testing.T) { + for _, stage := range []string{"schema-eight-upgrade", "already-schema-ten"} { + t.Run(stage, func(t *testing.T) { + f, a, id, _ := coverageFixture(t, 0, false) + coverageFinalize(t, f, a, id, 0) + for _, event := range []string{"insert", "update", "delete"} { + admissionSQL(t, f, "DROP TRIGGER review_comparison_dirty_review_execution_attempts_"+event) + } + admissionSQL(t, f, `UPDATE metadata SET value='1' WHERE key='schema:review_comparison'`) + // A retained dirty proof must be re-derived from unchanged valid source. + admissionSQL(t, f, `UPDATE review_comparison_proofs SET state='dirty'`) + if stage == "schema-eight-upgrade" { + restorePreCooldownAttemptSchema(t, f) + admissionSQL(t, f, `UPDATE metadata SET value='8' WHERE key='schema:review_execution'`) + } + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if n := attemptCount(t, f.store, `SELECT count(*) FROM sqlite_schema WHERE type='trigger' AND name LIKE 'review_comparison_dirty_review_execution_attempts_%'`); n != 3 { + t.Fatal("attempt triggers lost", n) + } + if n := attemptCount(t, f.store, `SELECT count(*) FROM review_comparison_proofs WHERE state='ready'`); n != 1 { + t.Fatal("repair failed to rederive retained proof", n) + } + admissionSQL(t, f, `UPDATE review_execution_attempts SET revision=revision WHERE id=?`, a.ID) + if n := attemptCount(t, f.store, `SELECT count(*) FROM review_comparison_proofs WHERE state='dirty'`); n != 1 { + t.Fatal("repaired trigger did not invalidate proof", n) + } + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal("idempotent repaired startup", err) + } + }) + } +} diff --git a/internal/reviewexec/comparison_schema.go b/internal/reviewexec/comparison_schema.go index 8fe2fd3b1..4749265a2 100644 --- a/internal/reviewexec/comparison_schema.go +++ b/internal/reviewexec/comparison_schema.go @@ -3,6 +3,8 @@ package reviewexec import ( "context" "database/sql" + "errors" + "strconv" "strings" "github.com/benhook1013/FireController/internal/core" @@ -62,8 +64,57 @@ func ComparisonSchemaSQL() []string { return statements } +// Rebuilding the attempts table in execution migration nine drops its three +// dirty-proof triggers. A versioned repair also covers already-upgraded stores; +// the migration backfill re-derives proofs that may have missed invalidation. +func comparisonAttemptTriggerRepairSQL() []string { + var statements []string + const prefix = "CREATE TRIGGER review_comparison_dirty_review_execution_attempts_" + for _, statement := range ComparisonSchemaSQL() { + if strings.HasPrefix(statement, prefix) { + name := strings.Fields(statement)[2] + statements = append(statements, "DROP TRIGGER IF EXISTS "+name, statement) + } + } + return statements +} + +func comparisonSchemaMigrations() [][]string { + return [][]string{ComparisonSchemaSQL(), comparisonAttemptTriggerRepairSQL()} +} + +// Execution migrations can rebuild a table owned by comparison triggers. Refuse +// unknown or damaged comparison authority before touching that shared schema. +func retainedComparisonSchema(ctx context.Context, q interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +}) (bool, error) { + var raw string + err := q.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_comparison'`).Scan(&raw) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, core.NormalizeStorageError(err) + } + version, err := strconv.Atoi(raw) + if err != nil || version < 1 || strconv.Itoa(version) != raw { + return false, core.Fail("schema_invalid", "Domain schema version metadata is invalid.", 500) + } + if version > len(comparisonSchemaMigrations()) { + return false, core.Fail("schema_unsupported", "A domain schema is newer than this service; use a compatible binary.", 500) + } + var installed bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='review_comparison_proofs')`).Scan(&installed); err != nil { + return false, core.NormalizeStorageError(err) + } + if !installed { + return false, core.Fail("schema_invalid", "Retained comparison schema is missing its proof table.", 500) + } + return true, nil +} + func ensureComparisonSchema(ctx context.Context, store *core.Store) error { - if err := store.EnsureSchemaWithBackfill(ctx, "review_comparison", [][]string{ComparisonSchemaSQL()}, backfillComparisonProofs); err != nil { + if err := store.EnsureSchemaWithBackfill(ctx, "review_comparison", comparisonSchemaMigrations(), backfillComparisonProofs); err != nil { return err } return nil diff --git a/internal/reviewexec/configuration_compatibility.go b/internal/reviewexec/configuration_compatibility.go new file mode 100644 index 000000000..c6ed37264 --- /dev/null +++ b/internal/reviewexec/configuration_compatibility.go @@ -0,0 +1,70 @@ +package reviewexec + +import ( + "context" + "database/sql" + "slices" + + "github.com/benhook1013/FireController/internal/strictjson" +) + +// Retained requests may survive pause-only or successor-only configuration +// changes. Every intervening revision must preserve the request's source plan. +func compatibleQueuedConfiguration(ctx context.Context, tx *sql.Tx, o Operation, current Configuration, revision int64) (bool, error) { + if current.Paused || revision < o.ConfigurationRevision { + return false, nil + } + if revision == o.ConfigurationRevision { + return true, nil + } + rows, err := tx.QueryContext(ctx, `SELECT revision,body_json FROM review_execution_config WHERE project_id=? AND revision BETWEEN ? AND ? ORDER BY revision`, o.ProjectID, o.ConfigurationRevision, revision) + if err != nil { + return false, err + } + defer rows.Close() + expected := o.ConfigurationRevision + var original, previous Configuration + var prefix []int64 + for rows.Next() { + var n int64 + var body string + var c Configuration + if err := rows.Scan(&n, &body); err != nil { + return false, err + } + if n != expected || len(body) > 8192 || strictjson.Decode([]byte(body), &c) != nil || validateConfigurationShape(c) != nil { + return false, newStoredUnavailable(storedConfigurationHistory, "Stored source refresh is unavailable.") + } + expected++ + index := slices.Index(c.Queue, o.PullNumber) + if index < 0 { + return false, nil + } + if n == o.ConfigurationRevision { + if c.Paused { + return false, nil + } + original, previous = c, c + prefix = slices.Clone(c.Queue[:index+1]) + continue + } + if c.Paused != previous.Paused { + if !sameSourceConfiguration(c, previous) { + return false, nil + } + previous = c + continue + } + if c.CapabilityID != original.CapabilityID || c.Mode != original.Mode || !sameChannelSet(c.Channels, original.Channels) || !slices.Equal(c.Queue[:index+1], prefix) || slices.Equal(c.Queue, previous.Queue) { + return false, nil + } + previous = c + } + if err := rows.Err(); err != nil { + return false, err + } + if expected != revision+1 { + return false, newStoredUnavailable(storedConfigurationHistory, "Stored source refresh is unavailable.") + } + return true, nil +} diff --git a/internal/reviewexec/configuration_compatibility_test.go b/internal/reviewexec/configuration_compatibility_test.go new file mode 100644 index 000000000..671020a8a --- /dev/null +++ b/internal/reviewexec/configuration_compatibility_test.go @@ -0,0 +1,355 @@ +package reviewexec + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" +) + +func TestWaitingReviewSurvivesOnlyQueueChangesAfterItsTarget(t *testing.T) { + for _, scenario := range []string{"remove later", "append later", "replace later", "move predecessor", "remove target", "mode", "channels", "capability", "paused then restored", "pause only then restored", "explicit unchanged replacement"} { + t.Run(scenario, func(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + request := f.enqueue(t, attemptProject, "original-request", "cli", 2, 1) + c := Configuration{CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}} + revision := int64(1) + change := func(key string) { + t.Helper() + c.ExpectedRevision = &revision + raw, err := f.e.Configure(context.Background(), f.scope(t, attemptProject, f.admin, true), key, c) + if err != nil { + t.Fatal(err) + } + var r Receipt + if json.Unmarshal(raw, &r) != nil { + t.Fatal("receipt") + } + revision = r.Revision + } + safe := false + switch scenario { + case "remove later": + c.Queue = []int64{2} + safe = true + case "append later": + c.Queue = []int64{2, 4, 6} + safe = true + case "replace later": + c.Queue = []int64{2, 6} + safe = true + case "move predecessor": + c.Queue = []int64{4, 2} + case "remove target": + c.Queue = []int64{4} + case "mode": + c.Mode = "stacked" + case "channels": + c.Channels = []string{"cli"} + case "capability": + c.CapabilityID = "other-account" + case "pause only then restored": + c.Paused = true + change("pause") + c.Paused = false + safe = true + case "paused then restored": + c.Paused = true + change("pause") + c.Paused = false + c.Queue = []int64{2, 6} + } + change("queue-change") + attempt, err := f.e.StartAttempt(context.Background(), attemptProject, request.ID) + if err != nil { + t.Fatal(err) + } + operation, err := f.e.ReadOperation(context.Background(), f.scope(t, attemptProject, f.writer, false), request.ID) + if err != nil { + t.Fatal(err) + } + if operation.ConfigurationRevision != 1 { + t.Fatal("original configuration provenance changed") + } + if safe { + if attempt.ID == "" || attempt.State != "preparing" { + t.Fatal("harmless later queue edit held original request", operation) + } + } else if attempt.ID != "" || operation.State != "held" || operation.Reason != "configuration_changed" { + t.Fatal("meaningful configuration change admitted stale request", operation) + } + }) + } +} + +func TestWaitingReviewChannelSetCompatibilityAndUnchangedQueueBarrier(t *testing.T) { + for _, test := range []struct { + name string + initialChannels []string + nextChannels []string + nextQueue []int64 + pauseResume bool + compatible bool + }{ + {name: "reordered channels with suffix edit", initialChannels: []string{"cli", "hosted"}, nextChannels: []string{"hosted", "cli"}, nextQueue: []int64{2, 6}, compatible: true}, + {name: "reordered channels alone keeps unchanged queue barrier", initialChannels: []string{"cli", "hosted"}, nextChannels: []string{"hosted", "cli"}, nextQueue: []int64{2, 4}}, + {name: "channel added", initialChannels: []string{"cli"}, nextChannels: []string{"cli", "hosted"}, nextQueue: []int64{2, 6}}, + {name: "channel removed", initialChannels: []string{"cli", "hosted"}, nextChannels: []string{"cli"}, nextQueue: []int64{2, 6}}, + {name: "pause resume with reorder and suffix edit", initialChannels: []string{"cli", "hosted"}, nextChannels: []string{"hosted", "cli"}, nextQueue: []int64{2, 6}, pauseResume: true, compatible: true}, + } { + t.Run(test.name, func(t *testing.T) { + f := newAttemptFixture(t) + configure := func(key string, expected int64, c Configuration) int64 { + t.Helper() + c.ExpectedRevision = &expected + raw, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), key, c) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if json.Unmarshal(raw, &receipt) != nil { + t.Fatal("configuration receipt") + } + return receipt.Revision + } + c := Configuration{CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 4}, Channels: append([]string(nil), test.initialChannels...)} + revision := configure("initial", 0, c) + request := f.enqueue(t, attemptProject, "queued", "cli", 2, revision) + if test.pauseResume { + c.Paused = true + revision = configure("pause", revision, c) + c.Paused = false + c.Channels = append([]string(nil), test.nextChannels...) + revision = configure("resume-reordered", revision, c) + c.Queue = append([]int64(nil), test.nextQueue...) + } else { + c.Channels = append([]string(nil), test.nextChannels...) + c.Queue = append([]int64(nil), test.nextQueue...) + } + configure("configuration-change", revision, c) + + attempt, err := f.e.StartAttempt(t.Context(), attemptProject, request.ID) + if err != nil { + t.Fatal(err) + } + operation, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), request.ID) + if err != nil { + t.Fatal(err) + } + if test.compatible { + if attempt.ID == "" || attempt.State != "preparing" || operation.State != "preparing" { + t.Fatal("compatible channel-set change held original request", attempt, operation) + } + } else if attempt.ID != "" || operation.State != "held" || operation.Reason != "configuration_changed" { + t.Fatal("incompatible channel or unchanged-queue edit admitted stale request", attempt, operation) + } + }) + } +} + +func TestPreparingReviewRechecksEveryInterveningQueueRevision(t *testing.T) { + for _, meaningful := range []bool{false, true} { + t.Run(map[bool]string{false: "suffix only", true: "prefix moved then restored"}[meaningful], func(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + r := f.enqueue(t, attemptProject, "preparing-request", "cli", 2, 1) + a, err := f.e.StartAttempt(context.Background(), attemptProject, r.ID) + if err != nil { + t.Fatal(err) + } + revision := int64(1) + c := Configuration{CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 6}, Channels: []string{"cli", "hosted"}} + if meaningful { + c.Queue = []int64{4, 2} + } + for i := 0; i < 2; i++ { + c.ExpectedRevision = &revision + raw, err := f.e.Configure(context.Background(), f.scope(t, attemptProject, f.admin, true), []string{"first-edit", "second-edit"}[i], c) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if json.Unmarshal(raw, &receipt) != nil { + t.Fatal("receipt") + } + revision = receipt.Revision + c.Queue = []int64{2, 8} + } + admitted, err := f.e.Admit(context.Background(), attemptProject, a.ID, a.Revision, attemptAnchor(attemptProject, 2), "") + if meaningful { + if err == nil { + t.Fatal("restored prefix hid earlier change") + } + } else if err != nil || admitted.State != "active" { + t.Fatal("suffix edits invalidated prepared original comparison", admitted, err) + } + }) + } +} + +func TestSupervisorKeepsOriginalRequestAcrossLaterQueueCleanup(t *testing.T) { + f := supervisorFixture(t) + r := f.enqueue(t, attemptProject, "waiting-original", "cli", 2, 1) + revision := int64(1) + _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "unrelated-cleanup", Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}}) + if err != nil { + t.Fatal(err) + } + driver := &controlledDriver{prepare: func(ctx context.Context, o Operation, c Configuration, a Attempt) (Preparation, error) { + if o.ID != r.ID || o.ConfigurationRevision != 1 || len(c.Queue) != 2 || c.Queue[1] != 4 { + t.Fatal("preparation lost original configuration") + } + revision := int64(2) + _, err := f.e.Configure(ctx, f.scope(t, attemptProject, f.admin, true), "later-add-during-preparation", Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 6}, Channels: []string{"cli", "hosted"}}) + if err != nil { + return Preparation{}, err + } + return Preparation{Anchor: attemptAnchor(attemptProject, 2)}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal(err) + } + operation, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), r.ID) + if err != nil || operation.State != "completed" || operation.ConfigurationRevision != 1 || driver.prepares.Load() != 1 || driver.calls.Load() != 1 { + t.Fatal("unrelated cleanup disrupted or duplicated original execution", operation, err) + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal(err) + } + if driver.calls.Load() != 1 { + t.Fatal("completed original request dispatched again") + } +} + +func TestSourceConfigurationChannelSetsPreserveApplicability(t *testing.T) { + for _, test := range []struct { + name string + initial, next []string + valid bool + }{ + {name: "reordered", initial: []string{"cli", "hosted"}, next: []string{"hosted", "cli"}, valid: true}, + {name: "added", initial: []string{"cli"}, next: []string{"cli", "hosted"}}, + {name: "removed", initial: []string{"cli", "hosted"}, next: []string{"cli"}}, + } { + t.Run(test.name, func(t *testing.T) { + original := Configuration{CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: test.initial} + current := original + current.Channels = test.next + beforeOriginal, beforeCurrent := encoded(original), encoded(current) + if got := sameSourceConfiguration(current, original); got != test.valid { + t.Fatal("whole source channel-set applicability", got, test.valid) + } + if got := sameSourceTargetConfiguration(current, original, 2, 4); got != test.valid { + t.Fatal("target source channel-set applicability", got, test.valid) + } + if encoded(original) != beforeOriginal || encoded(current) != beforeCurrent { + t.Fatal("source comparison mutated a channel list") + } + current.Queue = []int64{2, 4, 6} + current.Paused = true + beforeCurrent = encoded(current) + if got := sameSourceTargetConfiguration(current, original, 2, 4); got != test.valid { + t.Fatal("suffix and pause source applicability", got, test.valid) + } + if sameSourceConfiguration(current, original) { + t.Fatal("whole-queue pause guard was relaxed") + } + if encoded(original) != beforeOriginal || encoded(current) != beforeCurrent { + t.Fatal("source comparison mutated retained plans") + } + }) + } +} + +func TestWaitingReviewRejectsDamagedConfigurationHistory(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, damage := range []string{"revision gap", "malformed JSON", "oversized JSON", "unknown field", "duplicate field", "invalid shape"} { + t.Run(channel+"/"+damage, func(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "queued-original", channel, 2, 1) + for revision := int64(1); revision <= 2; revision++ { + c := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 4, 6}, Channels: []string{"cli", "hosted"}} + if revision == 2 { + c.Queue = append(c.Queue, 8) + } + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), fmt.Sprintf("suffix-%d", revision), c); err != nil { + t.Fatal(err) + } + } + var body string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_execution_config WHERE project_id=? AND revision=2`, attemptProject).Scan(&body); err != nil { + t.Fatal(err) + } + switch damage { + case "revision gap": + admissionSQL(t, f, `DELETE FROM review_execution_config WHERE project_id=? AND revision=2`, attemptProject) + case "malformed JSON": + body = `{` + case "oversized JSON": + body += strings.Repeat(" ", 8192) + case "unknown field": + body = strings.TrimSuffix(body, "}") + `,"unknown":true}` + case "duplicate field": + body = strings.TrimSuffix(body, "}") + `,"paused":false}` + case "invalid shape": + body = strings.Replace(body, `"expected_revision":1`, `"expected_revision":null`, 1) + } + if damage != "revision gap" { + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=? WHERE project_id=? AND revision=2`, body, attemptProject) + } + attempt, err := f.e.StartAttempt(t.Context(), attemptProject, request.ID) + attemptCode(t, err, "storage_unavailable") + if attempt.ID != "" { + t.Fatal("damaged history created an attempt", attempt) + } + driver := &controlledDriver{} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal("candidate history stopped the supervisor", err) + } + op, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), request.ID) + if err != nil || op.State != "queued" || op.Reason != "" || op.Revision != request.Revision || op.ConfigurationRevision != 1 || op.AttemptID != "" { + t.Fatal("storage damage became a normal configuration hold or changed original request", op, err) + } + if driver.prepares.Load() != 0 || driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("damaged history acquired capacity or invoked the provider") + } + }) + } + } +} + +func TestQueuedConfigurationRejectsTruncatedHistory(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + request := f.enqueue(t, attemptProject, "queued-original", "cli", 2, 1) + revision := int64(1) + c := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 4, 6}, Channels: []string{"cli", "hosted"}} + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "suffix", c); err != nil { + t.Fatal(err) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + o, err := readOperation(t.Context(), tx, attemptProject, request.ID) + if err != nil { + t.Fatal(err) + } + current, revision, err := readConfiguration(t.Context(), tx, attemptProject) + if err != nil { + t.Fatal(err) + } + // The caller's retained upper revision must be present, even when no later + // row exists to reveal a gap inside the loop. + if _, err := tx.ExecContext(t.Context(), `DELETE FROM review_execution_config WHERE project_id=? AND revision=?`, attemptProject, revision); err != nil { + t.Fatal(err) + } + compatible, err := compatibleQueuedConfiguration(t.Context(), tx, o, current, revision) + attemptCode(t, err, "storage_unavailable") + if compatible { + t.Fatal("truncated history was compatible") + } +} diff --git a/internal/reviewexec/cooldown_projection_fallback_test.go b/internal/reviewexec/cooldown_projection_fallback_test.go new file mode 100644 index 000000000..0e905d7f6 --- /dev/null +++ b/internal/reviewexec/cooldown_projection_fallback_test.go @@ -0,0 +1,65 @@ +package reviewexec + +import ( + "context" + "strings" + "testing" +) + +func TestNativeProjectionUnusableHostedCooldownHoldsOnlyItsOperation(t *testing.T) { + for _, scenario := range []string{"absent", "malformed", "oversized"} { + t.Run(scenario, func(t *testing.T) { + f := attemptProjectionFixture(t, true) + f.configure(t, otherAttemptProject, "other-account", 0, false) + receipt := f.enqueue(t, attemptProject, "unusable-hosted-cooldown", "hosted", 2, 1) + body := "{}" + if scenario == "oversized" { + body = strings.Repeat("x", 16385) + } + driver := &controlledDriver{prepare: func(ctx context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + if o.Channel != "hosted" { + return Preparation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber)}, nil + } + if scenario != "absent" { + if _, err := f.store.DB().ExecContext(ctx, `INSERT INTO review_hosted_preflight(attempt_id,project_id,body_json) VALUES(?,?,?)`, a.ID, o.ProjectID, body); err != nil { + return Preparation{}, err + } + } + return Preparation{}, sourceHold("hosted_allowance_cooldown") + }} + drivers := map[string]Driver{"test-capability": driver, "other-account": driver} + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal("unusable Hosted evidence stopped unrelated work", err) + } + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_operations WHERE id=?`, receipt.ID).Scan(&state, &reason); err != nil || state != "held" || reason != "hosted_allowance_cooldown" { + t.Fatal("cooldown refusal did not retain local hold", state, reason, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_operation_waits WHERE baseline_attempt_id IS NOT NULL`) != 0 || driver.calls.Load() != 0 { + t.Fatal("unproven cooldown retained capacity, invented timer, or dispatched") + } + if scenario != "absent" { + var retained string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_hosted_preflight`).Scan(&retained); err != nil || retained != body { + t.Fatal("local hold rewrote malformed retained evidence", err) + } + } + if scenario != "absent" { + _, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), receipt.ID) + attemptCode(t, err, "storage_unavailable") + } + var attemptID string + if err := f.store.DB().QueryRow(`SELECT attempt_id FROM review_operations WHERE id=?`, receipt.ID).Scan(&attemptID); err != nil { + t.Fatal(err) + } + _, projected := projectedAttempt(t, f, Attempt{ID: attemptID}) + if projected.State != "held" { + t.Fatal("local hold not projected", projected.State) + } + other := f.enqueue(t, otherAttemptProject, "healthy-after-hosted-hold", "cli", 2, 1) + if err := f.e.processNext(t.Context(), drivers); err != nil || supervisorOperationState(t, f, other.ID) != "completed" || driver.calls.Load() != 1 { + t.Fatal("another project did not continue after local hold", err) + } + }) + } +} diff --git a/internal/reviewexec/current_parent_enrollment_test.go b/internal/reviewexec/current_parent_enrollment_test.go new file mode 100644 index 000000000..0fec59967 --- /dev/null +++ b/internal/reviewexec/current_parent_enrollment_test.go @@ -0,0 +1,49 @@ +package reviewexec + +import "testing" + +func TestVerifyActionRetainedRequestRequiresCurrentParentEnrollment(t *testing.T) { + for _, removeParent := range []bool{false, true} { + t.Run(map[bool]string{false: "unrelated suffix removed", true: "actual parent removed"}[removeParent], func(t *testing.T) { + f, prior, id, parent := coverageFixture(t, 1, false) + adjudicationDecide(t, f, id, "reject-parent", 0, 0, "rejected") + coverageFinalize(t, f, prior, id, 1) + revision := int64(1) + c := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{4, 2, 6}, Channels: []string{"cli", "hosted"}} + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "stack", c); err != nil { + t.Fatal(err) + } + child := f.start(t, attemptProject, f.enqueue(t, attemptProject, "child", "cli", 4, 2)) + // Keep source resolution bound to the original queue even after its suffix changes. + revision = 2 + c.Queue = []int64{4, 2} + if removeParent { + c.Queue = []int64{4, 6} + } + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "suffix", c); err != nil { + t.Fatal(err) + } + current, err := f.e.ExecutionContext(t.Context(), attemptProject, child.OperationID) + if err != nil || len(current.Configuration.Queue) != 3 || current.Configuration.Queue[1] != 2 { + t.Fatal("original source configuration lost", current, err) + } + anchor := attemptAnchor(attemptProject, 4) + anchor.ParentPullNumber, anchor.ParentSHA, anchor.BaseSHA, anchor.BaseRef = 2, parent.Pull.HeadSHA, parent.Pull.HeadSHA, "parent-branch" + child, err = f.e.Admit(t.Context(), attemptProject, child.ID, child.Revision, anchor, "") + if err != nil { + t.Fatal(err) + } + parent.Pull.HeadRef = "parent-branch" + before := adjudicationState(t, f, child) + err = f.e.VerifyAction(t.Context(), attemptProject, child.ID, child.Revision, parent) + if removeParent { + attemptCode(t, err, "validation_failed") + } else if err != nil { + t.Fatal("unrelated removal blocked action", err) + } + if before != adjudicationState(t, f, child) { + t.Fatal("final guard changed retained state") + } + }) + } +} diff --git a/internal/reviewexec/execution_comparison_upgrade_test.go b/internal/reviewexec/execution_comparison_upgrade_test.go new file mode 100644 index 000000000..074b12b45 --- /dev/null +++ b/internal/reviewexec/execution_comparison_upgrade_test.go @@ -0,0 +1,50 @@ +package reviewexec + +import "testing" + +func TestExecutionEightUpgradePreservesCurrentComparisonTriggers(t *testing.T) { + f, a, id, _ := coverageFixture(t, 0, false) + coverageFinalize(t, f, a, id, 0) + // Reconstruct both genuine execution-v8 cardinality constraints, retaining + // the independent comparison-v2 schema and its live invalidation triggers. + restorePreCooldownAttemptSchema(t, f) + for _, statement := range []string{ + `CREATE TABLE old_reservations(provider TEXT NOT NULL,repository_id INTEGER NOT NULL,pull_number INTEGER NOT NULL,action_class TEXT NOT NULL,account TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),PRIMARY KEY(provider,repository_id,pull_number,action_class),UNIQUE(provider,account,action_class))`, + `INSERT INTO old_reservations SELECT * FROM review_execution_reservations`, + `DROP TABLE review_execution_reservations`, + `ALTER TABLE old_reservations RENAME TO review_execution_reservations`, + `UPDATE metadata SET value='8' WHERE key='schema:review_execution'`, + } { + admissionSQL(t, f, statement) + } + for _, statement := range comparisonAttemptTriggerRepairSQL() { + admissionSQL(t, f, statement) + } + assertTriggers := func() { + t.Helper() + if n := attemptCount(t, f.store, `SELECT count(*) FROM sqlite_schema WHERE type='trigger' AND name LIKE 'review_comparison_dirty_review_execution_attempts_%'`); n != 3 { + t.Fatal("attempt invalidation triggers missing", n) + } + var version string + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_comparison'`).Scan(&version); err != nil || version != "2" { + t.Fatal("comparison marker changed", version, err) + } + } + assertTriggers() + before := snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_evidence") + snapshotTable(t, f, "review_comparison_proofs") + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + assertTriggers() + if after := snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_evidence") + snapshotTable(t, f, "review_comparison_proofs"); before != after { + t.Fatal("upgrade changed retained source/proof") + } + admissionSQL(t, f, `UPDATE review_execution_attempts SET revision=revision WHERE id=?`, a.ID) + if n := attemptCount(t, f.store, `SELECT count(*) FROM review_comparison_proofs WHERE state='dirty'`); n != 1 { + t.Fatal("attempt mutation did not invalidate proof", n) + } + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal("restart", err) + } + assertTriggers() +} diff --git a/internal/reviewexec/hosted_comparison_test.go b/internal/reviewexec/hosted_comparison_test.go index 1b689ff3a..29e338481 100644 --- a/internal/reviewexec/hosted_comparison_test.go +++ b/internal/reviewexec/hosted_comparison_test.go @@ -214,23 +214,27 @@ func TestHostedComparisonCompletedMissingCaptureGrowth(t *testing.T) { } func TestComparisonVersionFourUpgradePreservesJournal(t *testing.T) { - f, a, id, current := hostedComparisonFixture(t, true) + f, a, id, current := coverageFixture(t, 0, false) coverageFinalize(t, f, a, id, 0) before := adjudicationState(t, f, a) admissionSQL(t, f, `DROP TABLE review_hosted_preflight`) admissionSQL(t, f, `DROP TABLE review_hosted_allowance_queries`) admissionSQL(t, f, `DROP INDEX review_operations_completed_comparison`) admissionSQL(t, f, `CREATE INDEX review_operations_cli_admission ON review_operations(project_id,pull_number,channel,state,id)`) + restorePreCooldownAttemptSchema(t, f) + admissionSQL(t, f, `ALTER TABLE review_operations DROP COLUMN override_file_limit`) + admissionSQL(t, f, `ALTER TABLE review_operations DROP COLUMN allow_out_of_order`) + admissionSQL(t, f, `UPDATE metadata SET value='1' WHERE key='schema:review_comparison'`) admissionSQL(t, f, `UPDATE metadata SET value='4' WHERE key='schema:review_execution'`) if err := EnsureSchema(t.Context(), f.store); err != nil { t.Fatal(err) } var version string - if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "6" { + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "10" { t.Fatal("ordered comparison migration", version, err) } if adjudicationState(t, f, a) != before { t.Fatal("index migration changed retained journal/evidence") } - hostedComparisonRead(t, f, a, current, ComparisonState{Covered: true}) + coverageComparison(t, f, a, current, ComparisonState{Covered: true}) } diff --git a/internal/reviewexec/hosted_observation_historical_replay_test.go b/internal/reviewexec/hosted_observation_historical_replay_test.go new file mode 100644 index 000000000..e402c7e5c --- /dev/null +++ b/internal/reviewexec/hosted_observation_historical_replay_test.go @@ -0,0 +1,43 @@ +package reviewexec + +import ( + "strings" + "testing" +) + +func TestHostedObservationExactReplayAfterCooldownDetachmentAndRetry(t *testing.T) { + for _, retry := range []bool{false, true} { + t.Run(map[bool]string{false: "detached", true: "retry started"}[retry], func(t *testing.T) { + f, a, cooldown, now := queuedCooldown(t) + records, err := f.e.ReadHostedObservations(t.Context(), attemptProject, a.ID) + if err != nil || len(records) != 1 { + t.Fatal("original observation", records, err) + } + original := records[0] + if retry { + *now = cooldown.Observation.RetryNotBefore + next := f.start(t, attemptProject, Receipt{ID: a.OperationID}) + if next.ID == a.ID { + t.Fatal("retry reused attempt") + } + } + before := hostedObservationState(t, f, a) + got, err := f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, original.Input) + if err != nil || got != (Receipt{ID: original.ID, State: "observed", Revision: 1}) { + t.Fatal("historical exact replay", got, err) + } + changed := original.Input + changed.CaptureBytes++ + _, err = f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, changed) + attemptCode(t, err, "review_conflict") + fresh := original.Input + fresh.CaptureSHA256 = strings.Repeat("f", 64) + fresh.CaptureID = "review_capture_" + fresh.CaptureSHA256[:32] + _, err = f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, fresh) + attemptCode(t, err, "review_conflict") + if hostedObservationState(t, f, a) != before { + t.Fatal("historical replay or rejected append changed journal") + } + }) + } +} diff --git a/internal/reviewexec/hosted_observations.go b/internal/reviewexec/hosted_observations.go index ff7c6ee49..995724775 100644 --- a/internal/reviewexec/hosted_observations.go +++ b/internal/reviewexec/hosted_observations.go @@ -163,7 +163,13 @@ func (e *Engine) recordHostedObservationAt(ctx context.Context, project, attempt if rowProject != project || rowAttempt != attemptID || rowOperation != o.ID { return hostedObservationUnavailable() } - prior, err := decodeHostedObservation(body, id, project, attemptID, o.ID, position, owned.CaptureSHA256, bytes, a, o) + // Exact replay uses proven historical ownership without permitting new + // writes for an attempt detached by cooldown scheduling. + historical, err := historicalCooldownOperation(ctx, tx, o, a) + if err != nil { + return err + } + prior, err := decodeHostedObservation(body, id, project, attemptID, o.ID, position, owned.CaptureSHA256, bytes, a, historical) if err != nil { return err } @@ -259,6 +265,10 @@ func (e *Engine) ReadHostedObservations(ctx context.Context, project, attemptID if err != nil { return err } + o, err = historicalCooldownOperation(ctx, tx, o, a) + if err != nil { + return err + } rows, err := tx.QueryContext(ctx, `SELECT id,project_id,attempt_id,operation_id,position,capture_sha256,capture_bytes,body_json FROM review_hosted_observations WHERE project_id=? AND attempt_id=? ORDER BY position LIMIT 201`, project, attemptID) if err != nil { return err diff --git a/internal/reviewexec/hosted_preflight.go b/internal/reviewexec/hosted_preflight.go index 2a6d0995c..bd559dbb7 100644 --- a/internal/reviewexec/hosted_preflight.go +++ b/internal/reviewexec/hosted_preflight.go @@ -44,24 +44,32 @@ func hostedAllowanceSameSource(a, b Anchor) bool { } func validHostedAllowanceInput(in HostedAllowanceInput) bool { + return validHostedAllowanceObservation(in) && in.Observation.State == "available_observed" && in.Observation.Reason == "provider_available_observed" && in.Observation.RetryNotBefore.IsZero() +} + +func validHostedAllowanceObservation(in HostedAllowanceInput) bool { observed, ok := hostedObservationTime(in.ObservedAt) o := in.Observation return ok && hostedObservationID(in.QueryID, "review_hosted_query_") && validEvidenceAnchor(in.Anchor) && in.ChangedFiles > 0 && in.ChangedFiles <= 100000 && hash.MatchString(in.CaptureSHA256) && in.CaptureID == "review_capture_"+in.CaptureSHA256[:32] && in.CaptureBytes > 0 && in.CaptureBytes <= 48<<20 && - o.State == "available_observed" && o.Reason == "provider_available_observed" && o.QueryCommentID > 0 && o.ResponseCommentID > 0 && o.ResponseCommentID != o.QueryCommentID && + validHostedAllowanceOutcome(o) && o.QueryCommentID > 0 && o.ResponseCommentID > 0 && o.ResponseCommentID != o.QueryCommentID && o.QueryCreatedAt.Location() == time.UTC && !o.QueryCreatedAt.IsZero() && o.QueryCreatedAt.Year() >= 1 && o.QueryCreatedAt.Year() <= 9999 && - o.ResponseCreatedAt.Location() == time.UTC && !o.ResponseCreatedAt.IsZero() && o.ResponseCreatedAt.After(o.QueryCreatedAt) && !o.ResponseCreatedAt.After(observed) && o.RetryNotBefore.IsZero() + o.ResponseCreatedAt.Location() == time.UTC && !o.ResponseCreatedAt.IsZero() && o.ResponseCreatedAt.After(o.QueryCreatedAt) && !o.ResponseCreatedAt.After(observed) +} + +func validHostedAllowanceOutcome(o reviewprovider.HostedAllowanceObservation) bool { + return reviewprovider.ValidHostedAllowanceOutcome(o) } func hostedAllowanceUnavailable() error { - return core.Fail("storage_unavailable", "Stored hosted allowance observation is unavailable.", 500) + return newStoredUnavailable(storedHostedObservation, "Stored hosted allowance observation is unavailable.") } func decodeHostedAllowance(body, project, attemptID string) (hostedAllowanceRecord, error) { var retained hostedAllowanceRecord if len(body) > 16<<10 || strictjson.Validate([]byte(body)) != nil || json.Unmarshal([]byte(body), &retained) != nil || encoded(retained) != body || retained.ProjectID != project || retained.AttemptID != attemptID || !hostedObservationID(retained.OperationID, "review_operation_") || !identifier.MatchString(retained.ActorID) || retained.WorkerID != "" && !identifier.MatchString(retained.WorkerID) || - retained.ConfigurationRevision < 1 || retained.PolicyRevision < 1 || !hash.MatchString(retained.CapabilityFingerprint) || !validHostedAllowanceInput(retained.Input) { + retained.ConfigurationRevision < 1 || retained.PolicyRevision < 1 || !hash.MatchString(retained.CapabilityFingerprint) || !validHostedAllowanceObservation(retained.Input) { return hostedAllowanceRecord{}, hostedAllowanceUnavailable() } return retained, nil @@ -78,7 +86,22 @@ func hostedAllowanceBinding(record hostedAllowanceRecord, attempt Attempt, opera // admission. Exact replay is local and precedes freshness/current eligibility; // a replay cannot refresh provider facts or authorize another external action. func (e *Engine) RecordHostedAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input HostedAllowanceInput) error { - if ctx == nil || e == nil || e.store == nil || !identifier.MatchString(project) || !hostedObservationID(attemptID, "review_attempt_") || expectedRevision != 1 || !validHostedAllowanceInput(input) { + if !validHostedAllowanceInput(input) { + return invalid() + } + return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input) +} + +// RecordHostedCooldown retains attributed cooldown facts, never positive admission. +func (e *Engine) RecordHostedCooldown(ctx context.Context, project, attemptID string, expectedRevision int64, input HostedAllowanceInput) error { + if input.Observation.State != "cooldown_observed" { + return invalid() + } + return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input) +} + +func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input HostedAllowanceInput) error { + if ctx == nil || e == nil || e.store == nil || !identifier.MatchString(project) || !hostedObservationID(attemptID, "review_attempt_") || expectedRevision != 1 || !validHostedAllowanceObservation(input) { return invalid() } canonical, err := json.Marshal(input) @@ -109,6 +132,10 @@ func (e *Engine) RecordHostedAllowance(ctx context.Context, project, attemptID s if err != nil { return err } + operation, err = historicalCooldownOperation(ctx, tx, operation, attempt) + if err != nil { + return err + } query, err := readHostedQuery(ctx, tx, attempt, operation) if err != nil { return err @@ -137,6 +164,11 @@ func (e *Engine) RecordHostedAllowance(ctx context.Context, project, attemptID s return err } observation := owned.Observation + if observation.State == "cooldown_observed" { + if err := validateCooldownReference(ctx, tx, attempt, operation, query, owned); err != nil { + return err + } + } if query.ID != owned.QueryID || query.Comment == nil || query.Comment.ID != observation.QueryCommentID || !query.Comment.CreatedAt.Equal(observation.QueryCreatedAt) || !hostedAllowanceSameSource(query.Anchor, owned.Anchor) { return conflict() } @@ -152,7 +184,7 @@ func (e *Engine) RecordHostedAllowance(ctx context.Context, project, attemptID s if !freshAllowanceObservation(owned.ObservedAt, now) || !freshAllowanceObservation(owned.Anchor.ObservedAt, now) || observation.ResponseCreatedAt.Before(now.Add(-time.Minute)) || observation.ResponseCreatedAt.After(now.Add(5*time.Second)) { return invalid() } - if ceiling := current.Policy.Policy.MaxReviewFiles; ceiling > 0 && owned.ChangedFiles > ceiling { + if ceiling := current.Policy.Policy.MaxReviewFiles; !current.Operation.OverrideFileLimit && ceiling > 0 && owned.ChangedFiles > ceiling { return sourceHold("project_file_limit") } record := hostedAllowanceRecord{ProjectID: project, AttemptID: attempt.ID, OperationID: operation.ID, ActorID: operation.ActorID, WorkerID: operation.WorkerID, @@ -189,6 +221,10 @@ func readHostedAllowance(ctx context.Context, tx *sql.Tx, project, attemptID str if err != nil { return record, attempt, operation, err } + operation, err = historicalCooldownOperation(ctx, tx, operation, attempt) + if err != nil { + return record, attempt, operation, err + } query, err := readHostedQuery(ctx, tx, attempt, operation) if err != nil { return record, attempt, operation, err @@ -209,6 +245,9 @@ func (e *Engine) ReadHostedAllowance(ctx context.Context, project, attemptID str err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { record, _, _, err := readHostedAllowance(ctx, tx, project, attemptID) input = record.Input + if err == nil && !validHostedAllowanceInput(input) { + return conflict() + } return err }) if err != nil { @@ -233,7 +272,7 @@ func (e *Engine) VerifyHostedAction(ctx context.Context, project, attemptID stri if err != nil { return err } - if operation.Channel != "hosted" || attempt.State != "posting" || attempt.Anchor == nil || !hostedAllowanceSameSource(record.Input.Anchor, *attempt.Anchor) { + if !validHostedAllowanceInput(record.Input) || operation.Channel != "hosted" || attempt.State != "posting" || attempt.Anchor == nil || !hostedAllowanceSameSource(record.Input.Anchor, *attempt.Anchor) { return conflict() } intent, err := reviewprovider.HostedTriggerBody(reviewprovider.HostedTriggerIntent{OperationID: operation.ID, AttemptID: attempt.ID, HeadSHA: operation.HeadSHA}) @@ -258,7 +297,7 @@ func (e *Engine) VerifyHostedAction(ctx context.Context, project, attemptID stri if !freshAllowanceObservation(record.Input.ObservedAt, now) || record.Input.Observation.ResponseCreatedAt.Before(now.Add(-time.Minute)) || record.Input.Observation.ResponseCreatedAt.After(now.Add(5*time.Second)) { return sourceHold("allowance_stale") } - if ceiling := current.Policy.Policy.MaxReviewFiles; ceiling > 0 && record.Input.ChangedFiles > ceiling { + if ceiling := current.Policy.Policy.MaxReviewFiles; !current.Operation.OverrideFileLimit && ceiling > 0 && record.Input.ChangedFiles > ceiling { return sourceHold("project_file_limit") } return nil diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go new file mode 100644 index 000000000..97cb72b6e --- /dev/null +++ b/internal/reviewexec/hosted_priority.go @@ -0,0 +1,125 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "slices" + + "github.com/benhook1013/FireController/internal/core" +) + +// earlierQueuedReviewIntent preserves project queue priority even while the +// earlier request's timer is not due. It reserves no provider capacity. Both +// scheduler selection and the serialized attempt claim use this same snapshot +// check; allow_out_of_order concerns dependencies, not scheduling priority. +func (e *Engine) earlierQueuedReviewIntent(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64) (*Operation, error) { + return e.earlierQueuedReviewIntentInSnapshot(ctx, tx, o, c, revision, nil) +} + +type queuePriorityKey struct { + project string + channel string + pull int64 +} + +// An empty predecessor set can be reused only inside one read transaction. +// Binding-dependent decisions still run separately for every candidate. +func (e *Engine) earlierQueuedReviewIntentInSnapshot(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64, empty map[queuePriorityKey]bool) (*Operation, error) { + position := slices.Index(c.Queue, o.PullNumber) + if !validChannel(o.Channel) || o.State != "queued" || position < 1 || c.Paused || revision < o.ConfigurationRevision { + return nil, nil + } + key := queuePriorityKey{o.ProjectID, o.Channel, o.PullNumber} + if empty[key] { + return nil, nil + } + queue, err := json.Marshal(c.Queue) + if err != nil { + return nil, err + } + rows, err := tx.QueryContext(ctx, `SELECT o.id FROM review_operations o +JOIN json_each(?) q ON q.value=o.pull_number AND q.key'cli_draft_wait' +AND NOT EXISTS (SELECT 1 FROM review_operation_waits w WHERE w.operation_id=o.id AND w.paused=1) +ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Channel) + if err != nil { + return nil, err + } + var ids []string + for rows.Next() { + var id string + if err = rows.Scan(&id); err != nil { + _ = rows.Close() + return nil, err + } + ids = append(ids, id) + } + err = rows.Err() + _ = rows.Close() + if err != nil { + return nil, err + } + // An exact empty predecessor set needs no applicability decision. The + // selected operation still faces all normal guards at actual claim. + if len(ids) == 0 { + if empty != nil { + empty[key] = true + } + return nil, nil + } + // Inapplicable requests must still reach normal StartAttempt hold handling, + // rather than being hidden behind another intent indefinitely. + valid, err := e.hostedPriorityBinding(ctx, tx, o) + if err != nil || !valid { + return nil, err + } + for _, id := range ids { + earlier, err := readOperation(ctx, tx, o.ProjectID, id) + if err != nil { + return nil, err + } + valid, err := e.hostedPriorityBinding(ctx, tx, earlier) + if err != nil { + return nil, err + } + if valid { + return &earlier, nil + } + } + return nil, nil +} + +func (e *Engine) hostedPriorityBinding(ctx context.Context, tx *sql.Tx, o Operation) (bool, error) { + var err error + if o.Channel == "hosted" { + var installed bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM metadata WHERE key='schema:reviews')`).Scan(&installed); err != nil { + return false, err + } + if installed { + var repository int64 + err = tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repository) + if err != nil { + return false, err + } + pending, readErr := selectionExternalHostedPending(ctx, tx, o.ProjectID, repository, o.PullNumber) + if readErr != nil { + return false, readErr + } + if pending { + return false, nil + } + } + } + _, err = e.currentExecutionContext(ctx, tx, o) + if err == nil { + return true, nil + } + var refusal *core.Error + if errors.As(err, &refusal) && refusal.Status >= 400 && refusal.Status < 500 { + return false, nil + } + return false, err +} diff --git a/internal/reviewexec/hosted_priority_test.go b/internal/reviewexec/hosted_priority_test.go new file mode 100644 index 000000000..03b6f37b1 --- /dev/null +++ b/internal/reviewexec/hosted_priority_test.go @@ -0,0 +1,297 @@ +package reviewexec + +import ( + "bytes" + "context" + "database/sql" + "errors" + "log/slog" + "strings" + + "crypto/sha256" + "fmt" + "github.com/benhook1013/FireController/internal/core" + "sync" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func priorityCooldown(t *testing.T, f *attemptFixture, request Receipt, number int64, delay time.Duration) time.Time { + t.Helper() + a := f.start(t, attemptProject, request) + anchor := attemptAnchor(attemptProject, number) + q, _, err := f.e.BeginHostedAllowanceQuery(t.Context(), attemptProject, a.ID, 1, anchor, reviewprovider.Author{ID: 12, Login: "poster", Kind: "User"}, reviewprovider.Author{ID: 30, Login: "coderabbitai[bot]", Kind: "Bot"}) + if err != nil { + t.Fatal(err) + } + q, err = f.e.ConfirmHostedAllowanceQuery(t.Context(), attemptProject, a.ID, 1, hostedQueryComment(t, q)) + if err != nil { + t.Fatal(err) + } + digest := fmt.Sprintf("%x", sha256.Sum256([]byte(a.ID))) + observed := time.Now().UTC() + response := q.Comment.CreatedAt.Add(time.Nanosecond) + due := response.Add(delay) + in := HostedAllowanceInput{QueryID: q.ID, Anchor: anchor, ObservedAt: observed.Format(time.RFC3339Nano), ChangedFiles: 2, CaptureID: "review_capture_" + digest[:32], CaptureSHA256: digest, CaptureBytes: 1234, Observation: reviewprovider.HostedAllowanceObservation{State: "cooldown_observed", Reason: "provider_cooldown_observed", QueryCommentID: q.Comment.ID, ResponseCommentID: 92, QueryCreatedAt: q.Comment.CreatedAt, ResponseCreatedAt: response, RetryNotBefore: due}} + if _, err := f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, HostedObservationInput{Kind: "allowance_query", CaptureID: in.CaptureID, CaptureSHA256: digest, CaptureBytes: in.CaptureBytes, StartedAt: q.Comment.CreatedAt.Format(time.RFC3339Nano), FinishedAt: in.ObservedAt, ObservedAt: in.ObservedAt, ExpectedAnchor: anchor, Intent: q.Intent}); err != nil { + t.Fatal(err) + } + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, 1); err != nil { + t.Fatal(err) + } + return due +} + +func priorityPending(t *testing.T, f *attemptFixture, want ...string) { + t.Helper() + got, err := f.e.pending(t.Context()) + if err != nil || len(got) != len(want) { + t.Fatalf("pending count=%d want=%d: %v %+v", len(got), len(want), err, got) + } + ids := map[string]bool{} + for _, o := range got { + ids[o.ID] = true + } + for _, id := range want { + if !ids[id] { + t.Fatalf("missing pending %s: %+v", id, got) + } + } +} + +func TestHostedPriorityCooldownAndAtomicClaims(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + // The farther request was created first and its genuine retained cooldown + // expires first. Neither fact permits it to pass the nearer queued intent. + lower := f.enqueue(t, attemptProject, "lower-first", "hosted", 4, 1) + lowerDue := priorityCooldown(t, f, lower, 4, 3*time.Minute) + head := f.enqueue(t, attemptProject, "head-second", "hosted", 2, 1) + headDue := priorityCooldown(t, f, head, 2, 3*time.Minute+5*time.Second) + now := lowerDue + f.e.schedulingNow = func() time.Time { return now } + priorityPending(t, f) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, lower.ID); err != nil || a.ID != "" { + t.Fatal("lower passed future head", a, err) + } + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`); got != 0 { + t.Fatal("priority reserved provider capacity", got) + } + busy := f.start(t, otherAttemptProject, f.enqueue(t, otherAttemptProject, "busy", "hosted", 2, 1)) + now = headDue + // Another repository's Hosted reservation does not consume this repo's + // slot; the nearer queued intent still excludes the lower request. + priorityPending(t, f, head.ID) + if _, err := f.e.Advance(t.Context(), otherAttemptProject, busy.ID, 1, "cancelled", "synthetic_release", ""); err != nil { + t.Fatal(err) + } + priorityPending(t, f, head.ID) + // Race two independently constructed workers through the real serialized + // claim. Lower is refused whether it runs before or after the head claim. + other, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + other.schedulingNow = f.e.schedulingNow + var wg sync.WaitGroup + results := make(chan Attempt, 2) + errors := make(chan error, 2) + start := make(chan struct{}) + for _, claim := range []struct { + e *Engine + id string + }{{f.e, lower.ID}, {other, head.ID}} { + wg.Add(1) + go func() { + defer wg.Done() + <-start + a, err := claim.e.StartAttempt(t.Context(), attemptProject, claim.id) + results <- a + errors <- err + }() + } + close(start) + wg.Wait() + close(results) + close(errors) + for err := range errors { + if err != nil { + attemptCode(t, err, "review_busy") + } + } + claimed := 0 + for a := range results { + if a.ID != "" { + claimed++ + if a.OperationID != head.ID { + t.Fatal("lower won concurrent claim", a) + } + } + } + if claimed != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 { + t.Fatal("claim/accounting changed", claimed) + } +} + +func TestHostedPriorityOnlyUnpausedProjectHostedIntents(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + f.configure(t, otherAttemptProject, "other-account", 0, false) + lower := f.enqueue(t, attemptProject, "lower-bypass", "hosted", 4, 1) + // Preserve the migrated flag's semantics without requiring the later + // public explicit-order request option in this prerequisite slice. + admissionSQL(t, f, `UPDATE review_operations SET allow_out_of_order=1 WHERE id=?`, lower.ID) + cli := f.enqueue(t, attemptProject, "head-cli", "cli", 2, 1) + other := f.enqueue(t, otherAttemptProject, "other-head", "hosted", 2, 1) + // Front queue membership alone and a different channel/project are not + // Hosted intent in this project. The lower request remains selectable. + priorityPending(t, f, lower.ID, cli.ID, other.ID) + head := f.enqueue(t, attemptProject, "head-hosted", "hosted", 2, 1) + priorityPending(t, f, head.ID, cli.ID, other.ID) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, lower.ID); err != nil || a.ID != "" { + t.Fatal("dependency bypass also bypassed priority", a, err) + } + timerControl(t, f, head.ID, "pause", "pause-head") + priorityPending(t, f, lower.ID, cli.ID, other.ID) + timerControl(t, f, head.ID, "resume", "resume-head") + priorityPending(t, f, head.ID, cli.ID, other.ID) + f.configure(t, attemptProject, "test-capability", 1, true) + priorityPending(t, f, other.ID) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, lower.ID); err != nil || a.ID != "" { + t.Fatal("project pause bypassed", a, err) + } + f.configure(t, attemptProject, "test-capability", 2, false) + timerControl(t, f, head.ID, "cancel", "cancel-head") + priorityPending(t, f, lower.ID, cli.ID, other.ID) + f.start(t, attemptProject, lower) +} + +func TestHostedPriorityInvalidIntentCannotReserveTurn(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + head := f.enqueue(t, attemptProject, "invalid-head", "hosted", 2, 1) + lower := f.enqueue(t, attemptProject, "valid-lower", "hosted", 4, 1) + // The head no longer has its original capability binding. It must remain + // visible for its normal hold, without permanently reserving a queue turn. + admissionSQL(t, f, `UPDATE review_operations SET capability_fingerprint='retired-binding' WHERE id=?`, head.ID) + priorityPending(t, f, head.ID, lower.ID) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, head.ID); err != nil || a.ID != "" { + t.Fatal(a, err) + } + op, err := readOperation(t.Context(), f.store.DB(), attemptProject, head.ID) + if err != nil || op.State != "held" || op.Reason != "capability_changed" { + t.Fatal("invalid intent not resolved normally", op, err) + } + f.start(t, attemptProject, lower) +} + +// Damaged retained history cannot authorize a queue jump or stop another project. +func TestPriorityConfigurationHistoryIsolation(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, damaged := range []string{"candidate", "predecessor"} { + for _, damage := range []string{"malformed", "gap"} { + t.Run(channel+"/"+damaged+"/"+damage, func(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + number := int64(4) + if damaged == "predecessor" { + number = 2 + } + bad := f.enqueue(t, attemptProject, "damaged-history", channel, number, 1) + for revision := int64(1); revision <= 2; revision++ { + c := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2, 4, 6}, Channels: []string{"cli", "hosted"}} + if revision == 2 { + c.Queue = append(c.Queue, 8) + } + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), fmt.Sprintf("suffix-%d", revision), c); err != nil { + t.Fatal(err) + } + } + otherNumber := int64(2) + if damaged == "predecessor" { + otherNumber = 4 + } + same := f.enqueue(t, attemptProject, "same-project", channel, otherNumber, 3) + healthy := f.enqueue(t, otherAttemptProject, "healthy-project", channel, 2, 1) + if damage == "gap" { + admissionSQL(t, f, `DELETE FROM review_execution_config WHERE project_id=? AND revision=2`, attemptProject) + } else { + admissionSQL(t, f, `UPDATE review_execution_config SET body_json='private-corrupt-history' WHERE project_id=? AND revision=2`, attemptProject) + } + before, err := readOperation(t.Context(), f.store.DB(), attemptProject, bad.ID) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil))) + defer slog.SetDefault(previous) + seen := map[string]int{} + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + seen[o.ID]++ + return Preparation{}, core.Fail("review_evidence_pending", "synthetic hold", 409) + }} + for range 3 { + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal("candidate history stopped shared scheduling", err) + } + } + after, err := readOperation(t.Context(), f.store.DB(), attemptProject, bad.ID) + if err != nil || encoded(after) != encoded(before) { + t.Fatal("damaged request mutated", before, after, err) + } + if seen[bad.ID] != 0 || seen[healthy.ID] != 1 || driver.calls.Load() != 0 { + t.Fatal("provider work or healthy-project isolation", seen, driver.calls.Load()) + } + if damaged == "predecessor" && seen[same.ID] != 0 { + t.Fatal("unproven predecessor allowed queue jump", seen) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("history failure retained capacity") + } + if !strings.Contains(output.String(), bad.ID) || strings.Contains(output.String(), "private-corrupt-history") { + t.Fatal("missing or unsafe candidate diagnostic", output.String()) + } + if got := strings.Count(output.String(), `"operation_id":"`+bad.ID+`"`); got != 1 { + t.Fatal("repeated diagnostic was not bounded", got, output.String()) + } + }) + } + } + } +} + +func TestConfigurationHistoryIsolationIsTypedAndBounded(t *testing.T) { + now := time.Now() + e := &Engine{schedulingNow: func() time.Time { return now }} + op := Operation{ID: "review_operation_candidate", ProjectID: "project"} + for _, err := range []error{context.Canceled, context.DeadlineExceeded, sql.ErrTxDone, errors.New("database failure"), core.Fail("storage_unavailable", "Stored source refresh is unavailable.", 500)} { + if e.skipUnavailableConfiguration(t.Context(), op, err) || e.skipUnavailableConfiguration(t.Context(), op, fmt.Errorf("wrapped: %w", err)) { + t.Fatal("real storage error isolated", err) + } + } + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil))) + defer slog.SetDefault(previous) + unavailable := fmt.Errorf("private wrapper: %w", newStoredUnavailable(storedConfigurationHistory, "private retained history")) + for i := range 300 { + op.ID = fmt.Sprintf("review_operation_%d", i) + if !e.skipUnavailableConfiguration(t.Context(), op, unavailable) { + t.Fatal("typed history not isolated") + } + } + if len(e.configurationFailureNext) != 256 || strings.Count(output.String(), "\n") != 256 || strings.Contains(output.String(), "private") { + t.Fatal("unbounded or unsafe diagnostics", len(e.configurationFailureNext)) + } + now = now.Add(30 * time.Second) + if !e.skipUnavailableConfiguration(t.Context(), op, unavailable) || len(e.configurationFailureNext) != 1 || strings.Count(output.String(), "\n") != 257 { + t.Fatal("diagnostic throttle did not expire") + } +} diff --git a/internal/reviewexec/hosted_query.go b/internal/reviewexec/hosted_query.go index f20adc039..5e0864b09 100644 --- a/internal/reviewexec/hosted_query.go +++ b/internal/reviewexec/hosted_query.go @@ -32,7 +32,7 @@ type HostedAllowanceQuery struct { } func hostedQueryUnavailable() error { - return core.Fail("storage_unavailable", "Stored hosted allowance query is unavailable.", 500) + return newStoredUnavailable(storedHostedQuery, "Stored hosted allowance query is unavailable.") } func hostedQueryIntent(a Attempt, o Operation) (reviewprovider.HostedTriggerIntent, string, error) { intent := reviewprovider.HostedTriggerIntent{OperationID: o.ID, AttemptID: a.ID, HeadSHA: o.HeadSHA} @@ -55,7 +55,14 @@ func validHostedQueryComment(query HostedAllowanceQuery, comment reviewprovider. // readHostedQuery validates indexed facts against canonical owned JSON and the // original operation. Later review admission may have a separately refreshed // anchor; it cannot rewrite this earlier query's source observation. -func readHostedQuery(ctx context.Context, tx *sql.Tx, a Attempt, o Operation) (HostedAllowanceQuery, error) { +func readHostedQuery(ctx context.Context, tx EvidenceQuery, a Attempt, o Operation) (HostedAllowanceQuery, error) { + if o.AttemptID != a.ID { + var err error + o, err = historicalCooldownOperation(ctx, tx, o, a) + if err != nil { + return HostedAllowanceQuery{}, err + } + } var record HostedAllowanceQuery var id, project, attempt, operation, fingerprint, body string var revision int64 diff --git a/internal/reviewexec/hosted_query_test.go b/internal/reviewexec/hosted_query_test.go index 765d975bc..d23900f1a 100644 --- a/internal/reviewexec/hosted_query_test.go +++ b/internal/reviewexec/hosted_query_test.go @@ -44,12 +44,13 @@ func TestHostedQueryMigrationConcurrentBeginAndRetainedReplay(t *testing.T) { f, a, anchor, poster, provider := hostedQueryFixture(t) originalAttempt := attemptState(t, f, a) original := evidenceState(t, f, a) + restorePreSelectionExecutionSchema(t, f) admissionSQL(t, f, `DROP TABLE review_hosted_preflight`) admissionSQL(t, f, `DROP TABLE review_hosted_allowance_queries`) admissionSQL(t, f, `UPDATE metadata SET value='5' WHERE key='schema:review_execution'`) cliAllowanceReopen(t, f) var version string - if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "6" || evidenceState(t, f, a) != original { + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil || version != "10" || evidenceState(t, f, a) != original { t.Fatal("v5 upgrade changed retained state", version, err) } type result struct { diff --git a/internal/reviewexec/hosted_settlement.go b/internal/reviewexec/hosted_settlement.go index e41cce02a..e11ee3e3a 100644 --- a/internal/reviewexec/hosted_settlement.go +++ b/internal/reviewexec/hosted_settlement.go @@ -184,6 +184,9 @@ func (e *Engine) settleHostedHTTP(w http.ResponseWriter, r *http.Request) { if err := e.transitionRow(ctx, tx, a, reason, at); err != nil { return nil, err } + if err := core.AppendEvent(ctx, tx, scope, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { + return nil, err + } if err := core.AppendEvent(ctx, tx, scope, "review.hosted_settled", a.ID, a.Revision, audit); err != nil { return nil, err } diff --git a/internal/reviewexec/hosted_wait.go b/internal/reviewexec/hosted_wait.go new file mode 100644 index 000000000..dc149e503 --- /dev/null +++ b/internal/reviewexec/hosted_wait.go @@ -0,0 +1,426 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "math" + "net/http" + "strconv" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +const operationWaitHeader = "X-FC-Operation-Wait" + +// Version 1 advertised Hosted cooldown baselines only. Keep its existing CLI +// queued/pause shape; version 2 additionally understands CLI quota baselines. +// Version 3 adds the retained provider allowance estimate, never a retry clock. +func operationWaitForResponse(wait *OperationWait, channel, version string) *OperationWait { + if wait == nil || version != "1" && version != "2" && version != "3" { + return nil + } + if version == "1" && channel == "cli" && wait.BaselineAttemptID != "" { + return &OperationWait{Paused: wait.Paused} + } + if version != "3" { + copy := *wait + copy.CLIAllowance = nil + return © + } + return wait +} + +// Keep engine-level held facts intact while preserving older strict HTTP shapes. +func operationForResponse(operation Operation, version string) Operation { + // These columns preserve later-schema storage, but none of this slice's + // response capabilities negotiates their public request/response contract. + operation.AllowOutOfOrder, operation.OverrideFileLimit = false, false + operation.Wait = operationWaitForResponse(operation.Wait, operation.Channel, version) + if version != "3" { + operation.Allowance = nil + } + return operation +} + +// OperationWait retains dispatch scheduling, not provider availability or review +// completion. A paused ordinary queued operation need not have a cooldown. +type OperationWait struct { + CLIAllowance *AllowanceObservation `json:"cli_allowance,omitempty"` + BaselineAttemptID string `json:"baseline_attempt_id,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` + Paused bool `json:"paused"` +} + +func waitUnavailable() error { + return newStoredUnavailable(storedWaitingIntent, "Stored review waiting intent is unavailable.") +} + +func isWaitUnavailable(err error) bool { + return isStoredUnavailable(err, storedWaitingIntent) +} + +// Only absent or proven malformed retained dependencies describe a broken wait. +// Operational storage failures, including already normalized ones, keep their cause. +func waitDependencyError(err error) error { + if errors.Is(err, sql.ErrNoRows) || storedAllowanceUnavailable(err) || isStoredUnavailable(err, storedHostedObservation) || isStoredUnavailable(err, storedReviewAdmission) { + return waitUnavailable() + } + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "not_found" { + return waitUnavailable() + } + return err +} + +func readOperationWait(ctx context.Context, q EvidenceQuery, o Operation) (*OperationWait, error) { + var version string + if err := q.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil { + return nil, err + } + schemaVersion, err := strconv.Atoi(version) + if err != nil || schemaVersion < 1 || strconv.Itoa(schemaVersion) != version { + return nil, waitUnavailable() + } + if schemaVersion < 9 { + return nil, nil + } + var result OperationWait + var baseline sql.NullString + var paused int64 + err = q.QueryRowContext(ctx, `SELECT baseline_attempt_id,retry_not_before,paused FROM review_operation_waits WHERE operation_id=?`, o.ID).Scan(&baseline, &result.RetryNotBefore, &paused) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + result.BaselineAttemptID, result.Paused = baseline.String, paused == 1 + if paused != 0 && paused != 1 || baseline.Valid != (result.RetryNotBefore != "") || baseline.Valid && (!hostedObservationID(baseline.String, "review_attempt_") || !validChannel(o.Channel)) { + return nil, waitUnavailable() + } + if baseline.Valid { + if _, ok := hostedObservationTime(result.RetryNotBefore); !ok { + return nil, waitUnavailable() + } + a, err := readAttempt(ctx, q, o.ProjectID, baseline.String) + if err != nil { + return nil, waitDependencyError(err) + } + if a.State != "held" || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + return nil, waitUnavailable() + } + original, err := historicalCooldownOperation(ctx, q, o, a) + if err != nil { + return nil, err + } + if o.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, q, original, a) + if err != nil { + return nil, waitDependencyError(err) + } + if record.Observation.Remaining != 0 { + return nil, waitUnavailable() + } + in := record.Observation + result.CLIAllowance = &AllowanceObservation{Kind: "cli_exhausted", ObservedAt: in.ObservedAt, Remaining: &in.Remaining, Limit: &in.Limit, FullCapacityInMS: &in.FullCapacityInMS, RollingWindowMS: &in.RollingWindowMS} + } else { + record, err := readHostedAllowanceRecord(ctx, q, original, a) + if err != nil { + return nil, waitDependencyError(err) + } + if record.Input.Observation.State != "cooldown_observed" { + return nil, waitUnavailable() + } + } + latest, err := latestCooldownAttempt(ctx, q, o) + if err != nil { + return nil, err + } + if latest.Provider != a.Provider || latest.Account != a.Account { + return nil, waitUnavailable() + } + due, err := retainedCooldownDeadline(ctx, q, o, latest) + if err != nil { + return nil, err + } + if due.UTC().Format(time.RFC3339Nano) != result.RetryNotBefore { + return nil, waitUnavailable() + } + } + return &result, nil +} + +// currentOperationWait exposes pending scheduling only; retained rows still +// bind historical cooldowns after a later attempt starts or the request ends. +func currentOperationWait(o Operation) *OperationWait { + if o.State != "queued" || o.AttemptID != "" { + return nil + } + return o.Wait +} + +func (e *Engine) sampleExecutionTime() time.Time { + if e.schedulingNow != nil { + return e.schedulingNow() + } + return time.Now() +} + +func mustWaitTime(value string) time.Time { + // readOperationWait already validated the canonical timestamp. + at, _ := time.Parse(time.RFC3339Nano, value) + return at +} + +// historicalCooldownOperation supplies immutable original attribution for local +// history reads only. Live query/admission/action checks still require the real +// operation's current attempt. Only proven unused cooldown attempts qualify. +func historicalCooldownOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (Operation, error) { + if o.AttemptID == a.ID { + return o, nil + } + if o.Channel == "cli" { + return historicalCLIExhaustionOperation(ctx, q, o, a) + } + if o.Channel != "hosted" || a.OperationID != o.ID || a.ProjectID != o.ProjectID || a.State != "held" || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + return Operation{}, waitUnavailable() + } + var reason, state string + var owns bool + if err := q.QueryRowContext(ctx, `SELECT state,reason FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&state, &reason); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return Operation{}, waitUnavailable() + } + return Operation{}, err + } + if state != "held" || reason != "hosted_allowance_cooldown" { + return Operation{}, waitUnavailable() + } + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operation_waits WHERE operation_id=? AND baseline_attempt_id IS NOT NULL)`, o.ID).Scan(&owns); err != nil { + return Operation{}, err + } + if !owns { + return Operation{}, waitUnavailable() + } + o.AttemptID, o.State, o.Reason = a.ID, "held", reason + o.Wait = nil + return o, nil +} + +// RetryBaseline returns the first proven cooldown's source, never permission +// to reuse its allowance query. Every fresh attempt must compare before posting +// its own query and must independently pass the normal final action guards. +func (e *Engine) RetryBaseline(ctx context.Context, project, operationID string) (*Anchor, error) { + if !identifier.MatchString(project) || !hostedObservationID(operationID, "review_operation_") { + return nil, invalid() + } + var result *Anchor + err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + o, err := readOperationBase(ctx, tx, project, operationID) + if err != nil || o.Wait == nil || o.Wait.BaselineAttemptID == "" { + return err + } + a, err := readAttempt(ctx, tx, project, o.Wait.BaselineAttemptID) + if err != nil { + return err + } + original, err := historicalCooldownOperation(ctx, tx, o, a) + if err != nil { + return err + } + if o.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, tx, original, a) + if err == nil { + anchor := record.Observation.Anchor + result = &anchor + } + return err + } + record, err := readHostedAllowanceRecord(ctx, tx, original, a) + if err == nil { + anchor := record.Input.Anchor + result = &anchor + } + return err + }) + return result, err +} + +// ScheduleHostedCooldown atomically ends a proven unused attempt and releases +// shared capacity while preserving the same queued authorization. It never +// reopens a terminal request and never accepts caller-supplied cooldown facts. +func (e *Engine) ScheduleHostedCooldown(ctx context.Context, project, attemptID string, expectedAttemptRevision int64) (Attempt, error) { + var result Attempt + err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + var err error + result, err = e.scheduleHostedCooldown(ctx, tx, project, attemptID, expectedAttemptRevision) + return err + }) + if err == nil { + e.notifyOperation(result.OperationID) + } + return result, err +} + +// Used by normal preparation and startup recovery in their existing atomic write. +func (e *Engine) scheduleHostedCooldown(ctx context.Context, tx *sql.Tx, project, attemptID string, expectedAttemptRevision int64) (Attempt, error) { + a, err := readAttempt(ctx, tx, project, attemptID) + if err != nil { + return Attempt{}, err + } + o, err := readOperationBase(ctx, tx, project, a.OperationID) + if err != nil { + return Attempt{}, err + } + if a.Revision != expectedAttemptRevision || a.State != "preparing" || o.State != "preparing" || o.AttemptID != a.ID || o.Channel != "hosted" || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" || a.Revision == math.MaxInt64 || o.Revision == math.MaxInt64 { + return Attempt{}, conflict() + } + record, err := readHostedAllowanceRecord(ctx, tx, o, a) + if err != nil { + return Attempt{}, err + } + if record.Input.Observation.State != "cooldown_observed" { + return Attempt{}, waitUnavailable() + } + now := e.sampleExecutionTime().UTC() + due := record.Input.Observation.RetryNotBefore + if !due.After(now) || o.Wait != nil && o.Wait.RetryNotBefore != "" && !due.After(mustWaitTime(o.Wait.RetryNotBefore)) { + return Attempt{}, core.Fail("review_cooldown_elapsed", "The proven cooldown deadline has already elapsed; retain an explicit hold instead of retrying immediately.", 409) + } + at, err := attemptRecordingStamp(ctx, tx, o, &a, e.sampleAttemptTime()) + if err != nil { + return Attempt{}, err + } + recorded, valid := attemptRecordedTime(at) + if !valid || !due.After(recorded) { + return Attempt{}, core.Fail("review_cooldown_elapsed", "The proven cooldown deadline has already elapsed; retain an explicit hold instead of retrying immediately.", 409) + } + baseline := a.ID + if o.Wait != nil && o.Wait.BaselineAttemptID != "" { + baseline = o.Wait.BaselineAttemptID + } + a.State, a.Revision = "held", a.Revision+1 + if _, err := tx.ExecContext(ctx, `UPDATE review_execution_attempts SET state='held',revision=? WHERE id=?`, a.Revision, a.ID); err != nil { + return Attempt{}, err + } + // Project the real terminal preparation attempt while it is still the + // operation's current attempt, then detach it for the durable wait. + if _, err := tx.ExecContext(ctx, `UPDATE review_operations SET state='held',reason='hosted_allowance_cooldown',revision=revision+1,updated_at=? WHERE id=?`, at, o.ID); err != nil { + return Attempt{}, err + } + if err := e.transitionRow(ctx, tx, a, "hosted_allowance_cooldown", at); err != nil { + return Attempt{}, err + } + // Projection reads the previous detached cooldown while this attempt is + // still current. Install its replacement timer before atomically detaching. + if _, err := tx.ExecContext(ctx, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,?,?,0) ON CONFLICT(operation_id) DO UPDATE SET baseline_attempt_id=excluded.baseline_attempt_id,retry_not_before=excluded.retry_not_before`, o.ID, baseline, due.Format(time.RFC3339Nano)); err != nil { + return Attempt{}, err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM review_execution_reservations WHERE attempt_id=?`, a.ID); err != nil { + return Attempt{}, err + } + if _, err := tx.ExecContext(ctx, `UPDATE review_operations SET state='queued',reason='',attempt_id='' WHERE id=?`, o.ID); err != nil { + return Attempt{}, err + } + if err := core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { + return Attempt{}, err + } + return a, nil +} + +type OperationControl struct { + ExpectedRevision int64 `json:"expected_revision"` + Action string `json:"action"` +} + +type OperationControlReceipt struct { + ID string `json:"id"` + State string `json:"state"` + Revision int64 `json:"revision"` + Paused bool `json:"paused"` + RetryNotBefore string `json:"retry_not_before,omitempty"` +} + +func (e *Engine) ControlOperation(ctx context.Context, scope core.Scope, key, id string, input OperationControl) (json.RawMessage, error) { + if !hostedObservationID(id, "review_operation_") || input.ExpectedRevision < 1 || input.Action != "pause" && input.Action != "resume" && input.Action != "cancel" { + return nil, invalid() + } + result, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.operation.control", Target: id, Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { + o, err := readOperationBase(ctx, tx, scope.ProjectID, id) + if err != nil { + return nil, err + } + if o.Revision != input.ExpectedRevision || o.Revision == math.MaxInt64 { + return nil, conflict() + } + if o.State != "queued" || o.AttemptID != "" { + return nil, core.Fail("review_operation_started", "Only an undispatched queued review can be paused, resumed or cancelled; provider work is unchanged.", 409) + } + paused := input.Action == "pause" + state := "queued" + if input.Action == "cancel" { + state = "cancelled" + } + if _, err := tx.ExecContext(ctx, `INSERT INTO review_operation_waits(operation_id,paused) VALUES(?,?) ON CONFLICT(operation_id) DO UPDATE SET paused=excluded.paused`, id, paused); err != nil { + return nil, err + } + at, err := attemptRecordingStamp(ctx, tx, o, nil, e.sampleAttemptTime()) + if err != nil { + return nil, err + } + reason := "" + if state == "queued" && o.Reason == cliDraftWait { + reason = o.Reason + } + if _, err := tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,updated_at=? WHERE id=?`, state, reason, at, id); err != nil { + return nil, err + } + if err := core.AppendEvent(ctx, tx, scope, "review.operation_updated", id, o.Revision+1, map[string]string{"action": input.Action}); err != nil { + return nil, err + } + receipt := OperationControlReceipt{ID: id, State: state, Revision: o.Revision + 1, Paused: paused} + if o.Wait != nil { + receipt.RetryNotBefore = o.Wait.RetryNotBefore + } + return receipt, nil + }) + if err == nil { + e.notifyOperation(id) + select { + case e.wake <- struct{}{}: + default: + } + } + return result, err +} + +func (e *Engine) controlOperationHTTP(w http.ResponseWriter, r *http.Request) { + scope, err := e.store.Scope(r, "write") + if err != nil { + core.WriteError(w, err) + return + } + if _, err := core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + var input OperationControl + if err := core.ReadJSON(w, r, &input); err != nil { + core.WriteError(w, err) + return + } + key, err := core.IdempotencyKey(r, "idempotency_key_required") + if err != nil { + core.WriteError(w, err) + return + } + value, err := e.ControlOperation(r.Context(), scope, key, r.PathValue("operation_id"), input) + if err != nil { + core.WriteError(w, err) + return + } + core.WriteJSON(w, http.StatusOK, value) +} diff --git a/internal/reviewexec/hosted_wait_isolation_test.go b/internal/reviewexec/hosted_wait_isolation_test.go new file mode 100644 index 000000000..25b91a8c2 --- /dev/null +++ b/internal/reviewexec/hosted_wait_isolation_test.go @@ -0,0 +1,87 @@ +package reviewexec + +import ( + "context" + "testing" + "time" +) + +func TestHostedWaitHistoryIsolatesProjectAndChannel(t *testing.T) { + for _, due := range []bool{false, true} { + for _, dependency := range []string{"preflight", "query"} { + name := dependency + "/predecessor" + if due { + name = dependency + "/candidate" + } + t.Run(name, func(t *testing.T) { + f, a, cooldown, now := queuedCooldown(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + blocked := f.enqueue(t, attemptProject, "later-hosted", "hosted", 4, 1) + cli := f.enqueue(t, attemptProject, "healthy-cli", "cli", 2, 1) + hosted := f.enqueue(t, otherAttemptProject, "healthy-hosted", "hosted", 2, 1) + table := "review_hosted_preflight" + if dependency == "query" { + table = "review_hosted_allowance_queries" + } + admissionSQL(t, f, "UPDATE "+table+" SET body_json='private-damaged-wait' WHERE attempt_id=?", a.ID) + *now = cooldown.Observation.RetryNotBefore.Add(-time.Second) + if due { + *now = cooldown.Observation.RetryNotBefore + } + tables := []string{"review_operations", "review_execution_attempts", "review_operation_waits", table, "review_execution_reservations", "events"} + before := map[string]string{} + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + for _, probe := range []bool{false, true} { + pending, err := f.e.pendingForWorker(t.Context(), probe) + if err != nil { + t.Fatal("damaged Hosted wait stopped selection", err) + } + got := map[string]bool{} + for _, o := range pending { + got[o.ID] = true + } + if len(got) != 2 || !got[cli.ID] || !got[hosted.ID] || got[blocked.ID] || got[a.OperationID] { + t.Fatal("wait scope or predecessor priority lost", got) + } + } + for _, table := range tables { + if before[table] != snapshotTable(t, f, table) { + t.Fatal("selection mutated retained state", table) + } + } + seen := map[string]int{} + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + seen[o.ID]++ + return Preparation{}, sourceHold("synthetic_isolation_hold") + }} + for _, probe := range []bool{false, true} { + if err := f.e.processNextForWorker(t.Context(), map[string]Driver{"test-capability": driver}, probe); err != nil { + t.Fatal("damaged Hosted wait stopped healthy work", err) + } + } + if seen[cli.ID] != 1 || seen[hosted.ID] != 1 || seen[blocked.ID] != 0 || seen[a.OperationID] != 0 || driver.calls.Load() != 0 { + t.Fatal("healthy work or damaged scope changed", seen) + } + if supervisorOperationState(t, f, a.OperationID) != "queued" || supervisorOperationState(t, f, blocked.ID) != "queued" || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("damaged wait changed lifecycle or acquired capacity") + } + if before[table] != snapshotTable(t, f, table) { + t.Fatal("continuation rewrote damaged evidence") + } + }) + } + } +} + +func TestHostedWaitLookupFailureRemainsFatal(t *testing.T) { + f, _, cooldown, now := queuedCooldown(t) + *now = cooldown.Observation.RetryNotBefore + admissionSQL(t, f, `DROP TABLE review_hosted_preflight`) + if _, err := f.e.pending(t.Context()); err == nil || isWaitUnavailable(err) { + t.Fatal("database failure suppressed or relabeled", err) + } + err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": &controlledDriver{}}) + attemptCode(t, err, "review_persistence_failed") +} diff --git a/internal/reviewexec/hosted_wait_test.go b/internal/reviewexec/hosted_wait_test.go new file mode 100644 index 000000000..24e1a19a6 --- /dev/null +++ b/internal/reviewexec/hosted_wait_test.go @@ -0,0 +1,995 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/reviewprovider" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" +) + +func queuedCooldown(t *testing.T) (*attemptFixture, Attempt, HostedAllowanceInput, *time.Time) { + t.Helper() + f, a, in := cooldownObservationFixture(t) + now := time.Now().UTC() + f.e.schedulingNow = func() time.Time { return now } + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, 1); err != nil { + t.Fatal(err) + } + return f, a, in, &now +} + +func TestCooldownSchemaRetainsDependentRows(t *testing.T) { + f, a, in := cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + // Retain real CLI preflight and final evidence beside the preparing + // Hosted query/observation/reservation, exercising every dependent table. + cli := f.start(t, attemptProject, f.enqueue(t, attemptProject, "migration-cli", "cli", 4, 1)) + anchor := attemptAnchor(attemptProject, 4) + if err := f.e.RecordCLIAllowance(t.Context(), attemptProject, cli.ID, 1, CLIAllowanceObservation{Anchor: anchor, ObservedAt: stamp(), Remaining: 3, Limit: 5, FullCapacityInMS: 12000, RollingWindowMS: 3600000, ChangedFiles: 2}); err != nil { + t.Fatal(err) + } + cli, err := f.e.Admit(t.Context(), attemptProject, cli.ID, 1, anchor, "") + if err != nil { + t.Fatal(err) + } + digest := strings.Repeat("1", 64) + capture := ReviewEvidenceInput{CaptureID: "review_capture_" + digest[:32], CaptureSHA256: digest, CaptureBytes: 1024, StartedAt: stamp(), FinishedAt: stamp(), ExpectedAnchor: anchor, Review: reviewprovider.ParsedReview{Outcome: "completed", Complete: true, ReportedFindings: 0, ReviewedFiles: []string{"changed.go"}}} + if _, err := f.e.RecordReviewEvidence(t.Context(), attemptProject, cli.ID, capture); err != nil { + t.Fatal(err) + } + + tables := []string{"review_execution_attempts", "review_execution_reservations", "review_execution_transitions", "review_cli_preflight", "review_hosted_preflight", "review_hosted_allowance_queries", "review_execution_evidence", "review_hosted_observations", "review_operations", "receipts", "events"} + before := map[string]string{} + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + restorePreCooldownAttemptSchema(t, f) + admissionSQL(t, f, `UPDATE metadata SET value='8' WHERE key='schema:review_execution'`) + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal("retained migration", err) + } + for _, table := range tables { + if after := snapshotTable(t, f, table); after != before[table] { + t.Fatalf("migration rewrote %s", table) + } + } + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal("idempotent migration", err) + } + if err := validateExecutionForeignKeysTest(t.Context(), f.store.DB()); err != nil { + t.Fatal(err) + } +} + +func snapshotTable(t *testing.T, f *attemptFixture, table string) string { + t.Helper() + rows, err := f.store.DB().Query(`SELECT * FROM ` + table + ` ORDER BY rowid`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + columns, err := rows.Columns() + if err != nil { + t.Fatal(err) + } + result := [][]any{} + for rows.Next() { + values := make([]any, len(columns)) + ptrs := make([]any, len(columns)) + for i := range values { + ptrs[i] = &values[i] + } + if err := rows.Scan(ptrs...); err != nil { + t.Fatal(err) + } + result = append(result, values) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(result) + return string(b) +} +func validateExecutionForeignKeysTest(ctx context.Context, db *sql.DB) error { + c, err := db.Conn(ctx) + if err != nil { + return err + } + defer c.Close() + return validateExecutionForeignKeys(ctx, c) +} + +func TestCooldownWaitDueRestartAndOriginalHistory(t *testing.T) { + f, a, in, now := queuedCooldown(t) + scope := f.scope(t, attemptProject, f.writer, false) + o := bindingOperation(t, f, scope, a.OperationID) + if o.State != "queued" || o.AttemptID != "" || o.Wait == nil || o.Wait.BaselineAttemptID != a.ID || o.Wait.RetryNotBefore != in.Observation.RetryNotBefore.Format(time.RFC3339Nano) || o.Wait.Paused { + t.Fatal("wait", o) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("cooldown retained capacity") + } + original := snapshotTable(t, f, "review_hosted_preflight") + snapshotTable(t, f, "review_hosted_allowance_queries") + snapshotTable(t, f, "review_hosted_observations") + pending, err := f.e.pending(t.Context()) + if err != nil || len(pending) != 0 { + t.Fatal("early scheduler", pending, err) + } + early, err := f.e.StartAttempt(t.Context(), attemptProject, o.ID) + if err != nil || early.ID != "" { + t.Fatal("early attempt", early, err) + } + cliAllowanceReopen(t, f) + f.e.schedulingNow = func() time.Time { return *now } + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + after := bindingOperation(t, f, scope, a.OperationID) + if !reflect.DeepEqual(o, after) { + t.Fatal("restart changed wait", after) + } + *now = in.Observation.RetryNotBefore + pending, err = f.e.pending(t.Context()) + if err != nil || len(pending) != 1 { + t.Fatal("due scheduler", pending, err) + } + next := f.start(t, attemptProject, Receipt{ID: o.ID}) + if next.ID == a.ID || next.OperationID != a.OperationID { + t.Fatal("retry identity", next) + } + baseline, err := f.e.RetryBaseline(t.Context(), attemptProject, o.ID) + if err != nil || baseline == nil || *baseline != in.Anchor { + t.Fatal("baseline", baseline, err) + } + if records, err := f.e.ReadHostedObservations(t.Context(), attemptProject, a.ID); err != nil || len(records) != 1 { + t.Fatal("old observations", records, err) + } + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal("historical replay", err) + } + if original != snapshotTable(t, f, "review_hosted_preflight")+snapshotTable(t, f, "review_hosted_allowance_queries")+snapshotTable(t, f, "review_hosted_observations") { + t.Fatal("retry rewrote prior source") + } + + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts WHERE operation_id=?`, o.ID) != 2 { + t.Fatal("attempt history") + } +} + +func timerControl(t *testing.T, f *attemptFixture, id, action, key string) OperationControlReceipt { + t.Helper() + scope := f.scope(t, attemptProject, f.writer, false) + o := bindingOperation(t, f, scope, id) + raw, err := f.e.ControlOperation(t.Context(), scope, key, id, OperationControl{ExpectedRevision: o.Revision, Action: action}) + if err != nil { + t.Fatal(action, err) + } + var receipt OperationControlReceipt + if json.Unmarshal(raw, &receipt) != nil { + t.Fatal("control receipt") + } + return receipt +} + +func TestCooldownControlPauseResumeCancelAndProjectPause(t *testing.T) { + for _, scenario := range []string{"operation pause", "project pause", "cancel"} { + t.Run(scenario, func(t *testing.T) { + f, a, in, now := queuedCooldown(t) + scope := f.scope(t, attemptProject, f.writer, false) + switch scenario { + case "operation pause": + timerControl(t, f, a.OperationID, "pause", "pause") + case "project pause": + f.configure(t, attemptProject, "test-capability", 1, true) + case "cancel": + timerControl(t, f, a.OperationID, "cancel", "cancel") + } + *now = in.Observation.RetryNotBefore.Add(time.Hour) + pending, err := f.e.pending(t.Context()) + if err != nil || len(pending) != 0 { + t.Fatal("paused/cancelled scheduled", pending, err) + } + got, err := f.e.StartAttempt(t.Context(), attemptProject, a.OperationID) + if scenario == "cancel" { + attemptCode(t, err, "review_conflict") + o := bindingOperation(t, f, scope, a.OperationID) + if o.State != "cancelled" || o.Wait != nil { + t.Fatal("cancel projection", o) + } + return + } + if err != nil || got.ID != "" { + t.Fatal("paused started", got, err) + } + if scenario == "project pause" { + f.configure(t, attemptProject, "test-capability", 2, false) + } else { + timerControl(t, f, a.OperationID, "resume", "resume") + } + next := f.start(t, attemptProject, Receipt{ID: a.OperationID}) + if next.ID == a.ID { + t.Fatal("resume reused attempt") + } + o := bindingOperation(t, f, scope, a.OperationID) + if o.ConfigurationRevision != 1 || o.Wait != nil { + t.Fatal("resume projection/provenance", o) + } + _, err = f.e.ControlOperation(t.Context(), scope, "too-late", o.ID, OperationControl{ExpectedRevision: o.Revision, Action: "cancel"}) + attemptCode(t, err, "review_operation_started") + }) + } +} + +func TestCooldownDueRechecksCurrentAuthority(t *testing.T) { + for _, scenario := range []string{"revoked", "policy", "capability", "configuration", "closed allocation"} { + t.Run(scenario, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var in HostedAllowanceInput + if scenario == "closed allocation" { + f = roundFixture(t) + roundGrant(t, f, 2, "hosted", 0, 0, 3, "grant") + a = f.start(t, attemptProject, f.enqueue(t, attemptProject, "bound-cooldown", "hosted", 2, 1)) + in = retainTimerCooldown(t, f, a, 3*time.Minute) + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, 1); err != nil { + t.Fatal(err) + } + if configured, err := f.e.RoundAdmission(t.Context(), attemptProject, a.OperationID); err != nil || !configured { + t.Fatal("cooldown request lost its original grant binding", configured, err) + } + } else { + f, a, in, _ = queuedCooldown(t) + } + switch scenario { + case "revoked": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "policy": + admissionPolicy(t, f, 1) + case "capability": + bindEngine(t, f, Capability{ID: "test-capability", Provider: "coderabbit", Account: "changed-account", Channels: []string{"cli", "hosted"}}) + case "configuration": + f.configure(t, attemptProject, "other-account", 1, false) + case "closed allocation": + revision := int64(1) + if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "close", 2, "hosted", RoundControlRequest{ExpectedRevision: &revision, Action: "close"}); err != nil { + t.Fatal(err) + } + } + f.e.schedulingNow = func() time.Time { return in.Observation.RetryNotBefore } + next, err := f.e.StartAttempt(t.Context(), attemptProject, a.OperationID) + if err != nil || next.ID != "" { + t.Fatal("changed authority started", next, err) + } + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_operations WHERE id=?`, a.OperationID).Scan(&state, &reason); err != nil { + t.Fatal(err) + } + if state != "held" || reason == "" { + t.Fatal("missing explicit hold", state, reason) + } + if scenario == "closed allocation" && reason != "review_round_closed" { + t.Fatal("closed bound allocation held for another reason", reason) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts WHERE operation_id=?`, a.OperationID) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("authority refusal allocated retry") + } + }) + } +} + +func TestCooldownWaitProgressAndWireOptIn(t *testing.T) { + f, a, _, _ := queuedCooldown(t) + progress, err := f.e.ReadRoundProgressStages(t.Context(), evidenceReadScope(t, f, attemptProject, f.reader), []int64{2}) + if err != nil || progress.Items[0].Channels[0].Wait == nil || progress.Items[0].Channels[1].Wait != nil { + t.Fatal("current channel wait", progress, err) + } + for _, path := range []string{"/api/v1/projects/" + attemptProject + "/reviews/operations/" + a.OperationID, "/api/v1/projects/" + attemptProject + "/reviews/operations/" + a.OperationID + "/status", roundProgressPath(attemptProject) + "?pull_numbers=2&view=stages"} { + for _, opt := range []bool{false, true} { + r := httptest.NewRequest(http.MethodGet, path, nil) + r.Header.Set("Authorization", "Bearer "+f.reader) + if opt { + r.Header.Set(operationWaitHeader, "1") + } + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code != 200 || strings.Contains(w.Body.String(), `"wait":`) != opt { + t.Fatal("wire opt-in", path, opt, w.Code, w.Body.String()) + } + } + } +} + +func TestOperationHTTPPreservesReservedFlagsWithoutExposingThem(t *testing.T) { + f := supervisorFixture(t) + receipt := f.enqueue(t, attemptProject, "reserved-operation-flags", "cli", 2, 1) + admissionSQL(t, f, `UPDATE review_operations SET state='held',reason='synthetic_hold',allow_out_of_order=1,override_file_limit=1 WHERE id=?`, receipt.ID) + before := snapshotTable(t, f, "review_operations") + for _, version := range []string{"", "1", "2", "3", "4", "5", "unsupported"} { + for _, method := range []string{http.MethodGet, http.MethodPost} { + t.Run(method+"/"+version, func(t *testing.T) { + path := "/api/v1/projects/" + attemptProject + "/reviews/operations/" + receipt.ID + body, token := "", f.reader + if method == http.MethodPost { + path = "/api/v1/projects/" + attemptProject + "/reviews/requests" + body = encoded(Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "cli", HeadSHA: attemptAnchor(attemptProject, 2).CandidateSHA}) + token = f.writer + } + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Idempotency-Key", "reserved-operation-flags") + r.Header.Set("Prefer", "wait=1") + r.Header.Set(operationWaitHeader, version) + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code != http.StatusOK { + t.Fatal(w.Code, w.Body.String()) + } + if strings.Contains(w.Body.String(), `"allow_out_of_order"`) || strings.Contains(w.Body.String(), `"override_file_limit"`) { + t.Fatal("reserved flags escaped without a negotiated contract", w.Body.String()) + } + var legacy client.ReviewOperation + decoder := json.NewDecoder(w.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&legacy); err != nil || legacy.ID != receipt.ID || legacy.State != "held" { + t.Fatal("strict client rejected unnegotiated operation shape", legacy, err) + } + }) + } + } + o := cliWaitRead(t, f, receipt.ID) + if !o.AllowOutOfOrder || !o.OverrideFileLimit || before != snapshotTable(t, f, "review_operations") { + t.Fatal("HTTP projection mutated retained flags", o) + } +} + +func TestCooldownSnapshotRejectsCorruptWaitOwnership(t *testing.T) { + for _, scenario := range []string{"valid queued", "valid current retry", "deadline", "baseline", "queued pointer", "reservation", "evidence", "terminal held time", "missing transition"} { + t.Run(scenario, func(t *testing.T) { + f, a, in, now := queuedCooldown(t) + switch scenario { + case "valid current retry": + *now = in.Observation.RetryNotBefore + f.start(t, attemptProject, Receipt{ID: a.OperationID}) + case "deadline": + admissionSQL(t, f, `UPDATE review_operation_waits SET retry_not_before=?`, in.Observation.RetryNotBefore.Add(time.Hour).Format(time.RFC3339Nano)) + case "baseline": + admissionSQL(t, f, `UPDATE review_operations SET attempt_id=? WHERE id=?`, a.ID, a.OperationID) + case "queued pointer": + admissionSQL(t, f, `UPDATE review_operations SET state='active' WHERE id=?`, a.OperationID) + case "reservation": + admissionSQL(t, f, `INSERT INTO review_execution_reservations(provider,repository_id,pull_number,action_class,account,attempt_id) VALUES('coderabbit',801,2,'hosted','test-account',?)`, a.ID) + case "evidence": + admissionSQL(t, f, `INSERT INTO review_execution_evidence(id,project_id,attempt_id,operation_id,body_json,fingerprint) VALUES('corrupt',?,?,?,'{}','corrupt')`, attemptProject, a.ID, a.OperationID) + case "terminal held time": + admissionSQL(t, f, `UPDATE review_execution_transitions SET created_at=? WHERE attempt_id=? AND revision=2`, in.Observation.RetryNotBefore.Format(time.RFC3339Nano), a.ID) + case "missing transition": + admissionSQL(t, f, `DELETE FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, a.ID) + } + tx, err := f.store.DB().BeginTx(t.Context(), &sql.TxOptions{ReadOnly: true}) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + err = ValidateOperationWaitsSnapshot(t.Context(), tx) + if strings.HasPrefix(scenario, "valid") { + if err != nil { + t.Fatal(err) + } + } else if err == nil { + t.Fatal("corrupt wait accepted") + } else if scenario == "missing transition" { + attemptCode(t, err, "storage_unavailable") + } + }) + } +} + +func TestHistoricalCooldownLookupPreservesCancellation(t *testing.T) { + f, staleAttempt, _, _ := queuedCooldown(t) + currentAttempt, err := readAttempt(context.Background(), f.store.DB(), attemptProject, staleAttempt.ID) + if err != nil { + t.Fatal(err) + } + operation, err := readOperationBase(context.Background(), f.store.DB(), attemptProject, staleAttempt.OperationID) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := historicalCooldownOperation(ctx, f.store.DB(), operation, currentAttempt); !errors.Is(err, context.Canceled) { + t.Fatal("historical cooldown lookup hid cancellation", err) + } +} + +func TestCooldownSnapshotFindsDetachedHistoryWithoutWaitOrPreflight(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, current := range []bool{false, true} { + t.Run(channel+map[bool]string{false: "/detached", true: "/legacy_current"}[current], func(t *testing.T) { + var f *attemptFixture + var a Attempt + var err error + if channel == "cli" { + f, a, _, _ = cliWaitFixture(t) + } else { + var in HostedAllowanceInput + f, a, in = cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + } + reason, preflight := "allowance_exhausted", "review_cli_preflight" + if channel == "hosted" { + reason, preflight = "hosted_allowance_cooldown", "review_hosted_preflight" + } + if current { + _, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + } else if channel == "cli" { + _, err = f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision) + } else { + _, err = f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision) + } + if err != nil { + t.Fatal(err) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + for _, table := range []string{"review_operation_waits", preflight} { + if _, err := tx.Exec("DELETE FROM " + table); err != nil { + t.Fatal(err) + } + } + err = ValidateOperationWaitsSnapshot(t.Context(), tx) + if current && err != nil { + t.Fatal("legacy current hold requires no detached wait", err) + } + if !current && !isWaitUnavailable(err) { + t.Fatal("detached cooldown lost required evidence without snapshot refusal", err) + } + }) + } + } +} + +func TestScheduleHostedCooldownPreservesAllowanceReadErrors(t *testing.T) { + for _, scenario := range []string{"absent", "malformed", "database", "available"} { + t.Run(scenario, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var in HostedAllowanceInput + if scenario == "available" { + f, a, _, in = hostedAllowanceFixture(t) + if err := f.e.RecordHostedAllowance(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + } else { + f, a, in = cooldownObservationFixture(t) + if scenario != "absent" { + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + } + } + tables := []string{"review_operations", "review_execution_attempts", "review_execution_reservations", "review_execution_transitions", "review_operation_waits", "review_hosted_preflight", "events"} + before := make(map[string]string) + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if scenario == "malformed" { + _, err = tx.ExecContext(t.Context(), `UPDATE review_hosted_preflight SET body_json='{}' WHERE attempt_id=?`, a.ID) + } else if scenario == "database" { + _, err = tx.ExecContext(t.Context(), `DROP TABLE review_hosted_preflight`) + } + if err != nil { + t.Fatal(err) + } + got, err := f.e.scheduleHostedCooldown(t.Context(), tx, attemptProject, a.ID, a.Revision) + if got.ID != "" || err == nil { + t.Fatal("invalid allowance scheduled a cooldown", got, err) + } + switch scenario { + case "absent": + if !errors.Is(err, errAllowanceObservationAbsent) { + t.Error("missing observation classification changed", err) + } + case "malformed": + if !isStoredUnavailable(err, storedHostedObservation) { + t.Error("malformed observation classification changed", err) + } + case "database": + if isWaitUnavailable(err) || !strings.Contains(err.Error(), "no such table: review_hosted_preflight") { + t.Error("database failure became damaged waiting intent", err) + } + case "available": + if !isWaitUnavailable(err) { + t.Error("non-cooldown observation was not refused", err) + } + } + if err := tx.Rollback(); err != nil { + t.Fatal(err) + } + for _, table := range tables { + if snapshotTable(t, f, table) != before[table] { + t.Errorf("failed cooldown changed %s", table) + } + } + }) + } +} + +// Restore the actual schema8 attempt cardinality only in a disposable fixture. +// Other migration regressions invoke this before replaying older migrations. +func restorePreCooldownAttemptSchema(t *testing.T, f *attemptFixture) { + t.Helper() + conn, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + statements := []string{`PRAGMA foreign_keys=OFF`, `DROP TABLE review_operation_waits`, `DROP INDEX review_attempts_operation`, `DROP INDEX review_attempts_live_operation`, `CREATE TABLE old_attempts(id TEXT PRIMARY KEY,operation_id TEXT NOT NULL UNIQUE REFERENCES review_operations(id),project_id TEXT NOT NULL REFERENCES projects(id),provider TEXT NOT NULL,account TEXT NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL,anchor_json TEXT NOT NULL,intent TEXT NOT NULL,external_id TEXT NOT NULL)`, `INSERT INTO old_attempts SELECT * FROM review_execution_attempts`, `DROP TABLE review_execution_attempts`, `ALTER TABLE old_attempts RENAME TO review_execution_attempts`, `PRAGMA foreign_keys=ON`} + for _, statement := range statements { + if _, err := conn.ExecContext(t.Context(), statement); err != nil { + t.Fatal(statement, err) + } + } +} + +func TestCooldownSchemaRejectsDanglingReferencesAndRollsBackFailures(t *testing.T) { + for _, scenario := range []string{"dangling child", "version write failure"} { + t.Run(scenario, func(t *testing.T) { + f, a, in := cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + restorePreCooldownAttemptSchema(t, f) + admissionSQL(t, f, `UPDATE metadata SET value='8' WHERE key='schema:review_execution'`) + if scenario == "dangling child" { + conn, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + for _, statement := range []string{`PRAGMA foreign_keys=OFF`, `UPDATE review_hosted_preflight SET attempt_id='missing-retained-attempt'`, `PRAGMA foreign_keys=ON`} { + if _, err := conn.ExecContext(t.Context(), statement); err != nil { + t.Fatal(err) + } + } + conn.Close() + } else { + admissionSQL(t, f, `CREATE TRIGGER fail_timer_version BEFORE UPDATE ON metadata WHEN NEW.key='schema:review_execution' AND NEW.value='9' BEGIN SELECT RAISE(ABORT,'injected migration failure'); END`) + } + before := snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations") + snapshotTable(t, f, "review_execution_transitions") + snapshotTable(t, f, "review_hosted_preflight") + snapshotTable(t, f, "review_hosted_allowance_queries") + snapshotTable(t, f, "review_hosted_observations") + snapshotTable(t, f, "metadata") + if err := EnsureSchema(t.Context(), f.store); err == nil { + t.Fatal("invalid/injected migration committed") + } + after := snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations") + snapshotTable(t, f, "review_execution_transitions") + snapshotTable(t, f, "review_hosted_preflight") + snapshotTable(t, f, "review_hosted_allowance_queries") + snapshotTable(t, f, "review_hosted_observations") + snapshotTable(t, f, "metadata") + if before != after { + t.Fatal("failed migration changed retained bytes") + } + if attemptCount(t, f.store, `SELECT count(*) FROM sqlite_master WHERE name IN ('review_operation_waits','review_execution_attempts_next','review_attempts_operation','review_attempts_live_operation')`) != 0 { + t.Fatal("failed migration left new schema") + } + var ddl string + if err := f.store.DB().QueryRow(`SELECT sql FROM sqlite_master WHERE name='review_execution_attempts'`).Scan(&ddl); err != nil || !strings.Contains(ddl, "UNIQUE") { + t.Fatal("failed migration lost old attempt uniqueness", ddl, err) + } + var enabled int + if err := f.store.DB().QueryRow(`PRAGMA foreign_keys`).Scan(&enabled); err != nil || enabled != 1 { + t.Fatal("foreign key enforcement changed", enabled, err) + } + }) + } +} + +func retainTimerCooldown(t *testing.T, f *attemptFixture, a Attempt, minutes time.Duration) HostedAllowanceInput { + t.Helper() + anchor := attemptAnchor(attemptProject, 2) + q, created, err := f.e.BeginHostedAllowanceQuery(t.Context(), attemptProject, a.ID, 1, anchor, reviewprovider.Author{ID: 12, Login: "poster", Kind: "User"}, reviewprovider.Author{ID: 30, Login: "coderabbitai[bot]", Kind: "Bot"}) + if err != nil || !created { + t.Fatal("fresh query", err) + } + q, err = f.e.ConfirmHostedAllowanceQuery(t.Context(), attemptProject, a.ID, 1, hostedQueryComment(t, q)) + if err != nil { + t.Fatal(err) + } + digest := strings.Repeat("c", 64) + observed := stamp() + start, _ := time.Parse(time.RFC3339Nano, q.EarliestPosting) + in := HostedAllowanceInput{QueryID: q.ID, Anchor: anchor, ObservedAt: observed, ChangedFiles: 2, CaptureID: "review_capture_" + digest[:32], CaptureSHA256: digest, CaptureBytes: 1234, Observation: reviewprovider.HostedAllowanceObservation{State: "cooldown_observed", Reason: "provider_cooldown_observed", QueryCommentID: q.Comment.ID, ResponseCommentID: 92, QueryCreatedAt: q.Comment.CreatedAt, ResponseCreatedAt: q.Comment.CreatedAt.Add(time.Nanosecond), RetryNotBefore: q.Comment.CreatedAt.Add(time.Nanosecond).Add(minutes)}} + if _, err := f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, HostedObservationInput{Kind: "allowance_query", CaptureID: in.CaptureID, CaptureSHA256: digest, CaptureBytes: in.CaptureBytes, StartedAt: start.Truncate(time.Second).Format(time.RFC3339Nano), FinishedAt: observed, ObservedAt: observed, ExpectedAnchor: anchor, Intent: q.Intent}); err != nil { + t.Fatal(err) + } + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + return in +} + +func TestCooldownMultipleWaitsPreserveOneRoundOccupancyAndReleaseReservations(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "hosted", 0, 0, 2, "grant") + receipt := f.enqueue(t, attemptProject, "one-intent", "hosted", 2, 1) + first := f.start(t, attemptProject, receipt) + in := retainTimerCooldown(t, f, first, 3*time.Minute) + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, first.ID, 1); err != nil { + t.Fatal(err) + } + firstHistory := hostedAllowanceOnlyAttempt(t, f, first) + now := in.Observation.RetryNotBefore + f.e.schedulingNow = func() time.Time { return now } + second := f.start(t, attemptProject, receipt) + next := retainTimerCooldown(t, f, second, 6*time.Minute) + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, second.ID, 1); err != nil { + t.Fatal(err) + } + o := bindingOperation(t, f, f.scope(t, attemptProject, f.writer, false), receipt.ID) + if o.Wait == nil || o.Wait.BaselineAttemptID != first.ID || o.Wait.RetryNotBefore != next.Observation.RetryNotBefore.Format(time.RFC3339Nano) { + t.Fatal("repeated timer lost first comparison/latest deadline", o) + } + progress, err := f.e.ReadRoundProgressStages(t.Context(), evidenceReadScope(t, f, attemptProject, f.reader), []int64{2}) + if err != nil { + t.Fatal(err) + } + c := progress.Items[0].Channels[0] + if c.Pending != 1 || c.PendingExecution == nil || *c.PendingExecution != 1 || c.Used != 0 || c.Dry != 0 || c.Wait == nil { + t.Fatal("cooldown changed round accounting", c) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 { + t.Fatal("timer reserved capacity/credited review") + } + if hostedAllowanceOnlyAttempt(t, f, first) != firstHistory { + t.Fatal("second timer rewrote initial retained observation") + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err != nil { + t.Fatal(err) + } + timerControl(t, f, receipt.ID, "cancel", "cancel") + if c := readProgress(t, f, 2).Items[0].Channels[0]; c.Pending != 0 || c.Used != 0 { + t.Fatal("cancel did not release pending round", c) + } +} +func hostedAllowanceOnlyAttempt(t *testing.T, f *attemptFixture, a Attempt) string { + t.Helper() + var preflight, query string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_hosted_preflight WHERE attempt_id=?`, a.ID).Scan(&preflight); err != nil { + t.Fatal(err) + } + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_hosted_allowance_queries WHERE attempt_id=?`, a.ID).Scan(&query); err != nil { + t.Fatal(err) + } + return preflight + query +} + +func TestCooldownRecoveryPreservesOnlyProvenFuturePreparingWait(t *testing.T) { + for _, scenario := range []string{"future", "elapsed", "unknown", "old held"} { + t.Run(scenario, func(t *testing.T) { + f, a, in := cooldownObservationFixture(t) + if scenario != "unknown" { + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, 1, in); err != nil { + t.Fatal(err) + } + } + if scenario == "elapsed" { + f.e.schedulingNow = func() time.Time { return in.Observation.RetryNotBefore } + } + if scenario == "old held" { + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, 1, "held", "hosted_allowance_cooldown", ""); err != nil { + t.Fatal(err) + } + } + before := hostedAllowanceOnlyAttemptOptional(t, f, a) + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal(err) + } + o := bindingOperation(t, f, f.scope(t, attemptProject, f.writer, false), a.OperationID) + if scenario == "future" { + if o.State != "queued" || o.AttemptID != "" || o.Wait == nil { + t.Fatal("preparation crash lost known timer", o) + } + } else if o.Wait != nil || o.State != "cancelled" && scenario != "old held" || scenario == "old held" && o.State != "held" { + t.Fatal("unproven/elapsed/terminal work reopened", o) + } + if scenario == "elapsed" || scenario == "unknown" { + recovered, err := readAttempt(t.Context(), f.store.DB(), attemptProject, a.ID) + if err != nil || recovered.State != "cancelled" || recovered.Revision != a.Revision+1 || o.Reason != "supervisor_interrupted" { + t.Fatal("interrupted unused preparation lost its cancellation history", recovered, o, err) + } + } + if before != hostedAllowanceOnlyAttemptOptional(t, f, a) || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("recovery changed retained query/source or reserved capacity") + } + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal("recovery replay", err) + } + }) + } +} +func hostedAllowanceOnlyAttemptOptional(t *testing.T, f *attemptFixture, a Attempt) string { + t.Helper() + var result string + if err := f.store.DB().QueryRow(`SELECT coalesce((SELECT body_json FROM review_hosted_preflight WHERE attempt_id=?),'')||coalesce((SELECT body_json FROM review_hosted_allowance_queries WHERE attempt_id=?),'')`, a.ID, a.ID).Scan(&result); err != nil { + t.Fatal(err) + } + return result +} + +func TestCooldownRestoredProviderReleaseHoldsWaitAndRetainsHistory(t *testing.T) { + f, a, in, _ := queuedCooldown(t) + before := hostedAllowanceOnlyAttempt(t, f, a) + restoredHeld(t, f) + summary, err := restoredCall(t, f, time.Now()) + if err != nil || summary.QueuedOperations != 1 || summary.Attempts != 0 || summary.PausedProjects != 1 { + t.Fatal("restore reconciliation", summary, err) + } + o := bindingOperation(t, f, f.scope(t, attemptProject, f.writer, false), a.OperationID) + if o.State != "held" || o.Reason != "restore_reconciled" || o.Wait != nil || o.AttemptID != "" { + t.Fatal("restore resumed pending intent", o) + } + f.e.schedulingNow = func() time.Time { return in.Observation.RetryNotBefore.Add(time.Hour) } + pending, err := f.e.pending(t.Context()) + if err != nil || len(pending) != 0 { + t.Fatal("restore scheduled wait", pending, err) + } + if before != hostedAllowanceOnlyAttempt(t, f, a) { + t.Fatal("restore changed cooldown provenance") + } +} + +func TestCooldownRestoredProviderReleaseFreshAttemptAfterWaitAndControls(t *testing.T) { + for _, scenario := range []string{"fresh preparing retry", "pause resume then prepare"} { + t.Run(scenario, func(t *testing.T) { + var f *attemptFixture + var current Attempt + var firstID string + if scenario == "fresh preparing retry" { + var in HostedAllowanceInput + var now *time.Time + f, current, in, now = queuedCooldown(t) + firstID = current.ID + *now = in.Observation.RetryNotBefore + current = f.start(t, attemptProject, Receipt{ID: current.OperationID}) + } else { + f = newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + receipt := f.enqueue(t, attemptProject, "pause-restore", "hosted", 2, 1) + timerControl(t, f, receipt.ID, "pause", "pause") + timerControl(t, f, receipt.ID, "resume", "resume") + current = f.start(t, attemptProject, receipt) + } + restoredHeld(t, f) + summary, err := restoredCall(t, f, time.Now()) + if err != nil || summary.Attempts != 1 || summary.QueuedOperations != 0 || summary.PausedProjects != 1 { + t.Fatal("fresh revision reconciliation", summary, err) + } + o := bindingOperation(t, f, f.scope(t, attemptProject, f.writer, false), current.OperationID) + if o.State != "cancelled" || o.Reason != "restore_reconciled" || o.AttemptID != current.ID || o.Wait != nil { + t.Fatal("restored fresh attempt", o) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("restored retry reservation retained") + } + if firstID != "" { + var state string + if err := f.store.DB().QueryRow(`SELECT state FROM review_execution_attempts WHERE id=?`, firstID).Scan(&state); err != nil || state != "held" { + t.Fatal("old cooldown changed", state, err) + } + } + }) + } +} + +func TestCooldownControlCASReplayAndAtomicEventFailure(t *testing.T) { + f, a, _, _ := queuedCooldown(t) + scope := f.scope(t, attemptProject, f.writer, false) + o := bindingOperation(t, f, scope, a.OperationID) + input := OperationControl{ExpectedRevision: o.Revision, Action: "pause"} + admissionSQL(t, f, `CREATE TRIGGER fail_wait_control BEFORE INSERT ON events WHEN NEW.event_type='review.operation_updated' BEGIN SELECT RAISE(ABORT,'injected control failure'); END`) + before := snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "receipts") + if _, err := f.e.ControlOperation(t.Context(), scope, "pause-key", o.ID, input); err == nil { + t.Fatal("failed event accepted control") + } + if before != snapshotTable(t, f, "review_operation_waits")+snapshotTable(t, f, "review_operations")+snapshotTable(t, f, "receipts") { + t.Fatal("failed control changed wait/request/receipt") + } + admissionSQL(t, f, `DROP TRIGGER fail_wait_control`) + first, err := f.e.ControlOperation(t.Context(), scope, "pause-key", o.ID, input) + if err != nil { + t.Fatal(err) + } + before = snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "receipts") + snapshotTable(t, f, "events") + replay, err := f.e.ControlOperation(t.Context(), scope, "pause-key", o.ID, input) + if err != nil || string(first) != string(replay) { + t.Fatal("control replay", err) + } + if before != snapshotTable(t, f, "review_operation_waits")+snapshotTable(t, f, "review_operations")+snapshotTable(t, f, "receipts")+snapshotTable(t, f, "events") { + t.Fatal("control replay repeated mutation") + } + _, err = f.e.ControlOperation(t.Context(), scope, "stale-control", o.ID, input) + attemptCode(t, err, "review_conflict") + input.Action = "cancel" + _, err = f.e.ControlOperation(t.Context(), scope, "pause-key", o.ID, input) + attemptCode(t, err, "idempotency_conflict") +} + +func TestCooldownDetachedWorkspacesRetireWithoutTouchingCurrentAttempt(t *testing.T) { + f, a, in, now := queuedCooldown(t) + later := time.Now().Add(10 * time.Minute) + disposable, err := f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, later) + if err != nil || !disposable { + t.Fatal("detached cooldown leaked workspace", disposable, err) + } + disposable, err = f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, time.Now()) + if err != nil || disposable { + t.Fatal("cooldown workspace retired too early", disposable, err) + } + *now = in.Observation.RetryNotBefore + next := f.start(t, attemptProject, Receipt{ID: a.OperationID}) + disposable, err = f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, later) + if err != nil || !disposable { + t.Fatal("new attempt hid old terminal workspace", disposable, err) + } + disposable, err = f.e.WorkspaceDisposable(t.Context(), "test-capability", next.ID, later) + if err != nil || disposable { + t.Fatal("current preparation workspace disposable", disposable, err) + } + admissionSQL(t, f, `DELETE FROM review_operation_waits WHERE operation_id=?`, a.OperationID) + disposable, err = f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, later) + if err != nil || disposable { + t.Fatal("unowned detached workspace disposable", disposable, err) + } +} + +func TestCooldownDetachedAttemptPublicationRepairsLedgerOnlyHistory(t *testing.T) { + f := attemptProjectionFixture(t, false) + first := f.start(t, attemptProject, f.enqueue(t, attemptProject, "ledger-only-cooldown", "hosted", 2, 1)) + in := retainTimerCooldown(t, f, first, 3*time.Minute) + first, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, first.ID, 1) + if err != nil { + t.Fatal(err) + } + before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_execution_transitions") + hostedAllowanceOnlyAttempt(t, f, first) + pull := projectionPull(2) + receipt, err := f.e.PublishAttempt(t.Context(), attemptProject, first.ID, &pull) + if err != nil { + t.Fatal("initial detached publication", err) + } + _, projected := projectedAttempt(t, f, first) + assertProjectedTimes(t, f, first, projected, true) + if projected.Reason != "hosted_allowance_cooldown" || projected.SourceRunID != "" || projected.TriggerID != "" || projected.State != "held" { + t.Fatal("publication invented provider action/credit", projected) + } + digest := projectionDigest(t, f, "") + events := attemptCount(t, f.store, `SELECT count(*) FROM events`) + replay, err := f.e.PublishAttempt(t.Context(), attemptProject, first.ID, nil) + if err != nil || receipt != replay || digest != projectionDigest(t, f, "") || events != attemptCount(t, f.store, `SELECT count(*) FROM events`) { + t.Fatal("detached publication replay", replay, err) + } + if before != snapshotTable(t, f, "review_operations")+snapshotTable(t, f, "review_operation_waits")+snapshotTable(t, f, "review_execution_transitions")+hostedAllowanceOnlyAttempt(t, f, first) { + t.Fatal("publication changed waiting authorization/history") + } + f.e.schedulingNow = func() time.Time { return in.Observation.RetryNotBefore } + next := f.start(t, attemptProject, Receipt{ID: first.OperationID}) + if _, err := f.e.PublishAttempt(t.Context(), attemptProject, first.ID, nil); err != nil { + t.Fatal("later current attempt blocked history repair", err) + } + _, live := projectedAttempt(t, f, next) + if live.State != "preparing" { + t.Fatal("historical publication changed live projection", live) + } + admissionSQL(t, f, `DELETE FROM review_operation_waits WHERE operation_id=?`, first.OperationID) + _, err = f.e.PublishAttempt(t.Context(), attemptProject, first.ID, nil) + attemptCode(t, err, "observation_conflict") + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 { + t.Fatal("historical attempt projection created evidence") + } +} + +// restorePreSelectionExecutionSchema reconstructs the physical predecessor in +// an owned migration fixture, including pre-cooldown attempt cardinality and +// pre-repository hosted reservation cardinality. +func restorePreSelectionExecutionSchema(t *testing.T, f *attemptFixture) { + t.Helper() + restorePreCooldownAttemptSchema(t, f) + admissionSQL(t, f, `CREATE TABLE old_reservations(provider TEXT NOT NULL,repository_id INTEGER NOT NULL,pull_number INTEGER NOT NULL,action_class TEXT NOT NULL,account TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),PRIMARY KEY(provider,repository_id,pull_number,action_class),UNIQUE(provider,account,action_class))`) + admissionSQL(t, f, `INSERT INTO old_reservations SELECT * FROM review_execution_reservations`) + admissionSQL(t, f, `DROP TABLE review_execution_reservations`) + admissionSQL(t, f, `ALTER TABLE old_reservations RENAME TO review_execution_reservations`) + admissionSQL(t, f, `ALTER TABLE review_operations DROP COLUMN allow_out_of_order`) + admissionSQL(t, f, `ALTER TABLE review_operations DROP COLUMN override_file_limit`) + // Rebuilding the attempt table removed its derived-proof triggers, as on + // deployed predecessors; the independent comparison repair restores them. + admissionSQL(t, f, `UPDATE metadata SET value='1' WHERE key='schema:review_comparison'`) +} + +func TestOperationWaitPreservesDependencyLookupErrors(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + if channel == "cli" { + f, a, _, _ = cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + } else { + f, a, _, _ = queuedCooldown(t) + } + o, err := readOperation(t.Context(), f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + tables := []string{"review_operations", "review_execution_attempts", "review_operation_waits", "review_cli_preflight", "review_hosted_preflight", "events"} + before := map[string]string{} + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + matches := []string{"FROM review_execution_attempts", "FROM review_" + channel + "_preflight", "FROM projects"} + if channel == "hosted" { + matches = []string{"FROM review_execution_attempts", "FROM review_hosted_preflight", "FROM review_hosted_allowance_queries", "FROM review_hosted_observations"} + } + for _, match := range matches { + for _, canceled := range []bool{false, true} { + q := cliRetryFailureQuery{EvidenceQuery: f.store.DB(), match: match, cancel: canceled} + wait, err := readOperationWait(t.Context(), q, o) + if wait != nil || err == nil || isWaitUnavailable(err) || storedAllowanceUnavailable(err) || canceled && !errors.Is(err, context.Canceled) || !canceled && !strings.Contains(err.Error(), "missing_cli_retry_history") { + t.Errorf("lookup reclassified: %s canceled=%t wait=%v err=%v", match, canceled, wait, err) + } + } + } + for _, table := range tables { + if snapshotTable(t, f, table) != before[table] { + t.Fatal("read changed retained state", table) + } + } + }) + } +} + +func TestOperationWaitRejectsMissingAndCorruptBaseline(t *testing.T) { + for _, damage := range []string{"missing attempt", "invalid anchor", "missing allowance", "corrupt allowance"} { + t.Run(damage, func(t *testing.T) { + f, a, _, _ := queuedCooldown(t) + o, err := readOperation(t.Context(), f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + switch damage { + case "missing attempt": + admissionSQL(t, f, `UPDATE review_execution_attempts SET project_id=? WHERE id=?`, otherAttemptProject, a.ID) + case "invalid anchor": + admissionSQL(t, f, `UPDATE review_execution_attempts SET anchor_json='{' WHERE id=?`, a.ID) + case "missing allowance": + admissionSQL(t, f, `DELETE FROM review_hosted_preflight WHERE attempt_id=?`, a.ID) + case "corrupt allowance": + admissionSQL(t, f, `UPDATE review_hosted_preflight SET body_json='{}' WHERE attempt_id=?`, a.ID) + } + if wait, err := readOperationWait(t.Context(), f.store.DB(), o); wait != nil || !isWaitUnavailable(err) { + t.Fatal("retained dependency accepted", wait, err) + } + }) + } +} diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go new file mode 100644 index 000000000..d8a93101f --- /dev/null +++ b/internal/reviewexec/hosted_wait_validation.go @@ -0,0 +1,181 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// ValidateOperationWaitsSnapshot checks retained scheduling and attempt ownership +// without provider calls or current freshness checks. A wait row may remain as +// immutable-history attribution after its current scheduling intent has ended. +func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `SELECT coalesce(o.project_id,''),w.operation_id FROM review_operation_waits w LEFT JOIN review_operations o ON o.id=w.operation_id + UNION SELECT project_id,id FROM review_operations WHERE reason=? + UNION SELECT a.project_id,a.operation_id FROM review_execution_attempts a JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE t.reason=? + UNION SELECT a.project_id,a.operation_id FROM review_execution_attempts a + LEFT JOIN review_operations o ON o.id=a.operation_id + JOIN review_execution_transitions t ON t.attempt_id=a.id + WHERE (o.id IS NULL OR o.attempt_id<>a.id) AND t.reason IN ('allowance_exhausted','hosted_allowance_cooldown') + ORDER BY 2`, cliDraftWait, cliDraftWait) + if err != nil { + return err + } + var owners [][2]string + for rows.Next() { + var owner [2]string + if err := rows.Scan(&owner[0], &owner[1]); err != nil { + rows.Close() + return err + } + owners = append(owners, owner) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + for _, owner := range owners { + o, err := readOperationBase(ctx, tx, owner[0], owner[1]) + if err != nil { + return err + } + if err := validateOperationWaitHistory(ctx, tx, o); err != nil { + return err + } + } + return nil +} + +func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) error { + hasBaseline := o.Wait != nil && o.Wait.BaselineAttemptID != "" + if hasBaseline && o.AttemptID == o.Wait.BaselineAttemptID { + return waitUnavailable() + } + if o.Reason == cliDraftWait && (o.Channel != "cli" || o.State != "queued" || o.AttemptID != "") { + return waitUnavailable() + } + if o.AttemptID == "" { + if o.State != "queued" && o.State != "held" && o.State != "cancelled" { + return waitUnavailable() + } + } else if o.State == "queued" || o.Wait != nil && o.Wait.Paused { + return waitUnavailable() + } + rows, err := tx.QueryContext(ctx, `SELECT id FROM review_execution_attempts WHERE operation_id=? ORDER BY id`, o.ID) + if err != nil { + return err + } + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + ids = append(ids, id) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + var firstDeadline, lastDeadline, baselineDeadline time.Time + foundCurrent := o.AttemptID == "" + foundDraft := o.Reason == cliDraftWait + for _, id := range ids { + a, err := readAttempt(ctx, tx, o.ProjectID, id) + if err != nil { + return err + } + if id == o.AttemptID { + if a.State != o.State || a.OperationID != o.ID || a.ProjectID != o.ProjectID { + return waitUnavailable() + } + foundCurrent = true + continue + } + _, draft, err := historicalCLIDraftOperation(ctx, tx, o, a) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return waitUnavailable() + } + return err + } + if draft { + foundDraft = true + continue + } + if !hasBaseline { + return waitUnavailable() + } + historical, err := historicalCooldownOperation(ctx, tx, o, a) + if err != nil { + return err + } + var due time.Time + if o.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, tx, historical, a) + if err != nil { + if errors.Is(err, sql.ErrNoRows) || storedAllowanceUnavailable(err) { + return waitUnavailable() + } + return err + } + if record.Observation.Remaining != 0 { + return waitUnavailable() + } + due, err = cliExhaustionDeadline(ctx, tx, a) + if err != nil { + return err + } + } else { + record, err := readHostedAllowanceRecord(ctx, tx, historical, a) + if err != nil { + if errors.Is(err, sql.ErrNoRows) || storedAllowanceUnavailable(err) { + return waitUnavailable() + } + return err + } + if record.Input.Observation.State != "cooldown_observed" { + return waitUnavailable() + } + var at string + if err := tx.QueryRowContext(ctx, `SELECT created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&at); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return waitUnavailable() + } + return err + } + ended, valid := attemptRecordedTime(at) + if !valid || !record.Input.Observation.RetryNotBefore.After(ended) { + return waitUnavailable() + } + due = record.Input.Observation.RetryNotBefore + } + if firstDeadline.IsZero() || due.Before(firstDeadline) { + firstDeadline = due + } + if lastDeadline.IsZero() || due.After(lastDeadline) { + lastDeadline = due + } + if id == o.Wait.BaselineAttemptID { + baselineDeadline = due + } + var occupied bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) OR EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID).Scan(&occupied); err != nil { + return err + } + if occupied { + return waitUnavailable() + } + } + if !foundCurrent || o.Wait == nil && !foundDraft { + return waitUnavailable() + } + if hasBaseline && (baselineDeadline.IsZero() || !baselineDeadline.Equal(firstDeadline) || lastDeadline.UTC().Format(time.RFC3339Nano) != o.Wait.RetryNotBefore) { + return waitUnavailable() + } + return nil +} diff --git a/internal/reviewexec/http.go b/internal/reviewexec/http.go index 975b6a3aa..b6c64a784 100644 --- a/internal/reviewexec/http.go +++ b/internal/reviewexec/http.go @@ -16,6 +16,8 @@ import ( // Provider work always runs outside these request handlers. func (e *Engine) Register(mux *http.ServeMux) { e.registerCIWatchHTTP(mux) + mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/rounds/progress", e.readRoundProgressHTTP) + mux.HandleFunc("POST /api/v1/projects/{project_id}/reviews/operations/{operation_id}/control", e.controlOperationHTTP) mux.HandleFunc("POST /api/v1/projects/{project_id}/reviews/selections", e.enqueueRunHTTP) mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/selections/{selection_id}", e.readRunHTTP) adoptionholds.New(e.store).Register(mux) @@ -82,6 +84,7 @@ func (e *Engine) configureHTTP(w http.ResponseWriter, r *http.Request) { } func (e *Engine) enqueueHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Vary", operationWaitHeader) w.Header().Add("Vary", "Prefer") scope, err := e.store.Scope(r, "write") if err != nil { @@ -150,6 +153,7 @@ func (e *Engine) enqueueHTTP(w http.ResponseWriter, r *http.Request) { } } if terminal { + operation = operationForResponse(operation, r.Header.Get(operationWaitHeader)) core.WriteJSON(w, http.StatusOK, operation) return } @@ -158,6 +162,7 @@ func (e *Engine) enqueueHTTP(w http.ResponseWriter, r *http.Request) { } func (e *Engine) readOperationHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Vary", operationWaitHeader) w.Header().Add("Vary", "X-FC-Hosted-Observer") w.Header().Add("Vary", "Prefer") scope, err := e.store.Scope(r, "read") @@ -192,6 +197,10 @@ func (e *Engine) readOperationHTTP(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-FC-Hosted-Observer") == "1" { operation.Observer = e.observerStatus(operation) } + operation = operationForResponse(operation, r.Header.Get(operationWaitHeader)) + if operation.Channel == "cli" && operation.State == "queued" && e.sharedCLIQuotaWait(r.Context(), scope, operation.ID) { + w.Header().Set("X-FC-Review-Queued", "cli_quota_wait") + } core.WriteJSON(w, http.StatusOK, operation) } @@ -212,3 +221,38 @@ func (e *Engine) readExecutionConfigurationHTTP(w http.ResponseWriter, r *http.R } core.WriteJSON(w, http.StatusOK, configuration) } + +// sharedCLIQuotaWait supplies only a diagnostic for an already authorized read. +// Invalid or unavailable bindings provide no account-level quota assertion. +func (e *Engine) sharedCLIQuotaWait(ctx context.Context, scope core.Scope, id string) bool { + waiting := false + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + o, err := readOperationBase(ctx, tx, scope.ProjectID, id) + if err != nil { + return err + } + if o.Channel != "cli" || o.State != "queued" { + return nil + } + c, revision, err := readConfiguration(ctx, tx, scope.ProjectID) + if err != nil { + return err + } + compatible, err := compatibleQueuedConfiguration(ctx, tx, o, c, revision) + if err != nil { + return err + } + capability, ok := e.capabilities[c.CapabilityID] + if !compatible || !ok || e.validateConfiguration(c) != nil || o.CapabilityFingerprint != capability.Fingerprint { + return nil + } + now := e.sampleExecutionTime() + due, err := cliAccountRetryDeadline(ctx, tx, capability, now) + if err != nil { + return err + } + waiting = now.Before(due) + return nil + }) + return err == nil && waiting +} diff --git a/internal/reviewexec/operation_list_index_test.go b/internal/reviewexec/operation_list_index_test.go index 0bb56fe23..1dd73e379 100644 --- a/internal/reviewexec/operation_list_index_test.go +++ b/internal/reviewexec/operation_list_index_test.go @@ -15,6 +15,9 @@ func TestOperationListIndexFreshAndExistingDatabase(t *testing.T) { f, a, _ := cliAllowanceFixture(t) if upgrade { admissionSQL(t, f, `DROP INDEX IF EXISTS review_operations_listing`) + for _, index := range []string{"review_waits_live_retry", "review_transitions_exhaustion_time", "review_transitions_exhaustion_attempt"} { + admissionSQL(t, f, "DROP INDEX "+index) + } admissionSQL(t, f, `UPDATE metadata SET value='1' WHERE key='schema:review_execution_indexes'`) } before := attemptState(t, f, a) @@ -54,7 +57,7 @@ func TestOperationListIndexFreshAndExistingDatabase(t *testing.T) { } } var version string - if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution_indexes'`).Scan(&version); err != nil || version != "2" { + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_execution_indexes'`).Scan(&version); err != nil || version != "3" { t.Fatal("index migration missing", version, err) } if err := EnsureSchema(t.Context(), f.store); err != nil { diff --git a/internal/reviewexec/operation_status.go b/internal/reviewexec/operation_status.go index b24276a54..1bc5330a5 100644 --- a/internal/reviewexec/operation_status.go +++ b/internal/reviewexec/operation_status.go @@ -13,18 +13,20 @@ import ( // OperationStatus is a compact read projection, never execution or coverage authority. type OperationStatus struct { - Observer *HostedObserverStatus `json:"observer,omitempty"` - ID string `json:"id"` - PullNumber int64 `json:"pull_number"` - Channel string `json:"channel"` - State string `json:"state"` - Revision int64 `json:"revision"` - Stage string `json:"stage"` - Reason string `json:"reason"` - AttemptID string `json:"attempt_id"` - EvidenceID string `json:"evidence_id,omitempty"` - UpdatedAt string `json:"updated_at"` - NextAction string `json:"next_action"` + Wait *OperationWait `json:"wait,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` + Observer *HostedObserverStatus `json:"observer,omitempty"` + ID string `json:"id"` + PullNumber int64 `json:"pull_number"` + Channel string `json:"channel"` + State string `json:"state"` + Revision int64 `json:"revision"` + Stage string `json:"stage"` + Reason string `json:"reason"` + AttemptID string `json:"attempt_id"` + EvidenceID string `json:"evidence_id,omitempty"` + UpdatedAt string `json:"updated_at"` + NextAction string `json:"next_action"` } func operationStatusStage(o Operation, evidence string, complete bool) (string, string) { @@ -80,6 +82,10 @@ func (e *Engine) ReadOperationStatus(ctx context.Context, scope core.Scope, id s } stage, next := operationStatusStage(o, evidence, complete) result = OperationStatus{ID: o.ID, PullNumber: o.PullNumber, Channel: o.Channel, State: o.State, Revision: o.Revision, Stage: stage, Reason: o.Reason, AttemptID: o.AttemptID, EvidenceID: evidence, UpdatedAt: o.UpdatedAt, NextAction: next} + result.Wait = currentOperationWait(o) + if o.Channel == "hosted" && o.State == "held" && o.Reason == "hosted_allowance_cooldown" && o.Allowance != nil { + result.RetryNotBefore = o.Allowance.RetryNotBefore + } result.Observer = e.observerStatus(o) return nil }) @@ -130,6 +136,7 @@ func (e *Engine) WaitOperationStatus(ctx context.Context, scope core.Scope, id s return e.ReadOperationStatus(ctx, scope, id) } func (e *Engine) readOperationStatusHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Vary", operationWaitHeader) w.Header().Add("Vary", "Prefer") w.Header().Add("Vary", "X-FC-Hosted-Observer") scope, err := e.store.Scope(r, "read") @@ -164,5 +171,12 @@ func (e *Engine) readOperationStatusHTTP(w http.ResponseWriter, r *http.Request) if r.Header.Get("X-FC-Hosted-Observer") != "1" { value.Observer = nil } + value.Wait = operationWaitForResponse(value.Wait, value.Channel, r.Header.Get(operationWaitHeader)) + if r.Header.Get(operationWaitHeader) != "3" { + value.RetryNotBefore = "" + } + if value.Channel == "cli" && value.State == "queued" && e.sharedCLIQuotaWait(r.Context(), scope, value.ID) { + w.Header().Set("X-FC-Review-Queued", "cli_quota_wait") + } core.WriteJSON(w, http.StatusOK, value) } diff --git a/internal/reviewexec/operation_status_test.go b/internal/reviewexec/operation_status_test.go index 5299837f3..7706b97c6 100644 --- a/internal/reviewexec/operation_status_test.go +++ b/internal/reviewexec/operation_status_test.go @@ -12,12 +12,15 @@ import ( "time" ) -func statusHTTP(t *testing.T, f *attemptFixture, id, query, prefer string) *httptest.ResponseRecorder { +func statusHTTP(t *testing.T, f *attemptFixture, id, query, prefer string, waitVersion ...string) *httptest.ResponseRecorder { t.Helper() r := httptest.NewRequest("GET", "/api/v1/projects/"+attemptProject+"/reviews/operations/"+id+"/status"+query, nil) r.SetPathValue("project_id", attemptProject) r.SetPathValue("operation_id", id) r.Header.Set("Authorization", "Bearer "+f.reader) + if len(waitVersion) > 0 { + r.Header.Set(operationWaitHeader, waitVersion[0]) + } if prefer != "" { r.Header.Set("Prefer", prefer) } diff --git a/internal/reviewexec/operation_wait_test.go b/internal/reviewexec/operation_wait_test.go index 14186bfde..71fc771a9 100644 --- a/internal/reviewexec/operation_wait_test.go +++ b/internal/reviewexec/operation_wait_test.go @@ -101,7 +101,7 @@ func TestOperationWaitPreAttemptHoldAndRecovery(t *testing.T) { if recovery { f.start(t, attemptProject, r) } else { - f.configure(t, attemptProject, "test-capability", 1, true) + f.configure(t, attemptProject, "other-account", 1, false) } done, _ := startOperationWait(t, f, operationReadScope(t, f), r.ID, 900) operationWaitRegistered(t, f.e, 1) @@ -246,7 +246,7 @@ func TestOperationHTTPWaitImmediateReplayAndHeaderAdmission(t *testing.T) { if w.Code != 202 || json.Unmarshal(w.Body.Bytes(), &receipt) != nil || receipt.State != "queued" || receipt.Revision != 1 { t.Fatal(w.Code, w.Body.String()) } - f.configure(t, attemptProject, "test-capability", 1, true) + f.configure(t, attemptProject, "other-account", 1, false) if _, err := f.e.StartAttempt(t.Context(), attemptProject, receipt.ID); err != nil { t.Fatal(err) } @@ -283,7 +283,7 @@ func TestOperationHTTPDefaultWaitAndRetainedGETWake(t *testing.T) { if err := f.store.DB().QueryRow(`SELECT id FROM review_operations`).Scan(&id); err != nil { t.Fatal(err) } - f.configure(t, attemptProject, "test-capability", 1, true) + f.configure(t, attemptProject, "other-account", 1, false) if _, err := f.e.StartAttempt(t.Context(), attemptProject, id); err != nil { t.Fatal(err) } diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go index 9fa0ab015..cea371e88 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -54,7 +54,11 @@ func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operat if err != nil { return ExecutionContext{}, err } - if configuration.Paused || revision != operation.ConfigurationRevision || e.validateConfiguration(configuration) != nil || !slices.Contains(configuration.Queue, operation.PullNumber) || !slices.Contains(configuration.Channels, operation.Channel) { + compatible, err := compatibleQueuedConfiguration(ctx, tx, operation, configuration, revision) + if err != nil { + return ExecutionContext{}, err + } + if !compatible || e.validateConfiguration(configuration) != nil || !slices.Contains(configuration.Queue, operation.PullNumber) || !slices.Contains(configuration.Channels, operation.Channel) { return ExecutionContext{}, conflict() } capability := e.capabilities[configuration.CapabilityID] @@ -85,7 +89,11 @@ func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operat if err != nil { return ExecutionContext{}, err } - result.Configuration, result.Policy = configuration, policy + original, err := sourceConfiguration(ctx, tx, operation.ProjectID, operation.ConfigurationRevision) + if err != nil { + return ExecutionContext{}, err + } + result.Configuration, result.Policy = original, policy return result, nil } @@ -209,13 +217,19 @@ func verifyPredecessors(ctx context.Context, tx *sql.Tx, project string, current } return nil } - if !slices.Contains(current.Configuration.Queue, current.Operation.PullNumber) || len(predecessors) > 100 { + // Resolve source with the retained configuration, but require every actual + // ancestor to remain enrolled in this final action's current snapshot. + configuration, _, err := readConfiguration(ctx, tx, project) + if err != nil { + return err + } + if !slices.Contains(configuration.Queue, current.Operation.PullNumber) || len(predecessors) > 100 { return invalid() } number, head, branch := target.ParentPullNumber, target.ParentSHA, target.BaseRef seen := map[int64]bool{current.Operation.PullNumber: true} for _, plan := range predecessors { - if number == 0 || seen[number] || !slices.Contains(current.Configuration.Queue, number) || plan.Pull.Number != number || plan.Pull.HeadSHA != head || plan.Pull.HeadRef != branch { + if number == 0 || seen[number] || !slices.Contains(current.Configuration.Queue, number) || !slices.Contains(configuration.Queue, number) || plan.Pull.Number != number || plan.Pull.HeadSHA != head || plan.Pull.HeadRef != branch { return invalid() } seen[number] = true diff --git a/internal/reviewexec/policy_admission_test.go b/internal/reviewexec/policy_admission_test.go index b18e8322b..704c1fad0 100644 --- a/internal/reviewexec/policy_admission_test.go +++ b/internal/reviewexec/policy_admission_test.go @@ -81,7 +81,9 @@ func TestPolicyAdmissionEnqueueRequiresPolicyAndRetainsKeyedRevision(t *testing. if err != nil || !reflect.DeepEqual(operation, retained) { t.Fatal("replay silently adopted new policy", retained, err) } - _, err = f.e.Enqueue(t.Context(), scope, "new-paused-key", request) + pausedRequest := request + pausedRequest.PullNumber = 4 + _, err = f.e.Enqueue(t.Context(), scope, "new-paused-key", pausedRequest) attemptCode(t, err, "reviews_paused") if policyState(t, f) != before || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 { t.Fatal("paused new key changed journal") @@ -309,6 +311,7 @@ func TestPolicyAdmissionVersionTwoMigrationRetainsUnboundJournal(t *testing.T) { t.Fatal(err) } admissionSQL(t, f, `DROP TABLE review_hosted_preflight`) + restorePreSelectionExecutionSchema(t, f) admissionSQL(t, f, `DROP TABLE review_hosted_allowance_queries`) admissionSQL(t, f, `DROP INDEX review_operations_completed_comparison`) admissionSQL(t, f, `DROP TABLE review_cli_preflight`) diff --git a/internal/reviewexec/preparation_recovery.go b/internal/reviewexec/preparation_recovery.go new file mode 100644 index 000000000..08abf45aa --- /dev/null +++ b/internal/reviewexec/preparation_recovery.go @@ -0,0 +1,66 @@ +package reviewexec + +import ( + "context" +) + +// PreparationRecoveryError leaves an undispatched attempt preparing after a +// local retention failure. Startup must reconcile its original private source +// before ordinary interrupted-attempt recovery can release its reservation. +type PreparationRecoveryError struct{ Err error } + +func (e *PreparationRecoveryError) Error() string { + return "Review preparation retention requires recovery." +} +func (e *PreparationRecoveryError) Unwrap() error { return e.Err } + +type preparationRecoveryDriver interface { + RecoverPreparation(context.Context, Operation, Attempt) error +} + +func (e *Engine) reconcilePreparingDrivers(ctx context.Context, drivers map[string]Driver) error { + rows, err := e.store.DB().QueryContext(ctx, `SELECT a.project_id,a.id,a.operation_id FROM review_execution_attempts a + JOIN review_operations o ON o.id=a.operation_id AND o.attempt_id=a.id + WHERE a.state='preparing' AND o.state='preparing' AND o.channel='hosted' + AND NOT EXISTS (SELECT 1 FROM review_hosted_preflight p WHERE p.attempt_id=a.id) ORDER BY a.id`) + if err != nil { + return err + } + type identity struct{ project, attempt, operation string } + var ids []identity + for rows.Next() { + var id identity + if err = rows.Scan(&id.project, &id.attempt, &id.operation); err != nil { + rows.Close() + return err + } + ids = append(ids, id) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + for _, id := range ids { + a, err := readAttempt(ctx, e.store.DB(), id.project, id.attempt) + if err != nil { + return err + } + o, err := readOperationBase(ctx, e.store.DB(), id.project, id.operation) + if err != nil { + return err + } + for key, capability := range e.capabilities { + if capability.Fingerprint != o.CapabilityFingerprint || capability.Provider != a.Provider || capability.Account != a.Account { + continue + } + if driver, ok := drivers[key].(preparationRecoveryDriver); ok { + if err := driver.RecoverPreparation(ctx, o, a); err != nil { + return err + } + } + break + } + } + return nil +} diff --git a/internal/reviewexec/quota_test_helpers_test.go b/internal/reviewexec/quota_test_helpers_test.go new file mode 100644 index 000000000..36baba90a --- /dev/null +++ b/internal/reviewexec/quota_test_helpers_test.go @@ -0,0 +1,19 @@ +package reviewexec + +import ( + "net/http/httptest" + "testing" +) + +func versionWaitRead(t *testing.T, f *attemptFixture, path, version string) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest("GET", path, nil) + request.Header.Set("Authorization", "Bearer "+f.writer) + request.Header.Set(operationWaitHeader, version) + response := httptest.NewRecorder() + f.handler.ServeHTTP(response, request) + if response.Code != 200 { + t.Fatal("versioned wait read", path, version, response.Code, response.Body.String()) + } + return response +} diff --git a/internal/reviewexec/requests.go b/internal/reviewexec/requests.go index 896cb2ce0..158cefa82 100644 --- a/internal/reviewexec/requests.go +++ b/internal/reviewexec/requests.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "slices" + "strconv" "github.com/benhook1013/FireController/internal/core" ) @@ -176,6 +177,14 @@ func (e *Engine) enqueueRequestTx(ctx context.Context, tx *sql.Tx, scope core.Sc if !slices.Contains(c.Queue, r.PullNumber) || !slices.Contains(c.Channels, r.Channel) { return Receipt{}, core.Fail("review_not_configured", "The selected PR or channel is not configured.", 409) } + var pending string + err = tx.QueryRowContext(ctx, `SELECT id FROM review_operations WHERE project_id=? AND pull_number=? AND channel=? AND state IN ('queued','preparing','posting','active','uncertain') ORDER BY created_at,id LIMIT 1`, scope.ProjectID, r.PullNumber, r.Channel).Scan(&pending) + if err == nil { + return Receipt{}, &core.Error{Code: "review_inflight", Message: "This PR already has a pending review request; keep or control that original operation.", Status: 409, Details: map[string]string{"operation_id": pending}} + } + if !errors.Is(err, sql.ErrNoRows) { + return Receipt{}, err + } if err := requireSourceObligationsClear(ctx, tx, scope.ProjectID, r.PullNumber); err != nil { return Receipt{}, err } @@ -207,14 +216,52 @@ func (e *Engine) enqueueRequestTx(ctx context.Context, tx *sql.Tx, scope core.Sc } func readOperation(ctx context.Context, tx EvidenceQuery, project, id string) (Operation, error) { + o, err := readOperationBase(ctx, tx, project, id) + if err == nil { + o.Allowance, err = readHeldAllowance(ctx, tx, o) + } + return o, err +} + +func readOperationBase(ctx context.Context, tx EvidenceQuery, project, id string) (Operation, error) { var o Operation - err := tx.QueryRowContext(ctx, `SELECT id,project_id,actor_id,worker_id,configuration_revision,policy_revision,capability_fingerprint,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at FROM review_operations WHERE project_id=? AND id=?`, project, id).Scan(&o.ID, &o.ProjectID, &o.ActorID, &o.WorkerID, &o.ConfigurationRevision, &o.PolicyRevision, &o.CapabilityFingerprint, &o.PullNumber, &o.Channel, &o.HeadSHA, &o.State, &o.Revision, &o.Reason, &o.AttemptID, &o.CreatedAt, &o.UpdatedAt) + orderColumn, limitColumn, err := operationFlagColumns(ctx, tx) + if err != nil { + return o, err + } + err = tx.QueryRowContext(ctx, `SELECT id,project_id,actor_id,worker_id,configuration_revision,policy_revision,capability_fingerprint,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,`+orderColumn+`,`+limitColumn+` FROM review_operations WHERE project_id=? AND id=?`, project, id).Scan(&o.ID, &o.ProjectID, &o.ActorID, &o.WorkerID, &o.ConfigurationRevision, &o.PolicyRevision, &o.CapabilityFingerprint, &o.PullNumber, &o.Channel, &o.HeadSHA, &o.State, &o.Revision, &o.Reason, &o.AttemptID, &o.CreatedAt, &o.UpdatedAt, &o.AllowOutOfOrder, &o.OverrideFileLimit) if errors.Is(err, sql.ErrNoRows) { return o, core.Fail("not_found", "The review operation is unavailable in this project.", 404) } + if err == nil { + o.Wait, err = readOperationWait(ctx, tx, o) + } return o, err } +// Older retained snapshots supply false only for flags introduced after their +// declared version. Missing or malformed current columns fail the operation read. +func operationFlagColumns(ctx context.Context, q EvidenceQuery) (string, string, error) { + var version string + if err := q.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_execution'`).Scan(&version); err != nil { + return "", "", err + } + const order = `CASE WHEN typeof(allow_out_of_order)='integer' AND allow_out_of_order IN (0,1) THEN allow_out_of_order END` + const limit = `CASE WHEN typeof(override_file_limit)='integer' AND override_file_limit IN (0,1) THEN override_file_limit END` + schemaVersion, err := strconv.Atoi(version) + if err != nil || schemaVersion < 1 || strconv.Itoa(schemaVersion) != version { + return "", "", adjudicationStorageError() + } + switch { + case schemaVersion < 7: + return "0", "0", nil + case schemaVersion == 7: + return order, "0", nil + default: + return order, limit, nil + } +} + func (e *Engine) ReadOperation(ctx context.Context, scope core.Scope, id string) (Operation, error) { if !identifier.MatchString(id) { return Operation{}, invalid() @@ -223,6 +270,7 @@ func (e *Engine) ReadOperation(ctx context.Context, scope core.Scope, id string) err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { var err error o, err = readOperation(ctx, tx, scope.ProjectID, id) + o.Wait = currentOperationWait(o) return err }) return o, err diff --git a/internal/reviewexec/resolve.go b/internal/reviewexec/resolve.go index a817e1844..216c557ba 100644 --- a/internal/reviewexec/resolve.go +++ b/internal/reviewexec/resolve.go @@ -153,3 +153,19 @@ func RecheckSource(ctx context.Context, reader TargetReader, repositoryID int64, func unavailableParentHold(pull reviewprovider.Pull) error { return &core.Error{Code: "review_held", Message: "The checked PR base branch has no available open parent.", Status: 409, Details: map[string]string{"reason": "parent_unavailable", "pull_number": strconv.FormatInt(pull.Number, 10), "base_ref": pull.BaseRef}} } + +func obsoleteTargetReason(pull reviewprovider.Pull, repositoryID, number int64, head string) string { + if !sameTarget(pull, repositoryID, number) { + return "" + } + if pull.Merged { + return "target_merged" + } + if pull.State == "closed" { + return "target_closed" + } + if pull.State == "open" && pull.HeadSHA != head { + return "target_superseded" + } + return "" +} diff --git a/internal/reviewexec/restored_provider_work.go b/internal/reviewexec/restored_provider_work.go index 6890a6bd0..218020eb8 100644 --- a/internal/reviewexec/restored_provider_work.go +++ b/internal/reviewexec/restored_provider_work.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "math" + "slices" "time" "github.com/benhook1013/FireController/internal/core" @@ -53,7 +54,7 @@ func AbandonRestoredProviderWork(ctx context.Context, tx *sql.Tx, instanceID str return result, restoredWorkInvalid() } } - execution, err := restoredDomain(ctx, tx, "review_execution", "review_operations", "6") + execution, err := restoredDomain(ctx, tx, "review_execution", "review_operations", "9", "10") if err != nil { return result, err } @@ -74,7 +75,7 @@ func AbandonRestoredProviderWork(ctx context.Context, tx *sql.Tx, instanceID str enabled bool query string }{ - {execution, `SELECT o.capability_fingerprint,o.policy_revision,a.anchor_json,r.action_class,t.external_id,c.body_json,q.body_json FROM review_operations o,review_execution_attempts a,review_execution_reservations r,review_execution_transitions t,review_execution_config c,review_hosted_allowance_queries q LIMIT 0`}, + {execution, `SELECT o.capability_fingerprint,o.policy_revision,o.allow_out_of_order,o.override_file_limit,a.anchor_json,r.action_class,t.external_id,c.body_json,q.body_json,w.baseline_attempt_id,w.retry_not_before,w.paused FROM review_operations o,review_execution_attempts a,review_execution_reservations r,review_execution_transitions t,review_execution_config c,review_hosted_allowance_queries q,review_operation_waits w LIMIT 0`}, {source, `SELECT ` + refreshMetadataColumns + `,ci_observation_json,review_state_json FROM review_source_refreshes LIMIT 0`}, {checkpoint, `SELECT p.body_json,r.body_json,i.body_json FROM review_checkpoint_publications p,review_checkpoint_revisions r,review_checkpoint_intents i LIMIT 0`}, } @@ -94,6 +95,7 @@ func AbandonRestoredProviderWork(ctx context.Context, tx *sql.Tx, instanceID str enabled bool query string }{ + {execution, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE typeof(allow_out_of_order)!='integer' OR allow_out_of_order NOT IN (0,1) OR typeof(override_file_limit)!='integer' OR override_file_limit NOT IN (0,1))`}, {execution, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE state NOT IN ('queued','preparing','posting','active','uncertain','held','failed','completed','cancelled','rate_limited')) OR EXISTS(SELECT 1 FROM review_execution_attempts WHERE state NOT IN ('preparing','posting','active','uncertain','held','failed','completed','cancelled','rate_limited'))`}, {source, `SELECT EXISTS(SELECT 1 FROM review_source_refreshes WHERE state NOT IN ('queued','running','completed','held'))`}, } @@ -107,6 +109,9 @@ func AbandonRestoredProviderWork(ctx context.Context, tx *sql.Tx, instanceID str } if execution { + if err := ValidateOperationWaitsSnapshot(ctx, tx); err != nil { + return result, restoredWorkInvalid() + } if err = abandonRestoredAttempts(ctx, tx, at, &result); err == nil { err = pauseRestoredConfigurations(ctx, tx, &result) } @@ -127,7 +132,7 @@ func AbandonRestoredProviderWork(ctx context.Context, tx *sql.Tx, instanceID str return result, nil } -func restoredDomain(ctx context.Context, tx *sql.Tx, domain, table, version string) (bool, error) { +func restoredDomain(ctx context.Context, tx *sql.Tx, domain, table string, versions ...string) (bool, error) { var exists bool if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?)`, table).Scan(&exists); err != nil { return false, restoredWorkInvalid() @@ -137,7 +142,7 @@ func restoredDomain(ctx context.Context, tx *sql.Tx, domain, table, version stri if !exists && errors.Is(err, sql.ErrNoRows) { return false, nil } - if err != nil || !exists || v != version { + if err != nil || !exists || !slices.Contains(versions, v) { return false, restoredWorkSchema() } return true, nil @@ -203,7 +208,7 @@ func abandonRestoredAttempts(ctx context.Context, tx *sql.Tx, at time.Time, summ if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_execution_attempts WHERE operation_id=?`, o.ID).Scan(&linked); err != nil { return err } - if !restoredOperationValid(o) || o.AttemptID != "" || linked != 0 { + if !restoredOperationValid(o) || o.AttemptID != "" || linked != 0 && validateOperationWaitHistory(ctx, tx, o) != nil { return restoredWorkInvalid() } stamp, err := attemptRecordingStamp(ctx, tx, o, nil, at) @@ -227,7 +232,10 @@ func abandonRestoredAttempts(ctx context.Context, tx *sql.Tx, at time.Time, summ if err != nil { return err } - if !restoredOperationValid(o) || a.ID != o.AttemptID || a.ProjectID != o.ProjectID || a.OperationID != o.ID || a.State != o.State || a.Revision < 1 || a.Revision >= math.MaxInt64-1 || o.Revision != a.Revision+1 || !hostedObservationID(a.ID, "review_attempt_") || !identifier.MatchString(a.Provider) || !identifier.MatchString(a.Account) || (a.ExternalID != "" && !identifier.MatchString(a.ExternalID)) { + // Operation revisions also include queued controls and earlier cooldown + // attempts. Current ownership plus the complete transition/reservation + // validation below establishes this attempt, not revision equality. + if !restoredOperationValid(o) || a.ID != o.AttemptID || a.ProjectID != o.ProjectID || a.OperationID != o.ID || a.State != o.State || a.Revision < 1 || a.Revision >= math.MaxInt64-1 || o.Revision <= a.Revision || !hostedObservationID(a.ID, "review_attempt_") || !identifier.MatchString(a.Provider) || !identifier.MatchString(a.Account) || (a.ExternalID != "" && !identifier.MatchString(a.ExternalID)) { return restoredWorkInvalid() } stamp, err := attemptRecordingStamp(ctx, tx, o, &a, at) diff --git a/internal/reviewexec/restored_provider_work_test.go b/internal/reviewexec/restored_provider_work_test.go index 8558cc2bf..f5852320c 100644 --- a/internal/reviewexec/restored_provider_work_test.go +++ b/internal/reviewexec/restored_provider_work_test.go @@ -253,7 +253,7 @@ func TestRestoredProviderWorkCapacityRollback(t *testing.T) { // Canonical queued rows use one genuine request as a template. No provider // evidence or completion is synthesized by this capacity fixture. original := f.enqueue(t, attemptProject, "capacity-template", "cli", 2, 1) - _, err := f.store.DB().Exec(`WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO review_operations SELECT 'overflow-'||x,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision FROM review_operations,n WHERE id=?`, original.ID) + _, err := f.store.DB().Exec(`WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO review_operations (id,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision) SELECT 'overflow-'||x,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision FROM review_operations,n WHERE id=?`, original.ID) if err != nil { t.Fatal(err) } diff --git a/internal/reviewexec/round_progress.go b/internal/reviewexec/round_progress.go new file mode 100644 index 000000000..504b72cb4 --- /dev/null +++ b/internal/reviewexec/round_progress.go @@ -0,0 +1,131 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + + "github.com/benhook1013/FireController/internal/core" +) + +// RoundProgressChannel contains current native allowance facts only. Pending +// counts operations bound to this epoch, not coverage or permission to dispatch. +type RoundProgressChannel struct { + Wait *OperationWait `json:"wait,omitempty"` + Channel string `json:"channel"` + Configured bool `json:"configured"` + Revision int64 `json:"revision"` + Epoch int64 `json:"epoch"` + Closed bool `json:"closed"` + Minimum int64 `json:"minimum"` + Maximum int64 `json:"maximum"` + MaximumUnbounded bool `json:"maximum_unbounded,omitempty"` + Taper int64 `json:"taper"` + Used int64 `json:"used"` + Dry int64 `json:"dry"` + Tapered bool `json:"tapered"` + Pending int64 `json:"pending"` + PendingExecution *int64 `json:"pending_execution,omitempty"` + PendingAdjudication *int64 `json:"pending_adjudication,omitempty"` +} + +type RoundProgressItem struct { + PullNumber int64 `json:"pull_number"` + Channels []RoundProgressChannel `json:"channels"` +} + +type RoundProgress struct { + ProjectID string `json:"project_id"` + EvaluatedAt string `json:"evaluated_at"` + Items []RoundProgressItem `json:"items"` +} + +func validRoundProgressNumbers(numbers []int64) bool { + if len(numbers) < 1 || len(numbers) > 100 { + return false + } + seen := make(map[int64]bool, len(numbers)) + for _, number := range numbers { + if number < 1 || number > 2147483647 || seen[number] { + return false + } + seen[number] = true + } + return true +} + +// ReadRoundProgress reads one bounded, authorized local snapshot. It does not +// interpret imported history or collect source, captures, CI or provider state. +func (e *Engine) ReadRoundProgress(ctx context.Context, scope core.Scope, numbers []int64) (RoundProgress, error) { + return e.readRoundProgress(ctx, scope, numbers, false) +} + +// ReadRoundProgressStages splits the same occupancy into execution and +// adjudication without changing reservation or completion accounting. +func (e *Engine) ReadRoundProgressStages(ctx context.Context, scope core.Scope, numbers []int64) (RoundProgress, error) { + return e.readRoundProgress(ctx, scope, numbers, true) +} + +func (e *Engine) readRoundProgress(ctx context.Context, scope core.Scope, numbers []int64, stages bool) (RoundProgress, error) { + if ctx == nil || e == nil || e.store == nil || !identifier.MatchString(scope.ProjectID) || !validRoundProgressNumbers(numbers) { + return RoundProgress{}, invalid() + } + numbers = append([]int64(nil), numbers...) + out := RoundProgress{ProjectID: scope.ProjectID, Items: make([]RoundProgressItem, 0, len(numbers))} + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + for _, number := range numbers { + item := RoundProgressItem{PullNumber: number, Channels: make([]RoundProgressChannel, 0, 2)} + for _, channel := range []string{"hosted", "cli"} { + control, err := readRoundRecord(ctx, tx, scope.ProjectID, number, channel) + if err != nil { + return err + } + var execution, adjudication int64 + if control.Configured { + execution, adjudication, err = roundOccupancyStages(ctx, tx, control, "") + if err != nil { + return err + } + } + progress := RoundProgressChannel{ + Channel: channel, Configured: control.Configured, Revision: control.Revision, + Epoch: control.Epoch, Closed: control.Closed, Minimum: control.Minimum, + Maximum: control.Maximum, MaximumUnbounded: control.MaximumUnbounded, Taper: control.Taper, Used: control.Used, + Dry: control.Dry, Tapered: control.Tapered, Pending: execution + adjudication, + } + if stages { + progress.PendingExecution, progress.PendingAdjudication = &execution, &adjudication + progress.Wait, err = readChannelWait(ctx, tx, scope.ProjectID, number, channel) + if err != nil { + return err + } + } + item.Channels = append(item.Channels, progress) + } + out.Items = append(out.Items, item) + } + out.EvaluatedAt = stamp() + return nil + }) + if err != nil { + return RoundProgress{}, err + } + return out, nil +} + +// Project only a current queued intent, never infer a timer from a held run. +func readChannelWait(ctx context.Context, tx *sql.Tx, project string, number int64, channel string) (*OperationWait, error) { + var id string + err := tx.QueryRowContext(ctx, `SELECT o.id FROM review_operations o JOIN review_operation_waits w ON w.operation_id=o.id WHERE o.project_id=? AND o.pull_number=? AND o.channel=? AND o.state='queued' AND o.attempt_id='' ORDER BY o.created_at,o.id LIMIT 1`, project, number, channel).Scan(&id) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + o, err := readOperationBase(ctx, tx, project, id) + if err != nil { + return nil, err + } + return currentOperationWait(o), nil +} diff --git a/internal/reviewexec/round_progress_http.go b/internal/reviewexec/round_progress_http.go new file mode 100644 index 000000000..b7f316a60 --- /dev/null +++ b/internal/reviewexec/round_progress_http.go @@ -0,0 +1,69 @@ +package reviewexec + +import ( + "net/http" + "strconv" + "strings" + + "github.com/benhook1013/FireController/internal/core" +) + +func roundProgressNumbers(r *http.Request) ([]int64, error) { + if len(r.URL.RawQuery) > 4096 { + return nil, invalid() + } + query, err := core.QueryKeys(r, "validation_failed", "pull_numbers", "view") + if err != nil { + return nil, err + } + if query.Has("view") && query.Get("view") != "stages" { + return nil, invalid() + } + raw := query.Get("pull_numbers") + // One hundred int32 values and their separating commas need at most 1099 bytes. + if raw == "" || len(raw) > 1099 { + return nil, invalid() + } + values := strings.Split(raw, ",") + if len(values) > 100 { + return nil, invalid() + } + numbers := make([]int64, 0, len(values)) + for _, value := range values { + number, err := strconv.ParseInt(value, 10, 32) + if err != nil || strconv.FormatInt(number, 10) != value { + return nil, invalid() + } + numbers = append(numbers, number) + } + if !validRoundProgressNumbers(numbers) { + return nil, invalid() + } + return numbers, nil +} + +func (e *Engine) readRoundProgressHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Vary", operationWaitHeader) + scope, err := e.store.Scope(r, "read") + if err != nil { + core.WriteError(w, err) + return + } + numbers, err := roundProgressNumbers(r) + if err != nil { + core.WriteError(w, err) + return + } + progress, err := e.readRoundProgress(r.Context(), scope, numbers, r.URL.Query().Get("view") == "stages") + if err != nil { + core.WriteError(w, err) + return + } + for i := range progress.Items { + for j := range progress.Items[i].Channels { + channel := &progress.Items[i].Channels[j] + channel.Wait = operationWaitForResponse(channel.Wait, channel.Channel, r.Header.Get(operationWaitHeader)) + } + } + core.WriteJSON(w, http.StatusOK, progress) +} diff --git a/internal/reviewexec/round_progress_stages_test.go b/internal/reviewexec/round_progress_stages_test.go new file mode 100644 index 000000000..b901a3b31 --- /dev/null +++ b/internal/reviewexec/round_progress_stages_test.go @@ -0,0 +1,111 @@ +package reviewexec + +import ( + "encoding/json" + "net/http" + "reflect" + "strings" + "testing" +) + +func progressStageChannel(t *testing.T, f *attemptFixture, query string, channel int) map[string]any { + t.Helper() + w := f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers=2&"+query, f.reader, "", "") + var response struct { + Items []struct { + Channels []map[string]any `json:"channels"` + } `json:"items"` + } + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &response) != nil || len(response.Items) != 1 || len(response.Items[0].Channels) != 2 { + t.Fatal("invalid progress", w.Code, w.Body.String()) + } + return response.Items[0].Channels[channel] +} + +func assertProgressStages(t *testing.T, value map[string]any, execution, adjudication float64) { + t.Helper() + if value["pending_execution"] != execution || value["pending_adjudication"] != adjudication || value["pending"] != execution+adjudication { + t.Fatal("stages lost or double-counted occupancy", value) + } +} + +func TestRoundProgressStagesExecutionAdjudicationAndFinalization(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "cli", 0, 0, 8, "grant-stages") + a, evidence := roundCapture(t, f, 600, true) + active := f.enqueue(t, attemptProject, "active-stages", "cli", 2, 1) + attempt := f.start(t, attemptProject, active) + if _, err := f.e.Admit(t.Context(), attemptProject, attempt.ID, attempt.Revision, attemptAnchor(attemptProject, 2), ""); err != nil { + t.Fatal(err) + } + // Rebuilding without capabilities proves these are provider-free local reads. + var err error + f.e, err = New(f.store, nil) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + f.e.Register(mux) + f.handler = mux + before := roundTables(t, f) + policyState(t, f) + attemptState(t, f, a) + staged := progressStageChannel(t, f, "view=stages", 1) + assertProgressStages(t, staged, 1, 1) + read, err := f.e.ReadRoundProgressStages(t.Context(), evidenceReadScope(t, f, attemptProject, f.reader), []int64{2}) + if err != nil || len(read.Items) != 1 || read.Items[0].Channels[1].PendingExecution == nil || read.Items[0].Channels[1].PendingAdjudication == nil || *read.Items[0].Channels[1].PendingExecution != 1 || *read.Items[0].Channels[1].PendingAdjudication != 1 { + t.Fatal("staged engine read disagrees", read, err) + } + assertProgressStages(t, progressStageChannel(t, f, "view=stages", 0), 0, 0) + legacy := progressStageChannel(t, f, "", 1) + if _, ok := legacy["pending_execution"]; ok { + t.Fatal("legacy response gained stages") + } + if _, ok := legacy["pending_adjudication"]; ok { + t.Fatal("legacy response gained stages") + } + delete(staged, "pending_execution") + delete(staged, "pending_adjudication") + if !reflect.DeepEqual(staged, legacy) || before != roundTables(t, f)+policyState(t, f)+attemptState(t, f, a) { + t.Fatal("read changed accounting or legacy fields") + } + roundFinalize(t, f, a, evidence, 600, true) + assertProgressStages(t, progressStageChannel(t, f, "view=stages", 1), 1, 0) +} + +func TestRoundProgressStagesLegacyEpochAndStrictReadScope(t *testing.T) { + f := roundFixture(t) + seedLegacyRoundGrant(t, f, 2, "cli", 0, 0, 8, "legacy-stages") + roundCapture(t, f, 601, true) + // Legacy controls retain terminal-unfinalized capacity until adjudication. + assertProgressStages(t, progressStageChannel(t, f, "view=stages", 1), 0, 1) + roundGrant(t, f, 2, "cli", 1, 0, 8, "convert-stages") + assertProgressStages(t, progressStageChannel(t, f, "view=stages", 1), 0, 1) + for _, query := range []string{"view=", "view=all", "view=stages&view=stages", "view=stages&unknown=x"} { + w := f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers=2&"+query, f.reader, "", "") + if w.Code != http.StatusBadRequest { + t.Fatal("invalid view accepted", query, w.Code) + } + } + w := f.request(http.MethodGet, roundProgressPath(otherAttemptProject)+"?pull_numbers=2&view=stages", f.reader, "", "") + if w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), `"items"`) { + t.Fatal("foreign project exposed", w.Code) + } + admissionSQL(t, f, `UPDATE grants SET can_read=0 WHERE credential_id='exec-reader-cred'`) + w = f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers=2&view=stages", f.reader, "", "") + if w.Code != http.StatusForbidden { + t.Fatal("revoked grant retained stage access", w.Code) + } + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-reader-cred'`) + w = f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers=2&view=stages", f.reader, "", "") + if w.Code != http.StatusUnauthorized { + t.Fatal("revoked credential retained stage access", w.Code) + } + // A predecessor-format epoch replacement fixture retains its original + // capture/binding while a later epoch owns current capacity. + g := roundFixture(t) + seedLegacyRoundGrant(t, g, 2, "cli", 0, 0, 8, "old-epoch") + roundCapture(t, g, 602, true) + seedLegacyRoundGrant(t, g, 2, "cli", 1, 0, 8, "new-epoch") + roundGrant(t, g, 2, "cli", 2, 0, 8, "convert-new-epoch") + g.enqueue(t, attemptProject, "current-epoch-stage", "cli", 2, 1) + assertProgressStages(t, progressStageChannel(t, g, "view=stages", 1), 1, 0) +} diff --git a/internal/reviewexec/round_progress_test.go b/internal/reviewexec/round_progress_test.go new file mode 100644 index 000000000..7a985eada --- /dev/null +++ b/internal/reviewexec/round_progress_test.go @@ -0,0 +1,535 @@ +package reviewexec + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func roundProgressPath(project string) string { + return "/api/v1/projects/" + project + "/reviews/rounds/progress" +} + +func readProgress(t *testing.T, f *attemptFixture, numbers ...int64) RoundProgress { + t.Helper() + progress, err := f.e.ReadRoundProgress(t.Context(), evidenceReadScope(t, f, attemptProject, f.reader), numbers) + if err != nil { + t.Fatal(err) + } + return progress +} + +func TestRoundProgressStoredFactsAndCompactHTTPWithoutCapabilities(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "cli", 0, 1, 4, "grant-cli") + roundGrant(t, f, 2, "hosted", 0, 0, 2, "grant-hosted") + a, evidence := roundCapture(t, f, 301, false) + roundFinalize(t, f, a, evidence, 301, false) + revision := int64(1) + if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "closed-cli", 2, "cli", RoundControlRequest{ExpectedRevision: &revision, Action: "close"}); err != nil { + t.Fatal(err) + } + // Current allowance reads require neither an available provider catalog nor + // a source observation. They must not reconstruct state from browser runs. + var err error + f.e, err = New(f.store, nil) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + f.e.Register(mux) + f.handler = mux + before := roundTables(t, f) + policyState(t, f) + attemptState(t, f, a) + w := f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers=4,2,2147483647", f.reader, "", "") + var result RoundProgress + var wire map[string]json.RawMessage + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &result) != nil || json.Unmarshal(w.Body.Bytes(), &wire) != nil || len(wire) != 3 { + t.Fatal("invalid compact progress response", w.Code, w.Body.String()) + } + at, err := time.Parse(time.RFC3339Nano, result.EvaluatedAt) + if err != nil || at.IsZero() || result.ProjectID != attemptProject || len(result.Items) != 3 { + t.Fatal("missing local evaluation identity", result, err) + } + for i, number := range []int64{4, 2, 2147483647} { + item := result.Items[i] + if item.PullNumber != number || len(item.Channels) != 2 || item.Channels[0].Channel != "hosted" || item.Channels[1].Channel != "cli" { + t.Fatal("request or channel order changed", item) + } + for _, channel := range item.Channels { + var fields map[string]any + raw, _ := json.Marshal(channel) + if json.Unmarshal(raw, &fields) != nil || len(fields) != 12 { + t.Fatal("channel field allowlist changed", string(raw)) + } + for _, key := range []string{"channel", "configured", "revision", "epoch", "closed", "minimum", "maximum", "taper", "used", "dry", "tapered", "pending"} { + if _, ok := fields[key]; !ok { + t.Fatal("required compact field missing", key) + } + } + if number != 2 && !reflect.DeepEqual(channel, RoundProgressChannel{Channel: channel.Channel}) { + t.Fatal("missing grant gained allowance or pending credit", channel) + } + } + } + hosted, cli := result.Items[1].Channels[0], result.Items[1].Channels[1] + if !hosted.Configured || hosted.Maximum != 2 || hosted.Taper != 2 || hosted.Closed || hosted.Pending != 0 { + t.Fatal("hosted allowance changed", hosted) + } + if !cli.Configured || cli.Revision != 2 || cli.Epoch != 1 || !cli.Closed || cli.Minimum != 1 || cli.Maximum != 4 || cli.Taper != 2 || cli.Used != 1 || cli.Dry != 1 || cli.Tapered || cli.Pending != 0 { + t.Fatal("native consumed/closed allowance changed", cli) + } + for _, private := range []string{"actor_id", "origin_", "capability", "evidence", "operation_id", "source", "ready", "coverage"} { + if strings.Contains(w.Body.String(), private) { + t.Fatal("progress exposed unrelated authority or private provenance", private) + } + } + if after := roundTables(t, f) + policyState(t, f) + attemptState(t, f, a); after != before { + t.Fatal("progress read changed controls, journal, receipts or events") + } +} + +func TestRoundProgressClosedCurrentEpochCountsAllLiveStates(t *testing.T) { + for _, state := range []string{"queued", "preparing", "posting", "active", "uncertain"} { + t.Run(state, func(t *testing.T) { + f := roundFixture(t) + channel := "cli" + if state == "posting" || state == "uncertain" { + channel = "hosted" + } + roundGrant(t, f, 2, channel, 0, 0, 3, "grant") + receipt := f.enqueue(t, attemptProject, "pending", channel, 2, 1) + if state != "queued" { + a := f.start(t, attemptProject, receipt) + if state != "preparing" { + intent := "" + if channel == "hosted" { + intent = "retained-posting-intent" + } + var err error + a, err = f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, attemptAnchor(attemptProject, 2), intent) + if err != nil { + t.Fatal(err) + } + if state == "uncertain" { + if _, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "uncertain", "ambiguous_post", ""); err != nil { + t.Fatal(err) + } + } + } + } + revision := int64(1) + if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, attemptProject, f.admin, true), "close-live", 2, channel, RoundControlRequest{ExpectedRevision: &revision, Action: "close"}); err != nil { + t.Fatal(err) + } + before := roundTables(t, f) + policyState(t, f) + result := readProgress(t, f, 2) + for _, actual := range result.Items[0].Channels { + if actual.Channel == channel { + if !actual.Closed || actual.Pending != 1 || actual.Epoch != 1 || actual.Revision != 2 || actual.Used != 0 { + t.Fatal("closure hid live capacity or counted consumed credit", actual) + } + } else if actual.Configured || actual.Pending != 0 { + t.Fatal("pending work crossed channels", actual) + } + } + if before != roundTables(t, f)+policyState(t, f) { + t.Fatal("pending read changed durable state") + } + }) + } +} + +func TestRoundProgressEpochProjectPullAndUnboundIsolation(t *testing.T) { + f := roundFixture(t) + seedLegacyRoundGrant(t, f, 2, "cli", 0, 0, 4, "epoch-one") + old := f.enqueue(t, attemptProject, "old-epoch", "cli", 2, 1) + a := f.start(t, attemptProject, old) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "fixture_stop", ""); err != nil { + t.Fatal(err) + } + seedLegacyRoundGrant(t, f, 2, "cli", 1, 1, 2, "epoch-two") + current := f.enqueue(t, attemptProject, "current-epoch", "cli", 2, 1) + // This retained-row fixture makes old-epoch filtering observable; ordinary + // grant replacement refuses live work and is proved in its owning tests. + admissionSQL(t, f, `UPDATE review_operations SET state='uncertain' WHERE id=?`, old.ID) + if roundOperation(t, f, current.ID).State != "queued" { + t.Fatal("current operation fixture is not pending") + } + // A legacy single-comparison request has no grant binding and must not be + // counted as current-epoch work merely because its PR appears in the batch. + f.enqueue(t, attemptProject, "unbound-hosted", "hosted", 4, 1) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + zero, minimum, maximum := int64(0), int64(0), int64(9) + if _, err := f.e.ConfigureRoundControl(t.Context(), f.scope(t, otherAttemptProject, f.admin, true), "other-grant", 2, "cli", RoundControlRequest{ExpectedRevision: &zero, Action: "grant", Minimum: &minimum, Maximum: &maximum}); err != nil { + t.Fatal(err) + } + f.enqueue(t, otherAttemptProject, "other-operation", "cli", 2, 1) + before := roundTables(t, f) + policyState(t, f) + result := readProgress(t, f, 4, 2) + if c := result.Items[1].Channels[1]; c.Epoch != 2 || c.Maximum != 2 || c.Minimum != 1 || c.Pending != 1 || c.Used != 0 || c.Dry != 0 { + t.Fatal("another epoch/project/PR changed current grant progress", c) + } + if c := result.Items[0].Channels[0]; c.Configured || c.Pending != 0 { + t.Fatal("unbound native work fabricated a current allowance", c) + } + other, err := f.e.ReadRoundProgress(t.Context(), evidenceReadScope(t, f, otherAttemptProject, f.other), []int64{2}) + if err != nil || other.Items[0].Channels[1].Maximum != 9 || other.Items[0].Channels[1].Pending != 1 { + t.Fatal("other project lost independent grant", other, err) + } + if before != roundTables(t, f)+policyState(t, f) { + t.Fatal("isolated reads changed stored state") + } +} + +func TestRoundProgressStrictQueryAndEngineValidationBeforeControlReads(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "cli", 0, 0, 4, "grant") + // A selected corrupted row would fail a real control read. Malformed input + // must still be rejected locally rather than reaching that state read. + admissionSQL(t, f, `UPDATE review_round_controls SET actor_id='invalid/actor' WHERE project_id=?`, attemptProject) + before := roundTables(t, f) + policyState(t, f) + numbers := make([]string, 101) + for i := range numbers { + numbers[i] = strconv.Itoa(i + 1) + } + queries := []string{"", "pull_numbers", "pull_numbers=", "pull_numbers=null", "pull_numbers=0", "pull_numbers=-1", "pull_numbers=01", "pull_numbers=%2B1", "pull_numbers=1.0", "pull_numbers=2147483648", "pull_numbers=1,", "pull_numbers=,1", "pull_numbers=1,,2", "pull_numbers=1,1", "pull_numbers=1,%202", "pull_numbers=1%0A", "pull_numbers=2&pull_numbers=4", "pull_numbers=2&unknown=x", "pull_numbers=%zz", "pull_numbers=1;other=x", "pull_numbers=" + strings.Join(numbers, ","), "pull_numbers=" + strings.Repeat("1", 4097)} + for _, query := range queries { + r := httptest.NewRequest(http.MethodGet, roundProgressPath(attemptProject), nil) + r.URL.RawQuery = query + r.Header.Set("Authorization", "Bearer "+f.reader) + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), `"code":"validation_failed"`) { + t.Fatal("invalid query reached control read or was accepted", query, w.Code, w.Body.String()) + } + } + scope := evidenceReadScope(t, f, attemptProject, f.reader) + tooMany := make([]int64, 101) + for i := range tooMany { + tooMany[i] = int64(i + 1) + } + for _, input := range [][]int64{nil, {}, {0}, {-1}, {2147483648}, {2, 2}, tooMany} { + _, err := f.e.ReadRoundProgress(t.Context(), scope, input) + attemptCode(t, err, "validation_failed") + } + if _, err := f.e.ReadRoundProgress(nil, scope, []int64{2}); err == nil { + t.Fatal("nil context accepted") + } + w := f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers=4,2", f.reader, "", "") + if w.Code != http.StatusInternalServerError || strings.Contains(w.Body.String(), `"items"`) { + t.Fatal("corrupt control returned partial or fabricated progress", w.Code, w.Body.String()) + } + if before != roundTables(t, f)+policyState(t, f) { + t.Fatal("validation or corrupt-read refusal changed state") + } +} + +func TestRoundProgressReadAuthorizationRevocationAndBatchBound(t *testing.T) { + f := roundFixture(t) + path := roundProgressPath(attemptProject) + "?pull_numbers=2" + scope := evidenceReadScope(t, f, attemptProject, f.reader) + for _, test := range []struct{ name, path, token, instance string }{ + {"foreign-project", strings.Replace(path, attemptProject, otherAttemptProject, 1), f.reader, f.store.InstanceID()}, + {"foreign-credential", path, f.other, f.store.InstanceID()}, + {"missing-access", path, "", f.store.InstanceID()}, + {"wrong-instance", path, f.reader, "other-instance"}, + } { + t.Run(test.name, func(t *testing.T) { + before := roundTables(t, f) + policyState(t, f) + r := httptest.NewRequest(http.MethodGet, test.path, nil) + if test.token != "" { + r.Header.Set("Authorization", "Bearer "+test.token) + } + r.Header.Set("X-FC-Instance", test.instance) + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code < 400 || strings.Contains(w.Body.String(), `"items"`) || before != roundTables(t, f)+policyState(t, f) { + t.Fatal("unauthorized read exposed data or mutated state", w.Code) + } + }) + } + values := make([]string, 100) + for i := range values { + values[i] = strconv.Itoa(i + 1) + } + w := f.request(http.MethodGet, roundProgressPath(attemptProject)+"?pull_numbers="+strings.Join(values, ","), f.reader, "", "") + var result RoundProgress + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Items) != 100 { + t.Fatal("maximum valid batch refused", w.Code) + } + admissionSQL(t, f, `UPDATE grants SET can_read=0 WHERE credential_id='exec-reader-cred'`) + _, err := f.e.ReadRoundProgress(t.Context(), scope, []int64{2}) + attemptCode(t, err, "forbidden") + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-reader-cred'`) + _, err = f.e.ReadRoundProgress(t.Context(), scope, []int64{2}) + attemptCode(t, err, "unauthorized") + if w := f.request(http.MethodGet, path, f.reader, "", ""); w.Code != http.StatusUnauthorized { + t.Fatal("revoked HTTP reader retained access", w.Code) + } +} + +func TestRoundProgressReadDoesNotWaitForWriterAdmission(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "cli", 0, 0, 2, "grant") + scope := evidenceReadScope(t, f, attemptProject, f.reader) + entered, release := make(chan struct{}), make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- f.store.BackgroundWrite(t.Context(), func(context.Context, *sql.Tx) error { close(entered); <-release; return nil }) + }() + <-entered + ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond) + result, err := f.e.ReadRoundProgress(ctx, scope, []int64{2}) + cancel() + close(release) + writerErr := <-done + if err != nil || writerErr != nil || len(result.Items) != 1 || !result.Items[0].Channels[1].Configured { + t.Fatal("read waited for writer admission", result, err, writerErr) + } +} + +func TestRoundProgressQueuedHoldDropsPendingAtomicallyWithEvent(t *testing.T) { + for _, failEvent := range []bool{false, true} { + name := "normal" + if failEvent { + name = "event-failure-and-retry" + } + t.Run(name, func(t *testing.T) { + f := roundFixture(t) + roundGrant(t, f, 2, "cli", 0, 0, 3, "grant") + receipt := f.enqueue(t, attemptProject, "queued-before-change", "cli", 2, 1) + if c := readProgress(t, f, 2).Items[0].Channels[1]; c.Pending != 1 || c.Used != 0 { + t.Fatal("queued operation was not included", c) + } + f.configure(t, attemptProject, "other-account", 1, false) + if failEvent { + admissionSQL(t, f, `CREATE TRIGGER progress_hold_event_failure BEFORE INSERT ON events WHEN NEW.event_type='review.operation_updated' BEGIN SELECT RAISE(ABORT,'fixture event failure'); END`) + before := roundTables(t, f) + policyState(t, f) + original := roundOperation(t, f, receipt.ID) + if _, err := f.e.StartAttempt(t.Context(), attemptProject, receipt.ID); err == nil { + t.Fatal("event failure did not reject the hold transaction") + } + if roundOperation(t, f, receipt.ID) != original || before != roundTables(t, f)+policyState(t, f) || readProgress(t, f, 2).Items[0].Channels[1].Pending != 1 { + t.Fatal("failed event partially committed hold or pending count") + } + admissionSQL(t, f, `DROP TRIGGER progress_hold_event_failure`) + } + attempt, err := f.e.StartAttempt(t.Context(), attemptProject, receipt.ID) + if err != nil || attempt.ID != "" { + t.Fatal("configuration hold unexpectedly created an attempt", attempt, err) + } + operation := roundOperation(t, f, receipt.ID) + if operation.State != "held" || operation.Reason != "configuration_changed" || operation.AttemptID != "" { + t.Fatal("queued operation did not retain the hold", operation) + } + before := roundTables(t, f) + policyState(t, f) + if c := readProgress(t, f, 2).Items[0].Channels[1]; c.Pending != 0 || c.Used != 0 || c.Dry != 0 { + t.Fatal("held operation kept occupied capacity or gained completion", c) + } + if count := attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.operation_updated' AND project_id=? AND resource_id=? AND revision=? AND payload_json='{}'`, attemptProject, receipt.ID, operation.Revision); count != 1 { + t.Fatal("hold event identity/revision not committed exactly once", count) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 || before != roundTables(t, f)+policyState(t, f) { + t.Fatal("hold read created an attempt, receipt or event") + } + }) + } +} + +func TestRoundProgressLedgerOnlyTerminalTransitionInvalidatesWithoutProjection(t *testing.T) { + for _, failEvent := range []bool{false, true} { + name := "normal" + if failEvent { + name = "event-failure-and-retry" + } + t.Run(name, func(t *testing.T) { + f := attemptProjectionFixture(t, false) + if err := EnsureRoundSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + roundGrant(t, f, 2, "cli", 0, 0, 3, "ledger-grant") + receipt := f.enqueue(t, attemptProject, "ledger-only-pending", "cli", 2, 1) + a := f.start(t, attemptProject, receipt) + if c := readProgress(t, f, 2).Items[0].Channels[1]; c.Pending != 1 { + t.Fatal("ledger-only action not pending", c) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_snapshots`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.observed'`) != 0 { + t.Fatal("missing PR fixture unexpectedly has a browser projection") + } + if failEvent { + admissionSQL(t, f, `CREATE TRIGGER progress_terminal_event_failure BEFORE INSERT ON events WHEN NEW.event_type='review.operation_updated' BEGIN SELECT RAISE(ABORT,'fixture event failure'); END`) + before := roundTables(t, f) + policyState(t, f) + attemptState(t, f, a) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "failed", "local_preparation_failed", ""); err == nil { + t.Fatal("event failure allowed terminal state to commit") + } + if before != roundTables(t, f)+policyState(t, f)+attemptState(t, f, a) || readProgress(t, f, 2).Items[0].Channels[1].Pending != 1 { + t.Fatal("failed invalidation partially changed ledger or pending count") + } + admissionSQL(t, f, `DROP TRIGGER progress_terminal_event_failure`) + } + terminal, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "failed", "local_preparation_failed", "") + if err != nil || terminal.State != "failed" { + t.Fatal("ledger-only failure transition unavailable", terminal, err) + } + operation := roundOperation(t, f, receipt.ID) + before := roundTables(t, f) + policyState(t, f) + attemptState(t, f, terminal) + if c := readProgress(t, f, 2).Items[0].Channels[1]; c.Pending != 0 || c.Used != 0 || c.Dry != 0 { + t.Fatal("terminal action stayed in flight or gained completion credit", c) + } + if count := attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.operation_updated' AND project_id=? AND resource_id=? AND revision=? AND payload_json='{}'`, attemptProject, receipt.ID, operation.Revision); count != 1 { + t.Fatal("ledger-only terminal state did not emit one compact matching event", count) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_snapshots`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.observed'`) != 0 || before != roundTables(t, f)+policyState(t, f)+attemptState(t, f, terminal) { + t.Fatal("terminal read fabricated display state or mutated retained facts") + } + }) + } +} + +func TestRoundProgressLedgerOnlyHostedSettlementInvalidatesAtomically(t *testing.T) { + f := attemptProjectionFixture(t, false) + if err := EnsureRoundSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + // Bind to the current grant through normal acceptance, before any attempt + // exists. Settlement must release pending capacity without final credit. + roundGrant(t, f, 2, "hosted", 0, 0, 2, "settlement-grant") + receipt := f.enqueue(t, attemptProject, "settlement-pending", "hosted", 2, 1) + a := f.start(t, attemptProject, receipt) + anchor := attemptAnchor(attemptProject, 2) + intent, err := reviewprovider.HostedTriggerBody(reviewprovider.HostedTriggerIntent{OperationID: a.OperationID, AttemptID: a.ID, HeadSHA: anchor.CandidateSHA}) + if err != nil { + t.Fatal(err) + } + a, err = f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, anchor, intent) + if err != nil { + t.Fatal(err) + } + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "uncertain", "dispatch_interrupted", "") + if err != nil { + t.Fatal(err) + } + finished := time.Now().Add(-time.Second).UTC().Format(time.RFC3339Nano) + input := HostedObservationInput{CaptureBytes: 1024, StartedAt: time.Now().Add(-2 * time.Second).UTC().Format(time.RFC3339Nano), FinishedAt: finished, ObservedAt: finished, ExpectedAnchor: anchor, Intent: intent} + // Use the same complete retained-observation path as hostedSettlementFixture; + // no direct state inserts bypass the public settlement admission guard. + for i := range hostedObservationLimit { + digest := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("controlled retained reference ", i)))) + input.CaptureSHA256, input.CaptureID = digest, "review_capture_"+digest[:32] + if _, err := f.e.RecordHostedObservation(t.Context(), attemptProject, a.ID, input); err != nil { + t.Fatal(err) + } + } + if c := readProgress(t, f, 2).Items[0].Channels[0]; c.Epoch != 1 || c.Pending != 1 || c.Used != 0 { + t.Fatal("uncertain settlement candidate not pending in current epoch", c) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_snapshots`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.observed'`) != 0 { + t.Fatal("ledger-only settlement fixture unexpectedly has browser state") + } + admissionSQL(t, f, `CREATE TRIGGER progress_settlement_event_failure BEFORE INSERT ON events WHEN NEW.event_type='review.operation_updated' BEGIN SELECT RAISE(ABORT,'fixture event failure'); END`) + before := roundTables(t, f) + policyState(t, f) + hostedObservationState(t, f, a) + failed := hostedSettlementCall(t, f, a, "progress-settlement", hostedSettlementBody(a)) + if failed.Code != http.StatusInternalServerError { + t.Fatal("failed invalidation allowed settlement", failed.Code, failed.Body.String()) + } + if before != roundTables(t, f)+policyState(t, f)+hostedObservationState(t, f, a) || readProgress(t, f, 2).Items[0].Channels[0].Pending != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations WHERE attempt_id=?`, a.ID) != 1 { + t.Fatal("failed settlement invalidation partially committed ledger, capacity or receipt") + } + admissionSQL(t, f, `DROP TRIGGER progress_settlement_event_failure`) + settled := hostedSettlementCall(t, f, a, "progress-settlement", hostedSettlementBody(a)) + if settled.Code != http.StatusOK { + t.Fatal("settlement retry failed", settled.Code, settled.Body.String()) + } + operation := roundOperation(t, f, receipt.ID) + if operation.State != "cancelled" || operation.Reason != "operator_verified_external_stop" || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations WHERE attempt_id=?`, a.ID) != 0 { + t.Fatal("settlement did not release the original action", operation) + } + if c := readProgress(t, f, 2).Items[0].Channels[0]; c.Pending != 0 || c.Used != 0 || c.Dry != 0 || c.Epoch != 1 { + t.Fatal("settlement kept pending capacity or fabricated credit", c) + } + if count := attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.operation_updated' AND project_id=? AND resource_id=? AND revision=? AND payload_json='{}'`, attemptProject, receipt.ID, operation.Revision); count != 1 { + t.Fatal("settlement did not emit one compact operation invalidation", count) + } + before = roundTables(t, f) + policyState(t, f) + hostedObservationState(t, f, a) + replay := hostedSettlementCall(t, f, a, "progress-settlement", hostedSettlementBody(a)) + if replay.Code != http.StatusOK || replay.Body.String() != settled.Body.String() || before != roundTables(t, f)+policyState(t, f)+hostedObservationState(t, f, a) { + t.Fatal("settlement replay duplicated events, receipts or credits", replay.Code, replay.Body.String()) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_snapshots`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.observed'`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 { + t.Fatal("settlement manufactured browser state or completed evidence") + } +} + +func TestRoundProgressLedgerOnlyStartupRecoveryInvalidatesAtomically(t *testing.T) { + f := attemptProjectionFixture(t, false) + if err := EnsureRoundSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + roundGrant(t, f, 2, "cli", 0, 0, 3, "recovery-cli-grant") + roundGrant(t, f, 2, "hosted", 0, 0, 2, "recovery-hosted-grant") + preparingReceipt := f.enqueue(t, attemptProject, "recovery-preparing", "cli", 2, 1) + preparing := f.start(t, attemptProject, preparingReceipt) + postingReceipt := f.enqueue(t, attemptProject, "recovery-posting", "hosted", 2, 1) + posting := f.start(t, attemptProject, postingReceipt) + var err error + posting, err = f.e.Admit(t.Context(), attemptProject, posting.ID, posting.Revision, attemptAnchor(attemptProject, 2), "retained-recovery-intent") + if err != nil { + t.Fatal(err) + } + for _, channel := range readProgress(t, f, 2).Items[0].Channels { + if channel.Epoch != 1 || channel.Pending != 1 || channel.Used != 0 { + t.Fatal("startup fixture lacks current-epoch pending work", channel) + } + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_snapshots`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.observed'`) != 0 { + t.Fatal("ledger-only startup fixture unexpectedly has browser state") + } + admissionSQL(t, f, `CREATE TRIGGER progress_recovery_event_failure BEFORE INSERT ON events WHEN NEW.event_type='review.operation_updated' BEGIN SELECT RAISE(ABORT,'fixture event failure'); END`) + before := roundTables(t, f) + policyState(t, f) + attemptState(t, f, preparing) + attemptState(t, f, posting) + if err := f.e.RecoverInterrupted(t.Context()); err == nil { + t.Fatal("failed invalidation allowed startup cancellation") + } + if before != roundTables(t, f)+policyState(t, f)+attemptState(t, f, preparing)+attemptState(t, f, posting) { + t.Fatal("failed startup invalidation partially changed attempts or capacity") + } + admissionSQL(t, f, `DROP TRIGGER progress_recovery_event_failure`) + if err := f.e.RecoverInterrupted(t.Context()); err != nil { + t.Fatal("startup recovery retry failed", err) + } + cancelled := roundOperation(t, f, preparingReceipt.ID) + uncertain := roundOperation(t, f, postingReceipt.ID) + if cancelled.State != "cancelled" || cancelled.Reason != "supervisor_interrupted" || uncertain.State != "uncertain" || uncertain.Reason != "supervisor_interrupted" { + t.Fatal("startup recovery changed the wrong lifecycle states", cancelled, uncertain) + } + progress := readProgress(t, f, 2) + if c := progress.Items[0].Channels[1]; c.Pending != 0 || c.Used != 0 || c.Dry != 0 || c.Epoch != 1 { + t.Fatal("preparing cancellation kept pending capacity or gained credit", c) + } + if c := progress.Items[0].Channels[0]; c.Pending != 1 || c.Used != 0 || c.Dry != 0 || c.Epoch != 1 { + t.Fatal("ambiguous hosted dispatch incorrectly released capacity or gained credit", c) + } + if count := attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.operation_updated' AND project_id=? AND resource_id=? AND revision=? AND payload_json='{}'`, attemptProject, preparingReceipt.ID, cancelled.Revision); count != 1 { + t.Fatal("startup cancellation lacks one compact matching invalidation", count) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations WHERE attempt_id=?`, preparing.ID) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations WHERE attempt_id=?`, posting.ID) != 1 { + t.Fatal("startup recovery released the wrong reservations") + } + before = roundTables(t, f) + policyState(t, f) + attemptState(t, f, preparing) + attemptState(t, f, posting) + if err := f.e.RecoverInterrupted(t.Context()); err != nil || before != roundTables(t, f)+policyState(t, f)+attemptState(t, f, preparing)+attemptState(t, f, posting) { + t.Fatal("repeated recovery duplicated events, transitions or credit", err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_snapshots`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM events WHERE event_type='review.observed'`) != 0 { + t.Fatal("startup recovery manufactured a browser projection") + } +} diff --git a/internal/reviewexec/schema.go b/internal/reviewexec/schema.go index 8bcd8bdef..f820d7361 100644 --- a/internal/reviewexec/schema.go +++ b/internal/reviewexec/schema.go @@ -2,38 +2,66 @@ package reviewexec import ( "context" + "database/sql" "github.com/benhook1013/FireController/internal/adoptionholds" "github.com/benhook1013/FireController/internal/core" ) func EnsureSchema(ctx context.Context, store *core.Store) error { + if _, err := retainedComparisonSchema(ctx, store.DB()); err != nil { + return err + } if err := EnsurePolicySchema(ctx, store); err != nil { return err } - if err := store.EnsureSchema(ctx, "review_execution", []string{ + if err := store.EnsureSchemaWithBackfill(ctx, "review_execution", [][]string{{ `CREATE TABLE review_execution_config(project_id TEXT NOT NULL REFERENCES projects(id),revision INTEGER NOT NULL CHECK(revision>0),body_json TEXT NOT NULL,PRIMARY KEY(project_id,revision))`, `CREATE TABLE review_operations(id TEXT PRIMARY KEY,project_id TEXT NOT NULL REFERENCES projects(id),actor_id TEXT NOT NULL,worker_id TEXT NOT NULL,configuration_revision INTEGER NOT NULL,pull_number INTEGER NOT NULL,channel TEXT NOT NULL,head_sha TEXT NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL,reason TEXT NOT NULL,attempt_id TEXT NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL,FOREIGN KEY(project_id,configuration_revision) REFERENCES review_execution_config(project_id,revision))`, `CREATE INDEX review_operations_pending ON review_operations(state,created_at,id)`, `CREATE TABLE review_execution_attempts(id TEXT PRIMARY KEY,operation_id TEXT NOT NULL UNIQUE REFERENCES review_operations(id),project_id TEXT NOT NULL REFERENCES projects(id),provider TEXT NOT NULL,account TEXT NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL,anchor_json TEXT NOT NULL,intent TEXT NOT NULL,external_id TEXT NOT NULL)`, `CREATE TABLE review_execution_reservations(provider TEXT NOT NULL,repository_id INTEGER NOT NULL,pull_number INTEGER NOT NULL,action_class TEXT NOT NULL,account TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),PRIMARY KEY(provider,repository_id,pull_number,action_class),UNIQUE(provider,account,action_class))`, `CREATE TABLE review_execution_transitions(attempt_id TEXT NOT NULL REFERENCES review_execution_attempts(id),revision INTEGER NOT NULL,state TEXT NOT NULL,reason TEXT NOT NULL,external_id TEXT NOT NULL,created_at TEXT NOT NULL,PRIMARY KEY(attempt_id,revision))`, - }, []string{`ALTER TABLE review_operations ADD COLUMN capability_fingerprint TEXT NOT NULL DEFAULT ''`}, []string{ + }, {`ALTER TABLE review_operations ADD COLUMN capability_fingerprint TEXT NOT NULL DEFAULT ''`}, { `ALTER TABLE review_operations ADD COLUMN policy_revision INTEGER NOT NULL DEFAULT 0`, - }, []string{ + }, { `CREATE TABLE review_cli_preflight(attempt_id TEXT PRIMARY KEY REFERENCES review_execution_attempts(id),project_id TEXT NOT NULL REFERENCES projects(id),body_json TEXT NOT NULL)`, `CREATE INDEX review_operations_cli_admission ON review_operations(project_id,pull_number,channel,state,id)`, - }, []string{ + }, { `CREATE INDEX review_operations_completed_comparison ON review_operations(project_id,channel,pull_number,id) WHERE state='completed'`, `DROP INDEX review_operations_cli_admission`, - }, []string{ + }, { `CREATE TABLE review_hosted_preflight(attempt_id TEXT PRIMARY KEY REFERENCES review_execution_attempts(id),project_id TEXT NOT NULL REFERENCES projects(id),body_json TEXT NOT NULL)`, `CREATE TABLE review_hosted_allowance_queries(id TEXT PRIMARY KEY,project_id TEXT NOT NULL REFERENCES projects(id),attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),operation_id TEXT NOT NULL REFERENCES review_operations(id),capability_fingerprint TEXT NOT NULL,revision INTEGER NOT NULL CHECK(revision IN (1,2)),body_json TEXT NOT NULL)`, - }); err != nil { + }, { + `ALTER TABLE review_operations ADD COLUMN allow_out_of_order INTEGER NOT NULL DEFAULT 0 CHECK(allow_out_of_order IN (0,1))`, + }, { + `ALTER TABLE review_operations ADD COLUMN override_file_limit INTEGER NOT NULL DEFAULT 0 CHECK(override_file_limit IN (0,1))`, + }, { + `PRAGMA defer_foreign_keys=ON`, + `CREATE TABLE review_execution_attempts_next(id TEXT PRIMARY KEY,operation_id TEXT NOT NULL REFERENCES review_operations(id),project_id TEXT NOT NULL REFERENCES projects(id),provider TEXT NOT NULL,account TEXT NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL,anchor_json TEXT NOT NULL,intent TEXT NOT NULL,external_id TEXT NOT NULL)`, + `INSERT INTO review_execution_attempts_next SELECT id,operation_id,project_id,provider,account,state,revision,anchor_json,intent,external_id FROM review_execution_attempts`, + `DROP TABLE review_execution_attempts`, + `ALTER TABLE review_execution_attempts_next RENAME TO review_execution_attempts`, + `CREATE INDEX review_attempts_operation ON review_execution_attempts(operation_id,id)`, + `CREATE UNIQUE INDEX review_attempts_live_operation ON review_execution_attempts(operation_id) WHERE state IN ('preparing','posting','active','uncertain')`, + `CREATE TABLE review_operation_waits(operation_id TEXT PRIMARY KEY REFERENCES review_operations(id),baseline_attempt_id TEXT REFERENCES review_execution_attempts(id),retry_not_before TEXT NOT NULL DEFAULT '',paused INTEGER NOT NULL DEFAULT 0 CHECK(paused IN(0,1)),CHECK((baseline_attempt_id IS NULL AND retry_not_before='') OR (baseline_attempt_id IS NOT NULL AND retry_not_before<>'')))`, + }, { + `CREATE TABLE review_execution_reservations_next(provider TEXT NOT NULL,repository_id INTEGER NOT NULL,pull_number INTEGER NOT NULL,action_class TEXT NOT NULL,account TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE REFERENCES review_execution_attempts(id),PRIMARY KEY(provider,repository_id,pull_number,action_class))`, + `INSERT INTO review_execution_reservations_next(provider,repository_id,pull_number,action_class,account,attempt_id) SELECT provider,repository_id,pull_number,action_class,account,attempt_id FROM review_execution_reservations`, + `DROP TABLE review_execution_reservations`, + `ALTER TABLE review_execution_reservations_next RENAME TO review_execution_reservations`, + `CREATE UNIQUE INDEX review_reservations_cli_account ON review_execution_reservations(provider,account,action_class) WHERE action_class='cli'`, + `CREATE UNIQUE INDEX review_reservations_hosted_account_repository ON review_execution_reservations(provider,account,repository_id,action_class) WHERE action_class='hosted'`, + }}, backfillExecutionSchema); err != nil { return err } // Index maintenance has its own version so newer execution-table // migrations retain their existing positions in deployed databases. - if err := store.EnsureSchema(ctx, "review_execution_indexes", []string{`DROP INDEX IF EXISTS review_operations_coverage`}, []string{`CREATE INDEX review_operations_listing ON review_operations(project_id,created_at DESC,id DESC)`}); err != nil { + if err := store.EnsureSchema(ctx, "review_execution_indexes", []string{`DROP INDEX IF EXISTS review_operations_coverage`}, []string{`CREATE INDEX review_operations_listing ON review_operations(project_id,created_at DESC,id DESC)`}, []string{ + `CREATE INDEX review_waits_live_retry ON review_operation_waits(rtrim(retry_not_before,'Z') DESC,operation_id,baseline_attempt_id) WHERE retry_not_before<>''`, + `CREATE INDEX review_transitions_exhaustion_time ON review_execution_transitions(rtrim(created_at,'Z') DESC,attempt_id,revision) WHERE state='held' AND reason='allowance_exhausted'`, + `CREATE INDEX review_transitions_exhaustion_attempt ON review_execution_transitions(attempt_id,rtrim(created_at,'Z')) WHERE state='held' AND reason='allowance_exhausted'`, + }); err != nil { return err } if err := EnsureEvidenceSchema(ctx, store); err != nil { @@ -65,3 +93,56 @@ func EnsureSchema(ctx context.Context, store *core.Store) error { } return EnsureSelectionSchema(ctx, store) } + +// Execution migration nine rebuilds attempts independently of the comparison +// schema version. Restore its triggers in the same migration transaction even +// when that separately versioned domain is already current. +func backfillExecutionSchema(ctx context.Context, conn *sql.Conn) error { + if err := validateExecutionForeignKeys(ctx, conn); err != nil { + return err + } + comparisonExists, err := retainedComparisonSchema(ctx, conn) + if err != nil { + return err + } + if comparisonExists { + for _, statement := range comparisonAttemptTriggerRepairSQL() { + if _, err := conn.ExecContext(ctx, statement); err != nil { + return err + } + } + } + return nil +} + +func validateExecutionForeignKeys(ctx context.Context, conn *sql.Conn) error { + rows, err := conn.QueryContext(ctx, `PRAGMA foreign_key_check`) + if err != nil { + return err + } + invalid := rows.Next() + rowErr := rows.Err() + closeErr := rows.Close() + if invalid { + return core.Fail("schema_invalid", "Execution migration found inconsistent retained references.", 500) + } + if rowErr != nil { + return rowErr + } + if closeErr != nil { + return closeErr + } + var enabled int + if err := conn.QueryRowContext(ctx, `PRAGMA foreign_keys`).Scan(&enabled); err != nil { + return err + } + if enabled != 1 { + return core.Fail("schema_invalid", "Execution migration requires enforced retained references.", 500) + } + // SQLite retains deferred violation bookkeeping from DROP of the original + // parent even when its replacement satisfies every child reference. Clear + // that bookkeeping only after checking all real constraints. Enforcement + // remains enabled throughout the exclusive migration and at commit. + _, err = conn.ExecContext(ctx, `PRAGMA defer_foreign_keys=OFF`) + return err +} diff --git a/internal/reviewexec/source_refresh.go b/internal/reviewexec/source_refresh.go index 8fabc3e43..05d040bab 100644 --- a/internal/reviewexec/source_refresh.go +++ b/internal/reviewexec/source_refresh.go @@ -278,15 +278,27 @@ func (e *Engine) refreshBinding(ctx context.Context, tx *sql.Tx, r sourceRefresh // reads. The actual parent can lie after the target or outside the queue; its // identity comes from provider facts, while its enrollment must remain stable. func sameSourceTargetConfiguration(a, b Configuration, number, parent int64) bool { - if a.CapabilityID != b.CapabilityID || a.Mode != b.Mode || !slices.Equal(a.Channels, b.Channels) { + if a.CapabilityID != b.CapabilityID || a.Mode != b.Mode || !sameChannelSet(a.Channels, b.Channels) { return false } left, right := slices.Index(a.Queue, number), slices.Index(b.Queue, number) return left >= 0 && right == left && slices.Equal(a.Queue[:left+1], b.Queue[:right+1]) && (parent == 0 || slices.Contains(a.Queue, parent) == slices.Contains(b.Queue, parent)) } +func sameChannelSet(a, b []string) bool { + if len(a) != len(b) { + return false + } + for _, channel := range a { + if !slices.Contains(b, channel) { + return false + } + } + return true +} + func sameSourceConfiguration(a, b Configuration) bool { - return a.CapabilityID == b.CapabilityID && a.Mode == b.Mode && slices.Equal(a.Queue, b.Queue) && slices.Equal(a.Channels, b.Channels) + return a.CapabilityID == b.CapabilityID && a.Mode == b.Mode && slices.Equal(a.Queue, b.Queue) && sameChannelSet(a.Channels, b.Channels) } func sourceConfiguration(ctx context.Context, tx *sql.Tx, project string, revision int64) (Configuration, error) { var c Configuration diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 67e5868d0..ed4b22cc0 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -5,6 +5,7 @@ import ( "database/sql" "encoding/json" "errors" + "log/slog" "reflect" "strings" "sync" @@ -61,6 +62,10 @@ func (e *Engine) Start(ctx context.Context, drivers map[string]Driver) (<-chan e if !e.running.CompareAndSwap(false, true) { return nil, conflict() } + if err := e.reconcilePreparingDrivers(ctx, owned); err != nil { + e.running.Store(false) + return nil, err + } if err := e.RecoverInterrupted(ctx); err != nil { e.running.Store(false) return nil, err @@ -75,14 +80,15 @@ func (e *Engine) Start(ctx context.Context, drivers map[string]Driver) (<-chan e return done, nil } -// supervise owns the same two finite work slots; provider waits never hold a -// database transaction. Start has already completed startup recovery. +// supervise owns the same two finite work slots. Only one probes retained Draft +// waits, so slow source reads cannot occupy both dispatch workers. Provider +// waits never hold a database transaction; startup recovery is already complete. func (e *Engine) supervise(ctx context.Context, owned map[string]Driver) error { workCtx, cancelWork := context.WithCancel(ctx) defer cancelWork() failures := make(chan error, 1) var workers sync.WaitGroup - for range 2 { + for worker := range 2 { workers.Go(func() { timer := time.NewTimer(0) defer timer.Stop() @@ -96,7 +102,7 @@ func (e *Engine) supervise(ctx context.Context, owned map[string]Driver) error { if workCtx.Err() != nil { return } - if err := e.processNext(workCtx, owned); err != nil { + if err := e.processNextForWorker(workCtx, owned, worker == 0); err != nil { select { case failures <- err: default: @@ -118,6 +124,10 @@ func (e *Engine) supervise(ctx context.Context, owned map[string]Driver) error { } func (e *Engine) pending(ctx context.Context) ([]Operation, error) { + return e.pendingForWorker(ctx, true) +} + +func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Operation, error) { ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() // Snapshot candidates and reservations together, without entering writer @@ -127,10 +137,18 @@ func (e *Engine) pending(ctx context.Context) ([]Operation, error) { return nil, err } defer tx.Rollback() + now := e.sampleExecutionTime() args := make([]any, 0, 4*len(e.capabilities)) for _, capability := range e.capabilities { args = append(args, capability.ID, capability.Provider, capability.Account, capability.Fingerprint) } + args = append(args, now.UTC().Format(time.RFC3339Nano)) + draftFilter := "" + if !probeDrafts { + // Filter before the finite candidate window: a prefix of Draft waits + // must not hide ready work in another project from this worker. + draftFilter = " AND NOT (o.channel='cli' AND o.reason='cli_draft_wait')" + } // Only matching retained bindings can be skipped as busy. Missing/changed // capabilities remain candidates for StartAttempt's normal hold handling. query := `WITH installed(id,provider,account,fingerprint) AS (VALUES (NULL,NULL,NULL,NULL)` + strings.Repeat(`,(?,?,?,?)`, len(e.capabilities)) + `) @@ -138,8 +156,10 @@ func (e *Engine) pending(ctx context.Context) ([]Operation, error) { JOIN review_execution_config c ON c.project_id=o.project_id AND c.revision=o.configuration_revision JOIN projects p ON p.id=o.project_id LEFT JOIN installed i ON i.id=CASE WHEN json_valid(c.body_json) THEN json_extract(c.body_json,'$.capability_id') END AND i.fingerprint=o.capability_fingerprint - WHERE o.state='queued' - AND NOT EXISTS (SELECT 1 FROM review_execution_reservations r WHERE r.provider=i.provider AND r.account=i.account AND r.action_class=o.channel) + WHERE o.state='queued'` + draftFilter + ` + AND NOT EXISTS (SELECT 1 FROM review_operation_waits w WHERE w.operation_id=o.id AND (w.paused=1 OR (w.retry_not_before<>'' AND julianday(w.retry_not_before)>julianday(?)))) + AND NOT EXISTS (SELECT 1 FROM review_execution_config latest WHERE latest.project_id=o.project_id AND latest.revision=(SELECT MAX(revision) FROM review_execution_config WHERE project_id=o.project_id) AND json_valid(latest.body_json) AND json_extract(latest.body_json,'$.paused')=1) + AND NOT EXISTS (SELECT 1 FROM review_execution_reservations r WHERE r.provider=i.provider AND r.account=i.account AND r.action_class=o.channel AND (o.channel='cli' OR r.repository_id=p.github_repository_id)) AND NOT EXISTS (SELECT 1 FROM review_execution_reservations r WHERE r.provider=i.provider AND r.repository_id=p.github_repository_id AND r.pull_number=o.pull_number AND r.action_class=o.channel) ORDER BY o.created_at,o.id LIMIT 256` rows, err := tx.QueryContext(ctx, query, args...) @@ -161,13 +181,68 @@ func (e *Engine) pending(ctx context.Context) ([]Operation, error) { if err != nil { return nil, err } + type configurationSnapshot struct { + configuration Configuration + revision int64 + } + configurations := map[string]configurationSnapshot{} + type accountKey struct{ provider, account string } + cliRetryDeadlines := map[accountKey]time.Time{} + cliUnavailable := map[accountKey]bool{} + emptyPredecessors := map[queuePriorityKey]bool{} out := make([]Operation, 0, len(ids)) for _, i := range ids { o, err := readOperation(ctx, tx, i.project, i.operation) if err != nil { + if e.skipUnavailableWait(ctx, o, err) { + continue + } return nil, err } if o.State == "queued" { + configuration, ok := configurations[o.ProjectID] + if !ok { + c, revision, err := readConfiguration(ctx, tx, o.ProjectID) + if err != nil { + return nil, err + } + configuration = configurationSnapshot{c, revision} + configurations[o.ProjectID] = configuration + } + c, revision := configuration.configuration, configuration.revision + earlier, err := e.earlierQueuedReviewIntentInSnapshot(ctx, tx, o, c, revision, emptyPredecessors) + if err != nil { + if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + continue + } + return nil, err + } + if earlier != nil { + continue + } + if o.Channel == "cli" { + if capability, ok := e.capabilities[c.CapabilityID]; ok && capability.Fingerprint == o.CapabilityFingerprint { + key := accountKey{capability.Provider, capability.Account} + if cliUnavailable[key] { + continue + } + due, cached := cliRetryDeadlines[key] + if !cached { + due, err = cliAccountRetryDeadline(ctx, tx, capability, now) + if err != nil { + if e.skipUnavailableWait(ctx, o, err) { + cliUnavailable[key] = true + continue + } + return nil, err + } + cliRetryDeadlines[key] = due + } + if now.Before(due) { + continue + } + } + } out = append(out, o) } } @@ -184,6 +259,8 @@ func preparationReason(err error) string { } if details, ok := failure.Details.(map[string]string); failure.Code == "review_held" && ok { switch reason := details["reason"]; reason { + case "pull_draft", "source_changed": + return reason case "source_obligations_pending", "repository_changed", "allowance_exhausted", "allowance_unavailable", "target_already_covered", "predecessor_identity_changed", "predecessor_unavailable", "predecessor_unfinished", "execution_binding_changed", "preparation_duplicate", "source_unavailable", "workspace_unavailable", "workspace_changed", "comparison_unavailable", "project_file_limit", "provider_activity_unproven", "provider_review_active", "provider_actor_unproven", "hosted_allowance_unproven", "hosted_allowance_cooldown", "standing_baseline_unproven": return reason } @@ -192,23 +269,116 @@ func preparationReason(err error) string { return "preparation_failed" } +// A malformed retained configuration affects this candidate's authority, not +// the database or other projects. Preserve the request and its queue turn. The +// bounded process-local throttle limits diagnostics, never admission or retries. +func (e *Engine) skipUnavailableConfiguration(ctx context.Context, o Operation, err error) bool { + if !isStoredUnavailable(err, storedConfigurationHistory) { + return false + } + now := e.sampleExecutionTime() + e.configurationFailureMu.Lock() + defer e.configurationFailureMu.Unlock() + if e.configurationFailureNext[o.ID].After(now) { + return true + } + for id, next := range e.configurationFailureNext { + if !next.After(now) { + delete(e.configurationFailureNext, id) + } + } + if len(e.configurationFailureNext) >= 256 { + return true + } + if e.configurationFailureNext == nil { + e.configurationFailureNext = make(map[string]time.Time) + } + e.configurationFailureNext[o.ID] = now.Add(30 * time.Second) + slog.WarnContext(ctx, "Review candidate configuration history unavailable", "project_id", o.ProjectID, "operation_id", o.ID, "reason", "configuration_history_unavailable") + return true +} + +// Typed wait validation failures refuse only this candidate and its guarded scope. Real +// database and context failures retain their normal supervisor behavior. +func (e *Engine) skipUnavailableWait(ctx context.Context, o Operation, err error) bool { + if !validChannel(o.Channel) || !isWaitUnavailable(err) { + return false + } + now := e.sampleExecutionTime() + e.configurationFailureMu.Lock() + defer e.configurationFailureMu.Unlock() + key := o.Channel + "-wait:" + o.ID + if e.configurationFailureNext[key].After(now) { + return true + } + for id, next := range e.configurationFailureNext { + if !next.After(now) { + delete(e.configurationFailureNext, id) + } + } + if len(e.configurationFailureNext) >= 256 { + return true + } + if e.configurationFailureNext == nil { + e.configurationFailureNext = make(map[string]time.Time) + } + e.configurationFailureNext[key] = now.Add(30 * time.Second) + slog.WarnContext(ctx, "Review candidate wait history unavailable", "project_id", o.ProjectID, "operation_id", o.ID, "channel", o.Channel, "reason", o.Channel+"_wait_history_unavailable") + return true +} + func (e *Engine) processNext(ctx context.Context, drivers map[string]Driver) error { - operations, err := e.pending(ctx) + return e.processNextForWorker(ctx, drivers, true) +} + +func (e *Engine) processNextForWorker(ctx context.Context, drivers map[string]Driver, probeDrafts bool) error { + operations, err := e.pendingForWorker(ctx, probeDrafts) if err != nil { if ctx.Err() != nil { return nil } return persistenceFailure() } + probeID := "" + if probeDrafts { + probeID = e.nextDraftProbe(operations) + } for _, o := range operations { if ctx.Err() != nil { return nil } - a, err := e.StartAttempt(ctx, o.ProjectID, o.ID) + if o.Channel == "cli" && o.Reason == cliDraftWait && o.ID != probeID { + continue + } + proceed, draftReady, explicitCLI, err := e.checkCLIDraft(ctx, o, drivers) if err != nil { if ctx.Err() != nil { return nil } + if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + continue + } + var refusal *core.Error + if errors.As(err, &refusal) && (refusal.Code == "overloaded" || refusal.Code == "review_conflict") { + continue + } + return persistenceFailure() + } + if !proceed { + continue + } + var draftReadyRevision int64 + if draftReady { + draftReadyRevision = o.Revision + } + a, err := e.startAttempt(ctx, o.ProjectID, o.ID, draftReadyRevision) + if err != nil { + if ctx.Err() != nil { + return nil + } + if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + continue + } var failure *core.Error if errors.As(err, &failure) { switch failure.Code { @@ -238,8 +408,25 @@ func (e *Engine) processNext(ctx context.Context, drivers map[string]Driver) err prepared, err := driver.Prepare(prepareCtx, o, c, a) cancel() if err != nil { + var recoverable *PreparationRecoveryError + if errors.As(err, &recoverable) { + return err + } state := "held" reason := preparationReason(err) + if explicitCLI && reason == "pull_draft" { + reason = cliDraftWait + } + if ctx.Err() == nil && (o.Channel == "hosted" && reason == "hosted_allowance_cooldown" || o.Channel == "cli" && reason == "allowance_exhausted") { + _, scheduleErr := e.persistCooldown(ctx, o, a) + if scheduleErr == nil { + return nil + } + var refusal *core.Error + if ctx.Err() == nil && !cooldownEvidenceUnavailable(o.Channel, scheduleErr) && (!errors.As(scheduleErr, &refusal) || refusal.Code != "review_cooldown_elapsed") { + return scheduleErr + } + } if ctx.Err() != nil { state = "cancelled" reason = "supervisor_stopping" diff --git a/internal/reviewexec/supervisor_cooldown.go b/internal/reviewexec/supervisor_cooldown.go new file mode 100644 index 000000000..de1426992 --- /dev/null +++ b/internal/reviewexec/supervisor_cooldown.go @@ -0,0 +1,132 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "github.com/benhook1013/FireController/internal/core" + "time" +) + +// Only unavailable provider evidence permits an operation-local hold. Do not +// turn unrelated database/context errors or a missing attempt into that claim. +func cooldownEvidenceUnavailable(channel string, err error) bool { + if channel == "cli" { + return errors.Is(err, sql.ErrNoRows) + } + return channel == "hosted" && (errors.Is(err, errAllowanceObservationAbsent) || storedAllowanceUnavailable(err) || isStoredUnavailable(err, storedHostedObservation)) +} + +func (e *Engine) persistCooldown(ctx context.Context, original Operation, a Attempt) (Attempt, error) { + local, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + var result Attempt + err := retryRunSelectionLocal(local, func() error { + entered := false + callbackDeadline := false + writeErr := e.store.BackgroundWrite(local, func(ctx context.Context, tx *sql.Tx) error { + entered = true + var err error + if original.Channel == "cli" { + result, err = e.scheduleCLICooldown(ctx, tx, a.ProjectID, a.ID, a.Revision) + } else { + result, err = e.scheduleHostedCooldown(ctx, tx, a.ProjectID, a.ID, a.Revision) + } + // A nonnil callback error makes BackgroundWrite roll back without + // invoking Commit. Only its actual child deadline is retryable; a + // domain overload or an expired outer budget is not that proof. + callbackDeadline = err != nil && errors.Is(ctx.Err(), context.DeadlineExceeded) && local.Err() == nil + return err + }) + if writeErr == nil { + e.notifyOperation(a.OperationID) + return nil + } + var failure *core.Error + if (!entered || callbackDeadline) && errors.As(writeErr, &failure) && failure.Code == "overloaded" { + return writeErr + } + // A failed commit may already be present. Only the exact original timer + // and guarded attempt transition reconcile that ambiguity without a write. + if recovered, ok := e.recordedCooldown(local, original, a); ok { + result = recovered + e.notifyOperation(a.OperationID) + return nil + } + if cooldownEvidenceUnavailable(original.Channel, writeErr) { + return writeErr + } + if errors.As(writeErr, &failure) && failure.Code == "review_cooldown_elapsed" { + return writeErr + } + return persistenceFailure() + }) + if err != nil { + if cooldownEvidenceUnavailable(original.Channel, err) { + return Attempt{}, err + } + var failure *core.Error + if errors.As(err, &failure) && (failure.Code == "review_persistence_failed" || failure.Code == "review_cooldown_elapsed") { + return Attempt{}, err + } + return Attempt{}, persistenceFailure() + } + return result, nil +} + +func (e *Engine) recordedCooldown(ctx context.Context, original Operation, a Attempt) (Attempt, bool) { + // A commit error can race supervisor shutdown. Reconcile only the exact + // durable outcome, with a separate bounded read that survives that caller. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second) + defer cancel() + var result Attempt + err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + current, err := readAttempt(ctx, tx, a.ProjectID, a.ID) + if err != nil { + return err + } + o, err := readOperation(ctx, tx, a.ProjectID, a.OperationID) + if err != nil { + return err + } + baseline := a.ID + if original.Wait != nil && original.Wait.BaselineAttemptID != "" { + baseline = original.Wait.BaselineAttemptID + } + if current.OperationID != a.OperationID || current.ProjectID != a.ProjectID || current.Provider != a.Provider || current.Account != a.Account || current.Revision != a.Revision+1 || current.State != "held" || current.Anchor != nil || current.Intent != "" || current.ExternalID != "" || o.ID != original.ID || o.ProjectID != original.ProjectID || o.PullNumber != original.PullNumber || o.Channel != original.Channel || o.ActorID != original.ActorID || o.WorkerID != original.WorkerID || o.PolicyRevision != original.PolicyRevision || o.Revision != original.Revision+2 || o.State != "queued" || o.AttemptID != "" || o.Reason != "" || o.HeadSHA != original.HeadSHA || o.ConfigurationRevision != original.ConfigurationRevision || o.CapabilityFingerprint != original.CapabilityFingerprint || o.Wait == nil || o.Wait.BaselineAttemptID != baseline { + return conflict() + } + historical, err := historicalCooldownOperation(ctx, tx, o, current) + if err != nil { + return err + } + if original.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, tx, historical, current) + if err != nil || record.Observation.Remaining != 0 { + return waitUnavailable() + } + due, err := cliExhaustionDeadline(ctx, tx, current) + if err != nil || o.Wait.RetryNotBefore != due.UTC().Format(time.RFC3339Nano) { + return conflict() + } + } else { + record, err := readHostedAllowanceRecord(ctx, tx, historical, current) + if err != nil { + return err + } + if record.Input.Observation.State != "cooldown_observed" || o.Wait.RetryNotBefore != record.Input.Observation.RetryNotBefore.UTC().Format(time.RFC3339Nano) { + return conflict() + } + } + var reserved bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?)`, a.ID).Scan(&reserved); err != nil { + return err + } + if reserved { + return conflict() + } + result = current + return nil + }) + return result, err == nil +} diff --git a/internal/reviewexec/supervisor_test.go b/internal/reviewexec/supervisor_test.go index 1e907116f..c511d468c 100644 --- a/internal/reviewexec/supervisor_test.go +++ b/internal/reviewexec/supervisor_test.go @@ -59,16 +59,32 @@ func TestSupervisorPendingSkipsBusyBeforeLimitAndWakesAfterRelease(t *testing.T) func TestSupervisorPendingUsesRetainedAccountAndStableTarget(t *testing.T) { f := supervisorFixture(t) - f.start(t, attemptProject, f.enqueue(t, attemptProject, "reserved", "cli", 2, 1)) - f.enqueue(t, attemptProject, "original-account", "cli", 4, 1) + + busy := f.enqueue(t, attemptProject, "reserved", "cli", 2, 1) + f.start(t, attemptProject, busy) + original := f.enqueue(t, attemptProject, "original-account", "cli", 4, 1) f.configure(t, attemptProject, "other-account", 1, false) - f.enqueue(t, attemptProject, "reserved-target-other-account", "cli", 2, 2) - free := f.enqueue(t, attemptProject, "free-target-other-account", "cli", 4, 2) + // Public admission forbids a second intent for the same target. Seed legacy + // pending rows directly to exercise retained-account filtering independently. + schedulerQueuedCopy(t, f, busy.ID, "reserved-target-other-account") + schedulerQueuedCopy(t, f, original.ID, "free-target-other-account") + if _, err := f.store.DB().Exec(`UPDATE review_operations SET configuration_revision=2,capability_fingerprint=? WHERE id IN ('reserved-target-other-account','free-target-other-account')`, f.e.capabilities["other-account"].Fingerprint); err != nil { + t.Fatal(err) + } + free := Receipt{ID: "free-target-other-account"} hosted := f.enqueue(t, attemptProject, "independent-channel", "hosted", 2, 2) if _, err := f.store.DB().Exec(`UPDATE projects SET repository='renamed/repository' WHERE id=?`, attemptProject); err != nil { t.Fatal(err) } operations, err := f.e.pending(context.Background()) + // The retained earlier CLI intent also preserves project queue priority. + if err != nil || len(operations) != 1 || operations[0].ID != hosted.ID { + t.Fatalf("reserved target or earlier queue intent was bypassed: %v %v", operations, err) + } + if _, err := f.store.DB().Exec(`UPDATE review_operations SET state='held',reason='synthetic_release' WHERE id='reserved-target-other-account'`); err != nil { + t.Fatal(err) + } + operations, err = f.e.pending(context.Background()) if err != nil || len(operations) != 2 { t.Fatalf("retained account/target filtering failed: %d %v", len(operations), err) } @@ -84,7 +100,7 @@ func TestSupervisorPendingUsesRetainedAccountAndStableTarget(t *testing.T) { t.Fatal(err) } operations, err = withoutCapabilities.pending(context.Background()) - if err != nil || len(operations) != 4 { + if err != nil || len(operations) != 3 { t.Fatalf("unavailable capabilities were silently hidden: %d %v", len(operations), err) } } @@ -105,12 +121,15 @@ func TestSupervisorBusyQueueDoesNotEnterWriterAndCoordinationStaysUsable(t *test if _, err := f.e.Admit(context.Background(), attemptProject, busy.ID, busy.Revision, attemptAnchor(attemptProject, 2), ""); err != nil { t.Fatal(err) } - for i := range 31 { - f.enqueue(t, attemptProject, fmt.Sprintf("busy-%02d", i), "cli", 4, 1) + + seed := f.enqueue(t, attemptProject, "busy-seed", "cli", 4, 1) + for i := range 30 { + schedulerQueuedCopy(t, f, seed.ID, fmt.Sprintf("busy-%02d", i)) } f.configure(t, otherAttemptProject, "test-capability", 0, false) - for i := range 8 { - f.enqueue(t, otherAttemptProject, fmt.Sprintf("other-project-busy-%02d", i), "cli", 2, 1) + other := f.enqueue(t, otherAttemptProject, "other-project-seed", "cli", 2, 1) + for i := range 7 { + schedulerQueuedCopy(t, f, other.ID, fmt.Sprintf("other-project-busy-%02d", i)) } // Occupy the real writer admission slot. A read-only busy scan must finish // without waiting for it; a failed StartAttempt would still wait here. @@ -361,9 +380,15 @@ func TestSupervisorReceiptsAndCoordinationRemainFastDuringProviderWait(t *testin t.Fatal("dispatch did not begin") } proveOrdinaryCoordination(t, f, "write-during-dispatch", receipt.ID) - queuedDuringDispatch, _ := supervisorRequest(t, f, "new-during-dispatch", "cli", 4) - if supervisorOperationState(t, f, queuedDuringDispatch.ID) != "queued" { - t.Fatal("new receipt waited for or bypassed occupied account during dispatch") + queuedDuringDispatch, _ := supervisorRequest(t, f, "new-during-preparation", "cli", 4) + if queuedDuringDispatch.ID != queuedDuringPrepare.ID || supervisorOperationState(t, f, queuedDuringDispatch.ID) != "queued" { + t.Fatal("original queued receipt was not replayed during dispatch") + } + started := time.Now() + _, err := f.e.Enqueue(t.Context(), f.scope(t, attemptProject, f.writer, false), "duplicate-during-dispatch", Request{ExpectedConfigurationRevision: 1, PullNumber: 4, Channel: "cli", HeadSHA: strings.Repeat("a", 40)}) + attemptCode(t, err, "review_inflight") + if time.Since(started) > time.Second { + t.Fatal("duplicate refusal waited for provider dispatch") } _, replay = supervisorRequest(t, f, "fast-receipt", "cli", 2) if !bytes.Equal(original, replay) || driver.calls.Load() != 1 { @@ -1113,8 +1138,13 @@ func TestSupervisorRetainedConfigurationFailureRetainsPreparingAttempt(t *testin if err := f.store.DB().QueryRow(`SELECT revision,state,reason FROM review_execution_transitions WHERE attempt_id=?`, attemptID).Scan(&transitionRevision, &transitionState, &transitionReason); err != nil || transitionRevision != 1 || transitionState != "preparing" || transitionReason != "preparing" { t.Fatal("configuration read failure rewrote original transition", transitionRevision, transitionState, transitionReason, err) } - if driver.prepares.Load() != 0 || driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_transitions`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM events`) != beforeEvents || attemptCount(t, f.store, `SELECT count(*) FROM receipts`) != beforeReceipts { - t.Fatal("configuration failure dispatched, settled or added journal effects") + var eventType, eventSubject, eventProject string + var eventRevision int64 + if err := f.store.DB().QueryRow(`SELECT event_type,resource_id,project_id,revision FROM events ORDER BY sequence DESC LIMIT 1`).Scan(&eventType, &eventSubject, &eventProject, &eventRevision); err != nil || eventType != "review.operation_updated" || eventSubject != receipt.ID || eventProject != attemptProject || eventRevision != 2 { + t.Fatal("preparing claim did not retain its exact operation event", eventType, eventSubject, eventProject, eventRevision, err) + } + if driver.prepares.Load() != 0 || driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_transitions`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM events`) != beforeEvents+1 || attemptCount(t, f.store, `SELECT count(*) FROM receipts`) != beforeReceipts { + t.Fatal("configuration failure dispatched, settled or changed effects beyond the preparing event") } } @@ -1198,3 +1228,180 @@ func TestSupervisorAdmissionWriterOverloadRetainsPreparation(t *testing.T) { t.Fatal("writer overload was hidden as changed admission facts or retried externally") } } + +// schedulerQueuedCopy creates historical contention fixtures independently of +// the public one-pending-intent-per-target admission boundary. +func schedulerQueuedCopy(t *testing.T, f *attemptFixture, seed, id string) { + t.Helper() + if _, err := f.store.DB().Exec(`INSERT INTO review_operations (id,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision) SELECT ?,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,'queued',1,'','',created_at,updated_at,capability_fingerprint,policy_revision FROM review_operations WHERE id=?`, id, seed); err != nil { + t.Fatal(err) + } +} + +func TestSupervisorCancellationDuringCooldownPersistenceSettlesPreparation(t *testing.T) { + f := supervisorFixture(t) + receipt := f.enqueue(t, attemptProject, "cancel-during-cooldown", "cli", 2, 1) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var persistStarted atomic.Bool + f.e.schedulingNow = func() time.Time { + if persistStarted.Load() { + cancel() + } + return time.Now().UTC() + } + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + observed := stamp() + anchor := attemptAnchor(o.ProjectID, o.PullNumber) + anchor.ObservedAt = observed + input := CLIAllowanceObservation{Anchor: anchor, ObservedAt: observed, Remaining: 0, Limit: 5, FullCapacityInMS: 0, RollingWindowMS: 3600000, ChangedFiles: 2} + if err := f.e.RecordCLIExhaustion(context.Background(), o.ProjectID, a.ID, a.Revision, input); err != nil { + return Preparation{}, err + } + persistStarted.Store(true) + return Preparation{}, sourceHold("allowance_exhausted") + }} + if err := f.e.processNext(ctx, map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal("orderly cancellation during cooldown persistence stopped the supervisor", err) + } + var state, operationState, reason string + var revision int64 + if err := f.store.DB().QueryRow(`SELECT a.state,a.revision,o.state,o.reason FROM review_execution_attempts a JOIN review_operations o ON o.id=a.operation_id WHERE o.id=?`, receipt.ID).Scan(&state, &revision, &operationState, &reason); err != nil || state != "cancelled" || revision != 2 || operationState != "cancelled" || reason != "supervisor_stopping" || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("cancelled cooldown retained preparation or reservation", state, revision, operationState, reason, err) + } +} + +func TestSupervisorUnusableHostedCooldownHoldsOnlyItsOperation(t *testing.T) { + for _, scenario := range []string{"absent", "malformed", "oversized"} { + t.Run(scenario, func(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + receipt := f.enqueue(t, attemptProject, "unusable-hosted-cooldown", "hosted", 2, 1) + body := "{}" + if scenario == "oversized" { + body = strings.Repeat("x", 16385) + } + driver := &controlledDriver{prepare: func(ctx context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + if o.Channel != "hosted" { + return Preparation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber)}, nil + } + if scenario != "absent" { + if _, err := f.store.DB().ExecContext(ctx, `INSERT INTO review_hosted_preflight(attempt_id,project_id,body_json) VALUES(?,?,?)`, a.ID, o.ProjectID, body); err != nil { + return Preparation{}, err + } + } + return Preparation{}, sourceHold("hosted_allowance_cooldown") + }} + drivers := map[string]Driver{"test-capability": driver, "other-account": driver} + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal("unusable Hosted evidence stopped unrelated work", err) + } + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_operations WHERE id=?`, receipt.ID).Scan(&state, &reason); err != nil || state != "held" || reason != "hosted_allowance_cooldown" { + t.Fatal("cooldown refusal did not retain local hold", state, reason, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_operation_waits WHERE baseline_attempt_id IS NOT NULL`) != 0 || driver.calls.Load() != 0 { + t.Fatal("unproven cooldown retained capacity, invented timer, or dispatched") + } + if scenario != "absent" { + var retained string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_hosted_preflight`).Scan(&retained); err != nil || retained != body { + t.Fatal("local hold rewrote malformed retained evidence", err) + } + } + other := f.enqueue(t, otherAttemptProject, "healthy-after-hosted-hold", "cli", 2, 1) + if err := f.e.processNext(t.Context(), drivers); err != nil || supervisorOperationState(t, f, other.ID) != "completed" || driver.calls.Load() != 1 { + t.Fatal("another project did not continue after local hold", err) + } + }) + } +} + +func TestSupervisorHostedCooldownDatabaseFailureRemainsFatal(t *testing.T) { + f := supervisorFixture(t) + receipt := f.enqueue(t, attemptProject, "cooldown-database-failure", "hosted", 2, 1) + driver := &controlledDriver{prepare: func(ctx context.Context, _ Operation, _ Configuration, _ Attempt) (Preparation, error) { + if _, err := f.store.DB().ExecContext(ctx, `DROP TABLE review_hosted_preflight`); err != nil { + return Preparation{}, err + } + return Preparation{}, sourceHold("hosted_allowance_cooldown") + }} + err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}) + attemptCode(t, err, "review_persistence_failed") + if supervisorOperationState(t, f, receipt.ID) != "preparing" || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 || driver.calls.Load() != 0 { + t.Fatal("database failure became a hold or lost guarded preparation") + } +} + +func TestCooldownEvidenceClassificationPreservesOperationalErrors(t *testing.T) { + for _, err := range []error{errAllowanceObservationAbsent, allowanceUnavailable(), hostedAllowanceUnavailable()} { + if !cooldownEvidenceUnavailable("hosted", fmt.Errorf("wrapped: %w", err)) { + t.Fatal("unusable Hosted evidence lost its local classification", err) + } + } + for _, err := range []error{sql.ErrNoRows, context.Canceled, context.DeadlineExceeded, errors.New("database failed"), core.Fail("storage_unavailable", "Stored hosted allowance observation is unavailable.", 500)} { + if cooldownEvidenceUnavailable("hosted", err) { + t.Fatal("operational error became an evidence hold", err) + } + } + f := supervisorFixture(t) + receipt := f.enqueue(t, attemptProject, "missing-cooldown-attempt", "hosted", 2, 1) + a := f.start(t, attemptProject, receipt) + o, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, receipt.ID) + if err != nil { + t.Fatal(err) + } + a.ID = "review_attempt_" + strings.Repeat("f", 32) + _, err = f.e.persistCooldown(t.Context(), o, a) + attemptCode(t, err, "review_persistence_failed") + if supervisorOperationState(t, f, receipt.ID) != "preparing" { + t.Fatal("missing attempt changed original preparation") + } +} + +func TestCooldownReconciliationSurvivesCallerCancellation(t *testing.T) { + for _, scenario := range []string{"committed", "mismatched", "uncommitted"} { + t.Run(scenario, func(t *testing.T) { + f, a, input := cooldownObservationFixture(t) + original, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + // persistCooldown receives the queued operation from before its + // preparation transition, not the now-preparing operation revision. + original.Revision-- + original.State, original.AttemptID = "queued", "" + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + var committed Attempt + if scenario != "uncommitted" { + committed, err = f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision) + if err != nil { + t.Fatal(err) + } + } + if scenario == "mismatched" { + original.HeadSHA = strings.Repeat("f", 40) + } + tables := []string{"review_operations", "review_execution_attempts", "review_execution_transitions", "review_execution_reservations", "review_operation_waits", "review_hosted_preflight", "events", "receipts"} + before := map[string]string{} + for _, table := range tables { + before[table] = snapshotTable(t, f, table) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + // Present the real durable outcome after caller cancellation. This + // exercises reconciliation without fabricating a database commit fault. + recovered, ok := f.e.recordedCooldown(ctx, original, a) + if ok != (scenario == "committed") || ok && (recovered.ID != committed.ID || recovered.Revision != committed.Revision || recovered.State != "held") { + t.Fatal("canceled caller lost or invented exact committed cooldown", recovered, ok) + } + for _, table := range tables { + if snapshotTable(t, f, table) != before[table] { + t.Fatal("read-only reconciliation changed durable history", table) + } + } + }) + } +} diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index 372ef3f79..5afc2cb8d 100644 --- a/internal/reviewexec/types.go +++ b/internal/reviewexec/types.go @@ -64,7 +64,21 @@ type Anchor struct { ObservedAt string `json:"observed_at"` } +type AllowanceObservation struct { + Kind string `json:"kind"` + ObservedAt string `json:"observed_at"` + Remaining *int64 `json:"remaining,omitempty"` + Limit *int64 `json:"limit,omitempty"` + FullCapacityInMS *int64 `json:"full_capacity_in_ms,omitempty"` + RollingWindowMS *int64 `json:"rolling_window_ms,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` +} + type Operation struct { + Wait *OperationWait `json:"wait,omitempty"` + Allowance *AllowanceObservation `json:"allowance,omitempty"` + AllowOutOfOrder bool `json:"allow_out_of_order,omitempty"` + OverrideFileLimit bool `json:"override_file_limit,omitempty"` Observer *HostedObserverStatus `json:"observer,omitempty"` ID string `json:"id"` ProjectID string `json:"project_id"` @@ -99,6 +113,12 @@ type Attempt struct { type Engine struct { runSourceBudget time.Duration + schedulingNow func() time.Time + configurationFailureMu sync.Mutex + configurationFailureNext map[string]time.Time + draftProbeMu sync.Mutex + draftProbeNext map[string]time.Time + draftProbeCursor string runWake chan struct{} runRunning atomic.Bool hostedObserverMu sync.Mutex @@ -226,3 +246,9 @@ func actorAllowed(ctx context.Context, tx *sql.Tx, project, actor, worker string err := tx.QueryRowContext(ctx, `SELECT count(*) FROM credentials c WHERE c.principal_id=? AND c.revoked=0 AND (c.is_admin=1 OR EXISTS(SELECT 1 FROM grants g WHERE g.credential_id=c.id AND g.project_id=? AND g.can_write=1)) AND (?='' OR EXISTS(SELECT 1 FROM workers w WHERE w.project_id=? AND w.id=?))`, actor, project, worker, project, worker).Scan(&n) return n == 1, err } + +// WithExecutionClock supplies the clock for review scheduling. A nil clock +// restores the default time.Now behavior. It does not alter persisted event times. +func WithExecutionClock(now func() time.Time) EngineOption { + return func(e *Engine) { e.schedulingNow = now } +} diff --git a/internal/reviewexec/wait_deadline.go b/internal/reviewexec/wait_deadline.go new file mode 100644 index 000000000..0cdb19b4c --- /dev/null +++ b/internal/reviewexec/wait_deadline.go @@ -0,0 +1,79 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// The baseline pins the first comparison, not the latest scheduling deadline. +// Select one detached cooldown in the caller's snapshot; other unused holds and +// a current preparation do not replace the retained timer's source. +func latestCooldownAttempt(ctx context.Context, q EvidenceQuery, o Operation) (Attempt, error) { + reason := "hosted_allowance_cooldown" + join := "" + order := "rtrim(t.created_at,'Z') DESC,a.id DESC" + if o.Channel == "cli" { + reason = "allowance_exhausted" + } else { + // Recording timestamps may tie after clock rollback. Hosted retries + // advance the provider deadline even then; random attempt IDs cannot + // establish their order. Read only a bounded scalar for tie selection, + // and validate the winning record below. Unreadable tied proof wins + // selection so it is refused rather than hidden by an older deadline. + join = " LEFT JOIN review_hosted_preflight p ON p.attempt_id=a.id " + deadline := `CASE WHEN typeof(p.body_json)='text' AND length(CAST(p.body_json AS BLOB))<=16384 THEN + CASE WHEN json_valid(p.body_json) THEN + CASE WHEN json_type(p.body_json,'$.input.observation.RetryNotBefore')='text' + THEN json_extract(p.body_json,'$.input.observation.RetryNotBefore') END + END END` + order = "rtrim(t.created_at,'Z') DESC,(" + deadline + ") IS NULL DESC,rtrim(" + deadline + ",'Z') DESC,a.id DESC" + } + var id string + err := q.QueryRowContext(ctx, `SELECT a.id FROM review_execution_attempts a + JOIN review_execution_transitions t ON t.attempt_id=a.id AND t.revision=a.revision `+join+` + WHERE a.operation_id=? AND a.id<>? AND t.state='held' AND t.reason=? + ORDER BY `+order+` LIMIT 1`, o.ID, o.AttemptID, reason).Scan(&id) + if err != nil { + return Attempt{}, waitDependencyError(err) + } + a, err := readAttempt(ctx, q, o.ProjectID, id) + return a, waitDependencyError(err) +} + +func retainedCooldownDeadline(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (time.Time, error) { + original, err := historicalCooldownOperation(ctx, q, o, a) + if err != nil { + return time.Time{}, waitDependencyError(err) + } + if o.Channel == "cli" { + record, err := readCLIAllowanceRecord(ctx, q, original, a) + if err != nil { + return time.Time{}, waitDependencyError(err) + } + if record.Observation.Remaining != 0 { + return time.Time{}, waitUnavailable() + } + return cliExhaustionDeadline(ctx, q, a) + } + record, err := readHostedAllowanceRecord(ctx, q, original, a) + if err != nil { + return time.Time{}, waitDependencyError(err) + } + if record.Input.Observation.State != "cooldown_observed" { + return time.Time{}, waitUnavailable() + } + var at string + if err := q.QueryRowContext(ctx, `SELECT created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&at); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return time.Time{}, waitUnavailable() + } + return time.Time{}, err + } + ended, valid := attemptRecordedTime(at) + if !valid || !record.Input.Observation.RetryNotBefore.After(ended) { + return time.Time{}, waitUnavailable() + } + return record.Input.Observation.RetryNotBefore, nil +} diff --git a/internal/reviewexec/wait_deadline_runtime_test.go b/internal/reviewexec/wait_deadline_runtime_test.go new file mode 100644 index 000000000..5074e18bb --- /dev/null +++ b/internal/reviewexec/wait_deadline_runtime_test.go @@ -0,0 +1,235 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "strings" + "testing" + "time" +) + +func deadlineRuntimeFixture(t *testing.T, channel string) (*attemptFixture, Attempt, *time.Time) { + t.Helper() + if channel == "cli" { + f, a, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + return f, a, now + } + f, a, _, now := queuedCooldown(t) + return f, a, now +} + +func deadlineRuntimeState(t *testing.T, f *attemptFixture) string { + t.Helper() + var result strings.Builder + for _, table := range []string{"review_operations", "review_execution_attempts", "review_execution_transitions", "review_operation_waits", "review_cli_preflight", "review_hosted_preflight", "review_execution_reservations", "events", "receipts"} { + result.WriteString(snapshotTable(t, f, table)) + } + return result.String() +} + +func TestWaitRuntimeRejectsCanonicalDeadlineMismatch(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, change := range []string{"shortened", "extended"} { + t.Run(channel+"/"+change, func(t *testing.T) { + f, a, now := deadlineRuntimeFixture(t, channel) + o := cliWaitRead(t, f, a.OperationID) + due := cliWaitDue(t, o) + forged := due.Add(-30 * time.Second) + if change == "extended" { + forged = due.Add(30 * time.Second) + } + admissionSQL(t, f, `UPDATE review_operation_waits SET retry_not_before=? WHERE operation_id=?`, forged.Format(time.RFC3339Nano), o.ID) + *now = due.Add(-15 * time.Second) + before := deadlineRuntimeState(t, f) + if wait, err := readOperationWait(t.Context(), f.store.DB(), o); wait != nil || !isWaitUnavailable(err) { + t.Error("canonical but contradictory deadline was accepted", wait, err) + } + if attempt, err := f.e.StartAttempt(t.Context(), attemptProject, o.ID); attempt.ID != "" || !isWaitUnavailable(err) { + t.Error("direct admission trusted a contradictory timer", attempt, err) + } + if pending, err := f.e.pending(t.Context()); err != nil || len(pending) != 0 { + t.Error("selection admitted a contradictory timer", pending, err) + } + if before != deadlineRuntimeState(t, f) { + t.Fatal("failed runtime proof mutated retained state") + } + }) + } + } +} + +func TestWaitRuntimeBindsLatestCooldown(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + damages := []string{"old-deadline", "latest-proof"} + if channel == "hosted" { + damages = append(damages, "equal-ended-old-deadline", "equal-ended-latest-proof") + } + for _, damage := range damages { + t.Run(channel+"/"+damage, func(t *testing.T) { + f, first, now := deadlineRuntimeFixture(t, channel) + baseline := cliWaitRead(t, f, first.OperationID) + firstDue := cliWaitDue(t, baseline) + var firstEnded string + if strings.HasPrefix(damage, "equal-ended") { + if err := f.store.DB().QueryRow(`SELECT created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, first.ID).Scan(&firstEnded); err != nil { + t.Fatal(err) + } + f.e.attemptNow = func() time.Time { return mustWaitTime(firstEnded) } + } + *now = firstDue + next := f.start(t, attemptProject, Receipt{ID: first.OperationID}) + // Projection reads the operation in the same transaction before + // the newly held preparation is detached from it. + f.e.publishAttempt = func(ctx context.Context, tx *sql.Tx, a Attempt) error { + _, err := readOperationBase(ctx, tx, a.ProjectID, a.OperationID) + return err + } + var due time.Time + if channel == "cli" { + in := CLIAllowanceObservation{Anchor: attemptAnchor(attemptProject, 2), ObservedAt: stamp(), Remaining: 0, Limit: 7, FullCapacityInMS: 3600000, RollingWindowMS: 86400000, ChangedFiles: 2} + if err := f.e.RecordCLIExhaustion(t.Context(), attemptProject, next.ID, next.Revision, in); err != nil { + t.Fatal(err) + } + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, next.ID, next.Revision); err != nil { + t.Fatal("second cooldown with in-transaction projection", err) + } + due = firstDue.Add(2 * time.Minute) + } else { + in := retainTimerCooldown(t, f, next, 6*time.Minute) + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, next.ID, next.Revision); err != nil { + t.Fatal("second cooldown with in-transaction projection", err) + } + due = in.Observation.RetryNotBefore + } + o := cliWaitRead(t, f, first.OperationID) + if o.Wait.BaselineAttemptID != first.ID || !cliWaitDue(t, o).Equal(due) || !due.After(firstDue) { + t.Fatal("latest timer replaced first comparison or retained old deadline", o.Wait, firstDue, due) + } + if channel == "cli" && (o.Wait.CLIAllowance == nil || *o.Wait.CLIAllowance.Limit != *baseline.Wait.CLIAllowance.Limit) { + t.Fatal("latest scheduling proof replaced the first allowance estimate") + } + if firstEnded != "" { + var latestEnded string + if err := f.store.DB().QueryRow(`SELECT created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, next.ID).Scan(&latestEnded); err != nil || latestEnded != firstEnded { + t.Fatal("fixture did not retain equal cooldown transition times", firstEnded, latestEnded, err) + } + } + if strings.HasSuffix(damage, "old-deadline") { + admissionSQL(t, f, `UPDATE review_operation_waits SET retry_not_before=? WHERE operation_id=?`, firstDue.Format(time.RFC3339Nano), o.ID) + } else { + admissionSQL(t, f, `UPDATE review_`+channel+`_preflight SET body_json='{}' WHERE attempt_id=?`, next.ID) + } + before := deadlineRuntimeState(t, f) + if wait, err := readOperationWait(t.Context(), f.store.DB(), o); wait != nil || !isWaitUnavailable(err) { + t.Error("first baseline concealed an unproven latest cooldown", wait, err) + } + if before != deadlineRuntimeState(t, f) { + t.Fatal("latest cooldown validation changed retained state") + } + }) + } + } +} + +func TestCLIAccountDeadlineCannotHideShortenedCooldown(t *testing.T) { + for _, scenario := range []struct { + name string + otherAccount bool + expired bool + extended bool + }{ + {name: "same-live"}, + {name: "other-live", otherAccount: true}, + {name: "same-expired", expired: true}, + {name: "other-expired", otherAccount: true, expired: true}, + {name: "extended-after-real-expiry", expired: true, extended: true}, + {name: "other-extended-after-real-expiry", otherAccount: true, expired: true, extended: true}, + } { + t.Run(scenario.name, func(t *testing.T) { + f, a, now := deadlineRuntimeFixture(t, "cli") + due := cliWaitDue(t, cliWaitRead(t, f, a.OperationID)) + capability := "test-capability" + if scenario.otherAccount { + capability = "other-account" + } + f.configure(t, otherAttemptProject, capability, 0, false) + other := f.enqueue(t, otherAttemptProject, "shortened-account-timer", "cli", 2, 1) + hosted := f.enqueue(t, otherAttemptProject, "independent-hosted-timer", "hosted", 4, 1) + timerControl(t, f, a.OperationID, "cancel", "cancel-shortened-donor") + forged := due.Add(-30 * time.Second) + if scenario.extended { + forged = due.Add(30 * time.Second) + } + admissionSQL(t, f, `UPDATE review_operation_waits SET retry_not_before=? WHERE operation_id=?`, forged.Format(time.RFC3339Nano), a.OperationID) + *now = due.Add(-15 * time.Second) + if scenario.expired { + *now = due + if !scenario.extended { + admissionSQL(t, f, `UPDATE review_cli_preflight SET body_json='{}' WHERE attempt_id=?`, a.ID) + } + } + before := deadlineRuntimeState(t, f) + blocked := !scenario.otherAccount && (!scenario.expired || scenario.extended) + deadline, err := cliAccountRetryDeadline(t.Context(), f.store.DB(), f.e.capabilities[capability], *now) + if blocked { + if !deadline.IsZero() || !isWaitUnavailable(err) { + t.Error("shortened cache hid a live account exhaustion", deadline, err) + } + } else if !deadline.IsZero() || err != nil { + t.Error("unrelated or expired corruption became a live account hold", deadline, err) + } + pending, err := f.e.pending(t.Context()) + if err != nil { + t.Fatal("account damage stopped unrelated scheduling", err) + } + got := map[string]bool{} + for _, operation := range pending { + got[operation.ID] = true + } + want := 2 + if blocked { + want = 1 + } + if !got[hosted.ID] || got[other.ID] == blocked || len(got) != want { + t.Error("account deadline lost scheduling isolation", got) + } + if before != deadlineRuntimeState(t, f) { + t.Fatal("account lookup changed retained state") + } + attempt, err := f.e.StartAttempt(t.Context(), otherAttemptProject, other.ID) + if blocked { + if attempt.ID != "" || !isWaitUnavailable(err) { + t.Error("direct cross-project admission bypassed retained floor", attempt, err) + } + } else if attempt.ID == "" || err != nil { + t.Error("unrelated or truly expired timer blocked admission", attempt, err) + } + }) + } +} + +func TestWaitDeadlineRuntimePreservesLookupErrors(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + f, a, _ := deadlineRuntimeFixture(t, channel) + o := cliWaitRead(t, f, a.OperationID) + before := deadlineRuntimeState(t, f) + for _, match := range []string{"SELECT a.id FROM review_execution_attempts a", "SELECT created_at FROM review_execution_transitions"} { + for _, canceled := range []bool{false, true} { + q := cliRetryFailureQuery{EvidenceQuery: f.store.DB(), match: match, cancel: canceled} + wait, err := readOperationWait(t.Context(), q, o) + if wait != nil || err == nil || isWaitUnavailable(err) || canceled && !errors.Is(err, context.Canceled) || !canceled && !strings.Contains(err.Error(), "missing_cli_retry_history") { + t.Error("latest deadline proof concealed an operational lookup failure", match, canceled, wait, err) + } + } + } + if before != deadlineRuntimeState(t, f) { + t.Fatal("failed proof lookup changed retained state") + } + }) + } +} diff --git a/internal/reviewexec/workspace_retention.go b/internal/reviewexec/workspace_retention.go new file mode 100644 index 000000000..8e92e20cd --- /dev/null +++ b/internal/reviewexec/workspace_retention.go @@ -0,0 +1,45 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// WorkspaceDisposable is an internal runtime read, not an agent permission. +// Terminal attempts cannot be restarted. Their immutable captures/evidence and +// journal remain retained separately; an account reservation always wins. +func (e *Engine) WorkspaceDisposable(ctx context.Context, capabilityID, attemptID string, now time.Time) (bool, error) { + if e == nil || ctx == nil || !identifier.MatchString(attemptID) { + return false, invalid() + } + capability, ok := e.capabilities[capabilityID] + if !ok { + return false, conflict() + } + var stamp string + err := e.store.DB().QueryRowContext(ctx, `SELECT t.created_at + FROM review_execution_attempts a + JOIN review_operations o ON o.id=a.operation_id AND o.project_id=a.project_id + JOIN review_execution_config c ON c.project_id=o.project_id AND c.revision=o.configuration_revision + JOIN review_execution_transitions t ON t.attempt_id=a.id AND t.revision=a.revision AND t.state=a.state + WHERE a.id=? AND a.provider=? AND a.account=? AND o.channel IN ('cli','hosted') + AND a.state IN ('completed','held','failed','cancelled','rate_limited') + AND ((o.attempt_id=a.id AND o.state=a.state) + OR (((o.channel='hosted' AND t.reason='hosted_allowance_cooldown') OR (o.channel='cli' AND t.reason='allowance_exhausted')) AND a.state='held' AND a.anchor_json='null' AND a.intent='' AND a.external_id='' + AND EXISTS(SELECT 1 FROM review_operation_waits w WHERE w.operation_id=o.id AND w.baseline_attempt_id IS NOT NULL))) + AND NOT EXISTS(SELECT 1 FROM review_execution_reservations r WHERE r.attempt_id=a.id) + AND json_valid(c.body_json) AND json_extract(c.body_json,'$.capability_id')=?`, attemptID, capability.Provider, capability.Account, capabilityID).Scan(&stamp) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + at, err := time.Parse(time.RFC3339Nano, stamp) + if err != nil { + return false, persistenceFailure() + } + return !at.After(now.Add(-5 * time.Minute)), nil +} diff --git a/internal/reviewexec/workspace_retention_test.go b/internal/reviewexec/workspace_retention_test.go new file mode 100644 index 000000000..0c1503c8c --- /dev/null +++ b/internal/reviewexec/workspace_retention_test.go @@ -0,0 +1,93 @@ +package reviewexec + +import ( + "testing" + "time" +) + +func TestWorkspaceRetentionProtectsLiveUncertainReservedAndRecentAttempts(t *testing.T) { + for _, state := range []string{"preparing", "posting", "active", "uncertain", "completed", "held", "failed", "cancelled", "rate_limited"} { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel+"/"+state, func(t *testing.T) { + f, a, _ := evidenceFixture(t, channel, true) + // Exercise persisted eligibility independently of transition mechanics. + for _, query := range []string{`UPDATE review_execution_attempts SET state=? WHERE id=?`, `UPDATE review_operations SET state=? WHERE attempt_id=?`, `UPDATE review_execution_transitions SET state=? WHERE attempt_id=? AND revision=2`} { + if _, err := f.store.DB().Exec(query, state, a.ID); err != nil { + t.Fatal(err) + } + } + now := time.Now().Add(10 * time.Minute) + allowed, err := f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, now) + if err != nil || allowed { + t.Fatal("reservation must protect every state", allowed, err) + } + if _, err = f.store.DB().Exec(`DELETE FROM review_execution_reservations WHERE attempt_id=?`, a.ID); err != nil { + t.Fatal(err) + } + allowed, err = f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, time.Now()) + if err != nil || allowed { + t.Fatal("recent attempt prematurely disposable", allowed, err) + } + terminal := state == "completed" || state == "held" || state == "failed" || state == "cancelled" || state == "rate_limited" + allowed, err = f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, now) + if err != nil || allowed != terminal { + t.Fatal(state, allowed, err) + } + allowed, err = f.e.WorkspaceDisposable(t.Context(), "other-account", a.ID, now) + if err != nil || allowed { + t.Fatal("cross-capability cleanup", allowed, err) + } + }) + } + } +} + +func TestWorkspaceRetentionReportsCorruptTransitionTime(t *testing.T) { + f, a, _ := evidenceFixture(t, "cli", true) + for _, query := range []string{ + `UPDATE review_execution_attempts SET state='completed' WHERE id=?`, + `UPDATE review_operations SET state='completed' WHERE attempt_id=?`, + `UPDATE review_execution_transitions SET state='completed',created_at='private-corrupt-time' WHERE attempt_id=? AND revision=2`, + `DELETE FROM review_execution_reservations WHERE attempt_id=?`, + } { + if _, err := f.store.DB().Exec(query, a.ID); err != nil { + t.Fatal(err) + } + } + allowed, err := f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, time.Now().Add(time.Hour)) + attemptCode(t, err, "review_persistence_failed") + if allowed || err.Error() != persistenceFailure().Error() { + t.Fatal("corruption lost safe storage error", allowed, err) + } +} + +func TestWorkspaceRetentionProtectsDetachedCooldownIntentAndReservation(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, protection := range []string{"intent", "reservation"} { + t.Run(channel+"/"+protection, func(t *testing.T) { + f, a := interruptedAllowanceFixture(t, channel) + var err error + if channel == "cli" { + _, err = f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision) + } else { + _, err = f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision) + } + if err != nil { + t.Fatal(err) + } + later := time.Now().Add(time.Hour) + if allowed, err := f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, later); err != nil || !allowed { + t.Fatal("baseline detached cooldown is not disposable", allowed, err) + } + if protection == "intent" { + admissionSQL(t, f, `UPDATE review_execution_attempts SET intent='retained-dispatch-intent' WHERE id=?`, a.ID) + } else { + admissionSQL(t, f, `INSERT INTO review_execution_reservations(provider,repository_id,pull_number,action_class,account,attempt_id) SELECT a.provider,p.github_repository_id,o.pull_number,o.channel,a.account,a.id FROM review_execution_attempts a JOIN review_operations o ON o.id=a.operation_id JOIN projects p ON p.id=a.project_id WHERE a.id=?`, a.ID) + } + if allowed, err := f.e.WorkspaceDisposable(t.Context(), "test-capability", a.ID, later); err != nil || allowed { + t.Fatal("detached workspace protection ignored", allowed, err) + } + }) + } + } +} diff --git a/internal/reviewprocess/process.go b/internal/reviewprocess/process.go index 531d6deb0..73e81781d 100644 --- a/internal/reviewprocess/process.go +++ b/internal/reviewprocess/process.go @@ -153,15 +153,15 @@ func (r *Runner) Usage(ctx context.Context, workspace reviewworkspace.Workspace, if err != nil { return Usage{}, err } - if usage.Remaining == 0 { - return Usage{}, processError("rate_limited", false) - } if err := r.manager.Verify(ctx, workspace); err != nil { if ctx.Err() != nil { return Usage{}, processError("usage_unavailable", false) } return Usage{}, processError("source_changed", false) } + if usage.Remaining == 0 { + return usage, processError("rate_limited", false) + } r.mu.Lock() if generation != r.usageGeneration || ctx.Err() != nil { r.mu.Unlock() diff --git a/internal/reviewprocess/process_test.go b/internal/reviewprocess/process_test.go index dbcfed836..66dda5d80 100644 --- a/internal/reviewprocess/process_test.go +++ b/internal/reviewprocess/process_test.go @@ -299,8 +299,9 @@ func TestUnsafeBillingRefreshClearsPermitWithoutReview(t *testing.T) { func TestZeroIncludedUsageIsExplicitRateLimited(t *testing.T) { f := newProcessFixture(t) r := f.runner(t, fmt.Sprintf(`printf '%%s' %q`, usageJSON("owner/repo", "owner", 0, 5, 0, 1))) - if _, err := r.Usage(context.Background(), f.workspace, "owner/repo", "owner"); !errorCode(err, "rate_limited") { - t.Fatalf("zero allowance result: %v", err) + usage, err := r.Usage(context.Background(), f.workspace, "owner/repo", "owner") + if !errorCode(err, "rate_limited") || usage.Remaining != 0 || usage.Limit != 5 || usage.RollingWindowMS != 1 { + t.Fatalf("zero allowance lost validated facts: %+v %v", usage, err) } if _, err := r.Review(context.Background(), f.workspace); !errorCode(err, "permit_required") { t.Fatalf("zero allowance authorized review: %v", err) @@ -696,3 +697,15 @@ func TestOwnedProcessConfigurationRejectsUnsupportedAndStartFailureIsSafe(t *tes t.Fatal("preexisting process accepted as a new owned group", err) } } + +func TestZeroUsageRejectsWorkspaceChangedByCommand(t *testing.T) { + f := newProcessFixture(t) + r := f.runner(t, fmt.Sprintf(`printf changed > source.txt; printf '%%s' %q`, usageJSON("owner/repo", "owner", 0, 5, 0, 1))) + usage, err := r.Usage(context.Background(), f.workspace, "owner/repo", "owner") + if !errorCode(err, "source_changed") || usage != (Usage{}) { + t.Fatalf("changed workspace retained exhaustion: %+v %v", usage, err) + } + if capture, err := r.Review(context.Background(), f.workspace); !errorCode(err, "source_changed") || capture.Started { + t.Fatalf("changed workspace authorized review: %v", err) + } +} diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index c12f714aa..444918b2f 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -124,10 +124,28 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, return preparation, err } anchor := reviewexec.Anchor{RepositoryID: current.RepositoryID, Repository: plan.Repository.FullName, PullNumber: plan.Pull.Number, CandidateSHA: plan.Pull.HeadSHA, BaseSHA: plan.Pull.BaseSHA, ParentSHA: plan.ParentSHA, ParentPullNumber: plan.ParentPullNumber, BaseRef: plan.Pull.BaseRef, MergeBaseSHA: workspace.MergeBaseSHA, PatchSHA256: workspace.PatchSHA256, ObservedAt: plan.ObservedAt} + baseline, err := d.engine.RetryBaseline(ctx, operation.ProjectID, operation.ID) + if err != nil { + return preparation, err + } + if baseline != nil && !sameHostedRetryComparison(*baseline, anchor) { + return preparation, reviewHold("source_changed") + } usage, err := d.usage(ctx, workspace, plan.Repository.FullName, d.capability.Organization) if err != nil { var failure *reviewprocess.Error if errors.As(err, &failure) && failure.Code == "rate_limited" { + if usage.Remaining != 0 { + return preparation, reviewHold("allowance_unavailable") + } + // A negative observation never grants dispatch permission. + if err := d.engine.RecordCLIExhaustion(ctx, operation.ProjectID, attempt.ID, attempt.Revision, reviewexec.CLIAllowanceObservation{Anchor: anchor, ObservedAt: time.Now().UTC().Format(time.RFC3339Nano), Remaining: usage.Remaining, Limit: usage.Limit, FullCapacityInMS: usage.FullCapacityInMS, RollingWindowMS: usage.RollingWindowMS, ChangedFiles: changedFiles}); err != nil { + var held *core.Error + if errors.As(err, &held) && held.Code == "review_held" { + return preparation, err + } + return preparation, reviewHold("allowance_unavailable") + } return preparation, reviewHold("allowance_exhausted") } return preparation, reviewHold("allowance_unavailable") diff --git a/internal/reviewruntime/cli_preparation_reason_test.go b/internal/reviewruntime/cli_preparation_reason_test.go index a705208ab..e45a10ebc 100644 --- a/internal/reviewruntime/cli_preparation_reason_test.go +++ b/internal/reviewruntime/cli_preparation_reason_test.go @@ -20,25 +20,43 @@ import ( func TestCLIDriverUsageFailureBecomesSafePreparationHold(t *testing.T) { for _, tc := range []struct { - name string - failure error - want string + name string + failure error + usage reviewprocess.Usage + failRetention bool + want string }{ - {"rate", &reviewprocess.Error{Code: "rate_limited"}, "allowance_exhausted"}, - {"wrapped rate", fmt.Errorf("private path or token: %w", &reviewprocess.Error{Code: "rate_limited"}), "allowance_exhausted"}, - {"usage", &reviewprocess.Error{Code: "usage_unavailable"}, "allowance_unavailable"}, - {"wrapped usage", fmt.Errorf("private path: %w", &reviewprocess.Error{Code: "usage_unavailable"}), "allowance_unavailable"}, - {"raw text", errors.New("rate_limited private token diagnostic"), "allowance_unavailable"}, - {"foreign typed code", core.Fail("rate_limited", "private diagnostic", 409), "allowance_unavailable"}, + {"rate", &reviewprocess.Error{Code: "rate_limited"}, reviewprocess.Usage{}, false, "allowance_unavailable"}, + {"wrapped rate", fmt.Errorf("private path or token: %w", &reviewprocess.Error{Code: "rate_limited"}), reviewprocess.Usage{}, false, "allowance_unavailable"}, + {"usage", &reviewprocess.Error{Code: "usage_unavailable"}, reviewprocess.Usage{}, false, "allowance_unavailable"}, + {"wrapped usage", fmt.Errorf("private path: %w", &reviewprocess.Error{Code: "usage_unavailable"}), reviewprocess.Usage{}, false, "allowance_unavailable"}, + {"raw text", errors.New("rate_limited private token diagnostic"), reviewprocess.Usage{}, false, "allowance_unavailable"}, + {"foreign typed code", core.Fail("rate_limited", "private diagnostic", 409), reviewprocess.Usage{}, false, "allowance_unavailable"}, + {"rate with nonzero remaining", &reviewprocess.Error{Code: "rate_limited"}, reviewprocess.Usage{Remaining: 1, Limit: 3, RollingWindowMS: 60000}, false, "allowance_unavailable"}, + {"exhaustion file limit", &reviewprocess.Error{Code: "rate_limited"}, reviewprocess.Usage{Limit: 3, RollingWindowMS: 60000}, false, "project_file_limit"}, + {"exhaustion validation fails", &reviewprocess.Error{Code: "rate_limited"}, reviewprocess.Usage{Limit: -1, RollingWindowMS: 60000}, false, "allowance_unavailable"}, + {"exhaustion retention fails", &reviewprocess.Error{Code: "rate_limited"}, reviewprocess.Usage{Limit: 3, RollingWindowMS: 60000}, true, "allowance_unavailable"}, } { t.Run(tc.name, func(t *testing.T) { f := newCLIDriverFixture(t) var usage atomic.Int64 f.driver.usage = func(context.Context, reviewworkspace.Workspace, string, string) (reviewprocess.Usage, error) { usage.Add(1) - return reviewprocess.Usage{}, tc.failure + if tc.name == "exhaustion file limit" { + // Force the retained-policy guard after the workspace's earlier + // ceiling check, isolating RecordCLIExhaustion's typed refusal. + if _, err := f.store.DB().Exec(`UPDATE review_policy_config SET body_json=json_set(body_json,'$.max_review_files',1)`); err != nil { + t.Fatal(err) + } + } + return tc.usage, tc.failure } op, a, c := f.start(t, 2, 1, "prepare-usage-refusal") + if tc.failRetention { + if _, err := f.store.DB().Exec(`CREATE TRIGGER reject_cli_exhaustion BEFORE INSERT ON review_cli_preflight BEGIN SELECT RAISE(ABORT,'private-exhaustion-storage-failure'); END`); err != nil { + t.Fatal(err) + } + } prepared, err := f.driver.Prepare(t.Context(), op, c, a) var failure *core.Error if !errors.As(err, &failure) || failure.Code != "review_held" { @@ -126,7 +144,7 @@ func TestCLIDriverRealUsageHoldSettlesSupervisorWithoutReview(t *testing.T) { if err != nil { t.Fatal(err) } - if operation.State == "held" { + if operation.State == "held" || mode == "exhausted" && operation.State == "queued" && operation.Wait != nil && operation.Wait.BaselineAttemptID != "" && operation.Wait.RetryNotBefore != "" { break } select { @@ -136,10 +154,18 @@ func TestCLIDriverRealUsageHoldSettlesSupervisorWithoutReview(t *testing.T) { } } stop() + expectedPreflight := 0 + if mode == "exhausted" { + expectedPreflight = 1 + if operation.State != "queued" || operation.Wait == nil || operation.Wait.RetryNotBefore == "" { + t.Fatal("real runner exhaustion did not retain queued wait", operation) + } + expected = "" + } if operation.Reason != expected || reviews.Load() != 0 || strings.Contains(operation.Reason, "private") { t.Fatal("safe hold reason missing or review dispatched", operation, reviews.Load()) } - if cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_cli_preflight`) != 0 { + if cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_cli_preflight`) != expectedPreflight { t.Fatal("preparation hold retained permission/reservation/evidence") } log, err := os.ReadFile(f.log) diff --git a/internal/reviewruntime/cli_quota_retry_test.go b/internal/reviewruntime/cli_quota_retry_test.go new file mode 100644 index 000000000..ecdd80a2e --- /dev/null +++ b/internal/reviewruntime/cli_quota_retry_test.go @@ -0,0 +1,116 @@ +package reviewruntime + +import ( + "context" + "errors" + "os/exec" + "strings" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviewprocess" + "github.com/benhook1013/FireController/internal/reviewworkspace" +) + +func TestCLIQuotaRetryRequalifiesOriginalComparisonBeforeAnotherUsageCheck(t *testing.T) { + for _, changed := range []bool{false, true} { + name := "unchanged" + if changed { + name = "moved-base" + } + t.Run(name, func(t *testing.T) { + f := newCLIDriverFixture(t) + now := time.Now().UTC() + var err error + f.engine, err = reviewexec.New(f.store, []reviewexec.Capability{{ID: f.capability.ID, Provider: "coderabbit", Account: f.capability.Account, Channels: f.capability.Channels, Fingerprint: f.capability.Fingerprint}}, reviewexec.WithNativeProjection(), reviewexec.WithExecutionClock(func() time.Time { return now })) + if err != nil { + t.Fatal(err) + } + f.driver.engine = f.engine + calls := 0 + usage := f.driver.usage + f.driver.usage = func(ctx context.Context, workspace reviewworkspace.Workspace, repo, org string) (reviewprocess.Usage, error) { + calls++ + if calls == 1 { + return reviewprocess.Usage{Limit: 3, RollingWindowMS: 3600000}, &reviewprocess.Error{Code: "rate_limited"} + } + return usage(ctx, workspace, repo, org) + } + op, a, c := f.start(t, 2, 1, "quota-pinned-request") + _, err = f.driver.Prepare(t.Context(), op, c, a) + var failure *core.Error + if !errors.As(err, &failure) || failure.Code != "review_held" { + t.Fatal("first quota observation", err) + } + if _, err = f.engine.ScheduleCLICooldown(t.Context(), f.project, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + queued, err := f.engine.ReadOperation(t.Context(), f.scope(t, f.writer, false), op.ID) + if err != nil || queued.Wait == nil { + t.Fatal("retained request", queued, err) + } + now, err = time.Parse(time.RFC3339Nano, queued.Wait.RetryNotBefore) + if err != nil { + t.Fatal(err) + } + if changed { + cache, err := f.manager.CachePath(901) + if err != nil { + t.Fatal(err) + } + gitOutput := func(args ...string) string { + cmd := exec.Command("git", args...) + cmd.Dir = cache + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("fixture git: %s: %v", out, err) + } + return strings.TrimSpace(string(out)) + } + tree := gitOutput("rev-parse", f.baseSHA+"^{tree}") + next := gitOutput("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit-tree", tree, "-p", f.baseSHA, "-m", "Advance base without changing the reviewed patch") + p := f.reader.pulls[2] + p.BaseSHA = next + f.reader.pulls[2] = p + } + next, err := f.engine.StartAttempt(t.Context(), f.project, op.ID) + if err != nil || next.ID == "" { + t.Fatal("retry claim", next, err) + } + current, err := f.engine.ExecutionContext(t.Context(), f.project, op.ID) + if err != nil { + t.Fatal(err) + } + prepared, err := f.driver.Prepare(t.Context(), current.Operation, current.Configuration, next) + if changed { + if !errors.As(err, &failure) || failure.Code != "review_held" { + t.Fatal("changed comparison was allowed", err) + } + reason, _ := failure.Details.(map[string]string) + if reason["reason"] != "source_changed" || calls != 1 { + t.Fatal("moved base reached quota query", reason, calls) + } + return + } + if err != nil || calls != 2 { + t.Fatal("unchanged request failed requalification", err, calls) + } + admitted, err := f.engine.Admit(t.Context(), f.project, next.ID, next.Revision, prepared.Anchor, prepared.Intent) + if err != nil { + t.Fatal(err) + } + result, err := f.driver.Dispatch(t.Context(), current.Operation, admitted, nil) + if err != nil || result.State != "completed" { + t.Fatal("original request did not execute once", result, err) + } + if _, err = f.engine.Advance(t.Context(), f.project, admitted.ID, admitted.Revision, result.State, result.Reason, ""); err != nil { + t.Fatal(err) + } + if err := reviewexec.ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 10); err != nil { + t.Fatal("completed retry damaged original quota evidence", err) + } + }) + } +} diff --git a/internal/reviewruntime/draft_admission_test.go b/internal/reviewruntime/draft_admission_test.go new file mode 100644 index 000000000..be1df4126 --- /dev/null +++ b/internal/reviewruntime/draft_admission_test.go @@ -0,0 +1,182 @@ +package reviewruntime + +import ( + "context" + "encoding/json" + "os" + "strings" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewexec" +) + +func setRuntimeDraft(f *cliDriverFixture, draft bool) { + pull := f.reader.pulls[2] + pull.IsDraft = &draft + f.reader.pulls[2] = pull +} + +func waitRuntimeDraftState(t *testing.T, f *cliDriverFixture, driver reviewexec.Driver, id, channel string) reviewexec.Operation { + t.Helper() + ctx, cancel := context.WithCancel(t.Context()) + done, err := f.engine.Start(ctx, map[string]reviewexec.Driver{f.capability.ID: driver}) + if err != nil { + cancel() + t.Fatal(err) + } + var operation reviewexec.Operation + var terminal bool + var readErr error + if channel == "cli" { + deadline := time.NewTimer(5 * time.Second) + ticker := time.NewTicker(20 * time.Millisecond) + defer deadline.Stop() + defer ticker.Stop() + probe: + for { + operation, readErr = f.engine.ReadOperation(t.Context(), f.scope(t, f.writer, false), id) + if readErr != nil || operation.Reason == "cli_draft_wait" { + break + } + select { + case <-deadline.C: + readErr = context.DeadlineExceeded + break probe + case <-t.Context().Done(): + readErr = t.Context().Err() + break probe + case <-ticker.C: + } + } + } else { + operation, terminal, readErr = f.engine.WaitOperation(t.Context(), f.scope(t, f.writer, false), id, 3) + } + cancel() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("draft hold did not stop cleanly") + } + if readErr != nil { + t.Fatal(readErr) + } + if channel == "cli" { + if terminal || operation.State != "queued" || operation.Reason != "cli_draft_wait" || operation.AttemptID != "" { + t.Fatal("explicit CLI request did not wait for Draft readiness", operation, terminal) + } + } else if !terminal || operation.State != "held" || operation.Reason != "pull_draft" { + t.Fatal("native Hosted draft hold lost its original reason", operation, terminal) + } + for _, table := range []string{"review_execution_reservations", "review_execution_evidence", "review_round_completions"} { + if cliCount(t, f.store, `SELECT count(*) FROM `+table) != 0 { + t.Fatal("draft spent capacity or credited a review", table) + } + } + return operation +} + +func TestDraftNativeDirectAndFinalAdmissionRefuseBothChannels(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *cliDriverFixture + var hosted *hostedDriverFixture + var driver reviewexec.Driver + if channel == "hosted" { + hosted = newHostedDriverFixture(t) + f, driver = hosted.cliDriverFixture, hosted.hosted + } else { + f = newCLIDriverFixture(t) + driver = f.driver + } + setRuntimeDraft(f, true) + raw, err := f.engine.Enqueue(t.Context(), f.scope(t, f.writer, false), "draft-direct", reviewexec.Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: channel, HeadSHA: f.headSHA}) + if err != nil { + t.Fatal(err) + } + var receipt reviewexec.Receipt + if err := json.Unmarshal(raw, &receipt); err != nil { + t.Fatal(err) + } + requested := waitRuntimeDraftState(t, f, driver, receipt.ID, channel) + if channel == "cli" { + if _, err := f.engine.ControlOperation(t.Context(), f.scope(t, f.writer, false), "cancel-draft-wait", requested.ID, reviewexec.OperationControl{ExpectedRevision: requested.Revision, Action: "cancel"}); err != nil { + t.Fatal(err) + } + } + if _, err := os.Stat(f.log); !os.IsNotExist(err) || f.fetches.Load() != 0 || hosted != nil && (hosted.provider.queries != 0 || hosted.provider.reviews != 0) { + t.Fatal("initial draft guard ran an allowance command, query or review", err) + } + // A fresh non-Draft preparation still cannot dispatch if the same + // current comparison becomes Draft before the final action boundary. + setRuntimeDraft(f, false) + var operation reviewexec.Operation + var attempt reviewexec.Attempt + if hosted != nil { + operation, attempt = hosted.prepareHosted(t) + } else { + operation, attempt = f.prepareAdmit(t, 2, 1, "ready-then-draft") + } + setRuntimeDraft(f, true) + expectedReason := "source_changed" + if channel == "hosted" { + expectedReason = "source_admission_changed" + } + result, err := driver.Dispatch(t.Context(), operation, attempt, func(context.Context, string) error { t.Error("draft review was posted"); return nil }) + if err != nil || result.State != "failed" || result.Reason != expectedReason || hosted != nil && hosted.provider.reviews != 0 { + t.Fatal("final source recheck admitted a Draft", result, err) + } + log, err := os.ReadFile(f.log) + if err != nil && !os.IsNotExist(err) || strings.Contains(string(log), "review ") { + t.Fatal("Draft started the CLI review process", err) + } + if cliCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_round_completions`) != 0 { + t.Fatal("Draft final refusal received completion credit") + } + }) + } +} + +func TestDraftHostedTimerRetryHoldsOriginalWithoutFreshProviderQuery(t *testing.T) { + f, now := newHostedCooldownRetryFixture(t) + op, first, config := f.startHosted(t) + waiting := scheduleRuntimeCooldown(t, f, op, first, config) + due, err := time.Parse(time.RFC3339Nano, waiting.Wait.RetryNotBefore) + if err != nil { + t.Fatal(err) + } + *now = due.Add(time.Millisecond) + setRuntimeDraft(f.cliDriverFixture, true) + held := waitRuntimeDraftState(t, f.cliDriverFixture, f.hosted, op.ID, "hosted") + if held.ID != op.ID || held.AttemptID == first.ID || f.provider.queries != 1 || f.provider.reviews != 0 { + t.Fatal("draft retry rebound intent or repeated provider work", held, f.provider.queries, f.provider.reviews) + } + if hostedDriverJournal(t, f, first.ID) != "held" { + t.Fatal("Draft changed the original ended cooldown attempt") + } +} + +func TestDraftAfterHostedTriggerDoesNotCancelOriginalReview(t *testing.T) { + f := newHostedDriverFixture(t) + op, attempt := f.prepareHosted(t) + confirmed := f.callback(t, &attempt) + result, err := f.hosted.Dispatch(t.Context(), op, attempt, func(ctx context.Context, id string) error { + if err := confirmed(ctx, id); err != nil { + return err + } + setRuntimeDraft(f.cliDriverFixture, true) + return nil + }) + if err != nil || result.State != "completed" || f.provider.reviews != 1 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 1 { + t.Fatal("later Draft canceled or erased the already issued review", result, err) + } + if _, err := f.engine.Advance(t.Context(), f.project, attempt.ID, attempt.Revision, result.State, result.Reason, result.ExternalID); err != nil { + t.Fatal(err) + } + if hostedDriverJournal(t, f, attempt.ID) != "completed" || cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("already issued completion was not retained") + } +} diff --git a/internal/reviewruntime/hosted_cooldown_retry_test.go b/internal/reviewruntime/hosted_cooldown_retry_test.go new file mode 100644 index 000000000..b64ace74e --- /dev/null +++ b/internal/reviewruntime/hosted_cooldown_retry_test.go @@ -0,0 +1,453 @@ +package reviewruntime + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestHostedCooldownRetryComparisonPreservesStableSource(t *testing.T) { + baseline := reviewexec.Anchor{RepositoryID: 901, Repository: "owner/repo", PullNumber: 2, CandidateSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), ParentSHA: strings.Repeat("c", 40), ParentPullNumber: 1, BaseRef: "source-1", MergeBaseSHA: strings.Repeat("d", 40), PatchSHA256: strings.Repeat("e", 64), ObservedAt: "2026-10-30T00:00:00Z"} + for field, mutate := range map[string]func(*reviewexec.Anchor){ + "repository identity": func(a *reviewexec.Anchor) { a.RepositoryID++ }, + "pull": func(a *reviewexec.Anchor) { a.PullNumber++ }, + "candidate": func(a *reviewexec.Anchor) { a.CandidateSHA = strings.Repeat("f", 40) }, + "base": func(a *reviewexec.Anchor) { a.BaseSHA = strings.Repeat("f", 40) }, + "parent": func(a *reviewexec.Anchor) { a.ParentSHA = strings.Repeat("f", 40) }, + "parent identity": func(a *reviewexec.Anchor) { a.ParentPullNumber++ }, + "base branch": func(a *reviewexec.Anchor) { a.BaseRef = "other" }, + "merge base": func(a *reviewexec.Anchor) { a.MergeBaseSHA = strings.Repeat("f", 40) }, + "patch": func(a *reviewexec.Anchor) { a.PatchSHA256 = strings.Repeat("f", 64) }, + } { + t.Run(field, func(t *testing.T) { + current := baseline + mutate(¤t) + if sameHostedRetryComparison(baseline, current) { + t.Fatal("changed stable comparison accepted") + } + }) + } + current := baseline + current.ObservedAt = "2026-10-30T00:05:00Z" + current.Repository = "renamed-owner/renamed-repo" + before := current + if !sameHostedRetryComparison(baseline, current) || !reflect.DeepEqual(current, before) || baseline.Repository != "owner/repo" || baseline.ObservedAt != "2026-10-30T00:00:00Z" { + t.Fatal("fresh observation or stable repository rename changed retained identity") + } +} + +// Every query and reply has a distinct provider identity; previous comments are +// still returned so the actual allowance resolver must attribute each attempt. +type cooldownRetryProvider struct{ *driverHostedProvider } + +func (p *cooldownRetryProvider) PostIssueComment(ctx context.Context, repo string, number int64, body string) (reviewprovider.IssueComment, error) { + comment, err := p.driverHostedProvider.PostIssueComment(ctx, repo, number, body) + if err == nil && strings.HasPrefix(body, "@coderabbitai rate limit\n\n") { + comment.ID = 1000 + int64(p.queries)*10 + if p.queries == 1 { + // Model supported provider clock lag so the first command is + // already historical when synthetic time advances without a + // real cooldown sleep. Original retained timestamps never change. + comment.CreatedAt = comment.CreatedAt.Add(-2 * time.Second) + comment.UpdatedAt = comment.CreatedAt + } + p.comments[len(p.comments)-1] = comment + } + return comment, err +} + +func (p *cooldownRetryProvider) IssueComments(ctx context.Context, repo string, number int64) ([]reviewprovider.IssueComment, error) { + p.histories++ + if repo != "owner/repo" || number != 2 { + p.t.Fatal("wrong retry query scope") + } + if len(p.comments) > 0 { + last := p.comments[len(p.comments)-1] + if strings.HasPrefix(last.Body, "@coderabbitai rate limit\n\n") { + at := time.Now().UTC() + p.comments = append(p.comments, reviewprovider.IssueComment{ID: last.ID + 1, Body: p.reply, Author: p.bot, CreatedAt: at, UpdatedAt: at}) + } + } + return append([]reviewprovider.IssueComment(nil), p.comments...), ctx.Err() +} + +func newHostedCooldownRetryFixture(t *testing.T) (*hostedDriverFixture, *time.Time) { + t.Helper() + f := newHostedDriverFixture(t) + now := time.Now().UTC() + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: f.capability.ID, Provider: "coderabbit", Account: f.capability.Account, Channels: f.capability.Channels, Fingerprint: f.capability.Fingerprint}}, reviewexec.WithNativeProjection(), reviewexec.WithExecutionClock(func() time.Time { return now })) + if err != nil { + t.Fatal(err) + } + f.engine, f.hosted.engine = engine, engine + f.hosted.provider = &cooldownRetryProvider{f.provider} + f.provider.reply = strings.Replace(runtimeAllowanceAvailable, "Reviews are available now.", "More reviews will be available in 1 minute.", 1) + return f, &now +} + +func scheduleRuntimeCooldown(t *testing.T, f *hostedDriverFixture, operation reviewexec.Operation, attempt reviewexec.Attempt, config reviewexec.Configuration) reviewexec.Operation { + t.Helper() + _, err := f.hosted.Prepare(t.Context(), operation, config, attempt) + var refusal *core.Error + if !errors.As(err, &refusal) || refusal.Code != "review_held" || refusal.Details.(map[string]string)["reason"] != "hosted_allowance_cooldown" { + t.Fatalf("actual query did not prove cooldown: %v (%#v)", err, refusal) + } + if _, err = f.engine.ScheduleHostedCooldown(t.Context(), f.project, attempt.ID, attempt.Revision); err != nil { + t.Fatal("schedule proven cooldown", err) + } + op, err := f.engine.ReadOperation(t.Context(), f.scope(t, f.writer, false), operation.ID) + if err != nil || op.ID != operation.ID || op.State != "queued" || op.AttemptID != "" || op.Wait == nil || op.Wait.RetryNotBefore == "" || op.Wait.Paused || f.provider.reviews != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("timer wait retained capacity or changed request", op, err) + } + return op +} + +func dueRuntimeCooldown(t *testing.T, f *hostedDriverFixture, now *time.Time, op reviewexec.Operation) (reviewexec.Operation, reviewexec.Attempt, reviewexec.Configuration) { + t.Helper() + due, err := time.Parse(time.RFC3339Nano, op.Wait.RetryNotBefore) + if err != nil { + t.Fatal(err) + } + *now = due.Add(time.Millisecond) + attempt, err := f.engine.StartAttempt(t.Context(), f.project, op.ID) + if err != nil { + t.Fatal("start due retry", err) + } + current, err := f.engine.ExecutionContext(t.Context(), f.project, op.ID) + if err != nil { + t.Fatal(err) + } + return current.Operation, attempt, current.Configuration +} + +func TestHostedCooldownRetryFreshAttemptFreshQueryAndSingleDispatch(t *testing.T) { + f, now := newHostedCooldownRetryFixture(t) + op, first, config := f.startHosted(t) + waiting := scheduleRuntimeCooldown(t, f, op, first, config) + baseline, err := f.engine.RetryBaseline(t.Context(), f.project, op.ID) + if err != nil || baseline == nil || waiting.Wait.BaselineAttemptID != first.ID { + t.Fatal("original comparison missing", baseline, err) + } + originalQuery, err := f.engine.ReadHostedAllowanceQuery(t.Context(), f.project, first.ID) + if err != nil { + t.Fatal(err) + } + originalObservations, err := f.engine.ReadHostedObservations(t.Context(), f.project, first.ID) + if err != nil { + t.Fatal(err) + } + originalBytes, _ := json.Marshal(originalObservations) + originalCaptures := make([]HostedCaptureRecord, len(originalObservations)) + for i, observation := range originalObservations { + in := observation.Input + originalCaptures[i], err = f.hostedCaptures.Read(t.Context(), first.ID, CaptureReference{ID: in.CaptureID, SHA256: in.CaptureSHA256, Bytes: in.CaptureBytes}) + if err != nil { + t.Fatal("read original immutable capture", err) + } + } + op, second, config := dueRuntimeCooldown(t, f, now, waiting) + if first.ID == second.ID || second.OperationID != first.OperationID { + t.Fatal("retry reused attempt or created a child request") + } + // A new positive response is necessary: keep the first attempt's cooldown + // comments intact, but let the new uniquely attributed query report capacity. + f.provider.reply = runtimeAllowanceAvailable + prepared, err := f.hosted.Prepare(t.Context(), op, config, second) + if err != nil || f.provider.queries != 2 || f.provider.reviews != 0 || !sameHostedRetryComparison(*baseline, prepared.Anchor) { + t.Fatal("retry did not independently query unchanged source", err, f.provider.queries) + } + secondQuery, err := f.engine.ReadHostedAllowanceQuery(t.Context(), f.project, second.ID) + if err != nil || secondQuery.ID == originalQuery.ID || secondQuery.Comment.ID == originalQuery.Comment.ID { + t.Fatal("fresh attempt reused old provider query", err) + } + second, err = f.engine.Admit(t.Context(), f.project, second.ID, second.Revision, prepared.Anchor, prepared.Intent) + if err != nil { + t.Fatal(err) + } + result, err := f.hosted.Dispatch(t.Context(), op, second, f.callback(t, &second)) + if err != nil || result.State != "completed" || f.provider.reviews != 1 { + t.Fatal("fresh positive allowance did not dispatch exactly once", result, err) + } + if _, err = f.hosted.Dispatch(t.Context(), op, second, f.callback(t, &second)); err != nil || f.provider.reviews != 1 { + t.Fatal("retry posted twice", err) + } + afterQuery, err := f.engine.ReadHostedAllowanceQuery(t.Context(), f.project, first.ID) + if err != nil || !reflect.DeepEqual(originalQuery, afterQuery) { + t.Fatal("retry changed original query", err) + } + afterObservations, err := f.engine.ReadHostedObservations(t.Context(), f.project, first.ID) + afterBytes, _ := json.Marshal(afterObservations) + if err != nil || string(afterBytes) != string(originalBytes) || hostedDriverJournal(t, f, first.ID) != "held" { + t.Fatal("retry changed original attempt/capture journal", err) + } + for i, observation := range originalObservations { + in := observation.Input + capture, err := f.hostedCaptures.Read(t.Context(), first.ID, CaptureReference{ID: in.CaptureID, SHA256: in.CaptureSHA256, Bytes: in.CaptureBytes}) + if err != nil || !reflect.DeepEqual(capture, originalCaptures[i]) { + t.Fatal("retry changed original immutable capture bytes", err) + } + } +} + +func TestHostedCooldownRetryRepeatedCooldownReleasesCapacityAndKeepsFirstBaseline(t *testing.T) { + f, now := newHostedCooldownRetryFixture(t) + op, first, config := f.startHosted(t) + waiting := scheduleRuntimeCooldown(t, f, op, first, config) + baseline, err := f.engine.RetryBaseline(t.Context(), f.project, op.ID) + if err != nil || baseline == nil { + t.Fatal(err) + } + op, second, config := dueRuntimeCooldown(t, f, now, waiting) + f.provider.reply = strings.Replace(runtimeAllowanceAvailable, "Reviews are available now.", "More reviews will be available in 60 minutes.", 1) + waiting = scheduleRuntimeCooldown(t, f, op, second, config) + if waiting.Wait.BaselineAttemptID != first.ID || first.ID == second.ID || f.provider.queries != 2 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 2 || cliCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 { + t.Fatal("repeated cooldown forked intent, reused attempt or replaced baseline", waiting) + } + after, err := f.engine.RetryBaseline(t.Context(), f.project, op.ID) + if err != nil || !reflect.DeepEqual(baseline, after) { + t.Fatal("repeated cooldown rebased original source", err) + } + if candidate, err := f.engine.StartAttempt(t.Context(), f.project, op.ID); err != nil || candidate.ID != "" || f.provider.queries != 2 || f.provider.reviews != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("future timer consumed shared capacity or provider work", err) + } +} + +func TestHostedCooldownRetryChangedOrUnusableSourceStopsBeforeFreshQuery(t *testing.T) { + for _, mode := range []string{"head", "base", "base branch", "closed", "unknown", "authorization", "authorization during preparation", "file policy", "channel closed", "provider active"} { + t.Run(mode, func(t *testing.T) { + f, now := newHostedCooldownRetryFixture(t) + op, first, config := f.startHosted(t) + waiting := scheduleRuntimeCooldown(t, f, op, first, config) + op, attempt, config := dueRuntimeCooldown(t, f, now, waiting) + pull := f.provider.pulls[2] + switch mode { + case "head": + pull.HeadSHA = f.baseSHA + case "base": + pull.BaseSHA = f.headSHA + case "base branch": + // Both current provider facts are valid. The retained original + // base branch still prevents quietly changing the retry target. + pull.BaseRef = "release" + f.provider.repository.DefaultBranch = "release" + case "closed": + pull.State = "closed" + case "unknown": + delete(f.provider.pulls, 2) + case "authorization": + if _, err := f.store.DB().Exec(`UPDATE grants SET can_write=0 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + case "authorization during preparation": + fetch := f.hosted.fetch + f.hosted.fetch = func(ctx context.Context, id int64, repository, head, base, token string) error { + if err := fetch(ctx, id, repository, head, base, token); err != nil { + return err + } + _, err := f.store.DB().Exec(`UPDATE grants SET can_write=0 WHERE project_id=?`, f.project) + return err + } + case "file policy": + one := int64(1) + if _, err := f.engine.ConfigurePolicy(t.Context(), f.scope(t, f.admin, true), "retry-file-policy", reviewexec.PolicyConfiguration{ExpectedRevision: &one, RequiredChannels: []string{"cli", "hosted"}, PausedChannels: []string{}, MaxReviewFiles: 1}); err != nil { + t.Fatal(err) + } + case "channel closed": + zero := int64(0) + if _, err := f.engine.ConfigureRoundControl(t.Context(), f.scope(t, f.admin, true), "close-retry-channel", 2, "hosted", reviewexec.RoundControlRequest{ExpectedRevision: &zero, Action: "close"}); err != nil { + t.Fatal(err) + } + case "provider active": + f.provider.activity = "active" + } + if mode != "unknown" { + f.provider.pulls[2] = pull + } + f.provider.reply = runtimeAllowanceAvailable + prepared, err := f.hosted.Prepare(t.Context(), op, config, attempt) + if err == nil || !reflect.DeepEqual(prepared, reviewexec.Preparation{}) || f.provider.queries != 1 || f.provider.reviews != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_hosted_allowance_queries`) != 1 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 { + t.Fatal("unusable retry source reached fresh allowance/provider action", err, f.provider.queries) + } + if mode == "base branch" { + var refusal *core.Error + if !errors.As(err, &refusal) || refusal.Details.(map[string]string)["reason"] != "source_changed" { + t.Fatal("valid new comparison escaped original retry baseline", err) + } + } + if mode == "unknown" { + var refusal *core.Error + if !errors.As(err, &refusal) || refusal.Code != "review_held" || refusal.Details.(map[string]string)["reason"] != "source_unavailable" { + t.Fatal("unknown retry source lost explicit held recovery reason", err) + } + } + if mode == "closed" { + var refusal *core.Error + if !errors.As(err, &refusal) || refusal.Details.(map[string]string)["reason"] != "target_changed" { + t.Fatal("retry rewrote structured source refusal", err) + } + } + }) + } +} + +func TestHostedCooldownRetryDoesNotChangeInitialSourceFailure(t *testing.T) { + f := newHostedDriverFixture(t) + op, attempt, config := f.startHosted(t) + delete(f.provider.pulls, 2) + _, err := f.hosted.Prepare(t.Context(), op, config, attempt) + var refusal *core.Error + if err == nil || errors.As(err, &refusal) || err.Error() != "synthetic missing scoped PR" || f.provider.queries != 0 || f.provider.reviews != 0 { + t.Fatal("initial source lookup gained retry-only behavior", err) + } +} + +func TestRetainHostedCooldownRejectsAvailableResponseWithAccurateReason(t *testing.T) { + f, got, _ := hostedBridgeObserved(t) + before := hostedBridgeState(t, f) + err := RetainHostedCooldown(t.Context(), f.captures, f.f.engine, f.a, f.anchor, 2, got.Capture) + var failure *core.Error + if !errors.As(err, &failure) || failure.Code != "review_held" || failure.Message != "The retained query has no proven cooldown response for this attempt." || hostedBridgeState(t, f) != before { + t.Fatal("cooldown refusal lost its reason or changed retained state", err) + } +} + +func TestHostedCooldownRetentionRetriesOnlyStorageFailures(t *testing.T) { + for _, code := range []string{"overloaded", "storage_unavailable", "review_held", "review_conflict", "validation_failed"} { + t.Run(code, func(t *testing.T) { + calls, waits := 0, 0 + failure := core.Fail(code, "fixture", 503) + err := retryHostedCooldownRetention(t.Context(), func(ctx context.Context, duration time.Duration) error { + waits++ + if duration != 200*time.Millisecond { + t.Fatal("unexpected retry delay", duration) + } + return ctx.Err() + }, func() error { + calls++ + if calls == 1 { + return failure + } + return nil + }) + if code == "overloaded" || code == "storage_unavailable" { + if err != nil || calls != 2 || waits != 1 { + t.Fatal("temporary retention failure not reconciled", calls, waits, err) + } + } else if err != failure || calls != 1 || waits != 0 { + t.Fatal("definitive refusal retried", calls, waits, err) + } + }) + } + calls := 0 + failure := core.Fail("overloaded", "fixture", 503) + err := retryHostedCooldownRetention(t.Context(), func(context.Context, time.Duration) error { return nil }, func() error { calls++; return failure }) + if calls != 3 || err != failure { + t.Fatal("retention retry was not bounded", calls, err) + } + ctx, cancel := context.WithCancel(t.Context()) + calls = 0 + err = retryHostedCooldownRetention(ctx, func(context.Context, time.Duration) error { cancel(); return ctx.Err() }, func() error { calls++; return failure }) + if calls != 1 || !errors.Is(err, context.Canceled) { + t.Fatal("retry ignored cancellation", calls, err) + } +} + +func TestHostedCooldownRetentionOutageRecoversOriginalAttemptOffline(t *testing.T) { + for _, damage := range []string{"none", "missing-capture", "malformed-capture", "workspace"} { + t.Run(damage, func(t *testing.T) { + f, _ := newHostedCooldownRetryFixture(t) + operation, attempt, config := f.startHosted(t) + if _, err := f.store.DB().Exec(`CREATE TRIGGER fail_cooldown_retention BEFORE INSERT ON review_hosted_preflight BEGIN SELECT RAISE(ABORT,'retention outage'); END`); err != nil { + t.Fatal(err) + } + waits := 0 + f.hosted.wait = func(ctx context.Context, _ time.Duration) error { waits++; return ctx.Err() } + _, err := f.hosted.Prepare(t.Context(), operation, config, attempt) + var recovery *reviewexec.PreparationRecoveryError + if !errors.As(err, &recovery) || waits != 2 { + t.Fatal("outage did not leave recoverable preparation after bounded retries", waits, err) + } + if got, err := f.engine.ReadOperation(t.Context(), f.scope(t, f.writer, false), operation.ID); err != nil || got.State != "preparing" || got.AttemptID != attempt.ID { + t.Fatal("original preparation lost", got, err) + } + // Restart while storage is still unavailable must leave the same attempt. + if _, err := f.engine.Start(t.Context(), map[string]reviewexec.Driver{f.capability.ID: f.hosted}); err == nil { + t.Fatal("startup ignored persistent storage outage") + } + if _, err := f.store.DB().Exec(`DROP TRIGGER fail_cooldown_retention`); err != nil { + t.Fatal(err) + } + query, err := f.engine.ReadHostedAllowanceQuery(t.Context(), f.project, attempt.ID) + if err != nil { + t.Fatal(err) + } + observations, err := f.engine.ReadHostedObservations(t.Context(), f.project, attempt.ID) + if err != nil || len(observations) == 0 { + t.Fatal(err) + } + in := observations[len(observations)-1].Input + ref := CaptureReference{ID: in.CaptureID, SHA256: in.CaptureSHA256, Bytes: in.CaptureBytes} + path := filepath.Join(f.hostedCaptures.root, hostedCaptureFilename(attempt.ID, ref)) + switch damage { + case "missing-capture": + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + case "malformed-capture": + if err := os.WriteFile(path, []byte("{}"), 0600); err != nil { + t.Fatal(err) + } + case "workspace": + a := query.Anchor + workspace, err := f.manager.Open(t.Context(), attempt.ID, a.CandidateSHA, a.BaseSHA, a.MergeBaseSHA, a.PatchSHA256, a.Repository) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace.Directory, "untracked"), []byte("changed"), 0600); err != nil { + t.Fatal(err) + } + } + before := []int{f.provider.queries, f.provider.reviews, f.provider.histories, f.reader.repositoryCalls} + for pass := 0; pass < 2; pass++ { + ctx, cancel := context.WithCancel(t.Context()) + done, err := f.engine.Start(ctx, map[string]reviewexec.Driver{f.capability.ID: f.hosted}) + if err != nil { + cancel() + t.Fatal(err) + } + cancel() + if err := <-done; err != nil { + t.Fatal(err) + } + got, err := f.engine.ReadOperation(t.Context(), f.scope(t, f.writer, false), operation.ID) + if err != nil || got.ID != operation.ID { + t.Fatal("request identity changed", got, err) + } + if damage == "none" { + if got.State != "queued" || got.Wait == nil || got.Wait.BaselineAttemptID != attempt.ID || got.Wait.RetryNotBefore == "" { + t.Fatal("original cooldown not recovered", got) + } + } else if got.State != "cancelled" || cliCount(t, f.store, `SELECT count(*) FROM review_hosted_preflight`) != 0 { + t.Fatal("unproven recovery retained cooldown", got) + } + } + after := []int{f.provider.queries, f.provider.reviews, f.provider.histories, f.reader.repositoryCalls} + if !reflect.DeepEqual(before, after) { + t.Fatal("recovery contacted provider", before, after) + } + if cliCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 1 { + t.Fatal("recovery created another attempt") + } + }) + } +} diff --git a/internal/reviewruntime/hosted_driver.go b/internal/reviewruntime/hosted_driver.go index 647c752ad..2c3ff1afe 100644 --- a/internal/reviewruntime/hosted_driver.go +++ b/internal/reviewruntime/hosted_driver.go @@ -162,9 +162,17 @@ func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operati d.mu.Unlock() } }() + baseline, err := d.engine.RetryBaseline(ctx, operation.ProjectID, operation.ID) + if err != nil { + return preparation, err + } reads := newSourceReads(d.provider) plan, _, err := resolveReviewSource(ctx, d.engine, reads, current.RepositoryID, current.Configuration, current.Operation) if err != nil { + var refusal *core.Error + if baseline != nil && ctx.Err() == nil && !errors.As(err, &refusal) { + return preparation, reviewHold("source_unavailable") + } return preparation, err } if err := d.checkIdle(ctx, plan); err != nil { @@ -175,6 +183,9 @@ func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operati return preparation, err } anchor := reviewexec.Anchor{RepositoryID: current.RepositoryID, Repository: plan.Repository.FullName, PullNumber: plan.Pull.Number, CandidateSHA: plan.Pull.HeadSHA, BaseSHA: plan.Pull.BaseSHA, ParentSHA: plan.ParentSHA, ParentPullNumber: plan.ParentPullNumber, BaseRef: plan.Pull.BaseRef, MergeBaseSHA: workspace.MergeBaseSHA, PatchSHA256: workspace.PatchSHA256, ObservedAt: plan.ObservedAt} + if baseline != nil && !sameHostedRetryComparison(*baseline, anchor) { + return preparation, reviewHold("source_changed") + } actor, err := d.provider.CurrentActor(ctx) if err != nil { return preparation, reviewHold("provider_actor_unproven") @@ -189,6 +200,14 @@ func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operati break } if observed.Observation.State == "cooldown_observed" { + if err := retryHostedCooldownRetention(ctx, d.wait, func() error { + return RetainHostedCooldown(ctx, d.captures, d.engine, attempt, anchor, fileCount, observed.Capture) + }); err != nil { + if retryableHostedRetention(err) || ctx.Err() != nil { + return preparation, &reviewexec.PreparationRecoveryError{Err: err} + } + return preparation, reviewHold("hosted_allowance_unproven") + } return preparation, reviewHold("hosted_allowance_cooldown") } if observed.Reason != "allowance_not_proven" || pass == 7 { diff --git a/internal/reviewruntime/hosted_driver_test.go b/internal/reviewruntime/hosted_driver_test.go index 280b00f87..7173c11c6 100644 --- a/internal/reviewruntime/hosted_driver_test.go +++ b/internal/reviewruntime/hosted_driver_test.go @@ -259,7 +259,7 @@ func TestHostedDriverFinalGuardsPreventReviewPOST(t *testing.T) { p.BaseSHA = strings.Repeat("9", 40) f.provider.pulls[2] = p case "configuration": - f.configure(t, "independent", []int64{2, 4}) + f.configure(t, "stacked", []int64{2, 4}) case "policy": one := int64(1) _, err := f.engine.ConfigurePolicy(t.Context(), f.scope(t, f.admin, true), "pause-hosted", reviewexec.PolicyConfiguration{ExpectedRevision: &one, RequiredChannels: []string{"hosted"}, PausedChannels: []string{"hosted"}}) @@ -576,3 +576,13 @@ func TestHostedDriverInvalidPostReceiptNeverRecordsTrigger(t *testing.T) { }) } } + +func TestHostedDriverFinalGuardPreservesHarmlessQueueSuffixChange(t *testing.T) { + f := newHostedDriverFixture(t) + op, a := f.prepareHosted(t) + f.configure(t, "independent", []int64{2, 4}) + result, err := f.hosted.Dispatch(t.Context(), op, a, f.callback(t, &a)) + if err != nil || result.State != "completed" || f.provider.reviews != 1 || f.provider.queries != 1 { + t.Fatal("harmless queue suffix edit changed original dispatch", result, err, f.provider.reviews, f.provider.queries) + } +} diff --git a/internal/reviewruntime/hosted_preflight.go b/internal/reviewruntime/hosted_preflight.go index 90865e97a..82ff944a2 100644 --- a/internal/reviewruntime/hosted_preflight.go +++ b/internal/reviewruntime/hosted_preflight.go @@ -2,6 +2,7 @@ package reviewruntime import ( "context" + "errors" "time" "github.com/benhook1013/FireController/internal/core" @@ -13,6 +14,14 @@ import ( // source rather than trusting a caller's parsed availability. It records no // review completion, provider action, attempt transition or execution permit. func RetainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference) error { + return retainHostedAllowance(ctx, captures, engine, attempt, anchor, changedFiles, reference, false) +} + +func RetainHostedCooldown(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference) error { + return retainHostedAllowance(ctx, captures, engine, attempt, anchor, changedFiles, reference, true) +} + +func retainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference, cooldown bool) error { if ctx == nil || captures == nil || engine == nil || !validHostedReference(reference) { return core.Fail("validation_failed", "Use the preparing hosted attempt and its private query capture.", 400) } @@ -53,9 +62,108 @@ func RetainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, en if err != nil { return err } - if observation.State != "available_observed" || query.Comment == nil || observation.QueryCommentID != query.Comment.ID { - return core.Fail("review_held", "The retained query has no proven available response for this attempt.", 409) + want := "available_observed" + if cooldown { + want = "cooldown_observed" + } + if observation.State != want || query.Comment == nil || observation.QueryCommentID != query.Comment.ID { + message := "The retained query has no proven available response for this attempt." + if cooldown { + message = "The retained query has no proven cooldown response for this attempt." + } + return core.Fail("review_held", message, 409) + } + input := reviewexec.HostedAllowanceInput{QueryID: query.ID, Anchor: anchor, + ObservedAt: record.Snapshot.ObservedAt.Format(time.RFC3339Nano), ChangedFiles: changedFiles, CaptureID: reference.ID, CaptureSHA256: reference.SHA256, CaptureBytes: reference.Bytes, Observation: observation} + if cooldown { + return engine.RecordHostedCooldown(ctx, attempt.ProjectID, attempt.ID, attempt.Revision, input) + } + return engine.RecordHostedAllowance(ctx, attempt.ProjectID, attempt.ID, attempt.Revision, input) +} + +// Retention is an idempotent local write of the same immutable capture. Retry +// transient writer admission failures without issuing another provider query. +// Every retry revalidates the original binding and reconciles an existing row. +func retryHostedCooldownRetention(ctx context.Context, wait func(context.Context, time.Duration) error, retain func() error) error { + for pass := 0; ; pass++ { + if err := ctx.Err(); err != nil { + return err + } + err := retain() + if err == nil || pass == 2 || !retryableHostedRetention(err) { + return err + } + if err := wait(ctx, 200*time.Millisecond); err != nil { + return err + } + } +} + +func retryableHostedRetention(err error) bool { + var failure *core.Error + return errors.As(err, &failure) && (failure.Code == "overloaded" || failure.Code == "storage_unavailable") +} + +// RecoverPreparation only replays immutable local source. It never observes or +// posts to the provider and cannot create an execution permit or new attempt. +func (d *HostedDriver) RecoverPreparation(ctx context.Context, operation reviewexec.Operation, attempt reviewexec.Attempt) error { + ctx, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + query, err := d.engine.ReadHostedAllowanceQuery(ctx, attempt.ProjectID, attempt.ID) + if err != nil { + if retryableHostedRetention(err) || ctx.Err() != nil { + return err + } + return nil + } + observations, err := d.engine.ReadHostedObservations(ctx, attempt.ProjectID, attempt.ID) + if err != nil { + return err + } + var reference CaptureReference + for i := len(observations) - 1; i >= 0; i-- { + in := observations[i].Input + if in.Kind == "allowance_query" { + reference = CaptureReference{ID: in.CaptureID, SHA256: in.CaptureSHA256, Bytes: in.CaptureBytes} + break + } + } + if reference.ID == "" { + return nil + } + record, err := d.captures.Read(ctx, attempt.ID, reference) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return nil + } + earliest, err := time.Parse(time.RFC3339Nano, query.EarliestPosting) + if err != nil { + return nil + } + observation, err := reviewprovider.ResolveHostedAllowance(reviewprovider.HostedAllowanceSnapshot{IssueComments: record.Snapshot.IssueComments, Complete: record.Snapshot.Complete, ObservedAt: record.Snapshot.ObservedAt}, record.Intent, record.PostingActor, record.ProviderActor, earliest) + if err != nil || observation.State != "cooldown_observed" { + return nil + } + anchor := query.Anchor + workspace, err := d.manager.Open(ctx, attempt.ID, anchor.CandidateSHA, anchor.BaseSHA, anchor.MergeBaseSHA, anchor.PatchSHA256, anchor.Repository) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return nil + } + files, err := d.manager.ChangedFiles(ctx, workspace) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return nil + } + err = RetainHostedCooldown(ctx, d.captures, d.engine, attempt, anchor, int64(len(files)), reference) + if retryableHostedRetention(err) || ctx.Err() != nil { + return err } - return engine.RecordHostedAllowance(ctx, attempt.ProjectID, attempt.ID, attempt.Revision, reviewexec.HostedAllowanceInput{QueryID: query.ID, Anchor: anchor, - ObservedAt: record.Snapshot.ObservedAt.Format(time.RFC3339Nano), ChangedFiles: changedFiles, CaptureID: reference.ID, CaptureSHA256: reference.SHA256, CaptureBytes: reference.Bytes, Observation: observation}) + return nil } diff --git a/internal/reviewruntime/retry_comparison.go b/internal/reviewruntime/retry_comparison.go new file mode 100644 index 000000000..0a15dbe06 --- /dev/null +++ b/internal/reviewruntime/retry_comparison.go @@ -0,0 +1,12 @@ +package reviewruntime + +import "github.com/benhook1013/FireController/internal/reviewexec" + +// Retained waits retry the same comparison, not newly discovered source. +func sameHostedRetryComparison(baseline, current reviewexec.Anchor) bool { + baseline.ObservedAt = "" + current.ObservedAt = "" + baseline.Repository = "" + current.Repository = "" + return baseline == current +} diff --git a/internal/reviews/channel_run_counts_test.go b/internal/reviews/channel_run_counts_test.go index 588b3887c..7add37604 100644 --- a/internal/reviews/channel_run_counts_test.go +++ b/internal/reviews/channel_run_counts_test.go @@ -122,41 +122,49 @@ func TestChannelRunCountsCorruptionAndPublicationRollback(t *testing.T) { } func TestChannelRunCountsSchemaEightMigrationAndRestart(t *testing.T) { - f, snapshots, _, _ := historyMigrationLegacyFixture(t) - migrations := append(reviewSchemaMigrations(), historyMigrationSQL(), CurrentSummarySchemaSQLV8(), CurrentRunOrderSchemaSQL(), pullMetadataMigrationSQL(), attemptReasonMigrationSQL()) - if err := f.store.EnsureSchemaWithBackfill(t.Context(), "reviews", migrations, backfillCurrentReviewIndexes); err != nil { - t.Fatal(err) - } - var version string - if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:reviews'`).Scan(&version); err != nil || version != "8" { - t.Fatal("genuine populated v8 required", version, err) - } - // A schema-only upgrade reuses valid caches. Damage a derived total so this - // fixture exercises backfill failure and rollback rather than a valid no-op. - if _, err := f.store.DB().Exec(`UPDATE review_current_totals SET run_count=run_count+1; CREATE TRIGGER reject_counts_backfill BEFORE INSERT ON review_current_totals BEGIN SELECT RAISE(ABORT,'synthetic count backfill failure'); END`); err != nil { - t.Fatal(err) - } - before := historyMigrationDatabaseDigest(t, f) - if err := EnsureSchema(t.Context(), f.store); err == nil || before != historyMigrationDatabaseDigest(t, f) { - t.Fatal("failed upgrade did not roll back metadata, DDL, cache and history", err) - } - if _, err := f.store.DB().Exec(`DROP TRIGGER reject_counts_backfill`); err != nil { - t.Fatal(err) - } - if err := EnsureSchema(t.Context(), f.store); err != nil { - t.Fatal(err) - } - var p PullResponse - nativeRead(t, f, "/pulls/7?snapshot="+snapshots[0], &p) - if !p.Pull.RunCounts.Valid(p.Pull.RunCount) || p.Pull.RunCounts.CLI != p.Pull.RunCount { - t.Fatal("v8 historical facts lost", p) - } - if err := ValidateCurrentSummaries(t.Context(), f.store.DB()); err != nil { - t.Fatal(err) - } - before = historyMigrationDatabaseDigest(t, f) - if err := EnsureSchema(t.Context(), f.store); err != nil || before != historyMigrationDatabaseDigest(t, f) { - t.Fatal("current startup repeated backfill", err) + // Preserve both rollback boundaries: the bridge forces a real cache rebuild, + // while this successor also checks the channel-count migration UPDATE. + for _, scenario := range []struct{ name, failureSQL string }{ + {"cache rebuild", `UPDATE review_current_totals SET run_count=run_count+1; CREATE TRIGGER reject_counts_backfill BEFORE INSERT ON review_current_totals BEGIN SELECT RAISE(ABORT,'synthetic count backfill failure'); END`}, + {"channel-count migration", `CREATE TRIGGER reject_counts_backfill BEFORE UPDATE ON review_current_totals BEGIN SELECT RAISE(ABORT,'synthetic count backfill failure'); END`}, + } { + t.Run(scenario.name, func(t *testing.T) { + + f, snapshots, _, _ := historyMigrationLegacyFixture(t) + migrations := append(reviewSchemaMigrations(), historyMigrationSQL(), CurrentSummarySchemaSQLV8(), CurrentRunOrderSchemaSQL(), pullMetadataMigrationSQL(), attemptReasonMigrationSQL()) + if err := f.store.EnsureSchemaWithBackfill(t.Context(), "reviews", migrations, backfillCurrentReviewIndexes); err != nil { + t.Fatal(err) + } + var version string + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:reviews'`).Scan(&version); err != nil || version != "8" { + t.Fatal("genuine populated v8 required", version, err) + } + if _, err := f.store.DB().Exec(scenario.failureSQL); err != nil { + t.Fatal(err) + } + before := historyMigrationDatabaseDigest(t, f) + if err := EnsureSchema(t.Context(), f.store); err == nil || before != historyMigrationDatabaseDigest(t, f) { + t.Fatal("failed upgrade did not roll back metadata, DDL, cache and history", err) + } + if _, err := f.store.DB().Exec(`DROP TRIGGER reject_counts_backfill`); err != nil { + t.Fatal(err) + } + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + var p PullResponse + nativeRead(t, f, "/pulls/7?snapshot="+snapshots[0], &p) + if !p.Pull.RunCounts.Valid(p.Pull.RunCount) || p.Pull.RunCounts.CLI != p.Pull.RunCount { + t.Fatal("v8 historical facts lost", p) + } + if err := ValidateCurrentSummaries(t.Context(), f.store.DB()); err != nil { + t.Fatal(err) + } + before = historyMigrationDatabaseDigest(t, f) + if err := EnsureSchema(t.Context(), f.store); err != nil || before != historyMigrationDatabaseDigest(t, f) { + t.Fatal("current startup repeated backfill", err) + } + }) } } From b682143b81e5757ee98cffdd62b634a0fdfd7277 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 15:11:34 +1300 Subject: [PATCH 02/21] Carry retained review client controls onto repaired quota stack --- docs/mcp.md | 1 + docs/retained-review-quota-controls.md | 6 +- internal/cli/cli.go | 40 +- internal/cli/operation_help.go | 5 + internal/cli/review_operation_control.go | 27 + internal/cli/review_operation_control_test.go | 110 ++++ internal/cli/review_operation_status.go | 12 +- internal/cli/review_wait_test.go | 10 +- internal/cli/reviews.go | 8 + internal/client/client.go | 22 + internal/client/review_agent_output.go | 59 +++ internal/client/review_agent_output_test.go | 13 + .../review_allowance_validation_test.go | 68 +++ internal/client/review_cli_wait_test.go | 218 ++++++++ internal/client/review_execution.go | 46 +- internal/client/review_operation_control.go | 97 ++++ .../client/review_operation_control_test.go | 497 ++++++++++++++++++ internal/client/review_operation_status.go | 35 +- internal/mcpadapter/adapter_test.go | 4 +- internal/mcpadapter/arguments.go | 3 + .../mcpadapter/review_operation_control.go | 30 ++ .../review_operation_control_test.go | 95 ++++ .../mcpadapter/review_operation_status.go | 12 +- internal/mcpadapter/review_wait_test.go | 10 +- internal/mcpadapter/tools.go | 9 +- 25 files changed, 1392 insertions(+), 45 deletions(-) create mode 100644 internal/cli/review_operation_control.go create mode 100644 internal/cli/review_operation_control_test.go create mode 100644 internal/client/review_allowance_validation_test.go create mode 100644 internal/client/review_cli_wait_test.go create mode 100644 internal/client/review_operation_control.go create mode 100644 internal/client/review_operation_control_test.go create mode 100644 internal/mcpadapter/review_operation_control.go create mode 100644 internal/mcpadapter/review_operation_control_test.go diff --git a/docs/mcp.md b/docs/mcp.md index 46dfa24c4..60666c777 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -75,6 +75,7 @@ Startup validates configuration without opening the credential or contacting the | `review_execution_read` | No fields; stored execution configuration and revision, without provider work. | | `review_operations_list` | Optional pull_number/channel/status/limit/cursor; one bounded page of retained operations, default five pending. No provider work or automatic continuation. | | `review_operation_read` | Required operation_id; optional wait_seconds (0–50/default 0) and diagnostics (default false). Compact retained status and original Hosted observer freshness, or explicit full detail, without provider polling. | +| `review_operation_control` | Required operation_id/expected_revision/action/idempotency_key; action pause, resume or cancel applies guarded [retained request controls](retained-review-quota-controls.md#reading-state), preserving original authorization and attempt history. | | `wait_for_ci` | Required targets (1–20), each with pull_number/head_sha and optional base_sha/after_observation_key/failure_workflow_ids (1–16 unique positive IDs); optional wait_seconds 0–900, default 300. Wait for [pinned required CI](ci-wait.md) without granting review coverage. | | `review_start` | Required channel/idempotency_key; optional expected_pull_number, expected_configuration_revision and wait_seconds (0–50/default 2) select at most one ordinary child. | | `review_selection_read` | Required selection_id; optional wait_seconds (0–50/default 0) follows the original selection and linked operation without new work. | diff --git a/docs/retained-review-quota-controls.md b/docs/retained-review-quota-controls.md index 71c1e5e9a..8f8186b66 100644 --- a/docs/retained-review-quota-controls.md +++ b/docs/retained-review-quota-controls.md @@ -2,7 +2,7 @@ This slice follows native CI observation and keeps an authorized review request alive when its provider has no available allowance. It does not discover new -reviews, increase grants, adjudicate findings, or merge pull requests. This slice delivers the server HTTP contract; bound client, CLI and MCP controls and wait diagnostics follow in a separate dependent slice. +reviews, increase grants, adjudicate findings, or merge pull requests. ## One request, multiple unused preparations @@ -38,7 +38,7 @@ Only one of the two supervisor workers probes retained Draft waits. Its scheduli Operation and round-progress reads expose waiting state only when requested with `X-FC-Operation-Wait`; round-progress reads also require the `view=stages` query parameter. Version 1 preserves the original Hosted shape; version 2 also understands CLI baselines. Version 3 adds retained provider allowance estimates. A full-capacity estimate is not the next retry time or a guarantee -that a review can start. Older clients continue receiving their existing shapes. Version 3 exposes `wait.cli_allowance` for a queued CLI baseline, held-operation `allowance` facts, and the compact held Hosted `retry_not_before` deadline. The existing bound clients retain their earlier response contract; version 3 client support follows in the dependent slice. Legacy responses without these optional facts remain readable; absence does not imply zero allowance or a provider reset. +that a review can start. Older clients continue receiving their existing shapes. The current bound clients request version 3 and preserve validated `wait.cli_allowance` for a queued CLI baseline, held-operation `allowance` facts, and the compact held Hosted `retry_not_before` deadline. Legacy responses without these optional facts remain readable; absence does not imply zero allowance or a provider reset. The public control endpoint is `POST /api/v1/projects/{project_id}/reviews/operations/{operation_id}/control`. @@ -54,7 +54,7 @@ Any credential with write permission in this project may control an undispatched - `validation_failed` refuses a malformed operation ID or request body, an `expected_revision` below 1, or an action other than `pause`, `resume` or `cancel`; correct the invalid fields before submitting the intended control. - `storage_unavailable` refuses a control when retained wait data is damaged or unavailable; retain the original request and idempotency key and inspect the retained state before attempting recovery. Do not submit a new key to bypass the failure. -Request submission can separately fail with `review_inflight`. It refuses a new-key request while another operation for the same project, PR and channel is queued, preparing, posting, active or uncertain. Its `operation_id` detail names the existing request. Read and retain that operation; the queued-only HTTP control may cancel it when cancellation is intended, while issued work must finish or follow its original recovery path. Do not submit another key to bypass the pending request. +Request submission can separately fail with `review_inflight`. It refuses a new-key request while another operation for the same project, PR and channel is queued, preparing, posting, active or uncertain. Its `operation_id` detail names the existing request. Read and retain that operation; queued-only `review_operation_control` may cancel it when cancellation is intended, while issued work must finish or follow its original recovery path. Do not submit another key to bypass the pending request. After an unknown outcome, recover with the same authenticated principal, project, worker, exact request body, operation ID and idempotency key. Do not invent a new key or assume that the action failed. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 2e0d292c1..843393183 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -46,15 +46,16 @@ type options struct { } type invocation struct { - ciWatch *ciWatchInvocation - reviewRun *reviewRunInvocation - operationHelp string - reviewOperations client.ReviewOperationsOptions - reviewOperationStatus *reviewOperationStatusInvocation - adoptionObligations *adoptionObligationsInvocation - roundAdoption *roundAdoptionInvocation - rounds *reviewRoundsInvocation - reviewCIDiagnostics bool + ciWatch *ciWatchInvocation + reviewRun *reviewRunInvocation + operationHelp string + reviewOperations client.ReviewOperationsOptions + reviewOperationStatus *reviewOperationStatusInvocation + reviewOperationControl *reviewOperationControlInvocation + adoptionObligations *adoptionObligationsInvocation + roundAdoption *roundAdoptionInvocation + rounds *reviewRoundsInvocation + reviewCIDiagnostics bool options command string subcommand string @@ -94,7 +95,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou call, ok := parseInvocation(args) if !ok { action := "Use fc version, fc context, fc doctor, or a documented service command." - if call.command == "reviews" && (call.subcommand == "ci-wait" || call.subcommand == "operations" || call.subcommand == "operation" || call.subcommand == "start" || call.subcommand == "run-read") { + if call.command == "reviews" && (call.subcommand == "ci-wait" || call.subcommand == "operations" || call.subcommand == "operation-control" || call.subcommand == "operation" || call.subcommand == "start" || call.subcommand == "run-read") { action = "Use fc reviews " + call.subcommand + " --help." } return report(stderr, ExitUsage, "invalid_arguments", "The command or its arguments are not supported.", action) @@ -348,6 +349,21 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou if err != nil { return reportClientError(stderr, err, ctx) } + if call.reviewOperationControl != nil { + encoded, err := json.Marshal(value) + if err == nil { + encoded = append(encoded, '\n') + var written int + written, err = stdout.Write(encoded) + if err == nil && written != len(encoded) { + err = io.ErrShortWrite + } + } + if err != nil { + return reportDetails(stderr, ExitConfig, diagnostic{Code: "output_failed", Message: "The review control receipt could not be written.", Action: "Retry the exact same key, request and bound instance; do not use a replacement key.", OutcomeUnknown: true}) + } + return ExitSuccess + } return emit(stdout, stderr, value) } @@ -387,7 +403,7 @@ func parseInvocation(args []string) (invocation, bool) { return call, false } call.command = remaining[0] - if len(remaining) == 3 && remaining[0] == "help" && remaining[1] == "reviews" && (remaining[2] == "operations" || remaining[2] == "operation") { + if len(remaining) == 3 && remaining[0] == "help" && remaining[1] == "reviews" && (remaining[2] == "operations" || remaining[2] == "operation-control" || remaining[2] == "operation") { call.operationHelp = remaining[2] return call, true } @@ -408,7 +424,7 @@ func parseInvocation(args []string) (invocation, bool) { } call.subcommand = remaining[1] operationArgs := remaining[2:] - if call.command == "reviews" && (call.subcommand == "ci-wait" || call.subcommand == "operations" || call.subcommand == "operation" || call.subcommand == "start" || call.subcommand == "run-read") && len(operationArgs) == 1 && operationArgs[0] == "--help" { + if call.command == "reviews" && (call.subcommand == "ci-wait" || call.subcommand == "operations" || call.subcommand == "operation-control" || call.subcommand == "operation" || call.subcommand == "start" || call.subcommand == "run-read") && len(operationArgs) == 1 && operationArgs[0] == "--help" { call.operationHelp = call.subcommand return call, true } diff --git a/internal/cli/operation_help.go b/internal/cli/operation_help.go index c65f612e5..f6d64342f 100644 --- a/internal/cli/operation_help.go +++ b/internal/cli/operation_help.go @@ -6,6 +6,11 @@ func emitOperationHelp(operation string, stdout, stderr io.Writer) int { usage := " reviews operations [--pr NUMBER] [--channel cli|hosted] [--all] [--limit N] [--cursor CURSOR]" semantics := "Read one compact newest-first page of retained project operations. Default five pending; --all includes held and terminal history. Reuse the same filters with a cursor. No provider reads, automatic pagination, execution or retry." documentation := "docs/review-operations.md" + if operation == "operation-control" { + documentation = "docs/retained-review-quota-controls.md" + usage = " reviews operation-control OPERATION_ID --action pause|resume|cancel --expect-revision N --key KEY" + semantics = "Control only a queued, undispatched operation using its current revision and explicit key. Pause retains the retry deadline; resume permits the same request to recheck when due. Cancel withdraws intent, never an issued provider request. Preserve exact request and key after unknown outcome. No changes to grants, taper, findings or project pause." + } if operation == "ci-wait" { documentation = "docs/ci-wait.md" usage = " reviews ci-wait --target PR:HEAD[:BASE] [--after-observation PR:KEY] [--failure-workflow PR:ID] [--wait-seconds 0-900 (default 300)]" diff --git a/internal/cli/review_operation_control.go b/internal/cli/review_operation_control.go new file mode 100644 index 000000000..9e8b24938 --- /dev/null +++ b/internal/cli/review_operation_control.go @@ -0,0 +1,27 @@ +package cli + +import ( + "github.com/benhook1013/FireController/internal/client" + "strconv" +) + +type reviewOperationControlInvocation struct { + id, key string + control client.ReviewOperationControl +} + +func parseReviewOperationControl(args []string) (*reviewOperationControlInvocation, bool) { + if len(args) < 1 { + return nil, false + } + in := &reviewOperationControlInvocation{id: args[0]} + values, ok := reviewSourceFlags(args[1:], "--action", "--expect-revision", "--key") + if !ok { + return nil, false + } + in.key = values["--key"] + in.control.Action = values["--action"] + n, err := strconv.ParseInt(values["--expect-revision"], 10, 64) + in.control.ExpectedRevision = n + return in, err == nil && strconv.FormatInt(n, 10) == values["--expect-revision"] && validMutationKey(in.key) && client.ValidateReviewOperationControl(in.id, in.control) == nil +} diff --git a/internal/cli/review_operation_control_test.go b/internal/cli/review_operation_control_test.go new file mode 100644 index 000000000..10e646dc5 --- /dev/null +++ b/internal/cli/review_operation_control_test.go @@ -0,0 +1,110 @@ +package cli_test + +import ( + "context" + "encoding/json" + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestReviewOperationControlCLIActualRevisionReplayAndBinding(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/control") && (r.Header.Get("X-FC-Worker") != worker || !strings.HasPrefix(r.URL.Path, "/api/v1/projects/"+project+"/")) { + t.Error("control lost identity/project") + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) + code, out, stderr := mutationInvoke(t, profiles, "builder", reviewRequestArgs()...) + var queued struct { + ID string `json:"id"` + State string `json:"state"` + Revision int64 `json:"revision"` + Diagnostic *client.ReviewOperationDiagnostic `json:"diagnostic,omitempty"` + } + if code != 0 || stderr != "" || strictjson.Decode([]byte(out), &queued) != nil || queued.State != "queued" || queued.Revision != 1 || !strings.HasPrefix(queued.ID, "review_operation_") { + t.Fatal("invalid adapted queued receipt", code, out, stderr) + } + id := queued.ID + invoke := func(action, rev, key string) client.ReviewOperationControlReceipt { + t.Helper() + code, out, stderr := mutationInvoke(t, profiles, "builder", "reviews", "operation-control", id, "--action", action, "--expect-revision", rev, "--key", key) + var v client.ReviewOperationControlReceipt + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &v) != nil { + t.Fatal(code, out, stderr) + } + return v + } + paused := invoke("pause", "1", "pause") + if !paused.Paused || paused.Revision != 2 { + t.Fatal(paused) + } + if replay := invoke("pause", "1", "pause"); replay != paused { + t.Fatal("replay changed", replay) + } + code, out, stderr = mutationInvoke(t, profiles, "builder", "reviews", "operation-control", id, "--action", "resume", "--expect-revision", "1", "--key", "stale") + if code != cli.ExitConflict || out != "" || !strings.Contains(stderr, "review_conflict") { + t.Fatal(code, out, stderr) + } + code, out, stderr = mutationInvoke(t, profiles, "builder", "reviews", "operation", id) + if code != 0 || !strings.Contains(out, `"wait":{"paused":true}`) { + t.Fatal(code, out, stderr) + } + resumed := invoke("resume", "2", "resume") + if resumed.Paused || resumed.Revision != 3 { + t.Fatal(resumed) + } + cancelled := invoke("cancel", "3", "cancel") + if cancelled.State != "cancelled" || cancelled.Revision != 4 { + t.Fatal(cancelled) + } +} + +func TestReviewOperationControlCLIHelpAndMalformedOffline(t *testing.T) { + id := "review_operation_" + strings.Repeat("a", 32) + for _, args := range [][]string{{"reviews", "operation-control", "--help"}, {"help", "reviews", "operation-control"}} { + code, out, stderr := mutationInvoke(t, "/missing/private-profiles", "absent", args...) + if code != 0 || stderr != "" || !strings.Contains(out, "undispatched") || !strings.Contains(out, "--expect-revision") || !strings.Contains(out, "docs/retained-review-quota-controls.md") { + t.Fatal(code, out, stderr) + } + } + for _, extra := range [][]string{{id, "--action", "pause", "--expect-revision", "1"}, {id, "--action", "stop", "--expect-revision", "1", "--key", "x"}, {id, "--action", "pause", "--expect-revision", "01", "--key", "x"}, {id, "--action", "pause", "--expect-revision", "1", "--key", "x", "--worker", "other"}, {id, "--action", "pause", "--action", "resume", "--expect-revision", "1", "--key", "x"}} { + args := append([]string{"reviews", "operation-control"}, extra...) + code, out, stderr := mutationInvoke(t, "/missing/private-profiles", "absent", args...) + if code != cli.ExitUsage || out != "" || !strings.Contains(stderr, "invalid_arguments") { + t.Fatal(code, out, stderr) + } + } +} + +func TestReviewControlOutputFailureRetainsSameKeyRecovery(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + server := httptest.NewServer(f.handler) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) + code, out, stderr := mutationInvoke(t, profiles, "builder", reviewRequestArgs()...) + var queued struct { + ID string `json:"id"` + } + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &queued) != nil { + t.Fatal(code, out, stderr) + } + args := []string{"--profiles-file", profiles, "--profile", "builder", "reviews", "operation-control", queued.ID, "--action", "pause", "--expect-revision", "1", "--key", "original-control-key"} + var diagnostic strings.Builder + code = cli.RunContext(context.Background(), args, map[string]string{}, roundFailWriter{}, &diagnostic) + if code != cli.ExitConfig || !strings.Contains(diagnostic.String(), `"outcome_unknown":true`) || !strings.Contains(diagnostic.String(), "exact same key") { + t.Fatal(code, diagnostic.String()) + } + code, out, stderr = mutationInvoke(t, profiles, "builder", args[4:]...) + var receipt client.ReviewOperationControlReceipt + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &receipt) != nil || !receipt.Paused || receipt.Revision != 2 { + t.Fatal("same-key recovery changed effect", code, out, stderr) + } +} diff --git a/internal/cli/review_operation_status.go b/internal/cli/review_operation_status.go index 51f79e712..8a4e49656 100644 --- a/internal/cli/review_operation_status.go +++ b/internal/cli/review_operation_status.go @@ -57,7 +57,15 @@ func parseReviewOperationStatus(args []string) (*reviewOperationStatusInvocation } func executeReviewOperationStatus(ctx context.Context, service *client.Client, value *reviewOperationStatusInvocation) (any, error) { if value.Diagnostics { - return service.WaitReviewOperation(ctx, value.ID, value.WaitSeconds) + operation, err := service.WaitReviewOperation(ctx, value.ID, value.WaitSeconds) + if out := client.AgentReviewOperation(operation); out.Diagnostic != nil { + return out, err + } + return operation, err + } + status, err := service.WaitReviewOperationStatus(ctx, value.ID, value.WaitSeconds) + if out := client.AgentReviewOperationStatus(status); out.Diagnostic != nil { + return out, err } - return service.WaitReviewOperationStatus(ctx, value.ID, value.WaitSeconds) + return status, err } diff --git a/internal/cli/review_wait_test.go b/internal/cli/review_wait_test.go index 394b256d9..6b13686fc 100644 --- a/internal/cli/review_wait_test.go +++ b/internal/cli/review_wait_test.go @@ -20,7 +20,7 @@ func TestReviewResultCLIWaitAndDetachUseOneRetainedAction(t *testing.T) { var posts atomic.Int64 var setupStarted atomic.Pointer[time.Time] preferences := make(chan string, 4) - readStarted := make(chan struct{}, 1) + readStarted := make(chan string, 1) service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/reviews/requests") { posts.Add(1) @@ -30,7 +30,7 @@ func TestReviewResultCLIWaitAndDetachUseOneRetainedAction(t *testing.T) { if !boundedReviewWait(r.Header.Get("Prefer"), 900, setupStarted.Load()) { t.Error("operation wait was shortened beyond elapsed setup time") } - readStarted <- struct{}{} + readStarted <- r.Header.Get("Prefer") } f.handler.ServeHTTP(w, r) })) @@ -65,7 +65,11 @@ func TestReviewResultCLIWaitAndDetachUseOneRetainedAction(t *testing.T) { }{code, out.String(), stderr.String()} }() select { - case <-readStarted: + case preference := <-readStarted: + seconds, err := strconv.Atoi(strings.TrimPrefix(preference, "wait=")) + if err != nil || seconds <= 5 || seconds > 900 { + t.Fatal("forwarded wait lost the caller budget or ordinary-deadline coverage", preference, err) + } case <-time.After(2 * time.Second): t.Fatal("explicit wait did not reach operation read") } diff --git a/internal/cli/reviews.go b/internal/cli/reviews.go index 3b0660a61..7b375d63f 100644 --- a/internal/cli/reviews.go +++ b/internal/cli/reviews.go @@ -11,6 +11,11 @@ import ( ) func parseReview(call invocation, args []string) (invocation, bool) { + if call.subcommand == "operation-control" { + var ok bool + call.reviewOperationControl, ok = parseReviewOperationControl(args) + return call, ok + } if call.subcommand == "ci-wait" { var ok bool call.ciWatch, ok = parseCIWatch(args) @@ -158,6 +163,9 @@ func executeReview(ctx context.Context, service *client.Client, call invocation) return client.AgentCIWatch(value), err } switch call.subcommand { + case "operation-control": + in := call.reviewOperationControl + return service.ControlReviewOperation(ctx, in.key, in.id, in.control) case "publication": return service.ReviewCheckpointPublication(ctx, call.position[0]) case "route": diff --git a/internal/client/client.go b/internal/client/client.go index 2dc0c70c3..7883c5dd4 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -349,6 +349,8 @@ func (c *Client) requestBounded(ctx context.Context, method string, segments []s // validates its own limit before transport; ordinary request budgets and shared // transport state remain unchanged. type sourceWaitOptions struct { + operationWait bool + queuedCause *string ciWatchChange, ciWorkflowDetails bool hostedObserver bool seconds int @@ -418,6 +420,9 @@ func (c *Client) requestWithCapabilities(ctx context.Context, method string, seg if wait.ciWorkflowDetails { r.Header.Set("X-FC-CI-Workflow-Details", "3") } + if wait.operationWait { + r.Header.Set("X-FC-Operation-Wait", "3") + } if wait.hostedObserver && method == http.MethodGet { r.Header.Set("X-FC-Hosted-Observer", "1") } @@ -467,6 +472,12 @@ func (c *Client) requestWithCapabilities(ctx context.Context, method string, seg return fail("connection_failed", "The service connection failed.", "Check the configured service address and transport.", 0) } defer response.Body.Close() + if wait != nil && wait.queuedCause != nil { + *wait.queuedCause = "" + if response.Header.Get("X-FC-Review-Queued") == "cli_quota_wait" { + *wait.queuedCause = "cli_quota_wait" + } + } if response.StatusCode >= 300 && response.StatusCode < 400 { if mutation { return unknownRequest("redirect_rejected", operation, "request was redirected", response.StatusCode) @@ -604,6 +615,13 @@ func (c *Client) serviceError(data []byte, status int) (*Error, bool) { } } } + if result.Code == "review_inflight" && status == http.StatusConflict { + result.Message = "This PR and channel already have a pending review request; no new request was accepted." + result.Action = "Inspect existing work with review_operations_list (CLI: reviews operations) and retain the original request. Do not submit another key to bypass it." + if details, ok := result.Details.(map[string]any); ok && details["operation_id"] != nil { + result.Action = "Read and retain the operation in details.operation_id with review_operation_read (CLI: reviews operation). Cancel only with queued-only review_operation_control when cancellation is intended; issued work must follow its original recovery path. Do not submit another key to bypass it." + } + } if result.Status == http.StatusServiceUnavailable && result.Code == "overloaded" { if details, ok := result.Details.(map[string]any); ok && details["reason"] == "result_wait_lifetime" { result.Message = "The controller ended this temporary wait during shutdown." @@ -662,6 +680,10 @@ func (c *Client) safeDetails(value any, code string) any { if n, ok := item.(float64); ok && (n >= 1 || n == 0 && (code == "primary_job_revision_conflict" || code == "checklist_revision_conflict" || code == "worker_pause_revision_conflict" || code == "job_workstream_revision_conflict" || code == "project_presentation_revision_conflict")) && n == float64(int64(n)) && n < 1<<53 { result[key] = int64(n) } + case "operation_id": + if id, ok := item.(string); ok && code == "review_inflight" && ValidateReviewOperationID(id) == nil && !c.sensitive(id) { + result[key] = id + } case "project_id": if id, ok := item.(string); ok && validID(id) && !c.sensitive(id) { result[key] = id diff --git a/internal/client/review_agent_output.go b/internal/client/review_agent_output.go index 24c82b4a8..56cf67258 100644 --- a/internal/client/review_agent_output.go +++ b/internal/client/review_agent_output.go @@ -54,3 +54,62 @@ func AgentReviewRunResult(value ReviewRunResult) any { } return value } + +// Retained wait guidance preserves the original request and never starts work. +type ReviewOperationOutput struct { + ReviewOperation + Diagnostic *ReviewOperationDiagnostic `json:"diagnostic,omitempty"` +} +type ReviewOperationStatusOutput struct { + ReviewOperationStatus + Diagnostic *ReviewOperationDiagnostic `json:"diagnostic,omitempty"` +} + +func retainedWaitDiagnostic(wait *ReviewOperationWait, channel, state, reason, queuedCause string) *ReviewOperationDiagnostic { + if wait != nil { + if diagnostic := operationWaitDiagnostic(wait, channel); diagnostic != nil { + return diagnostic + } + } + if state == "queued" && channel == "cli" && queuedCause == "cli_quota_wait" { + return &ReviewOperationDiagnostic{"This request is queued for shared CLI quota rechecks; no review is running.", "Keep this original request queued and continue other work. Do not submit a duplicate or reset rounds."} + } + if state == "held" && channel == "cli" && reason == "allowance_exhausted" { + return &ReviewOperationDiagnostic{"This historical CLI quota hold is terminal; it completed no review.", "If still authorized, retry later with a new request and current configuration/head. The original key replays this hold."} + } + return nil +} +func AgentReviewOperation(value ReviewOperation) ReviewOperationOutput { + return ReviewOperationOutput{value, retainedWaitDiagnostic(value.Wait, value.Channel, value.State, value.Reason, value.queuedCause)} +} +func AgentReviewOperationStatus(value ReviewOperationStatus) ReviewOperationStatusOutput { + out := ReviewOperationStatusOutput{value, retainedWaitDiagnostic(value.Wait, value.Channel, value.State, value.Reason, value.queuedCause)} + if value.State == "held" && value.Channel == "cli" && value.Reason == "allowance_exhausted" { + out.NextAction = "retry_later_with_new_request" + } + return out +} +func operationWaitDiagnostic(w *ReviewOperationWait, channel string) *ReviewOperationDiagnostic { + if channel == "cli" && w.RetryNotBefore != "" { + if w.Paused { + return &ReviewOperationDiagnostic{"This CLI request is paused before dispatch. Its comparison and quota-recheck schedule are retained; no review is running.", "Resume or cancel this same undispatched request with current revision/key. Resume preserves the comparison and still rechecks shared account quota and admission. It does not grant allowance or interrupt another review."} + } + return &ReviewOperationDiagnostic{"Included CLI quota was exhausted. This same request remains queued and automatically rechecks at or after retry_not_before, using bounded backoff shared across projects on the provider account. This is a server recheck time, not the provider reset or a promised start; no review is running.", "Keep this original request queued and continue other work. Pause/cancel only the undispatched request if needed; do not submit a duplicate or reset rounds. Before starting, the controller rechecks the pinned comparison, access, findings, publication safety and current allowance. A changed comparison is held for requalification rather than silently followed."} + } + scope, candidates := "", "" + if w.RetryNotBefore != "" { + scope = " This deadline schedules this request only; the provider limit’s scope across other PRs, repositories or accounts is unknown." + candidates = " Other authorized candidates still need their own admission and fresh provider checks." + } + if w.Paused { + retained := "Its review intent is retained; no retry deadline is recorded and no review is running." + if w.RetryNotBefore != "" { + retained = "Its retry deadline and review intent are retained; no review is running." + } + return &ReviewOperationDiagnostic{"This same operation is paused before provider dispatch. " + retained + scope, "Resume/cancel only this undispatched operation with current revision/key. Pause/resume cannot edit head or out-of-order intent. For an authorized replacement, follow review_operation_control guidance and respect any known cooldown; its timer is not transferred." + candidates} + } + if w.RetryNotBefore != "" { + return &ReviewOperationDiagnostic{"The provider reported a cooldown. This same operation automatically rechecks admission and allowance at or after retry_not_before; the deadline is not a reserved start time or review completion." + scope, "Keep this request for automatic retry. For an authorized intent change, see queued-only review_operation_control cancellation (CLI reviews operation-control); respect the known cooldown because its timer is not transferred. Pause/resume cannot edit head or out-of-order intent." + candidates} + } + return nil +} diff --git a/internal/client/review_agent_output_test.go b/internal/client/review_agent_output_test.go index 19af79c58..c3ed74e66 100644 --- a/internal/client/review_agent_output_test.go +++ b/internal/client/review_agent_output_test.go @@ -62,3 +62,16 @@ func TestAgentSelectionSourceHoldIsBoundedAndNeverReplacesChild(t *testing.T) { } } } + +func TestPausedReviewGuidanceRequiresRecordedDeadline(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + absent := operationWaitDiagnostic(&ReviewOperationWait{Paused: true}, channel) + if !strings.Contains(absent.Explanation, "no retry deadline is recorded") || strings.Contains(absent.Explanation, "retry deadline and review intent are retained") { + t.Fatal(channel, absent) + } + present := operationWaitDiagnostic(&ReviewOperationWait{Paused: true, RetryNotBefore: "2026-11-09T09:00:00Z"}, channel) + if strings.Contains(present.Explanation, "no retry deadline is recorded") { + t.Fatal(channel, present) + } + } +} diff --git a/internal/client/review_allowance_validation_test.go b/internal/client/review_allowance_validation_test.go new file mode 100644 index 000000000..859f943b3 --- /dev/null +++ b/internal/client/review_allowance_validation_test.go @@ -0,0 +1,68 @@ +package client + +import ( + "strings" + "testing" +) + +func TestRetainedAllowanceValidation(t *testing.T) { + zero, limit, full, window := int64(0), int64(8), int64(1000), int64(3600000) + baseline := ReviewOperation{Channel: "cli", State: "held", Reason: "allowance_exhausted", AttemptID: "review_attempt_" + strings.Repeat("a", 32), Allowance: &ReviewAllowanceObservation{Kind: "cli_exhausted", ObservedAt: "2026-01-01T00:00:00Z", Remaining: &zero, Limit: &limit, FullCapacityInMS: &full, RollingWindowMS: &window}} + for _, test := range []struct { + name string + mutate func(*ReviewOperation) + valid bool + }{ + {"valid", func(*ReviewOperation) {}, true}, + {"absent legacy observation", func(v *ReviewOperation) { v.Allowance = nil }, true}, + {"queued cannot be terminal exhaustion", func(v *ReviewOperation) { v.State = "queued" }, false}, + {"wrong channel", func(v *ReviewOperation) { v.Channel = "hosted" }, false}, + {"missing attempt", func(v *ReviewOperation) { v.AttemptID = "" }, false}, + {"missing observed time", func(v *ReviewOperation) { v.Allowance.ObservedAt = "" }, false}, + {"noncanonical time", func(v *ReviewOperation) { v.Allowance.ObservedAt = "2026-01-01T00:00:00+00:00" }, false}, + {"missing full capacity", func(v *ReviewOperation) { v.Allowance.FullCapacityInMS = nil }, false}, + {"cli cannot claim reset", func(v *ReviewOperation) { v.Allowance.RetryNotBefore = "2026-01-01T01:00:00Z" }, false}, + {"nonzero remaining", func(v *ReviewOperation) { n := int64(1); v.Allowance.Remaining = &n }, false}, + {"zero limit", func(v *ReviewOperation) { n := int64(0); v.Allowance.Limit = &n }, false}, + {"limit above maximum", func(v *ReviewOperation) { n := int64(10001); v.Allowance.Limit = &n }, false}, + {"negative full capacity", func(v *ReviewOperation) { n := int64(-1); v.Allowance.FullCapacityInMS = &n }, false}, + {"full capacity above maximum", func(v *ReviewOperation) { n := int64(86400001); v.Allowance.FullCapacityInMS = &n }, false}, + {"zero rolling window", func(v *ReviewOperation) { n := int64(0); v.Allowance.RollingWindowMS = &n }, false}, + {"rolling window above maximum", func(v *ReviewOperation) { n := int64(86400001); v.Allowance.RollingWindowMS = &n }, false}, + {"minimum limit", func(v *ReviewOperation) { n := int64(1); v.Allowance.Limit = &n }, true}, + {"maximum limit", func(v *ReviewOperation) { n := int64(10000); v.Allowance.Limit = &n }, true}, + {"minimum full capacity", func(v *ReviewOperation) { n := int64(0); v.Allowance.FullCapacityInMS = &n }, true}, + {"maximum full capacity", func(v *ReviewOperation) { n := int64(86400000); v.Allowance.FullCapacityInMS = &n }, true}, + {"minimum rolling window", func(v *ReviewOperation) { n := int64(1); v.Allowance.RollingWindowMS = &n }, true}, + {"maximum rolling window", func(v *ReviewOperation) { n := int64(86400000); v.Allowance.RollingWindowMS = &n }, true}, + {"missing rolling window", func(v *ReviewOperation) { v.Allowance.RollingWindowMS = nil }, false}, + {"unknown kind", func(v *ReviewOperation) { v.Allowance.Kind = "available" }, false}, + } { + t.Run(test.name, func(t *testing.T) { + v := baseline + a := *baseline.Allowance + v.Allowance = &a + test.mutate(&v) + if validReviewAllowance(v) != test.valid { + t.Fatal("incorrect allowance acceptance") + } + }) + } + hosted := ReviewOperation{Channel: "hosted", State: "held", Reason: "hosted_allowance_cooldown", AttemptID: baseline.AttemptID, Allowance: &ReviewAllowanceObservation{Kind: "hosted_cooldown", ObservedAt: "2026-01-01T00:00:00Z", RetryNotBefore: "2026-01-01T01:00:00Z"}} + if !validReviewAllowance(hosted) { + t.Fatal("valid hosted cooldown rejected") + } + for _, retry := range []string{"", "2026-01-01T01:00:00+00:00"} { + candidate := hosted + a := *hosted.Allowance + candidate.Allowance = &a + candidate.Allowance.RetryNotBefore = retry + if validReviewAllowance(candidate) { + t.Fatal("hosted cooldown accepted missing/noncanonical retry", retry) + } + } + hosted.Allowance.Remaining = &zero + if validReviewAllowance(hosted) { + t.Fatal("hosted cooldown accepted invented CLI balance") + } +} diff --git a/internal/client/review_cli_wait_test.go b/internal/client/review_cli_wait_test.go new file mode 100644 index 000000000..cdada41c5 --- /dev/null +++ b/internal/client/review_cli_wait_test.go @@ -0,0 +1,218 @@ +package client_test + +import ( + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/client" +) + +func TestCLIQuotaWaitHTTPFullAndCompact(t *testing.T) { + for _, compact := range []bool{false, true} { + for _, paused := range []bool{false, true} { + for _, sharedOnly := range []bool{false, true} { + t.Run(strings.Join([]string{boolName(compact), boolName(paused), boolName(sharedOnly)}, "/"), func(t *testing.T) { + op := sampleReviewOperation() + op.Channel, op.State, op.AttemptID, op.Reason = "cli", "queued", "", "" + if !sharedOnly { + op.Wait = &client.ReviewOperationWait{BaselineAttemptID: "review_attempt_" + strings.Repeat("b", 32), RetryNotBefore: "2026-01-01T00:10:00Z", Paused: paused} + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-FC-Review-Queued", "cli_quota_wait") + if compact { + _ = json.NewEncoder(w).Encode(client.ReviewOperationStatus{ID: op.ID, PullNumber: op.PullNumber, Channel: op.Channel, State: op.State, Revision: op.Revision, Stage: "queued", UpdatedAt: op.UpdatedAt, NextAction: "wait", Wait: op.Wait}) + } else { + _ = json.NewEncoder(w).Encode(op) + } + })) + defer server.Close() + c := newClient(t, server) + var diagnostic *client.ReviewOperationDiagnostic + if compact { + got, err := c.ReviewOperationStatus(t.Context(), op.ID) + if err != nil { + t.Fatal(err) + } + out := client.AgentReviewOperationStatus(got) + if !reflect.DeepEqual(got.Wait, op.Wait) || out.NextAction != "wait" || out.AttemptID != "" { + t.Fatal("original queued intent changed", out) + } + diagnostic = out.Diagnostic + } else { + got, err := c.ReviewOperation(t.Context(), op.ID) + if err != nil { + t.Fatal(err) + } + out := client.AgentReviewOperation(got) + if !reflect.DeepEqual(got.Wait, op.Wait) || out.State != "queued" || out.AttemptID != "" { + t.Fatal("original queued intent changed", out) + } + diagnostic = out.Diagnostic + } + if diagnostic == nil { + t.Fatal("missing quota guidance") + } + if paused && !sharedOnly { + if !strings.Contains(diagnostic.Explanation, "paused") || !strings.Contains(diagnostic.NextAction, "Resume or cancel this same") { + t.Fatal(diagnostic) + } + } else if !strings.Contains(diagnostic.Explanation, "quota") || !strings.Contains(diagnostic.NextAction, "original request queued") { + t.Fatal(diagnostic) + } + if strings.Contains(diagnostic.Explanation, "provider reported a cooldown") || strings.Contains(diagnostic.NextAction, "fresh key") { + t.Fatal("wait was turned into a terminal/manual retry", diagnostic) + } + if !sharedOnly && !paused && !strings.Contains(diagnostic.Explanation, "not the provider reset") { + t.Fatal("retry time looks like provider reset", diagnostic) + } + }) + } + } + } +} + +func TestHistoricalCLIQuotaHoldRemainsTerminal(t *testing.T) { + status := client.ReviewOperationStatus{Channel: "cli", State: "held", Reason: "allowance_exhausted", NextAction: "read_diagnostics"} + out := client.AgentReviewOperationStatus(status) + if out.State != "held" || out.Wait != nil || out.NextAction != "retry_later_with_new_request" { + t.Fatal("old terminal hold reopened", out) + } +} + +func TestReviewInflightRetainsOnlyValidatedOperationHandle(t *testing.T) { + for _, tc := range []struct { + name, code string + status int + details any + keep bool + }{ + {"valid", "review_inflight", http.StatusConflict, map[string]any{"operation_id": executionOperationID, "private": "UNTRUSTED_DETAIL"}, true}, + {"missing", "review_inflight", http.StatusConflict, nil, false}, + {"wrong-kind", "review_inflight", http.StatusConflict, map[string]any{"operation_id": "review_attempt_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, false}, + {"uppercase", "review_inflight", http.StatusConflict, map[string]any{"operation_id": strings.ToUpper(executionOperationID)}, false}, + {"numeric", "review_inflight", http.StatusConflict, map[string]any{"operation_id": 1}, false}, + {"wrong-status", "review_inflight", http.StatusBadRequest, map[string]any{"operation_id": executionOperationID}, true}, + {"wrong-code", "review_conflict", http.StatusConflict, map[string]any{"operation_id": executionOperationID}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var posts atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/instance") { + handshake(w) + return + } + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/reviews/requests") || r.Header.Get("Idempotency-Key") != "inflight-refusal" { + t.Error("inflight refusal caused unexpected follow-up work", r.Method, r.URL.Path) + } + posts.Add(1) + failure := map[string]any{"code": tc.code, "message": "Existing review request."} + if tc.details != nil { + failure["details"] = tc.details + } + write(w, tc.status, map[string]any{"error": failure, "request_id": "request-inflight"}) + })) + defer srv.Close() + c := newClient(t, srv) + value, err := c.RequestReview(t.Context(), "inflight-refusal", client.ReviewRequest{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)}, 0) + var failure *client.Error + if value.Receipt != nil || value.Operation != nil || !errors.As(err, &failure) || failure.Code != tc.code || failure.OutcomeUnknown || posts.Load() != 1 { + t.Fatal("refusal was treated as acceptance or retried", value, err) + } + if tc.code == "review_inflight" && tc.status == http.StatusConflict { + if !strings.Contains(failure.Action, "Do not submit another key") || strings.Contains(failure.Action, "current access") { + t.Fatal("pending work refusal lacks safe recovery guidance", failure.Action) + } + if tc.keep && (!strings.Contains(failure.Action, "details.operation_id") || !strings.Contains(failure.Action, "queued-only")) { + t.Fatal("valid handle lacks operation guidance", failure.Action) + } + if !tc.keep && strings.Contains(failure.Action, "details.operation_id") { + t.Fatal("guidance refers to a missing handle", failure.Action) + } + } else if strings.Contains(failure.Action, "Do not submit another key") { + t.Fatal("unrelated refusal acquired pending work guidance", failure.Action) + } + if tc.keep { + details, ok := failure.Details.(map[string]any) + if !ok || len(details) != 1 || details["operation_id"] != executionOperationID { + t.Fatal("validated pending-operation handle was dropped", failure.Details) + } + } else if failure.Details != nil { + t.Fatal("malformed or unrelated operation ID survived filtering", failure.Details) + } + }) + } +} + +func TestCLISharedQuotaGuidanceSurvivesResumedWait(t *testing.T) { + for _, compact := range []bool{false, true} { + for _, sharedQuota := range []bool{false, true} { + t.Run(strings.Join([]string{boolName(compact), boolName(sharedQuota)}, "/"), func(t *testing.T) { + op := sampleReviewOperation() + // Pause/resume leaves a valid retained row with no baseline or deadline. + op.Wait = &client.ReviewOperationWait{Paused: false} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + if r.Method != http.MethodGet { + t.Error("reading quota guidance started a mutation", r.Method) + } + w.Header().Set("Content-Type", "application/json") + if sharedQuota { + w.Header().Set("X-FC-Review-Queued", "cli_quota_wait") + } + if compact { + _ = json.NewEncoder(w).Encode(client.ReviewOperationStatus{ID: op.ID, PullNumber: op.PullNumber, Channel: op.Channel, State: op.State, Revision: op.Revision, Stage: "queued", UpdatedAt: op.UpdatedAt, NextAction: "wait", Wait: op.Wait}) + } else { + _ = json.NewEncoder(w).Encode(op) + } + })) + defer server.Close() + c := newClient(t, server) + var diagnostic *client.ReviewOperationDiagnostic + if compact { + got, err := c.ReviewOperationStatus(t.Context(), op.ID) + if err != nil { + t.Fatal(err) + } + out := client.AgentReviewOperationStatus(got) + if !reflect.DeepEqual(out.Wait, op.Wait) || out.ID != op.ID || out.State != "queued" || out.AttemptID != "" || out.NextAction != "wait" { + t.Fatal("resumed request changed", out) + } + diagnostic = out.Diagnostic + } else { + got, err := c.ReviewOperation(t.Context(), op.ID) + if err != nil { + t.Fatal(err) + } + out := client.AgentReviewOperation(got) + if !reflect.DeepEqual(out.Wait, op.Wait) || out.ID != op.ID || out.State != "queued" || out.AttemptID != "" { + t.Fatal("resumed request changed", out) + } + diagnostic = out.Diagnostic + } + if !sharedQuota { + if diagnostic != nil { + t.Fatal("empty wait invented quota guidance", diagnostic) + } + return + } + if diagnostic == nil || !strings.Contains(diagnostic.Explanation, "quota") || !strings.Contains(diagnostic.NextAction, "original request queued") || strings.Contains(diagnostic.NextAction, "new request") { + t.Fatal("resumed wait lost original-request quota guidance", diagnostic) + } + }) + } + } +} diff --git a/internal/client/review_execution.go b/internal/client/review_execution.go index e612b1ce8..f039b8dcf 100644 --- a/internal/client/review_execution.go +++ b/internal/client/review_execution.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "net/http" + "time" ) // ReviewExecutionConfiguration contains stored project settings only. It does @@ -50,6 +51,11 @@ func (r ReviewRequestResult) MarshalJSON() ([]byte, error) { } type ReviewOperation struct { + AllowOutOfOrder bool `json:"allow_out_of_order,omitempty"` + OverrideFileLimit bool `json:"override_file_limit,omitempty"` + queuedCause string + Wait *ReviewOperationWait `json:"wait,omitempty"` + Allowance *ReviewAllowanceObservation `json:"allowance,omitempty"` Observer *ReviewHostedObserverStatus `json:"observer,omitempty"` ID string `json:"id"` ProjectID string `json:"project_id"` @@ -69,6 +75,40 @@ type ReviewOperation struct { UpdatedAt string `json:"updated_at"` } +// ReviewAllowanceObservation describes this held attempt's retained facts, not +// current account availability or permission to start another review. +type ReviewAllowanceObservation struct { + Kind string `json:"kind"` + ObservedAt string `json:"observed_at"` + Remaining *int64 `json:"remaining,omitempty"` + Limit *int64 `json:"limit,omitempty"` + FullCapacityInMS *int64 `json:"full_capacity_in_ms,omitempty"` + RollingWindowMS *int64 `json:"rolling_window_ms,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` +} + +func validAllowanceTime(value string) bool { + parsed, err := time.Parse(time.RFC3339Nano, value) + return err == nil && !parsed.IsZero() && parsed.UTC().Format(time.RFC3339Nano) == value +} + +func validReviewAllowance(value ReviewOperation) bool { + a := value.Allowance + if a == nil { + return true + } + if value.State != "held" || value.AttemptID == "" || !validAllowanceTime(a.ObservedAt) { + return false + } + switch a.Kind { + case "cli_exhausted": + return value.Channel == "cli" && value.Reason == "allowance_exhausted" && a.Remaining != nil && *a.Remaining == 0 && a.Limit != nil && *a.Limit >= 1 && *a.Limit <= 10000 && a.FullCapacityInMS != nil && *a.FullCapacityInMS >= 0 && *a.FullCapacityInMS <= 86400000 && a.RollingWindowMS != nil && *a.RollingWindowMS >= 1 && *a.RollingWindowMS <= 86400000 && a.RetryNotBefore == "" + case "hosted_cooldown": + return value.Channel == "hosted" && value.Reason == "hosted_allowance_cooldown" && a.Remaining == nil && a.Limit == nil && a.FullCapacityInMS == nil && a.RollingWindowMS == nil && validAllowanceTime(a.RetryNotBefore) + } + return false +} + func validExecutionIdentifier(value string) bool { if len(value) == 0 || len(value) > 128 { return false @@ -142,7 +182,7 @@ func (c *Client) RequestReview(ctx context.Context, key string, request ReviewRe result.Receipt = &ReviewRequestReceipt{} return decodeReviewResponse(data, result.Receipt) } - if err := c.requestBoundedOptions(ctx, http.MethodPost, c.projectPath("reviews", "requests"), nil, true, key, body, http.StatusAccepted, true, &result, 4<<20, decode, &sourceWaitOptions{seconds: waitSeconds, status: &status}); err != nil { + if err := c.requestBoundedOptions(ctx, http.MethodPost, c.projectPath("reviews", "requests"), nil, true, key, body, http.StatusAccepted, true, &result, 4<<20, decode, &sourceWaitOptions{seconds: waitSeconds, status: &status, operationWait: true}); err != nil { return ReviewRequestResult{}, err } valid := false @@ -173,7 +213,7 @@ func (c *Client) WaitReviewOperation(ctx context.Context, id string, waitSeconds var status int err := resumeResultWait(ctx, waitSeconds, func(ctx context.Context, remaining int) error { value = ReviewOperation{} - return c.requestBoundedOptions(ctx, http.MethodGet, c.projectPath("reviews", "operations", id), nil, true, "", nil, http.StatusOK, false, &value, 4<<20, decodeReviewResponse, &sourceWaitOptions{seconds: remaining, status: &status, hostedObserver: true}) + return c.requestBoundedOptions(ctx, http.MethodGet, c.projectPath("reviews", "operations", id), nil, true, "", nil, http.StatusOK, false, &value, 4<<20, decodeReviewResponse, &sourceWaitOptions{seconds: remaining, status: &status, hostedObserver: true, operationWait: true, queuedCause: &value.queuedCause}) }) if err != nil { return ReviewOperation{}, reviewWaitTargetError(err, id) @@ -188,5 +228,5 @@ func (c *Client) validReviewOperation(value ReviewOperation) bool { if !validReviewHostedObserver(value.Observer, value.Channel, value.State, value.AttemptID) { return false } - return ValidateReviewOperationID(value.ID) == nil && value.ProjectID == c.identity.ProjectID && validExecutionIdentifier(value.ProjectID) && validExecutionIdentifier(value.ActorID) && (value.WorkerID == "" || validExecutionIdentifier(value.WorkerID)) && value.ConfigurationRevision >= 1 && value.PolicyRevision >= 0 && (value.CapabilityFingerprint == "" || controlHex(value.CapabilityFingerprint, 64)) && validPullNumber(value.PullNumber) && oneReviewOf(value.Channel, "cli", "hosted") && controlHex(value.HeadSHA, 40) && oneReviewOf(value.State, "queued", "preparing", "posting", "active", "completed", "failed", "cancelled", "rate_limited", "uncertain", "held") && value.Revision >= 1 && (value.Reason == "" || validExecutionIdentifier(value.Reason)) && (value.AttemptID == "" || validReviewOpaqueID(value.AttemptID, "review_attempt_")) && controlTime(value.CreatedAt) && controlTime(value.UpdatedAt) + return ValidateReviewOperationID(value.ID) == nil && value.ProjectID == c.identity.ProjectID && validExecutionIdentifier(value.ProjectID) && validExecutionIdentifier(value.ActorID) && (value.WorkerID == "" || validExecutionIdentifier(value.WorkerID)) && value.ConfigurationRevision >= 1 && value.PolicyRevision >= 0 && (value.CapabilityFingerprint == "" || controlHex(value.CapabilityFingerprint, 64)) && validPullNumber(value.PullNumber) && oneReviewOf(value.Channel, "cli", "hosted") && controlHex(value.HeadSHA, 40) && oneReviewOf(value.State, "queued", "preparing", "posting", "active", "completed", "failed", "cancelled", "rate_limited", "uncertain", "held") && value.Revision >= 1 && (value.Reason == "" || validExecutionIdentifier(value.Reason)) && (value.AttemptID == "" || validReviewOpaqueID(value.AttemptID, "review_attempt_")) && controlTime(value.CreatedAt) && controlTime(value.UpdatedAt) && validReviewOperationWait(value.Wait, value.Channel, value.State, value.AttemptID) && validReviewAllowance(value) } diff --git a/internal/client/review_operation_control.go b/internal/client/review_operation_control.go new file mode 100644 index 000000000..b6f22bde1 --- /dev/null +++ b/internal/client/review_operation_control.go @@ -0,0 +1,97 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "math" + "net/http" +) + +// ReviewOperationWait retains the same request while no provider action is running. +// A retry deadline is the earliest automatic recheck, not a promised start time. +type ReviewOperationWait struct { + CLIAllowance *ReviewAllowanceObservation `json:"cli_allowance,omitempty"` + BaselineAttemptID string `json:"baseline_attempt_id,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` + Paused bool `json:"paused"` +} + +func validReviewOperationWait(w *ReviewOperationWait, channel, state, attempt string) bool { + if w == nil { + return true + } + if state != "queued" || attempt != "" { + return false + } + if w.CLIAllowance != nil { + // These are the original exhausted baseline's facts, not new quota. + baseline := ReviewOperation{Channel: channel, State: "held", Reason: "allowance_exhausted", AttemptID: w.BaselineAttemptID, Allowance: w.CLIAllowance} + if channel != "cli" || !validReviewAllowance(baseline) { + return false + } + } + if w.BaselineAttemptID == "" { + return w.RetryNotBefore == "" + } + return oneReviewOf(channel, "cli", "hosted") && validReviewOpaqueID(w.BaselineAttemptID, "review_attempt_") && validAllowanceTime(w.RetryNotBefore) +} + +type ReviewOperationControl struct { + ExpectedRevision int64 `json:"expected_revision"` + Action string `json:"action"` +} + +type ReviewOperationControlReceipt struct { + ID string `json:"id"` + State string `json:"state"` + Revision int64 `json:"revision"` + Paused bool `json:"paused"` + RetryNotBefore string `json:"retry_not_before,omitempty"` +} + +func ValidateReviewOperationControl(id string, v ReviewOperationControl) error { + if ValidateReviewOperationID(id) != nil || v.ExpectedRevision < 1 || v.ExpectedRevision == math.MaxInt64 || !oneReviewOf(v.Action, "pause", "resume", "cancel") { + return mutationValidation() + } + return nil +} + +// ControlReviewOperation only changes an undispatched queued intent. +// It never claims to cancel an issued provider request or changes review allowance. +func (c *Client) ControlReviewOperation(ctx context.Context, key, id string, v ReviewOperationControl) (ReviewOperationControlReceipt, error) { + if !validMutationKey(key) || ValidateReviewOperationControl(id, v) != nil { + return ReviewOperationControlReceipt{}, mutationValidation() + } + body, _ := json.Marshal(v) + var out ReviewOperationControlReceipt + if err := c.requestBounded(ctx, http.MethodPost, c.projectPath("reviews", "operations", id, "control"), nil, true, key, body, http.StatusOK, true, &out, 16<<10, decodeReviewResponse); err != nil { + var failure *Error + if errors.As(err, &failure) && failure.Code == "review_conflict" && failure.Status == http.StatusConflict { + copy := *failure + copy.Message = "This operation's revision changed or cannot advance." + copy.Action = "Read this same operation's current state before deciding on a new control action; rereading cannot resolve a revision at the maximum value. To recover an unknown outcome, retain the original authenticated principal, project, worker, exact request body, operation ID and idempotency key rather than choosing a new action or key." + return ReviewOperationControlReceipt{}, © + } + if errors.As(err, &failure) && failure.Code == "review_operation_started" && failure.Status == http.StatusConflict { + copy := *failure + copy.Message = "This operation is no longer an undispatched queued request." + copy.Action = "Read this same operation for its current state. No provider cancellation occurred. Queued-only controls cannot reopen a held target_changed; follow its recovery diagnostic. Do not submit a replacement for posting, active or uncertain work." + return ReviewOperationControlReceipt{}, © + } + return out, err + } + valid := out.ID == id && out.Revision == v.ExpectedRevision+1 && (out.RetryNotBefore == "" || validAllowanceTime(out.RetryNotBefore)) + switch v.Action { + case "pause": + valid = valid && out.State == "queued" && out.Paused + case "resume": + valid = valid && out.State == "queued" && !out.Paused + case "cancel": + valid = valid && out.State == "cancelled" && !out.Paused + } + if !valid { + return ReviewOperationControlReceipt{}, unknownMutation("invalid_response", "The service returned invalid operation control facts; its outcome is unknown.", http.StatusOK) + } + return out, nil +} diff --git a/internal/client/review_operation_control_test.go b/internal/client/review_operation_control_test.go new file mode 100644 index 000000000..f9cba2ab3 --- /dev/null +++ b/internal/client/review_operation_control_test.go @@ -0,0 +1,497 @@ +package client_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "github.com/benhook1013/FireController/internal/client" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestReviewOperationWaitNegotiatedFullCompactAndLegacy(t *testing.T) { + for _, compact := range []bool{false, true} { + for _, paused := range []bool{false, true} { + for _, legacy := range []bool{false, true} { + t.Run(strings.Join([]string{boolName(compact), boolName(paused), boolName(legacy)}, "/"), func(t *testing.T) { + op := sampleReviewOperation() + op.Channel = "hosted" + op.State = "queued" + op.AttemptID = "" + op.Reason = "" + wait := &client.ReviewOperationWait{BaselineAttemptID: "review_attempt_" + strings.Repeat("b", 32), RetryNotBefore: "2026-01-01T00:10:00Z", Paused: paused} + if !legacy { + op.Wait = wait + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + w.Header().Set("Content-Type", "application/json") + if r.Header.Get("X-FC-Operation-Wait") != "3" { + t.Error("wait extension not negotiated") + } + if compact { + _ = json.NewEncoder(w).Encode(client.ReviewOperationStatus{ID: op.ID, PullNumber: op.PullNumber, Channel: op.Channel, State: op.State, Revision: op.Revision, Stage: "queued", Reason: "", AttemptID: "", UpdatedAt: op.UpdatedAt, NextAction: "wait", Wait: op.Wait}) + } else { + _ = json.NewEncoder(w).Encode(op) + } + })) + defer server.Close() + c := newClient(t, server) + if compact { + v, err := c.ReviewOperationStatus(t.Context(), op.ID) + if err != nil || (v.Wait == nil) != legacy || v.Wait != nil && *v.Wait != *wait { + t.Fatal(v, err) + } + } else { + v, err := c.ReviewOperation(t.Context(), op.ID) + if err != nil || (v.Wait == nil) != legacy || v.Wait != nil && *v.Wait != *wait { + t.Fatal(v, err) + } + } + }) + } + } + } +} +func boolName(v bool) string { + if v { + return "true" + } + return "false" +} + +func TestReviewOperationControlBoundSingleShotAndMalformed(t *testing.T) { + id := "review_operation_" + strings.Repeat("a", 32) + var requests atomic.Int64 + for _, action := range []string{"pause", "resume", "cancel"} { + t.Run(action, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + w.Header().Set("Content-Type", "application/json") + requests.Add(1) + body, _ := io.ReadAll(r.Body) + want := `{"expected_revision":3,"action":"` + action + `"}` + if r.Method != "POST" || r.URL.Path != "/api/v1/projects/project-one/reviews/operations/"+id+"/control" || r.Header.Get("Idempotency-Key") != "same-key" || r.Header.Get("X-FC-Worker") != "worker-one" || string(body) != want { + t.Error("bound exact control changed", r.URL, string(body)) + } + state := "queued" + if action == "cancel" { + state = "cancelled" + } + _ = json.NewEncoder(w).Encode(client.ReviewOperationControlReceipt{ID: id, State: state, Revision: 4, Paused: action == "pause", RetryNotBefore: "2026-01-01T00:10:00Z"}) + })) + defer server.Close() + c := newClient(t, server) + v, err := c.ControlReviewOperation(t.Context(), "same-key", id, client.ReviewOperationControl{ExpectedRevision: 3, Action: action}) + if err != nil || v.Revision != 4 || v.ID != id { + t.Fatal(v, err) + } + before := requests.Load() + for _, bad := range []client.ReviewOperationControl{{ExpectedRevision: 0, Action: action}, {ExpectedRevision: 3, Action: "stop"}} { + _, err := c.ControlReviewOperation(t.Context(), "same-key", id, bad) + if err == nil { + t.Fatal("bad control accepted") + } + } + _, err = c.ControlReviewOperation(t.Context(), "same-key", "bad", client.ReviewOperationControl{ExpectedRevision: 3, Action: action}) + if err == nil || requests.Load() != before { + t.Fatal("malformed contacted service") + } + }) + } +} + +func TestReviewOperationWaitRejectsMalformedFacts(t *testing.T) { + for _, bad := range []string{`null`, `{"paused":null}`, `{"paused":true,"retry_not_before":"2026-01-01T00:10:00Z"}`, `{"paused":false,"baseline_attempt_id":"review_attempt_` + strings.Repeat("a", 32) + `"}`, `{"paused":true,"private":"secret"}`, `{"paused":false,"paused":true}`} { + t.Run(bad, func(t *testing.T) { + op := sampleReviewOperation() + op.Channel = "hosted" + op.State = "queued" + op.AttemptID = "" + raw, _ := json.Marshal(op) + raw = append(raw[:len(raw)-1], []byte(`,"wait":`+bad+`}`)...) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write(raw) + })) + defer server.Close() + _, err := newClient(t, server).ReviewOperation(t.Context(), op.ID) + if err == nil { + t.Fatal("malformed wait accepted") + } + }) + } +} + +func TestReviewOperationControlActualWriterReadAndProjectIsolation(t *testing.T) { + f, _ := executionFixture(t) + for token, permissions := range map[string][]string{"synthetic-writer": {"read", "write"}, "synthetic-reader": {"read"}} { + sum := sha256.Sum256([]byte(token)) + f.call(t, "POST", "/api/v1/projects/"+f.project+"/credentials", f.admin, f.sender, map[string]any{"token_sha256": hex.EncodeToString(sum[:]), "permissions": permissions}) + } + srv := httptest.NewServer(f.handler) + defer srv.Close() + writer := f.newClient(t, "synthetic-writer", f.sender, srv.URL) + peer := f.newClient(t, "synthetic-writer", f.recipient, srv.URL) + reader := f.newClient(t, "synthetic-reader", f.sender, srv.URL) + queued, err := queuedReviewRequest(t, writer, t.Context(), "request", client.ReviewRequest{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "cli", HeadSHA: strings.Repeat("a", 40)}) + if err != nil { + t.Fatal(err) + } + before, err := reader.ReviewOperation(t.Context(), queued.ID) + if err != nil { + t.Fatal(err) + } + _, err = reader.ControlReviewOperation(t.Context(), "reader-pause", queued.ID, client.ReviewOperationControl{ExpectedRevision: 1, Action: "pause"}) + checkError(t, err, "forbidden") + paused, err := peer.ControlReviewOperation(t.Context(), "peer-pause", queued.ID, client.ReviewOperationControl{ExpectedRevision: 1, Action: "pause"}) + if err != nil || !paused.Paused { + t.Fatal(paused, err) + } + after, err := reader.ReviewOperation(t.Context(), queued.ID) + if err != nil || after.ActorID != before.ActorID || after.WorkerID != f.sender || after.Wait == nil || !after.Wait.Paused { + t.Fatal(after, err) + } + foreign := mutationFixture{store: f.store, admin: f.admin, tokenFile: f.tokenFile} + foreign.project = f.call(t, "POST", "/api/v1/projects", f.admin, "", map[string]any{"name": "Other", "repository": "other/repository"})["id"].(string) + otherWorker := f.call(t, "POST", "/api/v1/projects/"+foreign.project+"/workers", f.admin, "", map[string]any{"name": "Other"})["id"].(string) + _, err = foreign.newClient(t, f.admin, otherWorker, srv.URL).ControlReviewOperation(t.Context(), "foreign-pause", queued.ID, client.ReviewOperationControl{ExpectedRevision: 2, Action: "pause"}) + checkError(t, err, "not_found") + _, err = peer.ControlReviewOperation(t.Context(), "cancel", queued.ID, client.ReviewOperationControl{ExpectedRevision: 2, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + _, err = peer.ControlReviewOperation(t.Context(), "cannot-resume", queued.ID, client.ReviewOperationControl{ExpectedRevision: 3, Action: "resume"}) + var failure *client.Error + if !errors.As(err, &failure) || failure.Code != "review_operation_started" || !strings.Contains(failure.Action, "No provider cancellation occurred") || !strings.Contains(failure.Action, "held target_changed") || !strings.Contains(failure.Action, "Do not submit a replacement for posting, active or uncertain work") { + t.Fatal(err) + } + done, err := reader.ReviewOperation(t.Context(), queued.ID) + if err != nil || done.State != "cancelled" || done.Wait != nil { + t.Fatal(done, err) + } +} + +func TestReviewOperationRetainedOverrideFlagsWire(t *testing.T) { + for _, route := range []string{"read", "terminal-request"} { + for _, test := range []struct { + name, fields string + valid, allow, override bool + }{ + {"legacy", "", true, false, false}, + {"both", `,"allow_out_of_order":true,"override_file_limit":true`, true, true, true}, + {"allow", `,"allow_out_of_order":true`, true, true, false}, + {"override", `,"override_file_limit":true`, true, false, true}, + {"false", `,"allow_out_of_order":false,"override_file_limit":false`, true, false, false}, + {"null-allow", `,"allow_out_of_order":null`, false, false, false}, + {"null-override", `,"override_file_limit":null`, false, false, false}, + {"string-allow", `,"allow_out_of_order":"true"`, false, false, false}, + {"number-override", `,"override_file_limit":1`, false, false, false}, + {"alias", `,"Allow_Out_Of_Order":true`, false, false, false}, + {"duplicate", `,"allow_out_of_order":true,"allow_out_of_order":false`, false, false, false}, + } { + t.Run(route+"/"+test.name, func(t *testing.T) { + operation := sampleReviewOperation() + operation.WorkerID, operation.State = "worker-one", "completed" + encoded, err := json.Marshal(operation) + if err != nil { + t.Fatal(err) + } + body := strings.TrimSuffix(string(encoded), "}") + test.fields + "}" + var posts atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + if r.Method == "POST" { + posts.Add(1) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + defer service.Close() + c := newClient(t, service) + defer c.Close() + var got client.ReviewOperation + if route == "read" { + got, err = c.ReviewOperation(t.Context(), executionOperationID) + } else { + result, e := c.RequestReview(t.Context(), "retained-flags", client.ReviewRequest{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "cli", HeadSHA: operation.HeadSHA}, 0) + err = e + if result.Operation != nil { + got = *result.Operation + } + } + if !test.valid { + checkError(t, err, "invalid_response") + var failure *client.Error + if !errors.As(err, &failure) || failure.OutcomeUnknown != (route == "terminal-request") { + t.Fatal("lost outcome semantics", err) + } + } else { + if err != nil { + t.Fatal("valid retained operation rejected", err) + } + b, e := json.Marshal(got) + if e != nil { + t.Fatal(e) + } + var fields map[string]any + if json.Unmarshal(b, &fields) != nil || (fields["allow_out_of_order"] == true) != test.allow || (fields["override_file_limit"] == true) != test.override { + t.Fatal("retained flags changed", string(b)) + } + } + wantPosts := int64(0) + if route == "terminal-request" { + wantPosts = 1 + } + if posts.Load() != wantPosts { + t.Fatal("request retried or read mutated", posts.Load()) + } + }) + } + } +} + +func TestOperationWaitV3AllowanceWireAndLegacyReads(t *testing.T) { + for _, kind := range []string{"queued-full", "queued-status", "held-cli-full", "held-hosted-full", "held-hosted-status", "held-cli-request", "held-hosted-request", "legacy-full", "legacy-status"} { + t.Run(kind, func(t *testing.T) { + op := sampleReviewOperation() + op.WorkerID = "worker-one" + compact := strings.HasSuffix(kind, "status") + terminal := strings.HasSuffix(kind, "request") + held := strings.HasPrefix(kind, "held-") + legacy := strings.HasPrefix(kind, "legacy-") + hosted := strings.Contains(kind, "hosted") + op.Channel = "cli" + if hosted { + op.Channel = "hosted" + } + allowance := map[string]any{"kind": "cli_exhausted", "observed_at": "2026-01-01T00:00:00Z", "remaining": 0, "limit": 8, "full_capacity_in_ms": 0, "rolling_window_ms": 3600000} + if hosted { + allowance = map[string]any{"kind": "hosted_cooldown", "observed_at": "2026-01-01T00:00:00Z", "retry_not_before": "2026-01-01T00:10:00Z"} + } + if held { + op.State = "held" + op.AttemptID = "review_attempt_" + strings.Repeat("b", 32) + op.Reason = "allowance_exhausted" + if hosted { + op.Reason = "hosted_allowance_cooldown" + } + } + var requests atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + requests.Add(1) + version := r.Header.Get("X-FC-Operation-Wait") + if version != "3" { + t.Error("current client did not negotiate allowance version3", version) + } + var encoded []byte + if compact { + stage, next := "queued", "wait" + if held { + stage, next = "held", "read_diagnostics" + } + encoded, _ = json.Marshal(client.ReviewOperationStatus{ID: op.ID, PullNumber: op.PullNumber, Channel: op.Channel, State: op.State, Revision: op.Revision, Stage: stage, Reason: op.Reason, AttemptID: op.AttemptID, UpdatedAt: op.UpdatedAt, NextAction: next}) + } else { + encoded, _ = json.Marshal(op) + } + var wire map[string]any + if json.Unmarshal(encoded, &wire) != nil { + t.Error("fixture encoding") + return + } + if !held { + wait := map[string]any{"baseline_attempt_id": "review_attempt_" + strings.Repeat("b", 32), "retry_not_before": "2026-01-01T00:10:00Z", "paused": false} + if version == "3" && !legacy { + wait["cli_allowance"] = allowance + } + wire["wait"] = wait + } else if version == "3" { + if compact { + wire["retry_not_before"] = allowance["retry_not_before"] + } else { + wire["allowance"] = allowance + } + } + write(w, 200, wire) + })) + defer server.Close() + c := newClient(t, server) + defer c.Close() + var value any + var err error + if compact { + value, err = c.ReviewOperationStatus(t.Context(), op.ID) + } else if terminal { + result, e := c.RequestReview(t.Context(), "allowance-v3-original", client.ReviewRequest{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: op.Channel, HeadSHA: op.HeadSHA}, 0) + value, err = result.Operation, e + } else { + value, err = c.ReviewOperation(t.Context(), op.ID) + } + if err != nil { + t.Fatal("version3 operation facts rejected", err) + } + raw, e := json.Marshal(value) + if e != nil { + t.Fatal(e) + } + var got map[string]any + if json.Unmarshal(raw, &got) != nil { + t.Fatal("invalid operation output") + } + var facts any + if held && compact { + if got["retry_not_before"] != allowance["retry_not_before"] { + t.Fatal("held cooldown deadline lost", string(raw)) + } + } else { + if held { + facts = got["allowance"] + } else { + wait, ok := got["wait"].(map[string]any) + if !ok { + t.Fatal("original wait lost", string(raw)) + } + facts = wait["cli_allowance"] + } + if legacy { + if facts != nil { + t.Fatal("legacy response invented allowance", facts) + } + } else { + a, _ := json.Marshal(allowance) + b, _ := json.Marshal(facts) + if string(a) != string(b) { + t.Fatal("retained allowance changed", string(a), string(b)) + } + } + } + if requests.Load() != 1 { + t.Fatal("read or original request retried", requests.Load()) + } + }) + } +} + +func TestOperationWaitV3RejectsMalformedQueuedAllowance(t *testing.T) { + valid := `{"kind":"cli_exhausted","observed_at":"2026-01-01T00:00:00Z","remaining":0,"limit":8,"full_capacity_in_ms":0,"rolling_window_ms":3600000}` + for _, compact := range []bool{false, true} { + for name, allowance := range map[string]string{ + "hosted-scope": valid, "missing-baseline": valid, "null": `null`, "missing": `{}`, "positive": strings.Replace(valid, `"remaining":0`, `"remaining":1`, 1), "unknown-kind": strings.Replace(valid, `cli_exhausted`, `available`, 1), "unknown-field": strings.TrimSuffix(valid, "}") + `,"private":"secret"}`, "null-remaining": strings.Replace(valid, `"remaining":0`, `"remaining":null`, 1), "claimed-reset": strings.TrimSuffix(valid, "}") + `,"retry_not_before":"2026-01-01T00:10:00Z"}`, + } { + t.Run(boolName(compact)+"/"+name, func(t *testing.T) { + op := sampleReviewOperation() + if name == "hosted-scope" { + op.Channel = "hosted" + } + var raw []byte + if compact { + raw, _ = json.Marshal(client.ReviewOperationStatus{ID: op.ID, PullNumber: op.PullNumber, Channel: op.Channel, State: "queued", Revision: 1, Stage: "queued", UpdatedAt: op.UpdatedAt, NextAction: "wait"}) + } else { + raw, _ = json.Marshal(op) + } + body := strings.TrimSuffix(string(raw), "}") + `,"wait":{"baseline_attempt_id":"review_attempt_` + strings.Repeat("b", 32) + `","retry_not_before":"2026-01-01T00:10:00Z","paused":false,"cli_allowance":` + allowance + `}}` + if name == "missing-baseline" { + body = strings.Replace(body, `"baseline_attempt_id":"review_attempt_`+strings.Repeat("b", 32)+`"`, `"baseline_attempt_id":""`, 1) + body = strings.Replace(body, `"retry_not_before":"2026-01-01T00:10:00Z"`, `"retry_not_before":""`, 1) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + defer server.Close() + c := newClient(t, server) + defer c.Close() + var err error + if compact { + _, err = c.ReviewOperationStatus(t.Context(), op.ID) + } else { + _, err = c.ReviewOperation(t.Context(), op.ID) + } + checkError(t, err, "invalid_response") + }) + } + } +} + +func TestReviewOperationControlConflictRecoveryIsExplicit(t *testing.T) { + id := "review_operation_" + strings.Repeat("a", 32) + for _, test := range []struct { + name, code string + status int + revision int64 + }{ + {"stale", "review_conflict", http.StatusConflict, 4}, + {"exhausted", "review_conflict", http.StatusConflict, 9223372036854775807}, + {"uncertain-server-error", "review_conflict", http.StatusInternalServerError, 4}, + {"access-refusal", "forbidden", http.StatusForbidden, 4}, + {"already-started", "review_operation_started", http.StatusConflict, 4}, + } { + t.Run(test.name, func(t *testing.T) { + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + requests.Add(1) + body, _ := io.ReadAll(r.Body) + if r.Method != "POST" || r.URL.Path != "/api/v1/projects/project-one/reviews/operations/"+id+"/control" || r.Header.Get("X-FC-Worker") != "worker-one" || r.Header.Get("Idempotency-Key") != "original-control" || string(body) != `{"expected_revision":3,"action":"pause"}` { + t.Error("bound control request changed", r.URL, string(body)) + } + write(w, test.status, map[string]any{"error": map[string]any{"code": test.code, "message": "Control refused.", "details": map[string]any{"current_revision": test.revision}}, "request_id": "request-control-conflict"}) + })) + defer service.Close() + c := newClient(t, service) + _, err := c.ControlReviewOperation(t.Context(), "original-control", id, client.ReviewOperationControl{ExpectedRevision: 3, Action: "pause"}) + checkError(t, err, test.code) + failure := err.(*client.Error) + if requests.Load() != 1 || failure.Status != test.status || failure.RequestID != "request-control-conflict" || failure.OutcomeUnknown != (test.status >= 500) { + t.Fatal("refusal lost status, identity, or single-shot outcome", failure, requests.Load()) + } + if test.code == "review_conflict" && test.status == http.StatusConflict { + for _, fragment := range []string{"Read this same operation", "current state", "new control action", "maximum value", "unknown outcome", "original authenticated principal, project, worker, exact request body, operation ID and idempotency key"} { + if !strings.Contains(failure.Action, fragment) { + t.Errorf("conflict recovery omits %q: %s", fragment, failure.Action) + } + } + if strings.Contains(failure.Action, "current access") { + t.Fatal("revision conflict misdiagnosed as access refusal", failure) + } + } else if test.status >= 500 { + if strings.Contains(failure.Action, "new control action") || !strings.Contains(failure.Action, "same idempotency key") { + t.Fatal("uncertain outcome lost exact-key recovery", failure) + } + } else if test.code == "forbidden" && !strings.Contains(failure.Action, "current access") { + t.Fatal("unrelated access diagnostic changed", failure) + } else if test.code == "review_operation_started" && !strings.Contains(failure.Action, "No provider cancellation occurred") { + t.Fatal("issued-work refusal changed", failure) + } + }) + } +} diff --git a/internal/client/review_operation_status.go b/internal/client/review_operation_status.go index d397fe979..3a9ae5e47 100644 --- a/internal/client/review_operation_status.go +++ b/internal/client/review_operation_status.go @@ -7,18 +7,21 @@ import ( // ReviewOperationStatus omits private configuration and capture contents. type ReviewOperationStatus struct { - Observer *ReviewHostedObserverStatus `json:"observer,omitempty"` - ID string `json:"id"` - PullNumber int64 `json:"pull_number"` - Channel string `json:"channel"` - State string `json:"state"` - Revision int64 `json:"revision"` - Stage string `json:"stage"` - Reason string `json:"reason"` - AttemptID string `json:"attempt_id"` - EvidenceID string `json:"evidence_id,omitempty"` - UpdatedAt string `json:"updated_at"` - NextAction string `json:"next_action"` + queuedCause string + Wait *ReviewOperationWait `json:"wait,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` + Observer *ReviewHostedObserverStatus `json:"observer,omitempty"` + ID string `json:"id"` + PullNumber int64 `json:"pull_number"` + Channel string `json:"channel"` + State string `json:"state"` + Revision int64 `json:"revision"` + Stage string `json:"stage"` + Reason string `json:"reason"` + AttemptID string `json:"attempt_id"` + EvidenceID string `json:"evidence_id,omitempty"` + UpdatedAt string `json:"updated_at"` + NextAction string `json:"next_action"` } func (c *Client) ReviewOperationStatus(ctx context.Context, id string) (ReviewOperationStatus, error) { @@ -32,7 +35,7 @@ func (c *Client) WaitReviewOperationStatus(ctx context.Context, id string, secon var status int err := resumeResultWait(ctx, seconds, func(ctx context.Context, remaining int) error { value = ReviewOperationStatus{} - return c.requestBoundedOptions(ctx, http.MethodGet, c.projectPath("reviews", "operations", id, "status"), nil, true, "", nil, http.StatusOK, false, &value, 16<<10, decodeReviewResponse, &sourceWaitOptions{seconds: remaining, status: &status, hostedObserver: true}) + return c.requestBoundedOptions(ctx, http.MethodGet, c.projectPath("reviews", "operations", id, "status"), nil, true, "", nil, http.StatusOK, false, &value, 16<<10, decodeReviewResponse, &sourceWaitOptions{seconds: remaining, status: &status, hostedObserver: true, operationWait: true, queuedCause: &value.queuedCause}) }) if err != nil { return ReviewOperationStatus{}, reviewWaitTargetError(err, id) @@ -43,6 +46,12 @@ func (c *Client) WaitReviewOperationStatus(ctx context.Context, id string, secon return value, nil } func validCompactOperationStatus(v ReviewOperationStatus) bool { + if !validReviewOperationWait(v.Wait, v.Channel, v.State, v.AttemptID) { + return false + } + if v.RetryNotBefore != "" && (v.Channel != "hosted" || v.State != "held" || v.Reason != "hosted_allowance_cooldown" || v.AttemptID == "" || !validAllowanceTime(v.RetryNotBefore)) { + return false + } if !validReviewHostedObserver(v.Observer, v.Channel, v.State, v.AttemptID) { return false } diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index 023bd29d1..5617b6333 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -209,6 +209,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_obligation_retarget"] = true expected["review_obligation_resolve"] = true expected["review_queue_edit"] = true + expected["review_operation_control"] = true expected["wait_for_ci"] = true expected["review_rounds_read"], expected["review_rounds_configure"] = true, true expected["review_start"], expected["review_selection_read"] = true, true @@ -230,6 +231,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { writes["review_obligation_retarget"] = true writes["review_obligation_resolve"] = true writes["review_rounds_configure"] = true + writes["review_operation_control"] = true writes["job_primary_replace"] = true writes["map_entry_create"], writes["map_entry_replace"], writes["job_workstream_replace"] = true, true, true writes["worker_pause_replace"] = true @@ -246,7 +248,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { } delete(expected, tool.Name) a := tool.Annotations - if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { + if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_operation_control" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { t.Fatal("untruthful operation annotation") } data, _ := json.Marshal(tool.InputSchema) diff --git a/internal/mcpadapter/arguments.go b/internal/mcpadapter/arguments.go index 17a020f9b..8a87f1de1 100644 --- a/internal/mcpadapter/arguments.go +++ b/internal/mcpadapter/arguments.go @@ -92,6 +92,9 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { if name == "review_operations_list" { return operationListArguments(data) } + if name == "review_operation_control" { + return operationControlArguments(data) + } if name == "review_operation_read" { input, err := operationStatusArguments(data) if err != nil { diff --git a/internal/mcpadapter/review_operation_control.go b/internal/mcpadapter/review_operation_control.go new file mode 100644 index 000000000..c1b38b5b4 --- /dev/null +++ b/internal/mcpadapter/review_operation_control.go @@ -0,0 +1,30 @@ +package mcpadapter + +import ( + "encoding/json" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" + "math" +) + +func operationControlArguments(raw json.RawMessage) (arguments, error) { + var in struct { + ID string `json:"operation_id"` + Key string `json:"idempotency_key"` + Revision int64 `json:"expected_revision"` + Action string `json:"action"` + } + var out arguments + if strictjson.Decode(raw, &in) != nil { + return out, invalidArguments() + } + out.id, out.key = in.ID, in.Key + out.operationControl = client.ReviewOperationControl{ExpectedRevision: in.Revision, Action: in.Action} + if !validKey(in.Key) || client.ValidateReviewOperationControl(in.ID, out.operationControl) != nil { + return arguments{}, invalidArguments() + } + return out, nil +} +func operationControlDefinition() definition { + return definition{"review_operation_control", "Pause, resume or cancel only a queued undispatched operation using its current revision and explicit key. Pause retains the retry deadline; resume rechecks this same request when due. Cancel withdraws intent, never an issued provider request. Posting, active and uncertain work refuses. Preserve the original request/key after unknown output. No changes to grants, taper, findings or project pause.", map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{"operation_id": map[string]any{"type": "string", "pattern": "^review_operation_[a-f0-9]{32}$"}, "expected_revision": map[string]any{"type": "integer", "minimum": 1, "maximum": int64(math.MaxInt64 - 1)}, "action": map[string]any{"type": "string", "enum": []string{"pause", "resume", "cancel"}}, "idempotency_key": map[string]any{"type": "string", "minLength": 1, "maxLength": 128}}, "required": []string{"operation_id", "expected_revision", "action", "idempotency_key"}}} +} diff --git a/internal/mcpadapter/review_operation_control_test.go b/internal/mcpadapter/review_operation_control_test.go new file mode 100644 index 000000000..f946bb444 --- /dev/null +++ b/internal/mcpadapter/review_operation_control_test.go @@ -0,0 +1,95 @@ +package mcpadapter_test + +import ( + "encoding/json" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestReviewOperationControlSDKActualGuardReplayAndWait(t *testing.T) { + f, handler, _ := reviewControlsFixture(t) + var lose atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/control") && lose.Swap(false) { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, r) + if rec.Code != 200 { + t.Error(rec.Code, rec.Body.String()) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(rec.Code) + w.Write([]byte("{")) + return + } + handler.ServeHTTP(w, r) + })) + defer server.Close() + session := reviewControlsStdio(t, reviewControlsProfile(t, f, server.URL), "chosen") + args := executionArguments() + args["channel"] = "cli" + var queued client.ReviewRequestReceipt + decodeResult(t, call(t, session, "review_request", args), &queued) + before := f.providers.Load() + control := map[string]any{"operation_id": queued.ID, "expected_revision": 1, "action": "pause", "idempotency_key": "pause"} + lose.Store(true) + diagnosticResult(t, call(t, session, "review_operation_control", control), "invalid_response", true) + var first, replay client.ReviewOperationControlReceipt + decodeResult(t, call(t, session, "review_operation_control", control), &first) + decodeResult(t, call(t, session, "review_operation_control", control), &replay) + if first != replay || !first.Paused || first.Revision != 2 { + t.Fatal(first, replay) + } + var status client.ReviewOperationStatus + decodeResult(t, call(t, session, "review_operation_read", map[string]any{"operation_id": queued.ID}), &status) + if status.Wait == nil || !status.Wait.Paused || status.Wait.RetryNotBefore != "" || status.AttemptID != "" || status.State != "queued" { + t.Fatal(status) + } + control["action"], control["idempotency_key"] = "resume", "stale" + diagnosticResult(t, call(t, session, "review_operation_control", control), "review_conflict", false) + control["expected_revision"], control["idempotency_key"] = 2, "resume" + var resumed client.ReviewOperationControlReceipt + decodeResult(t, call(t, session, "review_operation_control", control), &resumed) + if resumed.Paused || resumed.State != "queued" || resumed.Revision != 3 { + t.Fatal(resumed) + } + control["expected_revision"], control["idempotency_key"], control["action"] = 3, "cancel", "cancel" + var cancelled client.ReviewOperationControlReceipt + decodeResult(t, call(t, session, "review_operation_control", control), &cancelled) + if cancelled.State != "cancelled" { + t.Fatal(cancelled) + } + if f.providers.Load() != before { + t.Fatal("controls called provider") + } +} + +func TestReviewOperationControlSDKStrictBeforeCredentials(t *testing.T) { + binding := localContext() + binding.ServerURL = "http://127.0.0.1:1" + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"alpha": binding}, "missing-private-token"), "alpha") + id := "review_operation_" + strings.Repeat("a", 32) + for _, raw := range []string{`{}`, `{"operation_id":"` + id + `","expected_revision":1,"action":"pause","idempotency_key":"x","worker_id":"other"}`, `{"operation_id":"` + id + `","expected_revision":null,"action":"pause","idempotency_key":"x"}`, `{"operation_id":"` + id + `","expected_revision":1,"action":"stop","idempotency_key":"x"}`, `{"operation_id":"` + id + `","expected_revision":1,"action":"pause","action":"resume","idempotency_key":"x"}`} { + diagnosticResult(t, call(t, session, "review_operation_control", json.RawMessage(raw)), "invalid_arguments", false) + } + listed, err := allDiscoveredTools(t, session) + if err != nil { + t.Fatal(err) + } + found := false + for _, tool := range listed.Tools { + if tool.Name == "review_operation_control" { + found = true + if tool.Annotations == nil || tool.Annotations.ReadOnlyHint || !tool.Annotations.IdempotentHint || tool.Annotations.OpenWorldHint == nil || *tool.Annotations.OpenWorldHint { + t.Fatal("wrong control annotations") + } + } + } + if !found { + t.Fatal("control missing discovery") + } +} diff --git a/internal/mcpadapter/review_operation_status.go b/internal/mcpadapter/review_operation_status.go index e5ffe2579..304f62ba9 100644 --- a/internal/mcpadapter/review_operation_status.go +++ b/internal/mcpadapter/review_operation_status.go @@ -40,9 +40,17 @@ func operationStatusArguments(raw json.RawMessage) (*operationStatusInput, error } func executeOperationStatus(ctx context.Context, service *client.Client, in *operationStatusInput) (any, error) { if in.Diagnostics { - return service.WaitReviewOperation(ctx, in.ID, in.WaitSeconds) + operation, err := service.WaitReviewOperation(ctx, in.ID, in.WaitSeconds) + if out := client.AgentReviewOperation(operation); out.Diagnostic != nil { + return out, err + } + return operation, err } - return service.WaitReviewOperationStatus(ctx, in.ID, in.WaitSeconds) + status, err := service.WaitReviewOperationStatus(ctx, in.ID, in.WaitSeconds) + if out := client.AgentReviewOperationStatus(status); out.Diagnostic != nil { + return out, err + } + return status, err } func operationStatusDefinition() definition { return definition{"review_operation_read", "Read compact retained operation state, cause and next action; optionally wait without provider polling. A posted trigger is not proof of provider execution or completion. Set diagnostics=true for the original full retained operation.", map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{ diff --git a/internal/mcpadapter/review_wait_test.go b/internal/mcpadapter/review_wait_test.go index 6cf5e66bc..ad8101c11 100644 --- a/internal/mcpadapter/review_wait_test.go +++ b/internal/mcpadapter/review_wait_test.go @@ -20,7 +20,7 @@ func TestReviewResultStdioWaitDoesNotBlockOtherToolsOrRetry(t *testing.T) { var posts atomic.Int64 var setupStarted atomic.Pointer[time.Time] preferences := make(chan string, 4) - readStarted := make(chan struct{}, 1) + readStarted := make(chan string, 1) readDetached := make(chan struct{}, 1) service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/reviews/requests") { @@ -32,7 +32,7 @@ func TestReviewResultStdioWaitDoesNotBlockOtherToolsOrRetry(t *testing.T) { if !boundedReviewWait(r.Header.Get("Prefer"), 50, setupStarted.Load()) { t.Error("operation wait was shortened beyond elapsed setup time") } - readStarted <- struct{}{} + readStarted <- r.Header.Get("Prefer") } handler.ServeHTTP(w, r) if waiting { @@ -63,7 +63,11 @@ func TestReviewResultStdioWaitDoesNotBlockOtherToolsOrRetry(t *testing.T) { done <- err }() select { - case <-readStarted: + case preference := <-readStarted: + seconds, err := strconv.Atoi(strings.TrimPrefix(preference, "wait=")) + if err != nil || seconds <= 5 || seconds > 50 { + t.Fatal("forwarded wait lost the caller budget or ordinary-deadline coverage", preference, err) + } case <-time.After(2 * time.Second): t.Fatal("long review read did not start") } diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index 0bf3452b0..92bd30d21 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -19,6 +19,7 @@ import ( const maxToolWaitSeconds = 50 type arguments struct { + operationControl client.ReviewOperationControl ciWatchTargets []client.CIWatchTarget reviewRun client.ReviewRunRequest reviewOperations client.ReviewOperationsOptions @@ -67,7 +68,7 @@ func boundServer(binding profile.Binding) *mcp.Server { s := mcp.NewServer(&mcp.Implementation{Name: "firecontroller", Version: Version}, &mcp.ServerOptions{Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Capabilities: &mcp.ServerCapabilities{Tools: &mcp.ToolCapabilities{}}, PageSize: 128}) definitions := append(toolDefinitions(), checkpointDefinitions()...) definitions = append(definitions, reviewRunDefinitions()...) - definitions = append(definitions, operationListDefinition()) + definitions = append(definitions, operationListDefinition(), operationControlDefinition()) definitions = append(definitions, roundControlDefinitions()...) definitions = append(definitions, adoptionDefinitions()...) definitions = append(definitions, queueEditDefinition()) @@ -82,9 +83,9 @@ func boundServer(binding profile.Binding) *mcp.Server { transports := sessionTransports{pools: make(map[*mcp.ServerSession]*client.TransportPool)} for _, tool := range definitions { known[tool.name] = true - write := adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + write := tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" openWorld := tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - destructive := adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" + destructive := tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" s.AddTool(&mcp.Tool{Name: tool.name, Description: tool.description, InputSchema: tool.schema, Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &openWorld}}, func(ctx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) { var args arguments var err error @@ -182,6 +183,8 @@ func boundServer(binding profile.Binding) *mcp.Server { var watch client.CIWatchResult watch, err = service.WatchCI(ctx, args.ciWatchTargets, args.reviewSourceWait) value = client.AgentCIWatch(watch) + case "review_operation_control": + value, err = service.ControlReviewOperation(ctx, args.key, args.id, args.operationControl) case "review_operation_read": value, err = executeOperationStatus(ctx, service, args.operationStatus) case "review_request": From 347e2a34e032fb425e61a373721e18d28648eae5 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 15:11:52 +1300 Subject: [PATCH 03/21] Repair backup schema bounds and cancellation, initial policy help and presentation nulls --- .github/workflows/ci.yml | 9 + Makefile | 1 + docs/README.md | 3 + docs/adoption-obligations.md | 10 +- docs/architecture.md | 2 +- docs/backups.md | 8 + docs/development.md | 12 +- docs/local-api.md | 23 +- docs/mcp.md | 44 ++- docs/review-execution.md | 4 + docs/review-import.md | 20 +- docs/review-round-controls.md | 6 +- docs/review-workspace.md | 28 +- docs/worker-retirement.md | 21 + internal/backup/administration_cancel_test.go | 221 +++++++++++ internal/backup/inventory.go | 53 ++- .../project_management_compatibility_test.go | 72 ++++ internal/backup/project_management_test.go | 70 ++++ internal/backup/worker_retirement_test.go | 64 +++ internal/cli/cli.go | 42 +- internal/cli/mutations.go | 8 +- internal/cli/operation_help.go | 15 + internal/cli/project_owner.go | 235 +++++++++++ internal/cli/project_owner_help.go | 68 ++++ internal/cli/project_owner_test.go | 276 +++++++++++++ internal/client/client.go | 18 +- internal/client/mutations.go | 17 +- internal/client/project_owner.go | 374 ++++++++++++++++++ internal/client/project_owner_test.go | 160 ++++++++ internal/client/reads.go | 18 +- internal/client/types.go | 1 + internal/client/worker_retirement.go | 82 ++++ internal/client/worker_retirement_test.go | 307 ++++++++++++++ internal/core/admin_read_test.go | 2 +- internal/core/auth.go | 34 +- internal/core/browser_session.go | 16 +- internal/core/event_project.go | 2 +- internal/core/event_stream_test.go | 2 +- internal/core/events.go | 19 +- internal/core/live_project_events_test.go | 2 +- internal/core/project_management.go | 39 ++ internal/core/project_management_test.go | 109 +++++ .../core/project_management_upgrade_test.go | 227 +++++++++++ internal/core/store.go | 12 + internal/core/types.go | 2 + internal/core/worker_retirement.go | 63 +++ .../core/worker_retirement_bounds_test.go | 90 +++++ internal/core/worker_retirement_test.go | 57 +++ internal/inbox/inbox.go | 58 ++- internal/inbox/worker_retirement_test.go | 227 +++++++++++ internal/jobs/jobs.go | 8 +- internal/jobs/notes.go | 16 +- internal/jobs/primary.go | 12 +- internal/jobs/worker_pause.go | 2 +- internal/jobs/worker_retirement_test.go | 81 ++++ internal/mcpadapter/adapter_test.go | 40 +- internal/mcpadapter/adoption.go | 8 +- internal/mcpadapter/arguments.go | 43 +- internal/mcpadapter/existing_management.go | 262 ++++++++++++ .../existing_management_native_test.go | 106 +++++ .../existing_management_sdk_test.go | 136 +++++++ .../mcpadapter/existing_management_test.go | 114 ++++++ internal/mcpadapter/mutations_test.go | 2 +- internal/mcpadapter/project_owner.go | 177 +++++++++ internal/mcpadapter/project_owner_test.go | 164 ++++++++ internal/mcpadapter/review_queue_edit.go | 4 +- internal/mcpadapter/tools.go | 33 +- internal/mcpadapter/worker_retirement_test.go | 133 +++++++ internal/publicsite/administration_test.go | 147 +++++++ internal/publicsite/service.go | 4 + internal/reviewexec/policy.go | 9 +- .../reviewexec/project_management_test.go | 41 ++ internal/reviewexec/requests.go | 28 +- internal/server/access.go | 173 ++++++-- internal/server/project_management_test.go | 194 +++++++++ internal/server/server.go | 24 +- internal/server/worker_retirement.go | 128 ++++++ .../server/worker_retirement_peer_test.go | 86 ++++ internal/server/worker_retirement_test.go | 266 +++++++++++++ .../{index-BoLFnGJQ.js => index-CYqpI_SB.js} | 2 +- internal/webui/assets/index.html | 2 +- tools/ci/admin-parent-fixture.go.txt | 96 +++++ tools/ci/generate-admin-parent-fixture.sh | 19 + .../packagedsmoke/project_management_test.go | 204 ++++++++++ webapp/src/project-event-types.ts | 1 + webapp/src/project-metadata.ts | 2 +- 86 files changed, 5840 insertions(+), 180 deletions(-) create mode 100644 docs/worker-retirement.md create mode 100644 internal/backup/administration_cancel_test.go create mode 100644 internal/backup/project_management_compatibility_test.go create mode 100644 internal/backup/project_management_test.go create mode 100644 internal/backup/worker_retirement_test.go create mode 100644 internal/cli/project_owner.go create mode 100644 internal/cli/project_owner_help.go create mode 100644 internal/cli/project_owner_test.go create mode 100644 internal/client/project_owner.go create mode 100644 internal/client/project_owner_test.go create mode 100644 internal/client/worker_retirement.go create mode 100644 internal/client/worker_retirement_test.go create mode 100644 internal/core/project_management.go create mode 100644 internal/core/project_management_test.go create mode 100644 internal/core/project_management_upgrade_test.go create mode 100644 internal/core/worker_retirement.go create mode 100644 internal/core/worker_retirement_bounds_test.go create mode 100644 internal/core/worker_retirement_test.go create mode 100644 internal/inbox/worker_retirement_test.go create mode 100644 internal/jobs/worker_retirement_test.go create mode 100644 internal/mcpadapter/existing_management.go create mode 100644 internal/mcpadapter/existing_management_native_test.go create mode 100644 internal/mcpadapter/existing_management_sdk_test.go create mode 100644 internal/mcpadapter/existing_management_test.go create mode 100644 internal/mcpadapter/project_owner.go create mode 100644 internal/mcpadapter/project_owner_test.go create mode 100644 internal/mcpadapter/worker_retirement_test.go create mode 100644 internal/publicsite/administration_test.go create mode 100644 internal/reviewexec/project_management_test.go create mode 100644 internal/server/project_management_test.go create mode 100644 internal/server/worker_retirement.go create mode 100644 internal/server/worker_retirement_peer_test.go create mode 100644 internal/server/worker_retirement_test.go rename internal/webui/assets/assets/{index-BoLFnGJQ.js => index-CYqpI_SB.js} (67%) create mode 100644 tools/ci/admin-parent-fixture.go.txt create mode 100644 tools/ci/generate-admin-parent-fixture.sh create mode 100644 tools/packagedsmoke/project_management_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30260995d..526017f77 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,6 +147,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false + fetch-depth: 0 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 26 @@ -160,8 +161,16 @@ jobs: with: go-version-file: go.mod cache: false + - name: Generate pinned administration predecessor bundle + run: bash tools/ci/generate-admin-parent-fixture.sh "$RUNNER_TEMP/admin-parent-fixture" + - name: Verify genuine predecessor inactive restore + env: + FC_ADMIN_PARENT_FIXTURE: ${{ runner.temp }}/admin-parent-fixture + run: go test -race -v -count=1 -run '^(TestProjectManagementRealParentBundleRemainsInactive|TestProjectManagementRealParentUpgradePreservesAllRowsAndSchemas|TestWorkerRetirementRealParentEmptyACKAndRetiredSendReplay)$' ./internal/backup ./internal/core ./internal/inbox - run: make build - name: Smoke packaged binaries + env: + FC_ADMIN_PARENT_FIXTURE: ${{ runner.temp }}/admin-parent-fixture run: make smoke - name: Install pinned Chromium working-directory: webapp diff --git a/Makefile b/Makefile index 8b01fa16c..6b05434e5 100644 --- a/Makefile +++ b/Makefile @@ -44,6 +44,7 @@ browser-build: # Requires the actual outputs from make build; no implicit rebuild. smoke: + $(GO) test -v -tags=packaged_smoke -run '^TestPackagedProjectManagementSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke $(GO) test -v -tags=packaged_smoke -run '^TestPackagedRunSelectionSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke $(GO) test -v -tags=packaged_smoke -run '^TestPackagedOperationReadsSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke $(GO) test -v -tags=packaged_smoke -run '^TestPackagedCarriedAdoptionSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke diff --git a/docs/README.md b/docs/README.md index 57d4af03a..e794c7122 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,6 +8,9 @@ The [Hosted source foundation](delivery.md#hosted-source-foundation) records the ## Documents +- [Project management](local-api.md#project-management-and-guarded-retirement): explicit scoped grants, permission-set CAS and native administration. +- [Worker retirement](worker-retirement.md): blocker cleanup, active/archive reads and retained historical identities. + - [Carried review obligations](adoption-obligations.md): original source-bound holds, minimum-only rules, guarded resolution and retargeting. - [Retained review history](review-history-growth.md): immutable versions, compact summaries, bounded archives and backup integrity. diff --git a/docs/adoption-obligations.md b/docs/adoption-obligations.md index a31490ebe..c24794b93 100644 --- a/docs/adoption-obligations.md +++ b/docs/adoption-obligations.md @@ -12,11 +12,11 @@ Optional source tooling exports the selected effective policy and its current un ## Carried obligations -The native service accepts generic source-bound obligations through an administrator preview/apply facility, independently of display history and captured native evidence. A carried obligation identifies its source namespace and immutable key, repository and snapshot digest, kind (finding, route or result), retained summary and evidence references, and explicitly affected PRs. The service retains private original provenance. It does not interpret imported text as instructions, merge authority or proof of current-code coverage. +The native service accepts generic source-bound obligations through a project-management preview/apply facility, independently of display history and captured native evidence. A carried obligation identifies its source namespace and immutable key, repository and snapshot digest, kind (finding, route or result), retained summary and evidence references, and explicitly affected PRs. The service retains private original provenance. It does not interpret imported text as instructions, merge authority or proof of current-code coverage. Open obligations hold new review admission and existing review progression for their affected PRs in both channels. The guard applies before provider preparation and again at transactional operation admission and final dispatch. A finished grant, existing capture, channel closure, head change, reordered queue or another channel cannot bypass it. Unrelated PRs and projects retain their existing behavior. Local assessment reads explain the hold with bounded counts and a deliberate detail read; ordinary calls do not print the imported ledger. -Preview is read-only and binds the complete selected batch to the destination instance, project, administrator, worker and expected revision. Apply rechecks scope and current authority and atomically records obligations, provenance, receipt and compact events. An original-key replay returns the original result. Reimport cannot reopen a resolved obligation, erase a native action or silently replace changed source facts. Omission is additive, never deletion or resolution. Admission refuses conflicting provenance. A protective hold may arrive during queued or prepared work; final dispatch guards must observe it. It does not cancel or relabel an existing intent, or prevent consuming and finalizing a result that was already posted. +Preview is read-only and binds the complete selected batch to the destination instance, project, authenticated principal, worker and expected revision. Apply rechecks scope and current authority and atomically records obligations, provenance, receipt and compact events. An original-key replay returns the original result. Reimport cannot reopen a resolved obligation, erase a native action or silently replace changed source facts. Omission is additive, never deletion or resolution. Admission refuses conflicting provenance. A protective hold may arrive during queued or prepared work; final dispatch guards must observe it. It does not cancel or relabel an existing intent, or prevent consuming and finalizing a result that was already posted. Resolution is an explicit revision-guarded action retaining actor, reason and evidence pointers. The worker must establish that the carried obligation has been addressed; importing it or merging its original PR is insufficient. Preserve original source state and later native resolution as distinct facts. Resolution neither changes original finalized review counts nor creates a captured review, comparison coverage, CI observation or merge permission. @@ -26,7 +26,7 @@ Admission validates each selected obligation, target list and resolution in boun ## Bound commands and authority -Import preview/apply use the private administrator profile. Listing, reading, retargeting and resolving use the selected project profile; retargeting and resolution require ordinary project write permission and a valid project worker, without an administrator or Overseer handoff. Ordinary commands remain compact and provider-free: +Import preview/apply require `manage` permission for the selected project or instance administration, plus a valid project worker. Ordinary project read/write permission is insufficient. CLI and MCP use the explicitly selected bound profile, and current authority is rechecked for preview, apply and exact-key replay. Listing, reading, retargeting and resolving use the selected project profile; retargeting and resolution require ordinary project write permission and a valid project worker, without an administrator or Overseer handoff. Ordinary commands remain compact and provider-free: ```sh fc reviews obligations adopt preview --file /private/obligations.json @@ -39,7 +39,7 @@ fc reviews obligations resolve OBLIGATION_ID --expected-revision 1 --reason "Cor The version-one batch contains `source: {namespace, repository_id, snapshot_sha256}`, `expected_revision` and one to one hundred `obligations`. Each obligation contains `source_key`, `kind` (`finding`, `route` or `result`), `affected_pull_numbers`, `summary`, `evidence` and `original_status` (`pending` or `open`). Original evidence may be an explicit empty array when unavailable; a native resolution requires at least one evidence pointer. Each normalized original JSON record is bounded to 32 KiB, each combined normalized resolution or retarget request to 16 KiB, and the complete normalized apply wrapper to 256 KiB. These encoded bounds include escaping. Full-detail reads have a 96 KiB HTTP response budget in the shared CLI/MCP client, preserving previously accepted originals, resolutions and retargets without tightening their limits. The three retained content blocks contribute at most 64 KiB; replacing request revisions with retained revisions and adding attribution, source identity and current scope adds less than 16 KiB. A conservative overhead bound allows eight 128-byte IDs, a 200-byte namespace, the 64-byte digest and three 64-byte timestamps at up to six encoded bytes per input byte, 101 ten-digit affected PRs plus separators, ten 20-byte numeric values, and 2 KiB for field names and JSON punctuation. The resulting bound is below 80 KiB, leaving headroom within the finite 96 KiB transport cap. Detail contains only the latest retarget, not its unbounded history. Backup validation retains the original admission limits. The CLI validates the owner-private regular input before reading credentials or making a request. Preview changes no state; apply binds its exact normalized content and preserves original-key recovery after lost output or later resolution. -`list` returns identity, status, revision and affected PRs, without expanding summaries or evidence. Its 512 KiB response budget accommodates one hundred items with maximally escaped 200-byte namespace and source keys and up to 101 affected PRs per route. `read` deliberately returns retained originals, current scope, the latest retarget if present and any native resolution. The HTTP owner is `/api/v1/projects/{project_id}/reviews/adoption-obligations`, with `GET`, `GET /{id}`, `POST /preview`, `POST /apply`, `POST /{id}/retarget` and `POST /{id}/resolve`; import preview/apply require administrator authority and a valid project worker. Resolution requires project write permission and a valid project worker, rechecked before the first mutation and original-key replay; read-only access cannot resolve obligations. Reads and mutations retain the ordinary short command budget and never call a review provider. +`list` returns identity, status, revision and affected PRs, without expanding summaries or evidence. Its 512 KiB response budget accommodates one hundred items with maximally escaped 200-byte namespace and source keys and up to 101 affected PRs per route. `read` deliberately returns retained originals, current scope, the latest retarget if present and any native resolution. The HTTP owner is `/api/v1/projects/{project_id}/reviews/adoption-obligations`, with `GET`, `GET /{id}`, `POST /preview`, `POST /apply`, `POST /{id}/retarget` and `POST /{id}/resolve`; import preview/apply retain the management authority and worker requirement above. Resolution requires project write permission and a valid project worker, rechecked before the first mutation and original-key replay; read-only access cannot resolve obligations. Reads and mutations retain the ordinary short command budget and never call a review provider. ### Refusals and recovery @@ -56,7 +56,7 @@ The native HTTP contract uses the following codes for guarded changes and source | `not_found` | The selected project, worker, obligation or linked retained source is absent in the bound scope. | Verify the binding and identifier. A policy link requires its matching obligation source to be retained in that project first; do not treat absence as clearance. | | `repository_changed` | A retained obligation source belongs to a different repository from the project's current binding. | Stop and have the repository/source binding verified. Retrying with a newer revision does not repair provenance. | | `adoption_obligation_not_route` | Retargeting an open `finding` or `result` obligation after its revision/status guard passes. | Stop retargeting it. Only `route` obligations can change receiver; resolution still requires actual completion evidence. | -| `forbidden` | Required administrator/project permission or worker attribution is missing, including on exact-key replay. | Stop until the required authority and valid project-worker binding are available. A previous receipt does not authorize its retrieval after permission loss. | +| `forbidden` | Required project-management, instance-administration or project-write permission or worker attribution is missing, including on exact-key replay. | Stop until the required authority and valid project-worker binding are available. A previous receipt does not authorize its retrieval after permission loss. | | `unauthorized` | Authentication is missing, invalid, expired or revoked, including on exact-key replay. | Restore valid authentication before retrying the unchanged original request/key; do not replace the key to bypass revocation. | ## Policy and obligation linkage diff --git a/docs/architecture.md b/docs/architecture.md index 8ff5b4cac..88082f118 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -18,7 +18,7 @@ Every stored project-owned resource has a project identifier. Names are unique o For the initial GitHub integration, one project binds one repository and a repository may belong to only one project within an instance. Creation/binding verifies GitHub's stable repository ID and atomically enforces that uniqueness; a renamed repository or alternate remote URL cannot bypass it. A duplicate returns `repository_already_configured` with the existing project reference when the caller may see it, otherwise an opaque conflict. An interrupted or concurrent binding must not leave two owners. Separate service instances are independent; GitHub Projects boards do not define this application boundary. Broader repository groupings require a separately reviewed design. -Credentials bind an authenticated principal to allowed projects and operations. A supplied worker name is attribution metadata, not permission. Project creation, access management, provider credentials, and project policy changes require administrative permission. The initial access model supports instance administrators and project-scoped read/write clients; additional roles require their own reviewed contract. +Credentials bind an authenticated principal to allowed projects and operations. A supplied worker name is attribution metadata, not permission. Project creation/listing, provider credentials, public publication configuration/preview/apply/unpublish and initial or changed capability binding require instance administration. Explicit project management grants permit project access administration and policy/configuration changes within the selected project; they never elevate a client to instance administration. Management implies read/write, but existing writers receive no automatic management grant. Current exact credentials and project permissions are rechecked for reads, mutations and receipt replay. The [local API](local-api.md) owns permission-set CAS and the [worker retirement contract](worker-retirement.md) owns guarded cleanup and retained identities. Every read, write, pagination cursor, review task, and event subscription validates project scope at the server. Cross-project references are rejected before mutation. The first release does not route messages across projects; Recipient names resolve only within the selected project. A future cross-project route must state both destination project and authorization explicitly. diff --git a/docs/backups.md b/docs/backups.md index 51c39070f..dcaf397d2 100644 --- a/docs/backups.md +++ b/docs/backups.md @@ -148,3 +148,11 @@ Registering a new successful managed backup clears the previous pruning result i The `review_comparison` and `review_route_policy` domains are each present when their corresponding `schema:` metadata marker is present. A marker without its required tables, or domain tables without their marker, refuses bundle creation, inspection and inactive restore. Each present domain must match its owning table, index, foreign-key and invalidation/retention trigger definitions exactly. Manual and scheduled backup creation, inspection and inactive restore independently rederive every native completion proof or receiving-route fact for the present domains from original retained authority. Missing, dirty, mismatched or forged cached facts in those domains refuse all three operations, including inspection and restore of resealed bundles. Creation fails before publishing a completed bundle; none of these operations repairs the facts. Supported predecessor bundles without an optional domain's marker and tables remain valid; inspection and inactive restore do not install the absent domain. Restore preserves original capture bytes, source anchors and frozen counts, and retains pending obligations across heads. For persistent failures, follow the owning recovery guidance for [completion proofs](reviews.md#retained-native-channel-completion) and [receiving-route facts](review-routes.md#source-and-receiving-authority). The [completion foundation qualification](delivery.md#native-channel-completion-foundation) records the executable proof limits. Rederivation can exceed the configured deadline even on a valid installation and return `backup_unavailable`. If the deadline was reached, a longer manual [`--timeout`](#operator-commands) or scheduled [`--backup-timeout`](#managed-scheduling-and-retention), up to the supported twenty-four-hour maximum, may allow it to finish. `backup_unavailable` alone does not establish that a timeout occurred. + +## Administration domains + +`project_management:1` adds explicit default-zero management to existing grants; `worker_retirements:1` retains scoped worker retirement facts without deleting worker identities. Inventory inspection validates these optional versions, physical schema, foreign keys and semantic records. Old bundles without either domain remain readable and restore without an inspection-time migration. Inactive restore preserves grant/retirement history while revoking all copied credentials, so retained management never automatically restores access. Unknown newer administration formats are refused before either core administration migration runs. + +Focused compatibility proof includes a genuine predecessor-binary bundle, unchanged predecessor rows through startup upgrade, exact predecessor empty-body acknowledgement replay, and resealed authority/retirement corruption rejection before target creation. This does not imply compatibility with unrelated newer integrated domain versions or replace the existing provider-resumption hold. + +CI qualification generates the administration compatibility bundle from pinned predecessor commit `383ce8c0bc4505dd89cf5cdec7fb2da1d7e556c8` with `tools/ci/generate-admin-parent-fixture.sh`, then runs the inactive-restore regression with `FC_ADMIN_PARENT_FIXTURE` set. The fixture contains a live synthetic bootstrap credential before restore and neither administration domain. No retained private bundle is committed. Focused SQL-reader tests cancel each administration semantic query deterministically; separate operation-level tests cover canceled inspect, restore, manual and managed creation without publishing or modifying source state. diff --git a/docs/development.md b/docs/development.md index dbf084c08..82bf73118 100644 --- a/docs/development.md +++ b/docs/development.md @@ -75,7 +75,7 @@ Supply `FC_PROFILE` through the agent host's process environment or select `--pr | Command | Returned scope | | --- | --- | | `fc doctor` | Verified instance/project/worker binding, without credentials or a PR scan. | -| `fc workers list` | One compact worker page in the bound project. | +| `fc workers list` | One compact active-worker page in the bound project; `--include-retired` also includes retired workers. | | `fc jobs context JOB_ID [--limit N]` | Complete current brief/checkpoint/checklist plus bound-worker focus/pause and pending previews, explicit omissions, continuation cursors and incoming-event watermark. | | `fc notes read NOTE_ID` | One full current note. | | `fc notes list` | One compact pending page for the bound worker and its currently assigned jobs; explicit scope/filter flags narrow or broaden selection. | @@ -104,7 +104,7 @@ Supply `FC_PROFILE` through the agent host's process environment or select `--pr | `fc inbox list` | Bound worker's compact message previews; optional unread/unacknowledged filters. | | `fc inbox thread ID` | Explicit bounded conversation page with full bodies. | -Administrator setup also supports [prepared review import](review-import.md) through `fc reviews import-preview --file ABSOLUTE_PATH` and `fc reviews import-apply --file ABSOLUTE_PATH --preview SHA256 --key KEY`. Preview is provider-free and read-only; apply uses the existing guarded observation receipt. These commands require deliberately selected administrator access rather than an ordinary worker credential. +Project management also supports [prepared review import](review-import.md#selected-sources-and-destination) through `fc reviews import-preview --file ABSOLUTE_PATH` and `fc reviews import-apply --file ABSOLUTE_PATH --preview SHA256 --key KEY`. Preview is provider-free and read-only; apply uses the existing guarded observation receipt. Select a profile with the owning contract's project-management or instance-administration authority; ordinary project read/write permission is insufficient. Review queue/run lists accept `--limit` and `--cursor`; omitted limits select five entries. Review selectors validate before credentials or HTTP, and reads perform no provider refresh or review execution. Source timestamps and completeness remain observations, not readiness. @@ -137,7 +137,7 @@ Quick local mutations use the same private profile and a five-second operation b | `fc jobs checklist-set ID --key KEY --expect-revision N --expect-checklist-revision C` | Exactly one of `--items JSON` or `--items-file PATH`; guarded ordered replacement, with unchanged content reported explicitly. | | `fc inbox send --key KEY --to WORKER_ID --body TEXT` | Optional `--reply-to MESSAGE_ID`; the bound worker is the sender. | | `fc inbox seen MESSAGE_ID --key KEY` | Only the bound actual recipient can change seen state. | -| `fc inbox ack MESSAGE_ID --key KEY` | Only the bound actual recipient can acknowledge; acknowledgment also establishes seen state. | +| `fc inbox ack MESSAGE_ID --key KEY [--worker WORKER_ID]` | Acknowledgment also establishes seen state; selecting another recipient requires project management. | The parser rejects incomplete, repeated, oversized and malformed arguments before opening profiles or credentials or contacting the service. Brief and body text remain exact UTF-8; selected title/assignment normalization follows the API. Omitted edit fields stay unchanged. Guarded edits return the current revision on conflict. A retained key replays the original receipt after current authorization; it never overwrites a newer revision. @@ -184,3 +184,9 @@ Use `reviews operations` to discover one page of retained operations and `review ## Explicit channel-front selection Use `fc reviews start --channel cli --key KEY` for one durable selection and at most one native child, or `--channel hosted` for the independent Hosted channel. Optional `--expect-pr NUMBER` and `--expected-configuration-revision REVISION` assert the selected target and accepted configuration. `fc reviews run-read --selection-id ID --wait-seconds SECONDS` observes the same selection and original child; it never starts another request. `start` defaults to a two-second wait and `run-read` to no wait; use `--wait-seconds 0` for an immediate receipt. Keep the original key when stdout is lost. A terminal hold requires a fresh authorized request after its cause is resolved. The [selection contract](review-round-controls.md#one-explicit-channel-front-run) owns bounds, recovery and the deferred automatic-scheduling boundary. + +## Native administration + +Use `reviews policy`, `reviews policy-configure --file /absolute/private.json --key KEY`, `reviews execution-configure --file /absolute/private.json --key KEY`, `workers create --name NAME --key KEY`, and `credentials grant|update|revoke`. Operation `--help` is local and runs before profiles or private files are read. Credential grant accepts either `--token-sha256` or an owner-private `--credential-file`; only the digest is transmitted. Permission replacement uses a private JSON file with complete expected and desired permission sets. Retain the original key and arguments after uncertain output; mutations are never automatically reposted. + +Use `workers retirement WORKER_ID` before `workers retire WORKER_ID --key KEY`. `workers list --include-retired` explicitly includes historical identities. `inbox list --worker WORKER_ID` selects a recipient without changing the acting worker; `inbox ack MESSAGE_ID --worker WORKER_ID --key KEY` requires current project management when acknowledging for another recipient. See [retirement](worker-retirement.md) for blockers and race semantics. diff --git a/docs/local-api.md b/docs/local-api.md index a30de83f6..c700d4d5e 100644 --- a/docs/local-api.md +++ b/docs/local-api.md @@ -18,7 +18,7 @@ The service creates an owner-only data directory when absent and stores its data The daemon supports only loopback listeners. Remote HTTPS access through deployment-owned reverse proxies has [hosted proof](hosting.md#executed-deployment-proof); the daemon does not terminate TLS itself. SQLite must use local storage, with one active service process; network-mounted databases and multiple active replicas are unsupported. -Clients send `Authorization: Bearer ` on API requests. Administrative project creation, project listing, and access management require the bootstrap administrator. Project clients receive explicit `read` and/or `write` grants. `X-FC-Worker` selects an existing worker in the request's project for attribution; it never grants permission. Sending messages and changing seen/ack state require that worker selection. +Clients send `Authorization: Bearer ` on API requests. Project creation and project listing require instance administration. Project access management accepts explicit project-management grants or an instance administrator. Project clients receive explicit `read`, `write` and `manage` permissions; `manage` implies read and write, while a writer is not implicitly a manager. `X-FC-Worker` selects an existing worker in the request's project for attribution; it never grants permission. Sending messages and changing seen/ack state require that worker selection. The authenticated `GET /api/v1/instance` returns the durable instance ID. Bound clients supply `X-FC-Instance` on every request; a mismatch returns `instance_mismatch` before domain reads, writes or provider work, including replacement after a client handshake. Missing headers remain supported for explicit administrative bootstrap. The local `fc context` command only reports configuration. @@ -28,7 +28,7 @@ The embedded browser derives an explicitly attenuated session after its bearer-a HTTPS deployments use a Secure, host-only `__Host-fc-browser-{session_id}` cookie at `/`. Only literal localhost or loopback HTTP origins use `fc-local-browser-{session_id}` without Secure. Forwarding headers never weaken cookie security. The deployment must preserve the public Host header; HTTPS termination belongs to [hosting infrastructure](hosting.md). Successful connection retains at most eight valid session cookies issued by this instance, within a 6 KiB cookie-header budget. The new connection is always kept; older retained sessions are expired as needed. Closing a tab without Disconnect therefore cannot grow this instance’s cookie header indefinitely. Other instances’ undecodable cookies and unrelated applications’ cookies are left alone. An evicted tab must connect again; ordinary reload preserves its retained session. -Session reads send exactly one `X-FC-Browser-Session` selector and its matching cookie, with the expected instance header and optional worker selector. Authorization plus a session selector is rejected; cookies without the selector do not authenticate requests. GET/HEAD requests retain project-read attenuation, including the verified instance handshake. Explicit write approval permits only message send/seen/ack and administrator presentation replacement, with a mandatory exact same-origin Origin. It never permits administrative listing, provider/review actions, publication, jobs or access changes. Encrypted initial write/admin allowances intersect current grants; later credential promotion does not broaden an existing session. `GET` on the browser-session endpoint requires the cookie plus selector and returns the same six current identity/capability fields for resume. Current credential revocation, grants, project binding and absolute expiry are enforced again during authorization, including active message streams. Durable instance signing material permits sessions to survive service restart; replacing the instance does not silently rebind them. +Session reads send exactly one `X-FC-Browser-Session` selector and its matching cookie, with the expected instance header and optional worker selector. Authorization plus a session selector is rejected; cookies without the selector do not authenticate requests. GET/HEAD requests retain project-read attenuation, including the verified instance handshake. Explicit write approval permits only message send/seen/ack and project-management presentation replacement, with a mandatory exact same-origin Origin. It never permits administrative listing, provider/review actions, publication, jobs or access changes. Encrypted initial write/management allowances intersect current grants; later credential promotion does not broaden an existing session. `GET` on the browser-session endpoint requires the cookie plus selector and returns the same six current identity/capability fields for resume. Current credential revocation, grants, project binding and absolute expiry are enforced again during authorization, including active message streams. Durable instance signing material permits sessions to survive service restart; replacing the instance does not silently rebind them. `DELETE` on the same endpoint takes the selector header and exactly `{}`, with no bearer header, and expires only that selector's cookie. The response is `{"session_id":"","logged_out":true}`. Clearing works for an expired or missing cookie and never revokes the original credential. POST and DELETE reject a supplied mismatched Origin or cross-site fetch metadata and do not enable cross-origin access. See [browser connection behavior](browser-guide.md#connect-and-navigate) for per-tab storage, reload and disconnect semantics. @@ -46,8 +46,9 @@ Receipt keys include their originating instance. Startup upgrades base schema ve | `POST /api/v1/projects/{project_id}/workers` | Scoped write sends `{name}`; returns compact worker receipt. | | `GET /api/v1/projects/{project_id}/workers` | Scoped bounded worker page. | | `GET /api/v1/projects/{project_id}/workers/{worker_id}` | Scoped worker detail. | -| `POST /api/v1/projects/{project_id}/credentials` | Administrator sends `{token_sha256, permissions}`; returns credential/principal IDs and project ID. | -| `DELETE /api/v1/projects/{project_id}/credentials/{credential_id}` | Administrator revokes access; requires an idempotency key. | +| `POST /api/v1/projects/{project_id}/credentials` | Project manager or instance administrator sends `{token_sha256, permissions}`; returns credential/principal IDs and project ID. | +| `PUT /api/v1/projects/{project_id}/credentials/{credential_id}` | Project manager or instance administrator sends `{expected_permissions, permissions}` with an idempotency key; stale permissions return `credential_permissions_changed`. | +| `DELETE /api/v1/projects/{project_id}/credentials/{credential_id}` | Project manager or instance administrator revokes access; requires an idempotency key. | For a project client, generate a high-entropy secret privately and register its lowercase SHA-256 hex digest, with permissions such as `["read", "write"]`. Keep the raw secret in the client's protected credential file. The service stores its hash; API receipts do not return the raw secret. Each registered credential currently establishes a separate principal. @@ -83,7 +84,7 @@ Statuses are `active`, `parked`, `blocked` and `completed`; creation defaults to | `GET /inbox/{worker_id}` | Compact previews and seen/ack state; optional `unread=true` and `unacknowledged=true` filters. | | `GET /conversations/{conversation_id}` | Explicit chronological full-body page with root/reply identities. | | `POST /messages/{message_id}/seen` | Strict `{}` body; only the selected actual recipient can mark seen. | -| `POST /messages/{message_id}/ack` | Strict `{}` body; only the selected actual recipient can acknowledge, atomically establishing seen. | +| `POST /messages/{message_id}/ack` | Strict object with optional recipient `worker_id`, defaulting to the acting worker. Acknowledging for another recipient requires current project management and preserves the acting worker. Atomically establishes seen. See [guarded retirement](#project-management-and-guarded-retirement). | Sender, recipient and reply references must belong to the selected project. Body is nonblank UTF-8, bounded to 16 KiB. Inbox previews contain at most 160 Unicode runes with explicit `preview_truncated`. Replies preserve conversation identity, and pages use a durable insertion sequence rather than timestamp ordering alone. @@ -103,7 +104,7 @@ See [development proof](development.md) for executed checks and unproven boundar Jobs and inbox schemas have separate ordered migration versions stored in instance metadata. Startup applies only missing migrations under the same exclusive transaction as their version records and refuses a newer domain version before running its DDL. Failed migrations roll back their schema changes and version updates together. The original unversioned domain tables enter this sequence at version zero using their idempotent initial DDL; this does not validate an arbitrarily modified database. Use a compatible binary for a newer schema rather than deleting version records. Migration checks run before serving requests, never during ordinary reads or writes. -The [native review workspace](review-workspace.md) owns its administrator observation and project-scoped queue/PR/run read routes. [Prepared review import](review-import.md) adds an explicit administrator preview/apply flow against that same observation transaction. Queue/PR/run reads and import preview read indexed stored evidence; observation and apply are guarded writes. None of these handlers performs provider refresh or job/message effects. +The [native review workspace](review-workspace.md) owns its administrator observation and project-scoped queue/PR/run read routes. [Prepared review import](review-import.md) adds an explicit preview/apply flow for administrators and project managers with `manage` permission against that same observation transaction. Queue/PR/run reads and import preview read indexed stored evidence; observation and apply are guarded writes. None of these handlers performs provider refresh or job/message effects. The [source refresh contract](review-source.md) owns its explicit POST, operation read and observed-policy read. Its short default wait returns a completed result directly where possible, with a pending receipt only when the work remains active; ordinary review reads never trigger that refresh. @@ -122,3 +123,13 @@ The [source refresh contract](review-source.md) owns its explicit POST, operatio ## Job resume context [Job resume context](job-context.md) owns `GET /jobs/{job_id}/context`, with an explicit worker binding and optional bounded limit. One authorized snapshot combines the complete current brief/latest checkpoint/checklist, worker focus/pause, selected pending-note/inbox previews and incoming-event watermark. Required content is never truncated; the response states which bodies or additional pages need explicit reads. This deliberate operation does not expand routine job reads or perform provider work. + +## Project management and guarded retirement + +A project manager can grant a new credential with `POST /api/v1/projects/{project_id}/credentials`, change an existing active non-administrator grant with `PUT /api/v1/projects/{project_id}/credentials/{credential_id}`, or revoke that project's grant with DELETE. All mutations require an explicit idempotency key. Grant accepts `{token_sha256, permissions}`; the lowercase SHA-256 digest is supplied instead of a raw secret. PUT requires complete `expected_permissions` and `permissions` arrays. Unique read/write/manage values normalize in that order, with manage implying read/write. Mismatched current permissions return `credential_permissions_changed` and only the selected grant's current permission set. A no-op returns `unchanged`; an update preserves credential/principal identity and records old/new permissions. Foreign, revoked and instance-administrator credentials are unavailable to this route. + +Revocation clears only this project's grant. Another active project grant remains usable; the credential is marked revoked only when none remain. Exact-key receipt replay retains the original result but still requires current management authority. Self-demotion or revocation cannot recover a privileged receipt. No grant operation creates instance authority. Initial and changed review capability binding remain operator-only; a manager may reconfigure an already bound capability within the project. + +Native CLI and MCP offer policy read/configuration, execution configuration, worker creation and credential grant/update/revoke. Policy replacement requires the complete existing `paused_channels` field as well as required channels and the revision. Execution replacement retains the current nonempty queue contract. The [retirement API](worker-retirement.md) adds preview, guarded retirement, active/archive lists and explicit manager-on-behalf acknowledgement without changing the acting identity. + +Existing browser presentation authority intersects the encrypted initial management ceiling with current grants. This slice keeps the existing explicit allow-writes opt-in and mutation allowlist; browser retirement controls and new browser scheduling controls are not implemented here. diff --git a/docs/mcp.md b/docs/mcp.md index 60666c777..979f64f6c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -28,18 +28,38 @@ Startup validates configuration without opening the credential or contacting the | Tool | Input and result | | --- | --- | -| `review_round_adoption_preview` | Administrator and valid project worker; required document. Preview the native [round-adoption document](review-round-controls.md#carried-rule-adoption) against its original-source and current revision guards; no live reviews are requested. | -| `review_round_adoption_apply` | Administrator and valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [round-adoption document](review-round-controls.md#carried-rule-adoption). Preserves retained attribution and accounting rules; tooling access is not review authorization. | +| `review_round_adoption_preview` | Project management or instance administration, and a valid project worker; required document. Preview the native [round-adoption document](review-round-controls.md#carried-rule-adoption) against its original-source and current revision guards; no live reviews are requested. | +| `review_round_adoption_apply` | Project management or instance administration, and a valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [round-adoption document](review-round-controls.md#carried-rule-adoption). Preserves retained attribution and accounting rules; tooling access is not review authorization. | | `review_obligations_list` | Project read access; optional pull_number/status/limit/cursor, with status open or resolved. Read one compact [carried-obligation](adoption-obligations.md#bound-commands-and-authority) page. Full bodies require review_obligation_read. | | `review_obligation_read` | Project read access; required obligation_id. Read one retained carried obligation and original evidence, without marking it resolved; see [carried-obligation reads](adoption-obligations.md#bound-commands-and-authority). | | `review_obligation_retarget` | Project write access and valid project worker; required obligation_id/expected_revision/target_pull_number/reason/idempotency_key. Move an open carried route to one receiving PR; target_pull_number zero means unassigned backlog. Preserves original provenance and source scope; does not resolve work or grant review credit. See [route receivers](adoption-obligations.md#current-receivers-of-carried-routes). | -| `review_obligations_import_preview` | Administrator and valid project worker; required document. Preview one strict native [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority), preserving original evidence and provenance; no application or new review. | -| `review_obligations_import_apply` | Administrator and valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority). Existing source conflicts and evidence requirements remain enforced. | +| `review_obligations_import_preview` | Project management or instance administration, and a valid project worker; required document. Preview one strict native [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority), preserving original evidence and provenance; no application or new review. | +| `review_obligations_import_apply` | Project management or instance administration, and a valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority). Existing source conflicts and evidence requirements remain enforced. | | `review_obligation_resolve` | Project write access and valid project worker; required obligation_id/document/idempotency_key. Resolve one carried obligation using the native {expected_revision,reason,evidence} document. Requires an evidence-backed [resolution](adoption-obligations.md#bound-commands-and-authority); grants no review credit. | | `context` | No fields; configured local identity, without service verification. | +| `review_policy_read` | Read current policy including paused_channels. | +| `review_policy_configure` | Complete policy replacement with expected_revision, paused_channels and explicit idempotency_key. | +| `review_execution_configure` | Guarded existing capability/configuration replacement with nonempty queue and explicit key. | +| `worker_create` | Create a named worker using an explicit key. | +| `worker_retirement_read` | Read bounded unfinished-job, pending-note and incoming-message blockers. | +| `worker_retire` | Guarded one-way retirement; explicit worker_id and key. | +| `project_credential_grant` | Grant a distinct credential digest scoped permissions; explicit key. | +| `project_credential_update` | Full expected_permissions/permissions CAS for credential_id and explicit key. | +| `project_credential_revoke` | Revoke only this project grant for credential_id and explicit key. | +| `presentation_replace` | Apply a strict native presentation document and key. | +| `presentation_history` | One bounded retained history page. | +| `presentation_revision_read` | Read one retained revision. | +| `publication_configuration_read` | Read selected public publication configuration; requires instance administration. | +| `publication_preview` | Preview a complete native publication document without publishing; requires instance administration. | +| `publication_apply` | Apply exact native document, preview_sha256 and key; requires instance administration. | +| `publication_unpublish` | Disable publication using expected_revision and key; requires instance administration. | +| `review_import_preview` | Project management or instance administration; preview a complete native [review import](review-import.md#selected-sources-and-destination). | +| `review_import_apply` | Project management or instance administration; apply exact native [review import](review-import.md#selected-sources-and-destination), preview_sha256 and key. | +| `review_transfer_preview` | Project management or instance administration; preview a bounded native [review-history transfer](review-import.md#additive-mixed-producer-transfer). | +| `review_transfer_apply` | Project management or instance administration; apply exact native [review-history transfer](review-import.md#additive-mixed-producer-transfer), preview_sha256 and key. | | `presentation_read` | Explicit bound-project appearance snapshot and project-metadata watermark; no provider work or mutation. | | `doctor` | No fields; verified instance/project/worker identity. | -| `workers_list` | Optional limit/cursor; one compact worker page. | +| `workers_list` | Optional limit/cursor/include_retired; one compact active or explicitly historical worker page. | | `worker_pause_read` | No fields; bound worker’s explicit pause, reason and independent revision. | | `worker_pause_history` | Optional limit/cursor; one explicit newest-first pause-history page. | | `jobs_list` | Optional worker_id/status/limit/cursor; one compact job page. | @@ -67,7 +87,7 @@ Startup validates configuration without opening the credential or contacting the | `note_list` | Optional worker_id/all_workers/direct_only/job_id/phase/kind/status/limit/cursor; compact notes for the bound worker and its currently assigned jobs by default. | | `note_history` | Required note_id and optional limit/cursor; one compact revision page. | | `note_revision_read` | Required note_id/revision; one full immutable note revision. | -| `inbox_list` | Optional unread/unacknowledged/limit/cursor; bound worker's compact preview page. | +| `inbox_list` | Optional unread/unacknowledged/limit/cursor/worker_id; selected recipient compact preview page without changing acting identity. | | `inbox_thread` | Required conversation_id and optional limit/cursor; explicit full-body conversation page. | | `inbox_snapshot` | Optional unread/unacknowledged/limit/cursor; one inbox page plus its atomic incoming-event watermark. | | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | @@ -98,7 +118,7 @@ Startup validates configuration without opening the credential or contacting the | `review_rounds_read` | Required pull_number/channel; compact native per-PR/channel grant, limits, cumulative consumed and clean counts, taper and closure. No provider work. | | `review_rounds_configure` | Required idempotency_key/pull_number/channel/expected_revision/action; grant requires minimum/maximum, taper requires taper, and close omits allocation fields. Project-write permission; original-key replay does not buy another round. See [round controls](review-round-controls.md). | | `review_queue` | Optional limit/cursor; stored queue, default five PRs. | -| `review_queue_edit` | Administrator-only native `document` plus `idempotency_key`; selected metadata, explicit retirement/reactivation and relative ordering through [bounded queue edits](review-workspace.md#bounded-queue-edits). No provider work or automatic retry. | +| `review_queue_edit` | Project management or instance administration; native `document` plus `idempotency_key`; selected metadata, explicit retirement/reactivation and relative ordering through [bounded queue edits](review-workspace.md#selected-queue-edits). No provider work or automatic retry. | | `review_pull` | Required pull_number, optional snapshot; compact PR summary with latest attempts per channel. | | `review_attempts` | Required pull_number, optional snapshot/limit/cursor; default five newest-first attempts with original producer and explicit continuation. | | `review_runs` | Required pull_number, optional snapshot/limit/cursor; default five stored run summaries. | @@ -118,7 +138,7 @@ Startup validates configuration without opening the credential or contacting the | `note_update` | Required idempotency_key/note_id/expected_revision plus selected scope/kind/body/status/status_reason fields; compact changed/unchanged receipt. | | `inbox_send` | Required idempotency_key/recipient_worker_id/body; optional reply_to_message_id; compact message receipt. | | `inbox_seen` | Required idempotency_key/message_id; explicit recipient seen transition. | -| `inbox_ack` | Required idempotency_key/message_id; explicit recipient acknowledgment, also establishing seen. | +| `inbox_ack` | Required idempotency_key/message_id; optional worker_id selects a recipient. Acknowledgment also establishes seen; another recipient requires project management. | Review queue/run/attempt lists default to five entries; other limits use the API default when omitted and accept explicit values from 1 to 100. Reads never advance seen/ack state, change a job or write a checkpoint. Assigned jobs do not claim to contain primary-job or full resume context. Snapshot and event cursors have different scopes. Event reads retain no cursor and never automatically poll or resubscribe; an explicitly requested bounded wait can return an empty `timed_out` page. The finite snapshot/event operations are separate from the explicit quiet wait; none establishes idle-agent wakeup. Invalid, unknown, duplicate, exactly mis-cased, null or oversized tool fields fail before service work. Profile selectors cannot be supplied as tool arguments. @@ -163,3 +183,11 @@ Clean source `e65315f3141fcba180499110cb0a5ad6f4948d6c` passed the actual packag ## Explicit review selection tools `review_start` accepts one durable channel selection with the caller's key and optional target/configuration assertions. `review_selection_read` observes a retained selection ID and its original native child, with optional bounded waiting. A `review_busy` response identifies another pending selection but creates no receipt and does not satisfy the refused caller's target assertion. Reads and canceled waits never authorize replacement work. See the [selection contract](review-round-controls.md#one-explicit-channel-front-run) for exact lifetime, authority and recovery semantics. + +## Native project administration + +The bound service exposes `review_policy_read`, `review_policy_configure`, `review_execution_configure`, `worker_create`, `project_credential_grant`, `project_credential_update` and `project_credential_revoke`. Mutation schemas require explicit keys and complete CAS inputs. Policy replacement includes `paused_channels`; execution configuration keeps an existing operator-bound capability and a nonempty queue. Grant takes a digest, never a raw secret. Management permissions and receipt replay follow the [local API](local-api.md#project-management-and-guarded-retirement). + +`worker_retirement_read` reports bounded blockers; `worker_retire` rechecks them atomically with ordinary write permission. `workers_list` defaults to active identities and accepts explicit `include_retired`. `inbox_list` and `inbox_ack` accept a selected `worker_id`; only acknowledgement for another recipient requires management. The authenticated acting worker remains unchanged. The existing inbox snapshot and seen operations do not accept another worker selector. + +Native presentation replacement/history/revision, public publication configuration/preview/apply/unpublish, and review import/transfer preview/apply tools delegate strict native documents to the existing validators. Public publication configuration, preview, apply and unpublish require instance administration; project management does not authorize them. Publication apply retains the explicit preview hash and revision. Existing round-adoption and adoption-obligation tools remain registered once. Read and preview tools perform no provider action; write/destructive annotations distinguish guarded mutations. New operation-control, settlement, history-collection and publication-prepare adapters are not part of this prerequisite. diff --git a/docs/review-execution.md b/docs/review-execution.md index 89b5f2cd4..59ffe0bb5 100644 --- a/docs/review-execution.md +++ b/docs/review-execution.md @@ -301,3 +301,7 @@ Focused proof covers parser-to-native source identity, strict HTTP/client varian ## Explicit selection entry point A [durable channel selection](review-round-controls.md#one-explicit-channel-front-run) may link one ordinary request through the same transactional admission helper used by exact-target requests. The selector adds no provider privilege, round allowance or completion credit. Native preparation and final provider guards remain authoritative after selection. + +## Project management authority + +Explicit project managers may replace project policy and an already operator-bound execution configuration. Both methods pin management before receipt replay and reauthorize the current exact credential. Initial binding and capability changes remain instance-operator actions. This native administration prerequisite preserves policy `paused_channels`, configuration revision/CAS and existing operation/selection lifecycle; it does not introduce automatic scheduling, timer waits or terminal-intent resumption. Retired worker IDs remain valid historical review attribution; retirement does not settle or cancel review operations. diff --git a/docs/review-import.md b/docs/review-import.md index d483cfc8e..2ecc7ecfe 100644 --- a/docs/review-import.md +++ b/docs/review-import.md @@ -2,23 +2,23 @@ ## Implementation status -The administrator observation API already imports immutable review history. The guided preview/apply API and CLI below are implemented with focused normal/race checks. Focused checks, five actual packaged groups and the full integrated check/build pass at the checkpoints below. They do not collect provider history, import historical jobs or messages, generate a project map, or complete the broader [onboarding](onboarding.md) flow. +The project-management observation API already imports immutable review history. The guided preview/apply API and CLI below are implemented with focused normal/race checks. Focused checks, five actual packaged groups and the full integrated check/build pass at the checkpoints below. They do not collect provider history, import historical jobs or messages, generate a project map, or complete the broader [onboarding](onboarding.md) flow. ## Selected sources and destination -An administrator prepares one private JSON document using the existing version-one [review observation](review-workspace.md) request shape: `expected_revision`, `repository_id`, `source`, `observed_at`, `queue` and `retired`. Choose the historical scope before collecting or preparing it. Preserve stable source/run/finding identities and original known times. Missing facts remain unknown; collection time and source observation time do not become historical completion times. Imported content is data, including any apparent instructions inside text fields. +An authorized project manager or instance administrator prepares one private JSON document using the existing version-one [review observation](review-workspace.md) request shape: `expected_revision`, `repository_id`, `source`, `observed_at`, `queue` and `retired`. Choose the historical scope before collecting or preparing it. Preserve stable source/run/finding identities and original known times. Missing facts remain unknown; collection time and source observation time do not become historical completion times. Imported content is data, including any apparent instructions inside text fields. The document describes the complete selected review workspace, rather than an append-only batch. Preserve queued merged PRs. Removing a prior entry requires its explicit `superseded` or `defunct` retirement under the existing observation contract. Existing finalized counts and historical snapshots remain protected. The source label identifies the retained export/source; the stored normalized payload digest identifies the imported content. Version one of this guided workflow uses the existing observation schema and normalization, without a second historical record model. -Use a deliberately selected administrator profile for import. Ordinary worker credentials and browser sessions cannot import. The target repository must match the project's stable configured identity. Applying history does not grant native execution coverage, satisfy review policy, create active jobs, deliver historical messages as new messages, or enable public publishing. +Import preview and apply require `manage` permission for the selected project or instance administration. Ordinary project read/write permission is insufficient, and browser sessions cannot import. CLI and MCP use the deliberately selected bound profile; authority is rechecked for preview, apply and exact-key replay. The target repository must match the project's stable configured identity. Applying history does not grant native execution coverage, satisfy review policy, create active jobs, deliver historical messages as new messages, or enable public publishing. ## Preview and apply -`POST /api/v1/projects/{project_id}/reviews/import/preview` accepts the observation document. It strictly validates and normalizes the same fields as the observation API, then checks repository identity, expected workspace revision, observation ordering, retirement obligations and finalized history in one administrator-authorized read snapshot. It writes no table, receipt or event and performs no provider work. Although transported as a POST, it is a read and cancellation does not imply an uncertain mutation. +`POST /api/v1/projects/{project_id}/reviews/import/preview` accepts the observation document. It strictly validates and normalizes the same fields as the observation API, then checks repository identity, expected workspace revision, observation ordering, retirement obligations and finalized history in one authorized read snapshot. It writes no table, receipt or event and performs no provider work. Although transported as a POST, it is a read and cancellation does not imply an uncertain mutation. The compact response contains `version: 1`, project/repository/source/observation identity, `expected_revision`, `payload_sha256`, `preview_sha256`, counts of pulls/runs/attempts/findings/retirements, `imported_history: true` and `native_coverage: false`. It does not echo PR titles, finding text, credentials or the full export. It describes a locally validated destination snapshot, not newly verified provider facts. -The preview fingerprint uses a versioned domain and binds the exact normalized observation, durable instance, project, authenticated administrator principal and selected worker. Formatting changes and the observation API's existing null-to-empty collection normalization do not change its meaning. Array order, source text and timestamp spelling retain their existing meaning. Changed content or destination requires another preview. The fingerprint is a stateless content binding, not a reservation, capability or proof that a human approved anything. +The preview fingerprint uses a versioned domain and binds the exact normalized observation, durable instance, project, authenticated principal and selected worker. Formatting changes and the observation API's existing null-to-empty collection normalization do not change its meaning. Array order, source text and timestamp spelling retain their existing meaning. Changed content or destination requires another preview. The fingerprint is a stateless content binding, not a reservation, capability or proof that a human approved anything. `POST /api/v1/projects/{project_id}/reviews/import/apply` accepts `{"preview_sha256":"64 lowercase hex characters","observation":{...}}` and an explicit `Idempotency-Key`. It verifies the binding and uses the same `reviews.observe` / `workspace` mutation, normalized request identity, admission guards and compact `observed` receipt as the original observation endpoint. Exact key/request replay returns that original receipt before rechecking a newer workspace revision. A changed source under the same key conflicts. A fresh key rechecks current authorization and every observation guard inside the write transaction; a preview never bypasses those checks. @@ -36,19 +36,19 @@ fc reviews queue Both commands use the selected private profile. The CLI checks its arguments and reads a bounded regular JSON file before accessing credentials or making requests. It also verifies that this document's compact wire encoding fits the future apply wrapper, so the same file remains usable for apply. Invalid syntax, encoding, duplicate keys, special files and oversized inputs produce safe diagnostics without file contents. The service owns complete observation and destination validation. No temporary file, preview record, generated key, automatic apply, provider collection or polling is hidden behind these commands. Calls keep the ordinary five-second client budget. Successful apply returns the compact existing receipt; failed output reports an unknown mutation outcome and exact-retry guidance. Preview output failure makes no mutation claim. -This administrator setup boundary is available through HTTP and CLI. It adds no ordinary worker MCP mutation or implicit agent-host installation. The optional onboarding skill teaches selecting sources, inspecting the preview, applying authorized history and checking the resulting workspace. Historical jobs/messages, provider collectors, interruption of provider pagination, persistent proposed maps, native Windows launcher generation and a graphical import wizard remain separate capabilities. +This project-management boundary is available through HTTP, CLI and the explicit `review_import_preview` / `review_import_apply` MCP tools. It does not install an agent host or broaden an ordinary project read/write grant. The optional onboarding skill teaches selecting sources, inspecting the preview, applying authorized history and checking the resulting workspace. Historical jobs/messages, provider collectors, interruption of provider pagination, persistent proposed maps, native Windows launcher generation and a graphical import wizard remain separate capabilities. ## Additive mixed-producer transfer -Additive transfer is a separate prepared-history operation. It keeps omitted current history visible and preserves every record's original producer. The complete-workspace observation/import above keeps its replacement semantics. Historical provider collection and resumable acquisition remain separate work. +Additive transfer is a separate prepared-history operation with the same project-management or instance-administration authority and current-authority checks as [review import](#selected-sources-and-destination). It keeps omitted current history visible and preserves every record's original producer. The complete-workspace observation/import above keeps its replacement semantics. Historical provider collection and resumable acquisition remain separate work. -An administrator prepares a version-one batch with `expected_revision`, `repository_id`, `publisher` and `groups`. Each group has an original `source` and `pulls` using the existing pull/run/attempt/finding fields. The publisher identifies the transfer, while each group's source continues to determine stable run and attempt identities. Two producers can retain the same external identifier without collision. Known historical times remain original; absent times remain unknown. Transfer text is data and grants no authority. +An authorized project manager or instance administrator prepares a version-one batch with `expected_revision`, `repository_id`, `publisher` and `groups`. Each group has an original `source` and `pulls` using the existing pull/run/attempt/finding fields. The publisher identifies the transfer, while each group's source continues to determine stable run and attempt identities. Two producers can retain the same external identifier without collision. Known historical times remain original; absent times remain unknown. Transfer text is data and grants no authority. A batch contains one to 100 nonempty producer groups and at most 100 pull appearances, 200 runs, 200 attempts and 1,000 findings in total. Existing individual record and per-group pull limits still apply, including 100 findings per run. The normalized batch and its eventual apply wrapper each fit 256 KiB. These limits bound one command; successive batches can retain more history than one batch holds. Repeated producer groups or duplicate producer/source identities are refused. Repeated PR metadata across groups must agree. Every selected pull has `complete: false`: importing a batch never claims complete PR or project coverage. Existing current PR metadata must match exactly; omitted PRs and records stay visible. New PRs append in request order. A retired PR requires explicit queue reactivation before transfer. Existing records keep their position, and new or returning records append without reordering retained entries. A linked attempt must name its original producer's run on the same PR, channel and head, either included in this batch or currently visible. An omitted historical run must be selected again before linking to it. -`POST /api/v1/projects/{project_id}/reviews/transfer/preview` validates shape, repository, current revision, metadata, immutable identities, finalized history, settled attempts and links in one administrator-authorized read snapshot. It writes nothing and calls no provider. Its compact response contains version, project/repository/publisher identity, expected revision, payload and preview digests, selected counts, `imported_history: true`, `native_coverage: false` and `coverage: "partial"`. Counts describe this batch, not all retained or provider history. The versioned fingerprint binds normalized content to the instance, project, authenticated administrator and selected worker; it reserves nothing. +`POST /api/v1/projects/{project_id}/reviews/transfer/preview` validates shape, repository, current revision, metadata, immutable identities, finalized history, settled attempts and links in one authorized read snapshot. It writes nothing and calls no provider. Its compact response contains version, project/repository/publisher identity, expected revision, payload and preview digests, selected counts, `imported_history: true`, `native_coverage: false` and `coverage: "partial"`. Counts describe this batch, not all retained or provider history. The versioned fingerprint binds normalized content to the instance, project, authenticated principal and selected worker; it reserves nothing. `POST /api/v1/projects/{project_id}/reviews/transfer/apply` accepts `{"preview_sha256":"64 lowercase hex characters","batch":{...}}` and an explicit `Idempotency-Key`. Fresh apply rechecks admission inside the original two-second write transaction. Snapshot provenance/digest, immutable versions, memberships, current references, compact summaries, event, optional public projection and compact `transferred` receipt commit together. An error rolls them back together. Exact same-key/batch replay rechecks current authority and returns the original receipt even after later workspace changes or restart. A changed batch or worker under that key conflicts. A preview mismatch uses `import_preview_mismatch`; changing the revision or content requires another preview and a deliberately selected new key. @@ -61,7 +61,7 @@ fc reviews transfer-preview --file /private/import/batch.json fc reviews transfer-apply --file /private/import/batch.json --preview SHA256 --key retained-batch-key ``` -They validate a bounded owner-private regular file before credentials or network access, use the ordinary five-second client budget and return useful local results directly. Preserve the exact file, profile, preview hash and key for uncertain apply recovery. There is no automatic key generation, application, provider collection, polling or worker MCP mutation. Focused validation covers service/client/CLI admission, replay, native-authority separation and retained backup behavior; implementation validation and installed qualification remain separate. +They validate a bounded owner-private regular file before credentials or network access, use the ordinary five-second client budget and return useful local results directly. Preserve the exact file, profile, preview hash and key for uncertain apply recovery. MCP `review_transfer_preview` and `review_transfer_apply` expose the same explicitly authorized operations. There is no automatic key generation, application, provider collection or polling. Focused validation covers service/client/CLI admission, replay, native-authority separation and retained backup behavior; implementation validation and installed qualification remain separate. ## Required proof diff --git a/docs/review-round-controls.md b/docs/review-round-controls.md index 0c492ce6a..f58246dfb 100644 --- a/docs/review-round-controls.md +++ b/docs/review-round-controls.md @@ -26,7 +26,7 @@ Candidate, base, effective-parent or history movement after start preserves earn ## Native control semantics -A per-PR/channel grant is an explicit project write operation, separate from administrator-owned project-wide required channels. Requested additional maximum is between one and 1,000; additional minimum is between zero and that maximum. The service stores checked cumulative stopping thresholds while preserving consumed counts, the accounting epoch, imported provenance and original operation attribution. Cumulative counters stay within 9,007,199,254,740,991. Historical controls retain their original representation and proof; an explicit edit moves the current rule to cumulative semantics. Existing unconfigured allocations remain unconfigured when already enrolled or re-added with retained native operations; eligible missing controls receive the selected [project defaults](#project-defaults) under the [enrollment rules](#operational-controls). Earned completion follows the [PR/channel rule](reviews.md#retained-native-channel-completion) in either case. +A per-PR/channel grant is an explicit project write operation, separate from project-management configuration of project-wide required channels. Requested additional maximum is between one and 1,000; additional minimum is between zero and that maximum. The service stores checked cumulative stopping thresholds while preserving consumed counts, the accounting epoch, imported provenance and original operation attribution. Cumulative counters stay within 9,007,199,254,740,991. Historical controls retain their original representation and proof; an explicit edit moves the current rule to cumulative semantics. Existing unconfigured allocations remain unconfigured when already enrolled or re-added with retained native operations; eligible missing controls receive the selected [project defaults](#project-defaults) under the [enrollment rules](#operational-controls). Earned completion follows the [PR/channel rule](reviews.md#retained-native-channel-completion) in either case. One eligible completion has a completed native operation/attempt, validated attributable complete capture and finalized source counts. An operation counts once, independently of whether its accepted findings have been fixed. Original finalized accepted counts determine its historical streak contribution; later decision/fix corrections remain separate obligations and do not rewrite consumed rounds. Failed, rate-limited and incomplete attempts consume no completed round. Queued, preparing, posting, active and uncertain work occupies capacity. An attributable complete terminal result awaiting finalization also occupies its original capacity, without receiving completion credit early. @@ -44,7 +44,7 @@ Per-PR changes use their own revision and actor attribution rather than changing 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. -Control reads are local, compact and provider-free. Project write mutations use the ordinary authorization, expected revision, idempotency and atomic event/receipt rules. Their compact change events identify the affected PR/channel resource and its revision; the durable event cursor remains the delivery deduplication identity. Storing a grant does not authorize provider calls. Carried adoption uses the separate administrator controls below; explicit channel-front selection uses the independently durable contract below. +Control reads are local, compact and provider-free. Project write mutations use the ordinary authorization, expected revision, idempotency and atomic event/receipt rules. Their compact change events identify the affected PR/channel resource and its revision; the durable event cursor remains the delivery deduplication identity. Storing a grant does not authorize provider calls. Carried adoption uses the separate project-management controls below; explicit channel-front selection uses the independently durable contract below. ## Refusals and recovery @@ -88,7 +88,7 @@ Focused tests exercise native grant, close, taper, replay, permission and admiss ## Carried rule adoption -An administrator can preview and apply one prepared effective PR/channel rule before execution enrollment. Adoption requires revision zero, no configured destination control and no unresolved native operation for that channel. Enrollment preserves the adopted rule. Preview binds the normalized input to the instance, project, administrator and worker; apply rechecks repository identity, authority and guards transactionally. Exact-key replay returns its original receipt without overwriting subsequent changes. +A caller with `manage` permission for the selected project or instance administration, plus a valid project worker, can preview and apply one prepared effective PR/channel rule before execution enrollment. Ordinary project read/write permission is insufficient. Adoption requires revision zero, no configured destination control and no unresolved native operation for that channel. Enrollment preserves the adopted rule. Preview binds the normalized input to the instance, project, authenticated principal and worker; apply rechecks repository identity, authority and guards transactionally. Exact-key replay returns its original receipt without overwriting subsequent changes. The prepared record retains remaining minimum and maximum, dry streak, taper threshold, reached taper and closure with source identity/key and digest. Native used starts at zero: imported configuration is not a native attempt, captured result or completed round. Genuine native completions advance the carried policy. Explicit additional grants stay finite and clear minimum-only state while retaining the carried origin and cumulative history. diff --git a/docs/review-workspace.md b/docs/review-workspace.md index 928ecb2d9..f2c86d5fb 100644 --- a/docs/review-workspace.md +++ b/docs/review-workspace.md @@ -2,7 +2,7 @@ ## Implemented boundary -The service stores project-scoped review observations and serves queue, PR history, run, finding, decision and fix-proof views from its own indexed database. Importing an observation is an explicit administrator action. Ordinary reads and browser refresh make no provider calls and do not construct another controller or renderer. Jobs and messaging do not depend on the reviews domain. +The service stores project-scoped review observations and serves queue, PR history, run, finding, decision and fix-proof views from its own indexed database. Importing an observation is an explicit project-management action. Ordinary reads and browser refresh make no provider calls and do not construct another controller or renderer. Jobs and messaging do not depend on the reviews domain. This slice provides the read model for the [review engine](reviews.md). Optional native execution and revision-bound policy admission are described in the [execution boundary](review-execution.md); [automatic provider observation](github-observation.md) separately updates existing enrolled PRs and retained external Hosted history. Fresh-source aggregate policy and merge-readiness assessment remain separate contracts. Explicit [captured-comparison policy assessment](review-controls.md#captured-comparison-assessment) is a separate provider-free read. Historical counts, a completed attempt, CI success and a matching head are separate facts. This API never returns a merge-ready verdict or authorizes a merge. Projects without observations return an explicitly unconfigured workspace. @@ -12,12 +12,12 @@ All paths below are relative to `/api/v1/projects/{project_id}`. Existing instan | Method and path | Result | | --- | --- | -| `POST /reviews/observations` | Administrator-only, revision-guarded observation append with a required idempotency key. | -| `POST /reviews/import/preview` | Administrator-only, provider-free prepared observation preview; no receipt or write. | -| `POST /reviews/import/apply` | Administrator-only prepared observation apply bound to its preview, with the existing observation receipt semantics. | -| `POST /reviews/transfer/preview` | Read-only administrator preview of bounded additive original-producer history. | -| `POST /reviews/transfer/apply` | Exact preview-bound administrator additive history apply. | -| `POST /reviews/queue/edits` | Selected metadata/order edits, retirement and reactivation (administrator). | +| `POST /reviews/observations` | Project management or instance administration; revision-guarded observation append with a required idempotency key. | +| `POST /reviews/import/preview` | Project management or instance administration; provider-free prepared observation preview; no receipt or write. | +| `POST /reviews/import/apply` | Project management or instance administration; prepared observation apply bound to its preview, with the existing observation receipt semantics. | +| `POST /reviews/transfer/preview` | Project management or instance administration; read-only preview of bounded additive original-producer history. | +| `POST /reviews/transfer/apply` | Project management or instance administration; exact preview-bound additive history apply. | +| `POST /reviews/queue/edits` | Selected metadata/order edits, retirement and reactivation (project management or instance administration). | | `GET /reviews/queue` | Compact ordered PR summaries, including merged and closed history. | | `GET /reviews/pulls/{number}` | One compact PR summary; no lifetime attempt array. | | `GET /reviews/pulls/{number}/attempts` | Newest-first original-producer attempt archive with cursor pagination. | @@ -28,9 +28,9 @@ Queue, run and attempt lists default to 20 items and accept `limit` up to 100 an Cursors bind the principal, project, route, order and retained snapshot. New imports cannot change a continuation page from an older snapshot. Detail links retain that snapshot for consistent drill-down. Access is checked again on every request, including historical reads and exact mutation retries. Unknown, duplicate and malformed query fields are rejected. PR numbers use canonical positive decimal values through 2147483647. -## Administrator observations +## Project-managed observations -The [prepared import contract](review-import.md) owns guided preview/apply and profile-bound administrator CLI commands. These routes share the observation transaction below; preview does not reserve a workspace revision. +Observation append requires `manage` permission for the selected project or instance administration; ordinary project read/write permission is insufficient. The [prepared import contract](review-import.md#selected-sources-and-destination) owns guided preview/apply and profile-bound CLI/MCP commands. These routes share the observation transaction below; preview does not reserve a workspace revision. The strict JSON body requires `expected_revision` (zero for the first observation), the configured stable GitHub `repository_id`, a bounded `source`, an RFC3339 `observed_at`, ordered `queue` entries and explicit `retired` entries. Omitted arrays normalize to empty arrays. The body and its normalized form are bounded to 256 KiB. A changed request under an existing idempotency key conflicts; an exact retained replay returns the original receipt before re-evaluating the revision. Replay still requires current authorization. @@ -64,7 +64,7 @@ Merged PRs remain in the queue as completed history. Removing a previously visib The browser exposes Reviews, PR history and run-finding pages, with source timestamps, incomplete or missing data, head mismatches, historical counts and source coverage limitations visible. It escapes imported text and generates external PR/commit links only from the verified project repository. It does not render imported HTML or accept arbitrary link destinations. “Refresh visible data” rereads the stored snapshot; it neither refreshes GitHub nor starts a review. These pages have no timer-based polling or new live transport. The [browser guide](browser-guide.md) owns connection privacy and packaging. -An initial installation may populate this boundary through a small explicit import. Profile-bound CLI commands `reviews queue`, `reviews pull`, `reviews runs`, `reviews attempts` and `reviews run`, plus the five matching [MCP read tools](mcp.md), inspect these stored projections without provider work. Queue/run/attempt tools default to five entries, while explicit run detail loads full findings. Snapshot selectors retain historical consistency. Startup conversion is limited to the supported retained-review schema. Optional [native executors](review-execution.md) publish retained native evidence through their own trusted path. Review observation writes are not exposed as worker tools. +An initial installation may populate this boundary through a small explicit import. Profile-bound CLI commands `reviews queue`, `reviews pull`, `reviews runs`, `reviews attempts` and `reviews run`, plus the five matching [MCP read tools](mcp.md), inspect these stored projections without provider work. Queue/run/attempt tools default to five entries, while explicit run detail loads full findings. Snapshot selectors retain historical consistency. Startup conversion is limited to the supported retained-review schema. Optional [native executors](review-execution.md) publish retained native evidence through their own trusted path. Direct observation append is not exposed as a worker tool; explicit prepared import and transfer use the project-management CLI/MCP boundary. ## Validation status @@ -80,11 +80,11 @@ These checks use synthetic observations on Linux/WSL Chromium. They do not estab ### Selected queue edits -Administrator queue edits maintain selected stored metadata, relative ordering and explicit retirement/reactivation without resubmitting a complete retained workspace. They are an administrator maintenance boundary, not another ordinary worker enrollment step. +Project-management queue edits maintain selected stored metadata, relative ordering and explicit retirement/reactivation without resubmitting a complete retained workspace. They are a project-management maintenance boundary, not another ordinary worker enrollment step. Complete observations replace a small workspace and retain their per-request bounds. A large workspace uses additive transfer for selected history and `POST /api/v1/projects/{project_id}/reviews/queue/edits` for selected metadata, retirement and reactivation. Neither operation requires a complete project export or a lifetime PR ceiling. -Queue edits require administrator access, an explicit idempotency key, the current `expected_revision`, the configured `repository_id` and a bounded `source` label for administrator provenance. The strict JSON document is limited to 256 KiB. Its `queue` and `retired` arrays select at most one hundred entries in total, with unique, disjoint PR numbers. At least one entry is required unless `order` is supplied. Omitted metadata and retirement arrays become empty; explicit null fields, unknown fields and duplicate keys are refused. +Queue edits require `manage` permission for the selected project or instance administration, an explicit idempotency key, the current `expected_revision`, the configured `repository_id` and a bounded `source` label for management provenance. The strict JSON document is limited to 256 KiB. Its `queue` and `retired` arrays select at most one hundred entries in total, with unique, disjoint PR numbers. At least one entry is required unless `order` is supplied. Omitted metadata and retirement arrays become empty; explicit null fields, unknown fields and duplicate keys are refused. Each `queue` entry contains `number`, `title`, `state`, `head_sha`, `base_ref`, `base_sha`, `ci_state` and `mergeability`, with optional `diff`, `is_draft` and `merged_at` under the [PR display metadata contract](#optional-pr-display-metadata). CI permits `unknown`, `pending`, `success`, `failure` and `not_required`. Omitted optional SHA/base strings become empty. Runs, attempts, findings, counts and completeness cannot be supplied. Without an explicit order, an existing PR keeps its position and retained producer histories; changing its head clears completeness. A new or previously absent PR appends with partial coverage. Explicitly selecting a retired PR reactivates it without inventing review evidence. @@ -94,13 +94,13 @@ Each `retired` entry names a currently visible PR and its `superseded` or `defun Omitted PRs and records remain unchanged. Revision admission, the new snapshot, history references, compact summaries, receipt, event and public projection refresh commit together. A queue edit inherits the prior observation time and does no provider work; it cannot claim freshly collected source facts. Exact original-key replay returns its original receipt after later changes or restart, subject to current authorization. A changed request under the same key conflicts. Successful HTTP 201 returns only the snapshot `id`, new `revision` and `outcome: queue_edited`. -The bound administrator CLI is: +The bound project-management CLI is: ```sh fc reviews queue-edit --file /private/queue-edit.json --key retained-action-key ``` -It validates a bounded regular file before credentials or network access, retains the ordinary five-second budget and never generates a key or retries automatically. A lost or invalid mutation response requires recovery with the original request, key and binding. MCP `review_queue_edit` sends the same native document and explicit `idempotency_key`; service administrator admission still applies. It does not request reviews or change scheduling configuration. +It validates a bounded regular file before credentials or network access, retains the ordinary five-second budget and never generates a key or retries automatically. A lost or invalid mutation response requires recovery with the original request, key and binding. MCP `review_queue_edit` sends the same native document and explicit `idempotency_key`; the same project-management or instance-administration admission still applies, including on original-key replay. It does not request reviews or change scheduling configuration. Focused regressions grow the workspace through actual native publication beyond 200 PRs, apply selected edits without dropping omitted merged history, preserve original cursor/detail and evidence bytes, retain retirement through later native publication, and prove exact original-key replay after intervening edits and database reopen. Optional-metadata, relative-order, rollback and client tests cover the same selected-edit boundary. CLI and SDK MCP tests exercise strict/authenticated native calls and lost-receipt recovery. These source checks do not establish live-provider behavior or installed rollout. diff --git a/docs/worker-retirement.md b/docs/worker-retirement.md new file mode 100644 index 000000000..e208f718c --- /dev/null +++ b/docs/worker-retirement.md @@ -0,0 +1,21 @@ +# Worker retirement + +Retirement removes a worker from ordinary active lists and new coordination targets while preserving its identity and history. Completed jobs, conversations, focus and pause history remain readable. Fresh focus and pause mutations are rejected after retirement; exact earlier receipts remain replayable without another effect. Credentials remain separate project access controls; retirement never revokes them or cancels review operations. + +## Clear unfinished work first + +Preview reports exact totals and up to twenty IDs for unfinished assigned jobs, pending notes attached directly to the worker or to its assigned jobs, and unacknowledged incoming messages. Reassign or complete jobs, move/consume/dismiss notes and explicitly acknowledge messages first. Retirement performs none of that cleanup automatically. + +The mutation rechecks blockers in the same transaction as retirement. Concurrent job assignment, reopened work, pending-note targeting and message delivery either prevent retirement or are rejected after it. New message sends also require an active sender. Historical references and exact prior receipt replay remain valid. + +## Native operations + +GET `/api/v1/projects/{project_id}/workers/{worker_id}/retirement` reads preview. POST to the sibling `/retire` route takes `{}` and an explicit key with ordinary project-write permission. A successful receipt contains the worker ID, revision two and `retired`; another deliberate retirement returns `unchanged`. `worker_retirement_blocked` includes current blocker handles; active-target admission returns `worker_retired`. Keep the exact key after an unknown outcome. + +CLI exposes `workers retirement WORKER_ID`, `workers retire WORKER_ID --key KEY`, and `workers list --include-retired`. MCP exposes `worker_retirement_read`, `worker_retire` and the explicit `workers_list.include_retired` option. Cursors are bound to active versus archive views. Direct worker reads retain historical identities. + +Any project reader may inspect a selected worker's inbox. Acknowledging a message for another recipient requires project management, using `inbox ack MESSAGE_ID --worker WORKER_ID --key KEY` or MCP `inbox_ack` with `worker_id`. The selected recipient is in the request body; the authenticated principal and actual acting worker are unchanged. Current management is checked before receipt replay and inside the mutation. Ordinary empty-body acknowledgement keeps its original wire and receipt identity. Added durable acting-worker audit detail is not exposed through the legacy incoming-message feed. + +## Persistence and scope + +The additive `worker_retirements:1` domain retains worker-table identities and foreign keys. Backups and inactive restore preserve retirement facts and reject malformed physical schemas or records. Existing bundles need no inspection-time migration. Native tests cover blockers, races, historical reads, peer acknowledgement, exact-key recovery and backup compatibility. Browser retirement controls, Delivery lanes and automatic scheduling remain later capabilities rather than implied by this native prerequisite. diff --git a/internal/backup/administration_cancel_test.go b/internal/backup/administration_cancel_test.go new file mode 100644 index 000000000..d07f0dac0 --- /dev/null +++ b/internal/backup/administration_cancel_test.go @@ -0,0 +1,221 @@ +package backup + +import ( + "context" + "database/sql" + "errors" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +// Intercept only the selected semantic query, leaving schema reads untouched. +type administrationCancellationReader struct { + sqlReader + cancel context.CancelFunc + phase string + once sync.Once + fired bool +} + +func (r *administrationCancellationReader) interrupt(query string) { + match := r.phase == "project_management" && strings.HasPrefix(query, "SELECT COUNT(*) FROM grants WHERE typeof(can_manage)") || r.phase == "worker_retirements" && strings.Contains(query, "FROM worker_retirements r LEFT JOIN workers") + match = match || r.phase == "grants_schema" && strings.Contains(query, "FROM sqlite_schema WHERE type='table' AND name='grants'") + if match { + r.once.Do(func() { r.fired = true; r.cancel() }) + } +} +func (r *administrationCancellationReader) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + r.interrupt(query) + return r.sqlReader.QueryRowContext(ctx, query, args...) +} +func (r *administrationCancellationReader) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + if r.phase == "retirement_schema" && strings.Contains(query, "FROM sqlite_schema") { + for _, arg := range args { + if arg == "worker_retirements" { + r.once.Do(func() { r.fired = true; r.cancel() }) + } + } + } + r.interrupt(query) + return r.sqlReader.QueryContext(ctx, query, args...) +} + +func TestAdministrationQueryCancellationIsUnavailableAndRetryable(t *testing.T) { + for _, phase := range []string{"project_management", "worker_retirements"} { + t.Run(phase, func(t *testing.T) { + store, err := core.Open(t.Context(), filepath.Join(t.TempDir(), "source")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + versions, err := validateSchema(t.Context(), store.DB(), false) + if err != nil { + t.Fatal(err) + } + before := backupRows(t, store.DB()) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + reader := &administrationCancellationReader{sqlReader: store.DB(), cancel: cancel, phase: phase} + err = validateAdministrationContent(ctx, reader, versions) + if !reader.fired || !errors.Is(ctx.Err(), context.Canceled) { + t.Fatal("selected SQL query was not interrupted", err) + } + backupCode(t, err, "backup_unavailable") + if !reflect.DeepEqual(before, backupRows(t, store.DB())) { + t.Fatal("validation changed source") + } + if err := validateAdministrationContent(t.Context(), store.DB(), versions); err != nil { + t.Fatal("retry failed", err) + } + }) + } +} + +// Intercept database/sql's context check in the real semantic validator, +// rather than canceling before the operation starts. Stack selection avoids +// production hooks, sleeps, and dependence on query timing. +type administrationOperationCancellation struct { + context.Context + cancel context.CancelFunc + phase string + operation string + target string + once sync.Once + fired atomic.Bool + copied atomic.Bool +} + +func (c *administrationOperationCancellation) Done() <-chan struct{} { + if c.Context.Err() == nil { + var pcs [64]uintptr + n := runtime.Callers(2, pcs[:]) + frames := runtime.CallersFrames(pcs[:n]) + administration, retirement, sqlQuery, inspecting := false, false, false, false + for { + frame, more := frames.Next() + administration = administration || frame.Function == "github.com/benhook1013/FireController/internal/backup.validateAdministrationContent" + retirement = retirement || frame.Function == "github.com/benhook1013/FireController/internal/core.ValidateWorkerRetirementsSnapshot" + sqlQuery = sqlQuery || frame.Function == "database/sql.(*Tx).QueryContext" + inspecting = inspecting || frame.Function == "github.com/benhook1013/FireController/internal/backup.inspectManifest" + if !more { + break + } + } + selected := administration && sqlQuery && ((c.phase == "worker_retirements") == retirement) + if c.operation == "restore_post_copy" { + selected = selected && !inspecting + } + if selected { + c.once.Do(func() { + if info, err := os.Stat(filepath.Join(c.target, "firecontroller.sqlite")); err == nil && info.Size() > 0 { + c.copied.Store(true) + } + c.fired.Store(true) + c.cancel() + }) + } + } + return c.Context.Done() +} + +func TestAdministrationOperationCancellationIsUnavailableAndRetryable(t *testing.T) { + for _, operation := range []string{"inspect", "restore", "restore_post_copy", "create", "managed_create"} { + for _, phase := range []string{"project_management", "worker_retirements"} { + t.Run(operation+"/"+phase, func(t *testing.T) { + source := filepath.Join(t.TempDir(), "source") + store, err := core.Open(t.Context(), source) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + versions, err := validateSchema(t.Context(), store.DB(), false) + if err != nil || versions["project_management"] != 1 || versions["worker_retirements"] != 1 || versions["recovery_history"] != 0 { + t.Fatal("fixture must select the two administration validators without recovery history", versions, err) + } + bundle, err := Create(t.Context(), store, source, filepath.Join(t.TempDir(), "bundles")) + if err != nil { + t.Fatal(err) + } + beforeBundle := restoreTree(t, bundle.Path) + beforeSource := backupRows(t, store.DB()) + target := filepath.Join(t.TempDir(), "destination") + run := func(ctx context.Context) error { + switch operation { + case "inspect": + _, err := Inspect(ctx, bundle.Path) + return err + case "restore", "restore_post_copy": + _, err := Restore(ctx, bundle.Path, target) + return err + case "create": + _, err := Create(ctx, store, source, target) + return err + default: + _, err := createManaged(ctx, store, source, target) + return err + } + } + base, cancel := context.WithCancel(t.Context()) + defer cancel() + ctx := &administrationOperationCancellation{Context: base, cancel: cancel, phase: phase, operation: operation, target: target} + err = run(ctx) + if !ctx.fired.Load() || !errors.Is(base.Err(), context.Canceled) { + t.Fatal("operation context was not canceled", err) + } + backupCode(t, err, "backup_unavailable") + if ctx.copied.Load() != (operation == "restore_post_copy") { + t.Fatal("cancellation reached the wrong restore copy phase", ctx.copied.Load()) + } + if operation == "create" || operation == "managed_create" { + entries, err := os.ReadDir(target) + if err != nil && !errors.Is(err, os.ErrNotExist) || len(entries) != 0 { + t.Fatal("interrupted validation retained an unpublished bundle", entries, err) + } + } else if _, err := os.Lstat(target); !errors.Is(err, os.ErrNotExist) { + t.Fatal("interrupted verification created a restore destination", err) + } + if !reflect.DeepEqual(beforeBundle, restoreTree(t, bundle.Path)) || !reflect.DeepEqual(beforeSource, backupRows(t, store.DB())) { + t.Fatal("interrupted validation changed the source or bundle") + } + if err := run(t.Context()); err != nil { + t.Fatal("uncanceled retry failed", err) + } + }) + } + } +} + +func TestAdministrationSchemaCancellationIsUnavailableAndRetryable(t *testing.T) { + for _, phase := range []string{"grants_schema", "retirement_schema"} { + t.Run(phase, func(t *testing.T) { + store, err := core.Open(t.Context(), filepath.Join(t.TempDir(), "source")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + before := backupRows(t, store.DB()) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + reader := &administrationCancellationReader{sqlReader: store.DB(), cancel: cancel, phase: phase} + _, err = validateSchema(ctx, reader, false) + if !reader.fired || !errors.Is(ctx.Err(), context.Canceled) { + t.Fatal("selected schema query not interrupted", err) + } + backupCode(t, err, "backup_unavailable") + if !reflect.DeepEqual(before, backupRows(t, store.DB())) { + t.Fatal("schema validation changed source") + } + if _, err := validateSchema(t.Context(), store.DB(), false); err != nil { + t.Fatal("retry failed", err) + } + }) + } +} diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index 0c0173d44..8f0489a9d 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -15,6 +15,7 @@ import ( "strings" "github.com/benhook1013/FireController/internal/adoptionholds" + "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/jobs" "github.com/benhook1013/FireController/internal/presentation" "github.com/benhook1013/FireController/internal/projectmap" @@ -221,9 +222,10 @@ type tableVersion struct { // Fixed application schema bounds are intentionally independent of migration // execution. Inspection never opens a Store or installs/rewrites a schema. -var supportedDomains = map[string]int{"review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 3, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"project_management": 1, "worker_retirements": 1, "review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 3, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} var tables = map[string]tableVersion{ "review_operation_waits": {"review_execution", 9, "operation_id baseline_attempt_id retry_not_before paused"}, + "worker_retirements": {"worker_retirements", 1, "project_id worker_id retired_at actor_id"}, "review_selections": {"review_selection", 1, "id project_id actor_id worker_id channel configuration_revision policy_revision capability_fingerprint expected_pull_number state reason revision operation_id created_at updated_at"}, "review_hosted_discovery_state": {"reviews", 11, "project_id repository_id pull_number cutoff_at initialized_at"}, "review_pull_versions": {"reviews", 4, "project_id number version_revision title state head_sha base_ref base_sha ci_state mergeability complete run_count attempt_count recent_runs_json latest_attempts_json"}, @@ -595,6 +597,23 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, err } } + if versions["project_management"] > 0 { + var statement string + if err := db.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(sql AS BLOB))<=16384 THEN sql ELSE NULL END FROM sqlite_schema WHERE type='table' AND name='grants'`).Scan(&statement); err != nil || historyDefinitionSQL(statement) != historyDefinitionSQL(`CREATE TABLE grants(credential_id TEXT NOT NULL REFERENCES credentials(id),project_id TEXT NOT NULL REFERENCES projects(id),can_read INTEGER NOT NULL CHECK(can_read IN(0,1)),can_write INTEGER NOT NULL CHECK(can_write IN(0,1)), can_manage INTEGER NOT NULL DEFAULT 0 CHECK(can_manage IN(0,1) AND (can_manage=0 OR (can_read=1 AND can_write=1))),PRIMARY KEY(credential_id,project_id))`) { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, invalid() + } + } + if versions["worker_retirements"] > 0 { + if err := validatePhysicalSchemaObjects(ctx, db, map[string]physicalSchemaObject{"worker_retirements": {"table", `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`}}, []string{"worker_retirements"}); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } + } if versions["review_execution"] >= 9 { // Schema nine owns durable wait identity and paired retry state even // when the bundle has no wait rows to exercise these constraints. @@ -635,6 +654,9 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ continue } columns := spec.columns + if name == "grants" && versions["project_management"] > 0 { + columns += " can_manage" + } if name == "review_current_totals" && versions["reviews"] >= 9 { columns += " hosted_run_count cli_run_count subagent_run_count manual_run_count" } @@ -702,6 +724,10 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ columnRows.Close() return nil, invalid() } + if name == "grants" && col == "can_manage" && (kind != "INTEGER" || notnull != 1 || defaultValue != "0" || pk != 0) { + columnRows.Close() + return nil, invalid() + } if name == "receipts" && (kind != "TEXT" || notnull != 1 || defaultValue != nil || pk != receiptPK[col]) { columnRows.Close() return nil, invalid() @@ -861,6 +887,9 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al return invalid() } } + if err := validateAdministrationContent(ctx, tx, versions); err != nil { + return err + } var identity, key string var sequence int64 if tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='instance_id'`).Scan(&identity) != nil || identity != m.SourceInstanceID || !instanceID.MatchString(identity) || tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='signing_key'`).Scan(&key) != nil || !digest.MatchString(key) || tx.QueryRowContext(ctx, `SELECT coalesce(max(sequence),0) FROM events`).Scan(&sequence) != nil || sequence != m.EventSequence { @@ -1238,6 +1267,7 @@ var canonicalForeignKeys = map[string][]foreignKey{ "job_checklist_history": {canonicalFK("jobs", "project_id,job_id", "project_id,id", "CASCADE")}, "restore_history": {}, "workers": {canonicalFK("projects", "project_id", "id", "NO ACTION")}, + "worker_retirements": {canonicalFK("projects", "project_id", "id", "NO ACTION"), canonicalFK("workers", "project_id,worker_id", "project_id,id", "NO ACTION")}, "grants": {canonicalFK("credentials", "credential_id", "id", "NO ACTION"), canonicalFK("projects", "project_id", "id", "NO ACTION")}, "events": {canonicalFK("projects", "project_id", "id", "NO ACTION")}, "jobs": {canonicalFK("projects", "project_id", "id", "CASCADE"), canonicalFK("workers", "project_id,worker_id", "project_id,id", "NO ACTION")}, @@ -1574,3 +1604,24 @@ func validateExternalHostedEvidenceIndexes(ctx context.Context, db sqlReader, ve } return nil } + +func validateAdministrationContent(ctx context.Context, db sqlReader, versions map[string]int) error { + if versions["project_management"] > 0 { + var bad int + if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM grants WHERE typeof(can_manage)<>'integer' OR can_manage NOT IN (0,1) OR (can_manage=1 AND (can_read<>1 OR can_write<>1))`).Scan(&bad); err != nil || bad != 0 { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } + if versions["worker_retirements"] > 0 { + if err := core.ValidateWorkerRetirementsSnapshot(ctx, db); err != nil { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } + return nil +} diff --git a/internal/backup/project_management_compatibility_test.go b/internal/backup/project_management_compatibility_test.go new file mode 100644 index 000000000..b21c5841b --- /dev/null +++ b/internal/backup/project_management_compatibility_test.go @@ -0,0 +1,72 @@ +package backup + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestProjectManagementRealParentBundleRemainsInactive(t *testing.T) { + root := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if root == "" { + t.Skip("requires genuine pinned-parent bundle") + } + provenance, err := os.ReadFile(filepath.Join(root, "parent-commit")) + if err != nil || strings.TrimSpace(string(provenance)) != "383ce8c0bc4505dd89cf5cdec7fb2da1d7e556c8" { + t.Fatal("fixture must come from pinned predecessor", err) + } + matches, err := filepath.Glob(filepath.Join(root, "backup_*")) + if err != nil || len(matches) != 1 { + t.Fatal("parent bundle missing", err) + } + bundle := matches[0] + if _, err := Inspect(t.Context(), bundle); err != nil { + t.Fatal(err) + } + dir := filepath.Join(t.TempDir(), "restored") + if _, err := Restore(t.Context(), bundle, dir); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var live, domains int + if err := db.QueryRow(`SELECT count(*) FROM credentials WHERE revoked=0`).Scan(&live); err != nil || live != 0 { + t.Fatal("old credentials revived", live, err) + } + if err := db.QueryRow(`SELECT count(*) FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`).Scan(&domains); err != nil || domains != 0 { + t.Fatal("inspection/restore migrated old bundle", domains, err) + } +} +func TestProjectManagementBackupRejectsResealedAuthorityCorruption(t *testing.T) { + for _, statement := range []string{ + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=sql || replace(hex(zeroblob(8192)),'0',' ') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'CHECK(can_manage IN(0,1) AND (can_manage=0 OR (can_read=1 AND can_write=1)))','CHECK(1)') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `UPDATE metadata SET value='2' WHERE key='schema:project_management'`, + `DELETE FROM metadata WHERE key='schema:project_management'`, + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'DEFAULT 0','DEFAULT 1') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'can_manage INTEGER NOT NULL','can_manage TEXT NOT NULL') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `PRAGMA ignore_check_constraints=ON; UPDATE grants SET can_manage=0.5; PRAGMA ignore_check_constraints=OFF`, + `PRAGMA ignore_check_constraints=ON; UPDATE grants SET can_manage=1,can_write=0; PRAGMA ignore_check_constraints=OFF`, + `PRAGMA foreign_keys=OFF; UPDATE grants SET credential_id='missing'; PRAGMA foreign_keys=ON`, + } { + t.Run(statement, func(t *testing.T) { + f := newRestoreFixture(t) + bundle := restoreBundle(t, f) + mutateBundleSQL(t, bundle.Path, statement) + if _, err := Inspect(t.Context(), bundle.Path); err == nil { + t.Fatal("corrupt management accepted") + } + dest := filepath.Join(t.TempDir(), "must-not-exist") + if _, err := Restore(t.Context(), bundle.Path, dest); err == nil { + t.Fatal("corrupt management restored") + } + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatal("target written before validation", err) + } + }) + } +} diff --git a/internal/backup/project_management_test.go b/internal/backup/project_management_test.go new file mode 100644 index 000000000..bab43e8f3 --- /dev/null +++ b/internal/backup/project_management_test.go @@ -0,0 +1,70 @@ +package backup + +import ( + "path/filepath" + "testing" +) + +func TestProjectManagementBackupRetainsOnlyExplicitScopedManagement(t *testing.T) { + f := newRestoreFixture(t) + var credential string + if err := f.store.DB().QueryRow(`SELECT credential_id FROM grants WHERE project_id=? AND can_write=1 LIMIT 1`, f.project).Scan(&credential); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1,can_read=1,can_write=1 WHERE credential_id=? AND project_id=?`, credential, f.project); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + dest := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), bundle.Path, dest); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dest, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var version string + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:project_management'`).Scan(&version); err != nil || version != "1" { + t.Fatal("management format gate lost", version, err) + } + var total, selected, live int + if err := db.QueryRow(`SELECT COUNT(*) FROM grants WHERE can_manage=1`).Scan(&total); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT COUNT(*) FROM grants WHERE credential_id=? AND project_id=? AND can_manage=1 AND can_read=1 AND can_write=1`, credential, f.project).Scan(&selected); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT COUNT(*) FROM credentials WHERE revoked=0`).Scan(&live); err != nil { + t.Fatal(err) + } + if total != 1 || selected != 1 || live != 0 { + t.Fatal("management broadened or restored access revived", total, selected, live) + } +} + +func TestProjectManagementBackupRefusesContradictoryGrant(t *testing.T) { + f := newRestoreFixture(t) + connection, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + if _, err = connection.ExecContext(t.Context(), `PRAGMA ignore_check_constraints=ON`); err != nil { + t.Fatal(err) + } + if _, err = connection.ExecContext(t.Context(), `UPDATE grants SET can_manage=1,can_write=0 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + if _, err = connection.ExecContext(t.Context(), `PRAGMA ignore_check_constraints=OFF`); err != nil { + t.Fatal(err) + } + if err = connection.Close(); err != nil { + t.Fatal(err) + } + if _, err := Create(t.Context(), f.store, f.dir, filepath.Join(t.TempDir(), "bundles")); err == nil { + t.Fatal("contradictory management authority accepted") + } +} diff --git a/internal/backup/worker_retirement_test.go b/internal/backup/worker_retirement_test.go new file mode 100644 index 000000000..df70ee8a5 --- /dev/null +++ b/internal/backup/worker_retirement_test.go @@ -0,0 +1,64 @@ +package backup + +import ( + "github.com/benhook1013/FireController/internal/core" + "path/filepath" + "testing" +) + +func retirementBackup(t *testing.T) (*restoreFixture, string, Summary) { + t.Helper() + f := newRestoreFixture(t) + worker := core.NewID("worker") + if _, err := f.store.DB().Exec(`INSERT INTO workers(project_id,id,name) VALUES(?,?,?)`, f.project, worker, "Retired worker"); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES(?,?,?,?)`, f.project, worker, "2026-11-01T00:00:00Z", "principal-backup-proof"); err != nil { + t.Fatal(err) + } + return f, worker, restoreBundle(t, f) +} + +func TestWorkerRetirementBackupPreservesIdentityAndRetirement(t *testing.T) { + _, worker, bundle := retirementBackup(t) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + dest := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), bundle.Path, dest); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dest, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var name, at, actor, version string + if err := db.QueryRow(`SELECT w.name,r.retired_at,r.actor_id FROM workers w JOIN worker_retirements r ON r.project_id=w.project_id AND r.worker_id=w.id WHERE w.id=?`, worker).Scan(&name, &at, &actor); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:worker_retirements'`).Scan(&version); err != nil || version != "1" || name != "Retired worker" || at != "2026-11-01T00:00:00Z" || actor != "principal-backup-proof" { + t.Fatal(name, at, actor, version, err) + } +} + +func TestWorkerRetirementBackupRejectsMalformedFacts(t *testing.T) { + for _, statement := range []string{ + `UPDATE worker_retirements SET retired_at='invalid'`, + `UPDATE worker_retirements SET actor_id=''`, + `UPDATE metadata SET value='2' WHERE key='schema:worker_retirements'`, + `DELETE FROM metadata WHERE key='schema:worker_retirements'`, + } { + t.Run(statement, func(t *testing.T) { + _, _, bundle := retirementBackup(t) + mutateBundleSQL(t, bundle.Path, statement) + if _, err := Inspect(t.Context(), bundle.Path); err == nil { + t.Fatal("malformed retirement accepted") + } + dest := filepath.Join(t.TempDir(), "must-not-exist") + if _, err := Restore(t.Context(), bundle.Path, dest); err == nil { + t.Fatal("malformed retirement restored") + } + }) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 843393183..ecdbb3cf5 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -46,6 +46,8 @@ type options struct { } type invocation struct { + ownerManagement *ownerManagementInvocation + includeRetired bool ciWatch *ciWatchInvocation reviewRun *reviewRunInvocation operationHelp string @@ -100,6 +102,11 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou } return report(stderr, ExitUsage, "invalid_arguments", "The command or its arguments are not supported.", action) } + if call.ownerManagement != nil { + if err := prepareOwnerManagement(ctx, call.ownerManagement); err != nil { + return reportClientError(stderr, err, ctx) + } + } if call.operationHelp != "" { return emitOperationHelp(call.operationHelp, stdout, stderr) } @@ -280,6 +287,9 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou } return emit(stdout, stderr, value) } + if call.ownerManagement != nil { + return executeOwnerManagement(requestCtx, ctx, service, call.ownerManagement, stdout, stderr) + } if call.mutation != nil { value, err := executeMutation(requestCtx, service, call.mutation) if err != nil { @@ -308,7 +318,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou case call.command == "workers" && call.subcommand == "pause-history": value, err = service.WorkerPauseHistory(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}) case call.command == "workers": - value, err = service.Workers(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}) + value, err = service.WorkersWithRetired(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, call.includeRetired) case call.command == "jobs" && call.subcommand == "context": value, err = service.JobContext(requestCtx, call.position[0], call.limit) case call.command == "jobs" && call.subcommand == "primary": @@ -334,7 +344,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou case call.command == "jobs" && call.subcommand == "checklist-history": value, err = service.JobChecklistHistory(requestCtx, call.position[0], client.PageOptions{Limit: call.limit, Cursor: call.cursor}) case call.command == "inbox" && call.subcommand == "list": - value, err = service.Inbox(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, client.InboxFilter{Unread: call.unread, Unacknowledged: call.unack}) + value, err = service.Inbox(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, client.InboxFilter{Unread: call.unread, Unacknowledged: call.unack}, call.worker) case call.command == "inbox" && call.subcommand == "snapshot": value, err = service.InboxSnapshot(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, client.InboxFilter{Unread: call.unread, Unacknowledged: call.unack}) case call.command == "inbox" && call.subcommand == "wait": @@ -403,6 +413,14 @@ func parseInvocation(args []string) (invocation, bool) { return call, false } call.command = remaining[0] + if len(remaining) == 2 && (remaining[1] == "help" || remaining[1] == "--help") && (call.command == "credentials" || call.command == "workers" || call.command == "reviews") { + call.operationHelp = call.command + " help" + return call, true + } + if len(remaining) == 3 && remaining[0] == "help" && ownerManagementOperation(remaining[1]+" "+remaining[2]) { + call.operationHelp = remaining[1] + " " + remaining[2] + return call, true + } if len(remaining) == 3 && remaining[0] == "help" && remaining[1] == "reviews" && (remaining[2] == "operations" || remaining[2] == "operation-control" || remaining[2] == "operation") { call.operationHelp = remaining[2] return call, true @@ -419,11 +437,20 @@ func parseInvocation(args []string) (invocation, bool) { call.setup, ok = parseProfileSetup(call.subcommand, remaining[2:]) return call, ok && (!call.hasProfile || validSetupText(call.profile)) && (!call.hasProfilesFile || validSetupText(call.profilesFile)) } - if call.command != "workers" && call.command != "jobs" && call.command != "inbox" && call.command != "reviews" && call.command != "notes" && call.command != "map" && call.command != "presentation" && call.command != "publication" || len(remaining) < 2 { + if call.command != "workers" && call.command != "jobs" && call.command != "inbox" && call.command != "reviews" && call.command != "notes" && call.command != "map" && call.command != "presentation" && call.command != "publication" && call.command != "credentials" || len(remaining) < 2 { return call, false } call.subcommand = remaining[1] operationArgs := remaining[2:] + if ownerManagementOperation(call.command + " " + call.subcommand) { + if len(operationArgs) == 1 && operationArgs[0] == "--help" { + call.operationHelp = call.command + " " + call.subcommand + return call, true + } + var ok bool + call.ownerManagement, ok = parseOwnerManagement(call.command+" "+call.subcommand, operationArgs) + return call, ok + } if call.command == "reviews" && (call.subcommand == "ci-wait" || call.subcommand == "operations" || call.subcommand == "operation-control" || call.subcommand == "operation" || call.subcommand == "start" || call.subcommand == "run-read") && len(operationArgs) == 1 && operationArgs[0] == "--help" { call.operationHelp = call.subcommand return call, true @@ -493,6 +520,7 @@ func parseInvocation(args []string) (invocation, bool) { case "jobs assigned": allowed["--limit"], allowed["--cursor"], allowed["--status"] = true, true, true case "inbox list": + allowed["--worker"] = true allowed["--limit"], allowed["--cursor"], allowed["--unread"], allowed["--unacknowledged"] = true, true, true, true case "inbox snapshot": allowed["--limit"], allowed["--cursor"], allowed["--unread"], allowed["--unacknowledged"] = true, true, true, true @@ -502,6 +530,9 @@ func parseInvocation(args []string) (invocation, bool) { default: return call, false } + if call.command == "workers" && call.subcommand == "list" { + allowed["--include-retired"] = true + } seen := make(map[string]bool) for i := 0; i < len(operationArgs); i++ { argument := operationArgs[i] @@ -515,6 +546,11 @@ func parseInvocation(args []string) (invocation, bool) { } seen[flag] = true switch flag { + case "--include-retired": + if assigned { + return call, false + } + call.includeRetired = true case "--unread": if assigned { return call, false diff --git a/internal/cli/mutations.go b/internal/cli/mutations.go index 90cd65e33..147afe415 100644 --- a/internal/cli/mutations.go +++ b/internal/cli/mutations.go @@ -10,6 +10,7 @@ import ( ) type mutationInvocation struct { + targetWorker string reviewCheckpoint client.ReviewCheckpointRequest reviewCheckpointRecovery client.ReviewCheckpointRecovery operation string @@ -73,6 +74,8 @@ func parseMutation(command, operation string, args []string) (*mutationInvocatio call := &mutationInvocation{operation: command + " " + operation} allowed := map[string]bool{"--key": true} switch call.operation { + case "inbox ack": + allowed["--worker"] = true case "jobs create", "jobs edit": for _, flag := range []string{"--title", "--brief", "--worker", "--status"} { allowed[flag] = true @@ -131,9 +134,10 @@ func parseMutation(command, operation string, args []string) (*mutationInvocatio if len(values["--brief"]) > 32<<10 { return nil, false } - if worker := values["--worker"]; worker != "" && !validResourceID(worker) { + if worker, present := values["--worker"]; present && (worker != "" || call.operation == "inbox ack") && !validResourceID(worker) { return nil, false } + call.targetWorker = values["--worker"] if status, present := values["--status"]; present && !validStatus(status) { return nil, false } @@ -217,6 +221,6 @@ func executeMutation(ctx context.Context, service *client.Client, call *mutation case "reviews finalize": return service.FinalizeReviewSource(ctx, call.key, call.id, call.reviewFinalize) default: - return service.Acknowledge(ctx, call.key, call.id) + return service.Acknowledge(ctx, call.key, call.id, call.targetWorker) } } diff --git a/internal/cli/operation_help.go b/internal/cli/operation_help.go index f6d64342f..533541c84 100644 --- a/internal/cli/operation_help.go +++ b/internal/cli/operation_help.go @@ -2,7 +2,22 @@ package cli import "io" +type operationHelpResponse struct { + Usage string `json:"usage"` + Required []string `json:"required"` + Optional []string `json:"optional"` + Semantics []string `json:"semantics"` + Example string `json:"example"` + FileExample map[string]any `json:"file_example,omitempty"` + FileFields map[string]string `json:"file_fields,omitempty"` + Next string `json:"next,omitempty"` + Documentation string `json:"documentation"` +} + func emitOperationHelp(operation string, stdout, stderr io.Writer) int { + if help, ok := ownerManagementHelp(operation); ok { + return emit(stdout, stderr, help) + } usage := " reviews operations [--pr NUMBER] [--channel cli|hosted] [--all] [--limit N] [--cursor CURSOR]" semantics := "Read one compact newest-first page of retained project operations. Default five pending; --all includes held and terminal history. Reuse the same filters with a cursor. No provider reads, automatic pagination, execution or retry." documentation := "docs/review-operations.md" diff --git a/internal/cli/project_owner.go b/internal/cli/project_owner.go new file mode 100644 index 000000000..6bad28e19 --- /dev/null +++ b/internal/cli/project_owner.go @@ -0,0 +1,235 @@ +package cli + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "path/filepath" + "strings" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type ownerManagementInvocation struct { + operation, key, id, file, credentialFile string + policy client.ConfigureReviewPolicyRequest + execution client.ConfigureReviewExecutionRequest + worker client.CreateWorkerRequest + grant client.GrantProjectCredentialRequest + update client.UpdateProjectCredentialRequest +} + +func ownerManagementOperation(operation string) bool { + switch operation { + case "reviews policy", "reviews policy-configure", "reviews execution-configure", "workers create", "workers retirement", "workers retire", "credentials grant", "credentials revoke", "credentials update": + return true + } + return false +} +func parseOwnerManagement(operation string, args []string) (*ownerManagementInvocation, bool) { + in := &ownerManagementInvocation{operation: operation} + if operation == "workers retirement" { + if len(args) != 1 || !validResourceID(args[0]) { + return nil, false + } + in.id = args[0] + return in, true + } + if operation == "reviews policy" { + return in, len(args) == 0 + } + positions := []string{} + values := map[string]string{} + var permissions []string + for i := 0; i < len(args); i++ { + if !strings.HasPrefix(args[i], "-") { + positions = append(positions, args[i]) + continue + } + flag, value, assigned := strings.Cut(args[i], "=") + switch flag { + case "--file", "--key", "--name", "--token-sha256", "--credential-file", "--permission": + default: + return nil, false + } + if _, ok := values[flag]; ok && flag != "--permission" { + return nil, false + } + if !assigned { + i++ + if i >= len(args) { + return nil, false + } + value = args[i] + } + if value == "" { + return nil, false + } + values[flag] = value + if flag == "--permission" { + permissions = append(permissions, value) + } + } + in.key, in.file, in.credentialFile = values["--key"], values["--file"], values["--credential-file"] + if !validMutationKey(in.key) { + return nil, false + } + allowed := map[string]bool{"--key": true} + idRequired := operation == "workers retire" || operation == "credentials revoke" || operation == "credentials update" + if idRequired { + if len(positions) != 1 || !validResourceID(positions[0]) { + return nil, false + } + in.id = positions[0] + } else if len(positions) != 0 { + return nil, false + } + switch operation { + case "reviews policy-configure", "reviews execution-configure", "credentials update": + allowed["--file"] = true + if !filepath.IsAbs(in.file) { + return nil, false + } + case "workers create": + allowed["--name"] = true + in.worker.Name = values["--name"] + if client.ValidateCreateWorker(in.worker) != nil { + return nil, false + } + case "credentials grant": + allowed["--token-sha256"], allowed["--credential-file"], allowed["--permission"] = true, true, true + in.grant = client.GrantProjectCredentialRequest{TokenSHA256: values["--token-sha256"], Permissions: permissions} + if (in.credentialFile == "") == (in.grant.TokenSHA256 == "") { + return nil, false + } + if in.credentialFile != "" { + if !filepath.IsAbs(in.credentialFile) { + return nil, false + } + in.grant.TokenSHA256 = strings.Repeat("a", 64) + } + if client.ValidateGrantProjectCredential(in.grant) != nil { + return nil, false + } + case "workers retire", "credentials revoke": + default: + return nil, false + } + for flag := range values { + if !allowed[flag] { + return nil, false + } + } + return in, true +} +func decodeOwnerJSON(body []byte, out any, required ...string) bool { + if strictjson.Decode(body, out) != nil { + return false + } + var fields map[string]json.RawMessage + if json.Unmarshal(body, &fields) != nil || fields == nil { + return false + } + for _, raw := range fields { + if string(raw) == "null" { + return false + } + } + for _, key := range required { + raw, ok := fields[key] + if !ok || string(raw) == "null" { + return false + } + } + return true +} +func prepareOwnerManagement(ctx context.Context, in *ownerManagementInvocation) error { + bad := func() error { + return &client.Error{Code: "invalid_management_input", Message: "Use the declared complete management fields in a bounded owner-private input file.", Action: "Check local help and correct the selected file; no service request was sent.", Status: 400} + } + if in.credentialFile != "" { + rawToken, err := readOwnerPrivateJSON(ctx, in.credentialFile) + if err != nil || len(rawToken) > 4096 { + return bad() + } + token := strings.TrimSpace(string(rawToken)) + if len(token) < 32 || len(token) > 256 { + return bad() + } + for _, r := range token { + if r < 33 || r > 126 { + return bad() + } + } + sum := sha256.Sum256([]byte(token)) + in.grant.TokenSHA256 = hex.EncodeToString(sum[:]) + } + if in.file == "" { + return nil + } + body, err := readOwnerPrivateJSON(ctx, in.file) + if err != nil { + return err + } + switch in.operation { + case "reviews policy-configure": + if !decodeOwnerJSON(body, &in.policy, "expected_revision", "required_channels", "max_review_files", "paused_channels") || client.ValidateConfigureReviewPolicy(in.policy) != nil { + return bad() + } + case "reviews execution-configure": + if !decodeOwnerJSON(body, &in.execution, "expected_revision", "capability_id", "mode", "queue", "channels", "paused") || client.ValidateConfigureReviewExecution(in.execution) != nil { + return bad() + } + case "credentials update": + if !decodeOwnerJSON(body, &in.update, "expected_permissions", "permissions") || client.ValidateUpdateProjectCredential(in.id, in.update) != nil { + return bad() + } + } + return nil +} +func executeOwnerManagement(ctx, parent context.Context, c *client.Client, in *ownerManagementInvocation, stdout, stderr io.Writer) int { + var v any + var err error + switch in.operation { + case "reviews policy": + v, err = c.ReviewPolicy(ctx) + case "reviews policy-configure": + v, err = c.ConfigureReviewPolicy(ctx, in.key, in.policy) + case "reviews execution-configure": + v, err = c.ConfigureReviewExecution(ctx, in.key, in.execution) + case "workers retirement": + v, err = c.WorkerRetirement(ctx, in.id) + case "workers retire": + v, err = c.RetireWorker(ctx, in.key, in.id) + case "workers create": + v, err = c.CreateWorker(ctx, in.key, in.worker) + case "credentials grant": + v, err = c.GrantProjectCredential(ctx, in.key, in.grant) + case "credentials revoke": + v, err = c.RevokeProjectCredential(ctx, in.key, in.id) + case "credentials update": + v, err = c.UpdateProjectCredential(ctx, in.key, in.id, in.update) + } + if err != nil { + return reportClientError(stderr, err, parent) + } + if in.operation == "reviews policy" || in.operation == "workers retirement" { + return emit(stdout, stderr, v) + } + b, err := json.Marshal(v) + if err == nil { + b = append(b, '\n') + var n int + n, err = stdout.Write(b) + if n != len(b) && err == nil { + err = io.ErrShortWrite + } + } + if err != nil { + return reportDetails(stderr, ExitConfig, diagnostic{Code: "output_failed", Message: "The management receipt could not be written.", Action: "Retain the original exact arguments, selected project and idempotency key for recovery.", OutcomeUnknown: true}) + } + return ExitSuccess +} diff --git a/internal/cli/project_owner_help.go b/internal/cli/project_owner_help.go new file mode 100644 index 000000000..d1396f30e --- /dev/null +++ b/internal/cli/project_owner_help.go @@ -0,0 +1,68 @@ +package cli + +func ownerManagementHelp(operation string) (operationHelpResponse, bool) { + out := operationHelpResponse{Usage: " " + operation, Required: []string{}, Optional: []string{}, Semantics: []string{"Uses only the selected project and acting worker. Management capability never grants permission to merge or request unauthorized provider work.", "For mutations, retain the exact request, binding and explicit key after an unknown outcome; no automatic retry."}, Documentation: "docs/review-execution.md"} + switch operation { + case "credentials help": + out.Optional = []string{"credentials grant --help", "credentials update --help", "credentials revoke --help"} + out.Semantics = []string{"Project-manager access changes use this bound project. Grant accepts only a digest or local private credential-file reference; update preserves an existing binding under an exact permission-set guard. No raw token arguments or instance administration."} + out.Documentation = "docs/local-api.md" + case "workers help": + out.Optional = []string{"workers create --help", "workers retirement --help", "workers retire --help", "workers list [--include-retired]"} + out.Semantics = []string{"Local worker command index; no profile, credential or service access. Use operation --help for permissions and retirement guards."} + out.Documentation = "docs/worker-retirement.md" + case "reviews help": + out.Optional = []string{"reviews policy --help", "reviews policy-configure --help", "reviews execution-configure --help", "reviews start --help", "reviews run-read --help"} + out.Semantics = []string{"Local review command index; no profile, credential or service access. Use operation --help for permissions and execution guards."} + case "reviews policy": + out.Documentation = "docs/review-controls.md" + out.Semantics = []string{"Read the current configured project review requirements and policy revision. No provider work or source refresh."} + case "reviews policy-configure": + out.Documentation = "docs/review-controls.md" + out.Usage += " --file POLICY_JSON --key KEY" + out.Required = []string{"--file (owner-private absolute JSON path)", "--key KEY"} + out.FileExample = map[string]any{"expected_revision": 0, "required_channels": []string{"cli", "hosted"}, "paused_channels": []string{}, "max_review_files": 0} + out.Semantics = append(out.Semantics, "Project manager; full policy replacement. max_review_files zero disables the optional project ceiling; provider restrictions remain independent. For initial configuration use expected_revision zero; reviews policy returns reviews_policy_unconfigured until configured. For replacement, read reviews policy for the current revision. Optional round_defaults provides hosted/cli objects with explicit minimum/maximum for newly initialized PR controls only. Omission uses product defaults; existing controls and taper are unchanged. See docs/review-round-controls.md. No review request.") + case "reviews execution-configure": + out.Usage += " --file CONFIG_JSON --key KEY" + out.Required = []string{"--file (owner-private absolute JSON path)", "--key KEY"} + out.FileExample = map[string]any{"expected_revision": 1, "capability_id": "configured-capability", "mode": "stacked", "queue": []int{42}, "channels": []string{"cli", "hosted"}, "paused": false} + out.Semantics = append(out.Semantics, "Project manager; full execution replacement. Read reviews execution and preserve unrelated fields. queue must retain at least one PR. Preserve the current capability_id; capability installation and initial binding are instance-owned. Existing limits/history remain; this requests no review.") + case "workers retirement", "workers retire": + out.Usage += " WORKER_ID" + out.Required = []string{"WORKER_ID"} + out.Semantics = []string{"Retirement is one-way and preserves historical worker references. Unfinished assigned jobs, pending direct/assigned-job notes and unacknowledged messages block retirement. Reassign or resolve work and explicitly acknowledge messages first; nothing is moved or acknowledged automatically."} + if operation == "workers retire" { + out.Usage += " --key KEY" + out.Required = append(out.Required, "--key KEY") + out.Semantics = append(out.Semantics, "Project writer; atomic blocker checks run again at retirement. Retain the exact request/key after an uncertain result; no automatic retry.") + } else { + out.Semantics = append(out.Semantics, "Read-only preview reports total blocker counts and up to 20 IDs per category. It is not a reservation or a guarantee a later retirement will succeed.") + } + out.Documentation = "docs/worker-retirement.md" + case "workers create": + out.Usage += " --name TEXT --key KEY" + out.Required = []string{"--name TEXT (1-200 UTF-8 bytes, no surrounding whitespace)", "--key KEY"} + out.Semantics = append(out.Semantics, "Project writer; create one named worker. Does not change the acting worker, create credentials or start an agent.") + out.Documentation = "docs/local-api.md" + case "credentials grant": + out.Usage += " (--token-sha256 HASH | --credential-file PATH) --permission read [--permission write|manage] --key KEY" + out.Required = []string{"exactly one --token-sha256 (64 lowercase hex) or --credential-file (existing private absolute path)", "--permission (repeat for unique read/write/manage)", "--key KEY"} + out.Semantics = append(out.Semantics, "Project manager; create one distinct non-admin project credential grant. Only a SHA-256 digest is sent. An explicitly selected owner-private credential file is hashed locally; use a high-entropy token of 32-256 printable nonspace ASCII bytes after surrounding whitespace is trimmed. No raw token is accepted as an argument or printed. manage implies read/write. Existing credentials use update instead.") + out.Documentation = "docs/local-api.md" + case "credentials revoke": + out.Usage += " CREDENTIAL_ID --key KEY" + out.Required = []string{"CREDENTIAL_ID", "--key KEY"} + out.Semantics = append(out.Semantics, "Project manager; revoke only this project's grant. Other-project grants remain. No credential secret is read or printed.") + out.Documentation = "docs/local-api.md" + case "credentials update": + out.Usage += " CREDENTIAL_ID --file PERMISSIONS_JSON --key KEY" + out.Required = []string{"CREDENTIAL_ID", "--file (owner-private absolute JSON path)", "--key KEY"} + out.FileExample = map[string]any{"expected_permissions": []string{"read", "write"}, "permissions": []string{"read", "write", "manage"}} + out.Semantics = append(out.Semantics, "Project manager; exact permission-set guard on one active non-admin credential's grant. Preserves credential, token, principal and worker binding. Changes no other project. manage implies read/write.") + out.Documentation = "docs/local-api.md" + default: + return operationHelpResponse{}, false + } + return out, true +} diff --git a/internal/cli/project_owner_test.go b/internal/cli/project_owner_test.go new file mode 100644 index 000000000..315707f5d --- /dev/null +++ b/internal/cli/project_owner_test.go @@ -0,0 +1,276 @@ +package cli_test + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" +) + +func TestProjectOwnerCLIExistingOperationsAndPrivateCredentialHash(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + const rawToken = "synthetic-private-delegated-token" + var leaked bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + if bytes.Contains(body, []byte(rawToken)) { + leaked = true + } + if strings.Contains(r.URL.RawQuery, rawToken) { + leaked = true + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + invoke := func(args ...string) string { + t.Helper() + code, out, stderr := mutationInvoke(t, profiles, "owner", args...) + if code != 0 || stderr != "" || strings.Contains(out, rawToken) || strings.Contains(stderr, rawToken) { + t.Fatal(code, out, stderr) + } + return out + } + file := func(name string, value any) string { + t.Helper() + p := filepath.Join(t.TempDir(), name) + b, _ := json.Marshal(value) + if os.WriteFile(p, b, 0600) != nil { + t.Fatal("private request fixture") + } + return p + } + policyFile := file("policy.json", client.ConfigureReviewPolicyRequest{PausedChannels: []string{}, ExpectedRevision: 1, RequiredChannels: []string{"cli", "hosted"}, MaxReviewFiles: 88, RoundDefaults: &client.ReviewRoundDefaults{Hosted: client.ReviewRoundBounds{Minimum: 2, Maximum: 5}, CLI: client.ReviewRoundBounds{Minimum: 0, Maximum: 8}}}) + var policy client.ReviewRequestReceipt + if json.Unmarshal([]byte(invoke("reviews", "policy-configure", "--file", policyFile, "--key", "policy-change")), &policy) != nil || policy.Revision != 2 { + t.Fatal(policy) + } + var current client.ReviewPolicyRecord + if json.Unmarshal([]byte(invoke("reviews", "policy")), ¤t) != nil || current.Policy.MaxReviewFiles != 88 || current.Policy.RoundDefaults == nil || current.Policy.RoundDefaults.Hosted.Maximum != 5 || current.Policy.RoundDefaults.CLI.Minimum != 0 { + t.Fatal(current) + } + executionFile := file("execution.json", client.ConfigureReviewExecutionRequest{ExpectedRevision: 1, CapabilityID: "fixture", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}, Paused: true}) + invoke("reviews", "execution-configure", "--file", executionFile, "--key", "execution-change") + var created client.WorkerCreateReceipt + if json.Unmarshal([]byte(invoke("workers", "create", "--name", "CLI Inspector", "--key", "create-worker")), &created) != nil || created.ID == "" { + t.Fatal(created) + } + credentialFile := filepath.Join(t.TempDir(), "new.token") + if os.WriteFile(credentialFile, []byte(rawToken+"\n"), 0600) != nil { + t.Fatal("private token fixture") + } + var grant client.ProjectCredentialReceipt + if json.Unmarshal([]byte(invoke("credentials", "grant", "--credential-file", credentialFile, "--permission", "read", "--key", "grant-reader")), &grant) != nil || grant.ID == "" { + t.Fatal(grant) + } + updateFile := file("permissions.json", client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"read", "write"}}) + invoke("credentials", "update", grant.ID, "--file", updateFile, "--key", "update-reader") + staleCode, staleOut, staleErr := mutationInvoke(t, profiles, "owner", "credentials", "update", grant.ID, "--file", updateFile, "--key", "stale-update") + if staleCode != cli.ExitConflict || staleOut != "" || !strings.Contains(staleErr, "returned current_permissions") { + t.Fatal(staleCode, staleOut, staleErr) + } + invoke("credentials", "revoke", grant.ID, "--key", "revoke-reader") + message := f.call(t, "POST", "/api/v1/projects/"+project+"/messages", f.admin, worker, map[string]any{"recipient_worker_id": created.ID, "body": "Selected inbox"})["id"].(string) + f.call(t, "POST", "/api/v1/projects/"+project+"/messages", f.admin, created.ID, map[string]any{"recipient_worker_id": worker, "body": "Selected outbox"}) + var inbox client.Page[client.InboxItem] + if json.Unmarshal([]byte(invoke("inbox", "list", "--worker", created.ID)), &inbox) != nil || len(inbox.Items) != 1 || inbox.Items[0].RecipientWorkerID != created.ID { + t.Fatal(inbox) + } + denied, _, deniedErr := mutationInvoke(t, profiles, "owner", "inbox", "ack", message, "--key", "no-impersonation") + if denied == 0 || !strings.Contains(deniedErr, "forbidden") { + t.Fatal(denied, deniedErr) + } + if leaked { + t.Fatal("credential reached query output") + } +} + +func TestProjectOwnerCLIHelpAndMalformedBeforeProfiles(t *testing.T) { + for _, op := range [][]string{{"reviews", "policy"}, {"reviews", "policy-configure"}, {"reviews", "execution-configure"}, {"workers", "create"}, {"credentials", "grant"}, {"credentials", "revoke"}, {"credentials", "update"}} { + code, out, stderr := run(append(op, "--help"), nil) + if code != 0 || stderr != "" || !strings.Contains(out, "documentation") { + t.Fatal(op, code, out, stderr) + } + if op[0] == "reviews" && op[1] == "policy-configure" { + var help struct { + FileExample struct { + ExpectedRevision *int64 `json:"expected_revision"` + } `json:"file_example"` + } + if err := json.Unmarshal([]byte(out), &help); err != nil || help.FileExample.ExpectedRevision == nil || *help.FileExample.ExpectedRevision != 0 || !strings.Contains(out, "reviews_policy_unconfigured") || !strings.Contains(out, "For replacement") { + t.Fatal("initial policy guidance missing", out, err) + } + } + if op[0] == "credentials" && op[1] == "grant" && (!strings.Contains(out, "32-256 printable nonspace ASCII bytes") || !strings.Contains(out, "surrounding whitespace is trimmed")) { + t.Fatal("credential-file bounds missing from local help", out) + } + } + p := filepath.Join(t.TempDir(), "incomplete.json") + if os.WriteFile(p, []byte(`{"expected_revision":1,"capability_id":"fixture","mode":"independent","queue":[],"channels":["cli"]}`), 0600) != nil { + t.Fatal("private fixture") + } + code, out, stderr := run([]string{"--profiles-file", "/missing/private-profiles", "reviews", "execution-configure", "--file", p, "--key", "bad"}, nil) + if code == cli.ExitSuccess || out != "" || !strings.Contains(stderr, "invalid_management_input") { + t.Fatal(code, out, stderr) + } + for _, defaults := range []string{`null`, `{"hosted":{"minimum":0,"maximum":1}}`, `{"hosted":{"minimum":0,"maximum":1},"cli":{"minimum":2,"maximum":1}}`} { + body := `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":` + defaults + `}` + if err := os.WriteFile(p, []byte(body), 0600); err != nil { + t.Fatal(err) + } + code, out, stderr := run([]string{"--profiles-file", "/missing/private-profiles", "reviews", "policy-configure", "--file", p, "--key", "bad"}, nil) + if code == cli.ExitSuccess || out != "" || !strings.Contains(stderr, "invalid_management_input") { + t.Fatal("invalid policy defaults reached profile loading", code, out, stderr) + } + } + for _, args := range [][]string{{"workers", "create", "--name", " padded ", "--key", "x"}, {"credentials", "grant", "--token-sha256", "raw secret", "--permission", "read", "--key", "x"}, {"credentials", "update", "bad/id", "--file", p, "--key", "x"}} { + code, out, stderr := run(append([]string{"--profiles-file", "/missing"}, args...), nil) + if code != cli.ExitUsage || out != "" || !strings.Contains(stderr, "invalid_arguments") { + t.Fatal(args, code, out, stderr) + } + } +} + +func TestProjectOwnerCLICredentialFileBoundsPreserveHashAndReceipt(t *testing.T) { + for _, tc := range []struct { + name, token, padding string + }{ + {"minimum", strings.Repeat("!", 32), " \t\r\n"}, + {"maximum", strings.Repeat("~", 256), "\r\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := setupServiceFixture(t) + project := f.project(t, "credential-boundary") + worker := f.worker(t, project, "Owner") + var leaked atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + if bytes.Contains(body, []byte(tc.token)) || strings.Contains(r.URL.RawQuery, tc.token) { + leaked.Store(true) + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + credentialFile := filepath.Join(t.TempDir(), "boundary.token") + if err := os.WriteFile(credentialFile, []byte(tc.padding+tc.token+tc.padding), 0600); err != nil { + t.Fatal(err) + } + code, out, stderr := mutationInvoke(t, profiles, "owner", "credentials", "grant", "--credential-file", credentialFile, "--permission", "read", "--key", "boundary-grant") + if code != cli.ExitSuccess || stderr != "" || strings.Contains(out, tc.token) || strings.Contains(out, credentialFile) { + t.Fatal(code, out, stderr) + } + var grant client.ProjectCredentialReceipt + if json.Unmarshal([]byte(out), &grant) != nil || grant.ID == "" || grant.PrincipalID == "" || grant.ProjectID != project || grant.Outcome != "granted" { + t.Fatal("invalid boundary grant receipt", out) + } + // Digest input must preserve the exact receipt and principal from the trimmed file input. + sum := sha256.Sum256([]byte(tc.token)) + code, replay, stderr := mutationInvoke(t, profiles, "owner", "credentials", "grant", "--token-sha256", hex.EncodeToString(sum[:]), "--permission", "read", "--key", "boundary-grant") + if code != cli.ExitSuccess || stderr != "" || replay != out || leaked.Load() { + t.Fatal("credential digest or replay changed", code, replay, stderr) + } + if got := f.call(t, "GET", "/api/v1/projects/"+project, tc.token, worker, nil); got["id"] != project { + t.Fatal("granted boundary token cannot authenticate", got) + } + }) + } +} + +func TestProjectOwnerCLICredentialFileRejectsInvalidTokensBeforeHTTP(t *testing.T) { + f := setupServiceFixture(t) + project := f.project(t, "invalid-credentials") + worker := f.worker(t, project, "Owner") + var requests atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + for _, tc := range []struct { + name, token string + }{ + {"empty", ""}, + {"one-byte", "!"}, + {"short", strings.Repeat("!", 31)}, + {"short-padded", " \t" + strings.Repeat("!", 31) + "\r\n"}, + {"long", strings.Repeat("!", 257)}, + {"long-padded", "\t" + strings.Repeat("!", 257) + "\n"}, + {"raw-limit", strings.Repeat("!", 4096)}, + {"past-raw-limit", strings.Repeat("!", 4097)}, + {"excessive-padding", strings.Repeat(" ", 4096) + strings.Repeat("!", 32)}, + {"whitespace-only", " \t\r\n"}, + {"interior-space", strings.Repeat("!", 16) + " " + strings.Repeat("!", 16)}, + {"interior-newline", strings.Repeat("!", 16) + "\n" + strings.Repeat("!", 16)}, + {"control", strings.Repeat("!", 32) + "\x7f"}, + {"non-ascii", strings.Repeat("!", 32) + "é"}, + } { + t.Run(tc.name, func(t *testing.T) { + credentialFile := filepath.Join(t.TempDir(), "rejected.token") + if err := os.WriteFile(credentialFile, []byte(tc.token), 0600); err != nil { + t.Fatal(err) + } + for _, profileFile := range []string{profiles, filepath.Join(t.TempDir(), "missing-profiles.json")} { + code, out, stderr := mutationInvoke(t, profileFile, "owner", "credentials", "grant", "--credential-file", credentialFile, "--permission", "read", "--key", "invalid-grant") + if code != cli.ExitUsage || out != "" || !strings.Contains(stderr, "invalid_management_input") || !strings.Contains(stderr, "no service request was sent") || requests.Load() != 0 { + t.Fatal("invalid token reached profiles or HTTP", code, out, stderr, requests.Load()) + } + if strings.Contains(stderr, credentialFile) || tc.token != "" && strings.TrimSpace(tc.token) != "" && strings.Contains(stderr, tc.token) { + t.Fatal("private credential input reached diagnostics") + } + } + }) + } +} + +func TestManagementGroupHelpIsStructuredAndLocal(t *testing.T) { + for _, tc := range []struct { + group, documentation string + operations []string + }{ + {"credentials", "docs/local-api.md", []string{"credentials grant --help", "credentials update --help", "credentials revoke --help"}}, + {"workers", "docs/worker-retirement.md", []string{"workers create --help", "workers retirement --help", "workers retire --help", "workers list [--include-retired]"}}, + {"reviews", "docs/review-execution.md", []string{"reviews policy --help", "reviews policy-configure --help", "reviews execution-configure --help", "reviews start --help", "reviews run-read --help"}}, + } { + for _, argument := range []string{"help", "--help"} { + t.Run(tc.group+"/"+argument, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + var out, errout bytes.Buffer + code := cli.RunContext(ctx, []string{"--profiles-file", "/missing/private-profile.json", tc.group, argument}, nil, &out, &errout) + if code != cli.ExitSuccess || errout.Len() != 0 || out.Len() > 4096 || strings.Contains(out.String(), "private-profile") { + t.Fatalf("local group help: code=%d stdout=%s stderr=%s", code, &out, &errout) + } + var help struct { + Usage string `json:"usage"` + Required []string `json:"required"` + Optional []string `json:"optional"` + Semantics []string `json:"semantics"` + Documentation string `json:"documentation"` + } + if err := json.Unmarshal(out.Bytes(), &help); err != nil { + t.Fatalf("help must be a structured object: %v; stdout=%s", err, &out) + } + if help.Usage != " "+tc.group+" help" || help.Required == nil || len(help.Required) != 0 || !slices.Equal(help.Optional, tc.operations) || len(help.Semantics) == 0 || help.Documentation != tc.documentation { + t.Fatalf("group help lost its command contract: %+v", help) + } + }) + } + } +} diff --git a/internal/client/client.go b/internal/client/client.go index 7883c5dd4..73466d8fe 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -572,7 +572,13 @@ func (c *Client) serviceError(data []byte, status int) (*Error, bool) { return invalidResponse(), false } details, err := json.Marshal(value.Error.Details) - if err != nil || len(details) > 4096 || c.hasSensitive(&value) { + if err != nil || c.hasSensitive(&value) { + return invalidResponse(), false + } + // Three groups of twenty 128-byte identities can exceed the ordinary + // detail budget. Allow only the validated blocker shape in a 48 KiB + // envelope, including worst-case six-byte JSON escapes per identity byte. + if len(details) > 4096 && (value.Error.Code != "worker_retirement_blocked" || len(details) > 48<<10 || safeWorkerRetirementBlockers(value.Error.Details) == nil) { return invalidResponse(), false } result := fail(value.Error.Code, "The service refused this scoped request.", "Check the selected instance, project, worker and current access.", status) @@ -670,6 +676,16 @@ func (c *Client) safeDetails(value any, code string) any { return nil } result := make(map[string]any) + if code == "credential_permissions_changed" { + for key, item := range safeCredentialPermissionDetails(object) { + result[key] = item + } + } + if code == "worker_retirement_blocked" { + if blocks := safeWorkerRetirementBlockers(object); blocks != nil { + return blocks + } + } for key, item := range object { switch key { case "reason": diff --git a/internal/client/mutations.go b/internal/client/mutations.go index e7c191f4a..54a0ed672 100644 --- a/internal/client/mutations.go +++ b/internal/client/mutations.go @@ -113,17 +113,26 @@ func (c *Client) MarkSeen(ctx context.Context, key, id string) (MessageReceipt, return c.transition(ctx, key, id, "seen") } -func (c *Client) Acknowledge(ctx context.Context, key, id string) (MessageReceipt, error) { - return c.transition(ctx, key, id, "ack") +func (c *Client) Acknowledge(ctx context.Context, key, id string, selectedWorker ...string) (MessageReceipt, error) { + if _, err := c.selectedWorker(selectedWorker); err != nil { + return MessageReceipt{}, err + } + return c.transition(ctx, key, id, "ack", selectedWorker...) } -func (c *Client) transition(ctx context.Context, key, id, action string) (MessageReceipt, error) { +func (c *Client) transition(ctx context.Context, key, id, action string, selectedWorker ...string) (MessageReceipt, error) { if !validMutationKey(key) || !validID(id) { return MessageReceipt{}, mutationValidation() } var result MessageReceipt path := c.projectPath("messages", id, action) - if err := c.mutate(ctx, http.MethodPost, path, key, struct{}{}, http.StatusOK, &result); err != nil { + var input struct { + WorkerID string `json:"worker_id,omitempty"` + } + if len(selectedWorker) == 1 { + input.WorkerID = selectedWorker[0] + } + if err := c.mutate(ctx, http.MethodPost, path, key, input, http.StatusOK, &result); err != nil { return MessageReceipt{}, err } want := action diff --git a/internal/client/project_owner.go b/internal/client/project_owner.go new file mode 100644 index 000000000..7858e4a77 --- /dev/null +++ b/internal/client/project_owner.go @@ -0,0 +1,374 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "github.com/benhook1013/FireController/internal/strictjson" + "math" + "net/http" + "strings" + "unicode" + "unicode/utf8" +) + +type ReviewPolicy struct { + PausedChannels []string `json:"paused_channels"` + RequiredChannels []string `json:"required_channels"` + MaxReviewFiles int64 `json:"max_review_files"` + RoundDefaults *ReviewRoundDefaults `json:"round_defaults,omitempty"` +} +type ReviewPolicyRecord struct { + ProjectID string `json:"project_id"` + Revision int64 `json:"revision"` + ActorID string `json:"actor_id"` + RecordedAt string `json:"recorded_at"` + Policy ReviewPolicy `json:"policy"` +} +type ConfigureReviewPolicyRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + PausedChannels []string `json:"paused_channels"` + RequiredChannels []string `json:"required_channels"` + MaxReviewFiles int64 `json:"max_review_files"` + RoundDefaults *ReviewRoundDefaults `json:"round_defaults,omitempty"` +} +type ConfigureReviewExecutionRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + CapabilityID string `json:"capability_id"` + Mode string `json:"mode"` + Queue []int64 `json:"queue"` + Channels []string `json:"channels"` + Paused bool `json:"paused"` +} +type CreateWorkerRequest struct { + Name string `json:"name"` +} +type WorkerCreateReceipt struct { + ID string `json:"id"` + Revision int64 `json:"revision"` + Outcome string `json:"outcome"` +} +type GrantProjectCredentialRequest struct { + TokenSHA256 string `json:"token_sha256"` + Permissions []string `json:"permissions"` +} +type ProjectCredentialReceipt struct { + ID string `json:"id"` + PrincipalID string `json:"principal_id,omitempty"` + ProjectID string `json:"project_id"` + Outcome string `json:"outcome"` +} + +func ownerChannels(values []string) bool { + if values == nil || len(values) < 1 || len(values) > 2 { + return false + } + seen := map[string]bool{} + for _, v := range values { + if !oneReviewOf(v, "cli", "hosted") || seen[v] { + return false + } + seen[v] = true + } + return true +} +func ownerText(s string, max int, multiline bool) bool { + if !utf8.ValidString(s) || len(s) < 1 || len(s) > max || strings.TrimSpace(s) != s { + return false + } + for _, r := range s { + if unicode.IsControl(r) && !(multiline && (r == '\n' || r == '\t')) { + return false + } + } + return true +} +func ValidateConfigureReviewPolicy(r ConfigureReviewPolicyRequest) error { + if r.PausedChannels == nil || len(r.PausedChannels) > 2 || !validPausedChannels(r.PausedChannels) || r.ExpectedRevision < 0 || r.ExpectedRevision == math.MaxInt64 || !ownerChannels(r.RequiredChannels) || r.MaxReviewFiles < 0 || r.MaxReviewFiles > 100000 || !validReviewRoundDefaults(r.RoundDefaults) { + return mutationValidation() + } + return nil +} +func ValidateConfigureReviewExecution(r ConfigureReviewExecutionRequest) error { + if r.ExpectedRevision < 0 || r.ExpectedRevision == math.MaxInt64 || !validExecutionIdentifier(r.CapabilityID) || !oneReviewOf(r.Mode, "independent", "stacked") || len(r.Queue) == 0 || len(r.Queue) > 100 || !ownerChannels(r.Channels) { + return mutationValidation() + } + seen := map[int64]bool{} + for _, n := range r.Queue { + if !validPullNumber(n) || seen[n] { + return mutationValidation() + } + seen[n] = true + } + return nil +} + +func ValidateCreateWorker(r CreateWorkerRequest) error { + if !ownerText(r.Name, 200, false) { + return mutationValidation() + } + return nil +} +func ValidateGrantProjectCredential(r GrantProjectCredentialRequest) error { + if len(r.TokenSHA256) != 64 || !lowerHex(r.TokenSHA256) || r.Permissions == nil || len(r.Permissions) < 1 || len(r.Permissions) > 3 { + return mutationValidation() + } + seen := map[string]bool{} + for _, p := range r.Permissions { + if !oneReviewOf(p, "read", "write", "manage") || seen[p] { + return mutationValidation() + } + seen[p] = true + } + if !seen["read"] && !seen["manage"] { + return mutationValidation() + } + return nil +} +func lowerHex(s string) bool { + for _, r := range s { + if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') { + return false + } + } + return true +} +func (c *Client) ReviewPolicy(ctx context.Context) (ReviewPolicyRecord, error) { + var v ReviewPolicyRecord + err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "policy"), nil, true, "", nil, http.StatusOK, false, &v, 8<<10, decodeResponse) + if err != nil { + return v, err + } + if v.ProjectID != c.identity.ProjectID || v.Revision < 1 || !validID(v.ActorID) || !validJobProgressTime(v.RecordedAt) || !ownerChannels(v.Policy.RequiredChannels) || v.Policy.PausedChannels == nil || !validPausedChannels(v.Policy.PausedChannels) || v.Policy.MaxReviewFiles < 0 || v.Policy.MaxReviewFiles > 100000 || !validReviewRoundDefaults(v.Policy.RoundDefaults) { + return ReviewPolicyRecord{}, invalidResponse() + } + return v, nil +} +func (c *Client) ConfigureReviewPolicy(ctx context.Context, key string, r ConfigureReviewPolicyRequest) (ReviewRequestReceipt, error) { + var v ReviewRequestReceipt + if !validMutationKey(key) || ValidateConfigureReviewPolicy(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "policy"), key, r, http.StatusOK, &v); err != nil { + return v, err + } + if v.ID != c.identity.ProjectID || v.State != "policy_configured" || v.Revision != r.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The policy receipt was invalid; retain the original key and request.", 200) + } + return v, nil +} +func (c *Client) ConfigureReviewExecution(ctx context.Context, key string, r ConfigureReviewExecutionRequest) (ReviewRequestReceipt, error) { + var v ReviewRequestReceipt + if !validMutationKey(key) || ValidateConfigureReviewExecution(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "execution", "configuration"), key, r, http.StatusCreated, &v); err != nil { + return v, err + } + if v.ID != c.identity.ProjectID || v.State != "configured" || v.Revision != r.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The execution receipt was invalid; retain the original key and request.", 201) + } + return v, nil +} + +func (c *Client) CreateWorker(ctx context.Context, key string, r CreateWorkerRequest) (WorkerCreateReceipt, error) { + var v WorkerCreateReceipt + if !validMutationKey(key) || ValidateCreateWorker(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("workers"), key, r, http.StatusOK, &v); err != nil { + return v, err + } + if !validID(v.ID) || v.Revision != 1 || v.Outcome != "created" { + return WorkerCreateReceipt{}, unknownMutation("invalid_response", "The worker receipt was invalid; retain original name and key.", 200) + } + return v, nil +} +func (c *Client) GrantProjectCredential(ctx context.Context, key string, r GrantProjectCredentialRequest) (ProjectCredentialReceipt, error) { + var v ProjectCredentialReceipt + if !validMutationKey(key) || ValidateGrantProjectCredential(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("credentials"), key, r, http.StatusOK, &v); err != nil { + return v, err + } + if !validID(v.ID) || !validID(v.PrincipalID) || v.ProjectID != c.identity.ProjectID || v.Outcome != "granted" { + return ProjectCredentialReceipt{}, unknownMutation("invalid_response", "The credential receipt was invalid; retain the digest, permissions and key.", 200) + } + return v, nil +} +func (c *Client) RevokeProjectCredential(ctx context.Context, key, id string) (ProjectCredentialReceipt, error) { + var v ProjectCredentialReceipt + if !validMutationKey(key) || !validID(id) { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodDelete, c.projectPath("credentials", id), key, struct{}{}, http.StatusOK, &v); err != nil { + return v, err + } + if v.ID != id || v.ProjectID != c.identity.ProjectID || v.PrincipalID != "" || v.Outcome != "revoked" { + return ProjectCredentialReceipt{}, unknownMutation("invalid_response", "The revoke receipt was invalid; retain the credential ID and key.", 200) + } + return v, nil +} + +type UpdateProjectCredentialRequest struct { + ExpectedPermissions []string `json:"expected_permissions"` + Permissions []string `json:"permissions"` +} +type ProjectCredentialUpdateReceipt struct { + ID string `json:"id"` + ProjectID string `json:"project_id"` + Outcome string `json:"outcome"` + Permissions []string `json:"permissions"` +} + +func ValidateUpdateProjectCredential(id string, r UpdateProjectCredentialRequest) error { + if !validID(id) || ValidateGrantProjectCredential(GrantProjectCredentialRequest{TokenSHA256: strings.Repeat("a", 64), Permissions: r.ExpectedPermissions}) != nil || ValidateGrantProjectCredential(GrantProjectCredentialRequest{TokenSHA256: strings.Repeat("a", 64), Permissions: r.Permissions}) != nil { + return mutationValidation() + } + return nil +} +func normalizedPermissions(p []string) []string { + read, write, manage := false, false, false + for _, v := range p { + switch v { + case "read": + read = true + case "write": + write = true + case "manage": + read, write, manage = true, true, true + } + } + r := []string{} + if read { + r = append(r, "read") + } + if write { + r = append(r, "write") + } + if manage { + r = append(r, "manage") + } + return r +} +func (c *Client) UpdateProjectCredential(ctx context.Context, key, id string, r UpdateProjectCredentialRequest) (ProjectCredentialUpdateReceipt, error) { + var v ProjectCredentialUpdateReceipt + if !validMutationKey(key) || ValidateUpdateProjectCredential(id, r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPut, c.projectPath("credentials", id), key, r, http.StatusOK, &v); err != nil { + return v, projectCredentialError(err, id) + } + want := strings.Join(normalizedPermissions(r.Permissions), ",") + if v.ID != id || v.ProjectID != c.identity.ProjectID || !oneReviewOf(v.Outcome, "updated", "unchanged") || strings.Join(v.Permissions, ",") != want { + return ProjectCredentialUpdateReceipt{}, unknownMutation("invalid_response", "The access update receipt was invalid; preserve original credential ID, permissions and key.", 200) + } + return v, nil +} + +// selectedWorker changes the resource selector, never the authenticated acting identity. +func (c *Client) selectedWorker(selected []string) (string, error) { + if len(selected) > 1 { + return "", validation() + } + worker := c.identity.WorkerID + if len(selected) == 1 && selected[0] != "" { + worker = selected[0] + } + if !validID(worker) { + return "", validation() + } + return worker, nil +} + +func safeCredentialPermissionDetails(object map[string]any) map[string]any { + id, ok := object["credential_id"].(string) + if !ok || !validID(id) { + return nil + } + raw, ok := object["current_permissions"].([]any) + if !ok { + return nil + } + var permissions []string + for _, v := range raw { + s, ok := v.(string) + if !ok { + return nil + } + permissions = append(permissions, s) + } + if ValidateGrantProjectCredential(GrantProjectCredentialRequest{TokenSHA256: strings.Repeat("a", 64), Permissions: permissions}) != nil || strings.Join(permissions, ",") != strings.Join(normalizedPermissions(permissions), ",") { + return nil + } + return map[string]any{"credential_id": id, "current_permissions": permissions} +} + +func projectCredentialError(err error, id string) error { + var e *Error + if !errors.As(err, &e) || e.Code != "credential_permissions_changed" || e.OutcomeUnknown { + return err + } + details, ok := e.Details.(map[string]any) + if !ok || details["credential_id"] != id { + return fail("invalid_response", "The service returned an unverifiable permission conflict.", "Preserve the intended credential change and verify the selected service; no new key was generated.", 409) + } + e.Message = "The selected credential's project permissions changed." + e.Action = "Compare returned current_permissions with the intended change. If still appropriate, use that set as expected_permissions with a new explicit key. This refused request changed no permissions." + return e +} + +func validPausedChannels(values []string) bool { + seen := map[string]bool{} + for _, value := range values { + if !oneReviewOf(value, "cli", "hosted") || seen[value] { + return false + } + seen[value] = true + } + return true +} + +type ReviewRoundBounds struct { + Minimum int64 `json:"minimum"` + Maximum int64 `json:"maximum"` +} + +// ReviewRoundDefaults affect only the first installation of a PR/channel control. +type ReviewRoundDefaults struct { + Hosted ReviewRoundBounds `json:"hosted"` + CLI ReviewRoundBounds `json:"cli"` +} + +func (d *ReviewRoundDefaults) UnmarshalJSON(body []byte) error { + type plain ReviewRoundDefaults + var value plain + if strictjson.Decode(body, &value) != nil { + return strictjson.ErrSyntax + } + var channels map[string]map[string]json.RawMessage + if json.Unmarshal(body, &channels) != nil || len(channels) != 2 { + return strictjson.ErrSyntax + } + for _, channel := range []string{"hosted", "cli"} { + bounds := channels[channel] + if len(bounds) != 2 || string(bounds["minimum"]) == "null" || len(bounds["minimum"]) == 0 || string(bounds["maximum"]) == "null" || len(bounds["maximum"]) == 0 { + return strictjson.ErrSyntax + } + } + *d = ReviewRoundDefaults(value) + return nil +} + +func validReviewRoundDefaults(value *ReviewRoundDefaults) bool { + if value == nil { + return true + } + for _, bounds := range []ReviewRoundBounds{value.Hosted, value.CLI} { + if bounds.Minimum < 0 || bounds.Maximum < 1 || bounds.Maximum > 1000 || bounds.Minimum > bounds.Maximum { + return false + } + } + return true +} diff --git a/internal/client/project_owner_test.go b/internal/client/project_owner_test.go new file mode 100644 index 000000000..d92869947 --- /dev/null +++ b/internal/client/project_owner_test.go @@ -0,0 +1,160 @@ +package client_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviews" +) + +func TestProjectOwnerClientActualScopedManagement(t *testing.T) { + f := newMutationFixture(t) + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if err := reviews.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "owner-capability", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}, reviewexec.WithNativeProjection()) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + engine.Register(mux) + f.handler = mux + service := httptest.NewServer(f.handler) + defer service.Close() + grant := func(token string, p []string) string { + sum := sha256.Sum256([]byte(token)) + return f.call(t, "POST", "/api/v1/projects/"+f.project+"/credentials", f.admin, f.sender, map[string]any{"token_sha256": hex.EncodeToString(sum[:]), "permissions": p})["id"].(string) + } + const ownerToken = "synthetic-private-manager-token" + grant(ownerToken, []string{"manage"}) + grant("synthetic-writer-token", []string{"read", "write"}) + grant("synthetic-reader-token", []string{"read"}) + owner := f.newClient(t, ownerToken, f.sender, service.URL) + writer := f.newClient(t, "synthetic-writer-token", f.sender, service.URL) + reader := f.newClient(t, "synthetic-reader-token", f.sender, service.URL) + policy := client.ConfigureReviewPolicyRequest{PausedChannels: []string{}, RequiredChannels: []string{"cli", "hosted"}, MaxReviewFiles: 99, RoundDefaults: &client.ReviewRoundDefaults{Hosted: client.ReviewRoundBounds{Minimum: 2, Maximum: 5}, CLI: client.ReviewRoundBounds{Minimum: 0, Maximum: 8}}} + _, err = writer.ConfigureReviewPolicy(t.Context(), "writer-policy", policy) + checkError(t, err, "forbidden") + first, err := owner.ConfigureReviewPolicy(t.Context(), "owner-policy", policy) + if err != nil || first.Revision != 1 { + t.Fatal(first, err) + } + replay, err := owner.ConfigureReviewPolicy(t.Context(), "owner-policy", policy) + if err != nil || !reflect.DeepEqual(first, replay) { + t.Fatal(replay, err) + } + record, err := reader.ReviewPolicy(t.Context()) + if err != nil || record.Policy.MaxReviewFiles != 99 || record.ProjectID != f.project || !reflect.DeepEqual(record.Policy.RoundDefaults, policy.RoundDefaults) { + t.Fatal(record, err) + } + _, err = owner.ConfigureReviewPolicy(t.Context(), "stale-policy", policy) + checkError(t, err, "review_conflict") + initial := client.ConfigureReviewExecutionRequest{CapabilityID: "owner-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}} + f.call(t, "POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", f.admin, f.sender, initial) + config := client.ConfigureReviewExecutionRequest{ExpectedRevision: 1, CapabilityID: "owner-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}} + _, err = writer.ConfigureReviewExecution(t.Context(), "writer-execution", config) + checkError(t, err, "forbidden") + configured, err := owner.ConfigureReviewExecution(t.Context(), "owner-execution", config) + if err != nil || configured.Revision != 2 { + t.Fatalf("configuration: %+v error: %#v", configured, err) + } + current, err := reader.ReviewExecution(t.Context()) + if err != nil || current.Queue == nil || len(current.Queue) != 1 { + t.Fatal(current, err) + } + worker, err := writer.CreateWorker(t.Context(), "create-inspector", client.CreateWorkerRequest{Name: "Inspector"}) + if err != nil || worker.Outcome != "created" { + t.Fatal(worker, err) + } + _, err = reader.CreateWorker(t.Context(), "read-create", client.CreateWorkerRequest{Name: "Denied"}) + checkError(t, err, "forbidden") + digest := sha256.Sum256([]byte("synthetic-new-nonadmin-token")) + newGrant, err := owner.GrantProjectCredential(t.Context(), "create-grant", client.GrantProjectCredentialRequest{TokenSHA256: hex.EncodeToString(digest[:]), Permissions: []string{"read"}}) + if err != nil || newGrant.PrincipalID == "" { + t.Fatal(newGrant, err) + } + update := client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"manage"}} + changed, err := owner.UpdateProjectCredential(t.Context(), "update-grant", newGrant.ID, update) + if err != nil || !reflect.DeepEqual(changed.Permissions, []string{"read", "write", "manage"}) { + t.Fatal(changed, err) + } + _, err = owner.UpdateProjectCredential(t.Context(), "stale-grant", newGrant.ID, update) + checkError(t, err, "credential_permissions_changed") + var mismatch *client.Error + if !errors.As(err, &mismatch) || mismatch.Details == nil { + t.Fatal("permission guard lost current set", err) + } + revoked, err := owner.RevokeProjectCredential(t.Context(), "revoke-grant", newGrant.ID) + if err != nil || revoked.Outcome != "revoked" { + t.Fatal(revoked, err) + } + other := f.call(t, "POST", "/api/v1/projects", f.admin, "", map[string]any{"name": "other", "repository": "owner/other"})["id"].(string) + otherDigest := sha256.Sum256([]byte("other-project-credential")) + foreign := f.call(t, "POST", "/api/v1/projects/"+other+"/credentials", f.admin, "", map[string]any{"token_sha256": hex.EncodeToString(otherDigest[:]), "permissions": []string{"read"}})["id"].(string) + _, err = owner.RevokeProjectCredential(t.Context(), "foreign-revoke", foreign) + var unavailable *client.Error + if !errors.As(err, &unavailable) || unavailable.Status != 404 { + t.Fatal(err) + } +} + +func TestOwnerClientLocalValidation(t *testing.T) { + c := &client.Client{} + for _, invoke := range []func() error{ + func() error { + _, e := c.ConfigureReviewPolicy(t.Context(), "k", client.ConfigureReviewPolicyRequest{PausedChannels: []string{}}) + return e + }, + func() error { + _, e := c.ConfigureReviewExecution(t.Context(), "k", client.ConfigureReviewExecutionRequest{CapabilityID: "x", Mode: "independent", Channels: []string{"cli"}}) + return e + }, + + func() error { + _, e := c.GrantProjectCredential(t.Context(), "k", client.GrantProjectCredentialRequest{TokenSHA256: "raw credential", Permissions: []string{"manage"}}) + return e + }, + func() error { + _, e := c.CreateWorker(t.Context(), "k", client.CreateWorkerRequest{Name: " padded "}) + return e + }, + } { + if err := invoke(); err == nil { + t.Fatal("invalid management input reached service") + } + } +} + +func TestOwnerCredentialConflictFiltersPrivateDetails(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + write(w, 409, map[string]any{"request_id": "request-one", "error": map[string]any{"code": "credential_permissions_changed", "message": "PRIVATE narrative", "details": map[string]any{"credential_id": "credential-one", "current_permissions": []string{"read", "write"}, "private_evidence": "PRIVATE evidence"}}}) + })) + defer server.Close() + c := newClient(t, server) + _, err := c.UpdateProjectCredential(t.Context(), "guarded-access", "credential-one", client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"manage"}}) + var e *client.Error + if !errors.As(err, &e) || e.Code != "credential_permissions_changed" || !strings.Contains(e.Action, "returned current_permissions") { + t.Fatal(err) + } + raw, _ := json.Marshal(e.Details) + if strings.Contains(string(raw), "PRIVATE") || !strings.Contains(string(raw), "current_permissions") { + t.Fatal(string(raw)) + } +} diff --git a/internal/client/reads.go b/internal/client/reads.go index 2d18872bc..5b6f8fecd 100644 --- a/internal/client/reads.go +++ b/internal/client/reads.go @@ -48,10 +48,16 @@ func (c *Client) Worker(ctx context.Context) (Worker, error) { return value, nil } func (c *Client) Workers(ctx context.Context, options PageOptions) (Page[Worker], error) { + return c.WorkersWithRetired(ctx, options, false) +} +func (c *Client) WorkersWithRetired(ctx context.Context, options PageOptions, includeRetired bool) (Page[Worker], error) { q, err := pageQuery(options) if err != nil { return Page[Worker]{}, err } + if includeRetired { + q.Set("include_retired", "true") + } var value Page[Worker] if err = c.get(ctx, c.projectPath("workers"), q, true, &value); err != nil { return Page[Worker]{}, err @@ -127,7 +133,11 @@ func (c *Client) JobHistory(ctx context.Context, id string, options PageOptions) } return value, nil } -func (c *Client) Inbox(ctx context.Context, options PageOptions, filter InboxFilter) (Page[InboxItem], error) { +func (c *Client) Inbox(ctx context.Context, options PageOptions, filter InboxFilter, selectedWorker ...string) (Page[InboxItem], error) { + worker, err := c.selectedWorker(selectedWorker) + if err != nil { + return Page[InboxItem]{}, err + } q, err := pageQuery(options) if err != nil { return Page[InboxItem]{}, err @@ -139,14 +149,16 @@ func (c *Client) Inbox(ctx context.Context, options PageOptions, filter InboxFil q.Set("unacknowledged", "true") } var value Page[InboxItem] - if err = c.get(ctx, c.projectPath("inbox", c.identity.WorkerID), q, true, &value); err != nil { + if err = c.get(ctx, c.projectPath("inbox", worker), q, true, &value); err != nil { return Page[InboxItem]{}, err } if !validPage(value, options) { return Page[InboxItem]{}, invalidResponse() } for _, item := range value.Items { - if !c.validInboxItem(item, filter) { + validationClient := *c + validationClient.identity.WorkerID = worker + if !validationClient.validInboxItem(item, filter) { return Page[InboxItem]{}, invalidResponse() } } diff --git a/internal/client/types.go b/internal/client/types.go index 1b504e7fe..5f1175c12 100644 --- a/internal/client/types.go +++ b/internal/client/types.go @@ -58,6 +58,7 @@ type Page[T any] struct { HasMore bool `json:"has_more"` } type Worker struct { + Retired bool `json:"retired,omitempty"` ID string `json:"id"` ProjectID string `json:"project_id"` Name string `json:"name"` diff --git a/internal/client/worker_retirement.go b/internal/client/worker_retirement.go new file mode 100644 index 000000000..a2d0d1fad --- /dev/null +++ b/internal/client/worker_retirement.go @@ -0,0 +1,82 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/benhook1013/FireController/internal/strictjson" +) + +type WorkerRetirementBlocker struct { + Count int64 `json:"count"` + IDs []string `json:"ids"` +} +type WorkerRetirementBlockers struct { + Jobs WorkerRetirementBlocker `json:"jobs"` + Notes WorkerRetirementBlocker `json:"notes"` + Messages WorkerRetirementBlocker `json:"messages"` +} +type WorkerRetirement struct { + WorkerID string `json:"worker_id"` + Retired bool `json:"retired"` + CanRetire bool `json:"can_retire"` + Blockers WorkerRetirementBlockers `json:"blockers"` +} +type WorkerRetirementReceipt struct { + ID string `json:"id"` + Revision int64 `json:"revision"` + Outcome string `json:"outcome"` +} + +func validWorkerRetirementBlockers(b WorkerRetirementBlockers) bool { + for _, group := range []WorkerRetirementBlocker{b.Jobs, b.Notes, b.Messages} { + if group.Count < 0 || group.Count >= 1<<53 || group.IDs == nil || len(group.IDs) != int(min(group.Count, 20)) { + return false + } + seen := map[string]bool{} + for _, id := range group.IDs { + if !validID(id) || seen[id] { + return false + } + seen[id] = true + } + } + return true +} +func (c *Client) WorkerRetirement(ctx context.Context, worker string) (WorkerRetirement, error) { + if !validID(worker) { + return WorkerRetirement{}, validation() + } + var value WorkerRetirement + if err := c.get(ctx, c.projectPath("workers", worker, "retirement"), nil, true, &value); err != nil { + return WorkerRetirement{}, err + } + empty := value.Blockers.Jobs.Count == 0 && value.Blockers.Notes.Count == 0 && value.Blockers.Messages.Count == 0 + if value.WorkerID != worker || !validWorkerRetirementBlockers(value.Blockers) || value.CanRetire != (!value.Retired && empty) { + return WorkerRetirement{}, invalidResponse() + } + return value, nil +} +func (c *Client) RetireWorker(ctx context.Context, key, worker string) (WorkerRetirementReceipt, error) { + if !validID(worker) || !validMutationKey(key) { + return WorkerRetirementReceipt{}, mutationValidation() + } + var value WorkerRetirementReceipt + if err := c.mutate(ctx, http.MethodPost, c.projectPath("workers", worker, "retire"), key, struct{}{}, http.StatusOK, &value); err != nil { + return WorkerRetirementReceipt{}, err + } + if value.ID != worker || value.Revision != 2 || !oneReviewOf(value.Outcome, "retired", "unchanged") { + return WorkerRetirementReceipt{}, unknownMutation("invalid_response", "The worker retirement receipt was invalid; its outcome is unknown.", http.StatusOK) + } + return value, nil +} + +func safeWorkerRetirementBlockers(value any) any { + body, err := json.Marshal(value) + var blockers WorkerRetirementBlockers + if err != nil || strictjson.Decode(body, &blockers) != nil || !completeShape(body, &blockers) || !validWorkerRetirementBlockers(blockers) { + return nil + } + return blockers +} diff --git a/internal/client/worker_retirement_test.go b/internal/client/worker_retirement_test.go new file mode 100644 index 000000000..8338e194a --- /dev/null +++ b/internal/client/worker_retirement_test.go @@ -0,0 +1,307 @@ +package client_test + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/client" +) + +func retirementPreview() client.WorkerRetirement { + empty := client.WorkerRetirementBlocker{IDs: []string{}} + return client.WorkerRetirement{WorkerID: "worker-target", CanRetire: true, Blockers: client.WorkerRetirementBlockers{Jobs: empty, Notes: empty, Messages: empty}} +} +func TestWorkerRetirementStrictBoundTransportAndSingleShotReceipt(t *testing.T) { + preview := retirementPreview() + receipt := client.WorkerRetirementReceipt{ID: preview.WorkerID, Revision: 2, Outcome: "retired"} + var reads, writes atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + if r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("resource selection changed actor") + } + switch r.Method { + case "GET": + reads.Add(1) + if r.URL.Path != "/api/v1/projects/project-one/workers/worker-target/retirement" || r.Header.Get("Idempotency-Key") != "" { + t.Error("preview routing") + } + write(w, 200, preview) + case "POST": + writes.Add(1) + body, _ := io.ReadAll(r.Body) + if r.URL.Path != "/api/v1/projects/project-one/workers/worker-target/retire" || string(body) != "{}" || r.Header.Get("Idempotency-Key") != "explicit-retirement" { + t.Error("retirement request identity changed", string(body)) + } + write(w, 200, receipt) + default: + t.Error("unexpected request") + w.WriteHeader(500) + } + })) + defer service.Close() + c := newClient(t, service) + if got, err := c.WorkerRetirement(t.Context(), preview.WorkerID); err != nil || !reflect.DeepEqual(got, preview) { + t.Fatal(got, err) + } + for _, retired := range []bool{false, true} { + preview = retirementPreview() + preview.Retired = retired + preview.CanRetire = !retired + if _, err := c.WorkerRetirement(t.Context(), preview.WorkerID); err != nil { + t.Fatal(err) + } + } + for name, corrupt := range map[string]func(*client.WorkerRetirement){ + "other worker": func(v *client.WorkerRetirement) { v.WorkerID = "foreign" }, + "retired eligible": func(v *client.WorkerRetirement) { v.Retired = true }, + "blocked eligible": func(v *client.WorkerRetirement) { + v.Blockers.Jobs = client.WorkerRetirementBlocker{Count: 1, IDs: []string{"job-one"}} + }, + "missing IDs": func(v *client.WorkerRetirement) { v.Blockers.Notes.Count = 1 }, + "nil IDs": func(v *client.WorkerRetirement) { v.Blockers.Notes.IDs = nil }, + "negative": func(v *client.WorkerRetirement) { v.Blockers.Messages.Count = -1 }, + "duplicate": func(v *client.WorkerRetirement) { + v.CanRetire = false + v.Blockers.Messages = client.WorkerRetirementBlocker{Count: 2, IDs: []string{"message-one", "message-one"}} + }, + "unsafe ID": func(v *client.WorkerRetirement) { + v.CanRetire = false + v.Blockers.Jobs = client.WorkerRetirementBlocker{Count: 1, IDs: []string{"../private"}} + }, + } { + t.Run(name, func(t *testing.T) { + preview = retirementPreview() + corrupt(&preview) + _, err := c.WorkerRetirement(t.Context(), "worker-target") + checkError(t, err, "invalid_response") + }) + } + preview = retirementPreview() + preview.CanRetire = false + preview.Blockers.Jobs.Count = 21 + for i := 0; i < 20; i++ { + preview.Blockers.Jobs.IDs = append(preview.Blockers.Jobs.IDs, "job-"+strings.Repeat("a", i+1)) + } + if _, err := c.WorkerRetirement(t.Context(), preview.WorkerID); err != nil { + t.Fatal("bounded count larger than IDs rejected", err) + } + for _, outcome := range []string{"retired", "unchanged"} { + receipt.Outcome = outcome + if got, err := c.RetireWorker(t.Context(), "explicit-retirement", "worker-target"); err != nil || got != receipt { + t.Fatal(got, err) + } + } + receipt.ID = "foreign" + _, err := c.RetireWorker(t.Context(), "explicit-retirement", "worker-target") + failure, ok := err.(*client.Error) + if !ok { + t.Fatal(err) + } + if failure.Code != "invalid_response" || !failure.OutcomeUnknown || writes.Load() != 3 { + t.Fatal("invalid receipt retried or treated as known", err, writes.Load()) + } + if reads.Load() != 12 { + t.Fatal("preview retry/fanout", reads.Load()) + } +} + +func TestWorkerArchiveAndSelectedAcknowledgementPreserveDefaultWire(t *testing.T) { + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + requests.Add(1) + if r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("selected ACK changed actor") + } + if r.Method == "GET" { + retired := r.URL.Query().Get("include_retired") == "true" + if !retired && r.URL.Query().Has("include_retired") { + t.Error("default list changed cursor query") + } + write(w, 200, client.Page[client.Worker]{Items: []client.Worker{{ID: "worker-target", ProjectID: "project-one", Name: "Target", Retired: retired}}}) + return + } + b, _ := io.ReadAll(r.Body) + want := "{}" + if r.Header.Get("Idempotency-Key") == "selected" { + want = `{"worker_id":"worker-target"}` + } + if string(b) != want || r.URL.Path != "/api/v1/projects/project-one/messages/message-one/ack" { + t.Error("ACK body/binding", string(b)) + } + write(w, 200, client.MessageReceipt{ID: "message-one", ConversationID: "conversation-one", Outcome: "acknowledged"}) + })) + defer service.Close() + c := newClient(t, service) + if page, err := c.Workers(t.Context(), client.PageOptions{}); err != nil || page.Items[0].Retired { + t.Fatal(page, err) + } + if page, err := c.WorkersWithRetired(t.Context(), client.PageOptions{}, true); err != nil || !page.Items[0].Retired { + t.Fatal(page, err) + } + if _, err := c.Acknowledge(t.Context(), "default", "message-one"); err != nil { + t.Fatal(err) + } + if _, err := c.Acknowledge(t.Context(), "selected", "message-one", "worker-target"); err != nil { + t.Fatal(err) + } + before := requests.Load() + for _, id := range []string{"", "../escape"} { + _, err := c.RetireWorker(t.Context(), "key", id) + checkError(t, err, "validation_failed") + } + if _, err := c.Acknowledge(t.Context(), "selected", "message-one", "../escape"); err == nil { + t.Fatal("invalid selected recipient") + } + if requests.Load() != before { + t.Fatal("malformed operation sent") + } +} + +func longRetirementBlockers(fill string) client.WorkerRetirementBlockers { + var groups [3]client.WorkerRetirementBlocker + for i := range groups { + groups[i].Count = (1 << 53) - 1 + for j := 0; j < 20; j++ { + groups[i].IDs = append(groups[i].IDs, strings.Repeat(fill, 125/len(fill))+strings.Repeat("x", 125%len(fill))+fmt.Sprintf("%03d", j)) + } + } + return client.WorkerRetirementBlockers{Jobs: groups[0], Notes: groups[1], Messages: groups[2]} +} + +func TestWorkerRetirementLongBlockersRemainDefinitive(t *testing.T) { + for _, fill := range []string{"a", "<", "\"", "é"} { + t.Run(fmt.Sprintf("fill-%x", fill), func(t *testing.T) { + blocks := longRetirementBlockers(fill) + details, err := json.Marshal(blocks) + if err != nil || len(details) <= 4096 || len(details) > 48<<10 { + t.Fatal("fixture must exceed the ordinary detail budget within the bounded blocker envelope", len(details), err) + } + var calls atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + calls.Add(1) + if r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("retirement selection changed actor") + } + if r.Method == "POST" { + body, _ := io.ReadAll(r.Body) + if string(body) != "{}" || r.Header.Get("Idempotency-Key") != "blocked-long" || r.URL.Path != "/api/v1/projects/project-one/workers/worker-target/retire" { + t.Error("retirement request identity changed") + } + } + write(w, http.StatusConflict, map[string]any{"error": map[string]any{"code": "worker_retirement_blocked", "message": "Clear blockers first.", "details": blocks}, "request_id": "request-long-blockers"}) + })) + defer service.Close() + c := newClient(t, service) + for _, mutate := range []bool{false, true} { + var err error + if mutate { + _, err = c.RetireWorker(t.Context(), "blocked-long", "worker-target") + } else { + _, err = c.WorkerRetirement(t.Context(), "worker-target") + } + checkError(t, err, "worker_retirement_blocked") + failure := err.(*client.Error) + if failure.Status != http.StatusConflict || failure.OutcomeUnknown || failure.RequestID != "request-long-blockers" || !reflect.DeepEqual(failure.Details, blocks) { + t.Fatal("definitive refusal lost bounded blocker handles", failure) + } + } + if calls.Load() != 2 { + t.Fatal("blocked retirement was retried or fanned out", calls.Load()) + } + }) + } +} + +func TestWorkerRetirementErrorDetailBoundsStayStrict(t *testing.T) { + blocks := longRetirementBlockers("a") + encode := func(value any) string { + t.Helper() + b, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return string(b) + } + valid := encode(blocks) + duplicate := longRetirementBlockers("a") + duplicate.Jobs.IDs[1] = duplicate.Jobs.IDs[0] + oversizedID := longRetirementBlockers("a") + oversizedID.Jobs.IDs[0] += "b" + extraID := longRetirementBlockers("a") + extraID.Jobs.IDs = append(extraID.Jobs.IDs, "extra") + sensitive := longRetirementBlockers("a") + sensitive.Jobs.IDs[0] = testToken + for _, test := range []struct { + name, code, details string + valid bool + }{ + {"ordinary-at-limit", "conflict", `"` + strings.Repeat("a", 4094) + `"`, true}, + {"ordinary-over-limit", "conflict", `"` + strings.Repeat("a", 4095) + `"`, false}, + {"other-code-blocker-shape", "conflict", valid, false}, + {"blocker-over-envelope", "worker_retirement_blocked", `"` + strings.Repeat("a", 48<<10) + `"`, false}, + {"transport-over-limit", "worker_retirement_blocked", `"` + strings.Repeat("a", 64<<10) + `"`, false}, + {"unknown-blocker-field", "worker_retirement_blocked", strings.Replace(valid, `"jobs":{`, `"jobs":{"unknown":0,`, 1), false}, + {"duplicate-blocker-field", "worker_retirement_blocked", strings.Replace(valid, `"jobs":{`, `"jobs":{"count":1,`, 1), false}, + {"null-count", "worker_retirement_blocked", strings.Replace(valid, `"count":9007199254740991`, `"count":null`, 1), false}, + {"unsafe-count", "worker_retirement_blocked", strings.Replace(valid, `9007199254740991`, `9007199254740992`, 1), false}, + {"duplicate-id", "worker_retirement_blocked", encode(duplicate), false}, + {"oversized-id", "worker_retirement_blocked", encode(oversizedID), false}, + {"extra-id", "worker_retirement_blocked", encode(extraID), false}, + {"sensitive-id", "worker_retirement_blocked", encode(sensitive), false}, + } { + t.Run(test.name, func(t *testing.T) { + var calls atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + calls.Add(1) + write(w, http.StatusConflict, map[string]any{"error": map[string]any{"code": test.code, "message": "Request refused.", "details": json.RawMessage(test.details)}, "request_id": "request-bounds"}) + })) + defer service.Close() + c := newClient(t, service) + for _, mutate := range []bool{false, true} { + var err error + if mutate { + _, err = c.RetireWorker(t.Context(), "bounded-error", "worker-target") + } else { + _, err = c.WorkerRetirement(t.Context(), "worker-target") + } + want := "invalid_response" + if test.valid { + want = test.code + } else if mutate && test.name != "transport-over-limit" { + want = "unexpected_status" + } + checkError(t, err, want) + failure := err.(*client.Error) + if failure.OutcomeUnknown != (mutate && !test.valid) || failure.Details != nil { + t.Fatal("invalid detail or outcome escaped its bounds", failure) + } + } + if calls.Load() != 2 { + t.Fatal("error was retried or fanned out", calls.Load()) + } + }) + } +} diff --git a/internal/core/admin_read_test.go b/internal/core/admin_read_test.go index 0f1ab2663..83b1bbbae 100644 --- a/internal/core/admin_read_test.go +++ b/internal/core/admin_read_test.go @@ -39,7 +39,7 @@ func TestReadReauthorizesAdministrativeScopeInSnapshot(t *testing.T) { } // Preserve ordinary project read access while withdrawing administrative // authority after the HTTP boundary obtained its scope. - if _, err := store.DB().Exec(`INSERT INTO grants SELECT id,'read-project',1,0 FROM credentials WHERE principal_id=?`, admin.PrincipalID); err != nil { + if _, err := store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write) SELECT id,'read-project',1,0 FROM credentials WHERE principal_id=?`, admin.PrincipalID); err != nil { t.Fatal(err) } if _, err := store.DB().Exec(`UPDATE credentials SET is_admin=0 WHERE principal_id=?`, admin.PrincipalID); err != nil { diff --git a/internal/core/auth.go b/internal/core/auth.go index 1e1244570..85e19c693 100644 --- a/internal/core/auth.go +++ b/internal/core/auth.go @@ -15,10 +15,30 @@ type querier interface { QueryRowContext(context.Context, string, ...any) *sql.Row } -// Administrative reports whether this scope was obtained through AdminScope. -// It pins the requirement; store reads and mutations reauthorize the credential. +// Administrative pins project-management authority for a project scope, or +// instance administration otherwise. Current credentials are rechecked. func (scope Scope) Administrative() bool { return scope.admin } +func (scope Scope) RequireAdministration() Scope { + scope.admin = true + return scope +} + +// RequireInstanceAdministration preserves the instance-only boundary for +// operations that project management must not authorize. Store reads and +// mutations recheck the authenticated credential, including receipt replay. +func (scope Scope) RequireInstanceAdministration() Scope { + scope.admin = true + scope.instanceAdmin = true + return scope +} + +func IsInstanceAdministrator(ctx context.Context, tx *sql.Tx, principal string) (bool, error) { + var allowed bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM credentials WHERE principal_id=? AND revoked=0 AND is_admin=1)`, principal).Scan(&allowed) + return allowed, err +} + // Authenticate validates a current credential for instance identity inspection. // Project data still requires Scope and administrative actions AdminScope. func (s *Store) Authenticate(r *http.Request) (Scope, error) { return s.authenticate(r) } @@ -102,7 +122,7 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio if scope.expiresAt.IsZero() || !time.Now().Before(scope.expiresAt) { return Fail("unauthorized", "The browser session has expired; connect again.", 401) } - if scope.sessionProject == "" || scope.ProjectID != scope.sessionProject || scope.readOnly && permission != "read" { + if scope.sessionProject == "" || scope.ProjectID != scope.sessionProject || scope.readOnly && permission != "read" || permission == "admin" && !scope.sessionManage { return Fail("forbidden", "The browser session does not permit this project operation.", 403) } } @@ -118,7 +138,7 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio if err != nil { return storageError(err) } - if permission == "admin" && admin != 1 { + if permission == "admin" && admin != 1 && (scope.ProjectID == "" || scope.instanceAdmin) { return Fail("forbidden", "Administrative permission is required.", 403) } if scope.ProjectID != "" { @@ -129,9 +149,9 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio return storageError(err) } if admin != 1 { - var read, write int - err = q.QueryRowContext(ctx, "SELECT can_read,can_write FROM grants WHERE credential_id=? AND project_id=?", credential, scope.ProjectID).Scan(&read, &write) - if errors.Is(err, sql.ErrNoRows) || (err == nil && (read != 1 || permission == "write" && write != 1)) { + var read, write, manage int + err = q.QueryRowContext(ctx, "SELECT can_read,can_write,can_manage FROM grants WHERE credential_id=? AND project_id=?", credential, scope.ProjectID).Scan(&read, &write, &manage) + if errors.Is(err, sql.ErrNoRows) || (err == nil && (read != 1 || permission == "write" && write != 1 || permission == "admin" && (manage != 1 || write != 1))) { return Fail("forbidden", "The credential does not grant this project operation.", 403) } if err != nil { diff --git a/internal/core/browser_session.go b/internal/core/browser_session.go index 2b16fa3f8..9fe3e422b 100644 --- a/internal/core/browser_session.go +++ b/internal/core/browser_session.go @@ -148,11 +148,17 @@ func (s *Store) browserCapabilities(ctx context.Context, q querier, scope Scope, } return false, false, err } - var admin int - if err := q.QueryRowContext(ctx, `SELECT is_admin FROM credentials WHERE token_sha256=? AND revoked=0`, scope.tokenHash).Scan(&admin); err != nil { - return false, false, storageError(err) + if !allowPresentation { + return true, false, nil } - return true, allowPresentation && admin == 1, nil + if err := s.authorize(ctx, q, scope, "admin"); err != nil { + var e *Error + if errors.As(err, &e) && e.Code == "forbidden" { + return true, false, nil + } + return false, false, err + } + return true, true, nil } // ExpireBrowserSession clears only the explicitly selected tab's cookie. It @@ -208,7 +214,7 @@ func (s *Store) browserScope(r *http.Request) (Scope, browserSessionClaims, erro if project != claims.ProjectID { return Scope{}, browserSessionClaims{}, Fail("forbidden", "The browser session permits only its project reads.", 403) } - scope := Scope{ProjectID: project, WorkerID: r.Header.Get("X-FC-Worker"), tokenHash: claims.CredentialHash, instanceID: s.instanceID, readOnly: true, expiresAt: time.Unix(claims.ExpiresAt, 0), sessionProject: claims.ProjectID} + scope := Scope{ProjectID: project, WorkerID: r.Header.Get("X-FC-Worker"), tokenHash: claims.CredentialHash, instanceID: s.instanceID, readOnly: true, expiresAt: time.Unix(claims.ExpiresAt, 0), sessionProject: claims.ProjectID, sessionManage: claims.CanEditPresentation} if len(r.Header.Values("X-FC-Worker")) > 1 || len(scope.WorkerID) > 128 { return Scope{}, browserSessionClaims{}, Fail("validation_failed", "Select at most one valid worker identity.", 400) } diff --git a/internal/core/event_project.go b/internal/core/event_project.go index 55e0adba8..6324bc2b4 100644 --- a/internal/core/event_project.go +++ b/internal/core/event_project.go @@ -16,7 +16,7 @@ const projectFeed = "events:project-metadata" var projectEventTypes = [...]string{ "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", "worker.pause_changed", "worker.primary_job_changed", + "workers.created", "workers.retired", "worker.pause_changed", "worker.primary_job_changed", "note.created", "note.updated", "review.observed", "reviews.policy_configured", "reviews.rounds_configured", "reviews.adoption_obligations_imported", "reviews.adoption_obligation_resolved", "reviews.adoption_obligation_retargeted", diff --git a/internal/core/event_stream_test.go b/internal/core/event_stream_test.go index 08a1a541d..485762c5f 100644 --- a/internal/core/event_stream_test.go +++ b/internal/core/event_stream_test.go @@ -21,7 +21,7 @@ func streamFixture(t *testing.T) (*Store, Scope, string) { t.Cleanup(func() { s.Close() }) token := "synthetic-core-stream-token-1234567" sum := sha256.Sum256([]byte(token)) - _, err = s.DB().Exec(`INSERT INTO projects VALUES('project','project',1,'synthetic/project');INSERT INTO workers VALUES('project','worker','worker');INSERT INTO credentials VALUES('credential','principal',?,0,0);INSERT INTO grants VALUES('credential','project',1,1)`, hex.EncodeToString(sum[:])) + _, err = s.DB().Exec(`INSERT INTO projects VALUES('project','project',1,'synthetic/project');INSERT INTO workers VALUES('project','worker','worker');INSERT INTO credentials VALUES('credential','principal',?,0,0);INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES('credential','project',1,1)`, hex.EncodeToString(sum[:])) if err != nil { t.Fatal(err) } diff --git a/internal/core/events.go b/internal/core/events.go index ac34be4bd..3d4e28f54 100644 --- a/internal/core/events.go +++ b/internal/core/events.go @@ -74,7 +74,10 @@ func (s *Store) readMessageEvents(ctx context.Context, scope Scope, after int64, if err := rows.Scan(&event.Sequence, &event.ProjectID, &event.Type, &event.ResourceID, &event.Revision, &event.ActorID, &payload, &event.CreatedAt); err != nil { return err } - event.Payload = json.RawMessage(payload) + event.Payload, err = messageFeedPayload(event.Type, payload) + if err != nil { + return err + } page.Items = append(page.Items, event) } if err := rows.Err(); err != nil { @@ -90,3 +93,17 @@ func (s *Store) readMessageEvents(ctx context.Context, scope Scope, after int64, }) return page, err } + +// Preserve the existing feed bytes and bounds unless the new peer-ACK audit +// field needs attenuation. The true actor remains in durable event storage. +func messageFeedPayload(kind, payload string) (json.RawMessage, error) { + var retained map[string]json.RawMessage + if err := json.Unmarshal([]byte(payload), &retained); err != nil { + return nil, err + } + if _, ok := retained["actor_worker_id"]; !ok { + return json.RawMessage(payload), nil + } + delete(retained, "actor_worker_id") + return json.Marshal(retained) +} diff --git a/internal/core/live_project_events_test.go b/internal/core/live_project_events_test.go index ad0d5dc1d..cc85358ce 100644 --- a/internal/core/live_project_events_test.go +++ b/internal/core/live_project_events_test.go @@ -34,7 +34,7 @@ func TestLiveProjectReplayVisibleStateOnly(t *testing.T) { } { commitProjectEvent(t, s, scope, kind, fmt.Sprintf("excluded-%d", i)) } - if _, err := s.DB().Exec(`INSERT INTO projects VALUES('foreign','Foreign',2,'synthetic/foreign'); INSERT INTO workers VALUES('foreign','worker','Worker'); INSERT INTO grants VALUES('credential','foreign',1,1)`); err != nil { + if _, err := s.DB().Exec(`INSERT INTO projects VALUES('foreign','Foreign',2,'synthetic/foreign'); INSERT INTO workers VALUES('foreign','worker','Worker'); INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES('credential','foreign',1,1)`); err != nil { t.Fatal(err) } foreign := scope diff --git a/internal/core/project_management.go b/internal/core/project_management.go new file mode 100644 index 000000000..aa06be97d --- /dev/null +++ b/internal/core/project_management.go @@ -0,0 +1,39 @@ +package core + +import ( + "context" + "database/sql" + "errors" + "strconv" +) + +// Project management is an explicit grant alongside read/write, never an +// instance-administrator credential or an automatic upgrade of existing writers. +func (s *Store) ensureProjectManagement(ctx context.Context) error { + return s.EnsureSchema(ctx, "project_management", []string{ + `ALTER TABLE grants ADD COLUMN can_manage INTEGER NOT NULL DEFAULT 0 CHECK(can_manage IN(0,1) AND (can_manage=0 OR (can_read=1 AND can_write=1)))`, + }) +} + +// Check both additive core formats before changing either; partial upgrades must +// not modify a database whose other administration domain is newer. +func (s *Store) checkAdministrationVersions(ctx context.Context) error { + for _, domain := range []string{"project_management", "worker_retirements"} { + var raw string + err := s.db.QueryRowContext(ctx, "SELECT value FROM metadata WHERE key=?", "schema:"+domain).Scan(&raw) + if errors.Is(err, sql.ErrNoRows) { + continue + } + if err != nil { + return storageError(err) + } + version, err := strconv.Atoi(raw) + if err != nil || version < 1 || strconv.Itoa(version) != raw { + return Fail("schema_invalid", "Domain schema version metadata is invalid.", 500) + } + if version > 1 { + return Fail("schema_unsupported", "A domain schema is newer than this service; use a compatible binary.", 500) + } + } + return nil +} diff --git a/internal/core/project_management_test.go b/internal/core/project_management_test.go new file mode 100644 index 000000000..c15743c40 --- /dev/null +++ b/internal/core/project_management_test.go @@ -0,0 +1,109 @@ +package core + +import ( + "context" + "database/sql" + "errors" + "net/http/httptest" + "path/filepath" + "testing" +) + +func TestProjectManagementScopeCannotEscapeOrSurviveDowngrade(t *testing.T) { + ctx := context.Background() + s, err := Open(ctx, filepath.Join(t.TempDir(), "private")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + for _, q := range []string{ + `INSERT INTO projects VALUES('one','One',1,'owner/one'),('two','Two',2,'owner/two')`, + `INSERT INTO credentials VALUES('manager','principal-manager','` + tokenHash("synthetic-project-manager") + `',0,0)`, + `INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) VALUES('manager','one',1,1,1),('manager','two',1,1,0)`, + } { + if _, err := s.DB().Exec(q); err != nil { + t.Fatal(err) + } + } + r := httptest.NewRequest("POST", "/owned-operation", nil) + r.SetPathValue("project_id", "one") + r.Header.Set("Authorization", "Bearer synthetic-project-manager") + managed, err := s.AdminScope(r) + if err != nil || !managed.Administrative() { + t.Fatalf("own management scope: %v", err) + } + ordinary, err := s.Scope(r, "write") + if err != nil { + t.Fatal(err) + } + for _, project := range []string{"two", ""} { + r.SetPathValue("project_id", project) + if _, err := s.AdminScope(r); err == nil { + t.Fatal("manager gained another project's or instance administration") + } + } + mutation := Mutation{Operation: "test.project.manage", Target: "settings", Key: "original-key", Request: struct{}{}} + _, err = s.Mutate(ctx, managed, mutation, func(context.Context, *sql.Tx) (any, error) { return map[string]string{"outcome": "saved"}, nil }) + if err != nil { + t.Fatal(err) + } + if _, err := s.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id='manager' AND project_id='one'`); err != nil { + t.Fatal(err) + } + called := false + err = s.Read(ctx, managed, func(context.Context, *sql.Tx) error { called = true; return nil }) + var failure *Error + if !errors.As(err, &failure) || failure.Code != "forbidden" || called { + t.Fatal("management read survived downgrade", err) + } + if _, _, err := s.Replay(ctx, managed, mutation); !errors.As(err, &failure) || failure.Code != "forbidden" { + t.Fatal("management receipt leaked after downgrade", err) + } + if _, err := s.Mutate(ctx, managed, mutation, func(context.Context, *sql.Tx) (any, error) { called = true; return nil, nil }); !errors.As(err, &failure) || failure.Code != "forbidden" || called { + t.Fatal("management mutation survived downgrade", err) + } + if err := s.Read(ctx, ordinary, func(context.Context, *sql.Tx) error { return nil }); err != nil { + t.Fatal("ordinary read/write grant changed", err) + } + copy := ordinary + copy.ProjectID = "two" + copy.admin = true + if err := s.Read(ctx, copy, func(context.Context, *sql.Tx) error { return nil }); !errors.As(err, &failure) || failure.Code != "forbidden" { + t.Fatal("copied project scope escaped management boundary", err) + } +} + +func TestProjectManagementMigrationPreservesExistingGrantsWithoutElevation(t *testing.T) { + ctx := context.Background() + dir := filepath.Join(t.TempDir(), "private") + s, err := Open(ctx, dir) + if err != nil { + t.Fatal(err) + } + for _, q := range []string{ + `INSERT INTO projects VALUES('one','One',1,'owner/one')`, + `INSERT INTO credentials VALUES('writer','principal-writer','` + tokenHash("synthetic-writer") + `',0,0)`, + `INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES('writer','one',1,1)`, + `DELETE FROM metadata WHERE key='schema:project_management'`, + `ALTER TABLE grants DROP COLUMN can_manage`, + } { + if _, err = s.DB().Exec(q); err != nil { + t.Fatal(err) + } + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + s, err = Open(ctx, dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + var read, write, manage int + if err = s.DB().QueryRow(`SELECT can_read,can_write,can_manage FROM grants WHERE credential_id='writer'`).Scan(&read, &write, &manage); err != nil || read != 1 || write != 1 || manage != 0 { + t.Fatal("existing writer changed or elevated", err) + } + if _, err = s.DB().Exec(`UPDATE grants SET can_read=0,can_manage=1 WHERE credential_id='writer'`); err == nil { + t.Fatal("management without read/write was stored") + } +} diff --git a/internal/core/project_management_upgrade_test.go b/internal/core/project_management_upgrade_test.go new file mode 100644 index 000000000..d115f3333 --- /dev/null +++ b/internal/core/project_management_upgrade_test.go @@ -0,0 +1,227 @@ +package core + +import ( + "context" + "database/sql" + "encoding/json" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" +) + +func copyManagementFixture(t *testing.T, from, to string) { + t.Helper() + if err := filepath.WalkDir(from, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(from, path) + if err != nil { + return err + } + target := filepath.Join(to, rel) + if d.IsDir() { + return os.MkdirAll(target, 0700) + } + body, err := os.ReadFile(path) + if err != nil { + return err + } + return os.WriteFile(target, body, 0600) + }); err != nil { + t.Fatal(err) + } +} +func managementRows(t *testing.T, db *sql.DB, query string) string { + t.Helper() + rows, err := db.Query(query) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + columns, err := rows.Columns() + if err != nil { + t.Fatal(err) + } + out := [][]any{} + for rows.Next() { + values := make([]any, len(columns)) + dest := make([]any, len(columns)) + for i := range values { + dest[i] = &values[i] + } + if err := rows.Scan(dest...); err != nil { + t.Fatal(err) + } + out = append(out, values) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + b, err := json.Marshal(out) + if err != nil { + t.Fatal(err) + } + return string(b) +} +func TestProjectManagementRealParentUpgradePreservesAllRowsAndSchemas(t *testing.T) { + parent := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if parent == "" { + t.Skip("requires genuine pinned-parent binary fixture; see administration proof") + } + dir := filepath.Join(t.TempDir(), "source") + copyManagementFixture(t, filepath.Join(parent, "source"), dir) + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + tables, err := db.Query(`SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`) + if err != nil { + t.Fatal(err) + } + names := []string{} + for tables.Next() { + var name string + if err := tables.Scan(&name); err != nil { + t.Fatal(err) + } + names = append(names, name) + } + tables.Close() + before := map[string]string{} + queries := map[string]string{} + for _, name := range names { + q := `SELECT * FROM "` + name + `" ORDER BY rowid` + if name == "metadata" { + q = `SELECT * FROM metadata WHERE key NOT IN ('schema:project_management','schema:worker_retirements') ORDER BY rowid` + } + queries[name] = q + before[name] = managementRows(t, db, q) + } + schema := managementRows(t, db, `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' AND name<>'grants' ORDER BY type,name`) + if got := managementRows(t, db, `SELECT key FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`); got != "[]" { + t.Fatal("fixture already has new domains", got) + } + db.Close() + s, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + queries["grants"] = `SELECT credential_id,project_id,can_read,can_write FROM grants ORDER BY rowid` + for _, name := range names { + if got := managementRows(t, s.DB(), queries[name]); got != before[name] { + t.Fatalf("old rows changed in %s", name) + } + } + if got := managementRows(t, s.DB(), `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' AND name NOT IN ('grants','worker_retirements') ORDER BY type,name`); got != schema { + t.Fatal("unrelated physical schema changed") + } + if got := managementRows(t, s.DB(), `SELECT can_manage FROM grants WHERE can_manage<>0`); got != "[]" { + t.Fatal("writer silently promoted", got) + } + if got := managementRows(t, s.DB(), `SELECT key,value FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements') ORDER BY key`); got != `[["schema:project_management","1"],["schema:worker_retirements","1"]]` { + t.Fatal(got) + } +} +func TestProjectManagementPrincipalUniquenessAndExactCredentialReauthorization(t *testing.T) { + s, scope, _ := streamFixture(t) + ctx := t.Context() + var principal, hash string + if err := s.DB().QueryRow(`SELECT principal_id,token_sha256 FROM credentials WHERE id='credential'`).Scan(&principal, &hash); err != nil { + t.Fatal(err) + } + if _, err := s.DB().Exec(`INSERT INTO credentials VALUES('sibling',?, ?,1,0)`, principal, strings.Repeat("b", 64)); err == nil { + t.Fatal("principal uniqueness lost") + } + for _, mutate := range []func(Scope) Scope{func(v Scope) Scope { v.PrincipalID = "other"; return v }, func(v Scope) Scope { v.tokenHash = strings.Repeat("c", 64); return v }, func(v Scope) Scope { v.instanceID = "other"; return v }} { + called := false + err := s.Read(ctx, mutate(scope), func(_ context.Context, _ *sql.Tx) error { called = true; return nil }) + if err == nil || called { + t.Fatal("forged credential accepted") + } + } + if _, err := s.DB().Exec(`UPDATE credentials SET token_sha256=? WHERE principal_id=?`, strings.Repeat("d", 64), principal); err != nil { + t.Fatal(err) + } + called := false + err := s.Read(ctx, scope, func(_ context.Context, _ *sql.Tx) error { called = true; return nil }) + if err == nil || called { + t.Fatal("old exact credential survived replacement") + } +} + +func TestProjectManagementNewerRetirementBlocksBeforeManagementMigration(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + for _, query := range []string{`DELETE FROM metadata WHERE key='schema:project_management'`, `ALTER TABLE grants DROP COLUMN can_manage`, `UPDATE metadata SET value='2' WHERE key='schema:worker_retirements'`} { + if _, err = s.DB().Exec(query); err != nil { + t.Fatal(err) + } + } + s.Close() + if next, err := Open(t.Context(), dir); err == nil { + next.Close() + t.Fatal("unknown retirement accepted") + } + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if got := managementRows(t, db, `SELECT key FROM metadata WHERE key='schema:project_management'`); got != "[]" { + t.Fatal("management migrated before newer-domain refusal") + } + var count int + if err := db.QueryRow(`SELECT count(*) FROM pragma_table_info('grants') WHERE name='can_manage'`).Scan(&count); err != nil || count != 0 { + t.Fatal("column changed before version refusal", count, err) + } +} + +func TestProjectManagementRealParentMigrationFailureRollsBack(t *testing.T) { + parent := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if parent == "" { + t.Skip("requires genuine pinned-parent binary fixture") + } + dir := filepath.Join(t.TempDir(), "source") + copyManagementFixture(t, filepath.Join(parent, "source"), dir) + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + before := managementRows(t, db, `SELECT * FROM grants ORDER BY credential_id,project_id`) + if _, err := db.Exec(`CREATE TRIGGER reject_management_version BEFORE INSERT ON metadata WHEN NEW.key='schema:project_management' BEGIN SELECT RAISE(ABORT,'synthetic migration failure'); END`); err != nil { + t.Fatal(err) + } + if next, err := Open(t.Context(), dir); err == nil { + next.Close() + t.Fatal("injected migration failure ignored") + } + if got := managementRows(t, db, `SELECT * FROM grants ORDER BY credential_id,project_id`); got != before { + t.Fatal("failed migration changed grants") + } + var columns, versions int + if err := db.QueryRow(`SELECT count(*) FROM pragma_table_info('grants') WHERE name='can_manage'`).Scan(&columns); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT count(*) FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`).Scan(&versions); err != nil { + t.Fatal(err) + } + if columns != 0 || versions != 0 { + t.Fatal("failed migration left schema or version", columns, versions) + } + if _, err := db.Exec(`DROP TRIGGER reject_management_version`); err != nil { + t.Fatal(err) + } + next, err := Open(t.Context(), dir) + if err != nil { + t.Fatal("retry after injected failure", err) + } + next.Close() +} diff --git a/internal/core/store.go b/internal/core/store.go index f2d2c40c0..a1bed6f1f 100644 --- a/internal/core/store.go +++ b/internal/core/store.go @@ -120,6 +120,18 @@ func Open(ctx context.Context, dataDir string, options ...OpenOption) (*Store, e _ = s.Close() return nil, storageError(err) } + if err = s.checkAdministrationVersions(ctx); err != nil { + _ = s.Close() + return nil, err + } + if err = s.ensureProjectManagement(ctx); err != nil { + _ = s.Close() + return nil, err + } + if err = s.ensureWorkerRetirements(ctx); err != nil { + _ = s.Close() + return nil, err + } return s, nil } diff --git a/internal/core/types.go b/internal/core/types.go index 78bdad0f4..c3213e73a 100644 --- a/internal/core/types.go +++ b/internal/core/types.go @@ -17,8 +17,10 @@ type Scope struct { tokenHash string instanceID string admin bool + instanceAdmin bool readOnly bool expiresAt time.Time + sessionManage bool sessionProject string } diff --git a/internal/core/worker_retirement.go b/internal/core/worker_retirement.go new file mode 100644 index 000000000..3ad57a863 --- /dev/null +++ b/internal/core/worker_retirement.go @@ -0,0 +1,63 @@ +package core + +import ( + "context" + "database/sql" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +func (s *Store) ensureWorkerRetirements(ctx context.Context) error { + return s.EnsureSchema(ctx, "worker_retirements", []string{ + `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`, + }) +} + +// CheckActiveWorker is for new coordination targets. CheckWorker and ordinary +// authorization intentionally retain access to historical worker identities. +func CheckActiveWorker(ctx context.Context, tx *sql.Tx, projectID, workerID string) error { + if err := CheckWorker(ctx, tx, projectID, workerID); err != nil { + return err + } + var retired bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM worker_retirements WHERE project_id=? AND worker_id=?)`, projectID, workerID).Scan(&retired); err != nil { + return storageError(err) + } + if retired { + return Fail("worker_retired", "This worker is retired; select an active worker for new coordination work.", 409) + } + return nil +} + +// RequireProjectManagementTx rechecks the actual authenticated management grant +// inside a mutation. Callers also pin the stronger scope before receipt replay. +func (s *Store) RequireProjectManagementTx(ctx context.Context, tx *sql.Tx, scope Scope) error { + return s.authorize(ctx, tx, scope, "admin") +} + +func ValidateWorkerRetirementsSnapshot(ctx context.Context, tx interface { + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +}) error { + // Canonical UTC RFC3339Nano uses at most 30 bytes (four-digit year, + // nine fractional digits and Z). Bound bytes before values cross into Go; + // invalid sentinels preserve oversized rows so validation rejects them. + rows, err := tx.QueryContext(ctx, `SELECT CASE WHEN length(CAST(r.retired_at AS BLOB))<=30 THEN r.retired_at ELSE '' END,CASE WHEN length(CAST(r.actor_id AS BLOB))<=256 THEN r.actor_id ELSE '' END,w.id FROM worker_retirements r LEFT JOIN workers w ON w.project_id=r.project_id AND w.id=r.worker_id`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var at, actor string + var worker sql.NullString + if err := rows.Scan(&at, &actor, &worker); err != nil { + return err + } + timestamp, err := time.Parse(time.RFC3339Nano, at) + if err != nil || timestamp.IsZero() || at != timestamp.UTC().Format(time.RFC3339Nano) || !worker.Valid || actor == "" || len(actor) > 256 || !utf8.ValidString(actor) || strings.TrimSpace(actor) != actor || strings.IndexFunc(actor, unicode.IsControl) >= 0 { + return Fail("storage_unavailable", "Stored worker retirement facts are invalid.", 500) + } + } + return rows.Err() +} diff --git a/internal/core/worker_retirement_bounds_test.go b/internal/core/worker_retirement_bounds_test.go new file mode 100644 index 000000000..1db967138 --- /dev/null +++ b/internal/core/worker_retirement_bounds_test.go @@ -0,0 +1,90 @@ +package core + +import ( + "context" + "database/sql" + "path/filepath" + "strings" + "testing" +) + +// Observe the actual SQL result, not just the final rejection: checking in Go +// after Scan would still materialize an unbounded attacker-controlled value. +type retirementBoundedReader struct { + db *sql.DB + t *testing.T + rows int +} + +func (r *retirementBoundedReader) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + rows, err := r.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + for rows.Next() { + var at, actor string + var worker sql.NullString + if err := rows.Scan(&at, &actor, &worker); err != nil { + r.t.Fatal(err) + } + if len(at) > 30 || len(actor) > 256 { + r.t.Fatalf("SQL returned unbounded values: timestamp=%d actor=%d", len(at), len(actor)) + } + r.rows++ + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + return r.db.QueryContext(ctx, query, args...) +} + +func TestWorkerRetirementSnapshotByteBounds(t *testing.T) { + const maximumTimestamp = "9999-12-31T23:59:59.999999999Z" + if len(maximumTimestamp) != 30 { + t.Fatal("incorrect canonical UTC timestamp bound") + } + for _, tc := range []struct { + name, at, actor string + valid bool + }{ + {"maximum", maximumTimestamp, strings.Repeat("a", 256), true}, + {"maximum_utf8", maximumTimestamp, strings.Repeat("é", 128), true}, + {"whole_second", "2026-11-01T00:00:00Z", "actor", true}, + {"timestamp_over_boundary", maximumTimestamp + "0", "actor", false}, + {"timestamp_large", strings.Repeat("t", 1<<20), "actor", false}, + {"actor_over_boundary", maximumTimestamp, strings.Repeat("a", 257), false}, + {"actor_utf8_over_boundary", maximumTimestamp, strings.Repeat("é", 129), false}, + {"actor_large", maximumTimestamp, strings.Repeat("a", 1<<20), false}, + {"actor_nul_large", maximumTimestamp, "a\x00" + strings.Repeat("a", 1<<20), false}, + } { + t.Run(tc.name, func(t *testing.T) { + store, err := Open(t.Context(), filepath.Join(t.TempDir(), "store")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + _, err = store.DB().ExecContext(t.Context(), `INSERT INTO projects(id,name,github_repository_id,repository) VALUES('project','Project',1,'owner/repo'); INSERT INTO workers(project_id,id,name) VALUES('project','valid','Valid'),('project','test','Test'); INSERT INTO worker_retirements VALUES('project','valid','2026-11-01T00:00:00Z','actor')`) + if err != nil { + t.Fatal(err) + } + _, err = store.DB().ExecContext(t.Context(), `INSERT INTO worker_retirements VALUES('project','test',?,?)`, tc.at, tc.actor) + if err != nil { + t.Fatal(err) + } + reader := &retirementBoundedReader{db: store.DB(), t: t} + err = ValidateWorkerRetirementsSnapshot(t.Context(), reader) + if reader.rows != 2 { + t.Fatal("SQL silently discarded retirement rows", reader.rows) + } + if tc.valid { + if err != nil { + t.Fatal("valid boundary rejected", err) + } + } else { + receiptCode(t, err, "storage_unavailable") + } + }) + } +} diff --git a/internal/core/worker_retirement_test.go b/internal/core/worker_retirement_test.go new file mode 100644 index 000000000..e90bae415 --- /dev/null +++ b/internal/core/worker_retirement_test.go @@ -0,0 +1,57 @@ +package core + +import ( + "context" + "database/sql" + "path/filepath" + "testing" +) + +func TestWorkerRetirementCoreOnlyStartupAndHistoricalIdentity(t *testing.T) { + dir := filepath.Join(t.TempDir(), "store") + store, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + defer func() { _ = store.Close() }() + err = store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `INSERT INTO projects(id,name,github_repository_id,repository) VALUES('project','Project',1,'owner/repo'); INSERT INTO workers(project_id,id,name) VALUES('project','worker','Worker')`); err != nil { + return err + } + if err := CheckActiveWorker(ctx, tx, "project", "worker"); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES('project','worker','2026-11-01T00:00:00Z','synthetic-actor')`) + return err + }) + if err != nil { + t.Fatal(err) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + store, err = Open(t.Context(), dir) + if err != nil { + t.Fatal("retirement schema did not survive ordinary startup", err) + } + tx, err := store.DB().BeginTx(t.Context(), &sql.TxOptions{ReadOnly: true}) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := CheckWorker(t.Context(), tx, "project", "worker"); err != nil { + t.Fatal("historical identity was deleted", err) + } + receiptCode(t, CheckActiveWorker(t.Context(), tx, "project", "worker"), "worker_retired") + if err := ValidateWorkerRetirementsSnapshot(t.Context(), tx); err != nil { + t.Fatal(err) + } + var version string + if err := tx.QueryRowContext(t.Context(), `SELECT value FROM metadata WHERE key='schema:worker_retirements'`).Scan(&version); err != nil || version != "1" { + t.Fatal("retirement domain version missing", version, err) + } + var domains int + if err := tx.QueryRowContext(t.Context(), `SELECT count(*) FROM sqlite_schema WHERE name IN('jobs','notes','inbox_messages')`).Scan(&domains); err != nil || domains != 0 { + t.Fatal("active identity check required application domains", domains, err) + } +} diff --git a/internal/inbox/inbox.go b/internal/inbox/inbox.go index 818bd2a79..31e95a009 100644 --- a/internal/inbox/inbox.go +++ b/internal/inbox/inbox.go @@ -115,10 +115,10 @@ func (h *handler) send(w http.ResponseWriter, r *http.Request) { return } result, err := h.store.Mutate(r.Context(), scope, core.Mutation{Operation: "messages.send", Target: "collection", Key: key, Request: request}, func(ctx context.Context, tx *sql.Tx) (any, error) { - if err := core.CheckWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { return nil, err } - if err := core.CheckWorker(ctx, tx, scope.ProjectID, request.RecipientWorkerID); err != nil { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, request.RecipientWorkerID); err != nil { return nil, err } id := core.NewID("msg") @@ -399,19 +399,44 @@ func (h *handler) transition(w http.ResponseWriter, r *http.Request, ack bool) { core.WriteError(w, err) return } - if scope.WorkerID == "" { - core.WriteError(w, core.Fail("validation_failed", "Select the recipient with X-FC-Worker.", http.StatusBadRequest)) - return - } if _, err := core.QueryKeys(r, "validation_failed"); err != nil { core.WriteError(w, err) return } - var request struct{} - if err := core.ReadJSON(w, r, &request); err != nil { + var request struct { + WorkerID string `json:"worker_id,omitempty"` + } + var input struct { + WorkerID json.RawMessage `json:"worker_id,omitempty"` + } + var body any = &input + if !ack { + body = &struct{}{} + } + if err := core.ReadJSON(w, r, body); err != nil { core.WriteError(w, err) return } + if input.WorkerID != nil && (json.Unmarshal(input.WorkerID, &request.WorkerID) != nil || !cleanID(request.WorkerID)) { + core.WriteError(w, core.Fail("validation_failed", "An explicit worker_id must identify the message recipient.", http.StatusBadRequest)) + return + } + recipientWorker := scope.WorkerID + if request.WorkerID != "" { + recipientWorker = request.WorkerID + } + if !cleanID(recipientWorker) { + core.WriteError(w, core.Fail("validation_failed", "Select the recipient with X-FC-Worker or an explicit worker_id for acknowledgement.", http.StatusBadRequest)) + return + } + onBehalf := recipientWorker != scope.WorkerID + if onBehalf { + if scope.WorkerID == "" { + core.WriteError(w, core.Fail("validation_failed", "Select the acting worker with X-FC-Worker for acknowledgement on behalf of another recipient.", http.StatusBadRequest)) + return + } + scope = scope.RequireAdministration() + } id := r.PathValue("message_id") operation, outcome := "messages.seen", "seen" if ack { @@ -423,26 +448,35 @@ func (h *handler) transition(w http.ResponseWriter, r *http.Request, ack bool) { return } result, err := h.store.Mutate(r.Context(), scope, core.Mutation{Operation: operation, Target: id, Key: key, Request: request}, func(ctx context.Context, tx *sql.Tx) (any, error) { + if onBehalf { + if err := h.store.RequireProjectManagementTx(ctx, tx, scope); err != nil { + return nil, err + } + } var conversationID, recipient string if err := tx.QueryRowContext(ctx, "SELECT conversation_id,recipient_worker_id FROM inbox_messages WHERE project_id=? AND id=?", scope.ProjectID, id).Scan(&conversationID, &recipient); err != nil { return nil, missing(err) } - if recipient != scope.WorkerID { + if recipient != recipientWorker { return nil, core.Fail("forbidden", "Only the message recipient can change receipt state.", http.StatusForbidden) } var seen, acknowledged bool var revision int64 - if err := tx.QueryRowContext(ctx, "SELECT seen,acknowledged,revision FROM inbox_recipient_state WHERE project_id=? AND message_id=? AND worker_id=?", scope.ProjectID, id, scope.WorkerID).Scan(&seen, &acknowledged, &revision); err != nil { + if err := tx.QueryRowContext(ctx, "SELECT seen,acknowledged,revision FROM inbox_recipient_state WHERE project_id=? AND message_id=? AND worker_id=?", scope.ProjectID, id, recipientWorker).Scan(&seen, &acknowledged, &revision); err != nil { return nil, err } if (ack && acknowledged) || (!ack && seen) { return receipt{ID: id, ConversationID: conversationID, Outcome: "unchanged"}, nil } acknowledged = acknowledged || ack - if _, err := tx.ExecContext(ctx, "UPDATE inbox_recipient_state SET seen=1,acknowledged=?,revision=revision+1 WHERE project_id=? AND message_id=? AND worker_id=?", acknowledged, scope.ProjectID, id, scope.WorkerID); err != nil { + if _, err := tx.ExecContext(ctx, "UPDATE inbox_recipient_state SET seen=1,acknowledged=?,revision=revision+1 WHERE project_id=? AND message_id=? AND worker_id=?", acknowledged, scope.ProjectID, id, recipientWorker); err != nil { return nil, err } - if err := core.AppendEvent(ctx, tx, scope, "message."+outcome, id, revision+1, map[string]string{"conversation_id": conversationID, "recipient_worker_id": scope.WorkerID}); err != nil { + payload := map[string]string{"conversation_id": conversationID, "recipient_worker_id": recipientWorker} + if onBehalf { + payload["actor_worker_id"] = scope.WorkerID + } + if err := core.AppendEvent(ctx, tx, scope, "message."+outcome, id, revision+1, payload); err != nil { return nil, err } return receipt{ID: id, ConversationID: conversationID, Outcome: outcome}, nil diff --git a/internal/inbox/worker_retirement_test.go b/internal/inbox/worker_retirement_test.go new file mode 100644 index 000000000..51086a6fb --- /dev/null +++ b/internal/inbox/worker_retirement_test.go @@ -0,0 +1,227 @@ +package inbox_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/inbox" + "github.com/benhook1013/FireController/internal/server" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestWorkerRetirementRealParentEmptyACKAndRetiredSendReplay(t *testing.T) { + root := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if root == "" { + t.Skip("requires actual parent-produced receipts") + } + body, err := os.ReadFile(filepath.Join(root, "fixture.json")) + if err != nil { + t.Fatal(err) + } + var f map[string]string + if json.Unmarshal(body, &f) != nil { + t.Fatal("fixture metadata") + } + dir := filepath.Join(t.TempDir(), "copy") + err = filepath.WalkDir(filepath.Join(root, "source"), func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(filepath.Join(root, "source"), path) + if err != nil { + return err + } + dest := filepath.Join(dir, rel) + if d.IsDir() { + return os.MkdirAll(dest, 0700) + } + b, err := os.ReadFile(path) + if err != nil { + return err + } + return os.WriteFile(dest, b, 0600) + }) + if err != nil { + t.Fatal(err) + } + s, err := core.Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + mux := server.New(s) + inbox.Register(mux, s) + call := func(path, key, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+f["token"]) + r.Header.Set("X-FC-Worker", f["worker"]) + r.Header.Set("Idempotency-Key", key) + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + mux.ServeHTTP(w, r) + return w + } + base := "/api/v1/projects/" + f["project"] + var before int + if err := s.DB().QueryRow(`SELECT count(*) FROM receipts`).Scan(&before); err != nil { + t.Fatal(err) + } + w := call(base+"/messages/"+f["message"]+"/ack", "parent-empty-ack", "{}") + if w.Code != 200 || w.Body.String() != f["ack_response"] { + t.Fatal("legacy ACK changed", w.Code, w.Body.String()) + } + explicit, _ := json.Marshal(map[string]string{"worker_id": f["worker"]}) + w = call(base+"/messages/"+f["message"]+"/ack", "parent-empty-ack", string(explicit)) + if w.Code != 409 { + t.Fatal("different body reused parent receipt", w.Code) + } + var after int + s.DB().QueryRow(`SELECT count(*) FROM receipts`).Scan(&after) + if before != after { + t.Fatal("replay mutated receipts") + } + var sendKey, original string + if err := s.DB().QueryRow(`SELECT key,response_json FROM receipts WHERE project_id=? AND operation='messages.send'`, f["project"]).Scan(&sendKey, &original); err != nil { + t.Fatal(err) + } + if _, err := s.DB().Exec(`INSERT INTO worker_retirements VALUES(?,?, '2026-11-01T00:00:00Z','synthetic-actor')`, f["project"], f["worker"]); err != nil { + t.Fatal(err) + } + message, _ := json.Marshal(map[string]string{"recipient_worker_id": f["worker"], "body": "Retained message with literal "}) + w = call(base+"/messages", sendKey, string(message)) + if w.Code != 201 || strings.TrimSpace(w.Body.String()) != original { + t.Fatal("retired sender lost exact history", w.Code, w.Body.String(), original) + } + w = call(base+"/messages", "new-after-retirement", string(message)) + if w.Code != 409 || !strings.Contains(w.Body.String(), "worker_retired") { + t.Fatal("new retired send admitted", w.Code, w.Body.String()) + } +} + +func TestWorkerRetirementACKRequiresActingWorker(t *testing.T) { + for _, tc := range []struct { + name string + onBehalf bool + explicitRecipient bool + }{ + {name: "manager", onBehalf: true, explicitRecipient: true}, + {name: "administrator", onBehalf: true, explicitRecipient: true}, + {name: "writer-default"}, + {name: "writer-explicit", explicitRecipient: true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := setup(t) + token := f.clientA + switch tc.name { + case "manager": + token = "synthetic-ack-manager-token" + f.grant(f.a, token, []string{"manage"}) + case "administrator": + token = f.admin + } + actor := f.recipient + if tc.onBehalf { + actor = f.sender + } + body := map[string]string{} + if tc.explicitRecipient { + body["worker_id"] = f.recipient + } + sent := f.send(f.a, f.clientA, f.sender, f.recipient, "Synthetic pending acknowledgement", "", "send") + path := f.path(f.a, "messages/"+sent.ID+"/ack") + before := f.receiptStateSnapshot(f.a, sent.ID, f.recipient) + if before.seen || before.acknowledged || before.revision != 1 { + t.Fatalf("unexpected initial recipient state: %+v", before) + } + + errorCode(t, f.request(http.MethodPost, path, token, "", "ack", body), http.StatusBadRequest, "validation_failed") + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != before { + t.Fatalf("missing acting worker changed durable state: before=%+v after=%+v", before, got) + } + if tc.onBehalf { + errorCode(t, f.request(http.MethodPost, path, f.clientA, actor, "writer-ack", body), http.StatusForbidden, "forbidden") + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != before { + t.Fatalf("ordinary writer changed another recipient's state: %+v", got) + } + } + + // A rejected request must not reserve its key or poison a corrected retry. + first := f.request(http.MethodPost, path, token, actor, "ack", body) + var result receipt + decode(t, first, http.StatusOK, &result) + if result != (receipt{ID: sent.ID, ConversationID: sent.ConversationID, Outcome: "acknowledged"}) { + t.Fatalf("unexpected acknowledgement receipt: %+v", result) + } + want := before + want.receipts++ + want.events++ + want.seen, want.acknowledged = true, true + want.revision++ + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != want { + t.Fatalf("acknowledgement did not commit exactly one transition: want=%+v got=%+v", want, got) + } + + var eventActor, payloadJSON, principal string + var revision int64 + if err := f.store.DB().QueryRow(`SELECT actor_id,payload_json,revision FROM events WHERE project_id=? AND resource_id=? AND event_type='message.acknowledged'`, f.a, sent.ID).Scan(&eventActor, &payloadJSON, &revision); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(token)) + if err := f.store.DB().QueryRow(`SELECT principal_id FROM credentials WHERE token_sha256=?`, hex.EncodeToString(sum[:])).Scan(&principal); err != nil { + t.Fatal(err) + } + var payload map[string]string + if err := json.Unmarshal([]byte(payloadJSON), &payload); err != nil { + t.Fatal(err) + } + if eventActor != principal || revision != want.revision || payload["recipient_worker_id"] != f.recipient || payload["conversation_id"] != sent.ConversationID { + t.Fatalf("acknowledgement lost principal or recipient attribution: actor=%q revision=%d payload=%v", eventActor, revision, payload) + } + actingWorker, hasActingWorker := payload["actor_worker_id"] + if tc.onBehalf && (!hasActingWorker || actingWorker != actor) || !tc.onBehalf && hasActingWorker { + t.Fatalf("acting-worker audit attribution changed: %v", payload) + } + + replay := f.request(http.MethodPost, path, token, actor, "ack", body) + decode(t, replay, http.StatusOK, nil) + if replay.Body.String() != first.Body.String() { + t.Fatal("exact-key replay changed the original acknowledgement receipt") + } + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != want { + t.Fatalf("exact-key replay changed durable state: %+v", got) + } + errorCode(t, f.request(http.MethodPost, path, token, "", "ack", body), http.StatusBadRequest, "validation_failed") + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != want { + t.Fatalf("replay without acting worker changed durable state: %+v", got) + } + }) + } +} + +type receiptStateSnapshot struct { + receipts, events int + seen, acknowledged bool + revision int64 +} + +func (f *fixture) receiptStateSnapshot(project, message, worker string) receiptStateSnapshot { + f.t.Helper() + var snapshot receiptStateSnapshot + if err := f.store.DB().QueryRow(`SELECT count(*) FROM receipts`).Scan(&snapshot.receipts); err != nil { + f.t.Fatal(err) + } + if err := f.store.DB().QueryRow(`SELECT count(*) FROM events`).Scan(&snapshot.events); err != nil { + f.t.Fatal(err) + } + if err := f.store.DB().QueryRow(`SELECT seen,acknowledged,revision FROM inbox_recipient_state WHERE project_id=? AND message_id=? AND worker_id=?`, project, message, worker).Scan(&snapshot.seen, &snapshot.acknowledged, &snapshot.revision); err != nil { + f.t.Fatal(err) + } + return snapshot +} diff --git a/internal/jobs/jobs.go b/internal/jobs/jobs.go index 6479bc2dd..6c0b8b525 100644 --- a/internal/jobs/jobs.go +++ b/internal/jobs/jobs.go @@ -148,7 +148,7 @@ func createJob(store *core.Store) http.HandlerFunc { Operation: "jobs.create", Target: "jobs", Key: key, Request: req, }, func(ctx context.Context, tx *sql.Tx) (any, error) { if req.WorkerID != "" { - if err := core.CheckWorker(ctx, tx, scope.ProjectID, req.WorkerID); err != nil { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, req.WorkerID); err != nil { return nil, err } } @@ -327,7 +327,11 @@ func editJob(store *core.Store) http.HandlerFunc { next.Status = *req.Status } if next.WorkerID != "" { - if err := core.CheckWorker(ctx, tx, scope.ProjectID, next.WorkerID); err != nil { + checkWorker := core.CheckWorker + if next.WorkerID != current.WorkerID || next.Status != "completed" { + checkWorker = core.CheckActiveWorker + } + if err := checkWorker(ctx, tx, scope.ProjectID, next.WorkerID); err != nil { return nil, err } } diff --git a/internal/jobs/notes.go b/internal/jobs/notes.go index 29ae32c88..302661bf4 100644 --- a/internal/jobs/notes.go +++ b/internal/jobs/notes.go @@ -162,14 +162,24 @@ func checkNoteTargets(ctx context.Context, tx *sql.Tx, n note) error { if err := primaryWorker(ctx, tx, n.ProjectID, n.WorkerID); err != nil { return err } + if n.Status == "pending" { + if err := core.CheckActiveWorker(ctx, tx, n.ProjectID, n.WorkerID); err != nil { + return err + } + } } if n.JobID != "" { - var exists int - err := tx.QueryRowContext(ctx, `SELECT 1 FROM jobs WHERE project_id=? AND id=?`, n.ProjectID, n.JobID).Scan(&exists) + var assigned string + err := tx.QueryRowContext(ctx, `SELECT COALESCE(worker_id,'') FROM jobs WHERE project_id=? AND id=?`, n.ProjectID, n.JobID).Scan(&assigned) if errors.Is(err, sql.ErrNoRows) { return core.Fail("job_not_found", "The target job is unavailable in this project.", 404) } - return err + if err != nil { + return err + } + if n.Status == "pending" && assigned != "" { + return core.CheckActiveWorker(ctx, tx, n.ProjectID, assigned) + } } return nil } diff --git a/internal/jobs/primary.go b/internal/jobs/primary.go index 7fb24a6d4..9e5afcbf6 100644 --- a/internal/jobs/primary.go +++ b/internal/jobs/primary.go @@ -58,6 +58,16 @@ func primaryWorker(ctx context.Context, tx *sql.Tx, project, worker string) erro } return err } + +func activePrimaryWorker(ctx context.Context, tx *sql.Tx, project, worker string) error { + err := core.CheckActiveWorker(ctx, tx, project, worker) + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "not_found" { + return core.Fail("worker_not_found", "The target worker is unavailable in this project.", 404) + } + return err +} + func primaryAssignment(ctx context.Context, tx *sql.Tx, project, worker, job string) error { var assigned string err := tx.QueryRowContext(ctx, `SELECT COALESCE(worker_id,'') FROM jobs WHERE project_id=? AND id=?`, project, job).Scan(&assigned) @@ -162,7 +172,7 @@ func replacePrimaryJob(store *core.Store) http.HandlerFunc { return } result, err := store.Mutate(r.Context(), scope, core.Mutation{Operation: "workers.primary-job", Target: worker, Key: key, Request: req}, func(ctx context.Context, tx *sql.Tx) (any, error) { - if err := primaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { + if err := activePrimaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { return nil, err } current, err := readPrimaryJob(ctx, tx, scope.ProjectID, worker) diff --git a/internal/jobs/worker_pause.go b/internal/jobs/worker_pause.go index be3238594..cf32cc310 100644 --- a/internal/jobs/worker_pause.go +++ b/internal/jobs/worker_pause.go @@ -132,7 +132,7 @@ func replaceWorkerPause(store *core.Store) http.HandlerFunc { return } result, err := store.Mutate(r.Context(), scope, core.Mutation{Operation: "workers.pause", Target: worker, Key: key, Request: req}, func(ctx context.Context, tx *sql.Tx) (any, error) { - if err := primaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { + if err := activePrimaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { return nil, err } current, err := readWorkerPause(ctx, tx, scope.ProjectID, worker) diff --git a/internal/jobs/worker_retirement_test.go b/internal/jobs/worker_retirement_test.go new file mode 100644 index 000000000..2b93db084 --- /dev/null +++ b/internal/jobs/worker_retirement_test.go @@ -0,0 +1,81 @@ +package jobs_test + +import ( + "fmt" + "reflect" + "testing" +) + +func TestWorkerRetirementFreezesFocusAndPauseButPreservesReadsAndReplay(t *testing.T) { + a := setupAPI(t) + p := a.createProject("Retirement focus", "owner/retirement-focus") + actor := a.createWorker(p, "actor") + target := a.createWorker(p, "target") + token := a.grant(p, "synthetic-retirement-focus-writer", "read", "write") + base := "/api/v1/projects/" + p + var completed [2]string + for i := range completed { + w := noteCall(a, "POST", base+"/jobs", token, actor, fmt.Sprint("completed-job-", i), map[string]any{"title": "Historical work", "status": "completed", "worker_id": target}) + noteOK(t, w, 201) + var created receipt + decodeResponse(t, w, &created) + completed[i] = created.ID + } + focusPath := base + "/workers/" + target + "/primary-job" + pausePath := base + "/workers/" + target + "/pause" + focusRequest := map[string]any{"expected_revision": 0, "job_id": completed[0]} + pauseRequest := map[string]any{"expected_revision": 0, "paused": true, "reason": "Retaining historical pause"} + focusReceipt := noteCall(a, "PUT", focusPath, token, actor, "old-focus", focusRequest) + pauseReceipt := noteCall(a, "PUT", pausePath, token, actor, "old-pause", pauseRequest) + noteOK(t, focusReceipt, 200) + noteOK(t, pauseReceipt, 200) + if _, err := a.store.DB().Exec(`INSERT INTO worker_retirements VALUES(?,?, '2026-11-01T00:00:00Z','synthetic-actor')`, p, target); err != nil { + t.Fatal(err) + } + before := pauseCounts(t, a) + for i, req := range []map[string]any{{"expected_revision": 1, "job_id": completed[1]}, {"expected_revision": 1, "job_id": ""}} { + noteError(t, noteCall(a, "PUT", focusPath, token, actor, fmt.Sprint("new-focus-", i), req), 409, "worker_retired") + } + noteError(t, noteCall(a, "PUT", pausePath, token, actor, "new-pause", map[string]any{"expected_revision": 1, "paused": false, "reason": ""}), 409, "worker_retired") + if !reflect.DeepEqual(before, pauseCounts(t, a)) { + t.Fatal("retired target mutation changed durable coordination state") + } + for _, path := range []string{focusPath, focusPath + "/history", pausePath, pausePath + "/history"} { + noteOK(t, noteCall(a, "GET", path, token, actor, "", nil), 200) + } + for _, replay := range []struct { + path, key, expected string + request map[string]any + }{{focusPath, "old-focus", focusReceipt.Body.String(), focusRequest}, {pausePath, "old-pause", pauseReceipt.Body.String(), pauseRequest}} { + got := noteCall(a, "PUT", replay.path, token, actor, replay.key, replay.request) + noteOK(t, got, 200) + if got.Body.String() != replay.expected { + t.Fatal("retirement changed an exact prior receipt") + } + } +} + +func TestWorkerRetirementPendingNotesAndReopenedJobsRefuseHistoricalTarget(t *testing.T) { + a := setupAPI(t) + p := a.createProject("Retirement", "owner/retirement") + actor := a.createWorker(p, "actor") + target := a.createWorker(p, "target") + token := a.grant(p, "synthetic-retirement-writer", "read", "write") + base := "/api/v1/projects/" + p + w := noteCall(a, "POST", base+"/jobs", token, actor, "completed-job", map[string]any{"title": "Historical work", "status": "completed", "worker_id": target}) + noteOK(t, w, 201) + var created receipt + decodeResponse(t, w, &created) + if _, err := a.store.DB().Exec(`INSERT INTO worker_retirements VALUES(?,?, '2026-11-01T00:00:00Z','synthetic-actor')`, p, target); err != nil { + t.Fatal(err) + } + for i, req := range []map[string]any{{"expected_revision": 1, "status": "active"}, {"expected_revision": 1, "worker_id": target, "status": "parked"}} { + noteError(t, noteCall(a, "PATCH", base+"/jobs/"+created.ID, token, actor, fmt.Sprint("reopen-", i), req), 409, "worker_retired") + } + for i, req := range []map[string]any{{"worker_id": target, "job_id": "", "phase": "", "kind": "reminder", "body": "Pending direct note"}, {"job_id": created.ID, "worker_id": "", "phase": "", "kind": "reminder", "body": "Pending historical job note"}} { + noteError(t, noteCall(a, "POST", base+"/notes", token, actor, fmt.Sprint("note-", i), req), 409, "worker_retired") + } + // Editing completed history must remain possible without making new work. + noteOK(t, noteCall(a, "PATCH", base+"/jobs/"+created.ID, token, actor, "history-title", map[string]any{"expected_revision": 1, "title": "Updated historical title"}), 200) + noteOK(t, noteCall(a, "GET", base+"/jobs/"+created.ID, token, actor, "", nil), 200) +} diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index 5617b6333..1033e368f 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -158,6 +158,38 @@ func allDiscoveredTools(t *testing.T, session *mcp.ClientSession) (*mcp.ListTool return nil, nil } +func TestAdministrationDiscoveryDescribesAuthority(t *testing.T) { + path := profiles(t, map[string]profile.Context{"alpha": localContext()}, "missing-private-token") + for _, version := range mcp.SupportedProtocolVersions() { + t.Run(version, func(t *testing.T) { + cs := connect(t, adapter(t, path, "alpha"), version) + tools, err := allDiscoveredTools(t, cs) + if err != nil { + t.Fatal(err) + } + contracts := map[string][]string{ + "inbox_list": {"bound worker", "worker_id", "project read permission", "acting identity unchanged", "never mark seen or acknowledged"}, + "inbox_ack": {"bound recipient", "worker_id", "another recipient requires project management", "acting identity unchanged", "also establishing seen", "supplied key"}, + "publication_configuration_read": {"Requires instance administration"}, + "publication_preview": {"Requires instance administration"}, + "publication_apply": {"Requires instance administration"}, + "publication_unpublish": {"Requires instance administration"}, + } + for _, tool := range tools.Tools { + for _, fragment := range contracts[tool.Name] { + if !strings.Contains(tool.Description, fragment) { + t.Errorf("%s discovery omits %q: %s", tool.Name, fragment, tool.Description) + } + } + delete(contracts, tool.Name) + } + if len(contracts) != 0 { + t.Fatal("authority-described tools missing from discovery", contracts) + } + }) + } +} + func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { c := localContext() path := profiles(t, map[string]profile.Context{"alpha": c}, "missing-private-token") @@ -222,6 +254,9 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_source_ci_assess"], expected["review_source_readiness"] = true, true expected["review_source_refresh"], expected["review_source_refresh_read"], expected["review_source_policy_assess"] = true, true, true expected["review_checkpoint_publish"], expected["review_checkpoint_read"], expected["review_checkpoint_recover"] = true, true, true + for _, name := range []string{"review_policy_read", "review_policy_configure", "review_execution_configure", "worker_create", "worker_retirement_read", "worker_retire", "project_credential_grant", "project_credential_update", "project_credential_revoke", "presentation_replace", "presentation_history", "presentation_revision_read", "publication_configuration_read", "publication_preview", "publication_apply", "publication_unpublish", "review_import_preview", "review_import_apply", "review_transfer_preview", "review_transfer_apply"} { + expected[name] = true + } if len(first.Tools) != len(expected) { t.Fatalf("first discovery page has %d tools, expected complete inventory of %d", len(first.Tools), len(expected)) } @@ -242,13 +277,16 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { writes["review_finding_decide"], writes["review_finding_fix"], writes["review_source_finalize"] = true, true, true writes["review_finding_route"], writes["review_route_decide"], writes["review_route_fix"] = true, true, true writes["review_checkpoint_publish"], writes["review_checkpoint_recover"] = true, true + for _, name := range []string{"review_policy_configure", "review_execution_configure", "worker_create", "worker_retire", "project_credential_grant", "project_credential_update", "project_credential_revoke", "presentation_replace", "publication_apply", "publication_unpublish", "review_import_apply", "review_transfer_apply"} { + writes[name] = true + } for _, tool := range tools.Tools { if !expected[tool.Name] { t.Fatalf("unexpected tool %q", tool.Name) } delete(expected, tool.Name) a := tool.Annotations - if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_operation_control" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { + if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_operation_control" || tool.Name == "review_policy_configure" || tool.Name == "review_execution_configure" || tool.Name == "worker_retire" || tool.Name == "project_credential_update" || tool.Name == "project_credential_revoke" || tool.Name == "presentation_replace" || tool.Name == "publication_apply" || tool.Name == "publication_unpublish" || tool.Name == "review_import_apply" || tool.Name == "review_transfer_apply" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { t.Fatal("untruthful operation annotation") } data, _ := json.Marshal(tool.InputSchema) diff --git a/internal/mcpadapter/adoption.go b/internal/mcpadapter/adoption.go index 55b952ebc..5b5045dbf 100644 --- a/internal/mcpadapter/adoption.go +++ b/internal/mcpadapter/adoption.go @@ -39,12 +39,12 @@ type adoptionSpec struct { } var adoptionSpecs = []adoptionSpec{ - {"review_round_adoption_preview", "Preview the existing native round-adoption document against its original-source and current revision guards; no live reviews are requested.", []string{"document"}, []string{"document"}, false, false, false}, - {"review_round_adoption_apply", "Apply the exact previewed native round-adoption document with preview_sha256 and explicit key. Preserves retained attribution and accounting rules; tooling access is not review authorization.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"review_round_adoption_preview", "Preview the existing native round-adoption document against its original-source and current revision guards; no live reviews are requested. Requires project management or instance administration and a valid project worker.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_round_adoption_apply", "Apply the exact previewed native round-adoption document with preview_sha256 and explicit key. Preserves retained attribution and accounting rules; tooling access is not review authorization. Requires project management or instance administration and a valid project worker.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, {"review_obligations_list", "Read one compact carried-obligation page, optionally scoped to pull_number and open/resolved status. Full bodies require review_obligation_read.", []string{"pull_number", "status", "limit", "cursor"}, nil, false, false, false}, {"review_obligation_read", "Read one explicit retained carried obligation and original evidence, without marking it resolved.", []string{"obligation_id"}, []string{"obligation_id"}, false, false, false}, - {"review_obligations_import_preview", "Preview one strict native carried-obligation batch, preserving original evidence and provenance; no application or new review.", []string{"document"}, []string{"document"}, false, false, false}, - {"review_obligations_import_apply", "Apply the exact previewed carried-obligation batch with preview_sha256 and explicit key. Existing source conflicts and evidence requirements remain enforced.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"review_obligations_import_preview", "Preview one strict native carried-obligation batch, preserving original evidence and provenance; no application or new review. Requires project management or instance administration and a valid project worker.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_obligations_import_apply", "Apply the exact previewed carried-obligation batch with preview_sha256 and explicit key. Existing source conflicts and evidence requirements remain enforced. Requires project management or instance administration and a valid project worker.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, {"review_obligation_retarget", "Change the receiving PR of one open carried route with expected_revision, explicit target_pull_number (zero means unassigned backlog), reason and key. Preserves original provenance and open status; no provider work or resolution. Findings/results cannot be retargeted.", []string{"obligation_id", "expected_revision", "target_pull_number", "reason", "idempotency_key"}, []string{"obligation_id", "expected_revision", "target_pull_number", "reason", "idempotency_key"}, true, true, false}, {"review_obligation_resolve", "Resolve one carried obligation using the native {expected_revision,reason,evidence} document and explicit key. Requires a real evidence-backed resolution; grants no review credit.", []string{"obligation_id", "document", "idempotency_key"}, []string{"obligation_id", "document", "idempotency_key"}, true, true, false}, } diff --git a/internal/mcpadapter/arguments.go b/internal/mcpadapter/arguments.go index 8a87f1de1..5554bf7b8 100644 --- a/internal/mcpadapter/arguments.go +++ b/internal/mcpadapter/arguments.go @@ -12,6 +12,11 @@ import ( "github.com/benhook1013/FireController/internal/strictjson" ) +type workersInput struct { + Limit *int `json:"limit,omitempty"` + Cursor string `json:"cursor,omitempty"` + IncludeRetired bool `json:"include_retired,omitempty"` +} type pageInput struct { Limit *int `json:"limit,omitempty"` Cursor string `json:"cursor,omitempty"` @@ -36,6 +41,7 @@ type historyInput struct { Cursor string `json:"cursor,omitempty"` } type inboxInput struct { + WorkerID string `json:"worker_id,omitempty"` Limit *int `json:"limit,omitempty"` Cursor string `json:"cursor,omitempty"` Unread bool `json:"unread,omitempty"` @@ -128,7 +134,7 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { case "context", "doctor", "presentation_read": dst = &struct{}{} case "workers_list": - dst = new(pageInput) + dst = new(workersInput) case "jobs_list": dst = new(jobsInput) case "jobs_assigned": @@ -152,6 +158,8 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { return args, invalidArguments() } switch v := dst.(type) { + case *workersInput: + limit, args.cursor, args.includeRetired = v.Limit, v.Cursor, v.IncludeRetired case *pageInput: limit, args.cursor = v.Limit, v.Cursor case *jobsInput: @@ -163,6 +171,10 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { case *historyInput: limit, args.cursor, args.id = v.Limit, v.Cursor, v.JobID case *inboxInput: + if name != "inbox_list" && v.WorkerID != "" { + return args, invalidArguments() + } + args.worker = v.WorkerID limit, args.cursor, args.unread, args.unack = v.Limit, v.Cursor, v.Unread, v.Unacknowledged case *inboxEventsInput: limit, args.cursor, waitMS = v.Limit, v.Cursor, v.WaitMS @@ -321,7 +333,28 @@ func mutationArguments(name string, data json.RawMessage) (arguments, error) { } args.key = input.Key args.send = client.SendMessageRequest{RecipientWorkerID: input.Recipient, Body: input.Body, ReplyToMessageID: input.Reply} - case "inbox_seen", "inbox_ack": + case "inbox_ack": + var fields map[string]json.RawMessage + if json.Unmarshal(data, &fields) != nil { + return args, invalidArguments() + } + if v, ok := fields["worker_id"]; ok { + var id string + if json.Unmarshal(v, &id) != nil || !validID(id) { + return args, invalidArguments() + } + } + var input struct { + Key string `json:"idempotency_key"` + ID string `json:"message_id"` + Worker string `json:"worker_id,omitempty"` + } + if strictjson.Decode(data, &input) != nil || !validKey(input.Key) || !validID(input.ID) || input.Worker != "" && !validID(input.Worker) { + return args, invalidArguments() + } + args.key, args.id, args.worker = input.Key, input.ID, input.Worker + return args, nil + case "inbox_seen": var input struct { Key string `json:"idempotency_key"` ID string `json:"message_id"` @@ -386,7 +419,7 @@ func toolDefinitions() []definition { {"presentation_read", "Read the bound project appearance and metadata watermark explicitly. No ordinary job or inbox call includes settings; no provider work or mutation.", schema(map[string]any{})}, {"context", "Inspect the immutable local profile configuration; no service verification or credential read.", schema(map[string]any{})}, {"doctor", "Verify the configured service instance, project and worker without provider work.", schema(map[string]any{})}, - {"workers_list", "Read one compact worker page in the bound project.", schema(map[string]any{"limit": limit, "cursor": cursor})}, + {"workers_list", "Read one compact active-worker page; include_retired explicitly includes retained historical identities.", schema(map[string]any{"limit": limit, "cursor": cursor, "include_retired": map[string]any{"type": "boolean"}})}, {"jobs_list", "Read one compact job page with explicit optional worker/status filters.", schema(map[string]any{"limit": limit, "cursor": cursor, "worker_id": id, "status": status})}, {"jobs_assigned", "Read one compact job page assigned to the bound worker; no primary/resume-context claim.", schema(map[string]any{"limit": limit, "cursor": cursor, "status": status})}, {"job_read", "Read explicit full detail and brief for one job.", schema(map[string]any{"job_id": id}, "job_id")}, @@ -394,7 +427,7 @@ func toolDefinitions() []definition { {"job_checkpoint_append", "Append an immutable checkpoint with an explicit key and current expected job revision; return a compact receipt without changing the job or automatically retrying.", schema(map[string]any{"job_id": id, "idempotency_key": key, "expected_job_revision": map[string]any{"type": "integer", "minimum": 1, "maximum": int64(math.MaxInt64)}, "done": checkpointText(8<<10, true), "next": checkpointText(8<<10, true), "blocker": checkpointText(4<<10, false), "evidence": map[string]any{"type": "array", "maxItems": 10, "items": checkpointText(1024, true)}}, "job_id", "idempotency_key", "expected_job_revision", "done", "next")}, {"job_checkpoint_latest", "Read the current job revision and latest checkpoint, or explicit null when none exists; the captured checkpoint revision may be older.", schema(map[string]any{"job_id": id}, "job_id")}, {"job_checkpoint_history", "Read one explicit full checkpoint archive page in descending sequence order; no automatic archive reads.", schema(map[string]any{"job_id": id, "limit": limit, "cursor": cursor}, "job_id")}, - {"inbox_list", "Read one compact preview page for the bound worker; never mark seen or acknowledged.", schema(map[string]any{"limit": limit, "cursor": cursor, "unread": map[string]any{"type": "boolean"}, "unacknowledged": map[string]any{"type": "boolean"}})}, + {"inbox_list", "Read one compact preview page for the bound worker, or a recipient selected by worker_id, with project read permission and the acting identity unchanged; never mark seen or acknowledged.", schema(map[string]any{"worker_id": id, "limit": limit, "cursor": cursor, "unread": map[string]any{"type": "boolean"}, "unacknowledged": map[string]any{"type": "boolean"}})}, {"inbox_snapshot", "Read one bounded compact inbox page and its explicit scoped event cursor; no cursor is saved, no messages are marked seen or acknowledged, and no provider work occurs.", schema(map[string]any{"limit": limit, "cursor": cursor, "unread": map[string]any{"type": "boolean"}, "unacknowledged": map[string]any{"type": "boolean"}})}, {"inbox_events", "Read one bounded incoming-message event page after an explicit cursor, optionally waiting up to 4000 ms. No cursor is saved, no automatic polling or subscription occurs, messages are never marked seen or acknowledged, and no provider work occurs.", schema(map[string]any{"cursor": map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": "Required explicit cursor from a scoped snapshot or replay page."}, "limit": limit, "wait_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 4000, "description": "One bounded wait; omission returns immediately."}}, "cursor")}, {"inbox_thread", "Read one explicit conversation page with full immutable bodies; no receipt-state change.", schema(map[string]any{"conversation_id": id, "limit": limit, "cursor": cursor}, "conversation_id")}, @@ -402,6 +435,6 @@ func toolDefinitions() []definition { {"job_edit", "Edit selected job fields with an explicit key and expected revision; empty brief/worker clears those fields. No automatic retry.", editSchema}, {"inbox_send", "Send an immutable message as the bound worker with an explicit key, optionally replying to a message; return a compact receipt.", schema(map[string]any{"idempotency_key": key, "recipient_worker_id": id, "body": map[string]any{"type": "string", "minLength": 1, "maxLength": 16 << 10}, "reply_to_message_id": id}, "idempotency_key", "recipient_worker_id", "body")}, {"inbox_seen", "Explicitly mark a message seen as its bound recipient worker using the supplied key.", schema(map[string]any{"idempotency_key": key, "message_id": id}, "idempotency_key", "message_id")}, - {"inbox_ack", "Explicitly acknowledge a message as its bound recipient worker, also establishing seen, using the supplied key.", schema(map[string]any{"idempotency_key": key, "message_id": id}, "idempotency_key", "message_id")}, + {"inbox_ack", "Explicitly acknowledge a message, also establishing seen, using the supplied key. Defaults to the bound recipient; an explicit worker_id for another recipient requires project management and keeps the acting identity unchanged.", schema(map[string]any{"worker_id": id, "idempotency_key": key, "message_id": id}, "idempotency_key", "message_id")}, }, reviewDefinitions()...) } diff --git a/internal/mcpadapter/existing_management.go b/internal/mcpadapter/existing_management.go new file mode 100644 index 000000000..3a665329b --- /dev/null +++ b/internal/mcpadapter/existing_management.go @@ -0,0 +1,262 @@ +package mcpadapter + +// Existing project-management tools expose named typed-client operations only. +// Documents are native operation inputs, never URLs, HTTP verbs or credentials. +import ( + "bytes" + "context" + "encoding/json" + "math" + "time" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type existingManagementInput struct { + Document json.RawMessage `json:"document,omitempty"` + Changes json.RawMessage `json:"changes,omitempty"` + IdempotencyKey string `json:"idempotency_key,omitempty"` + PreviewSHA256 string `json:"preview_sha256,omitempty"` + ExpectedRevision *int64 `json:"expected_revision,omitempty"` + Revision int64 `json:"revision,omitempty"` + Limit int `json:"limit,omitempty"` + Cursor string `json:"cursor,omitempty"` + PullNumber int64 `json:"pull_number,omitempty"` + Status string `json:"status,omitempty"` + ObligationID string `json:"obligation_id,omitempty"` + CollectionID string `json:"collection_id,omitempty"` + PageID string `json:"page_id,omitempty"` + SourceKey string `json:"source_key,omitempty"` + PullNumbers []int64 `json:"pull_numbers,omitempty"` + WaitSeconds int `json:"wait_seconds,omitempty"` + TargetPullNumber *int64 `json:"target_pull_number,omitempty"` + Reason string `json:"reason,omitempty"` +} +type existingManagementArgs struct { + name string + input existingManagementInput + presentation client.ReplacePresentationRequest + publication client.PublicationInput +} +type existingManagementSpec struct { + name, description string + fields, required []string + write, destructive, external bool +} + +var existingManagementSpecs = []existingManagementSpec{ + {"presentation_replace", "Replace this project's presentation using the native {expected_revision,presentation} document. Requires project management and an explicit key; preserves the normal theme/config validation.", []string{"document", "idempotency_key"}, []string{"document", "idempotency_key"}, true, true, false}, + {"presentation_history", "Read one presentation history page; no automatic continuation.", []string{"limit", "cursor"}, nil, false, false, false}, + {"presentation_revision_read", "Read one retained presentation revision.", []string{"revision"}, []string{"revision"}, false, false, false}, + {"publication_configuration_read", "Read this project's selected public publication configuration. Requires instance administration. Private edits are not published implicitly.", nil, nil, false, false, false}, + {"publication_preview", "Preview a complete native publication input {expected_revision,enabled,manifest}; returns its content and preview_sha256, without publishing. Requires instance administration.", []string{"document"}, []string{"document"}, false, false, false}, + {"publication_apply", "Apply the exact approved publication input with its preview_sha256, expected revision and explicit key. Requires instance administration. Makes only explicitly selected public content available.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"publication_unpublish", "Disable the selected project's public publication with current expected_revision and an explicit key. Requires instance administration. Retains private content and publication history.", []string{"expected_revision", "idempotency_key"}, []string{"expected_revision", "idempotency_key"}, true, true, false}, + {"review_import_preview", "Validate and preview a complete native review-import document without applying it or inventing review evidence. Requires project management or instance administration.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_import_apply", "Apply the exact previewed native review-import document with preview_sha256 and explicit key. Requires project management or instance administration; retains original evidence and existing admission guards.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"review_transfer_preview", "Preview one bounded additive native review-history transfer without applying it; no lifetime-project export or provider work. Requires project management or instance administration.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_transfer_apply", "Apply the exact previewed additive native review-history transfer with preview_sha256 and explicit key; does not reset controls or manufacture completion credit. Requires project management or instance administration.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, +} + +func existingManagementSpecFor(name string) (existingManagementSpec, bool) { + for _, s := range existingManagementSpecs { + if s.name == name { + return s, true + } + } + return existingManagementSpec{}, false +} +func existingManagementTool(name string) bool { _, ok := existingManagementSpecFor(name); return ok } +func existingManagementWrite(name string) bool { + s, ok := existingManagementSpecFor(name) + return ok && s.write +} +func existingManagementDestructive(name string) bool { + s, ok := existingManagementSpecFor(name) + return ok && s.destructive +} +func existingManagementExternal(name string) bool { + s, ok := existingManagementSpecFor(name) + return ok && s.external +} +func existingManagementDefinitions() []definition { + var out []definition + for _, s := range existingManagementSpecs { + properties := map[string]any{} + for _, name := range s.fields { + p := map[string]any{"type": "string", "minLength": 1, "maxLength": 128} + switch name { + case "document", "changes": + p = map[string]any{"type": "object", "description": "Strict native operation document. The existing typed client validates its exact fields, values and byte budget before any service call."} + case "revision": + p = map[string]any{"type": "integer", "minimum": 1, "maximum": int64(math.MaxInt64 - 1)} + case "expected_revision": + p = map[string]any{"type": "integer", "minimum": 0, "maximum": int64(math.MaxInt64 - 1)} + case "pull_number": + p = map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647} + case "target_pull_number": + p = map[string]any{"type": "integer", "minimum": 0, "maximum": 2147483647} + case "reason": + p = map[string]any{"type": "string", "minLength": 1, "maxLength": 4096} + case "pull_numbers": + p = map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "uniqueItems": true, "items": map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647}} + case "limit": + p = map[string]any{"type": "integer", "minimum": 1, "maximum": 100} + case "wait_seconds": + p = map[string]any{"type": "integer", "minimum": 0, "maximum": maxToolWaitSeconds} + case "preview_sha256": + p = map[string]any{"type": "string", "pattern": "^[a-f0-9]{64}$"} + case "cursor": + p = map[string]any{"type": "string", "minLength": 1, "maxLength": 4096} + case "status": + p = map[string]any{"type": "string", "enum": []string{"open", "resolved"}} + } + properties[name] = p + } + required := s.required + if required == nil { + required = []string{} + } + out = append(out, definition{s.name, s.description, map[string]any{"type": "object", "additionalProperties": false, "properties": properties, "required": required}}) + } + return out +} +func parseExistingManagementArguments(name string, raw json.RawMessage) (*existingManagementArgs, error) { + spec, ok := existingManagementSpecFor(name) + if !ok || len(raw) > (256<<10)+1024 || strictjson.Validate(raw) != nil { + return nil, invalidArguments() + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return nil, invalidArguments() + } + allowed := map[string]bool{} + for _, f := range spec.fields { + allowed[f] = true + } + for k, v := range fields { + if !allowed[k] || bytes.Equal(bytes.TrimSpace(v), []byte("null")) { + return nil, invalidArguments() + } + } + for _, k := range spec.required { + var text string + if value, exists := fields[k]; exists && json.Unmarshal(value, &text) == nil && text == "" { + return nil, invalidArguments() + } + if _, ok := fields[k]; !ok { + return nil, invalidArguments() + } + } + a := &existingManagementArgs{name: name} + if strictjson.Decode(raw, &a.input) != nil { + return nil, invalidArguments() + } + in := &a.input + if _, ok := fields["idempotency_key"]; ok && !validKey(in.IdempotencyKey) { + return nil, invalidArguments() + } + if _, ok := fields["preview_sha256"]; ok && !managementHash(in.PreviewSHA256) { + return nil, invalidArguments() + } + if in.ExpectedRevision != nil && (*in.ExpectedRevision < 0 || *in.ExpectedRevision == math.MaxInt64) { + return nil, invalidArguments() + } + if _, ok := fields["revision"]; ok && (in.Revision < 1 || in.Revision == math.MaxInt64) { + return nil, invalidArguments() + } + if _, ok := fields["pull_number"]; ok && (in.PullNumber < 1 || in.PullNumber > 2147483647) { + return nil, invalidArguments() + } + if _, ok := fields["limit"]; ok && (in.Limit < 1 || in.Limit > 100) { + return nil, invalidArguments() + } + if _, ok := fields["cursor"]; ok && !validEventCursor(in.Cursor) { + return nil, invalidArguments() + } + if _, present := fields["status"]; present && in.Status != "open" && in.Status != "resolved" { + return nil, invalidArguments() + } + if in.WaitSeconds < 0 || in.WaitSeconds > maxToolWaitSeconds { + return nil, invalidArguments() + } + var err error + switch name { + case "presentation_replace": + var document map[string]json.RawMessage + if json.Unmarshal(in.Document, &document) != nil { + return nil, invalidArguments() + } + if revision, present := document["expected_revision"]; !present || bytes.Equal(bytes.TrimSpace(revision), []byte("null")) { + return nil, invalidArguments() + } + if _, err := client.DecodePresentationConfig(document["presentation"]); err != nil { + return nil, invalidArguments() + } + err = strictjson.Decode(in.Document, &a.presentation) + if err == nil { + err = client.ValidateReplacePresentationRequest(a.presentation) + } + case "publication_preview", "publication_apply": + a.publication, err = client.DecodePublicationInput(in.Document) + if err == nil && name == "publication_apply" { + err = client.ValidatePublicationApply(in.IdempotencyKey, in.PreviewSHA256, a.publication) + } + case "publication_unpublish": + err = client.ValidatePublicationUnpublish(in.IdempotencyKey, *in.ExpectedRevision) + case "review_import_preview": + err = client.ValidateReviewImportDocument(in.Document) + case "review_import_apply": + err = client.ValidateReviewImportApply(in.IdempotencyKey, in.PreviewSHA256, in.Document) + case "review_transfer_preview": + err = client.ValidateReviewTransferDocument(in.Document) + case "review_transfer_apply": + err = client.ValidateReviewTransferApply(in.IdempotencyKey, in.PreviewSHA256, in.Document) + } + if err != nil { + return nil, invalidArguments() + } + return a, nil +} +func managementHash(value string) bool { + if len(value) != 64 { + return false + } + for _, r := range value { + if !(r >= 'a' && r <= 'f' || r >= '0' && r <= '9') { + return false + } + } + return true +} +func existingManagementBudget(a *existingManagementArgs) time.Duration { return 15 * time.Second } +func executeExistingManagement(ctx context.Context, c *client.Client, a *existingManagementArgs) (any, error) { + in := a.input + page := client.PageOptions{Limit: in.Limit, Cursor: in.Cursor} + switch a.name { + case "presentation_replace": + return c.ReplacePresentation(ctx, in.IdempotencyKey, a.presentation) + case "presentation_history": + return c.PresentationHistory(ctx, page) + case "presentation_revision_read": + return c.PresentationRevision(ctx, in.Revision) + case "publication_configuration_read": + return c.Publication(ctx) + case "publication_preview": + return c.PreviewPublication(ctx, a.publication) + case "publication_apply": + return c.ApplyPublication(ctx, in.IdempotencyKey, in.PreviewSHA256, a.publication) + case "publication_unpublish": + return c.Unpublish(ctx, in.IdempotencyKey, *in.ExpectedRevision) + case "review_import_preview": + return c.PreviewReviewImport(ctx, in.Document) + case "review_import_apply": + return c.ApplyReviewImport(ctx, in.IdempotencyKey, in.PreviewSHA256, in.Document) + case "review_transfer_preview": + return c.PreviewReviewTransfer(ctx, in.Document) + case "review_transfer_apply": + return c.ApplyReviewTransfer(ctx, in.IdempotencyKey, in.PreviewSHA256, in.Document) + } + return nil, invalidArguments() +} diff --git a/internal/mcpadapter/existing_management_native_test.go b/internal/mcpadapter/existing_management_native_test.go new file mode 100644 index 000000000..a654ab918 --- /dev/null +++ b/internal/mcpadapter/existing_management_native_test.go @@ -0,0 +1,106 @@ +package mcpadapter_test + +import ( + "crypto/sha256" + "encoding/hex" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/publicsite" + "net/http" + "net/http/httptest" + "testing" +) + +func TestExistingManagementOfficialSDKNativePublicationAndCurrentAuthority(t *testing.T) { + f := presentationSDKFixture(t) + if err := publicsite.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + publicsite.New(f.store, nil).Register(mux, t.Context()) + service := httptest.NewServer(mux) + defer service.Close() + session := reviewControlsStdio(t, reviewControlsProfile(t, f, service.URL), "chosen") + replace := map[string]any{"document": client.ReplacePresentationRequest{ExpectedRevision: 0, Presentation: client.PresentationConfig{Name: "Selected display"}}, "idempotency_key": "appearance-one"} + var first client.PresentationReceipt + decodeResult(t, call(t, session, "presentation_replace", replace), &first) + if first.ProjectID != f.project || first.Revision != 1 { + t.Fatal(first) + } + var replay client.PresentationReceipt + decodeResult(t, call(t, session, "presentation_replace", replace), &replay) + if replay != first { + t.Fatal("lost-response replay changed mutation", replay) + } + var revision client.PresentationRevision + decodeResult(t, call(t, session, "presentation_revision_read", map[string]any{"revision": 1}), &revision) + if revision.State.Name != "Selected display" || revision.Revision != 1 { + t.Fatal(revision) + } + input, err := client.DecodePublicationInput([]byte(`{"expected_revision":0,"enabled":true,"manifest":{"slug":"published-example","presentation":{"name":"Approved public display"},"description":"Explicitly approved public text"}}`)) + if err != nil { + t.Fatal(err) + } + // Project management still permits presentation changes, but publication + // requires the selected credential's current instance-administrator grant. + diagnosticResult(t, call(t, session, "publication_configuration_read", map[string]any{}), "forbidden", false) + diagnosticResult(t, call(t, session, "publication_preview", map[string]any{"document": input}), "forbidden", false) + diagnosticResult(t, call(t, session, "publication_unpublish", map[string]any{"expected_revision": 0, "idempotency_key": "manager-unpublish"}), "forbidden", false) + digest := sha256.Sum256([]byte(token)) + setAdministrator := func(enabled bool) { + t.Helper() + result, err := f.store.DB().Exec(`UPDATE credentials SET is_admin=? WHERE token_sha256=?`, enabled, hex.EncodeToString(digest[:])) + if err != nil { + t.Fatal(err) + } + if rows, err := result.RowsAffected(); err != nil || rows != 1 { + t.Fatal("selected fixture credential was not updated", rows, err) + } + } + setAdministrator(true) + var preview client.PublicationPreview + decodeResult(t, call(t, session, "publication_preview", map[string]any{"document": input}), &preview) + if preview.SHA256 == "" { + t.Fatal("preview lost native guard") + } + apply := map[string]any{"document": input, "preview_sha256": preview.SHA256, "idempotency_key": "publish-one"} + setAdministrator(false) + diagnosticResult(t, call(t, session, "publication_apply", apply), "forbidden", false) + setAdministrator(true) + var published client.PublicationReceipt + decodeResult(t, call(t, session, "publication_apply", apply), &published) + if published.Revision != 1 { + t.Fatal(published) + } + var configuration client.PublicationConfiguration + decodeResult(t, call(t, session, "publication_configuration_read", map[string]any{}), &configuration) + if configuration.Revision != 1 || !configuration.Enabled || configuration.Manifest == nil || configuration.Manifest.Description != input.Manifest.Description { + t.Fatal("publication selection changed", configuration) + } + var disabled client.PublicationReceipt + decodeResult(t, call(t, session, "publication_unpublish", map[string]any{"expected_revision": 1, "idempotency_key": "unpublish-one"}), &disabled) + if disabled.Revision != 2 { + t.Fatal(disabled) + } + // Demotion must reject the exact retained publication receipts without + // taking away the independent project-management presentation permission. + setAdministrator(false) + diagnosticResult(t, call(t, session, "publication_apply", apply), "forbidden", false) + diagnosticResult(t, call(t, session, "publication_unpublish", map[string]any{"expected_revision": 1, "idempotency_key": "unpublish-one"}), "forbidden", false) + decodeResult(t, call(t, session, "presentation_replace", replace), &replay) + if replay != first { + t.Fatal("instance-admin demotion changed project-management replay", replay) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + diagnosticResult(t, call(t, session, "presentation_replace", replace), "forbidden", false) + var retained client.PresentationRevision + decodeResult(t, call(t, session, "presentation_revision_read", map[string]any{"revision": 1}), &retained) + if retained.State.Name != "Selected display" { + t.Fatal("downgrade changed retained content") + } +} diff --git a/internal/mcpadapter/existing_management_sdk_test.go b/internal/mcpadapter/existing_management_sdk_test.go new file mode 100644 index 000000000..db4ecf516 --- /dev/null +++ b/internal/mcpadapter/existing_management_sdk_test.go @@ -0,0 +1,136 @@ +package mcpadapter_test + +import ( + "encoding/json" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/profile" + "github.com/benhook1013/FireController/internal/reviews" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +type managementWireCase struct { + name, method, path string + args map[string]any + write bool +} + +func managementWireCases(t *testing.T) []managementWireCase { + zero := int64(0) + hash := strings.Repeat("a", 64) + raw := func(v any) json.RawMessage { + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return b + } + pub := json.RawMessage(`{"expected_revision":0,"enabled":true,"manifest":{"slug":"example","presentation":{"name":"Approved public project"},"description":"Approved content"}}`) + imported := json.RawMessage(`{"expected_revision":0,"repository_id":1,"source":"prepared archive","observed_at":"2026-01-01T00:00:00Z","queue":[],"retired":[]}`) + transferred := raw(reviews.TransferRequest{Version: 1, ExpectedRevision: &zero, RepositoryID: 1, Publisher: "prepared archive", Groups: []reviews.TransferGroup{{Source: "original", Pulls: []reviews.PullInput{{Number: 2, Title: "Retained PR", State: "open", CIState: "unknown", Mergeability: "unknown", Runs: []reviews.RunInput{}, Attempts: []reviews.Attempt{}}}}}}) + preview := func(doc json.RawMessage) map[string]any { return map[string]any{"document": doc} } + apply := func(doc json.RawMessage) map[string]any { + return map[string]any{"document": doc, "preview_sha256": hash, "idempotency_key": "chosen"} + } + return []managementWireCase{ + {"presentation_replace", "PUT", "presentation", map[string]any{"document": raw(client.ReplacePresentationRequest{ExpectedRevision: 0, Presentation: client.PresentationConfig{Name: "Selected project"}}), "idempotency_key": "chosen"}, true}, + {"presentation_history", "GET", "presentation/history", map[string]any{}, false}, {"presentation_revision_read", "GET", "presentation/history/1", map[string]any{"revision": 1}, false}, + {"publication_configuration_read", "GET", "publication", map[string]any{}, false}, + {"publication_preview", "POST", "publication/preview", preview(pub), false}, {"publication_apply", "PUT", "publication", apply(pub), true}, {"publication_unpublish", "POST", "publication/unpublish", map[string]any{"expected_revision": 0, "idempotency_key": "chosen"}, true}, + {"review_import_preview", "POST", "reviews/import/preview", preview(imported), false}, {"review_import_apply", "POST", "reviews/import/apply", apply(imported), true}, + {"review_transfer_preview", "POST", "reviews/transfer/preview", preview(transferred), false}, {"review_transfer_apply", "POST", "reviews/transfer/apply", apply(transferred), true}, + } +} +func TestExistingManagementOfficialSDKBoundTransportAndPermissionRefusal(t *testing.T) { + var count atomic.Int64 + var active atomic.Value + active.Store(managementWireCase{}) + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v1/instance" { + json.NewEncoder(w).Encode(map[string]string{"instance_id": "instance-one"}) + return + } + count.Add(1) + current := active.Load().(managementWireCase) + if r.Method != current.method || r.URL.Path != "/api/v1/projects/project-one/"+current.path || r.Header.Get("X-FC-Instance") != "instance-one" || r.Header.Get("X-FC-Worker") != "worker-one" || r.Header.Get("Authorization") != "Bearer "+token { + t.Error("management request lost selected route or binding", r.Method, r.URL.Path, current.name) + } + if current.write && r.Header.Get("Idempotency-Key") != "chosen" || !current.write && r.Header.Get("Idempotency-Key") != "" { + t.Error("mutation key changed", current.name) + } + core.WriteError(w, core.Fail("forbidden", "Project management is required.", 403)) + })) + defer service.Close() + c := localContext() + c.ServerURL = service.URL + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"alpha": c}, credential(t)), "alpha") + listed, err := allDiscoveredTools(t, session) + if err != nil { + t.Fatal(err) + } + names := map[string]bool{} + for _, tool := range listed.Tools { + names[tool.Name] = true + } + for _, entry := range managementWireCases(t) { + t.Run(entry.name, func(t *testing.T) { + if !names[entry.name] { + t.Fatal("management tool missing from real discovery") + } + active.Store(entry) + before := count.Load() + diagnosticResult(t, call(t, session, entry.name, entry.args), "forbidden", false) + if count.Load() != before+1 { + t.Fatal("management call failed locally or retried/fanned out", count.Load()-before) + } + }) + } +} + +func TestPresentationReplacementRevisionGuardStaysLocal(t *testing.T) { + var calls, writes atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v1/instance" { + json.NewEncoder(w).Encode(map[string]string{"instance_id": "instance-one"}) + return + } + writes.Add(1) + if r.Method != "PUT" || r.URL.Path != "/api/v1/projects/project-one/presentation" || r.Header.Get("Idempotency-Key") != "chosen" || r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("presentation request identity changed") + } + var body client.ReplacePresentationRequest + if json.NewDecoder(r.Body).Decode(&body) != nil || body.ExpectedRevision != 0 || body.Presentation.Name != "Selected" { + t.Error("explicit zero revision was not preserved") + } + core.WriteError(w, core.Fail("forbidden", "Project management is required.", http.StatusForbidden)) + })) + defer service.Close() + binding := localContext() + binding.ServerURL = service.URL + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"alpha": binding}, credential(t)), "alpha") + for name, doc := range map[string]map[string]any{ + "missing": {"presentation": map[string]any{"name": "Selected"}}, + "null": {"expected_revision": nil, "presentation": map[string]any{"name": "Selected"}}, + "unknown": {"expected_revision": 0, "unknown": true, "presentation": map[string]any{"name": "Selected"}}, + } { + t.Run(name, func(t *testing.T) { + before := calls.Load() + diagnosticResult(t, call(t, session, "presentation_replace", map[string]any{"document": doc, "idempotency_key": "chosen"}), "invalid_arguments", false) + if calls.Load() != before { + t.Fatal("invalid document performed service work", calls.Load()-before) + } + }) + } + before := writes.Load() + diagnosticResult(t, call(t, session, "presentation_replace", map[string]any{"document": client.ReplacePresentationRequest{ExpectedRevision: 0, Presentation: client.PresentationConfig{Name: "Selected"}}, "idempotency_key": "chosen"}), "forbidden", false) + if writes.Load() != before+1 { + t.Fatal("explicit zero was rejected or automatically retried", writes.Load()-before) + } +} diff --git a/internal/mcpadapter/existing_management_test.go b/internal/mcpadapter/existing_management_test.go new file mode 100644 index 000000000..3eca53dfc --- /dev/null +++ b/internal/mcpadapter/existing_management_test.go @@ -0,0 +1,114 @@ +package mcpadapter + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestExistingManagementSchemasAndMalformedInputsStayLocal(t *testing.T) { + names := map[string]bool{} + for _, d := range existingManagementDefinitions() { + if names[d.name] || d.schema["additionalProperties"] != false { + t.Fatal("ambiguous management tool", d.name) + } + names[d.name] = true + for _, raw := range []json.RawMessage{[]byte(`null`), []byte(`{"project_id":"other-project"}`), []byte(`{"document":{},"idempotency_key":"a","idempotency_key":"b"}`)} { + if _, err := parseExistingManagementArguments(d.name, raw); err == nil { + t.Fatal("unsafe outer arguments accepted", d.name, string(raw)) + } + } + } + for name, raw := range map[string]string{ + "publication_unpublish": `{"expected_revision":null,"idempotency_key":"chosen"}`, + "presentation_replace": `{"document":{},"idempotency_key":"chosen"}`, + "review_import_apply": `{"document":{},"preview_sha256":"short","idempotency_key":"chosen"}`, + } { + if _, err := parseExistingManagementArguments(name, []byte(raw)); err == nil { + t.Fatal("malformed native input accepted", name) + } + } +} + +func TestReviewManagementToolDescriptionsStateAuthority(t *testing.T) { + want := map[string]bool{ + "review_import_preview": false, + "review_import_apply": false, + "review_transfer_preview": false, + "review_transfer_apply": false, + "review_round_adoption_preview": true, + "review_round_adoption_apply": true, + "review_obligations_import_preview": true, + "review_obligations_import_apply": true, + "review_queue_edit": false, + } + definitions := append(existingManagementDefinitions(), adoptionDefinitions()...) + definitions = append(definitions, queueEditDefinition()) + for _, d := range definitions { + workerRequired, ok := want[d.name] + if !ok { + continue + } + if !strings.Contains(d.description, "Requires project management or instance administration") || workerRequired && !strings.Contains(d.description, "valid project worker") { + t.Errorf("%s omits its required authority: %s", d.name, d.description) + } + delete(want, d.name) + } + if len(want) != 0 { + t.Fatalf("management tools missing from discovery: %v", want) + } +} + +func TestPresentationReplacementRequiresExplicitRevision(t *testing.T) { + for name, document := range map[string]string{ + "missing": `{"presentation":{"name":"Selected"}}`, + "null": `{"expected_revision":null,"presentation":{"name":"Selected"}}`, + "duplicate": `{"expected_revision":0,"expected_revision":1,"presentation":{"name":"Selected"}}`, + "unknown": `{"expected_revision":0,"unknown":true,"presentation":{"name":"Selected"}}`, + "mis-cased": `{"Expected_Revision":0,"presentation":{"name":"Selected"}}`, + "string": `{"expected_revision":"0","presentation":{"name":"Selected"}}`, + "negative": `{"expected_revision":-1,"presentation":{"name":"Selected"}}`, + "fractional": `{"expected_revision":0.5,"presentation":{"name":"Selected"}}`, + "exhausted": `{"expected_revision":9223372036854775807,"presentation":{"name":"Selected"}}`, + "nested-unknown": `{"expected_revision":0,"presentation":{"name":"Selected","unknown":true}}`, + "nested-duplicate": `{"expected_revision":0,"presentation":{"name":"Selected","name":"Other"}}`, + } { + t.Run(name, func(t *testing.T) { + raw := `{"document":` + document + `,"idempotency_key":"chosen"}` + if _, err := parseExistingManagementArguments("presentation_replace", []byte(raw)); err == nil { + t.Fatal("malformed revision document accepted", document) + } + }) + } + for _, revision := range []string{"0", "1", "9223372036854775806"} { + raw := `{"document":{"expected_revision":` + revision + `,"presentation":{"name":"Selected"}},"idempotency_key":"chosen"}` + args, err := parseExistingManagementArguments("presentation_replace", []byte(raw)) + if err != nil || args == nil { + t.Fatal("explicit valid revision rejected", revision, err) + } + encoded, err := json.Marshal(args.presentation.ExpectedRevision) + if err != nil || string(encoded) != revision { + t.Fatal("explicit revision changed", revision, string(encoded), err) + } + } +} + +func TestPresentationReplacementRejectsExplicitNullConfig(t *testing.T) { + for _, field := range []string{"name", "brand_name", "tagline", "headings", "theme"} { + t.Run(field, func(t *testing.T) { + config := map[string]any{"name": "Selected", field: nil} + raw, err := json.Marshal(map[string]any{"document": map[string]any{"expected_revision": 7, "presentation": config}, "idempotency_key": "chosen"}) + if err != nil { + t.Fatal(err) + } + if _, err := parseExistingManagementArguments("presentation_replace", raw); err == nil { + t.Fatal("explicit null accepted", field) + } + }) + } + raw := `{"document":{"expected_revision":7,"presentation":{"name":"Selected","brand_name":"Custom","tagline":"Custom tagline","headings":{},"theme":{}}},"idempotency_key":"chosen"}` + args, err := parseExistingManagementArguments("presentation_replace", []byte(raw)) + if err != nil || args.presentation.ExpectedRevision != 7 || args.presentation.Presentation.BrandName != "Custom" { + t.Fatal("valid replacement changed", args, err) + } +} diff --git a/internal/mcpadapter/mutations_test.go b/internal/mcpadapter/mutations_test.go index cb490cefe..5227ea446 100644 --- a/internal/mcpadapter/mutations_test.go +++ b/internal/mcpadapter/mutations_test.go @@ -202,7 +202,7 @@ func TestMutationArgumentsRejectBeforeCredentialAndHTTP(t *testing.T) { {"jobs_create", `{"title":"x"}`}, {"jobs_create", `{"idempotency_key":"","title":"x"}`}, {"jobs_create", `{"idempotency_key":" key","title":"x"}`}, {"jobs_create", `{"idempotency_key":"é","title":"x"}`}, {"jobs_create", `{"idempotency_key":"a\nb","title":"x"}`}, {"jobs_create", `{"idempotency_key":"` + strings.Repeat("k", 129) + `","title":"x"}`}, {"jobs_create", `{"idempotency_key":"k","title":" "}`}, {"jobs_create", `{"idempotency_key":"k","title":"` + strings.Repeat("x", 241) + `"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","brief":"` + strings.Repeat("x", (32<<10)+1) + `"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","worker_id":"../other"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","status":"ready"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","profile":"other"}`}, {"jobs_create", `{"idempotency_key":"k","idempotency_key":"other","title":"x"}`}, {"jobs_create", `{"idempotency_key":"k","Title":"x"}`}, {"jobs_create", `{"idempotency_key":"k","title":null}`}, {"jobs_create", `{"idempotency_key":"k","title":"bad\ud800"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":0,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1.5,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":9223372036854775807,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":9223372036854775808,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1,"brief":null}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1,"status":""}`}, {"job_edit", `{"idempotency_key":"k","job_id":"..","expected_revision":1,"title":"x"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":" "}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"` + strings.Repeat("x", (16<<10)+1) + `"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"x","reply_to_message_id":"a/b"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"x","sender_worker_id":"other"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"x","reply_to_message_id":null}`}, - {"inbox_seen", `{"message_id":"message"}`}, {"inbox_seen", `{"idempotency_key":"k","message_id":".."}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":"message","worker_id":"other"}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":null}`}, + {"inbox_seen", `{"message_id":"message"}`}, {"inbox_seen", `{"idempotency_key":"k","message_id":".."}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":"message","worker_id":""}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":null}`}, } for i, tc := range cases { t.Run(tc.name+string(rune('A'+i)), func(t *testing.T) { diff --git a/internal/mcpadapter/project_owner.go b/internal/mcpadapter/project_owner.go new file mode 100644 index 000000000..6a64a8a10 --- /dev/null +++ b/internal/mcpadapter/project_owner.go @@ -0,0 +1,177 @@ +package mcpadapter + +import ( + "bytes" + "context" + "encoding/json" + "math" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type ownerManagementInvocation struct { + name, key, id string + policy client.ConfigureReviewPolicyRequest + execution client.ConfigureReviewExecutionRequest + worker client.CreateWorkerRequest + grant client.GrantProjectCredentialRequest + update client.UpdateProjectCredentialRequest +} + +func ownerManagementTool(name string) bool { + switch name { + case "review_policy_read", "review_policy_configure", "review_execution_configure", "worker_create", "worker_retirement_read", "worker_retire", "project_credential_grant", "project_credential_revoke", "project_credential_update": + return true + } + return false +} +func ownerManagementWrite(name string) bool { + return ownerManagementTool(name) && name != "review_policy_read" && name != "worker_retirement_read" +} +func ownerManagementDestructive(name string) bool { + return ownerManagementWrite(name) && name != "worker_create" && name != "project_credential_grant" +} +func ownerDecode(raw json.RawMessage, out any, required ...string) bool { + if len(raw) == 0 { + raw = []byte("{}") + } + if len(raw) > 32<<10 || strictjson.Decode(raw, out) != nil { + return false + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return false + } + for _, v := range fields { + if bytes.Equal(bytes.TrimSpace(v), []byte("null")) { + return false + } + } + for _, k := range required { + if _, ok := fields[k]; !ok { + return false + } + } + return true +} +func ownerManagementArguments(name string, raw json.RawMessage) (arguments, error) { + var args arguments + in := &ownerManagementInvocation{name: name} + if name == "worker_retirement_read" { + var input struct { + Worker string `json:"worker_id"` + } + if !ownerDecode(raw, &input, "worker_id") || !validID(input.Worker) { + return args, invalidArguments() + } + in.id = input.Worker + args.ownerManagement = in + return args, nil + } + if name == "review_policy_read" { + if !ownerDecode(raw, &struct{}{}) { + return args, invalidArguments() + } + args.ownerManagement = in + return args, nil + } + if len(raw) > 32<<10 || strictjson.Validate(raw) != nil { + return args, invalidArguments() + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return args, invalidArguments() + } + if json.Unmarshal(fields["idempotency_key"], &in.key) != nil || !validKey(in.key) { + return args, invalidArguments() + } + delete(fields, "idempotency_key") + idField := "" + switch name { + case "worker_retire": + idField = "worker_id" + case "project_credential_revoke", "project_credential_update": + idField = "credential_id" + } + if idField != "" { + if json.Unmarshal(fields[idField], &in.id) != nil || !validID(in.id) { + return args, invalidArguments() + } + delete(fields, idField) + } + body, _ := json.Marshal(fields) + valid := false + switch name { + case "review_policy_configure": + valid = ownerDecode(body, &in.policy, "expected_revision", "required_channels", "max_review_files", "paused_channels") && client.ValidateConfigureReviewPolicy(in.policy) == nil + case "review_execution_configure": + valid = ownerDecode(body, &in.execution, "expected_revision", "capability_id", "mode", "queue", "channels", "paused") && client.ValidateConfigureReviewExecution(in.execution) == nil + case "worker_create": + valid = ownerDecode(body, &in.worker, "name") && client.ValidateCreateWorker(in.worker) == nil + case "project_credential_grant": + valid = ownerDecode(body, &in.grant, "token_sha256", "permissions") && client.ValidateGrantProjectCredential(in.grant) == nil + case "worker_retire", "project_credential_revoke": + valid = ownerDecode(body, &struct{}{}) + case "project_credential_update": + valid = ownerDecode(body, &in.update, "expected_permissions", "permissions") && client.ValidateUpdateProjectCredential(in.id, in.update) == nil + } + if !valid { + return args, invalidArguments() + } + args.ownerManagement = in + return args, nil +} +func executeOwnerManagement(ctx context.Context, c *client.Client, in *ownerManagementInvocation) (any, error) { + switch in.name { + case "review_policy_read": + return c.ReviewPolicy(ctx) + case "review_policy_configure": + return c.ConfigureReviewPolicy(ctx, in.key, in.policy) + case "review_execution_configure": + return c.ConfigureReviewExecution(ctx, in.key, in.execution) + case "worker_retirement_read": + return c.WorkerRetirement(ctx, in.id) + case "worker_retire": + return c.RetireWorker(ctx, in.key, in.id) + case "worker_create": + return c.CreateWorker(ctx, in.key, in.worker) + case "project_credential_grant": + return c.GrantProjectCredential(ctx, in.key, in.grant) + case "project_credential_revoke": + return c.RevokeProjectCredential(ctx, in.key, in.id) + case "project_credential_update": + return c.UpdateProjectCredential(ctx, in.key, in.id, in.update) + } + return nil, invalidArguments() +} +func ownerManagementDefinitions() []definition { + text := func(max int) map[string]any { return map[string]any{"type": "string", "maxLength": max} } + integer := func(min, max int64) map[string]any { + return map[string]any{"type": "integer", "minimum": min, "maximum": max} + } + strEnum := func(values ...string) map[string]any { return map[string]any{"type": "string", "enum": values} } + channels := map[string]any{"type": "array", "minItems": 1, "maxItems": 2, "uniqueItems": true, "items": strEnum("cli", "hosted")} + permissions := map[string]any{"type": "array", "minItems": 1, "maxItems": 3, "uniqueItems": true, "items": strEnum("read", "write", "manage")} + key := text(128) + key["minLength"] = 1 + revision := integer(0, math.MaxInt64-1) + var defs []definition + add := func(name, desc string, props map[string]any, required ...string) { + defs = append(defs, definition{name, desc, map[string]any{"type": "object", "additionalProperties": false, "properties": props, "required": required}}) + } + add("review_policy_read", "Read this project's current configured review requirements, policy revision and attribution. No source refresh or provider action.", map[string]any{}) + roundBounds := map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{"minimum": integer(0, 1000), "maximum": integer(1, 1000)}, "required": []string{"minimum", "maximum"}} + roundDefaults := map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{"hosted": roundBounds, "cli": roundBounds}, "required": []string{"hosted", "cli"}} + add("review_policy_configure", "Project manager: replace current review requirements with exact expected_revision and explicit key. max_review_files zero means no project ceiling; provider limits remain separate. Optional round_defaults sets hosted/cli minimum and maximum for newly initialized PR controls only; omission uses product defaults. Existing controls and taper are unchanged; no review request. See docs/review-round-controls.md.", map[string]any{"idempotency_key": key, "expected_revision": revision, "required_channels": channels, "paused_channels": map[string]any{"type": "array", "maxItems": 2, "uniqueItems": true, "items": strEnum("cli", "hosted")}, "max_review_files": integer(0, 100000), "round_defaults": roundDefaults}, "idempotency_key", "expected_revision", "required_channels", "max_review_files", "paused_channels") + add("review_execution_configure", "Project manager: full guarded replacement of existing capability selection, mode, ordered scheduling queue, channels and pause. Read current configuration and preserve fields outside the intended change. Preserve the current capability_id; capability installation and initial binding are instance-owned. Existing controls/history remain; this requests no review.", map[string]any{"idempotency_key": key, "expected_revision": revision, "capability_id": text(128), "mode": strEnum("independent", "stacked"), "queue": map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "uniqueItems": true, "items": integer(1, 2147483647)}, "channels": channels, "paused": map[string]any{"type": "boolean"}}, "idempotency_key", "expected_revision", "capability_id", "mode", "queue", "channels", "paused") + add("worker_retirement_read", "Read a worker retirement preview: unfinished assigned jobs, pending direct/assigned-job notes and unacknowledged messages, with total counts and up to 20 IDs each. Reassign/finish jobs, reassign/resolve notes and explicitly acknowledge messages first; no automatic changes. Preview is not a reservation.", map[string]any{"worker_id": text(128)}, "worker_id") + add("worker_retire", "Project writer: retire one worker after atomic unfinished-job, pending-note and unacknowledged-message checks. One-way, preserves historical references; never reassigns work, acknowledges messages, deletes credentials or changes acting identity. Use retirement preview first. Exact-key replay is retained; no automatic mutation retry.", map[string]any{"worker_id": text(128), "idempotency_key": key}, "worker_id", "idempotency_key") + add("worker_create", "Project writer: create one named worker in this bound project. Returns its ID; does not switch the acting worker, create credentials or start an agent.", map[string]any{"idempotency_key": key, "name": text(200)}, "idempotency_key", "name") + digest := text(64) + digest["pattern"] = "^[a-f0-9]{64}$" + add("project_credential_grant", "Project manager: grant this project to a distinct non-admin credential using only its lowercase SHA-256 digest. Raw tokens never enter tool arguments/output; generate/store credentials privately through onboarding. manage implies read/write. Explicit key; no other-project or instance authority.", map[string]any{"idempotency_key": key, "token_sha256": digest, "permissions": permissions}, "idempotency_key", "token_sha256", "permissions") + add("project_credential_revoke", "Project manager: revoke a known credential's access to this project only. Preserves its other-project grants; no token or acting identity change. Explicit key, original ID retained after unknown outcome.", map[string]any{"idempotency_key": key, "credential_id": text(128)}, "idempotency_key", "credential_id") + add("project_credential_update", "Project manager: replace one existing non-admin credential's permissions in this project under an exact expected_permissions guard. Preserves credential, principal, token and worker binding; changes no other project. manage implies read/write. No hidden role or identity switching.", map[string]any{"idempotency_key": key, "credential_id": text(128), "expected_permissions": permissions, "permissions": permissions}, "idempotency_key", "credential_id", "expected_permissions", "permissions") + return defs +} diff --git a/internal/mcpadapter/project_owner_test.go b/internal/mcpadapter/project_owner_test.go new file mode 100644 index 000000000..d880c9c99 --- /dev/null +++ b/internal/mcpadapter/project_owner_test.go @@ -0,0 +1,164 @@ +package mcpadapter_test + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/profile" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviews" +) + +func TestProjectOwnerSDKManagementAndSelectedWorker(t *testing.T) { + f := mutationFixture(t) + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if err := reviews.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "sdk-capability", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}, reviewexec.WithNativeProjection()) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + engine.Register(mux) + f.handler = mux + setup := func(method, path string, body any, selected ...string) map[string]any { + t.Helper() + raw, _ := json.Marshal(body) + r := httptest.NewRequest(method, path, bytes.NewReader(raw)) + r.Header.Set("Authorization", "Bearer "+f.admin) + r.Header.Set("Idempotency-Key", core.NewID("setup")) + actor := f.sender + if len(selected) > 0 { + actor = selected[0] + } + r.Header.Set("X-FC-Worker", actor) + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code < 200 || w.Code > 299 { + t.Fatal(w.Code, w.Body.String()) + } + var v map[string]any + if json.Unmarshal(w.Body.Bytes(), &v) != nil { + t.Fatal("setup response") + } + return v + } + const managerToken = "synthetic-private-sdk-manager" + digest := sha256.Sum256([]byte(managerToken)) + setup("POST", "/api/v1/projects/"+f.project+"/credentials", map[string]any{"token_sha256": hex.EncodeToString(digest[:]), "permissions": []string{"manage"}}) + setup("POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", map[string]any{"expected_revision": 0, "capability_id": "sdk-capability", "mode": "independent", "queue": []int{2}, "channels": []string{"cli", "hosted"}, "paused": false}) + tokenFile := filepath.Join(t.TempDir(), "owner.token") + if os.WriteFile(tokenFile, []byte(managerToken), 0600) != nil { + t.Fatal("private token fixture") + } + var lose atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/workers") && lose.Swap(false) { + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, r) + if rec.Code != 200 { + t.Error(rec.Code, rec.Body.String()) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(rec.Code) + w.Write([]byte("{")) + return + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + identity := profile.Context{Profile: "owner", ServerURL: server.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender} + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"owner": identity}, tokenFile), "owner") + var policy client.ReviewRequestReceipt + decodeResult(t, call(t, session, "review_policy_configure", map[string]any{"expected_revision": 0, "paused_channels": []string{}, "required_channels": []string{"cli", "hosted"}, "max_review_files": 100, "round_defaults": map[string]any{"hosted": map[string]any{"minimum": 2, "maximum": 5}, "cli": map[string]any{"minimum": 0, "maximum": 8}}, "idempotency_key": "policy"}), &policy) + var current client.ReviewPolicyRecord + decodeResult(t, call(t, session, "review_policy_read", nil), ¤t) + if current.Revision != policy.Revision || current.Policy.MaxReviewFiles != 100 || current.Policy.RoundDefaults == nil || current.Policy.RoundDefaults.Hosted.Maximum != 5 || current.Policy.RoundDefaults.CLI.Maximum != 8 { + t.Fatal(current) + } + var configured client.ReviewRequestReceipt + decodeResult(t, call(t, session, "review_execution_configure", map[string]any{"expected_revision": 1, "capability_id": "sdk-capability", "mode": "independent", "queue": []int{2, 4}, "channels": []string{"cli", "hosted"}, "paused": false, "idempotency_key": "execution"}), &configured) + if configured.Revision != 2 { + t.Fatal(configured) + } + for _, pair := range []struct { + pull int64 + channel string + maximum, minimum int64 + }{{2, "hosted", 3, 2}, {2, "cli", 6, 2}, {4, "hosted", 5, 2}, {4, "cli", 8, 0}} { + var control client.ReviewRoundControl + decodeResult(t, call(t, session, "review_rounds_read", map[string]any{"pull_number": pair.pull, "channel": pair.channel}), &control) + if !control.Configured || control.Minimum != pair.minimum || control.Maximum != pair.maximum || control.Used != 0 || control.Closed { + t.Fatal("SDK enrollment changed existing controls or missed defaults", control) + } + } + create := map[string]any{"name": "SDK Inspector", "idempotency_key": "create-worker"} + lose.Store(true) + diagnosticResult(t, call(t, session, "worker_create", create), "invalid_response", true) + var worker client.WorkerCreateReceipt + decodeResult(t, call(t, session, "worker_create", create), &worker) + if worker.Outcome != "created" { + t.Fatal(worker) + } + for i := 0; i < 2; i++ { + setup("POST", "/api/v1/projects/"+f.project+"/messages", map[string]any{"recipient_worker_id": f.recipient, "body": "Synthetic selected inbox"}) + } + var inbox client.Page[client.InboxItem] + decodeResult(t, call(t, session, "inbox_list", map[string]any{"worker_id": f.recipient, "limit": 1}), &inbox) + if len(inbox.Items) != 1 || !inbox.HasMore || inbox.Items[0].RecipientWorkerID != f.recipient { + t.Fatal(inbox) + } + diagnosticResult(t, call(t, session, "inbox_list", map[string]any{"worker_id": f.sender, "limit": 1, "cursor": inbox.Cursor}), "validation_failed", false) + newDigest := sha256.Sum256([]byte("new-private-sdk-credential")) + var grant client.ProjectCredentialReceipt + decodeResult(t, call(t, session, "project_credential_grant", map[string]any{"token_sha256": hex.EncodeToString(newDigest[:]), "permissions": []string{"read"}, "idempotency_key": "grant"}), &grant) + var update client.ProjectCredentialUpdateReceipt + decodeResult(t, call(t, session, "project_credential_update", map[string]any{"credential_id": grant.ID, "expected_permissions": []string{"read"}, "permissions": []string{"manage"}, "idempotency_key": "update"}), &update) + if len(update.Permissions) != 3 { + t.Fatal(update) + } + stale := diagnosticResult(t, call(t, session, "project_credential_update", map[string]any{"credential_id": grant.ID, "expected_permissions": []string{"read"}, "permissions": []string{"manage"}, "idempotency_key": "stale-update"}), "credential_permissions_changed", false) + if !strings.Contains(stale.Action, "returned current_permissions") { + t.Fatal(stale) + } + var revoke client.ProjectCredentialReceipt + decodeResult(t, call(t, session, "project_credential_revoke", map[string]any{"credential_id": grant.ID, "idempotency_key": "revoke"}), &revoke) + if revoke.Outcome != "revoked" { + t.Fatal(revoke) + } +} + +func TestProjectOwnerSDKInvalidBeforeCredentials(t *testing.T) { + identity := localContext() + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"chosen": identity}, "missing-owner-token"), "chosen") + for _, v := range []struct{ name, raw string }{ + {"inbox_snapshot", `{"worker_id":"other"}`}, + {"inbox_ack", `{"message_id":"msg-one","worker_id":"","idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":null,"idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":{"hosted":{"minimum":2,"maximum":1},"cli":{"minimum":0,"maximum":8}},"idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":{"hosted":{"minimum":2,"maximum":5},"cli":{"maximum":8}},"idempotency_key":"x"}`}, + {"review_execution_configure", `{"expected_revision":0,"capability_id":"x","mode":"independent","queue":[],"channels":["cli"],"idempotency_key":"x"}`}, + {"worker_create", `{"name":" padded ","idempotency_key":"x"}`}, + {"project_credential_grant", `{"token":"raw secret","permissions":["manage"],"idempotency_key":"x"}`}, + {"project_credential_update", `{"credential_id":"credential-one","expected_permissions":["read"],"permissions":null,"idempotency_key":"x"}`}, + {"project_credential_revoke", `{"credential_id":"bad/id","idempotency_key":"x"}`}, + } { + diagnosticResult(t, call(t, session, v.name, json.RawMessage(v.raw)), "invalid_arguments", false) + } +} diff --git a/internal/mcpadapter/review_queue_edit.go b/internal/mcpadapter/review_queue_edit.go index f8995cde3..945536547 100644 --- a/internal/mcpadapter/review_queue_edit.go +++ b/internal/mcpadapter/review_queue_edit.go @@ -7,7 +7,7 @@ import ( "github.com/benhook1013/FireController/internal/strictjson" ) -// This is the canonical administrator queue-edit document, independent of +// This is the canonical project-management queue-edit document, independent of // native review request policy and scheduling configuration. func queueEditArguments(raw json.RawMessage) (arguments, error) { var in struct { @@ -21,5 +21,5 @@ func queueEditArguments(raw json.RawMessage) (arguments, error) { } func queueEditDefinition() definition { - return definition{"review_queue_edit", "Apply the existing administrator queue edit document for selected metadata, explicit defunct/superseded retirement, reactivation or relative ordering. Requires expected_revision, repository_id and source inside document plus an explicit idempotency key. Preserves evidence and execution policy; performs no provider work.", map[string]any{"type": "object", "additionalProperties": false, "required": []string{"document", "idempotency_key"}, "properties": map[string]any{"document": map[string]any{"type": "object", "description": "Strict native queue edit document, at most 256 KiB; up to 100 metadata/retirement entries plus up to 100 order entries. Validated by the typed client before service I/O."}, "idempotency_key": map[string]any{"type": "string", "minLength": 1, "maxLength": 128}}}} + return definition{"review_queue_edit", "Apply the existing native queue edit document for selected metadata, explicit defunct/superseded retirement, reactivation or relative ordering. Requires project management or instance administration. Requires expected_revision, repository_id and source inside document plus an explicit idempotency key. Preserves evidence and execution policy; performs no provider work.", map[string]any{"type": "object", "additionalProperties": false, "required": []string{"document", "idempotency_key"}, "properties": map[string]any{"document": map[string]any{"type": "object", "description": "Strict native queue edit document, at most 256 KiB; up to 100 metadata/retirement entries plus up to 100 order entries. Validated by the typed client before service I/O."}, "idempotency_key": map[string]any{"type": "string", "minLength": 1, "maxLength": 128}}}} } diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index 92bd30d21..fb60b931b 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -21,6 +21,9 @@ const maxToolWaitSeconds = 50 type arguments struct { operationControl client.ReviewOperationControl ciWatchTargets []client.CIWatchTarget + ownerManagement *ownerManagementInvocation + existingManagement *existingManagementArgs + includeRetired bool reviewRun client.ReviewRunRequest reviewOperations client.ReviewOperationsOptions operationStatus *operationStatusInput @@ -67,6 +70,8 @@ type definition struct { func boundServer(binding profile.Binding) *mcp.Server { s := mcp.NewServer(&mcp.Implementation{Name: "firecontroller", Version: Version}, &mcp.ServerOptions{Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Capabilities: &mcp.ServerCapabilities{Tools: &mcp.ToolCapabilities{}}, PageSize: 128}) definitions := append(toolDefinitions(), checkpointDefinitions()...) + definitions = append(definitions, ownerManagementDefinitions()...) + definitions = append(definitions, existingManagementDefinitions()...) definitions = append(definitions, reviewRunDefinitions()...) definitions = append(definitions, operationListDefinition(), operationControlDefinition()) definitions = append(definitions, roundControlDefinitions()...) @@ -83,14 +88,18 @@ func boundServer(binding profile.Binding) *mcp.Server { transports := sessionTransports{pools: make(map[*mcp.ServerSession]*client.TransportPool)} for _, tool := range definitions { known[tool.name] = true - write := tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + write := ownerManagementWrite(tool.name) || existingManagementWrite(tool.name) || tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" openWorld := tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - destructive := tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" + destructive := ownerManagementDestructive(tool.name) || existingManagementDestructive(tool.name) || tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" s.AddTool(&mcp.Tool{Name: tool.name, Description: tool.description, InputSchema: tool.schema, Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &openWorld}}, func(ctx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) { var args arguments var err error if tool.name == "wait_for_ci" { args, err = ciWatchArguments(request.Params.Arguments) + } else if ownerManagementTool(tool.name) { + args, err = ownerManagementArguments(tool.name, request.Params.Arguments) + } else if existingManagementTool(tool.name) { + args.existingManagement, err = parseExistingManagementArguments(tool.name, request.Params.Arguments) } else if adoptionTool(tool.name) { args.adoption, err = parseAdoptionArguments(tool.name, request.Params.Arguments) } else if tool.name == "review_rounds_read" || tool.name == "review_rounds_configure" { @@ -141,6 +150,20 @@ func boundServer(binding profile.Binding) *mcp.Server { } options := client.PageOptions{Limit: args.limit, Cursor: args.cursor} var value any + if ownerManagementTool(tool.name) { + value, err = executeOwnerManagement(ctx, service, args.ownerManagement) + if err != nil { + return resultFailure(err), nil + } + return result(value, false), nil + } + if existingManagementTool(tool.name) { + value, err = executeExistingManagement(ctx, service, args.existingManagement) + if err != nil { + return resultFailure(err), nil + } + return result(value, false), nil + } switch tool.name { case "review_start": var result client.ReviewRunResult @@ -248,7 +271,7 @@ func boundServer(binding profile.Binding) *mcp.Server { case "worker_pause_history": value, err = service.WorkerPauseHistory(ctx, options) case "workers_list": - value, err = service.Workers(ctx, options) + value, err = service.WorkersWithRetired(ctx, options, args.includeRetired) case "jobs_list": value, err = service.Jobs(ctx, options, client.JobFilter{WorkerID: args.worker, Status: args.status}) case "jobs_assigned": @@ -280,7 +303,7 @@ func boundServer(binding profile.Binding) *mcp.Server { case "job_checklist_history": value, err = service.JobChecklistHistory(ctx, args.id, options) case "inbox_list": - value, err = service.Inbox(ctx, options, client.InboxFilter{Unread: args.unread, Unacknowledged: args.unack}) + value, err = service.Inbox(ctx, options, client.InboxFilter{Unread: args.unread, Unacknowledged: args.unack}, args.worker) case "inbox_snapshot": value, err = service.InboxSnapshot(ctx, options, client.InboxFilter{Unread: args.unread, Unacknowledged: args.unack}) case "inbox_events": @@ -296,7 +319,7 @@ func boundServer(binding profile.Binding) *mcp.Server { case "inbox_seen": value, err = service.MarkSeen(ctx, args.key, args.id) case "inbox_ack": - value, err = service.Acknowledge(ctx, args.key, args.id) + value, err = service.Acknowledge(ctx, args.key, args.id, args.worker) } if err != nil { return resultFailure(err), nil diff --git a/internal/mcpadapter/worker_retirement_test.go b/internal/mcpadapter/worker_retirement_test.go new file mode 100644 index 000000000..944d7ca10 --- /dev/null +++ b/internal/mcpadapter/worker_retirement_test.go @@ -0,0 +1,133 @@ +package mcpadapter_test + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" +) + +func TestWorkerRetirementSDKAndCLIExplicitRecipientWithoutIdentitySwitch(t *testing.T) { + f := mutationFixture(t) + var retirePosts atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/retire") { + retirePosts.Add(1) + } + if r.Method == "POST" && (strings.HasSuffix(r.URL.Path, "/retire") || strings.HasSuffix(r.URL.Path, "/ack")) && r.Header.Get("X-FC-Worker") != f.sender { + t.Error("selected resource impersonated recipient") + } + f.handler.ServeHTTP(w, r) + })) + defer service.Close() + binding := profile.Context{Profile: "writer", ServerURL: service.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender} + adminFile := filepath.Join(t.TempDir(), "admin.token") + if err := os.WriteFile(adminFile, []byte(f.admin), 0600); err != nil { + t.Fatal(err) + } + writerPath := profiles(t, map[string]profile.Context{"writer": binding}, f.credential) + adminPath := profiles(t, map[string]profile.Context{"admin": binding}, adminFile) + sdk := reviewControlsStdio(t, writerPath, "writer") + invoke := func(path, selected string, args ...string) []byte { + t.Helper() + var out, diag bytes.Buffer + full := append([]string{"--profiles-file", path, "--profile", selected}, args...) + if code := cli.RunContext(t.Context(), full, nil, &out, &diag); code != cli.ExitSuccess || diag.Len() != 0 { + t.Fatal(code, diag.String()) + } + return out.Bytes() + } + var message client.MessageReceipt + decodeResult(t, call(t, sdk, "inbox_send", map[string]any{"recipient_worker_id": f.recipient, "body": "Retirement must not silently acknowledge this", "idempotency_key": "retirement-message"}), &message) + var preview client.WorkerRetirement + decodeResult(t, call(t, sdk, "worker_retirement_read", map[string]any{"worker_id": f.recipient}), &preview) + if preview.CanRetire || preview.Retired || preview.Blockers.Messages.Count != 1 || !reflect.DeepEqual(preview.Blockers.Messages.IDs, []string{message.ID}) { + t.Fatal("unacknowledged message not visible", preview) + } + blocked := diagnosticResult(t, call(t, sdk, "worker_retire", map[string]any{"worker_id": f.recipient, "idempotency_key": "blocked-retirement"}), "worker_retirement_blocked", false) + var blockers client.WorkerRetirementBlockers + data, _ := json.Marshal(blocked.Details) + if json.Unmarshal(data, &blockers) != nil || blockers.Messages.Count != 1 || !reflect.DeepEqual(blockers.Messages.IDs, []string{message.ID}) { + t.Fatal("blocked retirement lost current safe handles", blocked) + } + diagnosticResult(t, call(t, sdk, "inbox_ack", map[string]any{"message_id": message.ID, "worker_id": f.recipient, "idempotency_key": "writer-cannot-ack-other"}), "forbidden", false) + diagnosticResult(t, call(t, sdk, "inbox_seen", map[string]any{"message_id": message.ID, "worker_id": f.recipient, "idempotency_key": "seen-stays-own"}), "invalid_arguments", false) + var ack client.MessageReceipt + if json.Unmarshal(invoke(adminPath, "admin", "inbox", "ack", message.ID, "--worker", f.recipient, "--key", "manager-selected-ack"), &ack) != nil || ack.Outcome != "acknowledged" { + t.Fatal("manager recipient ACK failed", ack) + } + if json.Unmarshal(invoke(writerPath, "writer", "workers", "retirement", f.recipient), &preview) != nil || !preview.CanRetire { + t.Fatal(preview) + } + var retired client.WorkerRetirementReceipt + request := map[string]any{"worker_id": f.recipient, "idempotency_key": "shared-retirement"} + decodeResult(t, call(t, sdk, "worker_retire", request), &retired) + var replay client.WorkerRetirementReceipt + if json.Unmarshal(invoke(writerPath, "writer", "workers", "retire", f.recipient, "--key", "shared-retirement"), &replay) != nil || replay != retired || retired.Outcome != "retired" || retired.Revision != 2 { + t.Fatal("CLI/SDK replay diverged", retired, replay) + } + if json.Unmarshal(invoke(writerPath, "writer", "workers", "retire", f.recipient, "--key", "already-retired"), &replay) != nil || replay.Outcome != "unchanged" { + t.Fatal(replay) + } + var active, archive client.Page[client.Worker] + decodeResult(t, call(t, sdk, "workers_list", map[string]any{}), &active) + decodeResult(t, call(t, sdk, "workers_list", map[string]any{"include_retired": true}), &archive) + if len(active.Items) != 1 || active.Items[0].ID != f.sender || len(archive.Items) != 2 { + t.Fatal("active/archive list wrong", active, archive) + } + found := false + for _, w := range archive.Items { + if w.ID == f.recipient { + found = w.Retired + } + } + if !found { + t.Fatal("retired identity lost", archive) + } + var cliArchive client.Page[client.Worker] + if json.Unmarshal(invoke(writerPath, "writer", "workers", "list", "--include-retired"), &cliArchive) != nil || !reflect.DeepEqual(cliArchive, archive) { + t.Fatal("CLI archive differs", cliArchive, archive) + } + if retirePosts.Load() != 4 || f.providers.Load() != 1 { + t.Fatal("automatic retry/provider work", retirePosts.Load(), f.providers.Load()) + } + var retirementEvents int + if err := f.store.DB().QueryRow("SELECT count(*) FROM events WHERE project_id=? AND event_type='workers.retired'", f.project).Scan(&retirementEvents); err != nil || retirementEvents != 1 { + t.Fatal("retirement duplicated", retirementEvents, err) + } +} + +func TestWorkerRetirementSDKAndCLIInvalidStayOffline(t *testing.T) { + sdk := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"chosen": localContext()}, "missing-private-credential"), "chosen") + for _, tc := range []struct{ name, raw string }{ + {"worker_retirement_read", `{"worker_id":null}`}, + {"worker_retire", `{"worker_id":"worker-one"}`}, + {"worker_retire", `{"worker_id":"worker-one","idempotency_key":"x","expected_revision":1}`}, + {"workers_list", `{"include_retired":null}`}, + {"inbox_ack", `{"message_id":"message-one","worker_id":null,"idempotency_key":"x"}`}, + } { + diagnosticResult(t, call(t, sdk, tc.name, json.RawMessage(tc.raw)), "invalid_arguments", false) + } + for _, operation := range []string{"retirement", "retire"} { + var out, diag bytes.Buffer + if code := cli.RunContext(t.Context(), []string{"workers", operation, "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "unacknowledged") || !strings.Contains(out.String(), "nothing is moved") { + t.Fatal("missing offline retirement help", code, out.String(), diag.String()) + } + } + for _, args := range [][]string{{"workers", "retirement"}, {"workers", "retire", "worker-one"}, {"workers", "list", "--include-retired=false"}, {"inbox", "seen", "message-one", "--worker", "worker-other", "--key", "x"}, {"inbox", "ack", "message-one", "--worker", "", "--key", "x"}} { + var out, diag bytes.Buffer + if code := cli.RunContext(t.Context(), append([]string{"--profile", "absent", "--profiles-file", "/unavailable"}, args...), nil, &out, &diag); code != cli.ExitUsage || out.Len() != 0 { + t.Fatal(args, code, diag.String()) + } + } +} diff --git a/internal/publicsite/administration_test.go b/internal/publicsite/administration_test.go new file mode 100644 index 000000000..b6c7c25ee --- /dev/null +++ b/internal/publicsite/administration_test.go @@ -0,0 +1,147 @@ +package publicsite + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http/httptest" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func publicationScope(t *testing.T, f *publicationFixture, token string) core.Scope { + t.Helper() + r := httptest.NewRequest("GET", f.base()+"/publication", nil) + r.SetPathValue("project_id", f.project) + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("X-FC-Worker", f.worker) + scope, err := f.store.AdminScope(r) + if err != nil { + t.Fatal(err) + } + return scope +} + +func requirePublicationForbidden(t *testing.T, err error) { + t.Helper() + var failure *core.Error + if !errors.As(err, &failure) || failure.Code != "forbidden" { + t.Errorf("want forbidden, got %v", err) + } +} + +func TestPublicationRejectsProjectManager(t *testing.T) { + f := newPublicationFixture(t) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + scope := publicationScope(t, f, f.reader) + input := Approved{0, true, testPublicManifest()} + preview := f.service.previewHash(scope, input) + base := f.base() + "/publication" + for _, call := range []struct { + method, path string + body any + }{ + {"GET", base, nil}, + {"POST", base + "/preview", input}, + {"PUT", base, map[string]any{"expected_revision": 0, "enabled": true, "manifest": input.Manifest, "preview_sha256": preview}}, + {"POST", base + "/unpublish", map[string]any{"expected_revision": 1}}, + } { + t.Run(call.method+call.path, func(t *testing.T) { + w := f.call(t, call.method, call.path, f.reader, "manager-publication", call.body) + if w.Code != 403 { + t.Fatalf("manager publication returned %d: %s", w.Code, w.Body.String()) + } + }) + } + // Service callers must receive the same boundary, even with a valid project + // administrative scope constructed outside the HTTP publication handlers. + _, err := f.service.Configuration(t.Context(), scope) + requirePublicationForbidden(t, err) + _, err = f.service.Preview(t.Context(), scope, input) + requirePublicationForbidden(t, err) + _, err = f.service.Apply(t.Context(), scope, "manager-apply", input, preview) + requirePublicationForbidden(t, err) + _, err = f.service.Unpublish(t.Context(), scope, "manager-unpublish", 0) + requirePublicationForbidden(t, err) + var count int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM project_publications`).Scan(&count); err != nil || count != 0 { + t.Fatal("manager changed publication", count, err) + } +} + +func TestPublicationRechecksCurrentAdministratorBeforeReceiptReplay(t *testing.T) { + for _, mode := range []string{"demoted", "revoked"} { + t.Run(mode, func(t *testing.T) { + f := newPublicationFixture(t) + scope := publicationScope(t, f, f.admin) + input := Approved{0, true, testPublicManifest()} + preview, err := f.service.Preview(t.Context(), scope, input) + if err != nil { + t.Fatal(err) + } + applied, err := f.service.Apply(t.Context(), scope, "admin-apply", input, preview.SHA256) + if err != nil { + t.Fatal(err) + } + replay, err := f.service.Apply(t.Context(), scope, "admin-apply", input, preview.SHA256) + if err != nil || !bytes.Equal(applied, replay) { + t.Fatal("admin apply replay", err) + } + unpublished, err := f.service.Unpublish(t.Context(), scope, "admin-unpublish", 1) + if err != nil { + t.Fatal(err) + } + replay, err = f.service.Unpublish(t.Context(), scope, "admin-unpublish", 1) + if err != nil || !bytes.Equal(unpublished, replay) { + t.Fatal("admin unpublish replay", err) + } + // Demotion retains project management, so the ordinary AdminScope contract + // still permits it. Publication must not leak either retained receipt. + digest := sha256.Sum256([]byte(f.admin)) + hash := hex.EncodeToString(digest[:]) + if _, err = f.store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) SELECT id,?,1,1,1 FROM credentials WHERE token_sha256=?`, f.project, hash); err != nil { + t.Fatal(err) + } + query := `UPDATE credentials SET is_admin=0 WHERE token_sha256=?` + if mode == "revoked" { + query = `UPDATE credentials SET revoked=1 WHERE token_sha256=?` + } + if _, err = f.store.DB().Exec(query, hash); err != nil { + t.Fatal(err) + } + check := func(err error) { + t.Helper() + var e *core.Error + want := "forbidden" + if mode == "revoked" { + want = "unauthorized" + } + if !errors.As(err, &e) || e.Code != want { + t.Errorf("want %s, got %v", want, err) + } + } + _, err = f.service.Configuration(t.Context(), scope) + check(err) + _, err = f.service.Preview(t.Context(), scope, Approved{2, true, input.Manifest}) + check(err) + _, err = f.service.Apply(t.Context(), scope, "admin-apply", input, preview.SHA256) + check(err) + _, err = f.service.Unpublish(t.Context(), scope, "admin-unpublish", 1) + check(err) + next := Approved{2, true, input.Manifest} + _, err = f.service.Apply(t.Context(), scope, "new-apply", next, f.service.previewHash(scope, next)) + check(err) + _, err = f.service.Unpublish(t.Context(), scope, "new-unpublish", 2) + check(err) + var enabled bool + var revision int64 + if err = f.store.DB().QueryRow(`SELECT enabled,revision FROM project_publications WHERE project_id=?`, f.project).Scan(&enabled, &revision); err != nil || enabled || revision != 2 { + t.Fatal("stale admin changed publication", enabled, revision, err) + } + }) + } +} diff --git a/internal/publicsite/service.go b/internal/publicsite/service.go index 443ea4adf..c688d0f18 100644 --- a/internal/publicsite/service.go +++ b/internal/publicsite/service.go @@ -229,6 +229,7 @@ func preserveReviewFacts(ctx context.Context, tx *sql.Tx, project string, m Mani } func (s *Service) Configuration(ctx context.Context, scope core.Scope) (Configuration, error) { + scope = scope.RequireInstanceAdministration() out := Configuration{} err := s.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { r, found, err := readRecord(ctx, tx, scope.ProjectID) @@ -246,6 +247,7 @@ func (s *Service) Configuration(ctx context.Context, scope core.Scope) (Configur } func (s *Service) Preview(ctx context.Context, scope core.Scope, input Approved) (Preview, error) { + scope = scope.RequireInstanceAdministration() input, err := approved(input) if err != nil { return Preview{}, err @@ -269,6 +271,7 @@ func (s *Service) Preview(ctx context.Context, scope core.Scope, input Approved) } func (s *Service) Apply(ctx context.Context, scope core.Scope, key string, input Approved, preview string) (json.RawMessage, error) { + scope = scope.RequireInstanceAdministration() input, err := approved(input) if err != nil { return nil, err @@ -334,6 +337,7 @@ func (s *Service) Apply(ctx context.Context, scope core.Scope, key string, input } func (s *Service) Unpublish(ctx context.Context, scope core.Scope, key string, revision int64) (json.RawMessage, error) { + scope = scope.RequireInstanceAdministration() if revision < 0 || revision >= math.MaxInt64 { return nil, invalid() } diff --git a/internal/reviewexec/policy.go b/internal/reviewexec/policy.go index 121dc170a..7bdf8cce1 100644 --- a/internal/reviewexec/policy.go +++ b/internal/reviewexec/policy.go @@ -78,6 +78,7 @@ func clonePolicyConfiguration(value PolicyConfiguration) PolicyConfiguration { // ConfigurePolicy stores one immutable administrator-attributed revision. It // performs no admission, provider observation, execution or policy assessment. func (e *Engine) ConfigurePolicy(ctx context.Context, scope core.Scope, key string, input PolicyConfiguration) (json.RawMessage, error) { + scope = scope.RequireAdministration() // Bound collection copying even for trusted direct callers. if len(input.RequiredChannels) > 2 || len(input.PausedChannels) > 2 { return nil, invalid() @@ -88,14 +89,6 @@ func (e *Engine) ConfigurePolicy(ctx context.Context, scope core.Scope, key stri return nil, invalid() } return e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.policy.configure", Target: "policy", Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { - // A write-capable scope is insufficient even for direct Go callers. - var admin int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM credentials WHERE principal_id=? AND is_admin=1 AND revoked=0`, scope.PrincipalID).Scan(&admin); err != nil { - return nil, err - } - if admin != 1 { - return nil, core.Fail("forbidden", "Administrative permission is required.", 403) - } var revision int64 if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(revision),0) FROM review_policy_config WHERE project_id=?`, scope.ProjectID).Scan(&revision); err != nil { return nil, err diff --git a/internal/reviewexec/project_management_test.go b/internal/reviewexec/project_management_test.go new file mode 100644 index 000000000..fa70e0bbf --- /dev/null +++ b/internal/reviewexec/project_management_test.go @@ -0,0 +1,41 @@ +package reviewexec + +import "testing" + +func TestProjectManagerConfiguresPolicyAndExecutionWithReplayReauthorization(t *testing.T) { + f := newAttemptFixtureWithPolicy(t, false) + if err := EnsurePolicySchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`); err != nil { + t.Fatal(err) + } + scope := f.scope(t, attemptProject, f.writer, false) + revision := int64(0) + initial := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli"}} + _, err := f.e.Configure(t.Context(), scope, "manager-cannot-bind", initial) + attemptCode(t, err, "operator_capability_binding_required") + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "operator-initial-binding", initial); err != nil { + t.Fatal(err) + } + revision = 1 + config := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli"}} + switched := config + switched.CapabilityID = "other-account" + _, err = f.e.Configure(t.Context(), scope, "manager-cannot-switch-account", switched) + attemptCode(t, err, "operator_capability_binding_required") + if _, err = f.e.Configure(t.Context(), scope, "owner-config", config); err != nil { + t.Fatal("manager execution config refused", err) + } + policy := policyInput(0) + if _, err := f.e.ConfigurePolicy(t.Context(), scope, "owner-policy", policy); err != nil { + t.Fatal("manager policy refused", err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`); err != nil { + t.Fatal(err) + } + _, err = f.e.Configure(t.Context(), scope, "owner-config", config) + attemptCode(t, err, "forbidden") + _, err = f.e.ConfigurePolicy(t.Context(), scope, "owner-policy", policy) + attemptCode(t, err, "forbidden") +} diff --git a/internal/reviewexec/requests.go b/internal/reviewexec/requests.go index 158cefa82..14020d509 100644 --- a/internal/reviewexec/requests.go +++ b/internal/reviewexec/requests.go @@ -51,28 +51,15 @@ func (e *Engine) validateConfiguration(c Configuration) error { // Configure retains every configuration revision. An update never silently // rebinds an already queued request to another provider or source policy. func (e *Engine) Configure(ctx context.Context, scope core.Scope, key string, c Configuration) (json.RawMessage, error) { + scope = scope.RequireAdministration() if err := validateConfigurationShape(c); err != nil { return nil, err } return e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.configure", Target: "configuration", Key: key, Request: c}, func(ctx context.Context, tx *sql.Tx) (any, error) { - // Recheck admin at the transaction boundary even for direct Go callers. - var admin int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM credentials WHERE principal_id=? AND is_admin=1 AND revoked=0`, scope.PrincipalID).Scan(&admin); err != nil { - return nil, err - } - if admin != 1 { - return nil, core.Fail("forbidden", "Administrative permission is required.", 403) - } - if err := e.validateConfiguration(c); err != nil { - return nil, err - } var revision int64 if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(revision),0) FROM review_execution_config WHERE project_id=?`, scope.ProjectID).Scan(&revision); err != nil { return nil, err } - if revision != *c.ExpectedRevision { - return nil, conflict() - } var previous Configuration if revision > 0 { var err error @@ -81,6 +68,19 @@ func (e *Engine) Configure(ctx context.Context, scope core.Scope, key string, c return nil, err } } + operator, err := core.IsInstanceAdministrator(ctx, tx, scope.PrincipalID) + if err != nil { + return nil, err + } + if !operator && (revision == 0 || c.CapabilityID != previous.CapabilityID) { + return nil, core.Fail("operator_capability_binding_required", "A service operator must establish or change this project's provider capability; preserve its current capability_id for project management.", 403) + } + if err := e.validateConfiguration(c); err != nil { + return nil, err + } + if revision != *c.ExpectedRevision { + return nil, conflict() + } defaults, err := enrollmentRoundDefaults(ctx, tx, scope.ProjectID) if err != nil { return nil, err diff --git a/internal/server/access.go b/internal/server/access.go index 9e4b5d40c..fed623005 100644 --- a/internal/server/access.go +++ b/internal/server/access.go @@ -7,11 +7,66 @@ import ( "encoding/hex" "errors" "net/http" + "slices" "strings" "github.com/benhook1013/FireController/internal/core" ) +type projectPermissions struct{ read, write, manage int } + +func permissionSet(values []string) (projectPermissions, []string, error) { + var p projectPermissions + invalid := func() (projectPermissions, []string, error) { + return projectPermissions{}, nil, core.Fail("validation_failed", "Permissions must be unique read/write/manage values and include read or manage.", 400) + } + if len(values) > 3 { + return invalid() + } + for _, value := range values { + switch value { + case "read": + if p.read != 0 { + return invalid() + } + p.read = 1 + case "write": + if p.write != 0 { + return invalid() + } + p.write = 1 + case "manage": + if p.manage != 0 { + return invalid() + } + p.manage = 1 + default: + return invalid() + } + } + if p.manage == 1 { + p.read, p.write = 1, 1 + } + if p.read != 1 { + return invalid() + } + return p, p.values(), nil +} + +func (p projectPermissions) values() []string { + values := []string{} + if p.read == 1 { + values = append(values, "read") + } + if p.write == 1 { + values = append(values, "write") + } + if p.manage == 1 { + values = append(values, "manage") + } + return values +} + func (a *api) grant(w http.ResponseWriter, r *http.Request) { scope, err := a.store.AdminScope(r) if err != nil { @@ -31,35 +86,12 @@ func (a *api) grant(w http.ResponseWriter, r *http.Request) { core.WriteError(w, core.Fail("validation_failed", "Provide the lowercase SHA-256 hash of a client credential.", 400)) return } - read, write := 0, 0 - for _, permission := range request.Permissions { - switch permission { - case "read": - if read != 0 { - core.WriteError(w, core.Fail("validation_failed", "Permissions must be unique read/write values.", 400)) - return - } - read = 1 - case "write": - if write != 0 { - core.WriteError(w, core.Fail("validation_failed", "Permissions must be unique read/write values.", 400)) - return - } - write = 1 - default: - core.WriteError(w, core.Fail("validation_failed", "Permissions must be unique read/write values.", 400)) - return - } - } - if read != 1 { - core.WriteError(w, core.Fail("validation_failed", "A project credential requires read permission.", 400)) + permissions, normalized, err := permissionSet(request.Permissions) + if err != nil { + core.WriteError(w, err) return } - // Canonical ordering makes equivalent permission sets the same request. - request.Permissions = []string{"read"} - if write == 1 { - request.Permissions = append(request.Permissions, "write") - } + request.Permissions = normalized k, err := key(r) if err != nil { core.WriteError(w, err) @@ -78,10 +110,10 @@ func (a *api) grant(w http.ResponseWriter, r *http.Request) { if _, err = tx.ExecContext(ctx, "INSERT INTO credentials(id,principal_id,token_sha256,is_admin,revoked) VALUES(?,?,?,0,0)", id, principal, request.TokenSHA256); err != nil { return nil, err } - if _, err = tx.ExecContext(ctx, "INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES(?,?,?,?)", id, scope.ProjectID, read, write); err != nil { + if _, err = tx.ExecContext(ctx, "INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) VALUES(?,?,?,?,?)", id, scope.ProjectID, permissions.read, permissions.write, permissions.manage); err != nil { return nil, err } - if err = core.AppendEvent(ctx, tx, scope, "credentials.granted", id, 1, map[string]string{"id": id, "principal_id": principal}); err != nil { + if err = core.AppendEvent(ctx, tx, scope, "credentials.granted", id, 1, map[string]any{"id": id, "principal_id": principal, "permissions": request.Permissions}); err != nil { return nil, err } return map[string]string{"id": id, "principal_id": principal, "project_id": scope.ProjectID, "outcome": "granted"}, nil @@ -89,6 +121,76 @@ func (a *api) grant(w http.ResponseWriter, r *http.Request) { complete(w, result, err) } +func (a *api) replaceGrant(w http.ResponseWriter, r *http.Request) { + scope, err := a.store.AdminScope(r) + if err != nil { + core.WriteError(w, err) + return + } + if _, err = core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + var wire struct { + ExpectedPermissions *[]string `json:"expected_permissions"` + Permissions *[]string `json:"permissions"` + } + if err = core.ReadJSON(w, r, &wire); err != nil { + core.WriteError(w, err) + return + } + if wire.ExpectedPermissions == nil || wire.Permissions == nil { + core.WriteError(w, core.Fail("validation_failed", "Provide expected_permissions and permissions arrays.", 400)) + return + } + _, expected, err := permissionSet(*wire.ExpectedPermissions) + if err != nil { + core.WriteError(w, err) + return + } + next, permissions, err := permissionSet(*wire.Permissions) + if err != nil { + core.WriteError(w, err) + return + } + k, err := key(r) + if err != nil { + core.WriteError(w, err) + return + } + id := r.PathValue("credential_id") + input := struct { + ExpectedPermissions []string `json:"expected_permissions"` + Permissions []string `json:"permissions"` + }{expected, permissions} + value, err := a.store.Mutate(r.Context(), scope, core.Mutation{Operation: "credentials.permissions.replace", Target: id, Key: k, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { + var previous projectPermissions + err := tx.QueryRowContext(ctx, `SELECT g.can_read,g.can_write,g.can_manage FROM grants g JOIN credentials c ON c.id=g.credential_id WHERE c.id=? AND g.project_id=? AND c.is_admin=0 AND c.revoked=0 AND g.can_read=1`, id, scope.ProjectID).Scan(&previous.read, &previous.write, &previous.manage) + if errors.Is(err, sql.ErrNoRows) { + return nil, core.Fail("not_found", "The active credential grant is unavailable in this project.", 404) + } + if err != nil { + return nil, err + } + current := previous.values() + if !slices.Equal(current, expected) { + return nil, &core.Error{Code: "credential_permissions_changed", Message: "The credential permissions changed; compare the returned current_permissions with the intended change before retrying.", Status: 409, Details: map[string]any{"credential_id": id, "current_permissions": current}} + } + outcome := "unchanged" + if !slices.Equal(current, permissions) { + if _, err = tx.ExecContext(ctx, `UPDATE grants SET can_read=?,can_write=?,can_manage=? WHERE credential_id=? AND project_id=?`, next.read, next.write, next.manage, id, scope.ProjectID); err != nil { + return nil, err + } + if err = core.AppendEvent(ctx, tx, scope, "credentials.permissions_changed", id, 1, map[string]any{"id": id, "previous_permissions": current, "permissions": permissions}); err != nil { + return nil, err + } + outcome = "updated" + } + return map[string]any{"id": id, "project_id": scope.ProjectID, "outcome": outcome, "permissions": permissions}, nil + }) + complete(w, value, err) +} + func (a *api) revoke(w http.ResponseWriter, r *http.Request) { scope, err := a.store.AdminScope(r) if err != nil { @@ -102,16 +204,21 @@ func (a *api) revoke(w http.ResponseWriter, r *http.Request) { } id := r.PathValue("credential_id") result, err := a.store.Mutate(r.Context(), scope, core.Mutation{Operation: "credentials.revoke", Target: id, Key: k, Request: struct{}{}}, func(ctx context.Context, tx *sql.Tx) (any, error) { - var revoked int - err := tx.QueryRowContext(ctx, "SELECT c.revoked FROM credentials c JOIN grants g ON g.credential_id=c.id WHERE c.id=? AND g.project_id=? AND c.is_admin=0", id, scope.ProjectID).Scan(&revoked) + var revoked, read, write, manage int + err := tx.QueryRowContext(ctx, "SELECT c.revoked,g.can_read,g.can_write,g.can_manage FROM credentials c JOIN grants g ON g.credential_id=c.id WHERE c.id=? AND g.project_id=? AND c.is_admin=0", id, scope.ProjectID).Scan(&revoked, &read, &write, &manage) if errors.Is(err, sql.ErrNoRows) { return nil, core.Fail("not_found", "The credential is unavailable in this project.", 404) } if err != nil { return nil, err } - if revoked == 0 { - if _, err = tx.ExecContext(ctx, "UPDATE credentials SET revoked=1 WHERE id=?", id); err != nil { + if revoked == 0 && (read != 0 || write != 0 || manage != 0) { + // This URL revokes only its project's authority. A credential may + // retain a grant elsewhere; never revoke another project's access. + if _, err = tx.ExecContext(ctx, "UPDATE grants SET can_read=0,can_write=0,can_manage=0 WHERE credential_id=? AND project_id=?", id, scope.ProjectID); err != nil { + return nil, err + } + if _, err = tx.ExecContext(ctx, "UPDATE credentials SET revoked=1 WHERE id=? AND NOT EXISTS(SELECT 1 FROM grants WHERE credential_id=? AND (can_read=1 OR can_write=1 OR can_manage=1))", id, id); err != nil { return nil, err } if err = core.AppendEvent(ctx, tx, scope, "credentials.revoked", id, 1, map[string]string{"id": id}); err != nil { diff --git a/internal/server/project_management_test.go b/internal/server/project_management_test.go new file mode 100644 index 000000000..b850c4f75 --- /dev/null +++ b/internal/server/project_management_test.go @@ -0,0 +1,194 @@ +package server_test + +import ( + "crypto/sha256" + "encoding/hex" + "net/http" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func projectManagerGrant(t *testing.T, f *fixture, project, token string) string { + t.Helper() + sum := sha256.Sum256([]byte(token)) + v := require(t, request(f.handler, "POST", "/api/v1/projects/"+project+"/credentials", f.admin, core.NewID("key"), "", `{"token_sha256":"`+hex.EncodeToString(sum[:])+`","permissions":["manage"]}`), http.StatusOK) + return v["id"].(string) +} + +func TestProjectManagerDelegatesOnlyItsProjectAndCannotCreateInstanceAuthority(t *testing.T) { + f := setup(t) + one, two := f.project(t, "owner/one"), f.project(t, "owner/two") + manager := "synthetic-project-manager-token" + id := projectManagerGrant(t, f, one, manager) + var read, write, manage, admin int + if err := f.store.DB().QueryRow(`SELECT g.can_read,g.can_write,g.can_manage,c.is_admin FROM grants g JOIN credentials c ON c.id=g.credential_id WHERE g.credential_id=? AND g.project_id=?`, id, one).Scan(&read, &write, &manage, &admin); err != nil || read != 1 || write != 1 || manage != 1 || admin != 0 { + t.Fatal("management did not imply project read/write only", err) + } + sum := sha256.Sum256([]byte("synthetic-delegated-manager")) + body := `{"token_sha256":"` + hex.EncodeToString(sum[:]) + `","permissions":["read","write","manage"]}` + v := require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", manager, "delegate-same-project", "", body), 200) + child := v["id"].(string) + if err := f.store.DB().QueryRow(`SELECT is_admin FROM credentials WHERE id=?`, child).Scan(&admin); err != nil || admin != 0 { + t.Fatal("delegation created global administration", err) + } + require(t, request(f.handler, "POST", "/api/v1/projects/"+two+"/credentials", manager, "not-other-project", "", body), 403) + require(t, request(f.handler, "POST", "/api/v1/projects", manager, "not-global-create", "", `{"name":"Other","repository":"owner/three"}`), 403) + require(t, request(f.handler, "GET", "/api/v1/projects", manager, "", "", ""), 403) + writer := "synthetic-ordinary-project-writer" + f.grant(t, one, writer, true) + require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", writer, "writer-cannot-delegate", "", body), 403) + // Same-key replay must be reauthorized after management is withdrawn. + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=?`, id); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", manager, "delegate-same-project", "", body), 403) +} + +func TestProjectManagerRevocationPreservesAnotherProjectsSharedGrant(t *testing.T) { + f := setup(t) + one, two := f.project(t, "owner/one"), f.project(t, "owner/two") + manager := "synthetic-project-manager-token" + projectManagerGrant(t, f, one, manager) + shared := "synthetic-shared-project-token" + id := f.grant(t, one, shared, true) + if _, err := f.store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES(?,?,1,1)`, id, two); err != nil { + t.Fatal(err) + } + before := count(t, f.store, "events") + path := "/api/v1/projects/" + one + "/credentials/" + id + require(t, request(f.handler, "DELETE", path, manager, "revoke-own-project", "", ""), 200) + require(t, request(f.handler, "GET", "/api/v1/projects/"+one, shared, "", "", ""), 403) + require(t, request(f.handler, "GET", "/api/v1/projects/"+two, shared, "", "", ""), 200) + var revoked int + if err := f.store.DB().QueryRow(`SELECT revoked FROM credentials WHERE id=?`, id).Scan(&revoked); err != nil || revoked != 0 { + t.Fatal("revocation affected other project", err) + } + if count(t, f.store, "events") != before+1 { + t.Fatal("revocation audit missing") + } + require(t, request(f.handler, "DELETE", path, manager, "another-key-same-revocation", "", ""), 200) + if count(t, f.store, "events") != before+1 { + t.Fatal("already withdrawn grant produced another event") + } + foreign := "synthetic-foreign-project-token" + foreignID := f.grant(t, two, foreign, true) + require(t, request(f.handler, "DELETE", "/api/v1/projects/"+one+"/credentials/"+foreignID, manager, "not-foreign-credential", "", ""), 404) + require(t, request(f.handler, "GET", "/api/v1/projects/"+two, foreign, "", "", ""), 200) +} + +func TestProjectManagerBrowserAppearanceCeilingAndDowngrade(t *testing.T) { + f := browserActionsFixture(t) + p := f.project(t, "owner/one") + worker := f.worker(t, p, "Owner") + manager := "synthetic-project-manager-token" + credential := projectManagerGrant(t, f, p, manager) + session := strings.Repeat("e", 32) + cookie := browserActionsLogin(t, f, p, manager, session, true) + body := `{"expected_revision":0,"presentation":{"name":"Owned project"}}` + r := browserActionRequest(f, "PUT", "/api/v1/projects/"+p+"/presentation", session, cookie, worker, "owner-appearance", body) + require(t, serveBrowserAction(f, r), 200) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=?`, credential); err != nil { + t.Fatal(err) + } + r = browserActionRequest(f, "PUT", "/api/v1/projects/"+p+"/presentation", session, cookie, worker, "owner-appearance", body) + require(t, serveBrowserAction(f, r), 403) + // An original writer cookie must not acquire appearance authority later. + id := strings.Repeat("f", 32) + plain := browserActionsLogin(t, f, p, manager, id, false) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id=?`, credential); err != nil { + t.Fatal(err) + } + r = browserActionRequest(f, "PUT", "/api/v1/projects/"+p+"/presentation", id, plain, worker, "no-cookie-elevation", body) + require(t, serveBrowserAction(f, r), 403) +} + +func TestProjectManagerChangesExistingGrantWithExactPermissionCAS(t *testing.T) { + f := setup(t) + one, two := f.project(t, "owner/one"), f.project(t, "owner/two") + manager := "synthetic-project-manager-token" + projectManagerGrant(t, f, one, manager) + token := "synthetic-retained-worker-token" + id := f.grant(t, one, token, true) + var principal, hash string + if err := f.store.DB().QueryRow(`SELECT principal_id,token_sha256 FROM credentials WHERE id=?`, id).Scan(&principal, &hash); err != nil { + t.Fatal(err) + } + path := "/api/v1/projects/" + one + "/credentials/" + id + body := `{"expected_permissions":["write","read"],"permissions":["manage"]}` + before := count(t, f.store, "events") + v := require(t, request(f.handler, "PUT", path, manager, "retain-identity-promote", "", body), 200) + if v["outcome"] != "updated" { + t.Fatal("grant was not updated") + } + var afterPrincipal, afterHash string + var admin int + if err := f.store.DB().QueryRow(`SELECT principal_id,token_sha256,is_admin FROM credentials WHERE id=?`, id).Scan(&afterPrincipal, &afterHash, &admin); err != nil || principal != afterPrincipal || hash != afterHash || admin != 0 { + t.Fatal("role edit replaced or globally elevated identity", err) + } + if count(t, f.store, "events") != before+1 { + t.Fatal("management edit was not audited") + } + // The retained credential now administers this project's grants itself. + sum := sha256.Sum256([]byte("synthetic-delegation-after-promotion")) + require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", token, "promoted-client-own-project", "", `{"token_sha256":"`+hex.EncodeToString(sum[:])+`","permissions":["read"]}`), 200) + require(t, request(f.handler, "GET", "/api/v1/projects", token, "", "", ""), 403) + require(t, request(f.handler, "PUT", path, manager, "stale-permission-guard", "", body), 409) + stale := request(f.handler, "PUT", path, manager, "another-stale-permission-guard", "", body) + if !strings.Contains(stale.Body.String(), "current_permissions") || strings.Contains(stale.Body.String(), hash) { + t.Fatal("stale conflict omitted safe permission detail or leaked credential hash") + } + // Equivalent normalized requests replay without changing the grant or its audit. + require(t, request(f.handler, "PUT", path, manager, "retain-identity-promote", "", `{"expected_permissions":["read","write"],"permissions":["read","write","manage"]}`), 200) + audits := count(t, f.store, "events") + unchanged := require(t, request(f.handler, "PUT", path, manager, "already-same-role", "", `{"expected_permissions":["manage"],"permissions":["read","write","manage"]}`), 200) + if unchanged["outcome"] != "unchanged" || count(t, f.store, "events") != audits { + t.Fatal("equivalent permission set manufactured a change") + } + require(t, request(f.handler, "PUT", path, manager, "retain-identity-promote", "", `{"expected_permissions":["manage"],"permissions":["read"]}`), 409) + require(t, request(f.handler, "PUT", "/api/v1/projects/"+two+"/credentials/"+id, manager, "not-other-project-grant", "", body), 403) + foreign := f.grant(t, two, "synthetic-unrelated-credential", true) + w := request(f.handler, "PUT", "/api/v1/projects/"+one+"/credentials/"+foreign, manager, "not-foreign-target", "", body) + require(t, w, 404) + if strings.Contains(w.Body.String(), "current_permissions") { + t.Fatal("foreign target leaked permissions") + } + var globalID string + if err := f.store.DB().QueryRow(`SELECT id FROM credentials WHERE is_admin=1`).Scan(&globalID); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES(?,?,1,1)`, globalID, one); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", "/api/v1/projects/"+one+"/credentials/"+globalID, manager, "not-global-administrator-target", "", body), 404) + for i, bad := range []string{`{}`, `{"expected_permissions":null,"permissions":["manage"]}`, `{"expected_permissions":["read","read"],"permissions":["manage"]}`, `{"expected_permissions":["read"],"permissions":["admin"]}`, `{"expected_permissions":["read"],"permissions":[]}`, `{"expected_permissions":["read"],"permissions":["write"]}`} { + require(t, request(f.handler, "PUT", path, manager, "bad-role-"+string(rune('a'+i)), "", bad), 400) + } +} + +func TestProjectManagerPermissionEditRollbackAndReplayAuthorization(t *testing.T) { + f := setup(t) + p := f.project(t, "owner/one") + manager := "synthetic-project-manager-token" + ownerID := projectManagerGrant(t, f, p, manager) + id := f.grant(t, p, "synthetic-managed-credential", false) + path := "/api/v1/projects/" + p + "/credentials/" + id + body := `{"expected_permissions":["read"],"permissions":["manage"]}` + if _, err := f.store.DB().Exec(`CREATE TRIGGER fail_management_event BEFORE INSERT ON events WHEN NEW.event_type='credentials.permissions_changed' BEGIN SELECT RAISE(ABORT,'synthetic event failure'); END`); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", path, manager, "retry-role-after-rollback", "", body), 500) + var write, manage int + if err := f.store.DB().QueryRow(`SELECT can_write,can_manage FROM grants WHERE credential_id=?`, id).Scan(&write, &manage); err != nil || write != 0 || manage != 0 { + t.Fatal("failed audit left authority changed", err) + } + if _, err := f.store.DB().Exec(`DROP TRIGGER fail_management_event`); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", path, manager, "retry-role-after-rollback", "", body), 200) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=?`, ownerID); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", path, manager, "retry-role-after-rollback", "", body), 403) +} diff --git a/internal/server/server.go b/internal/server/server.go index 2196011cc..ab7c4eaca 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -70,6 +70,9 @@ func New(store *core.Store, options ...Option) *http.ServeMux { mux.HandleFunc("GET /api/v1/projects/{project_id}/message-events", a.messageEvents) mux.HandleFunc("POST /api/v1/projects/{project_id}/credentials", a.grant) mux.HandleFunc("DELETE /api/v1/projects/{project_id}/credentials/{credential_id}", a.revoke) + mux.HandleFunc("PUT /api/v1/projects/{project_id}/credentials/{credential_id}", a.replaceGrant) + mux.HandleFunc("GET /api/v1/projects/{project_id}/workers/{worker_id}/retirement", a.workerRetirement) + mux.HandleFunc("POST /api/v1/projects/{project_id}/workers/{worker_id}/retire", a.retireWorker) if a.browser != nil { mux.Handle("/", a.browser) } else { @@ -111,6 +114,7 @@ type projectValue struct { Repository string `json:"repository"` } type workerValue struct { + Retired bool `json:"retired,omitempty"` ID string `json:"id"` ProjectID string `json:"project_id"` Name string `json:"name"` @@ -299,7 +303,11 @@ func (a *api) listWorkers(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } - query, err := listQuery(r) + if len(r.URL.RawQuery) > 16<<10 { + core.WriteError(w, core.Fail("validation_failed", "Use only one limit, one cursor and one include_retired query parameter.", 400)) + return + } + query, err := core.QueryKeys(r, "validation_failed", "limit", "cursor", "include_retired") if err != nil { core.WriteError(w, err) return @@ -309,13 +317,21 @@ func (a *api) listWorkers(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } + includeRetired := query.Get("include_retired") == "true" + if _, exists := query["include_retired"]; exists && !includeRetired { + core.WriteError(w, core.Fail("validation_failed", "Use include_retired=true to include archived workers.", 400)) + return + } filter := "workers" + if includeRetired { + filter += ":include_retired" + } after, err := a.store.ParseCursor(scope, filter, query.Get("cursor")) if err != nil { core.WriteError(w, err) return } - rows, err := a.store.DB().QueryContext(r.Context(), "SELECT id,project_id,name FROM workers WHERE project_id=? AND id>? ORDER BY id LIMIT ?", scope.ProjectID, after, limit+1) + rows, err := a.store.DB().QueryContext(r.Context(), "SELECT id,project_id,name,EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id) FROM workers w WHERE project_id=? AND id>? AND (? OR NOT EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id)) ORDER BY id LIMIT ?", scope.ProjectID, after, includeRetired, limit+1) if err != nil { core.WriteError(w, err) return @@ -324,7 +340,7 @@ func (a *api) listWorkers(w http.ResponseWriter, r *http.Request) { values := make([]workerValue, 0, limit+1) for rows.Next() { var value workerValue - if err = rows.Scan(&value.ID, &value.ProjectID, &value.Name); err != nil { + if err = rows.Scan(&value.ID, &value.ProjectID, &value.Name, &value.Retired); err != nil { core.WriteError(w, err) return } @@ -354,7 +370,7 @@ func (a *api) worker(w http.ResponseWriter, r *http.Request) { return } var value workerValue - err = a.store.DB().QueryRowContext(r.Context(), "SELECT id,project_id,name FROM workers WHERE project_id=? AND id=?", scope.ProjectID, r.PathValue("worker_id")).Scan(&value.ID, &value.ProjectID, &value.Name) + err = a.store.DB().QueryRowContext(r.Context(), "SELECT id,project_id,name,EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id) FROM workers w WHERE project_id=? AND id=?", scope.ProjectID, r.PathValue("worker_id")).Scan(&value.ID, &value.ProjectID, &value.Name, &value.Retired) if errors.Is(err, sql.ErrNoRows) { err = core.Fail("not_found", "The worker is unavailable in this project.", 404) } diff --git a/internal/server/worker_retirement.go b/internal/server/worker_retirement.go new file mode 100644 index 000000000..2e504b338 --- /dev/null +++ b/internal/server/worker_retirement.go @@ -0,0 +1,128 @@ +package server + +import ( + "context" + "database/sql" + "net/http" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +type workerRetirementItems struct { + Count int64 `json:"count"` + IDs []string `json:"ids"` +} +type workerRetirementBlockers struct { + Jobs workerRetirementItems `json:"jobs"` + Notes workerRetirementItems `json:"notes"` + Messages workerRetirementItems `json:"messages"` +} +type workerRetirementStatus struct { + WorkerID string `json:"worker_id"` + Retired bool `json:"retired"` + CanRetire bool `json:"can_retire"` + Blockers workerRetirementBlockers `json:"blockers"` +} + +func retirementItems(ctx context.Context, tx *sql.Tx, query string, args ...any) (workerRetirementItems, error) { + items := workerRetirementItems{IDs: []string{}} + rows, err := tx.QueryContext(ctx, query+` ORDER BY id LIMIT 20`, args...) + if err != nil { + return items, err + } + defer rows.Close() + for rows.Next() { + var id string + if err := rows.Scan(&id, &items.Count); err != nil { + return items, err + } + items.IDs = append(items.IDs, id) + } + return items, rows.Err() +} + +func readWorkerRetirement(ctx context.Context, tx *sql.Tx, project, worker string) (workerRetirementStatus, error) { + status := workerRetirementStatus{WorkerID: worker} + if err := core.CheckWorker(ctx, tx, project, worker); err != nil { + return status, err + } + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM worker_retirements WHERE project_id=? AND worker_id=?)`, project, worker).Scan(&status.Retired); err != nil { + return status, err + } + var err error + status.Blockers.Jobs, err = retirementItems(ctx, tx, `SELECT id,count(*) OVER() FROM jobs WHERE project_id=? AND worker_id=? AND status<>'completed'`, project, worker) + if err != nil { + return status, err + } + status.Blockers.Notes, err = retirementItems(ctx, tx, `SELECT n.id,count(*) OVER() FROM notes n WHERE n.project_id=? AND n.status='pending' AND (n.worker_id=? OR EXISTS(SELECT 1 FROM jobs j WHERE j.project_id=n.project_id AND j.id=n.job_id AND j.worker_id=?))`, project, worker, worker) + if err != nil { + return status, err + } + status.Blockers.Messages, err = retirementItems(ctx, tx, `SELECT m.id,count(*) OVER() FROM inbox_messages m LEFT JOIN inbox_recipient_state r ON r.project_id=m.project_id AND r.message_id=m.id AND r.worker_id=m.recipient_worker_id WHERE m.project_id=? AND m.recipient_worker_id=? AND COALESCE(r.acknowledged,0)=0`, project, worker) + status.CanRetire = !status.Retired && status.Blockers.Jobs.Count == 0 && status.Blockers.Notes.Count == 0 && status.Blockers.Messages.Count == 0 + return status, err +} + +func (a *api) workerRetirement(w http.ResponseWriter, r *http.Request) { + scope, err := a.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 + } + var status workerRetirementStatus + err = a.store.Read(r.Context(), scope, func(ctx context.Context, tx *sql.Tx) error { + var err error + status, err = readWorkerRetirement(ctx, tx, scope.ProjectID, r.PathValue("worker_id")) + return err + }) + complete(w, status, err) +} + +func (a *api) retireWorker(w http.ResponseWriter, r *http.Request) { + scope, err := a.store.Scope(r, "write") + if err != nil { + core.WriteError(w, err) + return + } + if _, err := core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + var request struct{} + if err := core.ReadJSON(w, r, &request); err != nil { + core.WriteError(w, err) + return + } + k, err := key(r) + if err != nil { + core.WriteError(w, err) + return + } + id := r.PathValue("worker_id") + result, err := a.store.Mutate(r.Context(), scope, core.Mutation{Operation: "workers.retire", Target: id, Key: k, Request: request}, func(ctx context.Context, tx *sql.Tx) (any, error) { + status, err := readWorkerRetirement(ctx, tx, scope.ProjectID, id) + if err != nil { + return nil, err + } + outcome := "unchanged" + if !status.Retired { + if !status.CanRetire { + return nil, &core.Error{Code: "worker_retirement_blocked", Message: "Finish, reassign or consume the listed jobs and notes, and explicitly acknowledge incoming messages before retiring this worker.", Status: 409, Details: status.Blockers} + } + if _, err := tx.ExecContext(ctx, `INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES(?,?,?,?)`, scope.ProjectID, id, time.Now().UTC().Format(time.RFC3339Nano), scope.PrincipalID); err != nil { + return nil, err + } + if err := core.AppendEvent(ctx, tx, scope, "workers.retired", id, 2, map[string]string{"worker_id": id}); err != nil { + return nil, err + } + outcome = "retired" + } + return map[string]any{"id": id, "revision": 2, "outcome": outcome}, nil + }) + complete(w, result, err) +} diff --git a/internal/server/worker_retirement_peer_test.go b/internal/server/worker_retirement_peer_test.go new file mode 100644 index 000000000..20f57c0d9 --- /dev/null +++ b/internal/server/worker_retirement_peer_test.go @@ -0,0 +1,86 @@ +package server_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" +) + +func TestWorkerRetirementPeerAckFeedKeepsOriginalWireAndAudit(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + live := httptest.NewServer(f.handler) + defer live.Close() + credential := filepath.Join(t.TempDir(), "credential") + if err := os.WriteFile(credential, []byte(f.admin), 0600); err != nil { + t.Fatal(err) + } + recipient, err := client.New(t.Context(), profile.Binding{Context: profile.Context{Profile: "fixture", ServerURL: live.URL, InstanceID: f.store.InstanceID(), ProjectID: project, WorkerID: target}, CredentialFile: credential}) + if err != nil { + t.Fatal(err) + } + defer recipient.Close() + snapshot, err := recipient.InboxSnapshot(t.Context(), client.PageOptions{}, client.InboxFilter{}) + if err != nil { + t.Fatal(err) + } + message := retirementJSON(t, f, "POST", base+"/messages", f.admin, actor, map[string]any{"recipient_worker_id": target, "body": "Synthetic coordination"}, 201)["id"].(string) + retirementJSON(t, f, "POST", base+"/messages/"+message+"/ack", f.admin, actor, map[string]any{"worker_id": target}, 200) + events, err := recipient.MessageEvents(t.Context(), snapshot.EventCursor, 100, 0) + if err != nil { + t.Fatal("actual typed feed rejected on-behalf ACK", err) + } + if len(events.Items) != 2 || events.Items[1].Type != "message.acknowledged" || events.Items[1].Payload.RecipientWorkerID != target || events.Items[1].Payload.ConversationID == "" { + t.Fatal("feed facts changed", events) + } + raw, err := json.Marshal(events) + if err != nil || strings.Contains(string(raw), "actor_worker_id") { + t.Fatal("public feed changed", err) + } + var stored string + if err = f.store.DB().QueryRow(`SELECT payload_json FROM events WHERE project_id=? AND event_type='message.acknowledged' AND resource_id=?`, project, message).Scan(&stored); err != nil || !strings.Contains(stored, `"actor_worker_id":"`+actor+`"`) { + t.Fatal("durable actor attribution was lost", err) + } +} + +func TestWorkerRetirementPeerBrowserOriginalManagementCeiling(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + token := "synthetic-promoted-writer-token-1234567" + f.grant(t, project, token, true) + oldID := strings.Repeat("a", 32) + oldCookie := browserActionsLogin(t, f, project, token, oldID, false) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE project_id=?`, project); err != nil { + t.Fatal(err) + } + managerID := strings.Repeat("b", 32) + managerCookie := browserActionsLogin(t, f, project, token, managerID, true) + message := retirementJSON(t, f, "POST", base+"/messages", f.admin, actor, map[string]any{"recipient_worker_id": target, "body": "Synthetic pending message"}, 201)["id"].(string) + path := base + "/messages/" + message + "/ack" + body := `{"worker_id":"` + target + `"}` + before := count(t, f.store, "receipts") + require(t, serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, oldID, oldCookie, actor, "original-key", body)), 403) + if count(t, f.store, "receipts") != before { + t.Fatal("old writer cookie performed management work") + } + first := serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, managerID, managerCookie, actor, "original-key", body)) + require(t, first, 200) + require(t, serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, oldID, oldCookie, actor, "original-key", body)), 403) + replay := serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, managerID, managerCookie, actor, "original-key", body)) + require(t, replay, 200) + if replay.Body.String() != first.Body.String() { + t.Fatal("original manager replay changed") + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE project_id=?`, project); err != nil { + t.Fatal(err) + } + require(t, serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, managerID, managerCookie, actor, "original-key", body)), 403) + require(t, request(f.handler, http.MethodPost, path, f.admin, "bearer-admin", actor, body), 200) +} diff --git a/internal/server/worker_retirement_test.go b/internal/server/worker_retirement_test.go new file mode 100644 index 000000000..94ee1bdd6 --- /dev/null +++ b/internal/server/worker_retirement_test.go @@ -0,0 +1,266 @@ +package server_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/inbox" + "github.com/benhook1013/FireController/internal/jobs" +) + +type retirementPreview struct { + WorkerID string `json:"worker_id"` + Retired bool `json:"retired"` + CanRetire bool `json:"can_retire"` + Blockers struct { + Jobs, Notes, Messages struct { + Count int `json:"count"` + IDs []string `json:"ids"` + } + } `json:"blockers"` +} + +func retirementFixture(t *testing.T) (*fixture, string, string, string) { + t.Helper() + f := setup(t) + for _, ensure := range []func(context.Context, *core.Store) error{jobs.EnsureSchema, inbox.EnsureSchema} { + if err := ensure(t.Context(), f.store); err != nil { + t.Fatal(err) + } + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + jobs.Register(mux, f.store) + inbox.Register(mux, f.store) + f.handler = mux + project := f.project(t, "owner/one") + return f, project, f.worker(t, project, "Actor"), f.worker(t, project, "Retiring") +} + +func retirementJSON(t *testing.T, f *fixture, method, path, token, actor string, body any, status int) map[string]any { + t.Helper() + text := "" + if body != nil { + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + text = string(data) + } + return require(t, request(f.handler, method, path, token, core.NewID("test"), actor, text), status) +} + +func retirementStatus(t *testing.T, f *fixture, path, token string) retirementPreview { + t.Helper() + w := request(f.handler, "GET", path, token, "", "", "") + require(t, w, 200) + var result retirementPreview + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + return result +} + +func TestWorkerRetirementBlockersCleanupHistoryAndActiveTargets(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + path := base + "/workers/" + target + writer, manager := "retirement-writer", "retirement-manager" + f.grant(t, project, writer, true) + projectManagerGrant(t, f, project, manager) + replacement := f.worker(t, project, "Replacement") + job := retirementJSON(t, f, "POST", base+"/jobs", writer, actor, map[string]any{"title": "Unfinished", "worker_id": target}, 201)["id"].(string) + completed := retirementJSON(t, f, "POST", base+"/jobs", writer, actor, map[string]any{"title": "Historical", "worker_id": target, "status": "completed"}, 201)["id"].(string) + createNote := func(worker, job string) string { + return retirementJSON(t, f, "POST", base+"/notes", writer, actor, map[string]any{"worker_id": worker, "job_id": job, "phase": "", "kind": "reminder", "body": "Retained reminder"}, 201)["id"].(string) + } + direct, assigned, historical := createNote(target, ""), createNote("", job), createNote("", completed) + message := retirementJSON(t, f, "POST", base+"/messages", writer, actor, map[string]any{"recipient_worker_id": target, "body": "Retained incoming message"}, 201)["id"].(string) + preview := retirementStatus(t, f, path+"/retirement", writer) + if preview.CanRetire || preview.Retired || preview.WorkerID != target || preview.Blockers.Jobs.Count != 1 || preview.Blockers.Notes.Count != 3 || preview.Blockers.Messages.Count != 1 || preview.Blockers.Jobs.IDs[0] != job || preview.Blockers.Messages.IDs[0] != message { + t.Fatal("unfinished applicable work was omitted", preview, assigned) + } + before := count(t, f.store, "events") + blocked := require(t, request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`), 409) + if blocked["error"].(map[string]any)["code"] != "worker_retirement_blocked" || count(t, f.store, "events") != before || count(t, f.store, "worker_retirements") != 0 { + t.Fatal("blocked retirement changed state", blocked) + } + retirementJSON(t, f, "PATCH", base+"/jobs/"+job, writer, actor, map[string]any{"expected_revision": 1, "worker_id": replacement}, 200) + preview = retirementStatus(t, f, path+"/retirement", writer) + if preview.Blockers.Jobs.Count != 0 || preview.Blockers.Notes.Count != 2 { + t.Fatal("job reassignment did not move its pending note applicability", preview) + } + for _, id := range []string{direct, historical} { + retirementJSON(t, f, "PATCH", base+"/notes/"+id, writer, actor, map[string]any{"expected_revision": 1, "status": "consumed"}, 200) + } + ack := base + "/messages/" + message + "/ack" + body := `{"worker_id":"` + target + `"}` + require(t, request(f.handler, "POST", ack, writer, "not-manager", actor, body), 403) + require(t, request(f.handler, "POST", ack, manager, "manager-ack", actor, body), 200) + var principal, payload string + if err := f.store.DB().QueryRow(`SELECT actor_id,payload_json FROM events WHERE project_id=? AND event_type='message.acknowledged' AND resource_id=?`, project, message).Scan(&principal, &payload); err != nil || principal == "" || !strings.Contains(payload, target) || !strings.Contains(payload, `"actor_worker_id":"`+actor+`"`) { + t.Fatal("on-behalf acknowledgement lost actual actor or recipient", principal, payload, err) + } + preview = retirementStatus(t, f, path+"/retirement", writer) + if !preview.CanRetire || preview.Blockers.Messages.Count != 0 || preview.Blockers.Notes.Count != 0 { + t.Fatal("explicit cleanup did not permit retirement", preview) + } + if _, err := f.store.DB().Exec(`CREATE TRIGGER refuse_retirement_event BEFORE INSERT ON events WHEN NEW.event_type='workers.retired' BEGIN SELECT RAISE(ABORT,'synthetic retirement event failure'); END`); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`), 500) + if count(t, f.store, "worker_retirements") != 0 { + t.Fatal("failed retirement event left a retired identity") + } + if _, err := f.store.DB().Exec(`DROP TRIGGER refuse_retirement_event`); err != nil { + t.Fatal(err) + } + retired := request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`) + result := require(t, retired, 200) + if result["id"] != target || result["revision"] != float64(2) || result["outcome"] != "retired" { + t.Fatal(result) + } + before = count(t, f.store, "events") + replay := request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`) + if replay.Code != 200 || !bytes.Equal(retired.Body.Bytes(), replay.Body.Bytes()) || count(t, f.store, "events") != before { + t.Fatal("retirement replay changed original receipt or history", replay.Body.String()) + } + unchanged := require(t, request(f.handler, "POST", path+"/retire", writer, "already-retired", actor, `{}`), 200) + if unchanged["outcome"] != "unchanged" || count(t, f.store, "events") != before { + t.Fatal("repeat retirement created another transition", unchanged) + } + preview = retirementStatus(t, f, path+"/retirement", writer) + if !preview.Retired || preview.CanRetire { + t.Fatal(preview) + } + active := request(f.handler, "GET", base+"/workers", writer, "", "", "") + require(t, active, 200) + if strings.Contains(active.Body.String(), target) || strings.Contains(active.Body.String(), `"retired":false`) { + t.Fatal("retired worker remained an ordinary target", active.Body.String()) + } + archive := request(f.handler, "GET", base+"/workers?include_retired=true", writer, "", "", "") + require(t, archive, 200) + if !strings.Contains(archive.Body.String(), target) || !strings.Contains(archive.Body.String(), `"retired":true`) { + t.Fatal("archived worker disappeared", archive.Body.String()) + } + if direct := require(t, request(f.handler, "GET", path, writer, "", target, ""), 200); direct["retired"] != true { + t.Fatal("historical worker attribution/authentication was revoked", direct) + } + // Historical corrections stay available, while reopening/attaching new + // unfinished work and sending to or from the retired identity are refused. + retirementJSON(t, f, "PATCH", base+"/jobs/"+completed, writer, actor, map[string]any{"expected_revision": 1, "brief": "Historical correction"}, 200) + for _, call := range []struct{ method, route, acting, body string }{ + {"POST", base + "/jobs", actor, `{"title":"New","worker_id":"` + target + `"}`}, + {"PATCH", base + "/jobs/" + completed, actor, `{"expected_revision":2,"status":"active"}`}, + {"PATCH", base + "/notes/" + direct, actor, `{"expected_revision":2,"status":"pending"}`}, + {"POST", base + "/notes", actor, `{"worker_id":"` + target + `","job_id":"","phase":"","kind":"reminder","body":"New"}`}, + {"POST", base + "/notes", actor, `{"worker_id":"","job_id":"` + completed + `","phase":"","kind":"reminder","body":"New"}`}, + {"POST", base + "/messages", actor, `{"recipient_worker_id":"` + target + `","body":"New"}`}, + {"POST", base + "/messages", target, `{"recipient_worker_id":"` + actor + `","body":"New"}`}, + } { + value := require(t, request(f.handler, call.method, call.route, writer, core.NewID("refused"), call.acting, call.body), 409) + if value["error"].(map[string]any)["code"] != "worker_retired" { + t.Fatal("new retired target was not refused", value) + } + } + retirementJSON(t, f, "PATCH", base+"/notes/"+direct, writer, actor, map[string]any{"expected_revision": 2, "body": "Historical note correction"}, 200) + retirementJSON(t, f, "GET", base+"/jobs/"+completed+"/history", writer, target, nil, 200) + var columns int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM pragma_table_info('workers')`).Scan(&columns); err != nil || columns != 3 { + t.Fatal("retirement rewrote base worker history schema", columns, err) + } +} + +func TestWorkerRetirementAdmissionRaceAndBoundedBlockers(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + path := base + "/workers/" + target + start := make(chan struct{}) + retire, assign := make(chan *httptest.ResponseRecorder, 1), make(chan *httptest.ResponseRecorder, 1) + go func() { + <-start + retire <- request(f.handler, "POST", path+"/retire", f.admin, "race-retire", actor, `{}`) + }() + go func() { + <-start + assign <- request(f.handler, "POST", base+"/jobs", f.admin, "race-job", actor, `{"title":"Racing assignment","worker_id":"`+target+`"}`) + }() + close(start) + r, a := <-retire, <-assign + if !(r.Code == 200 && a.Code == 409 || r.Code == 409 && a.Code == 201) { + t.Fatal("retirement and new assignment both succeeded or lost state", r.Code, r.Body.String(), a.Code, a.Body.String()) + } + bounded := f.worker(t, project, "Many notes") + for i := range 21 { + retirementJSON(t, f, "POST", base+"/notes", f.admin, actor, map[string]any{"worker_id": bounded, "job_id": "", "phase": "", "kind": "reminder", "body": fmt.Sprintf("Pending %d", i)}, 201) + } + preview := retirementStatus(t, f, base+"/workers/"+bounded+"/retirement", f.admin) + if preview.Blockers.Notes.Count != 21 || len(preview.Blockers.Notes.IDs) != 20 || preview.CanRetire { + t.Fatal("blocker response truncated its actual count or exceeded ID bound", preview) + } +} + +func TestWorkerRetirementManagementAckReplayReauthorizesAndIsolates(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + writer, manager := "ack-writer", "ack-manager" + f.grant(t, project, writer, true) + id := projectManagerGrant(t, f, project, manager) + message := retirementJSON(t, f, "POST", base+"/messages", writer, actor, map[string]any{"recipient_worker_id": target, "body": "Incoming"}, 201)["id"].(string) + path := base + "/messages/" + message + "/ack" + body := `{"worker_id":"` + target + `"}` + for _, invalid := range []string{`{"worker_id":null}`, `{"worker_id":""}`} { + require(t, request(f.handler, "POST", path, writer, core.NewID("invalid-ack"), actor, invalid), 400) + } + require(t, request(f.handler, "POST", path, writer, "ordinary-other-ack", actor, body), 403) + original := request(f.handler, "POST", path, manager, "managed-ack", actor, body) + require(t, original, 200) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=? AND project_id=?`, id, project); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "POST", path, manager, "managed-ack", actor, body), 403) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id=? AND project_id=?`, id, project); err != nil { + t.Fatal(err) + } + replay := request(f.handler, "POST", path, manager, "managed-ack", actor, body) + if replay.Code != 200 || !bytes.Equal(original.Body.Bytes(), replay.Body.Bytes()) { + t.Fatal("recovery changed the original explicit acknowledgement", replay.Body.String()) + } + // Default and explicit-own acknowledgement preserve ordinary writer access. + for i, ackBody := range []string{`{}`, body} { + message := retirementJSON(t, f, "POST", base+"/messages", writer, actor, map[string]any{"recipient_worker_id": target, "body": "Own incoming"}, 201)["id"].(string) + require(t, request(f.handler, "POST", base+"/messages/"+message+"/ack", writer, fmt.Sprintf("own-%d", i), target, ackBody), 200) + } + other := f.project(t, "owner/two") + foreign := f.worker(t, other, "Foreign") + require(t, request(f.handler, "GET", base+"/workers/"+foreign+"/retirement", writer, "", "", ""), 404) + require(t, request(f.handler, "POST", base+"/workers/"+foreign+"/retire", writer, "foreign-retire", actor, `{}`), 404) + require(t, request(f.handler, "POST", "/api/v1/projects/"+other+"/workers/"+foreign+"/retire", writer, "other-project-retire", "", `{}`), 403) + reader := "retirement-reader" + f.grant(t, project, reader, false) + require(t, request(f.handler, "GET", base+"/workers/"+target+"/retirement", reader, "", "", ""), 200) + require(t, request(f.handler, "POST", base+"/workers/"+target+"/retire", reader, "reader-retire", "", `{}`), 403) +} + +func TestWorkerListRawQueryBound(t *testing.T) { + f := setup(t) + project := f.project(t, "owner/query-bound") + base := "/api/v1/projects/" + project + "/workers?" + // Leading zeroes retain a valid page limit, distinguishing the raw byte + // bound from cursor/value validation. + for _, size := range []int{16 << 10, (16 << 10) + 1} { + query := "limit=" + strings.Repeat("0", size-len("limit=1")) + "1" + status := 200 + if size > 16<<10 { + status = 400 + } + require(t, request(f.handler, "GET", base+query, f.admin, "", "", ""), status) + } +} diff --git a/internal/webui/assets/assets/index-BoLFnGJQ.js b/internal/webui/assets/assets/index-CYqpI_SB.js similarity index 67% rename from internal/webui/assets/assets/index-BoLFnGJQ.js rename to internal/webui/assets/assets/index-CYqpI_SB.js index d8e87655c..6c5f1e5e5 100644 --- a/internal/webui/assets/assets/index-BoLFnGJQ.js +++ b/internal/webui/assets/assets/index-CYqpI_SB.js @@ -7,4 +7,4 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r= Error generating stack: `+e.message+` `+e.stack}}var Be=Object.prototype.hasOwnProperty,Ve=t.unstable_scheduleCallback,He=t.unstable_cancelCallback,Ue=t.unstable_shouldYield,We=t.unstable_requestPaint,Ge=t.unstable_now,Ke=t.unstable_getCurrentPriorityLevel,qe=t.unstable_ImmediatePriority,Je=t.unstable_UserBlockingPriority,Ye=t.unstable_NormalPriority,Xe=t.unstable_LowPriority,Ze=t.unstable_IdlePriority,Qe=t.log,$e=t.unstable_setDisableYieldValue,et=null,tt=null;function nt(e){if(typeof Qe==`function`&&$e(e),tt&&typeof tt.setStrictMode==`function`)try{tt.setStrictMode(et,e)}catch{}}var rt=Math.clz32?Math.clz32:ot,it=Math.log,at=Math.LN2;function ot(e){return e>>>=0,e===0?32:31-(it(e)/at|0)|0}var st=256,ct=262144,lt=4194304;function ut(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function dt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=ut(n))):i=ut(o):i=ut(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=ut(n))):i=ut(o)):i=ut(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function ft(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function pt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function _t(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function vt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0=_r),br=` `,xr=!1;function Sr(e,t){switch(e){case`keyup`:return hr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Cr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var wr=!1;function Tr(e,t){switch(e){case`compositionend`:return Cr(t);case`keypress`:return t.which===32?(xr=!0,br):null;case`textInput`:return e=t.data,e===br&&xr?null:e;default:return null}}function Er(e,t){if(wr)return e===`compositionend`||!gr&&Sr(e,t)?(e=Rn(),Ln=In=Fn=null,wr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Yr(n)}}function Zr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Zr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Qr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Jr(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Jr(e.document)}return t}function $r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var ei=Mn&&`documentMode`in document&&11>=document.documentMode,ti=null,ni=null,ri=null,ii=!1;function ai(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ii||ti==null||ti!==Jr(r)||(r=ti,`selectionStart`in r&&$r(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),ri&&qr(ri,r)||(ri=r,r=qf(ni,`onSelect`),0>=o,i-=o,Qi=1<<32-rt(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),R&&ea(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),R&&ea(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return R&&ea(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),R&&ea(a,g),u}function _(e,r,o,c){if(typeof o==`object`&&o&&o.type===te&&o.key===null&&o.props.ref===void 0&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case ee:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===te){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),lo(c,o),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===le&&no(l)===r.type){n(e,r.sibling),c=a(r,o.props),lo(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===te?(c=I(o.props.children,e.mode,c,o.key),lo(c,o),c.return=e,e=c):(c=Bi(o.type,o.key,o.props,null,e.mode,c),lo(c,o),c.return=e,e=c)}return s(e);case k:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=Ui(o,e.mode,c),c.return=e,e=c}return s(e);case le:return o=no(o),_(e,r,o,c)}if(ye(o))return h(e,r,o,c);if(ge(o)){if(l=ge(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return _(e,r,co(o),c);if(o.$$typeof===ie)return _(e,r,Da(e,o),c);uo(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=Vi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{so=0;var i=_(e,t,n,r);return oo=null,i}catch(t){if(t===Xa||t===Qa)throw t;var a=Ii(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var po=fo(!0),mo=fo(!1),ho=!1;function go(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function _o(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function B(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function vo(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Yu&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Ni(e),Mi(e,null,n),t}return ki(e,r,t,n),Ni(e)}function yo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bt(e,n)}}function bo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n}else e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var xo=!1;function So(){if(xo){var e=Va;if(e!==null)throw e}}function Co(e,t,n,r){xo=!1;var i=e.updateQueue;ho=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Q&f)===f:(r&f)===f){f!==0&&f===Ba&&(xo=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=D({},d,f);break a;case 2:ho=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),id|=o,e.lanes=o,e.memoizedState=d}}function wo(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function To(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=j.T,s={};s.types=o===null?null:o.types,j.T=s,oc(e,!1,t,n);try{var c=i(),l=j.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?q(e,t,Wa(c,r),kd(e)):q(e,t,r,kd(e))}catch(n){q(e,t,{then:function(){},status:`rejected`,reason:n},kd())}finally{M.p=a,o!==null&&s.types!==null&&(o.types=s.types),j.T=o}}function Xs(){}function Zs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Qs(e).queue;Ys(e,a,t,be,n===null?Xs:function(){return $s(e),n(r)})}function Qs(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:be,baseState:be,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fs,lastRenderedState:be},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fs,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function $s(e){var t=Qs(e);t.next===null&&(t=e.alternate.memoizedState),q(e,t.next.queue,{},kd())}function ec(){return Ea(sh)}function tc(){return cs().memoizedState}function nc(){return cs().memoizedState}function rc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=kd();e=B(n);var r=vo(t,e,n);r!==null&&(Md(r,t,n),yo(r,t,n)),t={cache:Na()},e.payload=t;return}t=t.return}}function ic(e,t,n){var r=kd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},sc(e)?cc(t,n):(n=Ai(e,t,n,r),n!==null&&(Md(n,e,r),lc(n,t,r)))}function ac(e,t,n){q(e,t,n,kd())}function q(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(sc(e))cc(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Kr(s,o))return ki(e,t,i,0),Xu===null&&Oi(),!1}catch{}if(n=Ai(e,t,i,r),n!==null)return Md(n,e,r),lc(n,t,r),!0}return!1}function oc(e,t,n,r){if(r={lane:2,revertLane:Nf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},sc(e)){if(t)throw Error(i(479))}else t=Ai(e,n,r,2),t!==null&&Md(t,e,2)}function sc(e){var t=e.alternate;return e===V||t!==null&&t===V}function cc(e,t){Ko=Go=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function lc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bt(e,n)}}var uc={readContext:Ea,use:H,useCallback:Qo,useContext:Qo,useEffect:Qo,useImperativeHandle:Qo,useLayoutEffect:Qo,useInsertionEffect:Qo,useMemo:Qo,useReducer:Qo,useRef:Qo,useState:Qo,useDebugValue:Qo,useDeferredValue:Qo,useTransition:Qo,useSyncExternalStore:Qo,useId:Qo,useHostTransitionStatus:Qo,useFormState:Qo,useActionState:Qo,useOptimistic:Qo,useMemoCache:Qo,useCacheRefresh:Qo,useEffectEvent:Qo},dc={readContext:Ea,use:H,useCallback:function(e,t){return ss().memoizedState=[e,t===void 0?null:t],e},useContext:Ea,useEffect:Is,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Ps(4194308,4,Hs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ps(4194308,4,e,t)},useInsertionEffect:function(e,t){Ps(4,2,e,t)},useMemo:function(e,t){var n=ss();t=t===void 0?null:t;var r=e();if(qo){nt(!0);try{e()}finally{nt(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ss();if(n!==void 0){var i=n(t);if(qo){nt(!0);try{n(t)}finally{nt(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=ic.bind(null,V,e),[r.memoizedState,e]},useRef:function(e){var t=ss();return e={current:e},t.memoizedState=e},useState:function(e){e=ys(e);var t=e.queue,n=ac.bind(null,V,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Ws,useDeferredValue:function(e,t){return qs(ss(),e,t)},useTransition:function(){var e=ys(!1);return e=Ys.bind(null,V,e.queue,!0,!1),ss().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=V,a=ss();if(R){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Xu===null)throw Error(i(349));Q&127||W(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,Is(_s.bind(null,r,o,e),[e]),r.flags|=2048,Ms(9,{destroy:void 0},gs.bind(null,r,o,n,t),null),n},useId:function(){var e=ss(),t=Xu.identifierPrefix;if(R){var n=$i,r=Qi;n=(r&~(1<<32-rt(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=Jo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[Dt]=t,o[Ot]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(np(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&ol(t)}}return dl(t),t.subtreeFlags&=-33554433,sl(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&ol(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=De.current,fa(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=aa,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[Dt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||$f(e.nodeValue,n)),e||la(t,!0)}else e=lp(e).createTextNode(r),e[Dt]=t,t.stateNode=e}return dl(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=fa(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[Dt]=t}else pa(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;dl(t),e=!1}else n=ma(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Lo(t),t):(Lo(t),null);if(t.flags&128)throw Error(i(558))}return dl(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=fa(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[Dt]=t}else pa(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;dl(t),a=!1}else a=ma(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(Lo(t),t):(Lo(t),null)}return Lo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),ll(t,t.updateQueue),dl(t),null);case 4:return Ae(),e===null&&Uf(t.stateNode.containerInfo),t.flags|=67108864,dl(t),null;case 10:return ba(t.type),dl(t),null;case 19:if(Bo(t),r=t.memoizedState,r===null)return dl(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)ul(r,!1);else{if(rd!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Vo(e),o!==null){for(t.flags|=128,ul(r,!1),e=o.updateQueue,t.updateQueue=e,ll(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)zi(n,e),n=n.sibling;return zo(t,Ro.current&1|2),R&&ea(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ge()>md&&(t.flags|=128,a=!0,ul(r,!1),t.lanes=4194304)}}else{if(!a){if(e=Vo(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,ll(t,e),ul(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!o.alternate&&!R)return dl(t),null}else 2*Ge()-r.renderingStartTime>md&&n!==536870912&&(t.flags|=128,a=!0,ul(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ge(),e.sibling=null,o=Ro.current,o=a?o&1|2:o&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||R?zo(t,o):(n=o,N(jo,t),N(Ro,n),Mo===null&&(Mo=t)),R&&ea(t,r.treeForkCount),e}return dl(t),null;case 22:case 23:return Lo(t),Ao(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(dl(t),t.subtreeFlags&6&&(t.flags|=8192)):dl(t),n=t.updateQueue,n!==null&&ll(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&we(Ka),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),ba(Ma),dl(t),null;case 25:return null;case 30:return t.flags|=33554432,dl(t),null}throw Error(i(156,t.tag))}function pl(e,t){switch(ra(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ba(Ma),Ae(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Me(t),null;case 31:if(t.memoizedState!==null){if(Lo(t),t.alternate===null)throw Error(i(340));pa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Lo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));pa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Bo(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return Ae(),null;case 10:return ba(t.type),null;case 22:case 23:return Lo(t),Ao(),e!==null&&we(Ka),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return ba(Ma),null;case 25:return null;default:return null}}function ml(e,t){switch(ra(t),t.tag){case 3:ba(Ma),Ae();break;case 26:case 27:case 5:Me(t);break;case 4:Ae();break;case 31:t.memoizedState!==null&&Lo(t);break;case 13:Lo(t);break;case 19:Bo(t);break;case 10:ba(t.type);break;case 22:case 23:Lo(t),Ao(),e!==null&&we(Ka);break;case 24:ba(Ma)}}function hl(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){ff(t,t.return,e)}}function gl(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){ff(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){ff(t,t.return,e)}}function _l(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{To(t,n)}catch(t){ff(e,e.return,t)}}}function vl(e,t,n){n.props=vc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){ff(e,t,n)}}function yl(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:var i=e.stateNode,a=xi(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Pp(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Fp(e);h(e.child,!1,Qp,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){ff(e,t,n)}}function bl(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){ff(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){ff(e,t,n)}else n.current=null}}function xl(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),np(r,t,n),r[Dt]=e,Vt(r),t=r;break a;case`link`:if(o=Gm(`link`,`href`,a).get(t+(n.href||``))){for(s=0;sg&&(o=g,g=h,h=o);var _=Xr(s,h),v=Xr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,j.T=null,n=Sd,Sd=null;var o=vd,s=bd;if(_d=0,yd=vd=null,bd=0,Yu&6)throw Error(i(331));var c=Yu;if(Yu|=4,Wu(o.current),Iu(o,o.current,s,n),Yu=c,Ef(0,!1),tt&&typeof tt.onPostCommitFiberRoot==`function`)try{tt.onPostCommitFiberRoot(et,o)}catch{}return!0}finally{M.p=a,j.T=r,cf(e,t)}}function df(e,t,n){t=Gi(n,t),t=wc(e.stateNode,t,2),e=vo(e,t,2),e!==null&&(_t(e,2),Tf(e))}function ff(e,t,n){if(e.tag===3)df(e,e,n);else for(;t!==null;){if(t.tag===3){df(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(gd===null||!gd.has(r))){e=Gi(n,e),n=Tc(2),r=vo(t,n,2),r!==null&&(Ec(n,r,t,e),_t(r,2),Tf(r));break}}t=t.return}}function pf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Ju;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(td=!0,i.add(n),e=mf.bind(null,e,t,n),t.then(e,e))}function mf(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Xu===e&&(Q&n)===n&&(rd===4||rd===3&&(Q&62914560)===Q&&300>Ge()-fd?Yu&2?od|=n:zd(e,0):od|=n,cd===Q&&(cd=0)),Tf(e)}function hf(e,t){t===0&&(t=ht()),e=ji(e,t),e!==null&&(_t(e,t),Tf(e))}function gf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),hf(e,n)}function _f(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),hf(e,n)}function vf(e,t){return Ve(e,t)}var yf=null,bf=null,xf=!1,Sf=!1,Cf=!1,wf=0;function Tf(e){e!==bf&&e.next===null&&(bf===null?yf=bf=e:bf=bf.next=e),Sf=!0,xf||(xf=!0,Mf())}function Ef(e,t){if(!Cf&&Sf){Cf=!0;do for(var n=!1,r=yf;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-rt(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,jf(r,a))}else a=Q,a=dt(r,r===Xu?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||ft(r,a)||(n=!0,jf(r,a))}r=r.next}while(n);Cf=!1}}function Df(){Of()}function Of(){Sf=xf=!1;var e=0;wf!==0&&hp()&&(e=wf);for(var t=Ge(),n=null,r=yf;r!==null;){var i=r.next,a=kf(r,t);a===0?(r.next=null,n===null?yf=i:n.next=i,i===null&&(bf=n)):(n=r,(e!==0||a&3)&&(Sf=!0)),r=i}_d!==0&&_d!==5||Ef(e,!1),wf!==0&&(wf=0)}function kf(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&ap(d)&&(c=c.responseEnd,o+=u*(c$m){s.length=o;break}f=new Promise(jp.bind(f)),s.push(f)}}}if(0`u`?null:document;function Tm(e,t,n){var r=wm;if(r&&typeof t==`string`&&t){var i=cn(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),ym.has(i)||(ym.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),np(t,`link`,e),Vt(t),r.head.appendChild(t)))}}function Em(e){xm.D(e),Tm(`dns-prefetch`,e,null)}function Dm(e,t){xm.C(e,t),Tm(`preconnect`,e,t)}function Om(e,t,n){xm.L(e,t,n);var r=wm;if(r&&e&&t){var i=`link[rel="preload"][as="`+cn(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+cn(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+cn(n.imageSizes)+`"]`)):i+=`[href="`+cn(e)+`"]`;var a=i;switch(t){case`style`:a=Pm(e);break;case`script`:a=Rm(e)}if(!(vm.has(a)||(e=D({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vm.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Fm(a))||t===`script`&&r.querySelector(zm(a))))){var o=r.createElement(`link`);np(o,`link`,e),t===`style`&&(o[Ft]=!0,o.onload=o.onerror=function(){Ht(o)}),Vt(o),r.head.appendChild(o)}}}function km(e,t){xm.m(e,t);var n=wm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+cn(r)+`"][href="`+cn(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rm(e)}if(!vm.has(a)&&(e=D({rel:`modulepreload`,href:e},t),vm.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zm(a)))return}r=n.createElement(`link`),np(r,`link`,e),Vt(r),n.head.appendChild(r)}}}function Am(e,t,n){xm.S(e,t,n);var r=wm;if(r&&e){var i=Bt(r).hoistableStyles,a=Pm(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Fm(a)))s.loading=5;else{e=D({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vm.get(a))&&Hm(e,n);var c=o=r.createElement(`link`);Vt(c),np(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jm(e,t){xm.X(e,t);var n=wm;if(n&&e){var r=Bt(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=D({src:e,async:!0},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Vt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mm(e,t){xm.M(e,t);var n=wm;if(n&&e){var r=Bt(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=D({src:e,async:!0,type:`module`},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Vt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nm(e,t,n,r){var a=(a=De.current)?bm(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Pm(n.href),t=Bt(a).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pm(n.href);var o=Bt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Fm(e)))?o._p||(s.instance=o,s.state.loading=5):(o=vm.get(e),o||(o={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vm.set(e,o)),Lm(a,e,o,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Rm(n),t=Bt(a).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Pm(e){return`href="`+cn(e)+`"`}function Fm(e){return`link[rel="stylesheet"][`+e+`]`}function Im(e){return D({},e,{"data-precedence":e.precedence,precedence:null})}function Lm(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[Ft]){r.loading=1;return}}else t=e.createElement(`link`),t[Ft]=!0,t.onload=t.onerror=Ht.bind(null,t),np(t,`link`,n),Vt(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Rm(e){return`[src="`+cn(e)+`"]`}function zm(e){return`script[async]`+e}function Bm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+cn(n.href)+`"]`);if(r)return t.instance=r,Vt(r),r;var a=D({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Vt(r),np(r,`style`,a),Vm(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Pm(n.href);var o=e.querySelector(Fm(a));if(o)return t.state.loading|=4,t.instance=o,Vt(o),o;r=Im(n),(a=vm.get(a))&&Hm(r,a),o=(e.ownerDocument||e).createElement(`link`),Vt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),np(o,`link`,r),t.state.loading|=4,Vm(o,n.precedence,e),t.instance=o;case`script`:return o=Rm(n.src),(a=e.querySelector(zm(o)))?(t.instance=a,Vt(a),a):(r=n,(a=vm.get(o))&&(r=D({},n),Um(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),Vt(a),np(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vm(r,n.precedence,e));return t.instance}function Vm(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qm(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jm(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function Ym(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Xm(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function Zm(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=Xm(t),e.suspenseyImages.push(t)),e=rh.bind(e),t.decode().then(e,e))}function Qm(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pm(r.href),a=t.querySelector(Fm(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=nh.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Vt(a);return}a=t.ownerDocument||t,r=Im(r),(i=vm.get(i))&&Hm(r,i),a=a.createElement(`link`),Vt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=nh.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var $m=0;function eh(e,t){return e.stylesheets&&e.count===0&&ah(e,e.stylesheets),0$m?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function th(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)ah(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function nh(){this.count--,th(this)}function rh(){this.imgCount--,th(this)}var ih=null;function ah(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ih=new Map,t.forEach(oh,e),ih=null,nh.call(e))}function oh(e,t){if(!(t.state.loading&4)){var n=ih.get(e);if(n)var r=n.get(null);else{n=new Map,ih.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,v=/^[\\/]{2}/;function y(e,t){return t+e.replace(/\\/g,`/`)}var b=`popstate`;function x(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function S(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return D(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:O(t)}return k(t,n,null,e)}function C(e,t){if(e===!1||e==null)throw Error(t)}function w(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function T(){return Math.random().toString(36).substring(2,10)}function E(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function D(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?ee(t):t,state:n,key:t&&t.key||r||T(),mask:i}}function O({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function ee(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function k(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=x(e)?e:D(h.location,e,t);n&&n(r,e),l=u()+1;let d=E(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=x(e)?e:D(h.location,e,t);n&&n(r,e),l=u();let i=E(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return te(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(b,d),c=e,()=>{i.removeEventListener(b,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function te(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),C(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:O(t);return i=i.replace(/ $/,`%20`),!n&&v.test(i)&&(i=r+i),new URL(i,r)}var A=c(u(),1),ne=class{#e=new Map;constructor(e){if(e)for(let[t,n]of e)this.set(t,n)}get(e){if(this.#e.has(e))return this.#e.get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw Error(`No value found for context`)}set(e,t){this.#e.set(e,t)}},re=class extends Error{},ie=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`children`,`unstable_validateParams`]);function ae(e){return ie.has(e)}var oe=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`middleware`,`children`,`unstable_validateParams`]);function se(e){return oe.has(e)}function ce(e){return e.index===!0}function le(e){let t={};return e.Component&&Object.assign(t,{element:A.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:A.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:A.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}function ue(e,t=le,n=[],r={},i=!1){return e.map((e,a)=>{let o=[...n,String(a)],s=typeof e.id==`string`?e.id:o.join(`-`);if(C(e.index!==!0||!e.children,`Cannot specify children on an index route`),C(i||!r[s],`Found a route id collision on id "${s}". Route id's must be globally unique within Data Router usages`),ce(e)){let n={...e,id:s};return r[s]=de(n,t(n)),n}{let n={...e,id:s,children:void 0};return r[s]=de(n,t(n)),e.children&&(n.children=ue(e.children,t,o,r,i)),n}})}function de(e,t){return Object.assign(e,{...t,...typeof t.lazy==`object`&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function fe(e,t,n=`/`){return pe(e,t,n,!1)}function pe(e,t,n,r,i){let a=Me((typeof t==`string`?ee(t):t).pathname||`/`,n);if(a==null)return null;let o=i??he(e),s=null,c=je(a);for(let e=0;s==null&&e{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;C(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=He([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(C(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),ge(e.children,t,u,l,o)),(e.path!=null||e.index)&&t.push({path:l,score:Te(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Ae(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of _e(e.path))a(e,t,!0,n)}),t}function _e(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=_e(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function ve(e){e.sort((e,t)=>e.score===t.score?Ee(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var ye=/^:[\w-]+$/,j=/^:[\w-]+/,M=3.5,be=3,xe=2,Se=1,Ce=10,we=-2,N=e=>e===`*`;function Te(e,t){let n=e.split(`/`),r=n.length;return n.some(N)&&(r+=we),t&&(r+=xe),n.filter(e=>!N(e)).reduce((e,t)=>e+(ye.test(t)?be:j.test(t)?M:t===``?Se:Ce),r)}function Ee(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function De(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e{if(t===`*`){let e=s[r]||``;o=Ue(a.slice(0,a.length-e.length),1)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function Ae(e,t=!1,n=!0){w(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/((?:[^/?()[\]*^\\]|\\.)+)\?(?=\/|$|\()/g,`(?:/$1)?`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function je(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return w(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Me(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function Ne({basename:e,pathname:t}){return t===`/`?e:He([e,t])}var Pe=e=>_.test(e);function Fe(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?ee(e):e,a;return n?(n=Ve(n),a=n.startsWith(`/`)||n.startsWith(`\\`)?Ie(n.substring(1),`/`):Ie(n,t)):a=t,{pathname:a,search:Ge(r),hash:Ke(i)}}function Ie(e,t){let n=Ue(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Le(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function Re(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function ze(e){let t=Re(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Be(e,t,n,r=!1){let i;typeof e==`string`?i=ee(e):(i={...e},C(!i.pathname||!i.pathname.includes(`?`),Le(`?`,`pathname`,`search`,i)),C(!i.pathname||!i.pathname.includes(`#`),Le(`#`,`pathname`,`hash`,i)),C(!i.search||!i.search.includes(`#`),Le(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=Fe(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Ve=e=>e.replace(/[\\/]{2,}/g,`/`),He=e=>Ve(e.join(`/`));function Ue(e,t=0){let n=e.length;for(;n>t&&e.charCodeAt(n-1)===47;)n--;return n===e.length?e:e.slice(0,n)}var We=e=>Ue(e).replace(/^\/*/,`/`),Ge=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Ke=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,qe=[`EvalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],Je=class{status;statusText;data;error;internal;constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function Ye(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Xe(e){return He(e.map(e=>e.route.path).filter(Boolean))||`/`}function Ze(e,t){let n=new URL(typeof e==`string`||e instanceof URL?e:e.url),r=typeof t==`string`?ee(t):t;if(n.pathname=r.pathname||`/`,r.search){let e=new URLSearchParams(r.search),t=e.getAll(`index`);e.delete(`index`);for(let n of t.filter(Boolean))e.append(`index`,n);let i=e.toString();n.search=i?`?${i}`:``}else n.search=``;return n.hash=r.hash||``,n}var Qe=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function $e(e,t){let n=e;if(typeof n!=`string`||!_.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Qe)try{let e=new URL(window.location.href),r=v.test(n)?new URL(y(n,e.protocol)):new URL(n),a=Me(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{w(!1,` contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}var et=Symbol(`Uninstrumented`),tt=new WeakMap;function nt(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(e=>e({id:t.id,index:t.index,path:t.path,instrument(e){e.lazy!=null&&n.lazy.push(e.lazy),e[`lazy.loader`]!=null&&n[`lazy.loader`].push(e[`lazy.loader`]),e[`lazy.action`]!=null&&n[`lazy.action`].push(e[`lazy.action`]),e[`lazy.middleware`]!=null&&n[`lazy.middleware`].push(e[`lazy.middleware`]),e.middleware!=null&&n.middleware.push(e.middleware),e.loader!=null&&n.loader.push(e.loader),e.action!=null&&n.action.push(e.action)}}));let r={};if(typeof t.lazy==`function`&&n.lazy.length>0){let e=t.lazy;r.lazy=async(...t)=>ct(await lt(n.lazy,void 0,()=>e(...t),ut))}if(typeof t.lazy==`object`){let e=t.lazy;if(typeof e.middleware==`function`&&n[`lazy.middleware`].length>0){let t=e.middleware;r.lazy=Object.assign(r.lazy||{},{middleware:async(...e)=>ct(await lt(n[`lazy.middleware`],void 0,()=>t(...e),ut))})}if(typeof e.loader==`function`&&n[`lazy.loader`].length>0){let t=e.loader;r.lazy=Object.assign(r.lazy||{},{loader:async(...e)=>ct(await lt(n[`lazy.loader`],void 0,()=>t(...e),ut))})}if(typeof e.action==`function`&&n[`lazy.action`].length>0){let t=e.action;r.lazy=Object.assign(r.lazy||{},{action:async(...e)=>ct(await lt(n[`lazy.action`],void 0,()=>t(...e),ut))})}}if(typeof t.loader==`function`&&n.loader.length>0){let e=it(t.loader),i=async(...t)=>ct(await lt(n.loader,dt(t[0]),()=>e(...t),ut));e.hydrate===!0&&(i.hydrate=!0),at(i,e),r.loader=i}if(typeof t.action==`function`&&n.action.length>0){let e=it(t.action),i=async(...t)=>ct(await lt(n.action,dt(t[0]),()=>e(...t),ut));at(i,e),r.action=i}return t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(e=>{let t=it(e),r=async(...e)=>ct(await lt(n.middleware,dt(e[0]),()=>t(...e),ut));return at(r,t),r})),r}function rt(e,t){let n={navigate:[],fetch:[]};if(t.forEach(e=>e({instrument(e){e.navigate!=null&&n.navigate.push(e.navigate),e.fetch!=null&&n.fetch.push(e.fetch)}})),n.navigate.length>0){let t=it(e.navigate),r=async(...r)=>{let[i,a]=r,o,s={to:typeof i==`number`||typeof i==`string`?i:i?O(i):`.`,...ft(e,a??{})};return ct(await lt(n.navigate,s,async()=>{if(typeof i==`number`)return await t(...r);let n=ot(e,e=>{o=e});try{return await t(...r)}finally{n()}},e=>({...ut(e),meta:o})))};at(r,t),e.navigate=r}if(n.fetch.length>0){let t=it(e.fetch),r=async(...r)=>{let[i,a,o,s]=r,c;return ct(await lt(n.fetch,{href:o??`.`,fetcherKey:i,...ft(e,s??{})},async()=>{let n=ot(e,e=>{c=e});try{return await t(...r)}finally{n()}},e=>({...ut(e),meta:c})))};at(r,t),e.fetch=r}return e}function it(e){return e[et]??e}function at(e,t){e[et]=t}function ot(e,t){return tt.set(e,t),()=>{tt.get(e)===t&&tt.delete(e)}}function st(e){let t=tt.get(e);return tt.delete(e),t}function ct(e){if(e.type===`error`)throw e.value;return e.value}async function lt(e,t,n,r,i={result:null,innerResult:null},a=e.length-1){let o=e[a];if(o){let s,c=async()=>(s?console.error(`You cannot call instrumented handlers more than once`):s=lt(e,t,n,r,i,a-1),await s,C(i.innerResult,`Expected an inner result`),i.innerResult);try{await o(c,t)}catch(e){console.error(`An instrumentation function threw an error:`,e)}s||await c(),await s}else{try{i.result={type:`success`,value:await n()}}catch(e){i.result={type:`error`,value:e}}i.innerResult=r(i.result,t)}return i.result||(i.result={type:`error`,value:Error(`No result assigned in instrumentation chain.`)},i.innerResult=r(i.result,t)),i.result}function ut(e){return e.type===`error`&&e.value instanceof Error?{status:`error`,error:e.value}:{status:`success`,error:void 0}}function dt(e){let{request:t,context:n,params:r}=e;return{...e,request:pt(t),params:{...r},context:mt(n)}}function ft(e,t){return{currentUrl:O(e.state.location),...`formMethod`in t?{formMethod:t.formMethod}:{},...`formEncType`in t?{formEncType:t.formEncType}:{},...`formData`in t?{formData:t.formData}:{},...`body`in t?{body:t.body}:{}}}function pt(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function mt(e){return{get:t=>e.get(t)}}var ht=class{#e=[];#t=[];#n;#r=0;constructor(e){this.#n=e}update(e){this.#e=e,this.#t=he(e),this.#r=this.#t.reduce((e,t)=>e+t.routesMeta.length,0)}get matchCost(){return this.#r}match(e,t=!1){return pe(this.#e,e,this.#n,t,this.#t)}},gt=new URL(`http://localhost`);function _t(e){if(e.createURL)return e.createURL(`/`);try{return new URL(e.createHref(`/`),gt)}catch{return gt}}function vt(e,t){return e.origin===t.origin&&(e.origin!==`null`||e.protocol===t.protocol&&e.host===t.host)}function yt(e,t){if(e.startsWith(`//`))return!0;let n=t.protocol.toLowerCase();return e.toLowerCase().startsWith(n)?t.host===``||e.slice(n.length).startsWith(`//`):!1}function bt(e,t,n,r){let i=null;try{i=e==null?null:new URL(e,n)}catch{}let a=new URL(t,n),o=i!=null&&!vt(i,n),s=!vt(a,n);if(r===`reject`){if(o||s)throw Error(`External navigation is not allowed`)}else if(s&&(i==null||!yt(e,i)||!vt(i,a)))throw Error(`External navigation is not allowed`)}var xt=[`POST`,`PUT`,`PATCH`,`DELETE`],St=new Set(xt),Ct=[`GET`,...xt],wt=new Set(Ct),Tt=new Set([301,302,303,307,308]),Et=new Set([307,308]),Dt={state:`idle`,location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ot={state:`idle`,data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},kt={state:`unblocked`,proceed:void 0,reset:void 0,location:void 0},At=`remix-router-transitions`,jt=Symbol(`ResetLoaderData`);function Mt(e,t){return e.unstable_routePatternMatching?(C(void 0,`You must call unstable_preloadRoutePattern() from "react-router/route-pattern" before enabling future.unstable_routePatternMatching.`),new(void 0)(t)):new ht(t)}var Nt=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#n=t,this.#n.update(e)}get stableRoutes(){return this.#e}get activeRoutes(){return this.#t??this.#e}get hasHMRRoutes(){return this.#t!=null}setRoutes(e){this.#e=e,this.#t||this.#n.update(e)}setHmrRoutes(e){this.#t=e,this.#n.update(e)}commitHmrRoutes(){this.#t&&(this.#e=this.#t,this.#t=void 0,this.#n.update(this.#e))}},Pt=new WeakMap;function Ft(e){let t=e.window?e.window:typeof window<`u`?window:void 0,n=t!==void 0&&t.document!==void 0&&t.document.createElement!==void 0;C(e.routes.length>0,`You must provide a non-empty routes array to createRouter`);let r=e.hydrationRouteProperties||[],i=e.mapRouteProperties,a=i||(()=>({}));if(e.instrumentations){let t=e.instrumentations;a=e=>({...i?.(e),...nt(t.map(e=>e.route).filter(Boolean),e)})}let o={...e.future},s=e.basename||`/`;s.startsWith(`/`)||(s=`/${s}`);let c=Mt(o,s),l={},u=new Nt(ue(e.routes,a,void 0,l),c),d=e.dataStrategy||Zt,f=null,p=new Set,m=null,h=null,g=null,_=e.hydrationData!=null,y=c.match(e.history.location),b=!1,x=null,S,T;if(y==null&&!e.patchRoutesOnNavigation){let t=Sn(404,{pathname:e.history.location.pathname}),{matches:n,route:r}=xn(u.activeRoutes);S=!0,T=!S,y=n,x={[r.id]:t}}else if(y&&!e.hydrationData&&_t(y,e.history.location.pathname).active&&(y=null),!y){S=!1,T=!S,y=[];let t=_t(null,e.history.location.pathname);t.active&&t.matches&&(b=!0,y=t.matches)}else if(y.some(e=>e.route.lazy))S=!1,T=!S;else if(!y.some(e=>Bt(e.route)))S=!0,T=!S;else{let t=e.hydrationData?e.hydrationData.loaderData:null,n=e.hydrationData?e.hydrationData.errors:null,r=y;if(n){let e=y.findIndex(e=>n[e.route.id]!==void 0);r=r.slice(0,e+1)}T=!1,S=!0,r.forEach(e=>{let r=Vt(e.route,t,n);T||=r.renderFallback,S&&=!r.shouldLoad})}let E,k={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,renderFallback:T,navigation:Dt,restoreScrollPosition:e.hydrationData==null&&null,preventScrollReset:!1,revalidation:`idle`,loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||x,fetchers:new Map,blockers:new Map},A=`POP`,ie=0,ae,oe=null,se=!1,ce,le=!1,de=new Map,fe=null,pe=!1,he=!1,ge=new Set,_e=new Map,ve=0,ye=-1,j=new Map,M=new Set,be=new Map,xe=new Map,Se=new Set,Ce=new Map,we,N=null;function Te(){if(f=e.history.listen(({action:t,location:n,delta:r})=>{if(we){we(),we=void 0;return}w(Ce.size===0||r!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=dt({currentLocation:k.location,nextLocation:n,historyAction:t});if(i&&r!=null){let t=new Promise(e=>{we=e});e.history.go(r*-1),ut(i,{state:`blocked`,location:n,proceed(){ut(i,{state:`proceeding`,proceed:void 0,reset:void 0,location:n}),t.then(()=>e.history.go(r))},reset(){let e=new Map(k.blockers);e.set(i,kt),Oe({blockers:e})}}),oe?.resolve(),oe=null}else return o.unstable_customRouteDiscovery&&(ie+=r||0),Fe(t,n)}),n){qn(t,de);let e=()=>Jn(t,de);t.addEventListener(`pagehide`,e),fe=()=>t.removeEventListener(`pagehide`,e)}return k.initialized||Fe(`POP`,k.location,{initialHydration:!0}),E}function Ee(){f&&f(),fe&&fe(),p.clear(),ce&&ce.abort(),k.fetchers.forEach((e,t)=>$e(k.fetchers,t)),k.blockers.forEach((e,t)=>lt(t))}function De(e){return p.add(e),()=>p.delete(e)}function Oe(e,t={}){let n=e.errors??null,r=n?Pt.get(n):void 0;r!==void 0&&(n=r),(e.errors!==void 0||e.initialized)&&(k.errors&&Pt.delete(k.errors),e.errors&&Pt.set(e.errors,n)),e.matches&&=e.matches.map(e=>{let t=l[e.route.id],n=e.route;return n.element!==t.element||n.errorElement!==t.errorElement||n.hydrateFallbackElement!==t.hydrateFallbackElement?{...e,route:t}:e}),k={...k,...e};let i=[],a=[];k.fetchers.forEach((e,t)=>{e.state===`idle`&&(Se.has(t)?i.push(t):a.push(t))}),Se.forEach(e=>{!k.fetchers.has(e)&&!_e.has(e)&&i.push(e)}),[...p].forEach(e=>e(k,{deletedFetchers:i,newErrors:n,viewTransitionOpts:t.viewTransitionOpts,flushSync:t.flushSync===!0})),i.forEach(e=>$e(k.fetchers,e)),a.forEach(e=>k.fetchers.delete(e))}function ke(t,n,{flushSync:r}={}){let i=k.actionData!=null&&k.navigation.formMethod!=null&&Ln(k.navigation.formMethod)&&k.navigation.state===`loading`&&t.state?._isRedirect!==!0,a;a=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:i?k.actionData:null;let o=n.loaderData?vn(k.loaderData,n.loaderData,n.matches||[],n.errors):k.loaderData,s=k.blockers;s.size>0&&!pe&&(s=new Map(s),s.forEach((e,t)=>s.set(t,kt)));let c=!pe&>(t,n.matches||k.matches),l=se===!0||k.navigation.formMethod!=null&&Ln(k.navigation.formMethod)&&t.state?._isRedirect!==!0;u.commitHmrRoutes(),pe||A===`POP`||(A===`PUSH`?e.history.push(t,t.state):A===`REPLACE`&&e.history.replace(t,t.state));let d;if(A===`POP`&&!pe&&t!==k.location){let e=de.get(k.location.pathname);e&&e.has(t.pathname)?d={currentLocation:k.location,nextLocation:t}:de.has(t.pathname)&&(d={currentLocation:t,nextLocation:k.location})}else if(le){let e=de.get(k.location.pathname);e?e.add(t.pathname):(e=new Set([t.pathname]),de.set(k.location.pathname,e)),d={currentLocation:k.location,nextLocation:t}}Oe({...n,actionData:a,loaderData:o,historyAction:A,location:t,initialized:!0,renderFallback:!1,navigation:Dt,revalidation:`idle`,restoreScrollPosition:c,preventScrollReset:l,blockers:s},{viewTransitionOpts:d,flushSync:r===!0}),Ae(),oe?.resolve(),oe=null,N?.resolve(),N=null}function Ae(){ie=0,A=`POP`,se=!1,le=!1,pe=!1,he=j.size>0}async function je(t,n){if(ae&&await ae,oe?.resolve(),oe=null,typeof t==`number`){oe||=Yn();let n=oe.promise;return e.history.go(t),n}let r=st(E),{path:i,submission:a,error:o}=Rt(!1,Lt(k.location,k.matches,s,t,n?.fromRouteId,n?.relative),n),c;if(n?.mask){let t=typeof n.mask==`string`?ee(n.mask):{...k.location.mask,...n.mask};if(c={pathname:t.pathname??``,search:t.search??``,hash:t.hash??``},v.test(c.pathname))throw Error(`External navigation is not allowed`);c.pathname.startsWith(`\\`)&&(c.pathname=c.pathname.replace(/^\\+/,`/`)),bt(typeof n.mask==`string`?n.mask:O(n.mask),O(c),e.history.createURL(`/`),`reject`)}let l=k.location,u=D(l,i,n&&n.state,void 0,c);u={...u,...e.history.encodeLocation(u)},bt(t==null?e.history.createHref(k.location):typeof t==`string`?t:O(t),e.history.createHref(u.mask||u),e.history.createURL(`/`),`reject`);let d=n&&n.replace!=null?n.replace:void 0,f=`PUSH`,p=k.location.pathname+k.location.search;d===!0?f=`REPLACE`:d===!1||a!=null&&Ln(a.formMethod)&&(a.formAction===p||u.pathname+u.search===p)&&(f=`REPLACE`);let m=n&&`preventScrollReset`in n?n.preventScrollReset===!0:void 0,h=(n&&n.flushSync)===!0,g=dt({currentLocation:l,nextLocation:u,historyAction:f});g?ut(g,{state:`blocked`,location:u,proceed(){ut(g,{state:`proceeding`,proceed:void 0,reset:void 0,location:u}),je(t,n)},reset(){let e=new Map(k.blockers);e.set(g,kt),Oe({blockers:e})}}):await Fe(f,u,{submission:a,pendingError:o,preventScrollReset:m,replace:n&&n.replace,enableViewTransition:n&&n.viewTransition,flushSync:h,callSiteDefaultShouldRevalidate:n&&n.defaultShouldRevalidate,instrumentationNavigateMetaReceiver:r})}function Ne(){if(ae)return ae.then(Ne);N||=Yn(),qe(),Oe({revalidation:`loading`});let e=N.promise;return k.navigation.state===`submitting`?e:k.navigation.state===`idle`?(Fe(k.historyAction,k.location,{startUninterruptedRevalidation:!0,dataStrategyInitiator:`revalidation`}),e):(Fe(A||k.historyAction,k.navigation.location,{overrideNavigation:k.navigation,dataStrategyInitiator:`revalidation`,enableViewTransition:le===!0}),e)}async function Fe(t,n,r){ae&&await ae,ce&&ce.abort(),ce=null,A=t,pe=(r&&r.startUninterruptedRevalidation)===!0,ht(k.location,k.matches),se=(r&&r.preventScrollReset)===!0,le=(r&&r.enableViewTransition)===!0;let i=r?.initialHydration&&k.matches&&k.matches.length>0&&!b?k.matches:c.match(n),a=(r&&r.flushSync)===!0;if(i&&k.initialized&&!he&&Tn(k.location,n)&&!(r&&r.submission&&Ln(r.submission.formMethod))){ke(n,{matches:i},{flushSync:a});return}let o=_t(i,n.pathname);if(o.active&&o.matches&&(i=o.matches),r?.instrumentationNavigateMetaReceiver){let t=Bn(e.history,n,i);r.instrumentationNavigateMetaReceiver(t)}if(!i){let{error:e,notFoundMatches:t,route:r}=ft(n.pathname);ke(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:a});return}let s=r&&r.overrideNavigation?{...r.overrideNavigation,matches:i,historyAction:t}:void 0;ce=new AbortController;let l=pn(e.history,n,ce.signal,r&&r.submission),u=r?.initialHydration?`initialization`:r?.dataStrategyInitiator??`navigation`,d=e.getContext?await e.getContext():new ne,f;if(r&&r.pendingError)f=[bn(i).route.id,{type:`error`,error:r.pendingError}];else if(r&&r.submission&&Ln(r.submission.formMethod)){let c=await Le(l,u,n,r.submission,i,t,d,o.active,r&&r.initialHydration===!0,{replace:r.replace,flushSync:a});if(c.shortCircuited)return;if(c.pendingActionResult){let[e,t]=c.pendingActionResult;if(An(t)&&Ye(t.error)&&t.error.status===404){ce=null,ke(n,{matches:c.matches,loaderData:{},errors:{[e]:t.error}});return}}i=c.matches||i,f=c.pendingActionResult,s=Hn(n,i,t,r.submission),a=!1,o.active=!1,l=pn(e.history,l.url,l.signal)}let{shortCircuited:p,matches:m,loaderData:h,errors:g,workingFetchers:_}=await Re(l,u,n,i,t,d,o.active,s,r&&r.submission,r&&r.fetcherSubmission,r&&r.replace,r&&r.initialHydration===!0,a,f,r&&r.callSiteDefaultShouldRevalidate);p||(ce=null,ke(n,{matches:m||i,...yn(f),loaderData:h,errors:g,..._?{fetchers:_}:{}}))}function Ie(){let t=Yn();ae=t.promise;let n=ie,r=oe;oe=null,ce?.abort(),ce=null,Ae(),N?.resolve(),N=null;let i=new Map(k.blockers);i.forEach((e,t)=>{e.state===`proceeding`&&i.set(t,kt)});let a=new Map(k.fetchers),o=at(a);a.forEach((e,t)=>{e.state===`loading`&&!_e.has(t)&&(a.set(t,Kn(e.data)),o=!0)}),ge.clear(),Oe({navigation:Dt,revalidation:`idle`,blockers:i,...o?{fetchers:a}:{}});function s(){ae=void 0,r?.resolve(),t.resolve()}return n?(we=s,e.history.go(-n)):s(),t.promise}async function Le(t,n,i,c,d,f,p,m,h,g={}){if(o.unstable_customRouteDiscovery||qe(),Oe({navigation:Un(i,d,f,c)},{flushSync:g.flushSync===!0}),m){let e=await vt(d,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await Ie(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=xn(u.activeRoutes);return{matches:t,pendingActionResult:[n.id,{type:`error`,error:e.error}]}}let t=bn(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:`error`,error:e.error}]}}if(e.matches)d=e.matches;else{let{notFoundMatches:e,error:t,route:n}=ft(i.pathname);return{matches:e,pendingActionResult:[n.id,{type:`error`,error:t}]}}}o.unstable_customRouteDiscovery&&qe();let _,v=zn(d,i);if(!v.route.action&&!v.route.lazy)_={type:`error`,error:Sn(405,{method:t.method,pathname:i.pathname,routeId:v.route.id})};else{let e=await Ge(t,i,rn(a,l,t,i,d,v,h?[]:r,p),p,null,n,f);if(_=e[v.route.id],!_){for(let t of d)if(e[t.route.id]){_=e[t.route.id];break}}if(t.signal.aborted)return{shortCircuited:!0}}if(jn(_)){let r;return r=g&&g.replace!=null?g.replace:fn(_.response.headers.get(`Location`),new URL(t.url),s,e.history)===k.location.pathname+k.location.search,await We(t,_,!0,n,{submission:c,replace:r}),{shortCircuited:!0}}if(An(_)){let e=bn(d,v.route.id);return(g&&g.replace)!==!0&&(A=`PUSH`),{matches:d,pendingActionResult:[e.route.id,_,v.route.id]}}return{matches:d,pendingActionResult:[v.route.id,_]}}async function Re(t,n,i,s,d,f,p,m,h,g,_,v,y,b,x){let S=m||Hn(i,s,d,h),C=h||g||Vn(S),w=!pe&&!v;if(p){if(w){let e=ze(b);Oe({navigation:S,...e===void 0?{}:{actionData:e}},{flushSync:y})}let e=await vt(s,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await Ie(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=xn(u.activeRoutes);return{matches:t,loaderData:{},errors:{[n.id]:e.error}}}let t=bn(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(e.matches)s=e.matches,v&&!t.signal.aborted&&Oe({matches:s});else{let{error:e,notFoundMatches:t,route:n}=ft(i.pathname);return{matches:t,loaderData:{},errors:{[n.id]:e}}}}let{dsMatches:T,revalidatingFetchers:E}=zt(t,f,a,l,e.history,k,s,C,i,v?[]:r,v===!0,he,ge,Se,be,M,c,b,x);if(ye=++ve,!e.dataStrategy&&!T.some(e=>e.shouldLoad)&&!T.some(e=>e.route.middleware&&e.route.middleware.length>0)&&E.length===0){let e=new Map(k.fetchers),t=at(e);return ke(i,{matches:s,loaderData:{},errors:b&&An(b[1])?{[b[0]]:b[1].error}:null,...yn(b),...t?{fetchers:e}:{}},{flushSync:y}),{shortCircuited:!0}}if(w){let e={};if(!p){e.navigation=S;let t=ze(b);t!==void 0&&(e.actionData=t)}E.length>0&&(e.fetchers=Be(E)),Oe(e,{flushSync:y})}E.forEach(e=>{tt(e.key),e.controller&&_e.set(e.key,e.controller)});let D=()=>E.forEach(e=>{_e.get(e.key)===e.controller&&tt(e.key)});ce&&ce.signal.addEventListener(`abort`,D);let{loaderResults:O,fetcherResults:ee}=await Ke(T,E,t,i,f,n,d);if(t.signal.aborted)return{shortCircuited:!0};ce&&ce.signal.removeEventListener(`abort`,D),E.forEach(e=>{_e.get(e.key)===e.controller&&_e.delete(e.key)});let te=Cn(O);if(te)return await We(t,te.result,!0,n,{replace:_}),{shortCircuited:!0};if(te=Cn(ee),te)return M.add(te.key),await We(t,te.result,!0,n,{replace:_}),{shortCircuited:!0};let A=new Map(k.fetchers),{loaderData:ne,errors:re}=_n(k,s,O,b,E,ee,A);if(v&&k.errors){let e=re??null;re={...k.errors,...re},Pt.set(re,e)}let ie=at(A),ae=ot(ye,A),oe=ie||ae||E.length>0;return{matches:s,loaderData:ne,errors:re,...oe?{workingFetchers:A}:{}}}function ze(e){if(e&&!An(e[1]))return{[e[0]]:e[1].data};if(k.actionData)return Object.keys(k.actionData).length===0?null:k.actionData}function Be(e){let t=new Map(k.fetchers);return e.forEach(e=>{let n=t.get(e.key),r=Wn(void 0,n?n.data:void 0);t.set(e.key,r)}),t}async function Ve(t,n,r,i){ae&&await ae,tt(t);let a=(i&&i.flushSync)===!0,o=st(E),l=Lt(k.location,k.matches,s,r,n,i?.relative),u=c.match(l),d=_t(u,l);if(d.active&&d.matches&&(u=d.matches),o&&o(Bn(e.history,l,u)),!u){Xe(t,n,Sn(404,{pathname:l}),{flushSync:a});return}let{path:f,submission:p,error:m}=Rt(!0,l,i);if(m){Xe(t,n,m,{flushSync:a});return}let h=e.getContext?await e.getContext():new ne,g=(i&&i.preventScrollReset)===!0;if(p&&Ln(p.formMethod)){await He(t,n,f,u,h,d.active,a,g,p,i&&i.defaultShouldRevalidate);return}let _={routeId:n,path:f,isDiscovering:d.active};be.set(t,_),await Ue(t,_,u,h,a,g,p)}async function He(t,n,i,s,u,d,f,p,m,h){o.unstable_customRouteDiscovery||qe(),be.delete(t);let g=k.fetchers.get(t);Je(t,Gn(m,g),{flushSync:f});let _=new AbortController;o.unstable_customRouteDiscovery&&_e.set(t,_);let v=pn(e.history,i,_.signal,m);if(d){let e=await vt(s,new URL(v.url).pathname,v.signal,t);if(o.unstable_customRouteDiscovery&&v.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){_e.delete(t),be.delete(t),Je(t,Kn(g?.data),{flushSync:f});return}if(e.type===`error`){Xe(t,n,e.error,{flushSync:f});return}if(e.matches)s=e.matches;else{Xe(t,n,Sn(404,{pathname:i}),{flushSync:f});return}}let y=zn(s,i);if(!y.route.action&&!y.route.lazy){Xe(t,n,Sn(405,{method:m.formMethod,pathname:i,routeId:n}),{flushSync:f});return}o.unstable_customRouteDiscovery&&qe(),_e.set(t,_);let b=ve,x=rn(a,l,v,i,s,y,r,u),S=await Ge(v,i,x,u,t,`fetcher`),w=S[y.route.id];if(!w){for(let e of x)if(S[e.route.id]){w=S[e.route.id];break}}if(v.signal.aborted){_e.get(t)===_&&_e.delete(t);return}if(Se.has(t)){if(An(w)){Je(t,Kn(void 0));return}jn(w)&&(he=!0,w={type:`data`,data:void 0})}else{if(jn(w)){if(ye>b)he=!0,w={type:`data`,data:void 0};else return _e.delete(t),M.add(t),Je(t,Wn(m)),We(v,w,!1,`fetcher`,{fetcherSubmission:m,preventScrollReset:p})}if(An(w)){Xe(t,n,w.error);return}}he=!0;let T=k.navigation.location||k.location,E=pn(e.history,T,_.signal),D=k.navigation.state===`idle`?k.matches:c.match(k.navigation.location);C(D,`Didn't find any matches after fetcher action`);let O=++ve;j.set(t,O);let{dsMatches:ee,revalidatingFetchers:te}=zt(E,u,a,l,e.history,k,D,m,T,r,!1,he,ge,Se,be,M,c,[y.route.id,w],h),ne=Wn(m,w.data),re=new Map(k.fetchers);re.set(t,ne),te.filter(e=>e.key!==t).forEach(e=>{let t=e.key,n=re.get(t),r=Wn(void 0,n?n.data:void 0);re.set(t,r),tt(t),e.controller&&_e.set(t,e.controller)}),Oe({fetchers:re});let ie=()=>te.forEach(e=>{_e.get(e.key)===e.controller&&tt(e.key)});_.signal.addEventListener(`abort`,ie);let{loaderResults:ae,fetcherResults:oe}=await Ke(ee,te,E,T,u,`fetcher`);if(_.signal.aborted){j.get(t)===O&&j.delete(t);return}_.signal.removeEventListener(`abort`,ie),j.delete(t),_e.delete(t),te.forEach(e=>{_e.get(e.key)===e.controller&&_e.delete(e.key)});let se=k.fetchers.has(t),le=e=>{if(!se)return e;let n=new Map(e.fetchers);return n.set(t,Kn(w.data)),{...e,fetchers:n}},ue=Cn(ae);if(ue)return k=le(k),We(E,ue.result,!1,`fetcher`,{preventScrollReset:p});if(ue=Cn(oe),ue)return M.add(ue.key),k=le(k),We(E,ue.result,!1,`fetcher`,{preventScrollReset:p});let de=new Map(k.fetchers);se&&de.set(t,Kn(w.data));let{loaderData:fe,errors:pe}=_n(k,D,ae,void 0,te,oe,de);ot(O,de),k.navigation.state===`loading`&&O>ye?(C(A,`Expected pending action`),ce&&ce.abort(),at(de),ke(k.navigation.location,{matches:D,loaderData:fe,errors:pe,fetchers:de})):(Oe({errors:pe,loaderData:vn(k.loaderData,fe,D,pe),fetchers:de}),he=j.size>0)}async function Ue(t,n,i,s,c,u,d){let{routeId:f,path:p}=n,m=k.fetchers.get(t);Je(t,Wn(d,m?m.data:void 0),{flushSync:c});let h=new AbortController;o.unstable_customRouteDiscovery&&_e.set(t,h);let g=pn(e.history,p,h.signal);if(n.isDiscovering){let e=await vt(i,new URL(g.url).pathname,g.signal,t);if(o.unstable_customRouteDiscovery&&g.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){_e.delete(t),be.delete(t),Je(t,Kn(m?.data),{flushSync:c});return}if(e.type===`error`){Xe(t,f,e.error,{flushSync:c});return}if(e.matches)i=e.matches,n.isDiscovering=!1;else{Xe(t,f,Sn(404,{pathname:p}),{flushSync:c});return}}let _=zn(i,p);_e.set(t,h);let v=ve,y=await Ge(g,p,rn(a,l,g,p,i,_,r,s),s,t,`fetcher`),b=y[_.route.id];if(!b){for(let e of i)if(y[e.route.id]){b=y[e.route.id];break}}if(_e.get(t)===h&&_e.delete(t),!g.signal.aborted){if(Se.has(t))Je(t,Kn(void 0));else{if(jn(b)){if(ye>v){Je(t,Kn(void 0));return}M.add(t),await We(g,b,!1,`fetcher`,{preventScrollReset:u});return}An(b)?Xe(t,f,b.error):Je(t,Kn(b.data))}}}async function We(r,i,a,o,{submission:c,fetcherSubmission:l,preventScrollReset:u,replace:d}={}){a||(oe?.resolve(),oe=null),i.response.headers.has(`X-Remix-Revalidate`)&&(he=!0);let f=i.response.headers.get(`Location`);C(f,`Expected a Location header on the redirect Response`);let p=f,m=new URL(r.url);f=fn(f,m,s,e.history),bt(p,f,m,`allow-explicit`);let h=D(k.location,f,{_isRedirect:!0});if(n){let e=!1;if(i.response.headers.has(`X-Remix-Reload-Document`))e=!0;else if(Pe(f)){let n=te(t,f,!0);e=n.origin!==t.location.origin||Me(n.pathname,s)==null}if(e){d?t.location.replace(f):t.location.assign(f);return}}ce=null;let g=d===!0||i.response.headers.has(`X-Remix-Replace`)?`REPLACE`:`PUSH`,{formMethod:_,formAction:v,formEncType:y}=k.navigation;!c&&!l&&_&&v&&y&&(c=Vn(k.navigation));let b=c||l;Et.has(i.response.status)&&b&&Ln(b.formMethod)?await Fe(g,h,{submission:{...b,formAction:f},preventScrollReset:u||se,enableViewTransition:a?le:void 0,dataStrategyInitiator:o}):await Fe(g,h,{overrideNavigation:Hn(h,[],g,c),fetcherSubmission:l,preventScrollReset:u||se,enableViewTransition:a?le:void 0,dataStrategyInitiator:o})}async function Ge(e,t,n,r,i,a,o=null){let c,l={};try{c=await an(d,e,t,n,i,a,r,!1,o)}catch(e){return n.filter(e=>e.shouldLoad).forEach(t=>{l[t.route.id]={type:`error`,error:e}}),l}if(e.signal.aborted)return l;if(!Ln(e.method))for(let e of n){if(c[e.route.id]?.type===`error`)break;c.hasOwnProperty(e.route.id)||k.loaderData.hasOwnProperty(e.route.id)||k.errors&&k.errors.hasOwnProperty(e.route.id)||!e.shouldCallHandler()||(c[e.route.id]={type:`error`,result:Error(`No result returned from dataStrategy for route ${e.route.id}`)})}for(let[t,r]of Object.entries(c))if(kn(r)){let i=r.result;l[t]={type:`redirect`,response:ln(i,e,t,n,s)}}else l[t]=await cn(r);return l}async function Ke(e,t,n,r,i,a,o=null){let s=Ge(n,r,e,i,null,a,o),c=Promise.all(t.map(async e=>{if(e.matches&&e.match&&e.request&&e.controller){let t=(await Ge(e.request,e.path,e.matches,i,e.key,a,o))[e.match.route.id];return{[e.key]:t}}return Promise.resolve({[e.key]:{type:`error`,error:Sn(404,{pathname:e.path})}})}));return{loaderResults:await s,fetcherResults:(await c).reduce((e,t)=>Object.assign(e,t),{})}}function qe(){he=!0,be.forEach((e,t)=>{o.unstable_customRouteDiscovery&&e.isDiscovering||(_e.has(t)&&ge.add(t),tt(t))})}function Je(e,t,n={}){let r=new Map(k.fetchers);r.set(e,t),Oe({fetchers:r},{flushSync:(n&&n.flushSync)===!0})}function Xe(e,t,n,r={}){let i=bn(k.matches,t),a=new Map(k.fetchers);$e(a,e),Oe({errors:{[i.route.id]:n},fetchers:a},{flushSync:(r&&r.flushSync)===!0})}function Ze(e){return xe.set(e,(xe.get(e)||0)+1),Se.has(e)&&Se.delete(e),k.fetchers.get(e)||Ot}function Qe(e,t){tt(e,t?.reason),be.delete(e),ge.delete(e),Je(e,Kn(null))}function $e(e,t){let n=k.fetchers.get(t);_e.has(t)&&!(n&&n.state===`loading`&&j.has(t))&&tt(t),be.delete(t),j.delete(t),M.delete(t),Se.delete(t),ge.delete(t),e.delete(t)}function et(e){let t=(xe.get(e)||0)-1;t<=0?(xe.delete(e),Se.add(e)):xe.set(e,t),Oe({fetchers:new Map(k.fetchers)})}function tt(e,t){let n=_e.get(e);n&&(n.abort(t),_e.delete(e))}function it(e,t){for(let n of e){let e=t.get(n);C(e,`Expected fetcher: ${n}`);let r=Kn(e.data);t.set(n,r)}}function at(e){let t=[],n=!1;for(let r of M){let i=e.get(r);C(i,`Expected fetcher: ${r}`),i.state===`loading`&&(M.delete(r),t.push(r),n=!0)}return it(t,e),n}function ot(e,t){let n=[];for(let[r,i]of j)if(i0}function ct(e,t){let n=k.blockers.get(e)||kt;return Ce.get(e)!==t&&Ce.set(e,t),n}function lt(e){k.blockers.delete(e),Ce.delete(e)}function ut(e,t){let n=k.blockers.get(e)||kt;C(n.state===`unblocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`proceeding`||n.state===`blocked`&&t.state===`unblocked`||n.state===`proceeding`&&t.state===`unblocked`,`Invalid blocker state transition: ${n.state} -> ${t.state}`);let r=new Map(k.blockers);r.set(e,t),Oe({blockers:r})}function dt({currentLocation:e,nextLocation:t,historyAction:n}){if(Ce.size===0)return;Ce.size>1&&w(!1,`A router only supports one blocker at a time`);let r=Array.from(Ce.entries()),[i,a]=r[r.length-1],o=k.blockers.get(i);if(!(o&&o.state===`proceeding`)&&a({currentLocation:e,nextLocation:t,historyAction:n}))return i}function ft(e){let t=Sn(404,{pathname:e}),n=u.activeRoutes,{matches:r,route:i}=xn(n);return{notFoundMatches:r,route:i,error:t}}function pt(e,t,n){if(m=e,g=t,h=n||null,!_&&k.navigation===Dt){_=!0;let e=gt(k.location,k.matches);e!=null&&Oe({restoreScrollPosition:e})}return()=>{m=null,g=null,h=null}}function mt(e,t){return h&&h(e,t.map(e=>me(e,k.loaderData)))||e.key}function ht(e,t){if(m&&g){let n=mt(e,t);m[n]=g()}}function gt(e,t){if(m){let n=mt(e,t),r=m[n];if(typeof r==`number`)return r}return null}function _t(t,n){if(e.patchRoutesOnNavigation){if(!t)return{active:!0,matches:c.match(n,!0)||[]};if(Object.keys(t[0].params).length>0)return{active:!0,matches:c.match(n,!0)}}return{active:!1,matches:null}}async function vt(t,n,r,i){if(!e.patchRoutesOnNavigation)return{type:`success`,matches:t};let s=t;for(;;){let t=l;try{await e.patchRoutesOnNavigation({signal:r,path:n,matches:s,fetcherKey:i,patch:(e,n)=>{r.aborted||Gt(e,n,u,t,a,!1)}})}catch(e){if(o.unstable_customRouteDiscovery){if(r.aborted)return{type:`aborted`};if(e instanceof re)return{type:`cancelled`}}return{type:`error`,error:e,partialMatches:s}}if(r.aborted)return{type:`aborted`};let d=c.match(n),f=null;if(d&&(Object.keys(d[0].params).length===0||(f=c.match(n,!0),!(f&&s.lengthe.route.id===t[n].route.id)}function xt(e){l={},u.setHmrRoutes(ue(e,a,void 0,l))}function St(e,t,n=!1){Gt(e,t,u,l,a,n),u.hasHMRRoutes||Oe({})}return E={get basename(){return s},get future(){return o},get state(){return k},get routes(){return u.stableRoutes},match(e){return c.match(e)},get manifest(){return l},get window(){return t},initialize:Te,subscribe:De,enableScrollRestoration:pt,navigate:je,fetch:Ve,revalidate:Ne,createHref:t=>e.history.createHref(t),createURL:t=>e.history.createURL(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ze,resetFetcher:Qe,deleteFetcher:et,dispose:Ee,getBlocker:ct,deleteBlocker:lt,patchRoutes:St,_internalFetchControllers:_e,_internalSetRoutes:xt,_internalSetStateDoNotUseOrYouWillBreakYourApp(e){Oe(e)}},e.instrumentations&&(E=rt(E,e.instrumentations.map(e=>e.router).filter(Boolean))),E}function It(e){return e!=null&&(`formData`in e&&e.formData!=null||`body`in e&&e.body!==void 0)}function Lt(e,t,n,r,i,a){let o,s;if(i){o=[];for(let e of t)if(o.push(e),e.route.id===i){s=e;break}}else o=t,s=t[t.length-1];let c=Be(r||`.`,ze(o),Me(e.pathname,n)||e.pathname,a===`path`);if(r??(c.search=e.search,c.hash=e.hash),(r==null||r===``||r===`.`)&&s){let e=Rn(c.search);if(s.route.index&&!e)c.search=c.search?c.search.replace(/^\?/,`?index&`):`?index`;else if(!s.route.index&&e){let e=new URLSearchParams(c.search),t=e.getAll(`index`);e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();c.search=n?`?${n}`:``}}return n!==`/`&&(c.pathname=Ne({basename:n,pathname:c.pathname})),O(c)}function Rt(e,t,n){if(!n||!It(n))return{path:t};if(n.formMethod&&!In(n.formMethod))return{path:t,error:Sn(405,{method:n.formMethod})};let r=()=>({path:t,error:Sn(400,{type:`invalid-body`})}),i=(n.formMethod||`get`).toUpperCase(),a=wn(t);if(n.body!==void 0){if(n.formEncType===`text/plain`){if(!Ln(i))return r();let e=typeof n.body==`string`?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((e,[t,n])=>`${e}${t}=${n}\n`,``):String(n.body);return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:e}}}if(n.formEncType===`application/json`){if(!Ln(i))return r();try{let e=typeof n.body==`string`?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:e,text:void 0}}}catch{return r()}}}C(typeof FormData==`function`,`FormData is not available in this environment`);let o,s;if(n.formData)o=mn(n.formData),s=n.formData;else if(n.body instanceof FormData)o=mn(n.body),s=n.body;else if(n.body instanceof URLSearchParams)o=n.body,s=hn(o);else if(n.body==null)o=new URLSearchParams,s=new FormData;else try{o=new URLSearchParams(n.body),s=hn(o)}catch{return r()}let c={formMethod:i,formAction:a,formEncType:n&&n.formEncType||`application/x-www-form-urlencoded`,formData:s,json:void 0,text:void 0};if(Ln(c.formMethod))return{path:t,submission:c};let l=ee(t);return e&&l.search&&Rn(l.search)&&o.append(`index`,``),l.search=`?${o}`,{path:O(l),submission:c}}function zt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=_?An(_[1])?_[1].error:_[1].data:void 0,b=i.createURL(a.location),x=i.createURL(c),S;if(u&&a.errors){let e=Object.keys(a.errors)[0];S=o.findIndex(t=>t.route.id===e)}else if(_&&An(_[1])){let e=_[0];S=o.findIndex(t=>t.route.id===e)-1}let C=_?_[1].statusCode:void 0,w=C&&C>=400,T={currentUrl:b,currentParams:a.matches[0]?.params||{},nextUrl:x,nextParams:o[0].params,...s,actionResult:y,actionStatus:C},E=Xe(o),D=o.map((i,o)=>{let{route:s}=i,f=null;if(S!=null&&o>S)f=!1;else if(s.lazy)f=!0;else if(!Bt(s))f=!1;else if(u){let{shouldLoad:e}=Vt(s,a.loaderData,a.errors);f=e}else Ht(a.loaderData,a.matches[o],i)&&(f=!0);if(f!==null)return nn(n,r,e,c,E,i,l,t,f);let p=!1;typeof v==`boolean`?p=v:w?p=!1:d||b.pathname+b.search===x.pathname+x.search?p=!0:b.search===x.search?Ut(a.matches[o],i)&&(p=!0):p=!0;let m={...T,defaultShouldRevalidate:p};return nn(n,r,e,c,E,i,l,t,Wt(i,m),m,v)}),O=[];return m.forEach((e,s)=>{if(u||!o.some(t=>t.route.id===e.routeId)||p.has(s)||e.isDiscovering)return;let c=a.fetchers.get(s),m=c&&c.state!==`idle`&&c.data===void 0,_=g.match(e.path);if(!_){O.push({key:s,routeId:e.routeId,path:e.path,matches:null,match:null,request:null,controller:null});return}if(h.has(s))return;let y=zn(_,e.path),b=new AbortController,x=pn(i,e.path,b.signal),S=null;if(f.has(s))f.delete(s),S=rn(n,r,x,e.path,_,y,l,t);else if(m)d&&(S=rn(n,r,x,e.path,_,y,l,t));else{let i;i=typeof v==`boolean`?v:!w&&d;let a={...T,defaultShouldRevalidate:i};Wt(y,a)&&(S=rn(n,r,x,e.path,_,y,l,t,a))}S&&O.push({key:s,routeId:e.routeId,path:e.path,matches:S,match:y,request:x,controller:b})}),{dsMatches:D,revalidatingFetchers:O}}function Bt(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function Vt(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!Bt(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,i=n!=null&&n[e.id]!==void 0;if(!r&&i)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader==`function`&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!i;return{shouldLoad:a,renderFallback:a}}function Ht(e,t,n){let r=!t||n.route.id!==t.route.id,i=!e.hasOwnProperty(n.route.id);return r||i}function Ut(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith(`*`)&&e.params[`*`]!==t.params[`*`]}function Wt(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n==`boolean`)return n}return t.defaultShouldRevalidate}function Gt(e,t,n,r,i,a){let o;if(e){let t=r[e];C(t,`No route found to patch children into: routeId = ${e}`),t.children||=[],o=t.children}else o=n.activeRoutes;let s=[],c=[];if(t.forEach(e=>{let t=o.find(t=>Kt(e,t));t?c.push({existingRoute:t,newRoute:e}):s.push(e)}),s.length>0){let t=ue(s,i,[e||`_`,`patch`,String(o?.length||`0`)],r);o.push(...t)}if(a&&c.length>0)for(let e=0;et.children?.some(t=>Kt(e,t)))??!1}var qt=new WeakMap,Jt=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let i=n[t.id];if(C(i,`No route found in manifest`),!i.lazy||typeof i.lazy!=`object`)return;let a=i.lazy[e];if(!a)return;let o=qt.get(i);o||(o={},qt.set(i,o));let s=o[e];if(s)return s;let c=(async()=>{let t=ae(e),n=i[e]!==void 0;if(t)w(!t,`Route property `+e+` is not a supported lazy route property. This property will be ignored.`),o[e]=Promise.resolve();else if(n)w(!1,`Route "${i.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let t=await a();t!=null&&(Object.assign(i,{[e]:t}),Object.assign(i,r(i)))}typeof i.lazy==`object`&&(i.lazy[e]=void 0,Object.values(i.lazy).every(e=>e===void 0)&&(i.lazy=void 0))})();return o[e]=c,c.catch(()=>{o[e]===c&&delete o[e]}),c},Yt=new WeakMap;function Xt(e,t,n,r,i){let a=n[e.id];if(C(a,`No route found in manifest`),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy==`function`){let t=Yt.get(a);if(t)return{lazyRoutePromise:t,lazyHandlerPromise:t};let n=(async()=>{C(typeof e.lazy==`function`,`No lazy route function found`);let t=await e.lazy(),n={};for(let e in t){let r=t[e];if(r===void 0)continue;let i=se(e),o=a[e]!==void 0;i?w(!i,`Route property `+e+` is not a supported property to be returned from a lazy route function. This property will be ignored.`):o?w(!o,`Route "${a.id}" has a static property "${e}" defined but its lazy function is also returning a value for this property. The lazy route property "${e}" will be ignored.`):n[e]=r}Object.assign(a,n),Object.assign(a,{...r(a),lazy:void 0})})();return Yt.set(a,n),n.catch(()=>{Yt.get(a)===n&&Yt.delete(a)}),{lazyRoutePromise:n,lazyHandlerPromise:n}}let o=Object.keys(e.lazy),s=[],c;for(let a of o){if(i&&i.includes(a))continue;let o=Jt({key:a,route:e,manifest:n,mapRouteProperties:r});o&&(s.push(o),a===t&&(c=o))}let l=s.length>0?Promise.all(s).then(()=>{}):void 0;return l?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:l,lazyHandlerPromise:c}}async function P(e){let t=e.matches.filter(e=>e.shouldLoad),n={};return(await Promise.all(t.map(e=>e.resolve()))).forEach((e,r)=>{n[t[r].route.id]=e}),n}async function Zt(e){return e.matches.some(e=>e.route.middleware)?Qt(e,()=>P(e)):P(e)}function Qt(e,t){return $t(e,t,e=>{if(Fn(e))throw e;return e},Dn,n);async function n(t,n,r){if(r)return Object.assign(r.value,{[n]:{type:`error`,result:t}});{let{matches:r}=e,i=Math.min(Math.max(r.findIndex(e=>e.route.id===n),0),Math.max(r.findIndex(e=>e.shouldCallHandler()),0)),a=r[i].route.id;for(let e of r.slice(0,i+1))try{await e._lazyPromises?.route}catch{a=e.route.id;break}return{[bn(r,a).route.id]:{type:`error`,result:t}}}}}async function $t(e,t,n,r,i){let{matches:a,...o}=e;return await en(o,a.flatMap(e=>e.route.middleware?e.route.middleware.map(t=>[e.route.id,t]):[]),t,n,r,i)}async function en(e,t,n,r,i,a,o=0){let{request:s}=e;if(s.signal.aborted)throw s.signal.reason??Error(`Request aborted: ${s.method} ${s.url}`);let c=t[o];if(!c)return await n();let[l,u]=c,d,f=async()=>{if(d)throw Error("You may only call `next()` once per middleware");try{return d={value:await en(e,t,n,r,i,a,o+1)},d.value}catch(e){return d={value:await a(e,l,d)},d.value}};try{let t=await u(e,f),n=t==null?void 0:r(t);return i(n)?n:d?n??d.value:(d={value:await f()},d.value)}catch(e){return await a(e,l,d)}}function tn(e,t,n,r,i){let a=Jt({key:`middleware`,route:r.route,manifest:t,mapRouteProperties:e}),o=Xt(r.route,Ln(n.method)?`action`:`loader`,t,e,i);return{middleware:a,route:o.lazyRoutePromise,handler:o.lazyHandlerPromise}}function nn(e,t,n,r,i,a,o,s,c,l=null,u){let d=!1,f=tn(e,t,n,a,o);return{...a,_lazyPromises:f,shouldLoad:c,shouldRevalidateArgs:l,shouldCallHandler(e){return d=!0,l?typeof u==`boolean`?Wt(a,{...l,defaultShouldRevalidate:u}):typeof e==`boolean`?Wt(a,{...l,defaultShouldRevalidate:e}):Wt(a,l):c},resolve(e){let{lazy:t,loader:o,middleware:l}=a.route,u=d||c||e&&!Ln(n.method)&&(t||o),p=l&&l.length>0&&!o&&!t;return u&&(Ln(n.method)||!p)?on({request:n,path:r,pattern:i,match:a,lazyHandlerPromise:f?.handler,lazyRoutePromise:f?.route,handlerOverride:e,scopedContext:s}):Promise.resolve({type:`data`,result:void 0})}}}function rn(e,t,n,r,i,a,o,s,c=null){return i.map(l=>l.route.id===a.route.id?nn(e,t,n,r,Xe(i),l,o,s,!0,c):{...l,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:tn(e,t,n,l,o),resolve:()=>Promise.resolve({type:`data`,result:void 0})})}async function an(e,t,n,r,i,a,o,s,c=null){r.some(e=>e._lazyPromises?.middleware)&&await Promise.all(r.map(e=>e._lazyPromises?.middleware));let l={request:t,url:Ze(t,n),pattern:Xe(r),params:r[0].params,context:o,matches:r,unstable_initiator:a,unstable_navigationType:a===`navigation`?c:null},u=s?()=>{throw Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:e=>{let t=l;return Qt(t,()=>e({...t,fetcherKey:i,runClientMiddleware:()=>{throw Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))},d=await e({...l,fetcherKey:i,runClientMiddleware:u});try{await Promise.all(r.flatMap(e=>[e._lazyPromises?.handler,e._lazyPromises?.route]))}catch{}return d}async function on({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:i,lazyRoutePromise:a,handlerOverride:o,scopedContext:s}){let c,l,u=Ln(e.method),d=u?`action`:`loader`,f=i=>{let a,c=new Promise((e,t)=>a=t);l=()=>a(),e.signal.addEventListener(`abort`,l);let u=a=>typeof i==`function`?i({request:e,url:Ze(e,t),pattern:n,params:r.params,context:s},...a===void 0?[]:[a]):Promise.reject(Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${r.route.id}]`)),f=(async()=>{try{return{type:`data`,result:await(o?o(e=>u(e)):u())}}catch(e){return{type:`error`,result:e}}})();return Promise.race([f,c])};try{let t=u?r.route.action:r.route.loader;if(i||a){if(t){let e,[n]=await Promise.all([f(t).catch(t=>{e=t}),i,a]);if(e!==void 0)throw e;c=n}else{await i;let t=u?r.route.action:r.route.loader;if(t)[c]=await Promise.all([f(t),a]);else if(d===`action`){let t=new URL(e.url),n=t.pathname+t.search;throw Sn(405,{method:e.method,pathname:n,routeId:r.route.id})}else return await a,{type:`data`,result:void 0}}}else if(t)c=await f(t);else{let t=new URL(e.url);throw Sn(404,{pathname:t.pathname+t.search})}}catch(e){return{type:`error`,result:e}}finally{l&&e.signal.removeEventListener(`abort`,l)}return c}async function sn(e){let t=e.headers.get(`Content-Type`);return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function cn(e){let{result:t,type:n}=e;if(Nn(t)){let e;try{e=await sn(t)}catch(e){return{type:`error`,error:e}}return n===`error`?{type:`error`,error:new Je(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:`data`,data:e,statusCode:t.status,headers:t.headers}}return n===`error`?Mn(t)?t.data instanceof Error?{type:`error`,error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:En(t),statusCode:Ye(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:t,statusCode:Ye(t)?t.status:void 0}:Mn(t)?{type:`data`,data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`data`,data:t}}function ln(e,t,n,r,i){let a=e.headers.get(`Location`);if(C(a,`Redirects returned/thrown from loaders/actions must have a Location header`),!Pe(a)){let o=r.slice(0,r.findIndex(e=>e.route.id===n)+1);a=Lt(new URL(t.url),o,i,a),e.headers.set(`Location`,a)}return e}var un=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function dn(e){try{return un.includes(new URL(e).protocol)}catch{return!1}}function fn(e,t,n,r){if(Pe(e)){let r=e,i=v.test(r)?new URL(y(r,t.protocol)):new URL(r);if(dn(i.toString()))throw Error(`Invalid redirect location`);let a=Me(i.pathname,n)!=null;if(i.origin===t.origin&&a)return Ve(i.pathname)+i.search+i.hash}try{if(dn(r.createURL(e).toString()))throw Error(`Invalid redirect location`)}catch{}return e}function pn(e,t,n,r){let i=e.createURL(wn(t)).toString(),a={signal:n};if(r&&Ln(r.formMethod)){let{formMethod:e,formEncType:t}=r;a.method=e.toUpperCase(),t===`application/json`?(a.headers=new Headers({"Content-Type":t}),a.body=JSON.stringify(r.json)):a.body=t===`text/plain`?r.text:t===`application/x-www-form-urlencoded`&&r.formData?mn(r.formData):r.formData}return new Request(i,a)}function mn(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r==`string`?r:r.name);return t}function hn(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function gn(e,t,n,r=!1,i=!1){let a={},o=null,s,c=!1,l={},u=n&&An(n[1])?n[1].error:void 0;return e.forEach(n=>{if(!(n.route.id in t))return;let d=n.route.id,f=t[d];if(C(!jn(f),`Cannot handle redirect results in processLoaderData`),An(f)){let t=f.error;if(u!==void 0&&(t=u,u=void 0),o||={},i)o[d]=t;else{let n=bn(e,d);o[n.route.id]??(o[n.route.id]=t)}r||(a[d]=jt),c||(c=!0,s=Ye(f.error)?f.error.status:500),f.headers&&(l[d]=f.headers)}else a[d]=f.data,f.statusCode&&f.statusCode!==200&&!c&&(s=f.statusCode),f.headers&&(l[d]=f.headers)}),u!==void 0&&n&&(o={[n[0]]:u},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:o,statusCode:s||200,loaderHeaders:l}}function _n(e,t,n,r,i,a,o){let{loaderData:s,errors:c}=gn(t,n,r);return i.filter(e=>!e.matches||e.matches.some(e=>e.shouldLoad)).forEach(t=>{let{key:n,routeId:r,controller:i}=t;if(i&&i.signal.aborted)return;let s=a[n];if(C(s,`Did not find corresponding fetcher result`),An(s)){let t=bn(e.matches,r);c&&c[t.route.id]||(c={...c,[t.route.id]:s.error}),o.delete(n)}else if(jn(s))C(!1,`Unhandled fetcher revalidation redirect`);else{let e=Kn(s.data);o.set(n,e)}}),{loaderData:s,errors:c}}function vn(e,t,n,r){let i=Object.entries(t).filter(([,e])=>e!==jt).reduce((e,[t,n])=>(e[t]=n,e),{}),a=0;for(let o of n){let n=o.route.id;if(!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&o.route.loader&&(i[n]=e[n],a++),r&&r.hasOwnProperty(n))break}return Object.keys(t).length===0&&a===Object.keys(e).length?e:i}function yn(e){return e?An(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function bn(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>e.route.ErrorBoundary!=null||e.route.errorElement!=null)||e[0]}function xn(e){let t=e.length===1?e[0]:e.find(e=>e.index||!e.path||e.path===`/`)||{id:`__shim-error-route__`};return{matches:[{params:{},pathname:``,pathnameBase:``,route:t}],route:t}}function Sn(e,{pathname:t,routeId:n,method:r,type:i,message:a}={}){let o=`Unknown Server Error`,s=`Unknown @remix-run/router error`;return e===400?(o=`Bad Request`,r&&t&&n?s=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:i===`invalid-body`&&(s=`Unable to encode submission body`)):e===403?(o=`Forbidden`,s=`Route "${n}" does not match URL "${t}"`):e===404?(o=`Not Found`,s=`No route matches URL "${t}"`):e===405&&(o=`Method Not Allowed`,r&&t&&n?s=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(s=`Invalid request method "${r.toUpperCase()}"`)),new Je(e||500,o,Error(s),!0)}function Cn(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[n,r]=t[e];if(jn(r))return{key:n,result:r}}}function wn(e){return O({...typeof e==`string`?ee(e):e,hash:``})}function Tn(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===``?t.hash!==``:e.hash===t.hash||t.hash!==``}function En(e){return new Je(e.init?.status??500,e.init?.statusText??`Internal Server Error`,e.data)}function Dn(e){return typeof e==`object`&&!!e&&Object.entries(e).every(([e,t])=>typeof e==`string`&&On(t))}function On(e){return typeof e==`object`&&!!e&&`type`in e&&`result`in e&&(e.type===`data`||e.type===`error`)}function kn(e){return Nn(e.result)&&Tt.has(e.result.status)}function An(e){return e.type===`error`}function jn(e){return(e&&e.type)===`redirect`}function Mn(e){return typeof e==`object`&&!!e&&`type`in e&&`data`in e&&`init`in e&&e.type===`DataWithResponseInit`}function Nn(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function Pn(e){return Tt.has(e)}function Fn(e){return Nn(e)&&Pn(e.status)&&e.headers.has(`Location`)}function In(e){return wt.has(e.toUpperCase())}function Ln(e){return St.has(e.toUpperCase())}function Rn(e){return new URLSearchParams(e).getAll(`index`).some(e=>e===``)}function zn(e,t){let n=typeof t==`string`?ee(t).search:t.search;if(e[e.length-1].route.index&&Rn(n||``))return e[e.length-1];let r=Re(e);return r[r.length-1]}function Bn(e,t,n){return{url:Ze(e.createURL(t),t),pattern:n?Xe(n):``,params:n?.[0]?.params?{...n[0].params}:{}}}function Vn(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:a,json:o}=e;if(t&&n&&r){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function Hn(e,t,n,r){return r?{state:`loading`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:`loading`,location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Un(e,t,n,r){return{state:`submitting`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function Wn(e,t){return e?{state:`loading`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:`loading`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Gn(e,t){return{state:`submitting`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Kn(e){return{state:`idle`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function qn(e,t){try{let n=e.sessionStorage.getItem(At);if(n){let e=JSON.parse(n);for(let[n,r]of Object.entries(e||{}))r&&Array.isArray(r)&&t.set(n,new Set(r||[]))}}catch{}}function Jn(e,t){if(t.size>0){let n={};for(let[e,r]of t)n[e]=[...r];try{e.sessionStorage.setItem(At,JSON.stringify(n))}catch(e){w(!1,`Failed to save applied view transitions in sessionStorage (${e}).`)}}}function Yn(){let e,t,n=new Promise((r,i)=>{e=async e=>{r(e);try{await n}catch{}},t=async e=>{i(e);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var Xn=A.createContext(null);Xn.displayName=`DataRouter`;var Zn=A.createContext(null);Zn.displayName=`DataRouterState`;var Qn=A.createContext(null);Qn.displayName=`DataRouterData`;var $n=A.createContext(null);$n.displayName=`DataRouterNavigation`;var er=A.createContext(!1);function tr(){return A.useContext(er)}var nr=A.createContext({isTransitioning:!1});nr.displayName=`ViewTransition`;var rr=A.createContext(null);rr.displayName=`Fetchers`;var ir=A.createContext(null);ir.displayName=`Await`;var ar=A.createContext(null);ar.displayName=`Navigation`;var or=A.createContext(null);or.displayName=`Location`;var sr=A.createContext({outlet:null,matches:[],isDataRoute:!1});sr.displayName=`Route`;var cr=A.createContext(!1);cr.displayName=`IsDataRoute`;var lr=A.createContext(void 0);lr.displayName=`RouteId`;var ur=A.createContext(null);ur.displayName=`RouteError`;var dr=`REACT_ROUTER_ERROR`,fr=`REDIRECT`,pr=`ROUTE_ERROR_RESPONSE`;function mr(e){if(e.startsWith(`${dr}:${fr}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function hr(e){if(e.startsWith(`${dr}:${pr}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Je(t.status,t.statusText,t.data)}catch{}}function gr(e,{relative:t}={}){C(_r(),`useHref() may be used only in the context of a component.`);let{basename:n,navigator:r}=A.useContext(ar),{hash:i,pathname:a,search:o}=wr(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:He([n,a])),r.createHref({pathname:s,search:o,hash:i})}function _r(){return A.useContext(or)!=null}function vr(){return C(_r(),`useLocation() may be used only in the context of a component.`),A.useContext(or).location}function yr(e){C(_r(),`useMatch() may be used only in the context of a component.`);let{pathname:t}=vr();return A.useMemo(()=>Oe(e,je(t)),[t,e])}var br=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function xr(){return A.useContext(cr)?Hr():Sr()}function Sr(){C(_r(),`useNavigate() may be used only in the context of a component.`);let e=A.useContext(Xn),{basename:t,navigator:n}=A.useContext(ar),{matches:r}=A.useContext(sr),{pathname:i}=vr(),a=JSON.stringify(ze(r)),o=A.useRef(!1);return A.useLayoutEffect(()=>{o.current=!0}),A.useCallback((r,s={})=>{if(w(o.current,br),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Be(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:He([t,c.pathname])),bt(typeof r==`string`?r:O(r),n.createHref(c),_t(n),`reject`),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}A.createContext(null);function Cr(){let{matches:e}=A.useContext(sr);return e[e.length-1]?.params??{}}function wr(e,{relative:t}={}){let{matches:n}=A.useContext(sr),{pathname:r}=vr(),i=JSON.stringify(ze(n));return A.useMemo(()=>Be(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Tr(e,t){return Er(e,t)}function Er(e,t,n){C(_r(),`useRoutes() may be used only in the context of a component.`);let{navigator:r}=A.useContext(ar),{matches:i}=A.useContext(sr),a=i[i.length-1],o=a?a.params:{};a&&a.pathname;let s=a?a.pathnameBase:`/`;a&&a.route;let c=vr(),l;if(t){let e=typeof t==`string`?ee(t):t;C(s===`/`||e.pathname?.startsWith(s),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${s}" but pathname "${e.pathname}" was given in the \`location\` prop.`),l=e}else l=c;let u=l.pathname||`/`,d=u;if(s!==`/`){let e=s.replace(/^\//,``).split(`/`);d=`/`+u.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let f;f=n?n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):n.router.match(n.state.location):fe(e,{pathname:d});let p=Nr(f&&f.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:He([s,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?s:He([s,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&p?A.createElement(or.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...l},navigationType:`POP`}},p):p}function Dr(){let e=zr(),t=Ye(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return A.createElement(A.Fragment,null,A.createElement(`h2`,null,`Unexpected Application Error!`),A.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?A.createElement(`pre`,{style:{padding:`0.5rem`,backgroundColor:`rgba(200,200,200, 0.5)`}},n):null,null)}var Or=A.createElement(Dr,null),kr=class extends A.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=er;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=hr(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:A.createElement(sr.Provider,{value:this.props.routeContext},A.createElement(cr.Provider,{value:this.props.routeContext.isDataRoute},A.createElement(lr.Provider,{value:this.props.routeContext.matches[this.props.routeContext.matches.length-1]?.route.id},A.createElement(ur.Provider,{value:e,children:this.props.component}))));return this.context?A.createElement(jr,{error:e},t):t}},Ar=new WeakMap;function jr({children:e,error:t}){let{basename:n,navigator:r}=A.useContext(ar);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=mr(t.digest);if(e){let i=Ar.get(t);if(i)throw i;let a=$e(e.location,n),o=a.absoluteURL||a.to;if(bt(e.location,o,_t(r),`allow-explicit`),dn(o))throw Error(`Invalid redirect location`);if(Qe&&!Ar.get(t)){if(a.isExternal||e.reloadDocument)window.location.href=o;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw Ar.set(t,n),n}}return A.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${o}`})}}return e}function Mr({routeContext:e,match:t,children:n}){let r=A.useContext(Xn);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),A.createElement(sr.Provider,{value:e},A.createElement(cr.Provider,{value:e.isDataRoute},A.createElement(lr.Provider,{value:t.route.id},n)))}function Nr(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);C(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Xe(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||Or,o&&(s<0&&c===0?(Wr(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?A.createElement(n.route.Component,null):n.route.element?n.route.element:e,A.createElement(Mr,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?A.createElement(kr,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Pr(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Fr(e){let t=A.useContext(Xn);return C(t,Pr(e)),t}function Ir(e){let t=A.useContext(Zn);return C(t,Pr(e)),t}function Lr(e){let t=A.useContext(Qn);return C(t,Pr(e)),t}function Rr(e){let t=A.useContext(lr);return C(t,`${e} can only be used on routes that contain a unique "id"`),t}function zr(){let e=A.useContext(ur),t=Lr(`useRouteError`),n=Rr(`useRouteError`);return e===void 0?t.errors?.[n]:e}var Br=0;function Vr(e){let{router:t,basename:n}=Fr(`useBlocker`),r=Ir(`useBlocker`),[i,a]=A.useState(``),o=A.useCallback(t=>{if(typeof e!=`function`)return!!e;if(n===`/`)return e(t);let{currentLocation:r,nextLocation:i,historyAction:a}=t;return e({currentLocation:{...r,pathname:Me(r.pathname,n)||r.pathname},nextLocation:{...i,pathname:Me(i.pathname,n)||i.pathname},historyAction:a})},[n,e]);return A.useEffect(()=>{let e=String(++Br);return a(e),()=>t.deleteBlocker(e)},[t]),A.useEffect(()=>{i!==``&&t.getBlocker(i,o)},[t,i,o]),i&&r.blockers.has(i)?r.blockers.get(i):kt}function Hr(){let{router:e}=Fr(`useNavigate`),t=Rr(`useNavigate`),n=A.useRef(!1);return A.useLayoutEffect(()=>{n.current=!0}),A.useCallback(async(r,i={})=>{w(n.current,br),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Ur={};function Wr(e,t,n){!t&&!Ur[e]&&(Ur[e]=!0,w(!1,n))}function Gr(e,t){if(e===!1||e==null)throw Error(t)}function Kr(e,t,n){let r=typeof e==`string`?new URL(e,n??(typeof window>`u`?`server://singlefetch/`:window.location.origin)):new URL(e);return n&&r.origin!==n&&(r=new URL(r.pathname+r.search+r.hash,n)),r.pathname.endsWith(`/`)?r.pathname=`${r.pathname}_.${t}`:r.pathname=`${r.pathname}.${t}`,r}async function qr(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function Jr(e){return e!=null&&typeof e.page==`string`}function Yr(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function Xr(e,t,n){return ti((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await qr(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Yr).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Zr(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Qr(e,t,{includeHydrateFallback:n}={}){return $r(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function $r(e){return[...new Set(e)]}function ei(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function ti(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Jr(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(ei(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}var ni={};function ri(e,t){!e&&!ni[t]&&(ni[t]=!0,console.warn(t))}var ii=A.createContext(void 0);ii.displayName=`FrameworkContext`;function ai(){let e=A.useContext(ii);return Gr(e,`You must render this element inside a element`),e}function oi(e,t){let n=A.useContext(ii),[r,i]=A.useState(!1),[a,o]=A.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=A.useRef(null);A.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),A.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:si(s,p),onBlur:si(c,m),onMouseEnter:si(l,p),onMouseLeave:si(u,m),onTouchStart:si(d,p)}]:[a,f,{}]:[!1,f,{}]}function si(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function ci({page:e,...t}){let n=tr(),{nonce:r}=ai(),{router:i}=Fr(`PrefetchPageLinks`),a=A.useMemo(()=>i.match(e),[i,i.routes,e]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?A.createElement(ui,{page:e,matches:a,...t}):A.createElement(di,{page:e,matches:a,...t})):null}function li(e){let{manifest:t,routeModules:n}=ai(),[r,i]=A.useState([]);return A.useEffect(()=>{let r=!1;return Xr(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function ui({page:e,matches:t,...n}){let r=vr(),{unstable_apiServerOrigin:i}=ai(),a=A.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=Kr(e,`rsc`,i),a=!1,o=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?a=!0:o.push(e.route.id);return a&&o.length>0&&n.searchParams.set(`_routes`,o.join(`,`)),[i?n.toString():n.pathname+n.search]},[e,r,t,i]);return A.createElement(A.Fragment,null,a.map(e=>A.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function di({page:e,matches:t,...n}){let r=vr(),{manifest:i,routeModules:a,unstable_apiServerOrigin:o}=ai(),{matches:s}=Ir(`PrefetchPageLinks`),{loaderData:c}=Lr(`PrefetchPageLinks`),l=A.useMemo(()=>Zr(e,t,s,i,r,`data`),[e,t,s,i,r]),u=A.useMemo(()=>Zr(e,t,s,i,r,`assets`),[e,t,s,i,r]),d=A.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,s=!1;if(t.forEach(e=>{let t=i.routes[e.route.id];t&&t.hasLoader&&(!l.some(t=>t.route.id===e.route.id)&&e.route.id in c&&a[e.route.id]?.shouldRevalidate||t.hasClientLoader?s=!0:n.add(e.route.id))}),n.size===0)return[];let u=Kr(e,`data`,o);return s&&n.size>0&&u.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[o?u.toString():u.pathname+u.search]},[c,r,i,l,t,e,a,o]),f=A.useMemo(()=>Qr(u,i),[u,i]),p=li(u);return A.createElement(A.Fragment,null,d.map(e=>A.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),f.map(e=>A.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),p.map(({key:e,link:t})=>A.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function fi(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}var pi=[`HydrateFallback`,`hydrateFallbackElement`],mi=class{status=`pending`;promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.status===`pending`&&(this.status=`resolved`,e(t))},this.reject=e=>{this.status===`pending`&&(this.status=`rejected`,t(e))}})}};function hi(e,t){e.ready.catch(e=>{if(!(t.visibilityState===`hidden`||typeof e==`object`&&e&&`name`in e&&e.name===`AbortError`))throw e})}function gi({router:e,flushSync:t,onError:n,useTransitions:r}){r=tr()||r;let[i,a]=A.useState(e.state),[o,s]=(0,A.useOptimistic)(i),c=A.useRef(o),[l,u]=A.useState(),[d,f]=A.useState({isTransitioning:!1}),[p,m]=A.useState(),[h,g]=A.useState(),[_,v]=A.useState(),y=A.useRef(new Map),b=A.useRef(new WeakSet),x=A.useCallback((i,{deletedFetchers:o,newErrors:l,flushSync:d,viewTransitionOpts:_})=>{c.current=i,l&&i.errors&&Pt.has(i.errors)&&(b.current.has(i.errors)?l=null:b.current.add(i.errors)),l&&n&&Object.values(l).forEach(e=>n(e,{location:i.location,params:i.matches[0]?.params??{},pattern:Xe(i.matches)})),i.fetchers.forEach((e,t)=>{e.data!==void 0&&y.current.set(t,e.data)}),o.forEach(e=>y.current.delete(e)),ri(d===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let x=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition==`function`;if(ri(_==null||x,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!_||!x)t&&d?t(()=>a(i)):r===!1?a(i):A.startTransition(()=>{r===!0&&s(e=>_i(e,i)),a(i)});else if(t&&d){t(()=>{h&&(p?.resolve(),h.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:_.currentLocation,nextLocation:_.nextLocation})});let n=e.window.document.startViewTransition(()=>{t(()=>a(i))});hi(n,e.window.document),n.finished.finally(()=>{t(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})})}),t(()=>g(n))}else h?(p?.resolve(),h.skipTransition(),v({state:i,currentLocation:_.currentLocation,nextLocation:_.nextLocation})):(u(i),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}))},[e.window,t,h,p,r,s,n]);A.useLayoutEffect(()=>e.subscribe(x),[e,x]),A.useLayoutEffect(()=>{let t=e.state.errors,n=t?Pt.get(t):null;(c.current!==e.state||t&&n&&!b.current.has(t))&&x(e.state,{deletedFetchers:[],flushSync:!1,newErrors:n??null})},[e,x]),A.useEffect(()=>{d.isTransitioning&&!d.flushSync&&m(new mi)},[d]),A.useEffect(()=>{if(p&&l&&e.window){let t=l,n=p.promise,i=e.window.document.startViewTransition(async()=>{r===!1?a(t):A.startTransition(()=>{r===!0&&s(e=>_i(e,t)),a(t)}),await n});hi(i,e.window.document),i.finished.finally(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})}),g(i)}},[l,p,e.window,r,s]),A.useEffect(()=>{p&&l&&o.location.key===l.location.key&&p.resolve()},[p,h,o.location,l]),A.useEffect(()=>{!d.isTransitioning&&_&&(u(_.state),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}),v(void 0))},[d.isTransitioning,_]);let S=A.useMemo(()=>({createHref:e.createHref,createURL:e.createURL,encodeLocation:e.encodeLocation,go:t=>e.navigate(t),push:(t,n,r)=>e.navigate(t,{state:n,preventScrollReset:r?.preventScrollReset}),replace:(t,n,r)=>e.navigate(t,{replace:!0,state:n,preventScrollReset:r?.preventScrollReset})}),[e]),C=e.basename||`/`,w=A.useMemo(()=>({router:e,navigator:S,static:!1,basename:C,onError:n}),[e,S,C,n]),T=A.useMemo(()=>({historyAction:o.historyAction,location:o.location,matches:o.matches,initialized:o.initialized,renderFallback:o.renderFallback,restoreScrollPosition:o.restoreScrollPosition,preventScrollReset:o.preventScrollReset,blockers:o.blockers}),[o.historyAction,o.location,o.matches,o.initialized,o.renderFallback,o.restoreScrollPosition,o.preventScrollReset,o.blockers]),E=A.useMemo(()=>({navigation:o.navigation,revalidation:o.revalidation}),[o.navigation,o.revalidation]),D=A.useMemo(()=>({loaderData:o.loaderData,actionData:o.actionData,errors:o.errors}),[o.loaderData,o.actionData,o.errors]),O=A.useMemo(()=>({fetchers:o.fetchers,fetcherData:y.current}),[o.fetchers]);return A.createElement(A.Fragment,null,A.createElement(Xn.Provider,{value:w},A.createElement(Zn.Provider,{value:T},A.createElement($n.Provider,{value:E},A.createElement(Qn.Provider,{value:D},A.createElement(rr.Provider,{value:O},A.createElement(nr.Provider,{value:d},A.createElement(bi,{basename:C,location:o.location,navigationType:o.historyAction,navigator:S,useTransitions:r},A.createElement(vi,{routes:e.routes,manifest:e.manifest,state:o,isStatic:!1,onError:n})))))))),null)}function _i(e,t){return{...e,navigation:t.navigation.state===`idle`?e.navigation:t.navigation,revalidation:t.revalidation===`idle`?e.revalidation:t.revalidation,actionData:t.navigation.state===`submitting`?e.actionData:t.actionData,fetchers:t.fetchers}}var vi=A.memo(yi);function yi({routes:e,manifest:t,state:n,isStatic:r,onError:i}){let a=A.useContext(Xn);C(a,`You must render this element inside a element`);let o=A.useContext(ii)?.routeDiscoveryRuntime;return A.useEffect(()=>{n.initialized&&o?.markReady()},[n.initialized,o]),Er(e,void 0,{router:a.router,manifest:t,state:n,isStatic:r,onError:i})}function F(e){C(!1,`A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .`)}function bi({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){C(!_r(),`You cannot render a inside another . You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=A.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=ee(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=A.useMemo(()=>{let e=Me(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return w(h!=null,` is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the won't render anything.`),h==null?null:A.createElement(ar.Provider,{value:c},A.createElement(or.Provider,{children:t,value:h}))}function xi({children:e,location:t}){return Tr(Si(e),t)}A.Component;function Si(e,t=[]){let n=[];return A.Children.forEach(e,(e,r)=>{if(!A.isValidElement(e))return;let i=[...t,r];if(e.type===A.Fragment){n.push.apply(n,Si(e.props.children,i));return}C(e.type===F,`[${typeof e.type==`string`?e.type:e.type.name}] is not a component. All component children of must be a or `);let a=e.props;C(!a.index||!a.children,`An index route cannot have child routes.`);let o={id:a.id||i.join(`-`),caseSensitive:a.caseSensitive,element:a.element,Component:a.Component,index:a.index,path:a.path,middleware:a.middleware,loader:a.loader,action:a.action,hydrateFallbackElement:a.hydrateFallbackElement,HydrateFallback:a.HydrateFallback,errorElement:a.errorElement,ErrorBoundary:a.ErrorBoundary,shouldRevalidate:a.shouldRevalidate,handle:a.handle,lazy:a.lazy};a.children&&(o.children=Si(a.children,i)),n.push(o)}),n}var Ci=`application/x-www-form-urlencoded`;function wi(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Ti(e){return wi(e)&&e.tagName.toLowerCase()===`button`}function Ei(e){return wi(e)&&e.tagName.toLowerCase()===`form`}function Di(e){return wi(e)&&e.tagName.toLowerCase()===`input`}function Oi(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function ki(e,t){return e.button===0&&(!t||t===`_self`)&&!Oi(e)}function Ai(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function ji(e,t){let n=Ai(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Mi=null;function Ni(){if(Mi===null)try{new FormData(document.createElement(`form`),0),Mi=!1}catch{Mi=!0}return Mi}var Pi=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Fi(e){return e!=null&&!Pi.has(e)?(w(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${Ci}"`),null):e}function Ii(e,t){let n,r,i,a,o;if(Ei(e)){let o=e.getAttribute(`action`);r=o?Me(o,t):null,n=e.getAttribute(`method`)||`get`,i=Fi(e.getAttribute(`enctype`))||Ci,a=new FormData(e)}else if(Ti(e)||Di(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a