640-skills
Agent Skills for Solopreneurs & Teams.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/KunoLu/640-skills with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/KunoLu/640-skills'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/kunolu--640-skills)HTML
<a href="/listings/kunolu--640-skills"><img src="/api/listings/kunolu--640-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
1. Install the Onboard Skill only
Paste this into your coding agent; replace the target agent if needed:
Install only sbtd-workflow-onboard from the KunoLu/640-skills v2.0.1 tag into my user-level global Skills directory for Codex, not this project. First resolve that revision and verify it exists; do not silently substitute main or a v1 package. Use the official skills CLI and copy the full directory. Show the resolved source and target. Do not run init/reset, install other tools, or change AGENTS/MCP configuration yet.
Prefer the terminal? With Node/npm available, use the [official Skills CLI](https://github.com/vercel-labs/skills):
npx --yes skills@latest add https://github.com/KunoLu/640-skills \ --skill sbtd-workflow-onboard --global --agent codex --yes --copy npx skills list --global --agent codex
`skills@latest` selects the CLI version, **not a Skill release**. An unpinned repository source reads the default branch, not the latest tag. Pinning syntax is `'KunoLu/640-skills#<reviewed-ref>@sbtd-workflow-onboard'`: replace `<reviewed-ref>` with an existing v2 tag or reviewed commit, and follow that revision's documentation. **Do not combine a historical v1 package with the v2 setup prompts below**: its initialization may install or invoke the retired Trellis/GitNexus workflow. For v1 data, use the migration prompt below instead of init/reset.
**Bootstrap is not setup.** It copies the self-contained Onboard package; it does not execute `onboard.py`, install the remaining Skills or Python dependencies, configure MCP, or initialize projects. Find the actual installed directory rather than assuming a HOME path. For OMP or another host, confirm its supported Skills CLI agent identifier and discovery path instead of assuming Onboard's platform name is the same identifier.
2. Review and initialize selected projects
Use sbtd-workflow-onboard to initialize /abs/project-one,/abs/project-two. Target platform: codex. These are the existing absolute project roots I want initialized; install project AGENTS.md in both. First check the installed package's Python dependencies and show plan --json, including global Skills, global AGENTS and host/MCP targets. Ask before installing missing prerequisites or applying the plan. After I approve, run init and report each project's writes, backups, skipped checks and remaining actions.
Use `omp` instead of `codex` for OMP setup. Multiple project roots are separated by English commas. A normal setup installs the **14 bundled + 19 required external Skills globally**; optional tools retain their own confirmation gates.
Onboard needs **Python 3.10+** and its declared dependencies for contract/state/migration validation. After reviewing and authorizing dependency installation, run this with the interpreter that will execute the installed copy:
python -m pip install -r /path/to/installed/sbtd-workflow-onboard/requirements.txt
> **Check the write scope.** Normal `init`/`reset` writes global Codex rules by default, and also backs up and overwrites `~/.omp/agent/AGENTS.md` when `~/.omp` already exists. Selecting a platform does not select the global AGENTS destination. `--global-agents-path` changes only the Codex target. Use project-only mode when global writes are not wanted.
[Bootstrap guide](sbtd-workflow-onboard/REFERENCE.md#official-skills-cli-bootstrap) · [Setup contract](sbtd-workflow-onboard/REFERENCE.md#two-execution-modes) · [Path resolution](sbtd-workflow-onboard/REFERENCE.md#paths)
<a id="usage"></a>
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 538 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <div align="center">
- # SBTD Workflow
- **Reusable agent rules, skills and onboarding for evidence-driven development.**
- [](#skills) [](#external-skills) [](LICENSE)
- **English** · [简体中文](README.zh.md)
- [Install](#install) · [Usage & prompts](#usage) · [Workflow](#workflow) · [Skills](#skills) · [Reference](#reference)
- </div>
- SBTD connects **specifications, behavior, tests and domain language**. Your coding agent does the work; the workflow makes scope, permissions and verification explicit.
- This repository is a **configuration and Skill source**, not a business application. The main workflow targets **Codex and Oh My Pi (OMP)**; the installers also expose Claude Code and Kimi adapters. Adapter availability is not proof of identical host behavior.
- > **Latest stable [v2.1.0](https://github.com/KunoLu/640-skills/releases/tag/v2.1.0) is released.** The catalog contains 14 bundled and 19 required external Skills. See the [English CHANGELOG](CHANGELOG.md) and [Chinese counterpart](CHANGELOG.zh.md) for the same release history. Code, CI, installation, native checks and actual host acceptance remain separate evidence layers; publishing a tag does not upgrade your environment. See the [delivery plan and acceptance boundaries](docs/prd/sbtd-workflow-v2-trellis-removal-graft-migration-prd.md).
- | [New installation](#install) | [Already installed](#onboard-prompts) | [Start a task](#task-prompts) |
- |---|---|---|
- | Bootstrap Onboard, then review setup | Check, upgrade or initialize another project | Choose a mode and copy a task prompt |
- <a id="install"></a>
- ## Install: start with your agent
- ### 1. Install the Onboard Skill only
- Paste this into your coding agent; replace the target agent if needed:
- ```text
- Install only sbtd-workflow-onboard from the KunoLu/640-skills v2.1.0 tag
- into my user-level global Skills directory for Codex, not this project.
- First resolve that revision and verify it exists; do not silently substitute main or a v1 package.
- Use the official skills CLI and copy the full directory. Show the resolved source and target.
- Do not run init/reset, install other tools, or change AGENTS/MCP configuration yet.
- ```
- Prefer the terminal? With Node/npm available, use the [official Skills CLI](https://github.com/vercel-labs/skills):
- ```bash
- npx --yes skills@latest add https://github.com/KunoLu/640-skills \
- --skill sbtd-workflow-onboard --global --agent codex --yes --copy
- npx skills list --global --agent codex
- ```
- `skills@latest` selects the CLI version, **not a Skill release**. An unpinned repository source reads the default branch, not the latest tag. Pinning syntax is `'KunoLu/640-skills#<reviewed-ref>@sbtd-workflow-onboard'`: replace `<reviewed-ref>` with an existing v2 tag or reviewed commit, and follow that revision's documentation. **Do not combine a historical v1 package with the v2 setup prompts below**: its initialization may install or invoke the retired Trellis/GitNexus workflow. For v1 data, use the migration prompt below instead of init/reset.
- **Bootstrap is not setup.** It copies the self-contained Onboard package; it does not execute `onboard.py`, install the remaining Skills or Python dependencies, configure MCP, or initialize projects. Find the actual installed directory rather than assuming a HOME path. For OMP or another host, confirm its supported Skills CLI agent identifier and discovery path instead of assuming Onboard's platform name is the same identifier.
- ### 2. Review and initialize selected projects
- ```text
- Use sbtd-workflow-onboard to initialize /abs/project-one,/abs/project-two.
- Target platform: codex. These are the existing absolute project roots I want initialized;
- install project AGENTS.md in both. First check the installed package's Python dependencies
- and show plan --json, including global Skills, global AGENTS and host/MCP targets.
- Ask before installing missing prerequisites or applying the plan. After I approve,
- run init and report each project's writes, backups, skipped checks and remaining actions.
- ```
- Use `omp` instead of `codex` for OMP setup. Multiple project roots are separated by English commas. A normal setup installs the **14 bundled + 19 required external Skills globally**; optional tools retain their own confirmation gates.
- Onboard needs **Python 3.10+** and its declared dependencies for contract/state/migration validation. After reviewing and authorizing dependency installation, run this with the interpreter that will execute the installed copy:
- ```bash
- python -m pip install -r /path/to/installed/sbtd-workflow-onboard/requirements.txt
- ```
- > **Check the write scope.** Normal `init`/`reset` writes global Codex rules by default, and also backs up and overwrites the OMP global rules file, following omp 18.19.0's own resolution: `$PI_CODING_AGENT_DIR/AGENTS.md` when `PI_CODING_AGENT_DIR` is non-empty (relative values, including a leading `~`, resolve against the process current directory — `~/x` means a folder literally named `~` there — and the directory is created when missing); a named profile (`OMP_PROFILE` before `PI_PROFILE`) targets `profiles/<name>/agent/AGENTS.md` and ignores the variable; otherwise `~/.omp/agent/AGENTS.md` only when `~/.omp` already exists, with `PI_CONFIG_DIR` naming the home subdirectory that replaces `.omp` (an absolute value is joined under home too, never used as an absolute path). Selecting a platform does not select the global AGENTS destination. `--global-agents-path` changes only the Codex target. Use project-only mode when global writes are not wanted.
- [Bootstrap guide](sbtd-workflow-onboard/REFERENCE.md#official-skills-cli-bootstrap) · [Setup contract](sbtd-workflow-onboard/REFERENCE.md#two-execution-modes) · [Path resolution](sbtd-workflow-onboard/REFERENCE.md#paths)
- <a id="usage"></a>
- ## Usage: copy a prompt for your goal
- These are **natural-language requests to your agent**, not new CLI commands. Replace bracketed inputs and `/abs/...` paths. The agent should read local facts first and ask only for missing choices or required authorization.
- <a id="onboard-prompts"></a>
- ### Manage an installation
- | Goal | Choose | What it means |
- |---|---|---|
- | Inspect without installing | `check` / `plan` | Read-only inventory and proposed work; not proof that setup ran |
- | First full setup | `init` | Install missing/invalid Skills; preserve valid Skill shells, not necessarily current content |
- | Add a project only | `init-projects` | Project AGENTS/ignore and applicable local assets; no global installation or user MCP/hooks |
- | Align an existing environment | `upgrade` | Fixed-baseline plan/apply/verify, explicit drift decisions, backups and recovery |
- | Deliberately reinstall | `reset` | Overwrite bundled Skills **without backup**, reinstall required externals; not an upgrade recovery protocol |
- | Move legacy data | `migration` | Approved projections, retained originals and verified receipts; separate deployment authorization; interrupted deployment evidence is reconciled from current state, never backfilled |
- | Retire detected legacy assets | `cleanup-legacy` | Display actual candidates, then obtain separate execution consent |
- | Restore an authorized batch | `recovery` | Plan and confirm restoration from trusted batch evidence; not a general undo command |
- The [first-time initialization prompt](#install) covers a new v2 installation after bootstrap. Use the following prompts for an existing installation or a v1 project; substitute the exact reviewed v2 source, project roots and configuration domains before execution.
- <details>
- <summary><strong>Run v2 init again — not a version upgrade</strong></summary>
- ```text
- Use the reviewed v2 sbtd-workflow-onboard package to plan init for platform codex
- and the existing project /abs/project. I want project AGENTS.md installed.
- Inspect the installed package revision and interpreter dependencies first.
- Show plan --json, exact global Skills/AGENTS/MCP targets and project writes/backups;
- wait for my approval before init. Preserve tasks, identity, lessons and legacy data.
- Explain which valid Skill shells init will skip; do not claim their contents were upgraded.
- If version alignment is needed, stop and propose an explicit upgrade plan instead.
- Do not reset, migrate, remove legacy assets or enable hooks under this request.
- ```
- </details>
- <details>
- <summary><strong>Inspection and project-only setup prompts</strong></summary>
- **Inspect the existing environment:**
- ```text
- Use sbtd-workflow-onboard to check my codex environment and /abs/project.
- This is read-only: report installed Skills, resolved paths, project conflicts,
- and missing prerequisites. Do not install, reset, migrate, clean up or change configuration.
- ```
- **Add a project without changing global configuration:**
- ```text
- Use sbtd-workflow-onboard in init-projects mode for /abs/project, platform omp.
- Install project AGENTS.md. First run project-only preflight and show the local write scope;
- wait for approval before writing. Do not install or modify global tools, Skills,
- AGENTS, MCP or hooks. Report whether the local Graft graph was built or unavailable.
- ```
- </details>
- <details>
- <summary><strong>Upgrade and reset prompts — different operations</strong></summary>
- **Recommended for an existing environment: explicit upgrade.**
- ```text
- Use sbtd-workflow-onboard to plan an upgrade to the reviewed Onboard package baseline.
- First confirm the exact global Skills root, global AGENTS targets, codex/omp configuration
- homes, any shell profiles, and an existing private backup vault. Inventory only that scope.
- Show upgrade --phase plan and all replace/preserve decisions for custom content; wait for
- approval before apply. Then verify disk content separately from protocol and real host loading.
- Ask separately before host probes. Do not clean up old assets or sync other environments.
- ```
- An isolated probe still rejects linked Skills by default. To retain a link, explicitly approve its physical target with `upgrade --phase authorize-link`, then pass the resulting document to `verify --probe --yes --link-authorization`. This grants only exact local target access and a temporary plain-directory projection; it does not replace the original link, follow nested links or prove a live session reload. See the [authorization commands and refusal boundaries](sbtd-workflow-onboard/REFERENCE.md#probe-skill-link-authorization).
- **Apply only the plan you have reviewed and approved:**
- ```text
- I approve the exact upgrade scope and replace/preserve decisions already shown in
- [upgrade-plan file]. Use the matching trusted v2 Onboard executor and recheck the source,
- targets and private vault. Read plan_id from that file and run upgrade --phase apply
- with the required confirmation; do not ask me to transcribe hashes.
- Save the actual receipt and backups. If scope or state has changed, stop rather than silently
- replanning under this approval. On partial failure, report measured writes and the retry path.
- Do not probe hosts, migrate projects, clean up or sync other environments.
- ```
- **Verify the applied upgrade without starting host probes:**
- ```text
- Use upgrade --phase verify with [the approved plan] and [its actual upgrade receipt].
- Verify the installed package and selected resources against that exact baseline.
- Report disk, runtime/protocol, host loading and legacy cleanup separately; mark unexecuted
- layers unverified. Do not add --probe or --yes, repair configuration, or delete backups.
- ```
- **Optional host and linked-Skill verification — approve the scope first:**
- ```text
- Show the exact host probes proposed for [upgrade plan and receipt], including configuration
- domains, subprocesses, temporary projections and potential side effects. These upgrade probes
- need no real authentication or model request; do not read or copy credential files.
- Wait for my explicit probe approval.
- For a linked Skill, show its logical path, physical target, identity and content boundary.
- Only after I approve that target, use upgrade --phase authorize-link and preserve its output.
- Then run upgrade --phase verify --probe --yes with that authorization where required.
- Keep the original link and unrelated configuration; report isolated host loading separately
- from any live session reload. Unproven isolation is blocked, not bypassed; real model/behavior
- smoke requires its own scope and controlled authentication, outside this upgrade probe.
- ```
- **Plan recovery of this upgrade, not a migration rollback:**
- ```text
- Use recovery --phase plan with --upgrade-plan [plan] and --upgrade-receipt [receipt].
- Confirm the private vault is trusted, inspect current drift and show the exact restoration
- scope and limits. Save the recovery plan only to the approved private location.
- Wait for separate recovery approval before recovery --phase apply; use the actual
- --upgrade-recovery-plan and read its recovery_id for --confirm-recovery.
- Preserve user changes, backups and partial receipts; do not execute untrusted historical code.
- ```
- These prompts map to the [implemented upgrade and recovery commands](sbtd-workflow-onboard/REFERENCE.md#upgrade-alignment). A successful `verify` does not grant cleanup permission; an old plan does not authorize a newly changed package or target set.
- **Use reset only when you intend to replace Skill content:**
- ```text
- Use the reviewed v2 sbtd-workflow-onboard package to plan reset for platform codex
- and /abs/project. I want project AGENTS.md rewritten, subject to the displayed plan.
- Verify the package revision and interpreter dependencies. Explain that bundled Skills
- will be overwritten without backup and required external Skills reinstalled.
- Identify custom Skill content; if I need it preserved, stop for a separately approved backup
- or propose upgrade instead. Show all global/project targets, AGENTS backups and MCP impact;
- preserve detected React Bits tier/registry. Wait for approval before reset.
- Preserve tasks, developer identity, specs, lessons, handoffs and legacy data.
- Reset is not migration, cleanup, a full-machine upgrade, or an automatic rollback guarantee.
- ```
- </details>
- <details>
- <summary><strong>Legacy migration, cleanup and recovery prompts</strong></summary>
- **Migrate an SBTD v1 project to v2 — package upgrade and data migration are separate:**
- ```text
- I use SBTD v1 in /abs/project and want to move to [reviewed v2 tag or commit]
- for [codex and/or omp, with the exact selected configuration domains].
- Start read-only: identify the installed Onboard version, old Trellis/GitNexus layout,
- project branch, custom rules, tasks/specs/lessons, shared HOME/Skills users and active processes.
- Do not run v1 init/reset, copy credentials, create directories or modify configuration yet.
- Separate the plan for upgrading the Onboard/Skills package from the project-data migration.
- If the old executor lacks the v2 upgrade entry point, show how to prepare the reviewed v2
- executor and preserve the existing installation; request that installation approval separately.
- Agree an external private vault, custodian, retained originals, publication decisions,
- approved candidates and recovery limits. Show the real migration plan before requesting apply.
- After authorized apply, request deployment approval separately; consume the bound
- manifest/receipts for new rules/Skills/wiring, then verify data, host behavior and recovery evidence.
- Only after verification, display batch and fresh cleanup candidates and request deletion
- approval separately. Keep unknown content and backups; do not promise writable Trellis rollback.
- Stop at each unapproved phase. Do not use reset as a substitute for upgrade or migration.
- ```
- **Request cleanup planning, not immediate deletion:**
- ```text
- sbtd cleanup for /abs/project. Show verified batch candidates if available and run a fresh
- cleanup-legacy plan. List every target and disclose shared global MCP impact before asking
- for execution consent. Preserve unknown content, CLI packages, global data and backups.
- ```
- **Recover a specific batch:**
- ```text
- Use sbtd-workflow-onboard recovery for [the explicitly selected migration or upgrade batch].
- Verify the trusted private vault and bound receipts. Show recovery --phase plan,
- current drift, exact restoration scope and what cannot be restored. Wait for my approval
- before apply; retain backups and report partial results honestly.
- ```
- **Reconcile interrupted deployment evidence:**
- ```text
- Use sbtd-workflow-onboard migration --phase reconcile for [the batch whose apply completed
- but whose cumulative deployment evidence was never saved]. Bind the exact manifest and
- complete apply receipt, prove the historical evidence path genuinely absent, and freshly
- observe current state into one new typed evidence document at a new private path.
- Do not forge the missing receipt or claim the original deployment ran to completion;
- I confirm --yes explicitly and run the standard verify afterwards.
- ```
- The migration planner accepts characterized Trellis **0.6.15 / 0.6.17 data layouts**, not arbitrary old versions. Hash claims on user content are not deletion authority; missing approvals, contradictory task relationships and unknown host configuration still block. A genuinely host-free project can retain an empty platform list without inventing host files. Vendor-uninstall runtime support remains separately pinned.
- Stale recorded template hashes may be reconciled only against the installed package's reviewed **exact path/version/content pins**; migration neither refreshes the old hash file nor fetches templates at runtime. Mixed project `AGENTS.md` content is not generated-file ownership: replacing it still requires the existing signed approval, bound to the actual before-state and exact candidate. Recognition is not authorization to apply or clean up.
- Migration deployment retains the approved project-rule body, removing only the maintenance pause and adding the managed Graft fence; it does not silently swap that body for the generic template.
- OMP deployment also recognizes configuration-input changes already proved by bound successful migration receipts and intact originals. Unrecorded drift still blocks; this does not waive runtime-version checks or authorize a deployment retry.
- An interrupted deployment whose evidence was never saved is reconciled from **current state**, not backfilled: `migration --phase reconcile` requires the complete successful apply receipt, a genuinely absent historical evidence path, a new non-overwriting output path and explicit `--yes`. It revalidates the signed runtime lineage, retained originals and sealed resources, then writes one new evidence document explicitly typed `kind: current-state` / `historical_execution: unknown` — each result pairs a before-state proven by the retained original with a freshly measured after-state, and no historical exit code, success claim or timestamp is invented. Acceptance means the current postconditions hold, not that the original process exited cleanly or wrote new targets; the subsequent standard `verify` reports `acceptance_basis: current-state`. This authorizes no install, deployment retry or cleanup, and the regular deploy/retry/recovery gates are unchanged.
- Consumers recheck that the cited manifest/apply objects are safe files with the recorded digests. The observer must match the manifest runtime or its exact signature-approved successor; reverse or unrelated lineage is rejected. Historical observers need not match the current consumer, and cumulative retries never rewrite their provenance. This does not authenticate historical execution or authorize refreshing old evidence.
- New cross-runtime observations retain the verified signed authorization in `observer_lineage`, so later pair-file rotation does not erase historical observer authority. Consumers verify it with the installed trusted key, never a key supplied by the evidence. Legacy records without this proof still require the matching current pair (unless observer and manifest runtimes match); lost authority is not invented. Accepted plans and evidence recheck direct and followup-ancestor provenance at output; cleanup and recovery also recheck before writes. Post-write refusals preserve measured results without claiming successful acceptance.
- Current-state acceptance completes semantic/lineage validation before its final snapshot-only pass over observed artifacts and pinned inputs. That pass includes absent resources; it is not an atomic cross-process snapshot and does not promise objects can never change afterward.
- Already aligned project rules can remain untouched under exact-template evidence. Document-only legacy task folders are archived as documents, not fabricated tasks; historical task branches remain historical, with explicit deferred recovery instead of an automatic checkout or rebinding.
- Ordinary RC upgrades use content comparison and native upgrade receipts, not a new local lineage signature on every release. To retire an already verified original migration after one Onboard replacement, cleanup can consume paired `--upgrade-plan` / `--upgrade-receipt` and the intact old package backup. This is cleanup-only: it verifies existing historical signatures without executing old code and does not authorize followup or migration recovery. Proven unrelated deployment-discovery file/absent drift may be left untouched; target, retained-asset, profile, tool, footprint and provenance drift still block. See the [cleanup contract](sbtd-workflow-onboard/REFERENCE.md#cleanup-runtime).
- [Upgrade & recovery](sbtd-workflow-onboard/REFERENCE.md#upgrade-alignment) · [Migration](sbtd-workflow-onboard/REFERENCE.md#migration-runtime) · [Cleanup](sbtd-workflow-onboard/REFERENCE.md#cleanup-runtime)
- </details>
- <a id="task-prompts"></a>
- ### Use SBTD in daily development
- **Start here for ordinary work:**
- ```text
- Use sbtd-task in default mode for [goal] in this repository.
- Read the project rules and relevant lessons, inspect the existing implementation,
- make the smallest correct change, and exercise the changed path.
- Report changed files, actual verification, skipped checks and remaining risks.
- Do not install tools, migrate data, deploy or sync configuration without separate authorization.
- ```
- | Situation | Recommended prompt |
- |---|---|
- | Small, bounded change | “Use sbtd-task in **lite** mode for [change]. Keep a shared short task card, acceptance checklist and focused verification; preserve all project safety requirements.” |
- | High-risk or audited delivery | “Use sbtd-task in **strict** mode for [goal]. Create a new branch, record requirements and acceptance, produce the Book Gate Plan, complete applicable gates and independent review, then report evidence.” |
- | Unclear requirements | “Use **grill-with-docs** for [idea]. Read repository facts first, clarify decisions and record domain language. After the full interview, run **book-ddd-distilled-modeling** and show the independent DDD Boundary Review before design or implementation.” |
- | Reproducible bug | “Use **diagnosing-bugs** for [observed failure]. Establish a failing feedback loop, identify the cause, then use **tdd** for a regression test where appropriate. Verify the preserved behavior as well as the fix.” |
- | UI and regression | “For [page/flow], use **ui-ux-pro-max**, **shadcn** if the project uses it, and **impeccable** for visual review. Use **gherkin-bdd** and **project-validation**; persist Playwright assets with **web-ui-autotest-generator** only if maintainable inputs are available.” |
- | Mobile / Hybrid | “Use **maestro-mobile-e2e** for [journey] on [iOS/Android]. Confirm the BDD source, app, device, backend, accounts and selectors before creating flows. Run the applicable Maestro validation and retain native reports plus Chinese summaries.” |
- | Simplicity review | “Use **ponytail-review** on this diff. Propose deletions and simpler native solutions without weakening correctness, readability or safety.” Use **ponytail-audit** for a whole-repository audit, **ponytail-debt** for existing deferral markers. |
- | Resume or hand off | “Continue SBTD task [task ID]. Check its root, branch and effective mode; preserve that mode and ask if candidates conflict.” / “Prepare an **sbtd-task** handoff for [task ID], preserving completed work, evidence, next action and limitations.” |
- | Read behavior into a knowledge base | “Use **knowledge-base-integration** to read [configured product/repositories] at [target ref]. Resolve exact SHAs, produce the behavior catalog, and report missing mappings. **Mutation: none**; do not rewrite `.feature` or publish evidence.” |
- Want tracker deliverables? Explicitly request **to-spec** or **to-tickets**, identify the tracker and authorize publication. These are not substitutes for local task state, and their tracker setup is not automatically supplied by Onboard.
- Want a different reply style? `adhd mode` opts into **i-have-adhd**; `/caveman` requests compact replies when Caveman is available. `normal mode` exits both. **Reply style never changes default/lite/strict execution requirements.**
- <a id="workflow"></a>
- ## How the workflow fits together
- SBTD is this repository's combination of four practices, not a new runtime or framework:
- | Practice | Question it answers | Typical artifact or method |
- |---|---|---|
- | **SDD** — Specification-Driven Development | What are we building, and why? | Requirements, PRD/design, acceptance criteria |
- | **BDD** — Behavior-Driven Development | What can a user observe? | Project-owned Gherkin scenarios and traceable tests |
- | **TDD** — Test-Driven Development | How do we prove a change at the right boundary? | Red–green–refactor at agreed test seams |
- | **DDD** — Domain-Driven Design | Which terms, rules and boundaries must agree? | Glossary, context/ADR decisions, independent boundary review |
- ```text
- Read project facts and lessons → resolve task, branch, scope and mode
- → clarify requirements / domain language as needed
- → full grill-with-docs? Independent DDD Boundary Review must be confirmed
- → specify observable behavior → design and applicable pre-development gates
- → implement with risk-appropriate TDD → smoke and readability review
- → project-native validation + applicable Web / Mobile / evidence checks
- → release-readiness review when triggered → record actual completion
- ```
- ### Choose an execution mode
- | Mode | Use it for | Working contract |
- |---|---|---|
- | `default` | Ordinary tasks | On-demand investigation, implementation and focused validation; only needed local records |
- | `lite` | Bounded tasks needing a shared trail | Short checklist and shared task card, not a mandatory full document pack |
- | `strict` | Explicitly rigorous delivery | Applicable before-dev/check/finish obligations, Book Gate Plan and required evidence |
- Mode precedence is **your current explicit choice → the same task's valid record → default for a genuinely new task**. A suggested change waits for your decision; continuing a task does not reset its mode. All modes preserve explicit deliverables, project rules and safety. Every completed full `grill-with-docs` requires the independent DDD review in **all three modes**.
- Strict gates are triggered by facts: domain ambiguity, persistent/shared data, uncertain legacy behavior, existing production-code edits, or production runtime/deployment changes. Not every gate runs on every task; a required but unavailable gate is **blocked**, not passed. [Strict contract](sbtd-workflow-onboard/templates/skills/sbtd-task/references/strict.md) · [Method routing](sbtd-workflow-onboard/templates/skills/sbtd-task/references/methods.md) · [Workflow paths](docs/assets/sbtd-workflow-paths.md)
- ### State without a second source of truth
- - `task.md` owns mode, status and events. Ordinary default tasks use `.sbtd/tasks/<id>/`; lite/strict or explicitly shared tasks use `ai/tasks/<id>/`. `.sbtd/active-task.json` is only a bookmark.
- - `cancelled` is a terminal cancellation, **not successful completion**: `completed_at` stays null. Cancellation never cascades to children; archive and explicit reopen preserve its history. Imported `blocked` records with an unknown prior phase require an explicit recovery choice. Update the task runtime, schema and Skill references together before using these records with older installations.
- - Handoffs live under protected `docs/handoffs/` on a real pause/switch or explicit request; they never override the task. Pure Q&A/read-only work creates no task, identity or handoff files.
- - Developer identity is needed for a durable lesson write, not ordinary work. A valid local `.sbtd/developer` wins; only genuine absence in a verified linked worktree allows reading the main checkout's identity. Never guess names or replace a malformed identity.
- [Task state](sbtd-workflow-onboard/templates/skills/sbtd-task/references/state.md) · [Handoffs](sbtd-workflow-onboard/templates/skills/sbtd-task/references/handoff.md) · [Lessons](sbtd-workflow-onboard/templates/skills/lessons-record/SKILL.md)
- <a id="skills"></a>
- ## Skill catalog
- **Installed together, used when relevant.** Normal Onboard `init`/`reset` targets global Skills. Bootstrap alone and project-only initialization do not install or activate the complete global workflow. The [catalog](sbtd-workflow-onboard/catalog.json) owns membership; click a Skill for its full instructions and references.
- ### 14 bundled Skills
- | Skill | Job / when to use it |
- |---|---|
- | [sbtd-workflow-onboard](sbtd-workflow-onboard/SKILL.md) | Check, install, initialize, upgrade, migrate and recover explicitly selected environments |
- | [sbtd-task](sbtd-workflow-onboard/templates/skills/sbtd-task/SKILL.md) | Route work through default/lite/strict; manage task state and continuation |
- | [gherkin-bdd](sbtd-workflow-onboard/templates/skills/gherkin-bdd/SKILL.md) | Author observable behavior; distinguish writable BDD sync from read-only ingest |
- | [project-validation](sbtd-workflow-onboard/templates/skills/project-validation/SKILL.md) | Select native checks, applicable testing tools and truthful evidence/report status |
- | [web-ui-autotest-generator](sbtd-workflow-onboard/templates/skills/web-ui-autotest-generator/SKILL.md) | Generate/audit maintainable Playwright assets and selector/coverage manifests |
- | [maestro-mobile-e2e](sbtd-workflow-onboard/templates/skills/maestro-mobile-e2e/SKILL.md) | Derive Mobile/Hybrid Maestro flows from BDD and verify real device prerequisites |
- | [knowledge-base-integration](sbtd-workflow-onboard/templates/skills/knowledge-base-integration/SKILL.md) | Product registry, Evidence Policy, Revision Sets, read-only ingest and staged smoke |
- | [lessons-record](sbtd-workflow-onboard/templates/skills/lessons-record/SKILL.md) | Record durable lessons with validated author identity and topic/index ownership |
- | [book-ddd-distilled-modeling](sbtd-workflow-onboard/templates/skills/book-ddd-distilled-modeling/SKILL.md) | Review domain language and boundaries; mandatory after every full grill-with-docs |
- | [book-ddia-data-design](sbtd-workflow-onboard/templates/skills/book-ddia-data-design/SKILL.md) | Review data ownership, consistency, schema, cache, migration and recovery design |
- | [book-legacy-change-safety](sbtd-workflow-onboard/templates/skills/book-legacy-change-safety/SKILL.md) | Characterize existing behavior and establish a safety net before risky changes |
- | [book-refactoring-pass](sbtd-workflow-onboard/templates/skills/book-refactoring-pass/SKILL.md) | Review the smallest safe structure change before production-code edits |
- | [book-release-readiness](sbtd-workflow-onboard/templates/skills/book-release-readiness/SKILL.md) | Review operational risk and rollback after required validation |
- | [seo-geo](sbtd-workflow-onboard/templates/skills/seo-geo/SKILL.md) | Audit search/AI visibility for public web surfaces, not internal apps or API regression |
- <a id="external-skills"></a>
- ### 19 required external Skills
- These are reviewed **upstream mirrors**, not local forks. `auto` and `stable` install from the bundled snapshot without fetching upstream; only an explicit `upstream` selection opts into current upstream evaluation. Exact revisions, checksums and licenses live in the [stable manifest](sbtd-workflow-onboard/assets/external-skills/stable/MANIFEST.json).
- | Area | Skills | Purpose |
- |---|---|---|
- | Clarification | [grilling](sbtd-workflow-onboard/assets/external-skills/stable/skills/grilling/SKILL.md), [grill-me](sbtd-workflow-onboard/assets/external-skills/stable/skills/grill-me/SKILL.md), [grill-with-docs](sbtd-workflow-onboard/assets/external-skills/stable/skills/grill-with-docs/SKILL.md) | Stress-test decisions; use the documented variant for domain records |
- | Specifications | [to-spec](sbtd-workflow-onboard/assets/external-skills/stable/skills/to-spec/SKILL.md), [to-tickets](sbtd-workflow-onboard/assets/external-skills/stable/skills/to-tickets/SKILL.md) | Turn agreed discussions into tracker specs and dependency-aware work slices |
- | Design | [domain-modeling](sbtd-workflow-onboard/assets/external-skills/stable/skills/domain-modeling/SKILL.md), [codebase-design](sbtd-workflow-onboard/assets/external-skills/stable/skills/codebase-design/SKILL.md) | Shared language, context decisions, module interfaces and test seams |
- | Debug & test | [diagnosing-bugs](sbtd-workflow-onboard/assets/external-skills/stable/skills/diagnosing-bugs/SKILL.md), [tdd](sbtd-workflow-onboard/assets/external-skills/stable/skills/tdd/SKILL.md) | Evidence-first diagnosis and red–green feedback loops |
- | UI | [ui-ux-pro-max](sbtd-workflow-onboard/assets/external-skills/stable/skills/ui-ux-pro-max/SKILL.md), [impeccable](sbtd-workflow-onboard/assets/external-skills/stable/skills/impeccable/SKILL.md), [shadcn](sbtd-workflow-onboard/assets/external-skills/stable/skills/shadcn/SKILL.md) | UX/design systems, visual refinement and shadcn/ui-specific implementation |
- | Simplicity | [ponytail](sbtd-workflow-onboard/assets/external-skills/stable/skills/ponytail/SKILL.md), [ponytail-review](sbtd-workflow-onboard/assets/external-skills/stable/skills/ponytail-review/SKILL.md), [ponytail-audit](sbtd-workflow-onboard/assets/external-skills/stable/skills/ponytail-audit/SKILL.md), [ponytail-debt](sbtd-workflow-onboard/assets/external-skills/stable/skills/ponytail-debt/SKILL.md) | Minimal implementation, diff review, whole-repo audit and deferral ledger |
- | Agent collaboration | [handoff](sbtd-workflow-onboard/assets/external-skills/stable/skills/handoff/SKILL.md), [writing-for-agents](sbtd-workflow-onboard/assets/external-skills/stable/skills/writing-for-agents/SKILL.md) | General handoff prose and agent-facing documentation; SBTD state remains owned by sbtd-task |
- | Reply structure | [i-have-adhd](sbtd-workflow-onboard/assets/external-skills/stable/skills/i-have-adhd/SKILL.md) | Opt-in, session-level, action-first replies; installation does not activate it |
- Onboard uses the **Ponytail skill-only provider**. An enabled official Ponytail plugin is a conflict, not permission to disable it; plugin management and `ponytail-gain`/`ponytail-help` are outside Onboard. [Provider boundary](sbtd-workflow-onboard/REFERENCE.md#ponytail-provider-boundary)
- <a id="verification"></a>
- ## Tools and verification boundaries
- | Tool / layer | Owns | Does not prove |
- |---|---|---|
- | Graft | Pinned, scoped structural analysis and impact assistance | Compiler semantics, business correctness or automatic host readiness |
- | Chrome DevTools MCP | Browser runtime, console/network/performance diagnosis | Repeatable CI regression |
- | Playwright MCP | Page exploration and locator assistance | A passing project Playwright suite |
- | Playwright CLI | Project-local Web regression and E2E | Full-stack behavior when only mocks/contracts are available |
- | Maestro CLI / MCP | Mobile/Hybrid flows; device/flow diagnostics; optional Web smoke | Primary Web regression or unavailable real-device behavior |
- | RTK / Caveman | Terminal-output / reply compression | Test execution, reports or reduced workflow obligations |
- Graft installation is separately confirmed and pinned by the [managed runtime](sbtd-workflow-onboard/scripts/graft_runtime.py). One global `sbtd-graft` connection per effective Codex/OMP configuration domain locks the real repository/worktree from startup cwd; project initialization prepares local graphs. No parent-directory multi-project graph, implicit cloud enrichment, or silent legacy binding replacement. Codex hooks are a separate opt-in; OMP setup does not write hooks. [Wiring contract](sbtd-workflow-onboard/REFERENCE.md#codex-and-omp-wiring-and-deployment)
- Managed Graft stays on the Graft command/tool contract even when Trail is installed: child environments disable automatic Trail switching and inherited Trail configuration. Project `.trail` notes are subject to the same no-link/no-special-file scope checks as native graph inputs. See [pin acceptance scenarios](sbtd-workflow-onboard/REFERENCE.md#graft-pin-acceptance-scenarios).
- **Report what actually ran.** Native commands are preferred for report-producing tests. Keep failed runs, named native/raw reports and same-stem **Chinese** summaries. Distinguish `full-stack`, `contract-backed`, `mock-backed`/`app-mocked`, `backend-only`, `smoke-only` and `blocked`; a generated report is not a passing test. Dirty local evidence is not exact PR-head CI proof.
- Agent-authored execution summaries use the [fixed Chinese report template](sbtd-workflow-onboard/templates/skills/project-validation/references/run-summary.zh-CN.md.template): conclusion/counts, run metadata, commands, BDD/scope, case results, failures/reruns, API URI coverage, artifacts/status, and limitations. Preserve failed rounds and source/deployment boundaries; unsupported fields need an explicit reason, not fabricated values. Coverage scoring is an appendix, not a substitute for execution results. Historical reports remain unchanged; reformatting retained evidence is a separately labeled preview, not a new test run.
- | Asset | Default location in a target project |
- |---|---|
- | BDD source | Existing project `.feature` convention; Chinese scenario text + English keywords when no convention exists |
- | Playwright test manifests | `tests/e2e/manifest/` — pass explicit paths, not root-level generator defaults |
- | Playwright retained reports | `tests/e2e/reports/html/` |
- | API reports | `tests/api/reports/` |
- | Maestro flows / reports | `maestro/flow/` / `.maestro/reports/` |
- | Unit reports | Project convention; otherwise `tests/unit/reports/` when required |
- | SBTD task-local evidence | `ai/tasks/**/reports/` — ignored; task documents remain shareable |
- Knowledge-base P1.1 produces read-only catalogs and smoke bundles; remote Evidence Store/PR Checks and publication remain P2 scope. BDD `sync` is a separate writable workflow. [Knowledge-base guide](sbtd-workflow-onboard/templates/skills/knowledge-base-integration/SKILL.md) · [Evidence contract](sbtd-workflow-onboard/templates/skills/project-validation/SKILL.md)
- <details>
- <summary><strong>Optional tools and common pitfalls</strong></summary>
- - Playwright is project-local. Java 17+ and Maestro, optional MCPs, RTK and Caveman require their applicable setup choices; an installed Skill does not prove its CLI/server is callable.
- - Caveman may compress repeated status updates under the global auto-lite policy; `normal mode` opts out for the task. ADHD structure is explicit opt-in only. See [presentation rules](sbtd-workflow-onboard/templates/skills/sbtd-task/references/presentation.md).
- - React Bits is an optional project enhancement, not a shadcn dependency. Free registries must be known; paid tiers require an existing entitlement and local key handling. Never put keys in chat, examples or reports. [React Bits scope](sbtd-workflow-onboard/REFERENCE.md#react-bits)
- - `init` is not content alignment; `reset` is not safe upgrade recovery. Upgrade verification separates disk, protocol and actual host loading; a preserved customization is not full alignment.
- - Legacy Trellis/GitNexus is migration input, not the current workflow. Normal setup does not initialize Trellis or perform legacy cleanup. Cleanup requires a displayed list and consent; backups have a separate retention/destruction boundary.
- </details>
- <a id="reference"></a>
- ## Reference and manual entrypoints
- | Need | Read |
- |---|---|
- | Full Onboard commands, scope and troubleshooting | [SKILL](sbtd-workflow-onboard/SKILL.md) · [REFERENCE](sbtd-workflow-onboard/REFERENCE.md) |
- | Bootstrap / init / reset / project-only flowcharts | [Bootstrap](docs/assets/npx-skills-global-onboard-install.md) · [Init](docs/assets/onboard-skill-init.md) · [Reset](docs/assets/onboard-skill-reset.md) · [Project-only](docs/assets/onboard-init-projects.md) |
- | Upgrade / migration / cleanup / recovery | [Upgrade](sbtd-workflow-onboard/REFERENCE.md#upgrade-alignment) · [Migration & recovery](sbtd-workflow-onboard/REFERENCE.md#migration-runtime) · [Cleanup](sbtd-workflow-onboard/REFERENCE.md#cleanup-runtime) |
- | Global / project rules | [Global template](sbtd-workflow-onboard/templates/agents/AGENTS.global.md) · [Project template](sbtd-workflow-onboard/templates/agents/AGENTS.project.md) |
- | Release history / monitored versions | [English CHANGELOG](CHANGELOG.md) · [中文变更日志](CHANGELOG.zh.md) · [ENTRYPOINT](ENTRYPOINT.md) · [Bilingual release/tag template](docs/release-notes-template.md) |
- <details>
- <summary><strong>Manual setup after bootstrap, or from a cloned checkout</strong></summary>
- Set `SBTD_ONBOARD_DIR` to the **actual installed package directory**, with dependencies prepared. First inspect:
- ```bash
- python "$SBTD_ONBOARD_DIR/scripts/onboard.py" plan \
- --platform codex --projects-root /abs/project-one,/abs/project-two --json
- ```
- Only after reviewing and approving that same scope:
- ```bash
- python "$SBTD_ONBOARD_DIR/scripts/onboard.py" init \
- --platform codex --projects-root /abs/project-one,/abs/project-two --yes --json
- ```
- A cloned checkout also provides complete interactive installers:
- ```bash
- bash install.sh
- ```
- ```powershell
- pwsh -File .\install.ps1
- ```
- For project-only setup, use `bash install.sh --platform codex --init-projects /abs/project` or `pwsh -File .\install.ps1 -Platform codex -InitProjects "C:\work\project"`. This is mutually exclusive with ordinary `--projects-root`/`--action` selections. Normal root-installer `init`/`reset` with `--yes`/`-Yes` and no project roots is **global-only**, not an implicit selection of cwd. Confirmation flags approve selected operations; they do not bypass conflicts or authorize migration.
- </details>
- <a id="repository"></a>
- ## Repository and maintenance
- | Path | Role |
- |---|---|
- | `README.md` / `README.zh.md` | English and Chinese reader entrypoints; detailed contracts stay in linked sources |
- | `sbtd-workflow-onboard/` | Self-contained installable Skill: runtime `scripts/`, payload `templates/`, mirrored `assets/`, catalog and reference |
- | `sbtd-runtime/` | Optional local statistics runtime and contracts, including a runnable Dashboard `serve` ([installation and use](sbtd-runtime/docs/install-and-use.md)). Not installed or copied by Onboard; start it manually from the repository root after installing the documented dependencies |
- | `install.sh` / `install.ps1` | Root installation interfaces; source root is the Onboard directory |
- | `ENTRYPOINT.md` | Tracked monitoring baseline and recoverable maintenance entrypoint |
- | `docs/lessons.md` | Required short lessons entry; index/topic detail is loaded only when relevant |
- | `prompts/automations/sbtd-workflow-tools-version-check.md` | Versioned automation prompt, not a live automation update |
- | `prompts/automations/references/` | Mandatory version-check scope policy and topic-routed compatibility checks |
- | `.github/workflows/validation.yml` | Project-native validation matrix |
- This source repository's root `AGENTS.md` is **optional, ignored and local-only**; it is not the project template or a fresh-clone prerequisite. Its root `.gitignore` is intentionally separate from the [target-project template](sbtd-workflow-onboard/templates/project/.gitignore):
- ```gitignore
- .DS_Store
- /.sbtd
- /docs/handoffs
- /ai/tasks/**/reports
- /graft
- /.graft
- __pycache__/
- /.pytest_cache/
- /.ruff_cache/
- AGENTS.md
- .chrome-devtools-mcp/
- .playwright-mcp/
- ```
- Ignore rules do not sanitize secrets, untrack existing files or authorize deletion. Task reports are local by default; publishing evidence requires redaction and a separately approved destination. **This template-source repository does not create `.feature` files**; its durable behavioral specifications use Markdown and existing tests.
- For source changes, assess both language READMEs, [English CHANGELOG](CHANGELOG.md), [Chinese CHANGELOG](CHANGELOG.zh.md) and the [versioned automation prompt](prompts/automations/sbtd-workflow-tools-version-check.md). The changelogs must match entry for entry: same versions, dates, order, facts, URLs, commit SHAs and code identifiers; only prose language differs. Update the top unpublished section in both, and preserve published history. Ordinary edits do **not** sync installed copies or live automation. Repository-maintenance `sync` requires explicit authorization; `update` advances monitored baselines other than Graft and archives the analyzed update. Graft's ENTRYPOINT baseline follows the pin in a published SBTD workflow version and is not advanced by official Graft releases or `update`. These are not Onboard upgrade commands or BDD sync requests.
- The version-check automation uses a short main prompt, a per-run scope policy and an on-demand impact checklist. It validates the assigned Orca workspace, protects existing changes, distinguishes unavailable evidence from “no update”, and keeps `ENTRYPOINT.md` as the fixed baseline for official tool releases. Graft is the exception: its recorded baseline changes only when a published workflow version contains a new agreed pin. Native tag names are retained separately from comparison versions. When no confirmed unpublished CHANGELOG section exists, release-note proposals stay in `UPDATE.md` or the run output; the automation does not invent the next tag. Updating these source files does not update the live automation; that remains an explicit `sync` operation.
- The native full-suite command remains `python -B -m unittest discover -s tests -p 'test_*.py'`. CI discovers that complete Linux set and partitions it into disjoint shards weighted by measured per-case seconds, splitting fixture-free cases individually and keeping class/module fixtures together (cases without a recorded weight are estimated at the median and listed in each shard inventory); Windows partitions its native scope without repeating overlapping PowerShell/Unicode selectors. macOS keeps its native scope. The existing check names aggregate all required shards; any failed, cancelled or missing shard blocks success. The minimum supported TOML-editor run remains a separate dependency variant, not a duplicate. Per-case timings, skip reasons and Chinese result summaries are retained as CI artifacts. Consult the [workflow](.github/workflows/validation.yml) and [runner](tests/run_ci.py) for exact scope. Source checks, installed-copy checks, real host loading and release acceptance remain separate evidence.
- Catalog-independent migration boundary tests narrow only their installation inputs: they retain the complete Onboard launcher package, multiple sibling Skills and all file-routing operations. Full-catalog lifecycle and installed-copy tests remain separate anchors. Every stage still runs the real migration/recovery APIs and fresh safety checks; smaller fixtures do not authorize cached verdicts, reused receipts or omitted drift cases. Compare total runner cost separately from parallel wall-clock time.
- Required native Windows checks (including ACLs, junctions, Unicode, PowerShell and enabled case-sensitive paths) and Linux case-sensitive checks must pass, not merely be selected: skip or expected failure blocks their shard.
- CI artifacts retain each native run attempt without overwriting failures. Partial retries may reuse successful shards from the same SHA; aggregation selects each shard's newest report, rejects newer failures or ambiguous duplicates, and proves that the union covers the complete scope exactly once. Skip totals count native events, including skipped subtests; parent-case status counts can differ. Preserve subtest identities and reasons when comparing runs.
- Windows currently uses four shards, Linux three, and macOS one job. After downloading a complete successful native report set, refresh scheduling inputs with `python -B tests/run_ci.py --platform windows --output <downloaded-reports> --refresh-weights` (use `linux` for Linux). Refresh requires a nonempty source revision and an unambiguous, complete, disjoint latest-attempt set; duplicate measurements or noncanonical shard filenames are rejected. Weights only change allocation, never test selection. Equal line/branch coverage alone does not justify removing a behavioral or platform boundary test.
- <a id="license"></a>
- ## License and credits
- Original repository and bundled original content use [Apache License 2.0](LICENSE), with [Onboard LICENSE](sbtd-workflow-onboard/LICENSE) and [NOTICE](sbtd-workflow-onboard/NOTICE) shipped in the package. Third-party mirrors retain their own licenses and pinned provenance; the adapted [seo-geo NOTICE](sbtd-workflow-onboard/templates/skills/seo-geo/NOTICE) records its upstream source and local changes.
sbtd-workflow-onboard/scripts/onboard.py · Bundled script · 7,594 lines · 1 finding marked
- #!/usr/bin/env python3
- from __future__ import annotations
- import argparse
- import datetime as dt
- import filecmp
- import hashlib
- import json
- import os
- import platform
- import re
- import shlex
- import shutil
- import stat
- import subprocess
- import sys
- import tarfile
- import tempfile
- import urllib.error
- import urllib.request
- from collections.abc import Callable
- from dataclasses import dataclass
- from pathlib import Path
- from typing import TYPE_CHECKING, cast
- if __name__ == "__main__":
- # Installed source directories can themselves be sealed deployment inputs.
- # CLI imports must not mutate those inputs by adding bytecode caches.
- sys.dont_write_bytecode = True
- if TYPE_CHECKING:
- from sbtd_identity import IdentityResult
- from graft_runtime import check_graft, install_graft
- from onboard_arguments import (
- SingleValueAction,
- WorkflowArgumentParser,
- _add_migration_context,
- _check_migration_context,
- add_cleanup_legacy_parser,
- add_migration_parser,
- add_recovery_parser,
- add_upgrade_parser,
- validate_cleanup_legacy_args,
- validate_developer_name,
- validate_migration_args,
- validate_recovery_args,
- validate_upgrade_args,
- )
- from sbtd_project import StateInspection, TaskDataError, inspect_project_state
- SKILL_DIR = Path(__file__).resolve().parents[1]
- SKILL_ENTRY_DIR = Path(__file__).absolute().parents[1]
- ONBOARD_SCRIPT_PATH = Path(__file__).absolute()
- CATALOG_PATH = SKILL_DIR / "catalog.json"
- EXTERNAL_STABLE_ROOT = SKILL_DIR / "assets" / "external-skills" / "stable"
- EXTERNAL_STABLE_MANIFEST = EXTERNAL_STABLE_ROOT / "MANIFEST.json"
- def read_skill_frontmatter_name(skill_md: Path) -> str | None:
- try:
- content = skill_md.read_bytes()
- except OSError:
- return None
- return skill_frontmatter_name_from_bytes(content)
- def skill_frontmatter_name_from_bytes(content: bytes) -> str | None:
- try:
- lines = content.decode("utf-8").splitlines()
- except UnicodeDecodeError:
- lines = content.decode("utf-8", errors="ignore").splitlines()
- if not lines or lines[0].strip() != "---":
- return None
- for line in lines[1:80]:
- stripped = line.strip()
- if stripped == "---":
- return None
- if stripped.startswith("name:"):
- return stripped.split(":", 1)[1].strip().strip("'\"")
- return None
- def validate_relative_catalog_path(value: object, field: str) -> str:
- if not isinstance(value, str) or not value:
- raise RuntimeError(f"{field} must be a non-empty relative path")
- if (
- Path(value).is_absolute()
- or re.match(r"^(?:[A-Za-z]:[\\/]|[\\/])", value)
- or re.search(r"(^|[\\/])\.\.([\\/]|$)", value)
- ):
- raise RuntimeError(
- f"{field} must be a relative path contained by its root: {value}"
- )
- return value
- def resolve_local_catalog_source(value: object, entry_id: str) -> Path:
- relative = validate_relative_catalog_path(
- value, f"SBTD Onboard catalog source for {entry_id}"
- )
- source = (SKILL_DIR / relative).resolve()
- try:
- source.relative_to(SKILL_DIR)
- except ValueError as exc:
- raise RuntimeError(
- f"SBTD Onboard catalog source escapes the Skill root: {relative}"
- ) from exc
- if not source.exists():
- raise RuntimeError(
- f"SBTD Onboard catalog source is missing for {entry_id}: {source}"
- )
- return source
- def valid_https_repository_url(value: object) -> bool:
- return (
- isinstance(value, str)
- and re.fullmatch(r"https://[^/?#\s]+/(?:[^/?#\s]+/)*[^/?#\s]+/?", value)
- is not None
- )
- CATALOG_KIND_CONTRACTS: dict[str, tuple[str, frozenset[str]]] = {
- "agent-template": (
- "agent:",
- frozenset({"codex-global-agents", "project-agents"}),
- ),
- "project-template": ("project:", frozenset({"project-gitignore"})),
- "bundled-skill": (
- "skill:",
- frozenset({"skill", "skill:sbtd-workflow-onboard"}),
- ),
- "external-skill": ("skill:", frozenset({"external-skill"})),
- }
- def load_catalog() -> dict[str, object]:
- try:
- catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- raise RuntimeError(f"cannot read SBTD Onboard catalog: {exc}") from exc
- if (
- catalog.get("schemaVersion") != 1
- or catalog.get("name") != "sbtd-workflow-onboard"
- ):
- raise RuntimeError("SBTD Onboard catalog identity or schema version is invalid")
- entries = catalog.get("entries")
- if not isinstance(entries, list) or not entries:
- raise RuntimeError("SBTD Onboard catalog must contain entries")
- seen: set[str] = set()
- for entry in entries:
- if not isinstance(entry, dict):
- raise RuntimeError("SBTD Onboard catalog entries must be objects")
- if set(entry) != {"id", "kind", "source", "targetRole"}:
- raise RuntimeError("SBTD Onboard catalog entries have invalid fields")
- entry_id = entry.get("id")
- entry_kind = entry.get("kind")
- source_value = entry.get("source")
- target_role = entry.get("targetRole")
- if (
- not isinstance(entry_id, str)
- or re.fullmatch(r"(agent|project|skill):[a-z0-9][a-z0-9-]*", entry_id)
- is None
- or entry_id in seen
- ):
- raise RuntimeError(
- f"SBTD Onboard catalog entry id is invalid or duplicated: {entry_id}"
- )
- contract = CATALOG_KIND_CONTRACTS.get(str(entry_kind))
- if contract is None:
- raise RuntimeError(f"SBTD Onboard catalog kind is invalid for {entry_id}")
- expected_prefix, allowed_roles = contract
- if not entry_id.startswith(expected_prefix):
- raise RuntimeError(
- f"SBTD Onboard catalog id does not match kind {entry_kind}: {entry_id}"
- )
- if not isinstance(target_role, str) or target_role not in allowed_roles:
- raise RuntimeError(
- f"SBTD Onboard catalog target role is invalid for {entry_id}: {target_role}"
- )
- if entry_kind == "external-skill":
- if not isinstance(source_value, dict) or set(source_value) != {
- "repo",
- "subpath",
- "aliases",
- }:
- raise RuntimeError(
- f"SBTD Onboard external source is invalid for {entry_id}"
- )
- repo = source_value.get("repo")
- subpath = source_value.get("subpath")
- aliases = source_value.get("aliases")
- if not valid_https_repository_url(repo):
- raise RuntimeError(
- f"SBTD Onboard external source repo must be a valid HTTPS "
- f"repository URL for {entry_id}"
- )
- validate_relative_catalog_path(
- subpath, f"SBTD Onboard external source subpath for {entry_id}"
- )
- if (
- not isinstance(aliases, list)
- or not aliases
- or any(not isinstance(alias, str) or not alias for alias in aliases)
- or len(aliases) != len(set(aliases))
- ):
- raise RuntimeError(
- f"SBTD Onboard external source is invalid for {entry_id}"
- )
- else:
- source = resolve_local_catalog_source(source_value, entry_id)
- if entry_kind in {"agent-template", "project-template"}:
- if not source.is_file():
- raise RuntimeError(
- f"SBTD Onboard {entry_kind} source must be a regular file "
- f"for {entry_id}: {source}"
- )
- else:
- if not source.is_dir():
- raise RuntimeError(
- f"SBTD Onboard bundled-skill source must be a directory "
- f"for {entry_id}: {source}"
- )
- expected_name = entry_id.removeprefix("skill:")
- actual_name = read_skill_frontmatter_name(source / "SKILL.md")
- if actual_name != expected_name:
- raise RuntimeError(
- f"SBTD Onboard bundled-skill frontmatter name must match "
- f"{entry_id}: expected {expected_name}, got "
- f"{actual_name or '<missing>'}"
- )
- seen.add(entry_id)
- return cast(dict[str, object], catalog)
- def catalog_source(catalog: dict[str, object], entry_id: str) -> Path:
- entries = cast(list[dict[str, object]], catalog["entries"])
- for entry in entries:
- if entry["id"] == entry_id:
- return (SKILL_DIR / str(entry["source"])).resolve()
- raise RuntimeError(f"SBTD Onboard catalog entry is missing: {entry_id}")
- def catalog_external_skill_sources(
- catalog: dict[str, object],
- ) -> dict[str, dict[str, object]]:
- sources: dict[str, dict[str, object]] = {}
- for entry in cast(list[dict[str, object]], catalog["entries"]):
- if entry.get("kind") != "external-skill":
- continue
- source = cast(dict[str, object], entry["source"])
- sources[str(entry["id"]).removeprefix("skill:")] = {
- "repo": str(source["repo"]),
- "subpath": str(source["subpath"]),
- "aliases": tuple(cast(list[str], source["aliases"])),
- }
- return sources
- CATALOG = load_catalog()
- GLOBAL_AGENTS_TEMPLATE = catalog_source(CATALOG, "agent:codex-global")
- PROJECT_AGENTS_TEMPLATE = catalog_source(CATALOG, "agent:project")
- PROJECT_GITIGNORE_TEMPLATE = catalog_source(CATALOG, "project:gitignore")
- SKILL_SOURCES = {
- str(entry["id"]).removeprefix("skill:"): (
- SKILL_DIR / str(entry["source"])
- ).resolve()
- for entry in cast(list[dict[str, object]], CATALOG["entries"])
- if entry.get("kind") == "bundled-skill"
- }
- EXTERNAL_SKILL_SOURCES = catalog_external_skill_sources(CATALOG)
- NVM_INSTALL_URL = "https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.5/install.sh"
- RTK_INSTALL_URL = (
- "https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh"
- )
- TEMURIN21_RELEASES_URL = "https://github.com/adoptium/temurin21-binaries/releases"
- TEMURIN_RELEASES_API_TEMPLATE = (
- "https://api.github.com/repos/adoptium/temurin{major}-binaries/releases/latest"
- )
- MAESTRO_INSTALL_URL = "https://get.maestro.mobile.dev"
- CAVEMAN_SOURCE_REPO = "https://github.com/JuliusBrussee/caveman.git"
- CAVEMAN_PINNED_REF = "v4.0.1"
- CAVEMAN_PINNED_REVISION = "d262ab3882952a59312ff3537cd86d894523c5ab"
- CAVEMAN_CORE_SKILL_SHA256 = "415d43518f2b1a9498c15a445d4657117b129ee5e81b19454ce348439cc6672b"
- CAVEMAN_KNOWN_CORE_SKILL_SHA256 = {
- "v4.0.1": CAVEMAN_CORE_SKILL_SHA256,
- "v2.6.0": "c4d7354b4b063d54601fcdd5097a5b1713d1a1a2e386ac39efa438aa1ffef8ce",
- "v2.5.0": "fec5718a391dd9d8c89746d39e0cc0fa7aa5b50447669a15e44c3244167828c0",
- }
- CAVEMAN_KNOWN_FAMILY_SHA256 = {
- # Reviewed at CAVEMAN_PINNED_REVISION.
- "v4.0.1": {
- "cavecrew": "2ba088a27199b7c41b9f9765bf6e8d6f580a645ce0094051f8f5d5733d6cb4de",
- "caveman": "7d9d77c6a276780f9295d377bb8dfb1fb5be5c16ccb5043e0d1b2acef23508ed",
- "caveman-commit": "68fce6cc3c50050e8ede6df99d4f478582d9b5952782c441acf2477b16d706db",
- "caveman-compress": "bf58594d45b03e559935a94a56528835f199808c282a6d7f29105e9599321db5",
- "caveman-discover": "0a52f133aef4d3b81e9554cc43132bcf1accedb1154f6ac8e75df24f5f58f537",
- "caveman-evidence-review": "fc5959727ef2f822d756c7e837abea51be91c32e0ca87758c1b77f68c98d5552",
- "caveman-explore": "8fa46ff537d60dba875442db7530918fe4790cfddfb2d60d23e3a82ba6c95a94",
- "caveman-help": "346cdf9f89e8be8e8006f2ec01836dd87f365f7b70853dc871aedff58f5c50ad",
- "caveman-learn": "2c2f56c8792c975a5b250348f970f24eb2654a364fd1162fb08c35625502fda9",
- "caveman-manage": "e6ad788986936cbe49bdf12cf122fa966dd9e20c0ea7716397e0049d9f833d5a",
- "caveman-optimize": "35dd36fa4b6fe800e9c1db8818b5e79ee18448372f33bd48ee593516d131a947",
- "caveman-review": "d50a54e5b5a5bae7fcac1a4472cfd34ce47c9a8183d1357928eac4c2bd8322db",
- "caveman-setup": "546eb697be5b87cec06117c4eb6d3e9eac55331cb860d2743c2d7b6f45c261b4",
- "caveman-stats": "00a8e24bd1544e07bf2e372700015746dc7ba3937b1d161bcf9377b2147921e4",
- },
- # Reviewed at f9a039a93d249f3fcdb47a9e02544cd1ce37ba4a.
- "v2.5.0": {
- "cavecrew": "673643f8c42f06f0904eb975a56923583c2cd47ce4bf5a5ac1e5e49b8e4b2c66",
- "caveman": "cfe5ad82c6b43421624d20dd30dc83100bb9516f889b0b2a8bb2cdd0dbd2a6be",
- "caveman-commit": "68fce6cc3c50050e8ede6df99d4f478582d9b5952782c441acf2477b16d706db",
- "caveman-compress": "3d618a06313658b3f108bf82c2f97591643e7fee83cb5990c30e5a044e9a0587",
- "caveman-discover": "0a52f133aef4d3b81e9554cc43132bcf1accedb1154f6ac8e75df24f5f58f537",
- "caveman-evidence-review": "fc5959727ef2f822d756c7e837abea51be91c32e0ca87758c1b77f68c98d5552",
- "caveman-explore": "81c49c489e8d94ffb4cf47e05632235a88d125c4a05e6d2cf64bc0535aa87895",
- "caveman-help": "63b42410962891586b7a5317391e39b8b0a90370144be4d7281e43c68b140947",
- "caveman-learn": "9c1442a0b61945e1bc37240d9a494be4658768e56e61b76943fb0cbc18d805cd",
- "caveman-manage": "e6ad788986936cbe49bdf12cf122fa966dd9e20c0ea7716397e0049d9f833d5a",
- "caveman-optimize": "35dd36fa4b6fe800e9c1db8818b5e79ee18448372f33bd48ee593516d131a947",
- "caveman-review": "d50a54e5b5a5bae7fcac1a4472cfd34ce47c9a8183d1357928eac4c2bd8322db",
- "caveman-setup": "546eb697be5b87cec06117c4eb6d3e9eac55331cb860d2743c2d7b6f45c261b4",
- "caveman-stats": "652eaffb8f6c635431ed238fa7ae2126e138ad7b1d26fae7390f8edc1af17bb0",
- },
- # Reviewed at b82c0ad42c2bedc1f2cd78e414dadfaffbaaeec3.
- "v2.6.0": {
- "cavecrew": "673643f8c42f06f0904eb975a56923583c2cd47ce4bf5a5ac1e5e49b8e4b2c66",
- "caveman": "26b5e133a79a0251dad5e57acaa22ef601731fe59fb4637f9f150d7dfc250bad",
- "caveman-commit": "68fce6cc3c50050e8ede6df99d4f478582d9b5952782c441acf2477b16d706db",
- "caveman-compress": "3d618a06313658b3f108bf82c2f97591643e7fee83cb5990c30e5a044e9a0587",
- "caveman-discover": "0a52f133aef4d3b81e9554cc43132bcf1accedb1154f6ac8e75df24f5f58f537",
- "caveman-evidence-review": "fc5959727ef2f822d756c7e837abea51be91c32e0ca87758c1b77f68c98d5552",
- "caveman-explore": "81c49c489e8d94ffb4cf47e05632235a88d125c4a05e6d2cf64bc0535aa87895",
- "caveman-help": "63b42410962891586b7a5317391e39b8b0a90370144be4d7281e43c68b140947",
- "caveman-learn": "9c1442a0b61945e1bc37240d9a494be4658768e56e61b76943fb0cbc18d805cd",
- "caveman-manage": "e6ad788986936cbe49bdf12cf122fa966dd9e20c0ea7716397e0049d9f833d5a",
- "caveman-optimize": "35dd36fa4b6fe800e9c1db8818b5e79ee18448372f33bd48ee593516d131a947",
- "caveman-review": "d50a54e5b5a5bae7fcac1a4472cfd34ce47c9a8183d1357928eac4c2bd8322db",
- "caveman-setup": "546eb697be5b87cec06117c4eb6d3e9eac55331cb860d2743c2d7b6f45c261b4",
- "caveman-stats": "652eaffb8f6c635431ed238fa7ae2126e138ad7b1d26fae7390f8edc1af17bb0",
- },
- }
- CAVEMAN_DRIFT_ADVICE = (
- "Local caveman family payload is newer or customized; "
- "review it before replacing the pinned baseline."
- )
- # Monitoring the v* installer/skill tag line only reports drift. A baseline
- # bump requires a human review of SKILL.md and installer behavior, then updates
- # ref, revision, hashes, and tests together in one change.
- JAVA_MIN_MAJOR = 17
- BUNDLED_SKILL_LEGACY_NAMES = {
- "sbtd-workflow-onboard": ("kuno-workflow-onboard-skills",),
- }
- CLI_TOOLS = (
- {
- "name": "rtk",
- "versionArgs": ("--version",),
- "globalInstall": "curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh",
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 359 on GitHub
- "projectInstall": None,
- "advice": "Install RTK from rtk-ai/rtk and verify with `rtk gain`; do not treat the unrelated Rust Type Kit package as valid.",
- },
- )
- AGENT_CLI_SPECS = {
- "codex": {
- "label": "Codex",
- "command": "codex",
- "npmPackage": "@openai/codex",
- "versionArgs": ("--version",),
- "advice": "Install the latest Codex CLI globally from the official @openai/codex npm package.",
- },
- "claude": {
- "label": "Claude Code",
- "command": "claude",
- "npmPackage": "@anthropic-ai/claude-code",
- "versionArgs": ("--version",),
- "advice": "Install the latest Claude Code CLI globally from the official @anthropic-ai/claude-code npm package.",
- },
- "kimi": {
- "label": "Kimi Code",
- "command": "kimi",
- "npmPackage": "@moonshot-ai/kimi-code",
- "versionArgs": ("--version",),
- "advice": "Install the latest Kimi Code CLI globally from the official @moonshot-ai/kimi-code npm package. The npm distribution requires a supported Node.js runtime.",
- },
- "oh-my-pi": {
- "label": "Oh My Pi",
- "command": "omp",
- "npmPackage": "@oh-my-pi/pi-coding-agent",
- "versionArgs": ("--version",),
- "advice": "Install the latest Oh My Pi CLI globally from @oh-my-pi/pi-coding-agent and verify the omp command. Upstream recommends its native or Bun installer, so npm installation must pass the command verification gate.",
- },
- }
- AGENT_PLATFORM_ALIASES = {
- "codex": "codex",
- "claude": "claude",
- "claude-code": "claude",
- "claudecode": "claude",
- "kimi": "kimi",
- "kimi-code": "kimi",
- "kimicode": "kimi",
- "oh-my-pi": "oh-my-pi",
- "ohmypi": "oh-my-pi",
- "omp": "oh-my-pi",
- }
- BUNDLED_SKILLS = tuple(SKILL_SOURCES.keys())
- MATTPOCOCK_CANONICAL_SKILLS = (
- "diagnosing-bugs",
- "tdd",
- "grill-me",
- "grill-with-docs",
- "grilling",
- "domain-modeling",
- "codebase-design",
- "handoff",
- "writing-for-agents",
- "to-spec",
- "to-tickets",
- )
- MATTPOCOCK_LEGACY_RENAMES = {
- "diagnose": "diagnosing-bugs",
- "write-a-skill": "writing-for-agents",
- "writing-great-skills": "writing-for-agents",
- "to-prd": "to-spec",
- "to-issues": "to-tickets",
- }
- MATTPOCOCK_REMOVED_SKILLS = {
- "zoom-out": "Removed upstream; use repo exploration, codebase-design, or book-refactoring-pass instead.",
- }
- MATTPOCOCK_REQUIRED_DEPENDENCIES = {
- "tdd": ("codebase-design",),
- "grill-me": ("grilling",),
- "grill-with-docs": ("grilling", "domain-modeling"),
- }
- PONYTAIL_REQUIRED_SKILLS = (
- "ponytail",
- "ponytail-review",
- "ponytail-audit",
- "ponytail-debt",
- )
- REFERENCED_SKILLS = (
- *MATTPOCOCK_CANONICAL_SKILLS,
- "ui-ux-pro-max",
- "impeccable",
- "shadcn",
- *PONYTAIL_REQUIRED_SKILLS,
- "i-have-adhd",
- )
- INTERACTION_SKILLS = ("caveman",)
- if set(EXTERNAL_SKILL_SOURCES) != set(REFERENCED_SKILLS):
- raise RuntimeError(
- "SBTD Onboard catalog external Skills do not match the referenced Skill contract"
- )
- MATTPOCOCK_REPO = str(EXTERNAL_SKILL_SOURCES["diagnosing-bugs"]["repo"])
- MATTPOCOCK_SKILL_SUBPATHS = {
- name: str(EXTERNAL_SKILL_SOURCES[name]["subpath"])
- for name in MATTPOCOCK_CANONICAL_SKILLS
- }
- if any(
- EXTERNAL_SKILL_SOURCES[name]["repo"] != MATTPOCOCK_REPO
- for name in MATTPOCOCK_CANONICAL_SKILLS
- ):
- raise RuntimeError(
- "SBTD Onboard catalog mattpocock Skills must share one repository"
- )
- EXTERNAL_REPO_TO_SKILLS: dict[str, tuple[str, ...]] = {}
- for _skill_name, _source_spec in EXTERNAL_SKILL_SOURCES.items():
- _repo = str(_source_spec["repo"])
- EXTERNAL_REPO_TO_SKILLS[_repo] = (
- *EXTERNAL_REPO_TO_SKILLS.get(_repo, ()),
- _skill_name,
- )
- BASE_MANUAL_CHECKS = (
- {
- "name": "Chrome DevTools MCP",
- "category": "mcp",
- "advice": "Confirm the active Agent or IDE exposes Chrome DevTools MCP tools before relying on it for Web runtime diagnostics.",
- "steps": (
- "Configure or enable the Chrome DevTools MCP server in the active Agent or IDE MCP settings.",
- "Confirm Google Chrome or Chrome for Testing is available when the MCP server requires it.",
- "Restart or reload the Agent environment so the MCP server is discovered.",
- "Confirm Chrome DevTools MCP tools are visible before relying on it for console, network, screenshot, or performance diagnostics.",
- "Treat Chrome DevTools MCP output as diagnostic evidence, not as a replacement for project tests or Playwright E2E.",
- ),
- },
- {
- "name": "Playwright MCP",
- "category": "mcp",
- "advice": "Confirm Playwright MCP tools are visible before relying on them for page exploration, accessibility snapshots, or locator assistance.",
- "steps": (
- "When the selected Playwright distribution exposes it, prefer its bundled `npx playwright mcp` entrypoint; otherwise configure a compatible dedicated Playwright MCP server.",
- "Restart or reload the Agent environment so the MCP server is discovered.",
- "Confirm Playwright MCP tools are visible to the Agent.",
- "Use Playwright MCP for exploration and locator assistance only; do not treat it as a substitute for project-level Playwright CLI.",
- ),
- },
- )
- @dataclass(frozen=True)
- class Operation:
- label: str
- source: Path
- target: Path
- kind: str
- same_location: bool = False
- skip_when_valid: bool = False
- def expand_path(value: str | None) -> Path | None:
- if not value:
- return None
- return Path(value).expanduser().resolve()
- def default_codex_home() -> Path:
- env_value = os.environ.get("CODEX_HOME")
- if env_value:
- return Path(env_value).expanduser().resolve()
- return (Path.home() / ".codex").resolve()
- def user_home() -> Path:
- if os.name == "nt":
- raw = os.environ.get("USERPROFILE") or os.environ.get("HOME")
- if raw:
- return Path(raw).expanduser()
- return Path.home()
- def detect_omp_root() -> Path | None:
- """Probe the default OMP config root (PI_CONFIG_DIR aware) for existence.
- The root mirrors Node ``path.join(home, PI_CONFIG_DIR or ".omp")``: an
- absolute-looking value stays under home and ``..`` may escape it, exactly
- as OMP 18.19.0 resolves it. An explicit PI_CODING_AGENT_DIR or named
- profile does not move this root.
- """
- from sbtd_omp_sources import omp_config_root
- root = omp_config_root(user_home(), os.environ)
- try:
- resolved = root.resolve()
- except OSError:
- return None
- return resolved if resolved.is_dir() else None
- def omp_agents_target() -> tuple[Path, bool]:
- """Resolve the OMP user-level AGENTS.md OMP 18.19.0 reads, plus explicitness.
- Explicit means a non-empty PI_CODING_AGENT_DIR or a named profile selected
- the agent directory; onboard then writes the target even when it does not
- exist yet. Without an explicit selector the historical rule stands: the
- target lives under the default config root and onboard writes only when
- that root already exists, never creating it.
- """
- from sbtd_omp_sources import active_omp_agent_dir
- resolved = active_omp_agent_dir(home=user_home(), environ=os.environ)
- agent_dir = resolved["agent_dir"]
- assert isinstance(agent_dir, Path)
- explicit = bool(resolved["override"]) or resolved["profile"] is not None
- return agent_dir / "AGENTS.md", explicit
- def omp_global_agents_path(omp_root: Path) -> Path:
- return omp_root / "agent" / "AGENTS.md"
- def known_global_skills_dirs() -> tuple[Path, ...]:
- home = Path.home()
- return tuple(
- path.resolve()
- for path in (
- home / ".agents" / "skills",
- home / ".agent" / "skills",
- home / ".codex" / "skills",
- home / ".claude" / "skills",
- home / ".pi" / "agent" / "skills",
- default_codex_home() / "skills",
- )
- )
- def installed_global_skills_dir() -> Path | None:
- known_roots = set(known_global_skills_dirs())
- for skill_dir in (SKILL_ENTRY_DIR, SKILL_DIR):
- if skill_dir.name != "sbtd-workflow-onboard":
- continue
- parent = skill_dir.parent.resolve()
- if parent in known_roots and (skill_dir / "SKILL.md").is_file():
- return parent
- return None
- def resolve_global_skills_dir(value: str | None = None) -> tuple[Path, str]:
- explicit = expand_path(value)
- if explicit:
- return explicit, "argument"
- environment = os.environ.get("AGENT_SKILLS_DIR")
- if environment:
- return Path(environment).expanduser().resolve(), "environment"
- installed = installed_global_skills_dir()
- if installed:
- return installed, "installed-skill-parent"
- return (default_codex_home() / "skills").resolve(), "platform-default"
- def default_global_skills_dir() -> Path:
- return resolve_global_skills_dir()[0]
- def resolve_project_root(
- args: argparse.Namespace, required: bool = False
- ) -> Path | None:
- """Resolve the single-project interface used by project-only tool installers."""
- project_root = expand_path(getattr(args, "project_root", None))
- if project_root and not project_root.is_dir():
- raise SystemExit(
- f"--project-root must be an existing directory: {project_root}"
- )
- if required and not project_root:
- raise SystemExit(
- "--project-root is required unless --skip-project-agents is used"
- )
- return project_root
- def resolve_project_roots(
- args: argparse.Namespace, required: bool = False
- ) -> list[Path]:
- raw = (getattr(args, "projects_root", None) or "").strip()
- if not raw:
- if required:
- raise SystemExit("--projects-root is required")
- return []
- roots: list[Path] = []
- for value in raw.split(","):
- candidate_text = value.strip()
- if not candidate_text:
- continue
- candidate = Path(candidate_text).expanduser()
- if not candidate.is_absolute():
- raise SystemExit(
- f"--projects-root only accepts absolute paths: {candidate_text}"
- )
- candidate = candidate.resolve()
- if not candidate.is_dir():
- raise SystemExit(f"Project root does not exist: {candidate}")
- if candidate not in roots:
- roots.append(candidate)
- if required and not roots:
- raise SystemExit("--projects-root must contain at least one absolute path")
- return roots
- def subprocess_command(command: tuple[str, ...]) -> tuple[str, ...] | str:
- """Return an executable form of ``command`` for ``subprocess.run``.
- Windows npm-style global CLIs are ``.CMD``/``.BAT`` batch launchers, not
- PE executables; starting them directly fails with error 193 or returns
- empty output. Resolve the real launcher and route batch files through
- ``cmd.exe /d /s /c``; other platforms and native executables keep the
- original argv tuple without a shell.
- """
- if platform.system() != "Windows" or not command:
- return command
- resolved = shutil.which(command[0])
- if not resolved or Path(resolved).suffix.lower() not in {".cmd", ".bat"}:
- return command
- return f'cmd.exe /d /s /c "{subprocess.list2cmdline([resolved, *command[1:]])}"'
- def run_command(
- command: tuple[str, ...],
- timeout: int = 30,
- env: dict[str, str] | None = None,
- cwd: Path | None = None,
- ) -> subprocess.CompletedProcess[str] | None:
- try:
- return subprocess.run(
- subprocess_command(command),
- check=False,
- capture_output=True,
- text=True,
- errors="replace",
- timeout=timeout,
- env=env,
- cwd=str(cwd) if cwd else None,
- )
- except (OSError, subprocess.TimeoutExpired):
- return None
- def shell_result(
- script: str, timeout: int = 300
- ) -> subprocess.CompletedProcess[str] | None:
- shell = shutil.which("bash") or shutil.which("sh")
- if not shell:
- return None
- return run_command((shell, "-lc", script), timeout=timeout)
- def command_output(
- command: tuple[str, ...], timeout: int = 10, env: dict[str, str] | None = None
- ) -> tuple[int | None, str]:
- completed = run_command(command, timeout=timeout, env=env)
- if completed is None:
- return None, ""
- output = (completed.stdout or completed.stderr).strip()
- return completed.returncode, output
- def command_version(command: str, version_args: tuple[str, ...]) -> str | None:
- _, output = command_output((command, *version_args), timeout=5)
- return output.splitlines()[0] if output else None
- def nvm_dir_shell_expr() -> str:
- return '${NVM_DIR:-$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "$HOME/.nvm" || printf %s "$XDG_CONFIG_HOME/nvm")}'
- def nvm_load_script() -> str:
- nvm_dir = nvm_dir_shell_expr()
- return (
- f'export NVM_DIR="{nvm_dir}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"'
- )
- def check_nvm() -> dict[str, object]:
- system = platform.system() or sys.platform
- if system == "Windows":
- path = shutil.which("nvm")
- version = command_version("nvm", ("version",)) if path else None
- return {
- "name": "nvm",
- "installed": bool(path),
- "path": path,
- "version": version,
- "installableByScript": False,
- "advice": "Native Windows should use nvm-windows, nvs, or WSL; the nvm-sh installer is for POSIX shells.",
- }
- completed = shell_result(
- f"{nvm_load_script()}; command -v nvm; nvm --version", timeout=10
- )
- installed = bool(completed and completed.returncode == 0)
- lines = (completed.stdout if completed else "").strip().splitlines()
- return {
- "name": "nvm",
- "installed": installed,
- "path": lines[0] if lines else None,
- "version": lines[-1] if len(lines) > 1 else None,
- "installableByScript": system in {"Darwin", "Linux"},
- "advice": "Install nvm first, then use `nvm install --lts`, `nvm alias default 'lts/*'`, and `nvm use --lts`.",
- }
- def activate_nvm_node_path() -> str | None:
- if platform.system() == "Windows":
- return None
- completed = shell_result(
- f"{nvm_load_script()}; "
- "(nvm use --lts >/dev/null 2>&1 || nvm use default >/dev/null 2>&1 || true); "
- "command -v npm",
- timeout=20,
- )
- if not completed or completed.returncode != 0:
- return None
- npm_path = (
- completed.stdout.strip().splitlines()[-1] if completed.stdout.strip() else ""
- )
- if not npm_path:
- return None
- npm_bin = str(Path(npm_path).parent)
- current = os.environ.get("PATH", "")
- if npm_bin not in current.split(os.pathsep):
- os.environ["PATH"] = f"{npm_bin}{os.pathsep}{current}"
- return npm_bin
- def check_npm_runtime() -> dict[str, object]:
- if not shutil.which("npm"):
- activate_nvm_node_path()
- npm_path = shutil.which("npm")
- node_path = shutil.which("node")
- npm_version = command_version("npm", ("--version",)) if npm_path else None
- node_version = command_version("node", ("--version",)) if node_path else None
- nvm = check_nvm()
- return {
- "platform": platform.system() or sys.platform,
- "npm": {
- "installed": bool(npm_path and npm_version),
- "path": npm_path,
- "version": npm_version,
- },
- "node": {
- "installed": bool(node_path and node_version),
- "path": node_path,
- "version": node_version,
- },
- "nvm": nvm,
- "advice": "Local tool detection does not require npm. Installing a selected npm-backed tool requires npm and explicit confirmation.",
- }
- def check_cli_tool(spec: dict[str, str | tuple[str, ...]]) -> dict[str, object]:
- name = str(spec["name"])
- path = shutil.which(name)
- version = command_version(name, spec["versionArgs"]) if path else None
- installed = bool(path and version)
- result = {
- "name": name,
- "category": "cli",
- "installed": installed,
- "path": path,
- "version": version,
- "globalInstall": spec["globalInstall"],
- "projectInstall": spec["projectInstall"],
- "advice": spec["advice"],
- }
- if name == "rtk" and path:
- with tempfile.TemporaryDirectory(prefix="sbtd-rtk-probe-") as probe_home:
- probe_env = {
- key: value
- for key, value in os.environ.items()
- if not key.upper().startswith("RTK_")
- }
- probe_env.update(
- HOME=probe_home,
- USERPROFILE=probe_home,
- XDG_CONFIG_HOME=str(Path(probe_home) / "config"),
- XDG_CACHE_HOME=str(Path(probe_home) / "cache"),
- XDG_DATA_HOME=str(Path(probe_home) / "data"),
- XDG_STATE_HOME=str(Path(probe_home) / "state"),
- )
- completed = run_command(
- (str(Path(path).resolve()), "gain"),
- timeout=10,
- env=probe_env,
- cwd=Path(probe_home),
- )
- code = completed.returncode if completed else None
- output = (
- (completed.stdout or completed.stderr).strip() if completed else ""
- )
- result["verificationScope"] = "isolated-probe"
- correct = code == 0
- version_looks_correct = bool(version and version.lower().startswith("rtk "))
- result["installed"] = correct
- result["rtkGainVerified"] = correct
- result["wrongPackageSuspected"] = not correct and not version_looks_correct
- result["verificationFailed"] = not correct and version_looks_correct
- result["verifyCommand"] = "rtk gain"
- result["verifyOutput"] = output.splitlines()[0] if output else None
- if result["wrongPackageSuspected"]:
- result["advice"] = (
- "An `rtk` command exists but `rtk gain` failed, so this may be the wrong rtk package. Confirm before uninstalling or replacing it."
- )
- elif result["verificationFailed"]:
- result["advice"] = (
- "The rtk binary looks like rtk-ai/rtk, but its isolated gain probe failed. Inspect the binary and probe error before choosing repair; the user's history directory was not tested."
- )
- elif name == "rtk":
- result["rtkGainVerified"] = False
- result["wrongPackageSuspected"] = False
- result["verificationFailed"] = False
- result["verifyCommand"] = "rtk gain"
- return result
- def normalize_agent_platform(value: str) -> str:
- normalized = value.strip().lower().replace("_", "-")
- platform_name = AGENT_PLATFORM_ALIASES.get(normalized)
- if not platform_name:
- allowed = ", ".join(("codex", "claude", "kimi", "oh-my-pi", "omp"))
- raise SystemExit(
- f"Unsupported Agent platform: {value}. Allowed values: {allowed}"
- )
- return platform_name
- def check_agent_cli(platform_value: str) -> dict[str, object]:
- platform_name = normalize_agent_platform(platform_value)
- spec = AGENT_CLI_SPECS[platform_name]
- command = str(spec["command"])
- version_args = tuple(str(item) for item in spec["versionArgs"])
- path = shutil.which(command)
- code, output = (
- command_output((command, *version_args), timeout=10) if path else (None, "")
- )
- version = output.splitlines()[0] if code == 0 and output else None
- npm_package = str(spec["npmPackage"])
- result: dict[str, object] = {
- "mode": "check-agent-cli",
- "platform": platform_name,
- "label": spec["label"],
- "command": command,
- "path": path,
- "version": version,
- "installed": bool(path and version),
- "npmPackage": npm_package,
- "installCommand": f"npm install -g {npm_package}@latest",
- "verifyCommand": command_display((command, *version_args)),
- "advice": spec["advice"],
- "runtime": check_npm_runtime(),
- }
- if path and not version:
- result["verificationFailed"] = True
- result["verifyOutput"] = output.splitlines()[0] if output else None
- return result
- def print_agent_cli_check(result: dict[str, object], as_json: bool) -> None:
- if as_json:
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return
- status = "installed" if result["installed"] else "missing"
- if result.get("verificationFailed"):
- status = "verification-failed"
- print(f"Target Agent CLI: {result['label']}")
- print(f"- status: {status}")
- print(f"- command: {result['command']}")
- if result.get("path"):
- print(f"- path: {result['path']}")
- if result.get("version"):
- print(f"- version: {result['version']}")
- if not result["installed"]:
- print(f"- install: {result['installCommand']}")
- print(f"- advice: {result['advice']}")
- def parse_java_major(output: str | None) -> int | None:
- if not output:
- return None
- match = re.search(
- r'(?:openjdk|java)?\s*version\s+"?(\d+)(?:\.(\d+))?', output, re.IGNORECASE
- )
- if not match:
- match = re.search(r"\b(\d+)(?:\.(\d+))?\.\d+", output)
- if not match:
- return None
- first = int(match.group(1))
- second = match.group(2)
- if first == 1 and second:
- return int(second)
- return first
- def java_version_output() -> tuple[str | None, str | None]:
- code, output = command_output(("java", "--version"), timeout=5)
- if code == 0 and output:
- return output.splitlines()[0], "java --version"
- code, output = command_output(("java", "-version"), timeout=5)
- if code == 0 and output:
- return output.splitlines()[0], "java -version"
- return None, "java --version"
- def java_binary_path(java_home: str | Path) -> Path:
- """Resolve the Java launcher inside a JDK home directory.
- Windows JDKs ship ``bin/java.exe``; other platforms ship ``bin/java``.
- Windows accepts both names so cross-platform JDK layouts still resolve.
- """
- home = Path(java_home)
- if platform.system() == "Windows":
- for name in ("java.exe", "java"):
- candidate = home / "bin" / name
- if candidate.is_file():
- return candidate
- return home / "bin" / "java.exe"
- return home / "bin" / "java"
- def usable_java_home(candidate: str | Path | None) -> Path | None:
- if not candidate:
- return None
- path = Path(candidate).expanduser()
- if java_binary_path(path).is_file():
- return path.resolve()
- return None
- def java_binary_version(java_binary: Path) -> tuple[str | None, str | None]:
- code, output = command_output((str(java_binary), "--version"), timeout=5)
- if code == 0 and output:
- return output.splitlines()[0], f"{java_binary} --version"
- code, output = command_output((str(java_binary), "-version"), timeout=5)
- if code == 0 and output:
- return output.splitlines()[0], f"{java_binary} -version"
- return None, f"{java_binary} --version"
- def java_home_major(java_home: Path) -> int | None:
- version, _ = java_binary_version(java_binary_path(java_home))
- return parse_java_major(version)
- def macos_java_home(major: int | None = None) -> Path | None:
- if platform.system() != "Darwin":
- return None
- helper = Path("/usr/libexec/java_home")
- if not helper.is_file():
- return None
- command = (str(helper), "-v", str(major)) if major else (str(helper),)
- code, output = command_output(command, timeout=5)
- if code != 0 or not output:
- return None
- return usable_java_home(output.splitlines()[0].strip())
- def infer_java_home_from_path(java_path: str | None) -> Path | None:
- if java_path:
- java_bin = Path(java_path).expanduser().resolve()
- if platform.system() == "Darwin" and java_bin == Path("/usr/bin/java"):
- return None
- is_java_launcher = (
- java_bin.name.lower() in {"java", "java.exe"}
- if platform.system() == "Windows"
- else java_bin.name == "java"
- )
- if is_java_launcher and java_bin.parent.name == "bin":
- inferred = usable_java_home(java_bin.parent.parent)
- if inferred:
- return inferred
- return None
- def java_home_candidates(java_path: str | None) -> list[Path]:
- candidates: list[Path] = []
- def add(candidate: str | Path | None) -> None:
- java_home = usable_java_home(candidate)
- if java_home and java_home not in candidates:
- candidates.append(java_home)
- add(infer_java_home_from_path(java_path))
- add(os.environ.get("JAVA_HOME"))
- add(macos_java_home())
- add(macos_java_home(JAVA_MIN_MAJOR))
- patterns = (
- Path.home() / "JDK" / "*" / "Contents" / "Home",
- Path.home() / "JDK" / "*",
- Path.home()
- / "Library"
- / "Java"
- / "JavaVirtualMachines"
- / "*"
- / "Contents"
- / "Home",
- Path("/Library/Java/JavaVirtualMachines") / "*" / "Contents" / "Home",
- Path("/usr/lib/jvm") / "*",
- )
- for pattern in patterns:
- for candidate in pattern.parent.glob(pattern.name):
- add(candidate)
- return candidates
- def select_java_home(
- java_path: str | None,
- ) -> tuple[Path | None, int | None, str | None]:
- candidates = java_home_candidates(java_path)
- candidate_info: list[tuple[Path, int | None]] = [
- (candidate, java_home_major(candidate)) for candidate in candidates
- ]
- if (
- candidate_info
- and candidate_info[0][1]
- and candidate_info[0][1] >= JAVA_MIN_MAJOR
- ):
- return candidate_info[0][0], candidate_info[0][1], "current-java-home"
- for candidate, major in candidate_info[1:] if candidate_info else []:
- if major and major >= JAVA_MIN_MAJOR:
- return candidate, major, "alternate-installed-jdk"
- return None, None, None
- def unique_path_entries(entries: list[str | None]) -> list[str]:
- result: list[str] = []
- seen: set[str] = set()
- for entry in entries:
- if not entry or entry in seen:
- continue
- seen.add(entry)
- result.append(entry)
- return result
- def maestro_bin_dir(maestro_path: str | None) -> str:
- if maestro_path:
- return str(Path(maestro_path).expanduser().parent)
- return str(Path.home() / ".maestro" / "bin")
- def mcp_path_value(java_home: str | None, maestro_path: str | None) -> str:
- java_bin = f"{java_home}/bin" if java_home else "<JAVA_HOME>/bin"
- return os.pathsep.join(
- unique_path_entries(
- [
- maestro_bin_dir(maestro_path),
- java_bin,
- "/usr/local/bin",
- "/opt/homebrew/bin",
- "/usr/bin",
- "/bin",
- "/usr/sbin",
- "/sbin",
- ]
- )
- )
- def toml_string(value: str) -> str:
- return value.replace("\\", "\\\\").replace('"', '\\"')
- def maestro_mcp_environment(
- java_check: dict[str, object], maestro_check: dict[str, object]
- ) -> dict[str, str]:
- java_home = str(java_check.get("javaHome") or "<JAVA_HOME>")
- path_value = mcp_path_value(
- str(java_check.get("javaHome")) if java_check.get("javaHome") else None,
- str(maestro_check.get("path")) if maestro_check.get("path") else None,
- )
- return {"JAVA_HOME": java_home, "PATH": path_value}
- def maestro_mcp_server_config(
- java_check: dict[str, object], maestro_check: dict[str, object]
- ) -> dict[str, object]:
- return {
- "command": "maestro",
- "args": ["mcp"],
- "env": maestro_mcp_environment(java_check, maestro_check),
- }
- def maestro_mcp_toml_example(
- java_check: dict[str, object], maestro_check: dict[str, object]
- ) -> str:
- env = maestro_mcp_environment(java_check, maestro_check)
- return "\n".join(
- [
- "[mcp_servers.maestro]",
- 'command = "maestro"',
- 'args = ["mcp"]',
- "",
- "[mcp_servers.maestro.env]",
- f'JAVA_HOME = "{toml_string(env["JAVA_HOME"])}"',
- f'PATH = "{toml_string(env["PATH"])}"',
- ]
- )
- def maestro_mcp_json_example(
- java_check: dict[str, object], maestro_check: dict[str, object]
- ) -> str:
- return json.dumps(
- {
- "mcpServers": {
- "maestro": maestro_mcp_server_config(java_check, maestro_check)
- }
- },
- indent=2,
- ensure_ascii=False,
- )
- def maestro_mcp_config_examples(
- java_check: dict[str, object], maestro_check: dict[str, object]
- ) -> dict[str, str]:
- return {
- "genericJson": maestro_mcp_json_example(java_check, maestro_check),
- "toml": maestro_mcp_toml_example(java_check, maestro_check),
- }
- def maestro_cli_env(java_check: dict[str, object]) -> dict[str, str] | None:
- java_home = java_check.get("javaHome")
- if not java_home:
- return None
- env = os.environ.copy()
- env["JAVA_HOME"] = str(java_home)
- env["PATH"] = os.pathsep.join(
- unique_path_entries([f"{java_home}/bin", os.environ.get("PATH")])
- )
- return env
- def build_maestro_mcp_manual_check(
- java_check: dict[str, object],
- maestro_check: dict[str, object],
- ) -> dict[str, object]:
- java_home = java_check.get("javaHome")
- maestro_ready = bool(maestro_check.get("installed"))
- server_config = maestro_mcp_server_config(java_check, maestro_check)
- config_examples = maestro_mcp_config_examples(java_check, maestro_check)
- readiness = (
- "Detected Java 17+ and Maestro CLI; adapt the generated command, args, and env values to the active Agent or IDE MCP configuration format."
- if java_home and maestro_ready
- else "Complete Java 17+ and Maestro CLI setup first, then replace any placeholder values before enabling Maestro MCP in the active Agent or IDE."
- )
- return {
- "name": "Maestro MCP",
- "category": "mcp",
- "advice": "Maestro MCP depends on Java 17+, a working Maestro CLI, and explicit MCP environment variables for JAVA_HOME and PATH.",
- "mcpServerConfig": server_config,
- "environment": server_config["env"],
- "configExample": config_examples["genericJson"],
- "configExamples": config_examples,
- "steps": (
- "Confirm Java 17+ is available with `java --version` or `java -version`; prefer the JDK currently used by the local machine when it is 17+, otherwise choose an installed JDK that is 17 or higher before installing a new JDK.",
- "Confirm the Maestro CLI works, for example with `maestro --help` and `maestro test --help`; ensure the MCP PATH includes the directory that contains the `maestro` binary.",
- readiness,
- "Configure the active Agent or IDE MCP settings with `command = maestro`, `args = [mcp]`, and the generated env values. Do not configure only command and args; include `JAVA_HOME` and `PATH` so `maestro mcp` can find Java and Maestro in the MCP server process environment.",
- "Restart or reload the Agent environment so the MCP server is discovered.",
- "Confirm Maestro MCP tools are visible before relying on device inspection, view hierarchy, screenshots, or flow assistance.",
- "If Maestro MCP is unavailable but Maestro CLI works, continue deterministic flow execution through `maestro test` and report MCP separately.",
- ),
- }
- REACT_PROJECT_DEPENDENCY_MARKERS = (
- "react",
- "react-dom",
- "next",
- "@vitejs/plugin-react",
- "@vitejs/plugin-react-swc",
- "@remix-run/react",
- "@tanstack/react-router",
- "@tanstack/react-start",
- )
- def project_dependencies(package_data: dict[str, object] | None) -> dict[str, object]:
- dependencies: dict[str, object] = {}
- if not package_data:
- return dependencies
- for key in (
- "dependencies",
- "devDependencies",
- "optionalDependencies",
- "peerDependencies",
- ):
- value = package_data.get(key)
- if isinstance(value, dict):
- dependencies.update(value)
- return dependencies
- def is_react_project(project_root: Path | None) -> bool:
- dependencies = project_dependencies(project_package_json(project_root))
- return any(marker in dependencies for marker in REACT_PROJECT_DEPENDENCY_MARKERS)
- def has_shadcn_components_config(project_root: Path | None) -> bool:
- return bool(project_root and (project_root / "components.json").is_file())
- def should_check_react_bits_tier(project_root: Path | None) -> bool:
- return bool(
- project_root
- and is_react_project(project_root)
- and has_shadcn_components_config(project_root)
- )
- def build_react_bits_tier_manual_check(project_root: Path) -> dict[str, object]:
- components_json = project_root / "components.json"
- return {
- "name": "React Bits tier selection",
- "category": "conditional-project-skill",
- "advice": "A React + shadcn/ui project was detected. Keep the default as shadcn/ui only; ask before adding React Bits Free, Starter, Pro, or Ultimate. Do not print or store any React Bits license key.",
- "detected": {
- "projectRoot": str(project_root),
- "componentsJson": str(components_json),
- "reactProject": True,
- },
- "steps": (
- "Tell the user that shadcn/ui covers normal application components, while React Bits Free or paid tiers are optional sources for more expressive animated components, blocks, or landing sections.",
- "Ask whether this project should stay with shadcn/ui only, add React Bits Free, or use an existing paid Starter / Pro / Ultimate entitlement.",
- "For React Bits Free, install only after the user confirms and a free source or registry has been explicitly configured for this workflow.",
- "For paid tiers, require explicit user confirmation and verify the current environment can read `REACTBITS_LICENSE_KEY` without printing it.",
- "When paid prerequisites are met and the user selects a paid tier, run `npx shadcn@latest add @reactbits-starter/skill --path .agents/skills/react-bits-pro --overwrite --yes` from the project root even when the target Skill already exists, then confirm `.agents/skills/react-bits-pro/SKILL.md` exists before using it.",
- "During reset, preserve the detected React Bits tier and registry; do not replace Free, Starter, Pro, or Ultimate with a different default tier without confirmation.",
- ),
- }
- def build_manual_checks(
- java_check: dict[str, object],
- maestro_check: dict[str, object],
- project_root: Path | None,
- ) -> tuple[dict[str, object], ...]:
- checks = list(cast(tuple[dict[str, object], ...], BASE_MANUAL_CHECKS))
- checks.insert(2, build_maestro_mcp_manual_check(java_check, maestro_check))
- if project_root and should_check_react_bits_tier(project_root):
- checks.append(build_react_bits_tier_manual_check(project_root))
- return tuple(checks)
- def check_java_for_maestro() -> dict[str, object]:
- path = shutil.which("java")
- current_version, current_version_command = (
- java_version_output() if path else (None, "java --version")
- )
- current_major = parse_java_major(current_version)
- java_home, java_home_major_value, java_home_source = select_java_home(path)
- if java_home:
- selected_version, selected_version_command = java_binary_version(
- java_binary_path(java_home)
- )
- selected_major = parse_java_major(selected_version) or java_home_major_value
- else:
- selected_version, selected_version_command, selected_major = (
- current_version,
- current_version_command,
- current_major,
- )
- installed = bool(java_home and selected_major and selected_major >= JAVA_MIN_MAJOR)
- result: dict[str, object] = {
- "name": "java",
- "category": "runtime",
- "installed": installed,
- "path": str(java_binary_path(java_home)) if installed and java_home else path,
- "currentPath": path,
- "currentVersion": current_version,
- "currentVersionMajor": current_major,
- "currentVersionCommand": current_version_command,
- "javaHome": str(java_home) if java_home else None,
- "javaHomeSource": java_home_source,
- "version": selected_version,
- "versionMajor": selected_major,
- "versionCommand": selected_version_command,
- "globalInstall": f"Install the latest OpenJDK Temurin 21 JDK from {TEMURIN21_RELEASES_URL}",
- "projectInstall": None,
- "advice": "Maestro requires Java 17+. Prefer the local machine's current JDK when it is 17+; if it is missing or lower than 17, use another installed JDK that is 17+ before asking to install a new JDK. Default new installs to the latest OpenJDK Temurin 21 JDK; user-selected versions must be 17 or higher.",
- }
- if not installed and path and current_major and current_major < JAVA_MIN_MAJOR:
- result["incompatibleVersion"] = True
- if (
- installed
- and current_major
- and current_major < JAVA_MIN_MAJOR
- and java_home_source == "alternate-installed-jdk"
- ):
- result["reason"] = (
- "The current `java` is lower than 17, but another installed JDK satisfies Maestro's Java prerequisite."
- )
- return result
- def check_maestro_cli(java_check: dict[str, object]) -> dict[str, object]:
- if not java_check.get("installed"):
- return {
- "name": "maestro",
- "category": "cli",
- "installed": False,
- "path": None,
- "version": None,
- "notChecked": True,
- "reason": "Java 17+ is required before Maestro CLI can be checked.",
- "globalInstall": "Install Java 17+ first, then install Maestro CLI with the official Maestro instructions.",
- "projectInstall": None,
- "advice": "Resolve the Java 17+ prerequisite first. Maestro MCP is unavailable until Maestro CLI works.",
- }
- path = shutil.which("maestro")
- env = maestro_cli_env(java_check)
- code, output = (
- command_output(("maestro", "--version"), timeout=10, env=env)
- if path
- else (None, "")
- )
- first_line = output.splitlines()[0] if output else None
- version = (
- first_line
- if code == 0 and first_line and not first_line.lower().startswith("exception")
- else None
- )
- result: dict[str, object] = {
- "name": "maestro",
- "category": "cli",
- "installed": bool(path and version),
- "path": path,
- "binDir": maestro_bin_dir(path),
- "version": version,
- "globalInstall": "Install Maestro CLI with the official Maestro installer or Homebrew tap after user confirmation.",
- "projectInstall": None,
- "advice": "Install Maestro CLI into the local development environment or CI runner after Java 17+ is available. Then configure Maestro MCP separately if needed.",
- }
- if path and not version:
- result["verificationFailed"] = True
- result["verifyCommand"] = "maestro --version"
- result["verifyOutput"] = first_line
- return result
- def project_package_json(project_root: Path | None) -> dict[str, object] | None:
- if not project_root:
- return None
- package_json = project_root / "package.json"
- if not package_json.is_file():
- return None
- try:
- return json.loads(package_json.read_text(encoding="utf-8"))
- except json.JSONDecodeError:
- return None
- def check_playwright_project(project_root: Path | None) -> dict[str, object]:
- package_data = project_package_json(project_root)
- config_paths: list[str] = []
- e2e_paths: list[str] = []
- if project_root:
- for name in (
- "playwright.config.ts",
- "playwright.config.js",
- "playwright.config.mts",
- "playwright.config.cts",
- ):
- candidate = project_root / name
- if candidate.is_file():
- config_paths.append(str(candidate))
- for name in ("tests/e2e", "e2e", "playwright-report", "test-results"):
- candidate = project_root / name
- if candidate.exists():
- e2e_paths.append(str(candidate))
- dependencies: dict[str, object] = {}
- scripts: dict[str, object] = {}
- if package_data:
- for key in ("dependencies", "devDependencies", "optionalDependencies"):
- value = package_data.get(key)
- if isinstance(value, dict):
- dependencies.update(value)
- value = package_data.get("scripts")
- if isinstance(value, dict):
- scripts = value
- has_dependency = "@playwright/test" in dependencies or "playwright" in dependencies
- playwright_scripts = {
- key: value
- for key, value in scripts.items()
- if isinstance(value, str) and "playwright" in value
- }
- installed = bool(has_dependency or config_paths or playwright_scripts)
- has_project_markers = bool(
- has_dependency or config_paths or e2e_paths or playwright_scripts
- )
- not_checked = project_root is None or not has_project_markers
- reason = None
- if project_root is None:
- reason = "No project root was provided, so project-level Playwright readiness was not checked."
- elif not has_project_markers:
- reason = "No package.json, Playwright config, or E2E directory was detected under the target project root."
- return {
- "name": "Playwright CLI",
- "category": "project-cli",
- "installed": installed,
- "applicable": not not_checked,
- "path": str(project_root) if project_root else None,
- "version": dependencies.get("@playwright/test")
- or dependencies.get("playwright"),
- "notChecked": not_checked,
- "reason": reason,
- "configPaths": config_paths,
- "e2ePaths": e2e_paths,
- "scripts": playwright_scripts,
- "globalInstall": "Do not install Playwright globally by default.",
- "projectInstall": "npm init playwright@latest or npm install -D @playwright/test, then npx playwright install",
- "advice": "Playwright CLI is a project-level Web E2E dependency. If Web regression or web-ui-autotest-generator needs it and it is missing, ask the user before installing it into the target project.",
- }
- def check_react_bits_project(project_root: Path) -> dict[str, object]:
- applicable = should_check_react_bits_tier(project_root)
- result: dict[str, object] = {
- "applicable": applicable,
- "projectRoot": str(project_root),
- "componentsJson": str(project_root / "components.json") if applicable else None,
- "selectionRequired": applicable,
- }
- if applicable:
- result["manualCheck"] = build_react_bits_tier_manual_check(project_root)
- else:
- result["reason"] = (
- "React Bits applies only when the project is React-based and has "
- "shadcn/ui initialized through components.json."
- )
- return result
- def build_project_check(
- project_root: Path, skip_agents: bool = False
- ) -> dict[str, object]:
- from sbtd_language_tooling import detect_project_languages
- return {
- "projectRoot": str(project_root),
- "playwright": check_playwright_project(project_root),
- "reactBits": check_react_bits_project(project_root),
- "sbtd": inspect_project_setup(project_root, skip_agents),
- "languages": detect_project_languages(project_root),
- }
- def build_projects_check_results(args: argparse.Namespace) -> dict[str, object]:
- project_roots = resolve_project_roots(args, required=True)
- return {
- "mode": "check-projects",
- "projects": [
- build_project_check(
- project_root, bool(getattr(args, "skip_project_agents", False))
- )
- for project_root in project_roots
- ],
- }
- def print_projects_check_results(results: dict[str, object], as_json: bool) -> None:
- if as_json:
- print(json.dumps(results, indent=2, ensure_ascii=False))
- return
- print("Project checks:")
- for item in results["projects"]:
- print(f"- project root: {item['projectRoot']}")
- playwright = item["playwright"]
- print(
- " Playwright CLI: "
- + (
- "installed"
- if playwright["installed"]
- else "missing"
- if playwright["applicable"]
- else "not-needed"
- )
- )
- react_bits = item["reactBits"]
- print(
- " React Bits tier selection: "
- + ("required" if react_bits["applicable"] else "not-needed")
- )
- sbtd = item["sbtd"]
- print(f" SBTD state: {sbtd['status']}")
- print(f" Reason: {sbtd['reason']}")
- if sbtd["nextStep"]:
- print(f" Next step: {sbtd['nextStep']}")
- languages = item.get("languages") or []
- names = (
- ", ".join(str(entry["display"]) for entry in languages)
- if languages
- else "none detected"
- )
- print(f" Languages: {names}")
- def check_skill(
- name: str, group: str, global_dir: Path, project_dir: Path | None
- ) -> dict[str, object]:
- locations: list[dict[str, str]] = []
- global_candidate = global_dir / name / "SKILL.md"
- global_valid = (
- external_skill_target_is_valid(global_dir, name)
- if group == "referenced"
- else global_candidate.is_file()
- )
- if global_valid:
- locations.append({"scope": "global", "path": str(global_candidate)})
- if project_dir:
- project_candidate = project_dir / name / "SKILL.md"
- project_valid = (
- external_skill_target_is_valid(project_dir, name)
- if group == "referenced"
- else project_candidate.is_file()
- )
- if project_valid:
- locations.append({"scope": "project", "path": str(project_candidate)})
- return {
- "name": name,
- "category": "skill",
- "group": group,
- "installed": bool(locations),
- "locations": locations,
- "globalTarget": str(global_dir / name / "SKILL.md"),
- "projectTarget": str(project_dir / name / "SKILL.md") if project_dir else None,
- "sourceRepo": EXTERNAL_SKILL_SOURCES.get(name, {}).get("repo")
- if group == "referenced"
- else None,
- }
- def report_entry(
- name: str,
- status: str,
- *,
- path: str | None = None,
- version: str | None = None,
- scope: str | None = None,
- reason: str | None = None,
- next_step: str | None = None,
- source_repo: str | None = None,
- ) -> dict[str, object]:
- entry: dict[str, object] = {"name": name, "status": status}
- optional = {
- "path": path,
- "version": version,
- "scope": scope,
- "reason": reason,
- "nextStep": next_step,
- "sourceRepo": source_repo,
- }
- for key, value in optional.items():
- if value:
- entry[key] = value
- return entry
- def cli_failure_reason(item: dict[str, object]) -> str:
- name = str(item["name"])
- if item.get("category") == "project-cli":
- reason = f"No project-level Playwright dependency, config, script, or E2E directory was detected under {item.get('path') or 'the target project root'}."
- elif item.get("incompatibleVersion"):
- reason = f"`{name}` exists at {item.get('path')}, but version {item.get('version')} is lower than the required Java {JAVA_MIN_MAJOR}+ for Maestro."
- elif item.get("notChecked") and item.get("reason"):
- reason = str(item["reason"])
- elif item.get("wrongPackageSuspected"):
- reason = f"`{name}` exists at {item.get('path')}, but `{item.get('verifyCommand')}` failed; it may be a different same-name package."
- elif item.get("verificationFailed"):
- reason = f"`{name}` exists at {item.get('path')}, but `{item.get('verifyCommand')}` failed."
- elif not item.get("path"):
- reason = f"`{name}` command was not found in PATH."
- elif not item.get("version"):
- reason = f"`{name}` exists at {item.get('path')}, but the version command returned no usable output."
- else:
- reason = f"`{name}` did not pass the installer verification checks."
- verify_output = item.get("verifyOutput")
- if verify_output:
- reason += f" First verification output: {verify_output}"
- return reason
- def cli_next_step(item: dict[str, object]) -> str:
- if item.get("notChecked") and item.get("advice"):
- return str(item["advice"])
- return (
- "Install or repair the required global tool, then rerun the check. "
- f"Suggested command: {item['globalInstall']}"
- )
- def skill_failure_reason(item: dict[str, object]) -> str:
- if item["name"] == "caveman":
- return (
- "No `caveman/SKILL.md` was found in the checked global skills directory: "
- + str(item["globalTarget"])
- )
- targets = [str(item["globalTarget"])]
- if item.get("projectTarget"):
- targets.append(str(item["projectTarget"]))
- return "No `SKILL.md` was found at the checked target path(s): " + ", ".join(
- targets
- )
- def _powershell_quote(part: str) -> str:
- """Quote one token for PowerShell, only when it actually needs quoting.
- A conservative whitelist of characters passes through unquoted (same idea
- as `shlex.join` on POSIX); anything else is wrapped in a single-quoted
- literal, where `'` is the only character requiring escape (doubling) and
- `$`, `%VAR%`, `!VAR!` stay literal. cmd.exe is not a supported target.
- """
- if re.fullmatch(r"[A-Za-z0-9_./:\\=-]+", part):
- return part
- return "'" + part.replace("'", "''") + "'"
- def shell_quote_path(path: Path) -> str:
- """Quote one path for the shell that `onboard_command()` targets.
- POSIX hosts get `shlex.quote`, so whitespace, `$`, backticks and glob
- characters stay literal in sh / bash / zsh. Windows hosts get PowerShell
- quoting via `_powershell_quote()`.
- """
- text = str(path)
- if os.name == "nt":
- return _powershell_quote(text)
- return shlex.quote(text)
- def render_shell_command(argv: list[str]) -> str:
- """Render argv as one runnable command for the host shell.
- POSIX: `shlex.join`. Windows: tokens that need it get PowerShell single
- quoting; the call operator `&` is only prefixed when the program name had
- to be quoted, because a leading quoted string is otherwise evaluated as an
- expression instead of being executed.
- """
- if os.name == "nt":
- quoted = [_powershell_quote(part) for part in argv]
- command = " ".join(quoted)
- return ("& " + command) if quoted[0].startswith("'") else command
- return shlex.join(argv)
- def onboard_command(*args: str) -> str:
- """Build a cwd-independent `python <onboard.py> ...` command string.
- Repair hints are read from arbitrary project directories, so the script
- path must be the installed absolute path rather than `scripts/onboard.py`.
- On Windows the rendered command is PowerShell-only; see `shell_prefix()`.
- """
- return render_shell_command(["python", str(ONBOARD_SCRIPT_PATH), *args])
- def shell_prefix() -> str:
- """Human-readable lead-in naming the shell a hint is rendered for."""
- return "Run in PowerShell: " if os.name == "nt" else ""
- def skill_next_step(item: dict[str, object]) -> str:
- name = str(item["name"])
- if name == "caveman":
- return (
- f"{shell_prefix()}After user confirmation, install the Codex skill with "
- f"`{onboard_command('install-caveman', '--yes')}`, then rerun `check`."
- )
- if item.get("sourceRepo"):
- return (
- f"{shell_prefix()}Install the required global Skill from the configured repository with "
- f"`{onboard_command('install-external-skills', '--skills', name, '--scope', 'global', '--source', 'auto', '--yes')}`."
- )
- return "Run `init` or `reset` to install the required global bundled Skills, then rerun `check`."
- def skipped_already_installed_entry(
- entry: dict[str, object],
- reason: str,
- next_step: str,
- ) -> dict[str, object]:
- skipped = dict(entry)
- skipped["status"] = "skipped-already-installed"
- skipped["reason"] = reason
- skipped["nextStep"] = next_step
- return skipped
- def build_installation_report(results: dict[str, object]) -> dict[str, object]:
- runtime = results["runtime"]
- installed: dict[str, list[dict[str, object]]] = {
- "runtime": [],
- "tools": [],
- "skills": [],
- }
- skipped_already_installed: dict[str, list[dict[str, object]]] = {
- "runtime": [],
- "tools": [],
- "skills": [],
- }
- failed_or_missing: dict[str, list[dict[str, object]]] = {
- "runtime": [],
- "tools": [],
- "skills": [],
- }
- not_checked: dict[str, list[dict[str, object]]] = {"tools": []}
- conditional_runtime: list[dict[str, object]] = []
- for name in ("npm", "node"):
- item = runtime[name]
- entry = report_entry(
- name,
- "installed" if item["installed"] else "missing",
- path=item.get("path"),
- version=item.get("version"),
- )
- if item["installed"]:
- installed["runtime"].append(entry)
- skipped_already_installed["runtime"].append(
- skipped_already_installed_entry(
- entry,
- f"`{name}` is already available in PATH.",
- "Skip bootstrap installation unless the user explicitly requests a reinstall or version change.",
- )
- )
- else:
- entry["status"] = "conditional"
- entry["reason"] = f"`{name}` is not available in PATH."
- entry["nextStep"] = (
- "Only if a selected npm-backed install or upgrade needs npm: " + str(runtime["advice"])
- if name == "npm"
- else "Prepare Node.js only for a selected Node-backed operation."
- )
- conditional_runtime.append(entry)
- nvm = runtime["nvm"]
- nvm_entry = report_entry(
- "nvm",
- "installed" if nvm["installed"] else "missing",
- path=nvm.get("path"),
- version=nvm.get("version"),
- )
- if nvm["installed"]:
- installed["runtime"].append(nvm_entry)
- skipped_already_installed["runtime"].append(
- skipped_already_installed_entry(
- nvm_entry,
- "`nvm` is already available.",
- "Skip nvm bootstrap unless the user explicitly requests a reinstall or version manager change.",
- )
- )
- elif not runtime["npm"]["installed"]:
- nvm_entry["status"] = "conditional"
- nvm_entry["reason"] = "npm and nvm are missing; bootstrap is conditional on a selected npm-backed operation."
- nvm_entry["nextStep"] = "Only prepare nvm if that operation requires it. " + str(nvm["advice"])
- conditional_runtime.append(nvm_entry)
- for item in results["tools"]:
- if item.get("optional"):
- continue
- if item.get("notChecked"):
- not_checked["tools"].append(
- report_entry(
- str(item["name"]),
- "not-checked",
- reason=str(
- item.get("reason") or "Prerequisites are not satisfied yet."
- ),
- next_step=cli_next_step(item),
- )
- )
- continue
- entry = report_entry(
- str(item["name"]),
- "installed" if item["installed"] else "missing",
- path=item.get("path"),
- version=item.get("version"),
- )
- if item["installed"]:
- installed["tools"].append(entry)
- skipped_already_installed["tools"].append(
- skipped_already_installed_entry(
- entry,
- f"`{item['name']}` is already installed and passed the current verification checks.",
- "Skip CLI installation unless the user explicitly requests reinstall, upgrade, replacement, or project-local installation.",
- )
- )
- else:
- if item.get("incompatibleVersion"):
- entry["status"] = "incompatible"
- elif item.get("wrongPackageSuspected"):
- entry["status"] = "wrong-package-suspected"
- elif item.get("verificationFailed"):
- entry["status"] = "verification-failed"
- entry["reason"] = cli_failure_reason(item)
- entry["nextStep"] = cli_next_step(item)
- failed_or_missing["tools"].append(entry)
- for item in results["skills"]:
- locations = item["locations"]
- if item["installed"]:
- for location in locations:
- installed["skills"].append(
- report_entry(
- str(item["name"]),
- "installed",
- path=location["path"],
- scope=location["scope"],
- source_repo=item.get("sourceRepo"),
- )
- )
- continue
- failed_or_missing["skills"].append(
- report_entry(
- str(item["name"]),
- "missing",
- reason=skill_failure_reason(item),
- next_step=skill_next_step(item),
- source_repo=item.get("sourceRepo"),
- )
- )
- manual_configuration = []
- for item in results["manualChecks"]:
- manual_item = {
- "name": item["name"],
- "category": item["category"],
- "status": "manual-required",
- "reason": "This item cannot be proven or completed safely by the installer alone.",
- "advice": item["advice"],
- "steps": item["steps"],
- }
- for key in (
- "mcpServerConfig",
- "environment",
- "configExample",
- "configExamples",
- ):
- if item.get(key):
- manual_item[key] = item[key]
- manual_configuration.append(manual_item)
- installed_count = sum(len(items) for items in installed.values())
- skipped_count = sum(len(items) for items in skipped_already_installed.values())
- failed_count = sum(len(items) for items in failed_or_missing.values())
- not_checked_count = sum(len(items) for items in not_checked.values())
- return {
- "summary": {
- "installed": installed_count,
- "skippedAlreadyInstalled": skipped_count,
- "failedOrMissing": failed_count,
- "notChecked": not_checked_count,
- "conditionalRuntime": len(conditional_runtime),
- "manualConfiguration": len(manual_configuration),
- },
- "installed": installed,
- "skippedAlreadyInstalled": skipped_already_installed,
- "failedOrMissing": failed_or_missing,
- "notChecked": not_checked,
- "conditionalRuntime": conditional_runtime,
- "manualConfiguration": manual_configuration,
- }
- def normalized_ponytail_repo_identity(value: str) -> str:
- identity = value.strip().lower().strip("/")
- for prefix in ("git+ssh://", "ssh://", "https://", "http://", "git://"):
- if identity.startswith(prefix):
- identity = identity[len(prefix):]
- break
- if identity.startswith("git@"):
- identity = identity[len("git@"):]
- elif identity.startswith("git:"):
- identity = identity[len("git:"):]
- if ":" in identity.split("/")[0]:
- identity = identity.replace(":", "/", 1)
- identity = identity.strip("/").removesuffix(".git").strip("/")
- return identity
- def is_official_ponytail_plugin(platform_name: str, record: object) -> bool:
- if not isinstance(record, dict):
- return False
- entry = cast(dict[str, object], record)
- if platform_name == "codex":
- canonical = str(entry.get("id") or entry.get("canonical") or "").lower()
- if canonical == "ponytail@ponytail":
- return True
- return (
- str(entry.get("name") or "") == "ponytail"
- and str(entry.get("marketplace") or "") == "ponytail"
- )
- if platform_name == "omp":
- if str(entry.get("name") or "") != "ponytail":
- return False
- expected = normalized_ponytail_repo_identity(
- str(EXTERNAL_SKILL_SOURCES["ponytail"]["repo"])
- )
- for key in ("source", "installSpec", "install", "url", "repository", "spec"):
- value = entry.get(key)
- if isinstance(value, str) and normalized_ponytail_repo_identity(value) == expected:
- return True
- return False
- return False
- def ponytail_plugin_record_enabled(record: dict[str, object]) -> bool:
- enabled = record.get("enabled")
- if isinstance(enabled, bool):
- return enabled
- status = str(record.get("status") or record.get("state") or "").lower()
- return status in {"enabled", "active", "on"}
- def plugin_records_from_map(mapping: dict[str, object]) -> list[dict[str, object]]:
- records: list[dict[str, object]] = []
- for key, value in mapping.items():
- if not isinstance(value, dict):
- continue
- record = {"name": str(key), **cast(dict[str, object], value)}
- if "@" in str(key):
- record.setdefault("id", str(key))
- records.append(record)
- return records
- def list_platform_plugins(platform_name: str) -> tuple[str, list[dict[str, object]]]:
- executable = shutil.which(platform_name)
- if executable is None:
- return "cli-unavailable", []
- try:
- completed = subprocess.run(
- subprocess_command((executable, "plugin", "list", "--json")),
- check=False,
- capture_output=True,
- text=True,
- errors="replace",
- timeout=10,
- )
- except (OSError, subprocess.TimeoutExpired):
- return "cli-unavailable", []
- if completed.returncode != 0:
- return "cli-unavailable", []
- try:
- payload = json.loads(completed.stdout)
- except json.JSONDecodeError:
- return "cli-unavailable", []
- records: list[dict[str, object]] = []
- if isinstance(payload, list):
- candidates: list[object] = payload
- for candidate in candidates:
- if isinstance(candidate, dict):
- records.append(cast(dict[str, object], candidate))
- return "ok", records
- if not isinstance(payload, dict):
- return "cli-unavailable", []
- body = cast(dict[str, object], payload)
- for key in ("plugins", "items", "data", "installed"):
- value = body.get(key)
- if isinstance(value, list):
- for candidate in value:
- if isinstance(candidate, dict):
- records.append(cast(dict[str, object], candidate))
- return "ok", records
- if isinstance(value, dict):
- return "ok", plugin_records_from_map(cast(dict[str, object], value))
- if body and all(isinstance(value, dict) for value in body.values()):
- records = plugin_records_from_map(body)
- return "ok", records
- def detect_ponytail_provider(global_skills_dir: Path) -> dict[str, object]:
- valid = [
- name
- for name in PONYTAIL_REQUIRED_SKILLS
- if external_skill_target_is_valid(global_skills_dir, name)
- ]
- existing = [
- name
- for name in PONYTAIL_REQUIRED_SKILLS
- if filesystem_entry_exists(global_skills_dir / name)
- ]
- if len(valid) == len(PONYTAIL_REQUIRED_SKILLS):
- skill_status = "complete"
- elif not existing:
- skill_status = "missing"
- elif valid:
- skill_status = "partial"
- else:
- skill_status = "invalid"
- platforms: dict[str, object] = {}
- any_unavailable = False
- enabled_found = False
- disabled_found = False
- for platform_name in ("codex", "omp"):
- if platform_name == "omp" and detect_omp_root() is None:
- platforms[platform_name] = {"status": "not-configured"}
- continue
- status, records = list_platform_plugins(platform_name)
- if status != "ok":
- platforms[platform_name] = {"status": "cli-unavailable"}
- any_unavailable = True
- continue
- official = [
- record
- for record in records
- if is_official_ponytail_plugin(platform_name, record)
- ]
- if any(ponytail_plugin_record_enabled(record) for record in official):
- enabled_found = True
- platforms[platform_name] = {"status": "installed-enabled"}
- elif official:
- disabled_found = True
- platforms[platform_name] = {"status": "installed-disabled"}
- else:
- platforms[platform_name] = {"status": "missing"}
- if enabled_found:
- provider = "conflict"
- plugin_status = "installed-enabled"
- elif any_unavailable:
- provider = "unknown"
- plugin_status = "cli-unavailable"
- elif disabled_found:
- provider = "onboard-stable"
- plugin_status = "installed-disabled"
- else:
- provider = "onboard-stable"
- plugin_status = "missing"
- if provider == "conflict":
- next_step = "disable-or-remove-plugin"
- elif skill_status == "missing":
- next_step = "install-required"
- elif skill_status in {"partial", "invalid"}:
- next_step = "repair-required"
- else:
- next_step = "none"
- return {
- "provider": provider,
- "skillStatus": skill_status,
- "requiredSkills": list(PONYTAIL_REQUIRED_SKILLS),
- "pluginStatus": plugin_status,
- "platforms": platforms,
- "nextStep": next_step,
- }
- def check_content_alignment(global_skills_dir: Path) -> dict[str, object]:
- """Report selected Skills content, never global rules or host readiness."""
- from onboard_contracts import ContractError
- try:
- from sbtd_upgrade_inventory import build_inventory
- inventory = build_inventory(
- {"schema_version": 1, "skills_roots": [str(global_skills_dir)]},
- package_root=SKILL_DIR,
- )
- resources = inventory["resources"]
- return {
- "scope": "skills-only",
- "checkedRoots": [str(global_skills_dir)],
- "status": "aligned" if all(
- row["classification"] == "current" for row in resources
- ) else "needs-alignment",
- "baseline": inventory["baseline"]["baseline_id"],
- "resources": [
- {key: row[key] for key in ("target", "classification", "decision", "details")}
- for row in resources
- ],
- "nextStep": "Use upgrade --phase plan with an explicit scope before replacing retained content.",
- }
- except (ContractError, OSError, ValueError, RuntimeError, ImportError) as error:
- return {
- "scope": "skills-only",
- "checkedRoots": [str(global_skills_dir)],
- "status": "unverified",
- "reason": getattr(error, "code", "inventory-unavailable"),
- "nextStep": "Run explicit upgrade planning with the complete installed package and declared dependencies.",
- }
- def build_check_results(args: argparse.Namespace) -> dict[str, object]:
- project_roots = resolve_project_roots(args)
- global_skills_dir, global_skills_dir_source = resolve_global_skills_dir(
- getattr(args, "global_skills_dir", None)
- )
- runtime = check_npm_runtime()
- skills = [
- check_skill(name, "bundled", global_skills_dir, None) for name in BUNDLED_SKILLS
- ]
- skills.extend(
- check_skill(name, "referenced", global_skills_dir, None)
- for name in REFERENCED_SKILLS
- )
- skills.extend(
- check_skill(name, "interaction", global_skills_dir, None)
- for name in INTERACTION_SKILLS
- )
- for item in skills:
- if item["name"] == "caveman":
- maintenance = caveman_maintenance_plan(global_skills_dir)
- item["maintenanceState"] = maintenance["state"]
- item["pinnedRef"] = maintenance["pinnedRef"]
- item["maintenanceScope"] = maintenance["scope"]
- item["maintenancePlannedAction"] = maintenance["plannedAction"]
- if maintenance.get("blockedReason"):
- item["maintenanceBlockedReason"] = maintenance["blockedReason"]
- tools = [check_cli_tool(spec) for spec in CLI_TOOLS]
- graft_check = check_graft()
- tools.append(graft_check)
- java_check = check_java_for_maestro()
- maestro_check = check_maestro_cli(java_check)
- tools.append(java_check)
- tools.append(maestro_check)
- manual_checks = build_manual_checks(java_check, maestro_check, None)
- project_checks = [
- build_project_check(
- project_root, bool(getattr(args, "skip_project_agents", False))
- )
- for project_root in project_roots
- ]
- missing = {
- "runtime": [],
- "tools": [
- item["name"]
- for item in tools
- if not item["installed"]
- and not item.get("notChecked")
- and not item.get("optional")
- ],
- "skills": [item["name"] for item in skills if not item["installed"]],
- }
- omp_root = detect_omp_root()
- omp_agents, omp_agents_explicit = omp_agents_target()
- from sbtd_language_tooling import check_language_tooling
- language_tooling = check_language_tooling(project_roots)
- results = {
- "mode": "check",
- "platform": platform.system() or sys.platform,
- "paths": {
- "globalSkillsDir": str(global_skills_dir),
- "globalSkillsDirSource": global_skills_dir_source,
- "projectRoots": [str(project_root) for project_root in project_roots],
- "ompRoot": str(omp_root) if omp_root else None,
- "ompGlobalAgents": (
- str(omp_agents)
- if omp_agents_explicit
- else (
- str(omp_global_agents_path(omp_root).resolve())
- if omp_root is not None
- else None
- )
- ),
- },
- "runtime": runtime,
- "graft": graft_check,
- "tools": tools,
- "skills": skills,
- "manualChecks": manual_checks,
- "projectChecks": project_checks,
- "missing": missing,
- "ponytailProvider": detect_ponytail_provider(global_skills_dir),
- "contentAlignment": check_content_alignment(global_skills_dir),
- "languageTooling": language_tooling,
- }
- results["installationReport"] = build_installation_report(results)
- return results
- def print_report_entries(
- entries: list[dict[str, object]], empty_message: str = "- none"
- ) -> None:
- if not entries:
- print(empty_message)
- return
- for item in entries:
- detail = []
- if item.get("scope"):
- detail.append(f"scope={item['scope']}")
- if item.get("path"):
- detail.append(f"path={item['path']}")
- if item.get("version"):
- detail.append(f"version={item['version']}")
- suffix = f" ({', '.join(detail)})" if detail else ""
- print(f"- {item['name']}: {item['status']}{suffix}")
- if item.get("sourceRepo"):
- print(f" source repo: {item['sourceRepo']}")
- if item.get("reason"):
- print(f" reason: {item['reason']}")
- if item.get("nextStep"):
- print(f" next: {item['nextStep']}")
- def print_indented_block(value: object, indent: int = 4) -> None:
- prefix = " " * indent
- for line in str(value).splitlines():
- print(f"{prefix}{line}")
- def print_config_examples(item: dict[str, object]) -> None:
- examples = item.get("configExamples")
- if isinstance(examples, dict) and examples:
- print(" config examples:")
- for name, example in examples.items():
- label = "generic MCP JSON" if name == "genericJson" else name
- print(f" {label}:")
- print_indented_block(example)
- return
- if item.get("configExample"):
- print(" config example:")
- print_indented_block(item["configExample"])
- def print_installation_report(
- report: dict[str, object], heading: str = "Installation report"
- ) -> None:
- print(f"\n{heading}:")
- summary = report["summary"]
- print(
- "Summary: "
- f"installed={summary['installed']}, "
- f"skipped_already_installed={summary['skippedAlreadyInstalled']}, "
- f"failed_or_missing={summary['failedOrMissing']}, "
- f"not_checked={summary['notChecked']}, "
- f"manual_configuration={summary['manualConfiguration']}"
- )
- print("\nInstalled runtime:")
- print_report_entries(report["installed"]["runtime"])
- print("\nInstalled CLI tools:")
- print_report_entries(report["installed"]["tools"])
- print("\nInstalled skills:")
- print_report_entries(report["installed"]["skills"])
- print("\nSkipped because already installed - runtime:")
- print_report_entries(report["skippedAlreadyInstalled"]["runtime"])
- print("\nSkipped because already installed - CLI tools:")
- print_report_entries(report["skippedAlreadyInstalled"]["tools"])
- print("\nFailed or missing runtime:")
- print_report_entries(report["failedOrMissing"]["runtime"])
- print("\nFailed or missing CLI tools:")
- print_report_entries(report["failedOrMissing"]["tools"])
- print("\nFailed or missing skills:")
- print_report_entries(report["failedOrMissing"]["skills"])
- print("\nNot checked:")
- print_report_entries(report["notChecked"]["tools"])
- print("\nConditional runtime prerequisites (no install selected):")
- print_report_entries(cast(list[dict[str, object]], report["conditionalRuntime"]))
- print("\nManual configuration required:")
- manual_items = report["manualConfiguration"]
- if not manual_items:
- print("- none")
- for item in manual_items:
- print(f"- {item['name']} [{item['category']}]: {item['status']}")
- print(f" reason: {item['reason']}")
- print(f" advice: {item['advice']}")
- print_config_examples(item)
- print(" steps:")
- for index, step in enumerate(item["steps"], start=1):
- print(f" {index}. {step}")
- def print_language_tooling(
- report: dict[str, object], heading: str = "Language tooling"
- ) -> None:
- print(f"\n{heading}: {report.get('status', 'unknown')}")
- for project in cast(list[dict[str, object]], report.get("projects") or []):
- languages = cast(list[dict[str, object]], project.get("languages") or [])
- if languages:
- names = ", ".join(str(item["display"]) for item in languages)
- print(f"- {project['root']}: {names}")
- ast_grep = cast(dict[str, object], report.get("astGrep") or {})
- if ast_grep:
- print(f"- omp ast-grep: {ast_grep.get('status')}")
- languages_map = cast(dict[str, dict[str, object]], report.get("languages") or {})
- for name in sorted(languages_map):
- entry = languages_map[name]
- if entry.get("builtIn"):
- for server in cast(list[dict[str, object]], entry.get("servers") or []):
- state = "available" if server.get("available") else "missing"
- print(f"- {entry['display']} server {server['command']}: {state}")
- else:
- state = (
- "custom lsp.yml entry configured"
- if entry.get("customConfigured")
- else "custom lsp.yml entry missing"
- )
- print(f"- {entry['display']}: {state}")
- for item in cast(list[dict[str, object]], report.get("guidance") or []):
- print(f" guidance: {item['summary']}")
- for step in cast(list[str], item.get("steps") or []):
- print(f" - {step}")
- if item.get("requiresConsent"):
- print(f" skip impact: {item['skipImpact']}")
- for write in cast(list[dict[str, object]], report.get("writes") or []):
- print(f" wrote: {write['action']} -> {write['path']}")
- for failure in cast(list[dict[str, object]], report.get("failures") or []):
- print(f" failed: {failure['action']} -> {failure['path']}: {failure['error']}")
- if report.get("nextStep") and report.get("status") in {
- "needs-confirmation",
- "configured",
- "failed",
- }:
- print(f" next: {report['nextStep']}")
- def run_language_tooling_step(
- mode: str, args: argparse.Namespace
- ) -> dict[str, object] | None:
- """omp LSP/ast-grep readiness plus consent-gated config writes.
- Detection and guidance are always read-only; the pending configuration
- writes run only with the separate ``--language-tooling`` consent flag.
- """
- if mode not in {"init", "init-projects"}:
- return None
- from sbtd_language_tooling import apply_language_tooling, check_language_tooling
- report = check_language_tooling(resolve_project_roots(args))
- if report["status"] == "skipped":
- return report
- return apply_language_tooling(
- report, confirmed=bool(getattr(args, "language_tooling", False))
- )
- def print_check_results(results: dict[str, object], as_json: bool) -> None:
- if as_json:
- print(json.dumps(results, indent=2, ensure_ascii=False))
- return
- print("Preflight check")
- print(f"Platform: {results['platform']}")
- paths = results["paths"]
- print(f"Global skills: {paths['globalSkillsDir']}")
- alignment = results.get("contentAlignment", {})
- print(f"Skills-only content alignment: {alignment.get('status', 'unverified')}")
- if alignment.get("status") != "aligned":
- print(" Installation validity does not prove content alignment; use explicit upgrade planning.")
- for project_root in paths["projectRoots"]:
- print(f"Project root: {project_root}")
- runtime = results["runtime"]
- print("\nRuntime preflight:")
- npm = runtime["npm"]
- node = runtime["node"]
- nvm = runtime["nvm"]
- npm_status = "installed" if npm["installed"] else "missing"
- node_status = "installed" if node["installed"] else "missing"
- nvm_status = "installed" if nvm["installed"] else "missing"
- print(
- f"- npm: {npm_status}"
- + (f" at {npm['path']} ({npm['version']})" if npm.get("path") else "")
- )
- print(
- f"- node: {node_status}"
- + (f" at {node['path']} ({node['version']})" if node.get("path") else "")
- )
- print(
- f"- nvm: {nvm_status}" + (f" ({nvm['version']})" if nvm.get("version") else "")
- )
- if not npm["installed"]:
- print(
- f" action: npm is needed only for a selected npm-backed install or upgrade; if that action is confirmed, {shell_prefix()}run `{onboard_command('ensure-npm', '--yes')}`."
- )
- print("\nCLI tools:")
- for item in results["tools"]:
- if item.get("optional"):
- continue
- status = "installed" if item["installed"] else "missing"
- if item.get("notChecked"):
- status = "not-checked"
- elif item.get("incompatibleVersion"):
- status = "incompatible"
- elif item.get("wrongPackageSuspected"):
- status = "wrong-package-suspected"
- elif item.get("verificationFailed"):
- status = "verification-failed"
- detail = f" ({item['version']})" if item.get("version") else ""
- path = f" at {item['path']}" if item.get("path") else ""
- print(f"- {item['name']}: {status}{path}{detail}")
- if item.get("verifyCommand"):
- verified = "passed" if item.get("installed") else "not passed"
- print(f" verify: {item['verifyCommand']} ({verified})")
- if item.get("verificationScope"):
- print(f" verification scope: {item['verificationScope']}")
- if item.get("reason"):
- print(f" reason: {item['reason']}")
- if not item["installed"]:
- print(f" global: {item['globalInstall']}")
- if item.get("projectInstall"):
- print(f" project: {item['projectInstall']}")
- print(f" advice: {item['advice']}")
- graft = results["graft"]
- assert isinstance(graft, dict)
- print("\nOptional Graft CLI:")
- print(f"- graft: {graft['status']}")
- if graft.get("reason"):
- print(f" reason: {graft['reason']}")
- if graft.get("nextStep"):
- print(f" next: {graft['nextStep']}")
- wiring = results.get("graftWiring")
- if isinstance(wiring, dict):
- print(f"\nGraft wiring: {wiring.get('status')}")
- if wiring.get("reason"):
- print(f" reason: {wiring['reason']}")
- if wiring.get("nextStep"):
- print(f" next: {wiring['nextStep']}")
- print("\nSkills:")
- for item in results["skills"]:
- status = "installed" if item["installed"] else "missing"
- print(f"- {item['name']} [{item['group']}]: {status}")
- for location in item["locations"]:
- print(f" {location['scope']}: {location['path']}")
- if not item["installed"]:
- print(f" global target: {item['globalTarget']}")
- if item["projectTarget"]:
- print(f" project target: {item['projectTarget']}")
- if item.get("sourceRepo"):
- print(f" source repo: {item['sourceRepo']}")
- if item.get("maintenanceState"):
- print(
- f" maintenance: {item['maintenanceState']}"
- f" (pinned {item.get('pinnedRef')}, {item.get('maintenanceScope')})"
- )
- if item.get("maintenancePlannedAction"):
- print(f" planned action: {item['maintenancePlannedAction']}")
- if item.get("maintenanceBlockedReason"):
- print(f" blocked: {item['maintenanceBlockedReason']}")
- print("\nManual checks:")
- for item in results["manualChecks"]:
- print(f"- {item['name']} [{item['category']}]: {item['advice']}")
- print_config_examples(item)
- provider = cast(dict[str, object], results["ponytailProvider"])
- print("\nPonytail provider:")
- print(f"- provider: {provider['provider']}")
- print(f"- skillStatus: {provider['skillStatus']}")
- print(f"- pluginStatus: {provider['pluginStatus']}")
- print(f"- nextStep: {provider['nextStep']}")
- if results["projectChecks"]:
- print("")
- print_projects_check_results(
- {"mode": "check-projects", "projects": results["projectChecks"]},
- False,
- )
- missing = results["missing"]
- if missing["runtime"] or missing["tools"] or missing["skills"]:
- print("\nMissing summary:")
- if missing["runtime"]:
- print("- runtime: " + ", ".join(missing["runtime"]))
- if missing["tools"]:
- print("- tools: " + ", ".join(missing["tools"]))
- if missing["skills"]:
- print("- skills: " + ", ".join(missing["skills"]))
- print(
- "Resolve prerequisites for the selected operation only; missing npm and optional Graft do not block unrelated safe work."
- )
- else:
- print("\nMissing summary: none")
- print_installation_report(results["installationReport"])
- language_tooling = results.get("languageTooling")
- if isinstance(language_tooling, dict):
- print_language_tooling(language_tooling)
- def backup_path(target: Path) -> Path:
- today = dt.date.today().isoformat()
- index = 1
- while True:
- candidate = target.with_name(f"{target.name}.{today}-{index}")
- if not candidate.exists():
- return candidate
- index += 1
- def remove_existing_target(target: Path) -> None:
- if target.is_dir() and not target.is_symlink():
- shutil.rmtree(target)
- else:
- target.unlink()
- EXTERNAL_TREE_DIGEST_EXCLUDED_DIRS = frozenset(
- {"__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache"}
- )
- EXTERNAL_TREE_DIGEST_EXCLUDED_SUFFIXES = frozenset({".pyc", ".pyo"})
- EXTERNAL_TREE_COMPARE_EXCLUDED_DIRS = {".git", *EXTERNAL_TREE_DIGEST_EXCLUDED_DIRS}
- def external_copy_ignore(*extra: str) -> Callable[[str, list[str]], set[str]]:
- """Copies drop exactly what the pinned digest drops; otherwise unauthenticated
- cache files reach installed Skills without changing treeSha256."""
- match_names = shutil.ignore_patterns(
- *extra, *sorted(EXTERNAL_TREE_DIGEST_EXCLUDED_DIRS)
- )
- def ignore(directory: str, names: list[str]) -> set[str]:
- ignored = set(match_names(directory, names))
- # The digest drops cache entries by file suffix and never rejects a
- # directory for its name, so a directory called `pkg.pyc` must still be
- # copied; a bare glob would drop that whole subtree while its files kept
- # counting toward treeSha256.
- for name in names:
- if name in ignored:
- continue
- if Path(name).suffix not in EXTERNAL_TREE_DIGEST_EXCLUDED_SUFFIXES:
- continue
- if Path(directory, name).is_dir():
- continue
- ignored.add(name)
- return ignored
- return ignore
- def compare_tree(
- source: Path, target: Path, ignored_names: set[str] | None = None
- ) -> list[str]:
- failures: list[str] = []
- ignored = ignored_names or set()
- for item in source.rglob("*"):
- rel = item.relative_to(source)
- if any(part in ignored for part in rel.parts):
- continue
- if rel.suffix in EXTERNAL_TREE_DIGEST_EXCLUDED_SUFFIXES and not item.is_dir():
- continue
- other = target / rel
- if item.is_dir():
- if not other.is_dir():
- failures.append(str(rel))
- continue
- if not other.is_file() or not filecmp.cmp(item, other, shallow=False):
- failures.append(str(rel))
- return failures
- def missing_file_lines(source_text: str, target_text: str) -> list[str]:
- target_lines = target_text.splitlines()
- if target_lines:
- target_lines[0] = target_lines[0].removeprefix("\ufeff")
- existing_lines = set(target_lines)
- missing_lines: list[str] = []
- pending_separator = False
- for line in source_text.splitlines():
- if not line:
- pending_separator = bool(missing_lines)
- continue
- if line in existing_lines:
- continue
- if pending_separator and missing_lines[-1] != "":
- missing_lines.append("")
- missing_lines.append(line)
- existing_lines.add(line)
- pending_separator = False
- return missing_lines
- def ensure_file_contains(source: Path, target: Path) -> str:
- source_text = source.read_text(encoding="utf-8")
- target.parent.mkdir(parents=True, exist_ok=True)
- if not target.exists():
- if not source_text.endswith("\n"):
- source_text += "\n"
- target.write_text(source_text, encoding="utf-8")
- return "created"
- existing = target.read_text(encoding="utf-8")
- missing_lines = missing_file_lines(source_text, existing)
- if not missing_lines:
- return "skipped-already-present"
- prefix = "" if not existing or existing.endswith("\n") else "\n"
- separator = "\n" if existing.strip() else ""
- addition = "\n".join(missing_lines) + "\n"
- target.write_text(
- f"{existing}{prefix}{separator}{addition}",
- encoding="utf-8",
- )
- return "updated"
- def copy_operation(operation: Operation) -> str:
- if operation.same_location:
- return "skipped-same-location"
- if (
- operation.kind == "dir"
- and operation.skip_when_valid
- and external_skill_target_is_valid(
- operation.target.parent, operation.target.name
- )
- ):
- return "skipped-already-valid"
- operation.target.parent.mkdir(parents=True, exist_ok=True)
- if operation.kind == "ensure-file-block":
- return ensure_file_contains(operation.source, operation.target)
- if operation.kind == "file":
- shutil.copy2(operation.source, operation.target)
- return "copied"
- if operation.target.exists():
- remove_existing_target(operation.target)
- action = "overwritten-without-backup"
- else:
- action = "copied"
- shutil.copytree(operation.source, operation.target)
- return action
- GITIGNORE_MUST_TRACK_PROBES = (
- ".gitignore",
- ".gitattributes",
- "AGENTS.md",
- "CLAUDE.md",
- ".agents/skills/example/SKILL.md",
- ".agents/skills/react-bits-pro/SKILL.md",
- "ai/tasks/index.md",
- "ai/tasks/example/task.md",
- "ai/tasks/example/legacy-task.json",
- "ai/tasks/example/prd.md",
- "ai/tasks/example/design.md",
- "ai/tasks/example/implement.md",
- "ai/tasks/example/reports.md",
- "ai/tasks/00-bootstrap-guidelines/task.md",
- "ai/tasks/parent/child/task.md",
- "ai/tasks/archive/2026-Q1/example/task.md",
- "ai/tasks/archive/undated/example/task.md",
- "docs/spec/lessons.md",
- "docs/lessons.md",
- "docs/lessons/index.md",
- "docs/lessons/topics/example.md",
- "docs/lessons/archive/2026-Q1.md",
- "docs/CONTEXT.md",
- "docs/adr/example.md",
- "docs/contexts/example/CONTEXT.md",
- "docs/contexts/example/adr/example.md",
- "docs/PRODUCT.md",
- "docs/DESIGN.md",
- "features/example.feature",
- "maestro/flow/smoke.yml",
- "maestro/flow/ios/smoke.yml",
- "maestro/flow/android/smoke.yml",
- "tests/unit/test_example.py",
- "tests/api/test_example.py",
- "tests/e2e/example.spec.ts",
- "tests/e2e/manifest/ui-test-manifest.json",
- "tests/e2e/manifest/ui-selector-audit.json",
- "tests/e2e/manifest/ui-test-coverage.json",
- )
- GITIGNORE_MUST_IGNORE_PROBES = (
- ".sbtd",
- ".sbtd/developer",
- ".sbtd/active-task.json",
- ".sbtd/tasks/example/task.md",
- "docs/handoffs",
- "docs/handoffs/session.md",
- "ai/tasks/example/reports",
- "ai/tasks/example/reports/raw.json",
- "ai/tasks/parent/child/reports",
- "ai/tasks/parent/child/reports/raw.json",
- "ai/tasks/archive/2026-Q1/example/reports",
- "ai/tasks/archive/2026-Q1/example/reports/raw.json",
- "ai/tasks/archive/undated/example/reports",
- "ai/tasks/archive/undated/example/reports/raw.json",
- "graft",
- "graft/index.json",
- ".graft",
- ".graft/state.json",
- ".env",
- ".env.local",
- ".impeccable/config.local.json",
- )
- GITIGNORE_PROBE_UNAVAILABLE = "unavailable"
- GITIGNORE_PROBE_ERROR = "error"
- # Checks that could not be evaluated. They are not failures, but the final
- # summary must not read as "everything was verified" once one is recorded.
- UNVERIFIED_CHECKS: list[str] = []
- def note_unverified(message: str) -> None:
- UNVERIFIED_CHECKS.append(message)
- print(f"Note: {message}", file=sys.stderr)
- @dataclass(frozen=True)
- class GitignoreVerdict:
- ignored: bool
- origin: str
- def gitignore_verdicts(
- project_root: Path,
- probes: tuple[str, ...],
- *,
- env: dict[str, str] | None = None,
- ) -> dict[str, GitignoreVerdict] | str:
- """Resolve every probe in one `git check-ignore` pass.
- `-v --non-matching` names the deciding line for both outcomes, so a
- negation that re-exposes a runtime path is reported as precisely as a broad
- exclusion that buries a workflow file. The verdict follows git's own rule:
- the last matching pattern wins and a `!` pattern means "not ignored", which
- `--quiet` alone cannot distinguish from "no pattern matched".
- `-z --stdin` is what makes that verdict trustworthy. It emits
- `source NUL linenum NUL pattern NUL pathname NUL`, so the deciding pattern
- arrives as its own field. Splitting the textual `source:linenum:pattern`
- form instead truncates any pattern containing a colon: `!.en[v:]` reduces
- to `]`, which drops the leading `!` and reports a re-included `.env` as
- ignored -- inverting the verdict for the exact case this check exists to
- catch.
- """
- result = run_project_command(
- (
- "git",
- "check-ignore",
- "--no-index",
- "-v",
- "--non-matching",
- "-z",
- "--stdin",
- ),
- project_root,
- timeout=60,
- stdin_text="".join(f"{probe}\0" for probe in probes),
- env=env,
- )
- if result is None or result.returncode == 128:
- return GITIGNORE_PROBE_UNAVAILABLE
- if result.returncode not in (0, 1):
- return GITIGNORE_PROBE_ERROR
- fields = result.stdout.split("\0")
- if fields and fields[-1] == "":
- fields.pop()
- if len(fields) % 4:
- return GITIGNORE_PROBE_ERROR
- verdicts: dict[str, GitignoreVerdict] = {}
- for index in range(0, len(fields), 4):
- source, linenum, pattern, path = fields[index : index + 4]
- verdicts[path] = GitignoreVerdict(
- ignored=bool(pattern) and not pattern.startswith("!"),
- origin=f"{source}:{linenum}:{pattern}" if pattern else "",
- )
- if set(verdicts) != set(probes):
- return GITIGNORE_PROBE_ERROR
- return verdicts
- def gitignore_effectiveness_failures(target: Path) -> list[str]:
- """Verify shared SBTD paths and local-state protection using Git semantics."""
- project_root = target.parent
- verdicts = gitignore_verdicts(
- project_root, GITIGNORE_MUST_TRACK_PROBES + GITIGNORE_MUST_IGNORE_PROBES
- )
- if isinstance(verdicts, str):
- if verdicts == GITIGNORE_PROBE_ERROR:
- return [
- "git check-ignore could not evaluate the merged .gitignore --"
- " resolve the repository error instead of trusting rules that"
- " were never verified"
- ]
- # git is missing or the project is outside a work tree: there is no
- # ignore semantics to query, so say the check was skipped instead of
- # letting a silent pass read as "verified effective".
- note_unverified(
- ".gitignore effectiveness verification skipped for"
- f" {project_root} -- git could not evaluate it (no git binary or no"
- " work tree), so the merged rules remain unverified."
- )
- return []
- failures: list[str] = []
- blocked: dict[str, list[str]] = {}
- for probe in GITIGNORE_MUST_TRACK_PROBES:
- verdict = verdicts[probe]
- if verdict.ignored:
- key = verdict.origin or "an unknown gitignore pattern"
- blocked.setdefault(key, []).append(probe)
- for origin, paths in blocked.items():
- shown = ", ".join(paths[:3])
- extra = f" (+{len(paths) - 3} more)" if len(paths) > 3 else ""
- failures.append(
- f"{origin} ignores paths that must stay trackable: {shown}{extra}"
- " -- confirm the intended shared paths before narrowing that pattern;"
- " do not remove unrelated project exclusions automatically"
- )
- for probe in GITIGNORE_MUST_IGNORE_PROBES:
- verdict = verdicts[probe]
- if verdict.ignored:
- continue
- if verdict.origin:
- failures.append(
- f"{verdict.origin} re-includes {probe}, which must stay ignored"
- " -- narrow that re-inclusion so local runtime state and"
- " secrets cannot be committed"
- )
- else:
- failures.append(
- f"{probe} must stay ignored but no pattern covers it -- restore"
- " the removed rule so local runtime state and secrets cannot be"
- " committed"
- )
- return failures
- def verify_operation(operation: Operation) -> list[str]:
- if operation.same_location:
- return []
- if (
- operation.kind == "dir"
- and operation.skip_when_valid
- and external_skill_target_is_valid(
- operation.target.parent, operation.target.name
- )
- ):
- return []
- if operation.kind == "ensure-file-block":
- if not operation.target.is_file():
- return [operation.label]
- source_text = operation.source.read_text(encoding="utf-8")
- target_text = operation.target.read_text(encoding="utf-8")
- if missing_file_lines(source_text, target_text):
- return [operation.label]
- return gitignore_effectiveness_failures(operation.target)
- if operation.kind == "file":
- if operation.target.is_file() and filecmp.cmp(
- operation.source, operation.target, shallow=False
- ):
- return []
- return [operation.label]
- return compare_tree(operation.source, operation.target)
- def canonical_external_skill_name(name: str) -> str:
- return MATTPOCOCK_LEGACY_RENAMES.get(name, name)
- def legacy_external_skill_names_for(canonical_name: str) -> list[str]:
- return [
- legacy_name
- for legacy_name, replacement_name in MATTPOCOCK_LEGACY_RENAMES.items()
- if replacement_name == canonical_name
- ]
- def filesystem_entry_exists(path: Path) -> bool:
- return path.exists() or path.is_symlink()
- def legacy_external_skill_identity_error(target: Path, legacy_name: str) -> str | None:
- if not target.is_dir() or target.is_symlink():
- return f"legacy target is not a regular Skill directory: {target}"
- skill_md = target / "SKILL.md"
- if not skill_md.is_file() or skill_md.is_symlink():
- return f"legacy target has no regular SKILL.md: {target}"
- actual_name = read_skill_frontmatter_name(skill_md)
- if actual_name != legacy_name:
- return (
- f"legacy Skill identity conflict: expected {legacy_name}, "
- f"found {actual_name or '<missing>'}"
- )
- return None
- def external_skill_dependency_closure(skill_names: list[str]) -> list[str]:
- selected: list[str] = []
- def add(name: str) -> None:
- if name in selected:
- return
- selected.append(name)
- for dependency in MATTPOCOCK_REQUIRED_DEPENDENCIES.get(name, ()):
- add(dependency)
- for skill_name in skill_names:
- add(skill_name)
- return selected
- def parse_skill_names(args: argparse.Namespace) -> list[str]:
- if getattr(args, "all", False):
- return external_skill_dependency_closure(list(EXTERNAL_SKILL_SOURCES.keys()))
- raw = getattr(args, "skills", None)
- if not raw:
- raise SystemExit("--skills or --all is required")
- requested = [item.strip() for item in raw.split(",") if item.strip()]
- if "all" in requested:
- return external_skill_dependency_closure(list(EXTERNAL_SKILL_SOURCES.keys()))
- removed = [name for name in requested if name in MATTPOCOCK_REMOVED_SKILLS]
- if removed:
- details = "; ".join(
- f"{name}: {MATTPOCOCK_REMOVED_SKILLS[name]}" for name in removed
- )
- raise SystemExit(f"Removed external skill(s): {details}")
- canonical_requested = [canonical_external_skill_name(name) for name in requested]
- unknown = [
- name for name in canonical_requested if name not in EXTERNAL_SKILL_SOURCES
- ]
- if unknown:
- known = ", ".join(EXTERNAL_SKILL_SOURCES.keys())
- raise SystemExit(
- f"Unknown external skill(s): {', '.join(unknown)}. Known: {known}"
- )
- names = canonical_requested
- if getattr(args, "expand_dependencies", True):
- names = external_skill_dependency_closure(canonical_requested)
- unique: list[str] = []
- for name in names:
- if name not in unique:
- unique.append(name)
- return unique
- def resolve_install_skills_dir(args: argparse.Namespace) -> Path:
- return resolve_global_skills_dir(args.global_skills_dir)[0]
- def external_install_plan(
- args: argparse.Namespace, selected: list[str], target_dir: Path
- ) -> dict[str, object]:
- legacy_targets = [
- {
- "name": legacy_name,
- "replacement": name,
- "target": str(target_dir / legacy_name),
- "targetExists": (target_dir / legacy_name).exists(),
- }
- for name in selected
- for legacy_name in legacy_external_skill_names_for(name)
- if (target_dir / legacy_name).exists()
- ]
- return {
- "mode": "install-external-skills",
- "scope": args.scope,
- "requestedSource": args.source,
- "targetDir": str(target_dir),
- "forceOverwriteExisting": True,
- "backupExistingTargets": "temporary-rollback",
- "transactionalInstall": True,
- "replaceFlagProvided": bool(args.replace),
- "removeLegacyAfterCanonicalCommit": legacy_targets,
- "skills": [
- {
- "name": name,
- "repo": EXTERNAL_SKILL_SOURCES[name]["repo"],
- "target": str(target_dir / name),
- "targetExists": (target_dir / name).exists(),
- }
- for name in selected
- ],
- }
- def print_external_install_plan(plan: dict[str, object], as_json: bool) -> None:
- if as_json:
- print(json.dumps(plan, indent=2, ensure_ascii=False))
- return
- print("External skill install plan")
- print(f"Scope: {plan['scope']}")
- print(f"Requested source: {plan['requestedSource']}")
- print(f"Target skills dir: {plan['targetDir']}")
- print(
- "Transactional install: yes, existing targets use a temporary rollback backup"
- )
- legacy_items = plan.get("removeLegacyAfterCanonicalCommit")
- if isinstance(legacy_items, list) and legacy_items:
- print("Legacy targets removed after canonical commit:")
- for item in legacy_items:
- if not isinstance(item, dict):
- raise RuntimeError(
- "external install legacy plan entry must be an object"
- )
- entry = cast(dict[str, object], item)
- status = "exists" if entry["targetExists"] else "missing"
- print(
- f"- {entry['name']} -> {entry['replacement']}: "
- f"{entry['target']} ({status})"
- )
- skill_items = plan.get("skills")
- if not isinstance(skill_items, list):
- raise RuntimeError("external install plan skills must be a list")
- for item in skill_items:
- if not isinstance(item, dict):
- raise RuntimeError("external install skill plan entry must be an object")
- entry = cast(dict[str, object], item)
- status = "exists" if entry["targetExists"] else "missing"
- print(f"- {entry['name']}: {entry['target']} ({status})")
- print(f" source: {entry['repo']}")
- def discover_skill_dirs(repo_root: Path) -> list[Path]:
- dirs: list[Path] = []
- for skill_md in repo_root.rglob("SKILL.md"):
- try:
- rel = skill_md.relative_to(repo_root)
- except ValueError:
- continue
- if ".git" in rel.parts:
- continue
- dirs.append(skill_md.parent)
- return dirs
- def resolve_contained_relative_path(root: Path, value: object, field: str) -> Path:
- raw = str(value or "")
- relative = Path(raw)
- if not raw or relative.is_absolute() or ".." in relative.parts:
- raise RuntimeError(
- f"{field} must be a non-empty relative path without '..': {raw or '<missing>'}"
- )
- resolved_root = root.resolve()
- candidate = (resolved_root / relative).resolve()
- try:
- candidate.relative_to(resolved_root)
- except ValueError as exc:
- raise RuntimeError(
- f"{field} must stay within its declared root: {raw}"
- ) from exc
- return candidate
- def source_dir_for_external_skill(repo_root: Path, skill_name: str) -> Path:
- spec = EXTERNAL_SKILL_SOURCES[skill_name]
- configured_subpath = spec.get("subpath")
- if configured_subpath:
- candidate = resolve_contained_relative_path(
- repo_root, configured_subpath, f"configured subpath for {skill_name}"
- )
- if (candidate / "SKILL.md").is_file():
- return candidate
- raise RuntimeError(
- f"configured subpath for {skill_name} does not contain SKILL.md: {configured_subpath}"
- )
- subpath = MATTPOCOCK_SKILL_SUBPATHS.get(skill_name)
- if subpath:
- candidate = resolve_contained_relative_path(
- repo_root, subpath, f"fallback subpath for {skill_name}"
- )
- if (candidate / "SKILL.md").is_file():
- return candidate
- aliases = {str(alias) for alias in spec["aliases"]}
- candidates = discover_skill_dirs(repo_root)
- if not candidates:
- raise RuntimeError("no SKILL.md files found in cloned repository")
- by_dir_name = [candidate for candidate in candidates if candidate.name in aliases]
- if len(by_dir_name) == 1:
- return by_dir_name[0]
- by_frontmatter = [
- candidate
- for candidate in candidates
- if read_skill_frontmatter_name(candidate / "SKILL.md") in aliases
- ]
- if len(by_frontmatter) == 1:
- return by_frontmatter[0]
- repo = str(spec["repo"])
- if len(EXTERNAL_REPO_TO_SKILLS[repo]) == 1 and len(candidates) == 1:
- return candidates[0]
- rel_candidates = ", ".join(
- str(candidate.relative_to(repo_root)) for candidate in candidates[:20]
- )
- if len(candidates) > 20:
- rel_candidates += ", ..."
- raise RuntimeError(
- f"could not uniquely locate {skill_name}; candidates: {rel_candidates}"
- )
- def external_tree_digest_excluded(relative: Path) -> bool:
- """Locally generated caches must not change a pinned Skill's identity."""
- if EXTERNAL_TREE_DIGEST_EXCLUDED_DIRS.intersection(relative.parts):
- return True
- return relative.suffix in EXTERNAL_TREE_DIGEST_EXCLUDED_SUFFIXES
- def external_tree_sha256(root: Path) -> str:
- digest = hashlib.sha256()
- files = [candidate for candidate in root.rglob("*") if candidate.is_file()]
- # Plain relative POSIX order, stable across operating systems: sorting
- # Path objects applies normcase folding on Windows, which reorders
- # case-differing names and would make pinned digests platform-dependent.
- files.sort(key=lambda candidate: candidate.relative_to(root).as_posix())
- for path in files:
- if external_tree_digest_excluded(path.relative_to(root)):
- continue
- if path.is_symlink():
- raise RuntimeError(
- f"external Skill contains an unsupported symlink: {path.relative_to(root)}"
- )
- relative = path.relative_to(root).as_posix().encode("utf-8")
- digest.update(len(relative).to_bytes(8, "big"))
- digest.update(relative)
- content = path.read_bytes()
- digest.update(len(content).to_bytes(8, "big"))
- digest.update(content)
- return digest.hexdigest()
- def prune_unmanaged_stable_skill_directories(
- manifest: dict[str, object], stable_root: Path
- ) -> list[str]:
- skills = manifest.get("skills")
- if not isinstance(skills, dict):
- raise RuntimeError("stable External Skills manifest skills must be an object")
- unresolved_skills_root = stable_root / "skills"
- if (
- not unresolved_skills_root.is_dir()
- or unresolved_skills_root.is_symlink()
- ):
- raise RuntimeError("stable External Skills skills directory is invalid")
- skills_root = unresolved_skills_root.resolve()
- expected: set[str] = set()
- for skill_name, entry in skills.items():
- if not isinstance(skill_name, str) or not isinstance(entry, dict):
- raise RuntimeError("stable External Skills manifest contains invalid skill metadata")
- target = resolve_contained_relative_path(
- stable_root,
- entry.get("stablePath"),
- f"stablePath for {skill_name}",
- ).resolve()
- try:
- relative = target.relative_to(skills_root)
- except ValueError as exc:
- raise RuntimeError(
- f"stablePath for {skill_name} must be under skills/"
- ) from exc
- if len(relative.parts) != 1:
- raise RuntimeError(
- f"stablePath for {skill_name} must be a direct child of skills/"
- )
- expected.add(relative.name)
- pruned: list[str] = []
- for candidate in unresolved_skills_root.iterdir():
- if candidate.name in expected:
- continue
- remove_existing_target(candidate)
- pruned.append(candidate.name)
- return sorted(pruned)
- def validate_external_skill_source(skill_name: str, source: Path) -> None:
- if not source.is_dir() or source.is_symlink():
- raise RuntimeError(
- f"external Skill source is not a regular directory: {source}"
- )
- skill_md = source / "SKILL.md"
- if not skill_md.is_file() or skill_md.is_symlink():
- raise RuntimeError(
- f"external Skill {skill_name} does not contain a regular SKILL.md"
- )
- frontmatter_name = read_skill_frontmatter_name(skill_md)
- if frontmatter_name != skill_name:
- raise RuntimeError(
- f"external Skill {skill_name} frontmatter name is {frontmatter_name or '<missing>'}"
- )
- for path in source.rglob("*"):
- if path.is_symlink():
- raise RuntimeError(
- f"external Skill {skill_name} contains an unsupported symlink: {path.relative_to(source)}"
- )
- def external_skill_target_is_valid(skills_root: Path, skill_name: str) -> bool:
- try:
- validate_external_skill_source(skill_name, skills_root / skill_name)
- except (OSError, RuntimeError):
- return False
- return True
- def load_external_stable_manifest(relaxed: bool = False) -> dict[str, object]:
- try:
- manifest = json.loads(EXTERNAL_STABLE_MANIFEST.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- raise RuntimeError(
- f"cannot read stable External Skills manifest: {exc}"
- ) from exc
- if manifest.get("schemaVersion") != 1:
- raise RuntimeError("stable External Skills manifest schemaVersion must be 1")
- repositories = manifest.get("repositories")
- skills = manifest.get("skills")
- if not isinstance(repositories, dict) or not isinstance(skills, dict):
- raise RuntimeError(
- "stable External Skills manifest must contain repositories and skills objects"
- )
- if not relaxed and set(skills) != set(EXTERNAL_SKILL_SOURCES):
- missing = sorted(set(EXTERNAL_SKILL_SOURCES) - set(skills))
- extra = sorted(set(skills) - set(EXTERNAL_SKILL_SOURCES))
- raise RuntimeError(
- "stable External Skills manifest does not match the canonical set; "
- f"missing={missing}, extra={extra}"
- )
- validate_external_stable_metadata(manifest, EXTERNAL_STABLE_ROOT)
- return manifest
- def validate_external_stable_metadata(
- manifest: dict[str, object], stable_root: Path
- ) -> None:
- repositories = manifest.get("repositories")
- if not isinstance(repositories, dict):
- raise RuntimeError(
- "stable External Skills manifest repositories must be an object"
- )
- for repository_id, repository in repositories.items():
- if not isinstance(repository, dict):
- raise RuntimeError(
- f"stable repository metadata is invalid: {repository_id}"
- )
- revision = str(repository.get("revision") or "")
- if not re.fullmatch(r"[0-9a-f]{40}", revision):
- raise RuntimeError(
- f"stable repository revision is invalid: {repository_id}"
- )
- license_files = repository.get("licenseFiles")
- if not isinstance(license_files, list) or not license_files:
- raise RuntimeError(
- f"stable repository has no licenseFiles: {repository_id}"
- )
- for license_entry in license_files:
- if not isinstance(license_entry, dict):
- raise RuntimeError(
- f"stable repository has an invalid license entry: {repository_id}"
- )
- source = str(license_entry.get("source") or "")
- stable_path = str(license_entry.get("stablePath") or "")
- if not source or not stable_path:
- raise RuntimeError(
- f"stable repository license file is missing or invalid: {repository_id}/{stable_path}"
- )
- license_path = resolve_contained_relative_path(
- stable_root,
- stable_path,
- f"license stablePath for {repository_id}",
- )
- if not license_path.is_file():
- raise RuntimeError(
- f"stable repository license file is missing or invalid: {repository_id}/{stable_path}"
- )
- def stable_external_skill_source(
- manifest: dict[str, object],
- skill_name: str,
- stable_root: Path = EXTERNAL_STABLE_ROOT,
- ) -> tuple[Path, str, str]:
- skills = manifest["skills"]
- repositories = manifest["repositories"]
- assert isinstance(skills, dict)
- assert isinstance(repositories, dict)
- skill = skills.get(skill_name)
- if not isinstance(skill, dict):
- raise RuntimeError(f"stable manifest has no entry for {skill_name}")
- repository_id = skill.get("repository")
- repository = repositories.get(repository_id)
- if not isinstance(repository_id, str) or not isinstance(repository, dict):
- raise RuntimeError(f"stable manifest repository is invalid for {skill_name}")
- source = resolve_contained_relative_path(
- stable_root,
- skill.get("stablePath"),
- f"stablePath for {skill_name}",
- )
- validate_external_skill_source(skill_name, source)
- expected_digest = str(skill.get("treeSha256") or "")
- actual_digest = external_tree_sha256(source)
- if not expected_digest or actual_digest != expected_digest:
- raise RuntimeError(
- f"stable External Skill checksum mismatch for {skill_name}: "
- f"expected {expected_digest or '<missing>'}, got {actual_digest}"
- )
- revision = str(repository.get("revision") or "")
- repo = str(repository.get("url") or "")
- if not re.fullmatch(r"[0-9a-f]{40}", revision):
- raise RuntimeError(
- f"stable External Skill revision is invalid for {skill_name}"
- )
- if repo != str(EXTERNAL_SKILL_SOURCES[skill_name]["repo"]):
- raise RuntimeError(
- f"stable External Skill repository does not match configured source for {skill_name}"
- )
- return source, revision, str(manifest.get("stableSet") or "")
- def clone_repo(repo: str, destination: Path) -> tuple[bool, str]:
- if not shutil.which("git"):
- return False, "git command not found"
- try:
- completed = subprocess.run(
- ("git", "clone", "--depth", "1", repo, str(destination)),
- check=False,
- capture_output=True,
- text=True,
- errors="replace",
- timeout=180,
- )
- except subprocess.TimeoutExpired:
- return False, "git clone timed out after 180 seconds"
- except OSError as exc:
- return False, str(exc)
- if completed.returncode == 0:
- return True, ""
- message = (completed.stderr or completed.stdout).strip()
- return False, message or f"git clone exited with {completed.returncode}"
- def cloned_repo_revision(repo_root: Path) -> str:
- try:
- completed = subprocess.run(
- ("git", "-C", str(repo_root), "rev-parse", "HEAD"),
- check=False,
- capture_output=True,
- text=True,
- errors="replace",
- timeout=30,
- )
- except (subprocess.TimeoutExpired, OSError) as exc:
- raise RuntimeError(
- f"cannot determine cloned repository revision: {exc}"
- ) from exc
- revision = completed.stdout.strip()
- if completed.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", revision):
- message = (completed.stderr or completed.stdout).strip()
- raise RuntimeError(
- message or "cloned repository did not return a full commit revision"
- )
- return revision
- def clone_repo_at_revision(
- repo: str, revision: str, destination: Path
- ) -> tuple[bool, str]:
- if not shutil.which("git"):
- return False, "git command not found"
- if not re.fullmatch(r"[0-9a-f]{40}", revision):
- return False, "revision must be a full 40-character lowercase commit SHA"
- commands = (
- ("git", "init", str(destination)),
- ("git", "-C", str(destination), "remote", "add", "origin", repo),
- ("git", "-C", str(destination), "fetch", "--depth", "1", "origin", revision),
- ("git", "-C", str(destination), "checkout", "--detach", "FETCH_HEAD"),
- )
- for command in commands:
- try:
- completed = subprocess.run(
- command,
- check=False,
- capture_output=True,
- text=True,
- errors="replace",
- timeout=180,
- )
- except subprocess.TimeoutExpired:
- return False, f"command timed out after 180 seconds: {shlex.join(command)}"
- except OSError as exc:
- return False, str(exc)
- if completed.returncode != 0:
- message = (completed.stderr or completed.stdout).strip()
- return False, message or f"command failed: {shlex.join(command)}"
- return True, ""
- def copy_external_skill(source: Path, target: Path) -> tuple[str, bool, str | None]:
- replaced_existing = target.exists()
- if target.exists():
- remove_existing_target(target)
- target.parent.mkdir(parents=True, exist_ok=True)
- try:
- shutil.copytree(
- source,
- target,
- ignore=external_copy_ignore(".git"),
- )
- except OSError as exc:
- return "failed", replaced_existing, str(exc)
- failures = compare_tree(source, target, EXTERNAL_TREE_COMPARE_EXCLUDED_DIRS)
- if failures:
- return (
- "failed",
- replaced_existing,
- "verification failed: " + ", ".join(failures[:20]),
- )
- return ("replaced" if replaced_existing else "installed"), replaced_existing, None
- def resolve_external_install_sources(
- selected: list[str], requested_source: str, workspace: Path
- ) -> dict[str, dict[str, object]]:
- manifest = (
- load_external_stable_manifest()
- if requested_source in {"auto", "stable"}
- else None
- )
- repo_groups: dict[str, list[str]] = {}
- for name in selected:
- repo = str(EXTERNAL_SKILL_SOURCES[name]["repo"])
- repo_groups.setdefault(repo, []).append(name)
- resolved: dict[str, dict[str, object]] = {}
- for index, (repo, names) in enumerate(repo_groups.items(), start=1):
- if requested_source == "upstream":
- try:
- repo_root = workspace / f"repo-{index}"
- ok, clone_error = clone_repo(repo, repo_root)
- if not ok:
- raise RuntimeError(clone_error)
- revision = cloned_repo_revision(repo_root)
- upstream_sources: dict[str, Path] = {}
- for name in names:
- source = source_dir_for_external_skill(repo_root, name)
- validate_external_skill_source(name, source)
- upstream_sources[name] = source
- for name, source in upstream_sources.items():
- resolved[name] = {
- "source": source,
- "repo": repo,
- "sourceUsed": "upstream",
- "sourceRevision": revision,
- "stableSet": None,
- "fallbackReason": None,
- }
- continue
- except (OSError, RuntimeError) as exc:
- raise RuntimeError(
- f"upstream External Skill group failed for {repo}: {exc}"
- ) from exc
- assert manifest is not None
- stable_group: dict[str, tuple[Path, str, str]] = {}
- for name in names:
- stable_group[name] = stable_external_skill_source(manifest, name)
- for name, (source, revision, stable_set) in stable_group.items():
- resolved[name] = {
- "source": source,
- "repo": repo,
- "sourceUsed": "stable",
- "sourceRevision": revision,
- "stableSet": stable_set,
- "fallbackReason": None,
- }
- return resolved
- def stage_external_skills(
- selected: list[str], resolved: dict[str, dict[str, object]], target_dir: Path
- ) -> Path:
- target_dir.mkdir(parents=True, exist_ok=True)
- staging = Path(tempfile.mkdtemp(prefix=".sbtd-external-staging-", dir=target_dir))
- try:
- for name in selected:
- source = Path(str(resolved[name]["source"]))
- destination = staging / name
- shutil.copytree(
- source,
- destination,
- ignore=external_copy_ignore(".git"),
- )
- validate_external_skill_source(name, destination)
- failures = compare_tree(source, destination, EXTERNAL_TREE_COMPARE_EXCLUDED_DIRS)
- if failures:
- raise RuntimeError(
- f"staging verification failed for {name}: "
- + ", ".join(failures[:20])
- )
- return staging
- except Exception:
- shutil.rmtree(staging, ignore_errors=True)
- raise
- def commit_external_skill_transaction(
- selected: list[str],
- resolved: dict[str, dict[str, object]],
- target_dir: Path,
- staging: Path,
- ) -> tuple[list[dict[str, object]], dict[str, object]]:
- legacy_names: list[str] = []
- for name in selected:
- for legacy_name in legacy_external_skill_names_for(name):
- if legacy_name not in legacy_names:
- legacy_names.append(legacy_name)
- identity_conflicts = [
- {
- "name": legacy_name,
- "replacement": canonical_external_skill_name(legacy_name),
- "target": str(target_dir / legacy_name),
- "status": "failed",
- "phase": "preflight-legacy-identity",
- "error": identity_error,
- }
- for legacy_name in legacy_names
- if filesystem_entry_exists(target_dir / legacy_name)
- if (
- identity_error := legacy_external_skill_identity_error(
- target_dir / legacy_name, legacy_name
- )
- )
- is not None
- ]
- if identity_conflicts:
- shutil.rmtree(staging, ignore_errors=True)
- return identity_conflicts, {
- "status": "aborted-before-commit",
- "rolledBack": False,
- "rollbackErrors": [],
- "rollbackPath": None,
- }
- rollback = Path(
- tempfile.mkdtemp(prefix=".sbtd-external-rollback-", dir=target_dir)
- )
- existed = {name: filesystem_entry_exists(target_dir / name) for name in selected}
- moved: list[tuple[Path, Path]] = []
- committed: list[Path] = []
- results: list[dict[str, object]] = []
- rollback_errors: list[str] = []
- retain_rollback = False
- try:
- for name in (*selected, *legacy_names):
- target = target_dir / name
- if not filesystem_entry_exists(target):
- continue
- backup = rollback / name
- shutil.move(str(target), str(backup))
- moved.append((target, backup))
- for name in selected:
- target = target_dir / name
- shutil.move(str(staging / name), str(target))
- committed.append(target)
- source_info = resolved[name]
- result = {
- "name": name,
- "repo": source_info["repo"],
- "target": str(target),
- "status": "replaced" if existed[name] else "installed",
- "phase": "commit",
- "replacedExisting": existed[name],
- "sourceUsed": source_info["sourceUsed"],
- "sourceRevision": source_info["sourceRevision"],
- "stableSet": source_info.get("stableSet"),
- "fallbackReason": source_info.get("fallbackReason"),
- }
- results.append(result)
- for legacy_name in legacy_names:
- if (rollback / legacy_name).exists():
- results.append(
- {
- "name": legacy_name,
- "replacement": canonical_external_skill_name(legacy_name),
- "target": str(target_dir / legacy_name),
- "status": "removed",
- "phase": "remove-legacy-after-commit",
- }
- )
- transaction = {
- "status": "committed",
- "rolledBack": False,
- "rollbackErrors": [],
- "rollbackPath": None,
- }
- return results, transaction
- except Exception as exc: # noqa: BLE001 - rollback must cover every local commit failure.
- for target in reversed(committed):
- try:
- remove_existing_target(target)
- except Exception as rollback_exc: # noqa: BLE001 - aggregate rollback failures.
- rollback_errors.append(f"remove {target}: {rollback_exc}")
- for target, backup in reversed(moved):
- try:
- if target.exists():
- remove_existing_target(target)
- shutil.move(str(backup), str(target))
- except Exception as rollback_exc: # noqa: BLE001 - aggregate rollback failures.
- rollback_errors.append(f"restore {target}: {rollback_exc}")
- results = [
- {
- "name": name,
- "repo": resolved[name]["repo"],
- "target": str(target_dir / name),
- "status": "failed",
- "phase": "commit",
- "sourceUsed": resolved[name]["sourceUsed"],
- "sourceRevision": resolved[name]["sourceRevision"],
- "stableSet": resolved[name].get("stableSet"),
- "fallbackReason": resolved[name].get("fallbackReason"),
- "error": str(exc),
- }
- for name in selected
- ]
- retain_rollback = bool(rollback_errors)
- return results, {
- "status": "rollback-failed" if rollback_errors else "rolled-back",
- "rolledBack": True,
- "rollbackErrors": rollback_errors,
- "rollbackPath": str(rollback) if retain_rollback else None,
- }
- finally:
- shutil.rmtree(staging, ignore_errors=True)
- if not retain_rollback:
- shutil.rmtree(rollback, ignore_errors=True)
- def remove_legacy_external_targets(
- target_dir: Path,
- selected: list[str],
- extra_legacy_names: list[str] | None = None,
- ) -> list[dict[str, object]]:
- results: list[dict[str, object]] = []
- legacy_names: list[str] = []
- for name in selected:
- for legacy_name in legacy_external_skill_names_for(name):
- if legacy_name not in legacy_names:
- legacy_names.append(legacy_name)
- for legacy_name in extra_legacy_names or []:
- if legacy_name not in legacy_names:
- legacy_names.append(legacy_name)
- for legacy_name in legacy_names:
- target = target_dir / legacy_name
- if not filesystem_entry_exists(target):
- continue
- identity_error = legacy_external_skill_identity_error(target, legacy_name)
- if identity_error is not None:
- results.append(
- {
- "name": legacy_name,
- "replacement": canonical_external_skill_name(legacy_name),
- "target": str(target),
- "status": "failed",
- "phase": "preflight-legacy-identity",
- "error": identity_error,
- }
- )
- continue
- try:
- remove_existing_target(target)
- results.append(
- {
- "name": legacy_name,
- "replacement": canonical_external_skill_name(legacy_name),
- "target": str(target),
- "status": "removed",
- "phase": "remove-legacy",
- }
- )
- except Exception as exc: # noqa: BLE001 - keep cleanup report per target.
- results.append(
- {
- "name": legacy_name,
- "replacement": canonical_external_skill_name(legacy_name),
- "target": str(target),
- "status": "failed",
- "phase": "remove-legacy",
- "error": str(exc),
- }
- )
- return results
- def scoped_skills_root(args: argparse.Namespace) -> Path:
- return resolve_global_skills_dir(args.global_skills_dir)[0]
- def external_migration_timestamp() -> str:
- return dt.datetime.now().strftime("%Y%m%d-%H%M%S")
- def external_migration_backup_root(skills_root: Path) -> Path:
- return skills_root.with_name(f"{skills_root.name}-backups")
- def detected_mattpocock_skill_names(skills_root: Path) -> list[str]:
- candidates = (
- *MATTPOCOCK_CANONICAL_SKILLS,
- *MATTPOCOCK_LEGACY_RENAMES.keys(),
- *MATTPOCOCK_REMOVED_SKILLS.keys(),
- )
- detected: list[str] = []
- for name in candidates:
- target = skills_root / name
- if filesystem_entry_exists(target):
- detected.append(name)
- return detected
- def canonical_migration_targets(detected: list[str]) -> list[str]:
- selected: list[str] = []
- for name in detected:
- if name in MATTPOCOCK_REMOVED_SKILLS:
- continue
- selected.append(canonical_external_skill_name(name))
- return external_skill_dependency_closure(selected)
- def build_external_migration_plan(args: argparse.Namespace) -> dict[str, object]:
- skills_root = scoped_skills_root(args)
- detected = detected_mattpocock_skill_names(skills_root)
- legacy = [
- name
- for name in detected
- if name in MATTPOCOCK_LEGACY_RENAMES or name in MATTPOCOCK_REMOVED_SKILLS
- ]
- selected = canonical_migration_targets(legacy)
- canonical = [name for name in detected if name in MATTPOCOCK_CANONICAL_SKILLS]
- return {
- "mode": "mattpocock-external-migration",
- "status": "planned" if legacy else "skipped",
- "reason": None
- if legacy
- else "no legacy mattpocock skills detected in global skills root",
- "targetDir": str(skills_root),
- "detectedLegacy": legacy,
- "detectedCanonical": canonical,
- "requiredCanonical": selected,
- "removeLegacy": legacy,
- "backupRoot": str(external_migration_backup_root(skills_root)),
- "autoMode": "legacy-only",
- }
- def backup_skill_target(target: Path, backup_dir: Path) -> str | None:
- if not target.exists():
- return None
- destination = backup_dir / target.name
- if destination.exists():
- remove_existing_target(destination)
- backup_dir.mkdir(parents=True, exist_ok=True)
- if target.is_dir() and not target.is_symlink():
- shutil.copytree(target, destination, ignore=external_copy_ignore())
- else:
- shutil.copy2(target, destination)
- return str(destination)
- def run_external_migration(plan: dict[str, object]) -> list[dict[str, object]]:
- if plan["status"] != "planned":
- return [
- {
- "status": "skipped",
- "reason": plan.get("reason"),
- }
- ]
- target_dir = Path(str(plan["targetDir"]))
- remove_legacy = plan.get("removeLegacy")
- if not isinstance(remove_legacy, list):
- raise RuntimeError("external migration removeLegacy must be a list")
- legacy = [
- str(name)
- for name in remove_legacy
- if filesystem_entry_exists(target_dir / str(name))
- ]
- if not legacy:
- return [
- {
- "status": "skipped",
- "reason": "legacy targets were already handled by canonical installation",
- }
- ]
- backup_dir = (
- external_migration_backup_root(target_dir)
- / f"mattpocock-1.0-migration-{external_migration_timestamp()}"
- )
- results: list[dict[str, object]] = []
- for name in legacy:
- identity_error = legacy_external_skill_identity_error(target_dir / name, name)
- if identity_error is not None:
- results.append(
- {
- "name": name,
- "replacement": canonical_external_skill_name(name),
- "target": str(target_dir / name),
- "status": "failed",
- "phase": "preflight-legacy-identity",
- "error": identity_error,
- }
- )
- continue
- if name in MATTPOCOCK_LEGACY_RENAMES:
- replacement = canonical_external_skill_name(name)
- if not external_skill_target_is_valid(target_dir, replacement):
- results.append(
- {
- "name": name,
- "status": "failed",
- "phase": "preflight",
- "error": f"canonical replacement is missing: {replacement}",
- }
- )
- if results:
- return results
- for name in legacy:
- try:
- backup = backup_skill_target(target_dir / name, backup_dir)
- results.append({"name": name, "status": "backed-up", "backup": backup})
- except Exception as exc: # noqa: BLE001 - keep migration report per target.
- results.append(
- {"name": name, "status": "failed", "phase": "backup", "error": str(exc)}
- )
- if any(item["status"] == "failed" for item in results):
- return results
- legacy_removals = remove_legacy_external_targets(target_dir, [], legacy)
- results.extend(legacy_removals)
- return results
- def execute_external_skill_install(
- args: argparse.Namespace, selected: list[str], target_dir: Path
- ) -> tuple[list[dict[str, object]], dict[str, object]]:
- try:
- with tempfile.TemporaryDirectory(
- prefix="sbtd-onboard-external-sources-"
- ) as tmp:
- resolved = resolve_external_install_sources(
- selected, args.source, Path(tmp)
- )
- staging = stage_external_skills(selected, resolved, target_dir)
- return commit_external_skill_transaction(
- selected, resolved, target_dir, staging
- )
- except Exception as exc: # noqa: BLE001 - no target is changed before the transaction begins.
- return (
- [
- {
- "name": name,
- "repo": EXTERNAL_SKILL_SOURCES[name]["repo"],
- "target": str(target_dir / name),
- "status": "failed",
- "phase": "prepare",
- "error": str(exc),
- }
- for name in selected
- ],
- {
- "status": "aborted-before-commit",
- "rolledBack": False,
- "rollbackErrors": [],
- "rollbackPath": None,
- },
- )
- def external_migration_identity_failures(
- plan: dict[str, object]
- ) -> list[dict[str, object]]:
- target_dir = Path(str(plan["targetDir"]))
- remove_legacy = plan.get("removeLegacy")
- if not isinstance(remove_legacy, list):
- raise TypeError("external migration removeLegacy must be a list")
- return [
- {
- "name": name,
- "replacement": canonical_external_skill_name(name),
- "target": str(target_dir / name),
- "status": "failed",
- "phase": "preflight-legacy-identity",
- "error": identity_error,
- }
- for name in (str(name) for name in remove_legacy)
- if filesystem_entry_exists(target_dir / name)
- if (
- identity_error := legacy_external_skill_identity_error(
- target_dir / name, name
- )
- )
- is not None
- ]
- def migrate_external_skills(args: argparse.Namespace) -> int:
- plan = build_external_migration_plan(args)
- payload: dict[str, object] = {
- "mode": "migrate-external-skills",
- "scope": args.scope,
- "requestedSource": args.source,
- "targetDir": plan["targetDir"],
- "plan": plan,
- "installationResults": [],
- "transaction": {
- "status": "not-required",
- "rolledBack": False,
- "rollbackErrors": [],
- "rollbackPath": None,
- },
- "results": [],
- }
- if plan["status"] == "skipped":
- payload["status"] = "skipped"
- payload["results"] = [
- {"status": "skipped", "reason": plan.get("reason")}
- ]
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print_external_migration_report(cast(list[dict[str, object]], payload["results"]))
- return 0
- identity_failures = external_migration_identity_failures(plan)
- if identity_failures:
- payload["status"] = "failed"
- payload["results"] = identity_failures
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print_external_migration_report(identity_failures)
- return 1
- if not args.yes:
- payload["status"] = "needs-confirmation"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print_external_migration_report(
- [{"status": "needs-confirmation", "reason": "rerun with --yes"}]
- )
- return 2
- required_canonical = plan["requiredCanonical"]
- if not isinstance(required_canonical, list):
- raise TypeError("external migration requiredCanonical must be a list")
- selected = [str(name) for name in required_canonical]
- installation_results: list[dict[str, object]] = []
- if selected:
- target_dir = Path(str(plan["targetDir"]))
- installation_results, transaction = execute_external_skill_install(
- args, selected, target_dir
- )
- payload["installationResults"] = installation_results
- payload["transaction"] = transaction
- if transaction["status"] != "committed":
- payload["status"] = "failed"
- payload["results"] = installation_results
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print_external_migration_report(installation_results)
- return 1
- migration_results = run_external_migration(build_external_migration_plan(args))
- results = [*installation_results, *migration_results]
- payload["results"] = results
- failed = [item for item in results if item["status"] == "failed"]
- payload["status"] = "failed" if failed else "migrated"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print_external_migration_report(results)
- return 1 if failed else 0
- def perform_external_skill_install(
- args: argparse.Namespace,
- selected: list[str],
- target_dir: Path,
- plan: dict[str, object],
- ) -> dict[str, object]:
- """Install one transaction and return its report without printing."""
- results, transaction = execute_external_skill_install(args, selected, target_dir)
- post_check = build_check_results(args)
- return {
- "mode": "install-external-skills",
- "scope": args.scope,
- "requestedSource": args.source,
- "targetDir": str(target_dir),
- "forceOverwriteExisting": True,
- "backupExistingTargets": "temporary-rollback",
- "replaceFlagProvided": bool(args.replace),
- "plan": plan,
- "results": results,
- "transaction": transaction,
- "postCheck": post_check,
- "installationReport": post_check["installationReport"],
- }
- def print_external_skill_install_result(
- payload: dict[str, object], as_json: bool
- ) -> None:
- if as_json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- return
- results = cast(list[dict[str, object]], payload["results"])
- transaction = cast(dict[str, object], payload["transaction"])
- print("\nExternal skill install results")
- for item in results:
- print(f"- {item['name']}: {item['status']}")
- if item.get("target"):
- print(f" target: {item['target']}")
- if item.get("sourceUsed"):
- print(f" source: {item['sourceUsed']} ({item.get('sourceRevision')})")
- if item.get("fallbackReason"):
- print(f" fallback: {item['fallbackReason']}")
- if item.get("error"):
- print(f" note: {item['error']}")
- print(f"Transaction: {transaction['status']}")
- if transaction.get("rollbackPath"):
- print(f"Rollback backup retained at: {transaction['rollbackPath']}")
- rollback_errors = transaction.get("rollbackErrors")
- if isinstance(rollback_errors, list):
- for rollback_error in rollback_errors:
- print(f" rollback error: {rollback_error}")
- print_installation_report(
- cast(dict[str, object], payload["installationReport"]),
- "Final installation report",
- )
- def install_external_skills(args: argparse.Namespace) -> int:
- selected = parse_skill_names(args)
- target_dir = resolve_install_skills_dir(args)
- plan = external_install_plan(args, selected, target_dir)
- if not args.yes:
- print_external_install_plan(plan, args.json)
- print(
- "Refusing to install external skills without --yes. Confirm with the user, then rerun with --yes.",
- file=sys.stderr,
- )
- return 2
- if not args.json:
- print_external_install_plan(plan, False)
- payload = perform_external_skill_install(args, selected, target_dir, plan)
- print_external_skill_install_result(payload, args.json)
- transaction = cast(dict[str, object], payload["transaction"])
- return 1 if transaction["status"] != "committed" else 0
- def stable_notice_attribution(repository_url: str) -> str:
- path_parts = [
- part for part in repository_url.removesuffix(".git").split("/") if part
- ]
- if len(path_parts) < 2:
- raise RuntimeError(
- f"cannot derive repository attribution from {repository_url}"
- )
- return "/".join(path_parts[-2:])
- def upsert_stable_third_party_notice(
- notice_path: Path,
- repository_url: str,
- license_name: str,
- license_file_mappings: list[dict[str, str]],
- ) -> str:
- attribution = stable_notice_attribution(repository_url)
- license_refs = ", ".join(
- f"`{mapping['stablePath']}`" for mapping in license_file_mappings
- )
- row = f"| `{attribution}` | {license_name} | {license_refs} |"
- text = (
- notice_path.read_text(encoding="utf-8") if notice_path.is_file() else ""
- )
- marker = f"| `{attribution}` |"
- if marker in text:
- text = "\n".join(
- line for line in text.splitlines() if not line.startswith(marker)
- )
- if text and not text.endswith("\n"):
- text += "\n"
- notice_path.write_text(text + row + "\n", encoding="utf-8")
- return row
- def parse_license_file_mappings(values: object) -> list[dict[str, str]]:
- if values is None:
- return []
- mappings: list[dict[str, str]] = []
- for raw in cast(list[str], values):
- source, separator, stable_path = str(raw).partition("=")
- if not separator or not source.strip() or not stable_path.strip():
- raise SystemExit(
- "--license-file must use SOURCE=STABLE_PATH, for example "
- "LICENSE=licenses/ponytail-LICENSE"
- )
- mappings.append({"source": source.strip(), "stablePath": stable_path.strip()})
- return mappings
- def promote_external_skills_stable(args: argparse.Namespace) -> int:
- if not re.fullmatch(r"[0-9a-f]{40}", str(args.revision)):
- raise SystemExit(
- "--revision must be a full 40-character lowercase commit SHA"
- )
- manifest = load_external_stable_manifest(relaxed=True)
- repositories = cast(dict[str, object], manifest["repositories"])
- skills = cast(dict[str, object], manifest["skills"])
- existing_repository = repositories.get(args.repository)
- registration = not isinstance(existing_repository, dict)
- license_name = ""
- license_file_mappings: list[dict[str, str]]
- if registration:
- if re.fullmatch(r"[a-z0-9][a-z0-9-]*", str(args.repository)) is None:
- raise SystemExit(f"Invalid stable repository id: {args.repository}")
- repository_url = str(getattr(args, "repo", None) or "")
- if not valid_https_repository_url(repository_url):
- raise SystemExit(
- "First-time stable repository registration requires --repo with a "
- "valid HTTPS repository URL."
- )
- license_name = str(getattr(args, "license", None) or "").strip()
- if not license_name:
- raise SystemExit(
- "First-time stable repository registration requires --license with "
- "an SPDX license id."
- )
- license_file_mappings = parse_license_file_mappings(
- getattr(args, "license_files", None)
- )
- if not license_file_mappings:
- raise SystemExit(
- "First-time stable repository registration requires at least one "
- "--license-file SOURCE=STABLE_PATH mapping."
- )
- selected = [
- name
- for name, source_spec in EXTERNAL_SKILL_SOURCES.items()
- if str(source_spec["repo"]) == repository_url
- ]
- if not selected:
- raise SystemExit(
- f"No catalog external Skills match --repo {repository_url}; register "
- "the catalog entries before promotion."
- )
- else:
- repository = cast(dict[str, object], existing_repository)
- repository_url = str(repository.get("url") or "")
- if getattr(args, "repo", None) and str(args.repo) != repository_url:
- raise SystemExit(
- f"--repo {args.repo} does not match the stable repository URL "
- f"{repository_url}; refusing to rewrite repository metadata."
- )
- if getattr(args, "license", None) or getattr(args, "license_files", None):
- raise SystemExit(
- "--license/--license-file are only valid for first-time repository "
- "registration; refusing to rewrite existing repository metadata."
- )
- existing_license_files = repository.get("licenseFiles")
- if not isinstance(existing_license_files, list):
- raise SystemExit(
- f"stable repository {args.repository} has no licenseFiles list"
- )
- license_file_mappings = cast(
- list[dict[str, str]], existing_license_files
- )
- selected = [
- name
- for name, entry in skills.items()
- if isinstance(entry, dict) and entry.get("repository") == args.repository
- ]
- plan = {
- "mode": "promote-external-skills-stable",
- "repository": args.repository,
- "repo": repository_url,
- "registration": registration,
- "revision": args.revision,
- "stableSet": args.stable_set,
- "skills": selected,
- "target": str(EXTERNAL_STABLE_ROOT),
- }
- if not args.yes:
- if args.json:
- print(json.dumps(plan, indent=2, ensure_ascii=False))
- else:
- print("Stable External Skills promotion plan")
- for key, value in plan.items():
- print(f"- {key}: {value}")
- print("Refusing to promote without --yes.", file=sys.stderr)
- return 2
- payload: dict[str, object] = {**plan, "status": "failed"}
- with tempfile.TemporaryDirectory(prefix="sbtd-external-promotion-source-") as tmp:
- repo_root = Path(tmp) / "repository"
- ok, error = clone_repo_at_revision(repository_url, args.revision, repo_root)
- if not ok:
- payload["error"] = error
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else error
- )
- return 1
- candidate_container = Path(
- tempfile.mkdtemp(
- prefix=".sbtd-stable-promotion-", dir=EXTERNAL_STABLE_ROOT.parent
- )
- )
- candidate_root = candidate_container / "stable"
- previous_root = candidate_container / "previous"
- retain_candidate_container = False
- try:
- shutil.copytree(
- EXTERNAL_STABLE_ROOT,
- candidate_root,
- ignore=external_copy_ignore(".git"),
- )
- candidate_manifest = json.loads(json.dumps(manifest))
- candidate_repositories = cast(
- dict[str, object], candidate_manifest["repositories"]
- )
- candidate_skills = cast(dict[str, object], candidate_manifest["skills"])
- if registration:
- candidate_repositories[args.repository] = {
- "url": repository_url,
- "revision": args.revision,
- "license": license_name,
- "licenseFiles": license_file_mappings,
- }
- for name in selected:
- candidate_skills[name] = {
- "repository": args.repository,
- "sourceSubpath": str(
- EXTERNAL_SKILL_SOURCES[name]["subpath"]
- ),
- "stablePath": f"skills/{name}",
- }
- for name in selected:
- entry = candidate_skills[name]
- if not isinstance(entry, dict):
- raise RuntimeError(f"stable Skill metadata is invalid: {name}")
- entry = cast(dict[str, object], entry)
- source = resolve_contained_relative_path(
- repo_root,
- entry.get("sourceSubpath"),
- f"sourceSubpath for {name}",
- )
- validate_external_skill_source(name, source)
- destination = resolve_contained_relative_path(
- candidate_root,
- entry.get("stablePath"),
- f"stablePath for {name}",
- )
- if destination.exists():
- remove_existing_target(destination)
- shutil.copytree(
- source,
- destination,
- ignore=external_copy_ignore(".git"),
- )
- validate_external_skill_source(name, destination)
- entry["treeSha256"] = external_tree_sha256(destination)
- payload["prunedStableSkills"] = prune_unmanaged_stable_skill_directories(
- candidate_manifest, candidate_root
- )
- for license_entry in license_file_mappings:
- source = resolve_contained_relative_path(
- repo_root,
- license_entry.get("source"),
- f"license source for {args.repository}",
- )
- destination = resolve_contained_relative_path(
- candidate_root,
- license_entry.get("stablePath"),
- f"license stablePath for {args.repository}",
- )
- if not source.is_file():
- raise RuntimeError(
- f"required upstream license file is missing: {source}"
- )
- destination.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, destination)
- if registration:
- upsert_stable_third_party_notice(
- candidate_root / "THIRD_PARTY_NOTICES.md",
- repository_url,
- license_name,
- license_file_mappings,
- )
- notice_text = (candidate_root / "THIRD_PARTY_NOTICES.md").read_text(
- encoding="utf-8"
- )
- attribution = stable_notice_attribution(repository_url)
- if f"| `{attribution}` |" not in notice_text:
- raise RuntimeError(
- "candidate THIRD_PARTY_NOTICES.md has no attribution row for "
- f"{attribution}"
- )
- candidate_repository = candidate_repositories[args.repository]
- if not isinstance(candidate_repository, dict):
- raise RuntimeError(
- f"stable repository metadata is invalid: {args.repository}"
- )
- candidate_repository = cast(dict[str, object], candidate_repository)
- candidate_repository["revision"] = args.revision
- candidate_manifest["stableSet"] = args.stable_set
- candidate_manifest["promotedAt"] = dt.date.today().isoformat()
- (candidate_root / "MANIFEST.json").write_text(
- json.dumps(candidate_manifest, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
- candidate_skill_names = set(
- cast(dict[str, object], candidate_manifest["skills"])
- )
- if candidate_skill_names != set(EXTERNAL_SKILL_SOURCES):
- missing_names = sorted(
- set(EXTERNAL_SKILL_SOURCES) - candidate_skill_names
- )
- extra_names = sorted(
- candidate_skill_names - set(EXTERNAL_SKILL_SOURCES)
- )
- raise RuntimeError(
- "candidate stable manifest does not match the canonical "
- f"catalog set; missing={missing_names}, extra={extra_names}"
- )
- validate_external_stable_metadata(candidate_manifest, candidate_root)
- for name in EXTERNAL_SKILL_SOURCES:
- stable_external_skill_source(candidate_manifest, name, candidate_root)
- shutil.move(str(EXTERNAL_STABLE_ROOT), str(previous_root))
- try:
- shutil.move(str(candidate_root), str(EXTERNAL_STABLE_ROOT))
- except Exception as commit_exc:
- try:
- shutil.move(str(previous_root), str(EXTERNAL_STABLE_ROOT))
- except Exception as restore_exc:
- retain_candidate_container = True
- raise RuntimeError(
- "stable promotion commit and rollback failed; previous stable set retained at "
- f"{previous_root}: commit={commit_exc}; rollback={restore_exc}"
- ) from restore_exc
- raise
- payload["status"] = "promoted"
- payload["promotedSkills"] = selected
- except Exception as exc: # noqa: BLE001 - promotion keeps the prior stable set on every failure.
- payload["error"] = str(exc)
- finally:
- if not retain_candidate_container:
- shutil.rmtree(candidate_container, ignore_errors=True)
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"Stable External Skills promotion: {payload['status']}")
- if payload.get("error"):
- print(f"- error: {payload['error']}")
- elif payload.get("promotedSkills"):
- print("- promoted: " + ", ".join(selected))
- return 0 if payload["status"] == "promoted" else 1
- def missing_required_external_skills(args: argparse.Namespace) -> list[str]:
- global_skills_dir = resolve_global_skills_dir(
- getattr(args, "global_skills_dir", None)
- )[0]
- return [
- name
- for name in EXTERNAL_SKILL_SOURCES
- if not external_skill_target_is_valid(global_skills_dir, name)
- ]
- def install_required_external_skills(
- args: argparse.Namespace, *, overwrite: bool = False
- ) -> dict[str, object] | None:
- if overwrite:
- selected = list(EXTERNAL_SKILL_SOURCES)
- if not args.json:
- print(
- "Reset will overwrite all required global external Skills: "
- + ", ".join(selected)
- )
- else:
- selected = missing_required_external_skills(args)
- if not selected:
- return None
- if not args.json:
- print(
- "Required global external Skills are missing and will be installed: "
- + ", ".join(selected)
- )
- install_args = argparse.Namespace(
- all=overwrite,
- skills=None if overwrite else ",".join(selected),
- scope="global",
- source="auto",
- global_skills_dir=getattr(args, "global_skills_dir", None),
- replace=False,
- yes=True,
- json=args.json,
- expand_dependencies=overwrite,
- )
- selected = parse_skill_names(install_args)
- target_dir = resolve_install_skills_dir(install_args)
- plan = external_install_plan(install_args, selected, target_dir)
- if not args.json:
- print_external_install_plan(plan, False)
- payload = perform_external_skill_install(install_args, selected, target_dir, plan)
- if not args.json:
- print_external_skill_install_result(payload, False)
- return payload
- def default_shell_profile() -> Path:
- shell_name = Path(os.environ.get("SHELL", "")).name
- if shell_name == "zsh":
- return Path.home() / ".zshrc"
- if shell_name == "bash" and platform.system() == "Darwin":
- return Path.home() / ".bash_profile"
- if shell_name == "bash":
- return Path.home() / ".bashrc"
- return Path.home() / ".profile"
- def ensure_profile_line(profile: Path, line: str, marker: str) -> bool:
- profile.parent.mkdir(parents=True, exist_ok=True)
- existing = profile.read_text(encoding="utf-8") if profile.exists() else ""
- if line in existing:
- return False
- prefix = "" if not existing or existing.endswith("\n") else "\n"
- with profile.open("a", encoding="utf-8") as handle:
- handle.write(f"{prefix}# {marker}\n{line}\n")
- return True
- def ensure_npm(args: argparse.Namespace) -> int:
- before = check_npm_runtime()
- payload: dict[str, object] = {
- "mode": "ensure-npm",
- "platform": before["platform"],
- "before": before,
- "actions": [],
- }
- if before["npm"]["installed"]:
- payload["status"] = "already-installed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("npm is already available.")
- print(f"npm: {before['npm']['path']} ({before['npm']['version']})")
- print(f"node: {before['node']['path']} ({before['node']['version']})")
- return 0
- system = platform.system() or sys.platform
- if system == "Windows":
- payload["status"] = "unsupported-platform"
- payload["advice"] = (
- "Native Windows is not supported by the nvm-sh installer. Use WSL with nvm-sh, "
- "or install a Windows Node version manager such as nvm-windows/nvs, then rerun check."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(
- "npm is missing, but native Windows cannot be fully configured by this nvm-sh installer."
- )
- print(payload["advice"])
- return 1
- install_actions = payload["actions"]
- install_actions.append(f"install or update nvm with {NVM_INSTALL_URL}")
- install_actions.append("install latest Node.js LTS with nvm")
- install_actions.append("set nvm default alias to lts/*")
- install_actions.append("switch current shell to Node.js LTS")
- if not args.yes:
- payload["status"] = "needs-confirmation"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("npm is missing.")
- print(f"Platform: {system}")
- for action in install_actions:
- print(f"- {action}")
- print("Rerun with --yes after user confirmation.")
- return 2
- installer_tool = (
- "curl" if shutil.which("curl") else "wget" if shutil.which("wget") else None
- )
- if not installer_tool:
- payload["status"] = "failed"
- payload["error"] = (
- "Neither curl nor wget is available to download the nvm installer."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- if installer_tool == "curl":
- install_script = f"curl -o- {NVM_INSTALL_URL} | bash"
- else:
- install_script = f"wget -qO- {NVM_INSTALL_URL} | bash"
- install_result = shell_result(install_script, timeout=300)
- if not install_result or install_result.returncode != 0:
- payload["status"] = "failed"
- payload["error"] = (
- (install_result.stderr or install_result.stdout).strip()
- if install_result
- else "Unable to execute shell installer."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- node_script = (
- f"{nvm_load_script()}; "
- "nvm install --lts; "
- "nvm alias default 'lts/*'; "
- "nvm use --lts; "
- "node --version; "
- "npm --version"
- )
- node_result = shell_result(node_script, timeout=600)
- if not node_result or node_result.returncode != 0:
- payload["status"] = "failed"
- payload["error"] = (
- (node_result.stderr or node_result.stdout).strip()
- if node_result
- else "Unable to run nvm after installation."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- after = check_npm_runtime()
- payload["after"] = after
- payload["status"] = "installed" if after["npm"]["installed"] else "failed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"ensure-npm status: {payload['status']}")
- if after["npm"]["installed"]:
- print(f"npm: {after['npm']['path']} ({after['npm']['version']})")
- print(f"node: {after['node']['path']} ({after['node']['version']})")
- else:
- print(
- "npm still is not available in PATH. Restart the shell or source the profile file, then rerun check."
- )
- return 0 if after["npm"]["installed"] else 1
- def install_agent_cli(args: argparse.Namespace) -> int:
- before = check_agent_cli(args.platform)
- payload: dict[str, object] = {
- "mode": "install-agent-cli",
- "platform": before["platform"],
- "label": before["label"],
- "command": before["command"],
- "npmPackage": before["npmPackage"],
- "installCommand": before["installCommand"],
- "verifyCommand": before["verifyCommand"],
- "runtime": before["runtime"],
- "before": before,
- }
- if before["installed"]:
- payload["status"] = "already-installed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"{before['label']} CLI is already installed and verified.")
- print(f"{before['command']}: {before['path']} ({before['version']})")
- return 0
- runtime = before["runtime"]
- if not runtime["npm"]["installed"]:
- payload["status"] = "npm-required"
- payload["advice"] = (
- f"{shell_prefix()}Install npm first with `{onboard_command('ensure-npm', '--yes')}` after user confirmation, "
- "then rerun install-agent-cli."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"{before['label']} CLI is missing and npm is not usable.")
- print(payload["advice"])
- return 2
- if not args.yes:
- payload["status"] = "needs-confirmation"
- payload["actions"] = [
- f"run `{before['installCommand']}`",
- f"verify `{before['verifyCommand']}`",
- ]
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"{before['label']} CLI is missing or failed verification.")
- for action in payload["actions"]:
- print(f"- {action}")
- print("Rerun with --yes after user confirmation.")
- return 2
- npm_package = f"{before['npmPackage']}@latest"
- install_result = run_command(("npm", "install", "-g", npm_package), timeout=900)
- payload["installOutput"] = command_excerpt(install_result)
- if not install_result or install_result.returncode != 0:
- payload["status"] = "failed"
- payload["error"] = (
- command_excerpt(install_result) or "npm global install failed."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- after = check_agent_cli(str(before["platform"]))
- payload["after"] = after
- payload["status"] = "installed" if after["installed"] else "verification-failed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"install-agent-cli status: {payload['status']}")
- if after["installed"]:
- print(f"{after['command']}: {after['path']} ({after['version']})")
- else:
- print(
- f"npm completed, but `{after['verifyCommand']}` did not pass. "
- "Check the npm global bin PATH and the package runtime prerequisites."
- )
- if after.get("verifyOutput"):
- print(f"First verification output: {after['verifyOutput']}")
- return 0 if after["installed"] else 1
- def install_rtk(args: argparse.Namespace) -> int:
- before = check_cli_tool(CLI_TOOLS[0])
- local_bin = Path.home() / ".local" / "bin"
- profile = expand_path(args.profile) or default_shell_profile()
- payload: dict[str, object] = {
- "mode": "install-rtk",
- "platform": platform.system() or sys.platform,
- "before": before,
- "installUrl": RTK_INSTALL_URL,
- "targetDir": str(local_bin),
- "profile": str(profile),
- }
- if before["installed"]:
- payload["status"] = "already-installed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("rtk is already installed and verified with `rtk gain`.")
- print(f"rtk: {before['path']} ({before['version']})")
- return 0
- if before.get("wrongPackageSuspected") and not args.replace_wrong:
- payload["status"] = "wrong-package-suspected"
- payload["advice"] = (
- "An `rtk` command exists but `rtk gain` failed. Confirm whether to remove or replace it before installing rtk-ai/rtk."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(payload["advice"])
- print(
- "Rerun with --replace-wrong after user confirmation if replacement is intended."
- )
- return 2
- if before.get("verificationFailed") and not args.reinstall:
- payload["status"] = "verification-failed"
- payload["advice"] = (
- "`rtk --version` looks like rtk-ai/rtk, but `rtk gain` failed. "
- "Check RTK data directory permissions first, or rerun with --reinstall after user confirmation."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(payload["advice"])
- return 2
- system = platform.system() or sys.platform
- if system == "Windows":
- payload["status"] = "manual-required"
- payload["advice"] = (
- "Download the Windows release zip from rtk-ai/rtk, extract rtk.exe into a directory on PATH "
- "such as %USERPROFILE%\\.local\\bin, then verify with `rtk --version` and `rtk gain`."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(payload["advice"])
- return 1
- if not args.yes:
- payload["status"] = "needs-confirmation"
- payload["actions"] = [
- f"run {RTK_INSTALL_URL}",
- f"ensure {local_bin} is in PATH via {profile}",
- "verify `rtk --version` and `rtk gain`",
- ]
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("rtk is missing or not verified.")
- for action in payload["actions"]:
- print(f"- {action}")
- print("Rerun with --yes after user confirmation.")
- return 2
- if (
- before.get("wrongPackageSuspected")
- and args.replace_wrong
- and shutil.which("cargo")
- ):
- run_command(("cargo", "uninstall", "rtk"), timeout=120)
- if not shutil.which("curl"):
- payload["status"] = "failed"
- payload["error"] = "curl is required for the rtk-ai/rtk quick install script."
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- install_result = shell_result(f"curl -fsSL {RTK_INSTALL_URL} | sh", timeout=300)
- if not install_result or install_result.returncode != 0:
- payload["status"] = "failed"
- payload["error"] = (
- (install_result.stderr or install_result.stdout).strip()
- if install_result
- else "Unable to run rtk installer."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- os.environ["PATH"] = f"{local_bin}{os.pathsep}{os.environ.get('PATH', '')}"
- profile_updated = ensure_profile_line(
- profile,
- 'export PATH="$HOME/.local/bin:$PATH"',
- "Added by sbtd-workflow-onboard for rtk",
- )
- after = check_cli_tool(CLI_TOOLS[0])
- payload["after"] = after
- payload["profileUpdated"] = profile_updated
- payload["status"] = "installed" if after["installed"] else "failed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"install-rtk status: {payload['status']}")
- if profile_updated:
- print(f"Updated PATH in {profile}")
- if after["installed"]:
- print(f"rtk: {after['path']} ({after['version']})")
- print("Verification passed: rtk gain")
- else:
- print(
- "rtk was installed but did not pass `rtk gain`. Check PATH, release download, and name-collision risk."
- )
- return 0 if after["installed"] else 1
- def is_caveman_family_name(name: str) -> bool:
- """Narrow matcher: entries Onboard may back up or replace."""
- return (
- name == "caveman"
- or name.startswith("caveman-")
- or name == "cavecrew"
- or name.startswith("cavecrew-")
- )
- def is_caveman_family_prefix_name(name: str) -> bool:
- """Broad, detection-only matcher for the fail-closed symlink guard.
- Anything named `caveman*` / `cavecrew*` (for example `caveman.local`)
- blocks maintenance when symlinked, but is never selected for mutation.
- """
- return name.startswith("caveman") or name.startswith("cavecrew")
- def caveman_family_dirs(skills_dir: Path) -> list[Path]:
- if not skills_dir.is_dir():
- return []
- return sorted(
- (
- entry
- for entry in skills_dir.iterdir()
- if (entry.is_dir() or entry.is_symlink() or entry.is_file())
- and is_caveman_family_name(entry.name)
- ),
- key=lambda entry: entry.name,
- )
- def caveman_family_fingerprints(skills_dir: Path) -> dict[str, str | None]:
- fingerprints: dict[str, str | None] = {}
- for entry in caveman_family_dirs(skills_dir):
- try:
- validate_external_skill_source(entry.name, entry)
- except RuntimeError:
- fingerprints[entry.name] = None
- else:
- fingerprints[entry.name] = external_tree_sha256(entry)
- return fingerprints
- def copy_caveman_entry(source: Path, destination: Path) -> None:
- if source.is_symlink():
- destination.symlink_to(source.readlink())
- elif source.is_dir():
- shutil.copytree(source, destination, symlinks=True)
- else:
- shutil.copy2(source, destination)
- def remove_caveman_entry(target: Path) -> None:
- if target.is_symlink() or not target.is_dir():
- target.unlink()
- else:
- shutil.rmtree(target)
- def caveman_payload_symlink_error(global_skills_dir: Path) -> str | None:
- """Return a fail-closed reason when any caveman family payload is a symlink.
- Covers the top-level `caveman` directory, its core `caveman/SKILL.md`
- (including dangling links), and every sibling `caveman*` / `cavecrew*`
- entry. Symlinked payloads are reported and never replaced.
- """
- skill_dir = global_skills_dir / "caveman"
- if skill_dir.is_symlink():
- return "Refusing to replace a symlinked caveman skill directory"
- if (skill_dir / "SKILL.md").is_symlink():
- return "Refusing to replace a symlinked caveman/SKILL.md core payload"
- if caveman_family_has_sibling_symlink(global_skills_dir):
- return "Refusing to touch a caveman family that contains a symlinked sibling entry"
- return None
- def classify_caveman_state(global_skills_dir: Path) -> str:
- skill_dir = global_skills_dir / "caveman"
- skill_md = skill_dir / "SKILL.md"
- if caveman_payload_symlink_error(global_skills_dir) is not None:
- return "abnormal"
- try:
- fingerprints = caveman_family_fingerprints(global_skills_dir)
- except (OSError, RuntimeError):
- return "unknown-drift"
- companions = {
- name: digest for name, digest in fingerprints.items() if name != "caveman"
- }
- if companions and not any(
- companions
- == {name: digest for name, digest in family.items() if name != "caveman"}
- for family in CAVEMAN_KNOWN_FAMILY_SHA256.values()
- ):
- return "unknown-drift"
- if not skill_dir.exists():
- # Partial family (surviving companions without the core) is drift:
- # only a fully absent family is an ordinary missing install.
- return "missing" if not fingerprints else "unknown-drift"
- if not skill_md.is_file():
- return "abnormal"
- try:
- core_bytes = skill_md.read_bytes()
- except OSError:
- return "abnormal"
- if skill_frontmatter_name_from_bytes(core_bytes) != "caveman":
- return "abnormal"
- digest = hashlib.sha256(core_bytes).hexdigest()
- for ref, core_digest in CAVEMAN_KNOWN_CORE_SKILL_SHA256.items():
- if digest == core_digest and fingerprints == CAVEMAN_KNOWN_FAMILY_SHA256.get(
- ref
- ):
- return "current" if ref == CAVEMAN_PINNED_REF else "outdated"
- return "unknown-drift"
- def caveman_maintenance_plan(global_skills_dir: Path) -> dict[str, object]:
- state = classify_caveman_state(global_skills_dir)
- symlink_error = caveman_payload_symlink_error(global_skills_dir)
- blocked_reason = symlink_error or caveman_family_nested_symlink_reason(
- global_skills_dir
- )
- if state == "abnormal" and blocked_reason is not None:
- action = "blocked"
- else:
- action = {
- "outdated": "upgrade",
- "abnormal": "repair",
- }.get(state, "none")
- plan: dict[str, object] = {
- "state": state,
- "plannedAction": action,
- "pinnedRef": CAVEMAN_PINNED_REF,
- "pinnedRevision": CAVEMAN_PINNED_REVISION,
- "scope": "workflow-skill-payload-only",
- }
- if blocked_reason is not None and action == "blocked":
- plan["blockedReason"] = blocked_reason
- return plan
- def restore_caveman_family(global_skills_dir: Path, backup_dir: Path | None) -> str | None:
- try:
- for target in caveman_family_dirs(global_skills_dir):
- remove_caveman_entry(target)
- if backup_dir:
- for source in backup_dir.iterdir():
- copy_caveman_entry(source, global_skills_dir / source.name)
- except (OSError, shutil.Error) as exc:
- return str(exc)
- return None
- def caveman_family_has_sibling_symlink(global_skills_dir: Path) -> bool:
- if not global_skills_dir.is_dir():
- return False
- try:
- return any(
- entry.is_symlink()
- for entry in global_skills_dir.iterdir()
- if entry.name != "caveman" and is_caveman_family_prefix_name(entry.name)
- )
- except OSError:
- # Cannot prove there is no symlink -> fail closed.
- return True
- def caveman_family_nested_symlink_reason(global_skills_dir: Path) -> str | None:
- """Return a fail-closed reason when a family payload nests a symlink.
- Recursively covers every path inside the broad ``caveman*`` / ``cavecrew*``
- prefix entries; a valid core with a nested link already lands in
- ``unknown-drift`` through the fingerprint scan, so this guard exists to
- stop an *abnormal* core containing a nested link from being repaired.
- Top-level links themselves are reported by
- ``caveman_payload_symlink_error`` and skipped here.
- """
- if not global_skills_dir.is_dir():
- return None
- try:
- entries = sorted(global_skills_dir.iterdir())
- except OSError:
- # Cannot prove there is no nested symlink -> fail closed.
- return "Refusing to repair a caveman payload whose entries cannot be read"
- for entry in entries:
- if not is_caveman_family_prefix_name(entry.name):
- continue
- if entry.is_symlink() or not entry.is_dir():
- continue
- walk_errors: list[OSError] = []
- try:
- has_nested = any(
- os.path.islink(os.path.join(dirpath, name))
- for dirpath, dirnames, filenames in os.walk(
- entry, followlinks=False, onerror=walk_errors.append
- )
- for name in (*dirnames, *filenames)
- )
- except OSError:
- has_nested = True # Cannot prove clean -> fail closed.
- if walk_errors:
- # Unreadable descendants can hide a symlink -> fail closed.
- has_nested = True
- if has_nested:
- return (
- "Refusing to repair a caveman payload that contains a nested "
- f"symlink under {entry.name}"
- )
- return None
- def install_caveman_payload(global_skills_dir: Path) -> dict[str, object]:
- result = caveman_maintenance_plan(global_skills_dir)
- result["status"] = "pending"
- result["sourceRepo"] = CAVEMAN_SOURCE_REPO
- result["familyScope"] = "caveman, caveman-*, cavecrew, cavecrew-* only"
- symlink_error = caveman_payload_symlink_error(global_skills_dir)
- if symlink_error is not None:
- result["status"] = "failed"
- result["error"] = symlink_error
- return result
- if result["state"] == "unknown-drift":
- result["status"] = "attention-required"
- result["advice"] = CAVEMAN_DRIFT_ADVICE
- return result
- if result["plannedAction"] == "blocked":
- result["status"] = "failed"
- result["error"] = str(
- result.get(
- "blockedReason",
- "Refusing to replace a caveman payload containing a symlink",
- )
- )
- return result
- try:
- return _install_caveman_payload_staged(global_skills_dir, result)
- except (OSError, shutil.Error) as exc:
- # Staging-directory creation/cleanup, staged reads and the source scan
- # sit outside the transactional backup/replace block; keep the
- # structured JSON contract instead of surfacing a traceback.
- result["status"] = "failed"
- result["error"] = f"Caveman staging failed: {exc}"
- return result
- def _install_caveman_payload_staged(
- global_skills_dir: Path, result: dict[str, object]
- ) -> dict[str, object]:
- with tempfile.TemporaryDirectory(prefix="sbtd-caveman-stage-") as temp_dir:
- stage_root = Path(temp_dir)
- repository = stage_root / "repository"
- cloned, clone_error = clone_repo_at_revision(
- CAVEMAN_SOURCE_REPO, CAVEMAN_PINNED_REVISION, repository
- )
- if not cloned:
- result["status"] = "blocked"
- result["error"] = clone_error
- return result
- source_skills_dir = repository / "skills"
- source_core = source_skills_dir / "caveman" / "SKILL.md"
- if (
- not source_core.is_file()
- or read_skill_frontmatter_name(source_core) != "caveman"
- ):
- result["status"] = "blocked"
- result["error"] = "Pinned caveman source has no valid caveman/SKILL.md"
- return result
- if (
- hashlib.sha256(source_core.read_bytes()).hexdigest()
- != CAVEMAN_CORE_SKILL_SHA256
- ):
- result["status"] = "blocked"
- result["error"] = (
- "Pinned caveman source does not match the reviewed core hash"
- )
- return result
- source_family = caveman_family_dirs(source_skills_dir)
- if (
- caveman_family_fingerprints(source_skills_dir)
- != CAVEMAN_KNOWN_FAMILY_SHA256[CAVEMAN_PINNED_REF]
- ):
- result["status"] = "blocked"
- result["error"] = (
- "Pinned caveman family does not match the reviewed payload"
- )
- return result
- try:
- global_skills_dir.parent.mkdir(parents=True, exist_ok=True)
- global_skills_dir.mkdir(parents=True, exist_ok=True)
- except OSError as exc:
- result["status"] = "failed"
- result["error"] = f"Unable to create global skills directory: {exc}"
- return result
- target_family = caveman_family_dirs(global_skills_dir)
- symlink_error = caveman_payload_symlink_error(global_skills_dir)
- if symlink_error is not None or any(
- target.is_symlink() for target in target_family
- ):
- result["status"] = "failed"
- result["error"] = (
- symlink_error
- or "Refusing to replace a symlinked caveman skill directory"
- )
- return result
- latest_plan = caveman_maintenance_plan(global_skills_dir)
- if latest_plan["state"] == "unknown-drift":
- result.update(latest_plan)
- result["status"] = "attention-required"
- result["advice"] = CAVEMAN_DRIFT_ADVICE
- return result
- if latest_plan["plannedAction"] == "blocked":
- result.update(latest_plan)
- result["status"] = "failed"
- result["error"] = str(
- latest_plan.get(
- "blockedReason",
- "Refusing to replace a caveman payload containing a symlink",
- )
- )
- return result
- # Back up whenever a family payload exists at mutation time. Anything
- # computed before the clone cannot see a family that appeared during
- # staging, so the recomputed `target_family` is the only safe
- # decision point.
- backup_dir: Path | None = None
- if target_family:
- try:
- timestamp = dt.datetime.now().strftime("%Y%m%d%H%M%S")
- backup_dir = Path(
- tempfile.mkdtemp(
- prefix=f"{global_skills_dir.name}.caveman.bak-{timestamp}-",
- dir=global_skills_dir.parent,
- )
- )
- for target in target_family:
- copy_caveman_entry(target, backup_dir / target.name)
- except (OSError, shutil.Error) as exc:
- result["status"] = "failed"
- result["error"] = (
- f"Unable to back up caveman workflow skill payload: {exc}"
- )
- if backup_dir:
- result["backup"] = str(backup_dir)
- return result
- mutation_started = False
- try:
- mutation_started = True
- for target in target_family:
- remove_caveman_entry(target)
- for source in source_family:
- copy_caveman_entry(source, global_skills_dir / source.name)
- except (OSError, shutil.Error) as exc:
- restore_error = (
- restore_caveman_family(global_skills_dir, backup_dir)
- if mutation_started
- else None
- )
- result["status"] = "failed"
- result["error"] = f"Unable to sync caveman workflow skill payload: {exc}"
- if restore_error:
- result["restoreError"] = restore_error
- if backup_dir:
- result["backup"] = str(backup_dir)
- return result
- after_state = classify_caveman_state(global_skills_dir)
- if after_state != "current":
- restore_error = (
- restore_caveman_family(global_skills_dir, backup_dir)
- if mutation_started
- else None
- )
- result["status"] = "failed"
- result["error"] = "Caveman workflow skill payload did not verify after sync"
- result["afterState"] = after_state
- if restore_error:
- result["restoreError"] = restore_error
- if backup_dir:
- result["backup"] = str(backup_dir)
- return result
- result["status"] = "success"
- result["afterState"] = after_state
- result["familySkills"] = [source.name for source in source_family]
- if backup_dir:
- result["backup"] = str(backup_dir)
- return result
- def maintain_caveman_payload(global_skills_dir: Path) -> dict[str, object]:
- plan = caveman_maintenance_plan(global_skills_dir)
- if plan["state"] == "unknown-drift":
- return {
- **plan,
- "status": "attention-required",
- "advice": CAVEMAN_DRIFT_ADVICE,
- }
- if plan["plannedAction"] == "blocked":
- return {
- **plan,
- "status": "failed",
- "error": plan.get(
- "blockedReason", "Refusing to replace a symlinked caveman payload"
- ),
- }
- if plan["plannedAction"] == "none":
- return {**plan, "status": "skipped"}
- return install_caveman_payload(global_skills_dir)
- def print_caveman_maintenance_details(maintenance: dict[str, object]) -> None:
- for label, value in (
- ("reason", maintenance.get("error") or maintenance.get("blockedReason")),
- ("backup", maintenance.get("backup")),
- ("restore error", maintenance.get("restoreError")),
- ("advice", maintenance.get("advice")),
- ):
- if value:
- print(f"- {label}: {value}")
- def install_caveman(args: argparse.Namespace) -> int:
- try:
- global_skills_dir = resolve_global_skills_dir(args.global_skills_dir)[0]
- except (OSError, RuntimeError) as exc:
- payload = {
- "mode": "install-caveman",
- "status": "failed",
- "error": f"Unable to resolve the global skills directory: {exc}",
- }
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- before = check_skill("caveman", "interaction", global_skills_dir, None)
- maintenance = caveman_maintenance_plan(global_skills_dir)
- payload: dict[str, object] = {
- "mode": "install-caveman",
- "agent": args.agent,
- "platform": platform.system() or sys.platform,
- "before": before,
- "maintenance": maintenance,
- "globalSkillsDir": str(global_skills_dir),
- "scope": "workflow-skill-payload-only",
- }
- if maintenance["state"] == "current":
- payload["status"] = "already-installed"
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else "caveman workflow skill payload is already current."
- )
- return 0
- if not args.yes:
- payload["status"] = "needs-confirmation"
- payload["actions"] = [
- f"stage pinned caveman {CAVEMAN_PINNED_REF} skill payload",
- f"sync caveman, caveman-*, cavecrew, cavecrew-* into {global_skills_dir}",
- "preserve plugins, hooks, statusline, and extensions unchanged",
- ]
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else "caveman workflow skill payload needs confirmation; rerun with --yes."
- )
- if not args.json:
- print_caveman_maintenance_details(maintenance)
- return 2
- if maintenance["state"] == "unknown-drift":
- payload["status"] = "attention-required"
- payload["advice"] = CAVEMAN_DRIFT_ADVICE
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["advice"]
- )
- return 2
- try:
- result = install_caveman_payload(global_skills_dir)
- except Exception as exc: # noqa: BLE001 - preserve the install JSON/text failure contract.
- result = {
- **maintenance,
- "status": "failed",
- "error": str(exc),
- }
- payload["maintenance"] = result
- after = check_skill("caveman", "interaction", global_skills_dir, None)
- payload["after"] = after
- payload["status"] = (
- "installed"
- if result["status"] == "success" and after["installed"]
- else result["status"]
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else f"install-caveman status: {payload['status']}"
- )
- if not args.json:
- print_caveman_maintenance_details(result)
- return 0 if payload["status"] == "installed" else 1
- def command_excerpt(
- completed: subprocess.CompletedProcess[str] | None, limit: int = 20
- ) -> str | None:
- if completed is None:
- return None
- output = "\n".join(part for part in (completed.stdout, completed.stderr) if part)
- lines = output.strip().splitlines()
- if not lines:
- return None
- return "\n".join(lines[-limit:])
- def github_json(url: str, timeout: int = 30) -> dict[str, object]:
- request = urllib.request.Request(
- url, headers={"User-Agent": "sbtd-workflow-onboard"}
- )
- with urllib.request.urlopen(request, timeout=timeout) as response:
- return json.loads(response.read().decode("utf-8"))
- def download_url(url: str, destination: Path, timeout: int = 900) -> None:
- request = urllib.request.Request(
- url, headers={"User-Agent": "sbtd-workflow-onboard"}
- )
- with (
- urllib.request.urlopen(request, timeout=timeout) as response,
- destination.open("wb") as handle,
- ):
- shutil.copyfileobj(response, handle)
- def temurin_platform_ids() -> tuple[str | None, str | None, str | None]:
- system = platform.system() or sys.platform
- machine = platform.machine().lower()
- if system == "Darwin":
- os_id = "mac"
- elif system == "Linux":
- os_id = "linux"
- else:
- return (
- None,
- None,
- f"Temurin tarball auto-install is only supported on macOS and Linux; current platform is {system}.",
- )
- if machine in {"x86_64", "amd64"}:
- arch_id = "x64"
- elif machine in {"arm64", "aarch64"}:
- arch_id = "aarch64"
- else:
- return (
- None,
- None,
- f"Unsupported CPU architecture for Temurin auto-install: {machine}.",
- )
- return os_id, arch_id, None
- def select_temurin_asset(major: int) -> dict[str, object]:
- os_id, arch_id, reason = temurin_platform_ids()
- if reason:
- raise RuntimeError(reason)
- release = github_json(TEMURIN_RELEASES_API_TEMPLATE.format(major=major))
- assets = release.get("assets")
- if not isinstance(assets, list):
- raise RuntimeError("GitHub release payload did not include assets.")
- prefix = f"OpenJDK{major}U-jdk_{arch_id}_{os_id}_hotspot_"
- for asset in assets:
- if not isinstance(asset, dict):
- continue
- name = str(asset.get("name") or "")
- url = str(asset.get("browser_download_url") or "")
- if (
- name.startswith(prefix)
- and name.endswith(".tar.gz")
- and "debugimage" not in name
- and "testimage" not in name
- and "static-libs" not in name
- and url
- ):
- return {
- "release": release.get("tag_name"),
- "name": name,
- "url": url,
- }
- raise RuntimeError(
- f"No matching Temurin {major} JDK tar.gz asset found for {arch_id}/{os_id}."
- )
- def safe_extract_tar(archive: Path, destination: Path) -> None:
- destination.mkdir(parents=True, exist_ok=True)
- destination_root = destination.resolve()
- with tarfile.open(archive, "r:gz") as tar:
- for member in tar.getmembers():
- target = (destination / member.name).resolve()
- if target != destination_root and destination_root not in target.parents:
- raise RuntimeError(f"Unsafe path in archive: {member.name}")
- tar.extractall(destination)
- def find_java_home(root: Path) -> Path:
- names = (
- ("bin/java.exe", "bin/java")
- if platform.system() == "Windows"
- else ("bin/java",)
- )
- candidates = sorted(
- candidate for name in names for candidate in root.rglob(name)
- )
- for java_bin in candidates:
- if java_bin.is_file():
- return java_bin.parent.parent
- expected = "bin/java.exe or bin/java" if platform.system() == "Windows" else "bin/java"
- raise RuntimeError(f"Extracted JDK archive did not contain {expected}.")
- def activate_java_home(java_home: Path) -> None:
- os.environ["JAVA_HOME"] = str(java_home)
- os.environ["PATH"] = f"{java_home / 'bin'}{os.pathsep}{os.environ.get('PATH', '')}"
- def install_java(args: argparse.Namespace) -> int:
- major = int(args.major)
- if major < JAVA_MIN_MAJOR:
- raise SystemExit(
- f"Refusing to install Java {major}. Maestro requires Java {JAVA_MIN_MAJOR}+."
- )
- before = check_java_for_maestro()
- install_root = expand_path(args.install_root) or (
- Path.home() / ".local" / "share" / "sbtd-workflow" / "jdks"
- )
- target_home = install_root / f"temurin-{major}"
- profile = expand_path(args.profile) or default_shell_profile()
- payload: dict[str, object] = {
- "mode": "install-java",
- "platform": platform.system() or sys.platform,
- "before": before,
- "major": major,
- "minimumMajor": JAVA_MIN_MAJOR,
- "releaseSource": TEMURIN21_RELEASES_URL,
- "targetJavaHome": str(target_home),
- "profile": str(profile),
- }
- if before["installed"] and not args.force:
- payload["status"] = "already-installed"
- payload["advice"] = (
- "An installed JDK already satisfies Maestro's Java 17+ prerequisite. Use --force only after confirming a version replacement is intended."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("An installed JDK already satisfies Maestro's Java 17+ prerequisite.")
- print(f"java: {before['path']} ({before['version']})")
- if before.get("javaHome"):
- print(f"JAVA_HOME: {before['javaHome']}")
- print(payload["advice"])
- return 0
- os_id, arch_id, platform_reason = temurin_platform_ids()
- if platform_reason:
- payload["status"] = "manual-required"
- payload["reason"] = platform_reason
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(platform_reason)
- print(
- f"Download a Java {major}+ JDK manually from {TEMURIN21_RELEASES_URL}."
- )
- return 1
- payload["targetPlatform"] = {"os": os_id, "arch": arch_id}
- payload["actions"] = [
- f"fetch the latest Temurin {major} JDK release asset from {TEMURIN21_RELEASES_URL}",
- f"extract it into {target_home}",
- f"write JAVA_HOME and PATH exports into {profile}",
- "verify `java --version` reports Java 17 or higher",
- ]
- if not args.yes:
- payload["status"] = "needs-confirmation"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(
- f"Java {JAVA_MIN_MAJOR}+ is missing or a Java {major} install was explicitly requested."
- )
- for action in payload["actions"]:
- print(f"- {action}")
- print("Rerun with --yes after user confirmation.")
- return 2
- try:
- asset = select_temurin_asset(major)
- payload["selectedAsset"] = asset
- with tempfile.TemporaryDirectory(prefix="sbtd-temurin-") as temp_dir:
- archive = Path(temp_dir) / str(asset["name"])
- extracted = Path(temp_dir) / "extracted"
- download_url(str(asset["url"]), archive)
- safe_extract_tar(archive, extracted)
- extracted_java_home = find_java_home(extracted)
- target_home.parent.mkdir(parents=True, exist_ok=True)
- if target_home.exists():
- backup = backup_path(target_home)
- shutil.move(str(target_home), str(backup))
- payload["backup"] = str(backup)
- shutil.move(str(extracted_java_home), str(target_home))
- except (OSError, RuntimeError, urllib.error.URLError, json.JSONDecodeError) as exc:
- payload["status"] = "failed"
- payload["error"] = str(exc)
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- activate_java_home(target_home)
- profile_updated = ensure_profile_line(
- profile,
- f'export JAVA_HOME="{target_home}"; export PATH="$JAVA_HOME/bin:$PATH"',
- f"Added by sbtd-workflow-onboard for Temurin {major}",
- )
- after = check_java_for_maestro()
- payload["after"] = after
- payload["profileUpdated"] = profile_updated
- payload["status"] = "installed" if after["installed"] else "failed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"install-java status: {payload['status']}")
- if profile_updated:
- print(f"Updated JAVA_HOME/PATH in {profile}")
- if after["installed"]:
- print(f"java: {after['path']} ({after['version']})")
- else:
- print(
- "Java was installed but did not pass the Java 17+ verification. Check JAVA_HOME and PATH."
- )
- return 0 if after["installed"] else 1
- def install_maestro(args: argparse.Namespace) -> int:
- java_before = check_java_for_maestro()
- before = check_maestro_cli(java_before)
- profile = expand_path(args.profile) or default_shell_profile()
- maestro_bin = Path.home() / ".maestro" / "bin"
- payload: dict[str, object] = {
- "mode": "install-maestro",
- "platform": platform.system() or sys.platform,
- "before": before,
- "java": java_before,
- "installUrl": MAESTRO_INSTALL_URL,
- "profile": str(profile),
- "maestroMcpConfig": maestro_mcp_server_config(java_before, before),
- "maestroMcpConfigExamples": maestro_mcp_config_examples(java_before, before),
- }
- if before["installed"] and not args.reinstall:
- payload["status"] = "already-installed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("Maestro CLI is already installed and verified.")
- print(f"maestro: {before['path']} ({before['version']})")
- print("Maestro MCP configuration:")
- print_config_examples(
- {"configExamples": payload["maestroMcpConfigExamples"]}
- )
- return 0
- if not java_before["installed"]:
- payload["status"] = "java-required"
- payload["advice"] = (
- f"Install Java {JAVA_MIN_MAJOR}+ first. Default command: "
- f"{shell_prefix()}`{onboard_command('install-java', '--major', '21', '--yes')}` after user confirmation."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"Maestro CLI requires Java {JAVA_MIN_MAJOR}+ before installation.")
- print(payload["advice"])
- return 2
- system = platform.system() or sys.platform
- if system == "Windows":
- payload["status"] = "manual-required"
- payload["advice"] = (
- "Use WSL with the official install script, or follow Maestro's regular Windows installation guide manually."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(payload["advice"])
- return 1
- if before.get("verificationFailed") and not args.reinstall:
- payload["status"] = "verification-failed"
- payload["advice"] = (
- "A maestro command exists but failed verification. Rerun with --reinstall only after confirming replacement is intended."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(payload["advice"])
- return 2
- payload["actions"] = [
- f'run the official Maestro installer: curl -fsSL "{MAESTRO_INSTALL_URL}" | bash',
- f"ensure {maestro_bin} is in PATH via {profile}",
- "verify `maestro --version` and `maestro test --help`",
- ]
- if not args.yes:
- payload["status"] = "needs-confirmation"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("Maestro CLI is missing or not verified.")
- for action in payload["actions"]:
- print(f"- {action}")
- print("Maestro MCP configuration after CLI installation:")
- print_config_examples(
- {"configExamples": payload["maestroMcpConfigExamples"]}
- )
- print("Rerun with --yes after user confirmation.")
- return 2
- if not shutil.which("curl"):
- payload["status"] = "failed"
- payload["error"] = "curl is required for the official Maestro install script."
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- install_result = shell_result(
- f'curl -fsSL "{MAESTRO_INSTALL_URL}" | bash', timeout=600
- )
- if not install_result or install_result.returncode != 0:
- payload["status"] = "failed"
- payload["error"] = (
- command_excerpt(install_result) or "Unable to run the Maestro installer."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- os.environ["PATH"] = f"{maestro_bin}{os.pathsep}{os.environ.get('PATH', '')}"
- profile_updated = ensure_profile_line(
- profile,
- 'export PATH="$HOME/.maestro/bin:$PATH"',
- "Added by sbtd-workflow-onboard for Maestro CLI",
- )
- java_after = check_java_for_maestro()
- after = check_maestro_cli(java_after)
- payload["after"] = after
- payload["maestroMcpConfig"] = maestro_mcp_server_config(java_after, after)
- payload["maestroMcpConfigExamples"] = maestro_mcp_config_examples(java_after, after)
- payload["profileUpdated"] = profile_updated
- payload["status"] = "installed" if after["installed"] else "failed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"install-maestro status: {payload['status']}")
- if profile_updated:
- print(f"Updated PATH in {profile}")
- if after["installed"]:
- print(f"maestro: {after['path']} ({after['version']})")
- print("Maestro MCP configuration:")
- print_config_examples(
- {"configExamples": payload["maestroMcpConfigExamples"]}
- )
- else:
- print(
- "Maestro installer completed but `maestro --version` did not pass. Check PATH, Java, and installer output."
- )
- return 0 if after["installed"] else 1
- def run_project_command(
- command: tuple[str, ...],
- cwd: Path,
- timeout: int = 900,
- stdin_text: str | None = None,
- env: dict[str, str] | None = None,
- ) -> subprocess.CompletedProcess[str] | None:
- try:
- return subprocess.run(
- subprocess_command(command),
- cwd=str(cwd),
- check=False,
- capture_output=True,
- text=True,
- errors="replace",
- timeout=timeout,
- input=stdin_text,
- env=env,
- )
- except (OSError, subprocess.TimeoutExpired):
- return None
- def command_display(command: tuple[str, ...]) -> str:
- return shlex.join(command)
- def aggregate_project_status(projects: list[dict[str, object]]) -> str:
- statuses = {str(item.get("status")) for item in projects}
- for status in ("failed", "blocked", "needs-user", "bootstrap-required"):
- if status in statuses:
- return status
- return "success" if projects else "skipped"
- def project_status_exit_code(status: object) -> int:
- if status in {"blocked", "needs-user"}:
- return 2
- if status == "failed":
- return 5
- if status == "bootstrap-required":
- return 6
- return 0
- def project_scaffold_conflict(project_root: Path, skip_agents: bool) -> str | None:
- """Reject unsafe destinations and newly hiding existing reserved data."""
- names = (".gitignore",) if skip_agents else (".gitignore", "AGENTS.md")
- try:
- for name in names:
- target = project_root / name
- try:
- metadata = target.lstat()
- except FileNotFoundError:
- continue
- if not stat.S_ISREG(metadata.st_mode):
- return f"{name} is not a regular installation target."
- if name == ".gitignore" and metadata.st_nlink > 1:
- return ".gitignore has multiple hard links; appending would modify another file."
- target = project_root / ".gitignore"
- current = target.read_text(encoding="utf-8") if target.exists() else ""
- missing = set(
- missing_file_lines(
- PROJECT_GITIGNORE_TEMPLATE.read_text(encoding="utf-8"), current
- )
- )
- existing: list[str] = []
- for relative in (".sbtd", "docs/handoffs", "graft", ".graft"):
- if f"/{relative}" not in missing:
- continue
- if "/" in relative:
- parent = project_root / "docs"
- if parent.is_symlink():
- return "docs is a symlink; reserved handoff ownership is not established."
- path = project_root / relative
- try:
- path.lstat()
- except FileNotFoundError:
- continue
- existing.append(relative)
- if not existing:
- return None
- verdicts = gitignore_verdicts(project_root, tuple(existing))
- if isinstance(verdicts, str) or any(
- not verdicts[path].ignored for path in existing
- ):
- return "Adding ignore rules would newly hide existing reserved data or its protection is unverified."
- tracked = run_project_command(
- ("git", "ls-files", "-z", "--", *existing), project_root, timeout=60
- )
- if tracked is None or tracked.returncode != 0 or tracked.stdout:
- return "Existing reserved data is tracked or its tracked state could not be verified."
- except (OSError, UnicodeError):
- return "Project installation targets could not be safely inspected."
- return None
- def inspect_project_setup(project_root: Path, skip_agents: bool) -> StateInspection:
- inspection = inspect_project_state(project_root)
- if inspection["status"] == "success":
- conflict = project_scaffold_conflict(project_root, skip_agents)
- if conflict:
- inspection.update(
- status="needs-user",
- reason=conflict,
- nextStep="Inspect the existing data and resolve the target or authorize its narrow protection before retrying; Onboard will not hide or replace it.",
- )
- return inspection
- def build_sbtd_project_setup(
- mode: str, args: argparse.Namespace, *, project_roots: list[Path] | None = None
- ) -> dict[str, object]:
- projects: list[dict[str, object]] = []
- roots = resolve_project_roots(args) if project_roots is None else project_roots
- for root in roots:
- projects.append(
- {
- "projectRoot": str(root),
- **inspect_project_setup(
- root, bool(getattr(args, "skip_project_agents", False))
- ),
- }
- )
- status = aggregate_project_status(projects)
- return {
- "mode": mode,
- "status": status,
- "projects": projects,
- "reason": (
- "Only selected project state is inspected; optional artifacts are not created."
- if projects
- else "--projects-root was not provided."
- ),
- "nextStep": (
- "Resolve each reported project condition before installation."
- if project_status_exit_code(status)
- else ""
- ),
- }
- def print_sbtd_project_setup_report(report: dict[str, object]) -> None:
- print("\nSBTD project setup:")
- print(f"- status: {report.get('status')}")
- if report.get("reason"):
- print(f" reason: {report['reason']}")
- for project in cast(list[dict[str, object]], report.get("projects", [])):
- print(f"- project root: {project['projectRoot']}")
- print(f" status: {project['status']}")
- print(f" reason: {project['reason']}")
- if project["nextStep"]:
- print(f" next step: {project['nextStep']}")
- # Explicit --developer identity integration. The library is imported lazily
- # inside each function because sbtd_identity -> sbtd_task_state -> onboard is
- # an intentional one-way dependency; a module-level import would be circular.
- _DEVELOPER_BLOCKING_STATUSES = (
- "failed",
- "conflict",
- "blocked",
- "needs-confirmation",
- "needs-protection",
- )
- def _developer_result(
- root: Path, requested: str, *, create: bool = False, protect: bool = False
- ) -> IdentityResult:
- from sbtd_identity import DeveloperStore, IdentityResult
- try:
- store = DeveloperStore(root, read_only=not create)
- if create:
- return store.ensure(requested, confirmed=True, protect=protect)
- return store.plan(requested)
- except (TaskDataError, OSError, RuntimeError) as error:
- return IdentityResult(
- "failed" if create else "blocked",
- path=str(root / ".sbtd/developer"),
- topology="unknown",
- reason="developer identity could not be safely inspected or initialized for this project",
- completed_steps=tuple(getattr(error, "completed_steps", ())),
- )
- def _developer_plan_entry(
- root: Path, requested: str, result: IdentityResult
- ) -> dict[str, object]:
- return {
- "projectRoot": str(root),
- "requestedName": requested,
- "status": result.status,
- "name": result.name,
- "source": result.source,
- "target": result.path,
- "topology": result.topology,
- "needsProtection": result.needs_protection,
- "reason": result.reason,
- "completedSteps": list(result.completed_steps),
- }
- def aggregate_developer_status(projects: list[dict[str, object]]) -> str:
- statuses = [str(project["status"]) for project in projects]
- if not statuses:
- return "blocked"
- for blocking in _DEVELOPER_BLOCKING_STATUSES:
- if blocking in statuses:
- return blocking
- if "created" in statuses:
- return "created"
- if "planned" in statuses:
- return "planned"
- return "unchanged"
- def _developer_plan_payload(
- requested: str, projects: list[dict[str, object]]
- ) -> dict[str, object]:
- return {
- "requestedName": requested,
- "status": aggregate_developer_status(projects),
- "reason": (
- None
- if projects
- else "--developer requires at least one explicit --projects-root; "
- "the name is never derived from or written to the cwd or HOME."
- ),
- "projects": projects,
- }
- def developer_plan_exit_code(developer_plan: dict[str, object]) -> int:
- status = str(developer_plan["status"])
- if status == "failed":
- return 5
- if status in _DEVELOPER_BLOCKING_STATUSES:
- return 2
- return 0
- def build_developer_plan(args: argparse.Namespace) -> dict[str, object] | None:
- """Read-only per-project identity plan for an explicit --developer name.
- Only the roots listed via --projects-root are inspected; without them the
- plan is blocked rather than falling back to the cwd or HOME.
- """
- requested = getattr(args, "developer", None)
- if requested is None:
- return None
- projects = [
- _developer_plan_entry(
- root, requested, _developer_result(root, requested)
- )
- for root in resolve_project_roots(args)
- ]
- return _developer_plan_payload(requested, projects)
- def ensure_developer_identities(
- developer_plan: dict[str, object],
- ) -> dict[str, object]:
- """Post-scaffold verified identity creation for the preflighted projects.
- Runs after scaffold writes. Only protection explicitly included in the
- confirmed identity plan may be completed by the shared narrow helper.
- """
- requested = str(developer_plan["requestedName"])
- projects: list[dict[str, object]] = []
- for entry in cast(list[dict[str, object]], developer_plan["projects"]):
- root = Path(str(entry["projectRoot"]))
- result = _developer_result(
- root, requested, create=True, protect=entry.get("needsProtection") is True
- )
- projects.append(_developer_plan_entry(root, requested, result))
- return _developer_plan_payload(requested, projects)
- def print_developer_plan(developer_plan: dict[str, object]) -> None:
- print("\nDeveloper identity:")
- print(f"- requested name: {developer_plan['requestedName']}")
- print(f"- status: {developer_plan['status']}")
- if developer_plan.get("reason"):
- print(f" reason: {developer_plan['reason']}")
- for project in cast(list[dict[str, object]], developer_plan["projects"]):
- print(f"- project root: {project['projectRoot']}")
- print(f" status: {project['status']}")
- if project.get("name"):
- print(f" name: {project['name']} (source: {project.get('source')})")
- if project.get("target"):
- print(f" target: {project['target']}")
- if project.get("needsProtection"):
- print(" needs protection: yes")
- if project.get("reason"):
- print(f" reason: {project['reason']}")
- def install_playwright_cli(args: argparse.Namespace) -> int:
- project_root = resolve_project_root(args, required=True)
- runtime = check_npm_runtime()
- before = check_playwright_project(project_root)
- package_json = project_root / "package.json"
- payload: dict[str, object] = {
- "mode": "install-playwright-cli",
- "projectRoot": str(project_root),
- "before": before,
- "runtime": runtime,
- }
- if before["installed"] and not args.reinstall:
- payload["status"] = "already-installed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("Project-level Playwright CLI is already present.")
- if before.get("version"):
- print(f"Playwright dependency: {before['version']}")
- return 0
- if not runtime["npm"]["installed"]:
- payload["status"] = "npm-required"
- payload["advice"] = (
- f"{shell_prefix()}Install npm first, for example with `{onboard_command('ensure-npm', '--yes')}` after user confirmation."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(
- "Playwright CLI is project-level Node tooling, but npm is not usable."
- )
- print(payload["advice"])
- return 2
- if not package_json.is_file():
- payload["status"] = "not-applicable"
- payload["reason"] = (
- "No package.json exists at the project root; do not create a Node test stack automatically."
- )
- payload["fallback"] = (
- "Use Playwright MCP or Chrome DevTools MCP for exploratory Web diagnostics, and add Playwright CLI only after the project accepts a Node test dependency."
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(payload["reason"])
- print(payload["fallback"])
- return 2
- payload["actions"] = [
- "install project dependency: npm install -D @playwright/test",
- "install Playwright browser binaries: npx playwright install",
- ]
- if args.skip_browsers:
- payload["actions"][-1] = (
- "skip browser binary installation because --skip-browsers was provided"
- )
- if not args.yes:
- payload["status"] = "needs-confirmation"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("Project-level Playwright CLI is missing.")
- for action in payload["actions"]:
- print(f"- {action}")
- print("Rerun with --yes after user confirmation.")
- return 2
- install_result = run_project_command(
- ("npm", "install", "-D", "@playwright/test"), project_root, timeout=900
- )
- payload["npmInstallOutput"] = command_excerpt(install_result)
- if not install_result or install_result.returncode != 0:
- payload["status"] = "failed"
- payload["error"] = command_excerpt(install_result) or "npm install failed."
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- if not args.skip_browsers:
- browsers_result = run_project_command(
- ("npx", "playwright", "install"), project_root, timeout=1200
- )
- payload["browserInstallOutput"] = command_excerpt(browsers_result)
- if not browsers_result or browsers_result.returncode != 0:
- payload["status"] = "browser-install-failed"
- payload["error"] = (
- command_excerpt(browsers_result) or "npx playwright install failed."
- )
- print(
- json.dumps(payload, indent=2, ensure_ascii=False)
- if args.json
- else payload["error"]
- )
- return 1
- after = check_playwright_project(project_root)
- payload["after"] = after
- payload["status"] = "installed" if after["installed"] else "failed"
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print(f"install-playwright-cli status: {payload['status']}")
- if after["installed"]:
- print(
- "Project-level Playwright CLI dependency/config marker is now present."
- )
- else:
- print(
- "Playwright install completed but no dependency/config/script marker was detected."
- )
- return 0 if after["installed"] else 1
- def build_operations(mode: str, args: argparse.Namespace) -> list[Operation]:
- project_roots = resolve_project_roots(args)
- operations: list[Operation] = []
- if mode != "init-projects":
- global_agents = expand_path(args.global_agents_path) or (
- default_codex_home() / "AGENTS.md"
- )
- operations.append(
- Operation(
- "codex global AGENTS.md",
- GLOBAL_AGENTS_TEMPLATE,
- global_agents,
- "file",
- )
- )
- omp_agents_path, omp_agents_explicit = omp_agents_target()
- if omp_agents_explicit or detect_omp_root() is not None:
- omp_agents = omp_agents_path.resolve()
- if omp_agents != global_agents.resolve():
- operations.append(
- Operation(
- "omp global AGENTS.md",
- GLOBAL_AGENTS_TEMPLATE,
- omp_agents,
- "file",
- )
- )
- skills_root = scoped_skills_root(args)
- for name, source in SKILL_SOURCES.items():
- target = skills_root / name
- operations.append(
- Operation(
- f"global skill {name}",
- source,
- target,
- "dir",
- source.resolve() == target.resolve(),
- skip_when_valid=mode == "init",
- )
- )
- for project_root in project_roots:
- if not args.skip_project_agents:
- operations.append(
- Operation(
- f"project AGENTS.md [{project_root}]",
- PROJECT_AGENTS_TEMPLATE,
- project_root / "AGENTS.md",
- "file",
- )
- )
- operations.append(
- Operation(
- f"project .gitignore [{project_root}]",
- PROJECT_GITIGNORE_TEMPLATE,
- project_root / ".gitignore",
- "ensure-file-block",
- )
- )
- return dedupe_file_operations(operations)
- def dedupe_file_operations(operations: list[Operation]) -> list[Operation]:
- seen: set[Path] = set()
- unique: list[Operation] = []
- for operation in operations:
- if operation.kind == "file":
- target = operation.target.resolve()
- if target in seen:
- continue
- seen.add(target)
- unique.append(operation)
- return unique
- def build_bundled_skill_migration_plan(
- mode: str, args: argparse.Namespace
- ) -> dict[str, object]:
- if mode == "init-projects":
- return {
- "mode": "bundled-skill-rename",
- "status": "skipped",
- "reason": "init-projects does not inspect or modify global skills.",
- }
- skills_root = scoped_skills_root(args)
- migrations: list[dict[str, object]] = []
- conflicts: list[dict[str, object]] = []
- for canonical_name, legacy_names in BUNDLED_SKILL_LEGACY_NAMES.items():
- canonical_target = skills_root / canonical_name
- legacy_targets: list[Path] = []
- for legacy_name in legacy_names:
- legacy_target = skills_root / legacy_name
- if not legacy_target.exists():
- continue
- actual_name = (
- read_skill_frontmatter_name(legacy_target / "SKILL.md")
- if legacy_target.is_dir()
- else None
- )
- if actual_name != legacy_name:
- conflicts.append(
- {
- "path": str(legacy_target),
- "expectedName": legacy_name,
- "actualName": actual_name,
- }
- )
- continue
- legacy_targets.append(legacy_target)
- migrations.append(
- {
- "canonicalName": canonical_name,
- "canonicalTarget": str(canonical_target),
- "legacyTargets": [str(path) for path in legacy_targets],
- }
- )
- return {
- "mode": "bundled-skill-rename",
- "status": (
- "blocked"
- if conflicts
- else "required"
- if any(item["legacyTargets"] for item in migrations)
- else "not-needed"
- ),
- "reason": (
- "A legacy path exists but its Skill identity does not match the "
- "legacy name; no files were changed."
- if conflicts
- else None
- ),
- "targetDir": str(skills_root),
- "migrations": migrations,
- "conflicts": conflicts,
- }
- def run_bundled_skill_migration(plan: dict[str, object]) -> list[dict[str, object]]:
- if plan.get("status") == "skipped":
- return []
- results: list[dict[str, object]] = []
- for raw_item in cast(list[dict[str, object]], plan.get("migrations") or []):
- canonical_name = str(raw_item["canonicalName"])
- canonical_target = Path(str(raw_item["canonicalTarget"]))
- legacy_targets = [
- Path(str(path)) for path in raw_item.get("legacyTargets") or []
- ]
- if read_skill_frontmatter_name(canonical_target / "SKILL.md") != canonical_name:
- results.append(
- {
- "name": canonical_name,
- "status": "failed",
- "target": str(canonical_target),
- "error": "canonical bundled Skill is missing or has invalid frontmatter",
- }
- )
- continue
- for legacy_target in legacy_targets:
- try:
- remove_existing_target(legacy_target)
- except OSError as exc:
- results.append(
- {
- "name": legacy_target.name,
- "status": "failed",
- "target": str(legacy_target),
- "canonicalTarget": str(canonical_target),
- "error": str(exc),
- }
- )
- continue
- results.append(
- {
- "name": legacy_target.name,
- "status": "removed",
- "target": str(legacy_target),
- "canonicalTarget": str(canonical_target),
- }
- )
- return results
- def print_bundled_skill_migration_report(results: list[dict[str, object]]) -> None:
- print("\nBundled Skill rename migration report:")
- if not results:
- print("- none")
- return
- for item in results:
- print(f"- {item['name']}: {item['status']}")
- print(f" target: {item['target']}")
- if item.get("canonicalTarget"):
- print(f" canonical target: {item['canonicalTarget']}")
- if item.get("error"):
- print(f" error: {item['error']}")
- def operation_plan_entry(operation: Operation) -> dict[str, object]:
- entry: dict[str, object] = {
- "label": operation.label,
- "source": str(operation.source),
- "target": str(operation.target),
- "kind": operation.kind,
- "targetExists": operation.target.exists(),
- "sameLocation": operation.same_location,
- }
- if operation.kind != "dir":
- return entry
- valid = external_skill_target_is_valid(
- operation.target.parent, operation.target.name
- )
- entry["targetValid"] = valid
- if operation.same_location:
- action = "skipped-same-location"
- entry["plannedActionOnInit"] = action
- entry["plannedActionOnReset"] = action
- return entry
- if valid:
- entry["plannedActionOnInit"] = "skipped-already-valid"
- entry["plannedActionOnReset"] = "overwritten-without-backup"
- return entry
- action = (
- "overwritten-without-backup" if operation.target.exists() else "copied"
- )
- entry["plannedActionOnInit"] = action
- entry["plannedActionOnReset"] = action
- return entry
- def build_plan_payload(
- mode: str,
- operations: list[Operation],
- bundled_migration_plan: dict[str, object] | None = None,
- external_migration_plan: dict[str, object] | None = None,
- global_skills_dir: Path | None = None,
- global_skills_dir_source: str | None = None,
- sbtd_init_plan: dict[str, object] | None = None,
- ) -> dict[str, object]:
- payload: dict[str, object] = {
- "mode": mode,
- "platform": platform.system() or sys.platform,
- "skillDir": str(SKILL_DIR),
- "globalSkillsDir": str(global_skills_dir) if global_skills_dir else None,
- "globalSkillsDirSource": global_skills_dir_source,
- "skillWritePolicy": {
- "init": "skip-valid-shells",
- "reset": "overwrite-all",
- },
- "operations": [operation_plan_entry(op) for op in operations],
- }
- if bundled_migration_plan:
- payload["bundledMigration"] = bundled_migration_plan
- if external_migration_plan:
- payload["externalMigration"] = external_migration_plan
- if sbtd_init_plan:
- payload["sbtdInit"] = sbtd_init_plan
- if global_skills_dir and mode in {"plan", "init", "reset"}:
- payload["cavemanMaintenance"] = caveman_maintenance_plan(global_skills_dir)
- payload["contentAlignment"] = check_content_alignment(global_skills_dir)
- if mode != "init-projects":
- payload["graft"] = check_graft()
- return payload
- def print_plan(payload: dict[str, object]) -> None:
- print(f"Mode: {payload['mode']}")
- print(f"Platform: {payload['platform']}")
- if "contentAlignment" in payload:
- print(f"Skills-only content alignment: {payload['contentAlignment']['status']}")
- if payload["contentAlignment"]["status"] != "aligned":
- print(" Existing valid Skills may be retained; use upgrade for confirmed content alignment.")
- for label, key in (("Optional Graft CLI", "graft"), ("Graft wiring", "graftWiring")):
- details = payload.get(key)
- if isinstance(details, dict):
- print(f"{label}: {details.get('status')}")
- if details.get("reason"):
- print(f" reason: {details['reason']}")
- if details.get("nextStep"):
- print(f" next: {details['nextStep']}")
- if key == "graftWiring" and details.get("status") == "planned":
- for operation in details.get("sharedOperations", []):
- print(f" host resource: {operation['target']}")
- if details.get("retireLegacy"):
- print(" retire only exact owned fixed-root MCP entries for:")
- for root in details.get("roots", []):
- print(f" {root}")
- for binding in details.get("bindings", []):
- if "legacy" in binding:
- print(f" approved old runtime: {json.dumps(binding['legacy'], sort_keys=True)}")
- print(" preserve originals; no runtime-directory or backup deletion")
- for item in payload["operations"]:
- if item["sameLocation"]:
- exists = "same source and target"
- else:
- exists = "exists" if item["targetExists"] else "missing"
- if item.get("plannedActionOnInit"):
- exists += (
- f", init={item['plannedActionOnInit']}"
- f", reset={item['plannedActionOnReset']}"
- )
- print(f"- {item['label']}: {item['target']} ({exists})")
- caveman_maintenance = payload.get("cavemanMaintenance")
- if caveman_maintenance:
- print("\nCaveman maintenance:")
- print(
- f"- state: {caveman_maintenance['state']}, "
- f"action: {caveman_maintenance['plannedAction']}, "
- f"pinned: {caveman_maintenance['pinnedRef']}"
- )
- print_caveman_maintenance_details(cast(dict[str, object], caveman_maintenance))
- bundled_migration_plan = payload.get("bundledMigration")
- if bundled_migration_plan:
- print("\nBundled Skill rename migration:")
- print(f"- status: {bundled_migration_plan['status']}")
- if bundled_migration_plan.get("targetDir"):
- print(f"- target skills dir: {bundled_migration_plan['targetDir']}")
- if bundled_migration_plan.get("reason"):
- print(f"- reason: {bundled_migration_plan['reason']}")
- for item in bundled_migration_plan.get("migrations") or []:
- if item.get("legacyTargets"):
- print(
- "- remove legacy: "
- + ", ".join(str(path) for path in item["legacyTargets"])
- )
- for item in bundled_migration_plan.get("conflicts") or []:
- print(
- "- legacy identity conflict: "
- f"{item['path']} (expected {item['expectedName']}, "
- f"got {item.get('actualName') or '<missing>'})"
- )
- external_migration_plan = payload.get("externalMigration")
- if external_migration_plan:
- print("\nExternal mattpocock migration:")
- print(f"- status: {external_migration_plan['status']}")
- if external_migration_plan.get("targetDir"):
- print(f"- target skills dir: {external_migration_plan['targetDir']}")
- if external_migration_plan.get("reason"):
- print(f"- reason: {external_migration_plan['reason']}")
- if external_migration_plan.get("detectedLegacy"):
- print(
- "- detected legacy: "
- + ", ".join(
- str(name) for name in external_migration_plan["detectedLegacy"]
- )
- )
- if external_migration_plan.get("detectedCanonical"):
- print(
- "- detected canonical: "
- + ", ".join(
- str(name) for name in external_migration_plan["detectedCanonical"]
- )
- )
- if external_migration_plan.get("requiredCanonical"):
- print(
- "- required canonical: "
- + ", ".join(
- str(name) for name in external_migration_plan["requiredCanonical"]
- )
- )
- if external_migration_plan.get("removeLegacy"):
- print(
- "- remove legacy: "
- + ", ".join(
- str(name) for name in external_migration_plan["removeLegacy"]
- )
- )
- sbtd_init_plan = payload.get("sbtdInit")
- if sbtd_init_plan:
- print_sbtd_project_setup_report(cast(dict[str, object], sbtd_init_plan))
- def operation_allows_existing_target(operation: Operation) -> bool:
- return operation.kind == "ensure-file-block"
- def operation_result(
- operation: Operation,
- status: str,
- action: str,
- *,
- backup: Path | None = None,
- reason: str | None = None,
- ) -> dict[str, object]:
- result: dict[str, object] = {
- "label": operation.label,
- "target": str(operation.target),
- "kind": operation.kind,
- "status": status,
- "action": action,
- }
- if backup:
- result["backup"] = str(backup)
- if reason:
- result["reason"] = reason
- return result
- def print_operation_report(
- results: list[dict[str, object]], heading: str = "Operation report"
- ) -> None:
- print(f"\n{heading}:")
- if not results:
- print("- none")
- return
- for item in results:
- print(f"- {item['label']}: {item['status']}")
- print(f" target: {item['target']}")
- print(f" action: {item['action']}")
- if item.get("backup"):
- print(f" backup: {item['backup']}")
- if item.get("reason"):
- print(f" reason: {item['reason']}")
- def print_external_migration_report(results: list[dict[str, object]]) -> None:
- print("\nExternal mattpocock migration report:")
- if not results:
- print("- none")
- return
- for item in results:
- label = item.get("name") or item.get("repo") or "migration"
- print(f"- {label}: {item['status']}")
- if item.get("phase"):
- print(f" phase: {item['phase']}")
- if item.get("target"):
- print(f" target: {item['target']}")
- if item.get("backup"):
- print(f" backup: {item['backup']}")
- if item.get("error"):
- print(f" error: {item['error']}")
- if item.get("reason"):
- print(f" reason: {item['reason']}")
- def ensure_confirmed(args: argparse.Namespace, mode: str) -> None:
- if mode == "plan":
- return
- if not args.yes:
- raise SystemExit(
- "Refusing to change files without --yes. Run plan first, then rerun with --yes."
- )
- def run(mode: str, args: argparse.Namespace) -> int:
- # One process may run several modes; a note left by an earlier run would
- # make a later one report checks it never skipped.
- UNVERIFIED_CHECKS.clear()
- if mode == "upgrade":
- from sbtd_upgrade_cli import run_upgrade
- return run_upgrade(args)
- if mode == "recovery" and (
- getattr(args, "upgrade_plan", None) is not None
- or getattr(args, "upgrade_recovery_plan", None) is not None
- ):
- from sbtd_upgrade_cli import run_upgrade_recovery
- return run_upgrade_recovery(args)
- if mode == "migration":
- try:
- from sbtd_migration import run_migration
- except ImportError:
- reason = "the installed migration runtime or its declared dependencies are unavailable"
- response = {
- "mode": "migration",
- "phase": args.phase,
- "status": "blocked",
- "manifest_id": None,
- "verification_id": None,
- "projects": [],
- "reason": reason,
- "nextStep": "Restore the complete installed Skill and its declared dependencies before retrying.",
- "migration": {},
- }
- if args.json:
- print(json.dumps(response, ensure_ascii=False, allow_nan=False))
- else:
- print(f"Migration {args.phase}: blocked")
- print(reason)
- print(response["nextStep"])
- return 2
- return run_migration(args)
- if mode == "recovery":
- from sbtd_recovery import run_recovery
- return run_recovery(args)
- if mode == "cleanup-legacy":
- from sbtd_cleanup_legacy import run_cleanup_legacy
- return run_cleanup_legacy(args)
- if mode in {"init", "init-projects"} and getattr(args, "migration_manifest", None):
- from sbtd_graft_deployment import run_migration_init
- return run_migration_init(mode, args)
- if mode == "check":
- results = build_check_results(args)
- if (
- getattr(args, "platform", None) in {"codex", "omp", "oh-my-pi"}
- or getattr(args, "graft_hooks", False)
- or getattr(args, "graft_retire_legacy", False)
- or getattr(args, "graft_legacy_bindings", None)
- ):
- from sbtd_graft_deployment import plan_normal_wiring
- results["graftWiring"] = plan_normal_wiring(
- mode, args,
- installation_targets=[
- op.target for op in build_operations(mode, args) if not op.same_location
- ],
- )
- developer_plan = build_developer_plan(args)
- if developer_plan is not None:
- results["developerPlan"] = developer_plan
- print_check_results(results, args.json)
- if cast(dict[str, object], results.get("graftWiring", {})).get("status") == "blocked":
- return 2
- if developer_plan is not None:
- if not args.json:
- print_developer_plan(developer_plan)
- developer_exit = developer_plan_exit_code(developer_plan)
- if developer_exit:
- print(
- "Developer identity preflight failed: resolve each "
- "conflicting or blocked project, or pass an explicit "
- "--projects-root.",
- file=sys.stderr,
- )
- return developer_exit
- provider = cast(dict[str, object], results["ponytailProvider"])
- if provider["provider"] == "conflict":
- print(
- "Ponytail provider conflict: the official Ponytail plugin is "
- "enabled; disable or remove it before using Onboard stable Skills.",
- file=sys.stderr,
- )
- return 4
- projects = cast(list[dict[str, object]], results["projectChecks"])
- return project_status_exit_code(
- aggregate_project_status(
- [cast(dict[str, object], item["sbtd"]) for item in projects]
- )
- )
- if mode == "check-projects":
- results = build_projects_check_results(args)
- print_projects_check_results(results, args.json)
- projects = cast(list[dict[str, object]], results["projects"])
- return project_status_exit_code(
- aggregate_project_status(
- [cast(dict[str, object], item["sbtd"]) for item in projects]
- )
- )
- if mode == "check-agent-cli":
- print_agent_cli_check(check_agent_cli(args.platform), args.json)
- return 0
- if mode == "ensure-npm":
- return ensure_npm(args)
- if mode == "install-agent-cli":
- return install_agent_cli(args)
- if mode == "install-rtk":
- return install_rtk(args)
- if mode == "install-graft":
- payload, code = install_graft(
- confirmed=bool(args.yes),
- telemetry_only=bool(args.telemetry_only),
- )
- if args.json:
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- else:
- print("Graft installation:")
- print(json.dumps(payload, indent=2, ensure_ascii=False))
- return code
- if mode == "install-caveman":
- return install_caveman(args)
- if mode == "install-java":
- return install_java(args)
- if mode == "install-maestro":
- return install_maestro(args)
- if mode == "install-playwright-cli":
- return install_playwright_cli(args)
- if mode == "install-external-skills":
- return install_external_skills(args)
- if mode == "migrate-external-skills":
- return migrate_external_skills(args)
- if mode == "promote-external-skills-stable":
- return promote_external_skills_stable(args)
- if mode in {"init", "reset"} and not args.json:
- print_check_results(build_check_results(args), False)
- print("")
- global_skills_dir, global_skills_dir_source = resolve_global_skills_dir(
- getattr(args, "global_skills_dir", None)
- )
- operations = build_operations(mode, args)
- bundled_migration_plan = build_bundled_skill_migration_plan(mode, args)
- external_migration_plan = (
- {
- "mode": "mattpocock-external-migration",
- "status": "skipped",
- "reason": "init-projects does not inspect or modify global skills.",
- }
- if mode == "init-projects"
- else build_external_migration_plan(args)
- )
- plan_payload = build_plan_payload(
- mode,
- operations,
- bundled_migration_plan,
- external_migration_plan,
- global_skills_dir,
- global_skills_dir_source,
- build_sbtd_project_setup(mode, args),
- )
- from sbtd_graft_deployment import plan_normal_wiring
- wiring_plan = plan_normal_wiring(
- mode, args,
- installation_targets=[op.target for op in operations if not op.same_location],
- )
- if wiring_plan["status"] != "skipped":
- plan_payload["graftWiring"] = wiring_plan
- developer_plan = build_developer_plan(args)
- if developer_plan is not None:
- plan_payload["developerPlan"] = developer_plan
- if mode in {"init", "reset"}:
- plan_payload["requiredExternalInstall"] = None
- plan_json_emitted = False
- def emit_plan_json() -> None:
- """Release the held-back plan as this run's single `--json` document.
- Write modes fold the plan into one merged document at the end of the
- run, so any path that returns before that has to emit the plan itself
- or `--json` would leave stdout empty.
- """
- nonlocal plan_json_emitted
- if args.json and not plan_json_emitted:
- plan_json_emitted = True
- print(json.dumps(plan_payload, indent=2, ensure_ascii=False))
- if not args.json:
- print_plan(plan_payload)
- if developer_plan is not None:
- print_developer_plan(developer_plan)
- if mode == "plan":
- emit_plan_json()
- if wiring_plan["status"] == "blocked":
- return 2
- if developer_plan is not None:
- return developer_plan_exit_code(developer_plan)
- return 0
- ensure_confirmed(args, mode)
- if wiring_plan["status"] == "blocked":
- emit_plan_json()
- return 2
- if developer_plan is not None:
- # Whole-batch identity preflight before any global or project
- # mutation: a conflict or unknown checkout anywhere stops the run
- # before the first project is written.
- developer_exit = developer_plan_exit_code(developer_plan)
- if developer_exit:
- print(
- "Developer identity preflight failed; no files were changed.",
- file=sys.stderr,
- )
- plan_payload["backups"] = []
- emit_plan_json()
- return developer_exit
- sbtd_preflight = cast(dict[str, object], plan_payload["sbtdInit"])
- preflight_exit = project_status_exit_code(sbtd_preflight["status"])
- if preflight_exit:
- plan_payload["sbtdProjectSetup"] = sbtd_preflight
- plan_payload["backups"] = []
- emit_plan_json()
- return preflight_exit
- if bundled_migration_plan.get("status") == "blocked":
- print(
- "Bundled Skill rename migration blocked: legacy Skill identity "
- "does not match the configured legacy name.",
- file=sys.stderr,
- )
- emit_plan_json()
- return 4
- external_identity_failures = (
- external_migration_identity_failures(external_migration_plan)
- if external_migration_plan.get("status") == "planned"
- else []
- )
- if external_identity_failures:
- print(
- "External mattpocock migration blocked: legacy Skill identity "
- "does not match the configured legacy name.",
- file=sys.stderr,
- )
- for item in external_identity_failures:
- label = item.get("name") or item.get("repo") or "migration"
- print(f"- {label}: {item.get('error', 'unknown failure')}", file=sys.stderr)
- emit_plan_json()
- return 4
- if mode in {"init", "reset"}:
- ponytail_provider = detect_ponytail_provider(global_skills_dir)
- if ponytail_provider["provider"] == "conflict":
- print(
- "Ponytail provider conflict: the official Ponytail plugin is "
- "enabled; disable or remove it before init/reset writes Onboard "
- "stable Skills.",
- file=sys.stderr,
- )
- emit_plan_json()
- return 4
- from sbtd_graft_deployment import legacy_bindings_unchanged
- if not legacy_bindings_unchanged(wiring_plan):
- plan_payload["graftWiring"] = {
- **wiring_plan,
- "status": "blocked",
- "reason": "the approved legacy bindings changed before installation",
- }
- plan_payload["backups"] = []
- emit_plan_json()
- print("Legacy binding approval changed; no installation writes were performed.", file=sys.stderr)
- return 2
- external_install = install_required_external_skills(
- args, overwrite=mode == "reset"
- )
- plan_payload["requiredExternalInstall"] = external_install
- if (
- external_install is not None
- and cast(dict[str, object], external_install["transaction"])["status"]
- != "committed"
- ):
- print(
- "Required global external Skill installation failed.", file=sys.stderr
- )
- emit_plan_json()
- return 4
- active_operations = [op for op in operations if not op.same_location]
- conflicts = [
- op
- for op in active_operations
- if op.target.exists() and not operation_allows_existing_target(op)
- ]
- backups: list[tuple[Path, Path]] = []
- backup_by_target: dict[Path, Path] = {}
- backed_up: set[Path] = set()
- for op in conflicts:
- if op.kind != "file":
- continue
- target = op.target.resolve()
- if target in backed_up or not op.target.exists():
- continue
- backup = backup_path(op.target)
- op.target.parent.mkdir(parents=True, exist_ok=True)
- shutil.move(str(op.target), str(backup))
- backups.append((op.target, backup))
- backup_by_target[op.target] = backup
- backup_by_target[target] = backup
- backed_up.add(target)
- operation_results: list[dict[str, object]] = []
- for op in active_operations:
- try:
- action = copy_operation(op)
- failures = verify_operation(op)
- if failures:
- operation_results.append(
- operation_result(
- op,
- "failed",
- action,
- backup=backup_by_target.get(op.target),
- reason="verification failed: " + ", ".join(failures[:20]),
- )
- )
- continue
- status = "skipped" if action.startswith("skipped") else "success"
- operation_results.append(
- operation_result(
- op,
- status,
- action,
- backup=backup_by_target.get(op.target),
- )
- )
- except Exception as exc: # noqa: BLE001 - report each file operation failure with context.
- operation_results.append(
- operation_result(
- op,
- "failed",
- "error",
- backup=backup_by_target.get(op.target),
- reason=str(exc),
- )
- )
- failed_operations = [
- item for item in operation_results if item["status"] == "failed"
- ]
- if backups and not args.json:
- # `--json` keeps stdout to a single document, and that document carries
- # `backups`, so the prose list would only corrupt the payload here.
- print("Backups:")
- for original, backup in backups:
- print(f"- {original} -> {backup}")
- if not args.json:
- print_operation_report(operation_results)
- if failed_operations:
- print("Verification failed:", file=sys.stderr)
- for item in failed_operations:
- print(
- f"- {item['label']}: {item.get('reason', 'unknown failure')}",
- file=sys.stderr,
- )
- emit_plan_json()
- return 3
- if developer_plan is not None:
- # Capture completed writes before identity work: its failure must not
- # leave automation with a plan that hides already-applied changes.
- plan_payload["operationResults"] = operation_results
- identity_roots = [
- Path(str(entry["projectRoot"]))
- for entry in cast(list[dict[str, object]], developer_plan["projects"])
- ]
- developer_plan = ensure_developer_identities(developer_plan)
- plan_payload["developerPlan"] = developer_plan
- if not args.json:
- print_developer_plan(developer_plan)
- developer_exit = developer_plan_exit_code(developer_plan)
- if developer_exit:
- plan_payload["sbtdProjectSetup"] = build_sbtd_project_setup(
- mode, args, project_roots=identity_roots
- )
- plan_payload["unverifiedChecks"] = list(UNVERIFIED_CHECKS)
- print(
- "Developer identity initialization failed; completed project "
- "writes are kept and reported.",
- file=sys.stderr,
- )
- plan_payload["backups"] = [
- {"target": str(target), "backup": str(backup)}
- for target, backup in backups
- ]
- emit_plan_json()
- return developer_exit
- bundled_migration_results = run_bundled_skill_migration(bundled_migration_plan)
- failed_bundled_migrations = [
- item for item in bundled_migration_results if item["status"] == "failed"
- ]
- if not args.json:
- print_bundled_skill_migration_report(bundled_migration_results)
- if failed_bundled_migrations:
- print("Bundled Skill rename migration failed:", file=sys.stderr)
- for item in failed_bundled_migrations:
- print(
- f"- {item['name']}: {item.get('error', 'unknown failure')}",
- file=sys.stderr,
- )
- emit_plan_json()
- return 4
- migration_results = run_external_migration(external_migration_plan)
- failed_migrations = [
- item for item in migration_results if item["status"] == "failed"
- ]
- if not args.json:
- print_external_migration_report(migration_results)
- if failed_migrations:
- print("External mattpocock migration failed:", file=sys.stderr)
- for item in failed_migrations:
- label = item.get("name") or item.get("repo") or "migration"
- print(f"- {label}: {item.get('error', 'unknown failure')}", file=sys.stderr)
- emit_plan_json()
- return 4
- caveman_maintenance: dict[str, object] = {
- "status": "skipped",
- "scope": "workflow-skill-payload-only",
- }
- if mode in {"init", "reset"}:
- try:
- caveman_maintenance = maintain_caveman_payload(global_skills_dir)
- except Exception as exc: # noqa: BLE001 - optional payload maintenance must not abort init/reset.
- caveman_maintenance = {
- "state": "abnormal",
- "plannedAction": "repair",
- "pinnedRef": CAVEMAN_PINNED_REF,
- "pinnedRevision": CAVEMAN_PINNED_REVISION,
- "scope": "workflow-skill-payload-only",
- "status": "failed",
- "error": str(exc),
- }
- if not args.json:
- print("\nCaveman maintenance:")
- print(
- f"- state: {caveman_maintenance['state']}, "
- f"action: {caveman_maintenance['plannedAction']}, "
- f"status: {caveman_maintenance['status']}"
- )
- print_caveman_maintenance_details(caveman_maintenance)
- sbtd_report = build_sbtd_project_setup(mode, args)
- from sbtd_graft_deployment import execute_normal_wiring
- wiring_result, wiring_exit = execute_normal_wiring(
- wiring_plan, template_written=not bool(getattr(args, "skip_project_agents", False)),
- )
- language_tooling = run_language_tooling_step(mode, args)
- if language_tooling is not None:
- plan_payload["languageTooling"] = language_tooling
- if wiring_plan["status"] != "skipped":
- plan_payload["graftWiring"] = wiring_result
- plan_payload["operationResults"] = operation_results
- if wiring_exit:
- wiring_status = "blocked" if wiring_exit == 2 else "failed"
- for project in cast(list[dict[str, object]], sbtd_report["projects"]):
- project.update(status=wiring_status, reason="host wiring did not complete", nextStep="Inspect the preserved wiring results and originals.")
- sbtd_report["status"] = wiring_status
- if args.json:
- # One run, one root object. The plan was held back above so it can be
- # merged here; flushing it earlier made stdout two concatenated
- # documents, which `json.loads` rejects on every successful write mode.
- #
- # The plan keys stay at the root so `mode` sits in the same place for
- # every mode -- `plan` and the check modes already answer there, and
- # nesting only write modes would make `--json` a different contract
- # depending on which mode produced it.
- plan_json_emitted = True
- print(
- json.dumps(
- {
- **plan_payload,
- "backups": [
- {"target": str(target), "backup": str(backup)}
- for target, backup in backups
- ],
- "sbtdProjectSetup": sbtd_report,
- "cavemanMaintenance": caveman_maintenance,
- "unverifiedChecks": list(UNVERIFIED_CHECKS),
- },
- indent=2,
- ensure_ascii=False,
- )
- )
- else:
- print_sbtd_project_setup_report(sbtd_report)
- if wiring_plan["status"] != "skipped":
- print("Host wiring: " + str(wiring_result["status"]))
- if wiring_result.get("hooks") == "configured-needs-host-trust":
- print("Hooks configured only: enable supported Codex hooks and trust their exact hashes in the host before use.")
- print("Host-event acceptance is separate from file and graph verification.")
- if language_tooling is not None:
- print_language_tooling(language_tooling)
- if wiring_exit:
- return wiring_exit
- setup_exit = project_status_exit_code(sbtd_report["status"])
- if setup_exit:
- return setup_exit
- if not args.json:
- # `--json` promises one machine-readable document on stdout. Each note
- # already went to stderr when it was recorded, and the JSON document
- # carries `unverifiedChecks`, so nothing is lost by staying quiet here.
- if UNVERIFIED_CHECKS:
- print("Verification passed, except for checks that could not be evaluated:")
- for item in UNVERIFIED_CHECKS:
- print(f"- {item}")
- else:
- print("Verification passed.")
- if mode == "init-projects":
- print_projects_check_results(build_projects_check_results(args), False)
- else:
- final_check = build_check_results(args)
- print_installation_report(
- final_check["installationReport"], "Final installation report"
- )
- return 0
- def build_parser() -> argparse.ArgumentParser:
- parser = WorkflowArgumentParser(
- description="Install or reset SBTD workflow AGENTS and skills."
- )
- subparsers = parser.add_subparsers(dest="mode", required=True)
- add_migration_parser(subparsers)
- add_recovery_parser(subparsers)
- add_cleanup_legacy_parser(subparsers)
- add_upgrade_parser(subparsers)
- for mode in ("check", "plan", "init", "reset", "init-projects"):
- sub = subparsers.add_parser(mode)
- if mode in {"init", "init-projects"}:
- _add_migration_context(sub)
- sub.add_argument(
- "--language-tooling",
- action="store_true",
- help="Apply the displayed omp LSP/ast-grep configuration writes after user confirmation; without it they are reported and skipped.",
- )
- sub.add_argument("--graft-hooks", action="store_true", help="Separately authorize the displayed Codex hooks; does not grant host trust.")
- sub.add_argument(
- "--no-mcp", action="store_true",
- help="Skip user-level Graft MCP wiring; selected project graph setup remains local.",
- )
- sub.add_argument(
- "--graft-retire-legacy",
- action="store_true",
- help="Explicitly replace exact owned fixed-project MCP entries for the selected roots; retain originals. Does not authorize environment or backup deletion.",
- )
- sub.add_argument(
- "--graft-legacy-bindings",
- action=SingleValueAction,
- help="Private version-1 JSON contract naming observed old runtime paths for --graft-retire-legacy across runtime changes.",
- )
- sub.add_argument(
- "--projects-root",
- required=mode == "init-projects",
- help="Comma-separated absolute project root paths.",
- )
- sub.add_argument(
- "--developer",
- action=SingleValueAction,
- type=validate_developer_name,
- help="Developer identity name (lowercase letters and digits) "
- "applied only to the explicitly listed --projects-root projects.",
- )
- sub.add_argument(
- "--skip-project-agents",
- action="store_true",
- help="Skip the project AGENTS template; explicitly selected Graft wiring still maintains its managed fence.",
- )
- sub.add_argument(
- "--global-agents-path", help="Override Codex global AGENTS.md path."
- )
- sub.add_argument(
- "--global-skills-dir", help="Override global skills directory."
- )
- sub.add_argument(
- "--yes", action="store_true", help="Allow init/reset to write files."
- )
- sub.add_argument(
- "--json", action="store_true", help="Print machine-readable plan."
- )
- sub.add_argument(
- "--platform",
- help="Target Agent platform: codex, claude, kimi, oh-my-pi, or omp.",
- )
- project_check = subparsers.add_parser("check-projects")
- project_check.add_argument(
- "--projects-root",
- required=True,
- help="Comma-separated absolute project root paths.",
- )
- project_check.add_argument(
- "--json", action="store_true", help="Print machine-readable project checks."
- )
- project_check.add_argument(
- "--skip-project-agents",
- action="store_true",
- help="Exclude project AGENTS.md from installation-target checks.",
- )
- graft_install = subparsers.add_parser("install-graft")
- graft_install.add_argument(
- "--yes", action="store_true",
- help="Confirm the pinned global package/native-script and telemetry-disable plan.",
- )
- graft_install.add_argument(
- "--telemetry-only", action="store_true",
- help="Persist only telemetry opt-out; refuse package installation if the verified CLI is no longer present.",
- )
- graft_install.add_argument(
- "--json", action="store_true", help="Print one machine-readable installation result."
- )
- install = subparsers.add_parser("install-external-skills")
- install.add_argument(
- "--skills",
- help="Comma-separated external skill names to install. Use 'all' for every known external skill.",
- )
- install.add_argument(
- "--all",
- action="store_true",
- help="Install every known external referenced skill.",
- )
- install.add_argument(
- "--scope",
- choices=("global",),
- default="global",
- help="Install into the global skills directory.",
- )
- install.add_argument(
- "--source",
- choices=("auto", "upstream", "stable"),
- default="auto",
- help=(
- "External Skill source policy: auto and stable use the vendored stable set; "
- "upstream is an explicit opt-in with no fallback."
- ),
- )
- install.add_argument(
- "--global-skills-dir", help="Override global skills directory."
- )
- install.add_argument(
- "--replace",
- action="store_true",
- help="Compatibility flag; replacement now uses a temporary transactional rollback backup.",
- )
- install.add_argument(
- "--yes", action="store_true", help="Allow external skill installation."
- )
- install.add_argument(
- "--json", action="store_true", help="Print machine-readable plan and results."
- )
- migrate = subparsers.add_parser("migrate-external-skills")
- migrate.add_argument(
- "--scope",
- choices=("global",),
- default="global",
- help="Migrate legacy external Skills in the global skills directory.",
- )
- migrate.add_argument(
- "--source",
- choices=("auto", "upstream", "stable"),
- default="auto",
- help=(
- "Canonical replacement source: auto and stable use the vendored stable "
- "set; upstream is an explicit opt-in with no fallback."
- ),
- )
- migrate.add_argument(
- "--global-skills-dir", help="Override global skills directory."
- )
- migrate.add_argument(
- "--yes", action="store_true", help="Allow external Skill migration."
- )
- migrate.add_argument(
- "--json", action="store_true", help="Print machine-readable migration results."
- )
- promote = subparsers.add_parser("promote-external-skills-stable")
- promote.add_argument(
- "--repository",
- required=True,
- help="Repository id from the stable External Skills manifest, or the new id for first-time registration.",
- )
- promote.add_argument(
- "--repo",
- help=(
- "Upstream HTTPS repository URL. Required for first-time repository "
- "registration; afterwards it may only repeat the manifest URL."
- ),
- )
- promote.add_argument(
- "--revision",
- required=True,
- help="Full 40-character lowercase upstream commit SHA to promote.",
- )
- promote.add_argument(
- "--stable-set",
- required=True,
- help="New Onboard stable set identifier, for example 2026-07-11.2.",
- )
- promote.add_argument(
- "--license",
- help="SPDX license id; required only for first-time repository registration.",
- )
- promote.add_argument(
- "--license-file",
- dest="license_files",
- action="append",
- help=(
- "License mapping SOURCE=STABLE_PATH, repeatable; required only for "
- "first-time repository registration."
- ),
- )
- promote.add_argument(
- "--yes", action="store_true", help="Allow stable snapshot replacement."
- )
- promote.add_argument(
- "--json", action="store_true", help="Print machine-readable plan and results."
- )
- npm = subparsers.add_parser("ensure-npm")
- npm.add_argument(
- "--yes",
- action="store_true",
- help="Install nvm and Node.js LTS when npm is missing.",
- )
- npm.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- agent_check = subparsers.add_parser("check-agent-cli")
- agent_check.add_argument(
- "--platform",
- required=True,
- help="Target Agent platform: codex, claude, kimi, oh-my-pi, or omp.",
- )
- agent_check.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- agent_install = subparsers.add_parser("install-agent-cli")
- agent_install.add_argument(
- "--platform",
- required=True,
- help="Target Agent platform: codex, claude, kimi, oh-my-pi, or omp.",
- )
- agent_install.add_argument(
- "--yes",
- action="store_true",
- help="Install the target Agent CLI globally from its official npm package after user confirmation.",
- )
- agent_install.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- rtk = subparsers.add_parser("install-rtk")
- rtk.add_argument(
- "--yes", action="store_true", help="Install rtk-ai/rtk when missing."
- )
- rtk.add_argument(
- "--replace-wrong",
- action="store_true",
- help="If an existing rtk command fails `rtk gain`, allow replacing it after user confirmation.",
- )
- rtk.add_argument(
- "--reinstall",
- action="store_true",
- help="Reinstall when rtk exists but `rtk gain` verification fails.",
- )
- rtk.add_argument(
- "--profile", help="Shell profile file to update with ~/.local/bin PATH."
- )
- rtk.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- caveman = subparsers.add_parser("install-caveman")
- caveman.add_argument(
- "--agent",
- default="codex",
- help="Retained for compatibility; the official caveman installer selects the platform-specific install path.",
- )
- caveman.add_argument(
- "--global-skills-dir",
- help="Override global skills directory used for post-install verification.",
- )
- caveman.add_argument(
- "--yes",
- action="store_true",
- help="Install the caveman Codex skill after user confirmation.",
- )
- caveman.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- java = subparsers.add_parser("install-java")
- java.add_argument(
- "--major",
- type=int,
- default=21,
- help="Temurin JDK major version to install. Must be 17 or higher; defaults to 21.",
- )
- java.add_argument(
- "--install-root",
- help="Directory that should contain the extracted Temurin JDK.",
- )
- java.add_argument(
- "--profile", help="Shell profile file to update with JAVA_HOME and PATH."
- )
- java.add_argument(
- "--force",
- action="store_true",
- help="Install even when an existing Java 17+ runtime is already available.",
- )
- java.add_argument(
- "--yes",
- action="store_true",
- help="Download and install the selected Temurin JDK after user confirmation.",
- )
- java.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- maestro = subparsers.add_parser("install-maestro")
- maestro.add_argument(
- "--profile", help="Shell profile file to update with ~/.maestro/bin PATH."
- )
- maestro.add_argument(
- "--reinstall",
- action="store_true",
- help="Run the official installer even when a maestro command already exists but fails verification.",
- )
- maestro.add_argument(
- "--yes",
- action="store_true",
- help="Run the official Maestro installer after user confirmation.",
- )
- maestro.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- playwright = subparsers.add_parser("install-playwright-cli")
- playwright.add_argument(
- "--project-root",
- required=True,
- help="Target project root where package.json exists.",
- )
- playwright.add_argument(
- "--reinstall",
- action="store_true",
- help="Run npm install even when Playwright project markers already exist.",
- )
- playwright.add_argument(
- "--skip-browsers",
- action="store_true",
- help="Install @playwright/test but skip `npx playwright install`.",
- )
- playwright.add_argument(
- "--yes",
- action="store_true",
- help="Install Playwright into the target project after user confirmation.",
- )
- playwright.add_argument(
- "--json", action="store_true", help="Print machine-readable results."
- )
- return parser
- def main() -> int:
- parser = build_parser()
- args = parser.parse_args()
- if args.mode == "migration":
- validate_migration_args(args, parser=parser)
- elif args.mode == "recovery":
- validate_recovery_args(args, parser=parser)
- elif args.mode == "cleanup-legacy":
- validate_cleanup_legacy_args(args, parser=parser)
- elif args.mode == "upgrade":
- validate_upgrade_args(args, parser=parser)
- elif args.mode in {"init", "init-projects"}:
- _check_migration_context(parser, args)
- return run(args.mode, args)
- if __name__ == "__main__":
- raise SystemExit(main())
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.