diff --git a/CHANGELOG.md b/CHANGELOG.md index d1fc56b49..21a4edac0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -191,6 +191,17 @@ breaking changes may land in a minor release. ### Fixed +- 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` + value the dev skill would HALT on, a non-string one included, is reported as + `skills.review-selection-invalid`, a `quick` or `thorough` selection whose own + lens set is all disabled as `skills.review-layers-empty`, and an override v7 + refuses to load as a `skills.customize-unreadable` problem. +- Report a missing dev primitive once, without stacking review-skill and dispatch + failures under the legacy `bmad-dev-auto` name on top of it. Name core-tools as + the v7 home of `bmad-review`, and note when a missing skill is installed only + globally (`~/.claude/skills`, `~/.agents/skills`). - Stop reading an empty psmux window listing as a dead session. psmux can drop a live server's reply and exit 0 with nothing, which the liveness probe took for a crashed CLI and the control-window prune for a verified kill. That listing now counts as a failed diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 29b98816f..833dd690d 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -708,10 +708,11 @@ Every finding's `check` is one of these ids. Severity is `ok`, `warning` or `pro | `skills.dev-renderer-config` | problem | a renderer stub's central config layer is missing | | `skills.dev-render-probe` | ok / problem | `--render-probe` only: the stub's render command succeeds in a temp copy | | `skills.customize-legacy` | warning | customize overrides named for the legacy dev primitive no longer apply | -| `skills.customize-unreadable` | warning | a customize override is not valid TOML | +| `skills.customize-unreadable` | warning / problem | a customize override is not valid TOML, or keys an array entry on an `id`/`code` that is not a non-empty string; a problem on a BMAD v7 tree | | `skills.review-layers-empty` | problem | the dev primitive has no enabled review layer | | `skills.review-layer-missing` | problem | a referenced review-layer skill is not installed | | `skills.review-layer-unresolved` | warning | a conditionally referenced review-layer skill is not installed | +| `skills.review-selection-invalid` | problem | BMAD v7: `workflow.review` is not `none`, `quick`, `thorough` or `auto` | | `skills.stories-dispatch` | ok | stories mode: the dev primitive supports folder+id dispatch | | `skills.stories-dispatch-missing` | problem | stories mode: the dispatch probe file is missing | | `skills.stories-dispatch-stale` | problem | stories mode: the dev primitive lacks folder+id dispatch | diff --git a/docs/setup-guide.md b/docs/setup-guide.md index 33647256c..2cdec902b 100644 --- a/docs/setup-guide.md +++ b/docs/setup-guide.md @@ -148,11 +148,32 @@ implementation and the follow-up review), installed by the BMad Method (bmm) module. `bmad-loop validate` checks it — plus any review skills its layers invoke — are present before a run starts. +bmad-loop resolves BMAD skills only from the project's own skill tree +(`.claude/skills`, `.agents/skills`). A global install (`npx skills add -g`, into +`~/.claude/skills` or `~/.agents/skills`) and a Claude Code plugin install are not used. +When `validate` finds a missing skill installed globally it says so, and +`detail.outside` names that copy, but the run still refuses: install the skill per +project with `npx skills add` without `-g`. + **Minimum BMAD-METHOD: v6.10.0** for sprint mode. Beyond the primitive itself (with its `customize.toml`), `bmad-loop validate` holds you to no fixed list of review skills: it reads the primitive you actually have installed and requires the reviewers that copy will actually invoke — which on current sources is none at all. +- **Lens sets (BMAD v7)** — `customize.toml` defines `[[workflow.quick_lenses]]` and + `[[workflow.thorough_lenses]]`, and `review` (`none`, `quick`, `thorough` or + `auto`) picks the set a run launches. `validate` reads every enabled lens in both + sets, because `auto`, an invocation's `--set workflow.review=…` and bmad-loop's own + `[tickets] thorough_review` can each select either one. The shipped lenses invoke no + skill, so a v7 tree requires no review skill. Any other `review` value, a non-string + one included, is `skills.review-selection-invalid`, because the primitive HALTs + every run on it. An override v7 cannot load (invalid TOML, or a lens `id`/`code` + that is not a non-empty string) is a `skills.customize-unreadable` problem rather + than a warning: v7 refuses to render the dev skill with it. + `validate` reports `skills.review-layers-empty` when the configured set has no + enabled lens: the `quick` or `thorough` set itself, or both sets under `auto`. A + `review = "none"` run launches no lens, so empty sets pass. A `review_layers` + override left over from a v6 install is ignored, as the v7 run ignores it. - **Layer-driven (post-6.10.0)** — `customize.toml` defines `[[workflow.review_layers]]`, and a layer's `instruction` may name a skill to hand off to. Current (6.11) sources define four layers — `blind-hunter`, @@ -169,8 +190,11 @@ reviewers that copy will actually invoke — which on current sources is none at A layer disabled with an empty `instruction`, or replaced in `_bmad/custom/bmad-build-auto.toml` by a recipe that runs something else, requires -nothing. If the shape cannot be read at all, `validate` falls back to requiring the two -v6.10.0 hunters — which a tree carrying `bmad-review` satisfies. +nothing. Lenses follow the same rules. If the shape cannot be read at all, `validate` +falls back to requiring the two v6.10.0 hunters, which a tree carrying `bmad-review` +satisfies. On v7, `bmad-review` ships in the core-tools module. When the dev primitive +itself is missing, `validate` reports only that: no reviewer is demanded without a +primitive to derive it from. `bmad-review-verification-gap` is required only when your installed layers name it: no tagged release ships it as a standalone skill, and on current sources it is a thin diff --git a/src/bmad_loop/checks.py b/src/bmad_loop/checks.py index b94946a9f..f458ce943 100644 --- a/src/bmad_loop/checks.py +++ b/src/bmad_loop/checks.py @@ -138,6 +138,8 @@ "skills.review-layer-missing", "skills.review-layer-unresolved", "skills.review-layers-empty", + # v7 `workflow.review` outside none/quick/thorough/auto HALTs every build-auto run + "skills.review-selection-invalid", "skills.customize-unreadable", "skills.stories-dispatch", "skills.stories-dispatch-missing", diff --git a/src/bmad_loop/cli.py b/src/bmad_loop/cli.py index d480de13d..d695a68ea 100644 --- a/src/bmad_loop/cli.py +++ b/src/bmad_loop/cli.py @@ -2833,8 +2833,16 @@ def _warn_preflight_would_abort( problems = [ p.message for p in install.missing_base_skills(paths.project, trees) - + (install.missing_stories_support(paths.project, trees) if require_stories else []) - + (install.missing_tickets_support(paths.project, trees) if require_tickets else []) + + ( + install.missing_stories_support(paths.project, trees, skip_unresolved=True) + if require_stories + else [] + ) + + ( + install.missing_tickets_support(paths.project, trees, skip_unresolved=True) + if require_tickets + else [] + ) + ( install.missing_sweep_skill(paths.project, _triage_trees(paths.project, pol)) if require_sweep @@ -2968,9 +2976,10 @@ def _require_base_skills( skill_trees = _skill_trees(project, pol, root, grants, review_owed=review_owed) findings = install.missing_base_skills(project, skill_trees) if require_stories: - findings += install.missing_stories_support(project, skill_trees) + # missing_base_skills above reports (and refuses) an unresolved primitive + findings += install.missing_stories_support(project, skill_trees, skip_unresolved=True) if require_tickets: - findings += install.missing_tickets_support(project, skill_trees) + findings += install.missing_tickets_support(project, skill_trees, skip_unresolved=True) # Severity decides. A review layer we can't statically resolve (a `when` gate, # an unrecognized handoff phrasing, an unparseable override) is reported and # then stepped over: aborting on it would be the false FAIL of #260, only now @@ -3073,6 +3082,12 @@ def _validate_stories_folder( return None +def _all_resolve(project: Path, trees: list[str]) -> bool: + """Every tree resolves a dev primitive — the precondition for a dispatch-probe ok + line, since the probes skip an unresolved tree rather than report it.""" + return all(install.resolve_dev_primitive(project, tree) is not None for tree in trees) + + def _validate_stories_queue( project: Path, paths: bmadconfig.ProjectPaths, @@ -3103,8 +3118,10 @@ def _validate_stories_queue( f"stories mode: {e} (spec folder: {folder})", {"spec_folder": str(folder)}, ) - stories_probs = install.missing_stories_support(project, skill_trees) - if skill_trees and not stories_probs: + # cmd_validate's skills.base check reports an unresolved primitive on these same + # trees; such a tree is skipped here, so it must also withhold the ok line. + stories_probs = install.missing_stories_support(project, skill_trees, skip_unresolved=True) + if skill_trees and not stories_probs and _all_resolve(project, skill_trees): # The total form, not `resolve_dev_primitive`: this ok line only renders when # the probe passed, and the probe ran against exactly this name — so an # unresolvable tree that somehow satisfied it is still reported as what was @@ -3420,8 +3437,8 @@ def _validate_tickets_mode_queue( retrospective=pol.gates.retrospective if pol is not None else None, ) ) - tickets_probs = install.missing_tickets_support(project, dev_trees) - if dev_trees and not tickets_probs: + tickets_probs = install.missing_tickets_support(project, dev_trees, skip_unresolved=True) + if dev_trees and not tickets_probs and _all_resolve(project, dev_trees): probed = list( dict.fromkeys( install.dev_primitive_or_default(project, tree) for tree in dict.fromkeys(dev_trees) diff --git a/src/bmad_loop/install.py b/src/bmad_loop/install.py index a27b0af0b..252d37dd8 100644 --- a/src/bmad_loop/install.py +++ b/src/bmad_loop/install.py @@ -89,6 +89,13 @@ BMAD_FLOOR_TEXT = ( "the bmm module (BMAD-METHOD >= 6.10.0) or, on BMAD v7, the method module (bmod-method >= 6.13)" ) +# Which upstream install ships the REVIEW skills a review finding names. They differ +# from the primitive's floor on v7: the merged `bmad-review` moved out of the method +# module into core-tools (the bmod-core-tools record lists it). +REVIEW_FLOOR_TEXT = ( + "the bmm module (BMAD-METHOD >= 6.10.0) or, on BMAD v7, the core-tools module " + "(which ships bmad-review)" +) # The inner dev primitive, in both upstream eras. BMAD-METHOD PR #2651 (shipped in # bmad-method 6.10.1-next.33) renamed `bmad-dev-auto` -> `bmad-build-auto` and left a @@ -189,7 +196,11 @@ # requirement, used when the installed skill's shape can't be read: normally the # reviewers are derived per tree from the dev primitive itself # (resolve_review_layers), because which skills the review step invokes is a -# property of that skill version, not of a catalog pinned in here (#260). +# property of that skill version, not of a catalog pinned in here (#260). Three +# shapes are read: step-04 prose (v6.10.0), [[workflow.review_layers]] +# (v6.10-6.12) and the v7 [[workflow.quick_lenses]]/[[workflow.thorough_lenses]] +# sets. Neither hunter exists upstream any more, so a v7 tree must never land on +# this fallback just because its shape went unread. # bmad-review-verification-gap is not in the fallback set: no tagged BMAD-METHOD # release ships it standalone (on current sources it is a thin forwarder to the # merged bmad-review), so demanding it of every project made `validate` @@ -211,7 +222,8 @@ # falls back to the static catalog only when the resolution is None (an unreadable # shape), never because it resolved to requiring nothing. Both topologies stay # supported; this constant is named here for the fallback path only, and the derived -# path sees it named in the layers themselves. +# path sees it named in the layers themselves. The v7 lens sets are the 6.11 shape +# again: every shipped lens says "Do not invoke any skill", so they derive nothing. MERGED_REVIEW_SKILL = "bmad-review" # The DEV_BASE_SKILLS entries MERGED_REVIEW_SKILL subsumes. bmad-dev-auto (the dev # primitive) is NOT here — the merged reviewer never substitutes for it. @@ -413,6 +425,14 @@ class ReviewResolution(NamedTuple): fail. ``active_layers`` names every layer with a non-empty ``instruction`` — all of them disabled is a run that HALTs. ``unreadable`` names override files that failed to parse. + + ``lens_sets`` names the v7 lens sets read (``("quick", "thorough")``), and is + empty for every other shape; ``active_layers`` then spans both sets, and + ``active_sets`` names the sets holding at least one enabled lens — a ``quick`` or + ``thorough`` selection launches only its own set. ``selection`` is the resolved + ``workflow.review`` string of that shape, or None when no string value is + configured. All three trail with defaults so every positional construction of + the older shapes stays valid. """ source: str @@ -421,6 +441,9 @@ class ReviewResolution(NamedTuple): layer_driven: bool active_layers: tuple[str, ...] unreadable: tuple[str, ...] + lens_sets: tuple[str, ...] = () + selection: str | None = None + active_sets: tuple[str, ...] = () def skills(self) -> tuple[str, ...]: """Every skill this review step may invoke, required or advisory.""" @@ -448,10 +471,59 @@ def _layers_of(data: Any) -> list[Any]: return list(layers) if isinstance(layers, list) else [] +# The v7 lens sets (BMAD-METHOD #2861), keyed by the `workflow.review` value that +# selects each: `[[workflow.quick_lenses]]` and `[[workflow.thorough_lenses]]`. +LENS_SETS = {"quick": "quick_lenses", "thorough": "thorough_lenses"} +# Every `workflow.review` value v7 bmad-build-auto accepts: its workflow.md HALTs +# the run on any other ("workflow.review must be none, quick, thorough, or auto"). +REVIEW_SELECTIONS = ("none", "quick", "thorough", "auto") + + +def _lens_sets_of(data: Any) -> dict[str, list[Any]]: + """The v7 lens arrays present in ``data``, as ``{"quick": [...], "thorough": [...]}``. + + A set appears only when its key holds an array — presence is what tells the lens + shape apart from the others, so an absent set is left out rather than reported + as ``[]``. Every hop is type-guarded as in :func:`_layers_of`. + """ + workflow = data.get("workflow") if isinstance(data, dict) else None + if not isinstance(workflow, dict): + return {} + found: dict[str, list[Any]] = {} + for name, key in LENS_SETS.items(): + lenses = workflow.get(key) + if isinstance(lenses, list): + found[name] = list(lenses) + return found + + +def _review_selection_of(data: Any) -> str | None: + """``workflow.review`` as text, or None only when the key is absent. + + A present non-string value (``review = false``) is not dropped: v7's template + HALTs on it like on any unknown word, so it comes back as its TOML literal + (``false``, ``1``, ``["quick"]``). That text never equals a valid selection — + those are bare words only a string can produce — so the caller reports it. + """ + workflow = data.get("workflow") if isinstance(data, dict) else None + if not isinstance(workflow, dict) or "review" not in workflow: + return None + selection = workflow["review"] + if isinstance(selection, str): + return selection + return json.dumps(selection, default=str) + + # BMAD's own merge keys for arrays of tables, in detection precedence order. _KEYED_MERGE_FIELDS = ("code", "id") +class _MalformedMergeKey(ValueError): + """An array of tables keys on a value that cannot identify an entry (anything but + a non-empty string, e.g. ``id = ["quick"]`` or ``id = 1``) — BMAD v7's resolver + rejects the whole customization on it rather than merging.""" + + def _keyed_merge_field(items: list[Any]) -> str | None: """The key an array of tables merges on, or None to append. @@ -477,10 +549,17 @@ def _merge_layer_arrays(base: list[Any], override: list[Any]) -> list[Any]: `src/scripts/resolve_customization.py`: keyed merge when the combined array opts into one (matching keys replace in place, new keys append), plain concatenation otherwise. + + Raises :class:`_MalformedMergeKey` when the chosen key holds anything but a + non-empty string, as v7's ``_detect_keyed_merge_field`` raises ``ConfigError`` — + and an array or table key would otherwise crash the preflight with ``TypeError``. """ key = _keyed_merge_field(base + override) if key is None: return base + override + for item in base + override: + if not isinstance(item[key], str) or not item[key]: + raise _MalformedMergeKey(f"`{key}` = {item[key]!r} is not a valid array-entry key") result: list[Any] = [] index_by_key: dict[Any, int] = {} for item in base: @@ -503,26 +582,53 @@ def _merge_layer_arrays(base: list[Any], override: list[Any]) -> list[Any]: return result -def _merged_review_layers( - project: Path, tree: str, skill: str -) -> tuple[list[Any], tuple[str, ...]] | None: +class _MergedReview(NamedTuple): + """A primitive's review config with project overrides applied, in every shape. + + ``layers`` is the merged ``review_layers`` array. ``lens_shape`` is True when the + SHIPPED config carries a lens set and no review layer — the v7 primitive, whose + run reads only ``lens_sets`` (each merged independently) and ``selection``. + """ + + layers: list[Any] + unreadable: tuple[str, ...] + lens_shape: bool + lens_sets: dict[str, list[Any]] + selection: str | None + + +def _merged_review_layers(project: Path, tree: str, skill: str) -> _MergedReview | None: """The skill's shipped review layers with project overrides applied. ``skill`` is the resolved dev-primitive name — the shipped config and its overrides are read from the SAME era, because that is what the run does. - Returns ``(layers, unreadable_override_paths)``, or None when the skill's OWN - customize.toml is absent or unparseable — the one case that genuinely means - "shape unknown", so the caller falls back to the static catalog. + Returns a :class:`_MergedReview`, or None when the skill's OWN customize.toml is + absent or unparseable — the one case that genuinely means "shape unknown", so + the caller falls back to the static catalog. - An unparseable OVERRIDE is not that case: BMAD's resolver warns and treats it - as empty, still resolving every other layer. Matching that keeps the preflight - agreeing with the run; the broken file is reported separately as a warning. + An unparseable OVERRIDE is not that case: the layer-era resolver warns and + treats it as empty, still resolving every other layer, so the preflight leaves + it out the same way and reports it separately — a warning there, a problem on + a v7 tree, whose strict loader refuses to render the skill at all. + + The lens sets merge exactly as the layers do, each set on its own (BMAD's + resolver deep-merges each array of tables by its key), and ``workflow.review`` + is a scalar: the last value wins, string or not. + + The shape is decided by the SHIPPED file, not the merge: a v7 run reads only the + lens sets, so a ``review_layers`` override left over from a v6 install is inert + there and must not pull the preflight onto the layer path — that would require + skills the run never invokes. A shipped file carrying a review layer keeps the + layer path whatever lens tables it also carries (the v6.10-6.12 contract). """ data = _read_toml(project / tree / skill / "customize.toml") if data is None: return None layers = _layers_of(data) + lens_sets = _lens_sets_of(data) + lens_shape = bool(lens_sets) and not layers + selection = _review_selection_of(data) unreadable: list[str] = [] for rel in _customize_overrides(skill): override = project / rel @@ -532,14 +638,64 @@ def _merged_review_layers( if extra is None: unreadable.append(rel.as_posix()) continue - layers = _merge_layer_arrays(layers, _layers_of(extra)) - return layers, tuple(unreadable) + try: + merged_layers = _merge_layer_arrays(layers, _layers_of(extra)) + merged_sets = { + name: _merge_layer_arrays(lens_sets.get(name, []), lenses) + for name, lenses in _lens_sets_of(extra).items() + } + except _MalformedMergeKey: + # reported with the unparseable overrides; the file is left out whole + unreadable.append(rel.as_posix()) + continue + layers = merged_layers + lens_sets.update(merged_sets) + override_selection = _review_selection_of(extra) + if override_selection is not None: + selection = override_selection + return _MergedReview(layers, tuple(unreadable), lens_shape, lens_sets, selection) -def _layer_id(layer: dict[str, Any], index: int) -> str: - """A layer's id for reporting — positional when it declares none.""" +def _layer_id(layer: dict[str, Any], index: int, label: str = "") -> str: + """A layer's id for reporting — positional when it declares none, prefixed with + ``label`` (a lens set's name) so positions in two sets cannot collide.""" lid = layer.get("id") - return lid if isinstance(lid, str) and lid else f"#{index + 1}" + return lid if isinstance(lid, str) and lid else f"{label}#{index + 1}" + + +def _collect_layer_skills( + layers: list[Any], + required: dict[str, list[str]], + advisory: dict[str, list[str]], + active: list[str], + label: str = "", +) -> None: + """Fold one array of review layers (or lenses) into the requirement buckets. + + A non-gated layer's invocation phrasing is required; a ``when``-gated layer's + invocations, and any bmad-* token not tied to an invocation phrasing, are + advisory. Empty-``instruction`` layers are disabled and contribute nothing. + """ + for index, layer in enumerate(layers): + if not isinstance(layer, dict): + continue + instruction = layer.get("instruction") + if not isinstance(instruction, str) or not instruction.strip(): + continue + layer_id = _layer_id(layer, index, label) + active.append(layer_id) + when = layer.get("when") + gated = isinstance(when, str) and bool(when.strip()) + invoked = _INVOKE_SKILL_RE.findall(instruction) + # A gated layer's invocations are advisory; so is any bmad-* token we + # can't tie to an invocation phrasing, in either kind of layer. + hard = [] if gated else invoked + soft = [s for s in _SKILL_REF_RE.findall(instruction) if gated or s not in invoked] + for bucket, skills in ((required, hard), (advisory, soft)): + for skill in skills: + ids = bucket.setdefault(skill, []) + if layer_id not in ids: + ids.append(layer_id) def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: @@ -569,6 +725,16 @@ def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: every layer whose condition does not hold, and that condition is evaluated by the model in run context — undecidable here, so hard-requiring its skill would be a false FAIL. + + BMAD v7 replaced the layers with two lens sets, ``[[workflow.quick_lenses]]`` + and ``[[workflow.thorough_lenses]]``, selected per run by ``workflow.review``. + Each lens is read with the same per-layer rule, over BOTH sets: the selection + that runs is not knowable from config (``auto`` follows the route the model + resolves, the invocation may ``--set workflow.review=...``, and bmad-loop's own + ``[tickets] thorough_review`` asks for ``thorough``), so any enabled lens may + run — the same rule that requires every enabled review layer. Shape precedence + is decided by :func:`_merged_review_layers`: a review-layer config keeps the + layer path, a v7 config takes the lens path, and anything else falls to step-04. """ # `primitive`, not `skill`: the layer loop below binds `skill` to each INVOKED # review skill, and the step-04 fallback after it reads this name as a directory. @@ -578,31 +744,20 @@ def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: merged = _merged_review_layers(project, tree, primitive) if merged is None: return None - layers, unreadable = merged - if layers: + unreadable = merged.unreadable + if merged.lens_shape or merged.layers: required: dict[str, list[str]] = {} advisory: dict[str, list[str]] = {} active: list[str] = [] - for index, layer in enumerate(layers): - if not isinstance(layer, dict): - continue - instruction = layer.get("instruction") - if not isinstance(instruction, str) or not instruction.strip(): - continue - layer_id = _layer_id(layer, index) - active.append(layer_id) - when = layer.get("when") - gated = isinstance(when, str) and bool(when.strip()) - invoked = _INVOKE_SKILL_RE.findall(instruction) - # A gated layer's invocations are advisory; so is any bmad-* token we - # can't tie to an invocation phrasing, in either kind of layer. - hard = [] if gated else invoked - soft = [s for s in _SKILL_REF_RE.findall(instruction) if gated or s not in invoked] - for bucket, skills in ((required, hard), (advisory, soft)): - for skill in skills: - ids = bucket.setdefault(skill, []) - if layer_id not in ids: - ids.append(layer_id) + active_sets: list[str] = [] + if merged.lens_shape: + for name, lenses in merged.lens_sets.items(): + before = len(active) + _collect_layer_skills(lenses, required, advisory, active, name) + if len(active) > before: + active_sets.append(name) + else: + _collect_layer_skills(merged.layers, required, advisory, active) return ReviewResolution( "customize.toml", {s: tuple(i) for s, i in required.items()}, @@ -611,6 +766,9 @@ def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: True, tuple(active), unreadable, + tuple(merged.lens_sets) if merged.lens_shape else (), + merged.selection if merged.lens_shape else None, + tuple(active_sets), ) try: step04 = (project / tree / primitive / "step-04-review.md").read_text(encoding="utf-8") @@ -638,7 +796,9 @@ def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: STORIES_PROBE_TEXT = "folder+id dispatch" -def missing_stories_support(project: Path, trees: Sequence[str]) -> list[Finding]: +def missing_stories_support( + project: Path, trees: Sequence[str], *, skip_unresolved: bool = False +) -> list[Finding]: """Problems for stories mode's stricter dev-primitive requirement. Sprint mode drives any dev primitive; stories mode needs the folder+id @@ -652,10 +812,19 @@ def missing_stories_support(project: Path, trees: Sequence[str]) -> list[Finding The two failures are separate check ids because they are separate conditions with separate remediations: ``-missing`` is a half install (reinstall the - module), ``-stale`` is an install that is simply too old (update it).""" + module), ``-stale`` is an install that is simply too old (update it). + + A tree whose primitive does not resolve is probed under + :data:`DEV_PRIMITIVE_NEW` — the name to install — and reported ``-missing``. + ``skip_unresolved`` drops such a tree instead: pass it only from a caller that + runs :func:`missing_base_skills` over the same trees, which already reports it + (``skills.base-missing``/``-shim``) and keeps the run refused.""" problems: list[Finding] = [] for tree in dict.fromkeys(trees): - skill = dev_primitive_or_default(project, tree) + skill = resolve_dev_primitive(project, tree) + if skill is None and skip_unresolved: + continue + skill = skill or DEV_PRIMITIVE_NEW probe = project / tree / skill / STORIES_PROBE_FILE detail = {"tree": tree, "skill": skill, "file": STORIES_PROBE_FILE} try: @@ -717,18 +886,24 @@ def bmod_method_version(project: Path, trees: Sequence[str]) -> str | None: return None -def missing_tickets_support(project: Path, trees: Sequence[str]) -> list[Finding]: +def missing_tickets_support( + project: Path, trees: Sequence[str], *, skip_unresolved: bool = False +) -> list[Finding]: """Problems for tickets mode's dev-primitive requirement: the resolved primitive's ``step-01-clarify-and-route.md`` must route a ticket from the tree (it carries :data:`TICKETS_PROBE_TEXT`). One problem :class:`Finding` per ``trees`` entry lacking it; callers gate this on tickets mode only. ``-missing`` (the step file is absent or unreadable: a half install) and - ``-stale`` (an install too old to know the ticket tree) are separate ids, as - in :func:`missing_stories_support`.""" + ``-stale`` (an install too old to know the ticket tree) are separate ids, and an + unresolved primitive is named and ``skip_unresolved`` honoured, as in + :func:`missing_stories_support`.""" problems: list[Finding] = [] for tree in dict.fromkeys(trees): - skill = dev_primitive_or_default(project, tree) + skill = resolve_dev_primitive(project, tree) + if skill is None and skip_unresolved: + continue + skill = skill or DEV_PRIMITIVE_NEW probe = project / tree / skill / TICKETS_PROBE_FILE detail = {"tree": tree, "skill": skill, "file": TICKETS_PROBE_FILE} try: @@ -1353,7 +1528,9 @@ def missing_sweep_skill(project: Path, trees: Sequence[str]) -> list[Finding]: return problems -def missing_base_skills(project: Path, trees: Sequence[str]) -> list[Finding]: +def missing_base_skills( + project: Path, trees: Sequence[str], *, home: Path | None = None +) -> list[Finding]: """Problems for the upstream skills the orchestrator drives but doesn't bundle. The dev primitive (bmad-build-auto, or a complete pre-rename bmad-dev-auto) and @@ -1395,6 +1572,11 @@ def missing_base_skills(project: Path, trees: Sequence[str]) -> list[Finding]: can have a post-consolidation `.claude` tree and a pre-merge `.agents` one side by side — and, across the rename, a different primitive era in each. + A nothing-resolved ``skills.base-missing`` notes a global install of the + primitive (``~/.claude/skills`` or ``~/.agents/skills``) when one exists, with + its path in ``detail["outside"]``; ``home`` overrides the probed home directory + (tests inject it). That is a hint, never a resolution: the run still refuses. + ``skills.base-incomplete`` carries ``missing_markers`` as a list — the message joins it with ", " for the human line, which a consumer would otherwise have to split back apart on a separator the message is free to change. @@ -1440,6 +1622,7 @@ def missing_base_skills(project: Path, trees: Sequence[str]) -> list[Finding]: ) ) elif resolved is None: + hint, outside = _outside_hint(DEV_PRIMITIVE_NEW, tree, home) problems.append( Finding( "skills.base-missing", @@ -1447,8 +1630,8 @@ def missing_base_skills(project: Path, trees: Sequence[str]) -> list[Finding]: f"{tree}/{DEV_PRIMITIVE_NEW} not found — the orchestrator drives this " f"upstream dev primitive directly; it ships with {BMAD_FLOOR_TEXT}; " f"install or update bmm (on v7, method) in this project " - f"(older installs name it {DEV_PRIMITIVE_LEGACY})", - {"tree": tree, "skill": DEV_PRIMITIVE_NEW}, + f"(older installs name it {DEV_PRIMITIVE_LEGACY}){hint}", + {"tree": tree, "skill": DEV_PRIMITIVE_NEW, **outside}, ) ) else: @@ -1505,7 +1688,7 @@ def missing_base_skills(project: Path, trees: Sequence[str]) -> list[Finding]: }, ) ) - problems.extend(_review_findings(project, tree)) + problems.extend(_review_findings(project, tree, home=home)) if resolved_stub and not (project / CENTRAL_CONFIG_REL).is_file(): problems.append( Finding( @@ -1883,6 +2066,48 @@ def dev_primitive_warnings(project: Path, trees: Sequence[str]) -> list[Finding] return findings +# Where `npx skills add -g` lays a skill down, relative to the home directory. Probed +# read-only for a HINT only: bmad-loop drives skills from the project's own tree and +# never resolves one from here (a session cwd'd in the project would not see it in +# every CLI, and a worktree could not seed it). Claude Code's plugin cache is not +# probed — BMAD no longer ships Claude plugins. +_OUTSIDE_SKILL_ROOTS = (".claude/skills", ".agents/skills") + + +def _outside_home() -> Path: + """The home directory :func:`_outside_copy` probes by default. A seam: the test + suite pins it (conftest) so an operator's real global skills never leak into a + finding a test asserts on.""" + return Path.home() + + +def _outside_copy(name: str, home: Path | None = None) -> str | None: + """``~//`` for the first global install of skill ``name`` found under + :data:`_OUTSIDE_SKILL_ROOTS`, or None. An undeterminable or unreadable home is + None: this only decorates a finding, so it must never crash the preflight.""" + try: + base = _outside_home() if home is None else home + for root in _OUTSIDE_SKILL_ROOTS: + if (base / root / name / "SKILL.md").is_file(): + return f"~/{root}/{name}" + except (OSError, RuntimeError): + return None + return None + + +def _outside_hint(name: str, tree: str, home: Path | None) -> tuple[str, dict[str, str]]: + """The message suffix and detail entry for a skill installed only outside the + project (:func:`_outside_copy`), or ``("", {})`` when there is none.""" + outside = _outside_copy(name, home) + if outside is None: + return "", {} + return ( + f"; a copy exists at {outside}, but bmad-loop only drives skills installed in " + f"this project's {tree} — install it per project (`npx skills add` without -g)", + {"outside": outside}, + ) + + def _where_clause(layer_ids: Sequence[str]) -> str: """How a finding's message names the layers that reach for a skill.""" if len(layer_ids) > 1: @@ -1892,7 +2117,7 @@ def _where_clause(layer_ids: Sequence[str]) -> str: return "review step invokes" -def _review_findings(project: Path, tree: str) -> list[Finding]: +def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> list[Finding]: """Findings for the review skills this tree's dev primitive invokes. Problems block; warnings never do. A skill is only a problem when the @@ -1906,40 +2131,99 @@ def _review_findings(project: Path, tree: str) -> list[Finding]: send them to a path that does not exist on a renamed project. The static-catalog fallback below has no :class:`ReviewResolution` to carry the name, so this resolves independently rather than widening that tuple. + + A tree whose primitive does not resolve gets NO review finding: the reviewers + derive from the primitive, :func:`missing_base_skills` already reports that root + cause, and the static fallback would otherwise demand the long-deleted hunters on + top of it. ``home`` overrides the home directory the out-of-project hint probes + (:func:`_outside_copy`); tests inject it. """ - primitive = dev_primitive_or_default(project, tree) + primitive = resolve_dev_primitive(project, tree) + if primitive is None: + return [] resolved = resolve_review_layers(project, tree) if resolved is None: # Unknown shape: keep the long-standing static requirement, which both real # topologies satisfy — the two hunters, or the merged reviewer instead. if (project / tree / MERGED_REVIEW_SKILL / "SKILL.md").is_file(): return [] - return [ - Finding( - "skills.base-missing", - "problem", - f"{tree}/{skill} not found — this review layer ships with " - f"{BMAD_FLOOR_TEXT}, as does the consolidated {MERGED_REVIEW_SKILL} " - f"skill that supersedes it in newer releases; install or update bmm " - f"(on v7, method) in this project", - {"tree": tree, "skill": skill}, + fallback: list[Finding] = [] + for skill in sorted(_REVIEW_LAYER_SKILLS): + if (project / tree / skill / "SKILL.md").is_file(): + continue + hint, outside = _outside_hint(skill, tree, home) + fallback.append( + Finding( + "skills.base-missing", + "problem", + f"{tree}/{skill} not found — this review layer ships with " + f"{BMAD_FLOOR_TEXT}, as does the consolidated {MERGED_REVIEW_SKILL} " + f"skill that supersedes it in newer releases; install " + f"{REVIEW_FLOOR_TEXT} in this project{hint}", + {"tree": tree, "skill": skill, **outside}, + ) ) - for skill in sorted(_REVIEW_LAYER_SKILLS) - if not (project / tree / skill / "SKILL.md").is_file() - ] + return fallback findings: list[Finding] = [] for rel in resolved.unreadable: + # v7 renders the primitive through `render_skill.py`, whose strict loader + # raises on this file, so no dev run starts; the layer-era resolver skipped it. + v7 = bool(resolved.lens_sets) + consequence = ( + "BMAD v7 refuses to render the dev skill with it, so every dev run fails to start" + if v7 + else "this project's review layers resolve without it" + ) findings.append( Finding( "skills.customize-unreadable", - "warning", - f"{rel} could not be parsed as TOML — the run's resolver skips a broken " - f"override layer, so this project's review layers resolve without it; " - f"fix the file or remove it", + "problem" if v7 else "warning", + f"{rel} could not be read as a customize override (invalid TOML, or an " + f"array entry whose `id`/`code` is not a non-empty string) — " + f"{consequence}; fix the file or remove it", {"tree": tree, "file": rel}, ) ) - if resolved.layer_driven and not resolved.active_layers: + override_rel = _customize_overrides(primitive)[0].as_posix() + selection = resolved.selection + if resolved.lens_sets and selection is not None and selection not in REVIEW_SELECTIONS: + findings.append( + Finding( + "skills.review-selection-invalid", + "problem", + f"{tree}/{primitive} resolves workflow.review = {selection!r} — its " + f"workflow HALTs every dev run on any value but " + f"{', '.join(REVIEW_SELECTIONS)}; fix `review` in {override_rel} or in " + f"the skill's customize.toml", + {"tree": tree, "source": resolved.source, "selection": selection}, + ) + ) + if resolved.lens_sets: + # `quick`/`thorough` launch only their own set, so an enabled lens in the other + # one cannot serve the run; `auto` may route to either, so it needs just one. + # An unset selection is left to the run: whether it HALTs is undecidable here. + if selection in LENS_SETS: + checked: tuple[str, ...] = (selection,) + else: + checked = resolved.lens_sets + if ( + selection is not None + and selection != "none" + and not any(name in resolved.active_sets for name in checked) + ): + tables = " / ".join(f"[[workflow.{LENS_SETS[n]}]]" for n in checked) + findings.append( + Finding( + "skills.review-layers-empty", + "problem", + f"{tree}/{primitive} has no enabled review lens (every `instruction` " + f"in {tables} is empty or absent) while workflow.review is " + f"{selection!r} — every dev run would HALT with no lens to launch; " + f're-enable a lens in {override_rel}, or set review = "none" there', + {"tree": tree, "source": resolved.source}, + ) + ) + elif resolved.layer_driven and not resolved.active_layers: findings.append( Finding( "skills.review-layers-empty", @@ -1947,26 +2231,28 @@ def _review_findings(project: Path, tree: str) -> list[Finding]: f"{tree}/{primitive} has no enabled review layer (every " f"`instruction` is empty) — every dev run would HALT blocked with " f"'no active review layers'; re-enable a layer in " - f"{_customize_overrides(primitive)[0].as_posix()}", + f"{override_rel}", {"tree": tree, "source": resolved.source}, ) ) for skill, layer_ids in sorted(resolved.required.items()): if (project / tree / skill / "SKILL.md").is_file(): continue + hint, outside = _outside_hint(skill, tree, home) findings.append( Finding( "skills.review-layer-missing", "problem", f"{tree}/{skill} not found — {tree}/{primitive}'s " f"{_where_clause(layer_ids)} it ({resolved.source}), so every dev run's " - f"review would fail; install or update the bmm module so this project's " - f"review layers resolve", + f"review would fail; install {REVIEW_FLOOR_TEXT} so this project's " + f"review layers resolve{hint}", { "tree": tree, "skill": skill, "layers": list(layer_ids), "source": resolved.source, + **outside, }, ) ) diff --git a/tests/conftest.py b/tests/conftest.py index 461ad360b..5e2c8da46 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1099,6 +1099,19 @@ def _stub_cli_version(monkeypatch): monkeypatch.setattr(install, "cli_version", lambda profile: STUB_CLI_VERSION) +@pytest.fixture(autouse=True) +def _isolate_outside_skill_home(monkeypatch, tmp_path_factory): + """Pin the home directory the out-of-project skill hint probes (#768). + + `install.missing_base_skills` notes a global `~/.claude/skills` or + `~/.agents/skills` copy of a missing skill in the finding's message and detail. + Unpinned, every test asserting on such a finding would depend on what the host + has installed globally — a developer with `npx skills add -g` would see failures + CI never does. Tests of the hint pass `home=` explicitly instead.""" + empty = tmp_path_factory.getbasetemp() / "no-outside-home" + monkeypatch.setattr(install, "_outside_home", lambda: empty) + + @pytest.fixture(autouse=True) def _isolate_mux_registry(monkeypatch): """Keep the psmux registry root, and the inside-a-pane marker, out of the diff --git a/tests/test_cli.py b/tests/test_cli.py index c35a2670a..d60409160 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -16398,6 +16398,56 @@ def v7_config(sandbox): ) +def test_validate_tickets_unresolved_primitive_reports_root_cause_only( + project, capsys, monkeypatch +): + """#768: with the dev primitive gone, validate reports `skills.base-missing` — + not a tickets-dispatch finding naming the legacy `bmad-dev-auto` step file, and + never a green `skills.tickets-dispatch` line from a probe that skipped the tree. + Ablation: drop the `_all_resolve` gate and the ok line comes back.""" + import shutil as _shutil + + from bmad_loop.install import DEV_PRIMITIVE_LEGACY, DEV_PRIMITIVE_NEW + + _make_tickets_validate_pass(project, monkeypatch, capsys) + _shutil.rmtree(project.project / ".claude" / "skills" / DEV_PRIMITIVE_NEW) + + doc = machine_json(["validate", "--project", str(project.project), "--json"], capsys, rc=1) + + assert doc["ok"] is False + checks = [f["check"] for f in doc["findings"]] + assert "skills.base-missing" in checks + assert not any(c.startswith("skills.tickets-dispatch") for c in checks) + # base-missing names the old spelling as a hint; no finding sends anyone to its dir + assert not any(f"{DEV_PRIMITIVE_LEGACY}/" in f["message"] for f in doc["findings"]) + + +@pytest.mark.parametrize("mode", ["tickets", "stories"]) +def test_require_base_skills_unresolved_primitive_still_refuses(tmp_path, capsys, mode): + """The run-start preflight skips the dispatch probe on an unresolved tree (it + would only restate the root cause under the legacy name) yet still refuses.""" + from bmad_loop.install import DEV_PRIMITIVE_LEGACY, DEV_PRIMITIVE_NEW + + _write_policy(tmp_path) + pol = policy_mod.load(tmp_path / ".bmad-loop" / "policy.toml") + + assert ( + cli._require_base_skills( + tmp_path, + pol, + tmp_path, + GrantSet.empty(), + require_tickets=mode == "tickets", + require_stories=mode == "stories", + ) + is False + ) + err = capsys.readouterr().err + assert f"{DEV_PRIMITIVE_NEW} not found" in err + assert DEV_PRIMITIVE_LEGACY + "/" not in err + assert "dispatch" not in err + + def test_validate_json_tickets_mode_document(project, capsys, monkeypatch): """A tickets project bmad-loop can drive validates ok: `mode` is `tickets`, the document names the active initiative and the v7 era, and the tickets checks ran diff --git a/tests/test_install.py b/tests/test_install.py index fc3ca79d7..989fed4d8 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -53,6 +53,7 @@ RENDERER_CONFIG_UTILS_REL, RENDERER_ENTRY_REL, RENDERER_SCRIPT_REL, + REVIEW_FLOOR_TEXT, SNAPSHOT_TOKEN_RE, _absent_renderer_sources, _copy_traversable, @@ -2967,11 +2968,10 @@ def test_floor_message_names_v7(tmp_path): def test_missing_base_skills_reports_absent_and_incomplete(tmp_path): claude = get_profile("claude") - # nothing installed → dev primitive + the two inline review layers reported - # missing (the hunters are required whenever the merged reviewer is absent — - # the primitive's step-04 invokes them on every run) + # nothing installed → only the dev primitive is reported missing: the review + # skills derive from it, so with nothing to derive from they are not demanded problems = missing_base_skills(tmp_path, [claude.skill_tree]) - assert len(problems) == 3 + assert len(problems) == 1 assert {p.check for p in problems} == {"skills.base-missing"} assert all("BMAD-METHOD >= 6.10.0" in p.message for p in problems) assert all(BMAD_FLOOR_TEXT in p.message for p in problems) @@ -3097,6 +3097,9 @@ def test_missing_stories_support_probes_step01_content(tmp_path): claude = get_profile("claude") tree = claude.skill_tree + # a resolvable primitive (SKILL.md is all the new name needs to resolve): an + # unresolved tree is named, but probed under DEV_PRIMITIVE_NEW, not this dir + _install_skills(tmp_path, tree, {STORIES_PROBE_SKILL: DEV_PRIMITIVE_MARKERS}) step01 = tmp_path / tree / STORIES_PROBE_SKILL / STORIES_PROBE_FILE # step-01 absent → reported (older/half install) @@ -3127,12 +3130,9 @@ def test_missing_base_skills_findings_carry_ids_and_detail(tmp_path): assert all(f.severity == "problem" for f in absent) assert all(f.check in VALIDATE_CHECKS for f in absent) # an empty tree names the CURRENT spelling — the older one appears in the - # message as a hint, never as the thing a consumer keys on - assert {f.detail["skill"] for f in absent} == { - DEV_PRIMITIVE_NEW, - "bmad-review-adversarial-general", - "bmad-review-edge-case-hunter", - } + # message as a hint, never as the thing a consumer keys on — and only the + # primitive: the reviewers derive from it, so none is demanded without it + assert {f.detail["skill"] for f in absent} == {DEV_PRIMITIVE_NEW} assert all(f.detail["tree"] == claude.skill_tree for f in absent) _install_base_skills(tmp_path, claude.skill_tree) @@ -3915,7 +3915,7 @@ def test_review_hunter_missing_without_merged_review_reported(tmp_path): } assert "bmad-review-edge-case-hunter" in problems[0].message assert "install the BMad Method" not in problems[0].message - assert "update bmm" in problems[0].message + assert REVIEW_FLOOR_TEXT in problems[0].message # The invoke-a-skill layer topology: four review layers, three invoking the merged @@ -5774,6 +5774,8 @@ def test_missing_stories_support_findings_split_absent_from_stale(tmp_path): claude = get_profile("claude") tree = claude.skill_tree + # a complete legacy primitive resolves, so the probe reads THIS dir + _install_skills(tmp_path, tree, {STORIES_PROBE_SKILL: DEV_PRIMITIVE_MARKERS}) step01 = tmp_path / tree / STORIES_PROBE_SKILL / STORIES_PROBE_FILE absent = missing_stories_support(tmp_path, [tree]) @@ -12651,3 +12653,439 @@ def test_missing_tickets_support_findings_split_absent_from_stale(tmp_path): install_build_auto_v7_skill(tmp_path, tree) assert missing_tickets_support(tmp_path, [tree]) == [] + + +# The BMAD v7 lens shape (BMAD-METHOD #2861), trimmed from the shipped +# bmad-build-auto/customize.toml: a `review` selection plus two lens sets. Every +# shipped lens says "Do not invoke any skill" — the derived requirement is empty. +LENS_CUSTOMIZE = ''' +[workflow] +review = "quick" + +[[workflow.quick_lenses]] +id = "quick" +name = "Quick" +instruction = """ +Launch a context-free subagent with this prompt: + +Read `{plan_file}` and the unified diff at `{diff_file}`. Report findings. +Do not invoke any skill, and do not spawn subagents of your own. +""" + +[[workflow.thorough_lenses]] +id = "blind-hunter" +name = "Blind Hunter" +instruction = """ +Launch a context-free subagent with this prompt: + +CONTENT: the unified diff at `{diff_file}`. +Do not invoke any skill, and do not spawn subagents of your own. +""" + +[[workflow.thorough_lenses]] +id = "edge-case-hunter" +name = "Edge Case Hunter" +instruction = """ +Launch a context-free subagent with this prompt: + +Read `{skill-root}/review-prompts/edge-case-hunter.md` completely and follow it. +Do not invoke any skill, and do not spawn subagents of your own. +""" +''' + +_HUNTERS = {"bmad-review-adversarial-general", "bmad-review-edge-case-hunter"} + + +def _lens_tree(root, customize=LENS_CUSTOMIZE): + """A v7 primitive (bmad-build-auto) carrying ``customize``, alone in its tree.""" + tree = get_profile("claude").skill_tree + _install_dev_auto(root, tree, skill=DEV_PRIMITIVE_NEW, customize=customize) + return tree + + +def test_v7_lens_sets_require_no_review_skill(tmp_path): + """#768: a v7 tree reviews through its own lens prompts and invokes no skill, so + neither the merged reviewer nor the two long-deleted hunters is demanded. + Ablation: with the lens path removed from resolve_review_layers the shape reads + as unknown and the static fallback FAILs on both hunters.""" + tree = _lens_tree(tmp_path) + assert not (tmp_path / tree / "bmad-review").exists() + + assert missing_base_skills(tmp_path, [tree]) == [] + + +def test_v7_lens_resolution_is_layer_driven(tmp_path): + tree = _lens_tree(tmp_path) + + resolved = resolve_review_layers(tmp_path, tree) + + assert resolved is not None + assert resolved.source == "customize.toml" + assert resolved.layer_driven is True + assert resolved.required == {} + assert resolved.advisory == {} + # BOTH sets count: the selection that runs is decided at run time + assert resolved.active_layers == ("quick", "blind-hunter", "edge-case-hunter") + assert resolved.lens_sets == ("quick", "thorough") + assert resolved.selection == "quick" + + +def test_v7_lens_invoking_a_skill_is_required_in_either_set(tmp_path): + """A thorough lens runs whenever the run asks for thorough (`auto` on a full + route, `--set workflow.review=thorough`, `[tickets] thorough_review`), so a + skill it invokes is required even while the configured selection is quick.""" + invoking = LENS_CUSTOMIZE.replace( + "Read `{skill-root}/review-prompts/edge-case-hunter.md` completely and follow it.", + "Invoke the `bmad-foo` skill on this diff.", + ) + tree = _lens_tree(tmp_path, invoking) + + problems = missing_base_skills(tmp_path, [tree]) + + assert [p.check for p in problems] == ["skills.review-layer-missing"] + assert problems[0].severity == "problem" + assert problems[0].detail["skill"] == "bmad-foo" + assert problems[0].detail["layers"] == ["edge-case-hunter"] + + _install_skills(tmp_path, tree, {"bmad-foo": ()}) + assert missing_base_skills(tmp_path, [tree]) == [] + + +def test_v7_gated_lens_skill_is_advisory(tmp_path): + """#260: a `when`-gated lens may never run, so its skill only warns.""" + gated = LENS_CUSTOMIZE.replace( + 'name = "Blind Hunter"\n', + 'name = "Blind Hunter"\nwhen = "the diff touches auth"\n', + ).replace( + "CONTENT: the unified diff at `{diff_file}`.", + "Invoke the `bmad-foo` skill on this diff.", + ) + tree = _lens_tree(tmp_path, gated) + + findings = missing_base_skills(tmp_path, [tree]) + + assert [(f.check, f.severity) for f in findings] == [ + ("skills.review-layer-unresolved", "warning") + ] + assert findings[0].detail["layers"] == ["blind-hunter"] + + +def test_v7_lens_override_replaces_by_id(tmp_path): + """The lens sets merge with project overrides keyed on `id`, per set — the + same deep merge BMAD's resolver applies at run time.""" + tree = _lens_tree(tmp_path) + override = _write_override( + tmp_path, + '[[workflow.thorough_lenses]]\nid = "blind-hunter"\n' + 'instruction = "Invoke the `bmad-foo` skill on this diff."\n', + skill=DEV_PRIMITIVE_NEW, + ) + + problems = missing_base_skills(tmp_path, [tree]) + assert [p.check for p in problems] == ["skills.review-layer-missing"] + assert problems[0].detail["layers"] == ["blind-hunter"] + + # an override emptying the lens disables it: nothing is required any more + override.write_text( + '[[workflow.thorough_lenses]]\nid = "blind-hunter"\ninstruction = ""\n', + encoding="utf-8", + ) + assert missing_base_skills(tmp_path, [tree]) == [] + resolved = resolve_review_layers(tmp_path, tree) + assert resolved is not None + assert "blind-hunter" not in resolved.active_layers + + +_ALL_LENSES_OFF = ( + '[[workflow.quick_lenses]]\nid = "quick"\ninstruction = ""\n' + '[[workflow.thorough_lenses]]\nid = "blind-hunter"\ninstruction = ""\n' + '[[workflow.thorough_lenses]]\nid = "edge-case-hunter"\ninstruction = ""\n' +) + + +def test_v7_all_lenses_disabled_is_reported(tmp_path): + """Every lens disabled under `auto` leaves the run nothing to launch on either + route. Ablation: drop the lens branch's empty check and this goes green.""" + tree = _lens_tree(tmp_path) + _write_override( + tmp_path, '[workflow]\nreview = "auto"\n' + _ALL_LENSES_OFF, skill=DEV_PRIMITIVE_NEW + ) + + problems = missing_base_skills(tmp_path, [tree]) + + assert [p.check for p in problems] == ["skills.review-layers-empty"] + assert problems[0].severity == "problem" + assert "[[workflow.quick_lenses]]" in problems[0].message + assert "[[workflow.thorough_lenses]]" in problems[0].message + + +@pytest.mark.parametrize( + ("selection", "disabled", "empty_table"), + [ + ("quick", '[[workflow.quick_lenses]]\nid = "quick"\ninstruction = ""\n', "quick_lenses"), + ( + "thorough", + '[[workflow.thorough_lenses]]\nid = "blind-hunter"\ninstruction = ""\n' + '[[workflow.thorough_lenses]]\nid = "edge-case-hunter"\ninstruction = ""\n', + "thorough_lenses", + ), + ], +) +def test_v7_selected_lens_set_disabled_is_reported(tmp_path, selection, disabled, empty_table): + """`quick`/`thorough` launch only their own set, so an enabled lens in the OTHER + set cannot serve the run. Ablation: check the combined active lenses instead of + the selected set and this goes green.""" + tree = _lens_tree(tmp_path) + _write_override( + tmp_path, f'[workflow]\nreview = "{selection}"\n' + disabled, skill=DEV_PRIMITIVE_NEW + ) + + problems = missing_base_skills(tmp_path, [tree]) + + assert [p.check for p in problems] == ["skills.review-layers-empty"] + assert f"[[workflow.{empty_table}]]" in problems[0].message + # the set that cannot run is not offered as the culprit + other = "thorough_lenses" if empty_table == "quick_lenses" else "quick_lenses" + assert other not in problems[0].message + + +def test_v7_auto_selection_needs_one_enabled_set(tmp_path): + """`auto` may route to either set, so one disabled set is not a HALT.""" + tree = _lens_tree(tmp_path) + _write_override( + tmp_path, + '[workflow]\nreview = "auto"\n[[workflow.quick_lenses]]\nid = "quick"\ninstruction = ""\n', + skill=DEV_PRIMITIVE_NEW, + ) + + assert missing_base_skills(tmp_path, [tree]) == [] + resolved = resolve_review_layers(tmp_path, tree) + assert resolved is not None and resolved.active_sets == ("thorough",) + + +@pytest.mark.parametrize("key", ["id", "code"]) +@pytest.mark.parametrize("value", ['["quick"]', "{ a = 1 }", "1", '""']) +def test_v7_lens_override_with_malformed_key_is_reported_not_raised(tmp_path, key, value): + """v7's loader accepts only a non-empty string merge key and refuses to render + the skill otherwise; the preflight reports the override as a problem instead of + crashing with TypeError on an unhashable key, and leaves the file out whole. + Ablation: drop the `_MalformedMergeKey` guard and the array/table cases raise + TypeError out of missing_base_skills while the int/empty cases go clean.""" + tree = _lens_tree(tmp_path) + shipped = LENS_CUSTOMIZE if key == "id" else LENS_CUSTOMIZE.replace("\nid = ", "\ncode = ") + _lens_tree(tmp_path, shipped) + _write_override( + tmp_path, + f'[[workflow.quick_lenses]]\n{key} = {value}\ninstruction = ""\n', + skill=DEV_PRIMITIVE_NEW, + ) + + findings = missing_base_skills(tmp_path, [tree]) + + assert [(f.check, f.severity) for f in findings] == [("skills.customize-unreadable", "problem")] + assert "fails to start" in findings[0].message + resolved = resolve_review_layers(tmp_path, tree) + assert resolved is not None + assert "quick" in resolved.active_sets + + +def test_v7_unparseable_override_is_a_problem(tmp_path): + """v7 renders the dev skill through a strict loader that raises on invalid TOML + in an override, so no dev run starts; the layer-era warning would let the run + preflight pass. Ablation: report it as a warning on every tree and this fails.""" + tree = _lens_tree(tmp_path) + _write_override(tmp_path, "this is not = valid toml [[[", skill=DEV_PRIMITIVE_NEW) + + findings = missing_base_skills(tmp_path, [tree]) + + assert [(f.check, f.severity) for f in findings] == [("skills.customize-unreadable", "problem")] + + +def test_v7_all_lenses_disabled_with_review_none_is_clean(tmp_path): + """`review = "none"` launches no lens by design, so empty sets are legitimate. + Ablation: drop the `selection != "none"` guard and this reports empty lenses.""" + tree = _lens_tree(tmp_path) + _write_override( + tmp_path, '[workflow]\nreview = "none"\n' + _ALL_LENSES_OFF, skill=DEV_PRIMITIVE_NEW + ) + + assert missing_base_skills(tmp_path, [tree]) == [] + + +def test_v7_invalid_review_selection_is_a_problem(tmp_path): + """bmad-build-auto's workflow.md HALTs every run on a `workflow.review` outside + none/quick/thorough/auto — shipped or overridden, the last string wins.""" + from bmad_loop.checks import VALIDATE_CHECKS + + assert "skills.review-selection-invalid" in VALIDATE_CHECKS + tree = _lens_tree(tmp_path, LENS_CUSTOMIZE.replace('review = "quick"', 'review = "deep"')) + + problems = missing_base_skills(tmp_path, [tree]) + assert [p.check for p in problems] == ["skills.review-selection-invalid"] + assert problems[0].detail["selection"] == "deep" + + # an override fixing it clears the problem... + override = _write_override(tmp_path, '[workflow]\nreview = "auto"\n', skill=DEV_PRIMITIVE_NEW) + assert missing_base_skills(tmp_path, [tree]) == [] + + # ...and an override breaking a valid shipped value raises it + _lens_tree(tmp_path) + override.write_text('[workflow]\nreview = "deep"\n', encoding="utf-8") + problems = missing_base_skills(tmp_path, [tree]) + assert [p.check for p in problems] == ["skills.review-selection-invalid"] + + +@pytest.mark.parametrize( + ("literal", "shown"), [("false", "false"), ("1", "1"), ('["quick"]', '["quick"]')] +) +def test_v7_non_string_review_selection_is_a_problem(tmp_path, literal, shown): + """A non-string `review` is not "unset": the override still replaces the shipped + value and the template HALTs on it. Ablation: drop non-string values in + `_review_selection_of` and the shipped `quick` wins, reporting nothing.""" + tree = _lens_tree(tmp_path) + _write_override(tmp_path, f"[workflow]\nreview = {literal}\n", skill=DEV_PRIMITIVE_NEW) + + problems = missing_base_skills(tmp_path, [tree]) + + assert [p.check for p in problems] == ["skills.review-selection-invalid"] + assert problems[0].detail["selection"] == shown + + +def test_review_layers_shape_still_wins_over_lenses(tmp_path): + """A shipped config carrying review layers keeps the v6.10-6.12 contract even + when it also carries lens tables: its layers decide the requirement.""" + both = LAYER_CUSTOMIZE + LENS_CUSTOMIZE.replace('[workflow]\nreview = "quick"\n', "") + tree = _lens_tree(tmp_path, both) + + resolved = resolve_review_layers(tmp_path, tree) + + assert resolved is not None + assert resolved.lens_sets == () + assert resolved.required == { + "bmad-review": ("blind-hunter", "edge-case-hunter", "verification-gap") + } + assert [p.check for p in missing_base_skills(tmp_path, [tree])] == [ + "skills.review-layer-missing" + ] + + +def test_v7_leftover_review_layers_override_is_inert(tmp_path): + """A v7 run reads only the lens sets, so a `review_layers` override left over + from a v6 install must not pull the preflight onto the layer path and require + the skills those dead layers name. Ablation: decide the shape on the MERGED + layers instead of the shipped file and bmad-review is required.""" + tree = _lens_tree(tmp_path) + _write_override( + tmp_path, + '[[workflow.review_layers]]\nid = "blind-hunter"\n' + 'instruction = "Invoke the `bmad-review` skill with only the `adversarial` lens"\n', + skill=DEV_PRIMITIVE_NEW, + ) + + assert missing_base_skills(tmp_path, [tree]) == [] + resolved = resolve_review_layers(tmp_path, tree) + assert resolved is not None and resolved.lens_sets == ("quick", "thorough") + + +def test_unresolved_primitive_reports_only_base_missing(tmp_path): + """#768: with no primitive there is nothing to derive reviewers from, so the + one finding is the root cause — not the deleted hunters on top of it. + Ablation: remove the early return in _review_findings and both hunters FAIL.""" + tree = get_profile("claude").skill_tree + + problems = missing_base_skills(tmp_path, [tree]) + + assert [(p.check, p.detail["skill"]) for p in problems] == [ + ("skills.base-missing", DEV_PRIMITIVE_NEW) + ] + assert not any(h in p.message for p in problems for h in _HUNTERS) + + +def test_tickets_dispatch_skips_unresolved_primitive(tmp_path): + """Callers that also run missing_base_skills skip an unresolved tree (it is + already reported); the default still reports it, under the CURRENT name — + never the legacy bmad-dev-auto dir nobody would install.""" + from bmad_loop.install import missing_tickets_support + + tree = get_profile("claude").skill_tree + + assert missing_tickets_support(tmp_path, [tree], skip_unresolved=True) == [] + reported = missing_tickets_support(tmp_path, [tree]) + assert [f.check for f in reported] == ["skills.tickets-dispatch-missing"] + assert reported[0].detail["skill"] == DEV_PRIMITIVE_NEW + assert DEV_PRIMITIVE_LEGACY not in reported[0].message + # the combined preflight still refuses: the root cause is a problem + assert [p.check for p in missing_base_skills(tmp_path, [tree])] == ["skills.base-missing"] + + +def test_stories_dispatch_skips_unresolved_primitive(tmp_path): + from bmad_loop.install import missing_stories_support + + tree = get_profile("claude").skill_tree + + assert missing_stories_support(tmp_path, [tree], skip_unresolved=True) == [] + reported = missing_stories_support(tmp_path, [tree]) + assert [f.check for f in reported] == ["skills.stories-dispatch-missing"] + assert reported[0].detail["skill"] == DEV_PRIMITIVE_NEW + assert DEV_PRIMITIVE_LEGACY not in reported[0].message + assert [p.check for p in missing_base_skills(tmp_path, [tree])] == ["skills.base-missing"] + + +def test_review_remediation_names_core_tools(tmp_path): + """On v7 the merged bmad-review ships in core-tools, not the method module.""" + tree = get_profile("claude").skill_tree + # unknown shape (unparseable customize.toml) → the static fallback + _install_dev_auto(tmp_path, tree, skill=DEV_PRIMITIVE_NEW, customize="x\n") + fallback = missing_base_skills(tmp_path, [tree]) + assert {f.detail["skill"] for f in fallback} == _HUNTERS + assert all("core-tools" in f.message for f in fallback) + + _install_dev_auto(tmp_path, tree, skill=DEV_PRIMITIVE_NEW, customize=LAYER_CUSTOMIZE) + derived = missing_base_skills(tmp_path, [tree]) + assert [f.check for f in derived] == ["skills.review-layer-missing"] + assert "core-tools" in derived[0].message + + +@pytest.mark.parametrize("root", [".claude/skills", ".agents/skills"]) +def test_outside_copy_hint_on_base_missing(tmp_path, root): + """A global (`npx skills add -g`) copy is named as a hint — the run still + refuses, because bmad-loop drives only the project's own tree.""" + home = tmp_path / "home" + project = tmp_path / "project" + tree = get_profile("claude").skill_tree + + bare = missing_base_skills(project, [tree], home=home) + assert "outside" not in bare[0].detail + assert "a copy exists" not in bare[0].message + + _install_skills(home, root, {DEV_PRIMITIVE_NEW: ()}) + problems = missing_base_skills(project, [tree], home=home) + + assert [p.check for p in problems] == ["skills.base-missing"] + expected = PurePosixPath("~", root, DEV_PRIMITIVE_NEW).as_posix() + assert problems[0].detail["outside"] == expected + assert expected in problems[0].message + assert "npx skills add" in problems[0].message + + +def test_outside_copy_hint_on_review_findings(tmp_path): + home = tmp_path / "home" + project = tmp_path / "project" + tree = get_profile("claude").skill_tree + _install_skills(home, ".claude/skills", {"bmad-review": (), **{h: () for h in _HUNTERS}}) + + _install_dev_auto(project, tree, skill=DEV_PRIMITIVE_NEW, customize=LAYER_CUSTOMIZE) + derived = missing_base_skills(project, [tree], home=home) + assert derived[0].detail["outside"] == "~/.claude/skills/bmad-review" + + _install_dev_auto(project, tree, skill=DEV_PRIMITIVE_NEW, customize="x\n") + fallback = missing_base_skills(project, [tree], home=home) + assert {f.detail["outside"] for f in fallback} == {f"~/.claude/skills/{h}" for h in _HUNTERS} + + +def test_outside_copy_unresolvable_home_is_no_hint(monkeypatch): + def no_home(): + raise RuntimeError("Could not determine home directory.") + + monkeypatch.setattr(install_mod, "_outside_home", no_home) + assert install_mod._outside_copy(DEV_PRIMITIVE_NEW) is None