From 7cea7544dcfc1915fc7cdc3f4d3a3dc54f8a61b9 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 9 Nov 2026 17:54:23 +0000 Subject: [PATCH 1/3] fix(roadmap): keep the refused stage reply and end a placeholder reply at once --- docs/ERRORS.md | 1 + docs/TELEMETRY.md | 2 +- k8s/README.md | 2 +- .../.openspec.yaml | 3 + .../4204-keep-refused-stage-reply/design.md | 18 + .../4204-keep-refused-stage-reply/proposal.md | 56 +++ .../specs/roadmap-stage-eval/spec.md | 12 + .../specs/roadmap-stage/spec.md | 30 ++ .../4204-keep-refused-stage-reply/tasks.md | 19 ++ src/devops_cli/config/constants.py | 5 + src/devops_cli/exceptions/__init__.py | 2 + src/devops_cli/exceptions/roadmap.py | 8 + src/devops_cli/lang/en/messages.py | 4 + src/devops_cli/roadmap/agent_run.py | 6 +- src/devops_cli/roadmap/stage/stage.py | 120 ++++++- .../roadmap/stage/stage_eval_run.py | 14 +- .../roadmap/stage/stage_plan_record.py | 65 +++- src/devops_cli/telemetry/instruments.py | 5 +- .../stage/test_roadmap_stage_eval_run.py | 21 ++ .../stage/test_roadmap_stage_refused_reply.py | 318 ++++++++++++++++++ 20 files changed, 693 insertions(+), 18 deletions(-) create mode 100644 openspec/changes/4204-keep-refused-stage-reply/.openspec.yaml create mode 100644 openspec/changes/4204-keep-refused-stage-reply/design.md create mode 100644 openspec/changes/4204-keep-refused-stage-reply/proposal.md create mode 100644 openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md create mode 100644 openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md create mode 100644 openspec/changes/4204-keep-refused-stage-reply/tasks.md create mode 100644 tests/roadmap/stage/test_roadmap_stage_refused_reply.py diff --git a/docs/ERRORS.md b/docs/ERRORS.md index a10ad62f6f..809d4ee9fb 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -108,6 +108,7 @@ Each exception class declares its `error_code` and `exit_code`. A command that a | `RoadmapPlanRewriteError` | `ROADMAP_PLAN_REWRITE_REFUSED` | `1` | Roadmap | Raised when `devops roadmap plan-recheck --confirm` refuses to write a rewritten plan (#3556). | | `RoadmapRefineError` | `ROADMAP_REFINE_FAILED` | `1` | Roadmap | Raised after a refine run in which the model call failed for one or more items. | | `RoadmapRunError` | `DEVOPS_CLI_ERROR` | `1` | Roadmap | Raised when one or more roadmap jobs fail during execution. | +| `RoadmapStageDegenerateError` | `ROADMAP_STAGE_FAILED` | `1` | Roadmap | Raised for an item whose plan reply holds a placeholder in every text of the plan (#4204). | | `RoadmapStageError` | `ROADMAP_STAGE_FAILED` | `1` | Roadmap | Raised after a stage run in which one or more items failed (#2654). | | `RunIndexNotConfiguredError` | `DEVOPS_CLI_ERROR` | `1` | Devops_cli.ai.run_store | No shared run index is configured. | | `SSHRegistrationError` | `GITHUB_OPERATION_FAILED` | `1` | Devops_cli.github.ssh | Raised when SSH/signing key registration on GitHub fails. | diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index e0bde19886..f055284a36 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -103,7 +103,7 @@ writes by name. | `devops_cli_roadmap_alternatives_searches` | Histogram | `1` | Web searches that a provider answered for one alternatives check, by verdict. One observation for each check that the alternatives job writes. A search that no provider answered does not count. A check that the job skips for its item class runs no search and observes 0. | | `devops_cli_roadmap_page_fetches_total` | Counter | `1` | Calls of the tool fetch_page in refine's investigation and in the alternatives check, by toolset (refine or alternatives) and result: ok for a page whose text the tool returned, refused for a URL that the tool refused before any request (not https, not named by a search result or by the item text, or not on a public host), limit for a call over the limit of fetches for one item, and error for a fetch that failed. The fetches that reach the Crawl4AI service also count in devops_cli_crawl4ai_fetches_total. | | `devops_cli_roadmap_stage_plan_record_total` | Counter | `1` | Uses of the plan file of the stage job, by result: hit for a plan that the job read from the file and so sent the planner no request, miss for an item with no file of its key, and written for a plan that the job wrote to the file. A miss that plans adds one to miss and one to written. The hit rate is hit divided by the sum of hit and miss. | -| `devops_cli_roadmap_stage_total` | Counter | `1` | Items that a stage round handled, one count for each item, by repository and result: staged for an item written as a branch and a draft pull request, needs_split for an item stopped on a task group over the budget, failed for an item that failed in the plan or in the writes, and skipped for an item the job left out with a reason. A plan with no write counts nothing. | +| `devops_cli_roadmap_stage_total` | Counter | `1` | Items that a stage round handled, one count for each item, by repository and result: staged for an item written as a branch and a draft pull request, needs_split for an item stopped on a task group over the budget, failed for an item that failed in the plan or in the writes, degenerate for an item whose plan reply was a placeholder in every text (the job sent no second request), and skipped for an item the job left out with a reason. A plan with no write counts nothing. | | `devops_cli_roadmap_tool_calls_total` | Counter | `1` | Tool calls of the roadmap planner and verifier, by tool, row, toolset and outcome. The outcome ok is a call that gave its result. The outcome empty is a call that ran and found nothing, such as a search with no match. The outcome error is a call that could not run or got no answer. The row is the job row of the run: stage for the planner, stage_verify for the verifier. Each run adds 0 for every tool of its toolset before its first model request. So a tool that no run calls keeps a series. | | `devops_cli_roadmap_tool_answer_chars` | Histogram | `{char}` | Characters in the answer of each tool call of the roadmap planner and verifier, after the cut of the tool, by tool, row and toolset. The text of a refusal counts. A call that got no answer adds no observation. | | `devops_cli_roadmap_tool_calls_per_run` | Histogram | `{call}` | Tool calls of each run of the roadmap planner and verifier, by row and toolset. A run that raised because a model call failed adds no observation. | diff --git a/k8s/README.md b/k8s/README.md index cf5909a92e..8b9a264a66 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -682,7 +682,7 @@ kubectl -n devops logs -f job/ 12. The Service's `/metrics` shows the budget and the suspended jobs (#2475): `devops_cli_service_budget_limit_requests` (the hourly budget), `devops_cli_service_budget_spent_requests` (the GitHub requests of the last hour, not counting the answers with status 304, which GitHub does not count against its rate limit), `devops_cli_service_budget_holds_total` (one count each time a hold begins), `devops_cli_service_job_suspended` (1 while a job of a repository, by `repo`, `row` and `class`, waits for its retry time or for new input after it failed 3 rounds in a row; `class` is the failure class of its last failed round, or `unknown` for an entry that an earlier version wrote; when the class changes, the series of the old class is set to 0), `devops_cli_service_job_retry_after_seconds` (the seconds before the next probe round of the job, by `repo`, `row` and `class`, as of its last failed round or check; 0 when the job has no retry time; #4065), `devops_cli_service_state_unkept` (1 while the last write of a state record failed, by `record`: `budget`, `halt` or `ledger`; 0 after the next write that works; #4048), `devops_cli_service_implement_jobs_total` (one count for each reported runner Job, by `repo`, `item_class` and `result`: `succeeded`, `failed` or `gone`; #3069), `devops_cli_service_implement_repair_rounds_total` (one count for each repair round of a reported runner Job, by `repo` and `item_class`; #3069), `devops_cli_service_implement_tokens_total` (tokens spent by a reported runner Job, by `repo` and `item_class`; #3069), `devops_cli_service_implement_consecutive_failures` (gauge of stops in a row of the same failure `class` for `repo`, kept in `service-consecutive-failures.json`; #3069) and `devops_cli_service_implement_failures_total` (one count for each runner Job that left a stop, by the failure `class` and `repo`, when a round reports the Job; #3065; the values of `class` are the classes in [docs/ROADMAP_WORKFLOW.md](../docs/ROADMAP_WORKFLOW.md), The failure classes, and a panel or rule matches no other value, #3476). Each counter of the Service starts its label sets at zero (#3495, [docs/TELEMETRY.md](../docs/TELEMETRY.md)), except `devops_cli_service_identity_refused_total`, whose label set starts with the first refusal. Each GitHub request counts in `devops_cli_github_requests_total` under its `method`, its `status` (the HTTP status of the answer, or `none` for a gh command or an attempt with no answer), the `repo` of the worker that sent it and the job `row` (`metrics`, `intake`, `refine`, `retitle`, `stage`, `implement`, `stage_ready` or `alternatives`); a request outside a worker or a row counts as `other`. To find what spent the budget, run `sum by (repo, row, method) (increase(devops_cli_github_requests_total{job="roadmap-service"}[1h]))` in Grafana Explore. A delivery of the App bot's own write counts as outcome `self` in `devops_cli_service_webhook_deliveries_total`. 13. A refine round writes at most 2 comments on one item in 24 hours. A round that finds 2 refine comments of the last 24 hours on an item leaves the item alone, with no model call and no comment. The item waits on a person and takes no place under the round's limit, so the round refines the next item. For each newest comment on the item that the cap leaves with no answer, the round records the time of that comment in the item's job record (`refine.capped_after`), logs `Refine left # alone and wrote no comment`, and adds 1 to `devops_cli_roadmap_refine_comments_capped_total`. A later round that finds no newer comment does not log or count the item again. A person refines the item at the cap with `devops roadmap refine --item --confirm`. A web search asks the providers of `search.providers` in order (`searxng`, `duckduckgo`, `firecrawl` by default, #3925). A provider that is not configured is skipped: `searxng` without `search.searxng_url`, and `firecrawl` without its key. A provider that fails (a timeout, HTTP 401, 402, 403, 429 or 5xx, or a reply that is not readable) or returns no hit passes the search on at once, with no retry and no wait. The first provider with a hit answers. Each request goes through the HTTP entry point. DuckDuckGo and Firecrawl use the public level (the public HTTPS rule of policy `devops-default-perimeter`, no new rule). SearXNG sends `GET /search` with `format=json` at the configured level: loopback, or private with `ai.allow_private_network`. The client follows no redirect and reads at most 1 MiB, and a reply with no result while an engine did not answer counts as `degraded`. An address that the egress check refuses counts as `refused` and passes the search on. Each attempt counts in `devops_cli_web_searches_total` by `backend` (a provider name, or `none`) and `result`: `ok`, `empty`, the HTTP status of a refused search, `degraded` for a reply that cannot be read, `error` for no answer, `refused` for a query that the guard stopped or an address that the egress check refused, or `exhausted` for a search that no provider answered. A failed attempt logs `A web search failed on ` with the status or the error class, and never the key or the query. The guard refuses an empty query, a query over 400 characters or 50 words, a query that starts with `!` or `:`, and a query that holds a secret, an e-mail address, a private address or an internal host name; it sends no request. DuckDuckGo needs no key, so a round on a public repository has web search with the default providers. Firecrawl stays the last provider for one release cycle. When `crawl4ai.url` is set, the run also has the tool `fetch_page`, which reads the text of one page through the Crawl4AI service. It takes an https URL that a search of the same run returned or that the item text names, and no other URL; it sends no request for any other URL. A run fetches at most 3 pages. The tool frames the text as data from an outside page, never an instruction, and names the source URL and the fetch date so that a comment can cite them. A failed fetch is a tool answer and uses one fetch. Each call counts in `devops_cli_roadmap_page_fetches_total` by `toolset` (`refine` or `alternatives`) and `result` (`ok`, `refused`, `limit` or `error`). The tool is off with no `crawl4ai.url`. The tool needs the Crawl4AI service and its token. It reads pages from the web, which is new egress, so a person sets `crawl4ai.url` in the live ConfigMap to enable it. 14. The row `alternatives` of the model lane runs after `refine`: on a first run, and 719 minutes after its last success. It runs `devops roadmap alternatives --confirm` for the repository. A round checks at most `roadmap.alternatives.first_pass_limit` items (20 by default) while an item has no check, and at most `roadmap.alternatives.limit` items (5 by default) after. The row runs about twice a day, so a first pass of 141 items takes about 4 days. A round takes first the items with no check, then the items whose check is older than `roadmap.alternatives.recheck_days` (30 by default) or whose text changed. A webhook makes the row due at no other time. The row changes no label and closes no issue. It does nothing, and logs `The alternatives check of is off`, for a private repository and when no search provider is configured. If the check of an item fails, the row records the failure in the item's job record (`alternatives.failed_at` and `alternatives.failed_error`, the class of the error), writes the other checks and succeeds. The row fails, and counts toward the suspension after 3 failed rounds, only when it tried items and checked none. A round takes a failed item again after `roadmap.alternatives.retry_days` (3 by default). Each written check adds 1 to `devops_cli_roadmap_alternatives_total` by `verdict`: `covers`, `partly`, `none`, `not-applicable`, `rejected` or `in-use`. Each round also sends two gauges by `repo` at its start, before it checks any item, also when it checks none (#2950): `devops_cli_roadmap_alternatives_unchecked_items` (the items that the check can take and has no check for, an item in the retry delay too) and `devops_cli_roadmap_alternatives_oldest_check_age_seconds` (the age of the oldest check among those items, sent only while one has a check). Each written check observes `devops_cli_roadmap_alternatives_searches` by `verdict`: the searches the check ran, 0 for a skip class. The row Alternatives Check of the dashboard `devops-cli Telemetry` shows the three, and the alert `RoadmapServiceAlternativesNotSearching` warns when the Service made no web search in 3 days while an item has no check. An item of the type `test`, `docs`, `refactor`, `chore`, `ci` or `perf`, and a `fix` with a Python traceback in its body, gets `not-applicable` with no model call; every other item must run a search before the check accepts a verdict, and gets one more turn to search. Once for a round that checks an item of no skip class, the check reads the ADRs of `docs/adr/` that are in force. An ADR that a later ADR supersedes is left out. The model sees the number, the title, the status lines and the `Considered Options` section of each ADR. The model proposes `rejected` with the number of an ADR, and `in-use` when the item names the tool. The job gives either verdict only when the text confirms it. It drops a proposal that it cannot confirm and keeps the verdict of the reply. A cut by the token cap leaves out whole ADRs and logs a warning. A `covers` verdict makes refine ask a person to adopt the tool or to keep the item with a reason. A `rejected` or `in-use` verdict asks nothing. The item waits on a person until a reply answers the question, and Ready items with a new covering tool go back to New. Refine records the tool it asked about in the job record (`refine.alternatives_asked`). `devops roadmap run --dry-run` lists the row when it is due. -15. The row `retitle` follows `refine` on the model lane (#3535). It is due on a first run and every 61 minutes. It shortens the title summary of at most 25 open items, as `devops roadmap retitle --confirm` does, with the model of the `triage` task. It needs no clone, and it reads and writes only the issues of the repository. The row `stage` follows `retitle` on the model lane (#2659), so the stage job reads the new titles in the same round. It runs `devops roadmap stage --confirm` in the model clone: it is due every 37 minutes, on a first run, and in a round where `refine` set an item Ready. It stages the Ready items that `roadmap.stage.filter` names, at most `roadmap.stage.limit` in a round, plans only items with the priority `P0-Critical` or `P1-High` while the count of open Planned items is at `roadmap.stage.planned_limit` (#3487, #3692), and splits a task group over `roadmap.stage.step_tokens`. Each task group has a kind (#3005): a `behavior` group has a failing test, and an `other` group has no test but a command or the steps of a manual check that prove it. The job sends a reply that breaks this rule back to the model once. It leaves out an item whose change folder is on the default branch or in its archive (#2714): a round reads that tree once with `git ls-tree`, so a merged staging pull request never makes a second one. The pull request it opens is a draft with the title `docs(openspec): plan # `. The job does not mark it ready: the row `stage_ready` does (step 18). Before it opens one, it checks each path of the plan (`reads`, `changes`, the code spans of the tasks and `verify`) against the tracked files of the commit it plans, read with one `git ls-files` for the round (#3010). A path that is no file there, and that no group up to its own creates, goes back to the model once with the files of the same name. When a later group creates the path, the problem names that group and tells the model to move it before the group that names the path (#3017). A second reply with a missing path stops the item, so no draft opens and the implement Job never meets a wrong path. `k8s/devops/configmap.example.yaml` holds the five settings, and `devops k8s deploy-stack --stack devops` applies them; each also has a variable, `DEVOPS_CLI_ROADMAP_STAGE_FILTER`, `DEVOPS_CLI_ROADMAP_STAGE_LIMIT`, `DEVOPS_CLI_ROADMAP_STAGE_PLANNED_LIMIT`, `DEVOPS_CLI_ROADMAP_STAGE_STEP_TOKENS` and `DEVOPS_CLI_ROADMAP_STAGE_TOOLSET`. The setting `roadmap.stage.toolset` is `extended` by default (#3238): a plan run then has three tools more than the nine that read the staged commit. `references` counts a text in every file of the commit. `read_issue` and `find_issues` read issues and pull requests of the repository on GitHub, as GET requests with the token of the Service and no other permission. `base` leaves them out. Each item of a round counts once in `devops_cli_roadmap_stage_total` by `repo` and its `result`: `staged`, `skipped`, `needs_split` or `failed`. Each call of a step sends its seconds to `devops_cli_roadmap_step_seconds` by `repo`, `row`, `step` and `result` (#4066): the steps `select`, `plan`, `gate`, `review` and `apply`, and the results `ok` and `error`. A gate that refuses a reply adds 1 to `devops_cli_roadmap_stage_gate_refusals_total` under the name of the gate. A failed item is recorded in its job record with the class of its error and the time (#3493), and the job leaves it out while it takes the other items: 1 hour for a `provider` or `ci_infra` class, 6 hours for a `parser` or `plan_defect` class, and no time for `head_moved` (`RETRY_AFTER` in `roadmap/failure.py`, #4060). A record with no class, or an unknown class, waits as `ci_infra`. The row fails a round only when it tried items and staged, stopped or returned none, or when a failure belongs to no item; three such rounds on the same input suspend the row. The ledger file keeps the class of each error, and a round that the stop of the Service ends counts as `stopped`, not as an error. The image carries the pinned OpenSpec and a Node runtime, so the job validates each change before it pushes: `kubectl -n devops exec deploy/roadmap-service -- openspec --version` prints the locked version. +15. The row `retitle` follows `refine` on the model lane (#3535). It is due on a first run and every 61 minutes. It shortens the title summary of at most 25 open items, as `devops roadmap retitle --confirm` does, with the model of the `triage` task. It needs no clone, and it reads and writes only the issues of the repository. The row `stage` follows `retitle` on the model lane (#2659), so the stage job reads the new titles in the same round. It runs `devops roadmap stage --confirm` in the model clone: it is due every 37 minutes, on a first run, and in a round where `refine` set an item Ready. It stages the Ready items that `roadmap.stage.filter` names, at most `roadmap.stage.limit` in a round, plans only items with the priority `P0-Critical` or `P1-High` while the count of open Planned items is at `roadmap.stage.planned_limit` (#3487, #3692), and splits a task group over `roadmap.stage.step_tokens`. Each task group has a kind (#3005): a `behavior` group has a failing test, and an `other` group has no test but a command or the steps of a manual check that prove it. The job sends a reply that breaks this rule back to the model once. It leaves out an item whose change folder is on the default branch or in its archive (#2714): a round reads that tree once with `git ls-tree`, so a merged staging pull request never makes a second one. The pull request it opens is a draft with the title `docs(openspec): plan # `. The job does not mark it ready: the row `stage_ready` does (step 18). Before it opens one, it checks each path of the plan (`reads`, `changes`, the code spans of the tasks and `verify`) against the tracked files of the commit it plans, read with one `git ls-files` for the round (#3010). A path that is no file there, and that no group up to its own creates, goes back to the model once with the files of the same name. When a later group creates the path, the problem names that group and tells the model to move it before the group that names the path (#3017). A second reply with a missing path stops the item, so no draft opens and the implement Job never meets a wrong path. `k8s/devops/configmap.example.yaml` holds the five settings, and `devops k8s deploy-stack --stack devops` applies them; each also has a variable, `DEVOPS_CLI_ROADMAP_STAGE_FILTER`, `DEVOPS_CLI_ROADMAP_STAGE_LIMIT`, `DEVOPS_CLI_ROADMAP_STAGE_PLANNED_LIMIT`, `DEVOPS_CLI_ROADMAP_STAGE_STEP_TOKENS` and `DEVOPS_CLI_ROADMAP_STAGE_TOOLSET`. The setting `roadmap.stage.toolset` is `extended` by default (#3238): a plan run then has three tools more than the nine that read the staged commit. `references` counts a text in every file of the commit. `read_issue` and `find_issues` read issues and pull requests of the repository on GitHub, as GET requests with the token of the Service and no other permission. `base` leaves them out. Each item of a round counts once in `devops_cli_roadmap_stage_total` by `repo` and its `result`: `staged`, `skipped`, `needs_split`, `failed` or `degenerate`. An item is `degenerate` when its plan reply holds a placeholder such as `x` in every text (#4204): the job sends no second request. A refused reply is logged with the line `stage reply refused: item=# request= input_tokens= tools_offered= result=`, and an item that fails in the plan keeps its refused replies and their problems in `roadmap/stage///.refused.json` beside its plan file, until the item is staged. Each call of a step sends its seconds to `devops_cli_roadmap_step_seconds` by `repo`, `row`, `step` and `result` (#4066): the steps `select`, `plan`, `gate`, `review` and `apply`, and the results `ok` and `error`. A gate that refuses a reply adds 1 to `devops_cli_roadmap_stage_gate_refusals_total` under the name of the gate. A failed item is recorded in its job record with the class of its error and the time (#3493), and the job leaves it out while it takes the other items: 1 hour for a `provider` or `ci_infra` class, 6 hours for a `parser` or `plan_defect` class, and no time for `head_moved` (`RETRY_AFTER` in `roadmap/failure.py`, #4060). A record with no class, or an unknown class, waits as `ci_infra`. The row fails a round only when it tried items and staged, stopped or returned none, or when a failure belongs to no item; three such rounds on the same input suspend the row. The ledger file keeps the class of each error, and a round that the stop of the Service ends counts as `stopped`, not as an error. The image carries the pinned OpenSpec and a Node runtime, so the job validates each change before it pushes: `kubectl -n devops exec deploy/roadmap-service -- openspec --version` prints the locked version. 16. The row `implement` follows `metrics` on the status lane (#2667, #2757). It calls no model, so a model-lane round that has not ended never delays it. It is due every 7 minutes and on a first run, in the clone of the status lane. The Service runs no step: a round only talks to the Kubernetes API, in three moves. It reports each Job that ended, with a comment on the item that holds the state and the last 40 lines of the log of the Job's pod, masked of secrets, and records `implement.job_state` as `succeeded`, `failed` or `gone`. It moves the deadline of each Job that has not ended (#3063, below). It waits while a Job of the repository has not ended. Else it makes one Job from CronJob `devops-cli-runner` for the first Staged or Planned item that the default filter names (a Planned item has its change folder on the default branch and no branch: a person merged the staging pull request, and the job makes the branch and the draft itself), with the args `roadmap implement --repo --item --confirm` and the item's number as the only item text, and records the name of the Job in `implement.job`, and the digest of the runner image that the CronJob template names in `implement.job_digest`. The same write sets the label `owner/service` on the item (#2910), and the report of the Job removes it. The comment that reports the Job names the digest. The Service makes no Job for an item that an agent or a person claimed, and a claim of an agent or a person ends a running Job at its next group boundary, with no push and no pull request. A round also sets the Status label of the items from their record (`status_sync.py`): it reads the plans on the default branch once for the sweep and for the plan, writes `status/planned` once a plan is merged, and writes `status/in-progress` as soon as the record names a Job, and again after it makes one. It writes only an open item that holds Ready or Planned with the label that a job last recorded, so a label that a person set stays. The rows `stage` and `stage_ready` use the same function. The Jobs of a repository carry the label `implement-repo`, whose value is a digest of the repository name, so the API is the lock and a restart of the Service loses nothing. A Job that leaves its item In Progress, or Ready or Planned with no stop, is a stop that the runner could not write, such as a pod that the kernel killed for its memory, unless an agent or a person claimed the item. The round then sets the item Blocked (`status/blocked`) and records `implement.stopped` as `job`. No Job is made for it before a clear rule runs. A stop that the runner writes sets Blocked in the same way, with the step in `implement.stopped`. After the report, the round clears the stop of each item that it set Blocked. It uses one of three rules, and a comment names the rule that ran. Rule `retry`: a comment `implement: retry`, made after the report by the owner, a member or a collaborator, clears the stop at once, whatever the image. Rule `continue` (#3721): three things must hold. The stop is `job`, which the round records for a Job that ended with no result. Examples are a pod that the kernel killed or evicted, a stalled Job that the Service ended, and a Job that no longer exists. The class in `implement.failure` has the action `retry` in `ACTION_BY_CLASS`. The count `implement.continuations` is less than the setting `roadmap.implement.continuations_per_item` (default 2, 0 turns the rule off). Kubernetes never restarts a Failed Job: `activeDeadlineSeconds` takes precedence over `backoffLimit`, and the template sets `backoffLimit: 0` on purpose. So a continuation is a new Job from the Service. The clear adds 1 to `implement.continuations`, a count and no other data, which stays after a clear. A retry of a person does not reset it. The comment says "continuation n of N", and at the limit it adds "No continuation is left". The rule runs before `digest`, reads no template and spends no clear by digest. The new Job takes the branch from `origin`. So it keeps the `wip:` commits that the run pushed for a group with more than one task (#3054). A group of one task that passed, and that no push kept, runs again. A class with another action, such as `oom` (`raise_limit`), waits for a retry, because a second run on the same limit ends the same way. Only a sign in the log gives the class `oom`. The Service reads no pod status, so a kill with no text in the log is continued as `ci_infra` (follow-up #3727). A stop that the runner wrote, with a step in `implement.stopped`, is no continuation. At the limit, a new runner image still clears the stop by the rule `digest`, within its limits. Rule `digest`: the digest in the template of CronJob `devops-cli-runner` is not `implement.job_digest`, so a new runner image has rolled out since the stop, and the class in `implement.failure` has the action `retry` in `ACTION_BY_CLASS` (#3481). A new image cannot fix a plan, a premise, a refused tool or a failed test, so a stop of another class, and a stop with no class on record, wait for a retry. Each clear by digest adds the class, the new digest and the time to `implement.digest_clears`, and the list stays after the clear. The settings `roadmap.implement.digest_clears_per_class` (default 1) and `roadmap.implement.digest_clears_per_item` (default 3) bound the entries; a stop at a limit stays Blocked until a retry, also for `ci_infra`. The comment of a clear by digest shows at most one time in 24 hours for an item (`implement.digest_clear_commented_at`), and the clear is recorded either way. The rule reads no image content: the Service holds digests and no map from a digest to commits. A clear sets Ready or Planned and removes `implement.stopped`, and the same round can make a Job for the item. The new Job overwrites `implement.job_digest`, so a second stop on the same image waits for a retry. A continuation is the exception, and `implement.continuations` bounds it. So the round makes no Job in a loop. A stop with no digest on record is cleared by a retry only, except a stop `job`, which a continuation clears with no digest. Inside one priority, a round takes an item with no digest clear before an item with one, and a retried item of a higher priority still goes before a new item of a lower priority. A Blocked stop that no rule clears costs one request in each round, the listing of its comments (6 an hour of `service.github_requests_per_hour`); the round reads the issue again only when a rule holds, and reads the template at most one time. The round clears no item that a Job holds, that an agent or a person claimed, or that a person labeled Blocked by hand. The failures ledger is unchanged: three failed rounds on the same input still suspend the row. If CronJob `devops-cli-runner` does not exist, the round fails with a message that names it: run `devops k8s deploy-stack --stack devops`, or wait for Argo CD. A Job that cannot pull its image (the package `runner` is not public, or no release published it) has an empty log, so it ends by its stall after 40 minutes, and the next round records the stop. Read the Jobs with `kubectl -n devops get jobs -l implement-repo`. The Job runs the checks that a person runs at a commit and at a push (#3043). Before the first step it runs `pre-commit install-hooks`, with `PRE_COMMIT_HOME` in the cache directory of the data directory, on the home volume. The two remote hook repositories come over public HTTPS (9 s and 51 MB, measured). A failed install stops the item at the step `hooks`, before any model request. Each step then runs the `pre-commit` stage on its staged changes as its last exit check. The child is `uv`, which holds no token. The Job installs no git hook, because git runs a hook with the token of the session, and the agent can edit the hook configuration. For the same reason every hook run gets `--config` with a copy of the configuration of the default branch, so an edit of the agent skips no hook. A hook run that runs out of time stops the step. A failed hook goes to the agent as a repair turn with its output. The setting `roadmap.implement.repair_rounds` (variable `DEVOPS_CLI_ROADMAP_IMPLEMENT_REPAIR_ROUNDS`, default 3) bounds the extra turns of a step for `ruff`, `mypy` and the hooks. Only a used budget stops the step. After the last group, the docs, the archive and the final rebase, and before the push, the Job runs the scoped checks: the `pre-push` stage of the hooks, `devops ci --check --only constructs,docs,openspec`, and `devops ci test` with the test modules that cover the changed Python files of `src/` and `tests/`. Above 30 test modules, which a change to a shared module gives, the tests check runs only the changed test modules, and it does not run when no test covers the change. A failed check starts a fix step, up to `repair_rounds` times for all scoped checks. The Job generates the docs again after each fix. It pushes a finished item only after all of them pass. A stop in this phase (a used budget, a fix step that stops, an error, a command that runs out of time) pushes the commits that passed to the item branch, as any other stop does, and the draft pull request stays a draft (#3645). The comment on the pull request shows the repair rounds of each step, and each run of a scoped check with its seconds. The extra run time of an item is about 10 s of hooks for each step, 9 s for the install, 35 s for the first two scoped checks, and at most about 3.5 minutes for the tests (12 test modules of the roadmap ran in 88 s on 2 CPUs). So it is 2 to 5 minutes in a Job that runs about an hour. The workflow checks `actionlint` and `zizmor` run in the `pre-push` stage only when the push changes a workflow, because the runner image holds no `actionlint`. A failed check of the pull request after the push gets a fix step, a push and a new watch, up to `repair_rounds` times, with a comment on the pull request for each round. 17. Each repository has three lanes, and each lane runs one round at a time in its own clone (#1532, #1534). The status lane runs the rows `metrics`, `implement`, `stage_ready`, `release_comments`, `github_status` and `cloudflare_status` in the clone `clone`. The row `metrics` reads the project metrics. The rows `github_status` and `cloudflare_status` each read one status page, need no clone, and are due every 13 minutes and on a first run (#4052). A read that fails fails its own row: the row counts `error` in `devops_cli_service_jobs_total`, writes no stamp to `schedule.json`, and the alert `RoadmapServiceJobsFailing` names the row when every round of the row failed for 1 hour. The other rows are not affected. The triage lane runs the row `intake` in the clone `triage-clone`. The model lane runs the rows `refine`, `retitle`, `stage` and `alternatives` in the clone `model-clone`. The ConfigMap sets the same chat model for both lanes (item 19). A poll and a webhook go to all three lanes. The lanes share the file `schedule.json` of the repository, the ledger `service-failures.json` and the lock that each write of an item's job record takes (#2757). When intake places a critical fix or P0 item, it writes a `refine_due` timestamp to `schedule.json` so refinement becomes due in the next model-lane round; the timestamp is written even when the write of another candidate of the same round failed. An Item that a person changed between the plan and the write of intake is not a failed placement: nothing is written for it, the round does not fail, and the next round decides the candidate again (#4042). A `schedule.json` that exists and cannot be read fails the round with an error that names the file, and no row runs. A person repairs or removes the file; a removed file makes every row due once (#4042). The label `lane` of `devops_cli_service_jobs_total`, `devops_cli_service_job_seconds_total` and `devops_cli_service_queue_depth` is `status`, `triage` or `model`. The label `row` of `devops_cli_service_jobs_total` is the name of the row that ended, and the label `result` is `success`, `error` or `stopped` (the stop of the Service ended the row). The label `row` of `devops_cli_github_requests_total`, `devops_cli_service_job_suspended` and `devops_cli_service_job_retry_after_seconds` is the name of the row; the two gauges of the ledger have no label `lane`, as row names are unique. A model-lane round that has not ended does not delay a status-lane or triage-lane round. 18. The row `stage_ready` follows `implement` on the status lane (#2865). It calls no model and needs no clone. It is due every 3 minutes and on a first run. A round reads the open items whose record holds `stage.pr` and no `stage.ready` of the same number and no `implement.job`; with no such item it sends no request of its own, since the listing of the issues is the one that `metrics` and `implement` read in the round. For each such item it reads the pull request (`GET pulls/`). A pull request that is not an open draft is only recorded in `stage.ready`. An open draft goes to the function `draft_readiness` with its check runs (`GET commits//check-runs`): when every check ended and passed, the row marks the pull request ready with `gh pr ready` (the same function as the implement job) and records `stage.ready`. A draft with a failed, cancelled or running check, or with no check, stays a draft, and the row does not retry a check. The row reads only the pull request that the stage job recorded, and never the draft of a person. It reads the check runs and not the commit statuses, because the App token holds `checks: read` and no `statuses` permission. A draft that waits for its checks costs 2 requests a round (12 an hour) of `service.github_requests_per_hour`; a pull request that the row marks costs 2 more for `gh pr ready` and 2 to record it, once. A refusal of `gh pr ready` fails the round, names the item, and the ledger of failed rounds suspends the row after three rounds in a row: check that the App holds `pull_requests: write` and `contents: write` (ADR 0015). A pull request that the row marked ready is no longer a draft, so the implement job leaves its item until a person merges the plan and the item is Planned. The row counts under `row="stage_ready"` in `devops_cli_github_requests_total`. diff --git a/openspec/changes/4204-keep-refused-stage-reply/.openspec.yaml b/openspec/changes/4204-keep-refused-stage-reply/.openspec.yaml new file mode 100644 index 0000000000..e4912fbf47 --- /dev/null +++ b/openspec/changes/4204-keep-refused-stage-reply/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-09 +skip_specs: false diff --git a/openspec/changes/4204-keep-refused-stage-reply/design.md b/openspec/changes/4204-keep-refused-stage-reply/design.md new file mode 100644 index 0000000000..55050bd99d --- /dev/null +++ b/openspec/changes/4204-keep-refused-stage-reply/design.md @@ -0,0 +1,18 @@ +# Design + +## Decisions + +- **Beside the plan file, one refused file for each item.** The file `.refused.json` is in the folder of `.json` and uses the key of the plan input. Both files are deleted by the same step (`_Writer` staging), so there is one cleanup path. The file holds the replies of the last failed plan only: a new failed plan replaces it, so the count of files is the count of failed items, and each file has a size bound. +- **No age limit.** The plan file has none (see Feasibility), and a second rule would be a second retention rule. A file stays until the item is staged. It is small, and a person can delete it. +- **Degenerate means every text.** The check reads `why`, `existing_tool`, each line of `feasibility` and the tasks `test`, `implementation` and `documentation` of every group, with `is_placeholder`. A reply with one real text goes back once, as before, because the model can mend it. The check runs before the gates, so a degenerate reply costs no gate run. +- **A subclass for the stop.** `RoadmapStageDegenerateError` is a `RoadmapStageError`, so `failure_class_of` gives it `plan_defect` and the retry wait of 6 hours stays. The metric and the eval tell it from `failed` by the type, and `StageFailure.degenerate` carries that fact to `stage_results`. A new `FailureClass` would change the table of actions and the wait, and the issue asks for neither. +- **Log fields from the run trace.** The log line reads the last `RunTrace` of the toolbox client, taken after the item was asked (`floor`), so a trace of an earlier item is no source. A plan with no toolbox run (a kept plan, a plain client) logs `request=1 input_tokens=0 tools_offered=False`. +- **Size bound.** A reply over `CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES` (131,072) is dropped and its size stays in `reply_bytes`. A problem is masked with `mask_secrets` and cut at `CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS` (8,000). + +## Rejected alternatives + +- **Log the whole reply.** The log has no place for a reply of 100 KB, and it can hold text of the issue. The file is the record. Rejected. +- **A 7-day cleanup of the file.** The plan file has no such cleanup, so the premise of #4204 is false. A new cleanup is new code for a file that is bounded and replaced. Rejected. +- **A new failure class `degenerate`.** It would change `ACTION_BY_CLASS`, `RETRY_AFTER` and every consumer of the class, for a fact that one boolean carries. Rejected. +- **Keep the refused replies of the verify rounds too.** `_repaired` raises its own error, and the issue names the first plan run. It can follow if the data asks for it. Rejected for now. +- **Count the degenerate reply as `failed`.** The metric would hide the placeholder rate, and the eval would have no count. Rejected. diff --git a/openspec/changes/4204-keep-refused-stage-reply/proposal.md b/openspec/changes/4204-keep-refused-stage-reply/proposal.md new file mode 100644 index 0000000000..88e44dfb39 --- /dev/null +++ b/openspec/changes/4204-keep-refused-stage-reply/proposal.md @@ -0,0 +1,56 @@ +# Proposal: #4204 + +## Why + +The stage job of the roadmap Service staged no item on 2026-11-09 (#4204). The live run of item #4062 needed the refused reply and the first problem text, and the job kept neither: it kept only the last problem, and a plan that fails the gates leaves no plan file. A reply that holds only placeholders (`x`, `placeholder`) in every text also used the second request, and the second reply was the same. The main causes were found and fixed in other pull requests: the gateway answered through a fallback model (#4216), the reference reason could be null (#4215), the reply was cut at 4096 output tokens (#4224), tool calls were joined (#4243), and the window estimate ended the tools too early (#4238). What remains of #4204 is the record of a refused reply and the early stop. + +## What Changes + +- `_gated` in `src/devops_cli/roadmap/stage/stage.py` logs one line `stage reply refused: item=# request= input_tokens= tools_offered= result=` for each refused reply. `request` is the number of the last request of the plan run, `input_tokens` is its input, and `tools_offered` says whether it offered a function tool. `RunTrace` gets the field `last_input_tokens`. +- A failed item keeps its refused replies and their problems in `roadmap/stage///.refused.json`, beside the plan file, under the key of the plan input. The staging of the item deletes the file, and a new failed plan replaces it. A reply over 128 KiB is dropped and only its size stays, and a problem is cut at 8,000 characters and masked for secrets. The file is written with the same atomic writer as the plan file. +- A first or second reply with a placeholder (`is_placeholder` of the pull request form) in `why`, `existing_tool`, each line of `feasibility` and each task of each group ends the item at once with the new `RoadmapStageDegenerateError`, a subclass of `RoadmapStageError`. The job sends no second request. `StageResult` gets the value `degenerate`, so `devops_cli_roadmap_stage_total{result="degenerate"}` counts the item and `failed` keeps the other failures. +- `devops roadmap eval stage` shows `degenerate N` in the line of how the cases ended, through the new `Outcome.DEGENERATE`. +- The change adds requirements to `roadmap-stage` and `roadmap-stage-eval`, because the log line, the file, the metric result and the report are observable. +- It fits one pull request. + +## Criteria of #4204 + +- 1 (log fields), 2 (kept replies) and 3 (`degenerate` result and eval count) are delivered here. Criterion 2 asks for a 7-day age limit "as the gated plan has". The premise is false: the plan file has no age limit. It goes when the item is staged or its input changes. The refused file follows the same rule, and it has a size bound. +- 4 (`staged` above 0 in each 24 hours) and 5 (name and remove the cause) are results of the fixes of #4215, #4216, #4224, #4238 and #4243, and #4205 holds them. They need Service data, not code. +- A schema violation (`StructuredOutputValidationError`) is not a refused reply: the reply never reaches `_gated`. Its failure line holds a count of violations. The text of the violations in the log is out of this change. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `roadmap-stage`: adds the requirements `A refused reply is logged`, `A failed item keeps its refused replies` and `A reply of placeholders ends the item`. +- `roadmap-stage-eval`: adds the requirement `The live report counts the degenerate cases`. + +## Impact + +- Code: `src/devops_cli/roadmap/stage/stage.py`, `src/devops_cli/roadmap/stage/stage_plan_record.py`, `src/devops_cli/roadmap/stage/stage_eval_run.py`, `src/devops_cli/roadmap/agent_run.py`, `src/devops_cli/exceptions/roadmap.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/telemetry/instruments.py`. +- Tests: `tests/roadmap/stage/test_roadmap_stage_refused_reply.py`, `tests/roadmap/stage/test_roadmap_stage_eval_run.py`. +- Documents: `k8s/README.md` (roadmap Service item 15), `docs/TELEMETRY.md` (generated). +- No new setting, so no ConfigMap change and no rollout order. The two constants are code constants. +- Metric: the label `result` of `devops_cli_roadmap_stage_total` gets one more value, `degenerate`. The series count grows by 1 for each repository (1 repository today, so 1 series). No label is added. +- The refused file is on the data volume of the Service, at most about 2 x (128 KiB + 8,000 characters) for each item that failed in the plan, and it is deleted when the item is staged. + +## Feasibility + +- The premise "the job keeps only the last problem": `_gated` in `stage.py` held `outcome.problem` of the second `_settle` only, and `_keep` wrote a plan file only for a plan that passed. Read in the code at `origin/main` 750cf789. +- The premise "the same placeholder reply returns on the second request": issue #4204 gives the log of 2026-11-08 and the sample of #3566. This change does not prove it; it removes the second request only for a reply that is a placeholder in every text, which the gates refuse in any case (`content`, `form`, `paths`, `spec-delta`). A reply that is only in part a placeholder still goes back once. +- The premise "the plan file has a 7-day age limit": false. `stage_plan_record.py` deletes a plan file when the item is staged or when the key changes (`delete_plan_record` in `_kept` and in the writer). No code ages a file. +- A reply with a placeholder `summary` fails the schema (`summary_problem`), so it never reaches the check. A placeholder in `why`, `existing_tool`, `feasibility` and the tasks passes the schema, as the log of #4204 shows. +- The usage of the last request: pydantic-ai gives `ModelResponse.usage.input_tokens` for each reply, and `RunTrace._add_reply` already sums it. `last_input_tokens` keeps the value of the last reply. +- First check, which fails on origin/main: `uv run devops ci fail-to-pass --base origin/main`. Second check: `uv run devops ci test tests/roadmap/stage/test_roadmap_stage_refused_reply.py tests/roadmap/stage/test_roadmap_stage_eval_run.py`. + +## Existing Tool Considered + +- pydantic-ai output validators with `ModelRetry` retry an invalid reply. They neither record the refused reply nor tell a placeholder reply from another one, and the stage job already sets the retries of the schema (`_REPLY_RETURNS`). +- `is_placeholder` of `roadmap/pull_form.py` is the placeholder rule of the content gate, and this change reuses it. No second word list. +- `write_json_file` with `atomic=True` and `mask_secrets` are the existing writer and masker. `RefusedRecord` is a pydantic model, as `StagePlanRecord` is. +- No open tool keeps a refused model reply per item in a Service. The cost to build: about 60,000 tokens, with tests, and about 2 hours. The cost to keep is low: one small module and a bounded file. The cost to fix: a change of the file layout touches one module. The change deletes no internal code. diff --git a/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md b/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md new file mode 100644 index 0000000000..f2fe7e8683 --- /dev/null +++ b/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md @@ -0,0 +1,12 @@ +## ADDED Requirements + +### Requirement: The live report counts the degenerate cases +The live run SHALL end a case with the outcome `degenerate` when the stage planner stops it on a reply that is a placeholder in every text, and the report SHALL show the count of such cases in the line of how the cases ended, `0` when there are none. + +#### Scenario: A reply of placeholders +- **WHEN** the model answers a case with `x` or `placeholder` in every text of the plan +- **THEN** the case ends `degenerate` after one model call, and the report shows `degenerate 1` + +#### Scenario: A run with no such reply +- **WHEN** the live run finishes and no reply is a placeholder in every text +- **THEN** the report shows `degenerate 0` diff --git a/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md b/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md new file mode 100644 index 0000000000..bf967c1114 --- /dev/null +++ b/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md @@ -0,0 +1,30 @@ +## ADDED Requirements + +### Requirement: A refused reply is logged +The stage job SHALL log one line `stage reply refused` for each reply of the model that it refuses, with the number of the item, the number of the last request of the plan run, the input of that request in tokens, whether that request offered a function tool, and the result `refused` or `degenerate`. + +#### Scenario: A reply that the gates refuse +- **WHEN** the gates refuse the reply of item 1 in the second request of a plan run, and that request offered a tool +- **THEN** the log holds one line with `item=#1`, `request=2`, the input of the request in tokens, `tools_offered=True` and `result=refused` + +### Requirement: A failed item keeps its refused replies +When a plan fails, the stage job SHALL write the refused replies and their problems to the file `.refused.json` beside the plan file of item ``, under the key of the plan input. A new failed plan SHALL replace the file, and the staging of the item SHALL delete it. A reply over the byte bound SHALL be dropped with its size kept, and a problem SHALL be masked for secrets and cut to the character bound. + +#### Scenario: The gates refuse a plan twice +- **WHEN** the gates refuse the first reply and the reply after the return of item 1 +- **THEN** the file `1.refused.json` holds the key and both replies, each with its problem, and no plan file exists + +#### Scenario: The item is staged +- **WHEN** a later round stages item 1 +- **THEN** the file `1.refused.json` is deleted + +### Requirement: A reply of placeholders ends the item +The stage job SHALL end an item at once, with no second request, when a reply is a placeholder in `why`, `existing_tool`, each line of `feasibility` and each task of each group. The item SHALL fail with the error `RoadmapStageDegenerateError`, the job SHALL keep the reply as a refused reply, and `devops_cli_roadmap_stage_total` SHALL count the item under the result `degenerate`. A reply with one text that is no placeholder SHALL go back to the model once. + +#### Scenario: The first reply is all placeholders +- **WHEN** the first reply of item 1 holds `x` or `placeholder` in every text of the plan +- **THEN** the model gets one request, the item fails with `RoadmapStageDegenerateError`, and the result of the item is `degenerate` + +#### Scenario: A reply with one real text +- **WHEN** the first reply holds `x` in `why` and in `feasibility` and a real text in `existing_tool` +- **THEN** the reply goes back to the model once, as for any refused reply, and the result stays `failed` if the second reply is refused diff --git a/openspec/changes/4204-keep-refused-stage-reply/tasks.md b/openspec/changes/4204-keep-refused-stage-reply/tasks.md new file mode 100644 index 0000000000..f449c5b17e --- /dev/null +++ b/openspec/changes/4204-keep-refused-stage-reply/tasks.md @@ -0,0 +1,19 @@ +# Tasks + +## 1. Refused replies and the degenerate stop + +- [x] 1.1 Write the failing tests for the refused file, the log line, the degenerate stop, the metric result and the eval count + - Verification: `$ uv run devops ci test tests/roadmap/stage/test_roadmap_stage_refused_reply.py tests/roadmap/stage/test_roadmap_stage_eval_run.py` +- [x] 1.2 Add `RefusedRecord`, `RoadmapStageDegenerateError`, `RunTrace.last_input_tokens`, the log line, `StageResult.DEGENERATE` and `Outcome.DEGENERATE` + - Verification: `$ uv run devops ci test tests/roadmap/stage/test_roadmap_stage_refused_reply.py tests/roadmap/stage/test_roadmap_stage_eval_run.py` + +## 2. Documents + +- [x] 2.1 Update the Service item of `k8s/README.md` and regenerate the metric table + - Verification: `$ uv run devops ci docs` + +## Workflow follow-up + +- Criteria 4 and 5 of #4204 (the `staged` count above 0 in each 24 hours, and the named cause) are the results of merged fixes. #4205 holds them. +- The text of the violations of a `StructuredOutputValidationError` in the log is not part of this change. +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 42b882fcb7..2212276d02 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -3176,6 +3176,11 @@ class WebhookExposure(StrEnum): CONST_ROADMAP_STAGE_MAP_MAX_FILES: Final[int] = 40 CONST_ROADMAP_STAGE_MAP_LINE_CHARS: Final[int] = 180 CONST_ROADMAP_STAGE_SPEC_MAX_CHARS: Final[int] = 16000 +# The refused-reply file of an item (#4204) holds at most two replies and their problems. A reply +# over the byte limit is dropped and only its size stays; a problem is cut to the character limit. +# So the file is at most about 2 x (128 KiB + 8,000 characters) in size. +CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES: Final[int] = 131_072 +CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS: Final[int] = 8_000 # The first plan request (#3477): the repository context and the body of the item each have a fixed # cap that does not grow with the window. A cap is also at most a share of a small window # (`_WINDOW_SHARE_CONTEXT` and `_WINDOW_SHARE_BODY` in the stage module). For the planner window of diff --git a/src/devops_cli/exceptions/__init__.py b/src/devops_cli/exceptions/__init__.py index 5651a2f265..908e67ca89 100644 --- a/src/devops_cli/exceptions/__init__.py +++ b/src/devops_cli/exceptions/__init__.py @@ -56,6 +56,7 @@ RoadmapPlanRewriteError, RoadmapRefineError, RoadmapRunError, + RoadmapStageDegenerateError, RoadmapStageError, ServiceStoppingError, ended_by_stop, @@ -154,6 +155,7 @@ "RoadmapPlanRewriteError", "RoadmapRefineError", "RoadmapRunError", + "RoadmapStageDegenerateError", "RoadmapStageError", "SSRFBlockedError", "SandboxError", diff --git a/src/devops_cli/exceptions/roadmap.py b/src/devops_cli/exceptions/roadmap.py index 8e61651e0f..a588732010 100644 --- a/src/devops_cli/exceptions/roadmap.py +++ b/src/devops_cli/exceptions/roadmap.py @@ -220,6 +220,14 @@ def __init__( ) +class RoadmapStageDegenerateError(RoadmapStageError): + """Raised for an item whose plan reply holds a placeholder in every text of the plan (#4204). + + The same request would give the same reply, so the job sends no second request. The error has + the code of `RoadmapStageError`; the stage metric counts it under the result `degenerate`. + """ + + class RoadmapPlanRewriteError(DevOpsCLIError): """Raised when `devops roadmap plan-recheck --confirm` refuses to write a rewritten plan (#3556). diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 5cb906ca0e..30ec357f5c 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -3347,6 +3347,10 @@ class RoadmapMessages: stage_left_archived: str = "Its change is archived on {branch}: the folder `{folder}` is there." # The files of the change that the stage job writes, and what its checks find wrong (#2654). stage_invalid: str = "The change fails its checks, also after a second try: {problem}" + stage_degenerate: str = ( + "Every text of the plan reply is a placeholder, such as `x` or `placeholder`. The same " + "request gives the same reply, so the job sends no second request." + ) stage_plan_record_unreadable: str = ( "The plan file {path} can't be read ({reason}). Remove it: the next run then asks the " "planner for a new plan." diff --git a/src/devops_cli/roadmap/agent_run.py b/src/devops_cli/roadmap/agent_run.py index 4118b0ec10..174e47f7c6 100644 --- a/src/devops_cli/roadmap/agent_run.py +++ b/src/devops_cli/roadmap/agent_run.py @@ -200,7 +200,8 @@ class RunTrace: prompt of its output tool, the names of the function tools that each request offered, in order (#3477), and the text of each tool answer, which a quote of the run may come from (#3039). A request that offered none holds an empty tuple. `limit` is the limit that ended the - tools of the run, or None (#3240).""" + tools of the run, or None (#3240). `last_input_tokens` is the input of the last request, the one + that the last reply answered (#4204).""" tool_calls: list[ToolCallRecord] = field(default_factory=list) requests: int = 0 @@ -210,6 +211,7 @@ class RunTrace: offered: list[tuple[str, ...]] = field(default_factory=list) limit: RunLimit | None = None tool_answers: list[str] = field(default_factory=list) + last_input_tokens: int = 0 @classmethod def combined(cls, traces: Iterable[RunTrace]) -> RunTrace: @@ -224,6 +226,7 @@ def combined(cls, traces: Iterable[RunTrace]) -> RunTrace: total.input_tokens += trace.input_tokens total.output_tokens += trace.output_tokens total.violations = trace.violations or total.violations + total.last_input_tokens = trace.last_input_tokens or total.last_input_tokens total.limit = trace.limit or total.limit return total @@ -269,6 +272,7 @@ def _add_reply( answers: Mapping[str, ToolReturnPart | RetryPromptPart], ) -> None: self.requests += 1 + self.last_input_tokens = reply.usage.input_tokens self.input_tokens += reply.usage.input_tokens self.output_tokens += reply.usage.output_tokens for part in reply.parts: diff --git a/src/devops_cli/roadmap/stage/stage.py b/src/devops_cli/roadmap/stage/stage.py index 8abb51ed10..59a0841e6b 100644 --- a/src/devops_cli/roadmap/stage/stage.py +++ b/src/devops_cli/roadmap/stage/stage.py @@ -81,7 +81,7 @@ from enum import StrEnum from functools import cache, partial from pathlib import Path -from typing import Any, Final, NamedTuple, Protocol +from typing import Any, Final, NamedTuple, NoReturn, Protocol from pydantic import BaseModel @@ -114,6 +114,7 @@ GitHubRateLimitError, GitHubUnauthenticatedError, GitOperationError, + RoadmapStageDegenerateError, RoadmapStageError, ServiceStoppingError, ToolExecutionError, @@ -144,7 +145,12 @@ planned_limit_priorities, read_planned_changes, ) -from devops_cli.roadmap.pull_form import SUMMARY_MAX_CHARS, summary_length, title_problems +from devops_cli.roadmap.pull_form import ( + SUMMARY_MAX_CHARS, + is_placeholder, + summary_length, + title_problems, +) from devops_cli.roadmap.pull_labels import add_pull_labels, read_title_labels, remove_pull_labels from devops_cli.roadmap.refine.refine import ( NextStep, @@ -196,13 +202,17 @@ from devops_cli.roadmap.stage.stage_paths import StagedTree, record_test_references from devops_cli.roadmap.stage.stage_pending import PendingStage, orphan_mark from devops_cli.roadmap.stage.stage_plan_record import ( + RefusedRecord, StagePlanRecord, delete_plan_record, + delete_refused_record, plan_key, plan_record_path, prompt_version, read_plan_record, + refused_record_path, write_plan_record, + write_refused_record, ) from devops_cli.roadmap.stage.stage_probe import blocked_by, probe_premise from devops_cli.roadmap.stage.stage_references import reference_files @@ -778,7 +788,8 @@ class StageFailure: """An item the job could not plan or write: the class of the error and why, never the model's text. `item` is the item itself, when the job read it, so that the job records the failure in the job record of the item (#3493). `failure_class` comes from the type of the error, and - `step` names the step that failed (#4056).""" + `step` names the step that failed (#4056). `degenerate` is true for an item whose plan reply was + a placeholder in every text, which the metric counts apart from a failure (#4204).""" number: int title: str @@ -787,6 +798,7 @@ class StageFailure: item: Item | None = field(default=None, compare=False, repr=False) failure_class: FailureClass = field(kw_only=True) step: StepName = field(kw_only=True) + degenerate: bool = field(default=False, kw_only=True) @dataclass(frozen=True) @@ -891,6 +903,20 @@ class _Refused(NamedTuple): reply: StageProposal +def _is_degenerate(proposal: StageProposal) -> bool: + """Whether every text of the plan reply is a placeholder: `why`, `existing_tool`, each line of + `feasibility` and each task of each group (#4204). The rule is `is_placeholder` of the pull + request form, the rule of the content gate, so the two do not differ.""" + tasks = ( + text + for group in proposal.groups + for text in (group.test, group.implementation, group.documentation) + if text is not None + ) + texts = [proposal.why, proposal.existing_tool, *proposal.feasibility, *tasks] + return all(is_placeholder(text) for text in texts) + + class StageClient(Protocol): """What the stage job needs of `LLMClient`: one structured call.""" @@ -1012,7 +1038,9 @@ def plan(self, target: StageTarget) -> StagedChange | OverBudget | Blocked | Fal # commit (#4064). request = kept.request self._dependency = None - outcome = self._gated(target, request, first=None if kept is None else kept.proposal) + outcome = self._gated( + target, request, first=None if kept is None else kept.proposal, key=key + ) if isinstance(outcome, StagedChange) and key is not None: self._keep(target, key, request, outcome.proposal, kept) verifier = self._verifier @@ -1064,25 +1092,95 @@ def _keep( emit(ROADMAP_STAGE_PLAN_RECORD_TOTAL, 1, {"result": "written"}) def _gated( - self, target: StageTarget, request: StageRequest, *, first: StageProposal | None = None + self, + target: StageTarget, + request: StageRequest, + *, + first: StageProposal | None = None, + key: str | None = None, ) -> StagedChange | OverBudget: """The change that passes the checks, with one return of a refused reply. `first` is a kept - plan that stands for the first reply of the model.""" + plan that stands for the first reply of the model. A reply that is a placeholder in every + text ends the item at once: the same request gives the same reply (#4204). A failed item + keeps its refused replies and their problems in a file under `key`, and each refused reply + is logged.""" + floor = len(self._toolbox_traces()) + refused: list[tuple[StageProposal, str]] = [] proposal = first or self._ask(StageProposal, CHANGE_TASK, request.for_model()) + if _is_degenerate(proposal): + self._stop_degenerate(target, key, refused, proposal, floor) outcome = self._settle(target, proposal, request, trace=self._trace_facts()) if isinstance(outcome, _Refused): + self._note_refused(target, floor, "refused") + refused.append((outcome.reply, outcome.problem)) again = { **request.for_model(), "previous": outcome.reply.model_dump(), "problem": outcome.problem, } proposal = self._ask(StageProposal, CHANGE_TASK, again) + if _is_degenerate(proposal): + self._stop_degenerate(target, key, refused, proposal, floor) outcome = self._settle(target, proposal, request, trace=self._trace_facts()) if isinstance(outcome, _Refused): + self._note_refused(target, floor, "refused") + refused.append((outcome.reply, outcome.problem)) + self._keep_refused(target, key, refused) message = MESSAGES.roadmap.stage_invalid.format(problem=outcome.problem) raise _stage_error(message, target) return outcome + def _toolbox_traces(self) -> list[RunTrace]: + """The runs of the toolbox client so far, or an empty list when no toolbox client ran.""" + if not isinstance(self._client, ToolboxClient): + return [] + return list(getattr(self._toolbox, "traces", [])) + + def _note_refused(self, target: StageTarget, floor: int, result: str) -> None: + """Log one line for a refused reply: the item, the number of the last request of the plan + run and its input in tokens, whether that request offered a tool, and the result. `floor` + is the number of runs before this item was asked, so a run of another item is no source. A + plan that no toolbox run made (a kept plan, a plain client) is one request with no count.""" + traces = self._toolbox_traces() + trace = traces[-1] if len(traces) > floor else None + logger.warning( + "stage reply refused: item=#%d request=%d input_tokens=%d tools_offered=%s result=%s", + target.item.number, + trace.requests if trace else 1, + trace.last_input_tokens if trace else 0, + bool(trace and trace.offered and trace.offered[-1]), + result, + ) + + def _keep_refused( + self, target: StageTarget, key: str | None, refused: Sequence[tuple[StageProposal, str]] + ) -> None: + """Write the refused replies of the item with their problems, as the item failed. A run + with no plan files keeps nothing.""" + files = self._plan_files + if files is None or key is None: + return + record = RefusedRecord.of( + key, [(reply.model_dump(), problem) for reply, problem in refused] + ) + write_refused_record(refused_record_path(files.repo, target.item.number), record) + + def _stop_degenerate( + self, + target: StageTarget, + key: str | None, + refused: list[tuple[StageProposal, str]], + proposal: StageProposal, + floor: int, + ) -> NoReturn: + """End the item for a reply that is a placeholder in every text, with no second request.""" + self._note_refused(target, floor, "degenerate") + refused.append((proposal, MESSAGES.roadmap.stage_degenerate)) + self._keep_refused(target, key, refused) + raise RoadmapStageDegenerateError( + MESSAGES.roadmap.stage_degenerate, failed_items=[target.item.number] + ) + def _verified( self, target: StageTarget, @@ -1511,6 +1609,7 @@ def _failure_of( target.item, failure_class=failure_class_of(exc), step=StepName.PLAN, + degenerate=isinstance(exc, RoadmapStageDegenerateError), ) @@ -2541,6 +2640,7 @@ def _stage(self, change: StagedChange) -> None: _stage_one(self._store, self._repo, self._source, self._sha, change, moved, now) # The item is staged, so its plan has no more use. A failed write raised above and kept it. delete_plan_record(plan_record_path(self._repo, change.target.item.number)) + delete_refused_record(refused_record_path(self._repo, change.target.item.number)) @contextmanager def _recording(self, planned: Iterable[StageFailure]) -> Iterator[None]: @@ -2567,6 +2667,7 @@ class StageResult(StrEnum): STAGED = "staged" NEEDS_SPLIT = "needs_split" FAILED = "failed" + DEGENERATE = "degenerate" SKIPPED = "skipped" @@ -2579,9 +2680,10 @@ def stage_results(plan: StagePlan, applied: StageApplied) -> dict[int, StageResu results |= dict.fromkeys(applied.stopped, StageResult.NEEDS_SPLIT) results |= dict.fromkeys(applied.returned, StageResult.SKIPPED) results |= dict.fromkeys(applied.rejected, StageResult.SKIPPED) - results |= dict.fromkeys( - (failure.number for failure in (*plan.failed, *applied.failed)), StageResult.FAILED - ) + results |= { + failure.number: StageResult.DEGENERATE if failure.degenerate else StageResult.FAILED + for failure in (*plan.failed, *applied.failed) + } open_items = {change.target.item.number for change in plan.ready if change.open_findings} results |= dict.fromkeys( (number for number in applied.staged if number in open_items), StageResult.FAILED diff --git a/src/devops_cli/roadmap/stage/stage_eval_run.py b/src/devops_cli/roadmap/stage/stage_eval_run.py index e9febdeb64..22b8d11a54 100644 --- a/src/devops_cli/roadmap/stage/stage_eval_run.py +++ b/src/devops_cli/roadmap/stage/stage_eval_run.py @@ -27,7 +27,12 @@ AIClientError, AICredentialsError, ) -from devops_cli.exceptions import GitOperationError, RoadmapStageError, ToolExecutionError +from devops_cli.exceptions import ( + GitOperationError, + RoadmapStageDegenerateError, + RoadmapStageError, + ToolExecutionError, +) from devops_cli.lang import MESSAGES from devops_cli.openspec.tool import OpenSpecTool from devops_cli.roadmap.clone_git import checkout_at @@ -54,10 +59,13 @@ class Outcome(StrEnum): - """How a case ended. `refused` is a plan that the checks refused after the one return.""" + """How a case ended. `refused` is a plan that the checks refused after the one return. + `degenerate` is a plan reply with a placeholder in every text, which the job refuses at once + (#4204).""" STAGED = "staged" REFUSED = "refused" + DEGENERATE = "degenerate" OVER_BUDGET = "over_budget" FAILED = "failed" @@ -130,6 +138,8 @@ def _planned_as(planned: StagedChange | OverBudget) -> tuple[Outcome, str]: def _ended(exc: Exception) -> tuple[Outcome, str]: """How a case that raised ended, and the reason, never the model's text.""" + if isinstance(exc, RoadmapStageDegenerateError): + return Outcome.DEGENERATE, mask_secrets(str(exc)) if isinstance(exc, RoadmapStageError): return Outcome.REFUSED, mask_secrets(str(exc)) reason = type(exc).__name__ diff --git a/src/devops_cli/roadmap/stage/stage_plan_record.py b/src/devops_cli/roadmap/stage/stage_plan_record.py index 7745fca074..06b82e23e4 100644 --- a/src/devops_cli/roadmap/stage/stage_plan_record.py +++ b/src/devops_cli/roadmap/stage/stage_plan_record.py @@ -1,4 +1,5 @@ -"""The plan that passes the gates of the stage job, kept as one file for each item (#4064). +"""The plan that passes the gates of the stage job, kept as one file for each item (#4064), and the +replies that the gates refuse, kept in a file beside it (#4204). The file holds the `StageProposal` and the `StageRequest` of the plan, under a key of the input: the item number, the title, the hashes of the body, the model name, the toolset name and the prompt @@ -10,11 +11,15 @@ import hashlib import json -from typing import TYPE_CHECKING, Any, Final +from typing import TYPE_CHECKING, Any, Final, Self from pydantic import BaseModel, ConfigDict, ValidationError from devops_cli.ai.task_loader import load_task_prompt +from devops_cli.config.constants import ( + CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS, + CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES, +) from devops_cli.exceptions.roadmap import RoadmapStageError from devops_cli.lang import MESSAGES from devops_cli.output.file_writer import write_json_file @@ -27,8 +32,10 @@ RESEARCH_TOOLS_TASK, TOOLS_TASK, ) +from devops_cli.security.sanitizer import mask_secrets if TYPE_CHECKING: + from collections.abc import Iterable, Mapping from pathlib import Path # The prompts of the planner. The version is the hash of their texts, because the code has no other @@ -47,6 +54,43 @@ class StagePlanRecord(BaseModel): request: StageRequest +class RefusedReply(BaseModel): + """A reply that the checks refused, with the problem that they found. `reply` is None for a + reply over the size bound, and `reply_bytes` is the size of its JSON text.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + reply: dict[str, Any] | None + reply_bytes: int + problem: str + + +class RefusedRecord(BaseModel): + """The refused replies of the last failed plan of an item, under the key of its input.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + key: str + replies: list[RefusedReply] + + @classmethod + def of(cls, key: str, refused: Iterable[tuple[Mapping[str, Any], str]]) -> Self: + """The record of `refused`, each a reply (the dump of the model) and its problem. The + problem is masked for secrets and cut, and a reply over the byte bound is dropped.""" + replies: list[RefusedReply] = [] + for reply, problem in refused: + size = len(json.dumps(reply, ensure_ascii=False, separators=(",", ":")).encode()) + kept = dict(reply) if size <= CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES else None + replies.append( + RefusedReply( + reply=kept, + reply_bytes=size, + problem=mask_secrets(problem)[:CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS], + ) + ) + return cls(key=key, replies=replies) + + def _digest(parts: list[Any]) -> str: return hashlib.sha256(json.dumps(parts, ensure_ascii=False).encode("utf-8")).hexdigest() @@ -82,6 +126,11 @@ def plan_record_path(repo: str, number: int, data_dir: Path | str | None = None) return service_state_dir(data_dir) / _STAGE_DIRECTORY / owner / name / f"{number}.json" +def refused_record_path(repo: str, number: int, data_dir: Path | str | None = None) -> Path: + """The refused-reply file of item `number`: `.refused.json` beside its plan file.""" + return plan_record_path(repo, number, data_dir).with_name(f"{number}.refused.json") + + def _unreadable(path: Path, reason: str) -> RoadmapStageError: return RoadmapStageError( MESSAGES.roadmap.stage_plan_record_unreadable.format( @@ -121,3 +170,15 @@ def write_plan_record(path: Path, record: StagePlanRecord) -> None: def delete_plan_record(path: Path) -> None: """Delete the file of a plan; a file that is not there is not an error.""" path.unlink(missing_ok=True) + + +def write_refused_record(path: Path, record: RefusedRecord) -> None: + """Write the refused replies atomically, so a stop of the job leaves the old file or the new + one.""" + path.parent.mkdir(parents=True, exist_ok=True) + write_json_file(path, record.model_dump(mode="json"), indent=2, atomic=True) + + +def delete_refused_record(path: Path) -> None: + """Delete the refused-reply file of an item; a file that is not there is not an error.""" + path.unlink(missing_ok=True) diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 6fe6d2d23d..20b87edbab 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -313,8 +313,9 @@ class Instrument: "1", "Items that a stage round handled, one count for each item, by repository and result: staged for an item " "written as a branch and a draft pull request, needs_split for an item stopped on a task " - "group over the budget, failed for an item that failed in the plan or in the writes, and " - "skipped for an item the job left out with a reason. A plan with no write counts nothing", + "group over the budget, failed for an item that failed in the plan or in the writes, " + "degenerate for an item whose plan reply was a placeholder in every text (the job sent no " + "second request), and skipped for an item the job left out with a reason. A plan with no write counts nothing", ) ROADMAP_STAGE_PLAN_RECORD_TOTAL = Instrument( "devops_cli_roadmap_stage_plan_record_total", diff --git a/tests/roadmap/stage/test_roadmap_stage_eval_run.py b/tests/roadmap/stage/test_roadmap_stage_eval_run.py index af8a3b8d9b..e6e30df0db 100644 --- a/tests/roadmap/stage/test_roadmap_stage_eval_run.py +++ b/tests/roadmap/stage/test_roadmap_stage_eval_run.py @@ -313,6 +313,26 @@ def _run(name: str, first: dict[GateName, list[str]] | None) -> CaseRun: return CaseRun(name, outcome, "", 1, first) +def test_a_reply_of_placeholders_ends_the_case_degenerate_after_one_call_and_the_score_counts_it( + cases: list[StageCase], stage_repo: StageRepo, model_fake: ModelFake, openspec: OpenSpecFake +) -> None: + case = _live_case(cases, stage_repo) + group = ( + make_stage_proposal() + .groups[0] + .model_copy(update={"test": "x", "implementation": "placeholder", "documentation": None}) + ) + model_fake.answer( + make_stage_proposal(why="x", existing_tool="x", feasibility=["x"], groups=[group]) + ) + + run = run_case(case, _client(model_fake), stage_repo.clone) + score = score_runs("model-x", [case], [run]) + + assert (run.outcome, run.calls) == (Outcome.DEGENERATE, 1) + assert (score.ended[Outcome.DEGENERATE], score.ended[Outcome.REFUSED]) == (1, 0) + + def test_the_score_counts_avoided_and_caught_defects_for_each_type_that_a_gate_catches( cases: list[StageCase], ) -> None: @@ -339,6 +359,7 @@ def test_the_score_counts_avoided_and_caught_defects_for_each_type_that_a_gate_c assert score.ended == { Outcome.STAGED: 3, Outcome.REFUSED: 0, + Outcome.DEGENERATE: 0, Outcome.OVER_BUDGET: 0, Outcome.FAILED: 1, } diff --git a/tests/roadmap/stage/test_roadmap_stage_refused_reply.py b/tests/roadmap/stage/test_roadmap_stage_refused_reply.py new file mode 100644 index 0000000000..3e11f7a800 --- /dev/null +++ b/tests/roadmap/stage/test_roadmap_stage_refused_reply.py @@ -0,0 +1,318 @@ +"""`devops roadmap stage`: a refused reply is kept and logged, and a reply of placeholders ends the +plan run at once as `degenerate` (#4204).""" + +from __future__ import annotations + +import json +import logging +from typing import TYPE_CHECKING, Any, cast + +import pytest + +from devops_cli.config.constants import ( + CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS, + CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES, +) +from devops_cli.exceptions.roadmap import RoadmapStageDegenerateError, RoadmapStageError +from devops_cli.roadmap.failure import FailureClass +from devops_cli.roadmap.stage.stage import ( + StagePlan, + StageResult, + parse_filters, + plan_item, + plan_stage, + stage_results, +) +from devops_cli.roadmap.stage.stage_plan_record import ( + RefusedRecord, + plan_record_path, + refused_record_path, + write_refused_record, +) +from devops_cli.roadmap.stage.stage_toolbox import ToolboxClient +from tests.support.builders import make_stage_proposal +from tests.support.fakes.github import github_json +from tests.support.fakes.roadmap_store import InMemoryRoadmapStore +from tests.support.roadmap_stage import ( + STAGE_REPO, + VALID_REPORT, + StageRepo, + apply_stage, + seed_stageable, + validate_args, +) +from tests.support.scripted_model import Script, call + +if TYPE_CHECKING: + from pathlib import Path + + from devops_cli.roadmap.stage.stage import StageClient + from tests.support.fakes.github import GitHubApiFake + from tests.support.fakes.model import ModelFake + from tests.support.fakes.openspec import OpenSpecFake + +pytestmark = pytest.mark.usefixtures("keyring_store") + +PULLS = f"/repos/{STAGE_REPO}/pulls" +OPENED = github_json({"number": 5, "html_url": "https://example.com/pull/5"}, status=201) +KEY = "k" * 64 + + +@pytest.fixture +def store() -> InMemoryRoadmapStore: + store = InMemoryRoadmapStore(repo=STAGE_REPO) + seed_stageable(store) + store.seed_file( + ".github/labels.yml", + '- name: "type/docs"\n color: "0075ca"\n- name: "scope/openspec"\n color: "0e8a16"\n', + ) + store.seed_pull("staging PR", head_ref="fix/1-the-job-drops-a-comment", draft=True) + return store + + +@pytest.fixture(autouse=True) +def valid_openspec(openspec_fake: OpenSpecFake) -> OpenSpecFake: + openspec_fake.script_sequence( + validate_args("1-the-job-drops-a-comment"), *[(0, VALID_REPORT)] * 6 + ) + return openspec_fake + + +def _plan(store: InMemoryRoadmapStore, repo: StageRepo) -> StagePlan: + return plan_stage( + store, + repo=STAGE_REPO, + source=repo.clone, + filters=parse_filters(()), + model=None, + ) + + +def _refused_file() -> Path: + return refused_record_path(STAGE_REPO, 1) + + +def _read() -> RefusedRecord: + return RefusedRecord.model_validate_json(_refused_file().read_text(encoding="utf-8")) + + +def _missing_path() -> Any: + """A reply that the `paths` gate refuses on each try.""" + group = make_stage_proposal().groups[0] + return make_stage_proposal( + groups=[group.model_copy(update={"changes": [*group.changes, "tests/test_missing.py"]})] + ) + + +def _placeholders() -> Any: + """A reply as the model sent it on 2026-11-08: `x` or `placeholder` in every text of the plan.""" + group = ( + make_stage_proposal() + .groups[0] + .model_copy( + update={ + "test": "x", + "implementation": "placeholder", + "documentation": None, + "verify": "x", + } + ) + ) + return make_stage_proposal( + why="x", existing_tool="placeholder", feasibility=["x"], groups=[group] + ) + + +# ── The refused reply file ──────────────────────────────────────────────────── + + +def test_the_refused_file_is_next_to_the_plan_file() -> None: + assert refused_record_path(STAGE_REPO, 1) == plan_record_path(STAGE_REPO, 1).with_name( + "1.refused.json" + ) + + +def test_a_plan_that_the_gates_refuse_twice_keeps_both_replies_and_both_problems( + store: InMemoryRoadmapStore, stage_repo: StageRepo, model_fake: ModelFake +) -> None: + refused = _missing_path() + model_fake.answer(refused) + + plan = _plan(store, stage_repo) + + record = _read() + assert (len(plan.failed), model_fake.call_count, len(record.replies)) == (1, 2, 2) + for entry in record.replies: + assert entry.reply == refused.model_dump() + assert "tests/test_missing.py" in entry.problem + assert not plan_record_path(STAGE_REPO, 1).exists() + + +def test_the_refused_file_holds_the_key_of_the_plan_input( + store: InMemoryRoadmapStore, stage_repo: StageRepo, model_fake: ModelFake +) -> None: + model_fake.answer(_missing_path()) + _plan(store, stage_repo) + first = json.loads(_refused_file().read_text(encoding="utf-8"))["key"] + store.write_issue_body(1, "The job drops the first comment of a thread.") + + _plan(store, stage_repo) + + second = json.loads(_refused_file().read_text(encoding="utf-8"))["key"] + assert (len(first), first != second) == (64, True) + + +def test_a_staged_item_deletes_its_refused_file( + store: InMemoryRoadmapStore, + stage_repo: StageRepo, + model_fake: ModelFake, + github_api: GitHubApiFake, +) -> None: + github_api.route("POST", PULLS, OPENED) + model_fake.answer(_missing_path()) + _plan(store, stage_repo) + assert _refused_file().is_file() + model_fake.reset() + model_fake.answer(make_stage_proposal()) + planned = _plan(store, stage_repo) + + applied = apply_stage(store, planned, source=stage_repo.clone) + + assert (applied.staged, _refused_file().exists()) == ((1,), False) + + +def test_a_reply_over_the_size_bound_is_dropped_and_its_size_stays( + isolate_data_dir: Path, +) -> None: + big = {"text": "a" * CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES} + long_problem = "p" * (CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS + 500) + + record = RefusedRecord.of(KEY, [(big, long_problem), ({"text": "small"}, "short")]) + write_refused_record(_refused_file(), record) + + first, second = _read().replies + assert (first.reply, first.reply_bytes > CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES) == ( + None, + True, + ) + assert len(first.problem) == CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS + assert (second.reply, second.problem) == ({"text": "small"}, "short") + + +def test_a_problem_text_is_masked_before_it_is_kept(isolate_data_dir: Path) -> None: + record = RefusedRecord.of( + KEY, [({"text": "a"}, "token ghp_abcdefghijklmnopqrstuvwxyz0123456789 in the reply")] + ) + + assert "ghp_abcdefghijklmnopqrstuvwxyz0123456789" not in record.replies[0].problem + + +# ── The reply of placeholders ───────────────────────────────────────────────── + + +def test_a_reply_of_placeholders_ends_the_plan_after_one_call_and_keeps_the_reply( + store: InMemoryRoadmapStore, stage_repo: StageRepo, model_fake: ModelFake +) -> None: + degenerate = _placeholders() + model_fake.answer(degenerate) + + plan = _plan(store, stage_repo) + + (failure,) = plan.failed + record = _read() + assert (model_fake.call_count, failure.error, failure.failure_class) == ( + 1, + "RoadmapStageDegenerateError", + FailureClass.PLAN_DEFECT, + ) + assert (failure.degenerate, [e.reply for e in record.replies]) == ( + True, + [degenerate.model_dump()], + ) + + +def test_a_reply_that_is_only_in_part_placeholders_goes_back_once_as_before( + store: InMemoryRoadmapStore, stage_repo: StageRepo, model_fake: ModelFake +) -> None: + partly = make_stage_proposal(why="x", feasibility=["x"]) + model_fake.answer(partly) + + plan = _plan(store, stage_repo) + + (failure,) = plan.failed + assert (model_fake.call_count, failure.error, failure.degenerate) == ( + 2, + "RoadmapStageError", + False, + ) + + +def test_a_degenerate_item_counts_under_the_result_degenerate_and_a_refused_one_under_failed( + store: InMemoryRoadmapStore, stage_repo: StageRepo, model_fake: ModelFake +) -> None: + model_fake.answer(_placeholders()) + degenerate = _plan(store, stage_repo) + model_fake.reset() + model_fake.answer(_missing_path()) + refused = _plan(store, stage_repo) + + assert ( + stage_results(degenerate, apply_stage(store, degenerate, source=stage_repo.clone)), + stage_results(refused, apply_stage(store, refused, source=stage_repo.clone)), + ) == ({1: StageResult.DEGENERATE}, {1: StageResult.FAILED}) + assert StageResult.DEGENERATE.value == "degenerate" + + +def test_the_degenerate_error_is_a_stage_error_with_the_code_of_a_stage_error() -> None: + error = RoadmapStageDegenerateError("every text is a placeholder", failed_items=[1]) + + assert (isinstance(error, RoadmapStageError), error.error_code, error.failed_items) == ( + True, + RoadmapStageError.error_code, + (1,), + ) + + +# ── The log line ────────────────────────────────────────────────────────────── + + +def test_a_refused_reply_of_a_plan_run_logs_the_request_size_the_request_number_and_the_tools( + store: InMemoryRoadmapStore, + stage_repo: StageRepo, + caplog: pytest.LogCaptureFixture, +) -> None: + item = store.item(1) + assert item is not None + sha = stage_repo.git("rev-parse", "HEAD") + script = Script(call("list_files", directory="src"), _placeholders(), reports_input=True) + client = ToolboxClient(script.model(), cast("StageClient", object()), stage_repo.clone, sha) + + with ( + caplog.at_level(logging.WARNING), + pytest.raises(RoadmapStageDegenerateError, match="placeholder"), + ): + plan_item(item, client=client, checkout=stage_repo.clone, sha=sha) + + (record,) = [r for r in caplog.records if "stage reply refused" in r.getMessage()] + tokens = client.traces[-1].last_input_tokens + assert tokens > 0 + assert record.getMessage() == ( + f"stage reply refused: item=#1 request=2 input_tokens={tokens} tools_offered=True " + "result=degenerate" + ) + + +def test_a_gate_refusal_logs_one_line_for_each_refused_reply( + store: InMemoryRoadmapStore, + stage_repo: StageRepo, + model_fake: ModelFake, + caplog: pytest.LogCaptureFixture, +) -> None: + model_fake.answer(_missing_path()) + + with caplog.at_level(logging.WARNING): + _plan(store, stage_repo) + + lines = [r.getMessage() for r in caplog.records if "stage reply refused" in r.getMessage()] + assert [line.rsplit(" ", 1)[1] for line in lines] == ["result=refused", "result=refused"] + assert all("item=#1 request=1 input_tokens=0 tools_offered=False" in line for line in lines) From d870a0a143bca961073446af9d17902b84e063e2 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 9 Nov 2026 18:11:58 +0000 Subject: [PATCH 2/3] test(roadmap): add the refused-reply limits to the limit table --- tests/roadmap/stage/test_roadmap_stage_refused_reply.py | 4 ++-- tests/roadmap/test_roadmap_limit_classes.py | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/roadmap/stage/test_roadmap_stage_refused_reply.py b/tests/roadmap/stage/test_roadmap_stage_refused_reply.py index 3e11f7a800..6164bf8aa1 100644 --- a/tests/roadmap/stage/test_roadmap_stage_refused_reply.py +++ b/tests/roadmap/stage/test_roadmap_stage_refused_reply.py @@ -266,8 +266,8 @@ def test_a_degenerate_item_counts_under_the_result_degenerate_and_a_refused_one_ def test_the_degenerate_error_is_a_stage_error_with_the_code_of_a_stage_error() -> None: error = RoadmapStageDegenerateError("every text is a placeholder", failed_items=[1]) - assert (isinstance(error, RoadmapStageError), error.error_code, error.failed_items) == ( - True, + assert (type(error).__bases__, error.error_code, error.failed_items) == ( + (RoadmapStageError,), RoadmapStageError.error_code, (1,), ) diff --git a/tests/roadmap/test_roadmap_limit_classes.py b/tests/roadmap/test_roadmap_limit_classes.py index e9284e6d82..78000010e8 100644 --- a/tests/roadmap/test_roadmap_limit_classes.py +++ b/tests/roadmap/test_roadmap_limit_classes.py @@ -70,6 +70,14 @@ "kept", "retries for a reply that breaks the schema; a stuck model fails again", ), + "CONST_ROADMAP_STAGE_REFUSED_REPLY_MAX_BYTES": ( + "kept", + "the size of a refused reply that the job keeps for a person; protects the data volume", + ), + "CONST_ROADMAP_STAGE_REFUSED_PROBLEM_MAX_CHARS": ( + "kept", + "the size of the problem text of a refused reply that the job keeps for a person", + ), "CONST_ROADMAP_REFINE_TOOL_MAX_LINES": ( "raised", "was 120; a tool answer, bounded by the window", From 585886dddb2ba3ba809c76426484741f7c35d2b1 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 9 Nov 2026 18:12:28 +0000 Subject: [PATCH 3/3] docs(openspec): archive the change of #4204 --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/roadmap-stage-eval/spec.md | 0 .../specs/roadmap-stage/spec.md | 0 .../tasks.md | 0 openspec/specs/roadmap-stage-eval/spec.md | 11 +++++++ openspec/specs/roadmap-stage/spec.md | 29 +++++++++++++++++++ 8 files changed, 40 insertions(+) rename openspec/changes/{4204-keep-refused-stage-reply => archive/2026-11-09-4204-keep-refused-stage-reply}/.openspec.yaml (100%) rename openspec/changes/{4204-keep-refused-stage-reply => archive/2026-11-09-4204-keep-refused-stage-reply}/design.md (100%) rename openspec/changes/{4204-keep-refused-stage-reply => archive/2026-11-09-4204-keep-refused-stage-reply}/proposal.md (100%) rename openspec/changes/{4204-keep-refused-stage-reply => archive/2026-11-09-4204-keep-refused-stage-reply}/specs/roadmap-stage-eval/spec.md (100%) rename openspec/changes/{4204-keep-refused-stage-reply => archive/2026-11-09-4204-keep-refused-stage-reply}/specs/roadmap-stage/spec.md (100%) rename openspec/changes/{4204-keep-refused-stage-reply => archive/2026-11-09-4204-keep-refused-stage-reply}/tasks.md (100%) diff --git a/openspec/changes/4204-keep-refused-stage-reply/.openspec.yaml b/openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/.openspec.yaml similarity index 100% rename from openspec/changes/4204-keep-refused-stage-reply/.openspec.yaml rename to openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/.openspec.yaml diff --git a/openspec/changes/4204-keep-refused-stage-reply/design.md b/openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/design.md similarity index 100% rename from openspec/changes/4204-keep-refused-stage-reply/design.md rename to openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/design.md diff --git a/openspec/changes/4204-keep-refused-stage-reply/proposal.md b/openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/proposal.md similarity index 100% rename from openspec/changes/4204-keep-refused-stage-reply/proposal.md rename to openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/proposal.md diff --git a/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md b/openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md similarity index 100% rename from openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md rename to openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/specs/roadmap-stage-eval/spec.md diff --git a/openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md b/openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md similarity index 100% rename from openspec/changes/4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md rename to openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/specs/roadmap-stage/spec.md diff --git a/openspec/changes/4204-keep-refused-stage-reply/tasks.md b/openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/tasks.md similarity index 100% rename from openspec/changes/4204-keep-refused-stage-reply/tasks.md rename to openspec/changes/archive/2026-11-09-4204-keep-refused-stage-reply/tasks.md diff --git a/openspec/specs/roadmap-stage-eval/spec.md b/openspec/specs/roadmap-stage-eval/spec.md index 38d610f20d..ee1a4eb74a 100644 --- a/openspec/specs/roadmap-stage-eval/spec.md +++ b/openspec/specs/roadmap-stage-eval/spec.md @@ -345,3 +345,14 @@ The live run SHALL build the facts context of a case with the same builder as th #### Scenario: The job keeps its error - **WHEN** the stage job plans an item and the staged commit lacks `src/devops_cli/roadmap/failure.py` - **THEN** the job raises `RoadmapStageError` and makes no model call + +### Requirement: The live report counts the degenerate cases +The live run SHALL end a case with the outcome `degenerate` when the stage planner stops it on a reply that is a placeholder in every text, and the report SHALL show the count of such cases in the line of how the cases ended, `0` when there are none. + +#### Scenario: A reply of placeholders +- **WHEN** the model answers a case with `x` or `placeholder` in every text of the plan +- **THEN** the case ends `degenerate` after one model call, and the report shows `degenerate 1` + +#### Scenario: A run with no such reply +- **WHEN** the live run finishes and no reply is a placeholder in every text +- **THEN** the report shows `degenerate 0` diff --git a/openspec/specs/roadmap-stage/spec.md b/openspec/specs/roadmap-stage/spec.md index b1e7492818..e41793ac44 100644 --- a/openspec/specs/roadmap-stage/spec.md +++ b/openspec/specs/roadmap-stage/spec.md @@ -3707,3 +3707,32 @@ A plan run or a review run of the stage job that ends because a tool call of its #### Scenario: A stop that invalid arguments did not cause - **WHEN** a run ends because the reply broke the schema with valid JSON, or because a budget limit was spent - **THEN** the stop is not marked as a stop by invalid arguments + +### Requirement: A refused reply is logged +The stage job SHALL log one line `stage reply refused` for each reply of the model that it refuses, with the number of the item, the number of the last request of the plan run, the input of that request in tokens, whether that request offered a function tool, and the result `refused` or `degenerate`. + +#### Scenario: A reply that the gates refuse +- **WHEN** the gates refuse the reply of item 1 in the second request of a plan run, and that request offered a tool +- **THEN** the log holds one line with `item=#1`, `request=2`, the input of the request in tokens, `tools_offered=True` and `result=refused` + +### Requirement: A failed item keeps its refused replies +When a plan fails, the stage job SHALL write the refused replies and their problems to the file `.refused.json` beside the plan file of item ``, under the key of the plan input. A new failed plan SHALL replace the file, and the staging of the item SHALL delete it. A reply over the byte bound SHALL be dropped with its size kept, and a problem SHALL be masked for secrets and cut to the character bound. + +#### Scenario: The gates refuse a plan twice +- **WHEN** the gates refuse the first reply and the reply after the return of item 1 +- **THEN** the file `1.refused.json` holds the key and both replies, each with its problem, and no plan file exists + +#### Scenario: The item is staged +- **WHEN** a later round stages item 1 +- **THEN** the file `1.refused.json` is deleted + +### Requirement: A reply of placeholders ends the item +The stage job SHALL end an item at once, with no second request, when a reply is a placeholder in `why`, `existing_tool`, each line of `feasibility` and each task of each group. The item SHALL fail with the error `RoadmapStageDegenerateError`, the job SHALL keep the reply as a refused reply, and `devops_cli_roadmap_stage_total` SHALL count the item under the result `degenerate`. A reply with one text that is no placeholder SHALL go back to the model once. + +#### Scenario: The first reply is all placeholders +- **WHEN** the first reply of item 1 holds `x` or `placeholder` in every text of the plan +- **THEN** the model gets one request, the item fails with `RoadmapStageDegenerateError`, and the result of the item is `degenerate` + +#### Scenario: A reply with one real text +- **WHEN** the first reply holds `x` in `why` and in `feasibility` and a real text in `existing_tool` +- **THEN** the reply goes back to the model once, as for any refused reply, and the result stays `failed` if the second reply is refused