From b498acb74650f2b280b7094ce3d350fb64c7e510 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 1 Oct 2026 09:02:52 +0000 Subject: [PATCH] feat(github): board-owned project status and truthful reconciliation (#703) Reconcile recomputed Status, Priority, Category, Value and Effort on every pass and overwrote whatever differed, so hand corrections on the board reverted. Status matched labels by substring with a Ready fallback, Category/Value/Effort came from type-label and title-keyword guesses, results were bare counts, and a failed fetch read as empty. - plan_item_changes plans each item's changes with the source that decided them. The board owns Status: it is set only when unset (from an exact status label, otherwise Backlog) or when the item's state forces Done, In Review or In Progress. Priority only fills an unset field from its label. Category, Value and Effort are never inferred. - reconcile_project_custom_fields returns the changes (planned in a dry run, applied otherwise), and `devops gh project reconcile` prints them. Reconcile and `project workflows list` refuse to guess board #2. - Failed reads of the board, issues and pull requests raise GitHubOperationError. get_repository_issues' REST fallback paginates, and roadmap sync, milestone reconciliation and release epics read every issue instead of treating a failed read as no issues. - The issues fetch drops pull requests, so each is reconciled once. - sync-roadmap reports the share of items that fell back to scope/cli. - The project sync help, MCP descriptions, tasks README, knowledge base and workflow expectations (Backlog, not Todo) match the behaviour. A dry run against board #2 plans 480 changes on 337 of 472 items, each filling an unset field or forcing a closed item to Done. Closes #703 --- AGENTS.md | 2 +- CHANGELOG.md | 4 + docs/CLI_REFERENCE.md | 6 +- docs/MCP_TOOLS.md | 8 +- docs/ROADMAP.md | 2 +- docs/agent/tasks/README.md | 4 +- ...tatus-declared-field-sources-and-truthf.md | 19 +- docs/commands/gh.md | 6 +- .../tasks/github_project_management.md | 7 +- src/devops_cli/ai/mcp/server.py | 4 +- src/devops_cli/commands/gh.py | 80 +-- src/devops_cli/config/constants.py | 4 +- src/devops_cli/github/issues.py | 48 +- src/devops_cli/github/projects.py | 472 ++++++++---------- src/devops_cli/github/release_epics.py | 7 +- src/devops_cli/github/roadmap_sync.py | 35 +- src/devops_cli/lang/en/help.py | 8 +- tests/test_gh_cmd.py | 48 +- tests/test_gh_issues_milestones.py | 18 +- tests/test_github_issues.py | 10 +- tests/test_github_projects.py | 85 ++-- tests/test_github_projects_reconcile.py | 242 +++++---- 22 files changed, 595 insertions(+), 524 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 63175cdcc0..1bf6ddc384 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -174,7 +174,7 @@ All work follows a test-first progressive verification strategy to optimize deve - Updates to task tracking files under `docs/agent/tasks/` MUST ONLY be made in the context of the functional changes delivering that specific task (bundled atomically into functional deliverable commits). They must NEVER be committed as standalone or isolated one-off commits. - **Strict Prohibition of Post-Merge Status PRs**: AI agents, automated workflows, and developers MUST NEVER open separate pull requests or author follow-up commits solely to update task statuses post-merge. All task documentation must be authored as merged/committed from the outset. - **Issue-Only Linking (No Pull Request or Review State in Task Files)**: A task file links its GitHub issue (`**Issue**: [#](https://github.com/dan-petty/devops-cli/issues/)`) and nothing else. The issue links the pull request that closes it through the PR body's closing keyword (`Closes #`), and GitHub shows that pull request on the issue. Task files MUST NEVER carry a `**PR**` field or an `In Review` status. The pull request number is unknown until the PR exists, so recording it takes a second commit, which re-runs every check and is itself a prohibited standalone tracking commit. Allowed statuses are `Backlog`, `Ready`, `In Progress` and `Done`, enforced by `tests/test_agent_task_files.py`. - - Maintain synchronization between `docs/agent/tasks/` and GitHub Projects v2 cards across these lifecycle states. `In Review` exists only on the card, derived from GitHub (`infer_item_status`), never in a task file: + - Maintain synchronization between `docs/agent/tasks/` and GitHub Projects v2 cards across these lifecycle states. `In Review` exists only on the card, derived from GitHub (`plan_item_changes`), never in a task file: - **Backlog**: Queued deliverables, backlog requirements, and upcoming milestone items awaiting assignment. - **Ready**: Scoped items with concrete acceptance criteria and tests designed, awaiting active development. - **In Progress (WIP)**: Active work items currently being authored or edited. **Card must be moved to In Progress before modifying code in `src/`**. If an early pull request is opened to pair or satisfy remote branch tracking, it MUST be opened as a **Draft Pull Request** (`--draft`). diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bad1229a8..909213579a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - **Gitleaks Scans Every File of a List Target (`devops_cli.security.gitleaks`)**: - A list target, such as the files of a review, now runs Gitleaks once per file and merges the outcomes, keeping every finding and the worst status. Before, the binary scanned only the first file, and since #763 the built-in patterns did too (#781). +- **Board-Owned Project Status and Truthful Reconciliation (`devops gh project reconcile`, `devops gh project sync`)**: + - The board owns Status: reconcile sets it only when unset, or when an item's state forces Done, In Review or In Progress, so manual triage is no longer reverted. Status labels match exactly, Priority only fills an unset field from its label, and Category, Value and Effort are no longer inferred (#703). + - `devops gh project reconcile` lists every field change with its old and new value and the source that decided it, and refuses to guess a board number when no board matches the template (#703). + - Failed reads of the board, issues or pull requests now raise instead of reading as empty, roadmap sync and release epics read every issue rather than the first 200 or 300, and each pull request is reconciled once (#703). - **Quality Gate Within Its Five-Minute Budget (`devops ci`, `tests/`)**: - The secops dry-run tests enable dry-run mode instead of running trivy, kube-linter and pluto over the whole workspace until they time out (#748). - The test network guard now fails external DNS lookups too; tests that validate egress against a resolving hostname declare the `public_dns` fixture (#748). diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 49089023e2..62aac1c23d 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -6124,7 +6124,7 @@ devops gh project status [OPTIONS] #### `devops gh project sync` -**Sync task items from docs/agent/tasks directory into GitHub Projects status.** +**Create or update the project board from its template, add open issues, and reconcile Status, Priority and Milestone; task files are not read.** ```bash devops gh project sync [OPTIONS] @@ -6138,11 +6138,11 @@ devops gh project sync [OPTIONS] | `--template`, `-t` | `path` | `.github/project-template.json` | Path to project template JSON | | `--repo`, `-R` | `string` | - | Target repository | | `--dry-run`, `--no-dry-run` | `boolean` | - | Preview task card items without remote mutations | -| `--reconcile-fields`, `--no-reconcile-fields` | `boolean` | `True` | Automatically infer and update project custom fields from taxonomy labels and issue state. | +| `--reconcile-fields`, `--no-reconcile-fields` | `boolean` | `True` | Also reconcile Status, Priority and Milestone from issue state and labels. | #### `devops gh project reconcile` -**Reconcile custom fields (Status, Priority, Category, Value, Effort) on project items.** +**Reconcile Status, Priority and Milestone on project items, listing each change and its source; the board owns Status.** ```bash devops gh project reconcile [OPTIONS] diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md index 5a13a9d344..9fd23ed911 100644 --- a/docs/MCP_TOOLS.md +++ b/docs/MCP_TOOLS.md @@ -64,9 +64,9 @@ The `devops-cli` FastMCP server exposes DevOps automation and AI review capabili | [`gh_pages_verify`](#gh-pages-verify) | Verify local repository readiness for GitHub Pages publishing. | | [`gh_project_audit`](#gh-project-audit) | Audit project board health and alignment against standardized template. | | [`gh_project_list`](#gh-project-list) | List available GitHub Projects v2 boards for user or organization. | -| [`gh_project_reconcile`](#gh-project-reconcile) | Reconcile custom fields (Status, Priority, Category, Value, Effort) on GitHub Projects v2 items. | +| [`gh_project_reconcile`](#gh-project-reconcile) | Reconcile Status, Priority and Milestone on GitHub Projects v2 items, listing each change and its source. | | [`gh_project_status`](#gh-project-status) | Inspect GitHub Projects v2 template configuration, fields, and view definitions. | -| [`gh_project_sync`](#gh-project-sync) | Synchronize task items from task tracking into GitHub Projects v2 status. | +| [`gh_project_sync`](#gh-project-sync) | Create or update the project board, add open issues, and reconcile Status, Priority and Milestone. | | [`gh_rate_limit`](#gh-rate-limit) | Inspect GitHub REST and GraphQL API rate limits, quotas, and reset countdowns. | | [`gh_run_view`](#gh-run-view) | View details and diagnostic failure logs of a specific GitHub Actions workflow run. | | [`gh_runs_list`](#gh-runs-list) | List recent GitHub Actions CI/CD workflow runs. | @@ -823,7 +823,7 @@ List available GitHub Projects v2 boards for user or organization. ### `gh_project_reconcile` -Reconcile custom fields (Status, Priority, Category, Value, Effort) on GitHub Projects v2 items. +Reconcile Status, Priority and Milestone on GitHub Projects v2 items, listing each change and its source. **Parameters:** @@ -841,7 +841,7 @@ Inspect GitHub Projects v2 template configuration, fields, and view definitions. ### `gh_project_sync` -Synchronize task items from task tracking into GitHub Projects v2 status. +Create or update the project board, add open issues, and reconcile Status, Priority and Milestone. **Parameters:** diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ec1c0920f0..38f790c1fc 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -730,7 +730,7 @@ High-density product roadmap, engineering milestones, and open-source integratio - *Constraint*: A port-less rule is worse than it looks: an agent-supplied `https://host:8443` entry, via the MCP tool, opens every port and protocol to that host. A policy is only as real as the CNI: `devops k8s bootstrap` starts minikube with no `--cni` (`commands/k8s/cluster_runtime.py:94,99`) while its help claims Calico (`lang/en/help.py:260`); that false claim is a separate item, and until it is fixed a zero denial count proves nothing. Under `--network=none` a connect fails inside the container, so no host-side enforcer sees it; report such lanes as uncounted, never as zero. Select the collector by label, never a resolved `/32`. - *Measured*: Whitelist entry `https://1.1.1.1:8443` yields a bare `1.1.1.1/32` rule with no `ports` (`.venv/bin/python -c "from devops_cli.sandbox.models import SandboxNetworkConfig as C; print(C(mode='public_whitelist', public_whitelist=['https://1.1.1.1:8443']).to_k8s_network_policy()['spec']['egress'])"`); 0 trace-context injections in the sandbox and docker packages (`grep -rn 'TRACEPARENT\|inject_env\|inject_trace_env' src/devops_cli/sandbox src/devops_cli/docker | wc -l`); 0 alerting rules (`grep -rn 'alert:' k8s | wc -l`). - *Source*: vibes `patterns/zero-trust-sandboxing-and-observability.md`, `resources/k8s/agent-sandbox/network-policy.yaml`, `resources/observability/prometheus-agent-alerts.yaml` -- [ ] **Board-Owned Project Status, Declared Field Sources and Truthful Project Sync (P0 - Critical, Issue #703)**: +- [x] **Board-Owned Project Status, Declared Field Sources and Truthful Project Sync (P0 - Critical, Issue #703)**: - *Context & Rationale*: Docs say `devops gh project sync` pushes task-file status to the board (`src/devops_cli/lang/en/help.py:746-748`, `docs/MCP_TOOLS.md:852`, `docs/agent/tasks/README.md:13`), but `sync_remote_project` only counts task items (`src/devops_cli/github/projects.py:1485`). `project reconcile` recomputes Status, Priority, Category, Value and Effort every pass (`projects.py:1169-1225`), and `_filter_differing_fields` (`:1154`) overwrites differing board values, so hand corrections revert, breaking `AGENTS.md:61`. Status matches labels by substring with a Ready fallback (`:1004-1021`): `status/ready-to-merge` and `status/triage` both yield Ready, and no `.github/labels.yml` label yields Backlog. Category/Value/Effort come from `TAXONOMY_CATEGORY_MAPPING` (`:1046`) keyed on the `type/feature` label roadmap sync puts on every issue (`github/roadmap_sync.py:121`), not the ROADMAP matrix; `_derive_scope` (`:77`) keyword-matches, which `AGENTS.md:21` prohibits. Nothing records which branch decided, results are counts (`projects.py:1431-1432`), and a failed issue fetch returns `[]` (`github/issues.py:118-140`). vibes `tools/sdlc_project_manager.py` hit the same faults; `tools/portfolio_balance.py` `classify()` returns `(kind, source)`. - *Deliverable*: Measure first: `project reconcile --dry-run` lists each change with field, old and new value, and source, and `reconcile_project_custom_fields` returns that list (live runs need `read:project`). Then the board owns Status: reconcile writes it only when unset or when issue/PR state forces Done, In Review or In Progress; other moves belong to the built-in workflows `project workflows list` audits. Status labels match exactly; `status/blocked` maps only if the template gains Blocked; `CONST_PROJECT_WORKFLOW_EXPECTATIONS` expects the template's Backlog, not Todo. Reconcile never overwrites a non-empty Category/Value/Effort with an inferred value. Once a join key exists (a test that every scheduled matrix row joins its item, or a key column), sync stamps Value/Effort from the matrix and Category through a declared category map; until then it stays unset. Sync reports the `scope/cli` fallback share. Fetch failures raise, fetches paginate past 200, and reconcile refuses a missing template board instead of defaulting to board 2 (`src/devops_cli/commands/gh.py:613`). Rewrite the three `project sync` texts. Separate: suffix priority (R1-16's first PR), priority refresh in `issues reconcile-roadmap`, promotion (planned `devops gh pm deps`), Ready ordering (Sprint Kanban `sort_by`), the literal-subset lint (Anti-Brittle Constant Elimination). - *Constraint*: Making task files write Status creates a second owner fighting the board and `Closes #N`. A reconciler that overwrites Status reverts manual triage; one that skips closed or PR-backed items leaves merged work outside Done. An inferred field that keeps writing is worse than an unset one: the board presents it as decided. A raised fetch error must stay distinct from a successful empty list, or a new repository never syncs. diff --git a/docs/agent/tasks/README.md b/docs/agent/tasks/README.md index a045477574..f1b4ca1a3a 100644 --- a/docs/agent/tasks/README.md +++ b/docs/agent/tasks/README.md @@ -10,7 +10,7 @@ Historically, a monolithic `docs/agent/task.md` file was used for task tracking 2. **Decommissioned Monolithic Index**: Centralized task visualization, roadmap tracking, and sprint management are managed natively through GitHub Projects v2 (`https://github.com/dan-petty/devops-cli/projects`) and GitHub Issues views (`https://github.com/dan-petty/devops-cli/issues/views`). No central index markdown file is maintained. 3. **Commit Context Rule**: Updates to task tracking files **MUST ONLY** occur in the commit that delivers the feature or fix, written as the file should read once merged (`**Status**: Done`). Standalone task-tracking commits, including follow-ups that only add a pull request number, are strictly prohibited. 4. **Issue-Only Linking**: A task file links its GitHub issue and nothing else. The issue links the pull request that closes it (`Closes #`), and GitHub shows that pull request on the issue. Task files never carry a pull request number or a review state: the number is unknown until the pull request exists, so recording it takes a second commit that re-runs every check. -5. **Automated Project Synchronization**: `devops gh project sync` (and FastMCP `gh_project_sync`) natively inspects `docs/agent/tasks/` and synchronizes all task cards into GitHub Projects v2. +5. **Project Synchronization**: `devops gh project sync` (and FastMCP `gh_project_sync`) creates or updates the board from `.github/project-template.json`, adds the repository's open issues, and reconciles Status, Priority and Milestone from GitHub. It does not read task files: the board owns Status, and task files are the implementation record. --- @@ -65,7 +65,7 @@ A task file records one of four statuses. `tests/test_agent_task_files.py` enfor - **In Progress (WIP)**: Active work item currently being authored. If an early PR is opened to share work, it must be a Draft Pull Request (`--draft`). - **Done**: Written by the delivering pull request, which merges with the work and closes the issue. -Review is not a task-file status. A GitHub Projects v2 card shows **In Review** while the pull request that closes its issue is open and ready for review; `devops gh project sync` derives it from GitHub (`infer_item_status`). +Review is not a task-file status. A GitHub Projects v2 card shows **In Review** while the pull request that closes its issue is open and ready for review; `devops gh project sync` derives it from GitHub (`plan_item_changes`). --- diff --git a/docs/agent/tasks/task-703-board-owned-project-status-declared-field-sources-and-truthf.md b/docs/agent/tasks/task-703-board-owned-project-status-declared-field-sources-and-truthf.md index 219bb8f4af..a4917f337e 100644 --- a/docs/agent/tasks/task-703-board-owned-project-status-declared-field-sources-and-truthf.md +++ b/docs/agent/tasks/task-703-board-owned-project-status-declared-field-sources-and-truthf.md @@ -1,7 +1,7 @@ # Task 703: Board-Owned Project Status, Declared Field Sources and Truthful Project Sync **Issue**: [#703](https://github.com/dan-petty/devops-cli/issues/703) -**Status**: Backlog +**Status**: Done **Milestone**: `v0.2.24` **Priority**: `priority/p0-critical` **Scope**: `type/feature`, `scope/github`, `priority/p0-critical` @@ -20,3 +20,20 @@ Docs say `devops gh project sync` pushes task-file status to the board (`src/dev - Unit and integration test coverage with structural tuple equality assertions. - Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$. - 100% passing across Gated CI validation suite (`uv run devops ci`). + +## 2. Delivered + +- [x] `reconcile_project_custom_fields` returns `changes`: each field change with its item, old and new value, and the source that decided it (the planned changes in a dry run, the applied ones otherwise). `devops gh project reconcile` prints them as a table. +- [x] The board owns Status. `plan_item_changes` sets it only when unset (from an exact `status/*` label, otherwise Backlog) or when the item's state forces Done (closed issue, merged or closed pull request), In Review (open pull request, or an issue with a linked open pull request) or In Progress (draft pull request). +- [x] Status labels match exactly, so `status/ready-to-merge` and `status/triage` no longer read as Ready; `status/blocked` maps only when the board's template has a Blocked status. `CONST_PROJECT_WORKFLOW_EXPECTATIONS` expects Backlog, not Todo. +- [x] Priority only fills an unset field from its `priority/*` label. Category, Value and Effort are never inferred: no join key between the matrix and items exists, so they stay unset unless set by hand. The taxonomy and title-keyword mappings are removed. +- [x] Fetch failures raise `GitHubOperationError` instead of returning `[]` or `None`: the board items, repository issues and pull requests, and `get_repository_issues`, whose REST fallback now paginates. Roadmap sync, milestone reconciliation and release epics read every issue (`limit=None`) and no longer treat a failed read as an empty repository. +- [x] The issues fetch drops pull requests, which the pulls fetch supplies with their merge state, so each pull request is reconciled once. +- [x] `project reconcile` and `project workflows list` refuse to guess board #2 when no board matches the template. +- [x] `devops gh issues sync-roadmap` reports how many eligible items fell back to `scope/cli`. +- [x] The `project sync` help, the `gh_project_sync` and `gh_project_reconcile` MCP descriptions, `docs/agent/tasks/README.md` and the project-management knowledge base say what sync and reconcile do. + +## 3. Verification + +- `devops gh project reconcile --dry-run` against board #2 (read-only): would change 337 of 472 items, 480 field changes. Every change fills an unset field or forces a closed item to Done: Status unset to Done 212, unset to Backlog 81, unset to In Review 2, set to Done (closed) 42; Priority unset to a label's value 143. No set Status is moved for any other reason, and no Category, Value or Effort is written. Before dropping pull requests from the issues fetch, the same run counted 683 items, reconciling each pull request twice. +- The 15 test files that touch projects, issues, roadmap sync, release epics and the `gh` commands: 351 passed. diff --git a/docs/commands/gh.md b/docs/commands/gh.md index 388013f904..69e332136d 100644 --- a/docs/commands/gh.md +++ b/docs/commands/gh.md @@ -225,7 +225,7 @@ devops gh project status [OPTIONS] ### `devops gh project sync` -**Sync task items from docs/agent/tasks directory into GitHub Projects status.** +**Create or update the project board from its template, add open issues, and reconcile Status, Priority and Milestone; task files are not read.** ```bash devops gh project sync [OPTIONS] @@ -239,11 +239,11 @@ devops gh project sync [OPTIONS] | `--template`, `-t` | `path` | `.github/project-template.json` | Path to project template JSON | | `--repo`, `-R` | `string` | - | Target repository | | `--dry-run`, `--no-dry-run` | `boolean` | - | Preview task card items without remote mutations | -| `--reconcile-fields`, `--no-reconcile-fields` | `boolean` | `True` | Automatically infer and update project custom fields from taxonomy labels and issue state. | +| `--reconcile-fields`, `--no-reconcile-fields` | `boolean` | `True` | Also reconcile Status, Priority and Milestone from issue state and labels. | ### `devops gh project reconcile` -**Reconcile custom fields (Status, Priority, Category, Value, Effort) on project items.** +**Reconcile Status, Priority and Milestone on project items, listing each change and its source; the board owns Status.** ```bash devops gh project reconcile [OPTIONS] diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/github_project_management.md b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/github_project_management.md index 3ef38448cf..62198c5cb5 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/github_project_management.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/github_project_management.md @@ -149,9 +149,10 @@ devops gh milestones close v0.2.14 - `In Review`: Pull Request opened with automated review and CI checks running. - `Done`: PR squash-merged, remote CI checks green, and issue closed. - Run `devops gh project audit` and `devops gh views audit` to detect missing fields, invalid options, or misconfigured view filters. -5. **Data-Driven Custom Field Reconciliation (`devops gh project sync`)**: - - Enforce enrichment of all 6 custom project fields (`Status`, `Milestone`, `Priority`, `Category`, `Value`, `Effort`) for every issue and PR card. - - Reconcile project item custom fields using declarative taxonomy mappings (`infer_item_category_value_effort` mapping `type/*` and `priority/*` to strategic categories, business value, and engineering effort). +5. **Custom Field Reconciliation (`devops gh project sync`, `devops gh project reconcile`)**: + - The board owns Status: reconcile sets it only when it is unset (from an exact `status/*` label, otherwise Backlog) or when issue or pull request state forces Done, In Review or In Progress, so manual triage is never reverted. + - Priority fills an unset field from its `priority/*` label, and Milestone mirrors the issue's milestone. Category, Value and Effort are never inferred; they stay as set by hand. + - `devops gh project reconcile --dry-run` lists every change with its old and new value and the source that decided it. - Run `devops gh project sync` (or FastMCP `gh_project_sync`) after creating issues, pushing branches, or opening PRs to keep project views fully updated. 6. **Active Milestone Resource Population & Zero-Empty Queue/Projects Policy**: - When initializing a new release branch or activating a milestone, AI agents must proactively author GitHub tracking issues for every planned deliverable in `docs/ROADMAP.md`. diff --git a/src/devops_cli/ai/mcp/server.py b/src/devops_cli/ai/mcp/server.py index 29d49d1e35..9e7be67c36 100644 --- a/src/devops_cli/ai/mcp/server.py +++ b/src/devops_cli/ai/mcp/server.py @@ -1606,7 +1606,7 @@ def gh_milestone_edit( @mcp.tool() def gh_project_sync(repo: str | None = None, dry_run: bool = True) -> str: - """Synchronize task items from task tracking into GitHub Projects v2 status.""" + """Create or update the project board, add open issues, and reconcile Status, Priority and Milestone.""" cmd = ["uv", "run", "devops", "gh", "project", "sync"] if dry_run: cmd.append("--dry-run") @@ -1798,7 +1798,7 @@ def gh_project_reconcile( repo: str | None = None, dry_run: bool = False, ) -> str: - """Reconcile custom fields (Status, Priority, Category, Value, Effort) on GitHub Projects v2 items.""" + """Reconcile Status, Priority and Milestone on GitHub Projects v2 items, listing each change and its source.""" cmd = ["uv", "run", "devops", "gh", "project", "reconcile"] if project_number is not None: _validate_mcp_int_bound("project_number", project_number, min_val=1) diff --git a/src/devops_cli/commands/gh.py b/src/devops_cli/commands/gh.py index d819bc7c24..78ff8c3586 100644 --- a/src/devops_cli/commands/gh.py +++ b/src/devops_cli/commands/gh.py @@ -579,6 +579,25 @@ def sync_project( print_info(f"Local tasks parsed: {len(items)} items ({summary}).") +def _resolve_project_number(owner: str, target_repo: str, project_number: int | None) -> int: + """Return the board number given, or the template board's, never a guessed one.""" + if project_number: + return project_number + from devops_cli.github.projects import find_remote_project, load_project_template + + template = load_project_template() + matched = find_remote_project(owner, template.name, repo=target_repo) + if not matched and template.short_name: + matched = find_remote_project(owner, template.short_name, repo=target_repo) + if not matched or not matched.get("number"): + print_error( + f"No project board named '{template.name}' found for {owner}; " + "pass --project-number to choose one." + ) + raise typer.Exit(1) + return int(matched["number"]) + + @project_app.command("reconcile", help=HELP.gh.project_reconcile) def reconcile_project_cmd( project_number: Annotated[ @@ -595,24 +614,13 @@ def reconcile_project_cmd( typer.Option("--dry-run", help="Preview field reconciliation without mutations"), ] = False, ) -> None: - """Reconcile custom fields (Status, Priority, Category, Value, Effort, Milestone) on project items.""" - from devops_cli.github.projects import ( - find_remote_project, - load_project_template, - reconcile_project_custom_fields, - ) + """Reconcile Status, Priority and Milestone on project items, listing every change and its source.""" + from devops_cli.github.projects import reconcile_project_custom_fields target_repo = repo or _resolve_repo() owner = target_repo.split("/")[0] if "/" in target_repo else "@me" - proj_num = project_number - if not proj_num: - template = load_project_template() - matched = find_remote_project(owner, template.name, repo=target_repo) - if not matched and template.short_name: - matched = find_remote_project(owner, template.short_name, repo=target_repo) - proj_num = int(matched.get("number", 2)) if matched else 2 + proj_num = _resolve_project_number(owner, target_repo, project_number) - mode_text = "[yellow][DRY RUN][/yellow] " if dry_run else "" try: res = reconcile_project_custom_fields( owner=owner, @@ -621,13 +629,31 @@ def reconcile_project_cmd( dry_run=dry_run, state=state, ) - print_success( - f"{mode_text}Reconciled project #{proj_num} custom fields: " - f"{res['items_reconciled']}/{res['items_evaluated']} items updated." - ) except Exception as exc: print_error(f"Failed to reconcile project #{proj_num}: {exc}") - raise typer.Exit(1) + raise typer.Exit(1) from exc + + changes = res.get("changes", []) + if changes: + print_table( + f"Project #{proj_num} Field Changes", + ["Item", "Field", "Old", "New", "Source"], + [ + [ + "#" + str(c["url"]).rstrip("/").rsplit("/", 1)[-1], + c["field"], + c["old"] or "(unset)", + c["new"], + c["source"], + ] + for c in changes + ], + ) + verb = "[yellow][DRY RUN][/yellow] Would change" if dry_run else "Changed" + print_success( + f"{verb} {res['items_reconciled']} of {res['items_evaluated']} items on project " + f"#{proj_num} ({len(changes)} field changes)." + ) @project_app.command("link", help=HELP.gh.project_link) @@ -661,21 +687,11 @@ def list_project_workflows( json_output: Annotated[bool, typer.Option("--json", help=HELP.options.json_output)] = False, ) -> None: """List built-in project workflows, enabled statuses, and configuration links.""" - from devops_cli.github.projects import ( - find_remote_project, - load_project_template, - ) from devops_cli.output import write_stream target_repo = repo or _resolve_repo() owner = target_repo.split("/")[0] if "/" in target_repo else "@me" - proj_num = project_number - if not proj_num: - template = load_project_template() - matched = find_remote_project(owner, template.name, repo=target_repo) - if not matched and template.short_name: - matched = find_remote_project(owner, template.short_name, repo=target_repo) - proj_num = int(matched.get("number", 2)) if matched else 2 + proj_num = _resolve_project_number(owner, target_repo, project_number) workflows = get_project_workflows(proj_num, owner, repo=target_repo) if json_output: @@ -1319,6 +1335,10 @@ def issues_sync_roadmap_cmd( ["Already Tracked", str(result.already_tracked)], ["Issues Created", str(result.created_count)], ["Task Files Created", str(len(result.task_files_created))], + [ + "Scope Fell Back to scope/cli", + f"{result.scope_fallbacks} of {result.eligible_uncompleted}", + ], ] mode_str = " (Dry-Run)" if dry_run else "" print_table(f"Roadmap Issues Synchronization{mode_str} ({target_repo})", columns, rows) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 12048617ed..120a0ffe60 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2196,9 +2196,9 @@ # `deleteProjectV2Workflow` -- there is no mutation that enables or configures one -- so # these are reported as a gap against the live board rather than applied. CONST_PROJECT_WORKFLOW_EXPECTATIONS: Final[dict[str, str]] = { - "Item added to project": "Set Status to Todo", + "Item added to project": "Set Status to Backlog", "Item closed": "Set Status to Done", - "Item reopened": "Set Status to Todo", + "Item reopened": "Set Status to Backlog", "Pull request linked to issue": "Set Status to In Progress", "Pull request merged": "Set Status to Done", "Auto-close issue": "Close the issue when its linked pull request merges", diff --git a/src/devops_cli/github/issues.py b/src/devops_cli/github/issues.py index c6f74ed419..18d1671800 100644 --- a/src/devops_cli/github/issues.py +++ b/src/devops_cli/github/issues.py @@ -11,6 +11,7 @@ from devops_cli.config.constants import CONST_GH_CLI from devops_cli.exceptions.git import GitHubOperationError +from devops_cli.github.client import parse_paginated_json from devops_cli.github.rate_limiter import run_gh logger = logging.getLogger(__name__) @@ -98,19 +99,24 @@ def _parse_single_issue(item: dict[str, Any]) -> GitHubIssue: ) +# gh issue list pages through results up to --limit, so "every issue" is a limit above any +# repository's issue count rather than a separate code path. +_EVERY_ISSUE = 100_000 + + def _filter_rest_issues( - raw_list: list[Any], milestone: str | None, limit: int + raw_list: list[Any], milestone: str | None, limit: int | None ) -> list[GitHubIssue]: """Filter raw REST issue dictionaries into typed GitHubIssue objects.""" issues: list[GitHubIssue] = [] for item in raw_list: - if not isinstance(item, dict) or "pull_request" in item: + if not isinstance(item, dict) or "pull_request" in item or "number" not in item: continue parsed = _parse_single_issue(item) if milestone and parsed.milestone != milestone: continue issues.append(parsed) - if len(issues) >= limit: + if limit is not None and len(issues) >= limit: break return issues @@ -120,24 +126,24 @@ def _fetch_issues_rest( state: str = "open", milestone: str | None = None, labels: list[str] | None = None, - limit: int = 30, + limit: int | None = 30, ) -> list[GitHubIssue]: - """Retrieve issues via GitHub REST API when gh issue list encounters rate limits or errors.""" - api_path = f"repos/{repo}/issues?state={state}&per_page={min(max(limit, 1), 100)}" + """Retrieve every page of issues via the REST API when gh issue list fails. + + Raises when this read fails too, so a failure never looks like a repository with no issues. + """ + api_path = f"repos/{repo}/issues?state={state}&per_page=100" if labels: api_path += f"&labels={','.join(labels)}" - cmd = [CONST_GH_CLI, "api", api_path] - res = run_gh(cmd, check=False, quiet=True) - if res.returncode != 0 or not res.stdout.strip(): - return [] - try: - raw_list = json.loads(res.stdout) - if not isinstance(raw_list, list): - return [] - return _filter_rest_issues(raw_list, milestone, limit) - except Exception as exc: - logger.debug("Failed to parse REST issues: %s", exc) - return [] + res = run_gh([CONST_GH_CLI, "api", "--paginate", api_path], check=False, quiet=True) + if res.returncode != 0: + err_output = f"{res.stderr or ''} {res.stdout or ''}".strip() + raise GitHubOperationError( + f"Failed to read issues for {repo} (exit {res.returncode}): {err_output[:256]}", + operation="fetch_issues", + details={"repo": repo, "state": state}, + ) + return _filter_rest_issues(parse_paginated_json(res.stdout or ""), milestone, limit) def get_repository_issues( @@ -146,9 +152,9 @@ def get_repository_issues( milestone: str | None = None, label: str | None = None, labels: list[str] | None = None, - limit: int = 30, + limit: int | None = 30, ) -> list[GitHubIssue]: - """Retrieve issues from repository via gh issue list with REST fallback.""" + """Retrieve issues via gh issue list with a REST fallback; ``limit=None`` reads every issue.""" cmd = [ CONST_GH_CLI, "issue", @@ -158,7 +164,7 @@ def get_repository_issues( "--state", state, "--limit", - str(limit), + str(_EVERY_ISSUE if limit is None else limit), "--json", "number,title,state,milestone,labels,assignees,createdAt,updatedAt,url", ] diff --git a/src/devops_cli/github/projects.py b/src/devops_cli/github/projects.py index 67ba05335d..033a24e091 100644 --- a/src/devops_cli/github/projects.py +++ b/src/devops_cli/github/projects.py @@ -6,7 +6,7 @@ import logging import re import subprocess -from collections.abc import Mapping +from collections.abc import Collection, Mapping from pathlib import Path from typing import Any, cast @@ -129,7 +129,7 @@ def _determine_section_status(heading: str) -> str | None: """Map a task markdown section heading to a standardized project status. Task files carry no review state: a project card takes `In Review` from the pull request - that closes its issue (`infer_item_status`), never from the file. + that closes its issue (`plan_item_changes`), never from the file. """ clean = heading.lower().replace("-", " ") if "completed" in clean or "done" in clean: @@ -846,10 +846,11 @@ def _parse_project_items_json(stdout: str) -> dict[str, dict[str, str | None]]: return items_data -def _fetch_project_items_data( - owner: str, project_number: int -) -> dict[str, dict[str, str | None]] | None: - """Retrieve items and current custom field values from the project board.""" +def _fetch_project_items_data(owner: str, project_number: int) -> dict[str, dict[str, str | None]]: + """Retrieve items and current custom field values from the project board. + + Raises when the board cannot be read, so a failed read never looks like an empty board. + """ owner_arg = _resolve_project_owner_arg(owner) cmd = [ CONST_GH_CLI, @@ -880,29 +881,25 @@ def _fetch_project_items_data( proc = run_gh(fallback_cmd, check=False, quiet=True, use_cache=True, cache_ttl=60.0) if proc.returncode == 0: - if proc.stdout and proc.stdout.strip(): - return _parse_project_items_json(proc.stdout) - return {} + return _parse_project_items_json(proc.stdout or "") err_output = f"{proc.stderr or ''} {proc.stdout or ''}".strip() check_github_rate_limit_error(err_output, operation="fetch_project_items") - logger.warning( - "Failed to retrieve project item custom fields for project #%d (exit %d): %s", - project_number, - proc.returncode, - err_output[:256], + raise GitHubOperationError( + f"Failed to read project #{project_number} items (exit {proc.returncode}): {err_output[:256]}", + operation="fetch_project_items", + details={"project_number": project_number}, ) - return None -def _fetch_repository_issues(repo: str, state: str = "open") -> list[dict[str, Any]]: - """Retrieve candidate issues from the repository via GitHub API.""" +def _fetch_repository_list(repo: str, kind: str, state: str) -> list[dict[str, Any]]: + """Fetch every page of a repository's issues or pull requests, raising if GitHub can't be read.""" res = run_gh( [ CONST_GH_CLI, "api", "--paginate", - f"repos/{repo}/issues?state={state}&per_page=100", + f"repos/{repo}/{kind}?state={state}&per_page=100", "-H", "Accept: application/vnd.github+json", ], @@ -911,9 +908,24 @@ def _fetch_repository_issues(repo: str, state: str = "open") -> list[dict[str, A use_cache=True, cache_ttl=DEFAULT_GH_CACHE_TTL_SECONDS, ) - if res.returncode != 0 or not res.stdout: - return [] - return parse_paginated_json(res.stdout) + if res.returncode != 0: + err_output = f"{res.stderr or ''} {res.stdout or ''}".strip() + check_github_rate_limit_error(err_output, operation=f"fetch_{kind}") + raise GitHubOperationError( + f"Failed to read {kind} for {repo} (exit {res.returncode}): {err_output[:256]}", + operation=f"fetch_{kind}", + details={"repo": repo, "state": state}, + ) + return parse_paginated_json(res.stdout or "") + + +def _fetch_repository_issues(repo: str, state: str = "open") -> list[dict[str, Any]]: + """Retrieve candidate issues from the repository via GitHub API. + + The issues endpoint also returns pull requests, without their merge state; those come + from the pulls endpoint instead, so each pull request is reconciled once. + """ + return [it for it in _fetch_repository_list(repo, "issues", state) if "pull_request" not in it] def _add_project_item_with_fallback( @@ -968,7 +980,7 @@ def sync_repository_issues_to_project( mutation_budget = budget or MutationBudget(limit=DEFAULT_GH_MAX_PROJECT_MUTATIONS_PER_SYNC) owner_arg = _resolve_project_owner_arg(owner) - existing_items = _fetch_project_items_data(owner, project_number) or {} + existing_items = _fetch_project_items_data(owner, project_number) existing_urls = set(existing_items.keys()) issues = _fetch_repository_issues(repo, state=state) added = 0 @@ -985,147 +997,124 @@ def sync_repository_issues_to_project( return added -def infer_item_priority(labels: list[Any]) -> str: - """Infer GitHub Projects Priority field from issue/PR taxonomy labels.""" - names = [lbl.get("name", "") if isinstance(lbl, dict) else str(lbl) for lbl in labels] - for n in names: - n_lower = n.lower() - if "p0-critical" in n_lower: - return "P0-Critical" - if "p1-high" in n_lower: - return "P1-High" - if "p2-medium" in n_lower: - return "P2-Medium" - if "p3-low" in n_lower: - return "P3-Low" - return "P2-Medium" - - -_STATUS_LABEL_MAPPINGS: tuple[tuple[str, str], ...] = ( - ("status/blocked", "Blocked"), - ("status/in-review", "In Review"), - ("status/in-progress", "In Progress"), - ("status/ready", "Ready"), - ("status/backlog", "Backlog"), -) +class FieldChange(BaseModel): + """One board field change that reconcile plans or makes, and what decided it.""" + url: str + field: str + old: str | None + new: str + source: str -def _match_status_from_labels(labels: list[Any]) -> str: - """Match project status from taxonomy labels.""" - names = [lbl.get("name", "") if isinstance(lbl, dict) else str(lbl) for lbl in labels] - for n in names: - n_lower = n.lower() - for prefix, status in _STATUS_LABEL_MAPPINGS: - if prefix in n_lower: - return status - return "Ready" +# Labels match exactly: `status/ready-to-merge` is not `status/ready`. +_STATUS_LABELS: dict[str, str] = { + "status/backlog": "Backlog", + "status/ready": "Ready", + "status/in-progress": "In Progress", + "status/in-review": "In Review", + "status/blocked": "Blocked", +} +_PRIORITY_LABELS: dict[str, str] = { + "priority/p0-critical": "P0-Critical", + "priority/p1-high": "P1-High", + "priority/p2-medium": "P2-Medium", + "priority/p3-low": "P3-Low", +} +_DEFAULT_STATUS = "Backlog" -def infer_item_status( - state: str, - labels: list[Any], - is_pr: bool = False, - has_open_pr: bool = False, - is_draft: bool = False, -) -> str: - """Infer GitHub Projects Status field from state, PR presence, draft status, and taxonomy labels.""" - st_upper = state.upper() - if st_upper in ("CLOSED", "MERGED"): - return "Done" - # Open PRs and issues with active open PRs - if is_pr: - return "In Progress" if is_draft else "In Review" - - if has_open_pr: - return "In Review" +def _label_names(labels: list[Any]) -> list[str]: + """Return the lower-cased names of an item's labels.""" + return [ + str(lbl.get("name", "") if isinstance(lbl, dict) else lbl).lower() for lbl in labels or [] + ] - return _match_status_from_labels(labels) +def _forced_status(item: Mapping[str, Any], has_open_pr: bool) -> tuple[str, str] | None: + """Return the status an item's state forces, with its source, or None.""" + url = str(item.get("html_url") or item.get("url") or "") + is_pr = "/pull/" in url or "pull_request" in item + if str(item.get("state", "OPEN")).upper() in ("CLOSED", "MERGED"): + if not is_pr: + return "Done", "issue closed" + return "Done", "pull request merged" if item.get("merged_at") else "pull request closed" + if is_pr: + if item.get("draft"): + return "In Progress", "draft pull request" + return "In Review", "open pull request" + if has_open_pr: + return "In Review", "linked open pull request" + return None -TAXONOMY_CATEGORY_MAPPING: dict[str, tuple[str, str, str]] = { - "type/feature": ("Major Project", "High", "High"), - "type/security": ("Quick Win", "High", "Low"), - "type/bug": ("Quick Win", "High", "Low"), - "type/refactor": ("Foundation", "High", "Medium"), - "type/infra": ("Foundation", "High", "Medium"), - "type/test": ("Foundation", "Medium", "Medium"), - "type/docs": ("Fill-In", "Medium", "Low"), - "type/chore": ("Fill-In", "Low", "Low"), -} -PRIORITY_CATEGORY_MAPPING: dict[str, tuple[str, str, str]] = { - "P0-Critical": ("Quick Win", "High", "Low"), - "P1-High": ("Foundation", "High", "Medium"), - "P2-Medium": ("Fill-In", "Medium", "Medium"), - "P3-Low": ("Fill-In", "Low", "Low"), -} +def _initial_status(labels: list[Any], status_options: Collection[str]) -> tuple[str, str]: + """Return the status for an item whose Status is unset, with its source.""" + for name in _label_names(labels): + status = _STATUS_LABELS.get(name) + if status is not None and status in status_options: + return status, f"label {name}" + return _DEFAULT_STATUS, "default for an unset status" -def _match_taxonomy_labels(labels: list[Any], priority: str) -> tuple[str, str, str] | None: - """Classify Project Category, Value, Effort from issue/PR taxonomy labels.""" - label_names = [lbl.get("name", "") if isinstance(lbl, dict) else str(lbl) for lbl in labels] - for name in label_names: - n_lower = name.lower() - for type_key, mapping in TAXONOMY_CATEGORY_MAPPING.items(): - if type_key in n_lower: - if priority in ("P0-Critical", "P1-High") and "bug" in n_lower: - return "Quick Win", "High", "Low" - return mapping +def _declared_priority(labels: list[Any]) -> tuple[str, str] | None: + """Return the priority a priority label declares, with its source, or None.""" + for name in _label_names(labels): + priority = _PRIORITY_LABELS.get(name) + if priority is not None: + return priority, f"label {name}" return None -def infer_item_category_value_effort( - title: str, priority: str, labels: list[Any] | None = None -) -> tuple[str, str, str]: - """Infer Category, Value, and Effort for GitHub Projects v2 custom fields.""" - if labels: - matched = _match_taxonomy_labels(labels, priority) - if matched is not None: - return matched +def _milestone_title(item: Mapping[str, Any]) -> str | None: + """Return the title of an item's milestone, if it has one.""" + milestone = item.get("milestone") + if isinstance(milestone, dict): + return str(milestone.get("title") or "") or None + return str(milestone) if milestone else None - if priority == "P0-Critical": - return "Quick Win", "High", "Low" - - t = title.lower() - title_rules: list[tuple[tuple[str, ...], tuple[str, str, str]]] = [ - ( - ("tree-sitter", "ast graph", "observability", "loki", "daemon"), - ("Major Project", "High", "High"), - ), - (("fastmcp", "mcp", "prompt grounding", "contract"), ("Quick Win", "High", "Low")), - ( - ("vector", "store", "tier", "valkey", "ingest", "cache"), - ("Foundation", "High", "Medium"), - ), - (("drift", "auditor", "usage", "docs", "chore"), ("Fill-In", "Medium", "Medium")), - ] - for keywords, mapping in title_rules: - if any(k in t for k in keywords): - return mapping - return PRIORITY_CATEGORY_MAPPING.get(priority, ("Fill-In", "Medium", "Medium")) +def plan_item_changes( + item: Mapping[str, Any], + current: Mapping[str, str | None], + *, + has_open_pr: bool = False, + status_options: Collection[str] = (), +) -> list[FieldChange]: + """Plan one item's board field changes, each with the source that decided it. + + The board owns Status: it is set only when unset, or when the item's state forces Done, + In Review or In Progress, so a person's triage is never reverted. Priority only fills an + unset field, from a priority label. Category, Value and Effort are never inferred: an + inferred value the board shows as decided is worse than an unset one. + """ + labels = item.get("labels", []) + status = _forced_status(item, has_open_pr) + if status is None and not current.get("status"): + status = _initial_status(labels, status_options) + priority = None if current.get("priority") else _declared_priority(labels) + milestone = _milestone_title(item) + + targets = ( + ("Status", status), + ("Priority", priority), + ("Milestone", (milestone, "issue milestone") if milestone else None), + ) + url = str(item.get("html_url") or item.get("url") or "") + changes: list[FieldChange] = [] + for field_name, target in targets: + if target is None: + continue + new, source = target + old = current.get(field_name.lower()) or None + if old is None or old.strip().lower() != new.strip().lower(): + changes.append(FieldChange(url=url, field=field_name, old=old, new=new, source=source)) + return changes def _fetch_repository_prs(repo: str, state: str = "open") -> list[dict[str, Any]]: """Retrieve candidate PRs from the repository via GitHub API.""" - res = run_gh( - [ - CONST_GH_CLI, - "api", - "--paginate", - f"repos/{repo}/pulls?state={state}&per_page=100", - "-H", - "Accept: application/vnd.github+json", - ], - check=False, - quiet=True, - use_cache=True, - cache_ttl=DEFAULT_GH_CACHE_TTL_SECONDS, - ) - if res.returncode != 0 or not res.stdout: - return [] - return parse_paginated_json(res.stdout) + return _fetch_repository_list(repo, "pulls", state) def _edit_project_item_field( @@ -1151,21 +1140,6 @@ def _edit_project_item_field( return proc.returncode == 0 -def _filter_differing_fields( - current_fields: Mapping[str, str | None] | None, - target_fields: list[tuple[str, str]], -) -> list[tuple[str, str]]: - """Return only target fields whose values differ from current remote values.""" - if current_fields is None: - return list(target_fields) - differing: list[tuple[str, str]] = [] - for fname, fval in target_fields: - curr = current_fields.get(fname.lower()) - if curr is None or curr.strip().lower() != fval.strip().lower(): - differing.append((fname, fval)) - return differing - - def _reconcile_single_item( owner: str, project_number: int, @@ -1174,78 +1148,47 @@ def _reconcile_single_item( has_open_pr: bool = False, current_fields: Mapping[str, str | None] | None = None, budget: MutationBudget | None = None, -) -> bool: - """Infer and apply custom fields to a project item only if values differ from remote state.""" - url = item.get("html_url") or item.get("url") or "" - if not url: - return False - title = item.get("title", "") - state = str(item.get("state", "OPEN")) - labels = item.get("labels", []) + status_options: Collection[str] = (), +) -> list[FieldChange]: + """Plan an item's field changes and, unless dry-running, apply them. - is_pr = "/pull/" in url or "pull_request" in item - is_draft = bool(item.get("draft", False)) - priority = infer_item_priority(labels) - status = infer_item_status( - state, labels, is_pr=is_pr, has_open_pr=has_open_pr, is_draft=is_draft - ) - category, val, eff = infer_item_category_value_effort(title, priority, labels=labels) - milestone_obj = item.get("milestone") - milestone_val = ( - milestone_obj.get("title") - if isinstance(milestone_obj, dict) - else (str(milestone_obj) if milestone_obj else None) - ) - - target_fields: list[tuple[str, str]] = [ - ("Status", status), - ("Priority", priority), - ("Category", category), - ("Value", val), - ("Effort", eff), - ] - if milestone_val: - target_fields.append(("Milestone", str(milestone_val))) - - fields_to_update = _filter_differing_fields( - current_fields=current_fields, - target_fields=target_fields, - ) - - if not fields_to_update: - return False - - if dry_run: - return True - - return _apply_field_updates( - owner, project_number, url, fields_to_update, current_fields, budget=budget + Returns the planned changes in a dry run, and the changes actually applied otherwise. + """ + if not (item.get("html_url") or item.get("url")): + return [] + changes = plan_item_changes( + item, + current_fields or {}, + has_open_pr=has_open_pr, + status_options=status_options, ) + if dry_run or not changes: + return changes + return _apply_field_updates(owner, project_number, changes, current_fields, budget=budget) def _apply_field_updates( owner: str, project_number: int, - url: str, - fields_to_update: list[tuple[str, str]], + changes: list[FieldChange], current_fields: Mapping[str, str | None] | None, budget: MutationBudget | None = None, -) -> bool: - """Apply field updates via gh project CLI, breaking early if quota exhausted.""" - updated_any = False - for fname, fval in fields_to_update: +) -> list[FieldChange]: + """Apply field changes via gh project CLI, stopping early if quota runs out.""" + applied: list[FieldChange] = [] + for change in changes: if (budget is not None and budget.is_exhausted) or _is_graphql_quota_exhausted(): logger.warning( "GraphQL quota critically low or reached mutation budget. Halting field update." ) break - if _edit_project_item_field(owner, project_number, url, fname, fval): - updated_any = True + if _edit_project_item_field(owner, project_number, change.url, change.field, change.new): + applied.append(change) if budget is not None: budget.record_mutation() if isinstance(current_fields, dict): - current_fields[fname.lower()] = fval - return updated_any + current_fields[change.field.lower()] = change.new + return applied def _extract_linked_issue_numbers(prs: list[dict[str, Any]]) -> set[int]: @@ -1337,28 +1280,34 @@ def _reconcile_candidate_items( open_pr_issue_numbers: set[int], dry_run: bool, budget: MutationBudget | None = None, -) -> int: - """Iterate over candidates and reconcile custom fields where values differ.""" - reconciled_count = 0 + status_options: Collection[str] = (), +) -> list[FieldChange]: + """Reconcile each candidate's fields, returning every change planned or applied.""" + changes: list[FieldChange] = [] for it in candidates: if not _can_continue_reconciliation(dry_run, budget=budget): break url = it.get("html_url") or it.get("url") or "" if dry_run and url not in items_data: continue - it_num = int(it.get("number", 0)) - current = items_data.get(url) - if _reconcile_single_item( - owner, - project_number, - it, - dry_run, - has_open_pr=(it_num in open_pr_issue_numbers), - current_fields=current, - budget=budget, - ): - reconciled_count += 1 - return reconciled_count + changes.extend( + _reconcile_single_item( + owner, + project_number, + it, + dry_run, + has_open_pr=(int(it.get("number", 0)) in open_pr_issue_numbers), + current_fields=items_data.get(url), + budget=budget, + status_options=status_options, + ) + ) + return changes + + +def _status_options(template: ProjectTemplate) -> list[str]: + """Return the Status options a project template declares.""" + return [opt.name for fld in template.fields if fld.name == "Status" for opt in fld.options] def reconcile_project_custom_fields( @@ -1368,41 +1317,35 @@ def reconcile_project_custom_fields( dry_run: bool = False, state: str = "open", budget: MutationBudget | None = None, + template: ProjectTemplate | None = None, ) -> dict[str, Any]: - """Reconcile custom field values (Status, Priority, Category, Value, Effort) on project items.""" + """Reconcile Status, Priority and Milestone on project items, listing every change. + + The result's ``changes`` holds each field change with its old and new value and the + source that decided it: the planned changes in a dry run, the applied ones otherwise. + """ + result: dict[str, Any] = { + "project_number": project_number, + "owner": owner, + "repo": repo, + "items_evaluated": 0, + "items_reconciled": 0, + "dry_run": dry_run, + "changes": [], + } if _is_graphql_quota_exhausted(): logger.warning( "GraphQL quota critically low or unknown. Skipping project custom field reconciliation." ) - return { - "project_number": project_number, - "owner": owner, - "repo": repo, - "items_evaluated": 0, - "items_reconciled": 0, - "dry_run": dry_run, - } - - items_data = _fetch_project_items_data(owner, project_number) - if items_data is None and not dry_run: - logger.warning("Failed to fetch project data. Skipping mutations.") - return { - "project_number": project_number, - "owner": owner, - "repo": repo, - "items_evaluated": 0, - "items_reconciled": 0, - "dry_run": dry_run, - } + return result + status_options = _status_options(template or load_project_template()) + active_items = _fetch_project_items_data(owner, project_number) mutation_budget = budget or MutationBudget(limit=DEFAULT_GH_MAX_PROJECT_MUTATIONS_PER_SYNC) issues = _fetch_repository_issues(repo, state=state) prs = _fetch_repository_prs(repo, state=state) candidates = issues + prs - open_pr_issue_numbers = _extract_linked_issue_numbers(prs) - active_items = items_data or {} - if not dry_run: _provision_missing_candidates( owner, project_number, candidates, active_items, budget=mutation_budget @@ -1413,25 +1356,22 @@ def reconcile_project_custom_fields( if dry_run else candidates ) - - reconciled_count = _reconcile_candidate_items( + changes = _reconcile_candidate_items( owner, project_number, eval_candidates, active_items, - open_pr_issue_numbers, + _extract_linked_issue_numbers(prs), dry_run, budget=mutation_budget, + status_options=status_options, ) - - return { - "project_number": project_number, - "owner": owner, - "repo": repo, - "items_evaluated": len(eval_candidates), - "items_reconciled": reconciled_count, - "dry_run": dry_run, - } + result.update( + items_evaluated=len(eval_candidates), + items_reconciled=len({change.url for change in changes}), + changes=[change.model_dump() for change in changes], + ) + return result def sync_remote_project( @@ -1473,7 +1413,7 @@ def sync_remote_project( ) if reconcile_fields: reconcile_project_custom_fields( - owner, repo, proj_num, dry_run=False, budget=mutation_budget + owner, repo, proj_num, dry_run=False, budget=mutation_budget, template=template ) return ProjectSyncResult( diff --git a/src/devops_cli/github/release_epics.py b/src/devops_cli/github/release_epics.py index 6839dc7420..10f97f4649 100644 --- a/src/devops_cli/github/release_epics.py +++ b/src/devops_cli/github/release_epics.py @@ -309,11 +309,8 @@ def sync_all_release_epics( version_filter: str | None = None, ) -> ReleaseEpicSyncResult: """Synchronize release tracking epics for roadmap milestones.""" - try: - issues = get_repository_issues(repo, state="all", limit=300) - except Exception as exc: - logger.warning("Failed to fetch repository issues: %s", exc) - issues = [] + # A failed read raises: treating it as "no issues" would create every epic again. + issues = get_repository_issues(repo, state="all", limit=None) specs = build_release_epic_specs(roadmap_path, issues) if version_filter: diff --git a/src/devops_cli/github/roadmap_sync.py b/src/devops_cli/github/roadmap_sync.py index 9a97dc4883..362e6d70de 100644 --- a/src/devops_cli/github/roadmap_sync.py +++ b/src/devops_cli/github/roadmap_sync.py @@ -51,6 +51,7 @@ class RoadmapItem(BaseModel): title: str priority: str = "priority/p1-high" scope: str = "scope/cli" + scope_is_fallback: bool = False labels: list[str] = Field(default_factory=list) context: str = "" sub_bullets: list[str] = Field(default_factory=list) @@ -74,6 +75,8 @@ class RoadmapSyncResult(BaseModel): dry_run: bool = False created_issues: list[dict[str, Any]] = Field(default_factory=list) task_files_created: list[str] = Field(default_factory=list) + # Eligible items whose scope no keyword decided, so they fell back to scope/cli. + scope_fallbacks: int = 0 def _extract_priority(item_header: str) -> str: @@ -87,14 +90,19 @@ def _extract_priority(item_header: str) -> str: return CONST_ROADMAP_PRIORITY_LABELS[match["level"]] if match else "priority/p1-high" -def _derive_scope(title: str) -> str: - """Derive standard scope taxonomy label from item title.""" +def _matched_scope(title: str) -> str | None: + """Return the scope label a keyword in the item title decides, or None.""" lower = title.lower() words = set(re.findall(r"\b[a-z0-9_-]+\b", lower)) for scope, keywords in CONST_ROADMAP_SCOPE_KEYWORDS.items(): if words & keywords: return scope - return "scope/cli" + return None + + +def _derive_scope(title: str) -> str: + """Derive standard scope taxonomy label from item title, falling back to scope/cli.""" + return _matched_scope(title) or "scope/cli" def _extract_existing_issue_number(title: str) -> int | None: @@ -128,7 +136,8 @@ def _parse_single_roadmap_item( clean_title = _clean_item_title(raw_title) priority = _extract_priority(item_header) - scope = _derive_scope(clean_title) + matched_scope = _matched_scope(clean_title) + scope = matched_scope or "scope/cli" issue_num = _extract_existing_issue_number(item_header) labels = ["type/feature", scope, priority] @@ -151,6 +160,7 @@ def _parse_single_roadmap_item( title=clean_title, priority=priority, scope=scope, + scope_is_fallback=matched_scope is None, labels=labels, context=context, sub_bullets=sub_bullets, @@ -419,19 +429,14 @@ def sync_roadmap_to_issues( if milestone_filter: uncompleted = [i for i in uncompleted if i.milestone == milestone_filter] - try: - existing_issues = get_repository_issues(repo, state="all", limit=200) - except Exception as exc: - logger.warning( - "Failed to retrieve existing GitHub issues for deduplication (treating as empty): %s", - exc, - ) - existing_issues = [] + # A failed read raises: treating it as "no issues" would file every item again. + existing_issues = get_repository_issues(repo, state="all", limit=None) result = RoadmapSyncResult( total_roadmap_items=len(all_items), eligible_uncompleted=len(uncompleted), dry_run=dry_run, + scope_fallbacks=sum(1 for item in uncompleted if item.scope_is_fallback), ) for item in uncompleted: @@ -535,11 +540,7 @@ def reconcile_issue_milestones_from_roadmap( ) -> IssueMilestoneReconcileResult: """Reconcile repository issue milestones and local task files to match docs/ROADMAP.md declarations.""" all_items = extract_roadmap_items(roadmap_path) - try: - existing_issues = get_repository_issues(repo, state="all", limit=200) - except Exception as exc: - logger.warning("Failed to retrieve existing GitHub issues: %s", exc) - existing_issues = [] + existing_issues = get_repository_issues(repo, state="all", limit=None) result = IssueMilestoneReconcileResult( total_roadmap_items=len(all_items), diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index c131c74a12..125cdba82e 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -761,13 +761,15 @@ class GHCommandHelp: project_list: str = "List available GitHub Projects v2 boards for user or organization." project_status: str = "Inspect project template structure and configured views." project_sync: str = ( - "Sync task items from docs/agent/tasks directory into GitHub Projects status." + "Create or update the project board from its template, add open issues, and reconcile " + "Status, Priority and Milestone; task files are not read." ) project_reconcile: str = ( - "Reconcile custom fields (Status, Priority, Category, Value, Effort) on project items." + "Reconcile Status, Priority and Milestone on project items, listing each change and " + "its source; the board owns Status." ) reconcile_fields: str = ( - "Automatically infer and update project custom fields from taxonomy labels and issue state." + "Also reconcile Status, Priority and Milestone from issue state and labels." ) project_link: str = "Link a GitHub Project v2 board to the repository." project_audit: str = "Audit project board items and fields against local tasks and template." diff --git a/tests/test_gh_cmd.py b/tests/test_gh_cmd.py index eaa6268d0b..d08f3fdb5a 100644 --- a/tests/test_gh_cmd.py +++ b/tests/test_gh_cmd.py @@ -302,23 +302,57 @@ def test_gh_views_audit() -> None: def test_gh_project_reconcile() -> None: - """devops gh project reconcile triggers field reconciliation.""" + """devops gh project reconcile lists every field change with what decided it.""" mock_res = { "project_number": 2, "items_evaluated": 10, - "items_reconciled": 8, - "dry_run": False, + "items_reconciled": 1, + "dry_run": True, + "changes": [ + { + "url": "https://github.com/dan-petty/devops-cli/issues/7", + "field": "Status", + "old": None, + "new": "Backlog", + "source": "default for an unset status", + } + ], } with patch( "devops_cli.github.projects.reconcile_project_custom_fields", return_value=mock_res, ): result = runner.invoke( - app, ["project", "reconcile", "--project-number", "2", "--repo", "dan-petty/devops-cli"] + app, + [ + "project", + "reconcile", + "--project-number", + "2", + "--repo", + "dan-petty/devops-cli", + "--dry-run", + ], ) - assert result.exit_code == 0 - assert "Reconciled project #2" in result.output - assert "8/10 items updated" in result.output + assert ( + result.exit_code, + "default for an unset status" in result.output, + "1 of 10 items" in result.output, + ) == (0, True, True) + + +def test_gh_project_reconcile_refuses_a_missing_board() -> None: + """Without a matching board, reconcile must not guess a board number.""" + with ( + patch("devops_cli.github.projects.find_remote_project", return_value=None), + patch("devops_cli.github.projects.reconcile_project_custom_fields") as mock_reconcile, + ): + result = runner.invoke(app, ["project", "reconcile", "--repo", "dan-petty/devops-cli"]) + assert (result.exit_code, mock_reconcile.called, "--project-number" in result.output) == ( + 1, + False, + True, + ) def test_gh_pr_threads_alias() -> None: diff --git a/tests/test_gh_issues_milestones.py b/tests/test_gh_issues_milestones.py index 6197cdd2fb..dc31ce0005 100644 --- a/tests/test_gh_issues_milestones.py +++ b/tests/test_gh_issues_milestones.py @@ -353,7 +353,7 @@ def test_cli_gh_issues_reconcile_roadmap() -> None: def test_project_custom_field_milestone_reconciliation() -> None: - """_reconcile_single_item detects when Project item Milestone field differs from target.""" + """_reconcile_single_item plans a Milestone change when the board's copy differs.""" item = { "url": "https://github.com/example/repo/issues/1", "title": "Test Issue", @@ -362,21 +362,21 @@ def test_project_custom_field_milestone_reconciliation() -> None: "milestone": {"title": "v0.2.21"}, } current_fields: dict[str, str | None] = { - "Status": "Backlog", - "Priority": "P1 - High", - "Category": "CLI", - "Value": "High", - "Effort": "Medium", - "Milestone": "v0.2.20", + "status": "Backlog", + "priority": "P1-High", + "category": "CLI", + "value": "High", + "effort": "Medium", + "milestone": "v0.2.20", } - should_update = _reconcile_single_item( + changes = _reconcile_single_item( owner="example", project_number=2, item=item, dry_run=True, current_fields=current_fields, ) - assert should_update is True + assert [(c.field, c.old, c.new) for c in changes] == [("Milestone", "v0.2.20", "v0.2.21")] def test_fastmcp_gh_tools() -> None: diff --git a/tests/test_github_issues.py b/tests/test_github_issues.py index 11dd52e4be..6ef0db623d 100644 --- a/tests/test_github_issues.py +++ b/tests/test_github_issues.py @@ -272,12 +272,16 @@ def test_fetch_issues_rest_filtering_and_limits() -> None: def test_fetch_issues_rest_errors_and_invalid_json() -> None: - """Verify _fetch_issues_rest returns empty list on subprocess error or bad JSON.""" + """A failed read raises; output holding no issues reads as none.""" + from devops_cli.exceptions.git import GitHubOperationError from devops_cli.github.issues import _fetch_issues_rest mock_fail = MagicMock(returncode=1, stdout="", stderr="Error") - with patch("devops_cli.github.issues.run_gh", return_value=mock_fail): - assert _fetch_issues_rest("dan-petty/devops-cli") == [] + with ( + patch("devops_cli.github.issues.run_gh", return_value=mock_fail), + pytest.raises(GitHubOperationError), + ): + _fetch_issues_rest("dan-petty/devops-cli") mock_bad_json = MagicMock(returncode=0, stdout="not-json", stderr="") with patch("devops_cli.github.issues.run_gh", return_value=mock_bad_json): diff --git a/tests/test_github_projects.py b/tests/test_github_projects.py index c1be9dd856..df2648c038 100644 --- a/tests/test_github_projects.py +++ b/tests/test_github_projects.py @@ -863,41 +863,6 @@ def test_paginated_project_fetch_helpers() -> None: assert prs[1]["number"] == 4 -def test_filter_differing_fields() -> None: - """_filter_differing_fields excludes fields that already match remote values.""" - from devops_cli.github.projects import _filter_differing_fields - - targets = [ - ("Status", "Done"), - ("Priority", "P1-High"), - ("Category", "Foundation"), - ("Value", "High"), - ("Effort", "Medium"), - ] - # If no current_fields provided, all targets returned - assert _filter_differing_fields(None, targets) == targets - - # If all match (case-insensitive), returns empty list - current_matching = { - "status": "Done", - "priority": "p1-high", - "category": "Foundation", - "value": "High", - "effort": "Medium", - } - assert _filter_differing_fields(current_matching, targets) == [] - - # If only Status differs, returns only Status - current_status_drift = { - "status": "In Progress", - "priority": "P1-High", - "category": "Foundation", - "value": "High", - "effort": "Medium", - } - assert _filter_differing_fields(current_status_drift, targets) == [("Status", "Done")] - - def test_reconcile_single_item_skips_matching_fields() -> None: """_reconcile_single_item makes zero edit calls if fields already match remote state.""" from unittest.mock import patch @@ -921,15 +886,15 @@ def test_reconcile_single_item_skips_matching_fields() -> None: reconciled = _reconcile_single_item( "owner", 2, item, dry_run=False, current_fields=current_matching ) - assert reconciled is False + assert reconciled == [] mock_edit.assert_not_called() def test_reconcile_single_item_edits_only_drifted_fields() -> None: - """_reconcile_single_item only invokes _edit_project_item_field for drifted fields.""" + """_reconcile_single_item edits only fields that need it; a set Priority stands.""" from unittest.mock import patch - from devops_cli.github.projects import _reconcile_single_item + from devops_cli.github.projects import FieldChange, _reconcile_single_item item = { "html_url": "https://example.com/owner/repo/issues/10", @@ -937,9 +902,9 @@ def test_reconcile_single_item_edits_only_drifted_fields() -> None: "state": "CLOSED", "labels": [{"name": "priority/p1-high"}, {"name": "type/feature"}], } - # Priority is P2-Medium remotely, but label says P1-High + # The issue closed, so Status is forced to Done; the board's P2 priority is a person's call. current_with_drift = { - "status": "Done", + "status": "In Progress", "priority": "P2-Medium", "category": "Major Project", "value": "High", @@ -954,12 +919,19 @@ def test_reconcile_single_item_edits_only_drifted_fields() -> None: reconciled = _reconcile_single_item( "owner", 2, item, dry_run=False, current_fields=current_with_drift ) - assert reconciled is True - assert mock_edit.call_count == 1 - call_args = mock_edit.call_args[0] - assert call_args[3] == "Priority" - assert call_args[4] == "P1-High" - assert current_with_drift["priority"] == "P1-High" + assert (reconciled, mock_edit.call_args[0][3:], current_with_drift["status"]) == ( + [ + FieldChange( + url="https://example.com/owner/repo/issues/10", + field="Status", + old="In Progress", + new="Done", + source="issue closed", + ) + ], + ("Status", "Done"), + "Done", + ) def test_extract_item_fields_case_insensitive() -> None: @@ -1043,11 +1015,16 @@ def test_apply_field_updates_respects_mutation_budget() -> None: """_apply_field_updates stops editing fields once mutation budget is exhausted.""" from unittest.mock import patch - from devops_cli.github.projects import MutationBudget, _apply_field_updates + from devops_cli.github.projects import FieldChange, MutationBudget, _apply_field_updates budget = MutationBudget(limit=2) - fields = [("Status", "Done"), ("Priority", "P1-High"), ("Category", "Quick Win")] - current = {"status": "Todo", "priority": "P2-Medium", "category": "Foundation"} + url = "https://example.com/1" + changes = [ + FieldChange(url=url, field="Status", old="Backlog", new="Done", source="issue closed"), + FieldChange(url=url, field="Priority", old=None, new="P1-High", source="label"), + FieldChange(url=url, field="Milestone", old=None, new="v1", source="issue milestone"), + ] + current = {"status": "Backlog", "priority": None, "milestone": None} with ( patch("devops_cli.github.projects._is_graphql_quota_exhausted", return_value=False), @@ -1055,11 +1032,9 @@ def test_apply_field_updates_respects_mutation_budget() -> None: "devops_cli.github.projects._edit_project_item_field", return_value=True ) as mock_edit, ): - updated = _apply_field_updates( - "owner", 1, "https://example.com/1", fields, current, budget=budget - ) - assert (updated, mock_edit.call_count, budget.total_mutations, budget.is_exhausted) == ( - True, + applied = _apply_field_updates("owner", 1, changes, current, budget=budget) + assert (applied, mock_edit.call_count, budget.total_mutations, budget.is_exhausted) == ( + changes[:2], 2, 2, True, @@ -1111,4 +1086,4 @@ def test_provision_and_reconcile_share_mutation_budget() -> None: reconciled = _reconcile_candidate_items( "owner", 1, candidates, items_data, set(), dry_run=False, budget=budget ) - assert (reconciled, mock_edit.call_count) == (0, 0) + assert (reconciled, mock_edit.call_count) == ([], 0) diff --git a/tests/test_github_projects_reconcile.py b/tests/test_github_projects_reconcile.py index ba3d7c8588..336b64acf8 100644 --- a/tests/test_github_projects_reconcile.py +++ b/tests/test_github_projects_reconcile.py @@ -5,95 +5,130 @@ import json from unittest.mock import MagicMock, patch +import pytest + +from devops_cli.exceptions.git import GitHubOperationError from devops_cli.github.projects import ( - infer_item_category_value_effort, - infer_item_priority, - infer_item_status, + FieldChange, + plan_item_changes, reconcile_project_custom_fields, ) +_URL = "https://github.com/owner/repo/issues/7" +_STATUSES = ("Backlog", "Ready", "In Progress", "In Review", "Done") + + +def _issue( + state: str = "OPEN", labels: list[str] | None = None, **extra: object +) -> dict[str, object]: + return { + "html_url": _URL, + "state": state, + "labels": [{"name": n} for n in labels or []], + **extra, + } + -def test_infer_item_priority() -> None: - assert infer_item_priority(["priority/p0-critical", "type/bug"]) == "P0-Critical" - assert infer_item_priority([{"name": "priority/p1-high"}]) == "P1-High" - assert infer_item_priority(["priority/p2-medium"]) == "P2-Medium" - assert infer_item_priority(["priority/p3-low"]) == "P3-Low" - assert infer_item_priority([]) == "P2-Medium" - - -def test_infer_item_status() -> None: - results = ( - infer_item_status("CLOSED", []), - infer_item_status("MERGED", []), - infer_item_status("OPEN", ["status/in-progress"]), - infer_item_status("OPEN", [{"name": "status/in-review"}]), - infer_item_status("OPEN", ["status/ready"]), - infer_item_status("OPEN", ["status/blocked"]), - infer_item_status("OPEN", ["status/backlog"]), - infer_item_status("OPEN", [], is_pr=True), - infer_item_status("OPEN", [], is_pr=True, is_draft=True), - infer_item_status("OPEN", [], is_pr=True, is_draft=False), - infer_item_status("OPEN", [], has_open_pr=True), - infer_item_status("OPEN", []), +def _changes( + item: dict[str, object], + current: dict[str, str | None] | None = None, + **kwargs: object, +) -> list[tuple[str, str | None, str, str]]: + planned = plan_item_changes(item, current or {}, status_options=_STATUSES, **kwargs) # type: ignore[arg-type] + return [(c.field, c.old, c.new, c.source) for c in planned] + + +def test_a_set_status_is_left_alone_when_nothing_forces_it() -> None: + """The board owns Status; a label must not revert a person's triage.""" + assert _changes(_issue(labels=["status/in-progress"]), {"status": "Ready"}) == [] + + +def test_an_unset_status_comes_from_an_exact_status_label() -> None: + assert _changes(_issue(labels=["status/in-progress"])) == [ + ("Status", None, "In Progress", "label status/in-progress") + ] + + +def test_a_status_label_only_matches_exactly() -> None: + """`status/ready-to-merge` and `status/triage` are not `status/ready`.""" + assert _changes(_issue(labels=["status/ready-to-merge", "status/triage"])) == [ + ("Status", None, "Backlog", "default for an unset status") + ] + + +def test_blocked_maps_only_when_the_board_has_a_blocked_status() -> None: + with_blocked = plan_item_changes( + _issue(labels=["status/blocked"]), {}, status_options=(*_STATUSES, "Blocked") ) - expected = ( - "Done", - "Done", - "In Progress", - "In Review", - "Ready", - "Blocked", - "Backlog", - "In Review", - "In Progress", - "In Review", - "In Review", - "Ready", + assert ( + _changes(_issue(labels=["status/blocked"])), + [(c.field, c.new) for c in with_blocked], + ) == ( + [("Status", None, "Backlog", "default for an unset status")], + [("Status", "Blocked")], ) - assert results == expected -def test_infer_item_category_value_effort() -> None: - cat, val, eff = infer_item_category_value_effort("Tree-sitter AST parser", "P1-High") - assert cat == "Major Project" - assert val == "High" - assert eff == "High" +def test_a_closed_issue_is_forced_to_done() -> None: + assert _changes(_issue(state="CLOSED"), {"status": "In Progress"}) == [ + ("Status", "In Progress", "Done", "issue closed") + ] - cat, val, eff = infer_item_category_value_effort("FastMCP Library Tools", "P0-Critical") - assert cat == "Quick Win" - assert val == "High" - assert eff == "Low" - cat, val, eff = infer_item_category_value_effort("Library Vector Store and Cache", "P1-High") - assert cat == "Foundation" - assert val == "High" - assert eff == "Medium" +def test_an_open_pull_request_is_forced_into_review_and_a_draft_into_progress() -> None: + pr_url = "https://github.com/owner/repo/pull/9" + ready = {"html_url": pr_url, "state": "open", "labels": [], "pull_request": {}} + draft = {**ready, "draft": True} + assert ( + _changes(ready, {"status": "Backlog"}), + _changes(draft, {"status": "Backlog"}), + ) == ( + [("Status", "Backlog", "In Review", "open pull request")], + [("Status", "Backlog", "In Progress", "draft pull request")], + ) -def test_infer_item_category_value_effort_from_labels() -> None: - # type/security -> Quick Win, High, Low - cat, val, eff = infer_item_category_value_effort( - "Custom Secret Tool", "P2-Medium", labels=["type/security"] - ) - assert cat == "Quick Win" - assert val == "High" - assert eff == "Low" +def test_an_issue_with_an_open_linked_pull_request_is_forced_into_review() -> None: + assert _changes(_issue(), {"status": "Ready"}, has_open_pr=True) == [ + ("Status", "Ready", "In Review", "linked open pull request") + ] - # type/docs -> Fill-In, Medium, Low - cat, val, eff = infer_item_category_value_effort( - "Update User Manual", "P2-Medium", labels=["type/docs"] + +def test_priority_is_set_from_its_label_only_when_unset() -> None: + labelled = _issue(labels=["priority/p1-high"]) + assert ( + _changes(labelled, {"status": "Ready"}), + _changes(labelled, {"status": "Ready", "priority": "P3-Low"}), + _changes(_issue(), {"status": "Ready"}), + ) == ( + [("Priority", None, "P1-High", "label priority/p1-high")], + [], + [], ) - assert cat == "Fill-In" - assert val == "Medium" - assert eff == "Low" - # type/feature -> Major Project, High, High - cat, val, eff = infer_item_category_value_effort( - "Polyglot Engine", "P1-High", labels=[{"name": "type/feature"}] + +def test_a_matching_value_is_not_rewritten_whatever_its_case() -> None: + assert _changes(_issue(state="CLOSED"), {"status": "done"}) == [] + + +def test_category_value_and_effort_are_never_inferred() -> None: + """An inferred field that keeps writing reads as decided; unset is honest.""" + fields = [c[0] for c in _changes(_issue(labels=["type/feature", "priority/p0-critical"]))] + assert {"Category", "Value", "Effort"} & set(fields) == set() + + +def test_the_milestone_field_mirrors_the_issue_milestone() -> None: + item = _issue(milestone={"title": "v0.2.24"}) + assert _changes(item, {"status": "Ready", "milestone": "v0.2.23"}) == [ + ("Milestone", "v0.2.23", "v0.2.24", "issue milestone") + ] + + +def test_a_field_change_records_the_item_it_belongs_to() -> None: + change = plan_item_changes(_issue(state="CLOSED"), {}, status_options=_STATUSES)[0] + assert change == FieldChange( + url=_URL, field="Status", old=None, new="Done", source="issue closed" ) - assert cat == "Major Project" - assert val == "High" - assert eff == "High" def test_reconcile_project_custom_fields_dry_run() -> None: @@ -109,8 +144,7 @@ def test_reconcile_project_custom_fields_dry_run() -> None: project_number=2, dry_run=True, ) - assert (res["dry_run"], res["project_number"]) == (True, 2) - assert "items_evaluated" in res + assert (res["dry_run"], res["project_number"], res["changes"]) == (True, 2, []) def test_reconcile_project_custom_fields_live() -> None: @@ -155,10 +189,32 @@ def mock_run_subprocess(cmd: list[str], **kwargs: object) -> MagicMock: project_number=2, dry_run=False, ) - assert (res["dry_run"], res["items_reconciled"] >= 1) == (False, True) - # Verify item-edit was called - edit_calls = [c for c in mock_cmd.call_args_list if "item-edit" in c[0][0]] - assert len(edit_calls) >= 5 # Status, Priority, Category, Value, Effort + edited = [ + c[0][0][c[0][0].index("--field") + 1] + for c in mock_cmd.call_args_list + if "item-edit" in c[0][0] + ] + assert (res["dry_run"], res["items_reconciled"], edited, res["changes"]) == ( + False, + 1, + ["Status", "Priority"], + [ + { + "url": "https://example.com/owner/repo/issues/74", + "field": "Status", + "old": None, + "new": "In Progress", + "source": "label status/in-progress", + }, + { + "url": "https://example.com/owner/repo/issues/74", + "field": "Priority", + "old": None, + "new": "P1-High", + "source": "label priority/p1-high", + }, + ], + ) def test_is_graphql_quota_exhausted() -> None: @@ -208,19 +264,21 @@ def test_reconcile_project_custom_fields_quota_exhausted() -> None: assert res["items_reconciled"] == 0 -def test_reconcile_project_custom_fields_fetch_failure_skips_mutations() -> None: +def test_a_failed_fetch_raises_rather_than_reading_as_empty() -> None: + """A failed read must stay distinct from a board or repository with nothing in it.""" + failed = MagicMock(returncode=1, stdout="", stderr="HTTP 502") with ( patch("devops_cli.github.projects._is_graphql_quota_exhausted", return_value=False), - patch("devops_cli.github.projects._fetch_project_items_data", return_value=None), + patch("devops_cli.github.projects._get_authenticated_user", return_value="owner"), + patch("devops_cli.github.projects.run_gh", return_value=failed), + pytest.raises(GitHubOperationError), ): - res = reconcile_project_custom_fields( + reconcile_project_custom_fields( owner="owner", repo="owner/repo", project_number=2, dry_run=False, ) - assert res["items_evaluated"] == 0 - assert res["items_reconciled"] == 0 def test_reconcile_project_custom_fields_empty_project_provisions_candidates() -> None: @@ -238,7 +296,7 @@ def test_reconcile_project_custom_fields_empty_project_provisions_candidates() - patch("devops_cli.github.projects._fetch_repository_issues", return_value=mock_issues), patch("devops_cli.github.projects._fetch_repository_prs", return_value=[]), patch("devops_cli.github.projects._provision_missing_candidates") as mock_prov, - patch("devops_cli.github.projects._reconcile_candidate_items", return_value=1), + patch("devops_cli.github.projects._reconcile_candidate_items", return_value=[]), ): res = reconcile_project_custom_fields( owner="owner", @@ -246,7 +304,7 @@ def test_reconcile_project_custom_fields_empty_project_provisions_candidates() - project_number=2, dry_run=False, ) - assert (res["items_evaluated"], res["items_reconciled"]) == (1, 1) + assert (res["items_evaluated"], res["items_reconciled"]) == (1, 0) mock_prov.assert_called_once() @@ -309,7 +367,7 @@ def test_reconcile_project_custom_fields_dry_run_filters_offboard_candidates() - patch("devops_cli.github.projects._fetch_repository_issues", return_value=mock_issues), patch("devops_cli.github.projects._fetch_repository_prs", return_value=[]), patch("devops_cli.github.projects._provision_missing_candidates") as mock_prov, - patch("devops_cli.github.projects._reconcile_candidate_items", return_value=1), + patch("devops_cli.github.projects._reconcile_candidate_items", return_value=[]), ): res_dry = reconcile_project_custom_fields( owner="owner", @@ -328,3 +386,15 @@ def test_reconcile_project_custom_fields_dry_run_filters_offboard_candidates() - ) assert (res_live["dry_run"], res_live["items_evaluated"]) == (False, 2) mock_prov.assert_called_once() + + +def test_the_issue_fetch_leaves_pull_requests_to_the_pulls_fetch() -> None: + """Read as issues, pull requests lack their merge state and would be reconciled twice.""" + from devops_cli.github.projects import _fetch_repository_issues + + listing = [{"number": 1, "html_url": "u1"}, {"number": 2, "html_url": "u2", "pull_request": {}}] + with patch( + "devops_cli.github.projects.run_gh", + return_value=MagicMock(returncode=0, stdout=json.dumps(listing), stderr=""), + ): + assert [it["number"] for it in _fetch_repository_issues("owner/repo")] == [1]