diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fee5f35a..6eb59b78c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -133,6 +133,25 @@ breaking changes may land in a minor release. ends there non-completed and takes the existing uncharged pauses (`hook channel silent:`, or `parked:` / `no work produced:` when the pane shows a parked prompt or never changed) instead of waiting out `session_timeout_min`. +- Add opt-in `[skills] user_roots` (default off): resolve a BMAD skill the project + lacks from the user-level folders the coding CLI loads on its own (`npx skills add -g`). + Each packaged profile declares those folders, its disabling variables and its + clash precedence in a new `[user_skills]` table; validate, preflight, `run --dry-run`, + dispatch and worktree seeding share one lookup, so `validate` checks the copy the + session loads. `validate` reports each driven skill's location (`skills.root`) and + warns on `skills.user-root-unavailable`, `-version-skew`, `-unsupported` (opencode + 1.x, whose sessions then refuse to start) and `-sandboxed`; sessions journal + `skill-user-root`. opencode 2.x allows only the BMAD module skills a session needs + from a user root. See ADR 0002 (#770). +- Warn with `skills.user-shadow` when a user-level copy of a driven skill outranks + the project's checked copy (claude, with `[skills] user_roots` off) or competes with + it (codex, antigravity, whatever the switch). +- Read opencode-http's project skills from `.agents/skills` as well as + `.claude/skills` (new profile field `extra_skill_trees`, refused when an entry starts + with `-`); on opencode 2.x the `.claude/skills` copy wins a duplicate id, as + `validate` assumes. +- Add a `{skill_dir}` profile prompt placeholder (the located skill folder); copilot's + prompt uses it. ### Changed @@ -176,6 +195,15 @@ breaking changes may land in a minor release. - With `[verify] reuse_unchanged` on, `post_review_verify` may carry the reused pass's `dev`/`fix` stage and sequence, flagged by the new `verification_reused` (#1002). - Name each BMAD-METHOD module folder in the module record's skill sources: `skills/core-tools` for `bmad`, `skills/method` for `bmad-build-auto`, `bmad-agent-po` and `bmad-retrospective`. BMAD-METHOD moved each module's skills into its own folder. +- Refuse a leading `~` in a profile's `skill_tree`, `extra_skill_trees`, `seed_files` + and `hooks.config_path` at load: it is not expanded. +- Report a skill tree, or a skill the run requires linked inside it, that resolves + outside the project or repository as `skills.tree-outside`; under worktree isolation + a link outside the repository is refused at preflight (and named by the + `run --dry-run` banner) instead of escalating mid-run. +- Change copilot's default prompt template to `{skill_dir}`: the text is unchanged + for project skills, but the config digest changes once, so the first resume of a + copilot run after upgrading journals `security_config_changed`. ### Removed @@ -201,8 +229,8 @@ breaking changes may land in a minor release. refuses to load as a `skills.customize-unreadable` problem. - Report a missing dev primitive once, without stacking review-skill and dispatch failures under the legacy `bmad-dev-auto` name on top of it. Name core-tools as - the v7 home of `bmad-review`, and note when a missing skill is installed only - globally (`~/.claude/skills`, `~/.agents/skills`). + the v7 home of `bmad-review`, and note when a missing skill is installed only in + one of the CLI's own user-level folders, naming `[skills] user_roots`. - Stop reading an empty psmux window listing as a dead session. psmux can drop a live server's reply and exit 0 with nothing, which the liveness probe took for a crashed CLI and the control-window prune for a verified kill. That listing now counts as a failed diff --git a/docs/FEATURES.md b/docs/FEATURES.md index c314b0908..8d6a8973d 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -348,6 +348,22 @@ bmad-loop drives a BMAD sprint unattended: a deterministic Python loop launches - **Tested by:** `tests/test_profile.py`, `tests/test_probe.py`, `tests/test_adapter_registry.py`, `tests/test_workspace_trust.py`, `tests/test_codex_trust.py`, `tests/test_generic_tmux.py`, `tests/test_cli.py` - **Docs:** [Choosing which CLIs to drive](setup-guide.md#choosing-which-clis-to-drive), [Codex shared app-server daemon](setup-guide.md#codex-shared-app-server-daemon), [Adapter authoring guide: finalizing a profile](adapter-authoring-guide.md#walkthrough-finalizing-a-profile), [CLI reference: probe-adapter](reference/cli.md#probe-adapter), [CLI reference: adapters](reference/cli.md#adapters) +### User-level skill roots + +- **Stability:** experimental +- **Description:** An opt-in that lets a run use BMAD skills installed in the user's home folder (`npx skills add -g`) instead of the project's skill trees. Each CLI's profile declares the user folders that CLI loads on its own and which copy it runs on a name clash, so `validate` checks the copy the session will load. +- **Properties:** + - Off by default: skills resolve only from the project's skill trees, and a skill found only in a user root keeps the run refused with a hint naming that copy. + - On, `validate`, the run preflight, `run --dry-run`, session dispatch and worktree seeding resolve every skill through the same lookup, and `validate` reports where each driven skill was found (`skills.root`). + - Only the folders a profile's `[user_skills]` table declares are searched; a root disabled by a set environment variable or unreadable is skipped and reported. + - With the switch on, a claude user copy outranks the project's, as Claude Code itself does. A user copy the CLI runs instead of the project copy the checks read is reported as `skills.user-shadow`: for claude with the switch off, for codex and antigravity (no stated order) with the switch on or off. + - Each session journals the skills it loads from a user root (`skill-user-root`); worktrees never copy from a user root. + - opencode-http 2.x allows only the BMAD module skills a session needs from a user root, never the operator's personal skills; on 1.x the session refuses to start and `validate` warns. + - A leading `~` in a profile's `skill_tree`, `extra_skill_trees`, `seed_files` or `hooks.config_path` is refused, and a skill tree linked outside the repository is refused at preflight under worktree isolation. +- **Config:** `[skills] user_roots`; profile `[user_skills]`, `extra_skill_trees` +- **Tested by:** `tests/test_skill_locate.py`, `tests/test_install.py`, `tests/test_profile.py`, `tests/test_cli.py`, `tests/test_engine.py`, `tests/test_engine_worktree.py`, `tests/test_opencode_protocol.py`, `tests/test_opencode_http.py` +- **Docs:** [Project skills and user-level skill roots](setup-guide.md#project-skills-and-user-level-skill-roots), [Adapter authoring guide: user-level skill roots](adapter-authoring-guide.md#user-level-skill-roots), [Configuration reference: [skills]](reference/configuration.md#skills) + ### Per-stage adapters - **Stability:** stable diff --git a/docs/adapter-authoring-guide.md b/docs/adapter-authoring-guide.md index 76608d907..03993210e 100644 --- a/docs/adapter-authoring-guide.md +++ b/docs/adapter-authoring-guide.md @@ -340,8 +340,10 @@ a new `name` extends the set. The aliases `claude-code-tmux` and `opencode` reso | `binary` | ✅ | — | Executable resolved on `PATH`. `validate` runs `--version` only on binary names a packaged profile declares (`adapter.binary-unrunnable`). | | `[hooks]` | ✅ | — | The [`HookSpec`](#hookspec-the-hooks-table) table. | | `adapter` | | `generic` (`opencode-http` if `dialect=none`) | Adapter kind, resolved against the live [registry](#shipping-a-new-adapter-class-out-of-tree) at run start and by `validate` (`adapter.kind`). `generic` with `dialect = "none"` is refused. | -| `skill_tree` | | `.claude/skills` | Project-relative tree the CLI reads skills from; `init` installs the `bmad-loop-*` skills here. Must stay inside the project. | -| `prompt_template` | | `{prompt}` | Renders the canonical `/skill args` prompt. Placeholders: `{prompt}` (whole string), `{skill}` (command name, no `/`), `{args}` (the rest). | +| `skill_tree` | | `.claude/skills` | Project-relative tree the CLI reads skills from; `init` installs the `bmad-loop-*` skills here. Must stay inside the project; a leading `~` is refused (it is not expanded). | +| `extra_skill_trees` | | `[]` | Further project-relative trees the CLI also reads skills from (opencode-http: `[".agents/skills"]`). Each entry gets the `skill_tree` checks and must differ from it. Read by validate, the run and worktree seeding; `init` installs only into `skill_tree`. | +| `[user_skills]` | | unset | The user-level folders the CLI loads skills from on its own, used only under `[skills] user_roots = true`. See [User-level skill roots](#user-level-skill-roots). Unset: no user root is resolved, hinted or shadow-checked. | +| `prompt_template` | | `{prompt}` | Renders the canonical `/skill args` prompt. Placeholders: `{prompt}` (whole string), `{skill}` (command name, no `/`), `{args}` (the rest), `{skill_dir}` (the skill's folder: `/`, or the absolute path when it resolved from a user root). | | `launch_args` | | `[]` | Argv after `binary` (`["-i"]` keeps gemini/copilot interactive). Under `opencode-http` it precedes `serve`; `validate` warns on unservable shapes. | | `bypass_args` | | `[]` | Permission-bypass flags for unattended runs, launched under `permission_mode = "bypass"`. A policy `extra_args` replaces them; `validate` warns (`policy.bypass-dropped`) when one is dropped. | | `model_flag` | | `--model` | Flag passed with the model name when one is configured. | @@ -454,6 +456,33 @@ settings_path = "~/.gemini/antigravity-cli/settings.json" key = "trustedWorkspaces" ``` +### User-level skill roots + +The `[user_skills]` table declares the folders in the user's home that the CLI loads skills +from by itself. bmad-loop resolves a skill from them only when the project sets +`[skills] user_roots = true`; with the switch off they serve the `skills.base-missing` hint +and the `skills.user-shadow` warning. + +```toml +[user_skills] +precedence = "project" +roots = [ + { path = "~/.copilot/skills", disabled_by = ["COPILOT_HOME"] }, + "~/.agents/skills", +] +``` + +| Key | Default | Meaning | +| ------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `precedence` | `"project"` | Which copy the CLI runs when the project and a user root both hold one: `project` (the project's), `user` (the user root's; validate and the run check that copy) or `unordered` (both load in no documented order; bmad-loop checks the project copy and warns). | +| `roots` | `[]` | The user roots, in the order the CLI reads them. Each is a `"~/..."` string or a `{ path = "~/...", disabled_by = [...] }` table. A path must start with `~/` and stay inside the home folder; duplicate roots are refused. | +| `disabled_by` | `[]` | Environment variables that make the CLI skip this root when set (even to an empty value), such as a variable that moves the CLI's config home. Read from bmad-loop's environment plus the profile's `[env]`; at session dispatch, also the env a `pre_session` plugin hook sets. | + +Declare only folders the CLI loads natively, as its own docs describe them. `validate` passes +a skill found in a declared root, so a root the CLI does not read gives a green `validate` +and a session that cannot find its skill. Recheck the list when the CLI changes how it +discovers skills. + ### Environment-fault patterns `env_fault_patterns` are matched line by line against the ANSI-stripped log tail of a diff --git a/docs/adr/0002-user-level-skill-roots.md b/docs/adr/0002-user-level-skill-roots.md new file mode 100644 index 000000000..9820e3f1a --- /dev/null +++ b/docs/adr/0002-user-level-skill-roots.md @@ -0,0 +1,86 @@ +# ADR 0002: Resolving BMAD skills from user-level skill roots + +- **Status:** Accepted (2026-11-15) +- **Date:** 2026-11-15 +- **Issues:** #770 (use globally installed BMAD skills); context #768 / PR #1054 (the project-tree-only rule this record reverses behind an opt-in) +- **Seam:** `skill_locate` (`src/bmad_loop/skill_locate.py`), the profile `[user_skills]` table (`src/bmad_loop/adapters/profile.py`), the `[skills] user_roots` policy switch + +**Decision in brief:** + +1. Keep project-tree-only resolution as the default. Add an opt-in switch, `[skills] user_roots = false`. +2. With the switch on, resolve a skill from a user-level folder only when the coding CLI's profile declares that folder: the folders the CLI loads natively, in the CLI's own order, with the CLI's own precedence (`project`, `user` or `unordered`) and the environment variables that make it skip a folder. +3. Route every skill question through one locator: `validate`, the run preflight, `run --dry-run`, session dispatch, the render probe, review-lens reads and worktree seeding. +4. opencode-http 2.x allows only the BMAD module skills a session needs from a user root; 1.x is refused. Worktrees never copy from a user root. + +## 1. Problem + +`npx skills add -g` installs skills into the user's home folder (`~/.agents/skills`, `~/.claude/skills`, and others depending on the target CLI). bmad-loop resolved every skill as `//`, so a project relying on a global install failed `validate` with `skills.base-missing`. The only workaround, a junction from the project tree to the global folder, passed `validate` and then broke `init` and worktree seeding, which escalated mid-run. + +On 2026-11-14 #768 (merged as PR #1054) settled the question as "project tree only": `validate` refused a global-only install and named the global copy in a read-only hint. The issue asked for the opposite. This record reverses that rule, behind an opt-in. + +Two facts shape the design: + +- **There is no single global folder.** Checked against vendor docs and source on 2026-11-15: + + | CLI | Global folders it loads | On a name clash | + | ----------- | ------------------------------------------------------------------- | ----------------------------------------------- | + | Claude Code | `~/.claude/skills` only | personal beats project | + | Codex | `~/.agents/skills` and the deprecated `~/.codex/skills` | both appear, no order | + | Gemini | `~/.agents/skills` and `~/.gemini/skills` | workspace beats user; `.agents` beats `.gemini` | + | Copilot CLI | `~/.copilot/skills` and `~/.agents/skills` | project beats personal | + | Antigravity | `~/.gemini/config/skills` | not documented | + | OpenCode | `~/.config/opencode/skills`, `~/.claude/skills`, `~/.agents/skills` | project wins | + +- **A stale global copy already ran in place of the one `validate` checked.** Claude Code runs `~/.claude/skills/` over the project's copy, so a project-tree-only `validate` could pass a primitive the session never loaded. + +The governing constraint: `validate` must never pass when the session cannot load the skill. + +## 2. Options + +### A. Keep the project-tree-only rule + +No change; document the per-project install. Rejected: it leaves the shadowing case above undetected, and it refuses an install method the skills CLI offers as a first-class choice. + +### B. A free-form `~` path in `skill_tree` + +Let a profile or policy name `skill_tree = "~/.agents/skills"`. Rejected: + +- A tree is also where `init` installs and what worktree seeding copies. A home path would make `init` write into the user's home and worktrees copy from it. +- Nothing ties the path to what the CLI loads. A path the CLI never reads gives a green `validate` and a session that cannot find its skill. +- It already loaded silently and resolved to a literal `/~/...`. This change refuses a leading `~` in every profile path instead. + +### C. Fall back to one global folder automatically + +When a skill is missing from the project, look in `~/.agents/skills`. Rejected: that folder is not what Claude Code, Antigravity or (with `COPILOT_HOME`) Copilot read, and the fallback ignores which copy a CLI prefers on a clash. `validate` would check a copy the session does not run. + +### D. Declared, per-CLI user roots behind an opt-in (chosen) + +Each packaged profile declares, in a `[user_skills]` table, the folders its CLI loads natively, in its own order, with its precedence and its disabling variables. A profile without the table (overlays, entry-point profiles) never resolves from a user root. The switch defaults off, so existing projects resolve exactly as before. + +## 3. Decision + +Option D. + +- **One locator.** `skill_locate.locate(project, scope, name)` answers every skill question. A `SkillScope` carries the project trees, the declared user roots and the switch; a plain tree string is a project-only scope, which keeps every existing caller and output unchanged. +- **Precedence follows the CLI.** `project`: the project copy, else a user copy. `user` (claude): the user copy, else the project's, so `validate` checks the copy Claude Code runs. `unordered` (codex, antigravity): the project copy is checked and a warning says both load. +- **Shadowing is reported with the switch off.** `skills.user-shadow` warns whenever the CLI may run a user copy over or beside the project copy the checks read, because the CLI loads it whether or not bmad-loop resolves it. With the switch on, a `user`-precedence copy is the one resolved, so only an `unordered` clash still warns. +- **Unavailable roots are skipped, not guessed.** A root whose disabling variable is set (in bmad-loop's environment plus the profile's `[env]`), that cannot be read, or that has no home folder is never resolved and is reported as `skills.user-root-unavailable`. +- **Visibility.** `validate` emits a `skills.root` line per driven skill; `run --dry-run` prints a note for each user-root skill; each session journals `skill-user-root` rows. + +### opencode isolation trade-off + +opencode-http keeps sessions hermetic from the operator's personal skills. On 1.x it sets `OPENCODE_DISABLE_EXTERNAL_SKILLS=1`; on 2.x it denies every skill and re-allows the project's ids. + +- **2.x:** the allow-list also takes the BMAD module skill ids the session needs from a user root: the dev primitive, its review lenses, the prompt skill, and the ids a user root's `bmod-*/bmod.toml` lists. Personal skills stay denied. This opens the hermetic boundary only by ids BMAD itself declares. +- **1.x:** there is no per-id control; lifting `OPENCODE_DISABLE_EXTERNAL_SKILLS` would expose every personal skill. User roots are unsupported there: `validate` warns (`skills.user-root-unsupported`) and the session refuses to spawn, so `validate` and the run agree. + +### Worktrees + +A worktree is a clean checkout; it never carries the user's home folder. Seeding copies only from project trees, and the seeding gate exempts skills the locator puts in a user root (journaled as `worktree-skills-user-root`): the session loads those from the home folder directly. A skill tree linked outside the repository is refused at preflight under worktree isolation (`skills.tree-outside`), because the worktree cannot carry it and the run used to escalate mid-run. + +## 4. Consequences + +- Deliberate changes with the switch off: a leading `~` in a profile path is a load error; `skills.tree-outside` refuses at preflight under worktree isolation; `skills.user-shadow` warns; the `skills.base-missing` hint names only a copy in the CLI's own user roots; opencode-http also reads `.agents/skills`; copilot's prompt names the located skill folder through `{skill_dir}`, which changes its config digest once. +- The vendor folder lists drift. The profiles carry the lists as data with source comments; they must be rechecked when a CLI changes how it discovers skills. +- Disabling variables are read from bmad-loop's environment, not a long-lived multiplexer server's, which can differ. +- Which copy opencode 1.x loads when one id is in both of its project trees is not pinned (2.x lists the primary tree last, so its copy wins); the skills CLI normally links the two. diff --git a/docs/adr/README.md b/docs/adr/README.md index f7f107f16..fe2423048 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -2,6 +2,7 @@ Each record states one design decision: the problem, the options that were weighed, what was chosen, and why. Records are numbered and never renumbered. A superseded record stays in place and links to the record that replaces it. -| ADR | Title | Status | -| --------------------------------- | ------------------------------------------------------------ | -------- | -| [0001](0001-mux-env-transport.md) | Carrying the state root into session and parked-window panes | Accepted | +| ADR | Title | Status | +| -------------------------------------- | ------------------------------------------------------------ | -------- | +| [0001](0001-mux-env-transport.md) | Carrying the state root into session and parked-window panes | Accepted | +| [0002](0002-user-level-skill-roots.md) | Resolving BMAD skills from user-level skill roots | Accepted | diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index f15cae228..a05dba905 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -797,6 +797,17 @@ Before relying on it: relay hooks are in the project's `.claude/settings.json` and work with any directory. - Never commit, ship or log credentials. Keep the config directories outside the project tree, and never echo their contents from a hook or wrapper. +- Setting `CLAUDE_CONFIG_DIR` makes Claude Code skip `~/.claude/skills`, so install the + skills your sessions use in the project tree. Under `[skills] user_roots`, what bmad-loop + catches depends on where the variable is set: + - **A `pre_session` hook:** a session whose skill came from `~/.claude/skills` stops + before launch, with an error naming the skill and the variable, unless the project + tree holds a byte-identical copy. So does a dev session whose primitive needs a + review skill that came from there. + - **The parent environment or the profile `[env]`:** preflight reports + `~/.claude/skills` as `skills.user-root-unavailable`. + - **A wrapper `binary`:** the script sets the variable after bmad-loop has checked the + session, so nothing catches it, and the session launches without that skill. ### Sweep (deferred-work cycle — bundles inherit all per-story stages) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 833dd690d..bbd5f0f1f 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -164,7 +164,8 @@ bmad-loop run [--project PROJECT] [--spec FOLDER] [--epic EPIC] [--story STORY] - Sprint mode selects stories at `backlog` or `ready-for-dev`. A `--story` that matches nothing, matches several stories, or is not actionable exits 1. - A non-integer `--epic` exits 2 outside tickets mode. - In tickets mode `run` resolves the selectors against the active initiative before anything is created. `--epic` must name one epic of the initiative table. `--story` goes through `tickets.py find` and must name one ticket that `next` lists as ready to start or to refine (and that is in the `--epic` epic, when both are given). Anything else exits 1. The run then picks only within the selection, and finishes once it has nothing left to start there. `--dry-run` applies the same selection. -- Refused with exit 1 before anything is created on: git below the supported floor, a dirty worktree, a worktree-isolation conflict, missing base skills, or a failing plugin-trust verdict. +- Refused with exit 1 before anything is created on: git below the supported floor, a dirty worktree, a worktree-isolation conflict, missing base skills, a skill tree that leaves the repository under worktree isolation (`skills.tree-outside`), or a failing plugin-trust verdict. +- Under `[skills] user_roots`, `--dry-run` prints one `note:` line on stderr for each skill that resolves from a user root (`~/…`), naming the copy the sessions will load. - `[stories] source = "tickets"` runs the active initiative's ticket tree. Before anything is created, `run` executes the `tickets.*` preflight (capability probe included) and refuses with exit 1 on a problem, including a ticket store it cannot classify or drive (`tickets.store-topology` and the refusals below). The classified topology is recorded on the run, and `resume`, `resolve` and the TUI refuse a store that changed since; `branch_per = "run"` prints the `tickets.branch-per-run` warning. Each picked ticket is dispatched as `ticket ` and, once verified at `built`, marked `done` under `[tickets] mark_done = "auto"` (left at `built` under `"never"`): inside its unit's commit for a store tracked in the code checkout (T1), after the code lands for a shared store, with a plan-only commit in a store that is its own repository (T3/T4). Under worktree isolation a unit's branch is `bmad-loop///`. - On a parent initiative, `run` builds the children one run each: the first child `next ` lists as ready, skipping one with no folder or nothing left to dispatch, then the next after each run that finishes. Before each pick, its first included (after the clean-worktree, skills and plugin-trust checks, and journaled in the first child's run), it marks every drained child's initiative `done` and prints `... closed (drained)`, or `... leaves open (: ...)` while a run holds the child, its first pick still finds work, or its store is refused. It prints `initiative chain : -> ` per switch, or `... ends ()` with each waiting child's unmet prerequisites and their status, and stops at a run that does not finish, including each child's pause at `epic-boundary` after every epic it finishes; `resume` or `resolve` driving that run to finished continues the chain. `--epic` and `--story` exit 1 there; `--run-id` names the first child's run; `--max-stories` is one budget for the whole chain, and the chain ends `max-stories` once it is spent. - A launch check that refuses the next child's run of a parent initiative (a dirty worktree, the skills, plugin trust, the child's store) ends the chain `launch-refused`, and `run` exits with that check's exit code. @@ -631,112 +632,119 @@ Codes 3–129 and 131 and above are unallocated. Every finding's `check` is one of these ids. Severity is `ok`, `warning` or `problem`; only `problem` fails `validate`. -| Check id | Severity | What it checks | -| -------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `bmad-config` | ok / problem | BMAD config loads and artifact paths resolve; on BMAD v7 the ok line names the era and the active initiative | -| `bmad-config.initiative-unset` | warning | BMAD v7 with no `[core] active_initiative`: artifacts resolve to the output folder | -| `bmad-config.v6-keys-ignored` | warning | a mixed install resolved as BMAD v7 for tickets mode, ignoring leftover v6 artifact keys | -| `policy` | ok / problem | `.bmad-loop/policy.toml` loads | -| `policy.deprecated` | warning | a deprecated `policy.toml` key still loads (for example an empty-name `[engine]` block) | -| `policy.isolation-repo-root` | problem | `isolation = "worktree"` with the project outside the code root | -| `policy.isolation-shared-artifact-dir` | warning | under worktree isolation, an artifact dir shared with the main checkout | -| `policy.model-qualified` | warning | an opencode-http role model that is not `provider/model` | -| `policy.extra-args-unservable` | warning | an opencode-http role's `extra_args` repeats an adapter-owned serve flag | -| `policy.effort-unsupported` | warning | `effort` set on a profile whose adapter ignores it | -| `policy.bypass-dropped` | warning | an explicit `extra_args` drops the profile's `bypass_args` | -| `adapter.permission-mode-unsupported` | problem | a role's profile cannot run its `permission_mode` on this platform | -| `adapter.permission-mode` | ok / warning | each role's permission posture; a warning for sandboxed Codex under worktree isolation when no linked-worktree gitdir grant rides | -| `adapter.launch-probe` | ok / warning / problem | `--probes`: each distinct `generic`-profile launch; a startup dialog is a problem, an unseen screen a warning; ok with nothing launched if no patterns | -| `adapter.profile` | problem | a role's adapter name does not resolve to a loadable profile | -| `adapter.binary` | ok / problem | the profile binary is on `PATH` | -| `adapter.binary-unrunnable` | warning | a packaged profile's binary is on `PATH` but `--version` fails | -| `adapter.httpx` | ok / problem | `httpx` is importable for an opencode-http profile | -| `adapter.launch-args-unservable` | warning | an opencode-http profile's `launch_args` cannot form a valid serve command | -| `adapter.opencode-version` | ok / warning | the OpenCode server API an opencode-http binary's `--version` reports is supported | -| `adapter.codex-version` | ok / warning | a Codex binary accepts `--no-daemon` (>= 0.156) and the profile's `launch_args` pass it | -| `adapter.hookless` | ok | the profile is hookless, so hook checks are skipped | -| `adapter.kind` | ok / problem | the profile's `adapter` kind is registered | -| `adapter.external` | warning | a third-party adapter entry point failed to load | -| `adapter.external-profile` | warning | a third-party profile entry point failed to load | -| `hooks.config-parse` | problem | the hook config file is not valid JSON, is not a JSON object, or has malformed handlers | -| `hooks.registered` | ok / problem | relay hooks are registered for the profile's events in the project hook config, where `init` writes them; user- or local-scope settings are not read | -| `hooks.events-incomplete` | ok / warning | a mapped hook event besides Stop has no relay; the warning names `bmad-loop init --cli `, or the CLI version it needs | -| `hooks.trust` | ok / problem | Codex project hook trust is current | -| `hooks.relay-path-unsafe` | warning | a registered relay path has shell metacharacters the host's quoting leaves unsafe | -| `hooks.relay-present` | ok / problem | each registered relay executable exists and is usable | -| `hooks.relay-stale` | warning | a registered relay path differs from this installation's relay | -| `queue.sprint-status` | ok / problem | sprint mode: `sprint-status.yaml` loads; counts actionable stories | -| `queue.sprint-status-unknown-keys` | warning | sprint mode: unknown keys in `sprint-status.yaml` were ignored | -| `queue.nested-specs` | warning | sprint mode: spec-like files in artifact subdirectories, or unreadable subdirectories | -| `queue.stories-manifest` | ok / problem | stories mode: `stories.yaml` and `SPEC.md` are valid | -| `git.worktree-clean` | ok / problem | the code root's worktree is clean | -| `git.probe` | problem | the git check itself failed (spawn, timeout, error) | -| `git.version` | ok / problem | host git meets the supported floor | -| `git.render-tracked` | warning | the rendered-skill output dir is tracked by git | -| `deferred.ledger-unreadable` | problem | the deferred-work ledger cannot be read | -| `deferred.ledger-untracked` | warning | the ledger is neither committed nor gitignored | -| `deferred.ledger-ignored-isolated` | warning | the ledger is gitignored under worktree isolation, so session writes are lost | -| `deferred.hard-gate` | ok / problem | an actionable story or ticket is gated by a not-`done` ledger entry; tickets mode also fails a v6 key no single ticket claims, or a tree fault | -| `deferred.hard-gate-unstructured` | warning | a not-done entry declares a gate `validate` cannot enforce (malformed, empty or misspelled `gate:`, or a prose-only `HARD GATE:`) | -| `deferred.closes-malformed` | warning | a spec's `closes_deferred` has an unreadable shape | -| `deferred.closes-entry-unreadable` | warning | `closes_deferred` names entries that are neither open nor done | -| `deferred.closes-unknown` | warning | `closes_deferred` names ids not in the ledger | -| `operator.actions-malformed` | warning | sprint mode: a parked story's `operator_actions` declares nothing readable | -| `operator.confirm-interrupted` | warning | sprint mode: a confirmation signed the spec but never advanced the board | -| `operator.registry-stale` | warning | sprint mode: a park record disagrees with the spec or board, so `confirm` will refuse it | -| `operator.park-record-missing` | warning | sprint mode: the board parks a story that no park record claims | -| `plugins.manifests` | ok / warning / problem | every `plugin.toml` parses (problem); unsupported manifests are skipped (warning) | -| `plugins.trust` | ok / problem | project plugins are granted and unchanged, and the grant store is readable | -| `mux.backend` | ok / problem | the selected multiplexer backend is available | -| `mux.preflight` | problem | multiplexer selection or readiness raised an error | -| `mux.backends-detected` | ok / warning | inventory of detected backends when more than one is registered; detection failure (warning) | -| `mux.backend-probe` | warning | a registered backend's platform or availability probe raised an error | -| `mux.selection` | ok / warning | why the backend was selected; `fallback` is a warning | -| `mux.external-backend` | warning | a third-party multiplexer backend entry point failed to load | -| `host.process` | ok / problem | the process host resolves; an unknown `BMAD_LOOP_PROCESS_HOST` is a problem | -| `host.win32-on-wsl-path` | warning | a Windows interpreter is working on a WSL UNC project path | -| `notify.desktop-unavailable` | warning | `[notify] desktop` is on but the platform has no desktop notifier | -| `environment.probes-not-run` | ok | probes are configured but `--probes` was not passed | -| `environment.probes-none` | ok | `--probes` was passed with no probes configured | -| `environment.probe` | ok / problem | one per probe under `--probes`; `detail.status` is `pass`, `fail`, `timeout` or `interrupted` | -| `skills.base` | ok | the dev primitive and review layers are present | -| `skills.base-missing` | problem | the dev primitive or a review-layer skill is not installed | -| `skills.base-incomplete` | problem | the dev primitive is missing marker files | -| `skills.base-shim` | problem | the legacy dev primitive is unusable and the new one is absent | -| `skills.dev-renderer` | problem | a renderer-stub primitive lacks its renderer script | -| `skills.dev-renderer-sources` | problem | a renderer stub's render sources are unresolved | -| `skills.dev-renderer-config` | problem | a renderer stub's central config layer is missing | -| `skills.dev-render-probe` | ok / problem | `--render-probe` only: the stub's render command succeeds in a temp copy | -| `skills.customize-legacy` | warning | customize overrides named for the legacy dev primitive no longer apply | -| `skills.customize-unreadable` | warning / problem | a customize override is not valid TOML, or keys an array entry on an `id`/`code` that is not a non-empty string; a problem on a BMAD v7 tree | -| `skills.review-layers-empty` | problem | the dev primitive has no enabled review layer | -| `skills.review-layer-missing` | problem | a referenced review-layer skill is not installed | -| `skills.review-layer-unresolved` | warning | a conditionally referenced review-layer skill is not installed | -| `skills.review-selection-invalid` | problem | BMAD v7: `workflow.review` is not `none`, `quick`, `thorough` or `auto` | -| `skills.stories-dispatch` | ok | stories mode: the dev primitive supports folder+id dispatch | -| `skills.stories-dispatch-missing` | problem | stories mode: the dispatch probe file is missing | -| `skills.stories-dispatch-stale` | problem | stories mode: the dev primitive lacks folder+id dispatch | -| `skills.tickets-dispatch` | ok | tickets mode: the dev primitive resolves a ticket from the ticket tree | -| `skills.tickets-dispatch-missing` | problem | tickets mode: the dispatch probe file is missing | -| `skills.tickets-dispatch-stale` | problem | tickets mode: the dev primitive predates the ticket tree | -| `skills.sweep` | ok | the `bmad-loop-sweep` skill is present in the triage skill trees | -| `skills.sweep-missing` | problem | `bmad-loop-sweep` is not installed in a triage skill tree | -| `skills.sweep-incomplete` | problem | `bmad-loop-sweep` is missing files | -| `tickets.era` | ok | tickets mode: names the ticket-tree script, the method module version and the active initiative | -| `tickets.script-missing` | problem | tickets mode: `_bmad/method/scripts/tickets.py` is not installed | -| `tickets.config-utils-missing` | problem | tickets mode: `_bmad/scripts/config_utils.py`, which `tickets.py` reads the config through, is missing | -| `tickets.uv-missing` | problem | tickets mode: `uv` is not on PATH (`bmad-build-auto` runs `tickets.py` with `uv run`) | -| `tickets.initiative-unset` | problem | tickets mode: no `[core] active_initiative` is set | -| `tickets.initiative-missing` | problem | tickets mode: the active initiative's folder does not exist | -| `tickets.initiative-parent` | ok / problem | tickets mode: the active initiative is a parent initiative; a problem unless worktree isolation runs without the auto retrospective | -| `tickets.store-not-repo` | problem | tickets mode: the ticket store is a tracker, or its config cannot be read; bmad-loop drives repo stores only | -| `tickets.store-topology` | ok / problem | tickets mode: the classified ticket-store layout; a problem for a store git cannot classify, or one tracked outside `repo_root` (worktree: the project) | -| `tickets.tree-untracked` | problem | tickets mode: the initiative folder is only partly tracked, or neither tracked nor gitignored inside the code checkout | -| `tickets.own-repo-isolation` | problem | tickets mode, worktree isolation: the mount redirect (shared store, or a parent's child) needs `_bmad/custom/config.user.toml` untracked and ignored | -| `tickets.workspace-unsupported` | problem | tickets mode: the project is not a git repository (a BMAD workspace); not supported yet | -| `tickets.store-sandbox` | warning | tickets mode: sessions write a shared store outside their cwd while a role's `extra_args` replace the profile's bypass flags or a role runs sandboxed | -| `tickets.branch-per-run` | warning | tickets mode: `[scm] branch_per = "run"` builds every ticket on one branch, which build-auto's branch-fit check may HALT | -| `tickets.capability` | ok / problem | `--probes` in tickets mode: `tickets.py --help` offers every command and `mark` status bmad-loop needs | -| `tickets.capability-not-run` | ok | tickets mode without `--probes`: the capability probe did not run | +| Check id | Severity | What it checks | +| -------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bmad-config` | ok / problem | BMAD config loads and artifact paths resolve; on BMAD v7 the ok line names the era and the active initiative | +| `bmad-config.initiative-unset` | warning | BMAD v7 with no `[core] active_initiative`: artifacts resolve to the output folder | +| `bmad-config.v6-keys-ignored` | warning | a mixed install resolved as BMAD v7 for tickets mode, ignoring leftover v6 artifact keys | +| `policy` | ok / problem | `.bmad-loop/policy.toml` loads | +| `policy.deprecated` | warning | a deprecated `policy.toml` key still loads (for example an empty-name `[engine]` block) | +| `policy.isolation-repo-root` | problem | `isolation = "worktree"` with the project outside the code root | +| `policy.isolation-shared-artifact-dir` | warning | under worktree isolation, an artifact dir shared with the main checkout | +| `policy.model-qualified` | warning | an opencode-http role model that is not `provider/model` | +| `policy.extra-args-unservable` | warning | an opencode-http role's `extra_args` repeats an adapter-owned serve flag | +| `policy.effort-unsupported` | warning | `effort` set on a profile whose adapter ignores it | +| `policy.bypass-dropped` | warning | an explicit `extra_args` drops the profile's `bypass_args` | +| `adapter.permission-mode-unsupported` | problem | a role's profile cannot run its `permission_mode` on this platform | +| `adapter.permission-mode` | ok / warning | each role's permission posture; a warning for sandboxed Codex under worktree isolation when no linked-worktree gitdir grant rides | +| `adapter.launch-probe` | ok / warning / problem | `--probes`: each distinct `generic`-profile launch; a startup dialog is a problem, an unseen screen a warning; ok with nothing launched if no patterns | +| `adapter.profile` | problem | a role's adapter name does not resolve to a loadable profile | +| `adapter.binary` | ok / problem | the profile binary is on `PATH` | +| `adapter.binary-unrunnable` | warning | a packaged profile's binary is on `PATH` but `--version` fails | +| `adapter.httpx` | ok / problem | `httpx` is importable for an opencode-http profile | +| `adapter.launch-args-unservable` | warning | an opencode-http profile's `launch_args` cannot form a valid serve command | +| `adapter.opencode-version` | ok / warning | the OpenCode server API an opencode-http binary's `--version` reports is supported | +| `adapter.codex-version` | ok / warning | a Codex binary accepts `--no-daemon` (>= 0.156) and the profile's `launch_args` pass it | +| `adapter.hookless` | ok | the profile is hookless, so hook checks are skipped | +| `adapter.kind` | ok / problem | the profile's `adapter` kind is registered | +| `adapter.external` | warning | a third-party adapter entry point failed to load | +| `adapter.external-profile` | warning | a third-party profile entry point failed to load | +| `hooks.config-parse` | problem | the hook config file is not valid JSON, is not a JSON object, or has malformed handlers | +| `hooks.registered` | ok / problem | relay hooks are registered for the profile's events in the project hook config, where `init` writes them; user- or local-scope settings are not read | +| `hooks.events-incomplete` | ok / warning | a mapped hook event besides Stop has no relay; the warning names `bmad-loop init --cli `, or the CLI version it needs | +| `hooks.trust` | ok / problem | Codex project hook trust is current | +| `hooks.relay-path-unsafe` | warning | a registered relay path has shell metacharacters the host's quoting leaves unsafe | +| `hooks.relay-present` | ok / problem | each registered relay executable exists and is usable | +| `hooks.relay-stale` | warning | a registered relay path differs from this installation's relay | +| `queue.sprint-status` | ok / problem | sprint mode: `sprint-status.yaml` loads; counts actionable stories | +| `queue.sprint-status-unknown-keys` | warning | sprint mode: unknown keys in `sprint-status.yaml` were ignored | +| `queue.nested-specs` | warning | sprint mode: spec-like files in artifact subdirectories, or unreadable subdirectories | +| `queue.stories-manifest` | ok / problem | stories mode: `stories.yaml` and `SPEC.md` are valid | +| `git.worktree-clean` | ok / problem | the code root's worktree is clean | +| `git.probe` | problem | the git check itself failed (spawn, timeout, error) | +| `git.version` | ok / problem | host git meets the supported floor | +| `git.render-tracked` | warning | the rendered-skill output dir is tracked by git | +| `deferred.ledger-unreadable` | problem | the deferred-work ledger cannot be read | +| `deferred.ledger-untracked` | warning | the ledger is neither committed nor gitignored | +| `deferred.ledger-ignored-isolated` | warning | the ledger is gitignored under worktree isolation, so session writes are lost | +| `deferred.hard-gate` | ok / problem | an actionable story or ticket is gated by a not-`done` ledger entry; tickets mode also fails a v6 key no single ticket claims, or a tree fault | +| `deferred.hard-gate-unstructured` | warning | a not-done entry declares a gate `validate` cannot enforce (malformed, empty or misspelled `gate:`, or a prose-only `HARD GATE:`) | +| `deferred.closes-malformed` | warning | a spec's `closes_deferred` has an unreadable shape | +| `deferred.closes-entry-unreadable` | warning | `closes_deferred` names entries that are neither open nor done | +| `deferred.closes-unknown` | warning | `closes_deferred` names ids not in the ledger | +| `operator.actions-malformed` | warning | sprint mode: a parked story's `operator_actions` declares nothing readable | +| `operator.confirm-interrupted` | warning | sprint mode: a confirmation signed the spec but never advanced the board | +| `operator.registry-stale` | warning | sprint mode: a park record disagrees with the spec or board, so `confirm` will refuse it | +| `operator.park-record-missing` | warning | sprint mode: the board parks a story that no park record claims | +| `plugins.manifests` | ok / warning / problem | every `plugin.toml` parses (problem); unsupported manifests are skipped (warning) | +| `plugins.trust` | ok / problem | project plugins are granted and unchanged, and the grant store is readable | +| `mux.backend` | ok / problem | the selected multiplexer backend is available | +| `mux.preflight` | problem | multiplexer selection or readiness raised an error | +| `mux.backends-detected` | ok / warning | inventory of detected backends when more than one is registered; detection failure (warning) | +| `mux.backend-probe` | warning | a registered backend's platform or availability probe raised an error | +| `mux.selection` | ok / warning | why the backend was selected; `fallback` is a warning | +| `mux.external-backend` | warning | a third-party multiplexer backend entry point failed to load | +| `host.process` | ok / problem | the process host resolves; an unknown `BMAD_LOOP_PROCESS_HOST` is a problem | +| `host.win32-on-wsl-path` | warning | a Windows interpreter is working on a WSL UNC project path | +| `notify.desktop-unavailable` | warning | `[notify] desktop` is on but the platform has no desktop notifier | +| `environment.probes-not-run` | ok | probes are configured but `--probes` was not passed | +| `environment.probes-none` | ok | `--probes` was passed with no probes configured | +| `environment.probe` | ok / problem | one per probe under `--probes`; `detail.status` is `pass`, `fail`, `timeout` or `interrupted` | +| `skills.base` | ok | the dev primitive and review layers are present | +| `skills.base-missing` | problem | the dev primitive or a review-layer skill is not installed | +| `skills.base-incomplete` | problem | the dev primitive is missing marker files | +| `skills.base-shim` | problem | the legacy dev primitive is unusable and the new one is absent | +| `skills.dev-renderer` | problem | a renderer-stub primitive lacks its renderer script | +| `skills.dev-renderer-sources` | problem | a renderer stub's render sources are unresolved | +| `skills.dev-renderer-config` | problem | a renderer stub's central config layer is missing | +| `skills.dev-render-probe` | ok / problem | `--render-probe` only: the stub's render command succeeds in a temp copy | +| `skills.customize-legacy` | warning | customize overrides named for the legacy dev primitive no longer apply | +| `skills.customize-unreadable` | warning / problem | a customize override is not valid TOML, or keys an array entry on an `id`/`code` that is not a non-empty string; a problem on a BMAD v7 tree | +| `skills.review-layers-empty` | problem | the dev primitive has no enabled review layer | +| `skills.review-layer-missing` | problem | a referenced review-layer skill is not installed | +| `skills.review-layer-unresolved` | warning | a conditionally referenced review-layer skill is not installed | +| `skills.review-selection-invalid` | problem | BMAD v7: `workflow.review` is not `none`, `quick`, `thorough` or `auto` | +| `skills.stories-dispatch` | ok | stories mode: the dev primitive supports folder+id dispatch | +| `skills.stories-dispatch-missing` | problem | stories mode: the dispatch probe file is missing | +| `skills.stories-dispatch-stale` | problem | stories mode: the dev primitive lacks folder+id dispatch | +| `skills.tickets-dispatch` | ok | tickets mode: the dev primitive resolves a ticket from the ticket tree | +| `skills.tickets-dispatch-missing` | problem | tickets mode: the dispatch probe file is missing | +| `skills.tickets-dispatch-stale` | problem | tickets mode: the dev primitive predates the ticket tree | +| `skills.sweep` | ok | the `bmad-loop-sweep` skill is present in the triage skill trees | +| `skills.sweep-missing` | problem | `bmad-loop-sweep` is not installed in a triage skill tree | +| `skills.sweep-incomplete` | problem | `bmad-loop-sweep` is missing files | +| `skills.root` | ok | where a driven skill was found: `detail` `{profile, tree, skill, root, origin}`, `origin` is `project` or `user` (validate only) | +| `skills.tree-outside` | warning / problem | a skill tree, or a required skill linked in it, resolves outside the project or repository; a problem under worktree isolation when the target is outside the repository (also refused at preflight) | +| `skills.user-shadow` | warning | a user-root copy competes with the project's: the CLI runs the user copy (`kind: overrides`) or loads both (`kind: competes`); `overrides` only with `[skills] user_roots` off, `competes` either way | +| `skills.user-root-unavailable` | warning | `[skills] user_roots`: a declared user root is skipped, disabled by a set variable (`env:`), unreadable, or there is no home folder | +| `skills.user-root-version-skew` | warning | the BMAD method module in a user root and the project's report different versions | +| `skills.user-root-unsupported` | warning | `[skills] user_roots`: opencode-http 1.x cannot load the skills that resolve from a user root; its sessions refuse to start | +| `skills.user-root-sandboxed` | warning | `[skills] user_roots`: a stage with `permission_mode = "sandboxed"` loads skills from a user root the sandbox may not let it read | +| `tickets.era` | ok | tickets mode: names the ticket-tree script, the method module version and the active initiative | +| `tickets.script-missing` | problem | tickets mode: `_bmad/method/scripts/tickets.py` is not installed | +| `tickets.config-utils-missing` | problem | tickets mode: `_bmad/scripts/config_utils.py`, which `tickets.py` reads the config through, is missing | +| `tickets.uv-missing` | problem | tickets mode: `uv` is not on PATH (`bmad-build-auto` runs `tickets.py` with `uv run`) | +| `tickets.initiative-unset` | problem | tickets mode: no `[core] active_initiative` is set | +| `tickets.initiative-missing` | problem | tickets mode: the active initiative's folder does not exist | +| `tickets.initiative-parent` | ok / problem | tickets mode: the active initiative is a parent initiative; a problem unless worktree isolation runs without the auto retrospective | +| `tickets.store-not-repo` | problem | tickets mode: the ticket store is a tracker, or its config cannot be read; bmad-loop drives repo stores only | +| `tickets.store-topology` | ok / problem | tickets mode: the classified ticket-store layout; a problem for a store git cannot classify, or one tracked outside `repo_root` (worktree: the project) | +| `tickets.tree-untracked` | problem | tickets mode: the initiative folder is only partly tracked, or neither tracked nor gitignored inside the code checkout | +| `tickets.own-repo-isolation` | problem | tickets mode, worktree isolation: the mount redirect (shared store, or a parent's child) needs `_bmad/custom/config.user.toml` untracked and ignored | +| `tickets.workspace-unsupported` | problem | tickets mode: the project is not a git repository (a BMAD workspace); not supported yet | +| `tickets.store-sandbox` | warning | tickets mode: sessions write a shared store outside their cwd while a role's `extra_args` replace the profile's bypass flags or a role runs sandboxed | +| `tickets.branch-per-run` | warning | tickets mode: `[scm] branch_per = "run"` builds every ticket on one branch, which build-auto's branch-fit check may HALT | +| `tickets.capability` | ok / problem | `--probes` in tickets mode: `tickets.py --help` offers every command and `mark` status bmad-loop needs | +| `tickets.capability-not-run` | ok | tickets mode without `--probes`: the capability probe did not run | The set is closed (`checks.VALIDATE_CHECKS`); plugins cannot add check ids. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index a67876be9..e63392970 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -270,6 +270,14 @@ Stories that owe external, human-only actions. | `enabled` | boolean | `true` | | let a session finish + commit a story whose acceptance criteria need a human action (buy a domain, publish a DNS record) and park it as awaiting-operator instead of forcing done or blocked · what is owed is recorded in the story spec's operator_actions: frontmatter, and `bmad-loop confirm ` completes the story once you have done it | | `on_review_demotion` | string | `"escalate"` | `escalate` / `park` | escalate: a review pass is never offered the park, and one that finalizes a done story at awaiting-operator is not accepted (default) · park: the review may demote it — the board moves done -> awaiting-operator, the story commits and parks · sprint mode with parks enabled only | +### `[skills]` + +Where skills are resolved from. + +| Key | Type | Default | Allowed | Description | +| --- | --- | --- | --- | --- | +| `user_roots` | boolean | `false` | | ON: a skill missing from the project's skill trees may resolve from the user-level folders the coding CLI loads on its own (its profile's [user_skills] roots, e.g. ~/.agents/skills after `npx skills add -g`); when both hold a copy, the profile's precedence picks, so a precedence = "user" CLI (claude) runs the user copy over the project's · OFF (default): the project's skill trees only | + ### `[mux]` Terminal-multiplexer backend (machine-specific — policy.toml is gitignored). @@ -281,3 +289,18 @@ Terminal-multiplexer backend (machine-specific — policy.toml is gitignored). + +## Skill resolution: `[skills] user_roots` + +Off (the default), every skill a run drives must be in one of the project's skill trees: each profile's `skill_tree`, plus its `extra_skill_trees` (opencode-http also reads `.agents/skills`). + +On, a skill the project trees lack, or one a CLI with `user` precedence (claude) runs from its personal folder instead, resolves from the user-level folders that CLI loads on its own, as its profile's `[user_skills]` table declares them. `validate`, the run preflight, `run --dry-run`, session dispatch and worktree seeding all use the same resolution, so `validate` checks the copy the session will load. A CLI with no `[user_skills]` table never resolves from a user root. + +What changes with the switch on: + +- `validate` lists where each driven skill was found (`skills.root`, `detail.origin` is `project` or `user`), and `run --dry-run` prints a `note:` line for each skill from a user root. +- Each session journals one `skill-user-root` entry per skill it loads from a user root. +- opencode-http 2.x allows those BMAD skills through its permission rules; 1.x cannot load them, so `validate` warns (`skills.user-root-unsupported`) and the session refuses to start. +- A dev or review stage with `permission_mode = "sandboxed"` that loads a user-root skill gets a `skills.user-root-sandboxed` warning: the sandbox may not let the CLI read your home folder. + +`skills.user-shadow` is reported with the switch off too: claude's user copy overriding the project's warns only with the switch off (on, it is the copy resolved), and a codex or antigravity clash warns either way. Per-CLI roots, precedence and the fresh-clone guidance are in the [setup guide](../setup-guide.md#project-skills-and-user-level-skill-roots); the profile keys are in the [adapter authoring guide](../adapter-authoring-guide.md#user-level-skill-roots). diff --git a/docs/reference/run-state.md b/docs/reference/run-state.md index 37354d007..8903b9fde 100644 --- a/docs/reference/run-state.md +++ b/docs/reference/run-state.md @@ -87,6 +87,8 @@ The opencode adapter's environment-fault classifier scans `.server.out` - **`journal.jsonl`** — append-only, one JSON object per line with `ts` and `kind`; the first entry is `run-start` (after one `journal-unpinned` row on a filesystem that reports no inode numbers). Lines end in LF on every platform. Written through the pinned run-directory descriptor by the engine, and by commands that act on the run (for example `stop`, `resume`, `resolve`). From the first session launch on, lines carry `log_task` / `log_pos`, pointing into the most recent session's log. A `session-end` entry carries `stop_failure` (the same `error` value) only when the session ended with such a `StopFailure` uncleared. `dev-decision`, `fix-decision` and `review-retry` entries carry `uncharged` (true for a usage-limit relaunch that charges no attempt or review cycle) and `usage_relaunches` (the story's relaunches so far, after this one). Worktree provisioning journals `worktree-hook-gated` (`story_key`, `reason`) for each hook event it left out because the installed CLI is older than the event's minimum version. - **`heartbeat.json`** (in `tasks//`) — the wait loop's proof of life, overwritten at most every 30 seconds while a session runs: remaining budget, stall-recovery state and probe or sampling failure counts. A session that can wait out a usage-limit reset (`[limits] quota_wait_max_min` above 0 and a profile with `usage_wait_patterns`) also carries `quota_waiting` and `quota_wait_s` (cumulative seconds waited), plus `quota_resets_at` while it waits on a line that named a reset. A session whose last turn ended on a Claude Code `StopFailure` that no later `Stop` cleared carries `stop_failure`, the reported `error` value. +Under `[skills] user_roots`, each session journals one `skill-user-root` entry (`task_id`, `role`, `skill`, `root`, `version`) per skill it loads from a user root, after the session log opens and before `session-start`. `version` is the `[bmod] version` of the user root's module record that lists the skill, or null. Worktree provisioning journals `worktree-skills-user-root` (`story_key`, `entries`: the `~/…` spellings) for the required skills the seeding gate skipped because they resolve from a user root. + A `session-end` entry carries `hook_channel_silent: true` when no hook event of any kind reached the session before it timed out or stalled (see [Silent hook channel pauses](../escalations-guide.md#silent-hook-channel-pauses)), and `stop_seen: true` when a session that did not complete had seen its Stop event; each is absent otherwise. `dev-decision`, `fix-decision`, `triage-decision` and `migrate-decision` entries always carry `hook_channel_silent`, and `workflow-end` carries it only when true. A real `run`, `sweep` or `resume` journals one `hook-relay-unregistered` entry (`role`, `profile`, `problem`) per role whose project hook config does not register the bmad-loop relay. - **`adopt-.json`** — written by `bmad-loop resolve --adopt-result` after the operator confirms a silent-channel triage attempt's `result.json`: `story_key`, `task_id`, `attempt`, `generation`, the artifact's `sha256`, `mtime_ns` and `size`, and `adopted_at`. The resumed sweep reads it only when it reaches that triage cycle, and removes it then; a sweep that exits before that (for example, with nothing open) leaves it on disk. Declining a later `resolve --adopt-result` withdraws it. The name never matches the `triage*.json` plan caches. Four journal kinds trace it: `sweep-triage-adopt-confirmed` (`story_key`, `task_id`, `sha256`; the confirm, written by `resolve`), `sweep-triage-adopted` (`story_key`, `task_id`, `sha256` and the plan's `bundles`, `decisions`, `already_resolved`, `blocked`, `skip` counts; the resumed sweep used it as the triage plan), `sweep-triage-adopt-rejected` (`story_key`, `task_id`, `errors`; the resumed sweep refused it), and `sweep-triage-adopt-withdrawn` (`story_key`, `task_id`; a declined `resolve --adopt-result` removed it). diff --git a/docs/setup-guide.md b/docs/setup-guide.md index 2cdec902b..73f1f4892 100644 --- a/docs/setup-guide.md +++ b/docs/setup-guide.md @@ -148,12 +148,73 @@ implementation and the follow-up review), installed by the BMad Method (bmm) module. `bmad-loop validate` checks it — plus any review skills its layers invoke — are present before a run starts. -bmad-loop resolves BMAD skills only from the project's own skill tree -(`.claude/skills`, `.agents/skills`). A global install (`npx skills add -g`, into -`~/.claude/skills` or `~/.agents/skills`) and a Claude Code plugin install are not used. -When `validate` finds a missing skill installed globally it says so, and -`detail.outside` names that copy, but the run still refuses: install the skill per -project with `npx skills add` without `-g`. +### Project skills and user-level skill roots + +By default bmad-loop resolves BMAD skills only from the project's own skill trees +(`.claude/skills`, `.agents/skills`). A Claude Code plugin install is never used. A global +install (`npx skills add -g`) is used only when you opt in: + +```toml +# .bmad-loop/policy.toml +[skills] +user_roots = true +``` + +With the switch on, a skill missing from the project trees may resolve from a user-level +folder, but only from the folders the coding CLI itself loads. Each CLI's profile declares +those folders, which the CLI reads first when both hold a copy (its precedence), and the +environment variables that make the CLI skip one: + +| CLI | Precedence | User roots, in the order the CLI reads them | +| ------------- | ----------- | ----------------------------------------------------------------------------------------------------------- | +| claude | `user` | `~/.claude/skills` (skipped when `CLAUDE_CONFIG_DIR` is set) | +| codex | `unordered` | `~/.agents/skills`; `~/.codex/skills` (skipped when `CODEX_HOME` is set) | +| gemini | `project` | `~/.agents/skills`; `~/.gemini/skills` (both skipped when `GEMINI_CLI_HOME` is set) | +| copilot | `project` | `~/.copilot/skills`; `~/.agents/skills` (both skipped when `COPILOT_HOME` is set) | +| antigravity | `unordered` | `~/.gemini/config/skills` | +| opencode-http | `project` | `~/.config/opencode/skills` (skipped when `XDG_CONFIG_HOME` is set); `~/.agents/skills`; `~/.claude/skills` | + +- `project`: the project copy wins; a user copy fills in only for a skill the project lacks. +- `user`: the CLI runs the user copy even when the project has one, so `validate` and the + run check that copy. +- `unordered`: the CLI loads both copies in no documented order. bmad-loop checks the + project copy and warns. + +`validate` reports where every driven skill was found as a `skills.root` line, and the run +journals each skill a session loads from a user root (`skill-user-root`). A user root that +a variable disables or that cannot be read (or every root, when there is no home folder) is reported as +`skills.user-root-unavailable`; a user root whose BMAD method module is a different version +from the project's as `skills.user-root-version-skew`. With the switch off, a missing skill +that one of the CLI's own user roots holds keeps the run refused, and the `skills.base-missing` +message names that copy (`detail.outside`) and the switch. + +`validate` warns with `skills.user-shadow` when a copy in a user root competes with the +project copy the checks read: with the switch off, Claude Code runs `~/.claude/skills/` +instead of the project copy; whatever the switch, Codex and Antigravity load both. (With the +switch on, claude's user copy is the one resolved and checked, so it is not reported.) +Remove the stale copy or bring the two to the same version. + +Worktrees never carry a user root: under worktree isolation a skill resolved from one is +loaded from your home folder, and the worktree seeding gate skips it (journaled as +`worktree-skills-user-root`). A skill tree linked to a folder outside the repository is a +`skills.tree-outside` problem under worktree isolation, refused before the run starts, +because the worktree cannot carry it; without isolation it is a warning. + +**Fresh clones and CI** have no user roots to fall back on. Either commit the project skill +tree, or commit the `skills-lock.json` that `npx skills add` writes and run +`npx skills install` after cloning (the skills CLI still labels that command +experimental). + +Known limitations: + +- The variables that disable a user root are read from bmad-loop's own environment plus the + profile's `[env]`. A long-lived tmux or psmux server can hand sessions a different + environment. +- When one skill id is in both of opencode's project trees, opencode 2.x loads the + `.claude/skills` copy, the one `validate` checks; on 1.x which copy loads is not pinned. + The skills CLI normally links the two, so they are identical. +- The CLIs' folder lists change over time. The profiles reflect the vendor docs at the time + of writing; recheck them when a CLI changes how it finds skills. **Minimum BMAD-METHOD: v6.10.0** for sprint mode. Beyond the primitive itself (with its `customize.toml`), `bmad-loop validate` holds you to no fixed list of review @@ -459,13 +520,22 @@ What differs on 2.x: - **Instructions:** 2.x reads only `AGENTS.md` — there is no `CLAUDE.md` fallback, so put project instructions the agent must see in `AGENTS.md`. -- **Skills:** 2.x has no switch to turn off the operator's personal skills - (`~/.claude/skills`, `~/.agents/skills`) and its built-in ones. The adapter keeps sessions - hermetic with permission rules instead: every skill is denied except the project's own, - so the model is offered only those. (`GET /api/skill` still lists every skill it found; - the rules govern what a session can load.) A project skill whose directory name contains - `*` or `?` stays denied, because 2.x reads those characters as rule wildcards; the spawn - records a `skill-ids-refused` event in the session lifecycle log. +- **Skills:** the adapter reads the project's skills from both `.claude/skills` and + `.agents/skills` (where the skills CLI installs opencode's project skills). 2.x has no + switch to turn off the operator's personal skills (`~/.claude/skills`, `~/.agents/skills`) + and its built-in ones. The adapter keeps sessions hermetic with permission rules instead: + every skill is denied except the project's own, so the model is offered only those. + (`GET /api/skill` still lists every skill it found; the rules govern what a session can + load.) A project skill whose directory name contains `*` or `?` stays denied, because 2.x + reads those characters as rule wildcards; the spawn records a `skill-ids-refused` event + in the session lifecycle log. +- **User-root skills:** with + [`[skills] user_roots`](#project-skills-and-user-level-skill-roots) on, 2.x also allows + the BMAD module skills the session needs from a user root (the dev skill, its review + skills, and the skills a user root's BMAD module records list) and records a + `skill-ids-user-allowed` lifecycle event; your personal skills stay denied. 1.x turns + external skills off entirely, so it cannot load them: `validate` warns + (`skills.user-root-unsupported`) and the session refuses to start. - **Logs:** a provider failure (rate limit, quota, refused connection) never reaches the server's stdout on 2.x, so the adapter records each one in `.provider-errors.log`, which the environment-fault classifier scans beside @@ -508,7 +578,9 @@ By default, Codex attaches to a shared background app-server daemon, which may h ### Skill location `claude` reads skills from `.claude/skills/`; `codex`, `gemini`, `copilot`, and `antigravity` -read from `.agents/skills/`. `init` installs the bundled `bmad-loop-*` skills into the right tree +read from `.agents/skills/`; opencode reads both. For skills installed in your home folder, +see [Project skills and user-level skill roots](#project-skills-and-user-level-skill-roots). +`init` installs the bundled `bmad-loop-*` skills into the right tree for each CLI you pass via `--cli`, so selecting any of the `.agents/skills/` CLIs populates it automatically. It skips skill dirs that already exist — pass `--force-skills` to overwrite a stale copy, or `--no-skills` to manage them yourself. diff --git a/pyproject.toml b/pyproject.toml index 218523b3e..e491a178f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -157,6 +157,7 @@ strict = [ "src/bmad_loop/ticketstore.py", "src/bmad_loop/usagereset.py", "src/bmad_loop/parked.py", + "src/bmad_loop/skill_locate.py", ] # Check against the floor of requires-python so we never lean on 3.12+ typing. pythonVersion = "3.11" diff --git a/src/bmad_loop/adapters/base.py b/src/bmad_loop/adapters/base.py index 1076dfff8..417f5ccf0 100644 --- a/src/bmad_loop/adapters/base.py +++ b/src/bmad_loop/adapters/base.py @@ -261,6 +261,16 @@ class SessionSpec: # Appended after `quota_wait_max_s` so positional constructions stay valid. usage_relaunch_mode: bool = False usage_relaunch_left: bool = False + # Where the prompt's skill was located (`skill_locate.prompt_skill_dir`), for + # the profile's `{skill_dir}` placeholder: None for a primary-tree hit, a miss + # or a prompt naming no skill (the renderer then spells `/`), + # `/` for an extra project tree, or the absolute folder for + # a user-root hit. `user_skill_ids`: the BMAD module skill ids this session's + # CLI loads from a user root (`install.user_root_skill_ids`), empty unless + # `[skills] user_roots` is on. Both set by the engine only; appended LAST so + # positional constructions stay valid. + skill_dir: str | None = None + user_skill_ids: tuple[str, ...] = () @dataclass(frozen=True) diff --git a/src/bmad_loop/adapters/generic.py b/src/bmad_loop/adapters/generic.py index cd2837213..cf78e1629 100644 --- a/src/bmad_loop/adapters/generic.py +++ b/src/bmad_loop/adapters/generic.py @@ -1415,7 +1415,7 @@ def interactive_argv(self, spec: SessionSpec) -> list[str]: argv = [ binary, *self.profile.launch_args, - self.profile.render_prompt(spec.prompt), + self.profile.render_prompt(spec.prompt, skill_dir=spec.skill_dir), *extra, ] if spec.model: diff --git a/src/bmad_loop/adapters/opencode_http.py b/src/bmad_loop/adapters/opencode_http.py index 861daba67..d267b1b9f 100644 --- a/src/bmad_loop/adapters/opencode_http.py +++ b/src/bmad_loop/adapters/opencode_http.py @@ -595,7 +595,20 @@ def _serve_argv(self, resolved_binary: str, port: int) -> list[str]: def _config_content(self, spec: SessionSpec, protocol: OpencodeProtocol | None = None) -> str: """The OPENCODE_CONFIG_CONTENT JSON for this session, in ``protocol``'s dialect (V1 when omitted): see :meth:`V1Protocol.config_content`.""" - return (protocol or _V1).config_content(spec, Path(spec.cwd) / self.profile.skill_tree) + primary, extras = self._skill_dirs(spec) + return (protocol or _V1).config_content( + spec, primary, extra_skill_dirs=extras, user_skill_ids=spec.user_skill_ids + ) + + def _skill_dirs(self, spec: SessionSpec) -> tuple[Path, list[Path]]: + """``(primary, extras)`` — the session's project skill trees under its + cwd: the profile's ``skill_tree`` (always), then each of its + ``extra_skill_trees`` that exists. A missing extra tree holds no skill + to load, so leaving it out keeps a single-tree project's config what + it always was.""" + cwd = Path(spec.cwd) + extras = [cwd / t for t in self.profile.extra_skill_trees] + return cwd / self.profile.skill_tree, [d for d in extras if d.is_dir()] def _session_env( self, spec: SessionSpec, password: str, protocol: OpencodeProtocol | None = None @@ -627,7 +640,7 @@ def _spawn_server(self, spec: SessionSpec) -> _ServerSession: # `opencode.cmd` shim that a bare-name Popen (which appends only # .exe) would never find. raise OpencodeServerError( - f"opencode binary {self.binary!r} not found on PATH; " f"see `bmad-loop validate`" + f"opencode binary {self.binary!r} not found on PATH; see `bmad-loop validate`" ) protocol, version = self._protocol_for(resolved) self._note_lifecycle( @@ -637,7 +650,21 @@ def _spawn_server(self, spec: SessionSpec) -> _ServerSession: major=protocol.major, verdict=support_verdict(version)[0], ) - refused = protocol.refused_skill_ids(Path(spec.cwd) / self.profile.skill_tree) + if spec.user_skill_ids: + if protocol.major < 2: + raise OpencodeServerError( + f"opencode {format_version(version)} cannot load skills from user roots " + f"(it runs with OPENCODE_DISABLE_EXTERNAL_SKILLS): install " + f"{', '.join(spec.user_skill_ids)} per project (`npx skills add` without -g) " + f"or upgrade to opencode 2.x" + ) + self._note_lifecycle( + spec.task_id, "skill-ids-user-allowed", ids=list(spec.user_skill_ids) + ) + primary, extras = self._skill_dirs(spec) + refused = protocol.refused_skill_ids( + primary, extra_skill_dirs=extras, user_skill_ids=spec.user_skill_ids + ) if refused: self._note_lifecycle(spec.task_id, "skill-ids-refused", ids=refused) password = secrets.token_urlsafe(16) @@ -929,7 +956,7 @@ def start_session(self, spec: SessionSpec) -> SessionHandle: if not sess.sse_connected.wait(timeout=self.health_timeout_s): raise OpencodeServerError("event stream did not connect") - self._prompt(sess, self.profile.render_prompt(spec.prompt)) + self._prompt(sess, self.profile.render_prompt(spec.prompt, skill_dir=spec.skill_dir)) except Exception: self._sessions.pop(spec.task_id, None) self._teardown(sess) diff --git a/src/bmad_loop/adapters/opencode_protocol.py b/src/bmad_loop/adapters/opencode_protocol.py index 0b8ecfeb3..eb09c6edd 100644 --- a/src/bmad_loop/adapters/opencode_protocol.py +++ b/src/bmad_loop/adapters/opencode_protocol.py @@ -43,7 +43,10 @@ - Hermetic skills need ``OPENCODE_DISABLE_EXTERNAL_SKILLS=1`` **plus** ``skills.paths=["/.claude/skills"]`` inside the config content — by default every server also sees the operator's personal - ``~/.claude/skills`` and ``~/.agents/skills``. + ``~/.claude/skills`` and ``~/.agents/skills``. The adapter lists every + project skill tree (the profile's ``skill_tree`` then its + ``extra_skill_trees``); a 1.x server therefore cannot load a user-root + skill at all, and a session that needs one is refused at spawn. - ``opencode serve`` survives parent SIGKILL (reparents to init and keeps serving); SIGTERM exits it cleanly. - All ``time.*`` fields are epoch **milliseconds**; ``POST /session/:id/abort`` @@ -138,7 +141,11 @@ skill per id, and the configured ``skills`` paths are applied after the ``~/.claude`` / ``~/.agents`` / ``~/.config/opencode`` roots (each scanned sequentially, sorted). A same-id personal copy in all three roots lost in - every start, with either side's scan slowed by 2000 extra skills. + every start, with either side's scan slowed by 2000 extra skills. That + same discovery is what serves ``[skills] user_roots``: the adapter adds no + user path to ``skills`` and re-allows, after the project ids, only the + BMAD module skill ids the engine located in a user root — every other + personal skill stays denied. - A ``question`` deny removes the ``question`` tool from what the model is offered, so an unattended session cannot park on a form. Reads are not gated: under the allow-all config a ``read`` of a path outside the project @@ -288,6 +295,7 @@ import json import re import time +from collections.abc import Sequence from dataclasses import dataclass, replace from pathlib import Path from typing import Any @@ -517,12 +525,25 @@ class OpencodeProtocol: # usage when the transcript read fails. usage_reads_transcript: bool = True - def config_content(self, spec: SessionSpec, skill_dir: Path) -> str: + def config_content( + self, + spec: SessionSpec, + skill_dir: Path, + *, + extra_skill_dirs: Sequence[Path] = (), + user_skill_ids: Sequence[str] = (), + ) -> str: raise NotImplementedError - def refused_skill_ids(self, skill_dir: Path) -> list[str]: - """Project skill ids :meth:`config_content` left out of this - session's hermetic skill set — the adapter crumbs them at spawn.""" + def refused_skill_ids( + self, + skill_dir: Path, + *, + extra_skill_dirs: Sequence[Path] = (), + user_skill_ids: Sequence[str] = (), + ) -> list[str]: + """Skill ids :meth:`config_content` left out of this session's + hermetic skill set — the adapter crumbs them at spawn.""" return [] def extra_env(self) -> dict[str, str]: @@ -642,16 +663,26 @@ class V1Protocol(OpencodeProtocol): trace_skip_types = frozenset({"message.part.delta"}) event_path = "/event" - def config_content(self, spec: SessionSpec, skill_dir: Path) -> str: + def config_content( + self, + spec: SessionSpec, + skill_dir: Path, + *, + extra_skill_dirs: Sequence[Path] = (), + user_skill_ids: Sequence[str] = (), + ) -> str: """The OPENCODE_CONFIG_CONTENT JSON for this session: blanket permission allow (the bypass-flags analogue), the hermetic - skills path (project skills only, paired with - OPENCODE_DISABLE_EXTERNAL_SKILLS=1 in the env), and the model when the - policy sets one (config-file model is the "provider/model" string - form).""" + skills paths (every project skill tree, primary first, and nothing + else — paired with OPENCODE_DISABLE_EXTERNAL_SKILLS=1 in the env), and + the model when the policy sets one (config-file model is the + "provider/model" string form). ``user_skill_ids`` is accepted for the + shared signature and ignored: 1.x cannot load a user-root skill without + dropping the external-skills switch, so the adapter refuses such a + session at spawn instead.""" config: dict[str, Any] = { "permission": "allow", - "skills": {"paths": [str(skill_dir)]}, + "skills": {"paths": [str(d) for d in (skill_dir, *extra_skill_dirs)]}, } if spec.model: config["model"] = spec.model @@ -1010,15 +1041,31 @@ class V2Protocol(OpencodeProtocol): model_settle_s = 5.0 model_poll_s = 0.25 - def config_content(self, spec: SessionSpec, skill_dir: Path) -> str: + def config_content( + self, + spec: SessionSpec, + skill_dir: Path, + *, + extra_skill_dirs: Sequence[Path] = (), + user_skill_ids: Sequence[str] = (), + ) -> str: """The OPENCODE_CONFIG_CONTENT JSON for this session, in V2's native keys. ``permissions`` is an ordered rule list where the LAST match wins: allow everything (the bypass-flags analogue), deny ``question`` (an unattended session must never park on a form), then the hermetic - skills recipe — deny every skill, and re-allow each project skill by - id. V2 has no ``OPENCODE_DISABLE_EXTERNAL_SKILLS``, so these rules are - the only thing hiding the operator's personal and the built-in skills. - ``skills`` points discovery at the project tree; ``model`` is the + skills recipe — deny every skill, re-allow each project skill by id + (from every project tree, primary first), then each + ``user_skill_ids`` entry: the BMAD module skills the engine located + in a user root, which V2 discovers on its own from ``~/.claude``, + ``~/.agents`` and ``~/.config/opencode``. V2 has no + ``OPENCODE_DISABLE_EXTERNAL_SKILLS``, so these rules are the only thing + hiding the operator's personal and the built-in skills. ``skills`` + points discovery at the project trees (no user path: V2 scans those + roots anyway), primary LAST: V2 registers explicit ``skills`` entries + above every discovered root and in array order, the later source + supplying a duplicate id, so the primary tree's copy — the one + :func:`bmad_loop.skill_locate.locate` resolves and validate reads — + wins a clash with an extra tree. ``model`` is the ``"provider/model"`` string when the policy sets one. An id the rule matcher would read as a pattern is never re-allowed (:meth:`refused_skill_ids`).""" @@ -1027,26 +1074,36 @@ def config_content(self, spec: SessionSpec, skill_dir: Path) -> str: {"action": "question", "resource": "*", "effect": "deny"}, {"action": "skill", "resource": "*", "effect": "deny"}, ] - refused = self.refused_skill_ids(skill_dir) + dirs = (skill_dir, *extra_skill_dirs) permissions.extend( {"action": "skill", "resource": skill_id, "effect": "allow"} - for skill_id in project_skill_ids(skill_dir) - if skill_id not in refused + for skill_id in _v2_skill_ids(dirs, user_skill_ids) + if _V2_RULE_WILDCARDS.isdisjoint(skill_id) ) - config: dict[str, Any] = {"permissions": permissions, "skills": [str(skill_dir)]} + config: dict[str, Any] = { + "permissions": permissions, + "skills": [str(d) for d in reversed(dirs)], + } if spec.model: config["model"] = spec.model return json.dumps(config) - def refused_skill_ids(self, skill_dir: Path) -> list[str]: - """Project skill ids holding a rule-pattern metacharacter. V2 matches - a rule's ``resource`` as a wildcard (``*`` any run, ``?`` one char, - no escape — pinned in the 2.0.27 bundle), so an allow for a directory - named ``*`` would come last and re-allow every personal and built-in - skill. Such a skill stays denied, fail-closed.""" + def refused_skill_ids( + self, + skill_dir: Path, + *, + extra_skill_dirs: Sequence[Path] = (), + user_skill_ids: Sequence[str] = (), + ) -> list[str]: + """Skill ids — project or user-root — holding a rule-pattern + metacharacter. V2 matches a rule's ``resource`` as a wildcard (``*`` + any run, ``?`` one char, no escape — pinned in the 2.0.27 bundle), so + an allow for a directory named ``*`` would come last and re-allow + every personal and built-in skill. Such a skill stays denied, + fail-closed.""" return [ skill_id - for skill_id in project_skill_ids(skill_dir) + for skill_id in _v2_skill_ids((skill_dir, *extra_skill_dirs), user_skill_ids) if not _V2_RULE_WILDCARDS.isdisjoint(skill_id) ] @@ -1647,6 +1704,18 @@ def _v2_by_model( _V2_RULE_WILDCARDS = frozenset("*?") +def _v2_skill_ids(dirs: Sequence[Path], user_skill_ids: Sequence[str]) -> list[str]: + """Every skill id a V2 session may re-allow, first-seen order: each + project tree's ids (:func:`project_skill_ids`, tree by tree), then the + user-root ids. An id in two places is listed once — V2 keeps one skill + per id, so a second allow adds nothing.""" + ids: dict[str, None] = {} + for skill_dir in dirs: + ids.update(dict.fromkeys(project_skill_ids(skill_dir))) + ids.update(dict.fromkeys(user_skill_ids)) + return list(ids) + + def project_skill_ids(skill_dir: Path) -> list[str]: """The ids of the skills under ``skill_dir`` (one ``/SKILL.md`` each), sorted — what V2's ``skill`` permission rules match on. The id is the diff --git a/src/bmad_loop/adapters/profile.py b/src/bmad_loop/adapters/profile.py index 375fb4b4a..e5af4b93d 100644 --- a/src/bmad_loop/adapters/profile.py +++ b/src/bmad_loop/adapters/profile.py @@ -48,10 +48,12 @@ from ..platform_util import ( has_parent_ref, is_absolute_path, + names_home_ref, names_tree_root, names_win32_alias, ) from ..policy import PERMISSION_MODES, PROFILE_ALIASES +from ..skill_locate import PRECEDENCES, UserSkillRoot, UserSkillsSpec, prompt_skill from .entrypoints import record_load_error from .multiplexer import ALLOWED_KEYS @@ -440,6 +442,15 @@ class CLIProfile: # None = off. APPENDED after linked_worktree_args for the same # positional-compatibility reason. subagent_spawn_marker: str | None = None + # More project-relative skill trees the CLI also reads, after `skill_tree`, + # in the order it reads them. APPENDED after subagent_spawn_marker for the + # same positional-compatibility reason. + extra_skill_trees: tuple[str, ...] = () + # The home-relative skill folders the CLI natively loads (`[user_skills]`), + # resolved by `bmad_loop.skill_locate`. None = the CLI declares none: no + # user-root resolution, shadow check or hint — the safe default for overlay + # and entry-point profiles. APPENDED last for the same reason. + user_skills: UserSkillsSpec | None = None @property def hookless(self) -> bool: @@ -456,17 +467,21 @@ def subagent_transcript_root(self) -> str: return self.subagent_transcript_dir return SUBAGENT_TRANSCRIPT_DIR_DEFAULTS.get(self.usage_parser, "") - def render_prompt(self, prompt: str) -> str: + def render_prompt(self, prompt: str, *, skill_dir: str | None = None) -> str: """Render the engine's canonical "/skill args" prompt for this CLI. Placeholders: {prompt} = the canonical string, {skill} = the leading - slash-command name without "/", {args} = everything after it. + slash-command name without "/", {args} = everything after it, {skill_dir} + = the folder holding the skill's SKILL.md — ``skill_dir`` when the engine + located it outside the primary tree (an extra tree, or the absolute folder + in a user root), else ``/``. """ - skill, args = "", prompt - if prompt.startswith("/"): - head, _, rest = prompt[1:].partition(" ") - skill, args = head, rest.strip() - return self.prompt_template.format(prompt=prompt, skill=skill, args=args) + skill, args = prompt_skill(prompt) + if skill_dir is None: + skill_dir = f"{self.skill_tree}/{skill}" + return self.prompt_template.format( + prompt=prompt, skill=skill, args=args, skill_dir=skill_dir + ) def for_permission_mode(self, mode: str, platform: str = sys.platform) -> CLIProfile: """This profile with ``bypass_args`` set to ``mode``'s launch args. @@ -539,6 +554,35 @@ def _check_linked_worktree_args( raise fail(f"{where} must use at least one of {', '.join(LINKED_WORKTREE_PLACEHOLDERS)}") +_ENV_VAR_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + +def _home_relative_bad(path: str) -> bool: + """True unless ``path`` is ``~/``. + + Home-anchored and nothing else: the target lives outside the project, so + the confinement is "under ~", and the remainder must name something inside + home — not home itself, not an absolute path smuggled after the prefix + (`~//etc/passwd` joins to `/etc/passwd`), not a `..` climb out.""" + rest = path[2:] + return ( + not path.startswith("~/") + or names_tree_root(rest) + or is_absolute_path(rest) + or has_parent_ref(rest) + ) + + +def _tree_key(path: str) -> str: + """A spelling-insensitive key for comparing two declared folders: separators + unified, empty and `.` components and a trailing slash dropped.""" + return "/".join(p for p in path.replace("\\", "/").split("/") if p not in ("", ".")) + + +def _same_tree(a: str, b: str) -> bool: + return _tree_key(a) == _tree_key(b) + + def _validate_profile(profile: CLIProfile, source: str) -> None: """Enforce every value-level invariant a ``CLIProfile`` must satisfy, whatever built it. @@ -592,6 +636,11 @@ def fail(msg: str) -> ProfileError: # `names_tree_root("")` is True, so this arm also carries the # "a real dialect must name a config_path at all" case. raise fail("hooks.config_path must be a project-relative path") + if names_home_ref(hooks.config_path): + raise fail( + "hooks.config_path must not start with '~': a leading '~' is not expanded; " + "hook config paths must be project-relative" + ) if names_win32_alias(hooks.config_path): raise fail( "hooks.config_path must not name a Windows device or end a component " @@ -818,6 +867,12 @@ def fail(msg: str) -> ProfileError: ): raise fail("skill_tree must be a project-relative path") + if names_home_ref(profile.skill_tree): + raise fail( + "skill_tree must not start with '~': a leading '~' is not expanded; " + f"skill trees must be project-relative: got {profile.skill_tree!r}" + ) + if names_win32_alias(profile.skill_tree): raise fail( "skill_tree must not name a Windows device or end a component in a period or space" @@ -830,26 +885,77 @@ def fail(msg: str) -> ProfileError: for seed in profile.seed_files: if names_tree_root(seed) or is_absolute_path(seed) or has_parent_ref(seed): raise fail(f"seed_files entries must be project-relative paths: got {seed!r}") + if names_home_ref(seed): + raise fail( + "seed_files entries must not start with '~': a leading '~' is not " + f"expanded; seed files must be project-relative: got {seed!r}" + ) if names_win32_alias(seed): raise fail( "seed_files entries must not name a Windows device or end a component " f"in a period or space: got {seed!r}" ) + for extra in profile.extra_skill_trees: + if names_tree_root(extra) or is_absolute_path(extra) or has_parent_ref(extra): + raise fail(f"extra_skill_trees entries must be project-relative paths: got {extra!r}") + if names_home_ref(extra): + raise fail( + "extra_skill_trees entries must not start with '~': a leading '~' is not " + f"expanded; skill trees must be project-relative: got {extra!r}" + ) + if names_win32_alias(extra): + raise fail( + "extra_skill_trees entries must not name a Windows device or end a " + f"component in a period or space: got {extra!r}" + ) + # An extra tree reaches the prompt as {skill_dir} ("/") and is + # outside the config digest, so it must never read as a command-line option. + if extra.startswith("-"): + raise fail( + "extra_skill_trees entries must not start with '-': the rendered " + f"{{skill_dir}} would read as a command-line option: got {extra!r}" + ) + if _same_tree(extra, profile.skill_tree): + raise fail(f"extra_skill_trees entries must differ from skill_tree: got {extra!r}") + if len({_tree_key(t) for t in profile.extra_skill_trees}) != len(profile.extra_skill_trees): + raise fail(f"extra_skill_trees has duplicate entries: {list(profile.extra_skill_trees)}") + + user_skills = profile.user_skills + if user_skills is not None: + if user_skills.precedence not in PRECEDENCES: + raise fail( + f"user_skills.precedence must be one of {sorted(PRECEDENCES)}: " + f"got {user_skills.precedence!r}" + ) + seen: set[str] = set() + for root in user_skills.roots: + if _home_relative_bad(root.path): + raise fail( + "user_skills root path must be a '~/'-prefixed path inside the home " + f"directory: got {root.path!r}" + ) + if names_win32_alias(root.path[2:]): + raise fail( + "user_skills root path must not name a Windows device or end a " + f"component in a period or space: got {root.path!r}" + ) + for var in root.disabled_by: + if not _ENV_VAR_NAME_RE.fullmatch(var): + raise fail( + "user_skills root disabled_by entries must be environment variable " + f"names ([A-Za-z_][A-Za-z0-9_]*): got {var!r} for {root.path!r}" + ) + key = _tree_key(root.path) + if key in seen: + raise fail(f"user_skills has duplicate roots: got {root.path!r} twice") + seen.add(key) + trust = profile.workspace_trust if trust is not None: settings_path = trust.settings_path rest = settings_path[2:] - # Home-anchored and nothing else: the file lives outside the project, so - # the confinement is "under ~", and the remainder must name something - # inside home — not home itself, not an absolute path smuggled after the - # prefix (`~//etc/passwd` joins to `/etc/passwd`), not a `..` climb out. - if ( - not settings_path.startswith("~/") - or names_tree_root(rest) - or is_absolute_path(rest) - or has_parent_ref(rest) - ): + if _home_relative_bad(settings_path): raise fail( "workspace_trust.settings_path must be a '~/'-prefixed path inside the " f"home directory: got {settings_path!r}" @@ -1026,6 +1132,47 @@ def str_list(key: str) -> tuple[str, ...]: raise fail("workspace_trust.settings_path and workspace_trust.key must be strings") workspace_trust = WorkspaceTrustSpec(settings_path=settings_path, key=key) + # `[user_skills]`: shape only, like workspace_trust. A root is a bare + # "~/..." string or a `{ path, disabled_by }` table; values (the `~/` + # confinement, variable names, precedence, duplicates) in `_validate_profile`. + user_d = doc.get("user_skills") + user_skills: UserSkillsSpec | None = None + if user_d is not None: + if not isinstance(user_d, dict): + raise fail("user_skills must be a table") + unknown = sorted(set(user_d) - {"precedence", "roots"}) + if unknown: + raise fail(f"user_skills has unknown keys: {unknown}") + precedence = user_d.get("precedence", UserSkillsSpec.precedence) + if not isinstance(precedence, str): + raise fail(f"user_skills.precedence must be a string: got {type(precedence).__name__}") + raw_roots = user_d.get("roots", []) + if not isinstance(raw_roots, list): + raise fail("user_skills.roots must be a list") + roots: list[UserSkillRoot] = [] + for raw_root in raw_roots: + if isinstance(raw_root, str): + roots.append(UserSkillRoot(path=raw_root)) + continue + if not isinstance(raw_root, dict): + raise fail( + 'user_skills.roots entries must be "~/..." strings or ' + "{ path, disabled_by } tables" + ) + unknown = sorted(set(raw_root) - {"path", "disabled_by"}) + if unknown: + raise fail(f"user_skills.roots entry has unknown keys: {unknown}") + root_path = raw_root.get("path") + if not isinstance(root_path, str): + raise fail("user_skills.roots entry path must be a string") + disabled_by = raw_root.get("disabled_by", []) + if not isinstance(disabled_by, list) or not all( + isinstance(x, str) for x in disabled_by + ): + raise fail("user_skills.roots entry disabled_by must be a list of strings") + roots.append(UserSkillRoot(path=root_path, disabled_by=tuple(disabled_by))) + user_skills = UserSkillsSpec(precedence=precedence, roots=tuple(roots)) + # Same shape-only rule as workspace_trust: four string lists, values in # `_validate_profile`. answers_d = doc.get("parked_answers") @@ -1135,6 +1282,8 @@ def str_list(key: str) -> tuple[str, ...]: parked_answers=parked_answers, permission_modes=permission_modes, subagent_spawn_marker=raw_spawn_marker, + extra_skill_trees=str_list("extra_skill_trees"), + user_skills=user_skills, ) _validate_profile(profile, source) return profile diff --git a/src/bmad_loop/checks.py b/src/bmad_loop/checks.py index f458ce943..fceffc6d0 100644 --- a/src/bmad_loop/checks.py +++ b/src/bmad_loop/checks.py @@ -130,6 +130,20 @@ "skills.base-missing", "skills.base-incomplete", "skills.base-shim", + # a skill tree (or a required skill in one) linked out of the project/repo + "skills.tree-outside", + # where each driven skill resolved: a project tree or a user root (validate only) + "skills.root", + # a project skill a user-root copy may override or compete with at run time + "skills.user-shadow", + # a declared user root that cannot resolve (disabler set, no home, unreadable) + "skills.user-root-unavailable", + # user-root and project bmod-method records name different BMAD-METHOD versions + "skills.user-root-version-skew", + # an opencode 1.x server while a needed skill resolves from a user root + "skills.user-root-unsupported", + # a sandboxed role whose skills resolve from a user root outside the project + "skills.user-root-sandboxed", "skills.customize-legacy", "skills.dev-renderer", "skills.dev-renderer-config", diff --git a/src/bmad_loop/cli.py b/src/bmad_loop/cli.py index d695a68ea..d03d9eb93 100644 --- a/src/bmad_loop/cli.py +++ b/src/bmad_loop/cli.py @@ -40,6 +40,7 @@ resolve, runs, runsetup, + skill_locate, sprintstatus, ) from . import stories as stories_mod @@ -125,6 +126,7 @@ from .runsetup import make_adapters as _make_adapters from .runsetup import mux_reason_label as _mux_reason_label from .runsetup import platform_preflight as _platform_preflight +from .skill_locate import SkillScope from .stories_engine import StoriesEngine from .sweep import ( DW_ID_RE, @@ -693,10 +695,14 @@ def _validate_environment_probes( report.fail("environment.probe", message, detail) -def _check_opencode_version(report: ValidationReport, profile_name: str, resolved: str) -> None: +def _check_opencode_version( + report: ValidationReport, profile_name: str, resolved: str +) -> tuple[int, int, int] | None: """``adapter.opencode-version``: which OpenCode server API ``resolved`` would run, judged by the same :func:`opencode_protocol.support_verdict` the adapter - refuses unsupported majors with. OK or a warning, never a problem. + refuses unsupported majors with. OK or a warning, never a problem. Returns the + parsed version (None when unreadable), which ``skills.user-root-unsupported`` + reads. Called only once ``binary_runs`` saw ``--version`` exit 0, so a read that now fails, times out, or prints nothing is not ``adapter.binary-unrunnable``'s @@ -718,7 +724,7 @@ def _check_opencode_version(report: ValidationReport, profile_name: str, resolve f"and refuse to start without one (supported: {supported_ranges()})", {"profile": profile_name, "path": resolved, "output": None}, ) - return + return None detail: dict[str, object] = {"profile": profile_name, "path": resolved, "output": first_line} version = parse_opencode_version(first_line) if version is None: @@ -728,7 +734,7 @@ def _check_opencode_version(report: ValidationReport, profile_name: str, resolve f"OpenCode version — runs will refuse to start (supported: {supported_ranges()})", detail, ) - return + return None verdict, message = support_verdict(version) detail["version"] = ".".join(str(part) for part in version) detail["verdict"] = verdict @@ -746,6 +752,7 @@ def _check_opencode_version(report: ValidationReport, profile_name: str, resolve f"{profile_name}: {message} — it may work; upgrade if sessions misbehave", detail, ) + return version def _check_codex_version(report: ValidationReport, profile: CLIProfile, resolved: str) -> None: @@ -1035,11 +1042,12 @@ def cmd_validate(args: argparse.Namespace) -> int: # parse failure. from .plugins import store as plugin_store - dev_trees = ( - _skill_trees(project, pol, plugin_root, plugin_store.load_grants(project)) + dev_profiles = ( + _scoped_profiles(project, pol, plugin_root, plugin_store.load_grants(project)) if pol is not None - else [] + else {} ) + dev_trees = list(dev_profiles) if paths: _QUEUE_VALIDATORS[source]( @@ -1236,6 +1244,9 @@ def cmd_validate(args: argparse.Namespace) -> int: registered_relays: set[tuple[Path, str]] = set() relay_interpreters: set[str] = set() + # the server version each probed opencode-http profile reports, for the + # user-root check below (`skills.user-root-unsupported`) + opencode_versions: dict[str, tuple[int, int, int] | None] = {} for profile in profiles: # Keyed on the adapter KIND, not on `hookless`. httpx is the bundled # opencode family's optional extra — a fact about one adapter class, which @@ -1291,7 +1302,9 @@ def cmd_validate(args: argparse.Namespace) -> int: # compatibility contract. resolved_binary = runnable.get(profile.binary) if resolved_binary is not None: - _check_opencode_version(report, profile.name, resolved_binary) + opencode_versions[profile.name] = _check_opencode_version( + report, profile.name, resolved_binary + ) if profile.hooks.dialect == "codex-hooks-json": # The same packaged-provenance gate as the opencode read above; never # a problem, for the same rc contract. @@ -1640,16 +1653,23 @@ def cmd_validate(args: argparse.Namespace) -> int: resolved = list( dict.fromkeys( name - for tree in dict.fromkeys(dev_trees) + for tree in dev_trees if (name := install.resolve_dev_primitive(project, tree)) is not None ) ) report.ok( "skills.base", f"upstream skills present ({' + '.join(resolved)} + review layers)", - {"trees": list(dict.fromkeys(dev_trees)), "dev_primitive": resolved}, + {"trees": _tree_names(dev_trees), "dev_primitive": resolved}, ) report.extend(base_findings) + _report_skill_roots(report, project, pol, dev_profiles, opencode_versions) + # The same probe `_require_base_skills` runs, against the same code root, so a + # skill linked out of the repo under worktree isolation fails both alike. + if dev_trees and pol is not None: + report.extend( + install.skill_trees_outside(project, clean_root, dev_trees, isolation=pol.scm.isolation) + ) report.extend(install.dev_primitive_warnings(project, dev_trees)) # Opt-in only: the probe executes project-controlled content (the stub's argv and # render_skill.py), and plain validate must stay non-executing for a fresh clone. @@ -2250,10 +2270,12 @@ def _review_tree_gated(pol, root: Path, grants: GrantSet) -> bool: return "review" in roles -def _skill_trees( +def _skill_scopes( project: Path, pol, root: Path, grants: GrantSet, *, review_owed: bool = False -) -> list[str]: - """The skill trees this run's dev-primitive adapters read, one per distinct name. +) -> list[SkillScope]: + """The skill scopes this run's dev-primitive adapters load from, one per distinct + scope (:func:`skill_locate.scope_for`: the profile's project trees, plus its + declared user roots resolved under ``[skills] user_roots``). Shared by the real preflight and `cmd_validate` so the two cannot drift: validate's verdict has to key on exactly what makes run abort. Profiles that @@ -2277,23 +2299,111 @@ def _skill_trees( per-CLI Stop-signal hook registration as well as seeding, and a worktree without the review profile would stall a review-role session on a missing completion signal rather than merely miss a skill.""" + return list(_scoped_profiles(project, pol, root, grants, review_owed=review_owed)) + + +def _scoped_profiles( + project: Path, pol, root: Path, grants: GrantSet, *, review_owed: bool = False +) -> dict[SkillScope, list[str]]: + """:func:`_skill_scopes` with the profile names behind each scope, in order — + validate names them on its user-root findings.""" from .adapters.profile import ProfileError, get_profile roles = install.DEV_PRIMITIVE_ROLES if not review_owed and not _review_tree_gated(pol, root, grants): roles = tuple(role for role in roles if role != "review") - trees = [] + scopes: dict[SkillScope, list[str]] = {} for name in dict.fromkeys(pol.adapter.resolved(role).name for role in roles): try: - trees.append(get_profile(name, project).skill_tree) + profile = get_profile(name, project) except ProfileError: continue - return trees + scope = skill_locate.scope_for(profile, resolve_user=pol.skills.user_roots) + scopes.setdefault(scope, []).append(name) + return scopes + + +def _tree_names(scopes: list[SkillScope]) -> list[str]: + """The distinct primary tree spellings of ``scopes``, for a finding's detail — + a scope is not JSON, and two CLIs sharing a tree read it once.""" + return list(dict.fromkeys(scope.tree for scope in scopes)) + + +def _report_skill_roots( + report: ValidationReport, + project: Path, + pol, + dev_profiles: dict[SkillScope, list[str]], + opencode_versions: Mapping[str, tuple[int, int, int] | None], +) -> None: + """validate's user-root lines, over the same scopes the preflight gates on. + + - ``skills.root`` (ok): where each driven skill resolved, named per profile. + Validate only, never routed through ``missing_base_skills``: the run + preflight prints every non-problem finding there as ``warning:``. + - ``skills.user-root-unsupported``: an opencode-http profile whose binary + reports a 1.x server while a skill it needs resolves from a user root — the + session spawn refuses exactly that pair. + - ``skills.user-root-sandboxed``: a role launched with ``permission_mode = + "sandboxed"`` whose skills resolve from a user root outside the project, + which a sandbox may not let the session read. + + Warnings only: validate's exit code is a compatibility contract.""" + from .adapters import registry as adapter_registry + from .adapters.profile import ProfileError, get_profile + + for scope, names in dev_profiles.items(): + label = ", ".join(names) + for finding in install.skill_root_findings(project, [scope]): + report.add( + finding.check, + finding.severity, + f"{label}: {finding.message}", + {"profile": label, **(finding.detail or {})}, + ) + if not scope.resolve_user: + continue + user_ids = install.user_root_skill_ids(project, scope) + if not user_ids: + continue + for name in names: + try: + profile = get_profile(name, project) + except ProfileError: + continue + # Keyed by the loaded profile's canonical name: a policy alias + # (`opencode` → `opencode-http`) is what `names` carries. + version = opencode_versions.get(profile.name) + if ( + profile.adapter == adapter_registry.OPENCODE_HTTP + and version is not None + and version[0] < 2 + ): + shown = ".".join(str(part) for part in version) + report.warn( + "skills.user-root-unsupported", + f"{name}: opencode {shown} cannot load skills from user roots " + f"({', '.join(user_ids)}) — its sessions will refuse to start; " + f"install them per project (`npx skills add` without -g) or " + f"upgrade to opencode 2.x", + {"profile": name, "version": shown, "skills": list(user_ids)}, + ) + for role in install.DEV_PRIMITIVE_ROLES: + cfg = pol.adapter.resolved(role) + if cfg.name in names and cfg.permission_mode == "sandboxed": + report.warn( + "skills.user-root-sandboxed", + f'{role} ({cfg.name}) runs with permission_mode = "sandboxed" but ' + f"loads {', '.join(user_ids)} from a user root outside the project, " + f"which the sandbox may not let it read — install them per project " + f"(`npx skills add` without -g) if sessions cannot load them", + {"profile": cfg.name, "role": role, "skills": list(user_ids)}, + ) def _dev_skill_for_role(pol, project: Path, role: str) -> str: """The dev-primitive skill name ``role``'s adapter would invoke, for dry-run - previews. Mirrors `_require_base_skills`' profile→skill_tree lookup so the + previews. Mirrors `_require_base_skills`' profile→scope lookup so the preview and the real dispatch (``Engine._dev_skill``) resolve identically — a pre-rename project previews ``/bmad-dev-auto``, a post-rename one ``/bmad-build-auto``. An unloadable profile falls back to the legacy name; @@ -2301,10 +2411,13 @@ def _dev_skill_for_role(pol, project: Path, role: str) -> str: from .adapters.profile import ProfileError, get_profile try: - tree = get_profile(pol.adapter.resolved(role).name, project).skill_tree + scope = skill_locate.scope_for( + get_profile(pol.adapter.resolved(role).name, project), + resolve_user=pol.skills.user_roots, + ) except ProfileError: - tree = None - return install.dev_primitive_or_default(project, tree) + scope = None + return install.dev_primitive_or_default(project, scope) def _unknown_adapter_kinds(project: Path, pol) -> list[str]: @@ -2786,7 +2899,7 @@ def _warn_preflight_would_abort( Mirrors the refusals the dry-run's early return skips past, and only those: the under-floor git `_reject_under_floor_git` refuses first, the finding list - `_require_base_skills` gates on, the #414 isolation conflict + `_require_base_skills` gates on (``skills.tree-outside`` included), the #414 isolation conflict `_reject_isolation_conflict` refuses ahead of it, and the unregistered adapter kind `make_adapters` aborts on (`_unknown_adapter_kinds` — a preview reads none of the fields that would give the misconfiguration away). @@ -2829,7 +2942,15 @@ def _warn_preflight_would_abort( It reads the grant store the way the launch would, without its warning.""" from .plugins import store - trees = _skill_trees(paths.project, pol, paths.repo_root, store.load_grants(paths.project)) + trees = _skill_scopes(paths.project, pol, paths.repo_root, store.load_grants(paths.project)) + # Under `[skills] user_roots` a run drives a copy outside the project; say so, + # runnable or not, so the preview names what the sessions will load. + for found in install.skill_root_findings(paths.project, trees): + if (found.detail or {}).get("origin") == "user": + print( + f"note: {found.message} — `[skills] user_roots = true` in policy.toml", + file=sys.stderr, + ) problems = [ p.message for p in install.missing_base_skills(paths.project, trees) @@ -2850,6 +2971,13 @@ def _warn_preflight_would_abort( ) if p.severity == "problem" ] + problems += [ + p.message + for p in install.skill_trees_outside( + paths.project, paths.repo_root, trees, isolation=pol.scm.isolation + ) + if p.severity == "problem" + ] if require_tickets: problems += [ p.message @@ -2972,9 +3100,15 @@ def _require_base_skills( older install must fail loudly here rather than HALT `no stories.yaml`-style at dispatch time. ``require_tickets`` likewise probes it for the ticket-tree route tickets mode dispatches through. ``review_owed`` keeps the review tree - gated (`_skill_trees`).""" - skill_trees = _skill_trees(project, pol, root, grants, review_owed=review_owed) + gated (`_skill_scopes`). + + Every question is asked of the same scopes ``cmd_validate`` builds, so a skill + resolved from a user root under ``[skills] user_roots`` passes both alike.""" + skill_trees = _skill_scopes(project, pol, root, grants, review_owed=review_owed) findings = install.missing_base_skills(project, skill_trees) + # A skill linked out of the repo is refused here rather than escalated mid-run, + # where worktree seeding would skip it. + findings += install.skill_trees_outside(project, root, skill_trees, isolation=pol.scm.isolation) if require_stories: # missing_base_skills above reports (and refuses) an unresolved primitive findings += install.missing_stories_support(project, skill_trees, skip_unresolved=True) @@ -2999,10 +3133,10 @@ def _triage_trees(project: Path, pol) -> list[str]: """The skill tree the triage adapter reads — where a sweep dispatches ``/bmad-loop-sweep``. A list (empty or one entry) so it composes with the ``Sequence[str]`` probes; an unloadable profile is skipped exactly as - :func:`_skill_trees` skips one, since an unknown adapter name is the policy + :func:`_skill_scopes` skips one, since an unknown adapter name is the policy loader's problem, not the skill probe's. - Separate from :func:`_skill_trees` on purpose, not a widening of it: that + Separate from :func:`_skill_scopes` on purpose, not a widening of it: that helper's role set is the one `WorktreeFlow.worktree_profiles` provisions and every question it answers is a dev-primitive one (see its docstring).""" from .adapters.profile import ProfileError, get_profile @@ -3082,7 +3216,7 @@ def _validate_stories_folder( return None -def _all_resolve(project: Path, trees: list[str]) -> bool: +def _all_resolve(project: Path, trees: list[SkillScope]) -> bool: """Every tree resolves a dev primitive — the precondition for a dispatch-probe ok line, since the probes skip an unresolved tree rather than report it.""" return all(install.resolve_dev_primitive(project, tree) is not None for tree in trees) @@ -3092,7 +3226,7 @@ def _validate_stories_queue( project: Path, paths: bmadconfig.ProjectPaths, spec_folder: str, - skill_trees: list[str], + skill_trees: list[SkillScope], report: ValidationReport, ) -> None: """Stories-mode counterpart of ``cmd_validate``'s sprint-status gate: validate @@ -3135,7 +3269,7 @@ def _validate_stories_queue( report.ok( "skills.stories-dispatch", f"{' + '.join(probed)} supports folder+id dispatch (stories mode)", - {"trees": list(dict.fromkeys(skill_trees)), "dev_primitive": probed}, + {"trees": _tree_names(skill_trees), "dev_primitive": probed}, ) report.extend(stories_probs) @@ -3361,7 +3495,7 @@ def _validate_sprint_mode_queue( project: Path, paths: bmadconfig.ProjectPaths, spec_folder: str, - dev_trees: list[str], + dev_trees: list[SkillScope], report: ValidationReport, probes: bool, pol, @@ -3393,7 +3527,7 @@ def _validate_stories_mode_queue( project: Path, paths: bmadconfig.ProjectPaths, spec_folder: str, - dev_trees: list[str], + dev_trees: list[SkillScope], report: ValidationReport, probes: bool, pol, @@ -3410,7 +3544,7 @@ def _validate_tickets_mode_queue( project: Path, paths: bmadconfig.ProjectPaths, spec_folder: str, - dev_trees: list[str], + dev_trees: list[SkillScope], report: ValidationReport, probes: bool, pol, @@ -3447,7 +3581,7 @@ def _validate_tickets_mode_queue( report.ok( "skills.tickets-dispatch", f"{' + '.join(probed)} dispatches from the ticket tree (tickets mode)", - {"trees": list(dict.fromkeys(dev_trees)), "dev_primitive": probed}, + {"trees": _tree_names(dev_trees), "dev_primitive": probed}, ) report.extend(tickets_probs) @@ -3457,7 +3591,9 @@ def _validate_tickets_mode_queue( # `validate --probes`. _QUEUE_VALIDATORS: dict[ str, - Callable[[Path, bmadconfig.ProjectPaths, str, list[str], ValidationReport, bool, Any], None], + Callable[ + [Path, bmadconfig.ProjectPaths, str, list[SkillScope], ValidationReport, bool, Any], None + ], ] = { worksource.SOURCE_SPRINT: _validate_sprint_mode_queue, worksource.SOURCE_STORIES: _validate_stories_mode_queue, @@ -8263,15 +8399,22 @@ def _resolve_epic_close( from .adapters.profile import ProfileError, get_profile try: - tree = get_profile(pol.adapter.resolved("dev").name, project).skill_tree + # located as the session will load it: a user-root copy counts under + # `[skills] user_roots`, exactly as the run's own sessions resolve one + epic_scope = skill_locate.scope_for( + get_profile(pol.adapter.resolved("dev").name, project), + resolve_user=pol.skills.user_roots, + ) except ProfileError as e: print( f"cannot resolve {run_id}: cannot load the dev adapter profile: {e}", file=sys.stderr, ) return 1 - skill = project / tree / resolve.EPIC_CLOSE_SKILL / "SKILL.md" - if tree and not skill.is_file(): + skill = project / epic_scope.tree / resolve.EPIC_CLOSE_SKILL / "SKILL.md" + if epic_scope.tree and ( + skill_locate.locate(project, epic_scope, resolve.EPIC_CLOSE_SKILL) is None + ): print( f"cannot resolve {run_id}: the dev adapter's skill tree has no " f"{skill.as_posix()} — close epic {slug} by hand and commit it, then: " @@ -8349,6 +8492,7 @@ def _resolve_epic_close( prompt, model=dev_cfg.model, effort=dev_cfg.effort, + skill_dir=skill_locate.prompt_skill_dir(project, epic_scope, prompt), ) except NotImplementedError: print( diff --git a/src/bmad_loop/data/profiles/antigravity.toml b/src/bmad_loop/data/profiles/antigravity.toml index 2e17240d4..30523f960 100644 --- a/src/bmad_loop/data/profiles/antigravity.toml +++ b/src/bmad_loop/data/profiles/antigravity.toml @@ -87,3 +87,11 @@ events = { Stop = "Stop" } [workspace_trust] settings_path = "~/.gemini/antigravity-cli/settings.json" key = "trustedWorkspaces" + +# The home-relative skill folder Antigravity loads on its own, read only with +# `[skills] user_roots = true` (see bmad_loop.skill_locate). Which copy wins on a +# name clash with the workspace is not documented. +# Source: https://antigravity.google/docs/skills (2026-11-15). +[user_skills] +precedence = "unordered" +roots = ["~/.gemini/config/skills"] diff --git a/src/bmad_loop/data/profiles/claude.toml b/src/bmad_loop/data/profiles/claude.toml index ce0d23152..60a7136b8 100644 --- a/src/bmad_loop/data/profiles/claude.toml +++ b/src/bmad_loop/data/profiles/claude.toml @@ -299,3 +299,11 @@ args = [ '{"sandbox":{"enabled":true,"failIfUnavailable":true,"allowUnsandboxedCommands":false}}', ] platforms = ["linux", "darwin"] + +# The home-relative skill folders Claude Code loads on its own, read only with +# `[skills] user_roots = true` (see bmad_loop.skill_locate). Personal skills beat +# project skills on a name clash, and CLAUDE_CONFIG_DIR moves the personal folder +# away from ~/.claude. Source: https://code.claude.com/docs/en/skills (2026-11-15). +[user_skills] +precedence = "user" +roots = [{ path = "~/.claude/skills", disabled_by = ["CLAUDE_CONFIG_DIR"] }] diff --git a/src/bmad_loop/data/profiles/codex.toml b/src/bmad_loop/data/profiles/codex.toml index 9b307ec18..1b2df8565 100644 --- a/src/bmad_loop/data/profiles/codex.toml +++ b/src/bmad_loop/data/profiles/codex.toml @@ -65,3 +65,17 @@ linked_worktree_args = [ "-c", 'default_permissions="bmad_loop_worktree"', ] + +# The home-relative skill folders Codex loads on its own, read only with +# `[skills] user_roots = true` (see bmad_loop.skill_locate). ~/.agents/skills and +# the deprecated $CODEX_HOME/skills both load, with no stated order on a name +# clash; CODEX_HOME moves the second away from ~/.codex. +# Source: https://learn.chatgpt.com/docs/build-skills (2026-11-15). +[user_skills] +precedence = "unordered" +roots = [ + "~/.agents/skills", + { path = "~/.codex/skills", disabled_by = [ + "CODEX_HOME", + ] }, +] diff --git a/src/bmad_loop/data/profiles/copilot.toml b/src/bmad_loop/data/profiles/copilot.toml index 8ab923ac7..47462a78f 100644 --- a/src/bmad_loop/data/profiles/copilot.toml +++ b/src/bmad_loop/data/profiles/copilot.toml @@ -1,8 +1,11 @@ # GitHub Copilot CLI (GA since 2026-02). `-i ""` starts an interactive # session and auto-runs the prompt (a bare `-p` prompt runs headless and exits). -# Copilot has no native skill discovery, so the prompt tells it to read the -# SKILL.md directly (skills live in .agents/skills/, shared with codex/gemini and -# matching upstream BMAD-METHOD's github-copilot installer). "use subagents as +# Copilot CLI discovers skills itself (~/.copilot/skills, ~/.agents/skills and +# the project's .github/.claude/.agents skill folders; COPILOT_HOME stops it +# reading ~/.agents/skills), but the prompt still names the SKILL.md to load: +# {skill_dir} is the folder bmad-loop located — .agents/skills/, shared +# with codex/gemini and matching upstream BMAD-METHOD's github-copilot installer, +# or a user root's absolute folder under `[skills] user_roots`. "use subagents as # needed" keeps parallel skill phases (e.g. review layers) actually spawning # subagents, same as codex. # @@ -20,7 +23,7 @@ # 'disable' suppresses the --allow-all-* flags and will block unattended runs. name = "copilot" binary = "copilot" -prompt_template = "LOAD the FULL .agents/skills/{skill}/SKILL.md, read its entire contents and follow its directions exactly, using subagents as needed: {args}" +prompt_template = "LOAD the FULL {skill_dir}/SKILL.md, read its entire contents and follow its directions exactly, using subagents as needed: {args}" launch_args = ["-i"] # Three separate confirmations, each its own flag # (https://docs.github.com/en/copilot/reference/cli-command-reference): tool @@ -61,3 +64,19 @@ seed_files = [".github/copilot/settings.json"] dialect = "copilot-settings-json" config_path = ".github/copilot/settings.json" events = { agentStop = "Stop", sessionStart = "SessionStart", sessionEnd = "SessionEnd" } + +# The home-relative skill folders Copilot CLI loads on its own, read only with +# `[skills] user_roots = true` (see bmad_loop.skill_locate). Project skills beat +# personal ones; COPILOT_HOME moves ~/.copilot and stops it reading +# ~/.agents/skills. +# Source: https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-skills (2026-11-15). +[user_skills] +precedence = "project" +roots = [ + { path = "~/.copilot/skills", disabled_by = [ + "COPILOT_HOME", + ] }, + { path = "~/.agents/skills", disabled_by = [ + "COPILOT_HOME", + ] }, +] diff --git a/src/bmad_loop/data/profiles/gemini.toml b/src/bmad_loop/data/profiles/gemini.toml index 45c79678d..956e4980e 100644 --- a/src/bmad_loop/data/profiles/gemini.toml +++ b/src/bmad_loop/data/profiles/gemini.toml @@ -24,3 +24,19 @@ GEMINI_CLI_TRUST_WORKSPACE = "true" dialect = "gemini-settings-json" config_path = ".gemini/settings.json" events = { SessionStart = "SessionStart", AfterAgent = "Stop", SessionEnd = "SessionEnd" } + +# The home-relative skill folders Gemini CLI loads on its own, read only with +# `[skills] user_roots = true` (see bmad_loop.skill_locate). Workspace skills +# beat user skills, and ~/.agents/skills beats ~/.gemini/skills; GEMINI_CLI_HOME +# moves both away from the home directory. +# Source: https://geminicli.com/docs/cli/skills/ (2026-11-15). +[user_skills] +precedence = "project" +roots = [ + { path = "~/.agents/skills", disabled_by = [ + "GEMINI_CLI_HOME", + ] }, + { path = "~/.gemini/skills", disabled_by = [ + "GEMINI_CLI_HOME", + ] }, +] diff --git a/src/bmad_loop/data/profiles/opencode.toml b/src/bmad_loop/data/profiles/opencode.toml index 291804f02..4a1dbe8e3 100644 --- a/src/bmad_loop/data/profiles/opencode.toml +++ b/src/bmad_loop/data/profiles/opencode.toml @@ -14,6 +14,10 @@ adapter = "opencode-http" prompt_template = "Use the {skill} skill now: {args}" usage_parser = "none" skill_tree = ".claude/skills" +# The skills CLI (`npx skills add`) installs opencode's project skills into +# .agents/skills, while bmad-loop init seeds .claude/skills: the session reads +# both (V1 `skills.paths`, V2 `skills` plus an allow rule per id), primary first. +extra_skill_trees = [".agents/skills"] first_run_note = "run `opencode auth login` once on this machine; headless servers reuse the stored credentials" # Transport/provider environment-fault classification (#194). Unlike the tmux @@ -117,3 +121,17 @@ usage_limit_patterns = ['^provider-error event=\S+ type=provider[.]quota '] [hooks] dialect = "none" + +# The home-relative skill folders OpenCode loads on its own, read only with +# `[skills] user_roots = true` (see bmad_loop.skill_locate). XDG_CONFIG_HOME moves +# the first away from ~/.config. +# Source: https://opencode.ai/docs/skills/ (2026-11-15). +[user_skills] +precedence = "project" +roots = [ + { path = "~/.config/opencode/skills", disabled_by = [ + "XDG_CONFIG_HOME", + ] }, + "~/.agents/skills", + "~/.claude/skills", +] diff --git a/src/bmad_loop/data/settings/core.toml b/src/bmad_loop/data/settings/core.toml index afcc80260..863a5a957 100644 --- a/src/bmad_loop/data/settings/core.toml +++ b/src/bmad_loop/data/settings/core.toml @@ -578,6 +578,16 @@ default_ref = "OperatorPolicy.on_review_demotion" label = "review may park a done story" description = "escalate: a review pass is never offered the park, and one that finalizes a done story at awaiting-operator is not accepted (default) · park: the review may demote it — the board moves done -> awaiting-operator, the story commits and parks · sprint mode with parks enabled only" +[[section]] +name = "skills" +description = "where skills are resolved from" +[[section.field]] +key = "user_roots" +kind = "switch" +default_ref = "SkillsPolicy.user_roots" +label = "user-level skill folders" +description = "ON: a skill missing from the project's skill trees may resolve from the user-level folders the coding CLI loads on its own (its profile's [user_skills] roots, e.g. ~/.agents/skills after `npx skills add -g`); when both hold a copy, the profile's precedence picks, so a precedence = \"user\" CLI (claude) runs the user copy over the project's · OFF (default): the project's skill trees only" + [[section]] name = "mux" description = "terminal-multiplexer backend (machine-specific — policy.toml is gitignored)" diff --git a/src/bmad_loop/engine.py b/src/bmad_loop/engine.py index ae22b8e08..145692ae1 100644 --- a/src/bmad_loop/engine.py +++ b/src/bmad_loop/engine.py @@ -23,7 +23,16 @@ from enum import StrEnum from pathlib import Path from stat import S_ISREG -from typing import TYPE_CHECKING, Callable, Literal, NamedTuple, NoReturn, Protocol, Sequence +from typing import ( + TYPE_CHECKING, + Callable, + Literal, + Mapping, + NamedTuple, + NoReturn, + Protocol, + Sequence, +) from . import ( artifact_publication, @@ -32,6 +41,7 @@ envvars, gates, operatoractions, + skill_locate, ticketstore, verify, ) @@ -65,7 +75,12 @@ usage_relaunch, ) from .frontmatter import FrontmatterWriteError -from .install import dev_primitive_or_default +from .install import ( + dev_primitive_or_default, + module_record_version, + required_review_skill_names, + user_root_skill_ids, +) from .journal import SELF_MINTED_FIELDS, Journal, save_state from .model import ( ENV_FAULT_SITE_DISPATCH_PREFIX, @@ -1077,12 +1092,12 @@ def __init__( self._graceful_stopped = False self._graceful_remaining: int | None = None # dev-primitive name resolved from disk, memoized per (workspace project - # root, skill tree) — see _dev_skill. By tree because one run can mix them - # (dev=claude reads .claude/skills, review=codex reads .agents/skills), with - # None for an adapter that carries no profile at all; by project root + # root, skill scope) — see _dev_skill. By scope because one run can mix + # them (dev=claude reads .claude/skills, review=codex reads .agents/skills), + # with None for an adapter that carries no profile at all; by project root # because under isolation each unit resolves against its OWN worktree and # one Engine drives every unit of a run. - self._dev_skill_cache: dict[tuple[Path, str | None], str] = {} + self._dev_skill_cache: dict[tuple[Path, skill_locate.SkillScope | None], str] = {} # story_key -> the highest `verify-command-result` sequence allocated so # far. None until the first verify pass seeds it from the journal — see # _next_verification_sequence, which owns the whole invariant. @@ -5579,10 +5594,12 @@ def _dev_skill(self, role: str = "dev") -> str: either era. This is NOT ``policy.dev.skill`` — that stays the adapter discriminator ``_generic_dev`` reads; only the spelled name moves. - Resolution is per skill tree because one run can mix them (dev=claude → - ``.claude/skills``, review=codex → ``.agents/skills``), and memoized - because every prompt build would otherwise re-stat the tree. An adapter - with no ``profile`` (test fakes) yields tree None, which + Resolution is per skill scope (:meth:`_skill_scope`) because one run can + mix them (dev=claude → ``.claude/skills``, review=codex → + ``.agents/skills``), and memoized because every prompt build would + otherwise re-stat the tree. Under ``[skills] user_roots`` a primitive + installed only in a user root the CLI loads resolves too. An adapter with + no ``profile`` (test fakes) yields scope None, which ``dev_primitive_or_default`` maps to the legacy name. Resolved against the WORKSPACE, never the main checkout: the session runs @@ -5596,12 +5613,99 @@ def _dev_skill(self, role: str = "dev") -> str: The cache is keyed on the workspace root for the same reason: one Engine drives every unit of a run, so a resumed unit's worktree must not answer for the fresh worktrees mounted after it.""" - adapter = self.adapters.get(role) - tree = getattr(getattr(adapter, "profile", None), "skill_tree", None) + scope = self._skill_scope(role) project = self.workspace.paths.project - if (project, tree) not in self._dev_skill_cache: - self._dev_skill_cache[project, tree] = dev_primitive_or_default(project, tree) - return self._dev_skill_cache[project, tree] + if (project, scope) not in self._dev_skill_cache: + self._dev_skill_cache[project, scope] = dev_primitive_or_default(project, scope) + return self._dev_skill_cache[project, scope] + + def _skill_scope( + self, role: str, session_env: Mapping[str, str] | None = None + ) -> skill_locate.SkillScope | None: + """The skill scope ``role``'s sessions load skills from: its profile's + primary and extra trees, plus the profile's declared user roots — resolved + only under ``[skills] user_roots`` (#770). ``session_env`` is one + session's post-hook env, whose user-root disablers count too. None for an + adapter with no ``profile`` (test fakes), which every caller reads as + "nothing to locate".""" + profile = getattr(self.adapters.get(role), "profile", None) + if profile is None: + return None + return skill_locate.scope_for( + profile, resolve_user=self.policy.skills.user_roots, session_env=session_env + ) + + def _refuse_hook_changed_skill( + self, role: str, project: Path, scope: skill_locate.SkillScope, skill: str + ) -> None: + """Stop a launch whose post-hook env changes a skill the run preflight + checked for it. + + The prompt is built before the ``pre_session`` hooks run, against the + scope every session of the profile shares (:meth:`_dev_skill` picks the + primitive's name there), and the preflight checked the copies that scope + resolves. A hook that sets a user root's disabler (an account rotation's + ``CLAUDE_CONFIG_DIR``) changes what the CLI loads: it can hide the only + copy, so the CLI halts on an unknown command, or hand the session another + copy that no check read (an older primitive without ticket support, say). + Either stops the launch, unless the other copy holds the same files + (:func:`skill_locate.same_copy`). The prompt is not rebuilt, because hooks + may have rewritten it. + + The skills compared are the prompt's skill and, for the dev primitive, the + review skills it WILL invoke (:func:`required_review_skill_names`). An + advisory reviewer (a ``when``-gated layer, an unconfirmed reference) is left + out: its layer may never run, and preflight only warns when it is missing. + Only a skill the shared scope resolves counts: one that resolves nowhere is + preflight's finding, not the hook's.""" + if not skill: + return + shared = self._skill_scope(role) + if shared is None: + return + names = [skill] + if skill == self._dev_skill(role): + names += [n for n in required_review_skill_names(project, shared) if n != skill] + for name in dict.fromkeys(names): + before = skill_locate.locate(project, shared, name) + if before is None: + continue + after = skill_locate.locate(project, scope, name) + if after is not None and skill_locate.same_copy(before, after): + continue + needs = ( + f"names /{skill}" + if name == skill + else f"names /{skill}, whose review step needs {name}" + ) + if any(r.spelling == before.root and r.unavailable for r in scope.user_roots): + what = ( + "a pre-session hook hid that root: " + f"{self._hook_hid_cause(scope, before.root)} stops the CLI reading it" + ) + else: + what = "a pre-session hook's env changes which copy the CLI loads" + if after is not None: + what += f", so the session would load the copy in {after.root}, which no check read" + raise RuntimeError( + f"the {role} session prompt {needs}, which resolves from {before.root}, " + f"but {what}. Install the " + "skill in the project tree (one copy only), or stop the hook from setting it" + ) + + @staticmethod + def _hook_hid_cause(scope: skill_locate.SkillScope, root: str) -> str: + """The clause naming what hid ``root`` in the post-hook ``scope``: the + disabler the hook set, else the hook's env in general.""" + why = next( + ( + r.unavailable.removeprefix("env:") + for r in scope.user_roots + if r.spelling == root and r.unavailable.startswith("env:") + ), + None, + ) + return f"it sets {why}, which" if why else "its env" def _operator_park_enabled(self) -> bool: """Whether a dev session may park a story at ``awaiting-operator`` (#335). @@ -9551,6 +9655,32 @@ def _run_session( self._commit_engine_ledger(task, site=role) if prelaunch_validator is not None: prelaunch_validator() + # Where the final prompt's skill lives (#770), read off the post-gate text + # like `expected_spec` below so a plugin rewrite cannot desynchronize them: + # the `{skill_dir}` a profile template spells, and — only under + # `[skills] user_roots` — the module skill ids the CLI loads from a user + # root, each journaled so the run records which skills came from outside + # the project. Resolved against the post-hook `env` the session launches + # with: a `pre_session` plugin that sets a root's disabler (an account + # rotation's CLAUDE_CONFIG_DIR) hides that root from the CLI, so it is + # hidden here too. + skill_dir: str | None = None + user_skill_ids: tuple[str, ...] = () + user_skill_rows: list[tuple[str, str, str | None]] = [] + scope = self._skill_scope(role, env) + if scope is not None: + project = self.workspace.paths.project + skill_dir = skill_locate.prompt_skill_dir(project, scope, prompt) + if scope.resolve_user: + prompt_skill, _ = skill_locate.prompt_skill(prompt) + self._refuse_hook_changed_skill(role, project, scope, prompt_skill) + user_skill_ids = user_root_skill_ids(project, scope, prompt_skill) + for skill in user_skill_ids: + found = skill_locate.locate(project, scope, skill) + if found is not None: + user_skill_rows.append( + (skill, found.root, module_record_version(found.path.parent, skill)) + ) spec = SessionSpec( task_id=task_id, role=role, @@ -9623,8 +9753,19 @@ def _run_session( # the v6 defaults (`done`, none) for every base and stories session. success_statuses=self._session_success_statuses(role, label), fallback_result_dirs=self._session_fallback_dirs(role, label), + skill_dir=skill_dir, + user_skill_ids=user_skill_ids, ) self.journal.set_active_log(task_id) + for skill, root, version in user_skill_rows: + self.journal.append( + "skill-user-root", + task_id=task_id, + role=role, + skill=skill, + root=root, + version=version, + ) self.journal.append( "session-start", task_id=task_id, @@ -10933,7 +11074,7 @@ def _defer(self, task: StoryTask, reason: str) -> None: task, site="defer", message=( - "chore(deferred-work): restore ledger after deferring " f"{task.story_key}" + f"chore(deferred-work): restore ledger after deferring {task.story_key}" ), ) self._record_defer(task, reason) @@ -12611,9 +12752,13 @@ def _maybe_auto_retro(self, epic: int) -> None: if not clean: self._skip_auto_retro(epic, "dirty") return - adapter = self.adapters["retro"] - tree = getattr(getattr(adapter, "profile", None), "skill_tree", None) - if tree and not (self.workspace.paths.project / tree / RETRO_SKILL / "SKILL.md").is_file(): + # The copy the retro CLI loads (#770): a user-root install counts under + # `[skills] user_roots`; an adapter with no profile is not probed. + scope = self._skill_scope("retro") + if ( + scope is not None + and skill_locate.locate(self.workspace.paths.project, scope, RETRO_SKILL) is None + ): self._skip_auto_retro(epic, "skill-missing") return diff --git a/src/bmad_loop/install.py b/src/bmad_loop/install.py index 252d37dd8..97297c05b 100644 --- a/src/bmad_loop/install.py +++ b/src/bmad_loop/install.py @@ -36,7 +36,7 @@ from pathlib import Path, PurePosixPath, PureWindowsPath from typing import Any, Literal, NamedTuple -from . import bmadconfig, childrun, ticketlayout, ticketmodel, ticketstore, tickettree +from . import bmadconfig, childrun, skill_locate, ticketlayout, ticketmodel, ticketstore, tickettree from .adapters.profile import ( ALIASES, CANONICAL_EVENTS, @@ -49,6 +49,7 @@ from .platform_util import atomic_write_bytes, atomic_write_text, file_lock from .policy import POLICY_TEMPLATE from .process_host import ProcessHostError, get_process_host +from .skill_locate import Located, SkillScope, as_scope from .verify import ( GitError, git_below_floor, @@ -283,7 +284,56 @@ def _customize_overrides(skill: str) -> tuple[Path, ...]: ) -def resolve_dev_primitive(project: Path, tree: str) -> str | None: +# A skill question's tree argument: a plain tree string (a project-only scope over +# that one tree, exactly as before user roots existed) or a :class:`SkillScope` +# from :func:`skill_locate.scope_for`. Every question below resolves a skill +# through :func:`skill_locate.locate`, so the copy a check reads is the copy the +# session loads. +SkillTree = str | SkillScope + + +def _scope_items(trees: Iterable[SkillTree]) -> list[SkillScope]: + """``trees`` as scopes, deduplicated in first-seen order.""" + return list(dict.fromkeys(as_scope(tree) for tree in trees)) + + +def _skill_dir(project: Path, scope: SkillScope, name: str) -> Path: + """Where ``name``'s files are read: the located copy's folder, else the primary + tree's spelling of it (absent or SKILL.md-less), which is exactly the path a + plain string tree has always read.""" + found = skill_locate.locate(project, scope, name) + return found.path if found is not None else project / scope.tree / name + + +def _root_detail(found: Located | None) -> dict[str, str]: + """The additive ``root`` detail entry for a copy outside the primary tree.""" + return {} if found is None or found.primary else {"root": found.root} + + +def _searched_detail(scope: SkillScope) -> dict[str, list[str]]: + """The additive ``searched`` detail entry: every location a missing skill was + looked for, when that is more than the primary tree alone.""" + searched = list(scope.project_trees()) + if scope.resolve_user: + searched += [root.spelling for root in scope.user_roots if not root.unavailable] + return {"searched": searched} if len(searched) > 1 else {} + + +def _primitive_copy(project: Path, tree: SkillTree) -> Located | None: + """The located dev primitive :func:`resolve_dev_primitive` names, or None.""" + scope = as_scope(tree) + new = skill_locate.locate(project, scope, DEV_PRIMITIVE_NEW) + if new is not None: + return new + legacy = skill_locate.locate(project, scope, DEV_PRIMITIVE_LEGACY) + if legacy is not None and all( + _is_file(legacy.path / marker) for marker in DEV_PRIMITIVE_MARKERS + ): + return legacy + return None + + +def resolve_dev_primitive(project: Path, tree: SkillTree) -> str | None: """The dev-primitive skill name to drive in ``tree``, or None when none is usable. Prefers :data:`DEV_PRIMITIVE_NEW`; falls back to :data:`DEV_PRIMITIVE_LEGACY` @@ -295,25 +345,30 @@ def resolve_dev_primitive(project: Path, tree: str) -> str | None: :func:`missing_base_skills` against the resolved dir. Requiring markers here instead would make a truncated bmad-build-auto silently resolve to a legacy install (or to the shim's failure message), hiding the real problem. + + Each name is located through ``tree``'s scope (:func:`skill_locate.locate`), so a + user-root copy resolves only when the scope says the CLI would load it. """ - if _is_file(project / tree / DEV_PRIMITIVE_NEW / "SKILL.md"): - return DEV_PRIMITIVE_NEW - legacy = project / tree / DEV_PRIMITIVE_LEGACY - if _is_file(legacy / "SKILL.md") and all( - _is_file(legacy / marker) for marker in DEV_PRIMITIVE_MARKERS - ): - return DEV_PRIMITIVE_LEGACY + found = _primitive_copy(project, tree) + return found.name if found is not None else None + + +def _shim_copy(project: Path, tree: SkillTree) -> Located | None: + """The located legacy-named skill when it is only a forwarding shim (SKILL.md + present, at least one marker absent), else None.""" + legacy = skill_locate.locate(project, as_scope(tree), DEV_PRIMITIVE_LEGACY) + if legacy is None: + return None + if any(not (legacy.path / marker).is_file() for marker in DEV_PRIMITIVE_MARKERS): + return legacy return None -def _is_dev_primitive_shim(project: Path, tree: str) -> bool: +def _is_dev_primitive_shim(project: Path, tree: SkillTree) -> bool: """True when ``tree`` holds a legacy-named skill that is only a forwarding shim (SKILL.md present, at least one marker absent). Selects the failure *message* in :func:`missing_base_skills`; it is never a resolution input.""" - legacy = project / tree / DEV_PRIMITIVE_LEGACY - if not (legacy / "SKILL.md").is_file(): - return False - return any(not (legacy / marker).is_file() for marker in DEV_PRIMITIVE_MARKERS) + return _shim_copy(project, tree) is not None def _is_renderer_stub(skill_dir: Path) -> bool: @@ -387,21 +442,21 @@ def _absent_renderer_sources(skill_dir: Path) -> list[str]: return sorted(set(absent)) -def renderer_stub_resolved(project: Path, trees: Sequence[str]) -> bool: +def renderer_stub_resolved(project: Path, trees: Sequence[SkillTree]) -> bool: """Whether any active tree resolves to a renderer-backed dev primitive. Resolution is per tree and deduplicated exactly like :func:`missing_base_skills`. Public because the engine's seed-escalation decision reuses this exact preflight discriminator rather than re-deriving one (`worktree_flow`). """ - for tree in dict.fromkeys(trees): - resolved = resolve_dev_primitive(project, tree) - if resolved is not None and _is_renderer_stub(project / tree / resolved): + for scope in _scope_items(trees): + found = _primitive_copy(project, scope) + if found is not None and _is_renderer_stub(found.path): return True return False -def dev_primitive_or_default(project: Path, tree: str | None) -> str: +def dev_primitive_or_default(project: Path, tree: SkillTree | None) -> str: """Total form of :func:`resolve_dev_primitive` for callers that need a name. A prompt string — and a path this module has to probe *somewhere* to report on — @@ -597,7 +652,7 @@ class _MergedReview(NamedTuple): selection: str | None -def _merged_review_layers(project: Path, tree: str, skill: str) -> _MergedReview | None: +def _merged_review_layers(project: Path, tree: SkillTree, skill: str) -> _MergedReview | None: """The skill's shipped review layers with project overrides applied. ``skill`` is the resolved dev-primitive name — the shipped config and its @@ -621,8 +676,12 @@ def _merged_review_layers(project: Path, tree: str, skill: str) -> _MergedReview there and must not pull the preflight onto the layer path — that would require skills the run never invokes. A shipped file carrying a review layer keeps the layer path whatever lens tables it also carries (the v6.10-6.12 contract). + + The shipped ``customize.toml`` is read from the copy ``tree``'s scope locates + (a user-root copy when the session would load that one); the overrides are + always the project's own ``_bmad/custom/`` files, wherever the skill lives. """ - data = _read_toml(project / tree / skill / "customize.toml") + data = _read_toml(_skill_dir(project, as_scope(tree), skill) / "customize.toml") if data is None: return None layers = _layers_of(data) @@ -698,7 +757,7 @@ def _collect_layer_skills( ids.append(layer_id) -def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: +def resolve_review_layers(project: Path, tree: SkillTree) -> ReviewResolution | None: """Read the review skills this project will really invoke, or None if unknown. The primitive's installed NAME is resolved from disk here rather than taken as @@ -771,7 +830,9 @@ def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: tuple(active_sets), ) try: - step04 = (project / tree / primitive / "step-04-review.md").read_text(encoding="utf-8") + step04 = (_skill_dir(project, as_scope(tree), primitive) / "step-04-review.md").read_text( + encoding="utf-8" + ) except (OSError, UnicodeDecodeError): return None # step-04 is a whole prose document rather than a self-contained execution @@ -796,8 +857,20 @@ def resolve_review_layers(project: Path, tree: str) -> ReviewResolution | None: STORIES_PROBE_TEXT = "folder+id dispatch" +def _primitive_probe( + project: Path, scope: SkillScope, found: Located | None, name: str +) -> tuple[str, str, str, Path]: + """``(tree, skill, rel, path)`` of the dev primitive's file ``name``: the located + copy's, or — nothing resolved — :data:`DEV_PRIMITIVE_NEW`'s under the primary + tree, the name to install. ``rel`` is the skill folder as messages show it.""" + if found is None: + rel = f"{scope.tree}/{DEV_PRIMITIVE_NEW}" + return scope.tree, DEV_PRIMITIVE_NEW, rel, project / rel / name + return scope.tree, found.name, found.display, found.path / name + + def missing_stories_support( - project: Path, trees: Sequence[str], *, skip_unresolved: bool = False + project: Path, trees: Sequence[SkillTree], *, skip_unresolved: bool = False ) -> list[Finding]: """Problems for stories mode's stricter dev-primitive requirement. @@ -820,13 +893,12 @@ def missing_stories_support( runs :func:`missing_base_skills` over the same trees, which already reports it (``skills.base-missing``/``-shim``) and keeps the run refused.""" problems: list[Finding] = [] - for tree in dict.fromkeys(trees): - skill = resolve_dev_primitive(project, tree) - if skill is None and skip_unresolved: + for scope in _scope_items(trees): + found = _primitive_copy(project, scope) + if found is None and skip_unresolved: continue - skill = skill or DEV_PRIMITIVE_NEW - probe = project / tree / skill / STORIES_PROBE_FILE - detail = {"tree": tree, "skill": skill, "file": STORIES_PROBE_FILE} + tree, skill, rel, probe = _primitive_probe(project, scope, found, STORIES_PROBE_FILE) + detail = {"tree": tree, "skill": skill, "file": STORIES_PROBE_FILE, **_root_detail(found)} try: text = probe.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): @@ -838,7 +910,7 @@ def missing_stories_support( Finding( "skills.stories-dispatch-missing", "problem", - f"{tree}/{skill}/{STORIES_PROBE_FILE} not found — stories " + f"{rel}/{STORIES_PROBE_FILE} not found — stories " f"mode needs folder+id dispatch; update the BMad Method (bmm) module", detail, ) @@ -849,7 +921,7 @@ def missing_stories_support( Finding( "skills.stories-dispatch-stale", "problem", - f"{tree}/{skill} lacks folder+id dispatch (no " + f"{rel} lacks folder+id dispatch (no " f"{STORIES_PROBE_TEXT!r} in {STORIES_PROBE_FILE}) — stories mode needs a " f"newer {skill}; update the bmm module", {**detail, "marker": STORIES_PROBE_TEXT}, @@ -866,6 +938,7 @@ def missing_stories_support( # The method module's install record, relative to a skill tree: `[bmod] version` # names the installed BMAD-METHOD release. Display only. BMOD_METHOD_MANIFEST = "bmod-method/bmod.toml" +BMOD_METHOD_SKILL = "bmod-method" # A dev primitive that dispatches `ticket ` from the tree resolves it with # `uv run {project-root}/_bmad/method/scripts/tickets.py ... find ` in its # step-01; an older one has no ticket route. The marker is that script path, @@ -874,20 +947,27 @@ def missing_stories_support( TICKETS_PROBE_TEXT = "method/scripts/tickets.py" -def bmod_method_version(project: Path, trees: Sequence[str]) -> str | None: +def _bmod_version(manifest: Path) -> str | None: + """``[bmod] version`` of one ``bmod.toml``, or None.""" + data = _read_toml(manifest) + bmod = data.get("bmod") if data is not None else None + version = bmod.get("version") if isinstance(bmod, dict) else None + return version.strip() if isinstance(version, str) and version.strip() else None + + +def bmod_method_version(project: Path, trees: Sequence[SkillTree]) -> str | None: """``[bmod] version`` of the first ``/bmod-method/bmod.toml`` that has - one, or None. Display only: nothing gates on it.""" - for tree in dict.fromkeys(trees): - data = _read_toml(project / tree / BMOD_METHOD_MANIFEST) - bmod = data.get("bmod") if data is not None else None - version = bmod.get("version") if isinstance(bmod, dict) else None - if isinstance(version, str) and version.strip(): - return version.strip() + one, or None. Display only: nothing gates on it. Each tree's manifest is read + from the ``bmod-method`` copy its scope locates.""" + for scope in _scope_items(trees): + version = _bmod_version(_skill_dir(project, scope, BMOD_METHOD_SKILL) / "bmod.toml") + if version is not None: + return version return None def missing_tickets_support( - project: Path, trees: Sequence[str], *, skip_unresolved: bool = False + project: Path, trees: Sequence[SkillTree], *, skip_unresolved: bool = False ) -> list[Finding]: """Problems for tickets mode's dev-primitive requirement: the resolved primitive's ``step-01-clarify-and-route.md`` must route a ticket from the tree @@ -899,13 +979,12 @@ def missing_tickets_support( unresolved primitive is named and ``skip_unresolved`` honoured, as in :func:`missing_stories_support`.""" problems: list[Finding] = [] - for tree in dict.fromkeys(trees): - skill = resolve_dev_primitive(project, tree) - if skill is None and skip_unresolved: + for scope in _scope_items(trees): + found = _primitive_copy(project, scope) + if found is None and skip_unresolved: continue - skill = skill or DEV_PRIMITIVE_NEW - probe = project / tree / skill / TICKETS_PROBE_FILE - detail = {"tree": tree, "skill": skill, "file": TICKETS_PROBE_FILE} + tree, skill, rel, probe = _primitive_probe(project, scope, found, TICKETS_PROBE_FILE) + detail = {"tree": tree, "skill": skill, "file": TICKETS_PROBE_FILE, **_root_detail(found)} try: text = probe.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): @@ -913,7 +992,7 @@ def missing_tickets_support( Finding( "skills.tickets-dispatch-missing", "problem", - f"{tree}/{skill}/{TICKETS_PROBE_FILE} not found — tickets mode " + f"{rel}/{TICKETS_PROBE_FILE} not found — tickets mode " f"needs a dev primitive that dispatches from the ticket tree; " f"update the BMad Method module", detail, @@ -925,7 +1004,7 @@ def missing_tickets_support( Finding( "skills.tickets-dispatch-stale", "problem", - f"{tree}/{skill} cannot dispatch from the ticket tree (no " + f"{rel} cannot dispatch from the ticket tree (no " f"{TICKETS_PROBE_TEXT!r} in {TICKETS_PROBE_FILE}) — tickets mode needs " f"a newer {skill}; update the BMad Method module", {**detail, "marker": TICKETS_PROBE_TEXT}, @@ -972,8 +1051,7 @@ def _probe_unreadable(check: str, rel: str, fault: str) -> Finding: return Finding( check, "problem", - f"{rel} could not be checked ({fault}) — fix its permissions or the filesystem " - "and re-run", + f"{rel} could not be checked ({fault}) — fix its permissions or the filesystem and re-run", {"path": rel, "error": fault}, ) @@ -1065,7 +1143,7 @@ def _tickets_store_findings( ) if sandboxed_roles: causes.append( - f"{', '.join(sandboxed_roles)} run permission_mode = \"sandboxed\", whose " + f'{", ".join(sandboxed_roles)} run permission_mode = "sandboxed", whose ' 'sandbox confines writes to the working directory (use "bypass" there)' ) findings.append( @@ -1198,7 +1276,7 @@ def tickets_parent_problems( def tickets_preflight( paths: bmadconfig.ProjectPaths, - trees: Sequence[str], + trees: Sequence[SkillTree], *, probe_capability: bool, branch_per: str | None = None, @@ -1528,9 +1606,7 @@ def missing_sweep_skill(project: Path, trees: Sequence[str]) -> list[Finding]: return problems -def missing_base_skills( - project: Path, trees: Sequence[str], *, home: Path | None = None -) -> list[Finding]: +def missing_base_skills(project: Path, trees: Sequence[SkillTree]) -> list[Finding]: """Problems for the upstream skills the orchestrator drives but doesn't bundle. The dev primitive (bmad-build-auto, or a complete pre-rename bmad-dev-auto) and @@ -1572,10 +1648,10 @@ def missing_base_skills( can have a post-consolidation `.claude` tree and a pre-merge `.agents` one side by side — and, across the rename, a different primitive era in each. - A nothing-resolved ``skills.base-missing`` notes a global install of the - primitive (``~/.claude/skills`` or ``~/.agents/skills``) when one exists, with - its path in ``detail["outside"]``; ``home`` overrides the probed home directory - (tests inject it). That is a hint, never a resolution: the run still refuses. + A ``skills.base-missing`` (or ``review-layer-missing``) for a scope with + ``[skills] user_roots`` off notes a copy in one of that CLI's own user roots + (:func:`_home_hint`), with its display path in ``detail["outside"]``. That is + a hint, never a resolution: the run still refuses until the switch is set. ``skills.base-incomplete`` carries ``missing_markers`` as a list — the message joins it with ", " for the human line, which a consumer would otherwise have to @@ -1595,19 +1671,27 @@ def missing_base_skills( These are independent of the ordinary marker check: a damaged primitive may need both remediations. All are content-gated on the installed SKILL.md, so an inline pre-renderer install sees byte-stable behavior. + + A ``trees`` entry may be a :class:`SkillScope`: every skill is then located + through it (:func:`skill_locate.locate`), a copy outside the primary tree adds + ``detail["root"]``, a missing skill searched in more than one place adds + ``detail["searched"]``, and the user-root warnings of + :func:`_user_root_findings` join the list. A plain string is a project-only + scope and reports exactly what it always has. """ problems: list[Finding] = [] resolved_stub = False - for tree in dict.fromkeys(trees): - resolved = resolve_dev_primitive(project, tree) - if resolved is None and _is_dev_primitive_shim(project, tree): - legacy_dir = project / tree / DEV_PRIMITIVE_LEGACY - absent = [m for m in DEV_PRIMITIVE_MARKERS if not (legacy_dir / m).is_file()] + for scope in _scope_items(trees): + tree = scope.tree + found = _primitive_copy(project, scope) + shim = _shim_copy(project, scope) if found is None else None + if shim is not None: + absent = [m for m in DEV_PRIMITIVE_MARKERS if not (shim.path / m).is_file()] problems.append( Finding( "skills.base-shim", "problem", - f"{tree}/{DEV_PRIMITIVE_LEGACY} is unusable (missing " + f"{shim.display} is unusable (missing " f"{', '.join(absent)}) and {DEV_PRIMITIVE_NEW} is not installed — " f"most likely the forwarding shim the BMad Method's rename left " f"behind, otherwise a truncated install; update the bmm module. The " @@ -1618,11 +1702,12 @@ def missing_base_skills( "skill": DEV_PRIMITIVE_LEGACY, "expected": DEV_PRIMITIVE_NEW, "missing_markers": absent, + **_root_detail(shim), }, ) ) - elif resolved is None: - hint, outside = _outside_hint(DEV_PRIMITIVE_NEW, tree, home) + elif found is None: + hint, outside = _home_hint(scope, DEV_PRIMITIVE_NEW) problems.append( Finding( "skills.base-missing", @@ -1631,20 +1716,30 @@ def missing_base_skills( f"upstream dev primitive directly; it ships with {BMAD_FLOOR_TEXT}; " f"install or update bmm (on v7, method) in this project " f"(older installs name it {DEV_PRIMITIVE_LEGACY}){hint}", - {"tree": tree, "skill": DEV_PRIMITIVE_NEW, **outside}, + { + "tree": tree, + "skill": DEV_PRIMITIVE_NEW, + **outside, + **_searched_detail(scope), + }, ) ) else: - skill_dir = project / tree / resolved + resolved, skill_dir, rel, root = ( + found.name, + found.path, + found.display, + _root_detail(found), + ) absent = [m for m in DEV_PRIMITIVE_MARKERS if not (skill_dir / m).is_file()] if absent: problems.append( Finding( "skills.base-incomplete", "problem", - f"{tree}/{resolved} is incomplete (missing " + f"{rel} is incomplete (missing " f"{', '.join(absent)}) — reinstall it from the bmm module", - {"tree": tree, "skill": resolved, "missing_markers": absent}, + {"tree": tree, "skill": resolved, "missing_markers": absent, **root}, ) ) if _is_renderer_stub(skill_dir): @@ -1659,7 +1754,7 @@ def missing_base_skills( Finding( "skills.dev-renderer", "problem", - f"{tree}/{resolved}/SKILL.md renders via " + f"{rel}/SKILL.md renders via " f"{RENDERER_SCRIPT_MARKER} but the renderer script unit is " f"incomplete (missing {', '.join(absent_scripts)}) — the " "session would HALT without writing a spec; reinstall the " @@ -1668,6 +1763,7 @@ def missing_base_skills( "tree": tree, "skill": resolved, "missing_scripts": absent_scripts, + **root, }, ) ) @@ -1677,7 +1773,7 @@ def missing_base_skills( Finding( "skills.dev-renderer-sources", "problem", - f"{tree}/{resolved} renders via {RENDERER_SCRIPT_MARKER} but its " + f"{rel} renders via {RENDERER_SCRIPT_MARKER} but its " f"render sources are incomplete (unresolved: " f"{', '.join(absent_sources)}) — the session would HALT without " "writing a spec; reinstall the BMad Method (bmm) module", @@ -1685,10 +1781,12 @@ def missing_base_skills( "tree": tree, "skill": resolved, "missing_sources": absent_sources, + **root, }, ) ) - problems.extend(_review_findings(project, tree, home=home)) + problems.extend(_review_findings(project, scope)) + problems.extend(_user_root_findings(project, scope, found)) if resolved_stub and not (project / CENTRAL_CONFIG_REL).is_file(): problems.append( Finding( @@ -1720,7 +1818,7 @@ def missing_base_skills( _FENCE_OPEN_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})") -def dev_renderer_probe(project: Path, trees: Sequence[str]) -> list[Finding]: +def dev_renderer_probe(project: Path, trees: Sequence[SkillTree]) -> list[Finding]: """Execute each renderer stub's own render command in a throwaway copy. The ``skills.dev-renderer*`` checks in :func:`missing_base_skills` prove the @@ -1764,14 +1862,19 @@ def dev_renderer_probe(project: Path, trees: Sequence[str]) -> list[Finding]: executes. Plain ``validate`` must stay non-executing for a fresh clone, as the provenance note on the ``adapter.binary`` probe in ``cmd_validate`` records. No coding CLI is launched and no prompt is sent. + + The stub is the copy each tree's scope locates; a user-root copy is staged from + its own folder into the temp root's primary-tree position (``detail["root"]`` + names where it came from). """ - unique = list(dict.fromkeys(trees)) + scopes = list(_scope_items(trees)) + unique = list(dict.fromkeys(scope.tree for scope in scopes)) findings: list[Finding] = [] - for tree in unique: - resolved = resolve_dev_primitive(project, tree) - if resolved is None or not _is_renderer_stub(project / tree / resolved): + for scope in scopes: + found = _primitive_copy(project, scope) + if found is None or not _is_renderer_stub(found.path): continue - findings.append(_probe_render(project, tree, resolved)) + findings.append(_probe_render(project, scope.tree, found.name, source=found)) if not findings: findings.append( Finding( @@ -1849,15 +1952,18 @@ def _last_line(text: str) -> str: return lines[-1] if lines else "" -def _probe_render(project: Path, tree: str, skill: str) -> Finding: - """One tree's render verdict; see :func:`dev_renderer_probe` for the contract.""" - rel = f"{tree}/{skill}" - detail: dict[str, Any] = {"tree": tree, "skill": skill} +def _probe_render( + project: Path, tree: str, skill: str, *, source: Located | None = None +) -> Finding: + """One tree's render verdict; see :func:`dev_renderer_probe` for the contract. + ``source`` is the located copy to probe (default: ``/``).""" + rel = source.display if source is not None else f"{tree}/{skill}" + detail: dict[str, Any] = {"tree": tree, "skill": skill, **_root_detail(source)} def problem(message: str) -> Finding: return _render_problem(detail, message) - skill_dir = project / tree / skill + skill_dir = source.path if source is not None else project / tree / skill unparsed = f"{rel}/SKILL.md: the render command could not be parsed" try: skill_md = (skill_dir / "SKILL.md").read_text(encoding="utf-8") @@ -1866,8 +1972,7 @@ def problem(message: str) -> Finding: line = _render_command_line(skill_md) if line is None: return problem( - f"{unparsed} (no fenced code line names {RENDERER_SCRIPT_MARKER}); " - "nothing was executed" + f"{unparsed} (no fenced code line names {RENDERER_SCRIPT_MARKER}); nothing was executed" ) detail["command"] = line try: @@ -1887,7 +1992,7 @@ def problem(message: str) -> Finding: with tempfile.TemporaryDirectory( prefix="bmad-loop-render-probe-", ignore_cleanup_errors=True ) as tmp: - return _render_in(project, Path(tmp), template, detail) + return _render_in(project, Path(tmp), template, detail, source=skill_dir, rel=rel) except OSError as exc: return problem(f"{rel}: could not create a throwaway render directory ({exc})") @@ -1897,11 +2002,20 @@ def _render_problem(detail: Mapping[str, Any], message: str, **extra: Any) -> Fi def _render_in( - project: Path, root: Path, template: Sequence[str], detail: Mapping[str, Any] + project: Path, + root: Path, + template: Sequence[str], + detail: Mapping[str, Any], + *, + source: Path | None = None, + rel: str | None = None, ) -> Finding: - """Stage the copy under ``root``, run the substituted command there, classify it.""" + """Stage the copy under ``root``, run the substituted command there, classify it. + + ``source`` is the skill folder staged (default ``//``); it + always lands at ``//``, and ``rel`` is how messages name it.""" tree, skill = str(detail["tree"]), str(detail["skill"]) - rel = f"{tree}/{skill}" + rel = rel if rel is not None else f"{tree}/{skill}" def problem(message: str, **extra: Any) -> Finding: return _render_problem(detail, message, **extra) @@ -1909,7 +2023,9 @@ def problem(message: str, **extra: Any) -> Finding: unmap = _render_path_unmapper(root, project) tmp_skill = root / tree / skill try: - _stage_render_copy(project, project / tree / skill, root, tmp_skill) + _stage_render_copy( + project, source if source is not None else project / tree / skill, root, tmp_skill + ) except OSError as exc: return problem(f"{rel}: could not stage the throwaway render copy ({unmap(str(exc))})") argv = [ @@ -1969,8 +2085,7 @@ def problem(message: str, **extra: Any) -> Finding: if halt is not None: text = halt[len(_RENDER_HALT_PREFIX) :].strip() return problem( - f"{rel}: render HALTs: {text} — a dev session would stop here without " - "writing a spec", + f"{rel}: render HALTs: {text} — a dev session would stop here without writing a spec", rc=proc.returncode, halt=text, ) @@ -1991,7 +2106,7 @@ def problem(message: str, **extra: Any) -> Finding: ) -def dev_primitive_warnings(project: Path, trees: Sequence[str]) -> list[Finding]: +def dev_primitive_warnings(project: Path, trees: Sequence[SkillTree]) -> list[Finding]: """Advisory findings about a resolved dev primitive — validate-only, never a gate. One condition, and it is genuinely survivable — which is what keeps it out of @@ -2023,9 +2138,15 @@ def dev_primitive_warnings(project: Path, trees: Sequence[str]) -> list[Finding] Returns [] when nothing resolves — :func:`missing_base_skills` owns that story. """ findings: list[Finding] = [] - resolved = {tree: resolve_dev_primitive(project, tree) for tree in dict.fromkeys(trees)} - new_trees = [tree for tree, name in resolved.items() if name == DEV_PRIMITIVE_NEW] - legacy_trees = [tree for tree, name in resolved.items() if name == DEV_PRIMITIVE_LEGACY] + resolved = {scope: resolve_dev_primitive(project, scope) for scope in _scope_items(trees)} + new_trees = list( + dict.fromkeys(scope.tree for scope, name in resolved.items() if name == DEV_PRIMITIVE_NEW) + ) + legacy_trees = list( + dict.fromkeys( + scope.tree for scope, name in resolved.items() if name == DEV_PRIMITIVE_LEGACY + ) + ) if new_trees: orphaned = [ (CUSTOMIZE_DIR / f"{DEV_PRIMITIVE_LEGACY}{suffix}").as_posix() @@ -2066,45 +2187,22 @@ def dev_primitive_warnings(project: Path, trees: Sequence[str]) -> list[Finding] return findings -# Where `npx skills add -g` lays a skill down, relative to the home directory. Probed -# read-only for a HINT only: bmad-loop drives skills from the project's own tree and -# never resolves one from here (a session cwd'd in the project would not see it in -# every CLI, and a worktree could not seed it). Claude Code's plugin cache is not -# probed — BMAD no longer ships Claude plugins. -_OUTSIDE_SKILL_ROOTS = (".claude/skills", ".agents/skills") - - -def _outside_home() -> Path: - """The home directory :func:`_outside_copy` probes by default. A seam: the test - suite pins it (conftest) so an operator's real global skills never leak into a - finding a test asserts on.""" - return Path.home() - - -def _outside_copy(name: str, home: Path | None = None) -> str | None: - """``~//`` for the first global install of skill ``name`` found under - :data:`_OUTSIDE_SKILL_ROOTS`, or None. An undeterminable or unreadable home is - None: this only decorates a finding, so it must never crash the preflight.""" - try: - base = _outside_home() if home is None else home - for root in _OUTSIDE_SKILL_ROOTS: - if (base / root / name / "SKILL.md").is_file(): - return f"~/{root}/{name}" - except (OSError, RuntimeError): - return None - return None - - -def _outside_hint(name: str, tree: str, home: Path | None) -> tuple[str, dict[str, str]]: - """The message suffix and detail entry for a skill installed only outside the - project (:func:`_outside_copy`), or ``("", {})`` when there is none.""" - outside = _outside_copy(name, home) - if outside is None: +def _home_hint(scope: SkillScope, name: str) -> tuple[str, dict[str, str]]: + """The message suffix and ``outside`` detail entry for a skill the project lacks + but one of the scope's own user roots holds while ``[skills] user_roots`` is + off (:func:`skill_locate.home_copy`), or ``("", {})``. Only the roots the CLI + itself loads are probed, and with the switch on there is nothing to hint: a + user copy would have resolved.""" + if scope.resolve_user: + return "", {} + found = skill_locate.home_copy(scope, name) + if found is None: return "", {} return ( - f"; a copy exists at {outside}, but bmad-loop only drives skills installed in " - f"this project's {tree} — install it per project (`npx skills add` without -g)", - {"outside": outside}, + f"; a copy exists at {found.display}, which this CLI loads — set " + f"`[skills] user_roots = true` in .bmad-loop/policy.toml to use it, or install " + f"it per project (`npx skills add` without -g)", + {"outside": found.display}, ) @@ -2117,7 +2215,7 @@ def _where_clause(layer_ids: Sequence[str]) -> str: return "review step invokes" -def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> list[Finding]: +def _review_findings(project: Path, tree: SkillTree) -> list[Finding]: """Findings for the review skills this tree's dev primitive invokes. Problems block; warnings never do. A skill is only a problem when the @@ -2135,32 +2233,40 @@ def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> l A tree whose primitive does not resolve gets NO review finding: the reviewers derive from the primitive, :func:`missing_base_skills` already reports that root cause, and the static fallback would otherwise demand the long-deleted hunters on - top of it. ``home`` overrides the home directory the out-of-project hint probes - (:func:`_outside_copy`); tests inject it. + top of it. + + Every skill is located through ``tree``'s scope, as in :func:`missing_base_skills`. """ - primitive = resolve_dev_primitive(project, tree) - if primitive is None: + scope = as_scope(tree) + found = _primitive_copy(project, scope) + if found is None: return [] - resolved = resolve_review_layers(project, tree) + primitive, primitive_rel, root = found.name, found.display, _root_detail(found) + tree_name = scope.tree + + def present(skill: str) -> bool: + return skill_locate.locate(project, scope, skill) is not None + + resolved = resolve_review_layers(project, scope) if resolved is None: # Unknown shape: keep the long-standing static requirement, which both real # topologies satisfy — the two hunters, or the merged reviewer instead. - if (project / tree / MERGED_REVIEW_SKILL / "SKILL.md").is_file(): + if present(MERGED_REVIEW_SKILL): return [] fallback: list[Finding] = [] for skill in sorted(_REVIEW_LAYER_SKILLS): - if (project / tree / skill / "SKILL.md").is_file(): + if present(skill): continue - hint, outside = _outside_hint(skill, tree, home) + hint, outside = _home_hint(scope, skill) fallback.append( Finding( "skills.base-missing", "problem", - f"{tree}/{skill} not found — this review layer ships with " + f"{tree_name}/{skill} not found — this review layer ships with " f"{BMAD_FLOOR_TEXT}, as does the consolidated {MERGED_REVIEW_SKILL} " f"skill that supersedes it in newer releases; install " f"{REVIEW_FLOOR_TEXT} in this project{hint}", - {"tree": tree, "skill": skill, **outside}, + {"tree": tree_name, "skill": skill, **outside, **_searched_detail(scope)}, ) ) return fallback @@ -2181,7 +2287,7 @@ def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> l f"{rel} could not be read as a customize override (invalid TOML, or an " f"array entry whose `id`/`code` is not a non-empty string) — " f"{consequence}; fix the file or remove it", - {"tree": tree, "file": rel}, + {"tree": tree_name, "file": rel}, ) ) override_rel = _customize_overrides(primitive)[0].as_posix() @@ -2191,11 +2297,11 @@ def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> l Finding( "skills.review-selection-invalid", "problem", - f"{tree}/{primitive} resolves workflow.review = {selection!r} — its " + f"{primitive_rel} resolves workflow.review = {selection!r} — its " f"workflow HALTs every dev run on any value but " f"{', '.join(REVIEW_SELECTIONS)}; fix `review` in {override_rel} or in " f"the skill's customize.toml", - {"tree": tree, "source": resolved.source, "selection": selection}, + {"tree": tree_name, "source": resolved.source, "selection": selection, **root}, ) ) if resolved.lens_sets: @@ -2216,11 +2322,11 @@ def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> l Finding( "skills.review-layers-empty", "problem", - f"{tree}/{primitive} has no enabled review lens (every `instruction` " + f"{primitive_rel} has no enabled review lens (every `instruction` " f"in {tables} is empty or absent) while workflow.review is " f"{selection!r} — every dev run would HALT with no lens to launch; " f're-enable a lens in {override_rel}, or set review = "none" there', - {"tree": tree, "source": resolved.source}, + {"tree": tree_name, "source": resolved.source, **root}, ) ) elif resolved.layer_driven and not resolved.active_layers: @@ -2228,47 +2334,48 @@ def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> l Finding( "skills.review-layers-empty", "problem", - f"{tree}/{primitive} has no enabled review layer (every " + f"{primitive_rel} has no enabled review layer (every " f"`instruction` is empty) — every dev run would HALT blocked with " f"'no active review layers'; re-enable a layer in " f"{override_rel}", - {"tree": tree, "source": resolved.source}, + {"tree": tree_name, "source": resolved.source, **root}, ) ) for skill, layer_ids in sorted(resolved.required.items()): - if (project / tree / skill / "SKILL.md").is_file(): + if present(skill): continue - hint, outside = _outside_hint(skill, tree, home) + hint, outside = _home_hint(scope, skill) findings.append( Finding( "skills.review-layer-missing", "problem", - f"{tree}/{skill} not found — {tree}/{primitive}'s " + f"{tree_name}/{skill} not found — {primitive_rel}'s " f"{_where_clause(layer_ids)} it ({resolved.source}), so every dev run's " f"review would fail; install {REVIEW_FLOOR_TEXT} so this project's " f"review layers resolve{hint}", { - "tree": tree, + "tree": tree_name, "skill": skill, "layers": list(layer_ids), "source": resolved.source, **outside, + **_searched_detail(scope), }, ) ) for skill, layer_ids in sorted(resolved.advisory.items()): - if (project / tree / skill / "SKILL.md").is_file(): + if present(skill): continue findings.append( Finding( "skills.review-layer-unresolved", "warning", - f"{tree}/{skill} not found — {tree}/{primitive}'s " + f"{tree_name}/{skill} not found — {primitive_rel}'s " f"{_where_clause(layer_ids)} it conditionally, or names it in prose this " f"check cannot confirm is a handoff ({resolved.source}); install it if " f"that layer is meant to run", { - "tree": tree, + "tree": tree_name, "skill": skill, "layers": list(layer_ids), "source": resolved.source, @@ -2278,6 +2385,274 @@ def _review_findings(project: Path, tree: str, *, home: Path | None = None) -> l return findings +def _review_skill_names(project: Path, scope: SkillScope) -> tuple[str, ...]: + """Every review skill ``scope``'s dev primitive may invoke: the read review + shape's skills, else the static merged-or-standalone fallback the preflight and + the worktree gate apply to a shape that cannot be read.""" + review = resolve_review_layers(project, scope) + if review is not None: + return review.skills() + return _fallback_review_skill_names(project, scope) + + +def _fallback_review_skill_names(project: Path, scope: SkillScope) -> tuple[str, ...]: + """The static review requirement for a review shape that cannot be read: the + merged reviewer when it resolves, else the standalone hunters.""" + if skill_locate.locate(project, scope, MERGED_REVIEW_SKILL) is not None: + return (MERGED_REVIEW_SKILL,) + return tuple(sorted(_REVIEW_LAYER_SKILLS)) + + +def required_review_skill_names(project: Path, tree: SkillTree) -> tuple[str, ...]: + """The review skills ``tree``'s dev primitive WILL invoke: the ones whose + absence fails the run preflight (the problem-severity rows of + :func:`_review_findings`). That is the read shape's ``required`` skills, else + the static fallback for a shape that cannot be read. ``advisory`` skills are + left out, because a gated layer may never run and preflight only warns about + them.""" + scope = as_scope(tree) + review = resolve_review_layers(project, scope) + if review is not None: + return tuple(review.required) + return _fallback_review_skill_names(project, scope) + + +USER_SHADOW_CHECK = "skills.user-shadow" +USER_ROOT_UNAVAILABLE_CHECK = "skills.user-root-unavailable" +USER_ROOT_VERSION_SKEW_CHECK = "skills.user-root-version-skew" +SKILL_ROOT_CHECK = "skills.root" + +_UNAVAILABLE_REASONS = { + "no-home": "the home directory cannot be determined", + "unreadable": "it cannot be read", +} + + +def _unavailable_text(reason: str) -> str: + if reason.startswith("env:"): + return f"{reason[4:]} is set, so the CLI does not read it" + return _UNAVAILABLE_REASONS.get(reason, reason) + + +def _user_root_findings(project: Path, scope: SkillScope, found: Located | None) -> list[Finding]: + """The user-root warnings for one scope; empty for a scope without user roots + (every plain tree string). + + - ``skills.user-shadow``: a skill the run drives sits in both a project tree + and a user root and the CLI may run the user copy instead of the one the + checks read (:func:`skill_locate.shadow`) — ``user`` precedence with the + switch off, ``unordered`` precedence whatever the switch. + - ``skills.user-root-unavailable`` (switch on only): a declared root that can + never resolve — a disabler variable is set, the home is unknown, or the + folder cannot be read. + - ``skills.user-root-version-skew``: a user root's and a project tree's + ``bmod-method/bmod.toml`` name different BMAD-METHOD versions, so skills + from two installs may mix in one session. + """ + if not scope.user_roots: + return [] + tree = scope.tree + findings: list[Finding] = [] + names = (found.name, *_review_skill_names(project, scope)) if found is not None else () + for name in dict.fromkeys(names): + clash = skill_locate.shadow(project, scope, name) + if clash is None: + continue + checked, other = clash.checked.display, clash.other.display + if clash.kind == "overrides": + message = ( + f"{other} overrides {checked}: this CLI loads the personal copy over the " + f"project's, but the checks read the project copy — remove {other}, or set " + f"`[skills] user_roots = true` in .bmad-loop/policy.toml so the checks read " + f"the copy that runs" + ) + else: + message = ( + f"{checked} and {other} both load, in no order this CLI states — the checks " + f"read the project copy; remove one of them so a session cannot run the other" + ) + findings.append( + Finding( + USER_SHADOW_CHECK, + "warning", + message, + { + "tree": tree, + "skill": name, + "checked": checked, + "other": other, + "precedence": scope.precedence, + "kind": clash.kind, + }, + ) + ) + if scope.resolve_user: + for root in scope.user_roots: + if not root.unavailable: + continue + findings.append( + Finding( + USER_ROOT_UNAVAILABLE_CHECK, + "warning", + f"user skill root {root.spelling} is unavailable " + f"({_unavailable_text(root.unavailable)}) — skills installed there are " + f"not used for {tree}", + {"tree": tree, "root": root.spelling, "reason": root.unavailable}, + ) + ) + project_version = next( + ( + v + for t in scope.project_trees() + if (v := _bmod_version(project / t / BMOD_METHOD_MANIFEST)) is not None + ), + None, + ) + user_found = next( + ( + (root.spelling, v) + for root in scope.user_roots + if not root.unavailable + and root.path is not None + and (v := _bmod_version(root.path / BMOD_METHOD_MANIFEST)) is not None + ), + None, + ) + if project_version is not None and user_found is not None and user_found[1] != project_version: + user_root, user_version = user_found + findings.append( + Finding( + USER_ROOT_VERSION_SKEW_CHECK, + "warning", + f"{user_root}/{BMOD_METHOD_SKILL} is BMAD-METHOD {user_version} but " + f"{tree}/{BMOD_METHOD_SKILL} is {project_version} — a session may mix skills " + f"from the two installs; update the older one", + { + "tree": tree, + "root": user_root, + "user_version": user_version, + "project_version": project_version, + }, + ) + ) + return findings + + +def session_skill_candidates( + project: Path, scope: SkillTree, prompt_skill: str = "" +) -> tuple[str, ...]: + """Every skill a session of ``scope``'s CLI may load: ``prompt_skill`` (the + skill its prompt names, when it names one), the :data:`BASE_SKILLS` catalog and + the review skills the installed primitive invokes.""" + review = resolve_review_layers(project, scope) + return tuple( + dict.fromkeys( + ( + *((prompt_skill,) if prompt_skill else ()), + *BASE_SKILLS, + *(review.skills() if review is not None else ()), + ) + ) + ) + + +# A skill id read from a user root's module record names a folder under that root; +# anything but a plain name (a separator, `..`, a glob) is not one. +_SKILL_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") + + +def _module_skill_ids(root: Path) -> list[str]: + """Every id listed by ``[bmod] skills`` in ``root``'s ``bmod-*/bmod.toml`` + module records, in folder order. An unreadable root or record lists nothing.""" + try: + manifests = sorted(root.glob("bmod-*/bmod.toml")) + except OSError: + return [] + ids: list[str] = [] + for manifest in manifests: + data = _read_toml(manifest) + bmod = data.get("bmod") if data is not None else None + listed = bmod.get("skills") if isinstance(bmod, dict) else None + if isinstance(listed, list): + ids += [ + skill + for skill in listed + if isinstance(skill, str) and _SKILL_ID_RE.fullmatch(skill) and ".." not in skill + ] + return ids + + +def user_root_skill_ids(project: Path, scope: SkillTree, prompt_skill: str = "") -> tuple[str, ...]: + """The BMAD module skill ids a session of ``scope``'s CLI loads from a user root. + + Candidates are :func:`session_skill_candidates` plus every id a user root's + ``bmod-*/bmod.toml`` lists under ``[bmod] skills``; one is kept only where + :func:`skill_locate.locate` returns a user-root copy — so nothing with the + switch off, and never a personal skill no BMAD module record names. Feeds the + opencode allow-list and the run's user-root journal.""" + resolved = as_scope(scope) + ids = list(session_skill_candidates(project, resolved, prompt_skill)) + for root in resolved.user_roots: + if not root.unavailable and root.path is not None: + ids += _module_skill_ids(root.path) + kept: list[str] = [] + for skill in dict.fromkeys(ids): + found = skill_locate.locate(project, resolved, skill) + if found is not None and found.origin == "user": + kept.append(skill) + return tuple(kept) + + +def module_record_version(root: Path, skill: str) -> str | None: + """``[bmod] version`` of the first ``bmod-*/bmod.toml`` in ``root`` whose + ``[bmod] skills`` lists ``skill``, or None (no record names it, or it carries + no version). Display only: the run journals it beside each user-root skill.""" + try: + manifests = sorted(root.glob("bmod-*/bmod.toml")) + except OSError: + return None + for manifest in manifests: + data = _read_toml(manifest) + bmod = data.get("bmod") if data is not None else None + listed = bmod.get("skills") if isinstance(bmod, dict) else None + if isinstance(listed, list) and skill in listed: + return _bmod_version(manifest) + return None + + +def skill_root_findings(project: Path, scopes: Iterable[SkillTree]) -> list[Finding]: + """``skills.root`` ok lines: where each skill the run drives (the dev primitive + and its review skills) resolved, per scope. Validate-only — never part of + :func:`missing_base_skills`, whose caller in the run preflight prints every + non-problem finding as a warning.""" + findings: list[Finding] = [] + for scope in _scope_items(scopes): + found = _primitive_copy(project, scope) + if found is None: + continue + located = [found] + for skill in _review_skill_names(project, scope): + copy = skill_locate.locate(project, scope, skill) + if copy is not None: + located.append(copy) + for copy in located: + where = "user root" if copy.origin == "user" else "project tree" + findings.append( + Finding( + SKILL_ROOT_CHECK, + "ok", + f"{copy.name} resolves from {copy.display} ({where})", + { + "tree": scope.tree, + "skill": copy.name, + "root": copy.root, + "origin": copy.origin, + }, + ) + ) + return findings + + def _relay_executable() -> Path: """This installation's console entry point, independent of PATH: the invoked launcher when it is the ``bmad-loop`` script itself, else the sibling of the @@ -2917,6 +3292,119 @@ def _confined_to(target: Path, root: Path) -> bool: return False +TREE_OUTSIDE_CHECK = "skills.tree-outside" + + +def _resolved_text(path: Path) -> str: + """``path`` resolved for a finding's ``target``; the raw spelling if resolving fails.""" + try: + return str(path.resolve()) + except (OSError, RuntimeError): + return str(path) + + +def skill_trees_outside( + project: Path, repo_root: Path, trees: Iterable[SkillTree], *, isolation: str +) -> list[Finding]: + """``skills.tree-outside``: a skill tree, or a skill the run needs from one, + that a link carries out of where bmad-loop can follow it. + + Two shapes, judged by different roots because two different consumers refuse + them: + + - The **tree itself** resolving outside ``project`` (a junction from + ``.agents/skills`` to a global folder). ``init`` refuses to write through it + (:func:`_confined_to`), so it is a ``warning`` — unless worktree isolation is + on and it also leaves ``repo_root``, where seeding cannot copy a single skill + out of it and the finding is a ``problem``. Its skill-level links are then + not reported again. + - A **required skill directory** — the resolved dev primitive plus the review + skills it will invoke (:func:`required_review_skill_names`: the shape's + ``required`` skills, or for a shape that cannot be read the + merged-or-standalone fallback the worktree gate uses) — resolving outside + ``repo_root``. An advisory (``when``-gated) reviewer is left out, as in + :func:`base_skills_seed_incomplete`: it may never run, so its absence from a + worktree cannot stall the session. Only worktree isolation reads skills through a copy, + and its seeding skips a source outside the repo and then escalates the unit + mid-run, so it is a ``problem`` there and no finding at all otherwise: in + place, the session reads the link directly. + + A link that stays inside the repo (``.claude/skills -> .agents/skills``, the + ``skills`` CLI's own layout) is fine on both counts. A skill that is absent or + unresolved is :func:`missing_base_skills`' to report, not this check's. + ``detail``: ``tree``, ``skill`` (skill-level only), ``target`` (the resolved + path) and ``isolation``. + + For a :class:`SkillScope` the tree-level check covers its primary tree and the + skill-level check the copies its scope locates in a project tree. A skill + resolved from a user root is excluded: it is outside the repo by design, the + session loads it natively, and worktree seeding never copies it.""" + worktree = isolation == "worktree" + findings: list[Finding] = [] + for scope in _scope_items(trees): + tree = scope.tree + tree_dir = project / tree + if not _confined_to(tree_dir, project): + leaves_repo = not _confined_to(tree_dir, repo_root) + target = _resolved_text(tree_dir) + fatal = worktree and leaves_repo + consequence = ( + "; worktree isolation cannot seed skills from outside the repo, so every " + "isolated session would stall — install them per project or set " + '[scm] isolation = "none"' + if fatal + else "" + ) + findings.append( + Finding( + TREE_OUTSIDE_CHECK, + "problem" if fatal else "warning", + f"{tree} resolves outside the project ({target}) — `bmad-loop init` " + f"refuses to install into it; install the skills into the project " + f"(`npx skills add` without -g) rather than linking the tree" + f"{consequence}", + {"tree": tree, "target": target, "isolation": isolation}, + ) + ) + if fatal: + continue + if not worktree: + continue + primitive = resolve_dev_primitive(project, scope) + # only the reviewers the primitive will invoke, as the worktree's + # required-skill gate; an unreadable review shape takes its same + # merged-or-standalone fallback + review_skills = required_review_skill_names(project, scope) + required = (*((primitive,) if primitive is not None else ()), *review_skills) + for skill in dict.fromkeys(required): + found = skill_locate.locate(project, scope, skill) + if found is not None and found.origin == "user": + continue + skill_dir = found.path if found is not None else tree_dir / skill + if not skill_dir.is_dir() or _confined_to(skill_dir, repo_root): + continue + target = _resolved_text(skill_dir) + rel = found.display if found is not None else f"{tree}/{skill}" + findings.append( + Finding( + TREE_OUTSIDE_CHECK, + "problem", + f"{rel} resolves outside the repo ({target}) — worktree " + f"isolation cannot seed a skill from outside the repo, so the isolated " + f"session would stall on it; install it into the project (`npx skills " + f'add` without -g) or set [scm] isolation = "none"', + { + "tree": tree, + "skill": skill, + "target": target, + "isolation": isolation, + **_root_detail(found), + }, + ) + ) + return findings + + # Bound on one ` --version` probe for the hook-event version gate. CLI_VERSION_TIMEOUT_S = 10.0 # Successful probes by resolved binary path and profile env: one launch per diff --git a/src/bmad_loop/platform_util.py b/src/bmad_loop/platform_util.py index 639d35cc4..8d4ec8ba1 100644 --- a/src/bmad_loop/platform_util.py +++ b/src/bmad_loop/platform_util.py @@ -295,6 +295,20 @@ def names_win32_alias(value: str | Path) -> bool: ) +def names_home_ref(value: str | Path) -> bool: + """True if ``value``'s first component starts with ``~`` — ``~``, ``~/x``, + ``~\\x`` or ``~user/x``. + + Nothing that resolves a profile path expands ``~``: ``/~/x`` is a + literal directory named ``~`` inside the project, so a value spelled this way + passes every containment guard while meaning something the author did not + intend. Only the FIRST component counts, split on both separators like the + rest of the family — ``PROGRA~1/x`` (a Win32 short name) and ``a/~b`` are + ordinary names and stay allowed.""" + parts = [part for part in str(value).replace("\\", "/").split("/") if part] + return bool(parts) and parts[0].startswith("~") + + def is_wsl_unc_path(value: str | Path) -> bool: """True if ``value`` addresses a WSL distro's filesystem through the Windows UNC bridge — ``\\\\wsl.localhost\\\\...`` or its legacy ``\\\\wsl$\\\\...`` diff --git a/src/bmad_loop/policy.py b/src/bmad_loop/policy.py index 643081c76..24dd3f443 100644 --- a/src/bmad_loop/policy.py +++ b/src/bmad_loop/policy.py @@ -454,6 +454,14 @@ class MuxPolicy: honor_ambient_psmux_data_dir: bool = False +@dataclass(frozen=True) +class SkillsPolicy: + # Resolve skills from the user-level folders each coding CLI natively loads + # (its profile's `[user_skills]` roots, e.g. ~/.agents/skills) as well as the + # project's skill trees. Off = project trees only. See bmad_loop.skill_locate. + user_roots: bool = False + + @dataclass(frozen=True) class SweepPolicy: auto: str = "never" # never | per-epic | run-end @@ -801,6 +809,7 @@ class Policy: tui: TuiPolicy = field(default_factory=TuiPolicy) operator: OperatorPolicy = field(default_factory=OperatorPolicy) mux: MuxPolicy = field(default_factory=MuxPolicy) + skills: SkillsPolicy = field(default_factory=SkillsPolicy) def to_dict(self) -> dict[str, Any]: return asdict(self) @@ -1032,6 +1041,7 @@ def loads(text: str, plugin_schemas: dict[str, Any] | None = None) -> Policy: tui_d = _section(doc, "tui") operator_d = _section(doc, "operator") mux_d = _section(doc, "mux") + skills_d = _section(doc, "skills") gates = GatesPolicy( mode=_typed_str(gates_d, "gates", "mode", GatesPolicy.mode), @@ -1568,6 +1578,9 @@ def loads(text: str, plugin_schemas: dict[str, Any] | None = None) -> Policy: tui=tui, operator=operator, mux=mux, + skills=SkillsPolicy( + user_roots=_typed_bool(skills_d, "skills", "user_roots", SkillsPolicy.user_roots), + ), ) @@ -1862,6 +1875,12 @@ def _refuse_removed_engine(engine_d: dict[str, Any]) -> None: # Takes effect on the next bmad-loop invocation; a running TUI refuses launches # until restarted. # honor_ambient_psmux_data_dir = false + +[skills] +# Also resolve skills from the user-level folders each coding CLI loads on its +# own (for example ~/.agents/skills after `npx skills add -g`), as declared in +# its profile's [user_skills] table. Off = only the project's skill trees. +# user_roots = false """ diff --git a/src/bmad_loop/resolve.py b/src/bmad_loop/resolve.py index 58771fb66..cc4ca23f6 100644 --- a/src/bmad_loop/resolve.py +++ b/src/bmad_loop/resolve.py @@ -757,10 +757,12 @@ def run_epic_close_session( *, model: str = "", effort: str = "", + skill_dir: str | None = None, ) -> int: """Launch the interactive epic-close agent for epic ``slug`` attached to the caller's terminal, with ``prompt`` (:func:`epic_close_prompt`) as its first - prompt. + prompt. ``skill_dir`` is the located skill's ``{skill_dir}`` spelling + (:func:`skill_locate.prompt_skill_dir`), None for the primary tree. Blocks until the session exits. The session ends on process exit, as the resolve agent's does, never on prose. The returncode is returned for the @@ -783,6 +785,7 @@ def run_epic_close_session( }, model=model, effort=effort, + skill_dir=skill_dir, ) argv = adapter.interactive_argv(spec) env = {**os.environ, **adapter.interactive_env(spec)} diff --git a/src/bmad_loop/runsetup.py b/src/bmad_loop/runsetup.py index 6bd4799d8..687510a9b 100644 --- a/src/bmad_loop/runsetup.py +++ b/src/bmad_loop/runsetup.py @@ -342,6 +342,15 @@ def config_digest( Skill-content integrity is a real question and not one a config hash can answer. + + The same holds for the rest of the skill-location surface: + ``extra_skill_trees`` (more project trees planted beside ``skill_tree`` in + ``OPENCODE_CONFIG_CONTENT``), ``user_skills`` (which home folders a skill + may resolve from) and the ``[skills] user_roots`` switch (whether they + are read at all, which also widens opencode 2.x's skill allow-list to + the BMAD ids located there). Each moves only a pointer to instructions, + never a program, flag or variable, and a user root is writable without + any config change at all. * ``usage_parser`` — and with it the rest of the token-budget surface. It selects a read-only tally over a transcript the orchestrator opens anyway and decides no program, flag, or variable. Rewriting it to ``"none"`` DOES diff --git a/src/bmad_loop/skill_locate.py b/src/bmad_loop/skill_locate.py new file mode 100644 index 000000000..5e53ee6c9 --- /dev/null +++ b/src/bmad_loop/skill_locate.py @@ -0,0 +1,377 @@ +"""The one place that answers "where is skill X for this CLI?". + +Every skill question — validate, the run preflight, dispatch, worktree seeding, +the render probe and the review-lens reads — resolves a skill through +:func:`locate` over a :class:`SkillScope`, so the copy a check reads is the copy +the session will load. + +Doctrine: + +- **Off means project-only.** With ``[skills] user_roots = false`` (the + default) a scope resolves only from the project trees (the profile's + ``skill_tree`` then its ``extra_skill_trees``), exactly as before user roots + existed. :func:`shadow` and :func:`home_copy` still look at user roots with + the switch off, but only to warn and hint, never to resolve. +- **Roots are what each CLI natively loads.** A profile declares, in + ``[user_skills]``, the home-relative folders its CLI reads on its own and in + which order, plus the vendor variables that turn a folder off + (``disabled_by``). Nothing here invents a root a CLI would not read. +- **Validate must not pass what the session cannot load.** A root whose + disabler is set, whose home is unknown, or which cannot be read is carried as + *unavailable* and never resolves; precedence picks the copy the CLI itself + would pick (``user``: personal beats project; ``project`` and ``unordered``: + the project copy is checked, and ``unordered`` clashes are reported by + :func:`shadow`). + +Pure stdlib with no ``bmad_loop`` imports: the profile-side data types live +here so ``adapters/profile.py`` imports from this module, never the reverse. +The two seams :func:`user_home` and :func:`ambient_environ` are pinned by the +test suite's conftest so no test reads the real home directory. +""" + +from __future__ import annotations + +import os +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import Literal, Protocol + +PRECEDENCES: frozenset[str] = frozenset({"project", "user", "unordered"}) + +Origin = Literal["project", "user"] + + +@dataclass(frozen=True) +class UserSkillRoot: + """One declared user root: a ``~/``-prefixed folder and the environment + variables whose presence stops the CLI reading it.""" + + path: str + disabled_by: tuple[str, ...] = () + + +@dataclass(frozen=True) +class UserSkillsSpec: + """A profile's ``[user_skills]`` table: which copy wins on a name clash + (one of :data:`PRECEDENCES`) and the roots in the order the CLI reads them.""" + + precedence: str = "project" + roots: tuple[UserSkillRoot, ...] = () + + +@dataclass(frozen=True) +class UserRoot: + """A declared root resolved against a home directory and an environment. + + ``unavailable`` is ``""`` when the root can be read, else why not: + ``"env:"`` (a disabler is set), ``"no-home"`` or ``"unreadable"``. + ``path`` is ``None`` only for ``"no-home"``.""" + + spelling: str + path: Path | None + unavailable: str = "" + + +@dataclass(frozen=True) +class SkillScope: + """Everything needed to resolve a skill for one CLI. Frozen and hashable, + so it serves as a dedupe or cache key.""" + + tree: str + extra_trees: tuple[str, ...] = () + user_roots: tuple[UserRoot, ...] = () + precedence: str = "project" + resolve_user: bool = False + + def project_trees(self) -> tuple[str, ...]: + return (self.tree, *self.extra_trees) + + +@dataclass(frozen=True) +class Located: + """One present copy of a skill: ``path`` is its folder (holding + ``SKILL.md``), ``root`` the display spelling of the tree or user root it + sits in, and ``primary`` whether that is the profile's ``skill_tree``.""" + + name: str + path: Path + origin: Origin + root: str + primary: bool + + @property + def display(self) -> str: + return f"{self.root}/{self.name}" + + +@dataclass(frozen=True) +class Shadow: + """A name clash between the project copy and a user copy. ``checked`` is + the copy a project-only check reads; ``other`` the copy that may run + instead (``overrides``) or alongside it in no stated order (``competes``).""" + + name: str + checked: Located + other: Located + kind: Literal["overrides", "competes"] + + +class SkillProfile(Protocol): + """The profile fields a scope is built from (``CLIProfile`` satisfies it).""" + + @property + def skill_tree(self) -> str: ... + + @property + def extra_skill_trees(self) -> tuple[str, ...]: ... + + @property + def user_skills(self) -> UserSkillsSpec | None: ... + + @property + def env(self) -> Mapping[str, str]: ... + + +class _Default(Enum): + SEAM = "seam" + + +_SEAM = _Default.SEAM + + +def user_home() -> Path | None: + """The user's home directory, or ``None`` when it cannot be determined.""" + try: + return Path.home() + except RuntimeError: + return None + + +def ambient_environ() -> Mapping[str, str]: + """bmad-loop's own environment, read for root disablers.""" + return os.environ + + +def as_scope(tree: str | SkillScope) -> SkillScope: + """A plain tree string is a project-only scope over that one tree.""" + return tree if isinstance(tree, SkillScope) else SkillScope(tree) + + +def _user_root(root: UserSkillRoot, home: Path | None, environ: Mapping[str, str]) -> UserRoot: + if home is None: + return UserRoot(root.path, None, "no-home") + rest = root.path[2:] + path = home.joinpath(*[part for part in rest.split("/") if part]) + for var in root.disabled_by: + if var in environ: + return UserRoot(root.path, path, f"env:{var}") + try: + path.is_dir() + except OSError: + return UserRoot(root.path, path, "unreadable") + return UserRoot(root.path, path) + + +def build_scope( + tree: str, + *, + extra_trees: Iterable[str] = (), + user_skills: UserSkillsSpec | None = None, + resolve_user: bool = False, + home: Path | None | Literal[_Default.SEAM] = _SEAM, + environ: Mapping[str, str] | None = None, +) -> SkillScope: + """A scope over ``tree`` + ``extra_trees`` and the declared user roots. + + ``home`` defaults to :func:`user_home` and ``environ`` to + :func:`ambient_environ`, both read at call time. A disabler counts as set + when the variable is present at all, even empty: an unavailable root is the + conservative answer, since validate must not pass a copy the CLI skips.""" + if home is _SEAM: + home = user_home() + env = ambient_environ() if environ is None else environ + spec = user_skills or UserSkillsSpec() + return SkillScope( + tree=tree, + extra_trees=tuple(extra_trees), + user_roots=tuple(_user_root(r, home, env) for r in spec.roots), + precedence=spec.precedence, + resolve_user=resolve_user, + ) + + +def scope_for( + profile: SkillProfile, + *, + resolve_user: bool, + home: Path | None | Literal[_Default.SEAM] = _SEAM, + environ: Mapping[str, str] | None = None, + session_env: Mapping[str, str] | None = None, +) -> SkillScope: + """The scope ``profile``'s sessions load skills from. + + The disabler environment is ``environ`` (default :func:`ambient_environ`) + overlaid with the profile's own ``env``, which every session is launched + with, then ``session_env`` — one session's own env after its plugin hooks, + in the adapters' launch order. Without it the scope is the one every + session of the profile shares, which a ``pre_session`` hook setting a + disabler (an account-rotation ``CLAUDE_CONFIG_DIR``) can still narrow.""" + base = ambient_environ() if environ is None else environ + return build_scope( + profile.skill_tree, + extra_trees=profile.extra_skill_trees, + user_skills=profile.user_skills, + resolve_user=resolve_user, + home=home, + environ={**base, **profile.env, **(session_env or {})}, + ) + + +def _present(folder: Path) -> bool: + try: + return (folder / "SKILL.md").is_file() + except OSError: + return False + + +def _project_copies(project: Path, scope: SkillScope, name: str) -> list[Located]: + found: list[Located] = [] + for i, tree in enumerate(scope.project_trees()): + folder = project / tree / name + if _present(folder): + found.append(Located(name, folder, "project", tree, i == 0)) + return found + + +def _user_copies(scope: SkillScope, name: str) -> list[Located]: + found: list[Located] = [] + for root in scope.user_roots: + if root.unavailable or root.path is None: + continue + folder = root.path / name + if _present(folder): + found.append(Located(name, folder, "user", root.spelling, False)) + return found + + +def copies(project: Path, scope: SkillScope, name: str) -> list[Located]: + """Every present copy of ``name``: the primary tree, the extra trees, then + the available user roots in declared order. A copy whose folder cannot be + read is absent.""" + return [*_project_copies(project, scope, name), *_user_copies(scope, name)] + + +def locate(project: Path, scope: SkillScope, name: str) -> Located | None: + """The copy of ``name`` the CLI loads, or ``None``. + + Switch off: the first project copy. Switch on: under ``user`` precedence a + user copy beats the project copy; under ``project`` and ``unordered`` the + project copy is preferred and a user copy fills in only when it is absent.""" + project_found = _project_copies(project, scope, name) + if not scope.resolve_user: + return project_found[0] if project_found else None + user_found = _user_copies(scope, name) + first, second = ( + (user_found, project_found) if scope.precedence == "user" else (project_found, user_found) + ) + if first: + return first[0] + return second[0] if second else None + + +def shadow(project: Path, scope: SkillScope, name: str) -> Shadow | None: + """A clash between the project copy and a user copy, whatever the switch. + + ``user`` precedence with the switch off: the CLI runs the user copy over + the project copy the checks read (``overrides``). ``unordered``: both load + in no stated order (``competes``). Otherwise ``None``.""" + project_found = _project_copies(project, scope, name) + if not project_found: + return None + user_found = _user_copies(scope, name) + if not user_found: + return None + if scope.precedence == "user" and not scope.resolve_user: + return Shadow(name, project_found[0], user_found[0], "overrides") + if scope.precedence == "unordered": + return Shadow(name, project_found[0], user_found[0], "competes") + return None + + +def home_copy(scope: SkillScope, name: str) -> Located | None: + """The first available user-root copy of ``name``, whatever the switch.""" + found = _user_copies(scope, name) + return found[0] if found else None + + +SAME_COPY_MAX_FILES = 512 + + +def _skill_files(folder: Path) -> dict[str, Path] | None: + """Every file under ``folder`` keyed by its ``/``-joined relative path, or + ``None`` when the walk fails or passes :data:`SAME_COPY_MAX_FILES`. + + Linked folders are walked like real ones, so their files count too. A + folder reached twice (a link cycle, or two links to one folder) also + yields ``None``, which keeps the walk finite.""" + files: dict[str, Path] = {} + errors: list[OSError] = [] + seen: set[str] = set() + for dirpath, dirnames, filenames in os.walk(folder, onerror=errors.append, followlinks=True): + real = os.path.realpath(dirpath) + if real in seen: + return None + seen.add(real) + dirnames.sort() + base = Path(dirpath) + for name in filenames: + path = base / name + files[path.relative_to(folder).as_posix()] = path + if len(files) > SAME_COPY_MAX_FILES: + return None + return None if errors else files + + +def same_copy(a: Located, b: Located) -> bool: + """Whether two copies of a skill are the same skill: one folder, or two + folders holding byte-identical files at the same relative paths, linked + folders included. A folder that cannot be walked or read, that reaches one + folder twice through links, or that holds more than + :data:`SAME_COPY_MAX_FILES` files, is never the same as another one.""" + try: + if a.path.resolve() == b.path.resolve(): + return True + left, right = _skill_files(a.path), _skill_files(b.path) + if left is None or right is None or left.keys() != right.keys(): + return False + return all(left[rel].read_bytes() == right[rel].read_bytes() for rel in left) + except OSError: + return False + + +def prompt_skill(prompt: str) -> tuple[str, str]: + """Split a canonical ``"/skill args"`` prompt into ``(skill, args)``; + a prompt without a leading slash is ``("", prompt)``.""" + if not prompt.startswith("/"): + return "", prompt + head, _, rest = prompt[1:].partition(" ") + return head, rest.strip() + + +def prompt_skill_dir(project: Path, scope: SkillScope, prompt: str) -> str | None: + """The ``{skill_dir}`` spelling for ``prompt``'s skill. + + ``None`` for no skill, a miss or a primary-tree hit, so the renderer keeps + its relative default; ``"/"`` for an extra-tree hit; the + absolute native folder for a user-root hit.""" + skill, _ = prompt_skill(prompt) + if not skill: + return None + found = locate(project, scope, skill) + if found is None or found.primary: + return None + if found.origin == "project": + return found.display + return str(found.path) diff --git a/src/bmad_loop/tickets_engine.py b/src/bmad_loop/tickets_engine.py index 0230c7dba..f98149262 100644 --- a/src/bmad_loop/tickets_engine.py +++ b/src/bmad_loop/tickets_engine.py @@ -104,7 +104,7 @@ from pathlib import Path from typing import Any, NoReturn, Protocol -from . import deferredwork, gates, ticketlayout, ticketstore, verify +from . import deferredwork, gates, skill_locate, ticketlayout, ticketstore, verify from .adapters.base import SessionResult, SpecSnapshot from .checkpoints import CheckpointFlags, CheckpointFlowMixin from .engine import ( @@ -866,9 +866,13 @@ def _ticket_epic_retro(self, slug: str) -> str: if not clean: self._skip_auto_retro(0, "dirty", epic_ref=slug) self._pause_retro_refused(slug, "the tree has uncommitted changes") - adapter = self.adapters["retro"] - tree = getattr(getattr(adapter, "profile", None), "skill_tree", None) - if tree and not (self.workspace.paths.project / tree / RETRO_SKILL / "SKILL.md").is_file(): + # The copy the retro CLI loads (#770): a user-root install counts under + # `[skills] user_roots`; an adapter with no profile is not probed. + scope = self._skill_scope("retro") + if ( + scope is not None + and skill_locate.locate(self.workspace.paths.project, scope, RETRO_SKILL) is None + ): self._skip_auto_retro(0, "skill-missing", epic_ref=slug) return RETRO_VERDICT_UNKNOWN diff --git a/src/bmad_loop/worktree_flow.py b/src/bmad_loop/worktree_flow.py index 4699861d8..48b7727dc 100644 --- a/src/bmad_loop/worktree_flow.py +++ b/src/bmad_loop/worktree_flow.py @@ -37,6 +37,7 @@ codex_trust, deferredwork, gates, + skill_locate, sprintstatus, ticketstore, verify, @@ -61,6 +62,7 @@ RENDERER_SCRIPT_MARKER, RENDERER_SCRIPT_UNIT_REL, RENDERER_SEED_SENTINELS, + SkillTree, _absent_renderer_sources, _copy_traversable, _hook_command, @@ -341,13 +343,13 @@ def outside(text: str, entries: list[deferredwork.DWEntry]) -> Counter[str]: return unexplained, count -def _worktree_skill_copy_candidates(repo_root: Path, tree: str) -> tuple[str, ...]: - """Every upstream skill worth best-effort copying into ``tree``.""" +def _worktree_skill_copy_candidates(repo_root: Path, tree: SkillTree) -> tuple[str, ...]: + """Every upstream skill worth best-effort copying into ``tree``'s project trees.""" resolved = resolve_review_layers(repo_root, tree) return tuple(dict.fromkeys((*BASE_SKILLS, *(resolved.skills() if resolved else ())))) -def _required_worktree_skills(repo_root: Path, tree: str) -> tuple[str, ...]: +def _required_worktree_skills(repo_root: Path, tree: SkillTree) -> tuple[str, ...]: """Upstream skills whose absence deterministically stalls this tree's run. Match :func:`install.missing_base_skills`: gate the selected dev primitive and @@ -359,7 +361,7 @@ def _required_worktree_skills(repo_root: Path, tree: str) -> tuple[str, ...]: resolved = resolve_review_layers(repo_root, tree) if resolved is not None: review_skills = tuple(resolved.required) - elif (repo_root / tree / MERGED_REVIEW_SKILL / "SKILL.md").is_file(): + elif skill_locate.locate(repo_root, skill_locate.as_scope(tree), MERGED_REVIEW_SKILL): review_skills = (MERGED_REVIEW_SKILL,) else: review_skills = tuple(sorted(_REVIEW_LAYER_SKILLS)) @@ -929,7 +931,7 @@ def _central_config_seed_incomplete( def base_skills_seed_incomplete( worktree: Path, repo_root: Path, - trees: Sequence[str], + trees: Sequence[SkillTree], *, project: Path | None = None, ) -> list[str]: @@ -952,39 +954,76 @@ def base_skills_seed_incomplete( CRITICAL escalation here. Stories mode adds its content-keyed dispatch probe at the caller, where the run mode is available. - The skill trees are project-local: probed under :func:`provision_roots`. + The skill trees are project-local: probed under :func:`provision_roots`. A + :class:`~bmad_loop.skill_locate.SkillScope` widens that to every project tree + (the copy :func:`~bmad_loop.skill_locate.locate` picks is the one checked) and, + with ``[skills] user_roots`` on, exempts a required skill located in a user + root: the session loads it from the operator's home, which no worktree + carries and seeding never copies (:func:`base_skills_user_rooted` names them + for the journal). """ src_root, dst_root = provision_roots(worktree, repo_root, project) missing: list[str] = [] for tree in dict.fromkeys(trees): + scope = skill_locate.as_scope(tree) primitive = dev_primitive_or_default(src_root, tree) for skill in _required_worktree_skills(src_root, tree): - repo_skill = src_root / tree / skill - worktree_skill = dst_root / tree / skill - if not _is_file(repo_skill / "SKILL.md"): + located = skill_locate.locate(src_root, scope, skill) + if located is not None and located.origin == "user": + continue + if located is None: # Distinguish an unreadable directory from a skill the repo simply # does not carry. The walk yields only the former as a directory leaf. - if any(_is_dir(src) for _, src in _walk_traversable_files(repo_skill)): - missing.append(f"{tree}/{skill}") + for project_tree in scope.project_trees(): + repo_skill = src_root / project_tree / skill + if any(_is_dir(src) for _, src in _walk_traversable_files(repo_skill)): + missing.append(f"{project_tree}/{skill}") + break continue + located_tree = located.root + repo_skill = src_root / located_tree / skill + worktree_skill = dst_root / located_tree / skill if not _is_file(worktree_skill / "SKILL.md"): - missing.append(f"{tree}/{skill}") + missing.append(f"{located_tree}/{skill}") continue if skill != primitive: continue missing.extend( - f"{tree}/{skill}/{rel}" + f"{located_tree}/{skill}/{rel}" for rel in DEV_PRIMITIVE_MARKERS if _is_file(repo_skill / rel) and not _is_file(worktree_skill / rel) ) missing.extend( - f"{tree}/{skill}/{rel}" + f"{located_tree}/{skill}/{rel}" for rel in _absent_renderer_sources(worktree_skill) if _is_file(repo_skill.joinpath(*rel.split("/"))) ) return missing +def base_skills_user_rooted( + repo_root: Path, + trees: Sequence[SkillTree], + *, + project: Path | None = None, +) -> list[str]: + """Required upstream skills :func:`base_skills_seed_incomplete` exempts + because :func:`~bmad_loop.skill_locate.locate` puts them in a user root + (``[skills] user_roots`` on), as display spellings (``~/.agents/skills/x``). + Plain tree strings never resolve to a user root, so they yield nothing.""" + src_root = repo_root if project is None else project # provision_roots' src_root + found: dict[str, None] = {} + for tree in dict.fromkeys(trees): + scope = skill_locate.as_scope(tree) + if not scope.resolve_user: + continue + for skill in _required_worktree_skills(src_root, tree): + located = skill_locate.locate(src_root, scope, skill) + if located is not None and located.origin == "user": + found[located.display] = None + return list(found) + + def worktree_seed_undelivered( worktree: Path, repo_root: Path, @@ -1200,6 +1239,7 @@ def provision_worktree( on_pinned: Callable[[str, str, str], None] | None = None, project: Path | None = None, on_hook_gated: Callable[[str], None] | None = None, + user_roots: bool = False, ) -> list[str]: """Make a freshly-created git worktree a self-sufficient bmad-loop project. @@ -1466,8 +1506,10 @@ def shield(rel: str) -> str: if _central_config_seed_incomplete(worktree, repo_root, project=project): skipped.append(CENTRAL_CONFIG_REL) - # bundled skills into each CLI's skill tree (deduped: codex+gemini share one); - # never clobber a skill the checkout already carries (tracked or pre-existing). + # bundled skills into each CLI's PRIMARY skill tree (deduped: codex+gemini share + # one); never clobber a skill the checkout already carries (tracked or + # pre-existing). An extra tree gets none: `module_skills_seed_undelivered` + # probes the primary trees only, and bmad-loop's own skills live there. for tree in dict.fromkeys(p.skill_tree for p in profiles): tree_dir = dst_root / tree for skill in MODULE_SKILLS: @@ -1495,52 +1537,60 @@ def shield(rel: str) -> str: # dev/review skill does. A future # worktree-resident consumer arms the gate via escalate_unit over that # predicate's result. - # The orchestrator-driven upstream skills are not in the wheel; copy them - # from the MAIN REPO's installed tree (same tree path) so an isolated - # worktree can still resolve the dev primitive and the review layers. Skip - # silently when the main repo lacks them — the run-start preflight reports - # it. - # - # BASE_SKILLS names BOTH primitive eras, which is what carries the skill - # across the rename: the resolution below returns REVIEW skills only, so a - # primitive the catalog did not name would be silently left behind (the - # is_dir guard swallows the miss) and every isolated session would stall on - # an Unknown command. - # - # BASE_SKILLS is only the floor. The review layers this project actually - # invokes are read from the installed primitive — resolved on disk, so a - # renamed project resolves its own layers rather than degrading to the - # static catalog — exactly as the preflight reads them, so a reviewer named - # by a project override (a custom or renamed skill) is provisioned too. - # Validating a skill here and then not copying it is how preflight passes in - # the main checkout while the isolated review fails on a skill that was - # never there. - for skill in _worktree_skill_copy_candidates(src_root, tree): - dst = tree_dir / skill - try: - src = (src_root / tree / skill).resolve() - except (OSError, RuntimeError, ValueError): - continue - if not src.is_relative_to(repo_root) or not _is_dir(src): - continue - landed = [] - _copy_traversable( - src, - dst, - skip_existing=True, - worktree=worktree, - repo_root=repo_root, - copied_paths=landed, - ) - written.update(_written_rels(worktree, landed)) + + # The orchestrator-driven upstream skills are not in the wheel; copy them + # from the MAIN REPO's installed trees (same tree paths) so an isolated + # worktree can still resolve the dev primitive and the review layers. Skip + # silently when the main repo lacks them — the run-start preflight reports + # it. + # + # BASE_SKILLS names BOTH primitive eras, which is what carries the skill + # across the rename: the resolution below returns REVIEW skills only, so a + # primitive the catalog did not name would be silently left behind (the + # is_dir guard swallows the miss) and every isolated session would stall on + # an Unknown command. + # + # BASE_SKILLS is only the floor. The review layers this project actually + # invokes are read from the installed primitive — resolved on disk, so a + # renamed project resolves its own layers rather than degrading to the + # static catalog — exactly as the preflight reads them, so a reviewer named + # by a project override (a custom or renamed skill) is provisioned too. + # Validating a skill here and then not copying it is how preflight passes in + # the main checkout while the isolated review fails on a skill that was + # never there. + # + # Every PROJECT tree of each profile (`skill_tree`, then `extra_skill_trees`) + # is seeded the same way, each from its own main-repo counterpart. A user + # root (`[skills] user_roots`) is never a source: the session reads that copy + # from the operator's home in place, and the gate below exempts it. + scopes = list( + dict.fromkeys(skill_locate.scope_for(p, resolve_user=user_roots) for p in profiles) + ) + for scope in scopes: + candidates = _worktree_skill_copy_candidates(src_root, scope) + for tree in scope.project_trees(): + for skill in candidates: + dst = dst_root / tree / skill + try: + src = (src_root / tree / skill).resolve() + except (OSError, RuntimeError, ValueError): + continue + if not src.is_relative_to(repo_root) or not _is_dir(src): + continue + landed = [] + _copy_traversable( + src, + dst, + skip_existing=True, + worktree=worktree, + repo_root=repo_root, + copied_paths=landed, + ) + written.update(_written_rels(worktree, landed)) # Re-ask the result rather than trusting copy bookkeeping. A user-authored seed # can happen to spell a skill rel, so only this disk predicate may arm the gate. - skipped.extend( - base_skills_seed_incomplete( - worktree, repo_root, [profile.skill_tree for profile in profiles], project=project - ) - ) + skipped.extend(base_skills_seed_incomplete(worktree, repo_root, scopes, project=project)) # per-CLI signal-hook registration, baked to the main repo's relay (absolute). # Hookless profiles (HTTP/SSE transport) have no config to merge. @@ -1726,7 +1776,9 @@ def shield(rel: str) -> str: # Every rel below is spelled worktree-relative through `shield`: git reads the # exclude from the worktree root, and a nested project's surfaces sit under its # offset there (DW-379). `written` and `seeded_bmad` already are. - patterns = {f"/{shield(p.skill_tree)}" for p in profiles} + patterns = { + f"/{shield(tree)}" for p in profiles for tree in (p.skill_tree, *p.extra_skill_trees) + } # hookless profiles have no config_path, so there is nothing to shield: their # empty string would render as a bare "/", which git strips to a zero-length # pattern (the trailing slash becomes MUSTBEDIR) that matches nothing — inert, @@ -1923,10 +1975,10 @@ def worktree_profiles(self) -> list[CLIProfile]: fakes) contribute nothing, so provisioning is a no-op for them. The role set is :data:`install.DEV_PRIMITIVE_ROLES` — the same constant - `cli._skill_trees` starts from — rather than a local pair, so the gated set + `cli._skill_scopes` starts from — rather than a local pair, so the gated set stays a subset of the provisioned one: a tree gated but not provisioned ships a session into the `Unknown command` stall the preflight exists to - catch. The converse is deliberate: `cli._skill_trees` drops the review tree + catch. The converse is deliberate: `cli._skill_scopes` drops the review tree when ``[review]`` is off and no plugin binds a review workflow (DW-380), but provisioning keeps both profiles always — they drive per-CLI Stop-signal hook registration too, and a worktree without one stalls any session of @@ -2677,6 +2729,7 @@ def _record_pin(rel: str, dialect: str, text: str) -> None: on_hook_gated=lambda note: self.journal.append( "worktree-hook-gated", story_key=task.story_key, reason=note ), + user_roots=self.policy.skills.user_roots, ) except verify.GitError as e: # Every provisioning refusal carries its own cause — an unresolvable @@ -2795,6 +2848,12 @@ def _record_pin(rel: str, dialect: str, text: str) -> None: ) trees = [p.skill_tree for p in profiles] + # Every project tree plus, under `[skills] user_roots`, the user roots each + # CLI loads: the gates below check the copy each session will really run. + user_roots = self.policy.skills.user_roots + scopes = list( + dict.fromkeys(skill_locate.scope_for(p, resolve_user=user_roots) for p in profiles) + ) # The wheel's own bundled skills, journal-only like worktree-seed-dropped but # under their own kind so a user seed that spells a skill rel can neither forge # nor mask an entry. No MODULE_SKILLS entry has a worktree-resident consumer, @@ -2813,8 +2872,17 @@ def _record_pin(rel: str, dialect: str, text: str) -> None: # renderer-era primitives. Re-probe disk rather than trusting skipped_seeds, # which a user-authored seed rel could otherwise forge. Check this first so a # wholly absent primitive is not misdiagnosed as a renderer-surface problem. + # A required skill located in a user root is exempt (no worktree carries + # the operator's home, and seeding never copies from it); say which. + user_rooted = base_skills_user_rooted( + self.paths.repo_root, scopes, project=self.paths.project + ) + if user_rooted: + self.journal.append( + "worktree-skills-user-root", story_key=task.story_key, entries=user_rooted + ) absent_skills = base_skills_seed_incomplete( - unit.path, self.paths.repo_root, trees, project=self.paths.project + unit.path, self.paths.repo_root, scopes, project=self.paths.project ) if absent_skills: reason = ( @@ -2834,7 +2902,7 @@ def _record_pin(rel: str, dialect: str, text: str) -> None: # while a tracked stale worktree copy proves that existence alone is not # enough. Either shape would HALT a folder+id dispatch before writing a spec. stories_support = ( - missing_stories_support(self._mount_roots(unit.path)[1], trees) + missing_stories_support(self._mount_roots(unit.path)[1], scopes) if worksource.resumed_traits_for(self.state.source).stories_primitive else [] ) @@ -2858,7 +2926,7 @@ def _record_pin(rel: str, dialect: str, text: str) -> None: # renderer stub consumes the surface. The conjunct is load-bearing: inline # pre-#2601 SKILL.md projects may carry the same repo paths and must proceed. short_surface = [rel for rel in RENDERER_SEED_SENTINELS if rel in skipped_seeds] - if short_surface and renderer_stub_resolved(self.paths.project, trees): + if short_surface and renderer_stub_resolved(self.paths.project, scopes): reason = ( f"the dev primitive renders via {RENDERER_SCRIPT_MARKER} but the " "worktree's renderer surface came up short of the repo's " diff --git a/tests/conftest.py b/tests/conftest.py index 5e2c8da46..902d7089d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -33,6 +33,7 @@ install, platform_util, runs, + skill_locate, ticketlayout, ticketmodel, win32_at, @@ -1100,16 +1101,18 @@ def _stub_cli_version(monkeypatch): @pytest.fixture(autouse=True) -def _isolate_outside_skill_home(monkeypatch, tmp_path_factory): - """Pin the home directory the out-of-project skill hint probes (#768). - - `install.missing_base_skills` notes a global `~/.claude/skills` or - `~/.agents/skills` copy of a missing skill in the finding's message and detail. - Unpinned, every test asserting on such a finding would depend on what the host - has installed globally — a developer with `npx skills add -g` would see failures - CI never does. Tests of the hint pass `home=` explicitly instead.""" - empty = tmp_path_factory.getbasetemp() / "no-outside-home" - monkeypatch.setattr(install, "_outside_home", lambda: empty) +def _isolate_user_skill_roots(monkeypatch, tmp_path_factory): + """Pin the home directory and environment the skill locator reads. + + `skill_locate.scope_for` resolves each profile's `[user_skills]` roots + against the user's home and checks their disabler variables (CLAUDE_CONFIG_DIR, + CODEX_HOME, ...) in bmad-loop's environment. Unpinned, a developer with + `npx skills add -g` or an exported CODEX_HOME would see results CI never does. + The home is an empty base-temp dir (never created per test). Tests of real + behaviour pass `home=` / `environ=` or monkeypatch these seams.""" + empty = tmp_path_factory.getbasetemp() / "no-user-skill-home" + monkeypatch.setattr(skill_locate, "user_home", lambda: empty) + monkeypatch.setattr(skill_locate, "ambient_environ", lambda: {}) @pytest.fixture(autouse=True) diff --git a/tests/test_cli.py b/tests/test_cli.py index d60409160..d0b83c074 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -83,6 +83,11 @@ STORIES_SPEC_FOLDER = "_bmad-output/epic-1" +def _gated_trees(project, pol, root, grants, **kwargs): + """The primary tree names of the scopes the preflight gates on.""" + return [scope.tree for scope in cli._skill_scopes(project, pol, root, grants, **kwargs)] + + def _stories_entry(story_id, **over): d = {"id": story_id, "title": f"Story {story_id}", "description": "does a thing"} d.update(over) @@ -470,7 +475,7 @@ def test_dry_run_banner_stays_silent_for_a_warning_only_finding(project, capsys) 'id = "adversarial"\n' 'instruction = "Invoke the `bmad-review` skill with only the `adversarial` lens."\n' ) - for tree in cli._skill_trees(project.project, pol, project.project, GrantSet.empty()): + for tree in _gated_trees(project.project, pol, project.project, GrantSet.empty()): primitive = project.project / tree / install.DEV_PRIMITIVE_NEW (primitive / "customize.toml").write_text(layer, encoding="utf-8") @@ -480,7 +485,7 @@ def test_dry_run_banner_stays_silent_for_a_warning_only_finding(project, capsys) (custom / f"{install.DEV_PRIMITIVE_NEW}.toml").write_text("not = [toml\n", encoding="utf-8") findings = install.missing_base_skills( - project.project, cli._skill_trees(project.project, pol, project.project, GrantSet.empty()) + project.project, _gated_trees(project.project, pol, project.project, GrantSet.empty()) ) severities = {f.severity for f in findings} assert severities == {"warning"}, f"fixture no longer produces a warning-only set: {findings}" @@ -16448,6 +16453,75 @@ def test_require_base_skills_unresolved_primitive_still_refuses(tmp_path, capsys assert "dispatch" not in err +def test_validate_and_preflight_refuse_a_skill_linked_out_of_the_repo_under_worktree( + project, capsys, monkeypatch, tmp_path +): + """The dev primitive linked to a shared install outside the repo: in place it + loads through the link, but worktree seeding skips it and used to escalate the + unit mid-run. validate and the run-start preflight now refuse it alike, and + the dry-run banner says the real command would abort. + + Ablation: drop the validate call to `install.skill_trees_outside` and validate + exits 0 (this is its only problem); drop the preflight call and + `_require_base_skills` returns True; drop the banner's call and the preview + prints no `NOT runnable` line.""" + from bmad_loop.install import DEV_PRIMITIVE_LEGACY + + tree = ".claude/skills" + shared = tmp_path / "shared" / DEV_PRIMITIVE_LEGACY + + def skills(root): + # Lay the primitive down, then move it out of the project before the + # fixture commits: nothing tracked sits where the link will go. + install_dev_base_skills(root, tree, folder_id=True) + shared.parent.mkdir(parents=True) + shutil.move(str(root / tree / DEV_PRIMITIVE_LEGACY), str(shared)) + + _make_validate_pass( + project, + monkeypatch, + capsys, + policy=CLAUDE_ONLY_POLICY + '\n[scm]\nisolation = "worktree"\n', + skills=skills, + ) + link = project.project / tree / DEV_PRIMITIVE_LEGACY + if sys.platform == "win32": + import _winapi # Windows-only stdlib module; never os.symlink there + + _winapi.CreateJunction(str(shared), str(link)) + else: + link.symlink_to(shared, target_is_directory=True) + with (project.project / ".git" / "info" / "exclude").open("a", encoding="utf-8") as fh: + fh.write(f"/{tree}/{DEV_PRIMITIVE_LEGACY}\n") + + doc = machine_json(["validate", "--project", str(project.project), "--json"], capsys, rc=1) + + outside = [f for f in doc["findings"] if f["check"] == "skills.tree-outside"] + assert [(f["severity"], f["detail"]) for f in outside] == [ + ( + "problem", + { + "tree": tree, + "skill": DEV_PRIMITIVE_LEGACY, + "target": str(shared.resolve()), + "isolation": "worktree", + }, + ) + ] + assert doc["ok"] is False + + pol = policy_mod.load(project.project / ".bmad-loop" / "policy.toml") + assert ( + cli._require_base_skills(project.project, pol, project.project, GrantSet.empty()) is False + ) + assert f"{tree}/{DEV_PRIMITIVE_LEGACY} resolves outside the repo" in capsys.readouterr().err + + cli._warn_preflight_would_abort(project, pol) + err = capsys.readouterr().err + assert "this preview is NOT runnable as-is" in err + assert f"FAIL: {outside[0]['message']}" in err + + def test_validate_json_tickets_mode_document(project, capsys, monkeypatch): """A tickets project bmad-loop can drive validates ok: `mode` is `tickets`, the document names the active initiative and the v7 era, and the tickets checks ran @@ -23023,7 +23097,7 @@ def test_validate_operator_warnings_never_fail_the_run(project, capsys): def test_require_base_skills_does_not_gate_a_triage_only_skill_tree(project): """A triage CLI on its own skill tree must not be able to refuse a run. - ``_skill_trees`` iterates :data:`install.DEV_PRIMITIVE_ROLES` (dev, review), not + ``_skill_scopes`` iterates :data:`install.DEV_PRIMITIVE_ROLES` (dev, review), not :data:`runsetup.ROLES` (dev, review, triage). Every skill this preflight asks about — the dev primitive and the review layers its step-04 invokes inline — is one only a dev or review session dispatches, and ``WorktreeFlow`` only ever @@ -23034,7 +23108,7 @@ def test_require_base_skills_does_not_gate_a_triage_only_skill_tree(project): ``--force``. Triage's only prompt is ``/bmad-loop-sweep``, which ships in this wheel and is laid down by ``bmad-loop init``. - Ablation: point ``_skill_trees`` back at ``ROLES`` and the ``is True`` below goes + Ablation: point ``_skill_scopes`` back at ``ROLES`` and the ``is True`` below goes False — nothing installed ``.agents/skills/bmad-build-auto``, and nothing ever will.""" from bmad_loop.install import DEV_PRIMITIVE_ROLES @@ -23048,7 +23122,7 @@ def test_require_base_skills_does_not_gate_a_triage_only_skill_tree(project): # ...because triage's tree was never asked about. Asserting the whole list, not # `".agents/skills" not in`: the point is which trees ARE gated, and an empty # list would satisfy the negative form while gating nothing at all. - assert cli._skill_trees(project.project, pol, project.project, GrantSet.empty()) == [ + assert _gated_trees(project.project, pol, project.project, GrantSet.empty()) == [ ".claude/skills" ] @@ -23117,7 +23191,7 @@ def _break_plugin_discovery(root: Path) -> None: "discovery-fault", ], ) -def test_skill_trees_drop_review_only_when_no_review_session_can_spawn( +def test_skill_scopes_drop_review_only_when_no_review_session_can_spawn( project, extra_policy, arrange, expected ): """``review.enabled = false`` drops the review tree only when nothing can still @@ -23140,7 +23214,7 @@ def test_skill_trees_drop_review_only_when_no_review_session_can_spawn( # Asserting the whole list, not `".agents/skills" not in`: an empty list would # satisfy the negative form while gating nothing at all. assert ( - cli._skill_trees(project.project, pol, project.project, load_grants(project.project)) + _gated_trees(project.project, pol, project.project, load_grants(project.project)) == expected ) @@ -23151,7 +23225,7 @@ def test_require_base_skills_passes_review_off_without_the_review_tree(project): tree — the preflight passes. Enabling tea (three review-role workflows) gates ``.agents/skills`` again. - Ablation: with `_skill_trees` reverted to gate both `DEV_PRIMITIVE_ROLES` trees + Ablation: with `_skill_scopes` reverted to gate both `DEV_PRIMITIVE_ROLES` trees unconditionally (the `_review_tree_gated` check removed), the first ``is True`` goes False — nothing installed ``.agents/skills/bmad-build-auto``.""" _write_policy(project.project, REVIEW_DISABLED_POLICY) @@ -23304,7 +23378,7 @@ def launched(*_a, **_k): # the gate after the skills preflight: never reach a l assert agents_fails, err -def test_skill_trees_with_review_on_never_read_plugins(project, monkeypatch): +def test_skill_scopes_with_review_on_never_read_plugins(project, monkeypatch): """``review.enabled = true`` gates both trees without consulting plugins at all: a discovery walk that would raise is never reached.""" from bmad_loop.plugins import registry as registry_mod @@ -23316,7 +23390,7 @@ def boom(*_a, **_k): _write_policy(project.project, DUAL_CLIENT_POLICY) pol = policy_mod.load(project.project / ".bmad-loop" / "policy.toml") assert pol.review.enabled is True - assert cli._skill_trees(project.project, pol, project.project, GrantSet.empty()) == [ + assert _gated_trees(project.project, pol, project.project, GrantSet.empty()) == [ ".claude/skills", ".agents/skills", ] @@ -23333,7 +23407,7 @@ def boom(*_a, **_k): def test_gated_trees_are_a_subset_of_provisioned_trees(project, policy_text, gated_trees): """Gated ⊆ provisioned, pinned from BOTH sides rather than asserted in a comment. - ``cli._skill_trees`` decides which trees can REFUSE a run; + ``cli._skill_scopes`` decides which trees can REFUSE a run; ``WorktreeFlow.worktree_profiles`` decides which profiles get carried INTO a worktree. A tree gated but not provisioned drops the session into the `Unknown command` stall the preflight exists to catch, so gating may never @@ -23363,7 +23437,7 @@ def test_gated_trees_are_a_subset_of_provisioned_trees(project, policy_text, gat for role in ROLES } - gated = cli._skill_trees(project.project, pol, project.project, GrantSet.empty()) + gated = _gated_trees(project.project, pol, project.project, GrantSet.empty()) provisioned = { p.skill_tree for p in WorktreeFlow.worktree_profiles(SimpleNamespace(_adapters_get=lambda: adapters)) @@ -23957,7 +24031,7 @@ def _renamed_with_an_orphan(root): def test_validate_does_not_gate_a_triage_only_skill_tree(project, capsys, monkeypatch): """validate's verdict and run's abort are now one decision, on the same trees. - ``cmd_validate`` builds its trees through the same ``_skill_trees`` the real + ``cmd_validate`` builds its trees through the same ``_skill_scopes`` the real preflight calls, so a triage CLI on its own tree can no more fail validate than it can abort a run. Before that, ``cmd_validate`` passed ``[p.skill_tree for p in profiles]`` — every loaded profile, triage included — @@ -29071,3 +29145,215 @@ def test_sweep_store_source_judges_a_v7_sweep_as_a_tickets_run(project_v7): assert cli._sweep_store_source(v7, pol) == "tickets" v6 = dataclasses.replace(v7, era="v6", active_initiative="", initiative_folder=None) assert cli._sweep_store_source(v6, pol) == "sprint-status" + + +# ---- [skills] user_roots: validate and preflight resolve user-root skills ------- + +CODEX_USER_ROOTS_POLICY = '[adapter]\nname = "codex"\nmodel = "gpt-5"\n' +USER_ROOTS_ON = "\n[skills]\nuser_roots = true\n" + + +def _user_skill_home(monkeypatch, tmp_path, tree): + """A home whose ``tree`` (``.agents/skills``, ...) holds the dev primitive and + review skills, pinned as the locator's home.""" + from bmad_loop import skill_locate + + home = tmp_path / "home" + install_build_auto_skill(home, tree) + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + return home + + +def _global_only_codex(project, monkeypatch, capsys, tmp_path): + """codex on every role, the build skill only in `~/.agents/skills`, every other + validate gate green.""" + _user_skill_home(monkeypatch, tmp_path, ".agents/skills") + _make_validate_pass( + project, monkeypatch, capsys, policy=CODEX_USER_ROOTS_POLICY, skills=lambda root: None + ) + monkeypatch.setattr(probe_mod, "binary_version_text", lambda *_a, **_kw: "codex-cli 9.0.0") + + +def _set_user_roots(project, on): + text = CODEX_USER_ROOTS_POLICY + (USER_ROOTS_ON if on else "") + _write_policy(project.project, text) + return policy_mod.load(project.project / ".bmad-loop" / "policy.toml") + + +def test_user_roots_switch_validate_and_preflight_agree(project, capsys, monkeypatch, tmp_path): + """A global-only install: switch on, validate passes with `skills.root` naming + `~/.agents/skills` and the preflight passes; switch off, both refuse, and the + finding offers the switch. + + Ablation (performed): stop passing `pol.skills.user_roots` to `scope_for` in + `_scoped_profiles` and the switch-on leg reports base-missing and FAILS.""" + _global_only_codex(project, monkeypatch, capsys, tmp_path) + grants = load_grants(project.project) + + pol = _set_user_roots(project, True) + doc = machine_json(["validate", "--project", str(project.project), "--json"], capsys) + roots = [f for f in doc["findings"] if f["check"] == "skills.root"] + primitive = next(f for f in roots if f["detail"]["skill"] == "bmad-build-auto") + assert primitive["severity"] == "ok" + assert primitive["detail"] == { + "profile": "codex", + "tree": ".agents/skills", + "skill": "bmad-build-auto", + "root": "~/.agents/skills", + "origin": "user", + } + assert doc["counts"]["problem"] == 0 + assert cli._require_base_skills(project.project, pol, project.project, grants) is True + assert "skills.root" not in capsys.readouterr().err # never printed as a warning + + pol = _set_user_roots(project, False) + assert cli._require_base_skills(project.project, pol, project.project, grants) is False + assert "`[skills] user_roots = true`" in capsys.readouterr().err + doc = machine_json(["validate", "--project", str(project.project), "--json"], capsys, rc=1) + missing = next( + f + for f in doc["findings"] + if f["check"] == "skills.base-missing" and f["detail"]["skill"] == "bmad-build-auto" + ) + assert missing["detail"]["outside"] == "~/.agents/skills/bmad-build-auto" + assert "`[skills] user_roots = true`" in missing["message"] + assert not [f for f in doc["findings"] if f["check"] == "skills.root"] + + +def test_user_roots_dry_run_notes_the_user_root(project, capsys, monkeypatch, tmp_path): + """The dry-run preview says which skill a run would load from a user root.""" + _global_only_codex(project, monkeypatch, capsys, tmp_path) + _set_user_roots(project, True) + capsys.readouterr() + + assert cli.main(["run", "--project", str(project.project), "--dry-run"]) == 0 + + err = capsys.readouterr().err + assert "note: bmad-build-auto resolves from ~/.agents/skills/bmad-build-auto (user root)" in err + assert "NOT runnable" not in err + + +@pytest.mark.parametrize("on", [False, True], ids=["switch-off", "switch-on"]) +def test_user_roots_claude_shadow(project, capsys, monkeypatch, tmp_path, on): + """claude runs a personal `~/.claude/skills` copy over the project's: switch off + the preflight warns about the shadow; switch on it resolves the user copy and + has nothing to warn about.""" + from bmad_loop import install + + _user_skill_home(monkeypatch, tmp_path, ".claude/skills") + install_build_auto_skill(project.project, ".claude/skills") + _write_policy(project.project, CLAUDE_ONLY_POLICY + (USER_ROOTS_ON if on else "")) + pol = policy_mod.load(project.project / ".bmad-loop" / "policy.toml") + + assert cli._require_base_skills(project.project, pol, project.project, GrantSet.empty()) is True + err = capsys.readouterr().err + scopes = cli._skill_scopes(project.project, pol, project.project, GrantSet.empty()) + origins = { + f.detail["origin"] + for f in install.skill_root_findings(project.project, scopes) + if f.detail["skill"] == "bmad-build-auto" + } + if on: + assert "warning:" not in err + assert origins == {"user"} + else: + assert "warning:" in err and "~/.claude/skills/bmad-build-auto" in err + assert origins == {"project"} + + +def _user_root_report(project, policy_text, home_tree, monkeypatch, tmp_path, versions): + from bmad_loop.checks import ValidationReport + + _user_skill_home(monkeypatch, tmp_path, home_tree) + _write_policy(project.project, policy_text) + pol = policy_mod.load(project.project / ".bmad-loop" / "policy.toml") + report = ValidationReport() + profiles = cli._scoped_profiles(project.project, pol, project.project, GrantSet.empty()) + cli._report_skill_roots(report, project.project, pol, profiles, versions) + return {f.check: f for f in report.findings} + + +@pytest.mark.parametrize("name", ["opencode", "opencode-http"], ids=["alias", "canonical"]) +@pytest.mark.parametrize( + ("text", "warned"), [("1.19.0", True), ("opencode v2.0.27", False)], ids=["v1", "v2"] +) +def test_user_roots_opencode_v1_warns(project, monkeypatch, tmp_path, text, warned, name): + """opencode 1.x cannot load a user-root skill (its spawn refuses), so validate + warns; 2.x allows it. The version is the one `_check_opencode_version` parsed, + keyed by the canonical profile name the way `cmd_validate` stores it — so a + policy spelling the `opencode` alias still finds it. + + Ablation (performed): drop the `version[0] < 2` branch and both v1 rows FAIL; + look the version up by the policy name and the alias v1 row FAILS.""" + from bmad_loop.checks import ValidationReport + + monkeypatch.setattr(probe_mod, "binary_version_text", lambda *_a, **_kw: text) + version = cli._check_opencode_version(ValidationReport(), "opencode", "/usr/bin/opencode") + findings = _user_root_report( + project, + OPENCODE_QUALIFIED_POLICY.replace('"opencode"', f'"{name}"') + USER_ROOTS_ON, + ".config/opencode/skills", + monkeypatch, + tmp_path, + {"opencode-http": version}, + ) + if warned: + detail = findings["skills.user-root-unsupported"].detail + assert (detail["profile"], detail["version"]) == (name, "1.19.0") + assert "bmad-build-auto" in detail["skills"] + else: + assert "skills.user-root-unsupported" not in findings + assert findings["skills.root"].detail["origin"] == "user" + + +@pytest.mark.parametrize("mode", ["sandboxed", "bypass"]) +def test_user_roots_sandboxed_warns(project, monkeypatch, tmp_path, mode): + """A sandboxed role loading a user-root skill is warned about; bypass is not.""" + findings = _user_root_report( + project, + f'[adapter]\nname = "claude"\npermission_mode = "{mode}"\n' + USER_ROOTS_ON, + ".claude/skills", + monkeypatch, + tmp_path, + {}, + ) + if mode == "sandboxed": + finding = findings["skills.user-root-sandboxed"] + assert finding.severity == "warning" + assert finding.detail["profile"] == "claude" + assert "bmad-build-auto" in finding.detail["skills"] + else: + assert "skills.user-root-sandboxed" not in findings + + +def test_resolve_epic_close_finds_the_skill_in_a_user_root(project, capsys, monkeypatch, tmp_path): + """bmad-agent-po only in `~/.claude/skills`: with `[skills] user_roots` on the + epic-close session launches, told where the skill is; off, it is refused.""" + from bmad_loop import skill_locate + + home = tmp_path / "home" + skill = home / ".claude" / "skills" / "bmad-agent-po" / "SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("---\nname: bmad-agent-po\n---\n", encoding="utf-8") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + _run_dir, resumed = _epic_close_run(project, monkeypatch, capsys) + _fake_epic_tree(monkeypatch, project, "done") + dirs: list[str | None] = [] + _prompts, _claims = _epic_close_session(project, monkeypatch, lambda _prompt: 0, skill=False) + from bmad_loop import resolve + + stub = resolve.run_epic_close_session + + def capture(*a, skill_dir=None, **kw): + dirs.append(skill_dir) + return stub(*a, **kw) + + monkeypatch.setattr(resolve, "run_epic_close_session", capture) + + assert _resolve_epic_interactive(project, "--resume") == 1 # switch off: refused + assert dirs == [] and "bmad-agent-po/SKILL.md" in capsys.readouterr().err + + policy = project.project / ".bmad-loop" / "policy.toml" + policy.write_text(policy.read_text(encoding="utf-8") + USER_ROOTS_ON, encoding="utf-8") + _resolve_epic_interactive(project, "--resume") + assert dirs == [str(skill.parent)], capsys.readouterr().err diff --git a/tests/test_engine.py b/tests/test_engine.py index 103b69baf..f8d55169c 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -106,6 +106,7 @@ Policy, ReviewPolicy, ScmPolicy, + SkillsPolicy, StageAdapterPolicy, SweepPolicy, VerifyPolicy, @@ -20161,6 +20162,15 @@ def _prompt_task(**kw) -> StoryTask: return StoryTask(story_key="1-1-a", epic=1, **kw) +def _dev_skill_memo(engine) -> dict: + """``Engine._dev_skill_cache`` with each ``SkillScope`` key read as its primary + tree (None stays None), so a memo assertion names trees, not scope objects.""" + return { + (project, scope.tree if scope is not None else None): name + for (project, scope), name in engine._dev_skill_cache.items() + } + + def test_dev_prompts_spell_the_post_rename_primitive(project): """Every generic-dev leg (fresh, known spec, restore, repair) invokes the name resolved from the dev adapter's skill tree — here post-rename bmad-build-auto.""" @@ -20208,7 +20218,7 @@ def test_dev_prompt_falls_back_to_the_legacy_name_without_a_profile(project): assert engine._generic_dev_prompt(_prompt_task(), None).startswith("/bmad-dev-auto 1-1-a") # the None tree IS the fallback path, not an unresolved tree that happened to miss - assert engine._dev_skill_cache == {(project.project, None): "bmad-dev-auto"} + assert _dev_skill_memo(engine) == {(project.project, None): "bmad-dev-auto"} def test_review_prompt_resolves_through_the_review_adapters_own_tree(project): @@ -20231,7 +20241,7 @@ def test_review_prompt_resolves_through_the_review_adapters_own_tree(project): ) # each tree resolved independently — one memo entry per (workspace, tree), not # one per run - assert engine._dev_skill_cache == { + assert _dev_skill_memo(engine) == { (project.project, ".claude/skills"): "bmad-build-auto", (project.project, ".agents/skills"): "bmad-dev-auto", } @@ -25096,7 +25106,7 @@ def test_workflow_marker_is_named_for_the_workflows_own_role_tree(project): # disagreeing is what the assertions above are reading — not two names that # happen to coincide. assert engine._dev_skill() == "bmad-build-auto" - assert engine._dev_skill_cache == { + assert _dev_skill_memo(engine) == { (project.project, ".agents/skills"): "bmad-dev-auto", (project.project, ".claude/skills"): "bmad-build-auto", } @@ -25134,12 +25144,393 @@ def test_dev_prompt_resolves_in_the_reopened_worktree_not_the_main_checkout(proj engine.workspace = default assert engine._generic_dev_prompt(_prompt_task(), None).startswith("/bmad-build-auto 1-1-a") - assert engine._dev_skill_cache == { + assert _dev_skill_memo(engine) == { (worktree.resolve(), ".claude/skills"): "bmad-dev-auto", (project.project, ".claude/skills"): "bmad-build-auto", } +# ------------------------------- user-level skill roots: dispatch (#770) +# A codex dev adapter whose project tree is empty and whose user root +# `~/.agents/skills` (the codex profile's first declared root) carries the +# post-rename primitive: the `[skills] user_roots` switch decides whether the +# engine resolves, spells and journals that global copy. + + +def _user_root_policy(on: bool) -> Policy: + return Policy( + gates=GatesPolicy(mode="none"), + notify=QUIET, + scm=ScmPolicy(rollback_on_failure=True), + skills=SkillsPolicy(user_roots=on), + ) + + +def _global_codex_engine(project, monkeypatch, tmp_path, *, on: bool, script=(), global_only=True): + """An engine whose codex dev adapter sees ``bmad-build-auto`` only in the user + root ``~/.agents/skills`` (home pinned to ``tmp_path/home``), with a module + record there naming it. Returns ``(engine, adapter, skill_folder)``.""" + from conftest import attach_profile, install_build_auto_skill + + from bmad_loop import skill_locate + + home = tmp_path / "home" + root = install_build_auto_skill(home, ".agents/skills") + record = root / "bmod-method" / "bmod.toml" + record.parent.mkdir(parents=True) + record.write_text('[bmod]\nversion = "7.2.0"\nskills = ["bmad-build-auto"]\n', encoding="utf-8") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + engine, adapter = make_engine(project, list(script), policy=_user_root_policy(on)) + attach_profile(adapter, "codex") + if global_only: + assert not (project.project / ".agents/skills/bmad-build-auto").exists() + return engine, adapter, root / "bmad-build-auto" + + +def test_dev_prompt_spells_a_user_root_primitive_only_with_the_switch_on( + project, monkeypatch, tmp_path +): + """With `[skills] user_roots` on, a primitive installed only in a user root the + CLI loads resolves, so the prompt spells it; off, the project tree alone is + read and the unresolved primitive falls back to the legacy name. + + Ablation: pass `resolve_user=False` in `Engine._skill_scope` and the switch-on + half reddens (it spells `/bmad-dev-auto`).""" + on, _, _ = _global_codex_engine(project, monkeypatch, tmp_path, on=True) + prompt = on._generic_dev_prompt(_prompt_task(), None) + assert prompt.startswith("/bmad-build-auto 1-1-a") + assert "bmad-dev-auto" not in prompt + + off, _, _ = _global_codex_engine(project, monkeypatch, tmp_path / "off", on=False) + assert off._generic_dev_prompt(_prompt_task(), None).startswith("/bmad-dev-auto 1-1-a") + + +def test_session_spec_carries_the_user_root_skill_dir_and_journals_it( + project, monkeypatch, tmp_path +): + """At the one `SessionSpec` construction, a prompt naming a user-root skill + hands the adapter that skill's absolute folder as `skill_dir` and the user-root + ids as `user_skill_ids`, and journals one `skill-user-root` row per id.""" + engine, adapter, folder = _global_codex_engine( + project, monkeypatch, tmp_path, on=True, script=[SessionResult(status="completed")] + ) + + engine._run_session(_prompt_task(), role="dev", prompt="/bmad-build-auto 1-1-a", seq=1) + + (spec,) = adapter.sessions + assert spec.skill_dir == str(folder) + assert "bmad-build-auto" in spec.user_skill_ids + rows = [e for e in engine.journal.entries() if e["kind"] == "skill-user-root"] + assert {r["skill"] for r in rows} == set(spec.user_skill_ids) + (row,) = [r for r in rows if r["skill"] == "bmad-build-auto"] + assert row["role"] == "dev" + assert row["root"] == "~/.agents/skills" + assert row["version"] == "7.2.0" + + +@pytest.mark.parametrize( + ("hook_disables", "second_root"), + [(False, False), (True, False), (True, True)], + ids=["ambient", "hook-set", "hook-set-other-root-loads"], +) +def test_session_user_roots_resolve_against_the_post_hook_env( + project, monkeypatch, tmp_path, hook_disables, second_root +): + """A `pre_session` hook that sets a root's disabler (an account rotation's + CLAUDE_CONFIG_DIR; here codex's CODEX_HOME over `~/.codex/skills`) hides that + root from the launched CLI, so dispatch resolves against the post-hook env. + When the hidden root held the only copy of the skill the prompt names, the + launch stops before `session-start`: the prompt was spelled before the hook + ran, and the CLI would halt on an unknown command. When `~/.agents/skills`, + which codex ranks first, also holds it, the hook changes nothing and the + session launches from there. Without the hook the `~/.codex/skills` install + resolves. + + Ablation (performed): drop `env` from the `_skill_scope` call at the + `SessionSpec` construction and the hook-set row FAILS (the session launches).""" + from conftest import attach_profile, install_build_auto_skill + + from bmad_loop import skill_locate + + home = tmp_path / "home" + folder = install_build_auto_skill(home, ".codex/skills") / "bmad-build-auto" + if second_root: + folder = install_build_auto_skill(home, ".agents/skills") / "bmad-build-auto" + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + engine, adapter = make_engine( + project, [SessionResult(status="completed")], policy=_user_root_policy(True) + ) + attach_profile(adapter, "codex") + real_gate = engine._emit_session_gate + + def gate(*args, **kwargs): + prompt, env, ctx = real_gate(*args, **kwargs) + if hook_disables: + env = {**env, "CODEX_HOME": str(tmp_path / "rotated")} + return prompt, env, ctx + + monkeypatch.setattr(engine, "_emit_session_gate", gate) + + def run(): + engine._run_session(_prompt_task(), role="dev", prompt="/bmad-build-auto 1-1-a", seq=1) + + if hook_disables and not second_root: + with pytest.raises(RuntimeError, match=r"/bmad-build-auto.*~/\.codex/skills.*CODEX_HOME"): + run() + kinds = [e["kind"] for e in engine.journal.entries()] + assert adapter.sessions == [] + assert "session-start" not in kinds + assert "skill-user-root" not in kinds + return + + run() + (spec,) = adapter.sessions + rows = [e for e in engine.journal.entries() if e["kind"] == "skill-user-root"] + expected_root = "~/.agents/skills" if second_root else "~/.codex/skills" + assert spec.skill_dir == str(folder) + assert "bmad-build-auto" in spec.user_skill_ids + assert {r["root"] for r in rows} == {expected_root} + + +@pytest.mark.parametrize( + ("hook_disables", "project_copy"), + [(False, "older"), (True, "same"), (True, "older")], + ids=["ambient", "hook-set-same-copy", "hook-set-older-copy"], +) +def test_session_refuses_when_a_hook_swaps_the_primitive_for_another_copy( + project, monkeypatch, tmp_path, hook_disables, project_copy +): + """Claude ranks `~/.claude/skills` above the project tree, so the preflight + checks the user copy of the primitive. A `pre_session` hook that sets + CLAUDE_CONFIG_DIR hides that root and the CLI falls back to the project copy, + which no check read (an older primitive without ticket support, say). The + launch stops before `session-start`, naming both roots. A byte-identical + project copy keeps the launch going, as does an ambient launch that reads the + checked user copy. + + Ablation (performed): drop the `same_copy` comparison in + `_refuse_hook_changed_skill` (accept any post-hook copy) and the older-copy + row FAILS (the session launches); refuse every changed path regardless of + content and the same-copy row FAILS.""" + from conftest import attach_profile, install_build_auto_skill + + from bmad_loop import skill_locate + from bmad_loop.install import DEV_PRIMITIVE_NEW + + home = tmp_path / "home" + install_build_auto_skill(home, ".claude/skills") + install_build_auto_skill(project.project, ".claude/skills") + if project_copy == "older": + skill_md = project.project / ".claude/skills" / DEV_PRIMITIVE_NEW / "SKILL.md" + skill_md.write_text(skill_md.read_text(encoding="utf-8") + "\nolder\n", encoding="utf-8") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + engine, adapter = make_engine( + project, [SessionResult(status="completed")], policy=_user_root_policy(True) + ) + attach_profile(adapter, "claude") + real_gate = engine._emit_session_gate + + def gate(*args, **kwargs): + prompt, env, ctx = real_gate(*args, **kwargs) + if hook_disables: + env = {**env, "CLAUDE_CONFIG_DIR": str(tmp_path / "rotated")} + return prompt, env, ctx + + monkeypatch.setattr(engine, "_emit_session_gate", gate) + + def run(): + engine._run_session(_prompt_task(), role="dev", prompt=f"/{DEV_PRIMITIVE_NEW} 1-1-a", seq=1) + + if hook_disables and project_copy == "older": + with pytest.raises( + RuntimeError, + match=rf"/{DEV_PRIMITIVE_NEW}, which resolves from ~/\.claude/skills.*" + r"CLAUDE_CONFIG_DIR.*the copy in \.claude/skills, which no check read", + ): + run() + assert adapter.sessions == [] + assert "session-start" not in [e["kind"] for e in engine.journal.entries()] + return + + run() + (spec,) = adapter.sessions + expected = str(home / ".claude/skills" / DEV_PRIMITIVE_NEW) if not hook_disables else None + assert spec.skill_dir == expected + + +@pytest.mark.parametrize( + ("hook_disables", "project_reviewers"), + [(False, False), (True, False), (True, True)], + ids=["ambient", "hook-set-reviewer-hidden", "hook-set-reviewers-in-project"], +) +def test_session_refuses_when_a_hook_hides_a_required_review_skill( + project, monkeypatch, tmp_path, hook_disables, project_reviewers +): + """The dev primitive is in the project tree, but the review skills it must + invoke resolve only from `~/.codex/skills`. Preflight passes them against the + shared scope; a `pre_session` hook that sets CODEX_HOME hides that root, so the + primitive would launch and fail its review step. The launch stops before + `session-start`, naming the reviewer and the variable. Reviewers that the + project tree also carries keep the launch going. + + Ablation (performed): compare only the prompt's skill in + `_refuse_hook_changed_skill` and the reviewer-hidden row FAILS (the session + launches).""" + import shutil + + from conftest import attach_profile, install_build_auto_skill + + from bmad_loop import skill_locate + from bmad_loop.install import DEV_PRIMITIVE_NEW + + home = tmp_path / "home" + project_tree = install_build_auto_skill(project.project, ".agents/skills") + home_tree = install_build_auto_skill(home, ".codex/skills") + shutil.rmtree(home_tree / DEV_PRIMITIVE_NEW) + reviewers = sorted(p.name for p in home_tree.iterdir()) + assert reviewers + if not project_reviewers: + for name in reviewers: + shutil.rmtree(project_tree / name) + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + engine, adapter = make_engine( + project, [SessionResult(status="completed")], policy=_user_root_policy(True) + ) + attach_profile(adapter, "codex") + real_gate = engine._emit_session_gate + + def gate(*args, **kwargs): + prompt, env, ctx = real_gate(*args, **kwargs) + if hook_disables: + env = {**env, "CODEX_HOME": str(tmp_path / "rotated")} + return prompt, env, ctx + + monkeypatch.setattr(engine, "_emit_session_gate", gate) + + def run(): + engine._run_session(_prompt_task(), role="dev", prompt="/bmad-build-auto 1-1-a", seq=1) + + if hook_disables and not project_reviewers: + with pytest.raises( + RuntimeError, + match=rf"/bmad-build-auto, whose review step needs {reviewers[0]}.*" + r"~/\.codex/skills.*CODEX_HOME", + ): + run() + assert adapter.sessions == [] + assert "session-start" not in [e["kind"] for e in engine.journal.entries()] + return + + run() + (spec,) = adapter.sessions + assert spec.skill_dir is None + + +@pytest.mark.parametrize("gated", [True, False], ids=["advisory-launches", "required-refused"]) +def test_session_hook_guard_skips_an_advisory_review_skill(project, monkeypatch, tmp_path, gated): + """The primitive and its `blind` reviewer sit in the project tree. A second + layer names `bmad-review-performance`, which resolves only from + `~/.codex/skills`. When that layer is `when`-gated, the reviewer is advisory: + it may never run and preflight only warns when it is missing, so a + `pre_session` hook that sets CODEX_HOME and hides it does not stop the launch. + Ungated, the same reviewer is required and the launch stops. + + Ablation (performed): compare every reviewer (`ReviewResolution.skills()`, + advisory included) in `_refuse_hook_changed_skill` and the advisory row FAILS + (the launch is refused).""" + from conftest import attach_profile, install_build_auto_skill + + from bmad_loop import skill_locate + from bmad_loop.install import DEV_PRIMITIVE_NEW + + home = tmp_path / "home" + project_tree = install_build_auto_skill(project.project, ".agents/skills") + when_line = 'when = "the diff touches hot paths"\n' if gated else "" + (project_tree / DEV_PRIMITIVE_NEW / "customize.toml").write_text( + "[workflow]\n" + '[[workflow.review_layers]]\nid = "blind"\n' + 'instruction = "Invoke the `bmad-review` skill on this diff."\n' + f'[[workflow.review_layers]]\nid = "perf"\n{when_line}' + 'instruction = "Invoke the `bmad-review-performance` skill on this diff."\n', + encoding="utf-8", + ) + for name, root in (("bmad-review", project_tree), ("bmad-review-performance", None)): + folder = (root or home / ".codex/skills") / name + folder.mkdir(parents=True, exist_ok=True) + (folder / "SKILL.md").write_text(f"# {name}\n", encoding="utf-8") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + engine, adapter = make_engine( + project, [SessionResult(status="completed")], policy=_user_root_policy(True) + ) + attach_profile(adapter, "codex") + real_gate = engine._emit_session_gate + + def gate(*args, **kwargs): + prompt, env, ctx = real_gate(*args, **kwargs) + return prompt, {**env, "CODEX_HOME": str(tmp_path / "rotated")}, ctx + + monkeypatch.setattr(engine, "_emit_session_gate", gate) + + def run(): + engine._run_session(_prompt_task(), role="dev", prompt="/bmad-build-auto 1-1-a", seq=1) + + if not gated: + with pytest.raises( + RuntimeError, match=r"review step needs bmad-review-performance.*CODEX_HOME" + ): + run() + assert adapter.sessions == [] + return + + run() + (spec,) = adapter.sessions + assert spec.skill_dir is None + + +def test_session_spec_has_no_user_root_skills_with_the_switch_off(project, monkeypatch, tmp_path): + """Switch off: the same global-only install contributes nothing — no + `skill_dir` (the project-tree miss keeps the renderer's relative default), no + ids, no `skill-user-root` row. + + Ablation (performed): force `resolve_user=True` in `Engine._skill_scope` and + every assertion here reddens. The `scope.resolve_user` guard at the + `SessionSpec` construction only skips work: `user_root_skill_ids` is already + switch-gated through `locate`.""" + engine, adapter, _ = _global_codex_engine( + project, monkeypatch, tmp_path, on=False, script=[SessionResult(status="completed")] + ) + + engine._run_session(_prompt_task(), role="dev", prompt="/bmad-build-auto 1-1-a", seq=1) + + (spec,) = adapter.sessions + assert spec.skill_dir is None + assert spec.user_skill_ids == () + assert "skill-user-root" not in [e["kind"] for e in engine.journal.entries()] + + +def test_session_spec_skill_dir_is_none_for_a_primary_tree_hit(project, monkeypatch, tmp_path): + """A project-tree copy wins under the codex profile's `unordered` precedence, so + the spec carries no `skill_dir` (the renderer spells `/`) + and no user-root ids for that skill even with the switch on.""" + from conftest import install_build_auto_skill + + install_build_auto_skill(project.project, ".agents/skills") + engine, adapter, _ = _global_codex_engine( + project, + monkeypatch, + tmp_path, + on=True, + script=[SessionResult(status="completed")], + global_only=False, + ) + + engine._run_session(_prompt_task(), role="dev", prompt="/bmad-build-auto 1-1-a", seq=1) + + (spec,) = adapter.sessions + assert spec.skill_dir is None + assert "bmad-build-auto" not in spec.user_skill_ids + + # --------------------- the park-record put-back, confined to the project (#593) @@ -26095,6 +26486,45 @@ def test_auto_retro_skill_probe_passes_when_the_skill_is_installed(project): assert "retro-auto-finished" in _kinds(engine) +@pytest.mark.parametrize("on", [True, False]) +def test_auto_retro_skill_probe_reads_user_roots_only_with_the_switch_on( + project, monkeypatch, tmp_path, on +): + """A `bmad-retrospective` installed only in the retro CLI's user root + (`~/.claude/skills` for claude) passes the probe under `[skills] user_roots`; + off, the probe reads the project tree alone and skips as `skill-missing`. + + Ablation: restore the project-tree-only probe and the switch-on row reddens.""" + from conftest import attach_profile + + from bmad_loop import skill_locate + + home = tmp_path / "home" + skill = home / ".claude" / "skills" / "bmad-retrospective" / "SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("---\nname: bmad-retrospective\n---\n") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + policy = Policy( + gates=GatesPolicy(mode="none", retrospective="auto"), + notify=QUIET, + skills=SkillsPolicy(user_roots=on), + ) + _two_epic_sprint(project) + _commit_all(project) + retro = MockAdapter([retro_effect(project)]) + engine, _ = make_engine(project, [], policy=policy, retro_adapter=retro) + attach_profile(retro, "claude", project.project) + + engine._maybe_auto_retro(1) + + if on: + assert len(retro.sessions) == 1 + assert "retro-auto-finished" in _kinds(engine) + else: + assert retro.sessions == [] + assert _only(engine, "retro-auto-skipped")["reason"] == "skill-missing" + + def test_auto_retro_unreadable_board_is_refused(project, monkeypatch): sent = _record_notify(monkeypatch) engine, retro = _boundary_engine(project) diff --git a/tests/test_engine_worktree.py b/tests/test_engine_worktree.py index a4ebd47b8..c24a741fb 100644 --- a/tests/test_engine_worktree.py +++ b/tests/test_engine_worktree.py @@ -68,6 +68,7 @@ OperatorPolicy, Policy, ScmPolicy, + SkillsPolicy, TicketsPolicy, VerifyPolicy, ) @@ -1557,6 +1558,38 @@ def test_missing_upstream_skill_seed_escalates_before_dispatch_and_records_mount ) +def test_global_only_primitive_with_user_roots_on_does_not_escalate(project, tmp_path, monkeypatch): + """#770: under `[skills] user_roots` a dev primitive installed only in the + operator's home (`~/.claude/skills`, which claude loads) is not a seeding gap — + no worktree carries the home and seeding never copies from it — so the unit + dispatches instead of escalating, and the exemption is journaled. + + Ablation: drop the user-root `continue` in `base_skills_seed_incomplete` and the + gate reports `~/.claude/skills/bmad-build-auto` missing from the mount and the + run pauses before any session.""" + from bmad_loop import skill_locate + + home = tmp_path / "home" + install_build_auto_skill(home, ".claude/skills") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + commit_sprint(project, {"1-1-a": "ready-for-dev"}) + policy = replace(wt_policy(), skills=SkillsPolicy(user_roots=True)) + engine, adapter = make_engine( + project, + [wt_dev_effect(project, "1-1-a"), wt_review_effect(project, "1-1-a", clean=True)], + policy=policy, + ) + attach_profile(adapter) + + summary = engine.run() + + assert summary.done == 1 and not summary.paused, engine.state.paused_reason + assert "story-escalated" not in journal_kinds(engine) + rows = [e for e in engine.journal.entries() if e["kind"] == "worktree-skills-user-root"] + assert rows and rows[0]["story_key"] == "1-1-a" + assert f"~/.claude/skills/{DEV_PRIMITIVE_NEW}" in rows[0]["entries"] + + def _install_short_renderer_case(project, tmp_path, *, renderer_stub): """Install a complete primitive beside renderer scripts the seed cannot follow.""" tree = ".claude/skills" diff --git a/tests/test_generic_tmux.py b/tests/test_generic_tmux.py index 444493aeb..fdf822979 100644 --- a/tests/test_generic_tmux.py +++ b/tests/test_generic_tmux.py @@ -425,6 +425,19 @@ def test_codex_extra_args_keep_no_daemon(tmp_path): assert "--dangerously-bypass-approvals-and-sandbox" not in argv +def test_interactive_argv_renders_the_specs_skill_dir(tmp_path): + """The engine's located skill folder (`SessionSpec.skill_dir`) reaches the + copilot prompt's `{skill_dir}`; without one the prompt keeps the relative + `.agents/skills/` spelling. Ablation: drop `skill_dir=spec.skill_dir` + at the generic `render_prompt` call and the first assertion FAILS.""" + adapter = make_adapter(tmp_path, profile_name="copilot") + folder = str(tmp_path / "home" / ".agents" / "skills" / "bmad-dev-auto") + located = dataclasses.replace(make_spec(tmp_path), skill_dir=folder) + assert adapter.interactive_argv(located)[2].startswith(f"LOAD the FULL {folder}/SKILL.md,") + plain = adapter.interactive_argv(make_spec(tmp_path)) + assert plain[2].startswith("LOAD the FULL .agents/skills/bmad-dev-auto/SKILL.md,") + + def test_build_command_gemini_uses_interactive_flag(tmp_path): adapter = make_adapter(tmp_path, profile_name="gemini") cmd = adapter.build_command(make_spec(tmp_path)) diff --git a/tests/test_install.py b/tests/test_install.py index 989fed4d8..b18797033 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -12,6 +12,7 @@ import sys import zipfile from pathlib import Path, PurePosixPath, PureWindowsPath +from unittest import mock import pytest from conftest import ( @@ -37,6 +38,7 @@ import bmad_loop.worktree_flow as worktree_flow_mod from bmad_loop import verify from bmad_loop.adapters.profile import ProfileError, get_profile +from bmad_loop.checks import Finding from bmad_loop.install import ( BASE_SKILLS, BMAD_DIR, @@ -2955,6 +2957,60 @@ def test_provision_worktree_copies_base_skills_from_repo(tmp_path): assert (wt / claude.skill_tree / "bmad-dev-auto" / "step-04-review.md").is_file() +def test_provision_worktree_copies_base_skills_from_the_extra_tree(tmp_path): + """opencode-http also reads `.agents/skills` (`extra_skill_trees`), where the + skills CLI installs its project skills: a repo carrying the upstream skills + only there gets them seeded into the same tree of the worktree, the gate is + satisfied, and the wheel's own MODULE_SKILLS stay in the primary tree.""" + wt, repo = tmp_path / "wt", tmp_path / "repo" + opencode = get_profile("opencode-http") + (extra,) = opencode.extra_skill_trees + _install_base_skills(repo, extra) + + skipped = provision_worktree(wt, [opencode], repo) + + for skill in BASE_SKILLS: + assert (wt / extra / skill / "SKILL.md").is_file(), skill + assert not [rel for rel in skipped if rel.startswith(extra)] + assert ( + base_skills_seed_incomplete(wt, repo, [_user_scope("opencode-http", None, on=False)]) == [] + ) + for skill in MODULE_SKILLS: + assert (wt / opencode.skill_tree / skill).is_dir() + assert not (wt / extra / skill).exists() + + +def test_provision_worktree_never_copies_from_a_user_root(tmp_path, monkeypatch): + """Under `[skills] user_roots` a required skill located in the operator's home + is neither copied into the worktree nor reported missing by the seed gate — + the session loads it from the home in place — and `base_skills_user_rooted` + names it for the journal. With the switch off the same home is invisible. + + Ablation: drop the user-root `continue` in `base_skills_seed_incomplete` and + the gate reports `~/.agents/skills/bmad-build-auto` (and its reviewers).""" + from bmad_loop import skill_locate + from bmad_loop.worktree_flow import base_skills_user_rooted + + wt, repo, home = tmp_path / "wt", tmp_path / "repo", tmp_path / "home" + repo.mkdir() + _install_skills(home, ".agents/skills", _era_catalog(DEV_PRIMITIVE_NEW)) + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + codex = get_profile("codex") + + skipped = provision_worktree(wt, [codex], repo, user_roots=True) + + assert not (wt / codex.skill_tree / DEV_PRIMITIVE_NEW).exists() + assert not [rel for rel in skipped if "~" in rel or DEV_PRIMITIVE_NEW in rel] + scope = _user_scope("codex", home, on=True) + assert base_skills_seed_incomplete(wt, repo, [scope]) == [] + rooted = base_skills_user_rooted(repo, [scope]) + assert f"~/.agents/skills/{DEV_PRIMITIVE_NEW}" in rooted + assert all(entry.startswith("~/.agents/skills/") for entry in rooted) + # plain trees and the switch off never resolve from the home + assert base_skills_user_rooted(repo, [codex.skill_tree]) == [] + assert base_skills_user_rooted(repo, [_user_scope("codex", home, on=False)]) == [] + + def test_floor_message_names_v7(tmp_path): """The base-skill floor text names both config eras: a v7 project gets its skills from the method module, so a v6-only floor would send its operator after bmm.""" @@ -5552,6 +5608,28 @@ def test_shield_tracked_dir_with_nothing_landed_drops_cleanly(project, tmp_path) assert not [ln for ln in exclude if ln.startswith(f"/{tree}/")] +def test_shield_covers_the_extra_skill_trees(project, tmp_path): + """opencode-http's extra project tree (`.agents/skills`) is shielded beside + its primary one, so the base skills seeded there never reach `git add -A`. + + Ablation: build the shield from `p.skill_tree` alone and the extra-tree + pattern disappears.""" + repo = project.project + opencode = get_profile("opencode-http") + (extra,) = opencode.extra_skill_trees + _install_base_skills(repo, extra) + wt = tmp_path / "wt" + verify.worktree_add(repo, wt, "feat", "main") + + provision_worktree(wt, [opencode], repo) + + exclude = _wt_private_exclude(wt).read_text(encoding="utf-8").splitlines() + assert f"/{opencode.skill_tree}" in exclude + assert f"/{extra}" in exclude + assert (wt / extra / DEV_PRIMITIVE_NEW / "SKILL.md").is_file() + assert git(wt, "status", "--porcelain", "--untracked-files=all", "--", extra) == "" + + def test_shield_untracked_skill_tree_keeps_dir_pattern_without_per_file_noise(project, tmp_path): """An UNTRACKED tool directory keeps the ambient `/dir` pattern and gains nothing else: substitution is the TRACKED branch's answer only. Byte-identical behavior to @@ -11446,6 +11524,160 @@ def test_base_skills_seed_incomplete_ignores_inactive_catalog_symlink(tmp_path): assert base_skills_seed_incomplete(wt, repo, [tree]) == [] +def _link_dir(link, target): + """A directory link at ``link``: a junction on win32 (never ``os.symlink`` there — + it needs a privilege CI does not have), a symlink elsewhere.""" + link.parent.mkdir(parents=True, exist_ok=True) + if sys.platform == "win32": + import _winapi # Windows-only stdlib module + + _winapi.CreateJunction(str(target), str(link)) + elif hasattr(os, "symlink"): + link.symlink_to(target, target_is_directory=True) + else: + pytest.skip("no directory link primitive on this platform") + + +def _global_tree_link(tmp_path): + """``repo/.agents/skills`` linked to a complete global install outside the repo — + the #770 junction workaround. Returns ``(repo, tree, target)``.""" + repo, tree = tmp_path / "repo", ".agents/skills" + home_tree = tmp_path / "home" / ".agents" / "skills" + _install_dev_auto( + tmp_path / "home", + ".agents/skills", + skill=DEV_PRIMITIVE_NEW, + customize="[workflow]\n" + _layer("blind", "bmad-review"), + ) + _install_skills(tmp_path / "home", ".agents/skills", {"bmad-review": ()}) + repo.mkdir() + _link_dir(repo / tree, home_tree) + return repo, tree, str(home_tree.resolve()) + + +def test_skill_tree_outside_tree_link_warns_without_worktree(tmp_path): + """In place, the session reads straight through the link, so it only warns — + `init` is what refuses to write through it.""" + repo, tree, target = _global_tree_link(tmp_path) + + assert install_mod.skill_trees_outside(repo, repo, [tree], isolation="none") == [ + Finding( + "skills.tree-outside", + "warning", + mock.ANY, + {"tree": tree, "target": target, "isolation": "none"}, + ) + ] + + +def test_skill_tree_outside_tree_link_problem_under_worktree(tmp_path): + """Worktree seeding cannot copy one skill out of a tree linked out of the repo: + one problem for the tree, and its skill-level links are not repeated.""" + repo, tree, target = _global_tree_link(tmp_path) + + findings = install_mod.skill_trees_outside(repo, repo, [tree], isolation="worktree") + + assert findings == [ + Finding( + "skills.tree-outside", + "problem", + mock.ANY, + {"tree": tree, "target": target, "isolation": "worktree"}, + ) + ] + assert "worktree isolation" in findings[0].message + + +def test_skill_tree_outside_skill_link_only_under_worktree(tmp_path): + """A required reviewer linked to a shared install: invisible in place, and under + worktree isolation the preflight refusal that replaces the mid-run escalation. + The inactive catalog link beside it is not required, so it is not reported.""" + repo, tree = tmp_path / "repo", ".claude/skills" + _install_dev_auto( + repo, + tree, + skill=DEV_PRIMITIVE_NEW, + customize="[workflow]\n" + _layer("blind", "bmad-review"), + ) + for skill in ("bmad-review", "bmad-review-edge-case-hunter"): + _install_skills(tmp_path / "shared", "skills", {skill: ()}) + _link_dir(repo / tree / skill, tmp_path / "shared" / "skills" / skill) + + assert install_mod.skill_trees_outside(repo, repo, [tree], isolation="none") == [] + assert install_mod.skill_trees_outside(repo, repo, [tree], isolation="worktree") == [ + Finding( + "skills.tree-outside", + "problem", + mock.ANY, + { + "tree": tree, + "skill": "bmad-review", + "target": str((tmp_path / "shared" / "skills" / "bmad-review").resolve()), + "isolation": "worktree", + }, + ) + ] + + +def test_skill_tree_outside_skips_linked_advisory_reviewer(tmp_path): + """A `when`-gated reviewer linked to a shared install may never run, so the + worktree gate does not require it (`base_skills_seed_incomplete`) and neither + does this check — while a required reviewer linked the same way still is. + + Ablation: check `_review_skill_names` instead of `required_review_skill_names` + in `skill_trees_outside` and the advisory link is reported too.""" + repo, tree = tmp_path / "repo", ".claude/skills" + advisory = "bmad-review-performance" + _install_dev_auto( + repo, + tree, + skill=DEV_PRIMITIVE_NEW, + customize="[workflow]\n" + + _layer("blind", "bmad-review") + + _layer("perf", advisory, when="the diff touches hot paths"), + ) + _install_skills(repo, tree, {"bmad-review": ()}) + _install_skills(tmp_path / "shared", "skills", {advisory: ()}) + _link_dir(repo / tree / advisory, tmp_path / "shared" / "skills" / advisory) + + assert missing_base_skills(repo, [tree]) == [] + assert install_mod.skill_trees_outside(repo, repo, [tree], isolation="worktree") == [] + + shutil.rmtree(repo / tree / "bmad-review") + _install_skills(tmp_path / "shared", "skills", {"bmad-review": ()}) + _link_dir(repo / tree / "bmad-review", tmp_path / "shared" / "skills" / "bmad-review") + assert [ + f.detail["skill"] + for f in install_mod.skill_trees_outside(repo, repo, [tree], isolation="worktree") + ] == ["bmad-review"] + + +def test_skill_tree_outside_ignores_in_repo_link(tmp_path): + """The `skills` CLI's own layout — `.claude/skills` linked to `.agents/skills` — + stays inside the repo, so neither the tree nor its skills are reported, even + under worktree isolation. + + Ablation: make either `_confined_to` comparison in `skill_trees_outside` always + False and this reddens.""" + repo = tmp_path / "repo" + _install_dev_auto( + repo, + ".agents/skills", + skill=DEV_PRIMITIVE_NEW, + customize="[workflow]\n" + _layer("blind", "bmad-review"), + ) + _install_skills(repo, ".agents/skills", {"bmad-review": ()}) + _link_dir(repo / ".claude" / "skills", repo / ".agents" / "skills") + + for isolation in ("none", "worktree"): + assert ( + install_mod.skill_trees_outside( + repo, repo, [".claude/skills", ".agents/skills"], isolation=isolation + ) + == [] + ) + + @pytest.mark.parametrize( "resolve_fault", [pytest.param(None, id="oserror"), *NUL_PATH_RESOLVE_FAULTS] ) @@ -13046,46 +13278,329 @@ def test_review_remediation_names_core_tools(tmp_path): assert "core-tools" in derived[0].message -@pytest.mark.parametrize("root", [".claude/skills", ".agents/skills"]) -def test_outside_copy_hint_on_base_missing(tmp_path, root): - """A global (`npx skills add -g`) copy is named as a hint — the run still - refuses, because bmad-loop drives only the project's own tree.""" +@pytest.mark.parametrize( + ("profile", "root"), + [ + ("claude", ".claude/skills"), + ("codex", ".agents/skills"), + ("codex", ".codex/skills"), + ("gemini", ".gemini/skills"), + ("copilot", ".copilot/skills"), + ], +) +def test_home_hint_names_a_copy_in_the_profiles_own_root(tmp_path, profile, root): + """Switch off, a copy in one of the CLI's own user roots is named as a hint that + offers `[skills] user_roots` — the run still refuses.""" home = tmp_path / "home" project = tmp_path / "project" - tree = get_profile("claude").skill_tree + scope = _user_scope(profile, home, on=False) - bare = missing_base_skills(project, [tree], home=home) + bare = missing_base_skills(project, [scope]) assert "outside" not in bare[0].detail assert "a copy exists" not in bare[0].message _install_skills(home, root, {DEV_PRIMITIVE_NEW: ()}) - problems = missing_base_skills(project, [tree], home=home) + problems = missing_base_skills(project, [scope]) assert [p.check for p in problems] == ["skills.base-missing"] expected = PurePosixPath("~", root, DEV_PRIMITIVE_NEW).as_posix() assert problems[0].detail["outside"] == expected assert expected in problems[0].message + assert "`[skills] user_roots = true`" in problems[0].message assert "npx skills add" in problems[0].message -def test_outside_copy_hint_on_review_findings(tmp_path): +def test_home_hint_ignores_a_root_the_profile_does_not_load(tmp_path): + """claude loads only `~/.claude/skills`: a copy in `~/.agents/skills` is no hint, + since setting the switch would not make claude load it. + + Ablation: add `"~/.agents/skills"` to claude.toml's `[user_skills] roots` and + the hint appears.""" + home = tmp_path / "home" + _install_skills(home, ".agents/skills", {DEV_PRIMITIVE_NEW: ()}) + problems = missing_base_skills(tmp_path / "project", [_user_scope("claude", home, on=False)]) + + assert [p.check for p in problems] == ["skills.base-missing"] + assert "outside" not in problems[0].detail + assert "a copy exists" not in problems[0].message + + +def test_home_hint_on_review_findings(tmp_path): home = tmp_path / "home" project = tmp_path / "project" - tree = get_profile("claude").skill_tree + scope = _user_scope("claude", home, on=False) + tree = scope.tree _install_skills(home, ".claude/skills", {"bmad-review": (), **{h: () for h in _HUNTERS}}) _install_dev_auto(project, tree, skill=DEV_PRIMITIVE_NEW, customize=LAYER_CUSTOMIZE) - derived = missing_base_skills(project, [tree], home=home) + derived = missing_base_skills(project, [scope]) assert derived[0].detail["outside"] == "~/.claude/skills/bmad-review" _install_dev_auto(project, tree, skill=DEV_PRIMITIVE_NEW, customize="x\n") - fallback = missing_base_skills(project, [tree], home=home) + fallback = missing_base_skills(project, [scope]) assert {f.detail["outside"] for f in fallback} == {f"~/.claude/skills/{h}" for h in _HUNTERS} -def test_outside_copy_unresolvable_home_is_no_hint(monkeypatch): - def no_home(): - raise RuntimeError("Could not determine home directory.") +def test_home_hint_absent_without_a_home_or_for_a_plain_tree(tmp_path): + """No determinable home is no hint, and a plain tree string declares no user + roots, so it never probes the home directory at all.""" + project = tmp_path / "project" + no_home = missing_base_skills(project, [_user_scope("claude", None, on=False)]) + assert "outside" not in no_home[0].detail + plain = missing_base_skills(project, [get_profile("claude").skill_tree]) + assert "outside" not in plain[0].detail + + +# --- user-level skill roots through SkillScope --------------------------------- + + +def _user_scope(profile, home, *, on, environ=None): + """``profile``'s scope over a pinned ``home`` and environment.""" + from bmad_loop.skill_locate import scope_for + + return scope_for(get_profile(profile), resolve_user=on, home=home, environ=environ or {}) + + +def test_scope_global_only_install_resolves_from_the_user_root(tmp_path): + """Switch on: a global-only primitive resolves (no base-missing) and the findings + about that copy name its root; a plain string still reports today's base-missing.""" + home, project = tmp_path / "home", tmp_path / "project" + project.mkdir() + # truncated primitive (no step-04) plus the merged reviewer, all in ~/.agents/skills + _install_skills( + home, ".agents/skills", {DEV_PRIMITIVE_NEW: ("customize.toml",), "bmad-review": ()} + ) + scope = _user_scope("codex", home, on=True) + + findings = missing_base_skills(project, [scope]) + + assert [f.check for f in findings] == ["skills.base-incomplete"] + assert findings[0].detail["root"] == "~/.agents/skills" + assert findings[0].detail["tree"] == ".agents/skills" + assert findings[0].message.startswith(f"~/.agents/skills/{DEV_PRIMITIVE_NEW} is incomplete") + assert resolve_dev_primitive(project, scope) == DEV_PRIMITIVE_NEW + # the plain string, and the switch off, never resolve from home + assert [f.check for f in missing_base_skills(project, [".agents/skills"])] == [ + "skills.base-missing" + ] + assert resolve_dev_primitive(project, _user_scope("codex", home, on=False)) is None + + +def test_scope_missing_primitive_names_searched_roots_and_the_home_hint(tmp_path): + home, project = tmp_path / "home", tmp_path / "project" + project.mkdir() + + [on] = missing_base_skills(project, [_user_scope("codex", home, on=True)]) + assert on.check == "skills.base-missing" + assert on.detail["searched"] == [".agents/skills", "~/.agents/skills", "~/.codex/skills"] + assert "outside" not in on.detail + + _install_skills(home, ".codex/skills", {DEV_PRIMITIVE_NEW: ()}) + [off] = missing_base_skills(project, [_user_scope("codex", home, on=False)]) + assert off.check == "skills.base-missing" + assert "searched" not in off.detail + assert off.detail["outside"] == f"~/.codex/skills/{DEV_PRIMITIVE_NEW}" + assert "which this CLI loads" in off.message + assert "`[skills] user_roots = true`" in off.message + + +def _shadow_layout(tmp_path, tree, home_root): + home, project = tmp_path / "home", tmp_path / "project" + install_build_auto_skill(project, tree) + _install_skills(home, home_root, {DEV_PRIMITIVE_NEW: ()}) + return home, project + + +def _checks(findings, check): + return [f for f in findings if f.check == check] + + +def test_user_shadow_claude_personal_copy_overrides_with_the_switch_off(tmp_path): + home, project = _shadow_layout(tmp_path, ".claude/skills", ".claude/skills") + + off = missing_base_skills(project, [_user_scope("claude", home, on=False)]) + [shadow] = _checks(off, "skills.user-shadow") + assert shadow.severity == "warning" + assert shadow.detail == { + "tree": ".claude/skills", + "skill": DEV_PRIMITIVE_NEW, + "checked": f".claude/skills/{DEV_PRIMITIVE_NEW}", + "other": f"~/.claude/skills/{DEV_PRIMITIVE_NEW}", + "precedence": "user", + "kind": "overrides", + } + # switch on: the checks read the personal copy itself, so nothing is shadowed + on = missing_base_skills(project, [_user_scope("claude", home, on=True)]) + assert not _checks(on, "skills.user-shadow") + # a plain string never looks at home + assert not _checks(missing_base_skills(project, [".claude/skills"]), "skills.user-shadow") + + +def test_user_shadow_codex_unordered_copies_compete(tmp_path): + home, project = _shadow_layout(tmp_path, ".agents/skills", ".agents/skills") + + for on in (False, True): + findings = missing_base_skills(project, [_user_scope("codex", home, on=on)]) + [shadow] = _checks(findings, "skills.user-shadow") + assert shadow.detail["kind"] == "competes" + assert shadow.detail["precedence"] == "unordered" + + +def test_user_shadow_gemini_project_precedence_is_no_shadow(tmp_path): + """Negative: gemini's workspace copy wins, so a user copy shadows nothing. + Ablation: drop the precedence test in skill_locate.shadow and this fails.""" + home, project = _shadow_layout(tmp_path, ".agents/skills", ".agents/skills") + + for on in (False, True): + findings = missing_base_skills(project, [_user_scope("gemini", home, on=on)]) + assert not _checks(findings, "skills.user-shadow") + + +def test_user_root_unavailable_is_reported_only_with_the_switch_on(tmp_path): + home, project = tmp_path / "home", tmp_path / "project" + install_build_auto_skill(project, ".agents/skills") + environ = {"CODEX_HOME": str(tmp_path / "codex")} + + off = missing_base_skills(project, [_user_scope("codex", home, on=False, environ=environ)]) + assert not _checks(off, "skills.user-root-unavailable") + + on = missing_base_skills(project, [_user_scope("codex", home, on=True, environ=environ)]) + [finding] = _checks(on, "skills.user-root-unavailable") + assert finding.severity == "warning" + assert finding.detail == { + "tree": ".agents/skills", + "root": "~/.codex/skills", + "reason": "env:CODEX_HOME", + } + assert "CODEX_HOME is set" in finding.message + + +def _bmod_method(root, tree, version): + d = root / tree / "bmod-method" + d.mkdir(parents=True, exist_ok=True) + (d / "SKILL.md").write_text("# bmod-method\n", encoding="utf-8") + (d / "bmod.toml").write_text(f'[bmod]\nversion = "{version}"\n', encoding="utf-8") + + +def test_user_root_version_skew_warns_when_module_records_differ(tmp_path): + home, project = tmp_path / "home", tmp_path / "project" + install_build_auto_skill(project, ".agents/skills") + _bmod_method(project, ".agents/skills", "6.13.0") + _bmod_method(home, ".agents/skills", "6.13.0") + scope = _user_scope("codex", home, on=True) + + assert not _checks(missing_base_skills(project, [scope]), "skills.user-root-version-skew") + + _bmod_method(home, ".agents/skills", "6.12.0") + [skew] = _checks(missing_base_skills(project, [scope]), "skills.user-root-version-skew") + assert skew.severity == "warning" + assert skew.detail == { + "tree": ".agents/skills", + "root": "~/.agents/skills", + "user_version": "6.12.0", + "project_version": "6.13.0", + } + # the project record still answers the display-only version + assert install_mod.bmod_method_version(project, [scope]) == "6.13.0" + + +def test_render_probe_stages_a_user_root_primitive(tmp_path): + project, marker, primitive = _probe_project(tmp_path, RENDER_PROBE_OK_BODY, ".agents/skills") + home = tmp_path / "home" + (home / ".agents/skills").mkdir(parents=True) + shutil.move(primitive, home / ".agents/skills" / DEV_PRIMITIVE_NEW) + scope = _user_scope("codex", home, on=True) + + [finding] = dev_renderer_probe(project, [scope]) + + assert finding.severity == "ok", finding.message + assert finding.detail["root"] == "~/.agents/skills" + assert finding.message.startswith(f"~/.agents/skills/{DEV_PRIMITIVE_NEW} renders cleanly") + ran = json.loads(marker.read_text(encoding="utf-8")) + assert Path(ran["skill"]) == Path(ran["root"]) / ".agents/skills" / DEV_PRIMITIVE_NEW + assert ran["skill_md"] is True + # switch off: the project tree has no primitive, so there is nothing to render + [off] = dev_renderer_probe(project, [_user_scope("codex", home, on=False)]) + assert off.detail == {"trees": [".agents/skills"]} + + +def test_review_layers_read_the_user_copy_with_project_local_overrides(tmp_path): + home, project = tmp_path / "home", tmp_path / "project" + project.mkdir() + _install_dev_auto(home, ".agents/skills", skill=DEV_PRIMITIVE_NEW, customize=LAYER_CUSTOMIZE) + extra = ( + '[[workflow.review_layers]]\nid = "extra"\n' + 'instruction = "Invoke the `bmad-review-extra` skill on this diff"\n' + ) + override = project / install_mod.CUSTOMIZE_DIR / f"{DEV_PRIMITIVE_NEW}.toml" + override.parent.mkdir(parents=True) + override.write_text(extra, encoding="utf-8") + # an override beside the user copy is not the project's and is never read + stray = home / install_mod.CUSTOMIZE_DIR / f"{DEV_PRIMITIVE_NEW}.toml" + stray.parent.mkdir(parents=True) + stray.write_text(extra.replace("extra", "stray"), encoding="utf-8") + scope = _user_scope("codex", home, on=True) + + resolved = resolve_review_layers(project, scope) + + assert resolved is not None + assert set(resolved.required) == {"bmad-review", "bmad-review-extra"} + assert resolve_review_layers(project, _user_scope("codex", home, on=False)) is None + + +def test_user_root_skill_ids_keep_only_bmad_module_skills(tmp_path): + """A personal skill in the same root stays out. Ablation: collect every folder of + the user root instead of the candidates + module records and this fails.""" + home, project = tmp_path / "home", tmp_path / "project" + project.mkdir() + _install_skills( + home, + ".agents/skills", + {DEV_PRIMITIVE_NEW: (), "bmad-agent-po": (), "my-notes": (), "bmad-loop-sweep": ()}, + ) + _bmod_method(home, ".agents/skills", "6.13.0") + record = home / ".agents/skills/bmod-method/bmod.toml" + record.write_text( + '[bmod]\nversion = "6.13.0"\nskills = ["bmad-agent-po", "../escape", "*"]\n', + encoding="utf-8", + ) + # the project copy of the sweep skill wins under codex's project-first lookup + _install_skills(project, ".agents/skills", {"bmad-loop-sweep": ()}) + scope = _user_scope("codex", home, on=True) + + ids = install_mod.user_root_skill_ids(project, scope, "bmad-loop-sweep") + + assert DEV_PRIMITIVE_NEW in ids and "bmad-agent-po" in ids + assert "my-notes" not in ids + assert "bmad-loop-sweep" not in ids + assert not any(".." in i or "*" in i for i in ids) + assert install_mod.user_root_skill_ids(project, _user_scope("codex", home, on=False)) == () + + +def test_skill_root_findings_name_the_resolving_root(tmp_path): + home, project = tmp_path / "home", tmp_path / "project" + project.mkdir() + _install_skills(home, ".agents/skills", {**_era_catalog(DEV_PRIMITIVE_NEW), "bmad-review": ()}) + scope = _user_scope("codex", home, on=True) + + lines = install_mod.skill_root_findings(project, [scope]) + + assert lines and all(f.check == "skills.root" and f.severity == "ok" for f in lines) + by_skill = {f.detail["skill"]: f.detail for f in lines} + assert by_skill[DEV_PRIMITIVE_NEW] == { + "tree": ".agents/skills", + "skill": DEV_PRIMITIVE_NEW, + "root": "~/.agents/skills", + "origin": "user", + } + # never part of the preflight's finding list + assert not _checks(missing_base_skills(project, [scope]), "skills.root") + + +def test_skill_trees_outside_skips_user_root_skills(tmp_path): + home, project = tmp_path / "home", tmp_path / "project" + project.mkdir() + _install_skills(home, ".agents/skills", {**_era_catalog(DEV_PRIMITIVE_NEW), "bmad-review": ()}) + scope = _user_scope("codex", home, on=True) - monkeypatch.setattr(install_mod, "_outside_home", no_home) - assert install_mod._outside_copy(DEV_PRIMITIVE_NEW) is None + assert install_mod.skill_trees_outside(project, project, [scope], isolation="worktree") == [] diff --git a/tests/test_opencode_http.py b/tests/test_opencode_http.py index ded2a14f8..55a7d57b5 100644 --- a/tests/test_opencode_http.py +++ b/tests/test_opencode_http.py @@ -4440,6 +4440,50 @@ def test_v2_spawn_crumbs_refused_wildcard_skill_ids(tmp_path, v2_fake): assert [c["ids"] for c in crumbs] == [["*"]] +def test_v1_spawn_refuses_a_session_needing_user_root_skills(tmp_path, fake_opencode): + """opencode 1.x runs with OPENCODE_DISABLE_EXTERNAL_SKILLS, so a skill the + engine located in a user root could never load: the session is refused + before any server starts, naming the skills and both ways out.""" + launcher, rec = fake_opencode + adapter = make_adapter(tmp_path, binary=str(launcher)) + spec = make_spec(tmp_path, rec, "completed", user_skill_ids=("bmad-build-auto",)) + + with pytest.raises(OpencodeServerError, match="cannot load skills from user roots") as exc: + adapter.start_session(spec) + + assert "bmad-build-auto" in str(exc.value) and "2.x" in str(exc.value) + assert not (tmp_path / "run" / "logs" / "t-1.server.out").exists() + + +def test_v2_spawn_allows_and_crumbs_the_user_root_skill_ids(tmp_path, v2_fake): + """On 2.x the user-root ids join the allow-list after the project ids, and + the spawn records which ones in the lifecycle log.""" + launcher, rec = v2_fake + adapter = make_adapter(tmp_path, binary=str(launcher)) + spec = make_spec(tmp_path, rec, "completed", user_skill_ids=("bmad-build-auto",)) + + result = adapter.run(spec) + + assert result.status == "completed" + crumbs = [c for c in _lifecycle(tmp_path) if c["event"] == "skill-ids-user-allowed"] + assert [c["ids"] for c in crumbs] == [["bmad-build-auto"]] + rules = json.loads(adapter._config_content(spec, V2Protocol()))["permissions"] + assert rules[-1] == {"action": "skill", "resource": "bmad-build-auto", "effect": "allow"} + + +def test_config_content_lists_an_existing_agents_skill_tree(tmp_path): + """The opencode profile's extra tree (``.agents/skills``, where the skills + CLI installs opencode's project skills) joins the config once it exists.""" + (tmp_path / ".agents" / "skills").mkdir(parents=True) + adapter = make_adapter(tmp_path) + spec = SessionSpec(task_id="t", role="triage", prompt="p", cwd=tmp_path) + config = json.loads(adapter._config_content(spec)) + assert config["skills"]["paths"] == [ + str(tmp_path / ".claude" / "skills"), + str(tmp_path / ".agents" / "skills"), + ] + + def test_v2_completed_scenario_end_to_end(tmp_path, v2_fake, monkeypatch): """A 2.x `--version` picks the V2 codec and one session runs to completion over `/api/*`: create with the task title and the project as its location, diff --git a/tests/test_opencode_protocol.py b/tests/test_opencode_protocol.py index da73414b6..398d9a896 100644 --- a/tests/test_opencode_protocol.py +++ b/tests/test_opencode_protocol.py @@ -192,6 +192,77 @@ def test_v2_config_never_reallows_a_wildcard_skill_id(tmp_path): assert V1Protocol().refused_skill_ids(skill_dir) == [] +def test_v2_config_reads_every_project_tree_then_the_user_root_ids(tmp_path): + """Under ``[skills] user_roots`` the V2 recipe lists both project trees in + ``skills`` — primary last, since V2 lets the later explicit source supply a + duplicate id and the locator resolves the primary copy — and re-allows, after the deny-all, every project id of both + trees and then the user-root BMAD ids the engine located — an id present + twice is allowed once, and no user path is added (V2 scans those roots + itself).""" + primary = tmp_path / ".claude" / "skills" + extra = tmp_path / ".agents" / "skills" + _skill(primary, "bmad-dev-auto", "bmad-dev-auto") + _skill(extra, "bmad-review-adversarial", "bmad-review-adversarial") + _skill(extra, "bmad-dev-auto", "bmad-dev-auto") + + config = json.loads( + V2Protocol().config_content( + _spec(tmp_path), + primary, + extra_skill_dirs=[extra], + user_skill_ids=("bmad-build-auto", "bmad-review-adversarial"), + ) + ) + + assert config["skills"] == [str(extra), str(primary)] + rules = config["permissions"] + skill_rules = [r for r in rules if r["action"] == "skill"] + assert skill_rules == [ + {"action": "skill", "resource": "*", "effect": "deny"}, + {"action": "skill", "resource": "bmad-dev-auto", "effect": "allow"}, + {"action": "skill", "resource": "bmad-review-adversarial", "effect": "allow"}, + {"action": "skill", "resource": "bmad-build-auto", "effect": "allow"}, + ] + assert rules.index(skill_rules[0]) < min(rules.index(r) for r in skill_rules[1:]) + + +@pytest.mark.skipif(sys.platform == "win32", reason="`*` and `?` are not legal in Windows names") +def test_v2_config_never_reallows_a_wildcard_id_from_an_extra_tree_or_a_user_root(tmp_path): + """The wildcard refusal covers every source of an allow: an extra-tree + directory named ``?x`` and a user-root id ``*`` stay denied and are named + for the spawn crumb.""" + primary = tmp_path / ".claude" / "skills" + extra = tmp_path / ".agents" / "skills" + _skill(primary, "plain-skill", "plain-skill") + _skill(extra, "?x", "?x") + kw = {"extra_skill_dirs": [extra], "user_skill_ids": ("*", "bmad-build-auto")} + + rules = json.loads(V2Protocol().config_content(_spec(tmp_path), primary, **kw))["permissions"] + + assert [r["resource"] for r in rules if r["action"] == "skill"] == [ + "*", + "plain-skill", + "bmad-build-auto", + ] + assert [r["effect"] for r in rules if r["action"] == "skill"] == ["deny", "allow", "allow"] + assert V2Protocol().refused_skill_ids(primary, **kw) == ["?x", "*"] + + +def test_v1_config_lists_every_project_tree_and_ignores_user_ids(tmp_path): + """V1 keeps OPENCODE_DISABLE_EXTERNAL_SKILLS and widens only + ``skills.paths`` to both project trees; user-root ids never reach a 1.x + config (the adapter refuses that session at spawn).""" + primary = tmp_path / ".claude" / "skills" + extra = tmp_path / ".agents" / "skills" + config = json.loads( + V1Protocol().config_content( + _spec(tmp_path), primary, extra_skill_dirs=[extra], user_skill_ids=("bmad-x",) + ) + ) + assert config == {"permission": "allow", "skills": {"paths": [str(primary), str(extra)]}} + assert V1Protocol().extra_env() == {"OPENCODE_DISABLE_EXTERNAL_SKILLS": "1"} + + def test_v2_decode_frame_reads_data_envelope(): """V2 frames carry the session id under `data`, not V1's `properties`.""" v2 = V2Protocol() @@ -589,8 +660,7 @@ def test_v2_tool_failure_and_nonzero_exit_are_on_the_line(): ] ) assert lines == [ - f'{_G}[bmad] tool: shell {{"command": "rm -rf x"}} -> error: ' - f"permission.rejected: no{_R}\n", + f'{_G}[bmad] tool: shell {{"command": "rm -rf x"}} -> error: permission.rejected: no{_R}\n', f'{_G}[bmad] tool: shell {{"command": "exit 1"}} -> exit 1{_R}\n', ] diff --git a/tests/test_platform_util.py b/tests/test_platform_util.py index 5da3666e9..c50119b30 100644 --- a/tests/test_platform_util.py +++ b/tests/test_platform_util.py @@ -215,6 +215,21 @@ def test_names_win32_alias_leaves_the_root_and_parent_spellings_to_its_siblings( assert platform_util.names_win32_alias(value) is False +@pytest.mark.parametrize( + "value", ["~", "~/.agents/skills", "~\\.agents\\skills", "~user/skills", "~/", "~x"] +) +def test_names_home_ref_catches_home_spellings(value): + # Nothing expands `~`: every row resolves to a literal `/~...` dir. + assert platform_util.names_home_ref(value) is True + + +@pytest.mark.parametrize("value", ["PROGRA~1/x", "a/~b", ".claude/skills", "skills~", "x\\~y", ""]) +def test_names_home_ref_accepts_tilde_mid_name(value): + # Only the FIRST component counts: a Win32 short name or a `~` deeper in the + # path is an ordinary name. + assert platform_util.names_home_ref(value) is False + + # --------------------------------------------------------------- is_wsl_unc_path diff --git a/tests/test_policy.py b/tests/test_policy.py index 3591adff2..782ba6c30 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -653,6 +653,21 @@ def test_git_timeout_default_parse_and_template(): assert doc["limits"]["git_timeout_s"] == 120 +def test_skills_user_roots_default_parse_and_template(): + import tomllib + + assert policy.loads("").skills == policy.SkillsPolicy() + assert policy.loads("").skills.user_roots is False + assert policy.loads("[skills]\nuser_roots = true\n").skills.user_roots is True + with pytest.raises(policy.PolicyError, match=r"skills\.user_roots must be a boolean"): + policy.loads('[skills]\nuser_roots = "yes"\n') + # the emitted template documents the knob, commented out at its default + assert "\n[skills]\n" in policy.POLICY_TEMPLATE + assert "\n# user_roots = false\n" in policy.POLICY_TEMPLATE + assert tomllib.loads(policy.POLICY_TEMPLATE)["skills"] == {} + assert policy.loads(policy.POLICY_TEMPLATE).skills == policy.SkillsPolicy() + + def test_artifact_publication_limits_parse_validate_and_render(): import tomllib @@ -977,6 +992,7 @@ def test_array_policy_fields_keep_unset_distinct_from_empty(): ("tui", "low_frame_rate"), ("operator", "enabled"), ("mux", "honor_ambient_psmux_data_dir"), + ("skills", "user_roots"), ] diff --git a/tests/test_portability_guard.py b/tests/test_portability_guard.py index d56f3f370..d255455e6 100644 --- a/tests/test_portability_guard.py +++ b/tests/test_portability_guard.py @@ -346,6 +346,12 @@ ("cli.py", "_reject_plugin_trust"), ("cli.py", "_reject_under_floor_git"), ("engine.py", "_refuse_gated_story"), + # #770: a prompt skill that a pre_session hook's env hid from the CLI or swapped + # for another copy; test_engine.py + # test_session_user_roots_resolve_against_the_post_hook_env[hook-set], + # test_session_refuses_when_a_hook_swaps_the_primitive_for_another_copy, and + # test_session_refuses_when_a_hook_hides_a_required_review_skill + ("engine.py", "_refuse_hook_changed_skill"), ("platform_util.py", "_refuse_unwritable_target"), ("platform_util.py", "_refuse_unwritable_target_at"), # #810: a named or wrong-typed [engine] block; test_policy.py @@ -1095,6 +1101,9 @@ # `ts`-shaped float the TUI ages the `· idle ` text from. "since_ts", "site", + # `skill-user-root` (#770): a plain skill id, bound by + # `install._SKILL_ID_RE` — never a path or free text. + "skill", "skip", "spec_folder", # DW-522: whether `story-reverify-armed` copied the stashed spec back (a @@ -1174,6 +1183,8 @@ "models_unresolved", "verification_sequence", "verification_stage", + # `skill-user-root` (#770): a module record's `[bmod] version` string. + "version", "via", # `session-start-missing`: whole seconds the session had run without a # SessionStart when the notice fired — a measured integer. @@ -1797,6 +1808,11 @@ "session-rescued-post-kill", "session-start", "session-synthesized-from-frontmatter", + # `[skills] user_roots` (#770): one row per module skill a session's CLI + # loads from a user root — `task_id`, `role`, `skill` (a plain skill id), + # `root` (the root's `~/` spelling, dropped) and `version` (its module + # record's `[bmod] version`). + "skill-user-root", "spec-deferral-sighting-stale", "spec-deferrals-harvested", "spec-deferrals-malformed", @@ -2456,6 +2472,10 @@ "worktree-opened", "worktree-seed-dropped", "worktree-seed-skipped", + # #770: required skills the seed gate exempted because they resolve from a + # user root; `entries` is benign (scrub_json), as on + # `worktree-module-skills-dropped`. + "worktree-skills-user-root", "worktree-teardown-degraded", # DW-390 workspace-trust seeding: `key` is benign, `path` and `reason` # are presence-only in `diagnostics._JOURNAL_DROP_FIELDS`. diff --git a/tests/test_profile.py b/tests/test_profile.py index db8537af5..dd7f55a8a 100644 --- a/tests/test_profile.py +++ b/tests/test_profile.py @@ -20,6 +20,7 @@ load_profiles, parse_cli_version, ) +from bmad_loop.skill_locate import UserSkillRoot, UserSkillsSpec MINIMAL_PROFILE = """ name = "mycli" @@ -1181,6 +1182,30 @@ def test_render_prompt_passthrough_and_template(): assert claude.render_prompt("just do it") == "just do it" +def test_render_prompt_skill_dir_default_is_the_pre_placeholder_text(): + """copilot's `{skill_dir}` defaults to `/`, so a spec with no + located folder renders byte-identically to the pre-placeholder template — + including the `.agents/skills//SKILL.md` spelling of a slashless prompt — and + a given `skill_dir` substitutes. Ablation: default `skill_dir` to `""` (or drop + the default) and the byte-identity rows FAIL.""" + copilot = get_profile("copilot") + tail = ( + ", read its entire contents and follow its directions exactly, using subagents as needed: " + ) + assert copilot.render_prompt("/bmad-dev-auto 1-1-a") == ( + f"LOAD the FULL .agents/skills/bmad-dev-auto/SKILL.md{tail}1-1-a" + ) + assert copilot.render_prompt("just do it") == ( + f"LOAD the FULL .agents/skills//SKILL.md{tail}just do it" + ) + assert copilot.render_prompt("/bmad-dev-auto 1-1-a", skill_dir="/home/u/.agents/skills/x") == ( + f"LOAD the FULL /home/u/.agents/skills/x/SKILL.md{tail}1-1-a" + ) + # a template without the placeholder ignores it + claude = get_profile("claude") + assert claude.render_prompt("/bmad-dev-auto 1-1-a", skill_dir="/x") == "/bmad-dev-auto 1-1-a" + + _BYPASS = ("--permission-mode", "bypassPermissions") @@ -1492,6 +1517,24 @@ def test_user_profile_overlay(tmp_path): MINIMAL_PROFILE.replace("[hooks]", 'parked_prompt_patterns = "Enter"\n[hooks]'), "parked_prompt_patterns must be a list of strings", ), + # a leading `~` is never expanded: each field resolves it to a literal + # `/~/...` directory, so it is refused with its own message (#770) + ( + MINIMAL_PROFILE.replace("[hooks]", 'skill_tree = "~/.agents/skills"\n[hooks]'), + "skill_tree must not start with '~': a leading '~' is not expanded", + ), + ( + MINIMAL_PROFILE.replace( + 'config_path = ".mycli/settings.json"', 'config_path = "~/.mycli/settings.json"' + ), + "hooks.config_path must not start with '~': a leading '~' is not expanded", + ), + ( + MINIMAL_PROFILE.replace( + "[hooks]", 'seed_files = [".mcp.json", "~/.mcp.json"]\n[hooks]' + ), + "seed_files entries must not start with '~': a leading '~' is not expanded", + ), ], ) def test_invalid_profiles_rejected(tmp_path, mutation, match): @@ -1906,6 +1949,13 @@ def test_profile_scan_failure_degrades(profile_scan): ({"seed_files": ("/etc/passwd",)}, "seed_files"), ({"seed_files": (".",)}, "seed_files"), ({"hooks": HookSpec("claude-settings-json", "..", {"Stop": "Stop"})}, "relative"), + # a leading `~` is not expanded (#770) + ({"skill_tree": "~/.agents/skills"}, "skill_tree must not start with '~'"), + ({"seed_files": ("~/.mcp.json",)}, "seed_files entries must not start with '~'"), + ( + {"hooks": HookSpec("claude-settings-json", "~\\.m\\s.json", {"Stop": "Stop"})}, + "hooks.config_path must not start with '~'", + ), # a real dialect with nothing to write to ({"hooks": HookSpec("claude-settings-json", "", {"Stop": "Stop"})}, "config_path"), # hookless carrying hook plumbing is a contradiction either way in @@ -2148,3 +2198,325 @@ def test_workspace_trust_value_rejections_on_both_routes(tmp_path, settings_path ) with pytest.raises(ProfileError, match="workspace_trust"): profile_mod._validate_profile(constructed, "entry point test") + + +# ------------------------------------- [user_skills] + extra_skill_trees (#770) + + +def _toml_str(value: str) -> str: + # a TOML basic string; json.dumps escapes exactly what TOML needs here + return json.dumps(value) + + +def _user_skills_table(spec: UserSkillsSpec) -> str: + roots = ", ".join( + "{ path = %s, disabled_by = [%s] }" + % (_toml_str(r.path), ", ".join(_toml_str(v) for v in r.disabled_by)) + for r in spec.roots + ) + return f"\n[user_skills]\nprecedence = {_toml_str(spec.precedence)}\nroots = [{roots}]\n" + + +def _write_mycli(tmp_path: Path, text: str) -> Path: + profiles_dir = tmp_path / ".bmad-loop" / "profiles" + profiles_dir.mkdir(parents=True, exist_ok=True) + (profiles_dir / "mycli.toml").write_text(text, encoding="utf-8") + return tmp_path + + +def _assert_entry_point_refused(profile_scan, match: str, **over) -> None: + profile_scan(_FakeEntryPoint("acme", lambda: [_plugin_profile(**over)])) + profiles = load_profiles() + assert "acme" not in profiles, "an invalid profile must never reach the map" + assert match in profile_mod.external_profile_errors()["acme"] + + +def test_default_profile_declares_no_extra_trees_and_no_user_skills(tmp_path): + """Off by default on every route that does not opt in: a constructed profile + (entry point) and a TOML overlay that omits both keys.""" + constructed = CLIProfile(name="x", binary="x", hooks=HookSpec("none", "", {})) + assert constructed.extra_skill_trees == () + assert constructed.user_skills is None + overlay = load_profiles(_write_mycli(tmp_path, MINIMAL_PROFILE))["mycli"] + assert overlay.extra_skill_trees == () + assert overlay.user_skills is None + + +_PACKAGED_USER_SKILLS = { + "claude": UserSkillsSpec("user", (UserSkillRoot("~/.claude/skills", ("CLAUDE_CONFIG_DIR",)),)), + "codex": UserSkillsSpec( + "unordered", + (UserSkillRoot("~/.agents/skills"), UserSkillRoot("~/.codex/skills", ("CODEX_HOME",))), + ), + "gemini": UserSkillsSpec( + "project", + ( + UserSkillRoot("~/.agents/skills", ("GEMINI_CLI_HOME",)), + UserSkillRoot("~/.gemini/skills", ("GEMINI_CLI_HOME",)), + ), + ), + "antigravity": UserSkillsSpec("unordered", (UserSkillRoot("~/.gemini/config/skills"),)), + "copilot": UserSkillsSpec( + "project", + ( + UserSkillRoot("~/.copilot/skills", ("COPILOT_HOME",)), + UserSkillRoot("~/.agents/skills", ("COPILOT_HOME",)), + ), + ), + "opencode-http": UserSkillsSpec( + "project", + ( + UserSkillRoot("~/.config/opencode/skills", ("XDG_CONFIG_HOME",)), + UserSkillRoot("~/.agents/skills"), + UserSkillRoot("~/.claude/skills"), + ), + ), +} + + +def test_packaged_profiles_declare_their_user_skill_roots(): + """Every shipped profile parses to exactly its documented `[user_skills]` + spec — order matters (it is the CLI's read order) — and only opencode-http + declares an extra project skill tree (`.agents/skills`, where the skills + CLI installs opencode's project skills).""" + packaged = { + tomllib.loads(entry.read_text(encoding="utf-8"))["name"] + for entry in resources.files("bmad_loop.data").joinpath("profiles").iterdir() + if entry.name.endswith(".toml") + } + # the map covers every shipped profile, so a new one must state its roots here + assert packaged == set(_PACKAGED_USER_SKILLS) + profiles = load_profiles() + assert {name: profiles[name].user_skills for name in packaged} == _PACKAGED_USER_SKILLS + extra = {"opencode-http": (".agents/skills",)} + for name in packaged: + assert profiles[name].extra_skill_trees == extra.get(name, ()), name + + +def test_user_skills_parses_string_and_table_roots(tmp_path): + table = ( + "\n[user_skills]\n" + 'precedence = "unordered"\n' + 'roots = ["~/.mycli/skills", { path = "~/.agents/skills", disabled_by = ["MYCLI_HOME"] }]\n' + ) + spec = load_profiles(_write_mycli(tmp_path, MINIMAL_PROFILE + table))["mycli"].user_skills + assert spec == UserSkillsSpec( + "unordered", + (UserSkillRoot("~/.mycli/skills"), UserSkillRoot("~/.agents/skills", ("MYCLI_HOME",))), + ) + + +def test_user_skills_empty_table_takes_the_defaults(tmp_path): + spec = load_profiles(_write_mycli(tmp_path, MINIMAL_PROFILE + "\n[user_skills]\n"))[ + "mycli" + ].user_skills + assert spec == UserSkillsSpec(precedence="project", roots=()) + + +@pytest.mark.parametrize("precedence", sorted({"project", "user", "unordered"})) +def test_user_skills_accepts_every_precedence_on_both_routes(tmp_path, profile_scan, precedence): + spec = UserSkillsSpec(precedence, (UserSkillRoot("~/.mycli/skills", ("MYCLI_HOME",)),)) + project = _write_mycli(tmp_path, MINIMAL_PROFILE + _user_skills_table(spec)) + assert load_profiles(project)["mycli"].user_skills == spec + profile_scan(_FakeEntryPoint("acme", lambda: [_plugin_profile(user_skills=spec)])) + assert load_profiles()["acme"].user_skills == spec + assert profile_mod.external_profile_errors() == {} + + +@pytest.mark.parametrize( + ("table", "match"), + [ + pytest.param('user_skills = "~/.x"\n', "user_skills must be a table", id="not-a-table"), + pytest.param( + '\n[user_skills]\norder = "user"\n', + "user_skills has unknown keys: ['order']", + id="unknown-key", + ), + pytest.param( + "\n[user_skills]\nprecedence = 1\n", + "user_skills.precedence must be a string", + id="precedence-not-str", + ), + pytest.param( + '\n[user_skills]\nroots = "~/.x"\n', + "user_skills.roots must be a list", + id="roots-not-list", + ), + pytest.param( + "\n[user_skills]\nroots = [3]\n", + "user_skills.roots entries must be", + id="root-not-str-or-table", + ), + pytest.param( + '\n[user_skills]\nroots = [["~/.x"]]\n', + "user_skills.roots entries must be", + id="root-is-a-list", + ), + pytest.param( + '\n[user_skills]\nroots = [{ path = "~/.x", disable = ["A"] }]\n', + "user_skills.roots entry has unknown keys: ['disable']", + id="root-unknown-key", + ), + pytest.param( + "\n[user_skills]\nroots = [{ path = 3 }]\n", + "user_skills.roots entry path must be a string", + id="root-path-not-str", + ), + pytest.param( + '\n[user_skills]\nroots = [{ disabled_by = ["A"] }]\n', + "user_skills.roots entry path must be a string", + id="root-path-missing", + ), + pytest.param( + '\n[user_skills]\nroots = [{ path = "~/.x", disabled_by = "A" }]\n', + "user_skills.roots entry disabled_by must be a list of strings", + id="disabled-by-not-list", + ), + pytest.param( + '\n[user_skills]\nroots = [{ path = "~/.x", disabled_by = [1] }]\n', + "user_skills.roots entry disabled_by must be a list of strings", + id="disabled-by-entry-not-str", + ), + ], +) +def test_user_skills_shape_rejections(tmp_path, table, match): + """Shape is the TOML parser's job only — a constructed `UserSkillsSpec` has + no shape left to parse — so these rows have no entry-point twin.""" + # a bare `user_skills = ...` must sit above [hooks] to be top-level + text = table + MINIMAL_PROFILE if not table.startswith("\n") else MINIMAL_PROFILE + table + with pytest.raises(ProfileError, match=re.escape(match)): + load_profiles(_write_mycli(tmp_path, text)) + + +_PRECEDENCE_ERR = "user_skills.precedence must be one of" +_ROOT_ERR = "user_skills root path must be a '~/'-prefixed path inside the home directory" +_ROOT_ALIAS_ERR = "user_skills root path must not name a Windows device" +_VAR_ERR = "user_skills root disabled_by entries must be environment variable names" +_DUP_ERR = "user_skills has duplicate roots" + + +@pytest.mark.parametrize( + ("precedence", "roots", "match"), + [ + pytest.param("first", (), _PRECEDENCE_ERR, id="precedence-unknown"), + pytest.param("User", (), _PRECEDENCE_ERR, id="precedence-case"), + pytest.param("", (), _PRECEDENCE_ERR, id="precedence-empty"), + pytest.param("project", (UserSkillRoot(".claude/skills"),), _ROOT_ERR, id="not-home"), + pytest.param("project", (UserSkillRoot("/etc/skills"),), _ROOT_ERR, id="absolute"), + pytest.param("project", (UserSkillRoot("~skills"),), _ROOT_ERR, id="tilde-no-slash"), + pytest.param("project", (UserSkillRoot("~"),), _ROOT_ERR, id="tilde-alone"), + pytest.param("project", (UserSkillRoot("~/"),), _ROOT_ERR, id="home-itself"), + pytest.param("project", (UserSkillRoot("~/."),), _ROOT_ERR, id="home-dot"), + pytest.param("project", (UserSkillRoot("~//etc"),), _ROOT_ERR, id="smuggled-abs"), + pytest.param("project", (UserSkillRoot("~/C:/x"),), _ROOT_ERR, id="smuggled-drive"), + pytest.param("project", (UserSkillRoot("~/../x"),), _ROOT_ERR, id="parent-climb"), + pytest.param( + "project", (UserSkillRoot("~/.claude/../../x"),), _ROOT_ERR, id="nested-climb" + ), + pytest.param( + "project", (UserSkillRoot("~\\.claude\\skills"),), _ROOT_ERR, id="backslash-prefix" + ), + pytest.param( + "project", (UserSkillRoot("~/NUL/skills"),), _ROOT_ALIAS_ERR, id="win32-device" + ), + pytest.param( + "project", (UserSkillRoot("~/.claude/skills."),), _ROOT_ALIAS_ERR, id="win32-trim" + ), + pytest.param( + "project", (UserSkillRoot("~/.x", ("1X",)),), _VAR_ERR, id="var-leading-digit" + ), + pytest.param("project", (UserSkillRoot("~/.x", ("A-B",)),), _VAR_ERR, id="var-dash"), + pytest.param("project", (UserSkillRoot("~/.x", ("",)),), _VAR_ERR, id="var-empty"), + pytest.param("project", (UserSkillRoot("~/.x", ("$HOME",)),), _VAR_ERR, id="var-sigil"), + pytest.param( + "project", (UserSkillRoot("~/.x", ("OK", "A B")),), _VAR_ERR, id="var-space-second" + ), + pytest.param( + "project", + (UserSkillRoot("~/a/b"), UserSkillRoot("~/a/b")), + _DUP_ERR, + id="dup-exact", + ), + pytest.param( + "project", + (UserSkillRoot("~/a/b"), UserSkillRoot("~/a//b/")), + _DUP_ERR, + id="dup-spelling", + ), + pytest.param( + "project", + (UserSkillRoot("~/a/b", ("X",)), UserSkillRoot("~/./a/b", ("Y",))), + _DUP_ERR, + id="dup-other-disabler", + ), + ], +) +def test_user_skills_value_rejections_on_both_routes( + tmp_path, profile_scan, precedence, roots, match +): + """Value rules live in `_validate_profile`, so the TOML route and the + entry-point (constructed dataclass) route refuse the same set. + + ABLATION (run when written): deleting the precedence, the disabled_by name or + the duplicate-root guard in `_validate_profile` reddens every one of its rows + (the TOML half trips first; the entry-point half shares the same guard).""" + spec = UserSkillsSpec(precedence=precedence, roots=roots) + with pytest.raises(ProfileError, match=re.escape(match)): + load_profiles(_write_mycli(tmp_path, MINIMAL_PROFILE + _user_skills_table(spec))) + _assert_entry_point_refused(profile_scan, match, user_skills=spec) + + +def test_extra_skill_trees_parse_on_both_routes(tmp_path, profile_scan): + text = MINIMAL_PROFILE.replace("[hooks]", 'extra_skill_trees = [".agents/skills"]\n[hooks]') + assert load_profiles(_write_mycli(tmp_path, text))["mycli"].extra_skill_trees == ( + ".agents/skills", + ) + profile_scan( + _FakeEntryPoint("acme", lambda: [_plugin_profile(extra_skill_trees=(".agents/skills",))]) + ) + assert load_profiles()["acme"].extra_skill_trees == (".agents/skills",) + assert profile_mod.external_profile_errors() == {} + + +def test_extra_skill_trees_must_be_a_list_of_strings(tmp_path): + for value in ('".agents/skills"', "[1]"): + text = MINIMAL_PROFILE.replace("[hooks]", f"extra_skill_trees = {value}\n[hooks]") + with pytest.raises(ProfileError, match="extra_skill_trees must be a list of strings"): + load_profiles(_write_mycli(tmp_path, text)) + + +_EXTRA_REL_ERR = "extra_skill_trees entries must be project-relative paths" +_EXTRA_HOME_ERR = "extra_skill_trees entries must not start with '~': a leading '~' is not expanded" +_EXTRA_ALIAS_ERR = "extra_skill_trees entries must not name a Windows device" +_EXTRA_SAME_ERR = "extra_skill_trees entries must differ from skill_tree" +_EXTRA_DASH_ERR = "extra_skill_trees entries must not start with '-'" +_EXTRA_DUP_ERR = "extra_skill_trees has duplicate entries" + + +@pytest.mark.parametrize( + ("entries", "match"), + [ + pytest.param(("~/x",), _EXTRA_HOME_ERR, id="tilde-slash"), + pytest.param(("~",), _EXTRA_HOME_ERR, id="tilde-alone"), + pytest.param(("~user/skills",), _EXTRA_HOME_ERR, id="tilde-user"), + pytest.param(("/abs",), _EXTRA_REL_ERR, id="absolute"), + pytest.param(("C:/x",), _EXTRA_REL_ERR, id="drive"), + pytest.param(("../x",), _EXTRA_REL_ERR, id="parent"), + pytest.param(("",), _EXTRA_REL_ERR, id="empty"), + pytest.param((".",), _EXTRA_REL_ERR, id="dot"), + pytest.param(("CON",), _EXTRA_ALIAS_ERR, id="win32-device"), + pytest.param((".agents/skills.",), _EXTRA_ALIAS_ERR, id="win32-trim"), + pytest.param(("-cprint(1)#",), _EXTRA_DASH_ERR, id="leading-dash"), + # MINIMAL_PROFILE and _plugin_profile both keep the default skill_tree + pytest.param((".claude/skills",), _EXTRA_SAME_ERR, id="same-as-skill-tree"), + pytest.param(("./.claude//skills/",), _EXTRA_SAME_ERR, id="same-as-skill-tree-spelling"), + pytest.param((".agents/skills", ".agents/skills"), _EXTRA_DUP_ERR, id="dup-exact"), + pytest.param((".agents/skills", ".agents//skills/"), _EXTRA_DUP_ERR, id="dup-spelling"), + ], +) +def test_extra_skill_trees_value_rejections_on_both_routes(tmp_path, profile_scan, entries, match): + listed = ", ".join(_toml_str(e) for e in entries) + text = MINIMAL_PROFILE.replace("[hooks]", f"extra_skill_trees = [{listed}]\n[hooks]") + with pytest.raises(ProfileError, match=re.escape(match)): + load_profiles(_write_mycli(tmp_path, text)) + _assert_entry_point_refused(profile_scan, match, extra_skill_trees=entries) diff --git a/tests/test_settings_schema.py b/tests/test_settings_schema.py index f5c4f41c3..fbd72a7f5 100644 --- a/tests/test_settings_schema.py +++ b/tests/test_settings_schema.py @@ -45,6 +45,7 @@ Policy, ReviewPolicy, ScmPolicy, + SkillsPolicy, StageAdapterPolicy, StoriesPolicy, SweepPolicy, @@ -77,6 +78,7 @@ "tui": TuiPolicy, "operator": OperatorPolicy, "mux": MuxPolicy, + "skills": SkillsPolicy, "dev": DevPolicy, } diff --git a/tests/test_skill_locate.py b/tests/test_skill_locate.py new file mode 100644 index 000000000..5a48e2d88 --- /dev/null +++ b/tests/test_skill_locate.py @@ -0,0 +1,536 @@ +"""The skill locator (`bmad_loop.skill_locate`): pure resolution over a scope. + +Every test passes `home=` / `environ=` (or monkeypatches the seams), because +conftest pins `user_home` to an empty dir and `ambient_environ` to `{}`. +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass, field +from pathlib import Path + +import pytest + +from bmad_loop import skill_locate +from bmad_loop.skill_locate import ( + Located, + SkillScope, + UserRoot, + UserSkillRoot, + UserSkillsSpec, + as_scope, + build_scope, + copies, + home_copy, + locate, + prompt_skill, + prompt_skill_dir, + same_copy, + scope_for, + shadow, +) + +SKILL = "bmad-build-auto" +# Captured at import, before conftest's autouse fixture pins the seam. +_REAL_USER_HOME = skill_locate.user_home + + +def _skill(folder: Path) -> Path: + folder.mkdir(parents=True, exist_ok=True) + (folder / "SKILL.md").write_text("---\nname: x\n---\n", encoding="utf-8") + return folder + + +def _plant_directory_redirect(link: Path, target: Path) -> None: + """A directory redirect: a symlink on POSIX, a junction on win32 (no + privilege needed), as in tests/test_artifact_publication.py.""" + if sys.platform == "win32": + import _winapi # Windows-only stdlib module + + _winapi.CreateJunction(str(target), str(link)) + else: + link.symlink_to(target, target_is_directory=True) + + +@pytest.fixture +def layout(tmp_path): + project = tmp_path / "project" + home = tmp_path / "home" + project.mkdir() + home.mkdir() + return project, home + + +def _spec(precedence: str, *roots: str | UserSkillRoot) -> UserSkillsSpec: + return UserSkillsSpec( + precedence=precedence, + roots=tuple(r if isinstance(r, UserSkillRoot) else UserSkillRoot(r) for r in roots), + ) + + +def _scope(home, precedence="project", *, resolve_user, roots=("~/.agents/skills",), environ=None): + return build_scope( + ".agents/skills", + user_skills=_spec(precedence, *roots), + resolve_user=resolve_user, + home=home, + environ={} if environ is None else environ, + ) + + +# precedence x resolve_user x {project-only, user-only, both} -> expected origin +_MATRIX = [ + (precedence, resolve_user, placement, expected) + for precedence in ("project", "user", "unordered") + for resolve_user in (False, True) + for placement, expected in ( + ("project", "project"), + ("user", "user" if resolve_user else None), + ( + "both", + "user" if (resolve_user and precedence == "user") else "project", + ), + ) +] + + +@pytest.mark.parametrize(("precedence", "resolve_user", "placement", "expected"), _MATRIX) +def test_locate_precedence_matrix(layout, precedence, resolve_user, placement, expected): + """Off = project-only, whatever the precedence. On: `user` puts the user copy + first; `project` and `unordered` keep the project copy and fall back to a user + copy only when the project has none. + + Ablation: drop the `if not scope.resolve_user` early return in `locate` and the + (False, "user") rows fail with a user hit, and (False, "both") under `user` + precedence returns the user copy.""" + project, home = layout + if placement in ("project", "both"): + _skill(project / ".agents/skills" / SKILL) + if placement in ("user", "both"): + _skill(home / ".agents/skills" / SKILL) + found = locate(project, _scope(home, precedence, resolve_user=resolve_user), SKILL) + if expected is None: + assert found is None + return + assert found is not None + assert found.origin == expected + if expected == "project": + assert found == Located( + SKILL, project / ".agents/skills" / SKILL, "project", ".agents/skills", True + ) + assert found.display == f".agents/skills/{SKILL}" + else: + assert found == Located( + SKILL, home / ".agents/skills" / SKILL, "user", "~/.agents/skills", False + ) + assert found.display == f"~/.agents/skills/{SKILL}" + + +def test_locate_missing_everywhere_is_none(layout): + project, home = layout + assert locate(project, _scope(home, resolve_user=True), SKILL) is None + assert copies(project, _scope(home, resolve_user=True), SKILL) == [] + + +def test_a_folder_without_skill_md_is_not_a_copy(layout): + project, home = layout + (project / ".agents/skills" / SKILL).mkdir(parents=True) + (home / ".agents/skills" / SKILL).mkdir(parents=True) + assert locate(project, _scope(home, resolve_user=True), SKILL) is None + + +def test_copies_order_primary_extras_then_user_roots(layout): + project, home = layout + for tree in (".claude/skills", ".agents/skills", ".github/skills"): + _skill(project / tree / SKILL) + for root in (".config/opencode/skills", ".agents/skills"): + _skill(home / root / SKILL) + scope = build_scope( + ".claude/skills", + extra_trees=(".agents/skills", ".github/skills"), + user_skills=_spec("project", "~/.config/opencode/skills", "~/.agents/skills"), + resolve_user=True, + home=home, + environ={}, + ) + assert scope.project_trees() == (".claude/skills", ".agents/skills", ".github/skills") + found = copies(project, scope, SKILL) + assert [(c.origin, c.root, c.primary) for c in found] == [ + ("project", ".claude/skills", True), + ("project", ".agents/skills", False), + ("project", ".github/skills", False), + ("user", "~/.config/opencode/skills", False), + ("user", "~/.agents/skills", False), + ] + + +def test_extra_tree_fills_in_when_primary_lacks_the_skill(layout): + project, home = layout + _skill(project / ".agents/skills" / SKILL) + scope = build_scope(".claude/skills", extra_trees=(".agents/skills",), home=home, environ={}) + found = locate(project, scope, SKILL) + assert found is not None + assert (found.origin, found.root, found.primary) == ("project", ".agents/skills", False) + + +def test_user_roots_are_searched_in_declared_order(layout): + project, home = layout + _skill(home / ".gemini/skills" / SKILL) + _skill(home / ".agents/skills" / SKILL) + scope = _scope(home, resolve_user=True, roots=("~/.agents/skills", "~/.gemini/skills")) + found = locate(project, scope, SKILL) + assert found is not None and found.root == "~/.agents/skills" + scope = _scope(home, resolve_user=True, roots=("~/.gemini/skills", "~/.agents/skills")) + found = locate(project, scope, SKILL) + assert found is not None and found.root == "~/.gemini/skills" + + +def test_disabled_root_never_resolves(layout): + """A root whose disabler variable is set (even to "") is unavailable: never + located, never a shadow, never a home copy. + + Ablation: drop the `disabled_by` loop in `_user_root` and every assertion + below fails with the user copy resolving.""" + project, home = layout + _skill(home / ".claude/skills" / SKILL) + _skill(project / ".claude/skills" / "other") + root = UserSkillRoot("~/.claude/skills", ("CLAUDE_CONFIG_DIR",)) + for value in ("/elsewhere", ""): + scope = build_scope( + ".claude/skills", + user_skills=UserSkillsSpec("user", (root,)), + resolve_user=True, + home=home, + environ={"CLAUDE_CONFIG_DIR": value}, + ) + assert scope.user_roots == ( + UserRoot("~/.claude/skills", home / ".claude/skills", "env:CLAUDE_CONFIG_DIR"), + ) + assert locate(project, scope, SKILL) is None + assert home_copy(scope, SKILL) is None + # Unrelated variables leave it available. + scope = build_scope( + ".claude/skills", + user_skills=UserSkillsSpec("user", (root,)), + resolve_user=True, + home=home, + environ={"CODEX_HOME": "/x"}, + ) + assert scope.user_roots[0].unavailable == "" + assert locate(project, scope, SKILL) is not None + + +@dataclass(frozen=True) +class _Profile: + skill_tree: str = ".agents/skills" + extra_skill_trees: tuple[str, ...] = () + user_skills: UserSkillsSpec | None = None + env: dict[str, str] = field(default_factory=dict) + + +def test_scope_for_reads_the_disabler_from_the_profile_env(layout): + project, home = layout + _skill(home / ".codex/skills" / SKILL) + spec = _spec("unordered", "~/.agents/skills", UserSkillRoot("~/.codex/skills", ("CODEX_HOME",))) + plain = scope_for(_Profile(user_skills=spec), resolve_user=True, home=home) + assert locate(project, plain, SKILL) is not None + disabled = scope_for( + _Profile(user_skills=spec, env={"CODEX_HOME": "/srv/codex"}), resolve_user=True, home=home + ) + assert [r.unavailable for r in disabled.user_roots] == ["", "env:CODEX_HOME"] + assert locate(project, disabled, SKILL) is None + + +def test_scope_for_reads_the_disabler_from_the_ambient_environ(layout, monkeypatch): + project, home = layout + _skill(home / ".codex/skills" / SKILL) + spec = _spec("unordered", UserSkillRoot("~/.codex/skills", ("CODEX_HOME",))) + monkeypatch.setattr(skill_locate, "ambient_environ", lambda: {"CODEX_HOME": "/srv/codex"}) + scope = scope_for(_Profile(user_skills=spec), resolve_user=True, home=home) + assert scope.user_roots[0].unavailable == "env:CODEX_HOME" + # An explicit environ replaces the ambient one; the profile env still overlays. + scope = scope_for(_Profile(user_skills=spec), resolve_user=True, home=home, environ={}) + assert scope.user_roots[0].unavailable == "" + + +def test_scope_for_defaults_to_the_seams(layout, monkeypatch): + project, home = layout + _skill(home / ".agents/skills" / SKILL) + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + scope = scope_for(_Profile(user_skills=_spec("project", "~/.agents/skills")), resolve_user=True) + assert scope.user_roots == (UserRoot("~/.agents/skills", home / ".agents/skills"),) + found = locate(project, scope, SKILL) + assert found is not None and found.origin == "user" + + +def test_scope_for_a_packaged_profile(layout): + """`CLIProfile` satisfies the profile protocol.""" + from bmad_loop.adapters.profile import get_profile + + project, home = layout + scope = scope_for(get_profile("claude"), resolve_user=False, home=home, environ={}) + assert scope == SkillScope( + ".claude/skills", + user_roots=(UserRoot("~/.claude/skills", home / ".claude/skills"),), + precedence="user", + ) + + +def test_no_user_skills_means_no_roots(layout): + project, home = layout + _skill(home / ".agents/skills" / SKILL) + scope = scope_for(_Profile(), resolve_user=True, home=home) + assert scope == SkillScope(".agents/skills", resolve_user=True) + assert locate(project, scope, SKILL) is None + + +def test_no_home_marks_every_root_unavailable(layout): + project, _home = layout + scope = _scope(None, resolve_user=True, roots=("~/.agents/skills", "~/.codex/skills")) + assert scope.user_roots == ( + UserRoot("~/.agents/skills", None, "no-home"), + UserRoot("~/.codex/skills", None, "no-home"), + ) + assert locate(project, scope, SKILL) is None + assert home_copy(scope, SKILL) is None + + +def test_user_home_is_none_when_home_cannot_be_determined(monkeypatch): + def boom(): + raise RuntimeError("Could not determine home directory.") + + monkeypatch.setattr(Path, "home", staticmethod(boom)) + assert _REAL_USER_HOME() is None + + +def test_unreadable_root_is_unavailable(layout, monkeypatch): + project, home = layout + _skill(home / ".agents/skills" / SKILL) + real_is_dir = Path.is_dir + + def is_dir(self, *args, **kwargs): + if self == home / ".agents/skills": + raise PermissionError(13, "Permission denied") + return real_is_dir(self, *args, **kwargs) + + monkeypatch.setattr(Path, "is_dir", is_dir) + scope = _scope(home, resolve_user=True) + assert scope.user_roots == ( + UserRoot("~/.agents/skills", home / ".agents/skills", "unreadable"), + ) + assert locate(project, scope, SKILL) is None + + +def test_unreadable_copy_counts_as_absent(layout, monkeypatch): + project, home = layout + _skill(project / ".agents/skills" / SKILL) + real_is_file = Path.is_file + + def is_file(self, *args, **kwargs): + if self.name == "SKILL.md": + raise PermissionError(13, "Permission denied") + return real_is_file(self, *args, **kwargs) + + monkeypatch.setattr(Path, "is_file", is_file) + assert locate(project, _scope(home, resolve_user=True), SKILL) is None + + +def test_a_missing_root_is_available_but_empty(layout): + project, home = layout + scope = _scope(home, resolve_user=True, roots=("~/.nowhere/skills",)) + assert scope.user_roots[0].unavailable == "" + assert locate(project, scope, SKILL) is None + + +def test_redirected_skill_inside_a_user_root_resolves(layout, tmp_path): + """The skills CLI links each global skill into ~/.agents/skills: a link (a + junction on Windows) inside a user root is a copy at its native path.""" + project, home = layout + real = _skill(tmp_path / "store" / SKILL) + (home / ".agents/skills").mkdir(parents=True) + _plant_directory_redirect(home / ".agents/skills" / SKILL, real) + found = locate(project, _scope(home, resolve_user=True), SKILL) + assert found is not None + assert found.path == home / ".agents/skills" / SKILL + assert prompt_skill_dir(project, _scope(home, resolve_user=True), f"/{SKILL} x") == str( + home / ".agents/skills" / SKILL + ) + + +@pytest.mark.parametrize( + ("precedence", "resolve_user", "kind"), + [ + ("user", False, "overrides"), + ("user", True, None), + ("unordered", False, "competes"), + ("unordered", True, "competes"), + ("project", False, None), + ("project", True, None), + ], +) +def test_shadow(layout, precedence, resolve_user, kind): + project, home = layout + _skill(project / ".agents/skills" / SKILL) + _skill(home / ".agents/skills" / SKILL) + scope = _scope(home, precedence, resolve_user=resolve_user) + found = shadow(project, scope, SKILL) + if kind is None: + assert found is None + return + assert found is not None + assert found.kind == kind + assert found.checked.origin == "project" and found.checked.primary + assert found.other.display == f"~/.agents/skills/{SKILL}" + + +@pytest.mark.parametrize("placement", ["project", "user", "none"]) +def test_no_shadow_without_both_copies(layout, placement): + project, home = layout + if placement == "project": + _skill(project / ".agents/skills" / SKILL) + if placement == "user": + _skill(home / ".agents/skills" / SKILL) + for precedence in ("user", "unordered"): + assert shadow(project, _scope(home, precedence, resolve_user=False), SKILL) is None + + +def test_home_copy_ignores_the_switch(layout): + project, home = layout + _skill(home / ".agents/skills" / SKILL) + found = home_copy(_scope(home, resolve_user=False), SKILL) + assert found is not None and found.display == f"~/.agents/skills/{SKILL}" + assert home_copy(_scope(home, resolve_user=False), "absent") is None + + +def _copy(folder: Path, files: dict[str, str]) -> Located: + for rel, text in files.items(): + path = folder / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return Located(SKILL, folder, "user", "~/.agents/skills", False) + + +_FILES = {"SKILL.md": "---\nname: x\n---\n", "steps/step-01.md": "do it\n"} + + +@pytest.mark.parametrize( + ("other", "expected"), + [ + (_FILES, True), + ({**_FILES, "steps/step-01.md": "do it differently\n"}, False), + ({**_FILES, "steps/step-02.md": "more\n"}, False), + ({"SKILL.md": _FILES["SKILL.md"]}, False), + ], + ids=["identical", "changed-bytes", "extra-file", "missing-file"], +) +def test_same_copy_compares_every_file(tmp_path, other, expected): + """Two copies are the same skill only with identical relative paths and bytes. + + Ablation (performed): compare `SKILL.md` alone in `same_copy` and the + changed-bytes and extra-file rows FAIL.""" + a = _copy(tmp_path / "a" / SKILL, _FILES) + b = _copy(tmp_path / "b" / SKILL, other) + assert same_copy(a, b) is expected + assert same_copy(b, a) is expected + + +def test_same_copy_of_one_folder_and_of_a_redirect_to_it(tmp_path): + a = _copy(tmp_path / "a" / SKILL, _FILES) + link = tmp_path / "link" + _plant_directory_redirect(link, a.path) + assert same_copy(a, a) + assert same_copy(a, Located(SKILL, link, "user", "~/.claude/skills", False)) + + +def test_same_copy_refuses_an_oversized_or_missing_folder(tmp_path, monkeypatch): + a = _copy(tmp_path / "a" / SKILL, _FILES) + b = _copy(tmp_path / "b" / SKILL, _FILES) + monkeypatch.setattr(skill_locate, "SAME_COPY_MAX_FILES", 1) + assert not same_copy(a, b) + monkeypatch.setattr(skill_locate, "SAME_COPY_MAX_FILES", 512) + gone = Located(SKILL, tmp_path / "gone" / SKILL, "user", "~/.agents/skills", False) + assert not same_copy(a, gone) + + +def test_same_copy_walks_linked_folders(tmp_path): + """Files behind a linked folder count: identical `SKILL.md` files whose + `steps` links point at different contents are not the same skill. + + Ablation (performed): drop `followlinks=True` from `_skill_files` and the + differing-target assertion FAILS.""" + targets = {} + for side, text in (("a", "do it\n"), ("b", "do it differently\n")): + targets[side] = tmp_path / f"{side}-steps" + _copy(targets[side], {"step-01.md": text}) + a = _copy(tmp_path / "a" / SKILL, {"SKILL.md": _FILES["SKILL.md"]}) + b = _copy(tmp_path / "b" / SKILL, {"SKILL.md": _FILES["SKILL.md"]}) + _plant_directory_redirect(a.path / "steps", targets["a"]) + _plant_directory_redirect(b.path / "steps", targets["b"]) + assert not same_copy(a, b) + assert not same_copy(b, a) + plain = _copy(tmp_path / "plain" / SKILL, _FILES) + assert same_copy(a, plain) + + +def test_same_copy_refuses_a_link_cycle(tmp_path): + a = _copy(tmp_path / "a" / SKILL, _FILES) + b = _copy(tmp_path / "b" / SKILL, _FILES) + _plant_directory_redirect(b.path / "steps" / "loop", b.path) + assert not same_copy(a, b) + assert not same_copy(b, a) + + +@pytest.mark.parametrize( + ("prompt", "expected"), + [ + ("/bmad-build-auto story-1 --x", ("bmad-build-auto", "story-1 --x")), + ("/bmad-build-auto", ("bmad-build-auto", "")), + ("/bmad-build-auto padded ", ("bmad-build-auto", "padded")), + ("plain text", ("", "plain text")), + ("", ("", "")), + ], +) +def test_prompt_skill(prompt, expected): + assert prompt_skill(prompt) == expected + + +def test_prompt_skill_dir_spellings(layout): + """None for a primary hit or a miss (the renderer keeps its relative + default), the relative spelling for an extra tree, the absolute native folder + for a user root.""" + project, home = layout + _skill(project / ".claude/skills" / "primary") + _skill(project / ".agents/skills" / "extra") + _skill(home / ".agents/skills" / "personal") + scope = build_scope( + ".claude/skills", + extra_trees=(".agents/skills",), + user_skills=_spec("project", "~/.agents/skills"), + resolve_user=True, + home=home, + environ={}, + ) + assert prompt_skill_dir(project, scope, "/primary a b") is None + assert prompt_skill_dir(project, scope, "/missing a b") is None + assert prompt_skill_dir(project, scope, "no slash") is None + assert prompt_skill_dir(project, scope, "/extra a") == ".agents/skills/extra" + expected = str(home / ".agents/skills" / "personal") + assert prompt_skill_dir(project, scope, "/personal a") == expected + assert Path(expected).is_absolute() + + +def test_as_scope(): + assert as_scope("x") == SkillScope("x") + assert as_scope("x").project_trees() == ("x",) + scope = SkillScope("x", extra_trees=("y",), resolve_user=True) + assert as_scope(scope) is scope + + +def test_scope_is_hashable_and_dedupes(): + a = SkillScope(".agents/skills", user_roots=(UserRoot("~/.agents/skills", Path("/h")),)) + b = SkillScope(".agents/skills", user_roots=(UserRoot("~/.agents/skills", Path("/h")),)) + assert list(dict.fromkeys([a, b, SkillScope(".claude/skills")])) == [ + a, + SkillScope(".claude/skills"), + ] diff --git a/tests/test_tickets_engine.py b/tests/test_tickets_engine.py index 9588147b5..54c61f93d 100644 --- a/tests/test_tickets_engine.py +++ b/tests/test_tickets_engine.py @@ -58,6 +58,7 @@ Policy, ReviewPolicy, ScmPolicy, + SkillsPolicy, TicketsPolicy, VerifyPolicy, ) @@ -3304,6 +3305,47 @@ def test_ticket_retro_happy_path_commits_doc_only(project_v7): ) +@pytest.mark.parametrize("on", [True, False]) +def test_ticket_retro_skill_probe_reads_user_roots_only_with_the_switch_on( + project_v7, monkeypatch, tmp_path, on +): + """The retro CLI's `bmad-retrospective` installed only in its user root + (`~/.claude/skills` for claude) passes the probe under `[skills] user_roots` + and the retro session runs; off, the probe reads the project tree alone and + skips as `skill-missing`. Ablation: restore the project-tree-only probe in + `_ticket_epic_retro` and the switch-on row FAILS.""" + from conftest import attach_profile + + from bmad_loop import skill_locate + + home = tmp_path / "home" + skill = home / ".claude" / "skills" / "bmad-retrospective" / "SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("---\nname: bmad-retrospective\n---\n", encoding="utf-8") + monkeypatch.setattr(skill_locate, "user_home", lambda: home) + tree = _epic_tree(project_v7) + plan = Path(tree.finds["1.1"].plan) + engine, _ = make_engine( + project_v7, + tree, + policy=_retro_policy(skills=SkillsPolicy(user_roots=on)), + script=[_builds_finishing(project_v7, tree, plan)], + ) + retro = attach_profile(MockAdapter([_retro_writes(project_v7)]), "claude", project_v7.project) + engine.adapters["retro"] = retro + + engine.run() + + if on: + assert len(retro.sessions) == 1 + assert not _kinds(engine, "retro-auto-skipped") + assert load_state(engine.run_dir).ticket_epic_closures == {"epic-cart": "accepted"} + else: + assert retro.sessions == [] + [skipped] = _kinds(engine, "retro-auto-skipped") + assert (skipped["reason"], skipped["epic_ref"]) == ("skill-missing", "epic-cart") + + def test_ticket_retro_verdict_rejected_hard_gates_until_epic_done(project_v7): """A `rejected` verdict pauses again on every later pick while epic-cart stays open — with nothing else queued, and with epic-checkout's 2.1 ready — and