diff --git a/README.md b/README.md index 942bc540e6..8b7fdf02c3 100644 --- a/README.md +++ b/README.md @@ -380,6 +380,7 @@ and excessive permissions fail it, and every other finding is shown. | | | `devops roadmap run [OPTIONS]` | Run the roadmap jobs that are due, in order: metrics, then intake, refine and the alternatives check, and record each one's last success. Intake is due on an issue reopened, and decides at most 5 candidates a run and keeps a record of those it left beside the schedule; refine is due every hour, on a first run, and after an intake that placed a critical fix or a P0 item; the alternatives check is due once a day and on a first run, and checks at most roadmap.alternatives.limit items. Without --confirm, or with --dry-run, prints the due list and runs nothing. | | | `devops roadmap implement [OPTIONS]` | Implement a Staged item, in bounded steps. With --group it runs one task group of the change of an item in the checkout --source: the agent is pydantic-ai's Coder on the model of ai.tasks.implement. Its inputs are the item's title, problem and acceptance criteria, the change's proposal, design and tasks, the group, and the files the group names. The command refuses to start when they do not fit the window of the task, or when the checkout has uncommitted changes. The shell of the agent runs only git, uv, ruff and mypy, with a scratch home. When the agent returns, the command runs the verification commands of the group and ruff and mypy on the changed Python files, and checks that the agent made no commit, removed or renamed no test that existed at the start of the step, and ticked every task of the group. The command writes the tasks file back to its text before the run and keeps only the ticks of the group, so no edit of that file stops the step. An agent that forgets a tick gets one more turn that asks only for the ticks, and that may change only the tasks file. When every check passes, it commits the checkout as ' (#\)'. Otherwise it resets the checkout to the commit where the step started, reports the step as stopped with the reason and the masked diff of the work it discarded, and exits 1. It writes nothing to GitHub. Without --group it is the job. It takes each Staged or Planned item that a label filter names (default: status=ready, status=planned, effort=low). A Staged item has its staged branch and draft on origin. A Planned item has its change folder on the default branch and no branch: the job makes the branch \/\-\ there, with the slug of the folder, and opens the draft when the branch first holds a commit. The job rebases the branch, runs a step for each task group that has an unticked task, regenerates the documentation, archives the change, pushes, sets the title and the body of the pull request (the title of the issue, and a body that closes it), watches the checks, runs one fix step for a failed check, and marks the pull request ready. A step that fails stops the item: the job comments why and shows the masked diff of the discarded work, sets the Status to Ready, and runs the item again only after a comment 'implement: retry'. The job leaves out an item that an agent or a person claimed with a label owner/agent or owner/human. When one claims an item that a running job works on, the job ends it at the next group boundary, with no push and no pull request. The job never merges. --confirm runs steps only when the setting roadmap.implement.in_runner is true, which only the pod of a runner Job sets: the shell of the agent is no security boundary. On a workstation, --item \ --confirm starts that runner Job for the item, with the code of devops k8s run-job --template runner, and follows its log (--no-wait prints the Job's name). It refuses an item that an agent or a person claimed, an item that is neither Ready nor Planned, and a repository that has a runner Job that has not ended. --dry-run --item \ prints the Job and makes no request. | | | `devops roadmap explain [OPTIONS] ` | Say, for one issue, whether the stage job and the implement job take it. For each job the answer is yes, or no with the reason of the first rule that fails: the issue is closed or is no item, the filter, the rules of the job (the Status, the owner, the stop on record, the plan and the branch), and the limit of a run. The reasons are the texts of the 'Left out' list of stage --plan and implement --plan. The command reads GitHub and git, calls no model and writes nothing. It uses the filter and the limit that the Service uses for each job. A group over the step budget shows only when an earlier run recorded it. | +| | `devops roadmap inbox [OPTIONS]` | List what waits for a person, each line with its number, its age and the one command or action that clears it. The order is: ready plan pull requests of the jobs (G1), ready implementation pull requests of the jobs (G2), the open release pull request (G3), items in status/blocked with their cause, claims with no activity for 7 days, and labels of .github/labels.yml that the repository lacks. A second list holds the other open pull requests, those of people and agents, with drafts marked. The age is the time since the last update. A draft of a job and a pull request that a runner Job holds are not listed. The command reads the open issues, the open pull requests, the labels and the labels file, and the newest commit of that file when the labels differ. A run sends 5 requests, or 6 when the labels differ, and one more for each 100 open issues and pull requests. It calls no model and writes nothing. It leaves out an image digest that is not rolled yet: run devops argo cd apps status devops. | | | `devops roadmap return [OPTIONS] ` | Return an item to New with an evidence comment, handing it back to refinement when it cannot be built as specified or needs a refactor beyond its scope. The item gets the label status/new in place of its other status/* label. | | | `devops roadmap claim [OPTIONS] ` | Claim an item for an agent or a person with the label owner/agent or owner/human. An item has one owner. A person can take an item from the Service. The jobs stage and implement take no item that an agent or a person claimed. | | | `devops roadmap release [OPTIONS] ` | Release an item: remove its owner/* label, whoever holds it. No job removes the claim of an agent or a person. | diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 3519dd80ab..22a0278b6c 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -6636,6 +6636,21 @@ devops roadmap explain [OPTIONS] | `--limit` | `integer` | - | Items a run takes, for both jobs. Without it, each job uses its own limit: the setting roadmap.stage.limit for stage, and 1 for implement. | | `--dry-run` | `boolean` | - | Make no request: print the reads that a run makes, in order, with placeholders. | +### `devops roadmap inbox` + +**List what waits for a person, each line with its number, its age and the one command or action that clears it. The order is: ready plan pull requests of the jobs (G1), ready implementation pull requests of the jobs (G2), the open release pull request (G3), items in status/blocked with their cause, claims with no activity for 7 days, and labels of .github/labels.yml that the repository lacks. A second list holds the other open pull requests, those of people and agents, with drafts marked. The age is the time since the last update. A draft of a job and a pull request that a runner Job holds are not listed. The command reads the open issues, the open pull requests, the labels and the labels file, and the newest commit of that file when the labels differ. A run sends 5 requests, or 6 when the labels differ, and one more for each 100 open issues and pull requests. It calls no model and writes nothing. It leaves out an image digest that is not rolled yet: run devops argo cd apps status devops.** + +```bash +devops roadmap inbox [OPTIONS] +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--repo`, `-R` | `string` | - | Repository as owner/name (default: this checkout's origin). | +| `--dry-run` | `boolean` | - | Make no request: print the reads that a run makes, in order, with placeholders. | + ### `devops roadmap return` **Return an item to New with an evidence comment, handing it back to refinement when it cannot be built as specified or needs a refactor beyond its scope. The item gets the label status/new in place of its other status/* label.** diff --git a/docs/ROADMAP_WORKFLOW.md b/docs/ROADMAP_WORKFLOW.md index dbf4c6aa87..1e19293f8b 100644 --- a/docs/ROADMAP_WORKFLOW.md +++ b/docs/ROADMAP_WORKFLOW.md @@ -30,6 +30,7 @@ Notes on the table: - A plan that an agent or a person writes is part of the one pull request that closes the issue. It has no separate gate G1. G1 exists for a plan that the Service stages. - A person can do every step of an agent or of the Service. A person's claim beats the Service's claim. - The command `devops roadmap explain ` says why the stage job and the implement job take an Item or leave it out. It names the first rule that fails for each job. It calls no model and writes nothing. The option `--why` on `devops roadmap stage` and `devops roadmap implement` lists the open Items that the filter does not name. +- The command `devops roadmap inbox` lists what waits for a person, in the order of the gates. First the ready plan pull requests of the jobs (G1), the ready implementation pull requests of the jobs (G2) and the release pull request (G3). Then the Items in `status/blocked` with their cause, the claims with no activity for 7 days, and the labels of `.github/labels.yml` that the repository lacks. Each line has the number, the age and the one command or action that clears it. The pull requests of people and agents are in a second list. The command reads GitHub only and writes nothing. It does not list an image digest that is not rolled: `devops argo cd apps status devops` reads it. - The command `devops roadmap return --comment "" --confirm` sends an Item back to `status/new` when it cannot be built as written. ## The transitions @@ -160,8 +161,8 @@ Tracker [#2908](https://github.com/dan-petty/devops-cli/issues/2908) holds the w | :--- | :--- | :--- | | #2912 | Stop and retry | A stop sets `status/blocked` and not `status/ready`. A new runner image clears a stop once | | #2913 | The manual path | `devops roadmap implement` outside the runner makes the runner Job, and `--repo` is needed once | -| #2915 | All | A command lists what waits for a person | | #2916 | 6 Verify | One function decides when any draft pull request is ready | | #2867 | 6 Verify | A model evaluator marks a draft ready when it matches its issue and the project rules | | #2917 | 8 Release and learn | A release comments its version and its deploy time on each issue it carries | | #2919 | All | Metrics show the age of stuck Items, and one alert fires | +| #2968 | All | The counts of `devops roadmap inbox` are gauges with a Grafana panel, and the inbox lists an image digest that is not rolled | diff --git a/docs/commands/roadmap.md b/docs/commands/roadmap.md index 9277414a48..6c4baa6b92 100644 --- a/docs/commands/roadmap.md +++ b/docs/commands/roadmap.md @@ -186,6 +186,23 @@ devops roadmap explain [OPTIONS] --- +## `devops roadmap inbox` + +**List what waits for a person, each line with its number, its age and the one command or action that clears it. The order is: ready plan pull requests of the jobs (G1), ready implementation pull requests of the jobs (G2), the open release pull request (G3), items in status/blocked with their cause, claims with no activity for 7 days, and labels of .github/labels.yml that the repository lacks. A second list holds the other open pull requests, those of people and agents, with drafts marked. The age is the time since the last update. A draft of a job and a pull request that a runner Job holds are not listed. The command reads the open issues, the open pull requests, the labels and the labels file, and the newest commit of that file when the labels differ. A run sends 5 requests, or 6 when the labels differ, and one more for each 100 open issues and pull requests. It calls no model and writes nothing. It leaves out an image digest that is not rolled yet: run devops argo cd apps status devops.** + +```bash +devops roadmap inbox [OPTIONS] +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--repo`, `-R` | `string` | - | Repository as owner/name (default: this checkout's origin). | +| `--dry-run` | `boolean` | - | Make no request: print the reads that a run makes, in order, with placeholders. | + +--- + ## `devops roadmap return` **Return an item to New with an evidence comment, handing it back to refinement when it cannot be built as specified or needs a refactor beyond its scope. The item gets the label status/new in place of its other status/* label.** diff --git a/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/.openspec.yaml b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/.openspec.yaml new file mode 100644 index 0000000000..aa079bc5ee --- /dev/null +++ b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-31 diff --git a/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/design.md b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/design.md new file mode 100644 index 0000000000..9a3dcf904c --- /dev/null +++ b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/design.md @@ -0,0 +1,26 @@ +# Design + +## Decisions + +- **One function reads the inbox, the command prints it.** `read_inbox(store, repo, now)` returns an `Inbox`: the lines of the jobs, in the order of the gates, and the lines of people and agents. The command renders it. W10 (#2919) can count the same lines for its metrics, so the counts and the list cannot differ. +- **The store reads, the inbox judges.** `open_items`, `open_pulls` and `repository_labels` are plain reads on `RoadmapStore`, kept by both adapters. The rules (which pull request is a job's, what an old claim is) live in `inbox.py` only. A test with the in-memory store shows every category. +- **Open issues, not every issue.** `open_items` reads `issues?state=open`. The store keeps the listing of every issue for its life, and that is about 30 pages. The inbox needs only open items: blocked items and claims on open issues, and the records of open items for the pull request numbers. A closed item holds no `status/*` and no `owner/*` label, because `clear-status.yml` removes them. +- **A job pull request is named by a record.** `implement.pr` wins over `stage.pr`, because a staged branch keeps one pull request through both jobs. The record is exact; the title or the branch name is not. A pull request of an item that a Job holds (`implement.job` and no `implement.job_state`) is not listed: the Job pushes to it. +- **A draft is not "waiting".** The jobs' sections list only pull requests that are not drafts. The people section lists every pull request that no record names, a draft too, with the step that moves it on. This answers the case of 2026-10-31: a person sees at once which pull request is finished. +- **The age is the time since the last update.** For a pull request or an issue it is `updated_at`. GitHub gives no "ready since" time without one more request for each pull request. The heading says what the age means. +- **The activity of a claim.** It is the newest `updated_at` of the issue and of each open pull request whose head branch names the issue. The claim label write itself moves the issue, so a new claim is never old. A claim is old after `CONST_ROADMAP_INBOX_CLAIM_DAYS` days. The clearing step is `devops roadmap release --repo --confirm`. No job releases a claim, and the inbox only shows it. +- **The cause of a block.** It is `implement.stopped` (the step that stopped the item), else `refine.blocked_by`, else the text "no cause recorded". The step for a stopped item is the retry comment; the step for the others is to read the issue and to set the status by hand. +- **Labels.** The declared labels come from `.github/labels.yml` on the default branch, parsed by the spec type that `devops gh labels sync` uses. `diff_labels` names the labels to create or update. One line lists them. The age is the time since the file last changed on the default branch, which is a lower bound on how long the repository is behind. +- **The digest is left out.** See the proposal. The help text of the command says so. +- **The dry run lists the reads.** `inbox_requests` is built by `StoreRequests`, the same builders the store runs, so the plan cannot drift. The labels read of the second file is a condition. +- **No cap on lines.** The list is as long as the work that waits. A cap would hide work. + +## Rejected alternatives + +- **Read every issue with `items()`.** About 30 requests for each run, against 2. The Service budget is 500 requests an hour. Rejected on cost. +- **Find a job pull request by its title or branch.** A job and a person use the same forms. A record is exact and already exists. Rejected: a guess would put a person's pull request in the jobs' list. +- **Ask GraphQL for pull requests with their ready time and checks.** One query would give more, but the project keeps GraphQL for the places that need it, and the quota can run out while REST has room. REST with 3 reads is enough. +- **A commit read for each claim.** One more request for each claim and a branch listing. The pull request update time covers the case, since the workflow opens a draft with the first push. Left as a later step if the list shows a false claim. +- **Read the cluster for the digest.** A cluster call from a command that the Service may run, with no GitHub request budget. Rejected: `devops argo cd apps status` is the tool. +- **A Grafana panel now.** It needs the counts as gauges, and issue #2968 owns them. A panel on a second data path would be rebuilt. +- **An open tool.** No open tool knows the records of the jobs. diff --git a/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/proposal.md b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/proposal.md new file mode 100644 index 0000000000..2ed545594b --- /dev/null +++ b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/proposal.md @@ -0,0 +1,78 @@ +# Proposal + +## Why + +Issue #2915, part W7 of the tracker #2908. What waits for a person is spread over many places: plan pull requests to merge (G1), implementation pull requests to merge (G2), the release pull request (G3), stopped items, old claims, and repository state such as labels that are not synced. On 2026-10-31 the owner could not tell whether three pull requests (#2857 to #2859) were drafts in progress or finished. + +No command shows the whole list. A person must open the pull request list, the issue list and the labels page, and then guess which pull request belongs to a job. + +## What Changes + +- New command `devops roadmap inbox`. It prints, in this order, the lines that wait for a person: + 1. ready plan pull requests of the jobs (G1), + 2. ready implementation pull requests of the jobs (G2), + 3. the open release pull request (G3), + 4. items in `status/blocked`, each with its cause, + 5. old claims: an `owner/*` label with no activity for `CONST_ROADMAP_INBOX_CLAIM_DAYS` days (7), + 6. repository state that a person owns: labels that `.github/labels.yml` declares and the repository lacks or holds with another color or description. +- Each line has the number, the age and the one command or action that clears it. +- A second list, "Pull requests of people and agents", holds every other open pull request, so a person's own pull requests are apart from the jobs'. A draft is shown as a draft, with the command that moves it on. +- A pull request belongs to a job when the job record of an open item names it: `implement.pr` makes it an implementation pull request, `stage.pr` a plan pull request. The release pull request is the open pull request whose head branch starts with `release-please--branches--`. A draft of a job is not listed: it waits for its checks, not for a person. +- The command is read-only and calls no model. Its dry-run class is `request-plan`: `--dry-run` makes no request and lists the reads of a run. +- The store gets three reads: `open_items`, `open_pulls` and `repository_labels`. `Item` gets `updated_at`. `StoreRequests` gets the matching plan entries, so the dry run lists the same requests the run sends. +- `docs/ROADMAP_WORKFLOW.md` names the command and drops #2915 from "Planned changes". +- Observable behavior changes (a command and its output), so the change carries a spec delta. The delta only adds a capability; it modifies and removes no requirement. +- The change fits one pull request. + +### Requests, and the budget + +A run sends only reads: + +| Read | Pages or requests | +| :--- | :--- | +| Open issues and pull requests (`issues?state=open`) | one page for each 100, now 2 | +| Open pull requests (`pulls?state=open`) | one page for each 100, now 1 | +| Repository labels (`labels`) | one page for each 100, now 1 | +| `.github/labels.yml` on the default branch | 1 | +| Newest commit that changed `.github/labels.yml` | 1, only when the labels differ | + +Today a run sends 5 requests, or 6 when the labels differ. The number grows with the open issues and pull requests, and not with the closed ones. The old design read every issue, which is about 30 pages. If the Service ran the inbox at each 10-minute round of one repository, it would send about 36 requests an hour, which is 7 percent of `service.github_requests_per_hour` (500). This change does not run it in the Service. Issue #2968 decides that, with the gauges. + +### Out of scope + +- **A Grafana panel.** The data path is not trivial: the panel needs the counts as gauges that `emit` sends. Issue #2968 owns the gauges and the panel. They read the counts from `read_inbox`. Issue #2919 builds the age gauges and an age panel, and it does not wait for the inbox panel. +- **The image digest not yet rolled.** The read needs the registry and the Argo CD Application, which means a call to the cluster that the Service budget does not count and a workstation may not have. `devops argo cd apps status devops` already reads both and exits 1 when the pin is old. The inbox leaves the digest out and says so in the command help. Issue #2968 owns the digest line. +- **Branch commits for a claim.** The activity of a claim is the newest update of its issue or of its open pull request. A commit date for a branch with no pull request needs one more request for each claim. The workflow opens a draft pull request with the first push, so the gap is short. + +## Capabilities + +### New Capabilities + +- `roadmap-inbox`: the command that lists what waits for a person, with the age and the clearing step of each line. + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/roadmap/inbox.py` (new), `src/devops_cli/roadmap/store.py`, `src/devops_cli/roadmap/github_store.py`, `src/devops_cli/roadmap/memory_store.py`, `src/devops_cli/roadmap/request_plan.py`, `src/devops_cli/roadmap/title_labels.py`, `src/devops_cli/commands/roadmap.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/lang/en/help.py`, `src/devops_cli/lang/en/messages.py`. +- Documents: `docs/ROADMAP_WORKFLOW.md`; `README.md` and the command reference under `docs/` are regenerated by `devops docs generate --sync-readme`. +- Tests: `tests/roadmap/test_roadmap_inbox.py` (new), `tests/roadmap/test_roadmap_inbox_requests.py` (new), `tests/roadmap/test_roadmap_inbox_command.py` (new), `tests/roadmap/test_roadmap_store_contract.py`, `tests/roadmap_github_fake.py`. + +## Feasibility + +Checked on 2026-10-31 and 2026-11-01 against the real system: + +- Pull requests carry what the list needs. `devops gh api "repos/dan-petty/devops-cli/pulls?state=open&per_page=1"` returns `draft`, `user.login`, `head.ref`, `html_url`, `created_at` and `updated_at`. One listing of 100 pull requests holds all open ones (3 today). +- A job pull request is known from the job record. `StageRecordKey.PR` and `ImplementRecordKey.PR` hold the number of the pull request (`roadmap/store.py`). The stage job records `stage.pr` when it opens the draft, and the implement job records `implement.pr`. A staged item keeps one pull request through both jobs, so `implement.pr` wins over `stage.pr`. +- The release pull request has a fixed branch. The closed release pull requests of this repository (`pulls?state=closed`) all have the head branch `release-please--branches--main--components--devops-cli`, the form that release-please gives (`release-please--branches--`). The inbox matches the prefix. +- The branch form gives the issue of a person's pull request. `issue_of_branch` in `src/devops_cli/git/branch_form.py` reads `/-`. The inbox uses it for the activity of a claim. +- The label diff exists. `diff_labels` in `src/devops_cli/github/labels.py` partitions the declared labels into create, update and unchanged. The repository has 91 labels, so one page reads them. +- Open issues are cheap to read, closed ones are not. The repository reports 137 open issues and pull requests (`open_issues_count`). The listing `state=all` that the store caches is about 30 pages. So the inbox reads `state=open`. +- The dry-run rule. `tests/invariants/test_dry_run_class_ratchet.py` needs a class on every command. The inbox reads GitHub, so its class is `request-plan` and it declares `--dry-run`, as `claim` and `explain` do. +- The premise holds. No part of the item needs code that works around a missing tool. + +## Existing Tool Considered + +`gh pr list`, `gh issue list` and `gh-dash` (adopted for the pull request views) list pull requests and issues. None knows which pull request is a job's, which gate it waits at, or what a claim record says, so none gives the list in the order of the gates with one clearing step for each line. The change reuses `RoadmapStore`, `diff_labels`, `declared_label_specs`, `issue_of_branch`, `format_duration`, `StoreRequests` and `render_dry_run`. It builds `inbox.py` (about 200 lines) and three store reads. The written cost is about 80 000 tokens to build and review, and the tests keep the rest. It deletes no code. diff --git a/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/specs/roadmap-inbox/spec.md b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/specs/roadmap-inbox/spec.md new file mode 100644 index 0000000000..18fd207d1f --- /dev/null +++ b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/specs/roadmap-inbox/spec.md @@ -0,0 +1,69 @@ +# roadmap-inbox Specification + +## Purpose +How `devops roadmap inbox` lists what waits for a person on the roadmap: the pull requests of the jobs at their gates, the release pull request, blocked items, old claims and repository state, each with its age and the one step that clears it. + +## ADDED Requirements + +### Requirement: The inbox lists the gates of the jobs in order +`devops roadmap inbox` SHALL list, in this order: ready plan pull requests of the jobs, ready implementation pull requests of the jobs, the open release pull request, items in `status/blocked` with their cause, old claims, and labels that the repository lacks. A pull request is a job's when the job record of an open item names it in `implement.pr` or `stage.pr`; `implement.pr` wins. A draft pull request of a job SHALL NOT be listed. + +#### Scenario: Each category +- **WHEN** the repository holds a ready plan pull request, a ready implementation pull request, a release pull request, a blocked item, an old claim and a missing label +- **THEN** the output lists one line for each, in the order above + +#### Scenario: A draft of a job +- **WHEN** the record of an item names a draft pull request in `stage.pr` +- **THEN** the output does not list it + +#### Scenario: A staged branch that became an implementation +- **WHEN** one pull request is named by `stage.pr` and by `implement.pr` of an item +- **THEN** it is listed once, as an implementation pull request + +#### Scenario: A pull request that a Job holds +- **WHEN** the record of an item names a ready pull request and a runner Job that no round reported +- **THEN** the output does not list the pull request + +### Requirement: Each line has the number, the age and one clearing step +Each line SHALL show the number of its issue or pull request (`-` when it has none), the time since its last update, and the one command or action that clears it. A pull request of a job SHALL be cleared by a review and a merge at its gate, the release pull request by a merge, a stopped item by the comment `implement: retry`, an old claim by `devops roadmap release`, and missing labels by `devops gh labels sync`. + +#### Scenario: The command of a line +- **WHEN** the inbox lists an old claim of #7 and missing labels +- **THEN** the claim line shows `#7`, an age, and `devops roadmap release 7 --repo --confirm`, and the labels line shows `devops gh labels sync --repo ` + +#### Scenario: The cause of a block +- **WHEN** a blocked item records `implement.stopped` as `group 2` +- **THEN** its line shows `group 2` as the cause and the retry comment as the step + +### Requirement: Old claims are shown, never removed +A claim SHALL be old when its issue and every open pull request whose head branch names the issue (`/-`) have not changed for `CONST_ROADMAP_INBOX_CLAIM_DAYS` days. The inbox SHALL write nothing, so no claim is released. + +#### Scenario: A pull request keeps a claim young +- **WHEN** an item holds `owner/agent` and its issue is 10 days old, and the pull request `feat/7-x` changed 1 day ago +- **THEN** the inbox lists no old claim for the item + +#### Scenario: An idle claim +- **WHEN** an item holds `owner/human` and neither its issue nor any pull request changed for 8 days +- **THEN** the inbox lists the claim with an age of 8 days + +### Requirement: Pull requests of people and agents are listed apart +Every open pull request that no job record names and that is not the release pull request SHALL be listed in a second list, after the first. A ready one SHALL be cleared by a review and a merge. A draft SHALL be shown as a draft, with `devops pr monitor` and `devops pr ready` as its step. + +#### Scenario: A person's pull requests +- **WHEN** a person has one ready pull request and one draft, and a job has a ready plan pull request +- **THEN** the first list holds the plan pull request only, and the second list holds the two pull requests of the person, the draft marked as a draft + +### Requirement: The inbox reads a bounded number of requests and writes none +The inbox SHALL read the open issues, the open pull requests, the repository labels and `.github/labels.yml` once, and the newest commit of that file only when the labels differ. It SHALL NOT call a model, and it SHALL write nothing to GitHub or git. Its dry-run class SHALL be `request-plan`: `--dry-run` SHALL make no request and SHALL list the reads. + +#### Scenario: No write +- **WHEN** the inbox runs on a store that records writes +- **THEN** the store records no write + +#### Scenario: The reads +- **WHEN** the inbox runs against a store that counts reads of open issues, open pull requests and labels +- **THEN** each is read once, and no read of every issue happens + +#### Scenario: A dry run +- **WHEN** `inbox --dry-run` runs with processes and sockets refused +- **THEN** the exit status is 0, the output says that no request was made, and it lists the reads and no write diff --git a/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/tasks.md b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/tasks.md new file mode 100644 index 0000000000..fa7ed7db0e --- /dev/null +++ b/openspec/changes/archive/2026-11-01-2915-roadmap-inbox/tasks.md @@ -0,0 +1,37 @@ +# Tasks + +## 1. The store reads and their plan + +- [x] 1.1 Write failing tests in `tests/roadmap/test_roadmap_store_contract.py` for `open_items` (open items only, `updated_at` set, and no read of every issue), `open_pulls` (draft, head branch, update time) and `repository_labels`, on both adapters; and in `tests/roadmap/test_roadmap_inbox_requests.py` for the plan entries of `StoreRequests` and `inbox_requests` + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_store_contract.py tests/roadmap/test_roadmap_inbox_requests.py` +- [x] 1.2 Add `Item.updated_at`, the models `OpenPull` and `RepositoryLabel`, and the three reads to `RoadmapStore`, `GitHubRoadmapStore` and `InMemoryRoadmapStore` (with `seed_pull` and `seed_label`); add `StoreRequests.open_items`, `open_pulls` and `repository_labels` and `inbox_requests`; add `declared_label_specs` to `title_labels.py` + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_store_contract.py tests/roadmap/test_roadmap_github_store.py tests/roadmap/test_roadmap_inbox_requests.py tests/roadmap/test_roadmap_dry_runs.py` + +## 2. The inbox + +- [x] 2.1 Write failing tests in `tests/roadmap/test_roadmap_inbox.py` for the scenarios of "The inbox lists the gates of the jobs in order", "Each line has the number, the age and one clearing step", "Old claims are shown, never removed" and "Pull requests of people and agents are listed apart", with a fake repository + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_inbox.py` +- [x] 2.2 Write `src/devops_cli/roadmap/inbox.py`: `read_inbox`, `inbox_requests` and `render_inbox`, with the constants `CONST_ROADMAP_INBOX_CLAIM_DAYS` and `CONST_ROADMAP_RELEASE_BRANCH_PREFIX` and the messages of the lines + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_inbox.py` + +## 3. The command + +- [x] 3.1 Write failing tests in `tests/roadmap/test_roadmap_inbox_command.py` for the scenarios of "The inbox reads a bounded number of requests and writes none": the output, the reads counted, no write, no model, and the dry run with processes and sockets refused + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_inbox_command.py` +- [x] 3.2 Add `devops roadmap inbox` with the class `request-plan`, its help and the read failure message + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_inbox_command.py tests/invariants/test_dry_run_class_ratchet.py` + +## 4. The documents and the archive + +- [x] 4.1 Regenerate the command documents + - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` +- [x] 4.2 Name `devops roadmap inbox` in `docs/ROADMAP_WORKFLOW.md` and remove the line of #2915 from "Planned changes" + - Verification: `uv run devops ci test tests/invariants/test_roadmap_workflow_doc.py` +- [x] 4.3 Archive the change + - Verification: `uv run devops openspec archive 2915-roadmap-inbox` + +## Workflow follow-up + +- Issue #2968 owns the inbox counts as gauges, the Grafana panel of the inbox and the image digest line. #2919 builds the age panel and does not wait for it. +- Until #2968 merges, the image digest that is not yet rolled stays out of the inbox. `devops argo cd apps status devops` reads it. +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/openspec/specs/roadmap-inbox/spec.md b/openspec/specs/roadmap-inbox/spec.md new file mode 100644 index 0000000000..e4dc2fc20c --- /dev/null +++ b/openspec/specs/roadmap-inbox/spec.md @@ -0,0 +1,69 @@ +# roadmap-inbox Specification + +## Purpose +How `devops roadmap inbox` lists what waits for a person on the roadmap: the pull requests of the jobs at their gates, the release pull request, blocked items, old claims and repository state, each with its age and the one step that clears it. + +## Requirements + +### Requirement: The inbox lists the gates of the jobs in order +`devops roadmap inbox` SHALL list, in this order: ready plan pull requests of the jobs, ready implementation pull requests of the jobs, the open release pull request, items in `status/blocked` with their cause, old claims, and labels that the repository lacks. A pull request is a job's when the job record of an open item names it in `implement.pr` or `stage.pr`; `implement.pr` wins. A draft pull request of a job SHALL NOT be listed. + +#### Scenario: Each category +- **WHEN** the repository holds a ready plan pull request, a ready implementation pull request, a release pull request, a blocked item, an old claim and a missing label +- **THEN** the output lists one line for each, in the order above + +#### Scenario: A draft of a job +- **WHEN** the record of an item names a draft pull request in `stage.pr` +- **THEN** the output does not list it + +#### Scenario: A staged branch that became an implementation +- **WHEN** one pull request is named by `stage.pr` and by `implement.pr` of an item +- **THEN** it is listed once, as an implementation pull request + +#### Scenario: A pull request that a Job holds +- **WHEN** the record of an item names a ready pull request and a runner Job that no round reported +- **THEN** the output does not list the pull request + +### Requirement: Each line has the number, the age and one clearing step +Each line SHALL show the number of its issue or pull request (`-` when it has none), the time since its last update, and the one command or action that clears it. A pull request of a job SHALL be cleared by a review and a merge at its gate, the release pull request by a merge, a stopped item by the comment `implement: retry`, an old claim by `devops roadmap release`, and missing labels by `devops gh labels sync`. + +#### Scenario: The command of a line +- **WHEN** the inbox lists an old claim of #7 and missing labels +- **THEN** the claim line shows `#7`, an age, and `devops roadmap release 7 --repo --confirm`, and the labels line shows `devops gh labels sync --repo ` + +#### Scenario: The cause of a block +- **WHEN** a blocked item records `implement.stopped` as `group 2` +- **THEN** its line shows `group 2` as the cause and the retry comment as the step + +### Requirement: Old claims are shown, never removed +A claim SHALL be old when its issue and every open pull request whose head branch names the issue (`/-`) have not changed for `CONST_ROADMAP_INBOX_CLAIM_DAYS` days. The inbox SHALL write nothing, so no claim is released. + +#### Scenario: A pull request keeps a claim young +- **WHEN** an item holds `owner/agent` and its issue is 10 days old, and the pull request `feat/7-x` changed 1 day ago +- **THEN** the inbox lists no old claim for the item + +#### Scenario: An idle claim +- **WHEN** an item holds `owner/human` and neither its issue nor any pull request changed for 8 days +- **THEN** the inbox lists the claim with an age of 8 days + +### Requirement: Pull requests of people and agents are listed apart +Every open pull request that no job record names and that is not the release pull request SHALL be listed in a second list, after the first. A ready one SHALL be cleared by a review and a merge. A draft SHALL be shown as a draft, with `devops pr monitor` and `devops pr ready` as its step. + +#### Scenario: A person's pull requests +- **WHEN** a person has one ready pull request and one draft, and a job has a ready plan pull request +- **THEN** the first list holds the plan pull request only, and the second list holds the two pull requests of the person, the draft marked as a draft + +### Requirement: The inbox reads a bounded number of requests and writes none +The inbox SHALL read the open issues, the open pull requests, the repository labels and `.github/labels.yml` once, and the newest commit of that file only when the labels differ. It SHALL NOT call a model, and it SHALL write nothing to GitHub or git. Its dry-run class SHALL be `request-plan`: `--dry-run` SHALL make no request and SHALL list the reads. + +#### Scenario: No write +- **WHEN** the inbox runs on a store that records writes +- **THEN** the store records no write + +#### Scenario: The reads +- **WHEN** the inbox runs against a store that counts reads of open issues, open pull requests and labels +- **THEN** each is read once, and no read of every issue happens + +#### Scenario: A dry run +- **WHEN** `inbox --dry-run` runs with processes and sockets refused +- **THEN** the exit status is 0, the output says that no request was made, and it lists the reads and no write diff --git a/src/devops_cli/commands/roadmap.py b/src/devops_cli/commands/roadmap.py index 8ad518fbd0..553efd19d0 100644 --- a/src/devops_cli/commands/roadmap.py +++ b/src/devops_cli/commands/roadmap.py @@ -1,7 +1,8 @@ """`devops roadmap`: the roadmap on GitHub. Intake is the one way new work becomes an item, refine readies items, stage makes a Ready item Staged, implement takes a Staged or Planned item to a ready pull request, return sends an item back to New, claim and release say who works -on an item, and explain says why the stage job and the implement job take an item or leave it out. +on an item, explain says why the stage job and the implement job take an item or leave it out, and +inbox lists what waits for a person. Every command opens the roadmap store of the repository: labels and milestones hold the Items and their fields, and no command reads or writes a project board (ADR 0016). Intake reads @@ -9,7 +10,8 @@ `release` write GitHub state only with `--confirm`; `stage` and `implement` also write git, only to the staged branch of an item and never to the default branch. `implement --confirm` runs steps only in a runner pod. Outside one, `implement --item --confirm` starts the runner Job for the item -(#2913). `explain` reads GitHub and git, calls no model and writes nothing. A person plans the +(#2913). `explain` reads GitHub and git, and `inbox` reads GitHub only. Both call no model and +write nothing. A person plans the milestones; no command sets one. Every job's `--dry-run` makes no request at all (#412, #1125): it returns the job's result type @@ -781,6 +783,29 @@ def explain_cmd( write_stdout(render_explanation(explained) + "\n") +@app.command("inbox", help=HELP.roadmap.inbox) +@dry_run_class("request-plan") +def inbox_cmd( + repo: RepoOption = None, + dry_run: Annotated[bool, typer.Option("--dry-run", help=HELP.roadmap.inbox_dry_run)] = False, +) -> None: + """List what waits for a person, each line with its age and the step that clears it.""" + from datetime import UTC, datetime + + from devops_cli.roadmap.inbox import read_inbox, render_inbox + from devops_cli.roadmap.request_plan import inbox_requests + + target = _target(repo) + if dry_run or is_dry_run(): + reads, writes = inbox_requests(target) + render_dry_run("inbox", target, reads, writes) + return + with _exit_on_failure("Could not read the inbox"): + _, store = _open_store(target) + inbox = read_inbox(store, repo=target, now=datetime.now(UTC)) + write_stdout(render_inbox(inbox, repo=target) + "\n") + + def _resolve_comment(comment: str, comment_file: Path | None) -> str: """Extract comment text from inline option or file, raising if invalid or missing.""" clean = comment.strip() diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 2ed6ad140f..b6f63e39e6 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -3188,6 +3188,13 @@ class WebhookExposure(StrEnum): CONST_ROADMAP_STAGE_COMMENT_MARKER, ) CONST_ROADMAP_LABELS_PATH: Final[str] = ".github/labels.yml" +# `devops roadmap inbox` (#2915). A claim whose issue and open pull requests have not changed for +# this many days is old. The head branch of the release pull request starts with the prefix that +# release-please gives (`release-please--branches--`). The line of the labels names this +# many labels, then counts the rest. +CONST_ROADMAP_INBOX_CLAIM_DAYS: Final[int] = 7 +CONST_ROADMAP_RELEASE_BRANCH_PREFIX: Final[str] = "release-please--branches--" +CONST_ROADMAP_INBOX_LABEL_NAMES: Final[int] = 5 CONST_ROADMAP_TYPE_LABEL_PREFIX: Final[str] = "type/" CONST_ROADMAP_PRIORITY_LABEL_PREFIX: Final[str] = "priority/" CONST_ROADMAP_SCOPE_LABEL_PREFIX: Final[str] = "scope/" diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index c7803e5846..df3bd41c0b 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -1503,6 +1503,23 @@ class RoadmapCommandHelp: explain_dry_run: str = ( "Make no request: print the reads that a run makes, in order, with placeholders." ) + inbox: str = ( + "List what waits for a person, each line with its number, its age and the one command or " + "action that clears it. The order is: ready plan pull requests of the jobs (G1), ready " + "implementation pull requests of the jobs (G2), the open release pull request (G3), items " + "in status/blocked with their cause, claims with no activity for 7 days, and labels of " + ".github/labels.yml that the repository lacks. A second list holds the other open pull " + "requests, those of people and agents, with drafts marked. The age is the time since the " + "last update. A draft of a job and a pull request that a runner Job holds are not listed. " + "The command reads the open issues, the open pull requests, the labels and the labels " + "file, and the newest commit of that file when the labels differ. A run sends 5 requests, " + "or 6 when the labels differ, and one more for each 100 open issues and pull requests. " + "It calls no model and writes nothing. It leaves out an image digest that is not rolled " + "yet: run devops argo cd apps status devops." + ) + inbox_dry_run: str = ( + "Make no request: print the reads that a run makes, in order, with placeholders." + ) release: str = ( "Release an item: remove its owner/* label, whoever holds it. No job removes the claim " "of an agent or a person." diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 3f0bf96b2a..6d42d6acf4 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -2583,6 +2583,59 @@ class RoadmapMessages: "`gh api rate_limit`; that read costs no quota.", ) plan_modes_exclusive: str = "Pass one of {modes}, not more." + # `devops roadmap inbox` (#2915). + inbox_title: str = "Waiting for a person in {repo}. The age is the time since the last update." + inbox_empty: str = "Nothing waits for a person in {repo}." + inbox_footer: str = ( + "Not listed: an image digest that is not rolled yet. " + "Run `devops argo cd apps status devops` to read it." + ) + inbox_headings: dict[str, str] = field( + default_factory=lambda: { + "plan": "Ready plan pull requests of the jobs (G1)", + "implement": "Ready implementation pull requests of the jobs (G2)", + "release": "The release pull request (G3)", + "blocked": "Items in status/blocked", + "claim": "Claims with no activity for {days} days", + "labels": "Repository state that a person owns", + "person": "Pull requests of people and agents", + } + ) + inbox_line: str = " {number} {age} {subject}" + inbox_clear: str = " Clear it: {clear}" + inbox_no_number: str = "-" + inbox_no_age: str = "-" + inbox_subjects: dict[str, str] = field( + default_factory=lambda: { + "pull": "{title}", + "draft": "{title} (draft)", + "stopped": "{title}: stopped at {step}", + "blocked_by": "{title}: waits for {blockers}", + "no_cause": "{title}: no cause is recorded", + "claim": "{title} (claimed by {owner})", + "labels": "{count} label(s) of {path} are missing or changed on GitHub: {names}", + "more_labels": "{names}, and {more} more", + } + ) + inbox_clears: dict[str, str] = field( + default_factory=lambda: { + "plan": "Review it, then merge it (G1): {url}", + "implement": "Review it, then merge it (G2): {url}", + "release": "Review it, then merge it (G3): {url}", + "person_ready": "Review it, then merge it (G2): {url}", + "person_draft": ( + "Wait for the checks with `devops pr monitor {number} --repo {repo}`, " + "then run `devops pr ready {number} --repo {repo}`." + ), + "stopped": "Fix the cause, then comment `{retry}` on #{number}.", + "blocked": ( + "Fix the cause, then set the status by hand: `devops gh issues edit {number} " + "--repo {repo} --add-label status/ready --remove-label status/blocked`." + ), + "claim": "devops roadmap release {number} --repo {repo} --confirm", + "labels": "devops gh labels sync --repo {repo}", + } + ) plan_repeat_page: str = "per page, while GitHub links a next one" plan_placeholders: dict[str, str] = field( default_factory=lambda: { @@ -2628,6 +2681,8 @@ class RoadmapMessages: "workflow_run": "the workflow run {subject} cites", "commit": "the commit {subject} cites", "path_change": "the newest commit on the default branch that changed {subject}", + "open_pulls": "the open pull requests", + "repository_labels": "the labels of the repository", "visibility": "whether the repository is private", "web_search": "a Firecrawl web search for {subject}", "repository_facts": "the repository {subject}", @@ -2657,6 +2712,7 @@ class RoadmapMessages: "posted": "the change posts a comment", "check_on": "the repository is public and a Firecrawl key is set", "issues_unread": "the run has not read every issue yet", + "labels_differ": "the labels of the repository differ from .github/labels.yml", "still_waiting": "no comment follows refine's last comment on the waiting item", "capped": ( "the cap on refine's comments leaves the item alone, and no earlier round " diff --git a/src/devops_cli/roadmap/github_store.py b/src/devops_cli/roadmap/github_store.py index e26576c62c..c0439bf537 100644 --- a/src/devops_cli/roadmap/github_store.py +++ b/src/devops_cli/roadmap/github_store.py @@ -65,7 +65,9 @@ Item, ItemField, Milestone, + OpenPull, RepositoryFacts, + RepositoryLabel, RoadmapStore, already_closed, as_utc, @@ -201,6 +203,34 @@ def record(self) -> IssueRecord: ) +class _PullPayload(BaseModel): + number: int + title: str + html_url: str + draft: bool = False + head_ref: str = Field(validation_alias=AliasPath("head", "ref")) + updated_at: datetime + + def pull(self) -> OpenPull: + return OpenPull( + number=self.number, + title=self.title, + url=self.html_url, + head_ref=self.head_ref, + draft=self.draft, + updated_at=self.updated_at, + ) + + +class _LabelPayload(BaseModel): + name: str + color: str = "" + description: str | None = None + + def label(self) -> RepositoryLabel: + return RepositoryLabel(name=self.name, color=self.color, description=self.description or "") + + class _EventPayload(BaseModel): event: str created_at: datetime @@ -301,6 +331,8 @@ class _ReleasePayload(BaseModel): _MILESTONE = TypeAdapter(_MilestonePayload) _ISSUE = TypeAdapter(_IssuePayload) +_PULL = TypeAdapter(_PullPayload) +_LABEL = TypeAdapter(_LabelPayload) _EVENT = TypeAdapter(_EventPayload) _IS_PRIVATE = TypeAdapter(_IsPrivatePayload) _REPOSITORY_PAYLOAD = TypeAdapter(_RepositoryPayload) @@ -344,6 +376,16 @@ def milestones_endpoint(repo: str) -> str: return f"repos/{repo}/milestones?state=all" +def pulls_endpoint(repo: str) -> str: + """The REST listing of the open pull requests of `repo`.""" + return f"repos/{repo}/pulls?state=open" + + +def labels_endpoint(repo: str) -> str: + """The REST listing of the labels of `repo`.""" + return f"repos/{repo}/labels" + + def issues_endpoint(repo: str, query: str = "state=all") -> str: """The REST listing of `repo`'s issues that `query` selects, every one by default.""" return f"repos/{repo}/issues?{query}" @@ -568,6 +610,21 @@ def backlog(self) -> list[Item]: """The open Items in no milestone.""" return select_items(self._read_issues("milestone=none&state=open")) + def open_items(self) -> list[Item]: + """The open Items, from the listing of open issues: one page for each 100 open issues + and pull requests, and no read of the closed ones.""" + return select_items(self._read_issues("state=open")) + + def open_pulls(self) -> list[OpenPull]: + """The open pull requests, one page for each 100.""" + listing = self._listing(pulls_endpoint(self._repo), _PULL, "pull requests") + return [pull.pull() for pull in listing] + + def repository_labels(self) -> list[RepositoryLabel]: + """The labels of the repository, one page for each 100.""" + listing = self._listing(labels_endpoint(self._repo), _LABEL, "labels") + return [label.label() for label in listing] + def candidates(self) -> list[Candidate]: """The open issues of the repository that hold no Priority.""" return select_candidates(self._every_issue()) diff --git a/src/devops_cli/roadmap/inbox.py b/src/devops_cli/roadmap/inbox.py new file mode 100644 index 0000000000..d3e1d66c96 --- /dev/null +++ b/src/devops_cli/roadmap/inbox.py @@ -0,0 +1,282 @@ +"""The inbox: what waits for a person on the roadmap (#2915). + +`read_inbox` reads the open issues, the open pull requests, the labels of the repository and +`.github/labels.yml`, and returns the lines that a person must clear, with the number, the age and +the one step that clears each. It writes nothing and calls no model. It never reads every issue: +a closed item holds no `status/*` and no `owner/*` label (`clear-status.yml`), so the open ones +are enough. + +**The jobs' lines**, in the order of the gates (docs/ROADMAP_WORKFLOW.md): ready plan pull +requests (G1), ready implementation pull requests (G2), the release pull request (G3), items in +`status/blocked` with their cause, old claims, and labels that the repository lacks. A pull +request is a job's when the job record of an open item names it: `implement.pr` makes it an +implementation, `stage.pr` a plan, and `implement.pr` wins because a staged branch keeps one pull +request through both jobs. A draft of a job waits for its checks, so it is not listed, and a pull +request that a runner Job holds is not listed: the Job pushes to it. The release pull request is +the open one whose head branch starts with the prefix of release-please. + +**The people's lines** are every other open pull request, so a person's own pull requests are +apart from the jobs'. A draft is marked as a draft. + +**Age.** The time since the last update of the pull request or the issue. For a claim it is the +time since the newest update of the issue and of each open pull request on a branch that names +the issue (`/-`). The inbox shows an old claim and never removes it. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta +from enum import StrEnum + +from devops_cli.config.constants import ( + CONST_ROADMAP_IMPLEMENT_RETRY_COMMENT, + CONST_ROADMAP_INBOX_CLAIM_DAYS, + CONST_ROADMAP_INBOX_LABEL_NAMES, + CONST_ROADMAP_LABELS_PATH, + CONST_ROADMAP_RELEASE_BRANCH_PREFIX, + CONST_ROADMAP_STATUS_BLOCKED, +) +from devops_cli.git.branch_form import issue_of_branch +from devops_cli.github.labels import diff_labels +from devops_cli.lang import MESSAGES +from devops_cli.output import format_duration +from devops_cli.roadmap.pull_labels import declared_specs +from devops_cli.roadmap.status_sync import job_holds +from devops_cli.roadmap.store import ( + ImplementRecordKey, + Item, + OpenPull, + RefineRecordKey, + RoadmapStore, + StageRecordKey, +) + + +class InboxKind(StrEnum): + """What a line of the inbox is. The members are in the order the inbox lists them.""" + + PLAN = "plan" + IMPLEMENT = "implement" + RELEASE = "release" + BLOCKED = "blocked" + CLAIM = "claim" + LABELS = "labels" + PERSON = "person" + + +@dataclass(frozen=True) +class InboxLine: + """One thing that waits for a person: what it is, the number of its issue or pull request + (None when it has none), the time since its last update (None when GitHub gave none), what + it is about, and the one command or action that clears it.""" + + kind: InboxKind + number: int | None + age: timedelta | None + subject: str + clear: str + + +@dataclass(frozen=True) +class Inbox: + """The lines of the jobs and the repository, in the order of the gates, and the lines of the + pull requests of people and agents. Within a kind the oldest line comes first.""" + + jobs: tuple[InboxLine, ...] + people: tuple[InboxLine, ...] + + +def _recorded_number(text: str | None) -> int | None: + return int(text) if text is not None and text.isdecimal() else None + + +def _named_pulls(items: Iterable[Item]) -> dict[int, InboxKind | None]: + """The pull requests that the job record of an item names, by number: the kind they have as + a job's, or None when a runner Job holds the item. A stage pull request is a plan, and an + implement pull request is an implementation and wins for the same number.""" + named: dict[int, InboxKind | None] = {} + for item in items: + held = job_holds(item) + for key, kind in ( + (StageRecordKey.PR, InboxKind.PLAN), + (ImplementRecordKey.PR, InboxKind.IMPLEMENT), + ): + number = _recorded_number(item.job_record.get(key)) + if number is not None: + named[number] = None if held else kind + return named + + +def _pull_kind(pull: OpenPull, named: Mapping[int, InboxKind | None]) -> InboxKind | None: + """The kind of the line of `pull`, or None when no person must act on it now: a draft of a + job or the release, or a pull request that a runner Job holds.""" + if pull.head_ref.startswith(CONST_ROADMAP_RELEASE_BRANCH_PREFIX): + kind: InboxKind | None = InboxKind.RELEASE + elif pull.number in named: + kind = named[pull.number] + else: + return InboxKind.PERSON + return None if pull.draft else kind + + +def _age(now: datetime, moment: datetime | None) -> timedelta | None: + return None if moment is None else now - moment + + +def _pull_line(pull: OpenPull, kind: InboxKind, repo: str, now: datetime) -> InboxLine: + texts = MESSAGES.roadmap + clear_key = kind.value + if kind is InboxKind.PERSON: + clear_key = "person_draft" if pull.draft else "person_ready" + subject = texts.inbox_subjects["draft" if pull.draft else "pull"].format(title=pull.title) + clear = texts.inbox_clears[clear_key].format(url=pull.url, number=pull.number, repo=repo) + return InboxLine(kind, pull.number, _age(now, pull.updated_at), subject, clear) + + +def _pull_lines( + pulls: Iterable[OpenPull], named: Mapping[int, InboxKind | None], repo: str, now: datetime +) -> list[InboxLine]: + lines: list[InboxLine] = [] + for pull in pulls: + kind = _pull_kind(pull, named) + if kind is not None: + lines.append(_pull_line(pull, kind, repo, now)) + return lines + + +def _blocked_line(item: Item, repo: str, now: datetime) -> InboxLine: + """The line of a blocked item with its cause: the step that stopped it, else the items that + refine says it waits for, else the words that no cause is recorded.""" + texts = MESSAGES.roadmap + subjects, clears = texts.inbox_subjects, texts.inbox_clears + stopped = item.job_record.get(ImplementRecordKey.STOPPED) + blockers = item.job_record.get(RefineRecordKey.BLOCKED_BY) + if stopped: + subject = subjects["stopped"].format(title=item.title, step=stopped) + clear = clears["stopped"].format( + retry=CONST_ROADMAP_IMPLEMENT_RETRY_COMMENT, number=item.number + ) + else: + key = "blocked_by" if blockers else "no_cause" + subject = subjects[key].format(title=item.title, blockers=blockers) + clear = clears["blocked"].format(number=item.number, repo=repo) + return InboxLine(InboxKind.BLOCKED, item.number, _age(now, item.updated_at), subject, clear) + + +def _blocked_lines(items: Iterable[Item], repo: str, now: datetime) -> list[InboxLine]: + return [ + _blocked_line(item, repo, now) + for item in items + if item.status == CONST_ROADMAP_STATUS_BLOCKED + ] + + +def _activity(item: Item, pulls: Sequence[OpenPull]) -> datetime | None: + """The newest update of the issue of `item` and of each open pull request on a branch that + names the issue.""" + moments = [item.updated_at] + moments += [pull.updated_at for pull in pulls if issue_of_branch(pull.head_ref) == item.number] + return max((moment for moment in moments if moment is not None), default=None) + + +def _claim_lines( + items: Iterable[Item], pulls: Sequence[OpenPull], repo: str, now: datetime +) -> list[InboxLine]: + texts = MESSAGES.roadmap + limit = timedelta(days=CONST_ROADMAP_INBOX_CLAIM_DAYS) + lines: list[InboxLine] = [] + for item in items: + age = _age(now, _activity(item, pulls)) + if item.owner is None or (age is not None and age <= limit): + continue + subject = texts.inbox_subjects["claim"].format(title=item.title, owner=item.owner.lower()) + clear = texts.inbox_clears["claim"].format(number=item.number, repo=repo) + lines.append(InboxLine(InboxKind.CLAIM, item.number, age, subject, clear)) + return lines + + +def _label_names(names: Sequence[str]) -> str: + shown = ", ".join(names[:CONST_ROADMAP_INBOX_LABEL_NAMES]) + more = len(names) - CONST_ROADMAP_INBOX_LABEL_NAMES + if more <= 0: + return shown + return MESSAGES.roadmap.inbox_subjects["more_labels"].format(names=shown, more=more) + + +def _label_lines(store: RoadmapStore, repo: str, now: datetime) -> list[InboxLine]: + """One line for the labels of `.github/labels.yml` that the repository lacks or holds with + another color or description. Its age is the time since the file last changed, which is a + lower bound on how long the repository has been behind; the commit is read only then.""" + texts = MESSAGES.roadmap + existing = [label.model_dump() for label in store.repository_labels()] + to_create, to_update, _ = diff_labels(declared_specs(store, ref=None), existing) + names = [spec.name for spec in (*to_create, *to_update)] + if not names: + return [] + subject = texts.inbox_subjects["labels"].format( + count=len(names), path=CONST_ROADMAP_LABELS_PATH, names=_label_names(names) + ) + age = _age(now, store.path_changed_at(CONST_ROADMAP_LABELS_PATH)) + clear = texts.inbox_clears["labels"].format(repo=repo) + return [InboxLine(InboxKind.LABELS, None, age, subject, clear)] + + +def _order(line: InboxLine) -> tuple[int, bool, float]: + """Kind order, then the oldest first, a line with no age last.""" + seconds = line.age.total_seconds() if line.age is not None else 0.0 + return (list(InboxKind).index(line.kind), line.age is None, -seconds) + + +def read_inbox(store: RoadmapStore, *, repo: str, now: datetime) -> Inbox: + """What waits for a person in `repo` at `now`. It reads the open items, the open pull + requests, the labels and the labels file, and the newest commit of that file when the labels + differ, and writes nothing. A read that fails raises its error, and the labels file of a + repository that has none fails the read.""" + items = store.open_items() + pulls = store.open_pulls() + lines = [ + *_pull_lines(pulls, _named_pulls(items), repo, now), + *_blocked_lines(items, repo, now), + *_claim_lines(items, pulls, repo, now), + *_label_lines(store, repo, now), + ] + ordered = sorted(lines, key=_order) + return Inbox( + jobs=tuple(line for line in ordered if line.kind is not InboxKind.PERSON), + people=tuple(line for line in ordered if line.kind is InboxKind.PERSON), + ) + + +def _render_line(line: InboxLine) -> str: + texts = MESSAGES.roadmap + number = texts.inbox_no_number if line.number is None else f"#{line.number}" + age = texts.inbox_no_age if line.age is None else format_duration(line.age.total_seconds()) + head = texts.inbox_line.format(number=number, age=age, subject=line.subject) + return f"{head}\n{texts.inbox_clear.format(clear=line.clear)}" + + +def _render_section(kind: InboxKind, lines: Sequence[InboxLine]) -> str: + heading = MESSAGES.roadmap.inbox_headings[kind.value].format( + days=CONST_ROADMAP_INBOX_CLAIM_DAYS + ) + return "\n".join([heading, *(_render_line(line) for line in lines)]) + + +def render_inbox(inbox: Inbox, *, repo: str) -> str: + """The inbox as the report of the command: a section for each kind that has a line, the + jobs' sections first, then the people's, and the note on what the inbox leaves out.""" + texts = MESSAGES.roadmap + lines = (*inbox.jobs, *inbox.people) + if not lines: + return f"{texts.inbox_empty.format(repo=repo)}\n\n{texts.inbox_footer}" + sections = [ + _render_section(kind, [line for line in lines if line.kind is kind]) + for kind in InboxKind + if any(line.kind is kind for line in lines) + ] + return "\n\n".join([texts.inbox_title.format(repo=repo), *sections, texts.inbox_footer]) + + +__all__ = ["Inbox", "InboxKind", "InboxLine", "read_inbox", "render_inbox"] diff --git a/src/devops_cli/roadmap/memory_store.py b/src/devops_cli/roadmap/memory_store.py index 7a271b8f3c..60baccba96 100644 --- a/src/devops_cli/roadmap/memory_store.py +++ b/src/devops_cli/roadmap/memory_store.py @@ -1,7 +1,8 @@ """The in-memory roadmap store: the roadmap held in process, with no I/O, for tests. It keeps the promises the GitHub adapter keeps, so the contract suite runs against it. A test -seeds milestones with `seed_milestone` and issues with `seed_issue`, and acts as a person with +seeds milestones with `seed_milestone`, issues with `seed_issue`, pull requests with `seed_pull` +and labels with `seed_label`, and acts as a person with `as_actor`: a person's writes change labels and record changes under their name, but never touch the job record. Each issue keeps its body as GitHub does, the record block included, and every read takes the block out with the same rules as the GitHub adapter. @@ -45,7 +46,9 @@ Item, ItemField, Milestone, + OpenPull, RepositoryFacts, + RepositoryLabel, RoadmapStore, already_closed, as_utc, @@ -102,6 +105,9 @@ class _Roadmap: is_private: bool = False # The repositories `seed_repository` made, by full name. repositories: dict[str, RepositoryFacts] = field(default_factory=dict) + # The head branch and draft state of each pull request `seed_pull` made, by number. + pulls: dict[int, tuple[str, bool]] = field(default_factory=dict) + labels: list[RepositoryLabel] = field(default_factory=list) class InMemoryRoadmapStore(RoadmapStore): @@ -164,6 +170,7 @@ def seed_issue( author_association: str | None = DEFAULT_ROADMAP_MEMORY_AUTHOR_ASSOCIATION, sub_issues: int = 0, parent: int | None = None, + updated_at: datetime | None = None, ) -> int: """Open an issue (or a pull request) as GitHub would, returning its number. @@ -173,7 +180,8 @@ def seed_issue( the repository, the owner's unless given, since GitHub gives one for every issue. `sub_issues` is how many sub-issues GitHub records for it, and `parent` is the issue that has it as a sub-issue. The issue is created now by the store's clock, and closed - now when seeded closed. `body` is kept as given, so a test can seed a record block. + now when seeded closed, and last changed at `updated_at` when that is given. `body` is + kept as given, so a test can seed a record block. """ if milestone is not None: require_milestone(self._roadmap.milestones.values(), milestone, "roadmap.issue.seed") @@ -194,13 +202,34 @@ def seed_issue( pull_request=pull_request, author_association=author_association, created_at=now, - updated_at=now, + updated_at=as_utc(updated_at) if updated_at is not None else now, closed_at=now if state is GitHubState.CLOSED else None, sub_issues=sub_issues, parent=parent, ) return number + def seed_pull( + self, + title: str, + *, + head_ref: str, + draft: bool = False, + state: GitHubState = GitHubState.OPEN, + updated_at: datetime | None = None, + ) -> int: + """Open a pull request on the branch `head_ref`, a draft when `draft`, returning its + number. It is an issue that is a pull request, so it shares the numbers of the issues.""" + number = self.seed_issue(title, state=state, pull_request=True, updated_at=updated_at) + self._roadmap.pulls[number] = (head_ref, draft) + return number + + def seed_label(self, name: str, color: str, description: str = "") -> None: + """Add a label to the repository, as a person does on GitHub.""" + self._roadmap.labels.append( + RepositoryLabel(name=name, color=color, description=description) + ) + def seed_file(self, path: str, text: str, *, ref: str | None = None) -> None: """Commit `text` at `path` on `ref`, or on the default branch when `ref` is None.""" self._roadmap.files[(path, ref)] = text @@ -448,6 +477,34 @@ def backlog(self) -> list[Item]: if item.state is GitHubState.OPEN and item.milestone is None ] + def open_items(self) -> list[Item]: + """The open Items.""" + issues = (self._read(issue) for issue in self._roadmap.issues.values()) + return select_items(issue for issue in issues if issue.state is GitHubState.OPEN) + + def open_pulls(self) -> list[OpenPull]: + """The open pull requests that `seed_pull` made.""" + pulls = ( + (self._roadmap.issues[number], head_ref, draft) + for number, (head_ref, draft) in self._roadmap.pulls.items() + ) + return [ + OpenPull( + number=issue.number, + title=issue.title, + url=issue.url, + head_ref=head_ref, + draft=draft, + updated_at=issue.updated_at or self._roadmap.clock(), + ) + for issue, head_ref, draft in pulls + if issue.state is GitHubState.OPEN + ] + + def repository_labels(self) -> list[RepositoryLabel]: + """The labels that `seed_label` made.""" + return list(self._roadmap.labels) + def candidates(self) -> list[Candidate]: """The open issues of the repository that hold no Priority.""" return select_candidates(self._read(issue) for issue in self._roadmap.issues.values()) diff --git a/src/devops_cli/roadmap/pull_labels.py b/src/devops_cli/roadmap/pull_labels.py index ef1c440514..cd5fe6deac 100644 --- a/src/devops_cli/roadmap/pull_labels.py +++ b/src/devops_cli/roadmap/pull_labels.py @@ -13,18 +13,19 @@ from devops_cli.config.constants import CONST_ROADMAP_LABELS_PATH from devops_cli.exceptions.git import GitHubOperationError +from devops_cli.github.labels import LabelSpec from devops_cli.lang import MESSAGES from devops_cli.roadmap import store as roadmap_store -from devops_cli.roadmap.title_labels import TitleLabels, declared_label_names, title_labels +from devops_cli.roadmap.title_labels import TitleLabels, declared_label_specs, title_labels -def declared_labels(store: roadmap_store.RoadmapStore, *, ref: str | None) -> tuple[str, ...]: - """The names of the labels that `.github/labels.yml` declares in the repository of `store` on - `ref` (the default branch when None). A file that is missing, or is no list of label specs, or - a read that fails, raises `GitHubOperationError` that names the file.""" +def declared_specs(store: roadmap_store.RoadmapStore, *, ref: str | None) -> list[LabelSpec]: + """The labels that `.github/labels.yml` declares in the repository of `store` on `ref` (the + default branch when None). A file that is missing, or is no list of label specs, or a read + that fails, raises `GitHubOperationError` that names the file.""" text = store.repository_file(CONST_ROADMAP_LABELS_PATH, ref=ref) try: - return declared_label_names(text) + return declared_label_specs(text) except (yaml.YAMLError, ValidationError) as exc: raise GitHubOperationError( MESSAGES.pr.labels_unreadable.format( @@ -35,6 +36,12 @@ def declared_labels(store: roadmap_store.RoadmapStore, *, ref: str | None) -> tu ) from exc +def declared_labels(store: roadmap_store.RoadmapStore, *, ref: str | None) -> tuple[str, ...]: + """The names of the labels that `.github/labels.yml` declares, with the errors of + `declared_specs`.""" + return tuple(spec.name for spec in declared_specs(store, ref=ref)) + + def read_title_labels(repo: str, title: str, *, ref: str | None) -> TitleLabels: """The labels that `title` gives, checked against `.github/labels.yml` of `repo` on `ref` (the default branch when None). A file that is missing, or is no list of label specs, or a read that diff --git a/src/devops_cli/roadmap/request_plan.py b/src/devops_cli/roadmap/request_plan.py index 0fe14fd3ac..5efeb36b80 100644 --- a/src/devops_cli/roadmap/request_plan.py +++ b/src/devops_cli/roadmap/request_plan.py @@ -24,6 +24,7 @@ from devops_cli.config.constants import ( CONST_ROADMAP_ALTERNATIVES_MAX_FACT_READS, CONST_ROADMAP_ALTERNATIVES_MAX_SEARCHES, + CONST_ROADMAP_LABELS_PATH, CONST_URL_GITHUB_API_BASE, ) from devops_cli.config.defaults import DEFAULT_FIRECRAWL_SEARCH_URL, DEFAULT_PYPI_PACKAGE_URL @@ -161,6 +162,18 @@ def items(self, *, milestone: str | None = None) -> Requests: def backlog(self) -> Requests: return self._issues("milestone=none&state=open") + def open_items(self) -> Requests: + """The listing of the open issues, which `open_items` reads (#2915).""" + return self._issues("state=open") + + def open_pulls(self) -> Requests: + """The listing of the open pull requests (#2915).""" + return self.listing(gh.pulls_endpoint(self.repo), "open_pulls") + + def repository_labels(self) -> Requests: + """The listing of the labels of the repository (#2915).""" + return self.listing(gh.labels_endpoint(self.repo), "repository_labels") + def candidates(self) -> Requests: return self.every_issue() @@ -703,6 +716,25 @@ def explain_requests( return (*reads, *blockers), () +def inbox_requests( + repo: str, +) -> tuple[tuple[PlannedRequest, ...], tuple[PlannedRequest, ...]]: + """What `devops roadmap inbox` reads, in order (#2915). It reads the open issues, the open + pull requests, the labels of the repository and `.github/labels.yml` on the default branch, + and the newest commit that changed that file only when the labels differ. It reads the + listing of every issue never, makes no write and calls no model.""" + store = StoreRequests(repo) + differ = MESSAGES.roadmap.plan_conditions["labels_differ"] + reads = [ + *store.open_items(), + *store.open_pulls(), + *store.repository_labels(), + *store.file(CONST_ROADMAP_LABELS_PATH, None), + *within(store.path_change(CONST_ROADMAP_LABELS_PATH), differ), + ] + return tuple(reads), () + + def render_dry_run( job: str, repo: str, @@ -728,6 +760,7 @@ def render_dry_run( "alternatives_requests", "explain_requests", "implement_requests", + "inbox_requests", "is_page_repeat", "milestones_close_requests", "milestones_edit_requests", diff --git a/src/devops_cli/roadmap/store.py b/src/devops_cli/roadmap/store.py index 7ee3edefba..85945f580b 100644 --- a/src/devops_cli/roadmap/store.py +++ b/src/devops_cli/roadmap/store.py @@ -253,7 +253,8 @@ class Item(BaseModel): judge an Item by its text without a read of each issue. `author_association` is the author's relation to the repository, as on `IssueRecord`: a refine round refines only an Item that the owner, a member or a collaborator opened (#2478). `sub_issues` is how many - sub-issues the issue has, as on `IssueRecord`: an Item with some is a tracker. + sub-issues the issue has, as on `IssueRecord`: an Item with some is a tracker. `updated_at` is + when the issue last changed, as on `IssueRecord`. """ model_config = ConfigDict(frozen=True) @@ -268,6 +269,7 @@ class Item(BaseModel): milestone: str | None = None author_association: str | None = None sub_issues: int = 0 + updated_at: datetime | None = None status: str | None = None priority: str | None = None value: str | None = None @@ -379,6 +381,32 @@ class RepositoryFacts(BaseModel): released_at: datetime | None = None +class OpenPull(BaseModel): + """An open pull request of this repository, as the pull request listing gives it (#2915): + its branch, whether it is a draft, and when it last changed. A push, a comment and a label + each move `updated_at`.""" + + model_config = ConfigDict(frozen=True) + + number: int + title: str + url: str + head_ref: str + draft: bool = False + updated_at: datetime + + +class RepositoryLabel(BaseModel): + """A label that the repository holds on GitHub: its name, color and description (#2915). A + label with no description has an empty one.""" + + model_config = ConfigDict(frozen=True) + + name: str + color: str = "" + description: str = "" + + class Evidence(BaseModel): """A piece of evidence for a P0: its kind and the value that names it.""" @@ -702,6 +730,16 @@ def items(self, *, milestone: int | None = None) -> list[Item]: def backlog(self) -> list[Item]: """The open Items in no milestone.""" + def open_items(self) -> list[Item]: + """The open Items, in every milestone or none. It reads the open issues only, so its cost + does not grow with the closed ones (#2915).""" + + def open_pulls(self) -> list[OpenPull]: + """The open pull requests, with their branches and draft state (#2915).""" + + def repository_labels(self) -> list[RepositoryLabel]: + """The labels the repository holds on GitHub (#2915).""" + def candidates(self) -> list[Candidate]: """The open issues of the repository that hold no Priority.""" diff --git a/src/devops_cli/roadmap/title_labels.py b/src/devops_cli/roadmap/title_labels.py index fed2bdb4d1..5912da2af8 100644 --- a/src/devops_cli/roadmap/title_labels.py +++ b/src/devops_cli/roadmap/title_labels.py @@ -39,11 +39,16 @@ def labels(self) -> tuple[str, ...]: return tuple(label for label in (self.type_label, self.scope_label) if label) +def declared_label_specs(text: str) -> list[LabelSpec]: + """The labels that the text of `.github/labels.yml` declares. Text that is not YAML raises + `yaml.YAMLError`, and YAML that is no list of label specs raises `pydantic.ValidationError`.""" + return _LABEL_SPECS.validate_python(yaml.safe_load(text)) + + def declared_label_names(text: str) -> tuple[str, ...]: - """The names of the labels that the text of `.github/labels.yml` declares. Text that is not - YAML raises `yaml.YAMLError`, and YAML that is no list of label specs raises - `pydantic.ValidationError`.""" - return tuple(spec.name for spec in _LABEL_SPECS.validate_python(yaml.safe_load(text))) + """The names of the labels that the text of `.github/labels.yml` declares, with the errors of + `declared_label_specs`.""" + return tuple(spec.name for spec in declared_label_specs(text)) def requested_labels(title: str) -> tuple[str | None, str | None]: diff --git a/tests/ai/mcp/test_mcp.py b/tests/ai/mcp/test_mcp.py index e869453853..e39b71ea5c 100644 --- a/tests/ai/mcp/test_mcp.py +++ b/tests/ai/mcp/test_mcp.py @@ -591,6 +591,7 @@ def test_all_cli_commands_are_either_exposed_or_excluded() -> None: ("roadmap", "claim"), ("roadmap", "explain"), ("roadmap", "implement"), + ("roadmap", "inbox"), ("roadmap", "intake-eval"), ("roadmap", "release"), ("roadmap", "return"), diff --git a/tests/roadmap/test_roadmap_inbox.py b/tests/roadmap/test_roadmap_inbox.py new file mode 100644 index 0000000000..d62c0b058c --- /dev/null +++ b/tests/roadmap/test_roadmap_inbox.py @@ -0,0 +1,310 @@ +"""`read_inbox` (#2915): what waits for a person, in the order of the gates, each line with its +number, its age and the one step that clears it. A fake repository holds the issues, the pull +requests and the labels; no request leaves the process.""" + +from __future__ import annotations + +from collections.abc import Mapping +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest + +from devops_cli.config.constants import CONST_ROADMAP_LABELS_PATH +from devops_cli.exceptions.git import GitHubFileNotFoundError +from devops_cli.roadmap.inbox import Inbox, InboxKind, InboxLine, read_inbox, render_inbox +from devops_cli.roadmap.memory_store import InMemoryRoadmapStore +from devops_cli.roadmap.store import ( + GitHubState, + ImplementRecordKey, + ItemField, + RefineRecordKey, + StageRecordKey, + encode_job_record, + with_record, +) + +REPO = "example/roadmap" +NOW = datetime(2026, 11, 1, 12, 0, tzinfo=UTC) +LABELS = "- name: type/bug\n color: D73A4A\n description: A defect\n" + + +def _ago(**span: float) -> datetime: + return NOW - timedelta(**span) + + +@pytest.fixture +def store() -> InMemoryRoadmapStore: + made = InMemoryRoadmapStore(repo=REPO, clock=lambda: NOW) + made.seed_file(CONST_ROADMAP_LABELS_PATH, LABELS) + made.seed_label("type/bug", "D73A4A", "A defect") + return made + + +def _item( + store: InMemoryRoadmapStore, + title: str = "work", + *, + marks: Mapping[Any, str | None] | None = None, + fields: Mapping[ItemField, str] | None = None, + updated_at: datetime | None = None, + state: GitHubState = GitHubState.OPEN, +) -> int: + """An item of the roadmap whose job record holds `marks`.""" + block = encode_job_record({}, marks or {}) if marks else None + return store.seed_issue( + title, + body=with_record("", block), + fields={ItemField.PRIORITY: "P2-Medium", **(fields or {})}, + updated_at=updated_at, + state=state, + ) + + +def _lines(inbox: Inbox, kind: InboxKind) -> list[InboxLine]: + return [line for line in (*inbox.jobs, *inbox.people) if line.kind is kind] + + +def _read(store: InMemoryRoadmapStore) -> Inbox: + return read_inbox(store, repo=REPO, now=NOW) + + +def test_every_category_is_listed_once_in_the_order_of_the_gates( + store: InMemoryRoadmapStore, +) -> None: + plan = store.seed_pull("plan", head_ref="feat/1-plan", updated_at=_ago(days=2)) + _item(store, marks={StageRecordKey.PR: str(plan)}) + work = store.seed_pull("work", head_ref="feat/2-work", updated_at=_ago(days=1)) + _item(store, marks={ImplementRecordKey.PR: str(work)}) + release = store.seed_pull( + "release", + head_ref="release-please--branches--main--components--x", + updated_at=_ago(hours=3), + ) + blocked = _item( + store, fields={ItemField.STATUS: "Blocked"}, marks={ImplementRecordKey.STOPPED: "group 2"} + ) + claimed = _item(store, fields={ItemField.OWNER: "Agent"}, updated_at=_ago(days=9)) + store.seed_file(CONST_ROADMAP_LABELS_PATH, LABELS + "- name: scope/ci\n color: 0E8A16\n") + + inbox = _read(store) + + assert [(line.kind, line.number) for line in inbox.jobs] == [ + (InboxKind.PLAN, plan), + (InboxKind.IMPLEMENT, work), + (InboxKind.RELEASE, release), + (InboxKind.BLOCKED, blocked), + (InboxKind.CLAIM, claimed), + (InboxKind.LABELS, None), + ] + assert inbox.people == () + + +def test_a_draft_of_a_job_is_not_listed_and_is_not_a_persons_pull_request( + store: InMemoryRoadmapStore, +) -> None: + draft = store.seed_pull("plan", head_ref="feat/1-plan", draft=True) + _item(store, marks={StageRecordKey.PR: str(draft)}) + inbox = _read(store) + assert (inbox.jobs, inbox.people) == ((), ()) + + +def test_one_pull_request_of_the_stage_and_the_implement_job_is_an_implementation( + store: InMemoryRoadmapStore, +) -> None: + shared = store.seed_pull("one pull request", head_ref="feat/1-work") + _item(store, marks={StageRecordKey.PR: str(shared), ImplementRecordKey.PR: str(shared)}) + inbox = _read(store) + assert [(line.kind, line.number) for line in inbox.jobs] == [(InboxKind.IMPLEMENT, shared)] + + +def test_a_pull_request_that_a_runner_job_holds_is_not_listed( + store: InMemoryRoadmapStore, +) -> None: + held = store.seed_pull("pushed to", head_ref="feat/1-work") + _item(store, marks={StageRecordKey.PR: str(held), ImplementRecordKey.JOB: "runner-abc"}) + inbox = _read(store) + assert (inbox.jobs, inbox.people) == ((), ()) + + +def test_a_job_pull_request_of_a_closed_item_is_a_persons(store: InMemoryRoadmapStore) -> None: + """The record of a closed item names a pull request that is open again or never merged; it + is no job's work in progress, so it is listed as any other pull request.""" + stray = store.seed_pull("stray", head_ref="feat/1-work") + _item(store, marks={ImplementRecordKey.PR: str(stray)}, state=GitHubState.CLOSED) + inbox = _read(store) + assert ([line.number for line in inbox.people], inbox.jobs) == ([stray], ()) + + +def test_each_line_has_its_number_its_age_and_the_step_that_clears_it( + store: InMemoryRoadmapStore, +) -> None: + plan = store.seed_pull("plan", head_ref="feat/1-plan", updated_at=_ago(days=2, hours=3)) + _item(store, marks={StageRecordKey.PR: str(plan)}) + work = store.seed_pull("work", head_ref="feat/2-work") + _item(store, marks={ImplementRecordKey.PR: str(work)}) + release = store.seed_pull("release", head_ref="release-please--branches--main") + claimed = _item(store, fields={ItemField.OWNER: "Human"}, updated_at=_ago(days=8)) + store.seed_file(CONST_ROADMAP_LABELS_PATH, LABELS + "- name: scope/ci\n color: 0E8A16\n") + + inbox = _read(store) + clears = {line.kind: line.clear for line in inbox.jobs} + + assert inbox.jobs[0].age == timedelta(days=2, hours=3) + assert clears[InboxKind.PLAN] == f"Review it, then merge it (G1): {_url(plan)}" + assert clears[InboxKind.IMPLEMENT] == f"Review it, then merge it (G2): {_url(work)}" + assert clears[InboxKind.RELEASE] == f"Review it, then merge it (G3): {_url(release)}" + assert clears[InboxKind.CLAIM] == f"devops roadmap release {claimed} --repo {REPO} --confirm" + assert clears[InboxKind.LABELS] == f"devops gh labels sync --repo {REPO}" + + +def _url(number: int) -> str: + return f"https://github.com/{REPO}/pull/{number}" + + +def test_a_stopped_item_shows_its_step_and_is_cleared_by_the_retry_comment( + store: InMemoryRoadmapStore, +) -> None: + number = _item( + store, fields={ItemField.STATUS: "Blocked"}, marks={ImplementRecordKey.STOPPED: "group 2"} + ) + (line,) = _lines(_read(store), InboxKind.BLOCKED) + assert (line.number, "group 2" in line.subject, line.clear) == ( + number, + True, + f"Fix the cause, then comment `implement: retry` on #{number}.", + ) + + +def test_a_block_a_person_set_says_that_no_cause_is_recorded( + store: InMemoryRoadmapStore, +) -> None: + number = _item(store, fields={ItemField.STATUS: "Blocked"}) + (line,) = _lines(_read(store), InboxKind.BLOCKED) + assert ("no cause is recorded" in line.subject, number in {line.number}) == (True, True) + + +def test_the_blockers_that_refine_recorded_are_the_cause_of_a_block( + store: InMemoryRoadmapStore, +) -> None: + _item( + store, fields={ItemField.STATUS: "Blocked"}, marks={RefineRecordKey.BLOCKED_BY: "#12, #13"} + ) + (line,) = _lines(_read(store), InboxKind.BLOCKED) + assert "#12, #13" in line.subject + + +def test_a_pull_request_on_the_branch_of_the_issue_keeps_a_claim_young( + store: InMemoryRoadmapStore, +) -> None: + claimed = _item(store, fields={ItemField.OWNER: "Agent"}, updated_at=_ago(days=10)) + store.seed_pull("work", head_ref=f"feat/{claimed}-work", draft=True, updated_at=_ago(days=1)) + assert _lines(_read(store), InboxKind.CLAIM) == [] + + +def test_a_claim_with_no_activity_for_eight_days_is_old_and_shows_its_age( + store: InMemoryRoadmapStore, +) -> None: + claimed = _item(store, fields={ItemField.OWNER: "Human"}, updated_at=_ago(days=8)) + _item(store, fields={ItemField.OWNER: "Service"}, updated_at=_ago(days=6, hours=23)) + (line,) = _lines(_read(store), InboxKind.CLAIM) + assert (line.number, line.age, "human" in line.subject) == (claimed, timedelta(days=8), True) + + +def test_a_pull_request_of_another_issue_does_not_keep_a_claim_young( + store: InMemoryRoadmapStore, +) -> None: + claimed = _item(store, fields={ItemField.OWNER: "Agent"}, updated_at=_ago(days=10)) + store.seed_pull("other", head_ref=f"feat/{claimed + 1}-other", updated_at=_ago(days=1)) + assert [line.number for line in _lines(_read(store), InboxKind.CLAIM)] == [claimed] + + +def test_the_pull_requests_of_people_are_listed_apart_and_a_draft_is_marked( + store: InMemoryRoadmapStore, +) -> None: + plan = store.seed_pull("plan", head_ref="feat/1-plan") + _item(store, marks={StageRecordKey.PR: str(plan)}) + ready = store.seed_pull("mine, ready", head_ref="feat/3-mine", updated_at=_ago(days=1)) + draft = store.seed_pull("mine, draft", head_ref="fix/4-mine", draft=True) + + inbox = _read(store) + + assert [(line.number, line.kind) for line in inbox.jobs] == [(plan, InboxKind.PLAN)] + assert [line.number for line in inbox.people] == [ready, draft] + assert inbox.people[0].clear == f"Review it, then merge it (G2): {_url(ready)}" + assert "draft" in inbox.people[1].subject + assert inbox.people[1].clear == ( + f"Wait for the checks with `devops pr monitor {draft} --repo {REPO}`, " + f"then run `devops pr ready {draft} --repo {REPO}`." + ) + + +def test_the_lines_of_one_kind_are_oldest_first(store: InMemoryRoadmapStore) -> None: + newer = store.seed_pull("newer", head_ref="feat/1-a", updated_at=_ago(hours=1)) + older = store.seed_pull("older", head_ref="feat/2-b", updated_at=_ago(days=3)) + _item(store, marks={StageRecordKey.PR: str(newer)}) + _item(store, marks={StageRecordKey.PR: str(older)}) + assert [line.number for line in _read(store).jobs] == [older, newer] + + +def test_labels_that_differ_are_one_line_with_the_age_of_the_labels_file( + store: InMemoryRoadmapStore, +) -> None: + store.seed_file( + CONST_ROADMAP_LABELS_PATH, + "- name: type/bug\n color: '000000'\n description: A defect\n" + "- name: scope/ci\n color: 0E8A16\n", + ) + store.seed_commit(CONST_ROADMAP_LABELS_PATH, at=_ago(days=4)) + (line,) = _lines(_read(store), InboxKind.LABELS) + assert (line.number, line.age, "scope/ci" in line.subject, "type/bug" in line.subject) == ( + None, + timedelta(days=4), + True, + True, + ) + + +def test_labels_in_step_with_the_file_give_no_line_and_no_commit_read( + store: InMemoryRoadmapStore, +) -> None: + assert _read(store) == Inbox(jobs=(), people=()) + + +def test_a_repository_without_the_labels_file_fails_the_read_and_does_not_hide_it( + store: InMemoryRoadmapStore, +) -> None: + empty = InMemoryRoadmapStore(repo=REPO, clock=lambda: NOW) + with pytest.raises(GitHubFileNotFoundError, match=r"no \.github/labels\.yml"): + _read(empty) + + +def test_the_inbox_reads_open_work_only_writes_nothing_and_never_lists_every_issue( + store: InMemoryRoadmapStore, monkeypatch: pytest.MonkeyPatch +) -> None: + calls: list[str] = [] + for name in ("issues", "items", "candidates", "backlog"): + monkeypatch.setattr(store, name, lambda *a, _n=name, **k: calls.append(_n) or []) + store.seed_pull("plan", head_ref="feat/1-plan") + _read(store) + assert (calls, store.job_writes()) == ([], []) + + +def test_the_rendered_inbox_names_each_section_with_its_lines(store: InMemoryRoadmapStore) -> None: + plan = store.seed_pull("plan", head_ref="feat/1-plan", updated_at=_ago(days=1)) + _item(store, marks={StageRecordKey.PR: str(plan)}) + store.seed_pull("mine", head_ref="feat/3-mine") + + text = render_inbox(_read(store), repo=REPO) + + assert f"#{plan}" in text + assert "Ready plan pull requests of the jobs (G1)" in text + assert "Pull requests of people and agents" in text + assert text.index("(G1)") < text.index("Pull requests of people and agents") + assert "devops argo cd apps status devops" in text + + +def test_an_empty_inbox_says_that_nothing_waits(store: InMemoryRoadmapStore) -> None: + assert render_inbox(_read(store), repo=REPO).startswith( + f"Nothing waits for a person in {REPO}." + ) diff --git a/tests/roadmap/test_roadmap_inbox_command.py b/tests/roadmap/test_roadmap_inbox_command.py new file mode 100644 index 0000000000..e647fff36e --- /dev/null +++ b/tests/roadmap/test_roadmap_inbox_command.py @@ -0,0 +1,75 @@ +"""`devops roadmap inbox`: the report, the failure, and the dry run (#2915).""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import pytest + +from devops_cli.config.constants import CONST_ROADMAP_LABELS_PATH +from devops_cli.roadmap.github_store import listing_path, pulls_endpoint +from devops_cli.roadmap.memory_store import InMemoryRoadmapStore +from devops_cli.roadmap.store import ItemField, StageRecordKey, encode_job_record, with_record +from tests.support.fakes.github import API + +REPO = "example/roadmap" + + +def _plan_pull(store: InMemoryRoadmapStore) -> int: + pull = store.seed_pull("plan", head_ref="feat/1-plan") + block = encode_job_record({}, {StageRecordKey.PR: str(pull)}) + store.seed_issue("work", body=with_record("", block), fields={ItemField.PRIORITY: "P2-Medium"}) + return pull + + +def test_the_report_lists_a_ready_plan_pull_request_with_its_step( + cli: Callable[..., Any], roadmap_store: InMemoryRoadmapStore +) -> None: + roadmap_store.seed_file(CONST_ROADMAP_LABELS_PATH, "- name: type/bug\n color: D73A4A\n") + roadmap_store.seed_label("type/bug", "D73A4A") + pull = _plan_pull(roadmap_store) + + result = cli("roadmap", "inbox", "--repo", REPO) + + assert result.exit_code == 0, result.output + assert f"#{pull}" in result.stdout + assert "Review it, then merge it (G1)" in result.stdout + assert roadmap_store.job_writes() == [] + + +def test_a_repository_without_the_labels_file_exits_1_and_says_so( + cli: Callable[..., Any], roadmap_store: InMemoryRoadmapStore +) -> None: + result = cli("roadmap", "inbox", "--repo", REPO) + assert (result.exit_code, "Could not read the inbox" in result.output) == (1, True) + assert ".github/labels.yml" in result.output + + +def test_the_dry_run_opens_no_store_and_lists_the_reads_and_no_write( + cli: Callable[..., Any], + roadmap_store: InMemoryRoadmapStore, + roadmap_store_repos: list[str], +) -> None: + result = cli("roadmap", "inbox", "--repo", REPO, "--dry-run") + + assert result.exit_code == 0, result.output + assert roadmap_store_repos == [] + assert "Dry run: no request was made" in result.output + assert f"{API}{listing_path(pulls_endpoint(REPO))}" in result.output + assert "state=all" not in result.output + assert "PATCH" not in result.output + + +@pytest.mark.parametrize("flag", ["--confirm", "--plan"]) +def test_the_inbox_takes_no_write_option(cli: Callable[..., Any], flag: str) -> None: + assert cli("roadmap", "inbox", "--repo", REPO, flag).exit_code == 2 + + +def test_the_help_states_how_many_requests_a_run_sends(cli: Callable[..., Any]) -> None: + result = cli("roadmap", "inbox", "--help") + + text = " ".join(result.output.replace("│", " ").split()) + assert result.exit_code == 0, result.output + assert "5 requests, or 6 when the labels differ" in text + assert "one more for each 100 open issues and pull requests" in text diff --git a/tests/roadmap/test_roadmap_inbox_requests.py b/tests/roadmap/test_roadmap_inbox_requests.py new file mode 100644 index 0000000000..806fa21b41 --- /dev/null +++ b/tests/roadmap/test_roadmap_inbox_requests.py @@ -0,0 +1,60 @@ +"""The reads of `devops roadmap inbox` and their plan (#2915). + +The plan lists the same listings the store reads, built by the same functions, so a dry run +cannot drift from a run. The inbox sends only reads, and never reads the listing of every issue. +""" + +from __future__ import annotations + +from devops_cli.config.constants import CONST_ROADMAP_LABELS_PATH +from devops_cli.lang import MESSAGES +from devops_cli.roadmap.github_store import ( + issues_endpoint, + labels_endpoint, + listing_path, + path_commits_args, + pulls_endpoint, +) +from devops_cli.roadmap.request_plan import StoreRequests, inbox_requests +from tests.support.fakes.github import API + +REPO = "example/roadmap" + + +def _urls(plan: tuple[object, ...] | list[object]) -> list[str]: + return [request.argv[1] for request in plan if request.argv[0] == "GET"] # type: ignore[attr-defined] + + +def test_the_plan_of_each_listing_is_the_path_the_store_reads() -> None: + store = StoreRequests(REPO) + assert ( + _urls(store.open_items()), + _urls(store.open_pulls()), + _urls(store.repository_labels()), + ) == ( + [f"{API}{listing_path(issues_endpoint(REPO, 'state=open'))}"], + [f"{API}{listing_path(pulls_endpoint(REPO))}"], + [f"{API}{listing_path(labels_endpoint(REPO))}"], + ) + + +def test_a_listing_is_read_once_and_again_for_each_page() -> None: + page = MESSAGES.roadmap.plan_repeat_page + assert [r.repeat for r in StoreRequests(REPO).open_pulls()] == [page] + + +def test_the_inbox_plan_reads_open_issues_not_every_issue_and_writes_nothing() -> None: + reads, writes = inbox_requests(REPO) + urls = _urls(reads) + assert ( + writes, + any("state=all" in url for url in urls), + any("state=open" in url and "/issues?" in url for url in urls), + ) == ((), False, True) + + +def test_the_commit_of_the_labels_file_is_read_only_when_the_labels_differ() -> None: + reads, _ = inbox_requests(REPO) + commit = ("gh", *path_commits_args(REPO, CONST_ROADMAP_LABELS_PATH)) + commits = [r for r in reads if r.argv == commit] + assert [r.condition for r in commits] == [MESSAGES.roadmap.plan_conditions["labels_differ"]] diff --git a/tests/roadmap/test_roadmap_store_contract.py b/tests/roadmap/test_roadmap_store_contract.py index a9a8993860..795a09bbb9 100644 --- a/tests/roadmap/test_roadmap_store_contract.py +++ b/tests/roadmap/test_roadmap_store_contract.py @@ -34,12 +34,14 @@ IssueComment, Item, ItemField, + OpenPull, RefineRecordKey, RepositoryFacts, + RepositoryLabel, RoadmapStore, ) from tests.roadmap_github_fake import GitHubFake -from tests.support.fakes.github import GitHubApiFake, RunnerSession, github_json +from tests.support.fakes.github import API, GitHubApiFake, RunnerSession, github_json REPO = "example/roadmap" RECORD = "