From 7dd50a108b6e166e6177620fb61f729f1bd67006 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 8 Oct 2026 13:38:14 +0000 Subject: [PATCH] fix(roadmap): the metrics job walks its own clone's release tags, and intake stops on an unusable labels.yml before any model call (#1358) --- changelog.d/1358.md | 9 + ...8-metrics-clone-and-labels-config-error.md | 59 ++++++ src/devops_cli/commands/roadmap.py | 1 + src/devops_cli/github/metrics.py | 10 +- src/devops_cli/lang/en/messages.py | 14 ++ src/devops_cli/roadmap/intake.py | 54 ++++-- src/devops_cli/roadmap/intake_requests.py | 6 +- src/devops_cli/roadmap/run.py | 29 ++- tests/roadmap_board_fake.py | 52 +++++- tests/test_github_metrics.py | 95 +++++++--- tests/test_roadmap_intake.py | 171 +++++++++++++++--- tests/test_roadmap_run.py | 142 +++++++++++---- 12 files changed, 529 insertions(+), 113 deletions(-) create mode 100644 changelog.d/1358.md create mode 100644 docs/agent/tasks/task-1358-metrics-clone-and-labels-config-error.md diff --git a/changelog.d/1358.md b/changelog.d/1358.md new file mode 100644 index 0000000000..b909048faa --- /dev/null +++ b/changelog.d/1358.md @@ -0,0 +1,9 @@ +### Fixed +- The roadmap Service's `metrics` job now clones its repository, as `close` and `refine` do, and walks the release tags of that clone. It used to run `git tag` in the pod's working directory, which is not a git repository, so every run logged `Failed to inspect git tags` and `devops_cli_project_releases_total` read 0 for every repository. A clone that can't be prepared now fails the job, as it fails `close` and `refine` (#1358). +- The `metrics` and `refine` jobs fail, naming the job and `needs_clone`, when they are run without their repository's clone, instead of reading the working directory (#1358). +- `collect_project_metrics_report(root=...)` walks the tags of the repository at `root` as given, so a clone kept under `.data/` inside a workspace checkout reports its own releases, not the checkout's. Without `root`, as in `devops gh metrics`, it still uses the working tree around the current directory (#1358). +- Intake reads `.github/labels.yml` at a run's first candidate, before any timeline read, embedding call or proposal, and a run with no candidate does not read it. A missing file, or one that declares no `type/*` label other than `type/epic`, now stops intake with a configuration error that names the repository and the file and says the file must declare the `type/*` labels intake may assign; a file that is no label specs names the repository too. Any other failed read of the file is still reported as GitHub's error (#1358). + +### Changed +- `plan_intake` and `intake_candidate` take the repository they run on (`repo`), which `devops roadmap intake` and the Service's intake job pass (#1358). +- The intake `--dry-run` request plan lists the `.github/labels.yml` read first among the candidate reads, before the timeline reads and the embedding call, with the condition that the run has a candidate; for a `--title` candidate it has no condition (#1358). diff --git a/docs/agent/tasks/task-1358-metrics-clone-and-labels-config-error.md b/docs/agent/tasks/task-1358-metrics-clone-and-labels-config-error.md new file mode 100644 index 0000000000..c43eb63bf5 --- /dev/null +++ b/docs/agent/tasks/task-1358-metrics-clone-and-labels-config-error.md @@ -0,0 +1,59 @@ +# Task: The metrics job walks its own clone's release tags, and intake stops on an unusable labels.yml before any model call (#1358) + +**Issue**: [#1358](https://github.com/dan-petty/devops-cli/issues/1358) +**Status**: Done +**Milestone**: v0.2.29 +**Priority**: priority/p2-medium +**Scope**: type/bug, scope/telemetry, scope/github + +## Description + +Two defects in the roadmap Service (`devops serve --service`). + +- **The metrics job read the pod's working directory.** The `metrics` row of `DEFAULT_DUE_TABLE` did not set `needs_clone`, and `_run_metrics_adapter` dropped the `clone_path` the executor passes, calling `collect_project_metrics_report` with no `root`. The report then walked the tags of `find_worktree_root()` from the current directory, which in the pod is `WORKDIR /home/devops`, no git repository. Every run logged `Failed to inspect git tags` (71 lines in the 3 hours before 2026-10-08 ~12:35 UTC) and `devops_cli_project_releases_total` read 0 for every repository. Locally, `find_worktree_root` climbs past a clone kept under `.data/` inside a workspace checkout and returns the outer checkout (the known limit tracked in #617), so passing the clone was not enough on its own. +- **Intake read `.github/labels.yml` late and reported a missing file as GitHub's error.** `_Run.types` turned only YAML and label-spec errors into a `ConfigurationError`; a missing file raised the store's `GitHubFileNotFoundError`, and a file with no `type/*` label passed, after which every proposal was rejected. The file was first read inside `_decide`, after the candidates' timeline reads and the embedding call. + +The change: + +- **Metrics.** The `metrics` row has `needs_clone=True`, so the job runs in the repository's clone under `/roadmap///clone`, as `close` and `refine` do; `build_stub_table`'s `metrics` row follows its `needs_clone` argument. `_run_metrics_adapter` passes its clone to `collect_project_metrics_report` as `root`. That function walks `root` as given and calls `find_worktree_root()` only when `root` is None, which keeps `devops gh metrics` unchanged. A clone that can't be prepared fails the job, as it fails `close` and `refine`. +- **No fallback to the working directory.** `_run_metrics_adapter` and `_run_refine_adapter` take their clone through `_job_clone`, which raises `GitOperationError` naming the job and `needs_clone` when the executor gives none, so a table row that runs either without a clone fails the job instead of reading the working directory. Refine's `clone_path or Path.cwd()` was the same one-line fallback in the same file. +- **Intake.** `plan_intake` and `intake_candidate` take the repository (`repo`), which `_Run` holds; the CLI passes its resolved `--repo` and the Service's intake adapter the repository the executor runs. `_Planner.decide_all` reads `self.run.types` first when the run has a candidate, before `_checked` (timeline reads) and `_embed`; a run with no candidate reads nothing more. `_Run.types` raises `ConfigurationError(details={"path": ".github/labels.yml"})` naming the repository, the file and the ref for a missing file (chained to the store's `GitHubFileNotFoundError`), for a file that declares no `type/*` label other than `type/epic`, and for a file that is no label specs. The first two say the file must declare the `type/*` labels intake may assign. Any other failed read propagates as the store raised it (`GitHubOperationError`). The texts live in `lang/en/messages.py`. +- **Dry run.** `_Steps.decisions` lists the `labels` read first, before the timeline reads and the embedding call. Over the open issues it carries the condition "the run has a candidate"; for a `--title` candidate, which always is one, it carries none. + +## Acceptance Criteria + +- [x] The `metrics` row of `DEFAULT_DUE_TABLE` has `needs_clone=True`, and `_run_metrics_adapter` passes its clone to `collect_project_metrics_report` as `root`: `test_the_metrics_job_walks_the_release_tags_of_its_own_clone` runs `run_due_jobs` with that row over the bare remote `_make_bare_remote` builds in `tmp_path`, with two `v*` tags added to it, with `gh` faked at the process edge (`GitHubFake.process` in place of `subprocess.run`, `git` passed through) and the GitHub and Cloudflare status pages through `stub_web`. The registry's `devops_cli_project_releases_total` reads 2 and the job logs no WARNING record at all, so no `Failed to inspect git tags`, no `Project metrics collection failed` and no `Failed to query`. No devops-cli name is patched. It replaces `test_metrics_job_registered_in_default_due_table_and_adapter`. +- [x] `collect_project_metrics_report(root=)` walks the tags of `` itself; only `root=None` goes through `find_worktree_root` (`test_a_given_root_is_walked_as_it_is_even_inside_another_checkout`: a clone with two tags under `.data/` inside a checkout with two other tags reports the clone's, with no warning). `test_collect_project_metrics_report` patches no reader: its releases are three dated tags in `tmp_path`, its milestones and open issues' labels `GitHubFake`'s answers. +- [x] `build_stub_table`'s `metrics` row follows `needs_clone`, and a clone that can't be prepared fails `metrics` as it fails `close` and `refine` while the stub `intake` and `reprioritize` still run (`test_checkouts_git_management` expects `failed_jobs == ("close", "refine", "metrics")`). +- [x] Given no clone, the metrics and refine adapters raise `GitOperationError` naming the job and `needs_clone`, and read nothing (`test_a_job_that_reads_the_clone_fails_without_one_rather_than_reading_the_cwd`, both jobs). +- [x] A failed collection and failed status reads stay warnings that skip that part of the run: GitHub answering a milestone the report can't count and both status pages answering 404 give the job's three WARNING records, and the job returns its `JobOutcome` (`test_a_failed_metrics_collection_or_status_read_is_logged_and_the_job_goes_on`). +- [x] `plan_intake` reads `.github/labels.yml` once, at the run's first candidate, before the timeline reads and the embedding call; a run with no candidate does not read it (`test_a_run_with_no_candidate_needs_no_labels_file`; `test_a_labels_file_it_cant_use_stops_intake_before_any_read_or_model_call` records no `closures` call and leaves `FakeModel.embedded` and `FakeModel.requests` empty). +- [x] A missing file and one with only `type/epic` raise `ConfigurationError` with `details={"path": ".github/labels.yml"}`, and the message names the repository (`example/roadmap`), the file and the rule; a file that is no label specs names the repository and the file (same test, three cases). Through the command, the error names the `--repo` repository (`test_intake_names_the_repository_whose_labels_file_declares_no_type`). +- [x] A 502 on the read raises `GitHubOperationError`, neither a `ConfigurationError` nor a `GitHubFileNotFoundError`, before any model call (`test_a_labels_read_github_fails_stays_a_github_error`, a `GitHubRoadmapStore` over `GitHubFake` whose `files` entry answers `(1, "gh: Server Error (HTTP 502)")`). +- [x] The dry run lists the `labels` read before the timeline read (`test_dry_run_makes_no_request_and_prints_the_requests_a_run_makes_in_order`), with the candidate condition over the open issues and none for a `--title` candidate (`test_a_dry_runs_labels_read_waits_for_a_candidate_unless_it_has_a_title`), and `test_a_dry_runs_requests_follow_the_order_a_run_makes_them` passes for both of its cases. +- [x] No new test reaches the network or runs helm, and each new test's call phase is under 1 s (`uv run pytest tests/test_github_metrics.py tests/test_roadmap_run.py tests/test_roadmap_intake.py --durations=0`). +- [x] `uv run devops ci` passes within its 5-minute budget. +- [x] `changelog.d/1358.md` records the change; `CHANGELOG.md` and `docs/ROADMAP.md` are untouched. +- Pending a person: ship v0.2.29 so the Service runs a release image with this fix (merge the release PR; Argo CD deploys the new `service` tag). Both checks below wait on it. +- Pending a person, for the hour after the rollout: the Loki query `sum(count_over_time({namespace="devops"} |= "Failed to inspect git tags" [1h]))` returns nothing (baseline: 71 lines in the 3 hours before 2026-10-08 ~12:35 UTC). +- Pending a person, after the rollout: `kubectl -n devops exec deploy/roadmap-service -- sh -c 'ls -d /home/devops/.data/roadmap/*/*/clone'` prints one line for each repository in `service.repos`. + +## Decisions and deviations + +- **One pull request closes #1358**, carrying both the metrics and the intake criteria. The issue's option of two pull requests, the first without a closing keyword, is dropped: each item PR closes exactly one issue and changes its task file. +- **The run carries its repository.** `plan_intake` and `intake_candidate` take `repo` as a required keyword, as `plan_migration` does, rather than reading it from the store; the `RoadmapStore` protocol is unchanged. Every error `.github/labels.yml` causes names it, in the Service as on the command line. +- **Live check (c) is skipped:** all eight repositories the Service manages have `.github/labels.yml` with nine `type/*` labels (contents API, 2026-10-08), so none can show the error. Defect 2 is latent there; the fix keeps intake failing closed for the next repository onboarded without the file. +- **Failing closed on the reads stays with #974.** A clone that can't be prepared, or a row that gives none, now fails the metrics job, while a failed tag read, a REST read that warns and drops, a failed collection and a failed status read keep their warnings; the status probes' try blocks are unchanged. Making those reads fail closed, and a `repo` label on every project instrument, are the extensions the issue proposes for #974. +- **The clone check reuses `test_checkouts_git_management`** rather than a near-duplicate test: its failure half already sends the milestones webhook that makes `reprioritize` due, so a `metrics` stub there is the whole check. +- **The metrics run test asserts no WARNING record at all**, which also shows the process-edge fake answered every `gh` read the adapter makes; the adapter and the REST readers would otherwise swallow a missed one. The warning test drives a collection failure from the edge: a milestone whose `open_issues` is null fails the count outside the reader's own `try`. +- **The metrics run test reuses `_make_bare_remote`** and tags the commit it pushes. With only the `metrics` row in the table and no change in the round, the run looks up no current release, so `ensure_checkout` clones the default branch and checks out no release branch, before or after #1366's default-branch rule; tags don't depend on the branch. +- **`GitHubFake` is the shared `gh` fake at the process edge (#1307):** it now answers `gh api user`, `gh api rate_limit` (a full quota resetting in a minute), the repository, its Actions runs and its traffic, takes an `(exit code, output)` for a file, and `GitHubFake.process` stands in for `subprocess.run`: it answers a `gh` argv given as a list or a tuple, raises `CalledProcessError` for a failed answer under `check=True`, and passes every other program to the real one. `test_collect_project_metrics_report` used it too: it had been starting the real `gh` (five `gh api rate_limit` calls to GitHub with the test token). +- **The existing label-spec error text moved to `lang/en/messages.py`** with the two new ones, as all three are raised by the same property, and now names the repository as well. + +## Deliverables + +- [x] `src/devops_cli/roadmap/run.py`: the `metrics` rows need a clone; the metrics and refine adapters fail without one; the intake adapter passes its repository. +- [x] `src/devops_cli/github/metrics.py`: `collect_project_metrics_report` walks `root` as given. +- [x] `src/devops_cli/roadmap/intake.py`, `src/devops_cli/roadmap/intake_requests.py`, `src/devops_cli/commands/roadmap.py`, `src/devops_cli/lang/en/messages.py`: the run's repository, the early labels read, its configuration errors, and the dry-run step order and condition. +- [x] Tests: `tests/roadmap_board_fake.py`, `tests/test_roadmap_run.py`, `tests/test_github_metrics.py`, `tests/test_roadmap_intake.py`. +- [x] Changelog fragment: `changelog.d/1358.md`. diff --git a/src/devops_cli/commands/roadmap.py b/src/devops_cli/commands/roadmap.py index 659e8ce521..a9788ba801 100644 --- a/src/devops_cli/commands/roadmap.py +++ b/src/devops_cli/commands/roadmap.py @@ -385,6 +385,7 @@ def _intake( opened.append(store) plan = plan_intake( store, + repo=target, config=config, model=meter.model(build_intake_model()), ref=ref, diff --git a/src/devops_cli/github/metrics.py b/src/devops_cli/github/metrics.py index 568c3129e9..d96046bdee 100644 --- a/src/devops_cli/github/metrics.py +++ b/src/devops_cli/github/metrics.py @@ -498,8 +498,14 @@ def collect_project_metrics_report( ci_limit: int = 50, milestone_filter: str | None = None, ) -> ProjectMetricsReport: - """Aggregate complete project metrics across releases, CI checks, and milestones.""" - project_root = find_worktree_root(root) + """Aggregate complete project metrics across releases, CI checks, and milestones. + + The releases are the `v*` tags of the git repository at `root`, taken as it is, so a clone + nested in another checkout, as the roadmap jobs keep under the data directory, reports its + own tags (#1358). Without `root` they are the tags of the working tree around the current + directory (`find_worktree_root`). + """ + project_root = root if root is not None else find_worktree_root() target_repo = repo or get_repo_origin_name(project_root) or "repository" now_str = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC") diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 02f31abd55..17b7bc11ba 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -1760,6 +1760,7 @@ class RoadmapMessages: ) intake_request_conditions: dict[str, str] = field( default_factory=lambda: { + "candidate": "the run has a candidate", "closures": "{subject} is not on the board", "embed": "a candidate is off the board", "evidence": "the model cites any", @@ -1793,6 +1794,19 @@ class RoadmapMessages: "The candidate's {part} holds what looks like a secret, so intake sent it to no model " "and filed nothing. Remove it and run again." ) + intake_labels_unreadable: str = "{repo}'s {path} can't be read as label specs: {error}" + intake_labels_missing: str = ( + "{repo} has no {path} at {ref}. Intake decides no candidate without it: the file must " + "declare the type/* labels intake may assign." + ) + intake_labels_untyped: str = ( + "{repo}'s {path} at {ref} declares no type/* label other than type/epic. Intake decides " + "no candidate without one: the file must declare the type/* labels intake may assign." + ) + run_job_needs_clone: str = ( + "The roadmap {job} job reads its repository's clone and was given none: its row in the " + "due table must set needs_clone." + ) intake_borrow_needs_title: str = ( "--borrow-reason applies to a new candidate; pass it with --title and --body-file." ) diff --git a/src/devops_cli/roadmap/intake.py b/src/devops_cli/roadmap/intake.py index 2f1a9d23a2..07efa139db 100644 --- a/src/devops_cli/roadmap/intake.py +++ b/src/devops_cli/roadmap/intake.py @@ -17,9 +17,13 @@ looks like a secret is refused before it reaches a model or GitHub. **The proposal.** The model returns a type, a Priority from P1 to P3, Value and Effort, each -with a one-line reason, and optionally one piece of evidence. The candidate's text is untrusted: -code checks every value against its list, a `duplicate_of` outside the shortlist is rejected, -and a proposal with a value off its list, or an answer that never fits the schema, is skipped. +with a one-line reason, and optionally one piece of evidence. The types it may pick are the +`type/*` labels `.github/labels.yml` declares, `type/epic` aside; a run reads the file at its +first candidate, before any timeline read or model call, and stops with a `ConfigurationError` +naming the repository when the file is missing or declares none (#1358). The candidate's text +is untrusted: code checks every value against its list, a `duplicate_of` outside the shortlist +is rejected, and a proposal with a value off its list, or an answer that never fits the +schema, is skipped. P0 needs evidence whose value is a whole word of the candidate's text or was attached by the entry point's caller, that GitHub confirms (`RoadmapStore.evidence_holds`), from a trusted source: an author with write access, on an issue no agent filed, or the caller that attached it. @@ -104,6 +108,7 @@ ) from devops_cli.dry_run.requests import PlannedRequest, render_request_plan from devops_cli.exceptions.config import ConfigurationError +from devops_cli.exceptions.git import GitHubFileNotFoundError from devops_cli.exceptions.security import SecurityError from devops_cli.github.labels import LabelSpec from devops_cli.lang import MESSAGES @@ -475,9 +480,10 @@ def count(**conditions: object) -> int: @dataclass class _Run: - """What one run reads once.""" + """What one run reads once, from `repo`'s `store`.""" store: RoadmapStore + repo: str config: RoadmapConfig model: IntakeModel ref: str | None @@ -511,21 +517,34 @@ def next_release(self) -> Release | None: @cached_property def types(self) -> tuple[str, ...]: - """The `type/*` labels `.github/labels.yml` declares, `type/epic` aside.""" - text = self.store.repository_file(CONST_ROADMAP_LABELS_PATH, ref=self.ref) + """The `type/*` labels `.github/labels.yml` declares, `type/epic` aside. A file that is + missing, is no label specs or declares none is a configuration error naming the + repository; any other failed read stays GitHub's error (#1358).""" + path, texts = CONST_ROADMAP_LABELS_PATH, MESSAGES.roadmap + where = { + "repo": self.repo, + "path": path, + "ref": self.ref or texts.intake_placeholder_default_branch, + } try: + text = self.store.repository_file(path, ref=self.ref) specs = _LABEL_SPECS.validate_python(yaml.safe_load(text)) + except GitHubFileNotFoundError as exc: + missing = texts.intake_labels_missing.format(**where) + raise ConfigurationError(missing, details={"path": path}) from exc except (yaml.YAMLError, InvalidLabelsError) as exc: - raise ConfigurationError( - f"{CONST_ROADMAP_LABELS_PATH} can't be read as label specs: {str(exc)[:200]}", - details={"path": CONST_ROADMAP_LABELS_PATH}, - ) from exc - return tuple( + unreadable = texts.intake_labels_unreadable.format(**where, error=str(exc)[:200]) + raise ConfigurationError(unreadable, details={"path": path}) from exc + types = tuple( spec.name for spec in specs if spec.name.startswith(CONST_ROADMAP_TYPE_LABEL_PREFIX) and spec.name != CONST_ROADMAP_EPIC_LABEL ) + if not types: + untyped = texts.intake_labels_untyped.format(**where) + raise ConfigurationError(untyped, details={"path": path}) + return types @cached_property def openings(self) -> list[int]: @@ -957,6 +976,11 @@ class _Planner: opened: int = 0 def decide_all(self, subjects: Sequence[Subject]) -> Iterator[IntakeDecision]: + """Each candidate's decision, in turn. A run with a candidate reads `.github/labels.yml` + first, so a file it can't use stops it before any timeline read or model call (#1358).""" + if not subjects: + return + _ = self.run.types checked = [_checked(self.run, subject) for subject in subjects] own = self._embed(subjects, checked) for subject, vector in zip(subjects, own, strict=True): @@ -1096,13 +1120,15 @@ def _place( def plan_intake( store: RoadmapStore, *, + repo: str, config: RoadmapConfig, model: IntakeModel, ref: str | None = None, issues: Collection[int] = (), new: NewCandidate | None = None, ) -> IntakePlan: - """Decide every candidate, or only `issues`, or only the `new` candidate, writing nothing. + """Decide every candidate of `repo`, whose roadmap `store` reads, or only `issues`, or only + the `new` candidate, writing nothing. A `new` candidate whose text looks like it holds a secret raises `SecurityError` first. """ @@ -1110,6 +1136,7 @@ def plan_intake( new.refuse_secrets() run = _Run( store=store, + repo=repo, config=config, model=model, ref=ref, @@ -1232,6 +1259,7 @@ def intake_candidate( store: RoadmapStore, candidate: NewCandidate, *, + repo: str, config: RoadmapConfig, model: IntakeModel, ref: str | None = None, @@ -1239,7 +1267,7 @@ def intake_candidate( ) -> CandidateOutcome: """The entry point discovery (#745) and the review hand-off call: decide one candidate that is not an issue yet, and with `confirm` file and place it unless it is a duplicate or folds.""" - plan = plan_intake(store, config=config, model=model, ref=ref, new=candidate) + plan = plan_intake(store, repo=repo, config=config, model=model, ref=ref, new=candidate) (decision,) = plan.decisions applied = apply_intake(store, plan) if confirm else None number = applied.filed[0] if applied and applied.filed else None diff --git a/src/devops_cli/roadmap/intake_requests.py b/src/devops_cli/roadmap/intake_requests.py index 3eee28e47c..c43c6de705 100644 --- a/src/devops_cli/roadmap/intake_requests.py +++ b/src/devops_cli/roadmap/intake_requests.py @@ -144,11 +144,13 @@ def reads(self) -> list[PlannedRequest]: def decisions(self, subjects: Sequence[str], *, new: bool, repeat: str) -> list[PlannedRequest]: """The reads and model calls that decide each candidate, in the order a run makes them.""" store = self.store - planned: list[PlannedRequest] = [] + candidate = "" if new else MESSAGES.roadmap.intake_request_conditions["candidate"] + planned = self.step( + "labels", store.file(CONST_ROADMAP_LABELS_PATH, self.ref), when=candidate + ) for s in [] if new else subjects: planned += self.step("closures", store.closures(s), subject=s, repeat=repeat) planned.append(self.call("embed_new" if new else "embed", _Via.EMBEDDING)) - planned += self.step("labels", store.file(CONST_ROADMAP_LABELS_PATH, self.ref)) for index, subject in enumerate(subjects): planned.append(self.call("propose", _Via.MODEL, subject=subject, repeat=repeat)) planned += self.step( diff --git a/src/devops_cli/roadmap/run.py b/src/devops_cli/roadmap/run.py index d2882d6638..2d124c57cd 100644 --- a/src/devops_cli/roadmap/run.py +++ b/src/devops_cli/roadmap/run.py @@ -40,6 +40,7 @@ ) from devops_cli.core.process import run_subprocess from devops_cli.exceptions import GitOperationError, RoadmapRunError, SecurityError +from devops_cli.lang import MESSAGES from devops_cli.roadmap.reprioritize import current_release from devops_cli.roadmap.store import ( RELEASE_CHANGE_KINDS, @@ -346,10 +347,12 @@ def _refine_cross_job( def _run_intake_adapter( store: RoadmapStore, + *, + repo: str, config: RoadmapConfig | None = None, **_: Any, ) -> JobOutcome: - """Run intake job and return JobOutcome.""" + """Run intake on `repo` and return JobOutcome.""" from devops_cli.config.constants import CONST_ROADMAP_CRITICAL_FIX_LABELS from devops_cli.roadmap.config import read_roadmap_config from devops_cli.roadmap.intake import ( @@ -361,7 +364,7 @@ def _run_intake_adapter( active_config = config or read_roadmap_config(store, ref=None) model = build_intake_model() - plan = plan_intake(store, config=active_config, model=model) + plan = plan_intake(store, repo=repo, config=active_config, model=model) has_crit_or_p0 = False for dec in plan.decisions: if dec.outcome is Outcome.PLACE: @@ -474,6 +477,16 @@ def _run_reprioritize_adapter( return JobOutcome(changes=changes) +def _job_clone(job: str, clone_path: Path | None) -> Path: + """The clone `job` reads its repository in. A row that gives it none is a due-table error, + never a reason to read the working directory instead (#1358).""" + if clone_path is None: + raise GitOperationError( + MESSAGES.roadmap.run_job_needs_clone.format(job=job), operation="checkout" + ) + return clone_path + + def _run_refine_adapter( store: RoadmapStore, repo: str = "", @@ -487,7 +500,7 @@ def _run_refine_adapter( from devops_cli.roadmap.refine import apply_refine, plan_refine, raise_for_failed_items active_config = config or read_roadmap_config(store, ref=None) - source = clone_path or Path.cwd() + source = _job_clone("refine", clone_path) plan = plan_refine(store, repo=repo, source=source, config=active_config) if plan.has_writes: apply_refine(store, plan) @@ -497,9 +510,12 @@ def _run_refine_adapter( def _run_metrics_adapter( repo: str = "", + clone_path: Path | None = None, **_: Any, ) -> JobOutcome: - """Run project metrics collection adapter and update in-memory registry and OTLP.""" + """Collect the project metrics, walking the release tags of the job's clone of `repo`, and the + GitHub and Cloudflare status, into the in-memory registry and OTLP (#1358). A failed + collection or status read is logged and skipped; a missing clone fails the job.""" from devops_cli.github.metrics import ( collect_project_metrics_report, emit_project_metrics_telemetry, @@ -512,9 +528,10 @@ def _run_metrics_adapter( record_service_status_in_registry, ) + clone = _job_clone("metrics", clone_path) try: target_repo = repo or None - report = collect_project_metrics_report(repo=target_repo) + report = collect_project_metrics_report(root=clone, repo=target_repo) record_project_metrics_in_registry(report) emit_project_metrics_telemetry(report) except Exception as exc: @@ -569,6 +586,7 @@ def _run_metrics_adapter( name="metrics", interval=timedelta(minutes=DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES), runner=_run_metrics_adapter, + needs_clone=True, first_run_due=True, ), ) @@ -623,6 +641,7 @@ def build_stub_table( name="metrics", interval=timedelta(minutes=DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES), runner=r.get("metrics", lambda **_: JobOutcome()), + needs_clone=needs_clone, first_run_due=True, ) ) diff --git a/tests/roadmap_board_fake.py b/tests/roadmap_board_fake.py index 641b165040..ca9cdda8d8 100644 --- a/tests/roadmap_board_fake.py +++ b/tests/roadmap_board_fake.py @@ -10,21 +10,28 @@ `GitHubFake` is a whole repository and its board at the `gh` process edge: REST issues, milestones, labels, comments, events and files, the board's fields, and the `gh project` -writes, each applied to what later reads return. It keeps every argv, and charges each GraphQL -request the points GitHub's own estimate (`rateLimit(dryRun: true)`, board #2, 2026-10-08) gives -its shape (`GRAPHQL_POINTS`). Closing an issue runs the board's built-in "Item closed" workflow, -which sets its card's Status to Done. Neither starts `gh` or opens a socket. +writes, each applied to what later reads return. It also answers the project metrics reads +(the repository, its Actions runs and its traffic), `gh api user` with its `login`, and +`gh api rate_limit` with a full quota that resets in a minute. It keeps every argv, and charges +each GraphQL request the points GitHub's own estimate (`rateLimit(dryRun: true)`, board #2, +2026-10-08) gives its shape (`GRAPHQL_POINTS`). Closing an issue runs the board's built-in +"Item closed" workflow, which sets its card's Status to Done. Neither starts `gh` or opens a +socket. `GitHubFake.process` stands in for `subprocess.run` itself, answering `gh` and passing +every other program, such as `git`, to the real one. """ from __future__ import annotations import json import subprocess +import time from collections.abc import Callable, Iterable from copy import deepcopy +from pathlib import Path from typing import Any from urllib.parse import parse_qs, unquote, urlsplit +from devops_cli.config.constants import CONST_GH_CLI from devops_cli.roadmap.board_read import ( BOARD_BUDGET_OPERATION, BOARD_CARD_OPERATION, @@ -266,7 +273,8 @@ class GitHubFake: """One repository's issues, milestones and board, answering the store's `gh` commands. `issues` maps a number to its REST payload; `on_board` numbers start as cards with the - given `cards` fields. `lag` is how many board listings leave a card just added out. + given `cards` fields. `lag` is how many board listings leave a card just added out. `files` + maps a path to its text, or to the `(exit code, output)` `gh` gives for it, such as a 502. """ def __init__( @@ -274,12 +282,14 @@ def __init__( repo: str, *, milestones: Iterable[dict[str, Any]] = (), - files: dict[str, str] | None = None, + files: dict[str, str | tuple[int, str]] | None = None, events: Iterable[dict[str, Any]] = (), lag: int = 0, commits: Iterable[str] = (), + login: str = "roadmap-bot", ) -> None: self.repo = repo + self.login = login self.milestones = list(milestones) self.files = dict(files or {}) self.events = list(events) @@ -341,11 +351,34 @@ def __call__(self, args: list[str], **kwargs: Any) -> subprocess.CompletedProces text = output if isinstance(output, str) else json.dumps(output) return subprocess.CompletedProcess(args, returncode, text, "" if returncode == 0 else text) + def process( + self, run: Callable[..., subprocess.CompletedProcess[str]] + ) -> Callable[..., subprocess.CompletedProcess[str]]: + """A stand-in for `subprocess.run` that answers `gh`, given as a list or a tuple, as this + fake, raising `CalledProcessError` for a failed answer under `check=True` as `run` does, + and hands every other program to `run`, the real `subprocess.run`.""" + + def dispatch(cmd: Any, *args: Any, **kwargs: Any) -> subprocess.CompletedProcess[str]: + if not (isinstance(cmd, list | tuple) and cmd and Path(cmd[0]).name == CONST_GH_CLI): + return run(cmd, *args, **kwargs) + answer = self(list(cmd[1:]), **kwargs) + if kwargs.get("check"): + answer.check_returncode() + return answer + + return dispatch + def _answer(self, args: list[str], stdin: str | None) -> Any: if args[0] == "project": return self._project(args) if args[:2] == ["api", "graphql"]: return self._graphql(args, stdin) + if args[:2] == ["api", "user"]: + return f"{self.login}\n" + if args[:2] == ["api", "rate_limit"]: + reset = int(time.time()) + 60 + quota = {"limit": 5000, "remaining": 5000, "used": 0, "reset": reset} + return {"resources": {name: quota for name in ("core", "graphql", "search")}} assert args[0] == "api", f"not a gh command the store sends: {args}" return self._rest(args) @@ -448,6 +481,9 @@ def _rest(self, args: list[str]) -> Any: ) url = urlsplit(path) query = {key: values[0] for key, values in parse_qs(url.query).items()} + if url.path == f"repos/{self.repo}": + open_issues = sum(issue["state"] == "open" for issue in self.issues.values()) + return {"stargazers_count": 0, "forks_count": 0, "open_issues_count": open_issues} parts = url.path.removeprefix(f"repos/{self.repo}/").split("/") return self._rest_route(method, url.path, parts, query, fields, args) @@ -470,6 +506,10 @@ def _rest_route( return {"sha": parts[1]} if parts[1] in self.commits else (1, "HTTP 422") if parts[0] == "releases": return (1, "gh: Not Found (HTTP 404)") + if parts == ["actions", "runs"]: + return {"total_count": 0, "workflow_runs": []} + if parts[0] == "traffic": + return [] if parts[1] == "popular" else {"count": 0, "uniques": 0} if parts[0] == "milestones": return self.milestones if page == 1 else [] if parts == ["issues", "events"]: diff --git a/tests/test_github_metrics.py b/tests/test_github_metrics.py index c8af4feb2e..e47db3874d 100644 --- a/tests/test_github_metrics.py +++ b/tests/test_github_metrics.py @@ -4,7 +4,9 @@ import datetime import json +import logging import subprocess +from collections.abc import Callable, Sequence from pathlib import Path from typing import Any from unittest.mock import MagicMock @@ -39,6 +41,7 @@ record_project_metrics_in_registry, ) from devops_cli.telemetry.metrics import InMemoryMetricsRegistry +from tests.roadmap_board_fake import GitHubFake runner = CliRunner() @@ -253,39 +256,75 @@ def test_get_label_taxonomy_metrics(monkeypatch: pytest.MonkeyPatch) -> None: assert (p1.count, cli_scope.count) == (2, 2) -def test_collect_project_metrics_report(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """Verify aggregate report building across releases, CI checks, and milestones.""" - releases = [ - ReleaseCadenceMetric( - tag="v0.2.25", - published_at="2026-10-01", - days_since_prev=3.0, - commit_count=20, - pr_count=15, - ), - ReleaseCadenceMetric( - tag="v0.2.24", - published_at="2026-09-28", - days_since_prev=2.0, - commit_count=30, - pr_count=25, - ), - ] - monkeypatch.setattr( - "devops_cli.github.metrics.get_release_cadence_metrics", lambda *_, **__: releases - ) - monkeypatch.setattr("devops_cli.github.metrics.get_ci_workflow_metrics", lambda *_, **__: []) - monkeypatch.setattr("devops_cli.github.metrics.get_milestone_metrics", lambda *_, **__: []) - monkeypatch.setattr("devops_cli.github.metrics.get_label_taxonomy_metrics", lambda *_, **__: []) - - report = collect_project_metrics_report(root=tmp_path, repo="example/test-repo") - assert (report.repo, report.total_releases, report.average_cadence_days) == ( +def test_collect_project_metrics_report( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, git: Callable[..., None] +) -> None: + """The report takes its releases from the repository's tags and its milestones and open + issues' labels from GitHub, each read at its process edge.""" + root = tmp_path / "repo" + root.mkdir() + git(root, "init", "--quiet", "--initial-branch=main") + for tag, day in ( + ("v0.2.23", "2026-09-26"), + ("v0.2.24", "2026-09-28"), + ("v0.2.25", "2026-10-01"), + ): + monkeypatch.setenv("GIT_COMMITTER_DATE", f"{day}T12:00:00+00:00") + git(root, "commit", "--quiet", "--allow-empty", "-m", f"release {tag}") + git(root, "tag", tag) + milestone = {"title": "v0.2.25", "state": "closed", "open_issues": 1, "closed_issues": 3} + github = GitHubFake("example/test-repo", milestones=[milestone]) + github.seed_issue(1, "feat: export", labels=("type/feature",)) + monkeypatch.setattr(subprocess, "run", github.process(subprocess.run)) + + report = collect_project_metrics_report(root=root, repo="example/test-repo") + assert ( + report.repo, + [release.tag for release in report.releases], + report.average_cadence_days, + [(found.milestone, found.completion_rate) for found in report.milestones], + [(found.label, found.count) for found in report.taxonomy_labels], + ) == ( "example/test-repo", - 2, + ["v0.2.25", "v0.2.24", "v0.2.23"], 2.5, + [("v0.2.25", 75.0)], + [("type/feature", 1)], ) +def _tagged_repository(git: Callable[..., None], repo: Path, tags: Sequence[str]) -> None: + """A repository at `repo` with one commit for each of `tags`, each tagged by name.""" + repo.mkdir(parents=True) + git(repo, "init", "--quiet", "--initial-branch=main") + for tag in tags: + git(repo, "commit", "--quiet", "--allow-empty", "-m", f"release {tag}") + git(repo, "tag", tag) + + +def test_a_given_root_is_walked_as_it_is_even_inside_another_checkout( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + git: Callable[..., None], +) -> None: + """A local `devops roadmap run` keeps each repository's clone under `.data/`, inside the + workspace checkout (#1358). The report walks the tags of the clone it is given, not those of + the checkout around it, and every read it makes succeeds.""" + workspace = tmp_path / "workspace" + clone = workspace / ".data" / "roadmap" / "example" / "roadmap" / "clone" + _tagged_repository(git, workspace, ("v9.0.0", "v9.1.0")) + _tagged_repository(git, clone, ("v0.1.0", "v0.2.0")) + github = GitHubFake("example/roadmap") + monkeypatch.setattr(subprocess, "run", github.process(subprocess.run)) + with caplog.at_level(logging.WARNING): + report = collect_project_metrics_report(root=clone, repo="example/roadmap") + assert ( + [release.tag for release in report.releases], + [record.getMessage() for record in caplog.records if record.levelno >= logging.WARNING], + ) == (["v0.2.0", "v0.1.0"], []) + + def test_emit_project_metrics_telemetry(monkeypatch: pytest.MonkeyPatch) -> None: """Verify OpenTelemetry emission for all project metric series.""" emitted: list[tuple[Any, float, dict[str, str] | None]] = [] diff --git a/tests/test_roadmap_intake.py b/tests/test_roadmap_intake.py index b9cfa29fab..91ca2caf88 100644 --- a/tests/test_roadmap_intake.py +++ b/tests/test_roadmap_intake.py @@ -35,7 +35,8 @@ from devops_cli.config.settings import AIConfig from devops_cli.dry_run.state import in_dry_run_invocation from devops_cli.exceptions.ai import ModelGatewayUnreachableError -from devops_cli.exceptions.git import GitHubOperationError +from devops_cli.exceptions.config import ConfigurationError +from devops_cli.exceptions.git import GitHubFileNotFoundError, GitHubOperationError from devops_cli.exceptions.security import SecurityError from devops_cli.lang import MESSAGES from devops_cli.roadmap import store as roadmap_store_module @@ -133,14 +134,21 @@ def propose(self, request: ProposalRequest) -> ModelProposal: class Roadmap: """One repository's roadmap: v0.2.25 shipped and closed a day ago, v0.2.26 is current and - v0.2.27 planned.""" + v0.2.27 planned. Its `.github/labels.yml` holds `labels`, this repository's own by default; + with None it has none.""" - def __init__(self, store: InMemoryRoadmapStore | None = None, config: RoadmapConfig = CONFIG): + def __init__( + self, + store: InMemoryRoadmapStore | None = None, + config: RoadmapConfig = CONFIG, + labels: str | None = LABELS_YML, + ): self.now = NOW - timedelta(days=1) self.config = config self.store = store or InMemoryRoadmapStore(board_options=OPTIONS, clock=self.clock) self.person = self.store.as_actor("alice") - self.store.seed_file(".github/labels.yml", LABELS_YML) + if labels is not None: + self.store.seed_file(".github/labels.yml", labels) self.store.create_release(PREVIOUS, state=GitHubState.CLOSED) for title in (CURRENT, NEXT): self.store.create_release(title) @@ -191,7 +199,7 @@ def comments(self, number: int) -> list[str]: return self.store.comments_on(number) def plan(self, model: FakeModel, **options: Any) -> IntakePlan: - return plan_intake(self.store, config=self.config, model=model, **options) + return plan_intake(self.store, repo=REPO, config=self.config, model=model, **options) def run(self, model: FakeModel, **options: Any) -> list[JobWrite]: before = len(self.store.job_writes()) @@ -249,6 +257,102 @@ def test_with_no_candidates_intake_embeds_nothing_and_asks_the_model_nothing( assert (model.embedded, model.requests, plan.has_writes) == ([], [], False) +# ── The type/* labels `.github/labels.yml` declares (#1358) ───────────────────── + +LABELS_RULE = "must declare the type/* labels intake may assign" +ONLY_EPIC = "- name: type/epic\n color: '5319e7'\n description: A parent of other items.\n" + + +def test_a_run_with_no_candidate_needs_no_labels_file() -> None: + model = FakeModel() + plan = Roadmap(labels=None).plan(model) + assert (plan.decisions, model.embedded, model.requests) == ((), [], []) + + +@pytest.mark.parametrize( + ("labels", "names", "ruled"), + [ + (None, f"{REPO} has no .github/labels.yml at the default branch.", True), + ( + ONLY_EPIC, + f"{REPO}'s .github/labels.yml at the default branch declares no type/* label", + True, + ), + ("labels: none\n", f"{REPO}'s .github/labels.yml can't be read as label specs", False), + ], + ids=["missing", "only-epic", "not-label-specs"], +) +def test_a_labels_file_it_cant_use_stops_intake_before_any_read_or_model_call( + labels: str | None, names: str, ruled: bool +) -> None: + """The file is read at the run's first candidate, before its timeline read and the + embedding call. Its error names the repository the run was given, the file and, for a + missing or type-less file, the rule.""" + roadmap = Roadmap(labels=labels) + roadmap.issue("feat: export the board as CSV") + ran: list[str] = [] + store: Any = _Recorded(roadmap.store, ran) + model = FakeModel() + with pytest.raises(ConfigurationError) as raised: + plan_intake(store, repo=REPO, config=CONFIG, model=model) + message = str(raised.value) + assert ( + raised.value.details, + message.startswith(names), + LABELS_RULE in message, + "closures" in ran, + model.embedded, + model.requests, + ) == ({"path": ".github/labels.yml"}, True, ruled, False, [], []) + + +def test_intake_names_the_repository_whose_labels_file_declares_no_type( + board: Roadmap, fake_model: FakeModel +) -> None: + """The command hands the run its `--repo`, so the error names the repository.""" + board.store.seed_file(".github/labels.yml", ONLY_EPIC) + board.issue("feat: export the board as CSV") + output = _intake("--plan", exit_code=1) + assert ( + f"{REPO}'s .github/labels.yml at the default branch declares no type/* label" in output, + LABELS_RULE in output, + fake_model.requests, + ) == (True, True, []) + + +def test_a_dry_runs_labels_read_waits_for_a_candidate_unless_it_has_a_title() -> None: + """A run over the open issues reads `.github/labels.yml` only once it has a candidate; a + `--title` candidate always is one, so its read has no condition.""" + + def labels_read(plan: IntakePlan) -> str: + target = f"repos/{REPO}/contents/.github/labels.yml" + return next(r.condition for r in plan.requests if r.argv and r.argv[-1] == target) + + every = dry_run_intake(REPO) + new = dry_run_intake(REPO, new=NewCandidate(title="feat: idea", body="text")) + assert (labels_read(every), labels_read(new)) == ( + MESSAGES.roadmap.intake_request_conditions["candidate"], + "", + ) + + +def test_a_labels_read_github_fails_stays_a_github_error() -> None: + """Only a missing file is a configuration error: a 502 is GitHub's failure, raised as + such, still before any model call.""" + github, store = on_github() + github.files[".github/labels.yml"] = (1, "gh: Server Error (HTTP 502)") + github.seed_issue(1, "feat: export the board as CSV") + model = FakeModel() + with pytest.raises(GitHubOperationError) as raised: + plan_intake(store, repo=REPO, config=CONFIG, model=model) + assert ( + isinstance(raised.value, (ConfigurationError, GitHubFileNotFoundError)), + "HTTP 502" in str(raised.value), + model.embedded, + model.requests, + ) == (False, True, [], []) + + def test_the_model_judges_only_the_five_nearest_items(roadmap: Roadmap) -> None: for title in ("csv one", "csv two", "csv three", "csv four", "csv five", "other", "else"): roadmap.finished(title) @@ -555,6 +659,7 @@ def test_evidence_the_entry_points_caller_attaches_is_trusted_and_the_source_is_ source="https://example.test/review/1", evidence=(commit,), ), + repo=REPO, config=CONFIG, model=model, confirm=True, @@ -562,6 +667,7 @@ def test_evidence_the_entry_points_caller_attaches_is_trusted_and_the_source_is_ claimed = intake_candidate( roadmap.store, NewCandidate(title="fix: claimed", body="Introduced by abc1234."), + repo=REPO, config=CONFIG, model=model, confirm=True, @@ -617,7 +723,12 @@ def test_an_agent_opening_within_the_allowance_is_filed_with_source_agent( crowded: Roadmap, ) -> None: outcome = intake_candidate( - crowded.store, _new("feat: within"), config=TIGHT, model=FakeModel(), confirm=True + crowded.store, + _new("feat: within"), + repo=REPO, + config=TIGHT, + model=FakeModel(), + confirm=True, ) standing = outcome.plan.quota assert standing is not None @@ -635,13 +746,16 @@ def test_beyond_the_allowance_an_opening_folds_and_a_split_borrows_and_is_never_ crowded: Roadmap, ) -> None: model = FakeModel() - intake_candidate(crowded.store, _new("feat: first"), config=TIGHT, model=model, confirm=True) + intake_candidate( + crowded.store, _new("feat: first"), repo=REPO, config=TIGHT, model=model, confirm=True + ) folded = intake_candidate( - crowded.store, _new("feat: second"), config=TIGHT, model=model, confirm=True + crowded.store, _new("feat: second"), repo=REPO, config=TIGHT, model=model, confirm=True ) borrowed = intake_candidate( crowded.store, _new("feat: split", borrow_reason=BorrowReason.SPLIT, source=PARENT), + repo=REPO, config=TIGHT, model=model, confirm=True, @@ -659,8 +773,10 @@ def test_beyond_the_allowance_an_opening_folds_and_a_split_borrows_and_is_never_ def test_a_p1_bug_beyond_the_allowance_borrows(crowded: Roadmap) -> None: model = FakeModel(proposals={"fix: second": {"type": "type/bug", "priority": "P1-High"}}) - intake_candidate(crowded.store, _new("feat: first"), config=TIGHT, model=model, confirm=True) - bug = intake_candidate(crowded.store, _new("fix: second"), config=TIGHT, model=model) + intake_candidate( + crowded.store, _new("feat: first"), repo=REPO, config=TIGHT, model=model, confirm=True + ) + bug = intake_candidate(crowded.store, _new("fix: second"), repo=REPO, config=TIGHT, model=model) assert ( bug.decision.quota, bug.number, @@ -784,10 +900,11 @@ def test_dry_run_makes_no_request_and_prints_the_requests_a_run_makes_in_order( f"gh api 'repos/{REPO}/milestones?state=all&per_page=100&page=' [repeated per page", "GraphQL read the items on board ", f"gh api -X GET search/issues -f 'q=repo:{REPO} is:issue is:open' -F per_page=1", + f"{REPO}/contents/.github/labels.yml", + "[only if the run has a candidate]", "GraphQL read the closes and reopens on #7's timeline", "[only if #7 is not on the board]", "embedding every item", - f"{REPO}/contents/.github/labels.yml", "model the proposal for #7", "With --confirm", "REST write label #7 with its type/* label", @@ -938,7 +1055,7 @@ def test_a_dry_runs_requests_follow_the_order_a_run_makes_them(roadmap: Roadmap, store: Any = _Recorded(roadmap.store, ran) model: Any = _Recorded(FakeModel(proposals={title: REGRESSION}), ran) store.repository_file(".github/roadmap.toml") - plan = plan_intake(store, config=CONFIG, model=model, issues=issues, new=candidate) + plan = plan_intake(store, repo=REPO, config=CONFIG, model=model, issues=issues, new=candidate) apply_intake(store, plan) planned = _operations(dry_run_intake(REPO, issues=issues, new=candidate)) assert ( @@ -1214,7 +1331,7 @@ def chat_structured( model = GatewayIntakeModel(AIConfig(), embedder=_Embedder(), client=Client()) garbled = roadmap.issue("feat: garbled") fine = roadmap.issue("feat: fine") - plan = plan_intake(roadmap.store, config=CONFIG, model=model) + plan = plan_intake(roadmap.store, repo=REPO, config=CONFIG, model=model) apply_intake(roadmap.store, plan) skipped = plan.decisions[0] assert ( @@ -1323,7 +1440,7 @@ def test_a_duplicate_agent_candidate_folds_into_its_original_and_the_report_says original = roadmap.finished("feat: cache embeddings") model = FakeModel(duplicates={"feat: cached embeddings": "feat: cache embeddings"}) outcome = intake_candidate( - roadmap.store, _new("feat: cached embeddings"), config=CONFIG, model=model + roadmap.store, _new("feat: cached embeddings"), repo=REPO, config=CONFIG, model=model ) report = " ".join(render_intake(outcome.plan, repo=REPO).split()) assert ( @@ -1336,7 +1453,9 @@ def test_a_duplicate_agent_candidate_folds_into_its_original_and_the_report_says def test_a_skipped_agent_candidate_still_reports_its_quota_decision(roadmap: Roadmap) -> None: model = FakeModel(proposals={"feat: odd": {"value": "Enormous"}}) - outcome = intake_candidate(roadmap.store, _new("feat: odd"), config=CONFIG, model=model) + outcome = intake_candidate( + roadmap.store, _new("feat: odd"), repo=REPO, config=CONFIG, model=model + ) report = " ".join(render_intake(outcome.plan, repo=REPO).split()) assert (outcome.decision.outcome, outcome.decision.quota, "Quota: open" in report) == ( Outcome.SKIP, @@ -1350,8 +1469,12 @@ def test_a_fold_names_the_nearest_open_item_never_a_rejected_issue(crowded: Road "widget exporter", state=GitHubState.CLOSED, state_reason="not_planned" ) model = FakeModel(topics=("widget",)) - intake_candidate(crowded.store, _new("feat: first"), config=TIGHT, model=model, confirm=True) - folded = intake_candidate(crowded.store, _new("feat: widget export"), config=TIGHT, model=model) + intake_candidate( + crowded.store, _new("feat: first"), repo=REPO, config=TIGHT, model=model, confirm=True + ) + folded = intake_candidate( + crowded.store, _new("feat: widget export"), repo=REPO, config=TIGHT, model=model + ) assert (folded.decision.quota, folded.decision.fold_into in {1, 2, 3}, rejected) == ( QuotaDecision.FOLD, True, @@ -1363,10 +1486,13 @@ def test_a_persons_new_candidate_beyond_the_allowance_is_filed_and_not_counted( crowded: Roadmap, ) -> None: model = FakeModel() - intake_candidate(crowded.store, _new("feat: first"), config=TIGHT, model=model, confirm=True) + intake_candidate( + crowded.store, _new("feat: first"), repo=REPO, config=TIGHT, model=model, confirm=True + ) mine = intake_candidate( crowded.store, _new("feat: mine", filed_by=Filer.PERSON), + repo=REPO, config=TIGHT, model=model, confirm=True, @@ -1379,10 +1505,13 @@ def test_a_persons_new_candidate_beyond_the_allowance_is_filed_and_not_counted( def test_a_split_borrows_only_with_the_link_it_was_split_from(crowded: Roadmap) -> None: model = FakeModel() - intake_candidate(crowded.store, _new("feat: first"), config=TIGHT, model=model, confirm=True) + intake_candidate( + crowded.store, _new("feat: first"), repo=REPO, config=TIGHT, model=model, confirm=True + ) unlinked = intake_candidate( crowded.store, _new("feat: split", borrow_reason=BorrowReason.SPLIT), + repo=REPO, config=TIGHT, model=model, ) @@ -1433,7 +1562,7 @@ def test_a_retried_new_candidate_finds_the_issue_its_stopped_run_filed(roadmap: filed = roadmap.issue("feat: retry me", labels=("source/agent",)) model = FakeModel(duplicates={"feat: retry me": "feat: retry me"}) outcome = intake_candidate( - roadmap.store, _new("feat: retry me"), config=CONFIG, model=model, confirm=True + roadmap.store, _new("feat: retry me"), repo=REPO, config=CONFIG, model=model, confirm=True ) assert (outcome.decision.outcome, outcome.decision.original, len(roadmap.store.issues())) == ( Outcome.DUPLICATE, @@ -1503,7 +1632,7 @@ def on_github(board: int = 0, *, lag: int = 0) -> tuple[GitHubFake, GitHubRoadma def _intake_on_github( store: GitHubRoadmapStore, model: FakeModel, **options: Any ) -> tuple[IntakePlan, Any]: - plan = plan_intake(store, config=CONFIG, model=model, **options) + plan = plan_intake(store, repo=REPO, config=CONFIG, model=model, **options) return plan, lambda: apply_intake(store, plan, refine=lambda *_: None) diff --git a/tests/test_roadmap_run.py b/tests/test_roadmap_run.py index 19cb71e943..3302d6b588 100644 --- a/tests/test_roadmap_run.py +++ b/tests/test_roadmap_run.py @@ -18,7 +18,7 @@ from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any -from unittest.mock import MagicMock, patch +from unittest.mock import patch import pytest from typer.testing import CliRunner @@ -30,15 +30,21 @@ CONST_GH_CLI, CONST_ROADMAP_CLOSURE_BATCH_KEYS, CONST_ROADMAP_INTAKE_BATCH_KEYS, + CONST_URL_CLOUDFLARE_STATUS_SUMMARY, + CONST_URL_GITHUB_STATUS_SUMMARY, ) +from devops_cli.config.defaults import DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES from devops_cli.exceptions import GitOperationError, RoadmapRunError from devops_cli.github.rate_limiter import get_github_rate_limiter from devops_cli.roadmap.board_read import BOARD_BUDGET_OPERATION, BOARD_ITEMS_OPERATION from devops_cli.roadmap.github_store import GitHubRoadmapStore from devops_cli.roadmap.memory_store import InMemoryRoadmapStore from devops_cli.roadmap.run import ( + DEFAULT_DUE_TABLE, JobOutcome, JobRow, + _run_metrics_adapter, + _run_refine_adapter, build_stub_table, ensure_checkout, run_due_jobs, @@ -46,7 +52,10 @@ ) from devops_cli.roadmap.store import Change, ChangeKind, CloseReason, GitHubState, Release from devops_cli.server.service import TriggerBatch +from devops_cli.telemetry.instruments import PROJECT_RELEASES_TOTAL +from devops_cli.telemetry.metrics import GLOBAL_METRICS from tests.roadmap_board_fake import GitHubFake +from tests.web_fakes import StubWeb REPO = "example/roadmap" RELEASE = "v0.2.26" @@ -616,7 +625,8 @@ def test_checkouts_git_management( release_remote: Path, child_argvs: list[list[str]], ) -> None: - """Clones to expected path, tracks remote tip, sets identity, fails clone-dependent jobs.""" + """Clones to expected path, tracks remote tip, sets identity, fails clone-dependent jobs: + close, refine and metrics, which walks the clone's release tags (#1358).""" bare = release_remote data_dir = tmp_path / "data" @@ -638,6 +648,7 @@ def test_checkouts_git_management( ran_reprio = False called_close = False called_refine = False + called_metrics = False def stub_intake(**_: Any) -> JobOutcome: nonlocal ran_intake @@ -659,12 +670,18 @@ def stub_refine(**_: Any) -> JobOutcome: called_refine = True return JobOutcome() + def stub_metrics(**_: Any) -> JobOutcome: + nonlocal called_metrics + called_metrics = True + return JobOutcome() + fail_table = build_stub_table( { "intake": stub_intake, "close": stub_close, "reprioritize": stub_reprio, "refine": stub_refine, + "metrics": stub_metrics, }, needs_clone=True, ) @@ -693,6 +710,7 @@ def stub_refine(**_: Any) -> JobOutcome: ran_reprio, called_close, called_refine, + called_metrics, exc_info.value.failed_jobs, ) == ( True, @@ -703,7 +721,8 @@ def stub_refine(**_: Any) -> JobOutcome: True, False, False, - ("close", "refine"), + False, + ("close", "refine", "metrics"), ) @@ -1130,52 +1149,103 @@ def test_ensure_checkout_rejects_path_escape_and_malformed_repo_slugs(tmp_path: assert (len(results), all(results)) == (len(escapes), True) -def test_metrics_job_registered_in_default_due_table_and_adapter( +STATUS_PAGE = { + "page": {"id": "page", "name": "Status", "url": "https://example.com"}, + "status": {"indicator": "none", "description": "All Systems Operational"}, +} + + +def test_the_metrics_job_walks_the_release_tags_of_its_own_clone( + seeded_store: InMemoryRoadmapStore, + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + stub_web: StubWeb, + git: Callable[..., None], ) -> None: - """Verify metrics job is present in DEFAULT_DUE_TABLE and _run_metrics_adapter executes.""" - from devops_cli.config.defaults import DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES - from devops_cli.roadmap.run import DEFAULT_DUE_TABLE, _run_metrics_adapter - - metrics_row = next((r for r in DEFAULT_DUE_TABLE if r.name == "metrics"), None) + """The default table's metrics row clones the repository and walks its release tags there, + not in the working directory, which in the Service is no git repository (#1358). The gauge + reads the remote's two tags, and the job logs no warning, so every GitHub and status read it + made was answered.""" + row = next(row for row in DEFAULT_DUE_TABLE if row.name == "metrics") + remote = _make_bare_remote(tmp_path) + for tag in ("v0.1.0", "v0.2.0"): + git(remote, "tag", tag, f"release/{RELEASE}") + github = GitHubFake(REPO, milestones=[{"number": 26, "title": RELEASE, "state": "open"}]) + monkeypatch.setattr(subprocess, "run", github.process(subprocess.run)) + for url in (CONST_URL_GITHUB_STATUS_SUMMARY, CONST_URL_CLOUDFLARE_STATUS_SUMMARY): + stub_web.page(url, json.dumps(STATUS_PAGE)) + GLOBAL_METRICS.clear_metric(PROJECT_RELEASES_TOTAL.name) + data_dir = tmp_path / "data" + with caplog.at_level(logging.WARNING): + ran = run_due_jobs( + REPO, seeded_store, table=(row,), data_dir=data_dir, remote_url=str(remote), now=NOW + ) + clone = data_dir / "roadmap" / "example" / "roadmap" / "clone" assert ( - metrics_row is not None, - metrics_row.first_run_due if metrics_row else False, - metrics_row.interval.total_seconds() if metrics_row and metrics_row.interval else 0, + (row.needs_clone, row.first_run_due, row.interval), + ran, + (clone / ".git").is_dir(), + GLOBAL_METRICS.get_gauge(PROJECT_RELEASES_TOTAL.name), + [record.getMessage() for record in caplog.records if record.levelno >= logging.WARNING], ) == ( + (True, True, timedelta(minutes=DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES)), + ("metrics",), True, - True, - float(DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES * 60), + 2.0, + [], ) - called: list[str] = [] - fake_report = MagicMock() - monkeypatch.setattr( - "devops_cli.github.metrics.collect_project_metrics_report", - lambda **_: called.append("collect") or fake_report, - ) - monkeypatch.setattr( - "devops_cli.github.metrics.record_project_metrics_in_registry", - lambda _: called.append("record"), - ) + +def test_a_failed_metrics_collection_or_status_read_is_logged_and_the_job_goes_on( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + stub_web: StubWeb, + git: Callable[..., None], +) -> None: + """GitHub answers a milestone the report can't count, and neither status page answers: + each failure is a WARNING from the job, which still returns its outcome.""" + clone = tmp_path / "clone" + clone.mkdir() + git(clone, "init", "--quiet") + milestone = {"number": 26, "title": RELEASE, "state": "open", "open_issues": None} monkeypatch.setattr( - "devops_cli.github.metrics.emit_project_metrics_telemetry", - lambda _: called.append("emit"), + subprocess, "run", GitHubFake(REPO, milestones=[milestone]).process(subprocess.run) ) - - outcome = _run_metrics_adapter(repo="example/repo") - assert (isinstance(outcome, JobOutcome), called) == ( + with caplog.at_level(logging.WARNING): + outcome = _run_metrics_adapter(repo=REPO, clone_path=clone) + job = [r.getMessage() for r in caplog.records if r.name == "devops_cli.roadmap.run"] + status_pages = {CONST_URL_GITHUB_STATUS_SUMMARY, CONST_URL_CLOUDFLARE_STATUS_SUMMARY} + assert ( + outcome, + [message.partition(":")[0] for message in job], + status_pages <= set(stub_web.requested), + ) == ( + JobOutcome(), + [ + f"Project metrics collection failed for {REPO}", + "GitHub service status collection failed", + "Cloudflare service status collection failed", + ], True, - ["collect", "record", "emit"], ) - # Verify graceful degradation on exception - monkeypatch.setattr( - "devops_cli.github.metrics.collect_project_metrics_report", - MagicMock(side_effect=RuntimeError("GitHub API timeout")), + +@pytest.mark.parametrize( + ("job", "runner"), [("metrics", _run_metrics_adapter), ("refine", _run_refine_adapter)] +) +def test_a_job_that_reads_the_clone_fails_without_one_rather_than_reading_the_cwd( + seeded_store: InMemoryRoadmapStore, job: str, runner: Callable[..., JobOutcome] +) -> None: + """A row that runs metrics or refine without `needs_clone` is a table error, not a run + over the working directory, which in the Service is no git repository (#1358).""" + with pytest.raises(GitOperationError) as raised: + runner(store=seeded_store, repo=REPO, clone_path=None) + assert (f"roadmap {job} job" in str(raised.value), "needs_clone" in str(raised.value)) == ( + True, + True, ) - fail_outcome = _run_metrics_adapter(repo="example/repo") - assert isinstance(fail_outcome, JobOutcome) is True # ── On the GitHub store, at the `gh` process edge (#1361) ─────────────────────