diff --git a/cmd/fcd/reviews_test.go b/cmd/fcd/reviews_test.go index 96cbd59b..a9c716cd 100644 --- a/cmd/fcd/reviews_test.go +++ b/cmd/fcd/reviews_test.go @@ -162,7 +162,8 @@ func TestDaemonExplicitCLICatalogStartsAndStopsWithoutProviderWork(t *testing.T) case <-stdout.ready: case code := <-done: t.Fatalf("native startup failed: %d %s", code, stderr.String()) - case <-time.After(5 * time.Second): + // Cold SQLite schema initialization can exceed five seconds under -race. + case <-time.After(20 * time.Second): t.Fatal("native startup deadline") } var started map[string]string diff --git a/docs/mcp.md b/docs/mcp.md index af10ec30..93c4e4b2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -93,6 +93,10 @@ Startup validates configuration without opening the credential or contacting the | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | | `wait_for_messages` | Required event cursor; optional limit 1–100 and wait_seconds 1–50, default 20/25. One new-message event page or quiet timeout over a call-owned persistent stream. | | `review_execution_read` | No fields; stored execution configuration and revision, without provider work. | +| `review_scheduling_read` | No fields; stored project scheduling settings, revision and paused queued PRs, without provider work. | +| `review_scheduling_configure` | Required idempotency_key/expected_revision/automatic_hosted; optional automatic_cli preserves its existing value when omitted. Project management capability configures [default-off automatic scheduling](review-scheduling.md), including authorization for later provider work within existing review limits. | +| `review_pull_scheduling_read` | Required pull_number; reads the per-PR pause for new and undispatched explicit and automatic reviews, and its revision. | +| `review_pull_scheduling_update` | Required idempotency_key/pull_number/expected_revision/paused; optional reason is accepted only when pausing. Changes the [per-PR scheduling pause](review-scheduling.md#pause-a-pr) while preserving review limits and retained request controls. | | `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. | @@ -144,7 +148,7 @@ Review queue/run/attempt lists default to five entries; other limits use the API [Job progress](job-progress.md) owns update/checklist content limits, independent revisions, explicit archives and integration proof. Checklist replacement can remove or replace effective items and is annotated destructive; its immutable history remains available. Job updates and checklist operations perform no provider work. -Mutations require the caller to retain an explicit key and request; the adapter never generates a replacement key or automatically retries. Job edits require the current expected revision; empty brief or worker clears that field. A dispatched write with a lost, canceled or invalid response returns `outcome_unknown` when a tool result can be delivered. Host cancellation may suppress that result, so absence of a reply is never proof of rollback. Recover using the original request, key and binding. The [MCP annotations](https://modelcontextprotocol.io/specification/2025-11-25/schema#toolannotations) distinguish reads from writes. Repeating identical arguments retains the same explicit key and has no additional effect; job edits and review decision/fix corrections can replace effective fields while retained history remains; creation/checkpoint/send/receipt transitions add records or handling state. Job, message and evidence controls operate within the configured service. `review_start`, `review_request`, `review_source_refresh`, `review_checkpoint_publish` and `review_checkpoint_recover` are annotated open-world because they authorize external provider work; a queued receipt does not establish started or completed execution. The [CLI recovery rules](development.md#explicit-agent-mutations) also apply. +Mutations require the caller to retain an explicit key and request; the adapter never generates a replacement key or automatically retries. Job edits require the current expected revision; empty brief or worker clears that field. A dispatched write with a lost, canceled or invalid response returns `outcome_unknown` when a tool result can be delivered. Host cancellation may suppress that result, so absence of a reply is never proof of rollback. Recover using the original request, key and binding. The [MCP annotations](https://modelcontextprotocol.io/specification/2025-11-25/schema#toolannotations) distinguish reads from writes. Repeating identical arguments retains the same explicit key and has no additional effect; job edits and review decision/fix corrections can replace effective fields while retained history remains; creation/checkpoint/send/receipt transitions add records or handling state. Job, message and evidence controls operate within the configured service. `review_scheduling_configure`, `review_start`, `review_request`, `review_source_refresh`, `review_checkpoint_publish` and `review_checkpoint_recover` are annotated open-world because they authorize external provider work; a queued receipt does not establish started or completed execution. `review_pull_scheduling_update` is also annotated open-world: resuming a PR can make it eligible for later automatic provider work within existing controls, but the update itself does not dispatch a review. The [CLI recovery rules](development.md#explicit-agent-mutations) also apply. Explicit message, review-result, source-refresh and checkpoint waits are capped at 50 seconds in both discovery and argument validation. With the five-second service budget, these calls leave at least five seconds below a 60-second host tool deadline. Hosts with shorter configured limits need shorter requested waits. This MCP cap does not narrow CLI or typed-client limits. `wait_for_ci` accepts 0–900 seconds and is exempt from this 50-second cap. For waits over two seconds, its call budget is the selected wait plus fifteen seconds; shorter waits use fifteen seconds. Both are subject to an earlier host deadline. Configure the host tool deadline to cover that budget; the adapter shortens the forwarded wait to leave response time within any earlier deadline. See [CI waits](ci-wait.md) for reconnect and pinned-comparison behavior. diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index a00d8bfc..13008927 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -2,13 +2,13 @@ ## Source-slice boundary -This slice includes the scheduling engine, retained-state guards and HTTP API. Bound Go client, CLI and MCP controls and their packaged administration smoke are delivered in the dependent client slice. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. +This slice includes the scheduling engine, retained-state guards, HTTP API and CLI/MCP controls. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. Projects can independently opt in to automatic new Hosted or CLI requests. Both default to off. Explicit CLI requests continue to work without enabling automatic selection; a proven quota refusal retains any accepted request through [durable CLI waiting](retained-review-quota-controls.md), without replacing that operation. Automatic GitHub observation and timer-backed retries of explicit requests are independent of this setting. Retries of automatically selected requests still require their channel to be continuously enabled. See [observation](github-observation.md) and [timer-backed waiting](retained-review-quota-controls.md). ## Automatic Hosted requests -A project manager enables scheduling through the HTTP API; bound CLI and MCP delivery follows in the dependent client slice. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. This project scheduling write requires bearer authentication and active project worker attribution. Browser sessions do not authorize this route. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected CLI intent crossing a scheduling revision additionally needs the same explicit, writer-owned CLI basis in every revision. An unrelated-channel edit can preserve that basis; a missing basis or an authorizer change followed by a change back cannot prove CLI continuity. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The acceptance event records whether a new selection is explicit or automatic. Automatic selections and their children require matching retained scheduling attribution before selection, recovery or dispatch. Missing or conflicting attribution holds those requests. For older selections, a caller-supplied PR pin, an exact retained explicit mutation receipt, or complete retained history showing acceptance before automatic scheduling for that channel can establish explicit origin. An ambiguous legacy selection stays held. Current explicit authorization still applies. +A project manager enables scheduling through CLI, MCP or the HTTP API. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. This project scheduling write requires bearer authentication and active project worker attribution. Browser sessions do not authorize this route. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected CLI intent crossing a scheduling revision additionally needs the same explicit, writer-owned CLI basis in every revision. An unrelated-channel edit can preserve that basis; a missing basis or an authorizer change followed by a change back cannot prove CLI continuity. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The acceptance event records whether a new selection is explicit or automatic. Automatic selections and their children require matching retained scheduling attribution before selection, recovery or dispatch. Missing or conflicting attribution holds those requests. For older selections, a caller-supplied PR pin, an exact retained explicit mutation receipt, or complete retained history showing acceptance before automatic scheduling for that channel can establish explicit origin. An ambiguous legacy selection stays held. Current explicit authorization still applies. The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. @@ -22,7 +22,7 @@ Results still require normal adjudication, finalization and fix evidence. Automa ## Automatic CLI requests -A project manager can explicitly enable `automatic_cli` through CLI, MCP or the project scheduling API. A future browser editor must preserve the CLI setting when editing Hosted configuration. Both settings use the retained manager credential and active worker, with the same authorization rechecks before selection and dispatch. Changing either setting uses the shared scheduling revision. Older Hosted-only writes omit `automatic_cli` and preserve its current value; explicit `false` disables new CLI automation. +A project manager can explicitly enable `automatic_cli` through CLI, MCP or the project scheduling API. A future browser editor must preserve the CLI setting when editing Hosted configuration. Both settings use the retained manager credential and active worker, with the same authorization rechecks before selection and dispatch. Changing either setting uses the shared scheduling revision. Older Hosted-only writes omit `automatic_cli` and preserve its current value; explicit `false` disables new CLI automation. Omission preserves the setting, not the shared authorizer: a successful write leaving either channel enabled records the acting manager credential and active worker for new automation, even if the write disables only the other channel. Automatic CLI uses the ordinary durable channel-front selection and execution path, without out-of-order or file-limit overrides. Existing grants, maxima, taper, channel closure, exact current-head checks, source-owned predecessor dependencies, publication and adjudication requirements remain in force. No setting increases grants or adjudicates findings. A meaningful completed result or source/control change can authorize another selection; ticks, restart, failed attempts and cancellation alone cannot. CLI and Hosted results have separate intent digests, so a clean completion in the other channel does not recreate a cancelled request. @@ -48,8 +48,6 @@ The existing queue and PR detail views show current round allowance, closure or ## CLI and MCP -These scheduling commands and tools require the dependent client slice. The backend slice exposes the scheduling HTTP API. - Read the current scheduling revision before changing settings. Keep the exact request and key after an uncertain mutation outcome; replaying the same key cannot enable or pause twice. ```sh diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 050260a0..541075ad 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -46,6 +46,7 @@ type options struct { } type invocation struct { + reviewScheduling *reviewSchedulingInvocation ownerManagement *ownerManagementInvocation includeRetired bool ciWatch *ciWatchInvocation @@ -359,7 +360,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou if err != nil { return reportClientError(stderr, err, ctx) } - if call.reviewOperationControl != nil { + if call.reviewOperationControl != nil || call.reviewScheduling != nil && call.reviewScheduling.action != "read" { encoded, err := json.Marshal(value) if err == nil { encoded = append(encoded, '\n') @@ -382,6 +383,18 @@ func parseInvocation(args []string) (invocation, bool) { remaining := make([]string, 0, len(args)) for i := 0; i < len(args); i++ { argument := args[i] + // In scheduling pause, --reason owns its next token even when the + // literal reason resembles a global option. Profile selection is + // otherwise still processed in its normal positions. + if argument == "--reason" && len(remaining) >= 3 && + remaining[0] == "reviews" && remaining[1] == "scheduling" && remaining[2] == "pause" { + remaining = append(remaining, argument) + if i+1 < len(args) { + i++ + remaining = append(remaining, args[i]) + } + continue + } flag, value, assigned := strings.Cut(argument, "=") if flag != "--profile" && flag != "--profiles-file" { remaining = append(remaining, argument) @@ -413,6 +426,27 @@ func parseInvocation(args []string) (invocation, bool) { return call, false } call.command = remaining[0] + // Scheduling help is entirely local and has exact leaf grammar. + if len(remaining) >= 3 { + words := remaining + if words[0] == "help" { + words = words[1:] + } else if words[len(words)-1] == "--help" { + words = words[:len(words)-1] + } else { + words = nil + } + if len(words) == 2 || len(words) == 3 { + if words[0] == "reviews" && words[1] == "scheduling" { + name := strings.Join(words, " ") + if _, ok := operationHelp(name); ok { + call.operationHelp = name + return call, true + } + } + } + } + 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 diff --git a/internal/cli/operation_help.go b/internal/cli/operation_help.go index 533541c8..b9bffbfb 100644 --- a/internal/cli/operation_help.go +++ b/internal/cli/operation_help.go @@ -15,6 +15,9 @@ type operationHelpResponse struct { } func emitOperationHelp(operation string, stdout, stderr io.Writer) int { + if help, ok := operationHelp(operation); ok { + return emit(stdout, stderr, help) + } if help, ok := ownerManagementHelp(operation); ok { return emit(stdout, stderr, help) } diff --git a/internal/cli/review_operation_control_test.go b/internal/cli/review_operation_control_test.go index 10e646dc..02af3fd1 100644 --- a/internal/cli/review_operation_control_test.go +++ b/internal/cli/review_operation_control_test.go @@ -6,9 +6,12 @@ import ( "github.com/benhook1013/FireController/internal/cli" "github.com/benhook1013/FireController/internal/client" "github.com/benhook1013/FireController/internal/strictjson" + "io" "net/http" "net/http/httptest" + "reflect" "strings" + "sync/atomic" "testing" ) @@ -108,3 +111,77 @@ func TestReviewControlOutputFailureRetainsSameKeyRecovery(t *testing.T) { t.Fatal("same-key recovery changed effect", code, out, stderr) } } + +func TestReviewSchedulingCLIOutputFailureRetainsSameKeyRecovery(t *testing.T) { + for _, action := range []string{"configure", "pause", "resume"} { + for _, output := range []struct { + name string + writer io.Writer + }{{"failed", roundFailWriter{}}, {"short", shortMapOutput{}}} { + t.Run(action+"/"+output.name, func(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + var posts atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/scheduling") { + posts.Add(1) + if r.Header.Get("X-FC-Worker") != worker || r.Header.Get("X-FC-Instance") != f.store.InstanceID() || !strings.HasPrefix(r.URL.Path, "/api/v1/projects/"+project+"/") { + t.Error("scheduling mutation lost binding") + } + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) + expected, revision := "0", int64(1) + if action == "resume" { + mutationSuccess(t, profiles, "builder", "reviews", "scheduling", "pause", "--pr", "2", "--expect-revision", "0", "--key", "prepare-paused-pull") + expected, revision = "1", 2 + posts.Store(0) + } + args := []string{"reviews", "scheduling", action, "--expect-revision", expected, "--key", "original-scheduling-key"} + state, id := "pull_scheduling_updated", "2" + switch action { + case "configure": + args = append(args, "--automatic-hosted", "true") + state, id = "scheduling_configured", project + case "pause", "resume": + args = append(args, "--pr", "2") + } + full := append([]string{"--profiles-file", profiles, "--profile", "builder"}, args...) + var diag strings.Builder + code := cli.RunContext(t.Context(), full, nil, output.writer, &diag) + var failure struct { + Error client.Error `json:"error"` + } + if code != cli.ExitConfig || json.Unmarshal([]byte(diag.String()), &failure) != nil || failure.Error.Code != "output_failed" || !failure.Error.OutcomeUnknown || !strings.Contains(failure.Error.Action, "exact same key, request and bound instance") || posts.Load() != 1 { + t.Fatal("committed scheduling output failure lost exact recovery or retried", code, diag.String(), posts.Load()) + } + code, out, stderr := mutationInvoke(t, profiles, "builder", args...) + var receipt client.ReviewRequestReceipt + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &receipt) != nil || receipt.ID != id || receipt.State != state || receipt.Revision != revision || posts.Load() != 2 { + t.Fatal("exact recovery changed the scheduling effect", code, out, stderr, posts.Load()) + } + code, out, stderr = mutationInvoke(t, profiles, "builder", args...) + var replay client.ReviewRequestReceipt + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &replay) != nil || !reflect.DeepEqual(receipt, replay) || posts.Load() != 3 { + t.Fatal("scheduling replay changed receipt", code, out, stderr) + } + }) + } + } +} + +func TestReviewSchedulingCLIReadOutputFailureDoesNotClaimMutation(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}}) + for _, suffix := range [][]string{nil, {"read"}, {"read", "--pr", "2"}} { + args := append([]string{"--profiles-file", profiles, "--profile", "builder", "reviews", "scheduling"}, suffix...) + var diag strings.Builder + code := cli.RunContext(t.Context(), args, nil, roundFailWriter{}, &diag) + if code != cli.ExitConfig || !strings.Contains(diag.String(), "output_failed") || strings.Contains(diag.String(), "outcome_unknown") || strings.Contains(diag.String(), "same key") { + t.Fatal("read output failure gained mutation recovery semantics", code, diag.String()) + } + } +} diff --git a/internal/cli/review_scheduling.go b/internal/cli/review_scheduling.go new file mode 100644 index 00000000..e2302632 --- /dev/null +++ b/internal/cli/review_scheduling.go @@ -0,0 +1,112 @@ +package cli + +import ( + "context" + "strconv" + "strings" + + "github.com/benhook1013/FireController/internal/client" +) + +type reviewSchedulingInvocation struct { + action string + pull int64 + key string + config client.ConfigureReviewSchedulingRequest + pause client.ConfigureReviewPullSchedulingRequest +} + +func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { + in := &reviewSchedulingInvocation{action: "read"} + if len(args) > 0 && !strings.HasPrefix(args[0], "--") { + in.action, args = args[0], args[1:] + } + allowed := map[string]bool{"--pr": true} + switch in.action { + case "read": + case "configure": + allowed = map[string]bool{"--automatic-hosted": true, "--automatic-cli": true, "--expect-revision": true, "--key": true} + case "pause", "resume": + allowed["--expect-revision"], allowed["--key"] = true, true + if in.action == "pause" { + allowed["--reason"] = true + } + default: + return nil, false + } + values := map[string]string{} + for i := 0; i < len(args); i++ { + flag, value, assigned := strings.Cut(args[i], "=") + if !allowed[flag] { + return nil, false + } + if _, exists := values[flag]; exists { + return nil, false + } + if !assigned { + i++ + if i >= len(args) { + return nil, false + } + value = args[i] + // A separated flag after --key is almost always a missing value. + // Callers deliberately using such a key can use --key=VALUE. + if flag == "--key" && strings.HasPrefix(value, "--") { + return nil, false + } + } + if value == "" && flag != "--reason" { + return nil, false + } + values[flag] = value + } + if value, exists := values["--pr"]; exists { + n, err := strconv.ParseInt(value, 10, 32) + if err != nil || n < 1 || strconv.FormatInt(n, 10) != value { + return nil, false + } + in.pull = n + } + if in.action == "read" { + return in, true + } + if !validMutationKey(values["--key"]) { + return nil, false + } + in.key = values["--key"] + revision, err := strconv.ParseInt(values["--expect-revision"], 10, 64) + if err != nil || strconv.FormatInt(revision, 10) != values["--expect-revision"] { + return nil, false + } + if in.action == "configure" { + value := values["--automatic-hosted"] + if value != "true" && value != "false" { + return nil, false + } + in.config = client.ConfigureReviewSchedulingRequest{ExpectedRevision: revision, AutomaticHosted: value == "true"} + if value, exists := values["--automatic-cli"]; exists { + if value != "true" && value != "false" { + return nil, false + } + enabled := value == "true" + in.config.AutomaticCLI = &enabled + } + return in, client.ValidateConfigureReviewScheduling(in.config) == nil + } + in.pause = client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: revision, Paused: in.action == "pause", Reason: values["--reason"]} + return in, client.ValidateConfigureReviewPullScheduling(in.pull, in.pause) == nil +} + +func executeReviewScheduling(ctx context.Context, service *client.Client, in *reviewSchedulingInvocation) (any, error) { + switch in.action { + case "configure": + return service.ConfigureReviewScheduling(ctx, in.key, in.config) + case "pause", "resume": + return service.ConfigureReviewPullScheduling(ctx, in.key, in.pull, in.pause) + default: + if in.pull != 0 { + return service.ReviewPullScheduling(ctx, in.pull) + } + return service.ReviewScheduling(ctx) + } +} diff --git a/internal/cli/review_scheduling_guidance_test.go b/internal/cli/review_scheduling_guidance_test.go new file mode 100644 index 00000000..5bee8703 --- /dev/null +++ b/internal/cli/review_scheduling_guidance_test.go @@ -0,0 +1,18 @@ +package cli + +import ( + "strings" + "testing" +) + +func TestSchedulingConfigureHelpDistinguishesValueFromAuthorizer(t *testing.T) { + info, ok := operationHelp("reviews scheduling configure") + if !ok { + t.Fatal("configure help missing") + } + for _, phrase := range []string{"preserves the setting, not the authorizer", "shared authorizer for new work", "even when disabling only the other channel"} { + if !strings.Contains(strings.Join(info.Semantics, " "), phrase) { + t.Errorf("configure help is missing %q", phrase) + } + } +} diff --git a/internal/cli/review_scheduling_help.go b/internal/cli/review_scheduling_help.go new file mode 100644 index 00000000..041ed837 --- /dev/null +++ b/internal/cli/review_scheduling_help.go @@ -0,0 +1,43 @@ +package cli + +func operationHelp(operation string) (operationHelpResponse, bool) { + recovery := "Use an explicit --key (1-128 printable ASCII bytes without surrounding whitespace). After uncertain output retry the same key, exact request and binding; never invent a replacement key." + out := operationHelpResponse{Required: []string{}, Optional: []string{}} + switch operation { + case "reviews scheduling": + out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause --pr N --expect-revision N --key KEY [--reason TEXT] | resume --pr N --expect-revision N --key KEY" + out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)", "configure --automatic-hosted true|false (project manager; authorizes future automatic Hosted requests)", "pause|resume --pr N (writer; holds new/undispatched reviews without changing rounds)", "--reason TEXT (optional with pause, at most 256 UTF-8 bytes)"} + out.Optional = append(out.Optional, "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") + out.Semantics = []string{"Automation defaults off. Enabling requires this connection's active bound worker and current project-management authority; CLI automation is separately opt-in via --automatic-cli; omission preserves its current value. Existing grants and taper remain unchanged.", "Pause can precede any intent. Existing provider review collection continues, and separate operation pauses remain in effect. Read the current revision; mutations require an explicit key and preserve original-key recovery.", "No live provider request is needed to read or change a PR pause. Enabling project automation authorizes later Hosted or CLI selection under all existing comparison, obligation, round and provider guards."} + out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling read": + out.Usage = " reviews scheduling read [--pr N]" + out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)"} + out.Semantics = []string{"Returns stored scheduling state and its independent revision. Use the project revision for configure, or the selected PR revision for pause/resume. No provider request or writes."} + out.Example = " reviews scheduling read --pr 42" + out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling configure": + out.Usage = " reviews scheduling configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY" + out.Required = []string{"--automatic-hosted true|false", "--expect-revision N (current project scheduling revision, including 0)", "--key KEY"} + out.Semantics = []string{"Requires project-management authority. Read reviews scheduling for the current project scheduling revision. Enabling authorizes future automatic Hosted or CLI requests through this connection's active bound worker under the existing review guards. Both default off. Omitting --automatic-cli preserves the setting, not the authorizer. If either channel stays enabled, the current authenticated manager and bound worker become the shared authorizer for new work, even when disabling only the other channel. Automation does not adjudicate findings or increase grants.", recovery} + out.Optional = []string{"--automatic-cli true|false (separate opt-in; omission preserves the current CLI setting)"} + out.Example = " reviews scheduling configure --automatic-hosted true --expect-revision 0 --key automatic-hosted-1" + out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling pause", "reviews scheduling resume": + out.Usage = " " + operation + " --pr N --expect-revision N --key KEY" + out.Required = []string{"--pr N", "--expect-revision N (current PR scheduling revision, including 0)", "--key KEY"} + out.Semantics = []string{"Requires project write access. Read reviews scheduling read --pr N for this PR's scheduling revision. Changes new/undispatched review scheduling in both channels; existing provider collection continues. Does not change rounds, channel closure or separate operation pauses.", recovery} + if operation == "reviews scheduling pause" { + out.Usage += " [--reason TEXT]" + out.Optional = []string{"--reason TEXT (optional, at most 256 UTF-8 bytes)"} + out.Semantics = append(out.Semantics, "May pause before the first review intent. No live provider request is needed to pause a PR.") + } else { + out.Semantics = append(out.Semantics, "Clears the PR pause and its reason. Accepts no --reason flag; does not resume separately paused operations or reopen closed channels.") + } + out.Example = " " + operation + " --pr 42 --expect-revision 0 --key scheduling-42-1" + out.Documentation = "docs/review-scheduling.md" + default: + return out, false + } + return out, true +} diff --git a/internal/cli/review_scheduling_test.go b/internal/cli/review_scheduling_test.go new file mode 100644 index 00000000..b72dcd7e --- /dev/null +++ b/internal/cli/review_scheduling_test.go @@ -0,0 +1,195 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +func TestReviewSchedulingCLIExplicitControlsBeforeProfile(t *testing.T) { + for _, args := range [][]string{ + nil, {"--pr", "7"}, {"read", "--pr=7"}, + {"configure", "--automatic-hosted", "false", "--expect-revision", "0", "--key", "disable"}, + {"configure", "--automatic-hosted=true", "--expect-revision=3", "--key=enable"}, + {"pause", "--pr", "7", "--expect-revision", "0", "--reason", "Preparing changes", "--key", "pause"}, + {"resume", "--pr", "7", "--expect-revision", "1", "--key", "resume"}, + {"pause", "--pr=7", "--expect-revision=0", "--key=--reason=maintenance"}, + } { + call, ok := parseInvocation(append([]string{"reviews", "scheduling"}, args...)) + if !ok || call.reviewScheduling == nil || call.command != "reviews" { + t.Fatal("supported scheduling syntax refused", args, call, ok) + } + } + for _, args := range [][]string{ + {"configure", "--automatic-hosted", "true", "--key", "missing-revision"}, + {"configure", "--expect-revision", "0", "--key", "missing-explicit-bool"}, + {"configure", "--automatic-hosted", "yes", "--expect-revision", "0", "--key", "bad-bool"}, + {"configure", "--automatic-hosted", "true", "--expect-revision", "-1", "--key", "bad-revision"}, + {"--pr", "0"}, {"--pr", "07"}, {"--pr", "7", "--pr", "8"}, {"--key", "read-mutation"}, + {"pause", "--pr", "7", "--expect-revision", "0"}, + {"pause", "--pr=7", "--expect-revision=0", "--key", "--reason=maintenance"}, + {"configure", "--automatic-hosted=true", "--expect-revision=0", "--key", "--automatic-cli=true"}, + {"pause", "--pr", "7", "--expect-revision", "0", "--key", "bad-reason", "--reason", "line\nbreak"}, + {"pause", "--pr", "7", "--expect-revision", "0", "--key", "bad-reason", "--reason", strings.Repeat("x", 257)}, + {"resume", "--pr", "7", "--expect-revision", "1", "--key", "unexpected-reason", "--reason", "hidden"}, + {"configure", "--automatic-hosted", "true", "--expect-revision", "0", "--key", "foreign", "--worker", "other"}, + } { + var out, diag bytes.Buffer + code := RunContext(t.Context(), append([]string{"--profiles-file", "/missing", "reviews", "scheduling"}, args...), nil, &out, &diag) + if code != ExitUsage || out.Len() != 0 || !strings.Contains(diag.String(), "invalid_arguments") { + t.Fatal("invalid scheduling input reached profile/transport", args, code, out.String(), diag.String()) + } + } + var out, diag bytes.Buffer + if code := RunContext(t.Context(), []string{"--profiles-file", "/missing", "reviews", "scheduling", "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "docs/review-scheduling.md") || !strings.Contains(out.String(), "authorizes future") { + t.Fatal("scheduling help not usable offline", code, out.String(), diag.String()) + } +} + +func TestReviewSchedulingCLIOptionalAutomaticCLI(t *testing.T) { + base := []string{"configure", "--automatic-hosted=false", "--expect-revision=0", "--key=cli-setting"} + for _, value := range []string{"", "true", "false"} { + args := append([]string{}, base...) + if value != "" { + args = append(args, "--automatic-cli="+value) + } + in, ok := parseReviewScheduling(args) + if !ok || in.config.AutomaticHosted || (in.config.AutomaticCLI == nil) != (value == "") { + t.Fatalf("lost optional CLI state: %q %+v", value, in) + } + if value != "" && *in.config.AutomaticCLI != (value == "true") { + t.Fatal("wrong explicit CLI state") + } + } + for _, extra := range [][]string{{"--automatic-cli=yes"}, {"--automatic-cli="}, {"--automatic-cli"}, {"--automatic-cli=true", "--automatic-cli=false"}} { + if _, ok := parseReviewScheduling(append(append([]string{}, base...), extra...)); ok { + t.Fatal("accepted invalid CLI flag", extra) + } + } + if _, ok := parseReviewScheduling([]string{"configure", "--automatic-cli=true", "--expect-revision=0", "--key=missing-hosted"}); ok { + t.Fatal("Hosted flag must remain explicit") + } +} + +func TestReviewSchedulingLeafHelpIsOffline(t *testing.T) { + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { requests.Add(1) })) + defer service.Close() + path := filepath.Join(t.TempDir(), "profiles.json") + private := []byte("PRIVATE_INVALID_PROFILE") + if err := os.WriteFile(path, private, 0600); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + bound := filepath.Join(dir, "profiles.json") + token := filepath.Join(dir, "token") + if err := os.WriteFile(token, []byte("test-local-profile-token"), 0600); err != nil { + t.Fatal(err) + } + profile, err := json.Marshal(map[string]any{"version": 1, "profiles": map[string]any{ + "bound": map[string]string{"server_url": service.URL, "instance_id": "test-instance", "project_id": "test-project", "worker_id": "test-worker", "credential_file": token}, + }}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(bound, profile, 0600); err != nil { + t.Fatal(err) + } + absent := filepath.Join(dir, "absent.json") + offline, cancel := context.WithCancel(t.Context()) + cancel() + for _, leaf := range []string{"read", "configure", "pause", "resume"} { + for _, spelling := range [][]string{{"reviews", "scheduling", leaf, "--help"}, {"help", "reviews", "scheduling", leaf}} { + for _, profilePath := range []string{path, absent, bound} { + args := append([]string{"--profiles-file", profilePath, "--profile", "bound"}, spelling...) + ctx := offline + if profilePath == bound { + ctx = t.Context() + } + var stdout, stderr bytes.Buffer + code := RunContext(ctx, args, nil, &stdout, &stderr) + var help operationHelpResponse + if code != ExitSuccess || stderr.Len() != 0 || stdout.Len() > 2500 || json.Unmarshal(stdout.Bytes(), &help) != nil || !strings.HasPrefix(help.Usage, " reviews scheduling "+leaf) || help.Documentation != "docs/review-scheduling.md" { + t.Fatalf("%v: code=%d stdout=%s stderr=%s", args, code, &stdout, &stderr) + } + if leaf != "read" && (!strings.Contains(help.Usage, "--expect-revision N --key KEY") || !strings.Contains(strings.Join(help.Semantics, " "), "same key, exact request")) { + t.Fatal("mutation help omitted revision/key recovery", leaf, help) + } + if leaf == "pause" && !strings.Contains(help.Usage, "[--reason TEXT]") || leaf == "resume" && strings.Contains(help.Usage, "--reason") { + t.Fatal("pause/resume reason syntax drifted", help) + } + if call, ok := parseInvocation(strings.Fields(strings.TrimPrefix(help.Example, " "))); !ok || call.command == "help" || call.reviewScheduling == nil || call.reviewScheduling.action != leaf { + t.Fatal("help example does not select its real scheduling operation", leaf, call, ok) + } + } + } + } + if requests.Load() != 0 { + t.Fatal("help contacted a server") + } + // A regular bound command must reach this listener, or zero help + // requests would not establish that help avoided the transport. + var ignoredOut, ignoredErr bytes.Buffer + RunContext(t.Context(), []string{"--profiles-file", bound, "--profile", "bound", "reviews", "scheduling", "read"}, nil, &ignoredOut, &ignoredErr) + if requests.Load() != 1 { + t.Fatalf("positive control did not reach the bound server: requests=%d diagnostic=%s", requests.Load(), &ignoredErr) + } + if after, err := os.ReadFile(path); err != nil || !bytes.Equal(after, private) { + t.Fatal("help changed selected configuration", err) + } + parent, _ := operationHelp("reviews scheduling") + for _, leaf := range []string{"read", "configure", "pause", "resume"} { + if !strings.Contains(strings.Join(parent.Optional, " "), "reviews scheduling "+leaf+" --help") { + t.Fatal("parent help does not discover leaf", leaf) + } + } +} + +func TestReviewSchedulingLeafHelpKeepsExactGrammar(t *testing.T) { + for _, args := range [][]string{ + {"reviews", "scheduling", "resume", "--help", "extra"}, + {"reviews", "scheduling", "pause", "--help", "--pr", "42"}, + {"reviews", "scheduling", "configure", "--help=true"}, + {"reviews", "scheduling", "read", "--pr", "42", "--help"}, + {"help", "reviews", "scheduling", "unknown"}, + {"help", "reviews", "scheduling", "resume", "--key", "help-is-not-a-write"}, + {"reviews", "scheduling", "resume", "--help", "--profile=a", "--profile=b"}, + } { + var stdout, stderr bytes.Buffer + if code := RunContext(t.Context(), args, nil, &stdout, &stderr); code != ExitUsage || stdout.Len() != 0 || !strings.Contains(stderr.String(), "invalid_arguments") { + t.Fatalf("%v: code=%d stdout=%s stderr=%s", args, code, &stdout, &stderr) + } + } + call, ok := parseInvocation([]string{"reviews", "scheduling", "pause", "--pr", "42", "--expect-revision", "0", "--key", "pause-1", "--reason", "--help"}) + if !ok || call.command == "help" || call.reviewScheduling == nil || call.reviewScheduling.pause.Reason != "--help" { + t.Fatal("help-looking reason was treated as local help", call, ok) + } +} + +func TestSchedulingPauseProfileShapedReasonIsLiteral(t *testing.T) { + for _, args := range [][]string{ + {"--reason", "--profile=other"}, + {"--reason=--profile=other"}, + {"--reason", "--profile"}, + {"--reason=--profile"}, + {"--reason", "--profiles-file=other"}, + } { + t.Run(strings.Join(args, " "), func(t *testing.T) { + cmd := []string{"--profile", "selected", "reviews", "scheduling", "pause", "--pr", "2", "--expect-revision", "0", "--key", "pause-2"} + cmd = append(cmd, args...) + cmd = append(cmd, "--profiles-file", "expected.json") + got, ok := parseInvocation(cmd) + want := strings.TrimPrefix(args[len(args)-1], "--reason=") + if !ok || got.profile != "selected" || got.profilesFile != "expected.json" || got.reviewScheduling == nil || got.reviewScheduling.pause.Reason != want { + t.Fatalf("literal scheduling reason not retained: got %+v, wanted %q", got, want) + } + }) + } +} diff --git a/internal/cli/reviews.go b/internal/cli/reviews.go index 7b375d63..e219cae4 100644 --- a/internal/cli/reviews.go +++ b/internal/cli/reviews.go @@ -16,6 +16,11 @@ func parseReview(call invocation, args []string) (invocation, bool) { call.reviewOperationControl, ok = parseReviewOperationControl(args) return call, ok } + if call.subcommand == "scheduling" { + var ok bool + call.reviewScheduling, ok = parseReviewScheduling(args) + return call, ok + } if call.subcommand == "ci-wait" { var ok bool call.ciWatch, ok = parseCIWatch(args) @@ -158,6 +163,9 @@ func reviewID(value, prefix string) bool { } func executeReview(ctx context.Context, service *client.Client, call invocation) (any, error) { + if call.reviewScheduling != nil { + return executeReviewScheduling(ctx, service, call.reviewScheduling) + } if call.ciWatch != nil { value, err := service.WatchCI(ctx, call.ciWatch.targets, call.ciWatch.seconds) return client.AgentCIWatch(value), err diff --git a/internal/client/client.go b/internal/client/client.go index 73466d8f..5be30902 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -474,8 +474,9 @@ func (c *Client) requestWithCapabilities(ctx context.Context, method string, seg 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" + switch cause := response.Header.Get("X-FC-Review-Queued"); cause { + case "cli_quota_wait", "pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained": + *wait.queuedCause = cause } } if response.StatusCode >= 300 && response.StatusCode < 400 { diff --git a/internal/client/review_agent_output.go b/internal/client/review_agent_output.go index 56cf6725..cf7b317f 100644 --- a/internal/client/review_agent_output.go +++ b/internal/client/review_agent_output.go @@ -13,6 +13,13 @@ func AgentReviewSelection(value ReviewRunState) ReviewSelectionOutput { out := ReviewSelectionOutput{ReviewRunState: value} if value.Selection.State == "held" && value.Selection.OperationID == "" && value.Operation == nil { out.Diagnostic = selectionSourceDiagnostic(value.Selection.Reason) + } else if op := value.Operation; op != nil && value.Selection.OperationID == op.ID && op.ID != "" { + switch op.State { + case "queued": + out.Diagnostic = schedulingDiagnostic(op.queuedCause) + case "held": + out.Diagnostic = agentReviewOperationDiagnostic(op.Channel, op.State, op.Reason) + } } return out } @@ -21,6 +28,12 @@ func draftReadinessDiagnostic() *ReviewOperationDiagnostic { } func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { + if reason == "automation_authorization_changed" { + return &ReviewOperationDiagnostic{"This selection stopped before it created a review operation because its scheduling authorization no longer applies.", "Read review_scheduling_read / reviews scheduling. A project manager can authorize future automatic selections through an active bound worker. The retained selection records the refusal."} + } + if hint := heldSchedulingDiagnostic(reason); hint != nil { + return hint + } if reason == "pull_draft" { return draftReadinessDiagnostic() } @@ -45,6 +58,9 @@ func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { default: return nil } + if reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" { + return &ReviewOperationDiagnostic{explanation, "An explicit held selection is terminal and has no child operation; after addressing the source issue, if the review remains authorized, use one fresh reviews start / review_start with a new key and current configuration. Its old key replays the hold. An eligible automatic selection may recover on its original identity after at least thirty seconds, subject to its retained retry budget, unchanged authorization and normal admission checks. Preserve the original selection while automatic recovery remains eligible; this diagnostic does not establish eligibility or promise an exact retry time. Keep pending selections and selected child operations on their original identities. No round reset or extra grant is needed."} + } return &ReviewOperationDiagnostic{explanation, "This held selection is terminal and has no child operation. After addressing the source issue, if the review remains authorized, use one fresh reviews start / review_start with a new key and current configuration. The old key replays this hold. Keep pending selections and selected child operations on their original identities. No round reset or extra grant is needed; normal front, source and provider checks still apply."} } @@ -66,6 +82,14 @@ type ReviewOperationStatusOutput struct { } func retainedWaitDiagnostic(wait *ReviewOperationWait, channel, state, reason, queuedCause string) *ReviewOperationDiagnostic { + if state == "queued" { + if hint := schedulingDiagnostic(queuedCause); hint != nil { + return hint + } + } + if hint := agentReviewOperationDiagnostic(channel, state, reason); hint != nil { + return hint + } if wait != nil { if diagnostic := operationWaitDiagnostic(wait, channel); diagnostic != nil { return diagnostic @@ -113,3 +137,12 @@ func operationWaitDiagnostic(w *ReviewOperationWait, channel string) *ReviewOper } return nil } + +func agentReviewOperationDiagnostic(channel, state, reason string) *ReviewOperationDiagnostic { + // Queued reasons can outlive a resumed pause; only the current queued cause + // can establish a scheduling hold. Held operations retain their own reason. + if state == "held" { + return heldSchedulingDiagnostic(reason) + } + return nil +} diff --git a/internal/client/review_agent_output_test.go b/internal/client/review_agent_output_test.go index c3ed74e6..59a5c1a8 100644 --- a/internal/client/review_agent_output_test.go +++ b/internal/client/review_agent_output_test.go @@ -26,6 +26,9 @@ func TestAgentSelectionSourceHoldIsBoundedAndNeverReplacesChild(t *testing.T) { continue } phrases := []string{"terminal and has no child", "After addressing", "if the review remains authorized", "new key and current configuration", "old key replays", "pending selections and selected child", "No round reset or extra grant"} + if reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" { + phrases = []string{"An explicit held selection is terminal", "if the review remains authorized", "new key and current configuration", "old key replays", "eligible automatic selection may recover on its original identity", "after at least thirty seconds", "retained retry budget", "unchanged authorization", "Preserve the original selection", "does not establish eligibility or promise an exact retry time", "No round reset or extra grant"} + } if reason == "pull_draft" { phrases = []string{"After marking the PR ready for review", "if this review remains authorized", "new key and current configuration/head", "old key replays this terminal hold", "Do not reset rounds, grant extra reviews or retry automatically", "normal admission and provider checks"} for _, phrase := range []string{"GitHub Draft", "initial review readiness", "does not erase earned review progress"} { diff --git a/internal/client/review_run.go b/internal/client/review_run.go index f8cdc40c..fa80c1c3 100644 --- a/internal/client/review_run.go +++ b/internal/client/review_run.go @@ -148,10 +148,12 @@ func (c *Client) WaitReviewSelection(ctx context.Context, id string, waitSeconds return ReviewRunState{}, validation() } var result ReviewRunState + var queuedCause string var status int err := resumeResultWait(ctx, waitSeconds, func(ctx context.Context, remaining int) error { result = ReviewRunState{} - return c.requestBoundedOptions(ctx, http.MethodGet, c.projectPath("reviews", "selections", id), nil, true, "", nil, http.StatusOK, false, &result, 64<<10, decodeReviewResponse, &sourceWaitOptions{seconds: remaining, status: &status}) + queuedCause = "" + return c.requestBoundedOptions(ctx, http.MethodGet, c.projectPath("reviews", "selections", id), nil, true, "", nil, http.StatusOK, false, &result, 64<<10, decodeReviewResponse, &sourceWaitOptions{seconds: remaining, status: &status, queuedCause: &queuedCause}) }) if err != nil { return ReviewRunState{}, reviewSelectionWaitTargetError(err, id) @@ -159,5 +161,8 @@ func (c *Client) WaitReviewSelection(ctx context.Context, id string, waitSeconds if result.Selection.ID != id || !c.validReviewRun(result) { return ReviewRunState{}, invalidResponse() } + if result.Operation != nil && result.Operation.State == "queued" { + result.Operation.queuedCause = queuedCause + } return result, nil } diff --git a/internal/client/review_run_test.go b/internal/client/review_run_test.go index 0cda003d..a68f8dd8 100644 --- a/internal/client/review_run_test.go +++ b/internal/client/review_run_test.go @@ -376,3 +376,37 @@ func TestReviewRunActualHTTPAcceptsOnceAndReadDoesNotSelect(t *testing.T) { t.Fatal("retained read selected or lost scope", err) } } + +func TestReviewSelectionShowsLinkedSchedulingHeader(t *testing.T) { + for _, tc := range []struct { + state, header string + want bool + }{ + {"queued", "pull_scheduling_paused", true}, + {"queued", "unknown_reason", false}, + {"uncertain", "pull_scheduling_paused", false}, + } { + t.Run(tc.state+"/"+tc.header, func(t *testing.T) { + value := selectionSample() + value.Operation.State = tc.state + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/instance") { + handshake(w) + return + } + w.Header().Set("X-FC-Review-Queued", tc.header) + write(w, 200, value) + })) + defer srv.Close() + c := newClient(t, srv) + got, err := c.ReviewSelection(t.Context(), runSelectionID) + if err != nil { + t.Fatal(err) + } + d := client.AgentReviewSelection(got).Diagnostic + if (d != nil) != tc.want || d != nil && !strings.Contains(d.Explanation, "New reviews are paused for this PR") { + t.Fatalf("wrong scheduling guidance: %+v", d) + } + }) + } +} diff --git a/internal/client/review_scheduling.go b/internal/client/review_scheduling.go new file mode 100644 index 00000000..17796b4c --- /dev/null +++ b/internal/client/review_scheduling.go @@ -0,0 +1,197 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "github.com/benhook1013/FireController/internal/strictjson" + "math" + "net/http" + "strconv" + "time" + "unicode" + "unicode/utf8" +) + +type ReviewScheduling struct { + ProjectID string `json:"project_id"` + Revision int64 `json:"revision"` + AutomaticCLI bool `json:"automatic_cli"` + AutomaticHosted bool `json:"automatic_hosted"` + PausedPulls []ReviewPullScheduling `json:"paused_pulls"` + AuthorizingWorkerID string `json:"authorizing_worker_id,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + Reason string `json:"reason,omitempty"` +} + +type ReviewPullScheduling struct { + ProjectID string `json:"project_id"` + PullNumber int64 `json:"pull_number"` + Revision int64 `json:"revision"` + Paused bool `json:"paused"` + Reason string `json:"reason"` + ActorID string `json:"actor_id,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +type ConfigureReviewSchedulingRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + AutomaticHosted bool `json:"automatic_hosted"` + AutomaticCLI *bool `json:"automatic_cli,omitempty"` +} + +type ConfigureReviewPullSchedulingRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + Paused bool `json:"paused"` + Reason string `json:"reason,omitempty"` +} + +func validSchedulingRevision(revision int64) bool { return revision >= 0 && revision < math.MaxInt64 } +func validSchedulingTime(value string) bool { + if len(value) > 64 { + return false + } + at, err := time.Parse(time.RFC3339Nano, value) + return err == nil && !at.IsZero() +} +func validSchedulingReason(reason string) bool { + if len(reason) > 256 || !utf8.ValidString(reason) { + return false + } + for _, r := range reason { + if unicode.IsControl(r) { + return false + } + } + return true +} + +func ValidateConfigureReviewScheduling(input ConfigureReviewSchedulingRequest) error { + if !validSchedulingRevision(input.ExpectedRevision) { + return mutationValidation() + } + return nil +} + +func ValidateConfigureReviewPullScheduling(pull int64, input ConfigureReviewPullSchedulingRequest) error { + if !validPullNumber(pull) || !validSchedulingRevision(input.ExpectedRevision) || !validSchedulingReason(input.Reason) { + return mutationValidation() + } + return nil +} + +func validPullScheduling(value ReviewPullScheduling, project string, pull int64) bool { + if value.ProjectID != project || value.PullNumber != pull || !validPullNumber(pull) || value.Revision < 0 || !validSchedulingReason(value.Reason) || !value.Paused && value.Reason != "" { + return false + } + if value.Revision == 0 { + return !value.Paused && value.Reason == "" && value.ActorID == "" && value.UpdatedAt == "" + } + return validID(value.ActorID) && validSchedulingTime(value.UpdatedAt) +} + +// Older services omit automatic_cli. Accept that as off while always emitting +// an explicit boolean in CLI/MCP output, including after an enabled read. +func decodeReviewSchedulingResponse(data []byte, dst any) error { + if err := strictjson.Decode(data, dst); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil || fields == nil { + return strictjson.ErrSyntax + } + if _, present := fields["automatic_cli"]; !present { + fields["automatic_cli"] = json.RawMessage("false") + var err error + data, err = json.Marshal(fields) + if err != nil { + return err + } + } + if !completeShape(data, dst) { + return strictjson.ErrSyntax + } + return nil +} + +func (c *Client) ReviewScheduling(ctx context.Context) (ReviewScheduling, error) { + // Allow 100 paused pulls, including six-byte JSON escaping of each + // 256-byte reason and bounded identities, plus the response envelope. + var value ReviewScheduling + if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "scheduling"), nil, true, "", nil, http.StatusOK, false, &value, 512<<10, decodeReviewSchedulingResponse); err != nil { + return ReviewScheduling{}, err + } + if value.ProjectID != c.identity.ProjectID || value.Revision < 0 || value.PausedPulls == nil || len(value.PausedPulls) > 100 || value.Reason != "" && !safeCode(value.Reason) || value.AuthorizingWorkerID != "" && !validID(value.AuthorizingWorkerID) { + return ReviewScheduling{}, invalidResponse() + } + if value.Revision == 0 { + if value.AutomaticHosted || value.AutomaticCLI || value.AuthorizingWorkerID != "" || value.UpdatedAt != "" || value.Reason != "" { + return ReviewScheduling{}, invalidResponse() + } + } else if !validSchedulingTime(value.UpdatedAt) || (value.AutomaticHosted || value.AutomaticCLI) && value.AuthorizingWorkerID == "" { + return ReviewScheduling{}, invalidResponse() + } + seen := make(map[int64]bool, len(value.PausedPulls)) + for _, item := range value.PausedPulls { + if !item.Paused || seen[item.PullNumber] || !validPullScheduling(item, c.identity.ProjectID, item.PullNumber) { + return ReviewScheduling{}, invalidResponse() + } + seen[item.PullNumber] = true + } + return value, nil +} + +func (c *Client) ConfigureReviewScheduling(ctx context.Context, key string, input ConfigureReviewSchedulingRequest) (ReviewRequestReceipt, error) { + if !validMutationKey(key) || ValidateConfigureReviewScheduling(input) != nil { + return ReviewRequestReceipt{}, mutationValidation() + } + var receipt ReviewRequestReceipt + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "scheduling"), key, input, http.StatusOK, &receipt); err != nil { + return receipt, schedulingConflictGuidance(err, "reviews scheduling / review_scheduling_read") + } + if receipt.ID != c.identity.ProjectID || receipt.State != "scheduling_configured" || receipt.Revision != input.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The scheduling receipt was invalid; retain the original key and request.", http.StatusOK) + } + return receipt, nil +} + +func (c *Client) ReviewPullScheduling(ctx context.Context, pull int64) (ReviewPullScheduling, error) { + if !validPullNumber(pull) { + return ReviewPullScheduling{}, validation() + } + var value ReviewPullScheduling + if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "pulls", strconv.FormatInt(pull, 10), "scheduling"), nil, true, "", nil, http.StatusOK, false, &value, 4<<10, decodeResponse); err != nil { + return ReviewPullScheduling{}, err + } + if !validPullScheduling(value, c.identity.ProjectID, pull) { + return ReviewPullScheduling{}, invalidResponse() + } + return value, nil +} + +func (c *Client) ConfigureReviewPullScheduling(ctx context.Context, key string, pull int64, input ConfigureReviewPullSchedulingRequest) (ReviewRequestReceipt, error) { + if !validMutationKey(key) || ValidateConfigureReviewPullScheduling(pull, input) != nil { + return ReviewRequestReceipt{}, mutationValidation() + } + var receipt ReviewRequestReceipt + id := strconv.FormatInt(pull, 10) + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "pulls", id, "scheduling"), key, input, http.StatusOK, &receipt); err != nil { + return receipt, schedulingConflictGuidance(err, "reviews scheduling read --pr "+id+" / review_pull_scheduling_read") + } + if receipt.ID != id || receipt.State != "pull_scheduling_updated" || receipt.Revision != input.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The PR scheduling receipt was invalid; retain the original key and request.", http.StatusOK) + } + return receipt, nil +} + +// Rewrite only a confirmed stale revision. Preserve original replay guidance +// for timeouts, storage failures, and other unknown mutation outcomes. +func schedulingConflictGuidance(err error, currentRead string) error { + var failure *Error + if !errors.As(err, &failure) || failure.Code != "review_conflict" || failure.Status != http.StatusConflict || failure.OutcomeUnknown { + return err + } + copy := *failure + copy.Action = "Read current scheduling with " + currentRead + ". If the change is still needed, submit a new request with the current revision and a new idempotency key." + return © +} diff --git a/internal/client/review_scheduling_diagnostic.go b/internal/client/review_scheduling_diagnostic.go new file mode 100644 index 00000000..48399ddd --- /dev/null +++ b/internal/client/review_scheduling_diagnostic.go @@ -0,0 +1,23 @@ +package client + +func schedulingDiagnostic(reason string) *ReviewOperationDiagnostic { + switch reason { + case "pull_scheduling_paused": + return &ReviewOperationDiagnostic{"New reviews are paused for this PR; this is separate from an individual operation pause. Already issued reviews can still be collected.", "Read review_pull_scheduling_read / reviews scheduling read --pr N. Resume the PR only when authorized. Existing queued work retains its identity and any separate operation pause; a terminal held operation does not resume. Do not reset rounds or grant more reviews to clear this pause."} + case "automation_authorization_changed": + return &ReviewOperationDiagnostic{"Automatic scheduling for this channel is off, its authorization was interrupted, or its retained authorizer no longer has the required access. This retained selection/request cannot authorize provider work.", "Read review_scheduling_read / reviews scheduling. Re-enabling scheduling does not resume an operation whose channel authorization was interrupted. Inspect this retained operation before making a new authorized request. An authorized project manager can deliberately enable scheduling for new work with its current credential and active bound worker. Keep existing issued work on its original identity; do not switch another worker's credentials or reset rounds."} + case "automatic_intent_retained": + return &ReviewOperationDiagnostic{"An automatic review intent already exists for these same review facts; this selection did not create another provider request.", "Inspect existing scoped operations if needed. Ticks and observation refreshes do not restart cancelled, failed or held intent. Use a PR pause to prevent new scheduling across later meaningful changes. A separate explicit request still needs normal authorization and admission."} + } + return nil +} + +func heldSchedulingDiagnostic(reason string) *ReviewOperationDiagnostic { + if reason == "pull_scheduling_paused" { + return &ReviewOperationDiagnostic{ + "This request did not dispatch because new reviews were paused for this PR at the time. The retained hold does not establish the current PR pause.", + "Read review_pull_scheduling_read / reviews scheduling read --pr N for the current state. Resuming the PR cannot reopen this historical held request. Do not reset rounds or grant more reviews to clear a pause.", + } + } + return schedulingDiagnostic(reason) +} diff --git a/internal/client/review_scheduling_diagnostic_test.go b/internal/client/review_scheduling_diagnostic_test.go new file mode 100644 index 00000000..8c3e7a50 --- /dev/null +++ b/internal/client/review_scheduling_diagnostic_test.go @@ -0,0 +1,133 @@ +package client + +import ( + "reflect" + "strings" + "testing" +) + +func TestSchedulingDiagnosticsPreserveRetainedFacts(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { + v := ReviewOperationStatus{ID: "original", State: "held", Stage: "held", Reason: reason, Channel: "hosted", Revision: 3, NextAction: "read_diagnostics"} + out := AgentReviewOperationStatus(v) + if out.Diagnostic == nil || !reflect.DeepEqual(out.ReviewOperationStatus, v) || selectionSourceDiagnostic(reason) == nil { + t.Fatal("missing scheduling diagnostic or changed original facts", reason) + } + if agentReviewOperationDiagnostic("hosted", "active", reason) != nil { + t.Fatal("issued work gained scheduling refusal", reason) + } + } + if schedulingDiagnostic("unknown") != nil { + t.Fatal("invented scheduling refusal") + } +} + +func TestSchedulingDiagnosticsDoNotMislabelCLIAsHosted(t *testing.T) { + for _, reason := range []string{"automation_authorization_changed", "automatic_intent_retained"} { + value := AgentReviewOperationStatus(ReviewOperationStatus{State: "held", Stage: "held", Reason: reason, Channel: "cli", Revision: 1}) + if value.Diagnostic == nil || strings.Contains(value.Diagnostic.Explanation, "Hosted") { + t.Fatal("CLI refusal was attributed to the other channel", value) + } + } +} + +func TestQueuedSchedulingDiagnosticsUseCurrentCause(t *testing.T) { + const due = "2026-11-11T12:00:00Z" + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { + for _, channel := range []string{"cli", "hosted"} { + for _, tc := range []struct { + name, cause, explanation, action string + wait *ReviewOperationWait + }{ + {name: "awaiting_scheduler", cause: "awaiting_scheduler"}, + {name: "queue_order", cause: "queue_order"}, + {name: "absent_cause"}, + {name: "unknown_cause", cause: "unknown"}, + {name: "cooldown", cause: "cooldown", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, + {name: "queue_order_with_timer", cause: "queue_order", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, + {name: "quota_with_timer", cause: "cli_quota_wait", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, + {name: "operation_pause", cause: "operation_paused", wait: &ReviewOperationWait{Paused: true}, explanation: "no retry deadline is recorded", action: "Resume/cancel only this undispatched operation"}, + {name: "operation_pause_with_timer", cause: "operation_paused", wait: &ReviewOperationWait{Paused: true, RetryNotBefore: due}, explanation: "paused before", action: "Resume"}, + {name: "current_pr_pause", cause: "pull_scheduling_paused", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "New reviews are paused for this PR", action: "Resume the PR only when authorized"}, + {name: "current_authorization_hold", cause: "automation_authorization_changed", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "Automatic scheduling for this channel is off", action: "An authorized project manager"}, + {name: "current_retained_intent", cause: "automatic_intent_retained", explanation: "An automatic review intent already exists", action: "Inspect existing scoped operations"}, + {name: "quota_without_timer", cause: "cli_quota_wait"}, + } { + t.Run(channel+"/"+reason+"/"+tc.name, func(t *testing.T) { + explanation, action := tc.explanation, tc.action + if tc.name == "quota_without_timer" && channel == "cli" { + explanation, action = "queued for shared CLI quota rechecks", "Keep this original request queued" + } + operation := ReviewOperation{ID: "original", State: "queued", Reason: reason, Channel: channel, Revision: 3, Wait: tc.wait, queuedCause: tc.cause} + status := ReviewOperationStatus{ID: operation.ID, State: operation.State, Stage: "queued", Reason: reason, Channel: channel, Revision: operation.Revision, Wait: tc.wait, queuedCause: tc.cause, NextAction: "wait"} + full, compact := AgentReviewOperation(operation), AgentReviewOperationStatus(status) + if !reflect.DeepEqual(full.ReviewOperation, operation) || !reflect.DeepEqual(compact.ReviewOperationStatus, status) || !reflect.DeepEqual(full.Diagnostic, compact.Diagnostic) { + t.Fatal("wrappers changed retained facts or disagree", full, compact) + } + if explanation == "" { + if full.Diagnostic != nil { + t.Fatal("historical reason invented a current scheduling hold", full.Diagnostic) + } + return + } + if full.Diagnostic == nil || !strings.Contains(full.Diagnostic.Explanation, explanation) || !strings.Contains(full.Diagnostic.NextAction, action) { + t.Fatal("current cause or retained operation wait guidance was masked", explanation, action, full.Diagnostic) + } + }) + } + } + } +} + +func TestHeldSchedulingDiagnosticsIgnoreQueuedCause(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { + competingCause := "automatic_intent_retained" + if reason == competingCause { + competingCause = "automation_authorization_changed" + } + operation := ReviewOperation{State: "held", Channel: channel, Reason: reason, queuedCause: competingCause} + status := ReviewOperationStatus{State: "held", Stage: "held", Channel: channel, Reason: reason, queuedCause: competingCause, NextAction: "read_diagnostics"} + full, compact := AgentReviewOperation(operation), AgentReviewOperationStatus(status) + if !reflect.DeepEqual(full.Diagnostic, heldSchedulingDiagnostic(reason)) || !reflect.DeepEqual(compact.Diagnostic, full.Diagnostic) || !reflect.DeepEqual(full.ReviewOperation, operation) || !reflect.DeepEqual(compact.ReviewOperationStatus, status) { + t.Fatal("held scheduling guidance or retained facts changed", full, compact) + } + } + } +} + +func TestSchedulingDiagnosticExplainsInterruptedAuthorization(t *testing.T) { + diagnostic := schedulingDiagnostic("automation_authorization_changed") + for _, want := range []string{"Re-enabling scheduling does not resume", "Inspect this retained operation", "new authorized request", "original identity"} { + if diagnostic == nil || !strings.Contains(diagnostic.NextAction, want) { + t.Fatalf("missing continuity guidance %q: %+v", want, diagnostic) + } + } + if strings.Contains(diagnostic.Explanation, "Automatic Hosted") { + t.Fatal("shared authorization diagnostic excluded CLI") + } +} +func TestLinkedSchedulingDiagnosticUsesCurrentOrHistoricalOperation(t *testing.T) { + selection := ReviewRunSelection{State: "selected", OperationID: "review-original"} + for _, tc := range []struct{ state, cause, reason, want string }{ + {"queued", "pull_scheduling_paused", "", "New reviews are paused for this PR"}, + {"queued", "cooldown", "pull_scheduling_paused", ""}, + {"held", "automatic_intent_retained", "pull_scheduling_paused", "does not establish the current PR pause"}, + {"completed", "", "pull_scheduling_paused", ""}, + } { + op := &ReviewOperation{ID: selection.OperationID, State: tc.state, Channel: "cli", Reason: tc.reason, queuedCause: tc.cause} + result := AgentReviewSelection(ReviewRunState{Selection: selection, Operation: op}) + if result.Operation != op || result.Selection != selection { + t.Fatal("changed retained inputs", result) + } + if tc.want == "" { + if result.Diagnostic != nil { + t.Fatal("unexpected scheduling block", result) + } + continue + } + if result.Diagnostic == nil || !strings.Contains(result.Diagnostic.Explanation, tc.want) { + t.Fatal("missing exact scheduling block", result) + } + } +} diff --git a/internal/client/review_scheduling_test.go b/internal/client/review_scheduling_test.go new file mode 100644 index 00000000..56de2bdf --- /dev/null +++ b/internal/client/review_scheduling_test.go @@ -0,0 +1,459 @@ +package client_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "math" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviews" +) + +func TestReviewSchedulingClientActualHTTPControlsDoNotStartWork(t *testing.T) { + f := newMutationFixture(t) + for _, ensure := range []func() error{ + func() error { return reviewexec.EnsureSchema(t.Context(), f.store) }, + func() error { return reviews.EnsureSchema(t.Context(), f.store) }, + } { + if err := ensure(); err != nil { + t.Fatal(err) + } + } + e, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "scheduling-client", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + e.Register(mux) + f.handler = mux + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests.Add(1); f.handler.ServeHTTP(w, r) })) + defer service.Close() + grant := func(token string, permissions []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": permissions})["id"].(string) + } + const ownerToken = "synthetic-scheduling-owner" + ownerID := grant(ownerToken, []string{"manage"}) + grant("synthetic-scheduling-writer", []string{"read", "write"}) + grant("synthetic-scheduling-reader", []string{"read"}) + owner := f.newClient(t, ownerToken, f.sender, service.URL) + writer := f.newClient(t, "synthetic-scheduling-writer", f.sender, service.URL) + reader := f.newClient(t, "synthetic-scheduling-reader", f.sender, service.URL) + providerCalls := f.providerCalls.Load() + initial, err := reader.ReviewScheduling(t.Context()) + if err != nil || initial.Revision != 0 || initial.AutomaticHosted || initial.PausedPulls == nil || len(initial.PausedPulls) != 0 || initial.Reason != "" { + t.Fatal(initial, err) + } + pull, err := reader.ReviewPullScheduling(t.Context(), 2) + if err != nil || pull.Revision != 0 || pull.Paused || pull.ProjectID != f.project || pull.PullNumber != 2 { + t.Fatal(pull, err) + } + paused := client.ConfigureReviewPullSchedulingRequest{Paused: true, Reason: "Fix in progress"} + first, err := writer.ConfigureReviewPullScheduling(t.Context(), "pause-before-intent", 2, paused) + if err != nil || first.ID != "2" || first.Revision != 1 { + t.Fatal(first, err) + } + replay, err := writer.ConfigureReviewPullScheduling(t.Context(), "pause-before-intent", 2, paused) + if err != nil || !reflect.DeepEqual(first, replay) { + t.Fatal("pause replay changed", first, replay, err) + } + _, err = writer.ConfigureReviewPullScheduling(t.Context(), "stale-pause", 2, paused) + checkError(t, err, "review_conflict") + var conflict *client.Error + if !errors.As(err, &conflict) || !strings.Contains(conflict.Action, "reviews scheduling read --pr 2") || !strings.Contains(conflict.Action, "new idempotency key") { + t.Fatal("missing scoped PR conflict guidance", err) + } + _, err = reader.ConfigureReviewPullScheduling(t.Context(), "reader-pause", 2, paused) + checkError(t, err, "forbidden") + _, err = writer.ConfigureReviewPullScheduling(t.Context(), "pause-outside-queue", 99, paused) + if err != nil { + t.Fatal(err) + } + configuration := client.ConfigureReviewExecutionRequest{CapabilityID: "scheduling-client", Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}} + f.call(t, "POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", f.admin, f.sender, configuration) + before := requests.Load() + filtered, err := reader.ReviewScheduling(t.Context()) + if err != nil || requests.Load() != before+1 || len(filtered.PausedPulls) != 1 || filtered.PausedPulls[0].PullNumber != 2 || !filtered.PausedPulls[0].Paused || filtered.PausedPulls[0].Reason != paused.Reason { + t.Fatal("project GET lost queue-filtered pauses or added per-PR requests", filtered, err) + } + enable := client.ConfigureReviewSchedulingRequest{AutomaticHosted: true} + _, err = writer.ConfigureReviewScheduling(t.Context(), "writer-enable", enable) + checkError(t, err, "forbidden") + enabled, err := owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) + if err != nil || enabled.ID != f.project || enabled.Revision != 1 { + t.Fatal(enabled, err) + } + again, err := owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) + if err != nil || !reflect.DeepEqual(enabled, again) { + t.Fatal("enable replay changed", again, err) + } + _, err = owner.ConfigureReviewScheduling(t.Context(), "stale-enable", enable) + checkError(t, err, "review_conflict") + if !errors.As(err, &conflict) || !strings.Contains(conflict.Action, "review_scheduling_read") || !strings.Contains(conflict.Action, "current revision") { + t.Fatal("missing scoped project conflict guidance", err) + } + current, err := reader.ReviewScheduling(t.Context()) + if err != nil || !current.AutomaticHosted || current.Revision != 1 || current.AuthorizingWorkerID != f.sender || current.Reason != "" { + t.Fatal(current, err) + } + _, err = writer.ConfigureReviewPullScheduling(t.Context(), "writer-resume", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: 1, Paused: false, Reason: "discard on resume"}) + if err != nil { + t.Fatal(err) + } + resumed, err := reader.ReviewPullScheduling(t.Context(), 2) + if err != nil || resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { + t.Fatal(resumed, err) + } + // Use the actual server/store rather than inferring persistence from wire shape. + yes, no := true, false + for i, tc := range []struct { + hosted, wantCLI bool + cli *bool + }{{true, true, &yes}, {false, true, nil}, {true, false, &no}} { + rev := int64(i + 1) + request := client.ConfigureReviewSchedulingRequest{ExpectedRevision: rev, AutomaticHosted: tc.hosted, AutomaticCLI: tc.cli} + key := []string{"enable-cli", "preserve-cli", "disable-cli"}[i] + if _, err := owner.ConfigureReviewScheduling(t.Context(), key, request); err != nil { + t.Fatal(err) + } + saved, err := reader.ReviewScheduling(t.Context()) + if err != nil || saved.Revision != rev+1 || saved.AutomaticHosted != tc.hosted || saved.AutomaticCLI != tc.wantCLI { + t.Fatal("wrong stored scheduling settings", saved, err) + } + } + if _, err := f.store.DB().Exec(`UPDATE credentials SET revoked=1 WHERE id=?`, ownerID); err != nil { + t.Fatal(err) + } + withdrawn, err := reader.ReviewScheduling(t.Context()) + if err != nil || !withdrawn.AutomaticHosted || withdrawn.Reason != "authorizer_unavailable" || withdrawn.AuthorizingWorkerID != f.sender || len(withdrawn.PausedPulls) != 0 { + t.Fatal("withdrawn original authorization was not reported truthfully", withdrawn, err) + } + _, err = owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) + checkError(t, err, "unauthorized") + for _, table := range []string{"review_operations", "review_execution_attempts", "review_execution_reservations", "review_execution_evidence", "review_round_completions", "review_selections", "review_automatic_selections"} { + var count int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count != 0 { + t.Fatal("settings handler started or credited review work", table, count, err) + } + } + if f.providerCalls.Load() != providerCalls { + t.Fatal("settings/read/pause contacted a provider") + } +} + +func TestReviewSchedulingClientRejectsMalformedWireAndKeepsUnknownMutationsSingleShot(t *testing.T) { + var response atomic.Value + response.Store(`{"project_id":"project-one","revision":0,"automatic_hosted":false,"paused_pulls":[]}`) + 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) + w.Header().Set("Content-Type", "application/json") + if r.Method == "POST" { + body, _ := io.ReadAll(r.Body) + want := `{"expected_revision":0,"automatic_hosted":true}` + if strings.Contains(r.URL.Path, "/pulls/2/") { + want = `{"expected_revision":0,"paused":true}` + } + if r.Header.Get("Idempotency-Key") != "original-scheduling-key" || r.Header.Get("X-FC-Worker") != "worker-one" || r.Header.Get("X-FC-Instance") != "instance-one" || string(body) != want { + t.Error("mutation lost original key/body/binding") + } + } + _, _ = io.WriteString(w, response.Load().(string)) + })) + defer service.Close() + c := newClient(t, service) + defaultProject := map[string]any{"project_id": "project-one", "revision": 0, "automatic_hosted": false, "paused_pulls": []any{}} + validPaused := map[string]any{"project_id": "project-one", "pull_number": 2, "revision": 1, "paused": true, "reason": "Fixing", "actor_id": "actor-one", "updated_at": "2026-11-01T00:00:00Z"} + // Exhausted stored revisions remain readable; only another increment is + // invalid. Keep the largest legitimate native int64 exact on the wire. + maxProject := map[string]any{} + for key, value := range defaultProject { + maxProject[key] = value + } + maxProject["revision"], maxProject["updated_at"] = int64(math.MaxInt64), "2026-11-01T00:00:00Z" + encoded, _ := json.Marshal(maxProject) + response.Store(string(encoded)) + projectAtLimit, err := c.ReviewScheduling(t.Context()) + if err != nil || projectAtLimit.Revision != math.MaxInt64 { + t.Fatal("exhausted project revision became unreadable", projectAtLimit, err) + } + maxPull := map[string]any{} + for key, value := range validPaused { + maxPull[key] = value + } + maxPull["revision"] = int64(math.MaxInt64) + encoded, _ = json.Marshal(maxPull) + response.Store(string(encoded)) + pullAtLimit, err := c.ReviewPullScheduling(t.Context(), 2) + if err != nil || pullAtLimit.Revision != math.MaxInt64 { + t.Fatal("exhausted PR revision became unreadable", pullAtLimit, err) + } + for _, tc := range []struct { + name string + change func(map[string]any) + }{ + {"project-binding", func(v map[string]any) { v["project_id"] = "another-project" }}, + {"missing-paused-array", func(v map[string]any) { delete(v, "paused_pulls") }}, + {"null-paused-array", func(v map[string]any) { v["paused_pulls"] = nil }}, + {"duplicate-paused", func(v map[string]any) { v["paused_pulls"] = []any{validPaused, validPaused} }}, + {"default-enabled", func(v map[string]any) { v["automatic_hosted"] = true }}, + {"default-dated", func(v map[string]any) { v["updated_at"] = "2026-11-01T00:00:00Z" }}, + {"negative-revision", func(v map[string]any) { v["revision"] = -1 }}, + {"fractional-revision", func(v map[string]any) { v["revision"] = 1.5 }}, + {"bad-date", func(v map[string]any) { v["revision"] = 1; v["updated_at"] = "PRIVATE_INVALID_DATE" }}, + {"zero-date", func(v map[string]any) { v["revision"] = 1; v["updated_at"] = "0001-01-01T00:00:00Z" }}, + {"oversized-date", func(v map[string]any) { + v["revision"] = 1 + v["updated_at"] = "2026-11-01T00:00:00." + strings.Repeat("1", 50) + "Z" + }}, + } { + t.Run(tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range defaultProject { + v[k] = x + } + tc.change(v) + b, _ := json.Marshal(v) + response.Store(string(b)) + _, err := c.ReviewScheduling(t.Context()) + checkError(t, err, "invalid_response", "PRIVATE_INVALID_DATE") + }) + } + for _, tc := range []struct{ name, timestamp string }{ + {"offset", "2026-11-01T05:30:00+05:30"}, + {"redundant-precision", "2026-11-01T00:00:00.000000000Z"}, + } { + t.Run("project-valid-date-"+tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range defaultProject { + v[k] = x + } + v["revision"], v["updated_at"] = 1, tc.timestamp + b, _ := json.Marshal(v) + response.Store(string(b)) + if _, err := c.ReviewScheduling(t.Context()); err != nil { + t.Fatalf("valid RFC3339Nano timestamp %q was rejected: %v", tc.timestamp, err) + } + }) + } + for _, tc := range []struct { + name string + change func(map[string]any) + }{ + {"project-binding", func(v map[string]any) { v["project_id"] = "another-project" }}, + {"pull-binding", func(v map[string]any) { v["pull_number"] = 4 }}, + {"default-paused", func(v map[string]any) { v["revision"] = 0 }}, + {"missing-actor", func(v map[string]any) { delete(v, "actor_id") }}, + {"unpaused-reason", func(v map[string]any) { v["paused"] = false }}, + {"bad-date", func(v map[string]any) { v["updated_at"] = "PRIVATE_INVALID_DATE" }}, + {"zero-date", func(v map[string]any) { v["updated_at"] = "0001-01-01T00:00:00Z" }}, + } { + t.Run("pull-"+tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range validPaused { + v[k] = x + } + tc.change(v) + b, _ := json.Marshal(v) + response.Store(string(b)) + _, err := c.ReviewPullScheduling(t.Context(), 2) + checkError(t, err, "invalid_response") + }) + } + for _, tc := range []struct{ name, timestamp string }{ + {"offset", "2026-11-01T05:30:00+05:30"}, + {"redundant-precision", "2026-11-01T00:00:00.000000000Z"}, + } { + t.Run("pull-valid-date-"+tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range validPaused { + v[k] = x + } + v["updated_at"] = tc.timestamp + b, _ := json.Marshal(v) + response.Store(string(b)) + if _, err := c.ReviewPullScheduling(t.Context(), 2); err != nil { + t.Fatalf("valid RFC3339Nano timestamp %q was rejected: %v", tc.timestamp, err) + } + }) + } + for _, pull := range []bool{false, true} { + body := `{"id":"wrong-target","state":"scheduling_configured","revision":1}` + if pull { + body = `{"id":"4","state":"pull_scheduling_updated","revision":1}` + } + response.Store(body) + before := calls.Load() + var err error + if pull { + _, err = c.ConfigureReviewPullScheduling(t.Context(), "original-scheduling-key", 2, client.ConfigureReviewPullSchedulingRequest{Paused: true}) + } else { + _, err = c.ConfigureReviewScheduling(t.Context(), "original-scheduling-key", client.ConfigureReviewSchedulingRequest{AutomaticHosted: true}) + } + checkError(t, err, "invalid_response") + var unknown *client.Error + if !errors.As(err, &unknown) || !unknown.OutcomeUnknown || calls.Load() != before+1 { + t.Fatal("invalid mutation receipt lost uncertainty or retried", err) + } + } +} + +func TestReviewSchedulingClientLocalValidationNeedsNoConnection(t *testing.T) { + c := &client.Client{} + for _, invoke := range []func() error{ + func() error { _, err := c.ReviewPullScheduling(t.Context(), 0); return err }, + func() error { + _, err := c.ConfigureReviewScheduling(t.Context(), "", client.ConfigureReviewSchedulingRequest{}) + return err + }, + func() error { + _, err := c.ConfigureReviewScheduling(t.Context(), "key", client.ConfigureReviewSchedulingRequest{ExpectedRevision: -1}) + return err + }, + func() error { + _, err := c.ConfigureReviewScheduling(t.Context(), "key", client.ConfigureReviewSchedulingRequest{ExpectedRevision: math.MaxInt64}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2147483648, client.ConfigureReviewPullSchedulingRequest{}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: -1}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: math.MaxInt64}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: "line\nbreak"}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: strings.Repeat("a", 257)}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: string([]byte{255})}) + return err + }, + } { + if err := invoke(); err == nil { + t.Fatal("invalid local input reached the unconfigured connection") + } + } +} + +func TestSchedulingOptionalCLIWireContract(t *testing.T) { + for _, state := range []string{"omitted", "true", "false"} { + request := client.ConfigureReviewSchedulingRequest{AutomaticHosted: true} + want := `{"expected_revision":0,"automatic_hosted":true` + if state != "omitted" { + enabled := state == "true" + request.AutomaticCLI = &enabled + want += `,"automatic_cli":` + state + } + encoded, err := json.Marshal(request) + if err != nil || string(encoded) != want+"}" { + t.Fatalf("wrong optional CLI body: %s %v", encoded, err) + } + } + var response atomic.Value + response.Store("") + service := 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") + _, _ = io.WriteString(w, response.Load().(string)) + })) + defer service.Close() + c := newClient(t, service) + for _, tc := range []struct { + body string + valid, enabled bool + }{ + {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"paused_pulls":[]}`, true, false}, + {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[]}`, false, false}, + {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"automatic_cli":null,"paused_pulls":[]}`, false, false}, + {`{"project_id":"project-one","revision":1,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[],"updated_at":"2026-11-01T00:00:00Z"}`, false, false}, + {`{"project_id":"project-one","revision":1,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[],"updated_at":"2026-11-01T00:00:00Z","authorizing_worker_id":"worker-one"}`, true, true}, + } { + response.Store(tc.body) + value, err := c.ReviewScheduling(t.Context()) + if (err == nil) != tc.valid || tc.valid && value.AutomaticCLI != tc.enabled { + t.Fatalf("wrong scheduling validation: %+v %v", value, err) + } + } +} + +func TestReviewSchedulingClientReadsMaximumEscapedPausedQueue(t *testing.T) { + project := strings.Repeat("<", 128) + value := client.ReviewScheduling{ + ProjectID: project, Revision: math.MaxInt64, AutomaticHosted: true, AutomaticCLI: true, + AuthorizingWorkerID: strings.Repeat("&", 128), UpdatedAt: "2026-11-01T00:00:00.999999999+05:30", + PausedPulls: make([]client.ReviewPullScheduling, 100), + } + for i := range value.PausedPulls { + value.PausedPulls[i] = client.ReviewPullScheduling{ + ProjectID: project, PullNumber: 2147483647 - int64(i), Revision: math.MaxInt64, Paused: true, + Reason: strings.Repeat("<", 256), ActorID: strings.Repeat(">", 128), UpdatedAt: value.UpdatedAt, + } + } + encoded, err := json.Marshal(value) + if err != nil || len(encoded) <= 256<<10 { + t.Fatalf("fixture must exercise escaped reasons and maximum identities: bytes=%d err=%v", len(encoded), err) + } + var response atomic.Value + response.Store(encoded) + 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.Method != http.MethodGet || r.URL.Path != "/api/v1/projects/"+project+"/reviews/scheduling" { + t.Error("scheduling read changed scope or method") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(response.Load().([]byte)) + })) + defer service.Close() + selected := binding(t, service.URL) + selected.Context.ProjectID = project + c, err := client.New(t.Context(), selected) + if err != nil { + t.Fatal(err) + } + defer c.Close() + got, err := c.ReviewScheduling(t.Context()) + if err != nil || !reflect.DeepEqual(got, value) || calls.Load() != 1 { + t.Fatalf("valid maximum escaped scheduling response failed: calls=%d err=%v", calls.Load(), err) + } + // Retain a finite wire bound even for an otherwise valid response. + response.Store(append(append([]byte(nil), encoded...), []byte(strings.Repeat(" ", 512<<10))...)) + _, err = c.ReviewScheduling(t.Context()) + checkError(t, err, "invalid_response") + if calls.Load() != 2 { + t.Fatal("oversized scheduling read retried", calls.Load()) + } +} diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index 5511d5d0..f8fb898b 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -242,6 +242,8 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_obligation_resolve"] = true expected["review_queue_edit"] = true expected["review_operation_control"] = true + expected["review_scheduling_read"], expected["review_scheduling_configure"] = true, true + expected["review_pull_scheduling_read"], expected["review_pull_scheduling_update"] = true, true expected["wait_for_ci"] = true expected["review_rounds_read"], expected["review_rounds_configure"] = true, true expected["review_start"], expected["review_selection_read"] = true, true @@ -267,6 +269,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { writes["review_obligation_resolve"] = true writes["review_rounds_configure"] = true writes["review_operation_control"] = true + writes["review_scheduling_configure"], writes["review_pull_scheduling_update"] = true, 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 @@ -295,13 +298,13 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { if !a.IdempotentHint { t.Errorf("%s idempotentHint: want true, got false", tool.Name) } - wantDestructive := 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" + wantDestructive := tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" || 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" if a.DestructiveHint == nil { t.Errorf("%s destructiveHint: want %v, got nil", tool.Name, wantDestructive) } else if *a.DestructiveHint != wantDestructive { t.Errorf("%s destructiveHint: want %v, got %v", tool.Name, wantDestructive, *a.DestructiveHint) } - wantOpen := 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" + wantOpen := tool.Name == "review_pull_scheduling_update" || tool.Name == "review_scheduling_configure" || 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.OpenWorldHint == nil { t.Errorf("%s openWorldHint: want %v, got nil", tool.Name, wantOpen) } else if *a.OpenWorldHint != wantOpen { diff --git a/internal/mcpadapter/arguments.go b/internal/mcpadapter/arguments.go index 5554bf7b..f116fd64 100644 --- a/internal/mcpadapter/arguments.go +++ b/internal/mcpadapter/arguments.go @@ -63,6 +63,9 @@ func invalidArguments() *Diagnostic { } func parseArguments(name string, data json.RawMessage) (arguments, error) { + if reviewSchedulingTool(name) { + return reviewSchedulingArguments(name, data) + } if name == "wait_for_ci" { return ciWatchArguments(data) } diff --git a/internal/mcpadapter/review_scheduling.go b/internal/mcpadapter/review_scheduling.go new file mode 100644 index 00000000..8eb76a61 --- /dev/null +++ b/internal/mcpadapter/review_scheduling.go @@ -0,0 +1,146 @@ +package mcpadapter + +import ( + "bytes" + "encoding/json" + "math" + "math/big" + "strconv" + "strings" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +// schedulingInteger accepts the exact integral JSON numbers advertised by the +// scheduling tool schema. Do not pass through float64: revision CAS might target +// a different revision above the binary64 exact-integer range. +type schedulingInteger int64 + +func (n *schedulingInteger) UnmarshalJSON(raw []byte) error { + s := string(raw) + if len(s) == 0 || (s[0] != '-' && (s[0] < '0' || s[0] > '9')) || !json.Valid(raw) { + return invalidArguments() + } + if i := strings.IndexAny(s, "eE"); i >= 0 { + // Bound exponent work before exact rational parsing. The caller's + // 4096-byte input ceiling makes any nonzero value beyond this + // bound either fractional or outside int64. + exp, err := strconv.ParseInt(s[i+1:], 10, 16) + if err != nil || exp < -4116 || exp > 4116 { + mantissa := strings.TrimLeft(s[:i], "-0.") + if mantissa == "" { + *n = 0 + return nil + } + return invalidArguments() + } + } + v, ok := new(big.Rat).SetString(s) + if !ok || !v.IsInt() || !v.Num().IsInt64() { + return invalidArguments() + } + *n = schedulingInteger(v.Num().Int64()) + return nil +} + +func reviewSchedulingWrite(name string) bool { + return name == "review_scheduling_configure" || name == "review_pull_scheduling_update" +} + +func reviewSchedulingTool(name string) bool { + return reviewSchedulingWrite(name) || name == "review_scheduling_read" || name == "review_pull_scheduling_read" +} + +func reviewSchedulingArguments(name string, raw json.RawMessage) (arguments, error) { + var args arguments + if len(raw) == 0 { + raw = []byte("{}") + } + trimmed := bytes.TrimSpace(raw) + if len(raw) > 4096 || len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' { + return args, invalidArguments() + } + if name == "review_scheduling_read" { + var empty struct{} + if strictjson.Decode(raw, &empty) != nil { + return args, invalidArguments() + } + return args, nil + } + if name == "review_pull_scheduling_read" { + var wire struct { + PullNumber schedulingInteger `json:"pull_number"` + } + if strictjson.Decode(raw, &wire) != nil || wire.PullNumber < 1 || wire.PullNumber > 2147483647 { + return args, invalidArguments() + } + args.pullNumber = int64(wire.PullNumber) + return args, nil + } + if name == "review_scheduling_configure" { + var wire struct { + Revision *schedulingInteger `json:"expected_revision"` + Enabled *bool `json:"automatic_hosted"` + CLI *bool `json:"automatic_cli,omitempty"` + Key string `json:"idempotency_key"` + } + if strictjson.Decode(raw, &wire) != nil || wire.Revision == nil || wire.Enabled == nil || !client.ValidMutationKey(wire.Key) { + return args, invalidArguments() + } + var present map[string]json.RawMessage + if json.Unmarshal(raw, &present) != nil || present["automatic_cli"] != nil && wire.CLI == nil { + return args, invalidArguments() + } + args.key = wire.Key + args.reviewScheduling = client.ConfigureReviewSchedulingRequest{ExpectedRevision: int64(*wire.Revision), AutomaticHosted: *wire.Enabled, AutomaticCLI: wire.CLI} + if client.ValidateConfigureReviewScheduling(args.reviewScheduling) != nil { + return arguments{}, invalidArguments() + } + return args, nil + } + var wire struct { + PullNumber schedulingInteger `json:"pull_number"` + Revision *schedulingInteger `json:"expected_revision"` + Paused *bool `json:"paused"` + Reason *string `json:"reason,omitempty"` + Key string `json:"idempotency_key"` + } + if name != "review_pull_scheduling_update" || strictjson.Decode(raw, &wire) != nil || wire.Revision == nil || wire.Paused == nil || !client.ValidMutationKey(wire.Key) { + return args, invalidArguments() + } + var present map[string]json.RawMessage + if json.Unmarshal(raw, &present) != nil || present["reason"] != nil && (wire.Reason == nil || !*wire.Paused) { + return args, invalidArguments() + } + args.key, args.pullNumber = wire.Key, int64(wire.PullNumber) + args.reviewPullScheduling = client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: int64(*wire.Revision), Paused: *wire.Paused} + if wire.Reason != nil { + args.reviewPullScheduling.Reason = *wire.Reason + } + if client.ValidateConfigureReviewPullScheduling(args.pullNumber, args.reviewPullScheduling) != nil { + return arguments{}, invalidArguments() + } + return args, nil +} + +func reviewSchedulingDefinitions() []definition { + object := func(properties map[string]any, required ...string) map[string]any { + if required == nil { + required = []string{} + } + return map[string]any{"type": "object", "additionalProperties": false, "properties": properties, "required": required} + } + revision := map[string]any{"type": "integer", "minimum": 0, "maximum": int64(math.MaxInt64 - 1)} + pull := map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647} + key := map[string]any{"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[!-~]([ -~]{0,126}[!-~])?$", "description": "One to 128 printable ASCII bytes with no leading or trailing space. Retain the original key with the exact request after an unknown outcome."} + pullUpdate := object(map[string]any{"pull_number": pull, "expected_revision": revision, "paused": map[string]any{"type": "boolean"}, "reason": map[string]any{"type": "string", "maxLength": 256, "description": "Optional non-control text limited to 256 UTF-8 bytes; omit on resume."}, "idempotency_key": key}, "pull_number", "expected_revision", "paused", "idempotency_key") + pullUpdate["if"] = map[string]any{"properties": map[string]any{"paused": map[string]any{"const": false}}} + pullUpdate["then"] = map[string]any{"not": map[string]any{"required": []string{"reason"}}} + return []definition{ + {"review_scheduling_read", "Read this project's automatic Hosted and CLI settings and current queued PR pauses in one provider-free call. No settings, review or allowance changes. See docs/review-scheduling.md.", object(map[string]any{})}, + {"review_scheduling_configure", "Project manager: explicitly enable or disable automatic future Hosted or CLI requests under existing source, obligation, round and provider guards. Both default off. Optional automatic_cli preserves the current CLI setting when omitted. Existing grants and taper apply; no automatic adjudication or grant increase. If either channel stays enabled, this connection's current credential and active bound worker become the shared authorizer for new work, even when disabling only the other channel. Omission preserves the CLI setting, not the authorizer; withdrawn authority stops new automatic actions. This setting can authorize asynchronous provider work. Current revision and explicit key required; no automatic mutation retry. See docs/review-scheduling.md.", object(map[string]any{"expected_revision": revision, "automatic_hosted": map[string]any{"type": "boolean"}, "automatic_cli": map[string]any{"type": "boolean", "description": "Optional CLI opt-in; omission preserves the current setting."}, "idempotency_key": key}, "expected_revision", "automatic_hosted", "idempotency_key")}, + {"review_pull_scheduling_read", "Read one PR's temporary scheduling pause before or after an intent exists. Does not change Draft, grant, taper, closure or active provider work.", object(map[string]any{"pull_number": pull}, "pull_number")}, + {"review_pull_scheduling_update", "Writer: explicitly pause or resume new and undispatched reviews for one PR, including automatic Hosted and CLI selection. Does not cancel already-issued reviews or stop collecting results, change round credit or clear a separate operation pause. Retain current revision/key; reason is optional plain text only while paused and must be omitted on resume. See docs/review-scheduling.md.", pullUpdate}, + } +} diff --git a/internal/mcpadapter/review_scheduling_arguments_test.go b/internal/mcpadapter/review_scheduling_arguments_test.go new file mode 100644 index 00000000..4db339b3 --- /dev/null +++ b/internal/mcpadapter/review_scheduling_arguments_test.go @@ -0,0 +1,73 @@ +package mcpadapter + +import ( + "encoding/json" + "testing" +) + +func TestSchedulingOptionalCLIArguments(t *testing.T) { + for _, value := range []string{"", "true", "false"} { + raw := `{"expected_revision":0,"automatic_hosted":false,"idempotency_key":"cli-setting"` + if value != "" { + raw += `,"automatic_cli":` + value + } + args, err := reviewSchedulingArguments("review_scheduling_configure", json.RawMessage(raw+"}")) + if err != nil || (args.reviewScheduling.AutomaticCLI == nil) != (value == "") { + t.Fatalf("lost optional CLI state %q: %+v %v", value, args, err) + } + if value != "" && *args.reviewScheduling.AutomaticCLI != (value == "true") { + t.Fatal("wrong CLI state") + } + } + for _, raw := range []string{ + `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":null,"idempotency_key":"key"}`, + `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":"true","idempotency_key":"key"}`, + `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":true,"automatic_cli":false,"idempotency_key":"key"}`, + `{"expected_revision":0,"automatic_cli":true,"idempotency_key":"key"}`, + } { + if _, err := reviewSchedulingArguments("review_scheduling_configure", json.RawMessage(raw)); err == nil { + t.Fatal("accepted malformed CLI configuration", raw) + } + } +} + +func TestSchedulingPauseReasonIsOmittedOnResume(t *testing.T) { + for _, raw := range []string{ + `{"pull_number":7,"expected_revision":2,"paused":false,"idempotency_key":"resume"}`, + `{"pull_number":7,"expected_revision":2,"paused":true,"reason":"","idempotency_key":"pause-empty-reason"}`, + `{"pull_number":7,"expected_revision":2,"paused":true,"reason":"Fixing","idempotency_key":"pause-reason"}`, + } { + if _, err := reviewSchedulingArguments("review_pull_scheduling_update", json.RawMessage(raw)); err != nil { + t.Fatalf("rejected valid scheduling update %s: %v", raw, err) + } + } + for _, raw := range []string{ + `{"pull_number":7,"expected_revision":2,"paused":false,"reason":"no longer allowed","idempotency_key":"resume-reason"}`, + `{"pull_number":7,"expected_revision":2,"paused":false,"reason":"","idempotency_key":"resume-empty-reason"}`, + `{"pull_number":7,"expected_revision":2,"paused":false,"reason":null,"idempotency_key":"resume-null-reason"}`, + } { + if _, err := reviewSchedulingArguments("review_pull_scheduling_update", json.RawMessage(raw)); err == nil { + t.Fatalf("accepted reason on resume: %s", raw) + } + } +} + +func TestSchedulingEquivalentJSONIntegersAreExact(t *testing.T) { + read, err := reviewSchedulingArguments("review_pull_scheduling_read", []byte(`{"pull_number":7.0}`)) + if err != nil || read.pullNumber != 7 { + t.Fatalf("schema-interoperable read rejected: %v %v", read.pullNumber, err) + } + write, err := reviewSchedulingArguments("review_scheduling_configure", []byte(`{"expected_revision":9007199254740993.0,"automatic_hosted":false,"idempotency_key":"test"}`)) + if err != nil || write.reviewScheduling.ExpectedRevision != 9007199254740993 { + t.Fatalf("revision rounded or rejected: %v %v", write.reviewScheduling.ExpectedRevision, err) + } + pause, err := reviewSchedulingArguments("review_pull_scheduling_update", []byte(`{"pull_number":70e-1,"expected_revision":0.0,"paused":true,"reason":"work","idempotency_key":"test"}`)) + if err != nil || pause.pullNumber != 7 || pause.reviewPullScheduling.ExpectedRevision != 0 { + t.Fatalf("equivalent update rejected: %v %v", pause.pullNumber, err) + } + for _, raw := range []string{`7.1`, `"7"`, `null`, `2147483648.0`, `7.00000000000000000001`, `7e-999999`} { + if _, err := reviewSchedulingArguments("review_pull_scheduling_read", []byte(`{"pull_number":`+raw+`}`)); err == nil { + t.Errorf("accepted invalid pull number %s", raw) + } + } +} diff --git a/internal/mcpadapter/review_scheduling_schema_test.go b/internal/mcpadapter/review_scheduling_schema_test.go new file mode 100644 index 00000000..4b78154f --- /dev/null +++ b/internal/mcpadapter/review_scheduling_schema_test.go @@ -0,0 +1,83 @@ +package mcpadapter + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/google/jsonschema-go/jsonschema" +) + +func TestSchedulingToolSchemasMatchReasonAndKeyValidation(t *testing.T) { + for _, definition := range reviewSchedulingDefinitions() { + if !reviewSchedulingWrite(definition.name) { + continue + } + input, err := json.Marshal(definition.schema) + if err != nil { + t.Fatal(err) + } + var schema jsonschema.Schema + if err = json.Unmarshal(input, &schema); err != nil { + t.Fatal(err) + } + rule, err := schema.Resolve(nil) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name, key string + paused bool + reason *string + want bool + }{ + {"one ASCII", "x", false, nil, true}, + {"retain interior spaces", "with spaces", true, nil, true}, + {"flag-shaped literal", "--literal=value", false, nil, true}, + {"at byte limit", strings.Repeat("x", 128), true, nil, true}, + {"too long", strings.Repeat("x", 129), true, nil, false}, + {"non ASCII", "pr-é", true, nil, false}, + {"leading space", " bad", true, nil, false}, + {"trailing space", "bad ", true, nil, false}, + {"line break", "bad\n", true, nil, false}, + {"paused reason", "key", true, ptrString(""), true}, + {"resume reason", "key", false, ptrString(""), false}, + } { + args := map[string]any{"expected_revision": 1, "idempotency_key": tc.key} + if definition.name == "review_pull_scheduling_update" { + args["pull_number"], args["paused"] = 4, tc.paused + if tc.reason != nil { + args["reason"] = *tc.reason + } + } else { + if tc.reason != nil { + continue + } + args["automatic_hosted"] = false + } + b, err := json.Marshal(args) + if err != nil { + t.Fatal(err) + } + var instance any + if err = json.Unmarshal(b, &instance); err != nil { + t.Fatal(err) + } + _, parsed := reviewSchedulingArguments(definition.name, b) + if (rule.Validate(instance) == nil) != tc.want || (parsed == nil) != tc.want { + t.Fatalf("%s/%s: schema %v parser %v", definition.name, tc.name, rule.Validate(instance), parsed) + } + } + if definition.name == "review_pull_scheduling_update" { + if !strings.Contains(string(input), "256 UTF-8 bytes") { + t.Fatal("reason limit missing") + } + b, _ := json.Marshal(map[string]any{"expected_revision": 1, "pull_number": 4, "paused": true, "reason": strings.Repeat("é", 129), "idempotency_key": "key"}) + if _, err := reviewSchedulingArguments(definition.name, b); err == nil { + t.Fatal("invalid UTF-8 byte budget accepted") + } + } + } +} + +func ptrString(value string) *string { return &value } diff --git a/internal/mcpadapter/review_scheduling_test.go b/internal/mcpadapter/review_scheduling_test.go new file mode 100644 index 00000000..4b47ade6 --- /dev/null +++ b/internal/mcpadapter/review_scheduling_test.go @@ -0,0 +1,121 @@ +package mcpadapter_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" + "github.com/benhook1013/FireController/internal/reviewexec" +) + +func TestSchedulingSDKBoundControlsAndDiscovery(t *testing.T) { + f := mutationFixture(t) + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "scheduling-fixture", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + engine.Register(mux) + server := httptest.NewServer(mux) + defer server.Close() + managerCredential := filepath.Join(t.TempDir(), "manager.token") + if err := os.WriteFile(managerCredential, []byte(f.admin), 0600); err != nil { + t.Fatal(err) + } + managerProfile := profiles(t, map[string]profile.Context{"chosen": {Profile: "chosen", ServerURL: server.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender}}, managerCredential) + manager := reviewControlsStdio(t, managerProfile, "chosen") + writer := connect(t, f.adapter(t, server.URL, f.sender), "") + beforeProviders := f.providers.Load() + var initial client.ReviewScheduling + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &initial) + if initial.Revision != 0 || initial.AutomaticHosted || initial.PausedPulls == nil { + t.Fatal(initial) + } + diagnosticResult(t, call(t, writer, "review_scheduling_configure", map[string]any{"expected_revision": 0, "automatic_hosted": true, "idempotency_key": "writer-cannot-enable"}), "forbidden", false) + input := map[string]any{"expected_revision": 0, "automatic_hosted": true, "idempotency_key": "manager-enable"} + var first, replay client.ReviewRequestReceipt + decodeResult(t, call(t, manager, "review_scheduling_configure", input), &first) + decodeResult(t, call(t, manager, "review_scheduling_configure", input), &replay) + if first != replay || first.ID != f.project || first.Revision != 1 { + t.Fatal(first, replay) + } + // CLI opt-in is independent; a legacy Hosted-only write preserves it. + decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 1, "automatic_hosted": false, "automatic_cli": true, "idempotency_key": "manager-cli-enable"}), &first) + var automatic client.ReviewScheduling + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) + if automatic.AutomaticHosted || !automatic.AutomaticCLI || automatic.AuthorizingWorkerID != f.sender { + t.Fatal("CLI opt-in lost shared authorization", automatic) + } + decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 2, "automatic_hosted": true, "idempotency_key": "manager-legacy-preserve"}), &first) + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) + if !automatic.AutomaticHosted || !automatic.AutomaticCLI { + t.Fatal("legacy configuration changed CLI opt-in", automatic) + } + decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 3, "automatic_hosted": true, "automatic_cli": false, "idempotency_key": "manager-cli-disable"}), &first) + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) + if !automatic.AutomaticHosted || automatic.AutomaticCLI { + t.Fatal("explicit CLI disable was lost", automatic) + } + var paused client.ReviewRequestReceipt + decodeResult(t, call(t, writer, "review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 0, "paused": true, "reason": "Preparing changes", "idempotency_key": "pause-before-intent"}), &paused) + if paused.ID != strconv.Itoa(7) || paused.Revision != 1 { + t.Fatal(paused) + } + var state client.ReviewPullScheduling + decodeResult(t, call(t, writer, "review_pull_scheduling_read", map[string]any{"pull_number": json.RawMessage("7.0")}), &state) + if !state.Paused || state.Reason != "Preparing changes" || state.ProjectID != f.project { + t.Fatal(state) + } + decodeResult(t, call(t, writer, "review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 1, "paused": false, "idempotency_key": "resume-before-intent"}), &paused) + decodeResult(t, call(t, writer, "review_pull_scheduling_read", map[string]any{"pull_number": 7}), &state) + if state.Paused || state.Reason != "" || state.Revision != 2 { + t.Fatal(state) + } + for _, tc := range []struct { + name string + args map[string]any + }{ + {"review_scheduling_read", map[string]any{"project_id": "foreign"}}, + {"review_scheduling_configure", map[string]any{"expected_revision": 1, "automatic_hosted": nil, "idempotency_key": "null"}}, + {"review_scheduling_configure", map[string]any{"expected_revision": 1, "idempotency_key": "missing-bool"}}, + {"review_pull_scheduling_read", map[string]any{"pull_number": 0}}, + {"review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 2, "paused": nil, "idempotency_key": "null-pause"}}, + {"review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 2, "paused": true, "reason": nil, "idempotency_key": "null-reason"}}, + } { + diagnosticResult(t, call(t, manager, tc.name, tc.args), "invalid_arguments", false) + } + listed, err := allDiscoveredTools(t, manager) + if err != nil { + t.Fatal(err) + } + seen := 0 + for _, tool := range listed.Tools { + if tool.Name != "review_scheduling_read" && tool.Name != "review_scheduling_configure" && tool.Name != "review_pull_scheduling_read" && tool.Name != "review_pull_scheduling_update" { + continue + } + seen++ + write := tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" + if tool.Annotations == nil || tool.Annotations.ReadOnlyHint == write || tool.Annotations.OpenWorldHint == nil || *tool.Annotations.OpenWorldHint != (tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update") { + t.Fatal("unsafe annotations", tool.Name) + } + } + if seen != 4 || f.providers.Load() != beforeProviders { + t.Fatal("missing tools or provider work", seen, f.providers.Load(), beforeProviders) + } + for _, table := range []string{"review_selections", "review_operations", "review_execution_attempts"} { + var n int + if err := f.store.DB().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil || n != 0 { + t.Fatal("handler started review work", table, n, err) + } + } +} diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index fb60b931..064f3cd2 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -20,6 +20,8 @@ const maxToolWaitSeconds = 50 type arguments struct { operationControl client.ReviewOperationControl + reviewScheduling client.ConfigureReviewSchedulingRequest + reviewPullScheduling client.ConfigureReviewPullSchedulingRequest ciWatchTargets []client.CIWatchTarget ownerManagement *ownerManagementInvocation existingManagement *existingManagementArgs @@ -84,13 +86,14 @@ func boundServer(binding profile.Binding) *mcp.Server { definitions = append(definitions, projectMapDefinitions()...) definitions = append(definitions, jobContextDefinition(), messageWaitDefinition()) definitions = append(definitions, ciWatchDefinition()) + definitions = append(definitions, reviewSchedulingDefinitions()...) known := make(map[string]bool) transports := sessionTransports{pools: make(map[*mcp.ServerSession]*client.TransportPool)} for _, tool := range definitions { known[tool.name] = true - 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 := 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" + write := reviewSchedulingWrite(tool.name) || 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 == "review_pull_scheduling_update" || tool.name == "review_scheduling_configure" || tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + destructive := reviewSchedulingWrite(tool.name) || 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 @@ -202,6 +205,14 @@ func boundServer(binding profile.Binding) *mcp.Server { value, err = service.ReviewExecution(ctx) case "review_operations_list": value, err = service.ReviewOperations(ctx, args.reviewOperations) + case "review_scheduling_read": + value, err = service.ReviewScheduling(ctx) + case "review_scheduling_configure": + value, err = service.ConfigureReviewScheduling(ctx, args.key, args.reviewScheduling) + case "review_pull_scheduling_read": + value, err = service.ReviewPullScheduling(ctx, args.pullNumber) + case "review_pull_scheduling_update": + value, err = service.ConfigureReviewPullScheduling(ctx, args.key, args.pullNumber, args.reviewPullScheduling) case "wait_for_ci": var watch client.CIWatchResult watch, err = service.WatchCI(ctx, args.ciWatchTargets, args.reviewSourceWait) diff --git a/tools/packagedsmoke/project_management_test.go b/tools/packagedsmoke/project_management_test.go index b6622d25..9bf486b3 100644 --- a/tools/packagedsmoke/project_management_test.go +++ b/tools/packagedsmoke/project_management_test.go @@ -113,6 +113,18 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { var owner client.ProjectCredentialReceipt decode(t, cli(adminProfile, "admin", "credentials", "grant", "--credential-file", managerFile, "--permission", "manage", "--key", "grant-manager"), &owner) managerProfile := profile("manager", managerFile) + // Scheduling configuration is independent of execution configuration and keeps + // exact control identities across native CLI/MCP and restart. + var scheduling client.ReviewScheduling + decode(t, cli(managerProfile, "manager", "reviews", "scheduling"), &scheduling) + if scheduling.Revision != 0 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { + t.Fatal("new scheduling is not off", scheduling) + } + configured := cli(managerProfile, "manager", "reviews", "scheduling", "configure", "--automatic-hosted", "false", "--automatic-cli", "false", "--expect-revision", "0", "--key", "scheduling-off") + if !bytes.Equal(configured, cli(managerProfile, "manager", "reviews", "scheduling", "configure", "--automatic-hosted", "false", "--automatic-cli", "false", "--expect-revision", "0", "--key", "scheduling-off")) { + t.Fatal("scheduling exact replay changed") + } + var grant client.ProjectCredentialReceipt decode(t, cli(managerProfile, "manager", "credentials", "grant", "--credential-file", readerFile, "--permission", "read", "--key", "grant-reader"), &grant) permissionFile := filepath.Join(private, "permissions.json") @@ -155,6 +167,13 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { t.Fatal("missing MCP text") return nil } + + call("review_pull_scheduling_update", map[string]any{"pull_number": 42, "paused": true, "reason": "Synthetic scheduling hold", "expected_revision": 0, "idempotency_key": "scheduling-pause"}) + var paused client.ReviewPullScheduling + decode(t, call("review_pull_scheduling_read", map[string]any{"pull_number": 42}), &paused) + if !paused.Paused || paused.Revision != 1 { + t.Fatal("MCP pause not retained", paused) + } call("inbox_ack", map[string]any{"message_id": message.ID, "worker_id": target.ID, "idempotency_key": "peer-ack"}) var retired client.WorkerRetirementReceipt decode(t, call("worker_retire", map[string]any{"worker_id": target.ID, "idempotency_key": "retire"}), &retired) @@ -178,8 +197,27 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { daemon.stop(t) daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) managerProfile = profile("manager-restarted", managerFile) + var restartedPause client.ReviewPullScheduling + decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling", "read", "--pr", "42"), &restartedPause) + if !restartedPause.Paused || restartedPause.Revision != 1 || restartedPause.Reason != "Synthetic scheduling hold" { + t.Fatal("restart changed paused scheduling control", restartedPause) + } + cli(managerProfile, "manager-restarted", "reviews", "scheduling", "resume", "--pr", "42", "--expect-revision", "1", "--key", "scheduling-resume") + daemon.stop(t) + daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) + managerProfile = profile("manager-resumed", managerFile) + var resumed client.ReviewPullScheduling + decode(t, cli(managerProfile, "manager-resumed", "reviews", "scheduling", "read", "--pr", "42"), &resumed) + if resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { + t.Fatal("restart changed scheduling control", resumed) + } + decode(t, cli(managerProfile, "manager-resumed", "reviews", "scheduling"), &scheduling) + if scheduling.Revision != 1 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { + t.Fatal("restart changed default-off control", scheduling) + } + var replay client.WorkerRetirementReceipt - decode(t, cli(managerProfile, "manager-restarted", "workers", "retire", target.ID, "--key", "retire"), &replay) + decode(t, cli(managerProfile, "manager-resumed", "workers", "retire", target.ID, "--key", "retire"), &replay) if replay != retired { t.Fatal("restart changed retirement receipt") }