From a29766e5f81645768b786f6b3ca694d080c0e299 Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 20:01:04 -0600 Subject: [PATCH 1/8] feat(bmad): add module defaults, cross-skill rules, and unified customization Add `[bmod.defaults]` support in bmod.toml (validating table shape and key uniqueness against `config_questions`), 4-layer central config precedence with home-installed module discovery and `resolve_config.py --check`, `_bmad/custom/rules.toml` / `rules.user.toml` cross-skill rule matching (skipping heterogeneous type mismatches gracefully with `--check` warnings and read-only linked-worktree fallbacks), unified customization across all four surfaces in `bmad-customize` with trigger evals, and aligned reference docs and tests. --- docs/customize/adopt-bmad-across-a-team.md | 3 +- docs/customize/customize-bmad.md | 6 +- docs/reference/configuration.md | 21 +- docs/reference/module-files.md | 2 +- docs/toolsmith/modules.md | 12 +- evals/core-tools/bmad-customize/triggers.json | 74 ++ skills/core-tools/bmad-customize/SKILL.md | 129 +-- skills/core-tools/bmad-customize/bmod.toml | 6 +- .../bmad-customize/help/customization.md | 50 +- .../references/central-and-rules.md | 61 + .../references/document-templates.md | 32 + .../scripts/list_customizable_skills.py | 96 +- .../core-tools/bmad/scripts/config_utils.py | 1009 ++++++++++++++++- skills/core-tools/bmad/scripts/knowledge.py | 13 +- .../core-tools/bmad/scripts/render_skill.py | 28 +- .../core-tools/bmad/scripts/resolve_config.py | 29 +- .../bmad/scripts/resolve_customization.py | 27 +- .../bmod-core-tools/help/team-adoption.md | 22 +- tests/core-tools/bmad/test_setup_lifecycle.py | 24 +- tests/core-tools/bmad/test_story04_phase2.py | 871 ++++++++++++++ 20 files changed, 2313 insertions(+), 202 deletions(-) create mode 100644 evals/core-tools/bmad-customize/triggers.json create mode 100644 skills/core-tools/bmad-customize/references/central-and-rules.md create mode 100644 skills/core-tools/bmad-customize/references/document-templates.md create mode 100644 tests/core-tools/bmad/test_story04_phase2.py diff --git a/docs/customize/adopt-bmad-across-a-team.md b/docs/customize/adopt-bmad-across-a-team.md index 8b56f13fa0..29f47ca457 100644 --- a/docs/customize/adopt-bmad-across-a-team.md +++ b/docs/customize/adopt-bmad-across-a-team.md @@ -9,10 +9,11 @@ When you roll BMad out to a team, you want every developer, designer, and PM to Choose where a rule belongs by how broadly it applies: +- Rules that span multiple skills matching a name pattern belong in `_bmad/custom/rules.toml` (`_bmad/custom/rules.user.toml` for personal rules) through `bmad-customize`. - Rules that apply whenever an engineer does implementation or review work belong on Amelia (`bmad-agent-dev`). - Rules that apply to every structured document across Mary, John, Sally, Winston, Nadia, and Clio belong on `bmad-facilitate`. - Rules that apply to one document type (such as every PRD or brief) belong in a template extension under `_bmad/custom/facilitate-templates/`. -- Shared repository settings (such as output folder or a brand design system) belong in `bmad setup`. +- Shared central or module settings belong in `bmad setup` (`_bmad/config.toml`) for initial answers, and in `_bmad/custom/config.toml` through `bmad-customize` for team overrides. :::tip[Start with `bmad-customize` for Every Recipe] You do not need to hand-author TOML files to roll these out. Open chat, invoke `/bmad-customize`, and paste or adapt the plain-English request at the start of each recipe. `bmad-customize` creates the right file under `_bmad/custom/` and verifies the merged result. For the full TOML schema and merge rules, see [Configuration and Customization Reference](../reference/configuration.md). diff --git a/docs/customize/customize-bmad.md b/docs/customize/customize-bmad.md index b72c8b2c3f..12435c9202 100644 --- a/docs/customize/customize-bmad.md +++ b/docs/customize/customize-bmad.md @@ -39,8 +39,10 @@ Every customization falls into one of four areas: | --- | --- | --- | | **An agent's behavior** | Tell `bmad-customize` what to change on that agent | Change role focus, communication style, principles, standing facts, startup hooks, or custom menu shortcuts | | **A workflow's settings** | Tell `bmad-customize` which workflow behavior to change | Raise `bmad-build` review depth to `thorough`, add `on_complete` publishing steps, or set `bmad-facilitate` defaults | +| **Cross-skill rules** | Ask `bmad-customize` to write a `[[rules]]` entry in `_bmad/custom/rules.toml` (or `.user.toml`) | Apply shared `persistent_facts` or `on_complete` instructions across every skill matching `bmad-*` | +| **Central and module settings** | Ask `bmad-customize` for `_bmad/custom/config.toml` (or `config.user.toml`) overrides, or run `bmad setup` initially | Override `core.output_folder`, external sources/destinations, or `[modules.]` module settings without touching `_bmad/config.toml` | | **A document's structure or look** | Tell `bmad-customize` what a document should ask for, contain, or render | Add a required PRD section, change default facilitation mode, or set HTML view preferences | -| **Shared settings and custom casts** | Run `bmad setup` for shared project config, or ask `bmad-party-mode` / `bmad-customize` for custom discussion casts | Change your output folder, set a shared brand design system, or save a custom party cast | +| **Custom party casts** | Ask `bmad-party-mode` or `bmad-customize` for custom discussion casts | Save custom personas or focus groups in `bmad-party-mode` | ## Team Scope vs. Personal Scope @@ -78,7 +80,7 @@ To build custom personas, themed casts, or reusable focus groups, ask `bmad-part ## Shared Project Configuration -Shared project settings such as where BMad writes output, your active initiative, and module setup answers (such as your design system or Founder and Creative record folders) are managed by `bmad setup`. Ask the BMad Agent whenever you want to switch initiatives or change a setup answer. +Shared project settings such as where BMad writes output, your active initiative, and module setup answers are initialized by `bmad setup` (writing team defaults to `_bmad/config.toml` and personal choices to `_bmad/custom/config.user.toml`). To override central or module settings afterward — including team overrides in `_bmad/custom/config.toml`, personal overrides in `_bmad/custom/config.user.toml`, or defaults shipped in `[bmod.defaults]` — ask `bmad-customize` or `bmad`, without editing `_bmad/config.toml` manually. ## How Configuration Layers Work diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index d71b2702fd..b83a374844 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -23,15 +23,16 @@ If you want to know what can be tailored on a specific agent or skill, ask `"Hey ## Central Configuration Files -Project-wide setup answers and shared overrides live in three TOML layers under `_bmad/`, where higher-priority files win when the same key appears in more than one place: +Project-wide setup answers, unasked module defaults, and shared overrides merge across four TOML layers, where higher-priority layers win when the same key appears in more than one place: ```text Priority 1 (wins): _bmad/custom/config.user.toml (project personal overrides, gitignored) Priority 2: _bmad/custom/config.toml (team overrides, committed) -Priority 3 (base): _bmad/config.toml (setup-owned project defaults, committed) +Priority 3: _bmad/config.toml (setup-owned project defaults, committed) +Priority 4 (base): /bmod.toml [bmod.defaults] (shipped unasked module defaults) ``` -Running `bmad setup` writes team-scope answers to `_bmad/config.toml`, and project personal answers, model tiers, harness capabilities, and detected tooling to `_bmad/custom/config.user.toml`. Setup fills in missing keys and migrates renamed skill files on upgrades, while leaving anything you set under `_bmad/custom/` untouched. You can also ask `bmad` in chat to view or update any of these settings at any time without editing TOML by hand. +Running `bmad setup` writes prompted team answers to `_bmad/config.toml` and personal setup answers to `_bmad/custom/config.user.toml`, leaving unasked module defaults in each module's `bmod.toml` so module updates flow through automatically without editing project files. Setup preserves your overrides under `_bmad/custom/` (only renaming a per-skill file if a retired skill moves to a new name), and `bmad-customize` edits `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` without mutating `_bmad/config.toml`. Inside a fresh linked worktree where gitignored personal `*.user.toml` files (`config.user.toml`, `rules.user.toml`, `.user.toml`) are absent locally, BMAD reads your main checkout's `*.user.toml` files read-only until you create a worktree-local file. | Setting | Scope | What it controls | | --- | --- | --- | @@ -105,16 +106,20 @@ Three rules govern every destination: - **Explicit confirmation by default:** Every destination defaults to `mode = "ask"`, meaning skills must show the exact destination and payload summary before executing any external write. Use `mode = "manual"` for on-request-only targets, `mode = "auto"` only when explicitly opted in (unfinished drafts still require confirmation), and `mode = "disabled"` in a higher layer to mute an inherited entry. - **Layering and backward compatibility:** Shared team entries belong in `_bmad/custom/config.toml` (committed). Project personal entries and sparse overrides of team entries (such as changing `mode`, `scope`, or `for`) belong in `_bmad/custom/config.user.toml` (gitignored, highest priority). Replacing `scope` or `for` in a higher layer replaces that entry's tag list cleanly rather than appending stale tags. The central config resolver also preserves backward compatibility with existing per-skill `workflow.external_sources` and `workflow.external_handoffs` overrides as bundled skills adopt central sources and destinations. -## Per-Skill Override Files +## Cross-Skill Rules and Per-Skill Override Files -Every customizable skill ships a `customize.toml` inside its installed directory defining its defaults. Never edit installed skill files, because updates overwrite them. Instead, sparse override files sit under `_bmad/custom/` using the exact skill name: +Every customizable skill ships a `customize.toml` inside its installed directory defining its defaults. Never edit installed skill files, because updates overwrite them. Instead, shared cross-skill rules and sparse per-skill overrides sit under `_bmad/custom/` and merge in five layers: ```text -Priority 1 (wins): _bmad/custom/.user.toml (personal overrides, gitignored) -Priority 2: _bmad/custom/.toml (team overrides, committed) -Priority 3 (base): /customize.toml (shipped defaults) +Priority 1 (wins): _bmad/custom/.user.toml (personal skill overrides, gitignored) +Priority 2: _bmad/custom/rules.user.toml (personal cross-skill rules, gitignored) +Priority 3: _bmad/custom/.toml (team skill overrides, committed) +Priority 4: _bmad/custom/rules.toml (team cross-skill rules, committed) +Priority 5 (base): /customize.toml (shipped defaults) ``` +In `rules.toml` and `rules.user.toml`, each `[[rules]]` entry targets installed skill folders via `match` glob patterns (and optional `id` or `surface`), supplying `[rules.agent]` or `[rules.workflow]` tables. Keys not declared by a matched skill's `customize.toml` are skipped cleanly at load time unless they sit inside an open `{}` table such as `[workflow.harnesses]`. + :::caution[Keep Override Files Sparse] Only include the settings you intentionally change. Copying an entire `customize.toml` into `_bmad/custom/` locks in old defaults and prevents future skill improvements from taking effect. ::: diff --git a/docs/reference/module-files.md b/docs/reference/module-files.md index 1552ecc8cf..51dd722876 100644 --- a/docs/reference/module-files.md +++ b/docs/reference/module-files.md @@ -57,7 +57,7 @@ No other keys are allowed. ### `[bmod.config_defaults]` -Optional table of silent team defaults written by `bmad setup` under `[modules.]` in `_bmad/config.toml` without prompting the user (and never overwriting existing keys). Use `[bmod.config_defaults]` for settings with sensible defaults that users only adjust occasionally, reserving `[[bmod.config_questions]]` for choices every project must confirm at setup. +Optional table of silent team defaults written by `bmad setup` under `[modules.]` in `_bmad/config.toml` without prompting the user (and never overwriting existing keys), and read directly as Priority 4 runtime defaults below `_bmad/config.toml` and `_bmad/custom/config*.toml` if a key is not yet in `_bmad/config.toml`. Use `[bmod.config_defaults]` for settings with sensible defaults that users only adjust occasionally, reserving `[[bmod.config_questions]]` for choices every project must confirm at setup. - Accepts flat keys or nested subtables flattened into dotted keys (for example, `output.format` or `auto_validate`), keeping `{project-root}` literal and expanding `{directory_name}` like `config_questions`. - Values must be strings, booleans, or finite numbers (no lists, dates, or empty nested tables). diff --git a/docs/toolsmith/modules.md b/docs/toolsmith/modules.md index b4065c7521..c10c3dbf5c 100644 --- a/docs/toolsmith/modules.md +++ b/docs/toolsmith/modules.md @@ -95,13 +95,13 @@ Modules support two distinct override mechanisms: | | Configuration | Customization | | --- | --- | --- | -| Question it answers | What project facts or defaults belong to this module? | How should one skill behave differently here? | -| Defined in | `[bmod.config_defaults]` (silent) or `[[bmod.config_questions]]` (prompted) in the record's `bmod.toml` | `customize.toml` inside each skill | -| Set by | `bmad setup ` | `bmad-customize` | +| Question it answers | What project facts or defaults apply across module skills? | How should one skill or matching group behave differently here? | +| Defined in | `[bmod.config_defaults]` (silent) or `[[bmod.config_questions]]` (prompted) in the record's `bmod.toml` | `customize.toml` inside each skill (plus project `rules.toml`) | +| Set by | `bmad setup ` (prompted) and `bmad-customize` (central overrides) | `bmad-customize` | | Read as | `modules..` via `resolve_config.py` | `{workflow.}` or `{agent.}` via `resolve_customization.py` | -| Example | A shared workspace path or module tuning defaults | An extra activation step or custom template for one skill | +| Example | A shared workspace path or module tuning defaults | An extra activation step, cross-skill rule, or custom template | -Put module settings with sensible defaults in `[bmod.config_defaults]` so `bmad setup` seeds them into `_bmad/config.toml` silently and users can adjust them anytime later without hitting setup friction. Reserve `[[bmod.config_questions]]` only for values the user must decide at setup; mark personal preferences `scope = "user"` so they stay out of version control, and leave team paths in team scope. See [Make a Skill Customizable](make-a-skill-customizable.md) for per-skill overrides and [Configuration](../reference/configuration.md) for full details. +Put module settings with sensible defaults in `[bmod.config_defaults]` so `bmad setup` seeds them silently into `_bmad/config.toml` (and runtime resolution falls back to them at Priority 4 below `_bmad/config*.toml` if a key is absent from `_bmad/config.toml`). Reserve `[[bmod.config_questions]]` only for values the user must decide at setup; mark personal preferences `scope = "user"` so they stay out of version control, and leave team paths in team scope. See [Make a Skill Customizable](make-a-skill-customizable.md) for per-skill overrides and [Configuration](../reference/configuration.md) for full details. ## Write the Help @@ -109,7 +109,7 @@ Help is powered by `knowledge.py` for both the `bmad` skill and direct on-demand - **Skill-owned (`[skill.help]` in each `bmod.toml` + optional `/help/.md`):** Each skill's `phase`, concise `when`, optional `not_when`, `writes`, and `after`, plus skill-specific deep guides. - **Module-owned (`help/routing.toml` + cross-cutting `help/.md`):** Module `role`, `not_for`, `rules`, decision-first `[[routes]]`, optional cross-module `[[slots]]` and external `[[sources]]`, plus cross-cutting domain topics. -- **Project custom knowledge:** Plain `.md` guides in `_bmad/custom/knowledge/` (same frontmatter: `title`, `when`, `tags`, `related`) and `[[knowledge.sources]]` pointers (`id`, `when`, `how`, `tags`, `agents`) in `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` index alongside shipped help automatically. +- **Project custom knowledge:** Plain `.md` guides in `_bmad/custom/knowledge/` (same frontmatter: `title`, `when`, `tags`, `related`) and `[core.knowledge_sources.]` entries in `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` index alongside shipped help automatically. ## Depend on Other Skills diff --git a/evals/core-tools/bmad-customize/triggers.json b/evals/core-tools/bmad-customize/triggers.json new file mode 100644 index 0000000000..1b3ddfa72b --- /dev/null +++ b/evals/core-tools/bmad-customize/triggers.json @@ -0,0 +1,74 @@ +[ + { + "query": "customize bmad so every workflow reminds the team to check our API compatibility notes first", + "should_trigger": true + }, + { + "query": "apply one shared on_complete instruction across all my bmad-* skills via rules.toml", + "should_trigger": true + }, + { + "query": "override a setting in config.user.toml for my personal model preferences without changing team config", + "should_trigger": true + }, + { + "query": "make John's PRD include a Security Sign-off section for the whole team", + "should_trigger": true + }, + { + "query": "tailor the facilitator pitch deck template so every slide ends with an explicit risk callout", + "should_trigger": true + }, + { + "query": "what can I customize on Winston or the build skill?", + "should_trigger": true + }, + { + "query": "set a personal voice guide path just for me in _bmad/custom/config.user.toml", + "should_trigger": true + }, + { + "query": "change a module default under [modules.creative] in _bmad/custom/config.toml without editing _bmad/config.toml", + "should_trigger": true + }, + { + "query": "update our per-skill override in _bmad/custom/ so the skill starts in thorough review mode", + "should_trigger": true + }, + { + "query": "reset my personal rules.user.toml overrides back to the team defaults", + "should_trigger": true + }, + { + "query": "run initial bmad setup and configure our project folders for this repo", + "should_trigger": false + }, + { + "query": "install the founder module and answer its onboarding prompts", + "should_trigger": false + }, + { + "query": "build a brand new custom skill for generating release changelogs with bmad-toolsmith", + "should_trigger": false + }, + { + "query": "write a new PRD for our billing checkout redesign from these discovery notes", + "should_trigger": false + }, + { + "query": "edit src/auth/login.ts to validate JWT expiry before refreshing tokens", + "should_trigger": false + }, + { + "query": "review the current epic branch and check for regression risks before opening a PR", + "should_trigger": false + }, + { + "query": "check whether there are any module updates available for bmad", + "should_trigger": false + }, + { + "query": "help me understand how the ticket tree stores epics and stories in _bmad-obeya", + "should_trigger": false + } +] diff --git a/skills/core-tools/bmad-customize/SKILL.md b/skills/core-tools/bmad-customize/SKILL.md index 85c780c705..acb9a1dd6a 100644 --- a/skills/core-tools/bmad-customize/SKILL.md +++ b/skills/core-tools/bmad-customize/SKILL.md @@ -1,34 +1,29 @@ --- name: bmad-customize -description: Authors and updates customization overrides for installed BMad skills and their facilitation templates. Use when the user says 'customize bmad', 'override a skill', 'change agent behavior', 'customize a workflow', or wants a facilitation template (such as a PRD, deck, or brief) to coach, contain, or render something different +description: Authors and updates customization overrides, cross-skill rules, central and module settings, and facilitation templates under _bmad/custom/. Use when the user asks to customize bmad, override a skill, apply a cross-skill rule, change central or module settings in config.toml or config.user.toml, or tailor what a facilitation template (such as a PRD, deck, or brief) coaches, contains, or renders. --- # BMad Customize -Translate the user's intent into a correctly-placed TOML override file under `{project-root}/_bmad/custom/` for a customizable agent or workflow skill, or into a facilitation template file when the change is to a coached deliverable. Discover, route, author, write, verify. +Translate the user's request into the right file under `{project-root}/_bmad/custom/` using two-way placement: committed team files (`*.toml`, `facilitate-templates/`) or gitignored personal files (`*.user.toml`), never modifying installed skill directories or setup-owned `_bmad/config.toml`. Discover, route, author, confirm, verify. -Scope v1: per-skill `[agent]` overrides (`bmad-agent-.toml` / `.user.toml`) and per-skill `[workflow]` overrides (`bmad-.toml` / `.user.toml`). Central config (`{project-root}/_bmad/custom/config.toml`) is out of scope — point users at the [How to Customize BMad guide](https://docs.bmad-method.org/how-to/customize-bmad/). - -When the target's `customize.toml` doesn't expose what the user wants, say so plainly. Don't invent fields. +When an installed skill's `customize.toml` or module manifest does not expose what the user wants, say so plainly without inventing fields. ## Preflight -- `{project-root}` is the nearest folder containing `_bmad/`, from the working directory upward (in a linked git worktree, fall back to walking up from the parent of `git rev-parse --path-format=absolute --git-common-dir`). If `{project-root}` lies outside the active worktree, confirm the target path with the user before writing. -- No `{project-root}/_bmad/` → BMad is not set up here. Offer to run the `bmad` skill's setup, installing `bmad` first if you do not have it (`npx skills add bmad-code-org/BMAD-METHOD --skill bmad`). Stop if the user declines. -- `{project-root}/_bmad/scripts/resolve_customization.py` missing → continue, but Step 6 verify falls back to manual merge. -- Both present → proceed. - -## Activation +- `{project-root}` is the nearest folder containing `_bmad/`, walking upward from the working directory (in a linked git worktree, fall back to walking up from the parent of `git rev-parse --path-format=absolute --git-common-dir`). Confirm the target root with the user before writing if `{project-root}` sits outside the active worktree. +- Missing `{project-root}/_bmad/` -> offer to run the `bmad` skill's setup (installing `bmad` first via `npx skills add bmad-code-org/BMAD-METHOD --skill bmad` if absent), and stop if the user declines. +- Missing `{project-root}/_bmad/scripts/resolve_customization.py` -> proceed, falling back to manual layer inspection in Step 6. -Greet the user. A change to a document, even one naming its skill or agent, goes to Document templates. Otherwise, if the user's invocation already names a target skill AND a specific change, jump to Step 3. +## Step 1: Routing and classification -## Step 1: Classify intent +Determine the surface and load the matching reference before authoring. A change to a document, even one naming its skill or agent, goes to **Document template**. -- **Directed** — specific skill + specific change → Step 3. -- **Exploratory** — "what can I customize?" → Step 2. -- **Audit/iterate** — wants to review or change something already customized → Step 2, lead with skills that have existing overrides; read the existing override in Step 3 before composing. -- **Cross-cutting** — could live on multiple surfaces → Step 3, choose agent vs workflow explicitly with the user. -- **Document** — names a document type (a PRD, a brief, a postmortem) or a change to what one asks for, contains or renders → Document templates. The user need not know which skill writes it. +- **Per-skill override** (specific agent or workflow behavior) -> continue in Steps 2–6 below (`{project-root}/_bmad/custom/.toml` or `.user.toml`). +- **Cross-skill rule** (same rule across multiple skills or matching a pattern) -> read `references/central-and-rules.md` and author `{project-root}/_bmad/custom/rules.toml` or `rules.user.toml`. +- **Central or module setting** (`[core]` or `[modules.]`) -> read `references/central-and-rules.md` and author `{project-root}/_bmad/custom/config.toml` or `config.user.toml` (never editing setup-owned `_bmad/config.toml`). +- **Document template** (sections, prompts, rubric, or format of a facilitated document) -> read `references/document-templates.md`. +- **Audit / explore** ("what can I customize?" or review active overrides) -> run Discovery below first. ## Step 2: Discovery @@ -36,93 +31,53 @@ Greet the user. A change to a document, even one naming its skill or agent, goes uv run "{skill-root}/scripts/list_customizable_skills.py" --project-root "{project-root}" ``` -Use `--extra-root ` (repeatable) if the user has skills installed in additional locations. - -Group the returned `agents` and `workflows` for the user; for each show name, description, whether `has_team_override` or `has_user_override` is true. Surface any `errors[]`. For audit/iterate intents, lead with already-overridden entries. - -Empty list: show `scanned_roots`, ask whether skills live elsewhere (offer `--extra-root`); otherwise stop. - -## Step 3: Determine the right surface - -Read the target's `customize.toml`. Top-level `[agent]` or `[workflow]` block defines the surface. - -If a team or user override already exists, read it first and summarize what's already overridden before composing. - -**Cross-cutting intent — walk both surfaces with the user:** -- Every workflow a given agent runs → agent surface (e.g. `bmad-agent-pm.toml` with `persistent_facts`, `principles`). -- One workflow only → workflow surface (e.g. `bmad-build.toml` with `activation_steps_prepend`). -- Several specific workflows → multiple workflow overrides in sequence, not an agent override. - -**Single-surface heuristic:** -- Workflow-level: template swap, output path, step-specific behavior, or a named scalar already exposed (`*_template`, `on_complete`). Surgical, reliable. -- Agent-level: persona, communication style, org-wide facts, menu changes, behavior that should apply to every workflow the agent dispatches. +Repeat `--extra-root ` when skills live in additional folders. Summarize installed `agents`, `workflows`, `modules` (`defaults` and `question_keys`), `rules`, and `central_config` override status, surfacing any `errors[]`. -When ambiguous, present both with tradeoff, recommend one, let the user decide. +## Step 3: Choose the per-skill surface -Intent outside the exposed surface (step logic, ordering, anything not in `customize.toml`): say so; offer `activation_steps_prepend`/`append` or `persistent_facts` as approximations, or, if `bmad-toolsmith` is installed, recommend it to create a custom skill. +Read the target skill's `customize.toml` and any existing `{project-root}/_bmad/custom/.toml` or `.user.toml` (plus matching entries in `rules.toml` / `rules.user.toml`) before composing changes. -## Step 4: Compose the override +- **Agent surface** (`[agent]`): persona focus, tone, principles, persistent facts loaded in every capability, menu shortcuts. +- **Workflow surface** (`[workflow]`): output path, template choice, step hooks (`activation_steps_prepend`/`append`), completion hooks (`on_complete`), workflow-specific options. +- **Several specific skills or cross-cutting rules:** prefer `{project-root}/_bmad/custom/rules.toml` (or `.user.toml`) per `references/central-and-rules.md` instead of repeating identical overrides across files. +- **Missing field in `customize.toml`:** state what is unexposed and offer `activation_steps_prepend`/`append` or `persistent_facts`, or suggest `bmad-toolsmith` to build a custom skill. -Translate plain-English into TOML against the target's `customize.toml` fields. If an existing override was read, frame the change as additive. +## Step 4: Compose sparse TOML -Merge semantics: -- **Scalars** (`icon`, `role`, `*_template`, `on_complete`) — override wins. -- **Append arrays** (`persistent_facts`, `activation_steps_prepend`/`append`, `principles`) — team/user entries append in order. -- **Keyed arrays of tables** (menu items with `code` or `id`) — matching keys replace, new keys append. +Write only changed fields so shipped defaults continue arriving on updates. -Overrides are sparse: only the fields being changed. Never copy the whole `customize.toml`. +- **Scalars:** highest layer wins. +- **Tables:** merged recursively by key; open `{}` tables accept custom subkeys. +- **Keyed arrays of tables (`code` or `id`):** matching key replaces that item; new keys append. +- **Other arrays (`persistent_facts`, `activation_steps_*`, `principles`):** append in precedence order (`customize.toml` < `rules.toml` < `.toml` < `rules.user.toml` < `.user.toml`). -**Template swap** (`*_template` scalar): offer to copy the default template to `{project-root}/_bmad/custom/{skill-name}-{purpose}-template.md`, point the override at the new path, offer to help edit it. +For custom template swaps (`*_template`), offer to copy the shipped template under `{project-root}/_bmad/custom/{skill-name}-{purpose}-template.md` and point the override there. -## Document templates +## Step 5: Team vs personal placement -Every document `bmad-facilitate` writes, John's (`bmad-agent-pm`) and Mary's (`bmad-agent-analyst`) included, comes from a markdown template, not from TOML. The format is at `https://docs.bmad-method.org/customize/write-a-document-template/`. +Confirm placement under `{project-root}/_bmad/custom/` before writing: -1. Find the template: `uv run "{project-root}/_bmad/scripts/list_templates.py" --libraries-of "" --libraries-of "" "/assets" --project-root "{project-root}" --root "" --brief`, one `--root` per skills folder. Match the user's words to a template id; when more than one fits, such as `prd` and `prd-epic`, ask which, or both. When none is close to the document the user wants, a new document type, invoke the `bmad-facilitate` skill to write one with its `document-template` template instead of copying one; the steps below are for changing a template that exists. -2. Sort each change. About this document type → a template file: a section to add, one made required or optional, the order, an input to ask for, a writing or review rule, its rubric, its view's `layout`, whether its HTML view is made (`view`), the mode its runs start in (`mode`: `step-by-step`, `freeform` or `fast`), or whether its sections must run in order (`order: fixed`); an empty value clears the template's `mode` or `order`. For every document → `bmad-facilitate.toml` through Steps 4–6: `view` (`offer`, `always` or `never`), `style` and `mode` (`step-by-step`, `freeform` or `fast`), each over every template's own, `doc_standards`, reviewers, output. When it could be either, ask, offering this document type first. -3. Extend by default: `{project-root}/_bmad/custom/facilitate-templates/-.md`, or the user's existing extension of that id, updated. Read the template first, its `file` from the listing with `--template `, then write only the change under `extends: ` frontmatter: - - A `##` section with a comment saying where it goes and what to ask. It is required unless the comment starts `optional` or `include when`. To replace a template section, use its heading and say so in the comment. - - `stance`, `inputs`, `writing` or `done when` comments, added to the template's. - - `description`, `not_for`, `guidance`, `rubric`, `methods`, `output`, `style`, `layout`, `view`, `mode` or `order` frontmatter, replacing the template's. - - `facilitation_order` only to reorder or remove the template's own sections; it replaces the whole order, and a template section it leaves out is removed, including one the template adds in a later update. Never set it just to place a new section: the section's comment places it. -4. Copy only when the change outgrows an extension. To rebuild the document everywhere, copy it into that folder with its `template` id kept. For a different document beside it, such as a PRD for one team, give the copy a new id (`prd-billing`), its own `description` and `not_for`, and `agents:` naming the agent that should offer it; extensions of the original do not reach it. Either way, say the copy no longer receives updates to the original. -5. Placement: `{project-root}/_bmad/custom/facilitate-templates/` is the team's, committed. For personal-only templates kept out of git, save them to a gitignored folder inside `{project-root}` and add that path to `workflow.template_libraries` in `{project-root}/_bmad/custom/bmad-facilitate.user.toml`. -6. Show the file, wait for an explicit yes, and write it. Verify by running the listing again with `--template ` in place of `--brief`: show the template's `extensions`, merged `facilitation_order`, `removed`, `mode`, `layout` and `view`, and fix any `order_problems` before finishing. Asked what a run of it reads, list again with only the libraries that run passes (`bmad-facilitate`'s, and the calling agent's when an agent runs it), add `--merge` with a file in the system temp folder, and show that file. - -## Step 5: Team or user placement - -Under `{project-root}/_bmad/custom/`: -- `{skill-name}.toml` — team, committed. Policies, org conventions, compliance. -- `{skill-name}.user.toml` — user, gitignored. Personal tone, private facts, shortcuts. - -Default by character (policy → team, personal → user), confirm before writing. +- **Team (committed):** `{skill-name}.toml`, `rules.toml`, `config.toml`, `facilitate-templates/`. +- **Personal (gitignored):** `{skill-name}.user.toml`, `rules.user.toml`, `config.user.toml`. ## Step 6: Show, confirm, write, verify -1. Show the full TOML. If the file exists, show a diff. Never silently overwrite. -2. Wait for explicit yes. -3. Write. Create `{project-root}/_bmad/custom/` if needed. -4. Verify: +1. Show the full TOML or diff and wait for explicit approval before writing. +2. Create `{project-root}/_bmad/custom/` if absent and write the approved file. +3. Verify schema validation and effective resolved output: ``` + uv run "{project-root}/_bmad/scripts/resolve_customization.py" --skill "" --project-root "{project-root}" --check uv run "{project-root}/_bmad/scripts/resolve_customization.py" --skill "" --project-root "{project-root}" --key ``` - Show the merged output, point out the changed fields. + Fix any `errors[]` or unexpected merge outcome before concluding. When `_bmad/scripts/resolve_customization.py` is unavailable, inspect `/customize.toml`, matching entries in `rules.toml` and `rules.user.toml`, and `.toml` / `.user.toml` (including read-only main-checkout `*.user.toml` fallbacks in a linked worktree when absent locally) manually. +4. Summarize what changed, where the file lives (noting to commit team files), and wait for user acknowledgement. - **Resolver missing or fails:** read whichever layers exist — `/customize.toml` (base), `{project-root}/_bmad/custom/{skill-name}.toml` (team), `{project-root}/_bmad/custom/{skill-name}.user.toml` (user) — apply base → team → user with the same merge rules (scalars override, tables deep-merge, `code`/`id`-keyed arrays merge by key, all other arrays append), describe how the changed fields resolve. +## When this skill can't help - **Verify shows override didn't land** (field unchanged, merge conflict, file not picked up): re-enter Step 4 with the verify output as context. Usually wrong field name, wrong merge mode (scalar vs array), or wrong scope. -5. Summarize what changed, where the file lives, how to iterate. Remind the user to commit team overrides. +- **Initial setup, module install/removal, or interactive setup prompts:** invoke the `bmad` skill. +- **Workflow step logic absent from `customize.toml`:** use `bmad-toolsmith` to build a custom skill. +- **Skills without `customize.toml`:** cannot take per-skill TOML overrides (still check central `[modules.]` settings if the module exposes them). ## Complete when -- Override or template file written (or user explicitly aborted). -- User has seen resolver or listing output (or manual fallback merge summary). -- User has acknowledged the summary. - -Otherwise the skill isn't done — finish or tell the user they're exiting incomplete. - -## When this skill can't help - -- **Central config** (`{project-root}/_bmad/custom/config.toml`) — see the [How to Customize BMad guide](https://docs.bmad-method.org/how-to/customize-bmad/). -- **Step logic, ordering, behavior not in `customize.toml`** — open a feature request, or, if `bmad-toolsmith` is installed, use it to create a custom skill. Offer to help with either. -- **Skills without a `customize.toml`** — not customizable. +The target override, cross-skill rule, central/module setting, or custom template under `{project-root}/_bmad/custom/` is written only after explicit user confirmation, verified with the matching `--check` and resolution commands (zero `errors[]`), and summarized with team commit guidance when applicable. diff --git a/skills/core-tools/bmad-customize/bmod.toml b/skills/core-tools/bmad-customize/bmod.toml index c8ae30e61f..e2bdc09e81 100644 --- a/skills/core-tools/bmad-customize/bmod.toml +++ b/skills/core-tools/bmad-customize/bmod.toml @@ -4,6 +4,6 @@ source = "github:bmad-code-org/BMAD-METHOD/skills/core-tools" [skill.help] phase = "anytime" -when = "Skill, persona, template, and path overrides (_bmad/custom/)" -not_when = "Central _bmad/config.toml (edit directly)" -writes = "{project-root}/_bmad/custom/.toml" +when = "Skill, cross-skill rules, central overrides, and template edits (_bmad/custom/)" +not_when = "Initial _bmad/ setup or module install/questions (use bmad)" +writes = "{project-root}/_bmad/custom/" diff --git a/skills/core-tools/bmad-customize/help/customization.md b/skills/core-tools/bmad-customize/help/customization.md index e9f49996c6..6bcb49f9b4 100644 --- a/skills/core-tools/bmad-customize/help/customization.md +++ b/skills/core-tools/bmad-customize/help/customization.md @@ -1,41 +1,53 @@ --- title: "Customization Layers and Merge Rules" -when: "_bmad/custom/ overrides, merge rules, reset" -tags: [customize, customization, overrides, toml, config, user-toml, reset, prose, ai-slop, tone, voice, llm-writing] +when: "_bmad/custom/ overrides, rules.toml, config overrides, reset" +tags: [customize, customization, overrides, toml, config, rules, user-toml, reset, prose, tone, voice, ai-slop, llm-writing] related: [core-tools/team-adoption, bmad-facilitate/facilitate] --- # How Customization Works -Skills with a `customize.toml` expose safe override fields under `{project-root}/_bmad/custom/` so shipped skill files never need editing. +BMad keeps team and personal overrides under `{project-root}/_bmad/custom/` so skill updates never overwrite project settings. ## Precedence (highest wins) -1. `{project-root}/_bmad/custom/.user.toml` — personal overrides (gitignored) -2. `{project-root}/_bmad/custom/.toml` — team overrides (committed) -3. `/customize.toml` — shipped defaults +Per-skill and cross-skill rule layers merge in five tiers: -Central config merges across `_bmad/custom/config.user.toml` > `_bmad/custom/config.toml` > `_bmad/config.toml`. Edit central config directly or via `bmad` (`bmad-customize` edits skill overrides and facilitation templates). +1. `{project-root}/_bmad/custom/.user.toml` — personal skill overrides (gitignored; read-only main-checkout fallback in linked worktrees) +2. `{project-root}/_bmad/custom/rules.user.toml` — personal cross-skill rules matching `` (gitignored; read-only main-checkout fallback in linked worktrees) +3. `{project-root}/_bmad/custom/.toml` — team skill overrides (committed) +4. `{project-root}/_bmad/custom/rules.toml` — team cross-skill rules matching `` (committed) +5. `/customize.toml` — shipped defaults -## Merge rules & limits +Central config merges in four tiers: + +1. `{project-root}/_bmad/custom/config.user.toml` — personal central overrides (gitignored; read-only main-checkout fallback in linked worktrees) +2. `{project-root}/_bmad/custom/config.toml` — team central overrides (committed) +3. `_bmad/config.toml` — setup-owned project answers (committed) +4. `/bmod.toml` `[bmod.defaults]` — shipped unasked module defaults + +Use `bmad-customize` for per-skill files, `rules.toml` or `rules.user.toml`, central `_bmad/custom/config.toml` or `config.user.toml` overrides, and facilitation templates; use `bmad` for initial setup and module setup questions. + +## Merge rules and limits | Value shape | Merge behavior | |---|---| | Scalar | Higher layer wins. | -| Table | Merged key by key. | +| Table | Merged recursively key by key (`{}` tables allow custom subkeys). | | Array of tables keyed by `code` or `id` | Matching key replaces that entry; new keys append. | -| Other arrays (`persistent_facts`, steps) | Appended in order (lower layer → higher layer). | +| Other arrays (`persistent_facts`, steps) | Appended in precedence order (lower layer to higher layer). | -- Never invent fields absent from `customize.toml` and never copy the whole `customize.toml` (that blocks future shipped defaults). -- On agents, `agent.name` and `agent.title` are metadata; overriding them is a no-op. Use `activation_steps_prepend`, `activation_steps_append`, or `persistent_facts` to steer behavior. +- Keep override files sparse; copying the whole `customize.toml` freezes shipped defaults on updates. +- Never invent fields absent from `customize.toml`; cross-skill rules automatically ignore keys absent on a matched skill outside open `{}` tables. +- On agents, `agent.name` and `agent.title` stay fixed so agent names remain predictable. -## Troubleshooting & resetting +## Troubleshooting and resetting -- Verify merged output with `uv run "{project-root}/_bmad/scripts/resolve_customization.py" --skill "" --project-root "{project-root}"` or `uv run "{project-root}/_bmad/scripts/resolve_config.py" --project-root "{project-root}"`. -- Common causes when ignored: wrong filename, TOML syntax error, field under wrong table (`[agent]` vs `[workflow]`), personal `.user.toml` shadowing team file, or `uv` unavailable. -- Delete the field or file under `_bmad/custom/` to revert to shipped defaults. +- Verify overrides and catch typos with `uv run "{project-root}/_bmad/scripts/resolve_customization.py" --skill "" --project-root "{project-root}" --check` or `uv run "{project-root}/_bmad/scripts/resolve_config.py" --project-root "{project-root}" --check`, and inspect resolved values with `resolve_customization.py` or `resolve_config.py`. +- Common causes when ignored: wrong filename or `match` glob, TOML syntax error, field under wrong table (`[agent]` vs `[workflow]`), personal `.user.toml` shadowing team settings, or `uv` unavailable. +- Delete a field, rule entry, or override file under `_bmad/custom/` to revert to shipped defaults. -## Improving prose & removing AI-sounding tone +## Improving prose and removing AI tone -- Set project-wide writing, voice, and banned-phrase rules via `_bmad/custom/.toml` (`persistent_facts`, agent personality/style rules, or custom prompt instructions) and custom `bmad-facilitate` templates. -- Keep universal house style rules in `AGENTS.md`, or add on-demand team references in `_bmad/custom/knowledge/*.md` (retrieved by agents that query `knowledge.py`). +- Set team or cross-skill writing, voice, and banned-phrase rules via `_bmad/custom/rules.toml` (`persistent_facts`) or per-skill overrides, and place custom templates in `_bmad/custom/facilitate-templates/`. +- Keep universal house rules in `AGENTS.md`, and place on-demand team references in `_bmad/custom/knowledge/*.md` (indexed by `knowledge.py`). diff --git a/skills/core-tools/bmad-customize/references/central-and-rules.md b/skills/core-tools/bmad-customize/references/central-and-rules.md new file mode 100644 index 0000000000..209a11a74c --- /dev/null +++ b/skills/core-tools/bmad-customize/references/central-and-rules.md @@ -0,0 +1,61 @@ +# Central Config and Cross-Skill Rules + +Use this reference when the user wants to configure settings under `[core]` or `[modules.]`, or apply one rule across multiple skills through `_bmad/custom/`. + +Show the exact TOML change (or diff against the existing file), wait for an explicit confirmation, write under `{project-root}/_bmad/custom/`, and run the verification command before finishing. + +## Cross-skill rules (`rules.toml` / `rules.user.toml`) + +Define shared rules once instead of duplicating per-skill override files. Team rules live in `{project-root}/_bmad/custom/rules.toml` (committed); personal rules live in `{project-root}/_bmad/custom/rules.user.toml` (gitignored, with read-only main-checkout fallback inside a fresh linked worktree when absent locally). + +Each `[[rules]]` entry targets installed skills by directory name glob and provides `[rules.agent]` and/or `[rules.workflow]` tables using only keys that target skills expose in `customize.toml`: + +```toml +[[rules]] +id = "check-docs" +match = "bmad-*" + +[rules.workflow] +persistent_facts = ["Check the project docs before editing configuration."] +``` + +- `match`: a glob string or list of globs matched against each skill's folder name (defaults to `"*"`). +- `id`: optional rule identifier, unique within the file, for clarity and validation diagnostics. +- `surface`: optional `"agent"` or `"workflow"` when a rule applies exclusively to one surface. +- **Schema filtering:** keys absent from a matched skill's shipped `customize.toml` or incompatible in type with that skill's field schema (outside open `{}` tables) are skipped for that skill at runtime and surfaced as warnings by `--check`. +- **Precedence (lowest to highest):** `/customize.toml` < `rules.toml` < `.toml` < `rules.user.toml` < `.user.toml`. + +### Verify matching rules + +For each matched installed skill, run both schema validation and effective merge resolution: + +``` +uv run "{project-root}/_bmad/scripts/resolve_customization.py" --skill "" --project-root "{project-root}" --check +uv run "{project-root}/_bmad/scripts/resolve_customization.py" --skill "" --project-root "{project-root}" +``` + +Fix any `errors[]` before concluding, and report `warnings[]` if any rule key did not match all targeted skills. + +## Central and module settings (`config.toml` / `config.user.toml`) + +Setup creates and upgrades `_bmad/config.toml`, so never edit `_bmad/config.toml` here. Write shared team overrides to `{project-root}/_bmad/custom/config.toml` (committed) and personal settings to `{project-root}/_bmad/custom/config.user.toml` (gitignored). + +Effective central config merges four layers in ascending priority: + +1. Shipped module `[bmod.defaults]` (lowest, read from installed module records) +2. `_bmad/config.toml` (setup defaults) +3. `{project-root}/_bmad/custom/config.toml` (team overrides) +4. `{project-root}/_bmad/custom/config.user.toml` (personal overrides; or read-only main-checkout fallback inside a fresh linked worktree) + +- **Inspect available module keys:** run `uv run "{skill-root}/scripts/list_customizable_skills.py" --project-root "{project-root}"` and inspect `modules[]` (`defaults` and `question_keys`) and `central_config` before composing `[core]` or `[modules.]` entries. +- **Scalars and lists under `[core]` and `[modules.]`:** edit `{project-root}/_bmad/custom/config.toml` or `{project-root}/_bmad/custom/config.user.toml` directly via `bmad-customize`, keeping `_bmad/config.toml` untouched for `bmad` setup upgrades. +- **Structured `[core]` blocks (`models`, `capabilities`, `tooling`, `knowledge_sources`, `artifact_destinations`):** write atomically via `uv run "{project-root}/_bmad/scripts/detect_env.py" write --scope --project-root "{project-root}" --input -` or edit `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` directly. + +### Verify central config + +``` +uv run "{project-root}/_bmad/scripts/resolve_config.py" --project-root "{project-root}" --check +uv run "{project-root}/_bmad/scripts/resolve_config.py" --project-root "{project-root}" --key +``` + +Repeat `--root ` when installed skills live outside the project's default folders or home harness folders. Use `--resolve-models`, `--resolve-capabilities`, `--resolve-sources`, or `--resolve-destinations` when verifying semantic `[core]` blocks, fix any `errors[]`, and show the resolved output to confirm the override landed. diff --git a/skills/core-tools/bmad-customize/references/document-templates.md b/skills/core-tools/bmad-customize/references/document-templates.md new file mode 100644 index 0000000000..59ac60e251 --- /dev/null +++ b/skills/core-tools/bmad-customize/references/document-templates.md @@ -0,0 +1,32 @@ +# Document Templates + +Use this reference when the user asks to change a facilitation document template, add or reorder sections, set per-template defaults, or create a custom document variant under `{project-root}/_bmad/custom/`. + +Show the proposed template file (or diff), wait for explicit confirmation, write the file, and verify the merged template before finishing. + +## Workflow + +1. **Locate existing templates:** + ``` + uv run "{project-root}/_bmad/scripts/list_templates.py" --libraries-of "" --libraries-of "" "/assets" --project-root "{project-root}" --root "" --brief + ``` + Repeat `--root` for each active skills folder. Match the user's request to a template `id`; if multiple templates fit, ask which one (or both) to modify. When no existing template matches because the user wants a brand-new document type, invoke `bmad-facilitate` with its `document-template` template instead. + +2. **Route the change cleanly:** + - Specific to one document type -> edit or extend that template markdown file (`##` sections with placement/requirement comments, `stance`/`inputs`/`writing`/`done when` comments, or frontmatter keys `description`, `not_for`, `guidance`, `rubric`, `methods`, `output`, `style`, `layout`, `view`, `mode`, `order`; an empty value clears `mode` or `order`). + - Applies to every facilitated document (`mode`, `view`, `style`, `doc_standards`, `finalize_reviewers`, `output`) -> handle via `_bmad/custom/bmad-facilitate.toml` (or `.user.toml`) instead of editing every template. Ask when ambiguous. + +3. **Extend ship-safe by default:** + Inspect the base template with `--template ` first, then write a sparse extension at `{project-root}/_bmad/custom/facilitate-templates/-.md` (or update the existing extension for ``) using `extends: ` frontmatter: + - Add a `##` section with a HTML comment naming placement and what to ask (`optional` or `include when ...` when conditional; otherwise required). Match an existing heading and state replacement in its comment to replace a shipped section. + - Add `stance`, `inputs`, `writing`, or `done when` comments; they append to the base template's own. + - Set `facilitation_order` only when reordering or removing base sections, never merely to place a new section. + +4. **Copy only when extending is not enough:** + Copy the full template into `{project-root}/_bmad/custom/facilitate-templates/` with the same `template` id to replace it everywhere, or with a new `template` id (plus its own `description`, `not_for`, and `agents`) for a separate variant. Note to the user that a full copy no longer receives upstream updates to the original template. + +5. **Placement:** + `{project-root}/_bmad/custom/facilitate-templates/` is team-shared and committed. For personal templates kept out of version control, store them in a gitignored project folder and add that folder to `workflow.template_libraries` in `{project-root}/_bmad/custom/bmad-facilitate.user.toml`. + +6. **Verify:** + Run the listing command again with `--template ` in place of `--brief`, inspect `extensions`, merged `facilitation_order`, `removed`, `mode`, `layout`, and `view`, and fix any `order_problems` before finishing. When asked to show the full merged prompt text a run reads, rerun with only that runner's libraries plus `--merge ` and display the result. diff --git a/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py b/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py index 2b636bcffd..bde0a349c0 100644 --- a/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py +++ b/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py @@ -30,6 +30,7 @@ from __future__ import annotations import argparse +import copy import json import sys import tomllib @@ -42,7 +43,34 @@ # Top-level TOML blocks that indicate a customization surface. SURFACE_KEYS = ("agent", "workflow") -RESERVED_CUSTOM_FILES: frozenset[str] = frozenset({"config.toml", "config.user.toml", "bmad-state.user.toml"}) +_FALLBACK_RESERVED_CUSTOM_FILES: frozenset[str] = frozenset( + {"config.toml", "config.user.toml", "bmad-state.user.toml", "rules.toml", "rules.user.toml"} +) + + +def _load_reserved_custom_files() -> frozenset[str]: + """Load shared `RESERVED_CUSTOM_FILES` from sibling `bmad/scripts/config_utils.py` when present.""" + sibling_scripts = Path(__file__).resolve().parents[2] / "bmad" / "scripts" + if not (sibling_scripts / "config_utils.py").is_file(): + return _FALLBACK_RESERVED_CUSTOM_FILES + inserted = False + try: + if str(sibling_scripts) not in sys.path: + sys.path.insert(0, str(sibling_scripts)) + inserted = True + from config_utils import RESERVED_CUSTOM_FILES as shared_reserved + + if isinstance(shared_reserved, frozenset): + return shared_reserved + except Exception: + pass + finally: + if inserted and sys.path and sys.path[0] == str(sibling_scripts): + sys.path.pop(0) + return _FALLBACK_RESERVED_CUSTOM_FILES + + +RESERVED_CUSTOM_FILES: frozenset[str] = _load_reserved_custom_files() def default_skills_root() -> Path: @@ -88,12 +116,14 @@ def scan_skills( skills_roots: list[Path], project_root: Path, ) -> dict: - """Scan each skills root for directories that contain a customize.toml.""" + """Scan each skills root for customizable skills, module manifests, rules, and central config surfaces.""" agents: list[dict] = [] workflows: list[dict] = [] + modules: list[dict] = [] errors: list[str] = [] scanned_roots: list[str] = [] seen_names: set[str] = set() + seen_module_codes: set[str] = set() custom_dir = project_root / "_bmad" / "custom" for root in skills_roots: @@ -103,20 +133,56 @@ def scan_skills( scanned_roots.append(str(root)) for skill_dir in sorted(p for p in root.iterdir() if p.is_dir()): + skill_name = skill_dir.name + first_seen = skill_name not in seen_names + + bmod_toml = skill_dir / "bmod.toml" + if first_seen and bmod_toml.is_file(): + bmod_data = load_customize(bmod_toml) + if bmod_data is None: + errors.append(f"failed to parse {bmod_toml}") + elif isinstance(bmod_data.get("bmod"), dict): + bmod_table = bmod_data["bmod"] + code = bmod_table.get("code") + if isinstance(code, str) and code.strip() and code not in seen_module_codes: + seen_module_codes.add(code) + raw_defaults = bmod_table.get("defaults") + raw_questions = bmod_table.get("config_questions") + q_keys = ( + [ + q["key"] + for q in raw_questions + if isinstance(q, dict) and isinstance(q.get("key"), str) and q["key"] + ] + if isinstance(raw_questions, list) + else [] + ) + modules.append( + { + "code": code, + "name": skill_name, + "manifest_path": str(bmod_toml), + "defaults": copy.deepcopy(raw_defaults) if isinstance(raw_defaults, dict) else {}, + "question_keys": q_keys, + } + ) + customize_toml = skill_dir / "customize.toml" if not customize_toml.is_file(): + if (skill_dir / "SKILL.md").is_file() or bmod_toml.is_file(): + seen_names.add(skill_name) continue data = load_customize(customize_toml) if data is None: errors.append(f"failed to parse {customize_toml}") + seen_names.add(skill_name) continue - skill_name = skill_dir.name # If a skill with this name was already found in an earlier # root, skip it — roots are scanned in the order provided, so # the first occurrence wins. - if skill_name in seen_names: + if not first_seen: continue seen_names.add(skill_name) @@ -151,12 +217,34 @@ def scan_skills( else: workflows.append(entry) + setup_config = project_root / "_bmad" / "config.toml" + team_central = custom_dir / "config.toml" + user_central = custom_dir / "config.user.toml" + team_rules = custom_dir / "rules.toml" + user_rules = custom_dir / "rules.user.toml" + return { "project_root": str(project_root), "scanned_roots": scanned_roots, "custom_dir": str(custom_dir), "agents": agents, "workflows": workflows, + "modules": modules, + "central_config": { + "setup_config_path": str(setup_config), + "team_override_path": str(team_central), + "user_override_path": str(user_central), + "has_setup_config": setup_config.is_file(), + "has_team_override": team_central.is_file(), + "has_user_override": user_central.is_file(), + "setup_owned_files": ["_bmad/config.toml"], + }, + "rules": { + "team_rules_path": str(team_rules), + "user_rules_path": str(user_rules), + "has_team_rules": team_rules.is_file(), + "has_user_rules": user_rules.is_file(), + }, "errors": errors, } diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 9c94a841d6..32059dcbc0 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -6,6 +6,7 @@ from __future__ import annotations import copy +import fnmatch import os import re import stat @@ -20,7 +21,41 @@ class ConfigError(ValueError): _KEYED_MERGE_FIELDS = ("code", "id") -RESERVED_CUSTOM_FILES = frozenset({"config.toml", "config.user.toml", "bmad-state.user.toml"}) +RESERVED_CUSTOM_FILES = frozenset( + {"config.toml", "config.user.toml", "bmad-state.user.toml", "rules.toml", "rules.user.toml"} +) +CUSTOM_RULES_FILES = ("rules.toml", "rules.user.toml") +DEFAULT_SKILL_ROOT_CANDIDATES = ( + ".agents/skills", + ".claude/skills", + ".codex/skills", + ".cursor/skills", + ".windsurf/skills", + "skills", +) +HOME_SKILL_ROOT_CANDIDATES = ( + ".agents/skills", + ".claude/skills", + ".codex/skills", + ".cursor/skills", + ".windsurf/skills", +) +_CORE_CONFIG_KEYS = frozenset( + { + "project_name", + "output_folder", + "active_initiative", + "models", + "capabilities", + "tooling", + "knowledge_sources", + "artifact_destinations", + } +) +_SKIP = object() +_FILE_REF_RE = re.compile(r"(?:^|\s)file:([^\s,;'\")]+)") +_RULE_ENTRY_FIELDS = frozenset({"id", "match", "surface", "agent", "workflow"}) +_RULE_SURFACES = ("agent", "workflow") MODEL_TIERS = ("quick", "standard", "deep", "router") _CAPABILITY_KEYS = frozenset({"subagents", "inline_visuals", "computer_use", "browser_interaction"}) KNOWLEDGE_SOURCE_KINDS = ("mcp", "cli", "path", "url") @@ -355,10 +390,10 @@ def project_user_config_path(project_root: Path) -> Path: return project_root / "_bmad" / "custom" / "config.user.toml" -def worktree_fallback_user_config_candidate(project_root: Path) -> Path | None: - """Return the main-checkout `config.user.toml` candidate when `project_root` is a linked worktree lacking one.""" - local_user = project_user_config_path(project_root) - if _safe_exists(local_user) or _safe_is_symlink(local_user): +def worktree_fallback_custom_file_candidate(project_root: Path, filename: str) -> Path | None: + """Return the main-checkout `_bmad/custom/` candidate when `project_root` is a linked worktree lacking it.""" + local_file = project_root / "_bmad" / "custom" / filename + if _safe_exists(local_file) or _safe_is_symlink(local_file): return None resolved_root = _safe_resolve(project_root) if resolved_root is None: @@ -366,13 +401,23 @@ def worktree_fallback_user_config_candidate(project_root: Path) -> Path | None: counterpart = _worktree_counterpart_root(resolved_root) if counterpart is None: return None - return project_user_config_path(counterpart) + return counterpart / "_bmad" / "custom" / filename + + +def worktree_fallback_custom_file_path(project_root: Path, filename: str) -> Path | None: + """Return read-only main-checkout `_bmad/custom/` when `project_root` is a linked worktree lacking it.""" + candidate = worktree_fallback_custom_file_candidate(project_root, filename) + return candidate if (candidate is not None and _safe_is_file(candidate)) else None + + +def worktree_fallback_user_config_candidate(project_root: Path) -> Path | None: + """Return the main-checkout `config.user.toml` candidate when `project_root` is a linked worktree lacking one.""" + return worktree_fallback_custom_file_candidate(project_root, "config.user.toml") def worktree_fallback_user_config_path(project_root: Path) -> Path | None: """Return read-only main-checkout `config.user.toml` when `project_root` is a linked worktree lacking one.""" - candidate = worktree_fallback_user_config_candidate(project_root) - return candidate if (candidate is not None and _safe_is_file(candidate)) else None + return worktree_fallback_custom_file_path(project_root, "config.user.toml") def normalize_harness_slug(harness: str) -> str: @@ -487,38 +532,151 @@ def merge_layers(layers: Iterable[dict[str, Any]]) -> dict[str, Any]: return merged -def _central_layers_for_root( - project_root: Path, +def discover_default_skill_roots(project_roots: Iterable[Path]) -> list[Path]: + """Discover installed skills folders across ordered project roots and home harness folders.""" + roots = list(project_roots) + found: list[Path] = [] + seen: set[Path] = set() + for base in reversed(roots): + for rel in DEFAULT_SKILL_ROOT_CANDIDATES: + candidate = base / rel + if not _safe_is_dir(candidate): + continue + resolved = _safe_resolve(candidate) + if resolved is None or resolved in seen: + continue + seen.add(resolved) + found.append(resolved) + try: + home = Path.home() + except (OSError, RuntimeError): + home = None + if home is not None: + for rel in HOME_SKILL_ROOT_CANDIDATES: + candidate = home / rel + if not _safe_is_dir(candidate): + continue + resolved = _safe_resolve(candidate) + if resolved is None or resolved in seen: + continue + seen.add(resolved) + found.append(resolved) + return found + + +def _iter_skill_entries(root: Path) -> Iterable[Path]: + """Yield skill folders under `root`, supporting flat installs and 1-level grouped `skills//` trees.""" + try: + top_entries = sorted(root.iterdir(), key=lambda entry: entry.name) + except OSError: + return + for entry in top_entries: + if not _safe_is_dir(entry): + continue + if _safe_is_file(entry / "SKILL.md") or _safe_is_file(entry / "bmod.toml"): + yield entry + continue + try: + children = sorted(entry.iterdir(), key=lambda child: child.name) + except OSError: + continue + for child in children: + if _safe_is_dir(child) and (_safe_is_file(child / "SKILL.md") or _safe_is_file(child / "bmod.toml")): + yield child + + +def load_module_defaults( + skill_roots: Iterable[Path] | None = None, *, - require_project: bool = True, -) -> tuple[dict[str, Any], ...]: - bmad_dir = project_root / "_bmad" - local_user = project_user_config_path(project_root) + project_roots: Iterable[Path] = (), +) -> dict[str, Any]: + """Load shipped unasked `[bmod.defaults]` from installed `bmod.toml` records (lowest central layer).""" + roots = [r for r in skill_roots] if skill_roots is not None else discover_default_skill_roots(project_roots) + if not roots: + return {} + seen_folders: set[str] = set() + modules_defaults: dict[str, dict[str, Any]] = {} + for root in roots: + for entry in _iter_skill_entries(root): + if entry.name in seen_folders: + continue + manifest = entry / "bmod.toml" + if not _safe_is_file(manifest): + if _safe_is_file(entry / "SKILL.md"): + seen_folders.add(entry.name) + continue + seen_folders.add(entry.name) + try: + raw = manifest.read_text(encoding="utf-8-sig") + parsed = tomllib.loads(raw) + except (OSError, UnicodeError, tomllib.TOMLDecodeError): + continue + if not isinstance(parsed, dict): + continue + bmod_table = parsed.get("bmod") + if not isinstance(bmod_table, dict): + continue + code = bmod_table.get("code") + if not isinstance(code, str) or not code.strip(): + continue + raw_defaults = bmod_table.get("defaults") + if raw_defaults is None: + continue + if not isinstance(raw_defaults, dict) or code in raw_defaults: + continue + if raw_defaults and code not in modules_defaults: + modules_defaults[code] = copy.deepcopy(raw_defaults) + return {"modules": modules_defaults} if modules_defaults else {} + + +def _resolve_personal_custom_file(project_root: Path, filename: str) -> tuple[Path | None, bool]: + local_file = project_root / "_bmad" / "custom" / filename try: - local_present = local_user.exists() or local_user.is_symlink() + local_present = local_file.exists() or local_file.is_symlink() except OSError as error: - raise ConfigError(f"failed to stat {local_user}: {error}") from error + raise ConfigError(f"failed to stat {local_file}: {error}") from error if local_present: - user_layer = load_toml(local_user) - else: - fallback_user = worktree_fallback_user_config_path(project_root) - user_layer = load_cross_boundary_toml(fallback_user) if fallback_user is not None else {} - return ( - load_toml(bmad_dir / "config.toml", required=require_project), - load_toml(bmad_dir / "custom" / "config.toml"), - user_layer, - ) + return local_file, False + fallback = worktree_fallback_custom_file_path(project_root, filename) + return (fallback, True) if fallback is not None else (None, False) + + +def _load_personal_custom_toml(project_root: Path, filename: str) -> dict[str, Any]: + target, is_fallback = _resolve_personal_custom_file(project_root, filename) + if target is None: + return {} + return load_cross_boundary_toml(target) if is_fallback else load_toml(target) + + +def _user_layer_for_root(project_root: Path) -> dict[str, Any]: + return _load_personal_custom_toml(project_root, "config.user.toml") def central_config_layers_for_roots( project_roots: Iterable[Path], *, require_project: bool = True, + skill_roots: Iterable[Path] | None = None, ) -> tuple[dict[str, Any], ...]: - """Load central config layers across ordered `_bmad/` roots in ascending precedence (lowest -> highest).""" + """Load central config layers across ordered `_bmad/` roots in ascending precedence (lowest -> highest). + + Precedence: + 1. Shipped module `[bmod.defaults]` (if any installed module declares unasked defaults) + 2. Team layers per root (`_bmad/config.toml` then `_bmad/custom/config.toml` in root order) + 3. Personal layers per root (`_bmad/custom/config.user.toml` or read-only worktree fallback in root order) + """ + roots = tuple(project_roots) layers: list[dict[str, Any]] = [] - for root in project_roots: - layers.extend(_central_layers_for_root(root, require_project=require_project)) + if roots or skill_roots is not None: + defaults_layer = load_module_defaults(skill_roots, project_roots=roots) + if defaults_layer: + layers.append(defaults_layer) + for root in roots: + bmad_dir = root / "_bmad" + layers.append(load_toml(bmad_dir / "config.toml", required=require_project)) + layers.append(load_toml(bmad_dir / "custom" / "config.toml")) + for root in roots: + layers.append(_user_layer_for_root(root)) return tuple(layers) @@ -526,34 +684,801 @@ def central_config_layers( project_root: Path | None, *, require_project: bool = True, + skill_roots: Iterable[Path] | None = None, ) -> tuple[dict[str, Any], ...]: """Load central config layers in ascending precedence (lowest -> highest). Precedence: - 1. /_bmad/config.toml (project defaults, required unless require_project=False) - 2. /_bmad/custom/config.toml (team overrides, optional) - 3. /_bmad/custom/config.user.toml (or read-only main-checkout fallback in a linked worktree) + 1. Shipped module `[bmod.defaults]` (lowest, when present) + 2. /_bmad/config.toml (project defaults, required unless require_project=False) + 3. /_bmad/custom/config.toml (team overrides, optional) + 4. /_bmad/custom/config.user.toml (or read-only main-checkout fallback in a linked worktree) """ if project_root is None: + if skill_roots is not None: + defaults_layer = load_module_defaults(skill_roots) + return (defaults_layer,) if defaults_layer else () return () - return _central_layers_for_root(project_root, require_project=require_project) + return central_config_layers_for_roots((project_root,), require_project=require_project, skill_roots=skill_roots) + + +def load_central_config(project_root: Path, *, skill_roots: Iterable[Path] | None = None) -> dict[str, Any]: + return merge_layers(central_config_layers(project_root, require_project=True, skill_roots=skill_roots)) + + +def _normalize_rule_patterns(raw_match: Any, *, source: Path, index: int) -> tuple[str, ...]: + if raw_match is None: + return ("*",) + if isinstance(raw_match, str): + cleaned = raw_match.strip() + if not cleaned: + raise ConfigError(f"{source}: rules[{index}].match must not be empty") + return (cleaned,) + if isinstance(raw_match, list) and raw_match: + patterns: list[str] = [] + for entry in raw_match: + if not isinstance(entry, str) or not entry.strip(): + raise ConfigError(f"{source}: rules[{index}].match entries must be non-empty strings") + patterns.append(entry.strip()) + return tuple(patterns) + raise ConfigError(f"{source}: rules[{index}].match must be a pattern string or non-empty list of strings") + + +def _parse_rules_data( + data: dict[str, Any], *, path: Path +) -> list[tuple[str | None, tuple[str, ...], str | None, dict[str, Any]]]: + if not data: + return [] + unknown_top = sorted(set(data) - {"rules"}) + if unknown_top: + raise ConfigError(f"{path}: unsupported top-level keys in rules file: {', '.join(unknown_top)}") + raw_rules = data.get("rules") + if not isinstance(raw_rules, list): + raise ConfigError(f"{path}: `rules` must be an array of tables ([[rules]])") + parsed: list[tuple[str | None, tuple[str, ...], str | None, dict[str, Any]]] = [] + seen_ids: set[str] = set() + for index, entry in enumerate(raw_rules): + if not isinstance(entry, dict): + raise ConfigError(f"{path}: rules[{index}] must be a table") + unknown_fields = sorted(set(entry) - _RULE_ENTRY_FIELDS) + if unknown_fields: + raise ConfigError(f"{path}: rules[{index}] has unsupported fields: {', '.join(unknown_fields)}") + rule_id = entry.get("id") + normalized_id: str | None = None + if rule_id is not None: + if not isinstance(rule_id, str) or not rule_id.strip(): + raise ConfigError(f"{path}: rules[{index}].id must be a non-empty string") + normalized_id = rule_id.strip() + if normalized_id in seen_ids: + raise ConfigError(f"{path}: duplicate rule id {normalized_id!r}") + seen_ids.add(normalized_id) + patterns = _normalize_rule_patterns(entry.get("match"), source=path, index=index) + surface = entry.get("surface") + if surface is not None and surface not in _RULE_SURFACES: + raise ConfigError(f"{path}: rules[{index}].surface must be 'agent' or 'workflow', got {surface!r}") + payload: dict[str, Any] = {} + for key in _RULE_SURFACES: + if key in entry: + block = entry[key] + if not isinstance(block, dict): + raise ConfigError(f"{path}: rules[{index}].{key} must be a table") + if surface is not None and surface != key: + raise ConfigError(f"{path}: rules[{index}] sets surface={surface!r} alongside [rules.{key}]") + payload[key] = block + if not payload: + raise ConfigError(f"{path}: rules[{index}] must define [rules.agent] and/or [rules.workflow]") + parsed.append((normalized_id, patterns, surface, payload)) + return parsed + + +def _parse_rules_file(path: Path) -> list[tuple[str | None, tuple[str, ...], str | None, dict[str, Any]]]: + return _parse_rules_data(load_toml(path), path=path) + + +def _parse_rules_cross_boundary(path: Path) -> list[tuple[str | None, tuple[str, ...], str | None, dict[str, Any]]]: + return _parse_rules_data(load_cross_boundary_toml(path), path=path) + + +def _scalar_types_compatible(schema: Any, value: Any) -> bool: + if isinstance(value, (dict, list)): + return False + if isinstance(schema, bool) or isinstance(value, bool): + return isinstance(schema, bool) and isinstance(value, bool) + if isinstance(schema, (int, float)) and isinstance(value, (int, float)): + return isinstance(schema, float) or isinstance(value, int) + return type(schema) is type(value) + + +def _filter_rule_against_schema( + payload: Any, + schema: Any, + *, + source: Path, + path_label: str, + dropped_keys: list[str] | None = None, + mismatched_keys: list[str] | None = None, +) -> Any: + if isinstance(schema, dict): + if not isinstance(payload, dict): + if mismatched_keys is not None: + mismatched_keys.append(f"{path_label} (expected table, got {type(payload).__name__})") + return _SKIP + if not schema: + # Open subtable (`{}` in customize.toml): preserve keys verbatim. + return copy.deepcopy(payload) + filtered: dict[str, Any] = {} + for key, value in payload.items(): + child_label = f"{path_label}.{key}" if path_label else key + if key not in schema: + if dropped_keys is not None: + dropped_keys.append(child_label) + continue + child_schema = schema[key] + child_val = _filter_rule_against_schema( + value, + child_schema, + source=source, + path_label=child_label, + dropped_keys=dropped_keys, + mismatched_keys=mismatched_keys, + ) + if child_val is _SKIP: + continue + if isinstance(child_schema, dict) and child_schema and not child_val: + continue + filtered[key] = child_val + return filtered + if isinstance(schema, list): + if not isinstance(payload, list): + if mismatched_keys is not None: + mismatched_keys.append(f"{path_label} (expected list, got {type(payload).__name__})") + return _SKIP + return copy.deepcopy(payload) + if not _scalar_types_compatible(schema, payload): + if mismatched_keys is not None: + mismatched_keys.append(f"{path_label} (expected {type(schema).__name__}, got {type(payload).__name__})") + return _SKIP + return copy.deepcopy(payload) + + +def _matching_rule_layers_for_file( + path: Path, + skill_name: str, + defaults: dict[str, Any], + *, + cross_boundary: bool = False, +) -> list[dict[str, Any]]: + layers: list[dict[str, Any]] = [] + entries = _parse_rules_cross_boundary(path) if cross_boundary else _parse_rules_file(path) + for _rule_id, patterns, surface, payload in entries: + if not any(fnmatch.fnmatchcase(skill_name, pattern) for pattern in patterns): + continue + if surface is not None and surface not in defaults: + continue + filtered = _filter_rule_against_schema(payload, defaults, source=path, path_label="") + if filtered is not _SKIP and isinstance(filtered, dict) and filtered: + layers.append(filtered) + return layers + + +def _rules_entries_has_match(path: Path, skill_name: str, *, cross_boundary: bool = False) -> bool: + try: + entries = _parse_rules_cross_boundary(path) if cross_boundary else _parse_rules_file(path) + except ConfigError: + return True + return any(any(fnmatch.fnmatchcase(skill_name, pat) for pat in patterns) for _, patterns, _, _ in entries) + + +def has_matching_custom_rule(custom_dir: Path, skill_name: str, *, project_root: Path | None = None) -> bool: + """Return True when `_bmad/custom/rules*.toml` (or worktree fallback) matches `skill_name`.""" + for filename in CUSTOM_RULES_FILES: + path = custom_dir / filename + if _safe_is_file(path) and _rules_entries_has_match(path, skill_name): + return True + if project_root is not None: + fallback = worktree_fallback_custom_file_path(project_root, "rules.user.toml") + if fallback is not None and _rules_entries_has_match(fallback, skill_name, cross_boundary=True): + return True + return False + +def load_customization_for_roots(project_roots: Iterable[Path], skill_dir: Path) -> dict[str, Any]: + """Load effective customization across ordered `_bmad/` roots and project-local cross-skill rules. -def load_central_config(project_root: Path) -> dict[str, Any]: - return merge_layers(central_config_layers(project_root, require_project=True)) + Precedence (lowest -> highest): + 1. `/customize.toml` (shipped base) + 2. Team layers per root: `/_bmad/custom/rules.toml` matching rules, then `.toml` + 3. Personal layers per root: `/_bmad/custom/rules.user.toml` (or worktree fallback) matching rules, then `.user.toml` (or worktree fallback) + """ + roots = tuple(project_roots) + skill_name = skill_dir.name + defaults = load_toml(skill_dir / "customize.toml", required=True) + layers: list[dict[str, Any]] = [defaults] + for root in roots: + custom_dir = root / "_bmad" / "custom" + layers.extend(_matching_rule_layers_for_file(custom_dir / "rules.toml", skill_name, defaults)) + layers.append(load_toml(custom_dir / f"{skill_name}.toml")) + for root in roots: + rules_user_path, rules_is_fallback = _resolve_personal_custom_file(root, "rules.user.toml") + if rules_user_path is not None: + layers.extend( + _matching_rule_layers_for_file( + rules_user_path, + skill_name, + defaults, + cross_boundary=rules_is_fallback, + ) + ) + layers.append(_load_personal_custom_toml(root, f"{skill_name}.user.toml")) + merged = merge_layers(layers) + return apply_worktree_path_fallbacks(merged, roots[-1]) if roots else merged def load_customization(project_root: Path | None, skill_dir: Path) -> dict[str, Any]: + return load_customization_for_roots((project_root,) if project_root is not None else (), skill_dir) + + +def _extract_concrete_file_refs(value: Any) -> list[str]: + refs: list[str] = [] + if isinstance(value, str): + for match in _FILE_REF_RE.finditer(value): + target = match.group(1).strip().rstrip(".,;:)") + if target.startswith("{project-root}/"): + target = target[len("{project-root}/") :] + elif target.startswith("{project-root}\\"): + target = target[len("{project-root}\\") :] + if not target or any(ch in target for ch in "*?[{"): + continue + refs.append(target) + elif isinstance(value, list): + for item in value: + refs.extend(_extract_concrete_file_refs(item)) + elif isinstance(value, dict): + for child in value.values(): + refs.extend(_extract_concrete_file_refs(child)) + return refs + + +def _check_missing_file_refs( + node: Any, + project_root: Path, + *, + source: Path, + prefix: str, + errors: list[dict[str, str]], +) -> None: + if isinstance(node, dict): + for key, value in node.items(): + child_prefix = f"{prefix}.{key}" if prefix else str(key) + _check_missing_file_refs(value, project_root, source=source, prefix=child_prefix, errors=errors) + return + for target in _extract_concrete_file_refs(node): + candidate = Path(target) + if candidate.is_absolute(): + exists = _safe_exists(candidate) + else: + exists = _safe_exists(project_root / candidate) or ( + resolve_worktree_path_fallback(target, project_root) is not None + ) + if not exists: + errors.append( + { + "kind": "missing-file-ref", + "file": str(source), + "key": prefix, + "target": target, + "message": f"missing `file:` target {target!r} referenced at `{prefix}` in {source}", + } + ) + + +def _validate_override_against_schema( + override: Any, + schema: Any, + *, + source: Path, + prefix: str, + errors: list[dict[str, str]], +) -> None: + if isinstance(schema, dict): + if not isinstance(override, dict): + errors.append( + { + "kind": "type-mismatch", + "file": str(source), + "key": prefix, + "message": f"`{prefix}` must be a table, got {type(override).__name__}", + } + ) + return + if not schema: + return + for key, value in override.items(): + child_prefix = f"{prefix}.{key}" if prefix else str(key) + if key not in schema: + errors.append( + { + "kind": "unknown-key", + "file": str(source), + "key": child_prefix, + "message": f"unknown customization key `{child_prefix}` in {source}", + } + ) + else: + _validate_override_against_schema(value, schema[key], source=source, prefix=child_prefix, errors=errors) + return + if isinstance(schema, list): + if not isinstance(override, list): + errors.append( + { + "kind": "type-mismatch", + "file": str(source), + "key": prefix, + "message": f"`{prefix}` must be a list, got {type(override).__name__}", + } + ) + return + if not _scalar_types_compatible(schema, override): + errors.append( + { + "kind": "type-mismatch", + "file": str(source), + "key": prefix, + "message": f"`{prefix}` expected {type(schema).__name__}, got {type(override).__name__}", + } + ) + + +def _check_skill_override_file( + path: Path, + defaults: dict[str, Any], + root: Path, + *, + cross_boundary: bool, + checked_files: list[str], + errors: list[dict[str, str]], +) -> None: + checked_files.append(str(path)) + try: + data = load_cross_boundary_toml(path) if cross_boundary else load_toml(path) + except ConfigError as error: + errors.append({"kind": "invalid-toml", "file": str(path), "key": "", "message": str(error)}) + return + _validate_override_against_schema(data, defaults, source=path, prefix="", errors=errors) + _check_missing_file_refs(data, root, source=path, prefix="", errors=errors) + + +def _check_rules_file_for_skill( + rules_path: Path, + skill_name: str, + defaults: dict[str, Any], + root: Path, + *, + cross_boundary: bool, + checked_files: list[str], + errors: list[dict[str, str]], + warnings: list[dict[str, Any]], +) -> None: + checked_files.append(str(rules_path)) + try: + entries = _parse_rules_cross_boundary(rules_path) if cross_boundary else _parse_rules_file(rules_path) + except ConfigError as error: + errors.append({"kind": "invalid-rules", "file": str(rules_path), "key": "", "message": str(error)}) + return + for idx, (rule_id, patterns, surface, payload) in enumerate(entries): + if not any(fnmatch.fnmatchcase(skill_name, pat) for pat in patterns): + continue + if surface is not None and surface not in defaults: + continue + dropped: list[str] = [] + mismatched: list[str] = [] + filtered = _filter_rule_against_schema( + payload, + defaults, + source=rules_path, + path_label="", + dropped_keys=dropped, + mismatched_keys=mismatched, + ) + label = rule_id or f"rules[{idx}]" + if dropped: + warnings.append( + { + "kind": "unmatched-rule-key", + "file": str(rules_path), + "rule": label, + "keys": dropped, + "message": ( + f"rule `{label}` in {rules_path} sets keys not in `{skill_name}` " + f"customize.toml ({', '.join(dropped)})" + ), + } + ) + if mismatched: + warnings.append( + { + "kind": "rule-type-mismatch", + "file": str(rules_path), + "rule": label, + "keys": mismatched, + "message": ( + f"rule `{label}` in {rules_path} skipped keys with incompatible types " + f"for `{skill_name}` ({', '.join(mismatched)})" + ), + } + ) + if filtered is not _SKIP and isinstance(filtered, dict): + _check_missing_file_refs(filtered, root, source=rules_path, prefix="", errors=errors) + + +def check_customization(project_roots: Iterable[Path], skill_dir: Path) -> dict[str, Any]: + """Validate team/user overrides and matching cross-skill rules against shipped `customize.toml`.""" + defaults = load_toml(skill_dir / "customize.toml", required=True) + roots = tuple(project_roots) skill_name = skill_dir.name - custom_dir = project_root / "_bmad" / "custom" if project_root else None - merged = merge_layers( - ( - load_toml(skill_dir / "customize.toml", required=True), - load_toml(custom_dir / f"{skill_name}.toml") if custom_dir else {}, - load_toml(custom_dir / f"{skill_name}.user.toml") if custom_dir else {}, + errors: list[dict[str, str]] = [] + warnings: list[dict[str, Any]] = [] + checked_files: list[str] = [] + + if not roots: + warnings.append( + { + "kind": "no-project-root", + "message": "no _bmad/ project root found; only shipped customize.toml was checked", + } ) - ) - return apply_worktree_path_fallbacks(merged, project_root) if project_root is not None else merged + + for root in roots: + custom_dir = root / "_bmad" / "custom" + team_path = custom_dir / f"{skill_name}.toml" + if _safe_is_file(team_path): + _check_skill_override_file( + team_path, + defaults, + root, + cross_boundary=False, + checked_files=checked_files, + errors=errors, + ) + user_path, user_is_fallback = _resolve_personal_custom_file(root, f"{skill_name}.user.toml") + if user_path is not None and _safe_is_file(user_path): + _check_skill_override_file( + user_path, + defaults, + root, + cross_boundary=user_is_fallback, + checked_files=checked_files, + errors=errors, + ) + + team_rules = custom_dir / "rules.toml" + if _safe_is_file(team_rules): + _check_rules_file_for_skill( + team_rules, + skill_name, + defaults, + root, + cross_boundary=False, + checked_files=checked_files, + errors=errors, + warnings=warnings, + ) + user_rules, rules_is_fallback = _resolve_personal_custom_file(root, "rules.user.toml") + if user_rules is not None and _safe_is_file(user_rules): + _check_rules_file_for_skill( + user_rules, + skill_name, + defaults, + root, + cross_boundary=rules_is_fallback, + checked_files=checked_files, + errors=errors, + warnings=warnings, + ) + + return { + "skill": skill_name, + "ok": len(errors) == 0, + "checked_files": checked_files, + "errors": errors, + "warnings": warnings, + } + + +def _collect_table_keys_and_open_prefixes(node: dict[str, Any], prefix: str = "") -> tuple[set[str], set[str]]: + keys: set[str] = set() + open_prefixes: set[str] = set() + for raw_key, child in node.items(): + dotted = f"{prefix}.{raw_key}" if prefix else str(raw_key) + if isinstance(child, dict): + if child: + child_keys, child_open = _collect_table_keys_and_open_prefixes(child, dotted) + keys.update(child_keys) + open_prefixes.update(child_open) + else: + keys.add(dotted) + open_prefixes.add(dotted) + else: + keys.add(dotted) + return keys, open_prefixes + + +def _discover_module_schemas( + skill_roots: Iterable[Path] | None, + project_roots: tuple[Path, ...], + *, + errors: list[dict[str, str]], +) -> dict[str, tuple[set[str], set[str]]]: + roots = [r for r in skill_roots] if skill_roots is not None else discover_default_skill_roots(project_roots) + seen_folders: set[str] = set() + schemas: dict[str, tuple[set[str], set[str]]] = {} + for root in roots: + for entry in _iter_skill_entries(root): + if entry.name in seen_folders: + continue + manifest = entry / "bmod.toml" + if not _safe_is_file(manifest): + if _safe_is_file(entry / "SKILL.md"): + seen_folders.add(entry.name) + continue + seen_folders.add(entry.name) + try: + parsed = load_toml(manifest) + except ConfigError: + continue + bmod_table = parsed.get("bmod") + if not isinstance(bmod_table, dict): + continue + code = bmod_table.get("code") + if not isinstance(code, str) or not code.strip(): + continue + q_keys: set[str] = set() + raw_questions = bmod_table.get("config_questions") + if isinstance(raw_questions, list): + for q in raw_questions: + if isinstance(q, dict) and isinstance(q.get("key"), str) and q["key"]: + q_keys.add(q["key"]) + d_keys: set[str] = set() + d_open: set[str] = set() + raw_defaults = bmod_table.get("defaults") + if raw_defaults is not None: + if not isinstance(raw_defaults, dict) or code in raw_defaults: + errors.append( + { + "kind": "invalid-module-defaults", + "file": str(manifest), + "key": f"modules.{code}", + "message": f"invalid [bmod.defaults] in {manifest}", + } + ) + else: + d_keys, d_open = _collect_table_keys_and_open_prefixes(raw_defaults) + if code not in schemas: + schemas[code] = (q_keys | d_keys, d_open) + return schemas + + +def check_central_config( + project_roots: Iterable[Path], + *, + skill_roots: Iterable[Path] | None = None, +) -> dict[str, Any]: + """Validate `_bmad/custom/config*.toml` keys and structured `[core]` blocks against schemas and module manifests.""" + roots = tuple(project_roots) + errors: list[dict[str, str]] = [] + warnings: list[dict[str, Any]] = [] + checked_files: list[str] = [] + + if not roots: + warnings.append( + { + "kind": "no-project-root", + "message": "no _bmad/ project root found; central configuration was not checked", + } + ) + return {"ok": True, "checked_files": checked_files, "errors": errors, "warnings": warnings} + + module_schemas = _discover_module_schemas(skill_roots, roots, errors=errors) + setup_core_keys: set[str] = set() + setup_module_keys: dict[str, set[str]] = {} + parse_error = False + + for root in roots: + setup_cfg = root / "_bmad" / "config.toml" + if not _safe_is_file(setup_cfg): + continue + try: + setup_data = load_toml(setup_cfg) + except ConfigError as error: + parse_error = True + errors.append({"kind": "invalid-toml", "file": str(setup_cfg), "key": "", "message": str(error)}) + continue + setup_core = setup_data.get("core") + if isinstance(setup_core, dict): + setup_core_keys.update(str(k) for k in setup_core) + setup_mods = setup_data.get("modules") + if isinstance(setup_mods, dict): + for code, mod_table in setup_mods.items(): + if isinstance(mod_table, dict): + keys, _ = _collect_table_keys_and_open_prefixes(mod_table) + setup_module_keys.setdefault(str(code), set()).update(keys) + + for root in roots: + targets: list[tuple[Path, bool]] = [] + team_cfg = project_team_config_path(root) + if _safe_is_file(team_cfg): + targets.append((team_cfg, False)) + user_cfg, user_is_fallback = _resolve_personal_custom_file(root, "config.user.toml") + if user_cfg is not None and _safe_is_file(user_cfg): + targets.append((user_cfg, user_is_fallback)) + + for path, is_fallback in targets: + checked_files.append(str(path)) + try: + data = load_cross_boundary_toml(path) if is_fallback else load_toml(path) + except ConfigError as error: + parse_error = True + errors.append({"kind": "invalid-toml", "file": str(path), "key": "", "message": str(error)}) + continue + for top_key in sorted(set(data) - {"core", "modules"}): + errors.append( + { + "kind": "unknown-top-level-key", + "file": str(path), + "key": top_key, + "message": f"unsupported top-level table `{top_key}` in {path}; expected `core` or `modules`", + } + ) + if "core" in data: + core_table = data["core"] + if not isinstance(core_table, dict): + errors.append( + { + "kind": "type-mismatch", + "file": str(path), + "key": "core", + "message": f"`core` must be a table, got {type(core_table).__name__}", + } + ) + else: + allowed_core = _CORE_CONFIG_KEYS | setup_core_keys + for key, value in core_table.items(): + if key not in allowed_core: + errors.append( + { + "kind": "unknown-core-key", + "file": str(path), + "key": f"core.{key}", + "message": f"unknown central key `core.{key}` in {path}", + } + ) + elif key in ("project_name", "output_folder", "active_initiative") and not isinstance( + value, str + ): + errors.append( + { + "kind": "type-mismatch", + "file": str(path), + "key": f"core.{key}", + "message": f"`core.{key}` must be a string, got {type(value).__name__}", + } + ) + if "modules" in data: + mods_table = data["modules"] + if not isinstance(mods_table, dict): + errors.append( + { + "kind": "type-mismatch", + "file": str(path), + "key": "modules", + "message": f"`modules` must be a table, got {type(mods_table).__name__}", + } + ) + else: + for code, mod_table in mods_table.items(): + if not isinstance(mod_table, dict): + errors.append( + { + "kind": "type-mismatch", + "file": str(path), + "key": f"modules.{code}", + "message": f"`modules.{code}` must be a table, got {type(mod_table).__name__}", + } + ) + continue + if code in module_schemas or code in setup_module_keys: + schema_keys, open_prefixes = module_schemas.get(code, (set(), set())) + allowed_mod = schema_keys | setup_module_keys.get(code, set()) + override_keys, _ = _collect_table_keys_and_open_prefixes(mod_table) + for mod_key in sorted(override_keys): + if ( + mod_key in allowed_mod + or any(mod_key == p or mod_key.startswith(f"{p}.") for p in open_prefixes) + or any(ak.startswith(f"{mod_key}.") for ak in allowed_mod) + ): + continue + errors.append( + { + "kind": "unknown-module-key", + "file": str(path), + "key": f"modules.{code}.{mod_key}", + "message": f"unknown module setting `modules.{code}.{mod_key}` in {path}", + } + ) + elif module_schemas: + errors.append( + { + "kind": "unknown-module", + "file": str(path), + "key": f"modules.{code}", + "message": f"unknown module `{code}` in {path}; not found in installed module manifests", + } + ) + else: + warnings.append( + { + "kind": "unverified-module", + "file": str(path), + "key": f"modules.{code}", + "message": ( + f"no installed module manifests found to verify `modules.{code}`; " + "pass `--root ` when checking out-of-tree installs" + ), + } + ) + + if not parse_error: + try: + layers = central_config_layers_for_roots(roots, require_project=False, skill_roots=skill_roots) + merged = merge_layers(layers) + except ConfigError as error: + errors.append({"kind": "invalid-central-config", "file": "", "key": "", "message": str(error)}) + merged = {} + layers = () + core = merged.get("core") if isinstance(merged.get("core"), dict) else {} + if "models" in core: + try: + resolve_models(layers) + except ConfigError as error: + errors.append({"kind": "invalid-core-block", "file": "", "key": "core.models", "message": str(error)}) + if "capabilities" in core or "tooling" in core: + try: + resolve_capabilities(merged) + except ConfigError as error: + errors.append( + {"kind": "invalid-core-block", "file": "", "key": "core.capabilities", "message": str(error)} + ) + if "knowledge_sources" in core: + try: + resolve_knowledge_sources(layers, project_root=roots[-1], include_disabled=True) + except ConfigError as error: + errors.append( + { + "kind": "invalid-core-block", + "file": "", + "key": "core.knowledge_sources", + "message": str(error), + } + ) + if "artifact_destinations" in core: + try: + resolve_artifact_destinations(layers, project_root=roots[-1], include_disabled=True) + except ConfigError as error: + errors.append( + { + "kind": "invalid-core-block", + "file": "", + "key": "core.artifact_destinations", + "message": str(error), + } + ) + + return { + "ok": len(errors) == 0, + "checked_files": checked_files, + "errors": errors, + "warnings": warnings, + } def _dedupe_strings(items: Iterable[str]) -> list[str]: diff --git a/skills/core-tools/bmad/scripts/knowledge.py b/skills/core-tools/bmad/scripts/knowledge.py index 01db9166fd..9cc1b534b6 100644 --- a/skills/core-tools/bmad/scripts/knowledge.py +++ b/skills/core-tools/bmad/scripts/knowledge.py @@ -86,6 +86,9 @@ from bmod_utils import ( scan as scan, ) +from config_utils import ( # noqa: E402 + DEFAULT_SKILL_ROOT_CANDIDATES as DEFAULT_ROOT_CANDIDATES, +) from config_utils import ( # noqa: E402 ConfigError, central_config_layers, @@ -123,16 +126,6 @@ }) # fmt: skip -DEFAULT_ROOT_CANDIDATES = ( - ".agents/skills", - ".claude/skills", - ".codex/skills", - ".cursor/skills", - ".windsurf/skills", - "skills", -) - - def discover_roots(project_root: Path | None) -> list[Path]: """Find unique existing skills roots under `project_root`.""" if project_root is None: diff --git a/skills/core-tools/bmad/scripts/render_skill.py b/skills/core-tools/bmad/scripts/render_skill.py index ead6d0ff6f..52d2800d05 100644 --- a/skills/core-tools/bmad/scripts/render_skill.py +++ b/skills/core-tools/bmad/scripts/render_skill.py @@ -28,6 +28,7 @@ from config_utils import ( # noqa: E402 ConfigError, + discover_default_skill_roots, find_project_root, is_path_field, load_central_config, @@ -119,8 +120,14 @@ def _leaf_paths(table: dict[str, Any], prefix: str = "") -> set[str]: def _declares(defaults: dict[str, Any], path: str) -> bool: node: Any = defaults - for part in path.split("."): - if not isinstance(node, dict) or part not in node: + parts = path.split(".") + for index, part in enumerate(parts): + if not isinstance(node, dict): + return False + if index > 0 and len(node) == 0: + # Open subtable in customize.toml (an empty `{}` table): allow user-defined keys below it. + return True + if part not in node: return False node = node[part] return True @@ -687,7 +694,12 @@ def _publish(destination: Path, outputs: dict[str, bytes], manifest: dict[str, A def render( - project_root: Path, skill_dir: Path, *, overrides: Path | None = None, assignments: list[str] | None = None + project_root: Path, + skill_dir: Path, + *, + overrides: Path | None = None, + assignments: list[str] | None = None, + skill_roots: tuple[Path, ...] = (), ) -> Path: project_root = project_root.resolve(strict=True) skill_dir = skill_dir.resolve(strict=True) @@ -696,7 +708,11 @@ def render( sources = _load_sources(skill_dir) assets = _load_assets(skill_dir) - central = load_central_config(project_root) + discovered = tuple(discover_default_skill_roots((project_root,))) if not skill_roots else () + effective_skill_roots = tuple( + dict.fromkeys((skill_dir.parent, *(root.resolve() for root in skill_roots), *discovered)) + ) + central = load_central_config(project_root, skill_roots=effective_skill_roots) has_customization = bool(overrides is not None or assignments) or (skill_dir / "customize.toml").is_file() defaults = load_toml(skill_dir / "customize.toml", required=True) if has_customization else None _check_persistent_layers(project_root, skill_dir, defaults) @@ -914,7 +930,9 @@ def main() -> int: roots = tuple(args.root) skill_dir = _resolve_skill_dir(args.skill, project_root, roots) report_owed_setup(skill_dir.resolve(), project_root.resolve(), roots) - entry = render(project_root, skill_dir, overrides=args.overrides, assignments=args.assignments) + entry = render( + project_root, skill_dir, overrides=args.overrides, assignments=args.assignments, skill_roots=roots + ) # Printed, not named: a file the model is told to read may be read only in part. workflow = entry.read_text(encoding="utf-8") except (ConfigError, RenderError, OSError, UnicodeError, ValueError) as error: diff --git a/skills/core-tools/bmad/scripts/resolve_config.py b/skills/core-tools/bmad/scripts/resolve_config.py index 46dd46f30a..a0efcda0f0 100644 --- a/skills/core-tools/bmad/scripts/resolve_config.py +++ b/skills/core-tools/bmad/scripts/resolve_config.py @@ -21,6 +21,7 @@ ConfigError, apply_worktree_path_fallbacks, central_config_layers, + check_central_config, find_project_root, merge_layers, resolve_artifact_destinations, @@ -92,6 +93,13 @@ def main() -> int: default=None, help="Project root containing _bmad/ (auto-discovered from cwd or linked worktree when omitted)", ) + parser.add_argument( + "--root", + type=Path, + action="append", + default=[], + help="Active skills root holding installed module defaults (`[bmod.defaults]`), repeatable, first wins.", + ) parser.add_argument( "--key", "-k", @@ -173,8 +181,22 @@ def main() -> int: action="store_true", help='Include entries with mode = "disabled" when using --resolve-sources or --resolve-destinations.', ) + parser.add_argument( + "--check", + action="store_true", + help="Validate _bmad/custom/config*.toml keys and structured blocks against core schema and installed module manifests.", + ) args = parser.parse_args() + if args.check and ( + args.key + or args.resolve_models + or args.resolve_capabilities + or args.resolve_sources + or args.resolve_destinations + ): + parser.error("--check cannot be combined with query or resolver flags") + if args.tier and not args.resolve_models: parser.error("--tier requires --resolve-models") if (args.scope or args.no_general or args.legacy_external_sources is not None) and not args.resolve_sources: @@ -197,7 +219,12 @@ def main() -> int: "error: project root not found; pass --project-root pointing to the folder containing _bmad/\n" ) return 1 - layers = central_config_layers(project_root, require_project=True) + skill_roots = tuple(root.resolve() for root in args.root) or None + if args.check: + report = check_central_config((project_root,), skill_roots=skill_roots) + write_json_stdout(report) + return 0 if report["ok"] else 1 + layers = central_config_layers(project_root, require_project=True, skill_roots=skill_roots) merged = merge_layers(layers) resolved_merged = apply_worktree_path_fallbacks(merged, project_root) except (ConfigError, OSError) as error: diff --git a/skills/core-tools/bmad/scripts/resolve_customization.py b/skills/core-tools/bmad/scripts/resolve_customization.py index 6625af4add..6ad306de67 100755 --- a/skills/core-tools/bmad/scripts/resolve_customization.py +++ b/skills/core-tools/bmad/scripts/resolve_customization.py @@ -13,7 +13,14 @@ sys.dont_write_bytecode = True try: - from config_utils import ConfigError, find_project_root, load_customization + from config_utils import ( + ConfigError, + check_customization, + find_project_root, + has_matching_custom_rule, + load_customization, + worktree_fallback_custom_file_path, + ) except ModuleNotFoundError as error: if error.name != "tomllib": raise @@ -61,9 +68,13 @@ def candidate_project_roots(skill_dir: Path) -> list[Path]: def has_override(root: Path, skill_name: str) -> bool: custom_dir = root / "_bmad" / "custom" try: - return any((custom_dir / name).is_file() for name in (f"{skill_name}.toml", f"{skill_name}.user.toml")) + if any((custom_dir / name).is_file() for name in (f"{skill_name}.toml", f"{skill_name}.user.toml")): + return True except OSError: return False + if worktree_fallback_custom_file_path(root, f"{skill_name}.user.toml") is not None: + return True + return has_matching_custom_rule(custom_dir, skill_name, project_root=root) def warn_on_masked_override(chosen: Path, rejected: list[Path], skill_name: str) -> None: @@ -120,8 +131,16 @@ def main() -> int: help="A skills root the host has active, in precedence order, project roots first (repeatable). " "Without it, the setup preflight makes no claim about other skills or the module record.", ) + parser.add_argument( + "--check", + action="store_true", + help="Validate overrides and matching cross-skill rules against shipped customize.toml schema and local file: refs.", + ) args = parser.parse_args() + if args.check and args.key: + parser.error("--check cannot be combined with --key") + try: skill_dir = Path(args.skill).resolve() if args.project_root: @@ -131,6 +150,10 @@ def main() -> int: project_root = candidates[0] if candidates else None if project_root is not None: warn_on_masked_override(project_root, candidates[1:], skill_dir.name) + if args.check: + report = check_customization((project_root,) if project_root is not None else (), skill_dir) + write_json_stdout(report) + return 0 if report["ok"] else 1 merged = load_customization(project_root, skill_dir) except (ConfigError, OSError) as error: sys.stderr.write(f"error: {error}\n") diff --git a/skills/core-tools/bmod-core-tools/help/team-adoption.md b/skills/core-tools/bmod-core-tools/help/team-adoption.md index 114cfd621f..e282c2cb26 100644 --- a/skills/core-tools/bmod-core-tools/help/team-adoption.md +++ b/skills/core-tools/bmod-core-tools/help/team-adoption.md @@ -1,30 +1,32 @@ --- title: "Team Adoption and Shared Rules" -when: "Team _bmad/custom/, AGENTS.md, hooks, .user.toml" -tags: [team, adoption, customization, config, baseline, overrides, user-toml] +when: "Team _bmad/custom/, rules.toml, AGENTS.md, hooks, .user.toml" +tags: [team, adoption, customization, config, rules, baseline, overrides, user-toml] related: [bmad-customize/customization, bmad-facilitate/facilitate] --- # Team Adoption and Shared Rules -Teams enforce shared conventions through committed overrides under `{project-root}/_bmad/custom/` and short repo rules in `AGENTS.md`, while individuals keep experiments in gitignored `.user.toml` files. +Teams share conventions through committed files under `{project-root}/_bmad/custom/` and short rules in `AGENTS.md`, while individuals keep personal preferences in gitignored `*.user.toml` files. ## Choose the file by scope | Scope | Where it goes | Committed | |---|---|---| | Every session, even outside BMad skills | `{project-root}/AGENTS.md` (keep short and verified) | Yes | -| Shared central paths or setup answers | `_bmad/config.toml` or `_bmad/custom/config.toml` | Yes | +| Central defaults or module settings | `_bmad/config.toml` (`bmad`) or `_bmad/custom/config.toml` (`bmad-customize`) | Yes | +| Cross-skill shared rules by glob | `_bmad/custom/rules.toml` via `bmad-customize` | Yes | | Every workflow one agent runs | `_bmad/custom/.toml` via `bmad-customize` | Yes | | One workflow skill | `_bmad/custom/.toml` via `bmad-customize` | Yes | -| Personal overrides / experiments | `_bmad/custom/.user.toml` | No | +| Personal rules, overrides, or central settings | `_bmad/custom/rules.user.toml`, `.user.toml`, or `config.user.toml` | No | | Shared document templates / extensions | `_bmad/custom/facilitate-templates/` or `_bmad/custom/ingest-templates/` | Yes | -| Team knowledge & external sources | `_bmad/custom/knowledge/*.md` or `[[knowledge.sources]]` in `_bmad/custom/config.toml` (personal pointers in gitignored `config.user.toml`) | Yes (`config.user.toml`: No) | +| Team knowledge & external sources | `_bmad/custom/knowledge/*.md` or `[core.knowledge_sources.]` in `_bmad/custom/config.toml` | Yes (`config.user.toml`: No) | ## What teams configure most often -- **Standing facts (`persistent_facts`):** Short rules or pointers to existing standards docs (prefer linking a living standards doc over copying it). -- **Required tools & MCPs:** Name exact tools and when to call them. -- **Completion hooks (`on_complete`):** Post-run actions (e.g., publishing to a wiki or tracker); ask before any team-visible write. +- **Shared rules (`rules.toml`):** Apply `persistent_facts`, `activation_steps_prepend`, or `on_complete` across matching `bmad-*` skills in one file without duplicating overrides. +- **Standing facts (`persistent_facts`):** Short rules or `file:` pointers to living team docs. +- **Required tools & MCPs:** Name exact tools and when to consult them, or register `[core.knowledge_sources.]` / `[core.artifact_destinations.]`. +- **Completion hooks (`on_complete`):** Post-run actions such as publishing after explicit confirmation. - **Templates & extensions:** Extend shipped templates with `extends: ` in `_bmad/custom/facilitate-templates/` so upstream updates still arrive. -- **Weekly baseline promotion:** Let engineers experiment in `.user.toml` files and review weekly to promote proven rules into committed `_bmad/custom/.toml` files. +- **Weekly baseline promotion:** Experiment in `.user.toml` files and promote proven rules into committed team `.toml` files. diff --git a/tests/core-tools/bmad/test_setup_lifecycle.py b/tests/core-tools/bmad/test_setup_lifecycle.py index d1e3943281..cb1c603d1f 100644 --- a/tests/core-tools/bmad/test_setup_lifecycle.py +++ b/tests/core-tools/bmad/test_setup_lifecycle.py @@ -40,7 +40,15 @@ def setUp(self): def test_reserved_custom_files_shared_and_preserved_by_migrate_v6(self): self.assertEqual( config_utils.RESERVED_CUSTOM_FILES, - frozenset({"config.toml", "config.user.toml", "bmad-state.user.toml"}), + frozenset( + { + "config.toml", + "config.user.toml", + "rules.toml", + "rules.user.toml", + "bmad-state.user.toml", + } + ), ) self.assertEqual(setup.RESERVED_CUSTOM_FILES, config_utils.RESERVED_CUSTOM_FILES) self.assertEqual(migrate_v6.RESERVED_CUSTOM_FILES, config_utils.RESERVED_CUSTOM_FILES) @@ -63,6 +71,16 @@ def test_reserved_custom_files_shared_and_preserved_by_migrate_v6(self): custom = project / "_bmad" / "custom" state_file = custom / "bmad-state.user.toml" state_file.write_text("first_run_offered = true\n", encoding="utf-8") + rules_file = custom / "rules.toml" + rules_file.write_text( + '[[rules]]\nid = "team"\nmatch = "bmad-*"\n\n[rules.workflow]\npersistent_facts = ["Check docs"]\n', + encoding="utf-8", + ) + rules_user_file = custom / "rules.user.toml" + rules_user_file.write_text( + '[[rules]]\nid = "personal"\nmatch = "bmad-*"\n\n[rules.workflow]\npersistent_facts = ["Check docs"]\n', + encoding="utf-8", + ) stray_file = custom / "bmad-nonexistent.toml" stray_file.write_text('[workflow]\na = "b"\n', encoding="utf-8") @@ -70,10 +88,14 @@ def test_reserved_custom_files_shared_and_preserved_by_migrate_v6(self): retirement = setup.retirement_report(project, bmad_skill, installation, ()) unused = migrate_v6.unused_customizations(project, installation, retirement) self.assertNotIn("bmad-state.user.toml", unused) + self.assertNotIn("rules.toml", unused) + self.assertNotIn("rules.user.toml", unused) self.assertIn("bmad-nonexistent.toml", unused) cleaned = migrate_v6.clean(project, bmad_skill, roots=(skills,)) self.assertTrue(state_file.is_file()) + self.assertTrue(rules_file.is_file()) + self.assertTrue(rules_user_file.is_file()) self.assertFalse(stray_file.exists()) self.assertEqual(cleaned["removed_customizations"], ["_bmad/custom/bmad-nonexistent.toml"]) self.assertEqual(list_customizable.RESERVED_CUSTOM_FILES, config_utils.RESERVED_CUSTOM_FILES) diff --git a/tests/core-tools/bmad/test_story04_phase2.py b/tests/core-tools/bmad/test_story04_phase2.py new file mode 100644 index 0000000000..c6d1986edf --- /dev/null +++ b/tests/core-tools/bmad/test_story04_phase2.py @@ -0,0 +1,871 @@ +"""Deterministic tests for Story 4 Phase 2: `[bmod.defaults]`, `_bmad/custom/rules*.toml`, and unified customization tools.""" + +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parents[3] +BMAD_SCRIPTS = REPO_ROOT / "skills" / "core-tools" / "bmad" / "scripts" +CUSTOMIZE_SCRIPT = REPO_ROOT / "skills" / "core-tools" / "bmad-customize" / "scripts" / "list_customizable_skills.py" +SCAN_READS_SCRIPT = REPO_ROOT / "skills" / "toolsmith" / "bmad-toolsmith" / "scripts" / "scan_config_reads.py" + +if str(BMAD_SCRIPTS) not in sys.path: + sys.path.insert(0, str(BMAD_SCRIPTS)) + +import bmod_utils # noqa: E402 +import config_utils # noqa: E402 +import migrate_v6 # noqa: E402 +import render_skill # noqa: E402 +import setup as bmad_setup # noqa: E402 +import setup_check # noqa: E402 +import validate_manifests # noqa: E402 + + +def _load_module(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +list_customizable_skills = _load_module("list_customizable_skills_phase2", CUSTOMIZE_SCRIPT) + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def _run( + script: Path, args: list[str], *, cwd: Path, env: dict[str, str] | None = None +) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(script), *args], + cwd=str(cwd), + env=env, + text=True, + capture_output=True, + check=False, + ) + + +def _isolated_home_env(home_dir: Path) -> dict[str, str]: + env = dict(os.environ) + env["HOME"] = str(home_dir) + env["USERPROFILE"] = str(home_dir) + return env + + +_GIT_ENV_STRIP = ( + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_PREFIX", + "GIT_SUPER_PREFIX", +) + + +def _git(cwd: Path, *args: str) -> str: + env = dict(os.environ) + for var in _GIT_ENV_STRIP: + env.pop(var, None) + env["GIT_CONFIG_NOSYSTEM"] = "1" + env["GIT_CONFIG_GLOBAL"] = os.devnull + res = subprocess.run( + ["git", *args], + cwd=str(cwd), + env=env, + text=True, + capture_output=True, + check=False, + ) + if res.returncode != 0: + raise AssertionError(f"git {' '.join(args)} failed: {res.stderr or res.stdout}") + return res.stdout.strip() + + +class ModuleDefaultsTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + self.empty_home = self.root / "empty-home" + patcher = mock.patch("pathlib.Path.home", return_value=self.empty_home) + patcher.start() + self.addCleanup(patcher.stop) + + def test_bmod_defaults_validation_and_question_collision_rejection(self): + path = self.root / "bmod-acme" / "bmod.toml" + _write( + path, + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + "[bmod.defaults]\ntimeout_seconds = 30\n[bmod.defaults.thresholds]\nmax_retries = 2\n", + ) + parsed = bmod_utils.read_bmod_file(path) + self.assertIsNotNone(parsed) + assert parsed is not None and parsed.bmod is not None + self.assertEqual(parsed.bmod.defaults, {"timeout_seconds": 30, "thresholds": {"max_retries": 2}}) + + # Collision with config_questions fails loudly. + _write( + path, + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "thresholds.mode"\nprompt = "Mode?"\ndefault = "fast"\n' + '[bmod.defaults.thresholds]\nmode = "slow"\n', + ) + with self.assertRaisesRegex(Exception, "conflicts with config question"): + bmod_utils.read_bmod_file(path) + + # Nesting own module code fails loudly. + _write( + path, + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + "[bmod.defaults.acme]\nfoo = 1\n", + ) + with self.assertRaisesRegex(Exception, "must not nest module 'acme'"): + bmod_utils.read_bmod_file(path) + + def test_validate_manifests_and_scan_config_reads_accept_bmod_defaults(self): + repo = self.root / "repo" + src = "github:acme/mods/skills" + _write( + repo / "skills" / "bmod-acme" / "bmod.toml", + f'[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "{src}"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "asked_key"\nprompt = "Asked?"\ndefault = "yes"\n' + '[bmod.defaults]\ndefault_depth = "deep"\n[bmod.defaults.limits]\nmax_items = 5\n', + ) + _write( + repo / "skills" / "bmod-acme" / "SKILL.md", + "---\nname: bmod-acme\ndescription: 'Acme. Use when testing.'\n---\n", + ) + _write(repo / "skills" / "bmod-acme" / "help" / "help.md", "# Help\n\nAcme help.\n") + _write( + repo / "skills" / "acme-run" / "bmod.toml", + f'[skill]\nbmod = "bmod-acme"\nsource = "{src}"\n', + ) + _write( + repo / "skills" / "acme-run" / "SKILL.md", + "---\nname: acme-run\ndescription: 'Run. Use when testing.'\n---\n\n" + 'Run `uv run "{project-root}/_bmad/scripts/resolve_config.py" --key modules.acme.asked_key ' + "--key modules.acme.default_depth --key modules.acme.limits`.\n", + ) + report = validate_manifests.check_repo(repo) + self.assertEqual(report.problems, ()) + + scan_res = _run(SCAN_READS_SCRIPT, [str(repo / "skills")], cwd=repo) + self.assertEqual(scan_res.returncode, 0, scan_res.stderr) + scan_data = json.loads(scan_res.stdout) + self.assertEqual(scan_data["unasked"], []) + self.assertEqual(scan_data["unread"], []) + self.assertEqual(scan_data["records"][0]["defaults"], ["default_depth", "limits.max_items"]) + + def test_four_layer_precedence_and_non_materialization_in_setup(self): + project = self.root / "project" + skills = project / ".agents" / "skills" + src = f"file:{(self.root / 'src').as_posix()}" + _write( + skills / "bmod-core-tools" / "bmod.toml", + '[bmod]\ncode = "core-tools"\nversion = "7.0.1-next"\nupdate_source = "plugin:local"\n' + 'skills = ["bmad"]\npre_install_message = ""\npost_install_message = ""\n', + ) + _write( + skills / "bmod-core-tools" / "SKILL.md", + "---\nname: bmod-core-tools\ndescription: 'Core. Use when testing.'\n---\n", + ) + shutil_files = list(BMAD_SCRIPTS.parent.rglob("*")) + for src_path in shutil_files: + if src_path.is_file() and "__pycache__" not in src_path.parts: + rel = src_path.relative_to(BMAD_SCRIPTS.parent) + dst = skills / "bmad" / rel + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_bytes(src_path.read_bytes()) + + _write( + skills / "bmod-tea" / "bmod.toml", + f'[bmod]\ncode = "tea"\nversion = "1.0.0"\nupdate_source = {json.dumps(src, ensure_ascii=False)}\n' + 'skills = ["tea-check"]\nrequired_skills = ["bmad"]\n' + 'pre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\na = "shipped"\nb = "shipped"\nc = "shipped"\nd = "shipped"\n' + '[bmod.defaults.nested]\nkeep = true\noverride = "shipped"\n', + ) + _write( + skills / "bmod-tea" / "SKILL.md", + "---\nname: bmod-tea\ndescription: 'Tea. Use when testing.'\n---\n", + ) + _write( + skills / "tea-check" / "bmod.toml", + f'[skill]\nbmod = "bmod-tea"\nsource = {json.dumps(src, ensure_ascii=False)}\n', + ) + _write( + skills / "tea-check" / "SKILL.md", + "---\nname: tea-check\ndescription: 'Check. Use when testing.'\n---\n", + ) + _write( + skills / "tea-check" / "workflow.md", + "A={{ config.modules.tea.a }}|B={{ config.modules.tea.b }}|C={{ config.modules.tea.c }}|D={{ config.modules.tea.d }}\n", + ) + + # Run setup: must NOT materialize [bmod.defaults] into _bmad/config.toml and must report 0 pending questions. + setup_res = bmad_setup.setup(project, skills / "bmad", roots=(skills,)) + self.assertEqual(setup_res["pending_questions"], []) + raw_team_cfg = (project / "_bmad" / "config.toml").read_text(encoding="utf-8") + self.assertNotIn("modules.tea", raw_team_cfg) + self.assertEqual(setup_check.owed(skills / "tea-check", project, (skills,)), []) + + # Layer overrides across all 4 tiers. + _write( + project / "_bmad" / "config.toml", + raw_team_cfg + '\n[modules.tea]\nb = "config"\nc = "config"\nd = "config"\n', + ) + _write( + project / "_bmad" / "custom" / "config.toml", + '[modules.tea]\nc = "custom-team"\nd = "custom-team"\n[modules.tea.nested]\noverride = "team"\n', + ) + _write( + project / "_bmad" / "custom" / "config.user.toml", + '[modules.tea]\nd = "custom-user"\n', + ) + + merged = config_utils.load_central_config(project) + self.assertEqual( + merged["modules"]["tea"], + { + "a": "shipped", + "b": "config", + "c": "custom-team", + "d": "custom-user", + "nested": {"keep": True, "override": "team"}, + }, + ) + + cli_cfg = _run(BMAD_SCRIPTS / "resolve_config.py", ["--key", "modules.tea"], cwd=project) + self.assertEqual(cli_cfg.returncode, 0, cli_cfg.stderr) + self.assertEqual(json.loads(cli_cfg.stdout)["modules.tea"]["a"], "shipped") + self.assertEqual(json.loads(cli_cfg.stdout)["modules.tea"]["d"], "custom-user") + + rendered_path = render_skill.render(project, skills / "tea-check") + self.assertEqual( + rendered_path.read_text(encoding="utf-8").strip(), "A=shipped|B=config|C=custom-team|D=custom-user" + ) + + +class CrossSkillRulesAndCustomizeTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + self.empty_home = self.root / "empty-home" + patcher = mock.patch("pathlib.Path.home", return_value=self.empty_home) + patcher.start() + self.addCleanup(patcher.stop) + + def _stage_skill(self, parent: Path, name: str, customize_toml: str) -> Path: + skill_dir = parent / name + _write(skill_dir / "customize.toml", customize_toml) + _write( + skill_dir / "SKILL.md", + f"---\nname: {name}\ndescription: 'Skill {name}. Use when testing.'\n---\n\nBody.\n", + ) + return skill_dir + + def test_rules_matching_filtering_open_tables_and_five_layer_precedence(self): + project = self.root / "proj" + ws = self.root / "ws" + skills = project / ".agents" / "skills" + _write( + project / "_bmad" / "config.toml", + '[core]\nproject_name = "p"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write( + ws / "_bmad" / "config.toml", '[core]\nproject_name = "w"\noutput_folder = "{project-root}/_bmad-output"\n' + ) + _write(project / "docs" / "team.md", "team standard\n") + + eval_skill = self._stage_skill( + skills, + "bmad-eval", + '[workflow]\npersistent_facts = ["shipped"]\non_complete = ""\nreports_folder = "{skill-path}/.eval-results"\n' + "[workflow.harnesses]\n", + ) + agent_skill = self._stage_skill( + skills, + "bmad-agent-sample", + '[agent]\nname = "Sample"\nrole = "base"\npersistent_facts = ["shipped-agent"]\n', + ) + + _write( + project / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "all-facts"\nmatch = "bmad-*"\n[rules.workflow]\npersistent_facts = ["team-rule", "file:docs/team.md"]\n' + 'nonexistent_field = "silently-ignored"\n' + '[rules.workflow.harnesses.codex]\ncommand = ["codex", "{prompt}"]\n' + '[rules.agent]\npersistent_facts = ["agent-team-rule"]\n' + '[[rules]]\nmatch = ["bmad-eval"]\nsurface = "workflow"\n[rules.workflow]\non_complete = "rule-complete"\n', + ) + _write( + project / "_bmad" / "custom" / "bmad-eval.toml", + '[workflow]\npersistent_facts = ["team-skill"]\non_complete = "skill-complete"\n', + ) + _write( + project / "_bmad" / "custom" / "rules.user.toml", + '[[rules]]\nmatch = "bmad-eval"\n[rules.workflow]\npersistent_facts = ["user-rule"]\n', + ) + _write( + project / "_bmad" / "custom" / "bmad-eval.user.toml", + '[workflow]\npersistent_facts = ["user-skill"]\n', + ) + + merged_eval = config_utils.load_customization(project, eval_skill) + self.assertEqual( + merged_eval["workflow"]["persistent_facts"], + ["shipped", "team-rule", "file:docs/team.md", "team-skill", "user-rule", "user-skill"], + ) + self.assertEqual(merged_eval["workflow"]["on_complete"], "skill-complete") + self.assertEqual(merged_eval["workflow"]["harnesses"], {"codex": {"command": ["codex", "{prompt}"]}}) + self.assertNotIn("nonexistent_field", merged_eval["workflow"]) + + merged_agent = config_utils.load_customization(project, agent_skill) + self.assertEqual(merged_agent["agent"]["persistent_facts"], ["shipped-agent", "agent-team-rule"]) + self.assertNotIn("workflow", merged_agent) + + # Ordered multi-root stacking: ws team rule < ws team skill < repo team rule < repo team skill < ws user < repo user. + _write( + ws / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nmatch = "bmad-eval"\n[rules.workflow]\npersistent_facts = ["ws-team-rule"]\n', + ) + _write(ws / "_bmad" / "custom" / "bmad-eval.toml", '[workflow]\npersistent_facts = ["ws-team-skill"]\n') + _write( + ws / "_bmad" / "custom" / "rules.user.toml", + '[[rules]]\nmatch = "bmad-eval"\n[rules.workflow]\npersistent_facts = ["ws-user-rule"]\n', + ) + _write(ws / "_bmad" / "custom" / "bmad-eval.user.toml", '[workflow]\npersistent_facts = ["ws-user-skill"]\n') + + stacked = config_utils.load_customization_for_roots([ws, project], eval_skill) + self.assertEqual( + stacked["workflow"]["persistent_facts"], + [ + "shipped", + "ws-team-rule", + "ws-team-skill", + "team-rule", + "file:docs/team.md", + "team-skill", + "ws-user-rule", + "ws-user-skill", + "user-rule", + "user-skill", + ], + ) + + def test_rules_validation_and_rendered_skill_integration(self): + project = self.root / "proj-render" + skills = project / ".agents" / "skills" + _write( + project / "_bmad" / "config.toml", + '[core]\nproject_name = "pr"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + skill_dir = self._stage_skill( + skills, + "bmad-demo", + '[workflow]\npersistent_facts = ["base"]\n[workflow.harnesses]\n', + ) + _write( + skill_dir / "workflow.md", + "FACTS={{ workflow.persistent_facts | join(',') }}\n", + ) + _write( + project / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nmatch = "bmad-*"\n[rules.workflow]\npersistent_facts = ["shared"]\n', + ) + _write( + project / "_bmad" / "custom" / "bmad-demo.toml", + '[workflow.harnesses.custom]\ncommand = ["echo", "{prompt}"]\n', + ) + out = render_skill.render(project, skill_dir).read_text(encoding="utf-8") + self.assertEqual(out.strip(), "FACTS=base,shared") + + # Incompatible field types in a rule skip safely and surface a warning via check_customization. + _write( + project / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nmatch = "bmad-*"\n[rules.workflow]\npersistent_facts = "not-a-list"\n', + ) + merged_after_mismatch = config_utils.load_customization(project, skill_dir) + self.assertEqual(merged_after_mismatch["workflow"]["persistent_facts"], ["base"]) + mismatch_chk = config_utils.check_customization((project,), skill_dir) + self.assertTrue(mismatch_chk["ok"]) + self.assertEqual([w["kind"] for w in mismatch_chk["warnings"]], ["rule-type-mismatch"]) + + def test_resolve_customization_check_and_reserved_custom_files(self): + self.assertIn("rules.toml", config_utils.RESERVED_CUSTOM_FILES) + self.assertIn("rules.user.toml", config_utils.RESERVED_CUSTOM_FILES) + self.assertEqual(config_utils.RESERVED_CUSTOM_FILES, bmad_setup.RESERVED_CUSTOM_FILES) + self.assertEqual(config_utils.RESERVED_CUSTOM_FILES, migrate_v6.RESERVED_CUSTOM_FILES) + self.assertEqual(config_utils.RESERVED_CUSTOM_FILES, list_customizable_skills.RESERVED_CUSTOM_FILES) + + project = self.root / "check-proj" + skills = project / ".agents" / "skills" + _write( + project / "_bmad" / "config.toml", + '[core]\nproject_name = "c"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write(project / "docs" / "real.md", "ok\n") + skill_dir = self._stage_skill( + skills, + "bmad-sample", + '[workflow]\npersistent_facts = ["base"]\non_complete = ""\n[workflow.harnesses]\n', + ) + _write( + project / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "r1"\nmatch = "bmad-*"\n[rules.workflow]\n' + 'persistent_facts = ["file:docs/real.md", "file:{output_folder}/skip.md", "file:docs/*.md"]\n' + 'other_skill_only = "ignored-with-warning"\n', + ) + _write( + project / "_bmad" / "custom" / "bmad-sample.toml", + '[workflow]\npersistent_facts = ["ok"]\n[workflow.harnesses.local]\ncommand = ["echo"]\n', + ) + + # Warnings only -> exit 0, ok=True. + ok_res = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_dir), "--project-root", str(project), "--check"], + cwd=project, + ) + self.assertEqual(ok_res.returncode, 0, ok_res.stderr) + ok_data = json.loads(ok_res.stdout) + self.assertTrue(ok_data["ok"]) + self.assertEqual(ok_data["errors"], []) + self.assertEqual(len(ok_data["warnings"]), 1) + + # Per-skill typo and broken concrete file: ref -> exit 1 with structured errors. + _write( + project / "_bmad" / "custom" / "bmad-sample.toml", + '[workflow]\non_compelte = "typo"\npersistent_facts = ["file:docs/missing.md"]\n', + ) + bad_res = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_dir), "--project-root", str(project), "--check"], + cwd=project, + ) + self.assertEqual(bad_res.returncode, 1) + bad_data = json.loads(bad_res.stdout) + self.assertFalse(bad_data["ok"]) + kinds = {err["kind"] for err in bad_data["errors"]} + self.assertEqual(kinds, {"unknown-key", "missing-file-ref"}) + + # migrate_v6.unused_customizations never flags rules.toml / rules.user.toml as unused. + _write( + project / "_bmad" / "custom" / "rules.user.toml", + '[[rules]]\nmatch = "*"\n[rules.workflow]\npersistent_facts = ["u"]\n', + ) + fake_bmad_skill = skills / "bmad" + _write(fake_bmad_skill / "SKILL.md", "---\nname: bmad\ndescription: 'BMad. Use when testing.'\n---\n") + _write( + skills / "bmod-core-tools" / "bmod.toml", + '[bmod]\ncode = "core-tools"\nversion = "7.0.1-next"\nupdate_source = "plugin:local"\n' + 'skills = ["bmad", "bmad-sample"]\npre_install_message = ""\npost_install_message = ""\n', + ) + _write( + skills / "bmod-core-tools" / "SKILL.md", + "---\nname: bmod-core-tools\ndescription: 'Core. Use when testing.'\n---\n", + ) + _write(skill_dir / "bmod.toml", '[skill]\nbmod = "bmod-core-tools"\nsource = "plugin:local"\n') + _write(fake_bmad_skill / "bmod.toml", '[skill]\nbmod = "bmod-core-tools"\nsource = "plugin:local"\n') + installation = bmad_setup.discover_installation(fake_bmad_skill, (skills,)) + retirement = bmad_setup.retirement_report(project, fake_bmad_skill, installation, ()) + self.assertEqual(migrate_v6.unused_customizations(project, installation, retirement), []) + + def test_list_customizable_skills_surfaces_central_config_rules_and_modules(self): + project = self.root / "cust-list" + skills = project / ".agents" / "skills" + _write( + project / "_bmad" / "config.toml", + '[core]\nproject_name = "c"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write(project / "_bmad" / "custom" / "config.toml", '[core]\noutput_folder = "out"\n') + _write( + project / "_bmad" / "custom" / "rules.user.toml", + '[[rules]]\nmatch = "*"\n[rules.workflow]\npersistent_facts = ["x"]\n', + ) + _write( + skills / "bmod-demo" / "bmod.toml", + '[bmod]\ncode = "demo"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["demo-flow"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "workspace_dir"\nprompt = "Where?"\ndefault = "ws"\n' + '[bmod.defaults]\ndefault_depth = "standard"\n', + ) + self._stage_skill(skills, "demo-flow", "[workflow]\npersistent_facts = []\n") + + res = _run(CUSTOMIZE_SCRIPT, ["--project-root", str(project), "--skills-root", str(skills)], cwd=project) + self.assertEqual(res.returncode, 0, res.stderr) + data = json.loads(res.stdout) + self.assertTrue(data["central_config"]["has_setup_config"]) + self.assertTrue(data["central_config"]["has_team_override"]) + self.assertFalse(data["central_config"]["has_user_override"]) + self.assertEqual(data["central_config"]["setup_owned_files"], ["_bmad/config.toml"]) + self.assertFalse(data["rules"]["has_team_rules"]) + self.assertTrue(data["rules"]["has_user_rules"]) + self.assertEqual(len(data["modules"]), 1) + self.assertEqual(data["modules"][0]["code"], "demo") + self.assertEqual(data["modules"][0]["defaults"], {"default_depth": "standard"}) + self.assertEqual(data["modules"][0]["question_keys"], ["workspace_dir"]) + + def test_heterogeneous_cross_skill_rule_skips_incompatible_types_and_warns_in_check(self): + project = self.root / "hetero" + skills = project / ".agents" / "skills" + _write( + project / "_bmad" / "config.toml", + '[core]\nproject_name = "h"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + skill_str = self._stage_skill( + skills, + "bmad-str-skill", + '[workflow]\non_complete = ""\npersistent_facts = ["str-base"]\n', + ) + skill_list = self._stage_skill( + skills, + "bmad-list-skill", + '[workflow]\non_complete = []\npersistent_facts = ["list-base"]\n', + ) + _write( + project / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "shared-finish"\nmatch = "bmad-*"\n\n[rules.workflow]\n' + 'on_complete = "Publish summary"\npersistent_facts = ["shared-fact"]\n', + ) + + # String-typed skill receives both fields; list-typed skill skips incompatible `on_complete` cleanly. + merged_str = config_utils.load_customization(project, skill_str) + self.assertEqual(merged_str["workflow"]["on_complete"], "Publish summary") + self.assertEqual(merged_str["workflow"]["persistent_facts"], ["str-base", "shared-fact"]) + + merged_list = config_utils.load_customization(project, skill_list) + self.assertEqual(merged_list["workflow"]["on_complete"], []) + self.assertEqual(merged_list["workflow"]["persistent_facts"], ["list-base", "shared-fact"]) + + cli_list = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_list), "--project-root", str(project)], + cwd=project, + ) + self.assertEqual(cli_list.returncode, 0, cli_list.stderr) + + chk = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_list), "--project-root", str(project), "--check"], + cwd=project, + ) + self.assertEqual(chk.returncode, 0, chk.stderr) + report = json.loads(chk.stdout) + self.assertTrue(report["ok"]) + self.assertEqual(report["errors"], []) + self.assertEqual([w["kind"] for w in report["warnings"]], ["rule-type-mismatch"]) + + def test_home_installed_module_defaults_resolved_without_explicit_root_and_degrades_on_unresolvable_home(self): + project = self.root / "home-proj" + _write( + project / "_bmad" / "config.toml", + '[core]\nproject_name = "hp"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + fake_home = self.root / "fake-home" + _write( + fake_home / ".agents" / "skills" / "bmod-acme" / "bmod.toml", + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\ndepth = "deep"\nregion = "us"\n', + ) + + # Home-installed module default resolves with no --root flag. + res_home = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(project), "--key", "modules.acme"], + cwd=project, + env=_isolated_home_env(fake_home), + ) + self.assertEqual(res_home.returncode, 0, res_home.stderr) + self.assertEqual(json.loads(res_home.stdout)["modules.acme"], {"depth": "deep", "region": "us"}) + + # Project-local install takes precedence over home install. + _write( + project / ".claude" / "skills" / "bmod-acme" / "bmod.toml", + '[bmod]\ncode = "acme"\nversion = "1.1.0"\nupdate_source = "plugin:local"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\ndepth = "project-shallow"\n', + ) + res_proj = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(project), "--key", "modules.acme.depth"], + cwd=project, + env=_isolated_home_env(fake_home), + ) + self.assertEqual(res_proj.returncode, 0, res_proj.stderr) + self.assertEqual(json.loads(res_proj.stdout)["modules.acme.depth"], "project-shallow") + + # Unresolvable Path.home degrades without error. + with mock.patch("pathlib.Path.home", side_effect=RuntimeError("no home")): + layers = config_utils.central_config_layers(project) + self.assertEqual(config_utils.merge_layers(layers)["modules"]["acme"]["depth"], "project-shallow") + + def test_linked_worktree_fallback_for_rules_user_and_skill_user(self): + main_repo = self.root / "wt-main" + wt = self.root / "wt-linked" + skills = main_repo / ".agents" / "skills" + self._stage_skill( + skills, + "bmad-wt-skill", + '[workflow]\npersistent_facts = ["shipped"]\non_complete = "shipped"\n', + ) + _write( + main_repo / ".gitignore", + "_bmad/custom/*.user.toml\n", + ) + _write( + main_repo / "_bmad" / "config.toml", + '[core]\nproject_name = "wt"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write( + main_repo / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "team-rule"\nmatch = "bmad-*"\n[rules.workflow]\npersistent_facts = ["team-rule"]\n', + ) + _git(main_repo, "init", "-b", "main") + _git(main_repo, "config", "user.email", "test@example.com") + _git(main_repo, "config", "user.name", "Test User") + _git(main_repo, "add", "-A") + _git(main_repo, "commit", "--no-verify", "-m", "init") + _git(main_repo, "worktree", "add", "-b", "feature", str(wt)) + + # Gitignored personal files live only in main checkout. + _write( + main_repo / "_bmad" / "custom" / "rules.user.toml", + '[[rules]]\nid = "personal-rule"\nmatch = "bmad-*"\n' + '[rules.workflow]\npersistent_facts = ["main-user-rule"]\non_complete = "main-user-rule"\n', + ) + _write( + main_repo / "_bmad" / "custom" / "bmad-wt-skill.user.toml", + '[workflow]\npersistent_facts = ["main-user-skill"]\n', + ) + + # Fresh linked worktree inherits both read-only without copying into wt. + wt_skill = wt / ".agents" / "skills" / "bmad-wt-skill" + wt_merged = config_utils.load_customization(wt, wt_skill) + self.assertEqual( + wt_merged["workflow"]["persistent_facts"], + ["shipped", "team-rule", "main-user-rule", "main-user-skill"], + ) + self.assertEqual(wt_merged["workflow"]["on_complete"], "main-user-rule") + self.assertFalse((wt / "_bmad" / "custom" / "rules.user.toml").exists()) + self.assertFalse((wt / "_bmad" / "custom" / "bmad-wt-skill.user.toml").exists()) + + chk_res = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(wt_skill), "--project-root", str(wt), "--check"], + cwd=wt, + ) + self.assertEqual(chk_res.returncode, 0, chk_res.stderr) + chk_data = json.loads(chk_res.stdout) + self.assertTrue(chk_data["ok"]) + self.assertTrue(any("rules.user.toml" in p for p in chk_data["checked_files"])) + self.assertTrue(any("bmad-wt-skill.user.toml" in p for p in chk_data["checked_files"])) + + # Creating worktree-local rules.user.toml shadows main checkout rules.user.toml cleanly. + _write( + wt / "_bmad" / "custom" / "rules.user.toml", + '[[rules]]\nid = "wt-rule"\nmatch = "bmad-*"\n[rules.workflow]\non_complete = "wt-local"\n', + ) + wt_shadowed = config_utils.load_customization(wt, wt_skill) + self.assertEqual(wt_shadowed["workflow"]["on_complete"], "wt-local") + self.assertNotIn("main-user-rule", wt_shadowed["workflow"]["persistent_facts"]) + self.assertIn("main-user-skill", wt_shadowed["workflow"]["persistent_facts"]) + + def test_resolve_config_check_validates_central_overrides_and_open_default_tables(self): + project = self.root / "central-check" + skills = project / ".agents" / "skills" + _write( + skills / "bmod-acme" / "bmod.toml", + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "workspace_dir"\nprompt = "Dir?"\ndefault = "ws"\n' + '[bmod.defaults]\ndepth = "deep"\n[bmod.defaults.hooks]\n', + ) + setup_text = '[core]\nproject_name = "cc"\noutput_folder = "{project-root}/_bmad-output"\n' + _write(project / "_bmad" / "config.toml", setup_text) + _write( + project / "_bmad" / "custom" / "config.toml", + '[core]\noutput_folder = "team-out"\n[modules.acme]\ndepth = "custom"\n' + '[modules.acme.hooks]\npost_run = "echo ok"\n', + ) + _write( + project / "_bmad" / "custom" / "config.user.toml", + '[core]\nactive_initiative = "init-1"\n[modules.acme]\nworkspace_dir = "mine"\n', + ) + + ok_res = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(project), "--check"], + cwd=project, + env=_isolated_home_env(self.empty_home), + ) + self.assertEqual(ok_res.returncode, 0, ok_res.stderr) + ok_data = json.loads(ok_res.stdout) + self.assertTrue(ok_data["ok"]) + self.assertEqual((project / "_bmad" / "config.toml").read_text(encoding="utf-8"), setup_text) + + # --check cannot combine with --key. + combo = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(project), "--check", "--key", "core"], + cwd=project, + ) + self.assertNotEqual(combo.returncode, 0) + + # Typo in [core] and typo in [modules.acme] both fail loudly. + _write(project / "_bmad" / "custom" / "config.toml", '[core]\noutput_foldr = "typo"\n') + _write(project / "_bmad" / "custom" / "config.user.toml", '[modules.acme]\ndpth = "typo"\n') + bad_res = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(project), "--check"], + cwd=project, + env=_isolated_home_env(self.empty_home), + ) + self.assertEqual(bad_res.returncode, 1) + bad_data = json.loads(bad_res.stdout) + self.assertEqual({e["kind"] for e in bad_data["errors"]}, {"unknown-core-key", "unknown-module-key"}) + + # Unknown module and malformed [core.knowledge_sources] fail loudly. + _write(project / "_bmad" / "custom" / "config.toml", "[modules.bogus]\nx = 1\n") + _write( + project / "_bmad" / "custom" / "config.user.toml", + '[core.knowledge_sources.bad]\nkind = "path"\n', + ) + bad_mod = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(project), "--check"], + cwd=project, + env=_isolated_home_env(self.empty_home), + ) + self.assertEqual(bad_mod.returncode, 1) + bad_mod_kinds = {e["kind"] for e in json.loads(bad_mod.stdout)["errors"]} + self.assertEqual(bad_mod_kinds, {"unknown-module", "invalid-core-block"}) + + def test_multi_root_central_config_layer_precedence(self): + outer = self.root / "outer" + inner = self.root / "inner" + _write( + inner / ".agents" / "skills" / "bmod-acme" / "bmod.toml", + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\ndefault_only = "d"\nouter_beats_default = "d"\n', + ) + _write(outer / "_bmad" / "config.toml", '[core]\nshared = "outer-team"\npers_vs_team = "outer-team"\n') + _write(outer / "_bmad" / "custom" / "config.user.toml", '[core]\npers_vs_team = "outer-user"\n') + _write( + inner / "_bmad" / "config.toml", + '[core]\nshared = "inner-team"\npers_vs_team = "inner-team"\n[modules.acme]\nouter_beats_default = "t"\n', + ) + _write(inner / "_bmad" / "custom" / "config.user.toml", '[core]\ninner_user = "iu"\n') + + layers = config_utils.central_config_layers_for_roots((outer, inner)) + merged = config_utils.merge_layers(layers) + # All team layers across roots come before all personal layers across roots. + self.assertEqual(merged["core"]["shared"], "inner-team") + self.assertEqual(merged["core"]["pers_vs_team"], "outer-user") + self.assertEqual(merged["core"]["inner_user"], "iu") + self.assertEqual(merged["modules"]["acme"], {"default_only": "d", "outer_beats_default": "t"}) + + def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scalar_types(self): + # 1. bmod_utils.parse_defaults rejects empty-table prefix collisions. + bmod_path = self.root / "bmod-edge" / "bmod.toml" + _write( + bmod_path, + '[bmod]\ncode = "edge"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["edge-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "thresholds.mode"\nprompt = "Mode?"\ndefault = "fast"\n' + "[bmod.defaults.thresholds]\n", + ) + with self.assertRaisesRegex(Exception, "conflicts with config question"): + bmod_utils.read_bmod_file(bmod_path) + + # 2. scan_config_reads accepts reads under empty {} [bmod.defaults] subtable. + scan_repo = self.root / "scan-open" + _write( + scan_repo / "skills" / "bmod-open" / "bmod.toml", + '[bmod]\ncode = "open"\nversion = "1.0.0"\nupdate_source = "github:acme/mods/skills"\n' + 'skills = ["open-run"]\npre_install_message = ""\npost_install_message = ""\n' + "[bmod.defaults.hooks]\n", + ) + _write( + scan_repo / "skills" / "bmod-open" / "SKILL.md", + "---\nname: bmod-open\ndescription: 'Open. Use when testing.'\n---\n", + ) + _write( + scan_repo / "skills" / "open-run" / "bmod.toml", + '[skill]\nbmod = "bmod-open"\nsource = "github:acme/mods/skills"\n', + ) + _write( + scan_repo / "skills" / "open-run" / "SKILL.md", + "---\nname: open-run\ndescription: 'Run. Use when testing.'\n---\n`modules.open.hooks.pre_step`\n", + ) + scan_res = _run(SCAN_READS_SCRIPT, [str(scan_repo / "skills")], cwd=scan_repo) + self.assertEqual(scan_res.returncode, 0, scan_res.stderr) + self.assertEqual(json.loads(scan_res.stdout)["unasked"], []) + + # 3. Duplicate rule ids, scalar int-vs-str per-skill mismatch, --check --key, no-root warning, malformed defaults. + proj = self.root / "edge-proj" + skills = proj / ".agents" / "skills" + skill_dir = self._stage_skill(skills, "bmad-edge", "[workflow]\nretries = 2\n") + _write( + proj / "_bmad" / "config.toml", + '[core]\nproject_name = "e"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write( + proj / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "dup"\nmatch = "*"\n[rules.workflow]\nretries = 1\n' + '[[rules]]\nid = "dup"\nmatch = "*"\n[rules.workflow]\nretries = 3\n', + ) + _write(proj / "_bmad" / "custom" / "bmad-edge.toml", '[workflow]\nretries = "bad"\n') + + chk = config_utils.check_customization((proj,), skill_dir) + self.assertFalse(chk["ok"]) + self.assertEqual({e["kind"] for e in chk["errors"]}, {"type-mismatch", "invalid-rules"}) + + combo = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_dir), "--project-root", str(proj), "--check", "--key", "workflow"], + cwd=proj, + ) + self.assertNotEqual(combo.returncode, 0) + + no_root = config_utils.check_customization((), skill_dir) + self.assertTrue(no_root["ok"]) + self.assertEqual([w["kind"] for w in no_root["warnings"]], ["no-project-root"]) + + _write( + skills / "bmod-bad" / "bmod.toml", + '[bmod]\ncode = "bad"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["bmad-edge"]\npre_install_message = ""\npost_install_message = ""\n' + 'defaults = "not-a-table"\n', + ) + # Normal central_config_layers skips bad defaults cleanly; check_central_config surfaces the manifest error. + self.assertGreaterEqual(len(config_utils.central_config_layers(proj)), 1) + central_chk = config_utils.check_central_config((proj,)) + self.assertFalse(central_chk["ok"]) + self.assertIn("invalid-module-defaults", {e["kind"] for e in central_chk["errors"]}) + + +if __name__ == "__main__": + unittest.main() From af0d5e406778092e250cb51b10b3c032f418d89e Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 20:29:00 -0600 Subject: [PATCH 2/8] fix(bmad): fix render root precedence, harness checks, and list validation Ensure `render_skill.render()` preserves explicit/project `skill_roots` precedence ahead of `skill_dir.parent`, validate per-harness `core.models.` and `core.capabilities.` tables inside `check_central_config()`, validate list element shapes across cross-skill rules and per-skill overrides, allow populated `[bmod.defaults]` tables with sibling non-colliding `config_questions` keys, and invoke `READ_RE` explicitly in the `scan_config_reads` open-table test. --- .../core-tools/bmad/scripts/config_utils.py | 91 ++++++++++++++++++ .../core-tools/bmad/scripts/render_skill.py | 2 +- tests/core-tools/bmad/test_story04_phase2.py | 95 ++++++++++++++++++- 3 files changed, 184 insertions(+), 4 deletions(-) diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 32059dcbc0..2c1862a2b9 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -52,6 +52,16 @@ class ConfigError(ValueError): "artifact_destinations", } ) +_STRING_LIST_CUSTOM_KEYS = frozenset( + { + "persistent_facts", + "activation_steps_prepend", + "activation_steps_append", + "principles", + "on_complete", + "template_libraries", + } +) _SKIP = object() _FILE_REF_RE = re.compile(r"(?:^|\s)file:([^\s,;'\")]+)") _RULE_ENTRY_FIELDS = frozenset({"id", "match", "surface", "agent", "workflow"}) @@ -789,6 +799,38 @@ def _scalar_types_compatible(schema: Any, value: Any) -> bool: return type(schema) is type(value) +def _validate_list_payload(payload: list[Any], schema: list[Any], *, leaf_key: str) -> str | None: + if leaf_key in _STRING_LIST_CUSTOM_KEYS: + if any(not isinstance(item, str) for item in payload): + return "expected list of str" + return None + if leaf_key == "menu": + if any( + not isinstance(item, dict) or not isinstance(item.get("code"), str) or not item["code"].strip() + for item in payload + ): + return "expected list of menu tables with non-empty string 'code'" + return None + if schema: + if all(isinstance(item, dict) for item in schema): + if any(not isinstance(item, dict) for item in payload): + return "expected list of tables" + try: + _detect_keyed_merge_field(schema + payload) + except ConfigError as error: + return str(error) + elif not isinstance(schema[0], (dict, list)): + sample = schema[0] + if any(not _scalar_types_compatible(sample, item) for item in payload): + return f"expected list of {type(sample).__name__}" + return None + try: + _detect_keyed_merge_field(payload) + except ConfigError as error: + return str(error) + return None + + def _filter_rule_against_schema( payload: Any, schema: Any, @@ -833,6 +875,12 @@ def _filter_rule_against_schema( if mismatched_keys is not None: mismatched_keys.append(f"{path_label} (expected list, got {type(payload).__name__})") return _SKIP + leaf_key = path_label.rsplit(".", 1)[-1] + list_error = _validate_list_payload(payload, schema, leaf_key=leaf_key) + if list_error is not None: + if mismatched_keys is not None: + mismatched_keys.append(f"{path_label} ({list_error})") + return _SKIP return copy.deepcopy(payload) if not _scalar_types_compatible(schema, payload): if mismatched_keys is not None: @@ -1017,6 +1065,17 @@ def _validate_override_against_schema( "message": f"`{prefix}` must be a list, got {type(override).__name__}", } ) + return + list_error = _validate_list_payload(override, schema, leaf_key=prefix.rsplit(".", 1)[-1]) + if list_error is not None: + errors.append( + { + "kind": "type-mismatch", + "file": str(source), + "key": prefix, + "message": f"`{prefix}` invalid list elements: {list_error}", + } + ) return if not _scalar_types_compatible(schema, override): errors.append( @@ -1441,6 +1500,24 @@ def check_central_config( resolve_models(layers) except ConfigError as error: errors.append({"kind": "invalid-core-block", "file": "", "key": "core.models", "message": str(error)}) + model_harnesses: set[str] = set() + for layer in layers: + layer_core = layer.get("core") if isinstance(layer, dict) else None + layer_models = layer_core.get("models") if isinstance(layer_core, dict) else None + if isinstance(layer_models, dict): + model_harnesses.update(str(k) for k in layer_models if k not in MODEL_TIERS and k != "seen_models") + for harness_key in sorted(model_harnesses): + try: + resolve_models(layers, harness=harness_key) + except ConfigError as error: + errors.append( + { + "kind": "invalid-core-block", + "file": "", + "key": f"core.models.{harness_key}", + "message": str(error), + } + ) if "capabilities" in core or "tooling" in core: try: resolve_capabilities(merged) @@ -1448,6 +1525,20 @@ def check_central_config( errors.append( {"kind": "invalid-core-block", "file": "", "key": "core.capabilities", "message": str(error)} ) + raw_caps = core.get("capabilities") + if isinstance(raw_caps, dict): + for harness_key in sorted(str(k) for k in raw_caps if k not in _CAPABILITY_KEYS): + try: + resolve_capabilities(merged, harness=harness_key) + except ConfigError as error: + errors.append( + { + "kind": "invalid-core-block", + "file": "", + "key": f"core.capabilities.{harness_key}", + "message": str(error), + } + ) if "knowledge_sources" in core: try: resolve_knowledge_sources(layers, project_root=roots[-1], include_disabled=True) diff --git a/skills/core-tools/bmad/scripts/render_skill.py b/skills/core-tools/bmad/scripts/render_skill.py index 52d2800d05..608e365d12 100644 --- a/skills/core-tools/bmad/scripts/render_skill.py +++ b/skills/core-tools/bmad/scripts/render_skill.py @@ -710,7 +710,7 @@ def render( assets = _load_assets(skill_dir) discovered = tuple(discover_default_skill_roots((project_root,))) if not skill_roots else () effective_skill_roots = tuple( - dict.fromkeys((skill_dir.parent, *(root.resolve() for root in skill_roots), *discovered)) + dict.fromkeys((*(root.resolve() for root in skill_roots), *discovered, skill_dir.parent)) ) central = load_central_config(project_root, skill_roots=effective_skill_roots) has_customization = bool(overrides is not None or assignments) or (skill_dir / "customize.toml").is_file() diff --git a/tests/core-tools/bmad/test_story04_phase2.py b/tests/core-tools/bmad/test_story04_phase2.py index c6d1986edf..482ece9921 100644 --- a/tests/core-tools/bmad/test_story04_phase2.py +++ b/tests/core-tools/bmad/test_story04_phase2.py @@ -800,7 +800,7 @@ def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scala with self.assertRaisesRegex(Exception, "conflicts with config question"): bmod_utils.read_bmod_file(bmod_path) - # 2. scan_config_reads accepts reads under empty {} [bmod.defaults] subtable. + # 2. scan_config_reads accepts reads under empty {} [bmod.defaults] subtable, while still flagging unknown keys. scan_repo = self.root / "scan-open" _write( scan_repo / "skills" / "bmod-open" / "bmod.toml", @@ -818,11 +818,14 @@ def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scala ) _write( scan_repo / "skills" / "open-run" / "SKILL.md", - "---\nname: open-run\ndescription: 'Run. Use when testing.'\n---\n`modules.open.hooks.pre_step`\n", + "---\nname: open-run\ndescription: 'Run. Use when testing.'\n---\n" + '`uv run "{project-root}/_bmad/scripts/resolve_config.py" --key modules.open.hooks.pre_step ' + "--key modules.open.undeclared_key`\n", ) scan_res = _run(SCAN_READS_SCRIPT, [str(scan_repo / "skills")], cwd=scan_repo) self.assertEqual(scan_res.returncode, 0, scan_res.stderr) - self.assertEqual(json.loads(scan_res.stdout)["unasked"], []) + scan_payload = json.loads(scan_res.stdout) + self.assertEqual([u["key"] for u in scan_payload["unasked"]], ["modules.open.undeclared_key"]) # 3. Duplicate rule ids, scalar int-vs-str per-skill mismatch, --check --key, no-root warning, malformed defaults. proj = self.root / "edge-proj" @@ -866,6 +869,92 @@ def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scala self.assertFalse(central_chk["ok"]) self.assertIn("invalid-module-defaults", {e["kind"] for e in central_chk["errors"]}) + def test_greptile_regressions_render_roots_sibling_defaults_list_elements_and_harness_checks(self): + # 1. render() honors explicit skill_roots before home skill_dir.parent. + proj = self.root / "render-prio" + proj_skills = proj / ".claude" / "skills" + home_skills = self.root / "home-skills" + _write( + proj / "_bmad" / "config.toml", + '[core]\nproject_name = "rp"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write( + proj_skills / "bmod-acme" / "bmod.toml", + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["acme-home"]\npre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\ndepth = "from-project"\n', + ) + _write( + home_skills / "bmod-acme" / "bmod.toml", + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["acme-home"]\npre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\ndepth = "from-home"\n', + ) + _write( + home_skills / "acme-home" / "SKILL.md", + "---\nname: acme-home\ndescription: 'Home. Use when testing.'\n---\n", + ) + _write( + home_skills / "acme-home" / "workflow.md", + "DEPTH={{ config.modules.acme.depth }}\n", + ) + rendered = render_skill.render( + proj, + home_skills / "acme-home", + skill_roots=(proj_skills, home_skills), + ) + self.assertEqual(rendered.read_text(encoding="utf-8").strip(), "DEPTH=from-project") + + # 2. bmod_utils.parse_defaults allows populated table siblings alongside a question, still rejects exact/empty collision. + sib_bmod = self.root / "bmod-sib" / "bmod.toml" + _write( + sib_bmod, + '[bmod]\ncode = "sib"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["sib-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "thresholds.mode"\nprompt = "Mode?"\ndefault = "fast"\n' + "[bmod.defaults.thresholds]\nmax_retries = 2\n", + ) + sib_parsed = bmod_utils.read_bmod_file(sib_bmod) + assert sib_parsed is not None and sib_parsed.bmod is not None + self.assertEqual(sib_parsed.bmod.defaults, {"thresholds": {"max_retries": 2}}) + + exact_bmod = self.root / "bmod-exact" / "bmod.toml" + _write( + exact_bmod, + '[bmod]\ncode = "exact"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["exact-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[[bmod.config_questions]]\nkey = "thresholds"\nprompt = "Thresholds?"\ndefault = "all"\n' + "[bmod.defaults.thresholds]\nmax_retries = 2\n", + ) + with self.assertRaisesRegex(Exception, "conflicts with config question"): + bmod_utils.read_bmod_file(exact_bmod) + + # 3. Rule list elements validate item types (skip with warning in rules; fail in per-skill overrides). + skill_list = self._stage_skill(proj_skills, "bmad-list-check", '[workflow]\npersistent_facts = ["ok"]\n') + _write( + proj / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "bad-elem"\nmatch = "*"\n[rules.workflow]\npersistent_facts = [1]\n', + ) + loaded_rule_list = config_utils.load_customization(proj, skill_list) + self.assertEqual(loaded_rule_list["workflow"]["persistent_facts"], ["ok"]) + chk_rule_list = config_utils.check_customization((proj,), skill_list) + self.assertTrue(chk_rule_list["ok"]) + self.assertEqual([w["kind"] for w in chk_rule_list["warnings"]], ["rule-type-mismatch"]) + + _write(proj / "_bmad" / "custom" / "bmad-list-check.toml", "[workflow]\npersistent_facts = [1]\n") + chk_override_list = config_utils.check_customization((proj,), skill_list) + self.assertFalse(chk_override_list["ok"]) + self.assertEqual([e["kind"] for e in chk_override_list["errors"]], ["type-mismatch"]) + + # 4. check_central_config validates per-harness models and capabilities subtables. + _write( + proj / "_bmad" / "custom" / "config.user.toml", + '[core.models.claude]\nstandard = 42\n[core.capabilities.claude]\nsubagents = "yes"\n', + ) + harness_chk = config_utils.check_central_config((proj,)) + self.assertFalse(harness_chk["ok"]) + self.assertEqual({e["key"] for e in harness_chk["errors"]}, {"core.models.claude", "core.capabilities.claude"}) + if __name__ == "__main__": unittest.main() From 9ab64f21f7d0949bddabe299165eace24f88e47b Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 20:36:34 -0600 Subject: [PATCH 3/8] fix(bmad): include all documented skill dirs in default discovery Include `.agent/skills`, `.cline/skills`, `.bob/skills`, and `.adal/skills` in `DEFAULT_SKILL_ROOT_CANDIDATES` and `HOME_SKILL_ROOT_CANDIDATES` so automatic `[bmod.defaults]` discovery covers all supported tool installs without requiring `--root`, and rename the regression test cleanly. --- .../core-tools/bmad/scripts/config_utils.py | 8 +++++++ tests/core-tools/bmad/test_story04_phase2.py | 24 ++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 2c1862a2b9..3c71231e7d 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -28,17 +28,25 @@ class ConfigError(ValueError): DEFAULT_SKILL_ROOT_CANDIDATES = ( ".agents/skills", ".claude/skills", + ".agent/skills", + ".cline/skills", ".codex/skills", ".cursor/skills", ".windsurf/skills", + ".bob/skills", + ".adal/skills", "skills", ) HOME_SKILL_ROOT_CANDIDATES = ( ".agents/skills", ".claude/skills", + ".agent/skills", + ".cline/skills", ".codex/skills", ".cursor/skills", ".windsurf/skills", + ".bob/skills", + ".adal/skills", ) _CORE_CONFIG_KEYS = frozenset( { diff --git a/tests/core-tools/bmad/test_story04_phase2.py b/tests/core-tools/bmad/test_story04_phase2.py index 482ece9921..983e201d20 100644 --- a/tests/core-tools/bmad/test_story04_phase2.py +++ b/tests/core-tools/bmad/test_story04_phase2.py @@ -616,6 +616,28 @@ def test_home_installed_module_defaults_resolved_without_explicit_root_and_degra self.assertEqual(res_proj.returncode, 0, res_proj.stderr) self.assertEqual(json.loads(res_proj.stdout)["modules.acme.depth"], "project-shallow") + # Also verify documented folders like `.agent/skills` and `.cline/skills` discover defaults automatically. + for extra_rel in (".agent/skills", ".cline/skills"): + extra_proj = self.root / f"proj-{extra_rel.split('/')[0].lstrip('.')}" + _write( + extra_proj / "_bmad" / "config.toml", + '[core]\nproject_name = "ep"\noutput_folder = "{project-root}/_bmad-output"\n', + ) + _write( + extra_proj / extra_rel / "bmod-docdir" / "bmod.toml", + '[bmod]\ncode = "docdir"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' + 'skills = ["docdir-run"]\npre_install_message = ""\npost_install_message = ""\n' + '[bmod.defaults]\ntool_dir = "discovered"\n', + ) + res_extra = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(extra_proj), "--key", "modules.docdir.tool_dir"], + cwd=extra_proj, + env=_isolated_home_env(self.empty_home), + ) + self.assertEqual(res_extra.returncode, 0, res_extra.stderr) + self.assertEqual(json.loads(res_extra.stdout)["modules.docdir.tool_dir"], "discovered") + # Unresolvable Path.home degrades without error. with mock.patch("pathlib.Path.home", side_effect=RuntimeError("no home")): layers = config_utils.central_config_layers(project) @@ -869,7 +891,7 @@ def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scala self.assertFalse(central_chk["ok"]) self.assertIn("invalid-module-defaults", {e["kind"] for e in central_chk["errors"]}) - def test_greptile_regressions_render_roots_sibling_defaults_list_elements_and_harness_checks(self): + def test_render_roots_sibling_defaults_list_elements_and_harness_checks(self): # 1. render() honors explicit skill_roots before home skill_dir.parent. proj = self.root / "render-prio" proj_skills = proj / ".claude" / "skills" From 49ebe58fd28b539de7eeb0829c00568bff7191ac Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 22:51:21 -0600 Subject: [PATCH 4/8] refactor(bmad): unify module defaults on bmod.config_defaults and document rules.toml --- docs/customize/customize-bmad.md | 3 +- docs/reference/configuration.md | 30 +++++-- .../bmad-customize/help/customization.md | 2 +- .../references/central-and-rules.md | 2 +- .../scripts/list_customizable_skills.py | 2 +- .../core-tools/bmad/scripts/config_utils.py | 41 ++++++--- .../core-tools/bmad/scripts/resolve_config.py | 2 +- skills/core-tools/bmad/scripts/setup_check.py | 2 +- tests/core-tools/bmad/test_story04_phase2.py | 89 ++++++++++++------- 9 files changed, 117 insertions(+), 56 deletions(-) diff --git a/docs/customize/customize-bmad.md b/docs/customize/customize-bmad.md index 12435c9202..77bf467b1c 100644 --- a/docs/customize/customize-bmad.md +++ b/docs/customize/customize-bmad.md @@ -24,6 +24,7 @@ Other everyday requests work the same way: - "Hey BMad, tell Amelia to always check our internal component library before writing new UI primitives." - "Hey BMad, make Mary always include a one-line risk summary when she creates a brief, just for me." - "Hey BMad, set my personal writing voice guide at `.local/my-voice.md` for facilitated documents, just for me." +- "For all BMad workflows on this team, always read `docs/api-standards.md` as a persistent fact and append a one-line outcome summary to `docs/run-log.md` when done" — `bmad-customize` writes a `[[rules]]` entry in `_bmad/custom/rules.toml` and verifies it with `resolve_customization.py --check` (personal cross-skill rules, such as "just for me across all agents," go to `_bmad/custom/rules.user.toml`). `bmad-customize` handles agent behavior, workflow settings, and document templates end to end. You do not need to know which underlying skill or file owns a setting before asking. @@ -80,7 +81,7 @@ To build custom personas, themed casts, or reusable focus groups, ask `bmad-part ## Shared Project Configuration -Shared project settings such as where BMad writes output, your active initiative, and module setup answers are initialized by `bmad setup` (writing team defaults to `_bmad/config.toml` and personal choices to `_bmad/custom/config.user.toml`). To override central or module settings afterward — including team overrides in `_bmad/custom/config.toml`, personal overrides in `_bmad/custom/config.user.toml`, or defaults shipped in `[bmod.defaults]` — ask `bmad-customize` or `bmad`, without editing `_bmad/config.toml` manually. +Shared project settings such as where BMad writes output, your active initiative, and module setup answers are initialized by `bmad setup` (writing team defaults to `_bmad/config.toml` and personal choices to `_bmad/custom/config.user.toml`). To override central or module settings afterward — including team overrides in `_bmad/custom/config.toml`, personal overrides in `_bmad/custom/config.user.toml`, or defaults declared in `[bmod.config_defaults]` — ask `bmad-customize` or `bmad`, without editing `_bmad/config.toml` manually. ## How Configuration Layers Work diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index b83a374844..d060768973 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -26,13 +26,13 @@ If you want to know what can be tailored on a specific agent or skill, ask `"Hey Project-wide setup answers, unasked module defaults, and shared overrides merge across four TOML layers, where higher-priority layers win when the same key appears in more than one place: ```text -Priority 1 (wins): _bmad/custom/config.user.toml (project personal overrides, gitignored) -Priority 2: _bmad/custom/config.toml (team overrides, committed) -Priority 3: _bmad/config.toml (setup-owned project defaults, committed) -Priority 4 (base): /bmod.toml [bmod.defaults] (shipped unasked module defaults) +Priority 1 (wins): _bmad/custom/config.user.toml (project personal overrides, gitignored) +Priority 2: _bmad/custom/config.toml (team overrides, committed) +Priority 3: _bmad/config.toml (setup-owned project defaults, committed) +Priority 4 (base): /bmod.toml [bmod.config_defaults] (shipped unasked module defaults) ``` -Running `bmad setup` writes prompted team answers to `_bmad/config.toml` and personal setup answers to `_bmad/custom/config.user.toml`, leaving unasked module defaults in each module's `bmod.toml` so module updates flow through automatically without editing project files. Setup preserves your overrides under `_bmad/custom/` (only renaming a per-skill file if a retired skill moves to a new name), and `bmad-customize` edits `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` without mutating `_bmad/config.toml`. Inside a fresh linked worktree where gitignored personal `*.user.toml` files (`config.user.toml`, `rules.user.toml`, `.user.toml`) are absent locally, BMAD reads your main checkout's `*.user.toml` files read-only until you create a worktree-local file. +Running `bmad setup` writes prompted team answers and seeds `[bmod.config_defaults]` into `_bmad/config.toml` (and personal setup answers to `_bmad/custom/config.user.toml`) without overwriting existing keys; runtime resolution also falls back to `[bmod.config_defaults]` at Priority 4 if a key has not been written to `_bmad/config.toml` yet. Setup preserves your overrides under `_bmad/custom/` (only renaming a per-skill file if a retired skill moves to a new name), and `bmad-customize` edits `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` without mutating `_bmad/config.toml`. Inside a fresh linked worktree where gitignored personal `*.user.toml` files (`config.user.toml`, `rules.user.toml`, `.user.toml`) are absent locally, BMAD reads your main checkout's `*.user.toml` files read-only until you create a worktree-local file. | Setting | Scope | What it controls | | --- | --- | --- | @@ -120,6 +120,26 @@ Priority 5 (base): /customize.toml (shipped defaults) In `rules.toml` and `rules.user.toml`, each `[[rules]]` entry targets installed skill folders via `match` glob patterns (and optional `id` or `surface`), supplying `[rules.agent]` or `[rules.workflow]` tables. Keys not declared by a matched skill's `customize.toml` are skipped cleanly at load time unless they sit inside an open `{}` table such as `[workflow.harnesses]`. +```toml +# Team cross-skill rules: _bmad/custom/rules.toml (committed) +[[rules]] +id = "team-workflow-standards" +match = "bmad-*" + +[rules.workflow] +persistent_facts = ["file:{project-root}/docs/api-standards.md"] +on_complete = "Log a one-line outcome summary to {project-root}/docs/run-log.md" + +[[rules]] +id = "agent-date-format" +match = "bmad-agent-*" + +[rules.agent] +persistent_facts = ["Always format dates in ISO 8601 (YYYY-MM-DD)."] +``` + +Personal cross-skill rules use the exact same `[[rules]]` schema in `_bmad/custom/rules.user.toml` (gitignored). + :::caution[Keep Override Files Sparse] Only include the settings you intentionally change. Copying an entire `customize.toml` into `_bmad/custom/` locks in old defaults and prevents future skill improvements from taking effect. ::: diff --git a/skills/core-tools/bmad-customize/help/customization.md b/skills/core-tools/bmad-customize/help/customization.md index 6bcb49f9b4..e2c629d673 100644 --- a/skills/core-tools/bmad-customize/help/customization.md +++ b/skills/core-tools/bmad-customize/help/customization.md @@ -24,7 +24,7 @@ Central config merges in four tiers: 1. `{project-root}/_bmad/custom/config.user.toml` — personal central overrides (gitignored; read-only main-checkout fallback in linked worktrees) 2. `{project-root}/_bmad/custom/config.toml` — team central overrides (committed) 3. `_bmad/config.toml` — setup-owned project answers (committed) -4. `/bmod.toml` `[bmod.defaults]` — shipped unasked module defaults +4. `/bmod.toml` `[bmod.config_defaults]` — shipped module defaults (seeded into `_bmad/config.toml` by `bmad setup`, and used as a runtime fallback if absent) Use `bmad-customize` for per-skill files, `rules.toml` or `rules.user.toml`, central `_bmad/custom/config.toml` or `config.user.toml` overrides, and facilitation templates; use `bmad` for initial setup and module setup questions. diff --git a/skills/core-tools/bmad-customize/references/central-and-rules.md b/skills/core-tools/bmad-customize/references/central-and-rules.md index 209a11a74c..62538dcb5a 100644 --- a/skills/core-tools/bmad-customize/references/central-and-rules.md +++ b/skills/core-tools/bmad-customize/references/central-and-rules.md @@ -42,7 +42,7 @@ Setup creates and upgrades `_bmad/config.toml`, so never edit `_bmad/config.toml Effective central config merges four layers in ascending priority: -1. Shipped module `[bmod.defaults]` (lowest, read from installed module records) +1. Shipped module `[bmod.config_defaults]` (lowest runtime fallback when a key is not in `_bmad/config.toml`, read from installed module records) 2. `_bmad/config.toml` (setup defaults) 3. `{project-root}/_bmad/custom/config.toml` (team overrides) 4. `{project-root}/_bmad/custom/config.user.toml` (personal overrides; or read-only main-checkout fallback inside a fresh linked worktree) diff --git a/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py b/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py index bde0a349c0..bff93a3222 100644 --- a/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py +++ b/skills/core-tools/bmad-customize/scripts/list_customizable_skills.py @@ -146,7 +146,7 @@ def scan_skills( code = bmod_table.get("code") if isinstance(code, str) and code.strip() and code not in seen_module_codes: seen_module_codes.add(code) - raw_defaults = bmod_table.get("defaults") + raw_defaults = bmod_table.get("config_defaults") raw_questions = bmod_table.get("config_questions") q_keys = ( [ diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 3c71231e7d..6d64fd69c5 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -608,7 +608,7 @@ def load_module_defaults( *, project_roots: Iterable[Path] = (), ) -> dict[str, Any]: - """Load shipped unasked `[bmod.defaults]` from installed `bmod.toml` records (lowest central layer).""" + """Load shipped `[bmod.config_defaults]` from installed `bmod.toml` records (lowest central layer).""" roots = [r for r in skill_roots] if skill_roots is not None else discover_default_skill_roots(project_roots) if not roots: return {} @@ -637,7 +637,7 @@ def load_module_defaults( code = bmod_table.get("code") if not isinstance(code, str) or not code.strip(): continue - raw_defaults = bmod_table.get("defaults") + raw_defaults = bmod_table.get("config_defaults") if raw_defaults is None: continue if not isinstance(raw_defaults, dict) or code in raw_defaults: @@ -675,17 +675,18 @@ def central_config_layers_for_roots( *, require_project: bool = True, skill_roots: Iterable[Path] | None = None, + include_module_defaults: bool = True, ) -> tuple[dict[str, Any], ...]: """Load central config layers across ordered `_bmad/` roots in ascending precedence (lowest -> highest). Precedence: - 1. Shipped module `[bmod.defaults]` (if any installed module declares unasked defaults) + 1. Shipped module `[bmod.config_defaults]` (if enabled and any installed module declares unasked defaults) 2. Team layers per root (`_bmad/config.toml` then `_bmad/custom/config.toml` in root order) 3. Personal layers per root (`_bmad/custom/config.user.toml` or read-only worktree fallback in root order) """ roots = tuple(project_roots) layers: list[dict[str, Any]] = [] - if roots or skill_roots is not None: + if include_module_defaults and (roots or skill_roots is not None): defaults_layer = load_module_defaults(skill_roots, project_roots=roots) if defaults_layer: layers.append(defaults_layer) @@ -703,25 +704,43 @@ def central_config_layers( *, require_project: bool = True, skill_roots: Iterable[Path] | None = None, + include_module_defaults: bool = True, ) -> tuple[dict[str, Any], ...]: """Load central config layers in ascending precedence (lowest -> highest). Precedence: - 1. Shipped module `[bmod.defaults]` (lowest, when present) + 1. Shipped module `[bmod.config_defaults]` (lowest, when present and enabled) 2. /_bmad/config.toml (project defaults, required unless require_project=False) 3. /_bmad/custom/config.toml (team overrides, optional) 4. /_bmad/custom/config.user.toml (or read-only main-checkout fallback in a linked worktree) """ if project_root is None: - if skill_roots is not None: + if include_module_defaults and skill_roots is not None: defaults_layer = load_module_defaults(skill_roots) return (defaults_layer,) if defaults_layer else () return () - return central_config_layers_for_roots((project_root,), require_project=require_project, skill_roots=skill_roots) + return central_config_layers_for_roots( + (project_root,), + require_project=require_project, + skill_roots=skill_roots, + include_module_defaults=include_module_defaults, + ) -def load_central_config(project_root: Path, *, skill_roots: Iterable[Path] | None = None) -> dict[str, Any]: - return merge_layers(central_config_layers(project_root, require_project=True, skill_roots=skill_roots)) +def load_central_config( + project_root: Path, + *, + skill_roots: Iterable[Path] | None = None, + include_module_defaults: bool = True, +) -> dict[str, Any]: + return merge_layers( + central_config_layers( + project_root, + require_project=True, + skill_roots=skill_roots, + include_module_defaults=include_module_defaults, + ) + ) def _normalize_rule_patterns(raw_match: Any, *, source: Path, index: int) -> tuple[str, ...]: @@ -1307,7 +1326,7 @@ def _discover_module_schemas( q_keys.add(q["key"]) d_keys: set[str] = set() d_open: set[str] = set() - raw_defaults = bmod_table.get("defaults") + raw_defaults = bmod_table.get("config_defaults") if raw_defaults is not None: if not isinstance(raw_defaults, dict) or code in raw_defaults: errors.append( @@ -1315,7 +1334,7 @@ def _discover_module_schemas( "kind": "invalid-module-defaults", "file": str(manifest), "key": f"modules.{code}", - "message": f"invalid [bmod.defaults] in {manifest}", + "message": f"invalid [bmod.config_defaults] in {manifest}", } ) else: diff --git a/skills/core-tools/bmad/scripts/resolve_config.py b/skills/core-tools/bmad/scripts/resolve_config.py index a0efcda0f0..a384dcac86 100644 --- a/skills/core-tools/bmad/scripts/resolve_config.py +++ b/skills/core-tools/bmad/scripts/resolve_config.py @@ -98,7 +98,7 @@ def main() -> int: type=Path, action="append", default=[], - help="Active skills root holding installed module defaults (`[bmod.defaults]`), repeatable, first wins.", + help="Active skills root holding installed module defaults (`[bmod.config_defaults]`), repeatable, first wins.", ) parser.add_argument( "--key", diff --git a/skills/core-tools/bmad/scripts/setup_check.py b/skills/core-tools/bmad/scripts/setup_check.py index 40cd096a09..e309190bfa 100644 --- a/skills/core-tools/bmad/scripts/setup_check.py +++ b/skills/core-tools/bmad/scripts/setup_check.py @@ -79,7 +79,7 @@ def owed(skill_dir: Path, project_root: Path | None, roots: tuple[Path, ...] = ( if record.questions or record.config_defaults: try: - config = load_central_config(project_root) + config = load_central_config(project_root, include_module_defaults=False) except ConfigError: config = None if config is not None: diff --git a/tests/core-tools/bmad/test_story04_phase2.py b/tests/core-tools/bmad/test_story04_phase2.py index 983e201d20..21d96833d6 100644 --- a/tests/core-tools/bmad/test_story04_phase2.py +++ b/tests/core-tools/bmad/test_story04_phase2.py @@ -1,4 +1,4 @@ -"""Deterministic tests for Story 4 Phase 2: `[bmod.defaults]`, `_bmad/custom/rules*.toml`, and unified customization tools.""" +"""Deterministic tests for Story 4 Phase 2: `[bmod.config_defaults]`, `_bmad/custom/rules*.toml`, and unified customization tools.""" from __future__ import annotations @@ -113,12 +113,18 @@ def test_bmod_defaults_validation_and_question_collision_rejection(self): path, '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' - "[bmod.defaults]\ntimeout_seconds = 30\n[bmod.defaults.thresholds]\nmax_retries = 2\n", + "[bmod.config_defaults]\ntimeout_seconds = 30\n[bmod.config_defaults.thresholds]\nmax_retries = 2\n", ) parsed = bmod_utils.read_bmod_file(path) self.assertIsNotNone(parsed) assert parsed is not None and parsed.bmod is not None - self.assertEqual(parsed.bmod.defaults, {"timeout_seconds": 30, "thresholds": {"max_retries": 2}}) + self.assertEqual( + parsed.bmod.config_defaults, + ( + bmod_utils.ConfigDefault("acme", "timeout_seconds", 30), + bmod_utils.ConfigDefault("acme", "thresholds.max_retries", 2), + ), + ) # Collision with config_questions fails loudly. _write( @@ -126,7 +132,7 @@ def test_bmod_defaults_validation_and_question_collision_rejection(self): '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "thresholds.mode"\nprompt = "Mode?"\ndefault = "fast"\n' - '[bmod.defaults.thresholds]\nmode = "slow"\n', + '[bmod.config_defaults.thresholds]\nmode = "slow"\n', ) with self.assertRaisesRegex(Exception, "conflicts with config question"): bmod_utils.read_bmod_file(path) @@ -136,9 +142,19 @@ def test_bmod_defaults_validation_and_question_collision_rejection(self): path, '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' - "[bmod.defaults.acme]\nfoo = 1\n", + "[bmod.config_defaults.acme]\nfoo = 1\n", ) - with self.assertRaisesRegex(Exception, "must not nest module 'acme'"): + with self.assertRaisesRegex(Exception, "must not start with module 'acme'"): + bmod_utils.read_bmod_file(path) + + # Empty nested tables fail loudly. + _write( + path, + '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' + 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' + "[bmod.config_defaults.empty]\n", + ) + with self.assertRaisesRegex(Exception, "must not be an empty table"): bmod_utils.read_bmod_file(path) def test_validate_manifests_and_scan_config_reads_accept_bmod_defaults(self): @@ -149,7 +165,7 @@ def test_validate_manifests_and_scan_config_reads_accept_bmod_defaults(self): f'[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "{src}"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "asked_key"\nprompt = "Asked?"\ndefault = "yes"\n' - '[bmod.defaults]\ndefault_depth = "deep"\n[bmod.defaults.limits]\nmax_items = 5\n', + '[bmod.config_defaults]\ndefault_depth = "deep"\n[bmod.config_defaults.limits]\nmax_items = 5\n', ) _write( repo / "skills" / "bmod-acme" / "SKILL.md", @@ -176,7 +192,7 @@ def test_validate_manifests_and_scan_config_reads_accept_bmod_defaults(self): self.assertEqual(scan_data["unread"], []) self.assertEqual(scan_data["records"][0]["defaults"], ["default_depth", "limits.max_items"]) - def test_four_layer_precedence_and_non_materialization_in_setup(self): + def test_four_layer_precedence_and_config_defaults_setup_plus_runtime_fallback(self): project = self.root / "project" skills = project / ".agents" / "skills" src = f"file:{(self.root / 'src').as_posix()}" @@ -202,8 +218,8 @@ def test_four_layer_precedence_and_non_materialization_in_setup(self): f'[bmod]\ncode = "tea"\nversion = "1.0.0"\nupdate_source = {json.dumps(src, ensure_ascii=False)}\n' 'skills = ["tea-check"]\nrequired_skills = ["bmad"]\n' 'pre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\na = "shipped"\nb = "shipped"\nc = "shipped"\nd = "shipped"\n' - '[bmod.defaults.nested]\nkeep = true\noverride = "shipped"\n', + '[bmod.config_defaults]\na = "shipped"\nb = "shipped"\nc = "shipped"\nd = "shipped"\n' + '[bmod.config_defaults.nested]\nkeep = true\noverride = "shipped"\n', ) _write( skills / "bmod-tea" / "SKILL.md", @@ -222,17 +238,19 @@ def test_four_layer_precedence_and_non_materialization_in_setup(self): "A={{ config.modules.tea.a }}|B={{ config.modules.tea.b }}|C={{ config.modules.tea.c }}|D={{ config.modules.tea.d }}\n", ) - # Run setup: must NOT materialize [bmod.defaults] into _bmad/config.toml and must report 0 pending questions. + # Run setup: silently seeds [bmod.config_defaults] into _bmad/config.toml with 0 pending questions. setup_res = bmad_setup.setup(project, skills / "bmad", roots=(skills,)) self.assertEqual(setup_res["pending_questions"], []) raw_team_cfg = (project / "_bmad" / "config.toml").read_text(encoding="utf-8") - self.assertNotIn("modules.tea", raw_team_cfg) + self.assertIn("[modules.tea]", raw_team_cfg) self.assertEqual(setup_check.owed(skills / "tea-check", project, (skills,)), []) - # Layer overrides across all 4 tiers. + # Strip `modules.tea` from _bmad/config.toml and keep only `b`/`c`/`d` overrides across layers so + # `a` and `nested.keep` prove runtime Priority 4 fallback still supplies new/unseeded defaults. + minimal_core = raw_team_cfg.split("[modules.tea]")[0].rstrip() _write( project / "_bmad" / "config.toml", - raw_team_cfg + '\n[modules.tea]\nb = "config"\nc = "config"\nd = "config"\n', + minimal_core + '\n\n[modules.tea]\nb = "config"\nc = "config"\nd = "config"\n', ) _write( project / "_bmad" / "custom" / "config.toml", @@ -508,7 +526,7 @@ def test_list_customizable_skills_surfaces_central_config_rules_and_modules(self '[bmod]\ncode = "demo"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["demo-flow"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "workspace_dir"\nprompt = "Where?"\ndefault = "ws"\n' - '[bmod.defaults]\ndefault_depth = "standard"\n', + '[bmod.config_defaults]\ndefault_depth = "standard"\n', ) self._stage_skill(skills, "demo-flow", "[workflow]\npersistent_facts = []\n") @@ -587,7 +605,7 @@ def test_home_installed_module_defaults_resolved_without_explicit_root_and_degra fake_home / ".agents" / "skills" / "bmod-acme" / "bmod.toml", '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\ndepth = "deep"\nregion = "us"\n', + '[bmod.config_defaults]\ndepth = "deep"\nregion = "us"\n', ) # Home-installed module default resolves with no --root flag. @@ -605,7 +623,7 @@ def test_home_installed_module_defaults_resolved_without_explicit_root_and_degra project / ".claude" / "skills" / "bmod-acme" / "bmod.toml", '[bmod]\ncode = "acme"\nversion = "1.1.0"\nupdate_source = "plugin:local"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\ndepth = "project-shallow"\n', + '[bmod.config_defaults]\ndepth = "project-shallow"\n', ) res_proj = _run( BMAD_SCRIPTS / "resolve_config.py", @@ -627,7 +645,7 @@ def test_home_installed_module_defaults_resolved_without_explicit_root_and_degra extra_proj / extra_rel / "bmod-docdir" / "bmod.toml", '[bmod]\ncode = "docdir"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["docdir-run"]\npre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\ntool_dir = "discovered"\n', + '[bmod.config_defaults]\ntool_dir = "discovered"\n', ) res_extra = _run( BMAD_SCRIPTS / "resolve_config.py", @@ -722,7 +740,7 @@ def test_resolve_config_check_validates_central_overrides_and_open_default_table '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "workspace_dir"\nprompt = "Dir?"\ndefault = "ws"\n' - '[bmod.defaults]\ndepth = "deep"\n[bmod.defaults.hooks]\n', + '[bmod.config_defaults]\ndepth = "deep"\n[bmod.config_defaults.hooks]\npost_run = ""\n', ) setup_text = '[core]\nproject_name = "cc"\noutput_folder = "{project-root}/_bmad-output"\n' _write(project / "_bmad" / "config.toml", setup_text) @@ -791,7 +809,7 @@ def test_multi_root_central_config_layer_precedence(self): inner / ".agents" / "skills" / "bmod-acme" / "bmod.toml", '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["acme-run"]\npre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\ndefault_only = "d"\nouter_beats_default = "d"\n', + '[bmod.config_defaults]\ndefault_only = "d"\nouter_beats_default = "d"\n', ) _write(outer / "_bmad" / "config.toml", '[core]\nshared = "outer-team"\npers_vs_team = "outer-team"\n') _write(outer / "_bmad" / "custom" / "config.user.toml", '[core]\npers_vs_team = "outer-user"\n') @@ -809,26 +827,26 @@ def test_multi_root_central_config_layer_precedence(self): self.assertEqual(merged["core"]["inner_user"], "iu") self.assertEqual(merged["modules"]["acme"], {"default_only": "d", "outer_beats_default": "t"}) - def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scalar_types(self): - # 1. bmod_utils.parse_defaults rejects empty-table prefix collisions. + def test_edge_cases_prefix_collision_scan_reads_duplicate_rule_id_scalar_types(self): + # 1. bmod_utils.parse_defaults rejects prefix collisions and empty nested tables. bmod_path = self.root / "bmod-edge" / "bmod.toml" _write( bmod_path, '[bmod]\ncode = "edge"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' 'skills = ["edge-run"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "thresholds.mode"\nprompt = "Mode?"\ndefault = "fast"\n' - "[bmod.defaults.thresholds]\n", + '[bmod.config_defaults]\nthresholds = "flat"\n', ) with self.assertRaisesRegex(Exception, "conflicts with config question"): bmod_utils.read_bmod_file(bmod_path) - # 2. scan_config_reads accepts reads under empty {} [bmod.defaults] subtable, while still flagging unknown keys. + # 2. scan_config_reads accepts dotted-prefix and leaf reads under [bmod.config_defaults], flagging unknown keys. scan_repo = self.root / "scan-open" _write( scan_repo / "skills" / "bmod-open" / "bmod.toml", '[bmod]\ncode = "open"\nversion = "1.0.0"\nupdate_source = "github:acme/mods/skills"\n' 'skills = ["open-run"]\npre_install_message = ""\npost_install_message = ""\n' - "[bmod.defaults.hooks]\n", + '[bmod.config_defaults.hooks]\npre_step = ""\n', ) _write( scan_repo / "skills" / "bmod-open" / "SKILL.md", @@ -841,8 +859,8 @@ def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scala _write( scan_repo / "skills" / "open-run" / "SKILL.md", "---\nname: open-run\ndescription: 'Run. Use when testing.'\n---\n" - '`uv run "{project-root}/_bmad/scripts/resolve_config.py" --key modules.open.hooks.pre_step ' - "--key modules.open.undeclared_key`\n", + '`uv run "{project-root}/_bmad/scripts/resolve_config.py" --key modules.open.hooks ' + "--key modules.open.hooks.pre_step --key modules.open.undeclared_key`\n", ) scan_res = _run(SCAN_READS_SCRIPT, [str(scan_repo / "skills")], cwd=scan_repo) self.assertEqual(scan_res.returncode, 0, scan_res.stderr) @@ -883,7 +901,7 @@ def test_edge_cases_empty_prefix_collision_open_defaults_duplicate_rule_id_scala skills / "bmod-bad" / "bmod.toml", '[bmod]\ncode = "bad"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["bmad-edge"]\npre_install_message = ""\npost_install_message = ""\n' - 'defaults = "not-a-table"\n', + 'config_defaults = "not-a-table"\n', ) # Normal central_config_layers skips bad defaults cleanly; check_central_config surfaces the manifest error. self.assertGreaterEqual(len(config_utils.central_config_layers(proj)), 1) @@ -904,13 +922,13 @@ def test_render_roots_sibling_defaults_list_elements_and_harness_checks(self): proj_skills / "bmod-acme" / "bmod.toml", '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["acme-home"]\npre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\ndepth = "from-project"\n', + '[bmod.config_defaults]\ndepth = "from-project"\n', ) _write( home_skills / "bmod-acme" / "bmod.toml", '[bmod]\ncode = "acme"\nversion = "1.0.0"\nupdate_source = "plugin:local"\n' 'skills = ["acme-home"]\npre_install_message = ""\npost_install_message = ""\n' - '[bmod.defaults]\ndepth = "from-home"\n', + '[bmod.config_defaults]\ndepth = "from-home"\n', ) _write( home_skills / "acme-home" / "SKILL.md", @@ -927,18 +945,21 @@ def test_render_roots_sibling_defaults_list_elements_and_harness_checks(self): ) self.assertEqual(rendered.read_text(encoding="utf-8").strip(), "DEPTH=from-project") - # 2. bmod_utils.parse_defaults allows populated table siblings alongside a question, still rejects exact/empty collision. + # 2. bmod_utils.parse_defaults allows populated table siblings alongside a question, still rejects exact collision. sib_bmod = self.root / "bmod-sib" / "bmod.toml" _write( sib_bmod, '[bmod]\ncode = "sib"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' 'skills = ["sib-run"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "thresholds.mode"\nprompt = "Mode?"\ndefault = "fast"\n' - "[bmod.defaults.thresholds]\nmax_retries = 2\n", + "[bmod.config_defaults.thresholds]\nmax_retries = 2\n", ) sib_parsed = bmod_utils.read_bmod_file(sib_bmod) assert sib_parsed is not None and sib_parsed.bmod is not None - self.assertEqual(sib_parsed.bmod.defaults, {"thresholds": {"max_retries": 2}}) + self.assertEqual( + sib_parsed.bmod.config_defaults, + (bmod_utils.ConfigDefault("sib", "thresholds.max_retries", 2),), + ) exact_bmod = self.root / "bmod-exact" / "bmod.toml" _write( @@ -946,7 +967,7 @@ def test_render_roots_sibling_defaults_list_elements_and_harness_checks(self): '[bmod]\ncode = "exact"\nversion = "1.0.0"\nupdate_source = "github:acme/mods"\n' 'skills = ["exact-run"]\npre_install_message = ""\npost_install_message = ""\n' '[[bmod.config_questions]]\nkey = "thresholds"\nprompt = "Thresholds?"\ndefault = "all"\n' - "[bmod.defaults.thresholds]\nmax_retries = 2\n", + "[bmod.config_defaults.thresholds]\nmax_retries = 2\n", ) with self.assertRaisesRegex(Exception, "conflicts with config question"): bmod_utils.read_bmod_file(exact_bmod) From 884f25d17ce59720af73565b683b30bbc6e9b256 Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 23:04:07 -0600 Subject: [PATCH 5/8] test(bmad): add bmad-customize behavioral evals and tighten trigger boundaries --- evals/core-tools/bmad-customize/cases.json | 285 ++++++++++++++++++ .../bmad-customize/files/api-standards.md | 4 + .../bmad-customize/files/config.toml | 7 + .../bmad-customize/files/custom.gitignore | 1 + skills/core-tools/bmad-customize/SKILL.md | 2 +- 5 files changed, 298 insertions(+), 1 deletion(-) create mode 100644 evals/core-tools/bmad-customize/cases.json create mode 100644 evals/core-tools/bmad-customize/files/api-standards.md create mode 100644 evals/core-tools/bmad-customize/files/config.toml create mode 100644 evals/core-tools/bmad-customize/files/custom.gitignore diff --git a/evals/core-tools/bmad-customize/cases.json b/evals/core-tools/bmad-customize/cases.json new file mode 100644 index 0000000000..fa4193b0e8 --- /dev/null +++ b/evals/core-tools/bmad-customize/cases.json @@ -0,0 +1,285 @@ +[ + { + "id": "cross-skill-team-rule-approval-gate", + "input": "Use bmad-customize to add a team-wide rule for all bmad-* workflows: always load docs/api-standards.md as a persistent fact and append a one-line outcome summary to docs/run-log.md when done.", + "skills": [ + "skills/core-tools/bmod-core-tools", + "skills/core-tools/bmad-review", + "skills/core-tools/bmad-facilitate", + "skills/core-tools/bmad-forge-idea", + "skills/method/bmad-agent-dev", + "skills/method/bmod-method" + ], + "files": [ + { + "from": "skills/core-tools/bmad/scripts/config_utils.py", + "to": "_bmad/scripts/config_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/bmod_utils.py", + "to": "_bmad/scripts/bmod_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/frontmatter.py", + "to": "_bmad/scripts/frontmatter.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_customization.py", + "to": "_bmad/scripts/resolve_customization.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_config.py", + "to": "_bmad/scripts/resolve_config.py" + }, + { + "from": "skills/core-tools/bmad/scripts/detect_env.py", + "to": "_bmad/scripts/detect_env.py" + }, + { + "from": "evals/core-tools/bmad-customize/files/config.toml", + "to": "_bmad/config.toml" + }, + { + "from": "evals/core-tools/bmad-customize/files/custom.gitignore", + "to": "_bmad/custom/.gitignore" + }, + { + "from": "evals/core-tools/bmad-customize/files/api-standards.md", + "to": "docs/api-standards.md" + } + ], + "rubric": [ + "_bmad/custom/rules.toml does NOT exist in the workspace after the turn (proposed first and waited for confirmation before writing)", + "_bmad/config.toml is byte-identical to the initial fixture", + "The final reply targets _bmad/custom/rules.toml and presents a valid [[rules]] TOML snippet with id, match = \"bmad-*\", and [rules.workflow] setting persistent_facts with file:{project-root}/docs/api-standards.md and on_complete referencing docs/run-log.md", + "The final reply explicitly asks the user to confirm before writing" + ] + }, + { + "id": "cross-skill-team-rule-write-and-verify", + "state_prefix": "[On the previous turn, you inspected the installed skills, proposed adding a team cross-skill workflow rule in _bmad/custom/rules.toml with match = \"bmad-*\", persistent_facts = [\"file:{project-root}/docs/api-standards.md\"], and on_complete = \"Append a one-line outcome summary to {project-root}/docs/run-log.md\", and asked the user to confirm before writing.] ", + "input": "Yes, go ahead and write _bmad/custom/rules.toml and verify it against the installed workflow skills.", + "skills": [ + "skills/core-tools/bmod-core-tools", + "skills/core-tools/bmad-review", + "skills/core-tools/bmad-facilitate", + "skills/core-tools/bmad-forge-idea", + "skills/method/bmad-agent-dev", + "skills/method/bmod-method" + ], + "files": [ + { + "from": "skills/core-tools/bmad/scripts/config_utils.py", + "to": "_bmad/scripts/config_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/bmod_utils.py", + "to": "_bmad/scripts/bmod_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/frontmatter.py", + "to": "_bmad/scripts/frontmatter.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_customization.py", + "to": "_bmad/scripts/resolve_customization.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_config.py", + "to": "_bmad/scripts/resolve_config.py" + }, + { + "from": "skills/core-tools/bmad/scripts/detect_env.py", + "to": "_bmad/scripts/detect_env.py" + }, + { + "from": "evals/core-tools/bmad-customize/files/config.toml", + "to": "_bmad/config.toml" + }, + { + "from": "evals/core-tools/bmad-customize/files/custom.gitignore", + "to": "_bmad/custom/.gitignore" + }, + { + "from": "evals/core-tools/bmad-customize/files/api-standards.md", + "to": "docs/api-standards.md" + } + ], + "rubric": [ + "_bmad/custom/rules.toml exists, parses cleanly as TOML, and contains a [[rules]] entry with non-empty id, match = \"bmad-*\", and [rules.workflow] setting persistent_facts including file:{project-root}/docs/api-standards.md and on_complete referencing docs/run-log.md", + "_bmad/config.toml is byte-identical to the initial fixture", + "The transcript shows running resolve_customization.py with --check against matching workflow skills including bmad-review and bmad-forge-idea with exit code 0", + "The final reply confirms _bmad/custom/rules.toml was written, reports the validation result (noting any soft warning on heterogeneous matched skills such as bmad-forge-idea if reported), and reminds the user to commit _bmad/custom/rules.toml" + ] + }, + { + "id": "cross-skill-personal-agent-rule", + "state_prefix": "[On the previous turn, you proposed adding a personal cross-skill rule in _bmad/custom/rules.user.toml for all bmad-agent-* skills with persistent_facts = [\"Always format dates in ISO 8601 (YYYY-MM-DD).\"] and waited for the user's confirmation.] ", + "input": "Confirmed — write that personal agent rule now and validate it.", + "skills": [ + "skills/core-tools/bmod-core-tools", + "skills/core-tools/bmad-review", + "skills/core-tools/bmad-facilitate", + "skills/core-tools/bmad-forge-idea", + "skills/method/bmad-agent-dev", + "skills/method/bmod-method" + ], + "files": [ + { + "from": "skills/core-tools/bmad/scripts/config_utils.py", + "to": "_bmad/scripts/config_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/bmod_utils.py", + "to": "_bmad/scripts/bmod_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/frontmatter.py", + "to": "_bmad/scripts/frontmatter.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_customization.py", + "to": "_bmad/scripts/resolve_customization.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_config.py", + "to": "_bmad/scripts/resolve_config.py" + }, + { + "from": "skills/core-tools/bmad/scripts/detect_env.py", + "to": "_bmad/scripts/detect_env.py" + }, + { + "from": "evals/core-tools/bmad-customize/files/config.toml", + "to": "_bmad/config.toml" + }, + { + "from": "evals/core-tools/bmad-customize/files/custom.gitignore", + "to": "_bmad/custom/.gitignore" + }, + { + "from": "evals/core-tools/bmad-customize/files/api-standards.md", + "to": "docs/api-standards.md" + } + ], + "rubric": [ + "_bmad/custom/rules.user.toml exists, parses cleanly as TOML, and contains a [[rules]] entry with non-empty id, match = \"bmad-agent-*\", and [rules.agent] setting persistent_facts containing the ISO 8601 date formatting rule", + "_bmad/custom/rules.toml does NOT exist in the workspace (personal scope stayed strictly in rules.user.toml)", + "_bmad/config.toml is byte-identical to the initial fixture", + "The transcript shows running resolve_customization.py with --check against bmad-agent-dev with exit code 0, and the final reply notes that rules.user.toml is personal and gitignored" + ] + }, + { + "id": "central-config-override-protects-setup-toml", + "state_prefix": "[On the previous turn, you explained that modules.method.repo_topology is a team central config setting currently set to 'monorepo' in _bmad/config.toml, proposed overriding it to 'polyrepo' in _bmad/custom/config.toml so _bmad/config.toml stays setup-owned, and asked the user to confirm.] ", + "input": "Yes, write the team central override to polyrepo and check the resolved config.", + "skills": [ + "skills/core-tools/bmod-core-tools", + "skills/core-tools/bmad-review", + "skills/core-tools/bmad-facilitate", + "skills/core-tools/bmad-forge-idea", + "skills/method/bmad-agent-dev", + "skills/method/bmod-method" + ], + "files": [ + { + "from": "skills/core-tools/bmad/scripts/config_utils.py", + "to": "_bmad/scripts/config_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/bmod_utils.py", + "to": "_bmad/scripts/bmod_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/frontmatter.py", + "to": "_bmad/scripts/frontmatter.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_customization.py", + "to": "_bmad/scripts/resolve_customization.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_config.py", + "to": "_bmad/scripts/resolve_config.py" + }, + { + "from": "skills/core-tools/bmad/scripts/detect_env.py", + "to": "_bmad/scripts/detect_env.py" + }, + { + "from": "evals/core-tools/bmad-customize/files/config.toml", + "to": "_bmad/config.toml" + }, + { + "from": "evals/core-tools/bmad-customize/files/custom.gitignore", + "to": "_bmad/custom/.gitignore" + }, + { + "from": "evals/core-tools/bmad-customize/files/api-standards.md", + "to": "docs/api-standards.md" + } + ], + "rubric": [ + "_bmad/custom/config.toml exists, parses cleanly as TOML, and sets modules.method.repo_topology = \"polyrepo\"", + "_bmad/config.toml is byte-identical to the initial fixture (still sets repo_topology = \"monorepo\" and was not edited)", + "The transcript shows running resolve_config.py --check with exit code 0 and resolving modules.method.repo_topology to polyrepo", + "The final reply confirms _bmad/custom/config.toml was updated without modifying _bmad/config.toml and reminds the user to commit _bmad/custom/config.toml" + ] + }, + { + "id": "unexposed-field-honesty", + "input": "Use bmad-customize to set max_parallel_gpu_workers = 8 on bmad-review.", + "skills": [ + "skills/core-tools/bmod-core-tools", + "skills/core-tools/bmad-review", + "skills/core-tools/bmad-facilitate", + "skills/core-tools/bmad-forge-idea", + "skills/method/bmad-agent-dev", + "skills/method/bmod-method" + ], + "files": [ + { + "from": "skills/core-tools/bmad/scripts/config_utils.py", + "to": "_bmad/scripts/config_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/bmod_utils.py", + "to": "_bmad/scripts/bmod_utils.py" + }, + { + "from": "skills/core-tools/bmad/scripts/frontmatter.py", + "to": "_bmad/scripts/frontmatter.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_customization.py", + "to": "_bmad/scripts/resolve_customization.py" + }, + { + "from": "skills/core-tools/bmad/scripts/resolve_config.py", + "to": "_bmad/scripts/resolve_config.py" + }, + { + "from": "skills/core-tools/bmad/scripts/detect_env.py", + "to": "_bmad/scripts/detect_env.py" + }, + { + "from": "evals/core-tools/bmad-customize/files/config.toml", + "to": "_bmad/config.toml" + }, + { + "from": "evals/core-tools/bmad-customize/files/custom.gitignore", + "to": "_bmad/custom/.gitignore" + }, + { + "from": "evals/core-tools/bmad-customize/files/api-standards.md", + "to": "docs/api-standards.md" + } + ], + "rubric": [ + "No new customization file (bmad-review.toml, bmad-review.user.toml, rules.toml, rules.user.toml, config.toml, config.user.toml) exists under _bmad/custom/", + "_bmad/config.toml is byte-identical to the initial fixture", + "The transcript shows inspecting bmad-review/customize.toml", + "The final reply states plainly that bmad-review does not expose a max_parallel_gpu_workers field without inventing one, and offers supported alternatives such as persistent_facts, activation_steps_prepend/append, or building/extending a custom skill with bmad-toolsmith" + ] + } +] diff --git a/evals/core-tools/bmad-customize/files/api-standards.md b/evals/core-tools/bmad-customize/files/api-standards.md new file mode 100644 index 0000000000..b2fe441c3d --- /dev/null +++ b/evals/core-tools/bmad-customize/files/api-standards.md @@ -0,0 +1,4 @@ +# API Standards + +- All public REST endpoints must return RFC 7807 Problem Details on error. +- Breaking API changes require a version bump and migration note. diff --git a/evals/core-tools/bmad-customize/files/config.toml b/evals/core-tools/bmad-customize/files/config.toml new file mode 100644 index 0000000000..c6bd07709d --- /dev/null +++ b/evals/core-tools/bmad-customize/files/config.toml @@ -0,0 +1,7 @@ +[core] +project_name = "acme-platform" +output_folder = "{project-root}/_bmad-output" +active_initiative = "default" + +[modules.method] +repo_topology = "monorepo" diff --git a/evals/core-tools/bmad-customize/files/custom.gitignore b/evals/core-tools/bmad-customize/files/custom.gitignore new file mode 100644 index 0000000000..42d7bc6332 --- /dev/null +++ b/evals/core-tools/bmad-customize/files/custom.gitignore @@ -0,0 +1 @@ +*.user.toml diff --git a/skills/core-tools/bmad-customize/SKILL.md b/skills/core-tools/bmad-customize/SKILL.md index acb9a1dd6a..8d8d7d4471 100644 --- a/skills/core-tools/bmad-customize/SKILL.md +++ b/skills/core-tools/bmad-customize/SKILL.md @@ -1,6 +1,6 @@ --- name: bmad-customize -description: Authors and updates customization overrides, cross-skill rules, central and module settings, and facilitation templates under _bmad/custom/. Use when the user asks to customize bmad, override a skill, apply a cross-skill rule, change central or module settings in config.toml or config.user.toml, or tailor what a facilitation template (such as a PRD, deck, or brief) coaches, contains, or renders. +description: 'Authors and edits customization overrides, cross-skill rules, central and module settings, and facilitation templates under _bmad/custom/. Use when the user asks to customize bmad, override a skill, apply a cross-skill rule, override settings in config.toml or config.user.toml, inspect customizable options, reset overrides, or extend an existing facilitation template (such as a PRD, deck, or brief). Not for initial BMad setup, installing or updating modules (use bmad), authoring new documents (use bmad-facilitate), or building new custom skills (use bmad-toolsmith).' --- # BMad Customize From 2867fb8ccb87d321a643c34094dd1bc567dd08f9 Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 20:51:56 -0600 Subject: [PATCH 6/8] feat(bmad): add polyrepo workspace linking, root stacking, and no-_bmad degradation Add pure-Python `git config bmad.workspace` discovery across repos, linked worktrees, and submodules with exact git-config escaping/line continuation and diagnostic reporting; stack workspace-to-repo central and skill customization layers with per-layer `{project-root}` / `file:` and relative path anchoring plus `core.standalone = true` and `--no-workspace` isolation; keep `setup.py` workspace-aware for shared `output_folder` and answered module questions; enforce cross-boundary write safety for mutating setup and onboarding CLI calls; update `tickets.py` (with `--no-workspace`), `read_store.py`, and `eval_common.py` for workspace-linked and stacked stores; fix non-`_bmad` fallbacks in `resolve_personas.py` and `resolve_party.py`; and document multi-repo, worktree, standalone, and harness skill-discovery topologies with comprehensive test coverage. --- docs/customize/adopt-bmad-across-a-team.md | 17 + docs/reference/configuration.md | 33 +- .../scripts/resolve_personas.py | 15 +- .../bmad-party-mode/scripts/resolve_party.py | 15 +- skills/core-tools/bmad/references/setup.md | 3 +- .../core-tools/bmad/scripts/config_utils.py | 530 +++++++++- .../core-tools/bmad/scripts/render_skill.py | 49 +- .../core-tools/bmad/scripts/resolve_config.py | 20 +- .../bmad/scripts/resolve_customization.py | 18 +- skills/core-tools/bmad/scripts/setup.py | 101 +- .../core-tools/bmad/scripts/startup_check.py | 15 +- .../bmod-core-tools/help/team-adoption.md | 15 +- .../bmad-agent-po/scripts/read_store.py | 55 +- skills/method/bmod-method/scripts/tickets.py | 425 +++++++- .../bmad-eval/scripts/eval_common.py | 209 +++- tests/core-tools/bmad/test_detect_env.py | 2 +- .../test_story17_polyrepo_and_degradation.py | 958 ++++++++++++++++++ .../bmad/test_worktree_root_discovery.py | 27 +- 18 files changed, 2404 insertions(+), 103 deletions(-) create mode 100644 tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py diff --git a/docs/customize/adopt-bmad-across-a-team.md b/docs/customize/adopt-bmad-across-a-team.md index 29f47ca457..fb94342733 100644 --- a/docs/customize/adopt-bmad-across-a-team.md +++ b/docs/customize/adopt-bmad-across-a-team.md @@ -135,6 +135,23 @@ BMad customizations load when a BMad skill runs. For short, universal rules that | Workflow or template customization | One workflow or one document type | Review depth, required sections, editorial standards, publishing hooks | | Shared project config (`bmad setup`) | Whole project | Output folder, design system, and module setup answers | +## Multi-Repo and Worktree Topologies + +You can organize `_bmad/` and your installed skills to fit single-repo or multi-repo projects on any AI harness: + +| Topology | Where `_bmad/` and planning live | How each repo connects | +| --- | --- | --- | +| **Single repository** | `/_bmad/` and `/_bmad-output/` | Automatic upward discovery from anywhere inside the repo | +| **Shared-parent polyrepo** | `/_bmad/` and shared planning output (`_bmad-output/` or a dedicated folder such as `_bmad-obeya/`) above sibling repos | Sibling repos automatically inherit the parent workspace; a repo with its own `_bmad/` stacks team and personal overrides on top | +| **Scattered polyrepo** | `/_bmad/` in a separate folder (such as a dedicated planning repo) | Run `git config bmad.workspace ` in each linked repo (and optionally point workspace `core.output_folder` at `{project-root}/_bmad-obeya`) | +| **Out-of-tree worktrees** | Main checkout's `_bmad/` or linked `bmad.workspace` | Resolved automatically through `.git` `commondir`, reading main-checkout `*.user.toml` files read-only until worktree-local files exist | + +- **Per-repo opt-out:** Add `standalone = true` under `[core]` in a repo's `_bmad/config.toml` or `_bmad/custom/config*.toml` to keep workspace inheritance off for that repo, or pass `--no-workspace` to `resolve_config.py`, `resolve_customization.py`, `render_skill.py`, `tickets.py`, or `read_store.py`. +- **Where skills live (harness discovery):** Skills remain separate from `_bmad/` so they keep working even inside repositories where `bmad setup` has not been run yet. Some AI harnesses (such as Antigravity) stop skill discovery at a repository's `.git` boundary, so skills placed only in a shared-parent folder above sibling repos can be hidden when a session opens inside a child repo: + - **User-global install** (`~/.agents/skills/`, `~/.claude/skills/`, `~/.codex/skills/`, etc.) works everywhere across scattered repos, shared-parent repos, and worktrees regardless of `.git` boundaries. + - **Repo-local install** (`.claude/skills/`, `.agents/skills/`, `.agent/skills/`, `.cline/skills/`, `.codex/skills/`, `.cursor/skills/`, `.windsurf/skills/`) pins exact skill versions inside each repository when a harness stops at `.git` or clones are scattered. + - **Shared-parent install** only reaches child sessions on harnesses that walk past `.git` (or when sessions open at the shared workspace root itself). + ## Troubleshooting - When an override does not take effect, ask `bmad-customize` to inspect your overrides, or verify the file under `_bmad/custom/` matches the exact skill directory name (for example, `bmad-agent-dev.toml`, not `bmad-dev.toml`). diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index d060768973..a257598dc6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -23,7 +23,7 @@ If you want to know what can be tailored on a specific agent or skill, ask `"Hey ## Central Configuration Files -Project-wide setup answers, unasked module defaults, and shared overrides merge across four TOML layers, where higher-priority layers win when the same key appears in more than one place: +Project-wide setup answers, unasked module defaults, and shared overrides merge across four TOML layers in a single repository, where higher-priority layers win when the same key appears in more than one place: ```text Priority 1 (wins): _bmad/custom/config.user.toml (project personal overrides, gitignored) @@ -32,12 +32,15 @@ Priority 3: _bmad/config.toml (setup-owned project d Priority 4 (base): /bmod.toml [bmod.config_defaults] (shipped unasked module defaults) ``` -Running `bmad setup` writes prompted team answers and seeds `[bmod.config_defaults]` into `_bmad/config.toml` (and personal setup answers to `_bmad/custom/config.user.toml`) without overwriting existing keys; runtime resolution also falls back to `[bmod.config_defaults]` at Priority 4 if a key has not been written to `_bmad/config.toml` yet. Setup preserves your overrides under `_bmad/custom/` (only renaming a per-skill file if a retired skill moves to a new name), and `bmad-customize` edits `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` without mutating `_bmad/config.toml`. Inside a fresh linked worktree where gitignored personal `*.user.toml` files (`config.user.toml`, `rules.user.toml`, `.user.toml`) are absent locally, BMAD reads your main checkout's `*.user.toml` files read-only until you create a worktree-local file. +When a repository also inherits an outer workspace `_bmad/` directory, the workspace's team and personal layers stack beneath the repository's layers (see [Multi-Repo Workspaces, Worktrees, and Layer Stacking](#multi-repo-workspaces-worktrees-and-layer-stacking)). + +Running `bmad setup` writes prompted team answers and seeds `[bmod.config_defaults]` into `_bmad/config.toml` (and personal setup answers to `_bmad/custom/config.user.toml`) without overwriting existing keys; runtime resolution also falls back to `[bmod.config_defaults]` at the lowest priority if a key has not been written to `_bmad/config.toml` yet. Setup preserves your overrides under `_bmad/custom/` (only renaming a per-skill file if a retired skill moves to a new name), and `bmad-customize` edits `_bmad/custom/config.toml` or `_bmad/custom/config.user.toml` without mutating `_bmad/config.toml`. Inside a fresh linked worktree where gitignored personal `*.user.toml` files (`config.user.toml`, `rules.user.toml`, `.user.toml`) are absent locally, BMAD reads your main checkout's `*.user.toml` files read-only until you create a worktree-local file. | Setting | Scope | What it controls | | --- | --- | --- | | `core.output_folder` | Team | Root folder holding initiatives, standalone epics, `backlog/`, and run folders (defaults to `_bmad-output`; for a multi-repo workspace, setup recommends a shared folder such as `../_bmad-output`) | | `core.active_initiative` | Personal | Active initiative, standalone epic, or child initiative under a program | +| `core.standalone` | Team / Personal | Set to `true` in a repository's central config to ignore any outer parent or linked workspace `_bmad/` layer and resolve only that repository's own `_bmad/` | | `core.models` / `core.models.` | Personal | Ordered model preference lists per semantic tier (`quick`, `standard`, `deep`, optional `router` for System-1 decisioning/routing models such as Gemini Decision or Jev); entries may be plain model names or `{ model, tool }` tables for models delivered over a CLI or MCP; unlike generic list appends, a higher-priority layer or harness table replaces the list for that tier (and an explicit empty list `[]` clears it before fallback to `standard`, where empty `standard` means the active session model); tracks `seen_models` deltas per harness | | `core.capabilities` / `core.capabilities.` | Personal | Interactive harness flags (`subagents`, `inline_visuals`, `computer_use`, `browser_interaction`) with optional per-harness overrides | | `core.tooling` | Personal | Detected local CLIs (`clis`), deep-research MCPs/subscriptions (`deep_research`), media/visual tools (`media`), external doc/storage/hosting services (`external_services`), per-domain `preferred` picks, and `ignore` opt-outs | @@ -51,6 +54,32 @@ Running `bmad setup` writes prompted team answers and seeds `[bmod.config_defaul Custom modules you install add their own setup questions under `modules..`; see [Module Files](./module-files.md). +## Multi-Repo Workspaces, Worktrees, and Layer Stacking + +Read-only BMad config, customization, and ticket scripts discover `_bmad/` using the same three-phase lookup without requiring `--project-root` (mutating setup and onboarding commands stop at repository and worktree boundaries): + +1. **Walk up from the working directory** to the nearest folder containing `_bmad/` (covering single-repo and shared-parent polyrepo layouts). +2. **Follow linked git worktrees** via `.git` -> `gitdir` -> `commondir` back to the main checkout (preserving monorepo subdirectory offsets), then walk up from there. +3. **Follow local git workspace links** from `/config`'s `[bmad] workspace = ` (`git config bmad.workspace `), allowing scattered repositories and their linked worktrees to share one workspace `_bmad/`. Relative `bmad.workspace` paths resolve against the repository's main checkout root (use an absolute path for git submodules or non-standard `.git` layouts); BMad parses `[bmad]` directly in `/config` without following `[include]`, `includeIf`, or `config.worktree`. + +When both an outer workspace root and an inner repository define `_bmad/` (stacking at most one outer workspace root beneath the inner repo), `resolve_config.py`, `resolve_customization.py`, `render_skill.py`, `tickets.py`, and `read_store.py` merge seven layers in priority order: + +```text +Priority 1 (wins): /_bmad/custom/config.user.toml (repo personal overrides) +Priority 2: /_bmad/custom/config.user.toml (workspace personal overrides) +Priority 3: /_bmad/custom/config.toml (repo team overrides) +Priority 4: /_bmad/config.toml (repo setup defaults) +Priority 5: /_bmad/custom/config.toml (workspace team overrides) +Priority 6: /_bmad/config.toml (workspace setup defaults) +Priority 7 (base): /bmod.toml [bmod.config_defaults] (shipped unasked module defaults) +``` + +Outer workspace layers expand `{project-root}` and relative path fields against the workspace root rather than the inner repository. + +- **Isolating a standalone repo:** Set `core.standalone = true` in a repo's `_bmad/config.toml`, `_bmad/custom/config.toml`, or `config.user.toml` to disable workspace inheritance, or pass `--no-workspace` for one-off isolation on `resolve_config.py`, `resolve_customization.py`, `render_skill.py`, `tickets.py`, or `read_store.py`. +- **Write protection across boundaries:** Mutating setup and onboarding commands refuse to modify an outer parent workspace or linked `bmad.workspace` target unless you pass `--project-root ` explicitly. +- **Standalone skill degradation:** Skills and scripts work without any `_bmad/` folder by falling back to `{skill-root}` defaults when central state is optional, or exiting cleanly with a setup prompt when central workspace state is required. + ## Knowledge Sources and Artifact Destinations BMad splits external integrations cleanly by direction under `[core]` so teams and individuals do not have to repeat the same Confluence space, Notion workspace, Obsidian vault, sibling repo, or preview host in every skill: diff --git a/skills/core-tools/bmad-forge-idea/scripts/resolve_personas.py b/skills/core-tools/bmad-forge-idea/scripts/resolve_personas.py index 705b12d227..a657d64dc5 100644 --- a/skills/core-tools/bmad-forge-idea/scripts/resolve_personas.py +++ b/skills/core-tools/bmad-forge-idea/scripts/resolve_personas.py @@ -56,6 +56,9 @@ def _run_json(cmd): """Run a resolver script and parse its JSON stdout. None on any failure.""" global _last_error _last_error = "" + if len(cmd) >= 2 and not Path(cmd[1]).is_file(): + _last_error = f"shared script not found: {cmd[1]}" + return None try: out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=60) except (OSError, subprocess.SubprocessError) as exc: @@ -81,13 +84,21 @@ def _load_toml(path: Path): return {} +def _scripts_dir(project_root: Path, skill_root: Path) -> Path: + """Locate BMad shared scripts from `_bmad/scripts`, falling back to sibling `bmad/scripts` when `_bmad` is absent.""" + for candidate in (project_root / "_bmad" / "scripts", skill_root.parent / "bmad" / "scripts"): + if candidate.is_dir(): + return candidate + return project_root / "_bmad" / "scripts" + + def load_roster(project_root: Path, skill_root: Path): """(agents, guests, groups, resolved_ok) from the skills installed beside this one. agents are {code: entry} for the default room. guests are the other roster members, available by name or through a group, as in party mode. """ - scripts = project_root / "_bmad" / "scripts" + scripts = _scripts_dir(project_root, skill_root) data = _run_json( [sys.executable, str(scripts / "roster.py"), "--skill", str(skill_root), "--project-root", str(project_root)] ) @@ -152,7 +163,7 @@ def find_party_skill(project_root: Path, skill_root: Path): def load_party_workflow(project_root: Path, party_skill: Path): """Merged [workflow] table for bmad-party-mode (base + user overrides).""" - resolver = project_root / "_bmad" / "scripts" / "resolve_customization.py" + resolver = _scripts_dir(project_root, party_skill) / "resolve_customization.py" data = _run_json( [ sys.executable, diff --git a/skills/core-tools/bmad-party-mode/scripts/resolve_party.py b/skills/core-tools/bmad-party-mode/scripts/resolve_party.py index c4b6f96b11..ea7d5f22e6 100644 --- a/skills/core-tools/bmad-party-mode/scripts/resolve_party.py +++ b/skills/core-tools/bmad-party-mode/scripts/resolve_party.py @@ -56,6 +56,9 @@ def _run_json(cmd): """Run a resolver script and parse its JSON stdout. None on any failure.""" global _last_error _last_error = "" + if len(cmd) >= 2 and not Path(cmd[1]).is_file(): + _last_error = f"shared script not found: {cmd[1]}" + return None try: out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=60) except (OSError, subprocess.SubprocessError) as exc: @@ -71,6 +74,14 @@ def _run_json(cmd): return None +def _scripts_dir(project_root: Path, skill_root: Path) -> Path: + """Locate BMad shared scripts from `_bmad/scripts`, falling back to sibling `bmad/scripts` when `_bmad` is absent.""" + for candidate in (project_root / "_bmad" / "scripts", skill_root.parent / "bmad" / "scripts"): + if candidate.is_dir(): + return candidate + return project_root / "_bmad" / "scripts" + + def load_roster(project_root: Path, skill_root: Path): """(agents, guests, groups, resolved, problems) from the skills installed beside this one. @@ -78,7 +89,7 @@ def load_roster(project_root: Path, skill_root: Path): that are not installed agents, available to groups only. problems are what roster.py could not use, so a missing agent or room is explained. """ - scripts = project_root / "_bmad" / "scripts" + scripts = _scripts_dir(project_root, skill_root) data = _run_json( [sys.executable, str(scripts / "roster.py"), "--skill", str(skill_root), "--project-root", str(project_root)] ) @@ -106,7 +117,7 @@ def merge_groups(roster_groups: list, custom_groups: list) -> list: def load_workflow(project_root: Path, skill_root: Path, *, strict: bool = False): """Merged [workflow] table. Falls back to the skill's base customize.toml unless strict.""" - script = project_root / "_bmad" / "scripts" / "resolve_customization.py" + script = _scripts_dir(project_root, skill_root) / "resolve_customization.py" data = _run_json( [ sys.executable, diff --git a/skills/core-tools/bmad/references/setup.md b/skills/core-tools/bmad/references/setup.md index 5f30fad5a5..cb93fd0ac4 100644 --- a/skills/core-tools/bmad/references/setup.md +++ b/skills/core-tools/bmad/references/setup.md @@ -22,6 +22,7 @@ Run with `--status`; it writes nothing. On a first install (`bmad_exists` false) - `absent_skills` are skills the user opted out of or that are new to the module, and `unmet_recommendations` are suggested additions. Both are optional, not faults. - `newer-available` and `pinned` updates include a clickable `changelog_url` when available — show it beside the version jump so the user knows what changed. - `scope_warning`: project and global BMad installs are mixed, which causes partial updates and shadowing; surface the warning clearly. +- `workspace_link`: when present with `status` other than `"ok"`, warn that `git config bmad.workspace` points to a missing, unreadable, or uninitialized workspace target. - `plugin-managed`: relay its `instruction`; the plugin updates the module. - `pinned`: the install is held at a tag, so `npx skills update` cannot raise it. Relay its `instruction`; run its `install` only if the user wants the newer version. - `unknown-version`: the installed copy predates module records; `npx skills update` fixes it. @@ -73,7 +74,7 @@ If `not_removed` is non-empty, `--clean` exits 1 with the JSON report: show the **Migrations.** Do steps 1 and 2 of `references/migrate.md`, Find and Match. Name each that applies with its `title`, `from` and `to`, and ask; on yes, continue with its steps 3 and 4. -**Answers.** On a first install, note `core.output_folder` (keep `{project-root}/_bmad-output` for a single repo; for multi-repo or polyrepo, recommend a shared folder such as `../_bmad-output` or an existing sibling output folder and offer to set it). When the user asks to view or change saved settings, show the relevant `answers` (including `core.project_name`, `core.output_folder`, and module defaults/answers with each value and file) and edit `core.` or `modules..` in that file on confirmation. +**Answers.** On a first install, or when the user asks to view or change saved settings, show the relevant `answers` from the setup run (including `core.project_name`, `core.output_folder`, and module defaults/answers, each with its value and file) and offer to change any. On a first install, note that planning output goes to `core.output_folder`. Keep `{project-root}/_bmad-output` for a single repo; when an answer says the workspace is one of several repos (multi-repo, polyrepo), recommend putting shared config and output in a common parent workspace folder or linking scattered repos with `git config bmad.workspace ` (or keeping a shared `../_bmad-output` sibling folder), and note that `core.standalone = true` disables outer workspace inheritance for a repo when needed. Edit `core.` or `modules..` in that file on confirmation. **Models, capabilities, tooling, sources, and destinations.** Run `uv run --no-cache "{skill-root}/scripts/detect_env.py" scan --project-root "{project-root}"`, adding each `--root ""` (and `--harness ""` when known). It detects local CLIs, installed tool skills, and whether `[core.models]` / `[core.capabilities]` are already saved in this project. diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 6d64fd69c5..467f156510 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -53,6 +53,7 @@ class ConfigError(ValueError): "project_name", "output_folder", "active_initiative", + "standalone", "models", "capabilities", "tooling", @@ -71,7 +72,7 @@ class ConfigError(ValueError): } ) _SKIP = object() -_FILE_REF_RE = re.compile(r"(?:^|\s)file:([^\s,;'\")]+)") +_FILE_REF_RE = re.compile(r'(?:^|\s)file:(?:"([^"]+)"|([^\s,;\'")]+))') _RULE_ENTRY_FIELDS = frozenset({"id", "match", "surface", "agent", "workflow"}) _RULE_SURFACES = ("agent", "workflow") MODEL_TIERS = ("quick", "standard", "deep", "router") @@ -280,8 +281,8 @@ def find_local_bmad_root(start: Path | None = None, *, stop_at: Path | None = No return None -def find_project_root(start: Path | None = None, *, fallback_to_git: bool = False) -> Path | None: - """Two-phase `_bmad/` project-root discovery: cwd walk-up first, then linked-worktree `commondir` fallback.""" +def find_git_repo_root(start: Path | None = None) -> Path | None: + """Return the nearest ancestor directory holding a `.git` directory or file.""" try: base = Path.cwd() if start is None else start except OSError: @@ -291,13 +292,305 @@ def find_project_root(start: Path | None = None, *, fallback_to_git: bool = Fals return None if _safe_is_file(current): current = current.parent + for candidate in (current, *current.parents): + git_entry = candidate / ".git" + if _safe_exists(git_entry) or _safe_is_symlink(git_entry): + return candidate + return None + + +def _logical_git_config_lines(text: str) -> list[str]: + """Join backslash-continued git-config lines while keeping `#`/`;` comments unjoined.""" + logical: list[str] = [] + pending: list[str] = [] + in_quotes = False + for raw_line in text.splitlines(): + line = raw_line[:-1] if raw_line.endswith("\r") else raw_line + in_comment = False + escaped_eol = False + i = 0 + n = len(line) + while i < n: + ch = line[i] + if in_quotes: + if ch == "\\": + if i + 1 < n: + i += 2 + continue + escaped_eol = True + break + if ch == '"': + in_quotes = False + i += 1 + continue + if ch in ("#", ";"): + in_comment = True + break + if ch == '"': + in_quotes = True + i += 1 + continue + if ch == "\\": + if i + 1 < n: + i += 2 + continue + escaped_eol = True + break + i += 1 + if escaped_eol and not in_comment: + pending.append(line[:-1]) + continue + pending.append(line) + logical.append("".join(pending)) + pending.clear() + in_quotes = False + if pending: + logical.append("".join(pending)) + return logical + + +def _strip_git_config_inline_comment_and_unquote(raw: str) -> str: + """Decode a git-config value, preserving quoted spaces and escapes in/outside quotes.""" + out: list[str] = [] + escapes = {"n": "\n", "t": "\t", "b": "\b"} + in_quotes = False + seen_content = False + last_significant = 0 + i = 0 + n = len(raw) + while i < n: + ch = raw[i] + if in_quotes: + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + out.append(escapes.get(nxt, nxt)) + i += 2 + elif ch == '"': + in_quotes = False + i += 1 + else: + out.append(ch) + i += 1 + seen_content = True + last_significant = len(out) + continue + if ch in ("#", ";"): + break + if ch == '"': + in_quotes = True + seen_content = True + i += 1 + continue + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + out.append(escapes.get(nxt, nxt)) + seen_content = True + last_significant = len(out) + i += 2 + continue + if ch in (" ", "\t"): + if seen_content: + out.append(ch) + i += 1 + continue + out.append(ch) + seen_content = True + last_significant = len(out) + i += 1 + return "".join(out[:last_significant]) + + +def _read_raw_git_config_bmad_workspace(config_path: Path) -> str | None: + """Pure-Python INI reader for local git config `[bmad] workspace = ...` (no subprocesses).""" + if not _safe_is_file(config_path): + return None + try: + text = config_path.read_text(encoding="utf-8-sig") + except (OSError, UnicodeError): + return None + in_bmad = False + found: str | None = None + for raw_line in _logical_git_config_lines(text): + stripped = raw_line.strip() + if not stripped or stripped[0] in ("#", ";"): + continue + if stripped.startswith("["): + end = stripped.find("]") + if end == -1: + in_bmad = False + continue + header = stripped[1:end].strip() + in_bmad = header.lower() == "bmad" + # Handle optional `[bmad] workspace = ...` trailing assignment on the header line cleanly. + remainder = stripped[end + 1 :].strip() + if not remainder or remainder[0] in ("#", ";"): + continue + stripped = remainder + if not in_bmad: + continue + if "=" in stripped: + key_part, val_part = stripped.split("=", 1) + if key_part.strip().lower() != "workspace": + continue + found = _strip_git_config_inline_comment_and_unquote(val_part) + continue + bare_key = stripped.split("#", 1)[0].split(";", 1)[0].strip().lower() + if bare_key == "workspace": + found = "" + return found + + +def _find_git_common_dir(start: Path | None = None) -> tuple[Path, Path] | None: + """Return `(repo_root, common_git_dir)` for standard repos, linked worktrees, or linked submodules.""" + try: + base = Path.cwd() if start is None else start + except OSError: + return None + current = _safe_resolve(base) + if current is None: + return None + if _safe_is_file(current): + current = current.parent + + for candidate in (current, *current.parents): + git_entry = candidate / ".git" + if _safe_is_dir(git_entry): + resolved_git = _safe_resolve(git_entry) + return (candidate, resolved_git) if resolved_git is not None else None + if not _safe_is_file(git_entry): + continue + first_line = _first_nonempty_line(git_entry) + if not first_line or not first_line.startswith("gitdir:"): + continue + raw_gitdir = first_line[len("gitdir:") :].strip() + if not raw_gitdir: + continue + gitdir_candidate = Path(raw_gitdir) + if not gitdir_candidate.is_absolute(): + gitdir_candidate = candidate / gitdir_candidate + gitdir = _safe_resolve(gitdir_candidate) + if gitdir is None: + continue + commondir_file = gitdir / "commondir" + if _safe_is_file(commondir_file): + raw_common = _first_nonempty_line(commondir_file) + if not raw_common: + continue + common_candidate = Path(raw_common) + if not common_candidate.is_absolute(): + common_candidate = gitdir / common_candidate + common = _safe_resolve(common_candidate) + if common is not None and _safe_is_dir(common): + return candidate, common + continue + if _read_raw_git_config_bmad_workspace(gitdir / "config") is not None: + return candidate, gitdir + return None + + +def _resolve_workspace_link(start: Path | None = None) -> tuple[Path | None, dict[str, Any] | None]: + """Resolve `git config bmad.workspace` from the repository's common git config without spawning git.""" + git_info = _find_git_common_dir(start) + if git_info is None: + return None, None + _repo_root, common_git_dir = git_info + config_path = common_git_dir / "config" + raw = _read_raw_git_config_bmad_workspace(config_path) + if raw is None: + return None, None + if not raw or "\x00" in raw or "\n" in raw or "\r" in raw: + return None, {"status": "invalid", "raw": raw, "config": str(config_path)} + + candidate = Path(raw) + if not candidate.is_absolute(): + candidate = common_git_dir.parent / candidate + resolved = _safe_resolve(candidate) + target = resolved if resolved is not None else Path(os.path.normpath(str(candidate))) + + try: + st = target.stat() + except FileNotFoundError: + return None, {"status": "missing", "raw": raw, "resolved": str(target), "config": str(config_path)} + except OSError as error: + return None, { + "status": "unreadable", + "raw": raw, + "resolved": str(target), + "config": str(config_path), + "error": str(error), + } + if not stat.S_ISDIR(st.st_mode): + return None, {"status": "not_dir", "raw": raw, "resolved": str(target), "config": str(config_path)} + + if target.name == "_bmad": + ws_root = target.parent + bmad_dir = target + else: + ws_root = target + bmad_dir = ws_root / "_bmad" + + try: + bmad_st = bmad_dir.stat() + except FileNotFoundError: + return None, { + "status": "missing_bmad", + "raw": raw, + "resolved": str(ws_root), + "config": str(config_path), + } + except OSError as error: + return None, { + "status": "unreadable", + "raw": raw, + "resolved": str(ws_root), + "config": str(config_path), + "error": str(error), + } + if not stat.S_ISDIR(bmad_st.st_mode): + return None, {"status": "missing_bmad", "raw": raw, "resolved": str(ws_root), "config": str(config_path)} + + final_root = _safe_resolve(ws_root) or ws_root + return final_root, {"status": "ok", "raw": raw, "resolved": str(final_root), "config": str(config_path)} + + +def find_linked_workspace_root(start: Path | None = None) -> Path | None: + """Return the linked BMad workspace root from local `git config bmad.workspace`, if valid.""" + ws_root, _diag = _resolve_workspace_link(start) + return ws_root + +def workspace_link_diagnostics(start: Path | None = None) -> dict[str, Any] | None: + """Return status metadata for local `git config bmad.workspace`, or `None` when unconfigured.""" + _ws_root, diag = _resolve_workspace_link(start) + return diag + + +def find_project_root( + start: Path | None = None, + *, + fallback_to_git: bool = False, + include_workspace: bool = True, +) -> Path | None: + """Three-phase `_bmad/` discovery: cwd walk-up, linked-worktree `commondir`, then `bmad.workspace`.""" + try: + base = Path.cwd() if start is None else start + except OSError: + return None + current = _safe_resolve(base) + if current is None: + return None + if _safe_is_file(current): + current = current.parent + + stop_at = (find_worktree_boundary(current) or find_git_repo_root(current)) if not include_workspace else None git_root: Path | None = None for candidate in (current, *current.parents): if _safe_is_dir(candidate / "_bmad"): return candidate if fallback_to_git and git_root is None and _safe_exists(candidate / ".git"): git_root = candidate + if stop_at is not None and candidate == stop_at: + break roots = _find_worktree_roots(current) if roots is not None: @@ -310,10 +603,68 @@ def find_project_root(start: Path | None = None, *, fallback_to_git: bool = Fals for candidate in (search_start, *search_start.parents): if _safe_is_dir(candidate / "_bmad"): return candidate + if not include_workspace and candidate == main_root: + break + + if include_workspace: + linked_ws = find_linked_workspace_root(current) + if linked_ws is not None: + return linked_ws return git_root if fallback_to_git else None +def find_outer_workspace_root(project_root: Path, *, fallback_start: Path | None = None) -> Path | None: + """Return the outer workspace `_bmad/` root inherited by `project_root`, or `None`.""" + resolved = _safe_resolve(project_root) + if resolved is None: + return None + if _safe_is_dir(resolved / "_bmad") and is_standalone(resolved): + return None + + linked = find_linked_workspace_root(resolved) or ( + find_linked_workspace_root(fallback_start) if fallback_start is not None else None + ) + if linked is not None and linked != resolved: + return linked + for parent in resolved.parents: + if _safe_is_dir(parent / "_bmad"): + return parent + counterpart = _worktree_counterpart_root(resolved) + if counterpart is not None: + for parent in counterpart.parents: + if _safe_is_dir(parent / "_bmad"): + return parent + return None + + +def is_standalone(project_root: Path) -> bool: + """Return True when `core.standalone = true` is set in central config layers for `project_root`.""" + bmad_dir = project_root / "_bmad" + merged = merge_layers( + ( + load_toml(bmad_dir / "config.toml"), + load_toml(project_team_config_path(project_root)), + _user_layer_for_root(project_root), + ) + ) + core = merged.get("core") + return isinstance(core, dict) and core.get("standalone") is True + + +def find_bmad_roots(start: Path | None = None, *, include_workspace: bool = True) -> tuple[Path, ...]: + """Return ordered `_bmad/` roots (`(workspace_root, repo_root)` or `(single_root,)` or `()`).""" + inner = find_project_root(start, include_workspace=include_workspace) + if inner is None: + return () + if not include_workspace or is_standalone(inner): + return (inner,) + outer = find_outer_workspace_root(inner, fallback_start=start) + if outer is not None and outer != inner: + return (outer, inner) + return (inner,) + + def _extract_project_relative(raw: str) -> str | None: """Extract a project-relative path suffix when `raw` is relative or `{project-root}/...`.""" cleaned = raw.strip() @@ -670,6 +1021,90 @@ def _user_layer_for_root(project_root: Path) -> dict[str, Any]: return _load_personal_custom_toml(project_root, "config.user.toml") +def _anchor_single_path(raw: str, root: Path) -> str: + cleaned = raw.strip() + if not cleaned: + return raw + if "{project-root}" in cleaned: + return raw.replace("{project-root}", root.as_posix()) + if cleaned.startswith("~") or "://" in cleaned or cleaned.startswith("{"): + return raw + if Path(cleaned).is_absolute(): + return raw + return Path(os.path.normpath(str(root / cleaned))).as_posix() + + +def _anchor_layer_paths(layer: dict[str, Any], root: Path) -> dict[str, Any]: + """Expand `{project-root}` and relative path fields on an outer layer against its own `root`.""" + resolved_root = _safe_resolve(root) or root + + def _walk( + node: Any, + path_parts: tuple[str, ...] = (), + *, + parent_table: dict[str, Any] | None = None, + is_path: bool = False, + ) -> Any: + if isinstance(node, dict): + return { + k: _walk( + v, (*path_parts, str(k)), parent_table=node, is_path=is_path_field((*path_parts, str(k)), node) + ) + for k, v in node.items() + } + if isinstance(node, list): + return [_walk(item, path_parts, parent_table=parent_table, is_path=is_path) for item in node] + if isinstance(node, str) and (is_path or "{project-root}" in node): + return _anchor_single_path(node, resolved_root) + return node + + return _walk(layer) + + +def _anchor_customization_file_refs(layer: dict[str, Any], root: Path) -> dict[str, Any]: + """Rewrite relative or `{project-root}` `file:` refs in an outer workspace customization layer against `root`.""" + resolved_root = _safe_resolve(root) or root + + def _rewrite_str(text: str) -> str: + def _sub(match: re.Match[str]) -> str: + quoted = match.group(1) + raw_target = quoted if quoted is not None else match.group(2) + stripped_tail = raw_target if quoted is not None else raw_target.rstrip(".,;:)") + trailing = "" if quoted is not None else raw_target[len(stripped_tail) :] + if not stripped_tail: + return match.group(0) + if stripped_tail.startswith("{project-root}/"): + rel = stripped_tail[len("{project-root}/") :] + anchored = ( + Path(os.path.normpath(str(resolved_root / rel))).as_posix() if rel else resolved_root.as_posix() + ) + elif stripped_tail.startswith("{project-root}\\"): + rel = stripped_tail[len("{project-root}\\") :] + anchored = ( + Path(os.path.normpath(str(resolved_root / rel))).as_posix() if rel else resolved_root.as_posix() + ) + elif stripped_tail.startswith(("{", "~")) or Path(stripped_tail).is_absolute(): + return match.group(0) + else: + anchored = Path(os.path.normpath(str(resolved_root / stripped_tail))).as_posix() + prefix_ws = match.group(0)[: match.group(0).index("file:")] + formatted = f'file:"{anchored}"' if any(ch.isspace() for ch in anchored) else f"file:{anchored}" + return f"{prefix_ws}{formatted}{trailing}" + + return _FILE_REF_RE.sub(_sub, text) + + def _walk(node: Any) -> Any: + if isinstance(node, dict): + return {k: _walk(v) for k, v in node.items()} + if isinstance(node, list): + return [_walk(item) for item in node] + if isinstance(node, str) and "file:" in node: + return _rewrite_str(node) + return node + + return _walk(layer) + + def central_config_layers_for_roots( project_roots: Iterable[Path], *, @@ -690,12 +1125,18 @@ def central_config_layers_for_roots( defaults_layer = load_module_defaults(skill_roots, project_roots=roots) if defaults_layer: layers.append(defaults_layer) + anchor_outer = len(roots) > 1 + inner_root = roots[-1] if roots else None for root in roots: bmad_dir = root / "_bmad" - layers.append(load_toml(bmad_dir / "config.toml", required=require_project)) - layers.append(load_toml(bmad_dir / "custom" / "config.toml")) + for layer in ( + load_toml(bmad_dir / "config.toml", required=require_project and root == inner_root), + load_toml(bmad_dir / "custom" / "config.toml"), + ): + layers.append(_anchor_layer_paths(layer, root) if anchor_outer and root != inner_root else layer) for root in roots: - layers.append(_user_layer_for_root(root)) + layer = _user_layer_for_root(root) + layers.append(_anchor_layer_paths(layer, root) if anchor_outer and root != inner_root else layer) return tuple(layers) @@ -969,14 +1410,24 @@ def load_customization_for_roots(project_roots: Iterable[Path], skill_dir: Path) skill_name = skill_dir.name defaults = load_toml(skill_dir / "customize.toml", required=True) layers: list[dict[str, Any]] = [defaults] + anchor_outer = len(roots) > 1 + inner_root = roots[-1] if roots else None for root in roots: custom_dir = root / "_bmad" / "custom" - layers.extend(_matching_rule_layers_for_file(custom_dir / "rules.toml", skill_name, defaults)) - layers.append(load_toml(custom_dir / f"{skill_name}.toml")) + for layer in ( + *_matching_rule_layers_for_file(custom_dir / "rules.toml", skill_name, defaults), + load_toml(custom_dir / f"{skill_name}.toml"), + ): + layers.append( + _anchor_layer_paths(_anchor_customization_file_refs(layer, root), root) + if anchor_outer and root != inner_root + else layer + ) for root in roots: rules_user_path, rules_is_fallback = _resolve_personal_custom_file(root, "rules.user.toml") + root_user_layers: list[dict[str, Any]] = [] if rules_user_path is not None: - layers.extend( + root_user_layers.extend( _matching_rule_layers_for_file( rules_user_path, skill_name, @@ -984,7 +1435,13 @@ def load_customization_for_roots(project_roots: Iterable[Path], skill_dir: Path) cross_boundary=rules_is_fallback, ) ) - layers.append(_load_personal_custom_toml(root, f"{skill_name}.user.toml")) + root_user_layers.append(_load_personal_custom_toml(root, f"{skill_name}.user.toml")) + for layer in root_user_layers: + layers.append( + _anchor_layer_paths(_anchor_customization_file_refs(layer, root), root) + if anchor_outer and root != inner_root + else layer + ) merged = merge_layers(layers) return apply_worktree_path_fallbacks(merged, roots[-1]) if roots else merged @@ -997,7 +1454,8 @@ def _extract_concrete_file_refs(value: Any) -> list[str]: refs: list[str] = [] if isinstance(value, str): for match in _FILE_REF_RE.finditer(value): - target = match.group(1).strip().rstrip(".,;:)") + quoted = match.group(1) + target = quoted.strip() if quoted is not None else match.group(2).strip().rstrip(".,;:)") if target.startswith("{project-root}/"): target = target[len("{project-root}/") :] elif target.startswith("{project-root}\\"): @@ -1380,8 +1838,36 @@ def check_central_config( errors.append({"kind": "invalid-toml", "file": str(setup_cfg), "key": "", "message": str(error)}) continue setup_core = setup_data.get("core") - if isinstance(setup_core, dict): + if setup_core is not None and not isinstance(setup_core, dict): + errors.append( + { + "kind": "type-mismatch", + "file": str(setup_cfg), + "key": "core", + "message": f"`core` must be a table, got {type(setup_core).__name__}", + } + ) + elif isinstance(setup_core, dict): setup_core_keys.update(str(k) for k in setup_core) + for key, value in setup_core.items(): + if key in ("project_name", "output_folder", "active_initiative") and not isinstance(value, str): + errors.append( + { + "kind": "type-mismatch", + "file": str(setup_cfg), + "key": f"core.{key}", + "message": f"`core.{key}` must be a string, got {type(value).__name__}", + } + ) + elif key == "standalone" and not isinstance(value, bool): + errors.append( + { + "kind": "type-mismatch", + "file": str(setup_cfg), + "key": f"core.{key}", + "message": f"`core.{key}` must be a bool, got {type(value).__name__}", + } + ) setup_mods = setup_data.get("modules") if isinstance(setup_mods, dict): for code, mod_table in setup_mods.items(): @@ -1449,6 +1935,15 @@ def check_central_config( "message": f"`core.{key}` must be a string, got {type(value).__name__}", } ) + elif key == "standalone" and not isinstance(value, bool): + errors.append( + { + "kind": "type-mismatch", + "file": str(path), + "key": f"core.{key}", + "message": f"`core.{key}` must be a bool, got {type(value).__name__}", + } + ) if "modules" in data: mods_table = data["modules"] if not isinstance(mods_table, dict): @@ -1591,6 +2086,17 @@ def check_central_config( } ) + link_diag = workspace_link_diagnostics(roots[-1]) + if link_diag is not None and link_diag.get("status") != "ok": + warnings.append( + { + "kind": "broken-workspace-link", + "file": str(link_diag.get("config", "")), + "key": "bmad.workspace", + "message": f"git config bmad.workspace target is unusable ({link_diag.get('status')}): {link_diag.get('raw', '')}", + } + ) + return { "ok": len(errors) == 0, "checked_files": checked_files, diff --git a/skills/core-tools/bmad/scripts/render_skill.py b/skills/core-tools/bmad/scripts/render_skill.py index 608e365d12..b3880a9bd2 100644 --- a/skills/core-tools/bmad/scripts/render_skill.py +++ b/skills/core-tools/bmad/scripts/render_skill.py @@ -16,7 +16,7 @@ import stat import sys import tomllib -from collections.abc import Callable +from collections.abc import Callable, Iterable from datetime import date, time from pathlib import Path from typing import Any @@ -28,12 +28,15 @@ from config_utils import ( # noqa: E402 ConfigError, + apply_worktree_path_fallbacks, + central_config_layers_for_roots, discover_default_skill_roots, + find_bmad_roots, find_project_root, is_path_field, - load_central_config, - load_customization, + load_customization_for_roots, load_toml, + merge_layers, resolve_worktree_path_fallback, structural_merge, ) @@ -133,13 +136,17 @@ def _declares(defaults: dict[str, Any], path: str) -> bool: return True -def _check_persistent_layers(project_root: Path, skill_dir: Path, defaults: dict[str, Any] | None) -> None: +def _check_persistent_layers( + project_roots: Iterable[Path] | Path, skill_dir: Path, defaults: dict[str, Any] | None +) -> None: """A persistent override may only set keys the skill declares; a stale or misspelled key halts.""" - custom_dir = project_root / "_bmad" / "custom" - for layer in (custom_dir / f"{skill_dir.name}.toml", custom_dir / f"{skill_dir.name}.user.toml"): - undeclared = sorted(path for path in _leaf_paths(load_toml(layer)) if not _declares(defaults or {}, path)) - if undeclared: - raise RenderError(f"{layer} sets keys {skill_dir.name} does not declare: {', '.join(undeclared)}") + roots = (project_roots,) if isinstance(project_roots, Path) else tuple(project_roots) + for root in roots: + custom_dir = root / "_bmad" / "custom" + for layer in (custom_dir / f"{skill_dir.name}.toml", custom_dir / f"{skill_dir.name}.user.toml"): + undeclared = sorted(path for path in _leaf_paths(load_toml(layer)) if not _declares(defaults or {}, path)) + if undeclared: + raise RenderError(f"{layer} sets keys {skill_dir.name} does not declare: {', '.join(undeclared)}") def _lookup(data: dict[str, Any], dotted_path: str, label: str) -> Any: @@ -700,6 +707,7 @@ def render( overrides: Path | None = None, assignments: list[str] | None = None, skill_roots: tuple[Path, ...] = (), + include_workspace: bool = True, ) -> Path: project_root = project_root.resolve(strict=True) skill_dir = skill_dir.resolve(strict=True) @@ -708,15 +716,18 @@ def render( sources = _load_sources(skill_dir) assets = _load_assets(skill_dir) - discovered = tuple(discover_default_skill_roots((project_root,))) if not skill_roots else () + roots = (project_root,) if not include_workspace else (find_bmad_roots(project_root) or (project_root,)) + effective_root = roots[-1] + discovered = tuple(discover_default_skill_roots(roots)) if not skill_roots else () effective_skill_roots = tuple( dict.fromkeys((*(root.resolve() for root in skill_roots), *discovered, skill_dir.parent)) ) - central = load_central_config(project_root, skill_roots=effective_skill_roots) + central_layers = central_config_layers_for_roots(roots, require_project=True, skill_roots=effective_skill_roots) + central = apply_worktree_path_fallbacks(merge_layers(central_layers), effective_root) has_customization = bool(overrides is not None or assignments) or (skill_dir / "customize.toml").is_file() defaults = load_toml(skill_dir / "customize.toml", required=True) if has_customization else None - _check_persistent_layers(project_root, skill_dir, defaults) - customization = load_customization(project_root, skill_dir) if has_customization else {} + _check_persistent_layers(roots, skill_dir, defaults) + customization = load_customization_for_roots(roots, skill_dir) if has_customization else {} supplied: set[str] = set() if defaults is not None: file_layer, command_layer = _invocation_customization(defaults, overrides, assignments or []) @@ -913,6 +924,11 @@ def main() -> int: default=[], help="a skills root the host has active, in precedence order, project roots first (repeatable)", ) + parser.add_argument( + "--no-workspace", + action="store_true", + help="read only the resolved repo's own _bmad/ root without inheriting an outer workspace root", + ) reconfigure = getattr(sys.stdout, "reconfigure", None) if reconfigure is not None: reconfigure(encoding="utf-8", errors=getattr(sys.stdout, "errors", None) or "strict") @@ -931,7 +947,12 @@ def main() -> int: skill_dir = _resolve_skill_dir(args.skill, project_root, roots) report_owed_setup(skill_dir.resolve(), project_root.resolve(), roots) entry = render( - project_root, skill_dir, overrides=args.overrides, assignments=args.assignments, skill_roots=roots + project_root, + skill_dir, + overrides=args.overrides, + assignments=args.assignments, + skill_roots=roots, + include_workspace=not args.no_workspace, ) # Printed, not named: a file the model is told to read may be read only in part. workflow = entry.read_text(encoding="utf-8") diff --git a/skills/core-tools/bmad/scripts/resolve_config.py b/skills/core-tools/bmad/scripts/resolve_config.py index a384dcac86..88ddd9a21a 100644 --- a/skills/core-tools/bmad/scripts/resolve_config.py +++ b/skills/core-tools/bmad/scripts/resolve_config.py @@ -20,8 +20,9 @@ MODEL_TIERS, ConfigError, apply_worktree_path_fallbacks, - central_config_layers, + central_config_layers_for_roots, check_central_config, + find_bmad_roots, find_project_root, merge_layers, resolve_artifact_destinations, @@ -186,6 +187,11 @@ def main() -> int: action="store_true", help="Validate _bmad/custom/config*.toml keys and structured blocks against core schema and installed module manifests.", ) + parser.add_argument( + "--no-workspace", + action="store_true", + help="Read only the resolved repo's own _bmad/ root without inheriting an outer workspace root.", + ) args = parser.parse_args() if args.check and ( @@ -220,13 +226,15 @@ def main() -> int: ) return 1 skill_roots = tuple(root.resolve() for root in args.root) or None + roots = (project_root,) if args.no_workspace else (find_bmad_roots(project_root) or (project_root,)) + effective_root = roots[-1] if args.check: - report = check_central_config((project_root,), skill_roots=skill_roots) + report = check_central_config(roots, skill_roots=skill_roots) write_json_stdout(report) return 0 if report["ok"] else 1 - layers = central_config_layers(project_root, require_project=True, skill_roots=skill_roots) + layers = central_config_layers_for_roots(roots, require_project=True, skill_roots=skill_roots) merged = merge_layers(layers) - resolved_merged = apply_worktree_path_fallbacks(merged, project_root) + resolved_merged = apply_worktree_path_fallbacks(merged, effective_root) except (ConfigError, OSError) as error: sys.stderr.write(f"error: {error}\n") return 1 @@ -249,7 +257,7 @@ def main() -> int: resolved_blocks["knowledge_sources"] = resolve_knowledge_sources( layers, scopes=args.scope or None, - project_root=project_root, + project_root=effective_root, include_disabled=args.include_disabled, include_general=not args.no_general, legacy_external_sources=legacy_sources, @@ -263,7 +271,7 @@ def main() -> int: categories=args.for_categories or None, artifact_format=args.artifact_format, modes=args.modes or None, - project_root=project_root, + project_root=effective_root, include_disabled=args.include_disabled, legacy_external_handoffs=legacy_handoffs, ) diff --git a/skills/core-tools/bmad/scripts/resolve_customization.py b/skills/core-tools/bmad/scripts/resolve_customization.py index 6ad306de67..02879768da 100755 --- a/skills/core-tools/bmad/scripts/resolve_customization.py +++ b/skills/core-tools/bmad/scripts/resolve_customization.py @@ -16,9 +16,10 @@ from config_utils import ( ConfigError, check_customization, + find_bmad_roots, find_project_root, has_matching_custom_rule, - load_customization, + load_customization_for_roots, worktree_fallback_custom_file_path, ) except ModuleNotFoundError as error: @@ -136,6 +137,11 @@ def main() -> int: action="store_true", help="Validate overrides and matching cross-skill rules against shipped customize.toml schema and local file: refs.", ) + parser.add_argument( + "--no-workspace", + action="store_true", + help="Read only the resolved repo's own _bmad/ root without inheriting an outer workspace root.", + ) args = parser.parse_args() if args.check and args.key: @@ -150,11 +156,17 @@ def main() -> int: project_root = candidates[0] if candidates else None if project_root is not None: warn_on_masked_override(project_root, candidates[1:], skill_dir.name) + if project_root is None: + roots: tuple[Path, ...] = () + elif args.no_workspace: + roots = (project_root,) + else: + roots = find_bmad_roots(project_root) or (project_root,) if args.check: - report = check_customization((project_root,) if project_root is not None else (), skill_dir) + report = check_customization(roots, skill_dir) write_json_stdout(report) return 0 if report["ok"] else 1 - merged = load_customization(project_root, skill_dir) + merged = load_customization_for_roots(roots, skill_dir) except (ConfigError, OSError) as error: sys.stderr.write(f"error: {error}\n") return 1 diff --git a/skills/core-tools/bmad/scripts/setup.py b/skills/core-tools/bmad/scripts/setup.py index 6c3ea76316..91769fb9dd 100644 --- a/skills/core-tools/bmad/scripts/setup.py +++ b/skills/core-tools/bmad/scripts/setup.py @@ -168,12 +168,17 @@ ) from config_utils import ( ConfigError, + _anchor_layer_paths, + find_git_repo_root, + find_linked_workspace_root, find_local_bmad_root, + find_outer_workspace_root, find_project_root, find_worktree_boundary, find_worktree_root, load_cross_boundary_toml, resolve_worktree_path_fallback, + workspace_link_diagnostics, worktree_fallback_user_config_candidate, worktree_fallback_user_config_path, ) @@ -274,15 +279,23 @@ def _resolve_cli_project_root(args: argparse.Namespace, parser: argparse.Argumen is_read_only = bool(args.status or args.list_config_questions or args.source_record is not None) if is_read_only: return find_project_root() or Path.cwd().resolve() - boundary = find_worktree_boundary() + wt_boundary = find_worktree_boundary() + boundary = wt_boundary or find_git_repo_root() local = find_local_bmad_root(stop_at=boundary) if local is not None: return local discovered = find_project_root() if discovered is not None: + linked_ws = find_linked_workspace_root() + if linked_ws is not None and discovered == linked_ws: + via = "outside the current repository (via bmad.workspace)" + elif wt_boundary is not None: + via = "via linked git worktree" + else: + via = "outside the current repository" raise RuntimeError( - f"found _bmad/ at {discovered} via linked git worktree; pass --project-root {discovered} " - f"to modify it explicitly, or --project-root {Path.cwd().resolve()} to set up locally" + f"found _bmad/ at {discovered} {via}; " + f"pass --project-root {discovered} to modify it explicitly, or --project-root {Path.cwd().resolve()} to set up locally" ) parser.error("--project-root is required when no _bmad/ exists at or above the working directory") raise AssertionError("unreachable") @@ -598,11 +611,59 @@ def payload(skill_root: Path) -> tuple[Path, Path]: return (scripts_src, config_src) +def _merge_outer_dicts(base: dict, over: dict) -> dict: + out = copy.deepcopy(base) + for key, value in over.items(): + if isinstance(value, dict) and isinstance(out.get(key), dict): + out[key] = _merge_outer_dicts(out[key], value) + else: + out[key] = copy.deepcopy(value) + return out + + +def _outer_workspace_layers(project_root: Path) -> tuple[Path | None, dict, dict]: + """Read-only outer workspace team and user config layers inherited by `project_root`, if any.""" + try: + outer_root = find_outer_workspace_root(project_root) + except ConfigError: + return None, {}, {} + if outer_root is None: + return None, {}, {} + outer_team: dict = {} + for cfg_path in (outer_root / "_bmad" / "config.toml", outer_root / "_bmad" / "custom" / "config.toml"): + try: + data = load_cross_boundary_toml(cfg_path) + except Exception: + data = {} + if isinstance(data, dict) and data: + outer_team = _merge_outer_dicts(outer_team, data) + outer_user: dict = {} + user_candidate = user_config_path(outer_root) + if not present(user_candidate): + user_candidate = worktree_fallback_user_config_path(outer_root) or user_candidate + try: + user_data = load_cross_boundary_toml(user_candidate) + except Exception: + user_data = {} + if isinstance(user_data, dict): + outer_user = user_data + return outer_root, outer_team, outer_user + + def team_config_plan(project_root: Path, config_src: Path) -> tuple[str | None, dict, str]: """The team file's text, its values with the template's new keys filled in, and the text setup would write.""" template_text = fill_team_config(config_src.read_text(encoding="utf-8"), project_root) template = parse_toml(template_text, config_src) existing_text, existing = existing_team_config(project_root) + outer_root, outer_team, _outer_user = _outer_workspace_layers(project_root) + if ( + outer_root is not None + and lookup(outer_team, ("core", "output_folder")) is not _MISSING + and lookup(existing, ("core", "output_folder")) is _MISSING + and isinstance(template.get("core"), dict) + ): + # Preserve workspace-inherited output_folder instead of stamping a repo default over it. + template["core"].pop("output_folder", None) merged = fill_keep(template, existing) if not isinstance(merged, dict): raise Exception(f"invalid team config: {project_root / '_bmad' / 'config.toml'}") @@ -1906,6 +1967,7 @@ def status_report( module=code, ) settled = ("current", "ahead", "plugin-managed", "pinned", "could-not-check") + link_diag = workspace_link_diagnostics(project_root) or workspace_link_diagnostics() return { "mode": "status", "module": code, @@ -1915,6 +1977,7 @@ def status_report( "custom_gitignore": gitignore_state, "scopes": scopes, **({"scope_warning": scopes["warning"]} if scopes["warning"] else {}), + **({"workspace_link": link_diag} if link_diag is not None else {}), "modules": modules, "missing_module_records": list(installation.missing_records), "duplicate_skills": duplicates_json( @@ -2266,14 +2329,19 @@ def find_pending_questions( project_root: Path, ) -> tuple[ConfigQuestion, ...]: """A team question is pending once per project, a user question once per person.""" + outer_root, outer_team, outer_user = _outer_workspace_layers(project_root) pending: list[ConfigQuestion] = [] for installed in modules: for question in installed.questions: path = ("modules", question.module, *question.key.split(".")) if question.scope == "user": - answered = has_path(user_config, path, user_config_path(project_root)) + answered = has_path(user_config, path, user_config_path(project_root)) or ( + outer_root is not None and has_path(outer_user, path, user_config_path(outer_root)) + ) else: - answered = has_path(config, path, project_root / "_bmad" / "config.toml") + answered = has_path(config, path, project_root / "_bmad" / "config.toml") or ( + outer_root is not None and has_path(outer_team, path, outer_root / "_bmad" / "config.toml") + ) if not answered: pending.append( question._replace(default=question.default.replace("{directory_name}", project_root.name)) @@ -2458,8 +2526,12 @@ def fill_team_config(text: str, project_root: Path) -> str: def _output_folder_details(config_text: str, project_root: Path) -> tuple[Path, bool]: - """Return `(output_path, is_worktree_fallback)` from the last config layer setting `core.output_folder`.""" - layers = [tomllib.loads(config_text)] + """Return `(output_path, is_external)` from the highest-precedence layer setting `core.output_folder`.""" + outer_root, outer_team, outer_user = _outer_workspace_layers(project_root) + layers: list[tuple[dict, bool]] = [] + if outer_root is not None and outer_team: + layers.append((_anchor_layer_paths(outer_team, outer_root), True)) + layers.append((tomllib.loads(config_text), False)) team_custom = project_root / "_bmad" / "custom" / "config.toml" try: has_team_custom = team_custom.is_file() @@ -2467,9 +2539,11 @@ def _output_folder_details(config_text: str, project_root: Path) -> tuple[Path, has_team_custom = False if has_team_custom: try: - layers.append(parse_toml(team_custom.read_text(encoding="utf-8-sig"), team_custom)) + layers.append((parse_toml(team_custom.read_text(encoding="utf-8-sig"), team_custom), False)) except OSError: pass + if outer_root is not None and outer_user: + layers.append((_anchor_layer_paths(outer_user, outer_root), True)) local_user = project_root / "_bmad" / "custom" / "config.user.toml" try: local_user_present = present(local_user) @@ -2479,21 +2553,26 @@ def _output_folder_details(config_text: str, project_root: Path) -> tuple[Path, has_local_user = False if has_local_user: try: - layers.append(parse_toml(local_user.read_text(encoding="utf-8-sig"), local_user)) + layers.append((parse_toml(local_user.read_text(encoding="utf-8-sig"), local_user), False)) except OSError: pass elif not local_user_present: fallback_user = worktree_fallback_user_config_path(project_root) if fallback_user is not None: - layers.append(load_cross_boundary_toml(fallback_user)) + layers.append((load_cross_boundary_toml(fallback_user), False)) folder = "" - for layer in layers: + is_external = False + for layer, layer_external in layers: core = layer.get("core") value = core.get("output_folder") if isinstance(core, dict) else None if isinstance(value, str): folder = value + is_external = layer_external folder = folder or "_bmad-output" root = project_root.resolve() + if is_external: + candidate = Path(folder) + return (candidate if candidate.is_absolute() else (root / candidate)), True fallback = resolve_worktree_path_fallback(folder, root) if fallback is not None: return fallback, True diff --git a/skills/core-tools/bmad/scripts/startup_check.py b/skills/core-tools/bmad/scripts/startup_check.py index 945af0f0e7..f977b8eb6e 100644 --- a/skills/core-tools/bmad/scripts/startup_check.py +++ b/skills/core-tools/bmad/scripts/startup_check.py @@ -35,6 +35,8 @@ sys.path.insert(0, _SCRIPTS_DIR) from config_utils import ( # noqa: E402 + find_git_repo_root, + find_linked_workspace_root, find_local_bmad_root, find_project_root, find_worktree_boundary, @@ -628,15 +630,22 @@ def _resolve_cli_project_root(raw: Path | None, *, mutating: bool = False) -> Pa if raw is not None: return raw.resolve() if mutating: - boundary = find_worktree_boundary() + wt_boundary = find_worktree_boundary() + boundary = wt_boundary or find_git_repo_root() local = find_local_bmad_root(stop_at=boundary) if local is not None: return local discovered = find_project_root() if discovered is not None: + linked_ws = find_linked_workspace_root() + if linked_ws is not None and discovered == linked_ws: + via = "outside the current repository (via bmad.workspace)" + elif wt_boundary is not None: + via = "via linked git worktree" + else: + via = "outside the current repository" raise RuntimeError( - f"found _bmad/ at {discovered} via linked git worktree; " - f"pass --project-root {discovered} to update its state explicitly" + f"found _bmad/ at {discovered} {via}; pass --project-root {discovered} to update its state explicitly" ) else: discovered = find_project_root() diff --git a/skills/core-tools/bmod-core-tools/help/team-adoption.md b/skills/core-tools/bmod-core-tools/help/team-adoption.md index e282c2cb26..50dbddffdf 100644 --- a/skills/core-tools/bmod-core-tools/help/team-adoption.md +++ b/skills/core-tools/bmod-core-tools/help/team-adoption.md @@ -1,7 +1,7 @@ --- title: "Team Adoption and Shared Rules" -when: "Team _bmad/custom/, rules.toml, AGENTS.md, hooks, .user.toml" -tags: [team, adoption, customization, config, rules, baseline, overrides, user-toml] +when: "Team _bmad/custom/, rules.toml, AGENTS.md, hooks, .user.toml, polyrepo, worktrees, standalone, skill placement" +tags: [team, adoption, customization, config, rules, baseline, overrides, user-toml, polyrepo, workspace, standalone, worktree] related: [bmad-customize/customization, bmad-facilitate/facilitate] --- @@ -30,3 +30,14 @@ Teams share conventions through committed files under `{project-root}/_bmad/cust - **Completion hooks (`on_complete`):** Post-run actions such as publishing after explicit confirmation. - **Templates & extensions:** Extend shipped templates with `extends: ` in `_bmad/custom/facilitate-templates/` so upstream updates still arrive. - **Weekly baseline promotion:** Experiment in `.user.toml` files and promote proven rules into committed team `.toml` files. + +## Workspace and multi-repo layouts + +Choose how `_bmad/` maps to your repositories; installed skills can live in any project or global tool folder independently: + +- **Single repo:** Put `_bmad/` in the repository root. +- **Shared-parent polyrepo:** Put workspace `_bmad/` in the parent folder above sibling repos so every repo inherits team/personal config and output folders, while an individual repo may still keep its own `_bmad/` layered on top. +- **Scattered polyrepo:** When repos sit in separate folders without a common `_bmad/` parent, run `git config bmad.workspace ` inside each repo so local git config points to the shared workspace `_bmad/`. +- **Out-of-tree worktrees:** Linked git worktrees automatically resolve their main checkout's `_bmad/` via git `commondir` (and fall back read-only to main-checkout `*.user.toml` files). +- **Standalone opt-out:** Set `core.standalone = true` in a repo's `_bmad/config.toml`, `_bmad/custom/config.toml`, or `config.user.toml` (or pass `--no-workspace`) to block outer workspace inheritance cleanly. +- **Harness skill placement:** Harnesses that stop skill discovery at `.git` (such as Antigravity) will not load skills placed only above sibling repos; install skills user-globally or inside each repo instead, separate from `_bmad/`. diff --git a/skills/method/bmad-agent-po/scripts/read_store.py b/skills/method/bmad-agent-po/scripts/read_store.py index 3403e824f0..812f6bce28 100644 --- a/skills/method/bmad-agent-po/scripts/read_store.py +++ b/skills/method/bmad-agent-po/scripts/read_store.py @@ -18,6 +18,7 @@ """ import argparse +import importlib.util import json import re import sys @@ -44,9 +45,50 @@ def merge(base: dict, over: dict) -> dict: return out -def store_config(project_root: Path, starters: Path) -> dict: - path = project_root / PROJECT_FILE - project = load(path) if path.is_file() else {} +def _resolve_bmad_roots(project_root: Path, *, include_workspace: bool = True) -> tuple[Path, ...]: + if not include_workspace: + return (project_root,) + here = Path(__file__).resolve() + candidates = [ + (project_root / "_bmad" / "scripts" / "config_utils.py", "bmad_config_utils_read_store"), + *( + (parent / "_bmad" / "scripts" / "config_utils.py", "bmad_config_utils_read_store") + for parent in project_root.parents + ), + (here.parents[2] / "bmad" / "scripts" / "config_utils.py", "bmad_config_utils_read_store"), + (here.parents[2] / "bmod-method" / "scripts" / "tickets.py", "bmad_tickets_read_store"), + ] + for candidate, mod_name in candidates: + try: + if not candidate.is_file(): + continue + spec = importlib.util.spec_from_file_location(mod_name, candidate) + if spec is None or spec.loader is None: + continue + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + except (OSError, ImportError): + continue + finder = getattr(module, "find_bmad_roots", None) + if not callable(finder): + continue + try: + roots = tuple(finder(project_root)) + except (OSError, ImportError) as error: + raise OSError(str(error)) from error + except Exception as error: + raise ValueError(str(error)) from error + return roots or (project_root,) + return (project_root,) + + +def store_config(project_root: Path, starters: Path, *, include_workspace: bool = True) -> dict: + roots = _resolve_bmad_roots(project_root, include_workspace=include_workspace) + project: dict = {} + for root in roots: + path = root / PROJECT_FILE + if path.is_file(): + project = merge(project, load(path)) tickets = project.get("tickets") store = tickets.get("store") if isinstance(tickets, dict) else None if not isinstance(store, str) or not store: @@ -76,6 +118,11 @@ def main() -> int: parser.add_argument( "--starters-dir", default=str(STARTERS), help="folder of starters; default: the skill's config/" ) + parser.add_argument( + "--no-workspace", + action="store_true", + help="read only the resolved repo's own store config without inheriting an outer workspace root", + ) args = parser.parse_args() starters = Path(args.starters_dir).expanduser() @@ -89,7 +136,7 @@ def main() -> int: return 0 if not args.project_root: parser.error("--project-root is required") - data = store_config(Path(args.project_root).expanduser(), starters) + data = store_config(Path(args.project_root).expanduser(), starters, include_workspace=not args.no_workspace) except (OSError, ValueError) as error: # ValueError covers a TOML or encoding failure sys.stderr.write(f"error: cannot read the store config: {error}\n") return 1 diff --git a/skills/method/bmod-method/scripts/tickets.py b/skills/method/bmod-method/scripts/tickets.py index 7ad5b75caf..e48aec0d4f 100644 --- a/skills/method/bmod-method/scripts/tickets.py +++ b/skills/method/bmod-method/scripts/tickets.py @@ -839,16 +839,30 @@ def load_shared(args) -> None: """Load the project's frontmatter module: from `--project-root`, else the project holding a folder given, else the working directory.""" global frontmatter + include_workspace = not getattr(args, "no_workspace", False) if args.project_root: root = Path(args.project_root).resolve() else: given = [Path(v).resolve() for v in vars(args).values() if isinstance(v, str) and is_path(v)] - root = next(filter(None, map(find_project_root, [*given, Path.cwd()])), None) + root = next( + filter(None, (find_project_root(p, include_workspace=include_workspace) for p in [*given, Path.cwd()])), + None, + ) if root is None: raise TicketError("no project root found: no _bmad/ at or above the working directory; pass --project-root") - path = root / "_bmad" / "scripts" / "frontmatter.py" - if not path.is_file(): - raise TicketError(f"{path} is missing. Run bmad setup for this project.") + roots = find_bmad_roots(root, include_workspace=include_workspace) or (root,) + path = next( + ( + r / "_bmad" / "scripts" / "frontmatter.py" + for r in reversed(roots) + if (r / "_bmad" / "scripts" / "frontmatter.py").is_file() + ), + None, + ) + if path is None: + raise TicketError( + f"{root / '_bmad' / 'scripts' / 'frontmatter.py'} is missing. Run bmad setup for this project." + ) spec = importlib.util.spec_from_file_location("bmad_frontmatter", path) frontmatter = importlib.util.module_from_spec(spec) spec.loader.exec_module(frontmatter) @@ -875,6 +889,13 @@ def _safe_is_file(path: Path) -> bool: return False +def _safe_is_symlink(path: Path) -> bool: + try: + return path.is_symlink() + except OSError: + return False + + def _safe_resolve(path: Path) -> Path | None: try: return path.resolve() @@ -982,16 +1003,237 @@ def _resolve_worktree_path_fallback(raw: str, project_root: Path) -> Path | None return fallback if _safe_exists(fallback) else None -def find_project_root(start: Path) -> Path | None: +def _logical_git_config_lines(text: str) -> list[str]: + """Join backslash-continued git-config lines while keeping `#`/`;` comments unjoined.""" + logical: list[str] = [] + pending: list[str] = [] + in_quotes = False + for raw_line in text.splitlines(): + line = raw_line[:-1] if raw_line.endswith("\r") else raw_line + in_comment = False + escaped_eol = False + i = 0 + n = len(line) + while i < n: + ch = line[i] + if in_quotes: + if ch == "\\": + if i + 1 < n: + i += 2 + continue + escaped_eol = True + break + if ch == '"': + in_quotes = False + i += 1 + continue + if ch in ("#", ";"): + in_comment = True + break + if ch == '"': + in_quotes = True + i += 1 + continue + if ch == "\\": + if i + 1 < n: + i += 2 + continue + escaped_eol = True + break + i += 1 + if escaped_eol and not in_comment: + pending.append(line[:-1]) + continue + pending.append(line) + logical.append("".join(pending)) + pending.clear() + in_quotes = False + if pending: + logical.append("".join(pending)) + return logical + + +def _strip_git_config_inline_comment_and_unquote(raw: str) -> str: + """Decode a git-config value, preserving quoted spaces and escapes in/outside quotes.""" + out: list[str] = [] + escapes = {"n": "\n", "t": "\t", "b": "\b"} + in_quotes = False + seen_content = False + last_significant = 0 + i = 0 + n = len(raw) + while i < n: + ch = raw[i] + if in_quotes: + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + out.append(escapes.get(nxt, nxt)) + i += 2 + elif ch == '"': + in_quotes = False + i += 1 + else: + out.append(ch) + i += 1 + seen_content = True + last_significant = len(out) + continue + if ch in ("#", ";"): + break + if ch == '"': + in_quotes = True + seen_content = True + i += 1 + continue + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + out.append(escapes.get(nxt, nxt)) + seen_content = True + last_significant = len(out) + i += 2 + continue + if ch in (" ", "\t"): + if seen_content: + out.append(ch) + i += 1 + continue + out.append(ch) + seen_content = True + last_significant = len(out) + i += 1 + return "".join(out[:last_significant]) + + +def _read_raw_git_config_bmad_workspace(config_path: Path) -> str | None: + if not _safe_is_file(config_path): + return None + try: + text = config_path.read_text(encoding="utf-8-sig") + except (OSError, UnicodeError): + return None + in_bmad = False + found: str | None = None + for raw_line in _logical_git_config_lines(text): + stripped = raw_line.strip() + if not stripped or stripped[0] in ("#", ";"): + continue + if stripped.startswith("["): + end = stripped.find("]") + if end == -1: + in_bmad = False + continue + in_bmad = stripped[1:end].strip().lower() == "bmad" + remainder = stripped[end + 1 :].strip() + if not remainder or remainder[0] in ("#", ";"): + continue + stripped = remainder + if not in_bmad: + continue + if "=" in stripped: + key_part, val_part = stripped.split("=", 1) + if key_part.strip().lower() != "workspace": + continue + found = _strip_git_config_inline_comment_and_unquote(val_part) + continue + bare_key = stripped.split("#", 1)[0].split(";", 1)[0].strip().lower() + if bare_key == "workspace": + found = "" + return found + + +def _find_git_common_dir(start: Path) -> tuple[Path, Path] | None: current = _safe_resolve(start) if current is None: return None if _safe_is_file(current): current = current.parent + for candidate in (current, *current.parents): + git_entry = candidate / ".git" + if _safe_is_dir(git_entry): + resolved_git = _safe_resolve(git_entry) + return (candidate, resolved_git) if resolved_git is not None else None + if not _safe_is_file(git_entry): + continue + first_line = _first_nonempty_line(git_entry) + if not first_line or not first_line.startswith("gitdir:"): + continue + raw_gitdir = first_line[len("gitdir:") :].strip() + if not raw_gitdir: + continue + gitdir_candidate = Path(raw_gitdir) + if not gitdir_candidate.is_absolute(): + gitdir_candidate = candidate / gitdir_candidate + gitdir = _safe_resolve(gitdir_candidate) + if gitdir is None: + continue + commondir_file = gitdir / "commondir" + if _safe_is_file(commondir_file): + raw_common = _first_nonempty_line(commondir_file) + if not raw_common: + continue + common_candidate = Path(raw_common) + if not common_candidate.is_absolute(): + common_candidate = gitdir / common_candidate + common = _safe_resolve(common_candidate) + if common is not None and _safe_is_dir(common): + return candidate, common + continue + if _read_raw_git_config_bmad_workspace(gitdir / "config") is not None: + return candidate, gitdir + return None + + +def _find_linked_workspace_root(start: Path) -> Path | None: + git_info = _find_git_common_dir(start) + if git_info is None: + return None + _repo_root, common_git_dir = git_info + raw = _read_raw_git_config_bmad_workspace(common_git_dir / "config") + if not raw or "\x00" in raw or "\n" in raw or "\r" in raw: + return None + candidate = Path(raw) + if not candidate.is_absolute(): + candidate = common_git_dir.parent / candidate + resolved = _safe_resolve(candidate) + if resolved is None or not _safe_is_dir(resolved): + return None + if resolved.name == "_bmad": + ws_root = resolved.parent + bmad_dir = resolved + else: + ws_root = resolved + bmad_dir = ws_root / "_bmad" + if not _safe_is_dir(bmad_dir): + return None + return _safe_resolve(ws_root) or ws_root + + +def _find_git_repo_root(start: Path) -> Path | None: + current = _safe_resolve(start) + if current is None: + return None + if _safe_is_file(current): + current = current.parent + for candidate in (current, *current.parents): + git_entry = candidate / ".git" + if _safe_exists(git_entry) or _safe_is_symlink(git_entry): + return candidate + return None + + +def find_project_root(start: Path, *, include_workspace: bool = True) -> Path | None: + current = _safe_resolve(start) + if current is None: + return None + if _safe_is_file(current): + current = current.parent + roots = _find_worktree_roots(current) + stop_at = (roots[0] if roots is not None else _find_git_repo_root(current)) if not include_workspace else None for p in (current, *current.parents): if _safe_is_dir(p / "_bmad"): return p - roots = _find_worktree_roots(current) + if stop_at is not None and p == stop_at: + break if roots is not None: wt_root, main_root = roots try: @@ -1002,65 +1244,169 @@ def find_project_root(start: Path) -> Path | None: for p in (search_start, *search_start.parents): if _safe_is_dir(p / "_bmad"): return p - return None + if not include_workspace and p == main_root: + break + return _find_linked_workspace_root(current) if include_workspace else None + + +def _worktree_counterpart_root(resolved_root: Path) -> Path | None: + roots = _find_worktree_roots(resolved_root) + if roots is None: + return None + worktree_root, main_root = roots + try: + rel_sub = resolved_root.relative_to(worktree_root) + except ValueError: + return None + counterpart = main_root / rel_sub if rel_sub.parts else main_root + return None if counterpart == resolved_root else counterpart + + +def _load_optional_toml(path: Path) -> dict: + if not _safe_is_file(path): + return {} + try: + parsed = tomllib.loads(path.read_text(encoding="utf-8-sig")) + return parsed if isinstance(parsed, dict) else {} + except (OSError, UnicodeError, tomllib.TOMLDecodeError): + return {} + + +def _merge_dicts(base: dict, over: dict) -> dict: + out = dict(base) + for key, value in over.items(): + if isinstance(value, dict) and isinstance(out.get(key), dict): + out[key] = _merge_dicts(out[key], value) + else: + out[key] = value + return out + + +def _is_standalone(project_root: Path) -> bool: + bmad_dir = project_root / "_bmad" + local_user = bmad_dir / "custom" / "config.user.toml" + if _safe_exists(local_user) or _safe_is_symlink(local_user): + user_data = _load_optional_toml(local_user) + else: + counterpart = _worktree_counterpart_root(project_root) + user_data = _load_optional_toml(counterpart / "_bmad" / "custom" / "config.user.toml") if counterpart else {} + merged = _merge_dicts( + _load_optional_toml(bmad_dir / "config.toml"), _load_optional_toml(bmad_dir / "custom" / "config.toml") + ) + merged = _merge_dicts(merged, user_data) + core = merged.get("core") + return isinstance(core, dict) and core.get("standalone") is True + + +def find_bmad_roots(start: Path, *, include_workspace: bool = True) -> tuple[Path, ...]: + inner = find_project_root(start, include_workspace=include_workspace) + if inner is None: + return () + if not include_workspace: + return (inner,) + outer: Path | None = None + linked = _find_linked_workspace_root(inner) or _find_linked_workspace_root(start) + if linked is not None and linked != inner: + outer = linked + if outer is None: + for parent in inner.parents: + if _safe_is_dir(parent / "_bmad"): + outer = parent + break + if outer is None: + counterpart = _worktree_counterpart_root(inner) + if counterpart is not None: + for parent in counterpart.parents: + if _safe_is_dir(parent / "_bmad"): + outer = parent + break + if outer is None or outer == inner or _is_standalone(inner): + return (inner,) + return (outer, inner) def project_root_for(args, start: Path) -> Path | None: - return Path(args.project_root).resolve() if args.project_root else find_project_root(start) + include_workspace = not getattr(args, "no_workspace", False) + return ( + Path(args.project_root).resolve() + if args.project_root + else find_project_root(start, include_workspace=include_workspace) + ) -def store_config(project_root: Path | None) -> dict: - """The `[tickets]` table of the project's store config, empty when there is none.""" +def store_config(project_root: Path | None, *, include_workspace: bool = True) -> dict: + """The merged `[tickets]` table across workspace and repo store configs, empty when there is none.""" if not project_root: return {} - cfg = project_root / "_bmad" / "custom" / "ticketing-store-config.toml" - if not cfg.is_file(): - return {} - tickets = tomllib.loads(read_text(cfg)).get("tickets", {}) - return tickets if isinstance(tickets, dict) else {} + roots = find_bmad_roots(project_root, include_workspace=include_workspace) or (project_root,) + merged: dict = {} + for root in roots: + cfg = root / "_bmad" / "custom" / "ticketing-store-config.toml" + if not cfg.is_file(): + continue + tickets = tomllib.loads(read_text(cfg)).get("tickets", {}) + if isinstance(tickets, dict): + merged = _merge_dicts(merged, tickets) + return merged -def store_name(project_root: Path | None) -> str: - store = store_config(project_root).get("store", "repo") +def store_name(project_root: Path | None, *, include_workspace: bool = True) -> str: + store = store_config(project_root, include_workspace=include_workspace).get("store", "repo") return store if isinstance(store, str) and store else "repo" -def central_config(project_root: Path) -> dict: - """The BMad config with its layers merged by the project's own `config_utils.py`.""" - path = project_root / "_bmad" / "scripts" / "config_utils.py" - if not path.is_file(): - raise TicketError(f"cannot read the BMad config: {path} is missing") +def central_config(project_root: Path, *, include_workspace: bool = True) -> dict: + """The BMad config with its stacked workspace/repo layers merged by `config_utils.py`.""" + roots = find_bmad_roots(project_root, include_workspace=include_workspace) or (project_root,) + path = next( + ( + r / "_bmad" / "scripts" / "config_utils.py" + for r in reversed(roots) + if (r / "_bmad" / "scripts" / "config_utils.py").is_file() + ), + None, + ) + if path is None: + raise TicketError( + f"cannot read the BMad config: {project_root / '_bmad' / 'scripts' / 'config_utils.py'} is missing" + ) spec = importlib.util.spec_from_file_location("bmad_config_utils", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) try: + if hasattr(module, "central_config_layers_for_roots"): + return module.merge_layers(module.central_config_layers_for_roots(roots, require_project=True)) return module.load_central_config(project_root) except module.ConfigError as e: raise TicketError(str(e)) from e -def tickets_root(project_root: Path, config: dict | None = None) -> Path: +def tickets_root(project_root: Path, config: dict | None = None, *, include_workspace: bool = True) -> Path: """`{output_folder}` for the project: the ticket tree lives beside the documents.""" - config = central_config(project_root) if config is None else config + config = central_config(project_root, include_workspace=include_workspace) if config is None else config core = config.get("core", {}) output = str(core.get("output_folder", "") if isinstance(core, dict) else "") fallback = _resolve_worktree_path_fallback(output, project_root) if fallback is not None: return fallback + if output and Path(output).is_absolute(): + return Path(output) output = output.replace("{project-root}", str(project_root)) return project_root / output -def active_initiative(project_root: Path) -> Path: +def active_initiative(project_root: Path, *, include_workspace: bool = True) -> Path: """`{output_folder}/{active_initiative}` for the project.""" - config = central_config(project_root) + config = central_config(project_root, include_workspace=include_workspace) core = config.get("core", {}) name = core.get("active_initiative") if isinstance(core, dict) else None if not isinstance(name, str) or not name.strip(): raise TicketError( "no active initiative: set core.active_initiative in _bmad/custom/config.user.toml, or pass a folder" ) - folder = container_of((tickets_root(project_root, config) / name.strip()).resolve()) + folder = container_of( + (tickets_root(project_root, config, include_workspace=include_workspace) / name.strip()).resolve() + ) if not folder.is_dir(): raise TicketError(f"active initiative folder not found: {folder}") return folder @@ -1070,14 +1416,15 @@ def active_initiative(project_root: Path) -> Path: def _folder(args) -> Path: + include_workspace = not getattr(args, "no_workspace", False) if args.dir is None: root = project_root_for(args, Path.cwd()) if root is None: raise TicketError("no project root found: no _bmad/ at or above the working directory; pass --project-root") # The store is then read from this project even when output_folder lies outside it. args.project_root = str(root) - folder = active_initiative(root) - backlog = (tickets_root(root) / "backlog").resolve() + folder = active_initiative(root, include_workspace=include_workspace) + backlog = (tickets_root(root, include_workspace=include_workspace) / "backlog").resolve() args.backlog = backlog if backlog.is_dir() and backlog != folder else None return folder return locate_dir(args, args.dir) @@ -1086,17 +1433,18 @@ def _folder(args) -> Path: def locate_dir(args, name: str) -> Path: """A `` argument as a folder: as given, else under the store, the active initiative and its `tickets/` folder, or the project root.""" + include_workspace = not getattr(args, "no_workspace", False) folder = Path(name).resolve() root = None if folder.is_dir() or Path(name).is_absolute() else project_root_for(args, Path.cwd()) bases = [] if root is not None: try: - bases = [tickets_root(root), root] + bases = [tickets_root(root, include_workspace=include_workspace), root] except TicketError: # no BMad config to name the store: the project root alone bases = [root] else: try: - active = active_initiative(root) + active = active_initiative(root, include_workspace=include_workspace) except TicketError: # none set: the store and the project root pass else: @@ -1578,7 +1926,7 @@ def parent_status_view(folder: Path, project_root: Path | None = None, seen: set def cmd_next(args) -> dict: folder = _folder(args) - store = store_name(project_root_for(args, folder)) + store = store_name(project_root_for(args, folder), include_workspace=not getattr(args, "no_workspace", False)) if store != "repo" and not args.synced: raise StoreRefusal(f"store is {store}: sync ticket status from the tracker first, then rerun with --synced") if is_parent(folder): @@ -1652,7 +2000,7 @@ def status_view(folder: Path, project_root: Path | None = None) -> dict: def cmd_status(args) -> dict: folder = _folder(args) root = project_root_for(args, folder) - store = store_name(root) + store = store_name(root, include_workspace=not getattr(args, "no_workspace", False)) view = parent_status_view if is_parent(folder) else status_view return with_backlog(args, {"store": store, **view(folder, root)}, lambda b: status_view(b, root)) @@ -1965,7 +2313,7 @@ def edit_frontmatter(path: Path, values: dict) -> str: def cmd_mark(args) -> dict: """Write status, assignee, and the blocked fields to the ticket's plan; never to its leaf file.""" folder = _folder(args) - store = store_name(project_root_for(args, folder)) + store = store_name(project_root_for(args, folder), include_workspace=not getattr(args, "no_workspace", False)) if store != "repo": raise StoreRefusal(f"store is {store}: change status through the store's write verb, not this script") t, tree = locate(args, folder, args.ref) @@ -2062,7 +2410,7 @@ def cmd_mirror(args) -> dict: """Write what the tracker returned into each ticket's leaf file; never `status`, which is the build's.""" folder = _folder(args) root = project_root_for(args, folder) - store = store_name(root) + store = store_name(root, include_workspace=not getattr(args, "no_workspace", False)) if store == "repo": raise StoreRefusal("store is repo: there is no tracker to mirror") items = json.load(sys.stdin) @@ -2195,7 +2543,7 @@ def set_after_line(block: str, current: list, new: list, where: str) -> str: def cmd_note(args) -> dict: """Append a note to a ticket no build has started: its entry's `notes`, or its leaf file's `## Notes`.""" folder = _folder(args) - store = store_name(project_root_for(args, folder)) + store = store_name(project_root_for(args, folder), include_workspace=not getattr(args, "no_workspace", False)) if store != "repo": raise StoreRefusal(f"store is {store}: add the note through the store, not this script") note = args.text.strip() @@ -2705,6 +3053,11 @@ def main() -> int: "--project-root", help="project holding _bmad/; default: walk up from the ticket folder, or the working directory with no folder", ) + parser.add_argument( + "--no-workspace", + action="store_true", + help="resolve only the current repository's own _bmad/ without inheriting an outer workspace root", + ) sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser( "next", diff --git a/skills/toolsmith/bmad-eval/scripts/eval_common.py b/skills/toolsmith/bmad-eval/scripts/eval_common.py index 68e35a62ca..a83ba6d704 100644 --- a/skills/toolsmith/bmad-eval/scripts/eval_common.py +++ b/skills/toolsmith/bmad-eval/scripts/eval_common.py @@ -166,8 +166,213 @@ def find_project_root(start: Path) -> Path | None: return git_root +def _logical_git_config_lines(text: str) -> list[str]: + """Join backslash-continued git-config lines while keeping `#`/`;` comments unjoined.""" + logical: list[str] = [] + pending: list[str] = [] + in_quotes = False + for raw_line in text.splitlines(): + line = raw_line[:-1] if raw_line.endswith("\r") else raw_line + in_comment = False + escaped_eol = False + i = 0 + n = len(line) + while i < n: + ch = line[i] + if in_quotes: + if ch == "\\": + if i + 1 < n: + i += 2 + continue + escaped_eol = True + break + if ch == '"': + in_quotes = False + i += 1 + continue + if ch in ("#", ";"): + in_comment = True + break + if ch == '"': + in_quotes = True + i += 1 + continue + if ch == "\\": + if i + 1 < n: + i += 2 + continue + escaped_eol = True + break + i += 1 + if escaped_eol and not in_comment: + pending.append(line[:-1]) + continue + pending.append(line) + logical.append("".join(pending)) + pending.clear() + in_quotes = False + if pending: + logical.append("".join(pending)) + return logical + + +def _strip_git_config_inline_comment_and_unquote(raw: str) -> str: + """Decode a git-config value, preserving quoted spaces and escapes in/outside quotes.""" + out: list[str] = [] + escapes = {"n": "\n", "t": "\t", "b": "\b"} + in_quotes = False + seen_content = False + last_significant = 0 + i = 0 + n = len(raw) + while i < n: + ch = raw[i] + if in_quotes: + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + out.append(escapes.get(nxt, nxt)) + i += 2 + elif ch == '"': + in_quotes = False + i += 1 + else: + out.append(ch) + i += 1 + seen_content = True + last_significant = len(out) + continue + if ch in ("#", ";"): + break + if ch == '"': + in_quotes = True + seen_content = True + i += 1 + continue + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + out.append(escapes.get(nxt, nxt)) + seen_content = True + last_significant = len(out) + i += 2 + continue + if ch in (" ", "\t"): + if seen_content: + out.append(ch) + i += 1 + continue + out.append(ch) + seen_content = True + last_significant = len(out) + i += 1 + return "".join(out[:last_significant]) + + +def _read_raw_git_config_bmad_workspace(config_path: Path) -> str | None: + if not _safe_is_file(config_path): + return None + try: + text = config_path.read_text(encoding="utf-8-sig") + except (OSError, UnicodeError): + return None + in_bmad = False + found: str | None = None + for raw_line in _logical_git_config_lines(text): + stripped = raw_line.strip() + if not stripped or stripped[0] in ("#", ";"): + continue + if stripped.startswith("["): + end = stripped.find("]") + if end == -1: + in_bmad = False + continue + in_bmad = stripped[1:end].strip().lower() == "bmad" + remainder = stripped[end + 1 :].strip() + if not remainder or remainder[0] in ("#", ";"): + continue + stripped = remainder + if not in_bmad: + continue + if "=" in stripped: + key_part, val_part = stripped.split("=", 1) + if key_part.strip().lower() != "workspace": + continue + found = _strip_git_config_inline_comment_and_unquote(val_part) + continue + bare_key = stripped.split("#", 1)[0].split(";", 1)[0].strip().lower() + if bare_key == "workspace": + found = "" + return found + + +def _find_git_common_dir(start: Path) -> tuple[Path, Path] | None: + current = _safe_resolve(start) + if current is None: + return None + if _safe_is_file(current): + current = current.parent + for candidate in (current, *current.parents): + git_entry = candidate / ".git" + if _safe_is_dir(git_entry): + resolved_git = _safe_resolve(git_entry) + return (candidate, resolved_git) if resolved_git is not None else None + if not _safe_is_file(git_entry): + continue + first_line = _first_nonempty_line(git_entry) + if not first_line or not first_line.startswith("gitdir:"): + continue + raw_gitdir = first_line[len("gitdir:") :].strip() + if not raw_gitdir: + continue + gitdir_candidate = Path(raw_gitdir) + if not gitdir_candidate.is_absolute(): + gitdir_candidate = candidate / gitdir_candidate + gitdir = _safe_resolve(gitdir_candidate) + if gitdir is None: + continue + commondir_file = gitdir / "commondir" + if _safe_is_file(commondir_file): + raw_common = _first_nonempty_line(commondir_file) + if not raw_common: + continue + common_candidate = Path(raw_common) + if not common_candidate.is_absolute(): + common_candidate = gitdir / common_candidate + common = _safe_resolve(common_candidate) + if common is not None and _safe_is_dir(common): + return candidate, common + continue + if _read_raw_git_config_bmad_workspace(gitdir / "config") is not None: + return candidate, gitdir + return None + + +def _find_linked_workspace_root(start: Path) -> Path | None: + git_info = _find_git_common_dir(start) + if git_info is None: + return None + _repo_root, common_git_dir = git_info + raw = _read_raw_git_config_bmad_workspace(common_git_dir / "config") + if not raw or "\x00" in raw or "\n" in raw or "\r" in raw: + return None + candidate = Path(raw) + if not candidate.is_absolute(): + candidate = common_git_dir.parent / candidate + resolved = _safe_resolve(candidate) + if resolved is None or not _safe_is_dir(resolved): + return None + if resolved.name == "_bmad": + ws_root = resolved.parent + bmad_dir = resolved + else: + ws_root = resolved + bmad_dir = ws_root / "_bmad" + if not _safe_is_dir(bmad_dir): + return None + return _safe_resolve(ws_root) or ws_root + + def find_bmad_root(start: Path) -> Path | None: - """Nearest ancestor holding `_bmad/`, walking linked-worktree `commondir` when absent locally.""" + """Nearest ancestor holding `_bmad/`, walking linked-worktree `commondir` or `bmad.workspace` when absent.""" current = _safe_resolve(start) if current is None: return None @@ -187,7 +392,7 @@ def find_bmad_root(start: Path) -> Path | None: for candidate in (search_start, *search_start.parents): if _safe_is_dir(candidate / "_bmad"): return candidate - return None + return _find_linked_workspace_root(current) # --- harness ----------------------------------------------------------------- diff --git a/tests/core-tools/bmad/test_detect_env.py b/tests/core-tools/bmad/test_detect_env.py index 7d3e36d3f0..1ac3333f64 100644 --- a/tests/core-tools/bmad/test_detect_env.py +++ b/tests/core-tools/bmad/test_detect_env.py @@ -436,7 +436,7 @@ def test_cli_classify_and_write_end_to_end(self): written = json.loads(write.stdout) self.assertEqual(written["status"], "written") self.assertEqual(written["scope"], "project") - self.assertEqual(Path(written["path"]), root / "_bmad" / "custom" / "config.user.toml") + self.assertEqual(Path(written["path"]), (root / "_bmad" / "custom" / "config.user.toml").resolve()) def test_review_edge_cases_long_inline_json_nan_utf8_partial_toggle_and_project_clis(self): with tempfile.TemporaryDirectory() as temp_dir: diff --git a/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py b/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py new file mode 100644 index 0000000000..e20569b722 --- /dev/null +++ b/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py @@ -0,0 +1,958 @@ +"""Deterministic tests for Story 17: scattered polyrepo linking, root stacking, Obeya decoupling, and no-_bmad degradation.""" + +from __future__ import annotations + +import importlib.util +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parents[3] +BMAD_SKILL = REPO_ROOT / "skills" / "core-tools" / "bmad" +BMAD_SCRIPTS = BMAD_SKILL / "scripts" +TICKETS_SCRIPT = REPO_ROOT / "skills" / "method" / "bmod-method" / "scripts" / "tickets.py" +READ_STORE_SCRIPT = REPO_ROOT / "skills" / "method" / "bmad-agent-po" / "scripts" / "read_store.py" +EVAL_COMMON_SCRIPT = REPO_ROOT / "skills" / "toolsmith" / "bmad-eval" / "scripts" / "eval_common.py" +CUSTOMIZE_LIST_SCRIPT = ( + REPO_ROOT / "skills" / "core-tools" / "bmad-customize" / "scripts" / "list_customizable_skills.py" +) +RESOLVE_PARTY_SCRIPT = REPO_ROOT / "skills" / "core-tools" / "bmad-party-mode" / "scripts" / "resolve_party.py" +RESOLVE_PERSONAS_SCRIPT = REPO_ROOT / "skills" / "core-tools" / "bmad-forge-idea" / "scripts" / "resolve_personas.py" +FOUNDER_NUMBERS_SCRIPT = ( + REPO_ROOT / "skills" / "founder" / "bmad-founder-agent-advisor" / "scripts" / "founder_numbers.py" +) +CREATIVE_LINT_SCRIPT = ( + REPO_ROOT / "skills" / "creative" / "bmad-creative-agent-director" / "scripts" / "creative_lint.py" +) + +if str(BMAD_SCRIPTS) not in sys.path: + sys.path.insert(0, str(BMAD_SCRIPTS)) + +import config_utils # noqa: E402 + +_GIT_ENV_STRIP = ( + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_PREFIX", + "GIT_SUPER_PREFIX", + "GIT_CONFIG_PARAMETERS", + "GIT_CONFIG_COUNT", + "GIT_CEILING_DIRECTORIES", +) + + +def _load_module(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +tickets_mod = _load_module("bmod_method_tickets_story17", TICKETS_SCRIPT) +eval_common = _load_module("bmad_eval_common_story17", EVAL_COMMON_SCRIPT) +read_store_mod = _load_module("bmad_read_store_story17", READ_STORE_SCRIPT) + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def _isolated_env(home_dir: Path | None = None) -> dict[str, str]: + env = dict(os.environ) + for var in _GIT_ENV_STRIP: + env.pop(var, None) + env["GIT_CONFIG_NOSYSTEM"] = "1" + env["GIT_CONFIG_GLOBAL"] = os.devnull + if home_dir is not None: + env["HOME"] = str(home_dir) + env["USERPROFILE"] = str(home_dir) + return env + + +def _git(cwd: Path, *args: str) -> str: + res = subprocess.run( + ["git", *args], + cwd=str(cwd), + env=_isolated_env(), + text=True, + capture_output=True, + check=False, + ) + if res.returncode != 0: + raise AssertionError(f"git {' '.join(args)} failed: {res.stderr or res.stdout}") + return res.stdout.strip() + + +def _run( + script: Path, + args: list[str], + *, + cwd: Path, + env: dict[str, str] | None = None, +) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(script), *args], + cwd=str(cwd), + env=env or _isolated_env(), + text=True, + capture_output=True, + check=False, + ) + + +def _install_bmad_runtime(root: Path, *, project_name: str, output_folder: str = "{project-root}/_bmad-output") -> None: + bmad_dir = root / "_bmad" + _write( + bmad_dir / "config.toml", + f"[core]\nproject_name = {json.dumps(project_name, ensure_ascii=False)}\n" + f"output_folder = {json.dumps(output_folder, ensure_ascii=False)}\n", + ) + _write(bmad_dir / "custom" / ".gitignore", "*.user.toml\n") + shutil.copytree(BMAD_SCRIPTS, bmad_dir / "scripts", dirs_exist_ok=True) + + +def _init_git_repo(repo: Path, message: str = "init") -> None: + repo.mkdir(parents=True, exist_ok=True) + _write(repo / "README.md", f"# {repo.name}\n") + _git(repo, "init", "-b", "main") + _git(repo, "config", "user.email", "test@example.com") + _git(repo, "config", "user.name", "Test User") + _git(repo, "add", "-A") + _git(repo, "commit", "--no-verify", "-m", message) + + +class Story17PolyrepoAndDegradationTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + self.empty_home = self.root / "empty-home" + self.empty_home.mkdir() + self.env = _isolated_env(self.empty_home) + patcher = mock.patch("pathlib.Path.home", return_value=self.empty_home) + patcher.start() + self.addCleanup(patcher.stop) + + def _stage_skill(self, parent: Path, name: str, customize_toml: str) -> Path: + skill_dir = parent / name + _write(skill_dir / "customize.toml", customize_toml) + _write( + skill_dir / "SKILL.md", + f"---\nname: {name}\ndescription: 'Skill {name}. Use when testing.'\n---\n\nBody.\n", + ) + return skill_dir + + def test_req1_scattered_git_config_workspace_formats_worktrees_submodules_and_diagnostics(self): + # 1. Scattered workspace linked via absolute, relative, spaced/quoted, and trailing /_bmad paths. + ws = self.root / "scattered ws" + _install_bmad_runtime(ws, project_name="scattered-ws", output_folder="{project-root}/_bmad-obeya") + + repo_abs = self.root / "repo-abs" + _init_git_repo(repo_abs) + _git(repo_abs, "config", "bmad.workspace", str(ws)) + self.assertEqual(config_utils.find_project_root(repo_abs), ws) + self.assertEqual(tickets_mod.find_project_root(repo_abs), ws) + self.assertEqual(eval_common.find_bmad_root(repo_abs), ws) + self.assertEqual(config_utils.workspace_link_diagnostics(repo_abs)["status"], "ok") + + # Trailing /_bmad normalizes cleanly to workspace root; inline #/; comments outside quotes strip cleanly. + repo_rel = self.root / "nested" / "repo-rel" + _init_git_repo(repo_rel) + config_file = repo_rel / ".git" / "config" + config_file.write_text( + config_file.read_text(encoding="utf-8") + + '[bmad]\n\tworkspace = "../../wrong-first"\n\tworkspace = "../../scattered ws/_bmad" # trailing comment\n', + encoding="utf-8", + ) + self.assertEqual(config_utils.find_project_root(repo_rel), ws) + self.assertEqual(tickets_mod.find_project_root(repo_rel), ws) + + # Linked worktree of a scattered repo inherits common git config bmad.workspace. + wt = self.root / "wt-scattered" + _git(repo_abs, "worktree", "add", str(wt), "-b", "wt-branch") + wt_sub = wt / "src" + wt_sub.mkdir() + self.assertEqual(config_utils.find_project_root(wt_sub), ws) + self.assertEqual(tickets_mod.find_project_root(wt_sub), ws) + self.assertEqual(eval_common.find_bmad_root(wt_sub), ws) + + # Submodule without its own bmad.workspace falls through to superproject's bmad.workspace. + super_repo = self.root / "super" + _init_git_repo(super_repo) + _git(super_repo, "config", "bmad.workspace", str(ws)) + sub_seed = self.root / "sub-seed" + _init_git_repo(sub_seed) + subprocess.run( + ["git", "-c", "protocol.file.allow=always", "submodule", "add", str(sub_seed), "mods/sub"], + cwd=str(super_repo), + env=_isolated_env(), + text=True, + capture_output=True, + check=True, + ) + sub_dir = super_repo / "mods" / "sub" + self.assertEqual(config_utils.find_project_root(sub_dir), ws) + + # Broken / missing / uninitialized / unreadable bmad.workspace degrades gracefully and surfaces diagnostics. + broken_repo = self.root / "broken-ws-repo" + _init_git_repo(broken_repo) + missing_target = self.root / "does-not-exist" + _git(broken_repo, "config", "bmad.workspace", str(missing_target)) + self.assertIsNone(config_utils.find_project_root(broken_repo)) + self.assertIsNone(tickets_mod.find_project_root(broken_repo)) + self.assertEqual(config_utils.workspace_link_diagnostics(broken_repo)["status"], "missing") + + no_bmad_dir = self.root / "plain-empty-dir" + no_bmad_dir.mkdir() + _git(broken_repo, "config", "bmad.workspace", str(no_bmad_dir)) + self.assertIsNone(config_utils.find_project_root(broken_repo)) + self.assertEqual(config_utils.workspace_link_diagnostics(broken_repo)["status"], "missing_bmad") + + # Install bmad skill and check resolve_config --check & setup --status report broken link safely. + _install_bmad_runtime(broken_repo, project_name="broken-inner") + check_broken = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(broken_repo), "--check"], + cwd=broken_repo, + env=self.env, + ) + self.assertEqual(check_broken.returncode, 0, check_broken.stderr) + check_data = json.loads(check_broken.stdout) + self.assertEqual([w["kind"] for w in check_data["warnings"]], ["broken-workspace-link"]) + + # Cross-platform PermissionError / unreadable target degradation via mock.patch + POSIX chmod 000. + orig_stat = Path.stat + + def _deny_target(self_path: Path, *args, **kwargs): + if self_path == no_bmad_dir: + raise PermissionError("access denied") + return orig_stat(self_path, *args, **kwargs) + + with mock.patch.object(Path, "stat", _deny_target): + diag = config_utils.workspace_link_diagnostics(broken_repo) + self.assertIsNotNone(diag) + assert diag is not None + self.assertEqual(diag["status"], "unreadable") + self.assertIsNone(config_utils.find_linked_workspace_root(broken_repo)) + + if sys.platform != "win32" and not (hasattr(os, "geteuid") and os.geteuid() == 0): + locked_ws = self.root / "locked-ws" + _install_bmad_runtime(locked_ws, project_name="locked") + locked_ws.chmod(0o000) + self.addCleanup(lambda: locked_ws.chmod(0o755) if locked_ws.exists() else None) + _git(broken_repo, "config", "bmad.workspace", str(locked_ws)) + diag_chmod = config_utils.workspace_link_diagnostics(broken_repo) + self.assertIsNotNone(diag_chmod) + assert diag_chmod is not None + self.assertEqual(diag_chmod["status"], "unreadable") + + def test_req2_workspace_repo_stacking_path_anchoring_standalone_and_write_protection(self): + ws = self.root / "ws-stack" + _install_bmad_runtime(ws, project_name="ws-team", output_folder="{project-root}/_bmad-obeya") + _write(ws / "docs" / "ws-standard.md", "workspace rule doc\n") + _write( + ws / "_bmad" / "custom" / "config.toml", + '[core]\noutput_folder = "{project-root}/_bmad-obeya"\n' + '[core.knowledge_sources.ws_docs]\nkind = "path"\ntarget = "{project-root}/docs/ws-standard.md"\n' + '[core.artifact_destinations.ws_out]\nkind = "path"\ntarget = "exports"\nfor = ["document"]\n' + '[modules.demo]\nteam_key = "ws-team"\nshared_override = "ws-team"\n', + ) + _write( + ws / "_bmad" / "custom" / "config.user.toml", + '[core]\nactive_initiative = "ws-init"\n[modules.demo]\nuser_stack = "ws-user"\n', + ) + _write( + ws / "_bmad" / "custom" / "rules.toml", + '[[rules]]\nid = "ws-facts"\nmatch = "demo-*"\n' + '[rules.workflow]\npersistent_facts = ["ws-fact", "file:docs/ws-standard.md"]\n', + ) + _write( + ws / "_bmad" / "custom" / "demo-skill.toml", + '[workflow]\npersistent_facts = ["ws-skill-team"]\nws_dir = "{project-root}/ws-artifacts"\n', + ) + + # Scattered repo linked via git config bmad.workspace (with its own _bmad/). + repo = self.root / "scattered-app" + _init_git_repo(repo) + _git(repo, "config", "bmad.workspace", str(ws)) + _install_bmad_runtime(repo, project_name="app-team", output_folder="{project-root}/_bmad-output") + _write(repo / "docs" / "repo-standard.md", "repo rule doc\n") + _write( + repo / "_bmad" / "custom" / "config.toml", + '[core]\noutput_folder = "{project-root}/app-out"\n' + '[modules.demo]\nshared_override = "repo-team"\nrepo_only = "repo-team"\n', + ) + _write( + repo / "_bmad" / "custom" / "config.user.toml", + '[modules.demo]\nuser_stack = "repo-user"\nws_only_user = "repo-user"\n', + ) + _write( + repo / "_bmad" / "custom" / "demo-skill.toml", + '[workflow]\npersistent_facts = ["repo-skill-team", "file:docs/repo-standard.md"]\n', + ) + + skills = repo / ".agents" / "skills" + skill_dir = self._stage_skill( + skills, + "demo-skill", + '[workflow]\npersistent_facts = ["shipped"]\nws_dir = "{project-root}/default-ws"\n', + ) + _write( + skill_dir / "workflow.md", + "PROJ={{ config.core.project_name }}|INIT={{ config.core.active_initiative }}" + "|TEAM={{ config.modules.demo.shared_override }}|FACTS={{ workflow.persistent_facts | join(',') }}\n", + ) + + # 1. Stacked resolve_config merges workspace team < repo team < workspace personal < repo personal. + res_cfg = _run( + BMAD_SCRIPTS / "resolve_config.py", + [ + "--project-root", + str(repo), + "--key", + "core.project_name", + "--key", + "core.active_initiative", + "--key", + "core.output_folder", + "--key", + "modules.demo", + "--resolve-sources", + "--resolve-destinations", + ], + cwd=repo, + env=self.env, + ) + self.assertEqual(res_cfg.returncode, 0, res_cfg.stderr) + cfg_data = json.loads(res_cfg.stdout) + self.assertEqual(cfg_data["core.project_name"], "app-team") + self.assertEqual(cfg_data["core.active_initiative"], "ws-init") + self.assertEqual( + cfg_data["modules.demo"], + { + "team_key": "ws-team", + "shared_override": "repo-team", + "repo_only": "repo-team", + "user_stack": "repo-user", + "ws_only_user": "repo-user", + }, + ) + # Outer workspace knowledge source & artifact destination anchored against workspace_root (ws), not repo! + ks_targets = {s["id"]: s["resolved_target"] for s in cfg_data["knowledge_sources"]["sources"]} + ad_targets = {d["id"]: d["resolved_target"] for d in cfg_data["artifact_destinations"]["destinations"]} + self.assertEqual(ks_targets["ws_docs"], (ws / "docs" / "ws-standard.md").as_posix()) + self.assertEqual(ad_targets["ws_out"], (ws / "exports").as_posix()) + + # 2. Stacked resolve_customization + per-layer file: ref anchoring + render_skill. + res_cust = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_dir), "--project-root", str(repo), "--key", "workflow"], + cwd=repo, + env=self.env, + ) + self.assertEqual(res_cust.returncode, 0, res_cust.stderr) + wf = json.loads(res_cust.stdout)["workflow"] + self.assertEqual( + wf["persistent_facts"], + [ + "shipped", + "ws-fact", + f"file:{(ws / 'docs' / 'ws-standard.md').as_posix()}", + "ws-skill-team", + "repo-skill-team", + "file:docs/repo-standard.md", + ], + ) + self.assertEqual(wf["ws_dir"], (ws / "ws-artifacts").as_posix()) + + res_render = _run( + BMAD_SCRIPTS / "render_skill.py", + ["--skill", str(skill_dir), "--project-root", str(repo)], + cwd=repo, + env=self.env, + ) + self.assertEqual(res_render.returncode, 0, res_render.stdout + res_render.stderr) + self.assertIn("PROJ=app-team|INIT=ws-init|TEAM=repo-team|FACTS=shipped,ws-fact,", res_render.stdout) + self.assertTrue((repo / "_bmad" / "render" / "demo-skill").is_dir()) + self.assertFalse((ws / "_bmad" / "render").exists()) + + # 3. --no-workspace isolates repo completely across resolve_config, resolve_customization, and render_skill. + res_no_ws = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(repo), "--no-workspace", "--key", "modules.demo", "--key", "core.active_initiative"], + cwd=repo, + env=self.env, + ) + self.assertEqual(res_no_ws.returncode, 0, res_no_ws.stderr) + no_ws_data = json.loads(res_no_ws.stdout) + self.assertNotIn("core.active_initiative", no_ws_data) + self.assertNotIn("team_key", no_ws_data["modules.demo"]) + + res_cust_no_ws = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(skill_dir), "--project-root", str(repo), "--no-workspace", "--key", "workflow"], + cwd=repo, + env=self.env, + ) + self.assertEqual( + json.loads(res_cust_no_ws.stdout)["workflow"]["persistent_facts"], + ["shipped", "repo-skill-team", "file:docs/repo-standard.md"], + ) + + # 4. core.standalone = true blocks outer workspace in config.toml, custom/config.toml, or config.user.toml, + # and higher-layer standalone = false re-enables it. + _write(repo / "_bmad" / "custom" / "config.toml", "[core]\nstandalone = true\n") + self.assertEqual(config_utils.find_bmad_roots(repo), (repo,)) + _write(repo / "_bmad" / "custom" / "config.user.toml", "[core]\nstandalone = false\n") + self.assertEqual(config_utils.find_bmad_roots(repo), (ws, repo)) + _write(repo / "_bmad" / "custom" / "config.user.toml", "[core]\nstandalone = true\n") + self.assertEqual(config_utils.find_bmad_roots(repo), (repo,)) + + # 5. Write-safety: mutating setup / startup_check in a repo without local _bmad/ refuses to mutate outer ws. + repo_no_bmad = self.root / "repo-unsetup" + _init_git_repo(repo_no_bmad) + _git(repo_no_bmad, "config", "bmad.workspace", str(ws)) + startup_res = _run( + BMAD_SCRIPTS / "startup_check.py", + ["--skill", str(BMAD_SKILL), "--mark-onboarded"], + cwd=repo_no_bmad, + env=self.env, + ) + self.assertEqual(startup_res.returncode, 1) + self.assertIn("outside the current repository", startup_res.stderr) + self.assertFalse((ws / "_bmad" / "custom" / "bmad-state.user.toml").exists()) + + setup_res = _run( + BMAD_SCRIPTS / "setup.py", + ["--skill", str(BMAD_SKILL)], + cwd=repo_no_bmad, + env=self.env, + ) + self.assertEqual(setup_res.returncode, 1) + self.assertIn("outside the current repository", setup_res.stderr) + + def test_req3_decoupled_obeya_tickets_and_store_stacking(self): + ws = self.root / "obeya-ws" + _install_bmad_runtime(ws, project_name="obeya-ws", output_folder="{project-root}/_bmad-obeya") + _write( + ws / "_bmad" / "custom" / "config.user.toml", + '[core]\nactive_initiative = "epic-alpha"\n', + ) + _write( + ws / "_bmad" / "custom" / "ticketing-store-config.toml", + '[tickets]\nstore = "jira"\n[tickets.extra]\nteam_id = "WS-1"\noverride_me = "ws"\n', + ) + init_dir = ws / "_bmad-obeya" / "epic-alpha" + _write( + init_dir / "epic-alpha.md", + "---\nid: epic-alpha\ntitle: Alpha\nstatus: in-progress\ntype: epic\n---\n\nAlpha body.\n", + ) + _write( + init_dir / "tickets" / "tickets.toml", + 'title = "Alpha"\nstatus = "in-progress"\nnext_id = 2\n' + '[[entry]]\nid = 1\ntype = "story"\ntitle = "First"\nrefine = false\n', + ) + _write( + init_dir / "tickets" / "story-1.md", + '---\nid: 1\ntitle: "First"\nparent: epic-alpha\nstatus: ready-for-dev\nrefined: true\ntype: story\n---\n\nStory body.\n', + ) + + # Repo with NO _bmad/ linked via bmad.workspace reads workspace Obeya store seamlessly. + repo = self.root / "code-repo" + _init_git_repo(repo) + _git(repo, "config", "bmad.workspace", str(ws)) + + res_status = _run(TICKETS_SCRIPT, ["status"], cwd=repo, env=self.env) + self.assertEqual(res_status.returncode, 0, res_status.stderr) + status_payload = json.loads(res_status.stdout) + self.assertEqual(status_payload["store"], "jira") + self.assertEqual(status_payload["counts"]["total"], 1) + + res_unsynced = _run(TICKETS_SCRIPT, ["next"], cwd=repo, env=self.env) + self.assertEqual(res_unsynced.returncode, 2) + self.assertIn("store is jira", res_unsynced.stderr) + + res_next = _run(TICKETS_SCRIPT, ["next", "--synced"], cwd=repo, env=self.env) + self.assertEqual(res_next.returncode, 0, res_next.stderr) + next_payload = json.loads(res_next.stdout) + self.assertEqual(next_payload["store"], "jira") + self.assertEqual([t["file"] for t in next_payload["ready_to_start"]], ["story-1.md"]) + + # Shared-parent / stacked repo inheriting workspace output_folder while overriding ticketing-store-config. + repo_child = ws / "services" / "api" + _init_git_repo(repo_child) + _write( + ws / "_bmad" / "config.toml", + '[core]\nproject_name = "obeya-ws"\noutput_folder = "{project-root}/_bmad-obeya"\n\n' + '[modules.demo]\nteam_ans = "ws-team"\n', + ) + _write( + ws / "_bmad" / "custom" / "config.user.toml", + '[core]\nactive_initiative = "epic-alpha"\n\n[modules.demo]\nuser_ans = "ws-user"\n', + ) + skills_root = self.root / "installed-skills" + shutil.copytree(BMAD_SKILL, skills_root / "bmad") + _write(skills_root / "bmad-demo" / "SKILL.md", "---\nname: bmad-demo\ndescription: demo\n---\n\n# Demo\n") + _write( + skills_root / "bmad-demo" / "bmod.toml", + '[bmod]\ncode = "demo"\nversion = "1.0.0"\nupdate_source = "github:example/demo"\n\n' + '[[bmod.config_questions]]\nkey = "team_ans"\nprompt = "Team?"\ndefault = "repo-default"\n\n' + '[[bmod.config_questions]]\nkey = "user_ans"\nprompt = "User?"\ndefault = "user-default"\nscope = "user"\n', + ) + # Workspace answers satisfy both questions so `setup.py` neither re-asks nor creates repo `_bmad-output`. + q_before = _run( + BMAD_SCRIPTS / "setup.py", + [ + "--project-root", + str(repo_child), + "--skill", + str(skills_root / "bmad"), + "--root", + str(skills_root), + "--list-config-questions", + ], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(q_before.returncode, 0, q_before.stderr) + self.assertEqual(json.loads(q_before.stdout), []) + + setup_res1 = _run( + BMAD_SCRIPTS / "setup.py", + ["--project-root", str(repo_child), "--skill", str(skills_root / "bmad"), "--root", str(skills_root)], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(setup_res1.returncode, 0, setup_res1.stderr) + setup_payload1 = json.loads(setup_res1.stdout) + self.assertEqual(setup_payload1["pending_questions"], []) + self.assertEqual(setup_payload1["answers_added"], []) + self.assertIn("demo", {m["module"] for m in setup_payload1["modules"]}) + self.assertNotIn("output_folder", (repo_child / "_bmad" / "config.toml").read_text(encoding="utf-8")) + self.assertFalse((repo_child / "_bmad-output").exists()) + + setup_res2 = _run( + BMAD_SCRIPTS / "setup.py", + ["--project-root", str(repo_child), "--skill", str(skills_root / "bmad"), "--root", str(skills_root)], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(setup_res2.returncode, 0, setup_res2.stderr) + self.assertEqual(json.loads(setup_res2.stdout)["status"], "current") + self.assertFalse(json.loads(setup_res2.stdout)["changed"]) + + rc_out = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(repo_child), "--key", "core.output_folder"], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(rc_out.returncode, 0, rc_out.stderr) + self.assertEqual(json.loads(rc_out.stdout)["core.output_folder"], (ws / "_bmad-obeya").resolve().as_posix()) + + _write( + repo_child / "_bmad" / "custom" / "ticketing-store-config.toml", + '[tickets]\n[tickets.extra]\noverride_me = "repo"\nrepo_tag = "API"\n', + ) + self.assertEqual(tickets_mod.tickets_root(repo_child), (ws / "_bmad-obeya").resolve()) + merged_store = tickets_mod.store_config(repo_child) + self.assertEqual(merged_store["store"], "jira") + self.assertEqual(merged_store["extra"], {"team_id": "WS-1", "override_me": "repo", "repo_tag": "API"}) + + # --no-workspace works identically on tickets.py and read_store.py. + t_iso = _run( + TICKETS_SCRIPT, + ["--project-root", str(repo_child), "--no-workspace", "status", str(init_dir)], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(t_iso.returncode, 0, t_iso.stderr) + self.assertEqual(json.loads(t_iso.stdout)["store"], "repo") + + # Linked repo without local _bmad/ refuses workspace resolution under --no-workspace. + t_linked_iso = _run(TICKETS_SCRIPT, ["--no-workspace", "status"], cwd=repo, env=self.env) + self.assertEqual(t_linked_iso.returncode, 1) + self.assertIn("no project root found", t_linked_iso.stderr) + + res_read_store = _run( + READ_STORE_SCRIPT, + ["--project-root", str(repo_child), "-k", "tickets.store", "-k", "tickets.extra.team_id"], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(res_read_store.returncode, 0, res_read_store.stderr) + self.assertEqual( + json.loads(res_read_store.stdout), + {"tickets.store": "jira", "tickets.extra.team_id": "WS-1"}, + ) + + res_read_store_iso = _run( + READ_STORE_SCRIPT, + ["--project-root", str(repo_child), "--no-workspace", "-k", "tickets.store"], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(res_read_store_iso.returncode, 0, res_read_store_iso.stderr) + self.assertEqual(res_read_store_iso.stdout.strip(), "repo") + + # Enabling core.standalone = true restores standalone setup output_folder without touching workspace. + _write(repo_child / "_bmad" / "custom" / "config.toml", "[core]\nstandalone = true\n") + setup_standalone = _run( + BMAD_SCRIPTS / "setup.py", + [ + "--project-root", + str(repo_child), + "--skill", + str(skills_root / "bmad"), + "--root", + str(skills_root), + "--module-answers", + "-", + ], + cwd=repo_child, + env=self.env, + ) + # Expect JSON answers prompt error (now module questions ARE pending again locally!) or supply answers: + self.assertNotEqual(setup_standalone.returncode, 0) + q_list = _run( + BMAD_SCRIPTS / "setup.py", + [ + "--project-root", + str(repo_child), + "--skill", + str(skills_root / "bmad"), + "--root", + str(skills_root), + "--list-config-questions", + ], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(q_list.returncode, 0, q_list.stderr) + self.assertEqual({q["key"] for q in json.loads(q_list.stdout)}, {"team_ans", "user_ans"}) + + answers_file = self.root / "standalone-answers.toml" + _write(answers_file, '[modules.demo]\nteam_ans = "solo"\nuser_ans = "solo-u"\n') + setup_standalone_ok = _run( + BMAD_SCRIPTS / "setup.py", + [ + "--project-root", + str(repo_child), + "--skill", + str(skills_root / "bmad"), + "--root", + str(skills_root), + "--module-answers", + str(answers_file), + ], + cwd=repo_child, + env=self.env, + ) + self.assertEqual(setup_standalone_ok.returncode, 0, setup_standalone_ok.stderr) + self.assertIn("output_folder", (repo_child / "_bmad" / "config.toml").read_text(encoding="utf-8")) + self.assertTrue((repo_child / "_bmad-output").is_dir()) + + # Without any _bmad/ root, tickets.py halts cleanly with JSON setup error and zero traceback. + bare_dir = self.root / "bare-tickets" / "epic-solo" + _write(bare_dir / "epic-solo.md", "---\nid: epic-solo\ntitle: Solo\nstatus: in-progress\ntype: epic\n---\n") + _write( + bare_dir / "tickets" / "tickets.toml", + 'title = "Solo"\nstatus = "in-progress"\nnext_id = 2\n' + '[[entry]]\nid = 1\ntype = "story"\ntitle = "Leaf"\nrefine = false\n', + ) + _write( + bare_dir / "tickets" / "story-1.md", + '---\nid: 1\ntitle: "Leaf"\nparent: epic-solo\nstatus: ready-for-dev\nrefined: true\ntype: story\n---\n', + ) + res_explicit = _run(TICKETS_SCRIPT, ["status", str(bare_dir)], cwd=self.root, env=self.env) + self.assertEqual(res_explicit.returncode, 1) + self.assertNotIn("Traceback", res_explicit.stderr) + self.assertIn("pass --project-root", json.loads(res_explicit.stderr)["error"]) + + # Passing --project-root pointing to ws supplies runtime/store cleanly even for external ticket dirs. + res_with_ws = _run( + TICKETS_SCRIPT, + ["--project-root", str(ws), "status", str(bare_dir)], + cwd=self.root, + env=self.env, + ) + self.assertEqual(res_with_ws.returncode, 0, res_with_ws.stderr) + self.assertEqual(json.loads(res_with_ws.stdout)["counts"]["total"], 1) + + def test_req4_no_bmad_degradation_matrix(self): + bare = self.root / "no-bmad-workspace" + bare.mkdir() + draft = bare / "draft.md" + _write(draft, "# Draft\n\nPlain clear writing without invented claims.\n") + + # 1. resolve_customization falls back cleanly to shipped defaults without _bmad/. + rc = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--skill", str(REPO_ROOT / "skills" / "core-tools" / "bmad-review"), "--key", "workflow"], + cwd=bare, + env=self.env, + ) + self.assertEqual(rc.returncode, 0, rc.stderr) + self.assertNotIn("Traceback", rc.stderr) + self.assertIn("workflow", json.loads(rc.stdout)) + + # 2. knowledge --digest works without _bmad/. + kn = _run( + BMAD_SCRIPTS / "knowledge.py", + ["--root", str(REPO_ROOT / "skills" / "core-tools"), "--digest"], + cwd=bare, + env=self.env, + ) + self.assertEqual(kn.returncode, 0, kn.stderr) + self.assertNotIn("Traceback", kn.stderr) + self.assertIn("BMad Knowledge Digest", kn.stdout) + + # 3. list_templates works without _bmad/. + lt = _run( + BMAD_SCRIPTS / "list_templates.py", + ["--root", str(REPO_ROOT / "skills" / "core-tools"), "--brief"], + cwd=bare, + env=self.env, + ) + self.assertEqual(lt.returncode, 0, lt.stderr) + self.assertNotIn("Traceback", lt.stderr) + + # 4. roster works without _bmad/. + rst = _run( + BMAD_SCRIPTS / "roster.py", + ["--root", str(REPO_ROOT / "skills" / "core-tools"), "--brief"], + cwd=bare, + env=self.env, + ) + self.assertEqual(rst.returncode, 0, rst.stderr) + self.assertNotIn("Traceback", rst.stderr) + self.assertIn("agents", json.loads(rst.stdout)) + + # 5. detect_env scan works without _bmad/. + de = _run(BMAD_SCRIPTS / "detect_env.py", ["scan"], cwd=bare, env=self.env) + self.assertEqual(de.returncode, 0, de.stderr) + self.assertNotIn("Traceback", de.stderr) + self.assertIsNone(json.loads(de.stdout)["target_paths"]["project_user_config"]) + + # 6. startup_check --no-network works without _bmad/. + sc = _run( + BMAD_SCRIPTS / "startup_check.py", + ["--skill", str(BMAD_SKILL), "--no-network"], + cwd=bare, + env=self.env, + ) + self.assertEqual(sc.returncode, 0, sc.stderr) + self.assertNotIn("Traceback", sc.stderr) + + # 7. list_customizable_skills works without _bmad/. + lcs = _run( + CUSTOMIZE_LIST_SCRIPT, + ["--project-root", str(bare), "--skills-root", str(REPO_ROOT / "skills" / "core-tools")], + cwd=bare, + env=self.env, + ) + self.assertEqual(lcs.returncode, 0, lcs.stderr) + self.assertNotIn("Traceback", lcs.stderr) + self.assertFalse(json.loads(lcs.stdout)["central_config"]["has_setup_config"]) + + # 8. resolve_party and resolve_personas fall back cleanly without _bmad/. + rp = _run( + RESOLVE_PARTY_SCRIPT, + [ + "--project-root", + str(bare), + "--skill", + str(REPO_ROOT / "skills" / "core-tools" / "bmad-party-mode"), + "--list-groups", + ], + cwd=bare, + env=self.env, + ) + self.assertEqual(rp.returncode, 0, rp.stderr) + self.assertNotIn("Traceback", rp.stderr) + + rpers = _run( + RESOLVE_PERSONAS_SCRIPT, + ["--project-root", str(bare), "--skill", str(REPO_ROOT / "skills" / "core-tools" / "bmad-forge-idea")], + cwd=bare, + env=self.env, + ) + self.assertEqual(rpers.returncode, 0, rpers.stderr) + self.assertNotIn("Traceback", rpers.stderr) + + # 9. read_store without _bmad/ uses shipped repo starter cleanly. + rs = _run( + READ_STORE_SCRIPT, + ["--project-root", str(bare), "-k", "tickets.store"], + cwd=bare, + env=self.env, + ) + self.assertEqual(rs.returncode, 0, rs.stderr) + self.assertEqual(rs.stdout.strip(), "repo") + + # 10. resolve_config & tickets without dir fail cleanly with actionable error and zero traceback. + rcfg = _run(BMAD_SCRIPTS / "resolve_config.py", ["--key", "core.output_folder"], cwd=bare, env=self.env) + self.assertEqual(rcfg.returncode, 1) + self.assertNotIn("Traceback", rcfg.stderr) + self.assertIn("_bmad", rcfg.stderr) + + t_nodir = _run(TICKETS_SCRIPT, ["status"], cwd=bare, env=self.env) + self.assertNotEqual(t_nodir.returncode, 0) + self.assertNotIn("Traceback", t_nodir.stderr) + self.assertIn("_bmad", t_nodir.stdout + t_nodir.stderr) + + # 11. founder_numbers, creative_lint, and eval_common require zero _bmad/. + fn = _run( + FOUNDER_NUMBERS_SCRIPT, + ["runway", "--cash", "100000", "--costs", "10000"], + cwd=bare, + env=self.env, + ) + self.assertEqual(fn.returncode, 0, fn.stderr) + cl = _run(CREATIVE_LINT_SCRIPT, ["metrics", str(draft)], cwd=bare, env=self.env) + self.assertEqual(cl.returncode, 0, cl.stderr) + self.assertIsNone(eval_common.find_bmad_root(bare)) + + def test_review_edge_cases_parser_setup_no_workspace_and_checks(self): + # 1. Git-config parser escape, quoting, continuation, and bare-key parity against real `git config --get`. + cfg = self.root / "test-git-config" + git_env = {k: v for k, v in self.env.items() if k not in _GIT_ENV_STRIP} + git_env["GIT_CONFIG_NOSYSTEM"] = "1" + git_env["GIT_CONFIG_GLOBAL"] = os.devnull + + cases = [ + ("[bmad]\n\tworkspace = C:\\\\Users\\\\me\\\\ws\n", "C:\\Users\\me\\ws"), + ("[bmad]\n\tworkspace = \\\\\\\\server\\\\share\\\\ws\n", "\\\\server\\share\\ws"), + ('[bmad]\n\tworkspace = /tmp/q\\"uote\n', '/tmp/q"uote'), + ("[bmad]\n\tworkspace = /tmp/back\\\\slash\n", "/tmp/back\\slash"), + ('[bmad]\n\tworkspace = " /lead"\n', " /lead"), + ('[bmad]\n\tworkspace = "trail " # comment\n', "trail "), + ("[bmad]\n\tworkspace = line1\\\nline2\n", "line1line2"), + ('[bmad]\n\tworkspace = "q1\\\nq2"\n', "q1q2"), + ("[bmad]\n# see C:\\dir\\\n\tworkspace = /ws\n", "/ws"), + ("[bmad]\n\tworkspace\n", ""), + ] + for content, expected in cases: + cfg.write_text(content, encoding="utf-8") + git_res = subprocess.run( + ["git", "config", "--file", str(cfg), "--get", "bmad.workspace"], + env=git_env, + capture_output=True, + text=True, + encoding="utf-8", + check=True, + ) + git_val = git_res.stdout[:-1] if git_res.stdout.endswith("\n") else git_res.stdout + self.assertEqual(git_val, expected, f"git mismatch for {content!r}") + self.assertEqual(config_utils._read_raw_git_config_bmad_workspace(cfg), expected) + self.assertEqual(tickets_mod._read_raw_git_config_bmad_workspace(cfg), expected) + self.assertEqual(eval_common._read_raw_git_config_bmad_workspace(cfg), expected) + + # Bare key `[bmad]\n\tworkspace` produces invalid diagnostic without crashing. + bare_repo = self.root / "bare-key-repo" + _init_git_repo(bare_repo) + (bare_repo / ".git" / "config").write_text( + (bare_repo / ".git" / "config").read_text(encoding="utf-8") + "\n[bmad]\n\tworkspace\n", + encoding="utf-8", + ) + diag = config_utils.workspace_link_diagnostics(bare_repo) + self.assertIsNotNone(diag) + assert diag is not None + self.assertEqual(diag["status"], "invalid") + + # 2. `resolve_config.py --check` flags non-bool `core.standalone` in `_bmad/config.toml`. + bad_standalone = self.root / "bad-standalone" + _install_bmad_runtime(bad_standalone, project_name="bad-standalone") + _write(bad_standalone / "_bmad" / "config.toml", '[core]\nproject_name = "bad"\nstandalone = "true"\n') + chk = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(bad_standalone), "--check"], + cwd=bad_standalone, + env=self.env, + ) + self.assertEqual(chk.returncode, 1) + chk_payload = json.loads(chk.stdout) + self.assertFalse(chk_payload["ok"]) + self.assertTrue( + any(e["kind"] == "type-mismatch" and e["key"] == "core.standalone" for e in chk_payload["errors"]) + ) + + # 3. Outer `file:` ref anchoring with spaces in workspace path re-parses cleanly via `_FILE_REF_RE`. + ws_spaces = self.root / "my ws root" + _install_bmad_runtime(ws_spaces, project_name="ws-spaces") + _write(ws_spaces / "docs" / "guide.md", "# Guide\n") + _write( + ws_spaces / "_bmad" / "custom" / "bmad-review.toml", + '[workflow]\npersistent_facts = ["Read file:{project-root}/docs/guide.md before reviewing."]\n', + ) + child_spaces = ws_spaces / "app" + _install_bmad_runtime(child_spaces, project_name="app-spaces") + merged_custom = config_utils.load_customization_for_roots( + (ws_spaces.resolve(), child_spaces.resolve()), + REPO_ROOT / "skills" / "core-tools" / "bmad-review", + ) + fact = merged_custom["workflow"]["persistent_facts"][0] + self.assertIn('file:"', fact) + parsed_refs = config_utils._extract_concrete_file_refs(merged_custom) + self.assertEqual(parsed_refs, [(ws_spaces / "docs" / "guide.md").resolve().as_posix()]) + + # 4. Linked worktree pointing to `bmad.workspace` reports `(via bmad.workspace)` on mutating refusal. + ws_target = self.root / "wt-linked-ws" + _install_bmad_runtime(ws_target, project_name="wt-linked-ws") + src_repo = self.root / "wt-linked-src" + _init_git_repo(src_repo) + _git(src_repo, "config", "bmad.workspace", str(ws_target)) + src_wt = self.root / "wt-linked-worktree" + _git(src_repo, "worktree", "add", "-b", "feat/ws-link", str(src_wt)) + + sc_mut = _run(BMAD_SCRIPTS / "startup_check.py", ["--mark-onboarded"], cwd=src_wt, env=self.env) + self.assertEqual(sc_mut.returncode, 1) + self.assertIn("outside the current repository (via bmad.workspace)", sc_mut.stderr) + self.assertNotIn("via linked git worktree", sc_mut.stderr) + + su_mut = _run(BMAD_SCRIPTS / "setup.py", ["--skill", str(BMAD_SKILL)], cwd=src_wt, env=self.env) + self.assertEqual(su_mut.returncode, 1) + self.assertIn("outside the current repository (via bmad.workspace)", su_mut.stderr) + self.assertNotIn("via linked git worktree", su_mut.stderr) + + # 5. Isolated `resolve_party.py` and `resolve_personas.py` without `_bmad/` or sibling `bmad/` avoid raw file errors. + isolated_skills = self.root / "isolated-skills" + shutil.copytree(REPO_ROOT / "skills" / "core-tools" / "bmad-party-mode", isolated_skills / "bmad-party-mode") + shutil.copytree(REPO_ROOT / "skills" / "core-tools" / "bmad-forge-idea", isolated_skills / "bmad-forge-idea") + empty_ws = self.root / "empty-ws" + empty_ws.mkdir() + + iso_rp = _run( + isolated_skills / "bmad-party-mode" / "scripts" / "resolve_party.py", + ["--project-root", str(empty_ws), "--skill", str(isolated_skills / "bmad-party-mode"), "--list-groups"], + cwd=empty_ws, + env=self.env, + ) + self.assertEqual(iso_rp.returncode, 0, iso_rp.stderr) + self.assertNotIn("can't open file", iso_rp.stdout + iso_rp.stderr) + + iso_pi = _run( + isolated_skills / "bmad-forge-idea" / "scripts" / "resolve_personas.py", + ["--project-root", str(empty_ws), "--skill", str(isolated_skills / "bmad-forge-idea")], + cwd=empty_ws, + env=self.env, + ) + self.assertEqual(iso_pi.returncode, 0, iso_pi.stderr) + self.assertNotIn("can't open file", iso_pi.stdout + iso_pi.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core-tools/bmad/test_worktree_root_discovery.py b/tests/core-tools/bmad/test_worktree_root_discovery.py index 65e0cc2278..6e5fcdf0d1 100644 --- a/tests/core-tools/bmad/test_worktree_root_discovery.py +++ b/tests/core-tools/bmad/test_worktree_root_discovery.py @@ -376,7 +376,19 @@ def test_case_04b_out_of_tree_worktree_resolves_untracked_repo_bmad(self): ) self.assertEqual(cust_res.returncode, 0, cust_res.stderr) self.assertEqual( - json.loads(cust_res.stdout)["workflow"]["persistent_facts"], ["shipped", "repo-untracked-override"] + json.loads(cust_res.stdout)["workflow"]["persistent_facts"], + ["shipped", "ws-outer-override", "repo-untracked-override"], + ) + + cust_isolated = _run_py( + SCRIPTS_DIR / "resolve_customization.py", + ["--skill", str(skills_dir / "demo-skill"), "--key", "workflow", "--no-workspace"], + cwd=wt, + ) + self.assertEqual(cust_isolated.returncode, 0, cust_isolated.stderr) + self.assertEqual( + json.loads(cust_isolated.stdout)["workflow"]["persistent_facts"], + ["shipped", "repo-untracked-override"], ) # 5. Bare-repo worktree (`repo.git/` and `.bare/`) resolving `_bmad/` @@ -506,7 +518,18 @@ def test_case_07_branch_local_committed_bmad_beats_main_checkout(self): cwd=nested, ) self.assertEqual(cust_res.returncode, 0, cust_res.stderr) - self.assertEqual(json.loads(cust_res.stdout)["workflow"]["persistent_facts"], ["shipped", "branch-fact"]) + self.assertEqual( + json.loads(cust_res.stdout)["workflow"]["persistent_facts"], + ["shipped", "workspace-outer-override", "branch-fact"], + ) + + cust_isolated = _run_py( + SCRIPTS_DIR / "resolve_customization.py", + ["--skill", str(wt / ".agents" / "skills" / "demo-skill"), "--key", "workflow", "--no-workspace"], + cwd=nested, + ) + self.assertEqual(cust_isolated.returncode, 0, cust_isolated.stderr) + self.assertEqual(json.loads(cust_isolated.stdout)["workflow"]["persistent_facts"], ["shipped", "branch-fact"]) render_res = _run_py( SCRIPTS_DIR / "render_skill.py", From d5ccc565b5b2d81ba04fc3cd2ddf9ca047b509ab Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 21:24:18 -0600 Subject: [PATCH 7/8] fix(bmad): enforce --no-workspace isolation, sparse outer path anchoring, and UTF-8 test subprocesses Pass `include_workspace` into initial root discovery across `resolve_config.py`, `resolve_customization.py`, and `render_skill.py` so `--no-workspace` without `--project-root` never leaks an inherited outer workspace root when a linked or child repository has no local `_bmad/`. Track cumulative outer-layer metadata when anchoring sparse `knowledge_sources..target` and `artifact_destinations..target` overrides in `config_utils.central_config_layers_for_roots`. Pin UTF-8 decoding on subprocess test runners in `test_story17_polyrepo_and_degradation.py` so Windows runs decode UTF-8 CLI output cleanly. --- .../core-tools/bmad/scripts/config_utils.py | 65 ++++++++++++---- .../core-tools/bmad/scripts/render_skill.py | 16 ++-- .../core-tools/bmad/scripts/resolve_config.py | 11 ++- .../bmad/scripts/resolve_customization.py | 22 ++++-- .../test_story17_polyrepo_and_degradation.py | 76 ++++++++++++++++++- 5 files changed, 152 insertions(+), 38 deletions(-) diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 467f156510..3335da13c2 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -689,14 +689,22 @@ def _is_path_key(key: str) -> bool: return key in _PATH_KEY_EXACT or key.endswith(_PATH_KEY_SUFFIXES) -def is_path_field(path_parts: tuple[str, ...], parent_table: dict[str, Any] | None = None) -> bool: +def is_path_field( + path_parts: tuple[str, ...], + parent_table: dict[str, Any] | None = None, + *, + inherited_kind: str | None = None, +) -> bool: """Return True when the scalar/list field addressed by `path_parts` holds filesystem paths.""" if not path_parts: return False - if len(path_parts) == 4 and path_parts[:2] == ("core", "knowledge_sources") and path_parts[3] == "target": - return isinstance(parent_table, dict) and parent_table.get("kind") == "path" - if len(path_parts) == 4 and path_parts[:2] == ("core", "artifact_destinations") and path_parts[3] == "target": - return isinstance(parent_table, dict) and parent_table.get("kind") == "path" + if ( + len(path_parts) == 4 + and path_parts[:2] in (("core", "knowledge_sources"), ("core", "artifact_destinations")) + and path_parts[3] == "target" + ): + kind = parent_table.get("kind") if isinstance(parent_table, dict) and "kind" in parent_table else inherited_kind + return kind == "path" return _is_path_key(path_parts[-1]) @@ -1034,7 +1042,11 @@ def _anchor_single_path(raw: str, root: Path) -> str: return Path(os.path.normpath(str(root / cleaned))).as_posix() -def _anchor_layer_paths(layer: dict[str, Any], root: Path) -> dict[str, Any]: +def _anchor_layer_paths( + layer: dict[str, Any], + root: Path, + prior_merged: dict[str, Any] | None = None, +) -> dict[str, Any]: """Expand `{project-root}` and relative path fields on an outer layer against its own `root`.""" resolved_root = _safe_resolve(root) or root @@ -1042,23 +1054,33 @@ def _walk( node: Any, path_parts: tuple[str, ...] = (), *, - parent_table: dict[str, Any] | None = None, is_path: bool = False, + prior_node: Any = None, ) -> Any: if isinstance(node, dict): - return { - k: _walk( - v, (*path_parts, str(k)), parent_table=node, is_path=is_path_field((*path_parts, str(k)), node) + out: dict[str, Any] = {} + for k, v in node.items(): + child_parts = (*path_parts, str(k)) + prior_child = prior_node.get(k) if isinstance(prior_node, dict) else None + inherited_kind = prior_node.get("kind") if isinstance(prior_node, dict) else None + out[k] = _walk( + v, + child_parts, + is_path=is_path_field( + child_parts, + node, + inherited_kind=inherited_kind if isinstance(inherited_kind, str) else None, + ), + prior_node=prior_child, ) - for k, v in node.items() - } + return out if isinstance(node, list): - return [_walk(item, path_parts, parent_table=parent_table, is_path=is_path) for item in node] + return [_walk(item, path_parts, is_path=is_path) for item in node] if isinstance(node, str) and (is_path or "{project-root}" in node): return _anchor_single_path(node, resolved_root) return node - return _walk(layer) + return _walk(layer, prior_node=prior_merged) def _anchor_customization_file_refs(layer: dict[str, Any], root: Path) -> dict[str, Any]: @@ -1127,16 +1149,27 @@ def central_config_layers_for_roots( layers.append(defaults_layer) anchor_outer = len(roots) > 1 inner_root = roots[-1] if roots else None + effective_outer: dict[str, Any] = {} for root in roots: bmad_dir = root / "_bmad" for layer in ( load_toml(bmad_dir / "config.toml", required=require_project and root == inner_root), load_toml(bmad_dir / "custom" / "config.toml"), ): - layers.append(_anchor_layer_paths(layer, root) if anchor_outer and root != inner_root else layer) + if anchor_outer and root != inner_root: + anchored = _anchor_layer_paths(layer, root, prior_merged=effective_outer) + effective_outer = merge_layers((effective_outer, anchored)) + layers.append(anchored) + else: + layers.append(layer) for root in roots: layer = _user_layer_for_root(root) - layers.append(_anchor_layer_paths(layer, root) if anchor_outer and root != inner_root else layer) + if anchor_outer and root != inner_root: + anchored = _anchor_layer_paths(layer, root, prior_merged=effective_outer) + effective_outer = merge_layers((effective_outer, anchored)) + layers.append(anchored) + else: + layers.append(layer) return tuple(layers) diff --git a/skills/core-tools/bmad/scripts/render_skill.py b/skills/core-tools/bmad/scripts/render_skill.py index b3880a9bd2..32b3604916 100644 --- a/skills/core-tools/bmad/scripts/render_skill.py +++ b/skills/core-tools/bmad/scripts/render_skill.py @@ -791,7 +791,7 @@ def render_pass(destination: Path) -> tuple[_RenderContext, dict[str, str]]: return destination / "workflow.md" -def _resolve_project_root(raw: str | None) -> Path: +def _resolve_project_root(raw: str | None, *, include_workspace: bool = True) -> Path: """The explicit `--project-root`, else the nearest folder containing `_bmad/` via cwd walk-up or linked-worktree `commondir`, else the project of an installed `_bmad/scripts/` copy. @@ -799,12 +799,13 @@ def _resolve_project_root(raw: str | None) -> Path: """ if raw is not None: return Path(raw) - found = find_project_root() + found = find_project_root(include_workspace=include_workspace) if found is not None: return found - scripts = Path(os.path.abspath(__file__)).parent - if scripts.name == "scripts" and scripts.parent.name == "_bmad": - return scripts.parent.parent + if include_workspace: + scripts = Path(os.path.abspath(__file__)).parent + if scripts.name == "scripts" and scripts.parent.name == "_bmad": + return scripts.parent.parent raise RenderError("project root not found; pass --project-root pointing to the folder containing _bmad/") @@ -942,7 +943,8 @@ def main() -> int: f"this skill requires render_skill.py version {args.require_version}, " f"but this project has version {RENDERER_VERSION}; update the bmad skill, then run bmad setup in this project" ) - project_root = _resolve_project_root(args.project_root) + include_workspace = not args.no_workspace + project_root = _resolve_project_root(args.project_root, include_workspace=include_workspace) roots = tuple(args.root) skill_dir = _resolve_skill_dir(args.skill, project_root, roots) report_owed_setup(skill_dir.resolve(), project_root.resolve(), roots) @@ -952,7 +954,7 @@ def main() -> int: overrides=args.overrides, assignments=args.assignments, skill_roots=roots, - include_workspace=not args.no_workspace, + include_workspace=include_workspace, ) # Printed, not named: a file the model is told to read may be read only in part. workflow = entry.read_text(encoding="utf-8") diff --git a/skills/core-tools/bmad/scripts/resolve_config.py b/skills/core-tools/bmad/scripts/resolve_config.py index 88ddd9a21a..55d507a8d3 100644 --- a/skills/core-tools/bmad/scripts/resolve_config.py +++ b/skills/core-tools/bmad/scripts/resolve_config.py @@ -74,12 +74,14 @@ def write_json_stdout(output) -> None: sys.stdout.write(json.dumps(output, indent=2, ensure_ascii=False) + "\n") -def _resolve_project_root(raw: str | None) -> Path | None: +def _resolve_project_root(raw: str | None, *, include_workspace: bool = True) -> Path | None: if raw: return Path(raw).resolve() - found = find_project_root() + found = find_project_root(include_workspace=include_workspace) if found is not None: return found + if not include_workspace: + return None scripts = Path(os.path.abspath(__file__)).parent if scripts.name == "scripts" and scripts.parent.name == "_bmad": return scripts.parent.parent @@ -219,14 +221,15 @@ def main() -> int: parser.error("--legacy-external-sources and --legacy-external-handoffs cannot both read from stdin (`-`)") try: - project_root = _resolve_project_root(args.project_root) + include_workspace = not args.no_workspace + project_root = _resolve_project_root(args.project_root, include_workspace=include_workspace) if project_root is None: sys.stderr.write( "error: project root not found; pass --project-root pointing to the folder containing _bmad/\n" ) return 1 skill_roots = tuple(root.resolve() for root in args.root) or None - roots = (project_root,) if args.no_workspace else (find_bmad_roots(project_root) or (project_root,)) + roots = (project_root,) if not include_workspace else (find_bmad_roots(project_root) or (project_root,)) effective_root = roots[-1] if args.check: report = check_central_config(roots, skill_roots=skill_roots) diff --git a/skills/core-tools/bmad/scripts/resolve_customization.py b/skills/core-tools/bmad/scripts/resolve_customization.py index 02879768da..5882320a75 100755 --- a/skills/core-tools/bmad/scripts/resolve_customization.py +++ b/skills/core-tools/bmad/scripts/resolve_customization.py @@ -48,7 +48,7 @@ def script_project_root() -> Path | None: return None -def candidate_project_roots(skill_dir: Path) -> list[Path]: +def candidate_project_roots(skill_dir: Path, *, include_workspace: bool = True) -> list[Path]: """Plausible project roots, most trustworthy first. The working directory leads because the project is where the user is working, @@ -56,11 +56,16 @@ def candidate_project_roots(skill_dir: Path) -> list[Path]: `~`, and any `~/_bmad` there would otherwise mask the real project's overrides. """ ordered: list[Path] = [] - for root in ( - find_project_root(fallback_to_git=True), - script_project_root(), - find_project_root(skill_dir, fallback_to_git=True), - ): + candidates = ( + ( + find_project_root(fallback_to_git=True), + script_project_root(), + find_project_root(skill_dir, fallback_to_git=True), + ) + if include_workspace + else (find_project_root(fallback_to_git=False, include_workspace=False),) + ) + for root in candidates: if root is not None and root not in ordered: ordered.append(root) return ordered @@ -149,16 +154,17 @@ def main() -> int: try: skill_dir = Path(args.skill).resolve() + include_workspace = not args.no_workspace if args.project_root: project_root = Path(args.project_root).resolve() else: - candidates = candidate_project_roots(skill_dir) + candidates = candidate_project_roots(skill_dir, include_workspace=include_workspace) project_root = candidates[0] if candidates else None if project_root is not None: warn_on_masked_override(project_root, candidates[1:], skill_dir.name) if project_root is None: roots: tuple[Path, ...] = () - elif args.no_workspace: + elif not include_workspace: roots = (project_root,) else: roots = find_bmad_roots(project_root) or (project_root,) diff --git a/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py b/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py index e20569b722..62c17c359e 100644 --- a/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py +++ b/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py @@ -87,7 +87,8 @@ def _git(cwd: Path, *args: str) -> str: ["git", *args], cwd=str(cwd), env=_isolated_env(), - text=True, + encoding="utf-8", + errors="replace", capture_output=True, check=False, ) @@ -107,7 +108,8 @@ def _run( [sys.executable, str(script), *args], cwd=str(cwd), env=env or _isolated_env(), - text=True, + encoding="utf-8", + errors="replace", capture_output=True, check=False, ) @@ -199,7 +201,8 @@ def test_req1_scattered_git_config_workspace_formats_worktrees_submodules_and_di ["git", "-c", "protocol.file.allow=always", "submodule", "add", str(sub_seed), "mods/sub"], cwd=str(super_repo), env=_isolated_env(), - text=True, + encoding="utf-8", + errors="replace", capture_output=True, check=True, ) @@ -953,6 +956,73 @@ def test_review_edge_cases_parser_setup_no_workspace_and_checks(self): self.assertEqual(iso_pi.returncode, 0, iso_pi.stderr) self.assertNotIn("can't open file", iso_pi.stdout + iso_pi.stderr) + # 6. `--no-workspace` without `--project-root` in a linked/shared repo with no local `_bmad/` + # isolates cleanly (never inherits the workspace root). + child_no_bmad = ws_target / "no-bmad-child" + _init_git_repo(child_no_bmad) + for target_dir in (src_repo, child_no_bmad): + rc_iso = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--no-workspace", "--key", "core.project_name"], + cwd=target_dir, + env=self.env, + ) + self.assertEqual(rc_iso.returncode, 1) + self.assertIn("project root not found", rc_iso.stderr) + + rs_iso = _run( + BMAD_SCRIPTS / "render_skill.py", + ["--no-workspace", "--skill", str(REPO_ROOT / "skills" / "core-tools" / "bmad-review")], + cwd=target_dir, + env=self.env, + ) + self.assertEqual(rs_iso.returncode, 1) + self.assertIn("project root not found", rs_iso.stdout) + + cust_iso = _run( + BMAD_SCRIPTS / "resolve_customization.py", + ["--no-workspace", "--skill", str(REPO_ROOT / "skills" / "core-tools" / "bmad-review")], + cwd=target_dir, + env=self.env, + ) + self.assertEqual(cust_iso.returncode, 0, cust_iso.stderr) + + # 7. Sparse outer personal override of `knowledge_sources..target` / `artifact_destinations..target` + # resolves relative paths against the workspace root using inherited `kind = "path"`. + ws_sparse = self.root / "sparse-ws" + _install_bmad_runtime(ws_sparse, project_name="sparse-ws") + _write( + ws_sparse / "_bmad" / "custom" / "config.toml", + '[core.knowledge_sources.docs]\nkind = "path"\ntarget = "team-docs"\n\n' + '[core.artifact_destinations.site]\nkind = "path"\ntarget = "team-out"\nfor = ["*"]\n', + ) + _write( + ws_sparse / "_bmad" / "custom" / "config.user.toml", + '[core.knowledge_sources.docs]\ntarget = "personal-docs"\n\n' + '[core.artifact_destinations.site]\ntarget = "personal-out"\n', + ) + _write(ws_sparse / "personal-docs" / "note.md", "# Personal\n") + _write(ws_sparse / "personal-out" / ".keep", "") + inner_sparse = ws_sparse / "services" / "web" + _init_git_repo(inner_sparse) + _install_bmad_runtime(inner_sparse, project_name="web") + rs_sparse = _run( + BMAD_SCRIPTS / "resolve_config.py", + ["--project-root", str(inner_sparse), "--resolve-sources", "--resolve-destinations"], + cwd=inner_sparse, + env=self.env, + ) + self.assertEqual(rs_sparse.returncode, 0, rs_sparse.stderr) + sparse_payload = json.loads(rs_sparse.stdout) + self.assertEqual( + sparse_payload["knowledge_sources"]["sources"][0]["target"], + (ws_sparse / "personal-docs").resolve().as_posix(), + ) + self.assertEqual( + sparse_payload["artifact_destinations"]["destinations"][0]["target"], + (ws_sparse / "personal-out").resolve().as_posix(), + ) + if __name__ == "__main__": unittest.main() From 169c89747c514f48a2c8db7840acccf33f8088d7 Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Sun, 29 Nov 2026 21:29:58 -0600 Subject: [PATCH 8/8] fix(bmad): include inner team layers when resolving sparse outer targets Update `effective_merged` across inner repository layers as well as outer layers inside `central_config_layers_for_roots`, so workspace personal overrides that change only `target` observe any intermediate repo-team `kind` override and never rewrite non-path external targets as filesystem paths. --- .../core-tools/bmad/scripts/config_utils.py | 22 ++++++++++-------- .../test_story17_polyrepo_and_degradation.py | 23 +++++++++++++++---- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/skills/core-tools/bmad/scripts/config_utils.py b/skills/core-tools/bmad/scripts/config_utils.py index 3335da13c2..57c5f6f805 100644 --- a/skills/core-tools/bmad/scripts/config_utils.py +++ b/skills/core-tools/bmad/scripts/config_utils.py @@ -1149,25 +1149,29 @@ def central_config_layers_for_roots( layers.append(defaults_layer) anchor_outer = len(roots) > 1 inner_root = roots[-1] if roots else None - effective_outer: dict[str, Any] = {} + effective_merged: dict[str, Any] = merge_layers(layers) if (anchor_outer and layers) else {} for root in roots: bmad_dir = root / "_bmad" for layer in ( load_toml(bmad_dir / "config.toml", required=require_project and root == inner_root), load_toml(bmad_dir / "custom" / "config.toml"), ): - if anchor_outer and root != inner_root: - anchored = _anchor_layer_paths(layer, root, prior_merged=effective_outer) - effective_outer = merge_layers((effective_outer, anchored)) - layers.append(anchored) + if anchor_outer: + resolved_layer = ( + _anchor_layer_paths(layer, root, prior_merged=effective_merged) if root != inner_root else layer + ) + effective_merged = merge_layers((effective_merged, resolved_layer)) + layers.append(resolved_layer) else: layers.append(layer) for root in roots: layer = _user_layer_for_root(root) - if anchor_outer and root != inner_root: - anchored = _anchor_layer_paths(layer, root, prior_merged=effective_outer) - effective_outer = merge_layers((effective_outer, anchored)) - layers.append(anchored) + if anchor_outer: + resolved_layer = ( + _anchor_layer_paths(layer, root, prior_merged=effective_merged) if root != inner_root else layer + ) + effective_merged = merge_layers((effective_merged, resolved_layer)) + layers.append(resolved_layer) else: layers.append(layer) return tuple(layers) diff --git a/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py b/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py index 62c17c359e..d61e9ff451 100644 --- a/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py +++ b/tests/core-tools/bmad/test_story17_polyrepo_and_degradation.py @@ -994,18 +994,27 @@ def test_review_edge_cases_parser_setup_no_workspace_and_checks(self): _write( ws_sparse / "_bmad" / "custom" / "config.toml", '[core.knowledge_sources.docs]\nkind = "path"\ntarget = "team-docs"\n\n' - '[core.artifact_destinations.site]\nkind = "path"\ntarget = "team-out"\nfor = ["*"]\n', + '[core.knowledge_sources.wiki]\nkind = "path"\ntarget = "team-wiki"\n\n' + '[core.artifact_destinations.site]\nkind = "path"\ntarget = "team-out"\nfor = ["*"]\n\n' + '[core.artifact_destinations.portal]\nkind = "path"\ntarget = "team-portal"\nfor = ["*"]\n', ) _write( ws_sparse / "_bmad" / "custom" / "config.user.toml", '[core.knowledge_sources.docs]\ntarget = "personal-docs"\n\n' - '[core.artifact_destinations.site]\ntarget = "personal-out"\n', + '[core.knowledge_sources.wiki]\ntarget = "space=Docs"\n\n' + '[core.artifact_destinations.site]\ntarget = "personal-out"\n\n' + '[core.artifact_destinations.portal]\ntarget = "space=Portal"\n', ) _write(ws_sparse / "personal-docs" / "note.md", "# Personal\n") _write(ws_sparse / "personal-out" / ".keep", "") inner_sparse = ws_sparse / "services" / "web" _init_git_repo(inner_sparse) _install_bmad_runtime(inner_sparse, project_name="web") + _write( + inner_sparse / "_bmad" / "custom" / "config.toml", + '[core.knowledge_sources.wiki]\nkind = "mcp"\ntool = "atlassian"\n\n' + '[core.artifact_destinations.portal]\nkind = "mcp"\ntool = "atlassian"\n', + ) rs_sparse = _run( BMAD_SCRIPTS / "resolve_config.py", ["--project-root", str(inner_sparse), "--resolve-sources", "--resolve-destinations"], @@ -1014,14 +1023,20 @@ def test_review_edge_cases_parser_setup_no_workspace_and_checks(self): ) self.assertEqual(rs_sparse.returncode, 0, rs_sparse.stderr) sparse_payload = json.loads(rs_sparse.stdout) + sources_by_id = {s["id"]: s for s in sparse_payload["knowledge_sources"]["sources"]} + dests_by_id = {d["id"]: d for d in sparse_payload["artifact_destinations"]["destinations"]} self.assertEqual( - sparse_payload["knowledge_sources"]["sources"][0]["target"], + sources_by_id["docs"]["target"], (ws_sparse / "personal-docs").resolve().as_posix(), ) + self.assertEqual(sources_by_id["wiki"]["kind"], "mcp") + self.assertEqual(sources_by_id["wiki"]["target"], "space=Docs") self.assertEqual( - sparse_payload["artifact_destinations"]["destinations"][0]["target"], + dests_by_id["site"]["target"], (ws_sparse / "personal-out").resolve().as_posix(), ) + self.assertEqual(dests_by_id["portal"]["kind"], "mcp") + self.assertEqual(dests_by_id["portal"]["target"], "space=Portal") if __name__ == "__main__":