diff --git a/CHANGELOG.md b/CHANGELOG.md index 6eb59b78c..ee4d57571 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -220,6 +220,8 @@ breaking changes may land in a minor release. ### Fixed +- Recognize TOML-based TEA setup and enforce blocking gates from the current story or ticket's scoped reports. + - Read BMAD v7's `quick_lenses`/`thorough_lenses` review sets in `validate` and the run preflight, so a v7 project is no longer required to install the deleted `bmad-review-adversarial-general` and `bmad-review-edge-case-hunter`. A `workflow.review` diff --git a/docs/tea-plugin-guide.md b/docs/tea-plugin-guide.md index 5358ac5a9..513aa16e9 100644 --- a/docs/tea-plugin-guide.md +++ b/docs/tea-plugin-guide.md @@ -1,7 +1,7 @@ # The Test Architect (TEA) plugin The bundled **`tea`** plugin wires the BMAD **Test Architect Enterprise (TEA)** -module — the "Murat" agent and its `bmad-testarch-*` workflows — into every +module into every bmad-loop run and sweep as **advisory-by-default quality steps**. It injects six TEA sessions across the pipeline (test-design, ATDD, automate after dev; trace, NFR, test-review just before commit), and an operator can flip any of the @@ -20,20 +20,9 @@ TEA-specific slice. ## Prerequisite: install TEA in your project -The plugin **orchestrates** TEA; it does not bundle it. You install TEA once, per -project, with the BMAD installer: - -```bash -npx bmad-method install # choose "Test Architect" (Enterprise) -``` - -That writes TEA's runtime to `_bmad/tea/config.yaml` plus its compiled per-CLI -commands (`.claude/commands/bmad/tea/*`, and the equivalent under `.agents/`, -`.gemini/`, `.agent/`). The plugin's **readiness gate** checks for -`_bmad/tea/config.yaml` at startup and **fails the run fast** with a remediation -message if it's missing (see [Readiness gate](#readiness-gate) below) — so an -operator who enables `tea` without installing TEA learns immediately instead of -watching six sessions flail. +Install the [TEA skills](https://github.com/bmad-code-org/bmad-method-test-architecture-enterprise) in your project and run `bmad setup tea` in your coding assistant. +Setup writes the `[modules.tea]` table to `_bmad/config.toml`. +Loop also recognizes classic installs with `_bmad/tea/config.yaml`. ## Enabling the plugin @@ -60,14 +49,14 @@ TEA work injects at **two** lifecycle stages that have a live worktree Each step runs as an extra agent session through the `dev` or `review` adapter, with `workflow-start` / `workflow-end` journal entries. -| Step | TEA workflow | Stage | Adapter | What it does | -| ---------- | --------------------------- | ----------------- | ------- | ---------------------------------------------------------------------- | -| `td` | `bmad-testarch-test-design` | `post_dev_phase` | dev | Risk assessment + risk-based coverage strategy for the change. | -| `atdd` | `bmad-testarch-atdd` | `post_dev_phase` | dev | Failing acceptance tests + an implementation checklist. | -| `automate` | `bmad-testarch-automate` | `post_dev_phase` | dev | Prioritized API/E2E tests, fixtures, and a Definition-of-Done summary. | -| `trace` | `bmad-testarch-trace` | `pre_commit_gate` | review | Map requirements → tests and record the quality-gate decision. | -| `nfr` | `bmad-testarch-nfr` | `pre_commit_gate` | review | Assess non-functional requirements and record the gate decision. | -| `review` | `bmad-testarch-test-review` | `pre_commit_gate` | review | Quality-check the written tests against TEA's knowledge base. | +| Step | TEA workflow | Stage | Adapter | What it does | +| ---------- | ------------------------------ | ----------------- | ------- | ---------------------------------------------------------------------- | +| `td` | `bmad-tea-test-design` | `post_dev_phase` | dev | Risk assessment + risk-based coverage strategy for the change. | +| `atdd` | `bmad-tea-automate` (red mode) | `post_dev_phase` | dev | Failing acceptance tests + an implementation checklist. | +| `automate` | `bmad-tea-automate` | `post_dev_phase` | dev | Prioritized API/E2E tests, fixtures, and a Definition-of-Done summary. | +| `trace` | `bmad-tea-trace` | `pre_commit_gate` | review | Map requirements → tests and record the quality-gate decision. | +| `nfr` | `bmad-tea-nfr` | `pre_commit_gate` | review | Assess non-functional requirements and record the gate decision. | +| `review` | `bmad-tea-test-review` | `pre_commit_gate` | review | Quality-check the written tests against TEA's knowledge base. | The three `post_dev_phase` steps run **after** the dev phase, in the order above; the three `pre_commit_gate` steps run **just before the commit**. That stage fires @@ -76,10 +65,7 @@ on **every** path into a commit — the review-converged path, the skip path `post_review_result` never fires because the review loop never runs), and the review-budget rescue — so the gates always evaluate the exact tree about to commit, and the `*_blocking` flags enforce even on stories that skip the review -loop. Each prompt is **CLI-agnostic** — natural-language intent plus the explicit -`bmad-testarch-*` workflow name, phrased around "the changes currently in the -working tree for `{story_key}`" so the same step works for a single story **and** -a sweep bundle. +loop. Gate prompts name the story spec or ticket ref as the target. ### Runs and sweeps, no extra wiring @@ -121,23 +107,18 @@ the orchestrator review loop entirely. When you mark a gate blocking (e.g. `nfr_blocking = true`), at commit time the plugin: -1. Locates that gate's latest artifact under TEA's configured `test_artifacts` - directory (read from `_bmad/tea/config.yaml`; falls back to the installer - default `_bmad-output/test-artifacts`). -2. Parses the gate verdict — from the trace gate's JSON, or the - `## Gate Decision` / `**Gate Status**` / `**Recommendation**` line of the NFR - and test-review markdown reports. -3. On a **FAIL** or **CONCERNS** verdict, vetoes the commit with `pause` — the - unit **escalates for human review** instead of landing. (`pre_commit` honors - only a `pause` veto, which is the right "blocking gate failed" semantic.) - `PASS` and `WAIVED` never block. - -**Enforcement is fail-open by design.** A gate with no blocking flag, no artifact, -or an artifact that can't be parsed into a known verdict **never** blocks the -commit — an unknown format must never wrongly stop a commit. Only a -confidently-parsed FAIL/CONCERNS on an operator-marked-blocking gate escalates. -The verdicts the plugin did read are recorded on the shared context (`tea_gates`) -as a breadcrumb for the journal. +1. Reads `[modules.tea].test_artifacts` from `_bmad/config.toml`, applying team and user overrides from `_bmad/custom/`. + The default is `_bmad-output/test-artifacts`. +2. Looks up the current story or ticket's exact report in `trace/`, `nfr/`, or `test-review/`. + Trace prefers the gate decision JSON, then the summary JSON, then the matrix. +3. Pauses for human review on **FAIL** or **CONCERNS**. + Missing, unreadable, and unevaluated results leave the commit path open. + The hook records recognized verdicts in the shared context under `tea_gates`. + +For classic installs, Loop reads `test_artifacts` from `_bmad/tea/config.yaml` and accepts the legacy flat files when the unit has no scoped report for that gate. +With central TEA configuration, Loop reads only scoped reports. +Sweep bundles without a story or ticket can still run the workflows for advisory evidence. +Loop leaves their current-format gates unevaluated because a system-wide report cannot identify a specific bundle. ## Worktree seeding @@ -147,7 +128,7 @@ or not guaranteed in a fresh checkout, so the plugin declares `seed_globs` to ```toml seed_globs = [ - "_bmad/**", # TEA runtime: config.yaml + testarch workflows + knowledge base + "_bmad/**", # TEA runtime: config, scripts, and knowledge base ".claude/skills/bmad-t*", # compiled TEA skills for claude-code ".agents/skills/bmad-t*", # codex / cursor compiled skill home ".gemini/skills/bmad-t*", # gemini compiled skill home @@ -173,9 +154,5 @@ The canonical source lives at `src/bmad_loop/data/plugins/tea/`: ### Readiness gate -With `require_tea` on (the default), `TeaPlugin.validate` refuses to start the run -unless `_bmad/tea/config.yaml` is present, raising a `PluginError` that names the -missing file and tells the operator to either run `npx bmad-method install` → -Test Architect, or set `require_tea = false` to run the steps advisory-only. Turn -`require_tea` off when you deliberately want the prompts to degrade gracefully -(e.g. on a CLI where TEA isn't installed) rather than gate the whole run. +With `require_tea` on (the default), Loop checks the selected project's TEA setup before starting the run. +Run `bmad setup tea` to configure TEA, or set `require_tea = false` to skip the startup check. diff --git a/src/bmad_loop/bmadconfig.py b/src/bmad_loop/bmadconfig.py index e530a036d..8900b1c0f 100644 --- a/src/bmad_loop/bmadconfig.py +++ b/src/bmad_loop/bmadconfig.py @@ -515,6 +515,21 @@ def read_core_value(project: Path, key: str) -> tuple[str, str] | None: return None if central is None else _core_value(central, key) +def read_module_config(project: Path, module: str) -> dict[str, object] | None: + """Read a module's settings from the three current central config layers.""" + central = _load_central(project, V7_CENTRAL_LAYERS_REL) + modules = central.get("modules") if central is not None else None + if not isinstance(modules, _Table): + return None + table = modules.get(module) + if table is None: + return None + if not isinstance(table, _Table): + assert isinstance(table, _Leaf) + raise BmadConfigError(f"`modules.{module}` in {table.layer} must be a table") + return {key: node.value if isinstance(node, _Leaf) else node for key, node in table.items()} + + def active_initiative(project: Path) -> str | None: """The project's live ``[core] active_initiative`` (stripped, as `tickets.py` strips it), or None when none is active. Read fresh on every call: the value is diff --git a/src/bmad_loop/data/plugins/tea/plugin.toml b/src/bmad_loop/data/plugins/tea/plugin.toml index 7d91879ba..1c41b3cc2 100644 --- a/src/bmad_loop/data/plugins/tea/plugin.toml +++ b/src/bmad_loop/data/plugins/tea/plugin.toml @@ -1,9 +1,9 @@ # Bundled Test Architect Enterprise (TEA) plugin for bmad-loop. # # Wires the BMAD "Test Architect Enterprise" module (the "Murat" agent + its -# `bmad-testarch-*` workflows) into every run and sweep as advisory-by-default +# `bmad-tea-*` skills) into every run and sweep as advisory-by-default # quality steps. It assumes TEA is already installed in the project -# (`npx bmad-method install` -> Test Architect), and orchestrates by injecting +# (install its skills and run `bmad setup tea`), and orchestrates by injecting # natural-language sessions that invoke the relevant TEA workflow at two # stages that have a live worktree: # @@ -46,7 +46,7 @@ author = "bmad-loop" # a fresh checkout, so prime them into an isolated per-worktree checkout. No-ops # under today's in-place (isolation = none) mode; needed once worktrees are used. seed_globs = [ - "_bmad/**", # TEA runtime: config.yaml + testarch workflows + knowledge base + "_bmad/**", # TEA runtime: config, scripts, and knowledge base ".claude/skills/bmad-t*", # compiled TEA skills for claude-code (bmad-tea + bmad-testarch-*) ".agents/skills/bmad-t*", # codex/cursor compiled skill home ".gemini/skills/bmad-t*", # gemini compiled skill home @@ -70,7 +70,7 @@ key = "require_tea" type = "bool" default = true label = "Require TEA installed" -help = "Fail fast at startup if the project has no _bmad/tea/config.yaml (TEA not installed). false = run anyway." +help = "Require [modules.tea] in BMAD's TOML config or a legacy _bmad/tea/config.yaml at startup." # Per-step enable flags (workflow-overlay convention: _enabled). Every # step ships on; set one false to drop just that workflow. @@ -79,42 +79,42 @@ key = "td_enabled" type = "bool" default = true label = "Enable test-design (TD)" -help = "post_dev_phase: risk assessment + coverage strategy for the changes (bmad-testarch-test-design)." +help = "post_dev_phase: risk assessment + coverage strategy for the changes (bmad-tea-test-design)." [[settings]] key = "atdd_enabled" type = "bool" default = true label = "Enable ATDD (AT)" -help = "post_dev_phase: failing acceptance tests + implementation checklist (bmad-testarch-atdd)." +help = "post_dev_phase: failing acceptance tests + implementation checklist (bmad-tea-automate)." [[settings]] key = "automate_enabled" type = "bool" default = true label = "Enable automate (TA)" -help = "post_dev_phase: prioritized API/E2E tests, fixtures, DoD summary (bmad-testarch-automate)." +help = "post_dev_phase: prioritized API/E2E tests, fixtures, DoD summary (bmad-tea-automate)." [[settings]] key = "trace_enabled" type = "bool" default = true label = "Enable trace (TR)" -help = "pre_commit_gate: map requirements to tests + record the quality-gate decision (bmad-testarch-trace)." +help = "pre_commit_gate: map requirements to tests + record the quality-gate decision (bmad-tea-trace)." [[settings]] key = "nfr_enabled" type = "bool" default = true label = "Enable NFR (NR)" -help = "pre_commit_gate: assess non-functional requirements + record the gate decision (bmad-testarch-nfr)." +help = "pre_commit_gate: assess non-functional requirements + record the gate decision (bmad-tea-nfr)." [[settings]] key = "review_enabled" type = "bool" default = true label = "Enable test-review (RV)" -help = "pre_commit_gate: quality check against the written tests (bmad-testarch-test-review)." +help = "pre_commit_gate: quality check against the written tests (bmad-tea-test-review)." # Per-gate blocking flags (workflow-overlay convention: _blocking). The # gate steps ship advisory; flip one true so a FAIL/CONCERNS verdict escalates @@ -150,35 +150,35 @@ help = "true = a failing test-review gate escalates the unit at commit instead o [workflows.td] stage = "post_dev_phase" role = "dev" -prompt = "Run the TEA Test Design workflow (skill `bmad-testarch-test-design`) for `{story_key}`. Produce a risk assessment and a risk-based coverage strategy for the changes currently in the working tree, and write the artifacts under TEA's configured test_artifacts directory. Do not modify production code." +prompt = "Run the TEA Test Design workflow (skill `bmad-tea-test-design`, or legacy `bmad-testarch-test-design` if installed) for `{story_key}`. Produce a risk assessment and a risk-based coverage strategy for the changes currently in the working tree, and write the artifacts under TEA's configured test_artifacts directory. Do not modify production code." blocking = false [workflows.atdd] stage = "post_dev_phase" role = "dev" -prompt = "Run the TEA ATDD workflow (skill `bmad-testarch-atdd`) for `{story_key}`. Generate failing acceptance tests plus an implementation checklist covering the changes currently in the working tree, written under TEA's configured test_artifacts directory." +prompt = "Run the TEA ATDD workflow (red mode in `bmad-tea-automate`, or legacy `bmad-testarch-atdd` if installed) for `{story_key}`. Generate failing acceptance tests plus an implementation checklist covering the changes currently in the working tree, written under TEA's configured test_artifacts directory." blocking = false [workflows.automate] stage = "post_dev_phase" role = "dev" -prompt = "Run the TEA Test Automation workflow (skill `bmad-testarch-automate`) for `{story_key}`. Generate prioritized API/E2E tests and fixtures for the changes currently in the working tree, plus a Definition-of-Done summary, under TEA's configured test_artifacts directory." +prompt = "Run the TEA Test Automation workflow (skill `bmad-tea-automate`, or legacy `bmad-testarch-automate` if installed) for `{story_key}`. Generate prioritized API/E2E tests and fixtures for the changes currently in the working tree, plus a Definition-of-Done summary, under TEA's configured test_artifacts directory." blocking = false [workflows.trace] stage = "pre_commit_gate" role = "review" -prompt = "Run the TEA Trace Requirements workflow (skill `bmad-testarch-trace`) for `{story_key}`. Map the requirements to the tests covering the changes currently in the working tree and record the quality-gate decision under TEA's configured test_artifacts directory." +prompt = "Run the TEA Trace Requirements workflow (skill `bmad-tea-trace`, or legacy `bmad-testarch-trace` if installed) for `{unit_ref}`. When this unit is a story or ticket, use it as the explicit story target. Map the requirements to the tests covering the changes currently in the working tree and record the quality-gate decision under TEA's configured test_artifacts directory." blocking = false [workflows.nfr] stage = "pre_commit_gate" role = "review" -prompt = "Run the TEA Non-Functional Requirements workflow (skill `bmad-testarch-nfr`) for `{story_key}`. Assess the NFRs of the changes currently in the working tree and record the gate decision under TEA's configured test_artifacts directory." +prompt = "Run the TEA Non-Functional Requirements workflow (skill `bmad-tea-nfr`, or legacy `bmad-testarch-nfr` if installed) for `{unit_ref}`. When this unit is a story or ticket, use it as the explicit story target. Assess the NFRs of the changes currently in the working tree and record the gate decision under TEA's configured test_artifacts directory." blocking = false [workflows.review] stage = "pre_commit_gate" role = "review" -prompt = "Run the TEA Test Review workflow (skill `bmad-testarch-test-review`) for `{story_key}`. Perform a quality check against the tests covering the changes currently in the working tree, using TEA's knowledge base and best practices, and record findings under TEA's configured test_artifacts directory." +prompt = "Run the TEA Test Review workflow (skill `bmad-tea-test-review`, or legacy `bmad-testarch-test-review` if installed) for `{unit_ref}`. When this unit is a story or ticket, use it as the explicit story target. Perform a quality check against the tests covering the changes currently in the working tree, using TEA's knowledge base and best practices, and record findings at TEA's default scoped report path under its configured test_artifacts directory." blocking = false diff --git a/src/bmad_loop/data/plugins/tea/tea_plugin.py b/src/bmad_loop/data/plugins/tea/tea_plugin.py index 4a2d6d870..b65263094 100644 --- a/src/bmad_loop/data/plugins/tea/tea_plugin.py +++ b/src/bmad_loop/data/plugins/tea/tea_plugin.py @@ -29,9 +29,11 @@ from __future__ import annotations import json +import re from pathlib import Path from typing import TYPE_CHECKING, Any +from bmad_loop.bmadconfig import BmadConfigError, read_module_config from bmad_loop.plugins.model import Plugin, PluginError if TYPE_CHECKING: @@ -45,6 +47,10 @@ # Verdicts that escalate a blocking gate. PASS / WAIVED (an explicit human # approval to proceed) / an unknown-or-not-evaluated verdict never block. BLOCKING_VERDICTS = frozenset({"FAIL", "CONCERNS"}) +NOT_EVALUATED = "NOT_EVALUATED" +DEFAULT_ARTIFACTS = "{project-root}/_bmad-output/test-artifacts" +LEGACY_CONFIG = Path("_bmad/tea/config.yaml") +GATE_FOLDERS = {"trace": "trace", "nfr": "nfr", "review": "test-review"} # Where each gate writes its decision, in probe order (first parseable wins). # * "json" — a TEA machine-readable file; read ``gate_status`` / ``decision`` @@ -109,6 +115,65 @@ def _scan_markdown(text: str, labels: tuple[str, ...], normalize) -> str | None: return None +def _run_key(ctx: HookContext) -> str | None: + """Map Loop's bound unit to TEA's story identity.""" + if ctx.sweep_bundle: + return None + ticket = ctx.ticket + if ticket is None: + story_key = Path(ctx.spec_file).stem if ctx.spec_file else ctx.story_key + if not ctx.spec_file and story_key: + story_key = story_key.replace(".", "-") + elif ticket.epic_slug == "backlog": + story_key = f"backlog--{Path(ticket.ref).stem}" + elif ctx.initiative and ticket.id: + initiative = ctx.initiative.removeprefix("initiative-") + if ticket.epic_slug.startswith("epic-"): + epic = f"e{ticket.epic_id}" if ticket.epic_id else ticket.epic_slug + story_key = f"{initiative}--{epic}-s{ticket.id}" + else: + story_key = f"{initiative}--s{ticket.id}" + else: + return None + if not story_key or "/" in story_key or "\\" in story_key: + return None + return f"story-{story_key}" + + +def _scoped_verdict(text: str) -> str | None: + """Read a current verdict at the start of its value, including no decision.""" + match = re.match(r"(NOT_EVALUATED|CONCERNS|FAIL|WAIVED|PASS)\b", text.strip(" *`").upper()) + return match[1] if match else None + + +def _scoped_markdown(text: str, kind: str) -> str | None: + labels = { + "md_trace": ("gate decision",), + "md_nfr": ("gate status", "overall status"), + "md_review": ("recommendation",), + } + for label in labels[kind]: + pattern = rf"^\s*(?:#+\s+)?\**{label}\**\s*:\s*\**([^\n]+)" + for match in re.finditer(pattern, text, re.IGNORECASE | re.MULTILINE): + value = match[1].strip() + if value.startswith("{") or "|" in value: + continue + if kind == "md_review": + value = value.lower().strip(" *`") + for recommendation, verdict in ( + ("request changes", "CONCERNS"), + ("approve", "PASS"), + ("block", "FAIL"), + ): + if re.match(rf"{recommendation}\b", value): + return verdict + else: + verdict = _scoped_verdict(value) + if verdict is not None: + return verdict + return None + + class TeaPlugin(Plugin): """Trust-gated in-process plugin (loads only when "tea" is in ``[plugins] enabled``). Owns the TEA readiness gate + blocking-gate @@ -123,20 +188,26 @@ class TeaPlugin(Plugin): # ----------------------------------------------------------- validation def validate(self, policy: Any) -> None: - """Readiness gate: with ``require_tea`` on, refuse to start unless TEA is - installed in the project (``_bmad/tea/config.yaml`` present). Raising here - propagates through ``registry.validate`` so the run fails fast at startup - rather than launching six sessions that each invoke a missing workflow.""" + self.validate_project(policy, Path.cwd()) + + def validate_project(self, policy: Any, project: Path) -> None: + """Accept current central TEA setup or a legacy module install.""" if not self._require_tea(): return - config = self._tea_config_path(self._project_root()) - if not config.is_file(): + try: + modern = read_module_config(project, "tea") + if modern is not None: + self._current_artifacts_dir(project, modern) + return + except BmadConfigError as error: + raise PluginError(f"plugin 'tea': {error}") from error + if not (project / LEGACY_CONFIG).is_file(): raise PluginError( "plugin 'tea': the Test Architect Enterprise (TEA) module is not " - f"installed in this project (missing {config}). Install it with " - "`npx bmad-method install` and choose 'Test Architect', or set " - "require_tea = false under [plugins.tea] in .bmad-loop/policy.toml " - "to run the TEA workflows advisory-only without it." + f"installed in this project (missing [modules.tea] in {project / '_bmad/config.toml'} " + f"and legacy {project / LEGACY_CONFIG}). Install the TEA skills and run " + "`bmad setup tea`, or set require_tea = false under [plugins.tea] " + "in .bmad-loop/policy.toml." ) # --------------------------------------------------------- enforcement @@ -152,23 +223,34 @@ def on_pre_commit(self, ctx: "HookContext") -> None: blocking verdicts escalate. ``pre_commit`` honors only a ``pause`` veto (a COMMITTING task has no legal move to DEFERRED), which is the right "blocking gate failed" semantic — escalate-for-human.""" - gates = [g for g in GATE_STEPS if bool(self.settings.get(f"{g}_blocking"))] + gates = [ + gate + for gate in GATE_STEPS + if self.settings.get(f"{gate}_enabled", True) and self.settings.get(f"{gate}_blocking") + ] if not gates: return # nothing flagged blocking -> advisory only, no artifact read # Resolve the tree TEA wrote into: the unit's worktree (where the # pre_commit_gate sessions just ran), falling back to the repo root. # Under isolation = none the two coincide. - root = ctx.worktree or ctx.repo_root + root = ctx.project_dir or ctx.worktree or ctx.repo_root if not root: return # fail-open: no tree to inspect - artifacts_dir = self._artifacts_dir(Path(root)) + project = Path(root) + modern = read_module_config(project, "tea") + artifacts_dir = ( + self._current_artifacts_dir(project, modern) + if modern is not None + else self._legacy_artifacts_dir(project) + ) + run_key = _run_key(ctx) verdicts: dict[str, str] = {} failed: list[tuple[str, str]] = [] for gate in gates: - verdict = self._gate_verdict(gate, artifacts_dir) - if verdict is None: + verdict = self._gate_verdict(gate, artifacts_dir, run_key, legacy=modern is None) + if verdict is None or verdict == NOT_EVALUATED: continue # fail-open: missing / unparseable / not-evaluated verdicts[gate] = verdict if verdict in BLOCKING_VERDICTS: @@ -191,59 +273,57 @@ def on_pre_commit(self, ctx: "HookContext") -> None: def _require_tea(self) -> bool: return bool(self.settings.get("require_tea", True)) - def _project_root(self) -> Path: - """The project root, resolved the way the engine resolves it: the run's - working directory (``bmad-loop``'s ``--project`` defaults to cwd, and the - process is not chdir'd into a worktree at construction time). validate() - has no ``HookContext`` to read ``repo_root`` from, so cwd is the available - signal; ``on_pre_commit`` uses ``ctx.worktree`` / ``ctx.repo_root`` for the - authoritative per-unit root.""" - return Path.cwd() - - def _tea_config_path(self, root: Path) -> Path: - return root / "_bmad" / "tea" / "config.yaml" - - def _artifacts_dir(self, root: Path) -> Path: - """TEA's configured ``test_artifacts`` directory, resolved against ``root``. - - Reads the ``test_artifacts`` line from ``_bmad/tea/config.yaml`` (a light - line parse — no YAML dependency, and robust if the file is absent), expands - the ``{project-root}`` / ``{output_folder}`` tokens, and falls back to the - installer default. A relative value is joined onto ``root``.""" - value = "{project-root}/_bmad-output/test-artifacts" - config = self._tea_config_path(root) + def _current_artifacts_dir(self, root: Path, config: dict[str, object]) -> Path: + value = config.get("test_artifacts", DEFAULT_ARTIFACTS) + if not isinstance(value, str) or not value.strip() or "\0" in value: + raise BmadConfigError("`modules.tea.test_artifacts` must be a non-empty path") + return root / value.replace("{project-root}", str(root)) + + def _legacy_artifacts_dir(self, root: Path) -> Path: + """Preserve classic YAML path and token handling.""" + value = DEFAULT_ARTIFACTS try: - for raw in config.read_text(encoding="utf-8").splitlines(): + for raw in (root / LEGACY_CONFIG).read_text(encoding="utf-8").splitlines(): line = raw.strip() if line.startswith("test_artifacts:"): value = line.split(":", 1)[1].strip().strip("\"'") break except OSError: - pass # fail-open: use the default location + pass value = value.replace("{project-root}", str(root)).replace( "{output_folder}", str(root / "_bmad-output") ) - path = Path(value) - return path if path.is_absolute() else root / value - - def _gate_verdict(self, gate: str, artifacts_dir: Path) -> str | None: - """The latest verdict for ``gate`` from its artifacts, or None. Probes each - candidate in order, returning the first that parses to a known verdict; - any read/parse error on a candidate is swallowed (fail-open) and the next - is tried.""" - for kind, filename in GATE_ARTIFACTS.get(gate, ()): - path = artifacts_dir / filename - if not path.is_file(): - continue + return root / value + + def _gate_verdict( + self, gate: str, artifacts_dir: Path, run_key: str | None, *, legacy: bool + ) -> str | None: + candidates = GATE_ARTIFACTS[gate] + if run_key is not None: + folder = artifacts_dir / GATE_FOLDERS[gate] + scoped = [ + (kind, folder / f"{Path(name).stem}-{run_key}{Path(name).suffix}") + for kind, name in candidates + ] + present = [(kind, path) for kind, path in scoped if path.is_file()] + if present: + return self._first_verdict(present, scoped=True) + if legacy: + flat = [(kind, artifacts_dir / name) for kind, name in candidates] + return self._first_verdict(flat, scoped=False) + return None + + def _first_verdict(self, candidates: list[tuple[str, Path]], *, scoped: bool) -> str | None: + for kind, path in candidates: try: - verdict = self._parse_artifact(kind, path) - except Exception: # nosec B112 - fail-open: a parse error never blocks + verdict = self._parse_artifact(kind, path, scoped=scoped) + except (OSError, ValueError): continue if verdict is not None: return verdict return None - def _parse_artifact(self, kind: str, path: Path) -> str | None: + def _parse_artifact(self, kind: str, path: Path, *, scoped: bool) -> str | None: """Extract a gate verdict from one artifact, by kind.""" text = path.read_text(encoding="utf-8") if kind == "json": @@ -251,8 +331,10 @@ def _parse_artifact(self, kind: str, path: Path) -> str | None: if isinstance(data, dict): raw = data.get("gate_status") or data.get("decision") if isinstance(raw, str): - return _verdict_token(raw) + return _scoped_verdict(raw) if scoped else _verdict_token(raw) return None + if scoped: + return _scoped_markdown(text, kind) if kind == "md_review": return _scan_markdown(text, ("recommendation",), _review_token) return _scan_markdown(text, _MD_LABELS[kind], lambda line: _verdict_token(line)) diff --git a/src/bmad_loop/engine.py b/src/bmad_loop/engine.py index 145692ae1..a1fbffc09 100644 --- a/src/bmad_loop/engine.py +++ b/src/bmad_loop/engine.py @@ -1064,7 +1064,7 @@ def __init__( # let every in-process plugin reject an incompatible config at startup # (e.g. the Unity plugin's editor_mode↔scm.isolation coupling) so the run # fails fast rather than mid-unit. - self._registry.validate(policy) + self._registry.validate(policy, project=self.paths.project) # a hook from a plugin not declared `read_only` voids any reusable verify # pass before it runs (#1002 / DW-640); the callback only touches state. self._bus = HookBus( @@ -3099,6 +3099,7 @@ def _make_context(self, stage: str, task: StoryTask | None, **fields) -> HookCon base: dict = { "run_id": self.state.run_id, "repo_root": str(self.paths.repo_root), + "project_dir": str(self.workspace.paths.project), "run_dir": str(self.run_dir), "shared": self.state.plugin_shared, # the dev + review CLI agent ids in this unit's worktree, for a plugin @@ -3113,6 +3114,10 @@ def _make_context(self, stage: str, task: StoryTask | None, **fields) -> HookCon attempt=task.attempt, worktree=task.worktree_path or str(self.workspace.root), branch=task.branch or None, + ticket=task.ticket, + initiative=self.paths.active_initiative, + spec_file=task.spec_file, + sweep_bundle=bool(task.dw_ids), ) base.update(fields) return HookContext(stage, **base) @@ -3218,11 +3223,17 @@ def _run_workflows(self, stage: str, task: StoryTask, seq: int) -> bool: other, so token budgets and the transcript trail account for it.""" if stage not in self._workflow_stages: return False + unit_ref = task.story_key + if task.ticket is not None: + unit_ref = task.ticket.ref + elif task.spec_file and not task.dw_ids: + unit_ref = task.spec_file for lp, wf in self._registry.workflows_for(stage): prompt = ( lp.manifest.render(wf.prompt) .replace("{story_key}", task.story_key) .replace("{run_id}", self.state.run_id) + .replace("{unit_ref}", unit_ref) ) self.journal.append( "workflow-start", diff --git a/src/bmad_loop/plugins/context.py b/src/bmad_loop/plugins/context.py index 4a68b7bbf..6debbad66 100644 --- a/src/bmad_loop/plugins/context.py +++ b/src/bmad_loop/plugins/context.py @@ -32,6 +32,7 @@ # is no cycle today — `verify` reaches deferredwork/bmadconfig/frontmatter/ # model/platform_util/policy/sprintstatus, none of which touch `plugins/` — # so this is layering, not a workaround. + from ..model import TicketBinding from ..verify import CommandResult # Veto actions, least to most conservative. `skip` drops the current unit and @@ -86,6 +87,11 @@ def __init__( branch: str | None = None, repo_root: str | None = None, run_dir: str | None = None, + project_dir: str | None = None, + spec_file: str | None = None, + ticket: TicketBinding | None = None, + initiative: str = "", + sweep_bundle: bool = False, agents: tuple[str, ...] = (), result_json: dict[str, Any] | None = None, session_status: str | None = None, @@ -116,6 +122,11 @@ def __init__( self._branch = branch self._repo_root = repo_root self._run_dir = run_dir + self._project_dir = project_dir + self._spec_file = spec_file + self._ticket = ticket + self._initiative = initiative + self._sweep_bundle = sweep_bundle # the agent ids of the CLIs that run in this unit's worktree (dev + review), # for a plugin that routes per-agent config (e.g. the engine's MCP routing). self._agents = tuple(agents) @@ -212,6 +223,27 @@ def repo_root(self) -> str | None: def run_dir(self) -> str | None: return self._run_dir + @property + def project_dir(self) -> str | None: + """The BMAD project directory in the checkout used for this stage.""" + return self._project_dir + + @property + def spec_file(self) -> str | None: + return self._spec_file + + @property + def ticket(self) -> TicketBinding | None: + return self._ticket + + @property + def initiative(self) -> str: + return self._initiative + + @property + def sweep_bundle(self) -> bool: + return self._sweep_bundle + @property def agents(self) -> tuple[str, ...]: return self._agents diff --git a/src/bmad_loop/plugins/model.py b/src/bmad_loop/plugins/model.py index 53ae0b2c6..870527dfb 100644 --- a/src/bmad_loop/plugins/model.py +++ b/src/bmad_loop/plugins/model.py @@ -19,6 +19,8 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: + from pathlib import Path + from .context import HookContext from .grants import Verdict @@ -110,7 +112,8 @@ class WorkflowSpec: generic ``_run_session`` path at an allowlisted ``stage`` (see WORKFLOW_STAGES). ``role`` selects which adapter runs it (WORKFLOW_ROLES); ``prompt`` is the agent prompt template, expanding ``{story_key}``, - ``{run_id}`` and ``{scripts}`` (the plugin's script dir). A ``blocking`` + ``{unit_ref}`` (ticket ref, story spec, or unit key), ``{run_id}``, and + ``{scripts}`` (the plugin's script dir). A ``blocking`` workflow whose session does not complete defers the unit (it routes through the engine's existing defer primitive); a non-blocking one is advisory. @@ -248,6 +251,10 @@ def validate(self, policy: Any) -> None: rejection, not a plugin bug, so the registry lets it propagate and the run fails fast rather than being isolated out. The default is a no-op.""" + def validate_project(self, policy: Any, project: Path) -> None: + """Validate with the selected BMAD project, even when launched from elsewhere.""" + self.validate(policy) + def hook(self, stage: str, ctx: "HookContext") -> None: """Route a stage to its ``on_`` handler, if defined. The bus wraps this call for failure isolation, so a subclass handler may raise freely.""" diff --git a/src/bmad_loop/plugins/registry.py b/src/bmad_loop/plugins/registry.py index 407ed09d3..709ab1ba3 100644 --- a/src/bmad_loop/plugins/registry.py +++ b/src/bmad_loop/plugins/registry.py @@ -525,10 +525,14 @@ def seed_globs(self) -> list[str]: dict.fromkeys(g for lp in self._active_for_seeds() for g in lp.manifest.seed_globs) ) - def validate(self, policy) -> None: + def validate(self, policy, *, project: Path | None = None) -> None: """Let every constructed in-process plugin self-validate against the run policy (``Plugin.validate``). A plugin raises to reject an incompatible config; the registry lets it propagate so the run fails fast at startup.""" for lp in self._loaded: - if lp.instance is not None: + if lp.instance is None: + continue + if project is None: lp.instance.validate(policy) + else: + lp.instance.validate_project(policy, project) diff --git a/tests/test_plugin_tea.py b/tests/test_plugin_tea.py index 38442b5c8..bc80cc589 100644 --- a/tests/test_plugin_tea.py +++ b/tests/test_plugin_tea.py @@ -23,6 +23,7 @@ import importlib.util import json import os +from pathlib import Path import pytest from conftest import ( @@ -37,7 +38,7 @@ from bmad_loop.adapters.mock import MockAdapter from bmad_loop.engine import Engine from bmad_loop.journal import Journal -from bmad_loop.model import RunState, TokenUsage +from bmad_loop.model import RunState, TicketBinding, TokenUsage from bmad_loop.plugins import PluginError, PluginRegistry, get_plugin, load_plugins from bmad_loop.plugins.model import PluginManifest from bmad_loop.policy import GatesPolicy, NotifyPolicy, PluginsPolicy, Policy @@ -113,7 +114,7 @@ def write_gate_artifact(project, gate: str, verdict: str) -> None: raise ValueError(f"unknown gate {gate!r}") -def pre_commit_ctx(project): +def pre_commit_ctx(project, **fields): """A minimal pre_commit HookContext pointing at the project tree (isolation = none: worktree == repo root), for unit-testing ``on_pre_commit`` directly.""" from bmad_loop.plugins.context import HookContext @@ -124,6 +125,7 @@ def pre_commit_ctx(project): worktree=str(project.project), repo_root=str(project.project), shared={}, + **fields, ) @@ -618,3 +620,155 @@ def test_advisory_default_commits_despite_failing_gate(project, monkeypatch): summary = engine.run() assert summary.done == 1 and not summary.paused + + +def install_current_tea(project): + config = project.project / "_bmad" / "config.toml" + config.parent.mkdir(exist_ok=True) + config.write_text('[modules.tea]\ntest_artifacts = "default-reports"\n', encoding="utf-8") + custom = config.parent / "custom" + custom.mkdir(exist_ok=True) + (custom / "config.toml").write_text( + '[modules.tea]\ntest_artifacts = "team-reports"\n', encoding="utf-8" + ) + (custom / "config.user.toml").write_text( + '[modules.tea]\ntest_artifacts = "{project-root}/current-reports"\n', encoding="utf-8" + ) + return project.project / "current-reports" + + +def write_report(artifacts, filename, content): + report = artifacts / filename + report.parent.mkdir(parents=True, exist_ok=True) + report.write_text(content, encoding="utf-8") + + +def test_current_install_to_blocking_trace(project): + artifacts = install_current_tea(project) + write_sprint(project, {"epic-1": "backlog", "1-1-a": "ready-for-dev"}) + policy = tea_policy( + td_enabled=False, + atdd_enabled=False, + automate_enabled=False, + nfr_enabled=False, + review_enabled=False, + trace_blocking=True, + ) + reg = PluginRegistry.build(project.project, policy) + + def trace_session(spec): + assert "bmad-tea-trace" in spec.prompt + assert "spec-1-1-a.md" in spec.prompt + write_report( + artifacts, "trace/gate-decision-story-spec-1-1-a.json", '{"gate_status":"FAIL"}' + ) + return workflow_effect([])(spec) + + script = [dev_effect(project, "1-1-a", followup_review=False), trace_session] + engine = make_engine(project, script, reg, policy) + summary = engine.run() + + assert summary.paused and summary.escalated == 1 + assert engine.state.plugin_shared["tea_gates"] == {"trace": "FAIL"} + + +@pytest.mark.parametrize( + "gate,filename,content,verdict", + [ + ("trace", "trace/e2e-trace-summary-story-1-1-a.json", '{"gate_status":"FAIL"}', "FAIL"), + ("trace", "trace/traceability-matrix-story-1-1-a.md", "## Gate Decision: FAIL", "FAIL"), + ( + "nfr", + "nfr/nfr-assessment-story-1-1-a.md", + "**Overall Status:** PASS\n**Gate Status:** CONCERNS ⚠️", + "CONCERNS", + ), + ("review", "test-review/test-review-story-1-1-a.md", "**Recommendation**: Block", "FAIL"), + ], +) +def test_current_scoped_verdict_wins_over_flat_report(project, gate, filename, content, verdict): + install_tea(project) + artifacts = install_current_tea(project) + flat_name = Path(filename).name.replace("-story-1-1-a", "") + flat_pass = { + "trace": ( + '{"gate_status":"PASS"}' if flat_name.endswith(".json") else "## Gate Decision: PASS" + ), + "nfr": "**Overall Status:** PASS", + "review": "**Recommendation**: Approve", + }[gate] + write_report(artifacts, flat_name, flat_pass) + write_report(artifacts, filename, content) + ctx = pre_commit_ctx(project) + _tea_instance(**{f"{gate}_blocking": True}).on_pre_commit(ctx) + + assert ctx.resolved_veto().action == "pause" + assert ctx.shared["tea_gates"] == {gate: verdict} + + +@pytest.mark.parametrize( + "current,verdict", + [ + (None, None), + ('{"gate_status":"NOT_EVALUATED"}', None), + ('{"gate_status":"PASS"}', "PASS"), + ("broken JSON", None), + ], +) +def test_current_trace_ignores_stale_flat_and_other_scopes(project, current, verdict): + install_tea(project) + artifacts = install_current_tea(project) + fail = '{"gate_status":"FAIL"}' + write_gate_artifact(project, "trace", "FAIL") + write_report(artifacts, "gate-decision.json", fail) + write_report(artifacts, "trace/gate-decision-story-1-2-unrelated.json", fail) + write_report(artifacts, "trace/gate-decision-system.json", fail) + if current is not None: + write_report(artifacts, "trace/e2e-trace-summary-story-1-1-a.json", current) + ctx = pre_commit_ctx(project) + _tea_instance(trace_blocking=True).on_pre_commit(ctx) + + assert not ctx.vetoed + assert ctx.shared.get("tea_gates", {}).get("trace") == verdict + + +def test_disabled_gate_ignores_existing_report(project): + artifacts = install_current_tea(project) + write_report(artifacts, "trace/gate-decision-story-1-1-a.json", '{"gate_status":"FAIL"}') + ctx = pre_commit_ctx(project) + _tea_instance(trace_blocking=True, trace_enabled=False).on_pre_commit(ctx) + + assert not ctx.vetoed + assert "tea_gates" not in ctx.shared + + +@pytest.mark.parametrize( + "ref,entry,folder,epic_id,scope", + [ + ("1.2", "2", "epic-checkout", "1", "shop--e1-s2"), + ("CC2", "CC2", "epic-loyalty", "", "shop--epic-loyalty-sCC2"), + ("6a", "6a", "initiative-shop", "", "shop--s6a"), + ("story-coupon.md", "", "backlog", "", "backlog--story-coupon"), + ], +) +def test_ticket_scope_uses_bound_container(project, ref, entry, folder, epic_id, scope): + artifacts = install_current_tea(project) + write_report(artifacts, f"trace/gate-decision-story-{scope}.json", '{"decision":"FAIL"}') + ticket = TicketBinding( + ref=ref, + id=entry, + epic_slug=folder, + epic_id=epic_id, + title="Ticket", + plan="", + risk="", + refined=False, + plan_checkpoint=False, + done_checkpoint=False, + hitl=False, + ) + ctx = pre_commit_ctx(project, ticket=ticket, initiative="initiative-shop") + _tea_instance(trace_blocking=True).on_pre_commit(ctx) + + assert ctx.shared["tea_gates"] == {"trace": "FAIL"} + assert ctx.resolved_veto().action == "pause"