diff --git a/.claude/skills/devstack-config/SKILL.md b/.claude/skills/devstack-config/SKILL.md deleted file mode 100644 index aae5629a..00000000 --- a/.claude/skills/devstack-config/SKILL.md +++ /dev/null @@ -1,172 +0,0 @@ ---- -name: devstack-config -description: "Edits this repository's devstack stack file (devstack.toml): adding or changing a service, a Compose group, a command or a group; watch paths, health checks, background workers, promotion holds, environment from Compose, placeholders. Validates every change with `devstack check` and knows that a running daemon does not reload the file. Use it whenever devstack.toml is created or touched, e.g. \"add the worker to devstack\", \"devstack should restart X when Y changes\", \"add a seed command\", \"the service needs variable Z\", \"why does the candidate not switch\", \"set up devstack for this repo\". For running the stack, use the skill `devstack`." ---- - - - -# devstack-config: change the stack file - -The reference for every key is **[docs/stack-file.md](https://github.com/nuetzliches/devstack/blob/v0.31.0/docs/stack-file.md)** -(this skill names the rules that are easy to get wrong; the reference has the -details). A complete example: [examples/devstack.toml](https://github.com/nuetzliches/devstack/blob/main/examples/devstack.toml). - -## Workflow - -1. Read the current `devstack.toml` and, for the part you change, the - matching section of the reference. -2. Change the file. Keep its order and comment style; say *why* in a comment - when a value is not obvious (a timeout, an ignored variable, a hold). -3. `devstack check` (and `devstack check --compose` when a Compose group, a - `compose = {…}` reference or an env file changed). Fix until it is clean; - it reports every problem at once. -4. If you used a key newer than `[stack] requires`, raise `requires`. -5. A running daemon does **not** reload the file. Tell the user it applies with - `devstack down` + `devstack up`, and ask before restarting a stack others may - be using. `devstack status` shows "the stack file changed" until then. -6. After the restart, verify the change itself (`devstack status`, the service's - log, the health URL), not only that the stack came up. - -`devstack schema` prints the JSON Schema of the file for editors. A repository -without a stack file starts from `devstack init` (a draft with TODOs). - -## Rules that are easy to get wrong - -- **Unknown keys are errors.** No key is ignored silently; read the error, do - not work around it. -- **`watch` vs `restart_on`.** Built services (`build` + `run`) get `watch`: a - change becomes a candidate that replaces the running instance once healthy. - Dev servers (`kind = "devserver"`) reload themselves and get `restart_on` - only for files their hot reload ignores (`tsconfig.json`, `angular.json`). - In `restart_on` a folder (`src/api`) covers the files in it; in `watch` - write `src/Api/**`, a bare folder matches no file there. A pattern that names only file types (`src/**/*.cs`) misses a folder that is - moved into place; `src/Api/**` sees it. -- **Health should mean ready.** devstack switches traffic to a candidate when - `health` answers 2xx. Point it at a readiness endpoint that checks what the - service needs (its database), not at a bare liveness probe; the timeout covers - a cold start. -- **Background workers run once.** While a candidate starts beside the main - instance, only one of them may run schedulers and queue consumers: put their - switches into `[services..workers] env = { X = "{is_main}" }`, not into - `env`. -- **Lanes have their own containers.** A worktree runs as a lane with its - ports moved (`[lanes] port_step`) and its own Compose project, so its - database is its own and needs no `{lane_suffix}`; services that hold nothing - per lane (a telemetry dashboard, a fake SMTP server) can stay shared: - `[compose.] shared = ["mailbox"]`. A dev server needs `{port}` - (in `run`, or in `env` for a config that reads it) to run in a lane. A - command names a Compose project as `{compose..project}`, never - literally (`docker compose -p {compose.app.project} exec -T db ...`): in a - lane that is the lane's own project, not the main tree's. -- **A lane's worktree has no `node_modules`**: the lane runs from a copy, - where `prepare` installs (`devstack check` warns about a dev server with - a `package.json` and no `prepare`). When git hooks need it (`npx eslint` in a - pre-commit hook), `prepare.link = ["web/node_modules"]` links it into the - worktree; `.gitignore` then needs `node_modules` without a trailing slash. - The linked directory is the lane's copy: reinstalling or deleting it in - the worktree empties what the lane runs from (say so in project notes - that tell agents to run `npm ci`). - Name what it makes as `outputs = ["web/node_modules"]` (and `version = - "node --version"`): the next lane with the same lockfile copies it from - the machine's store instead of running `npm ci` again. `link` must be - one of `outputs` then; add `requires = "0.23.0"` to `[stack]`. To have the - main branch's lockfile prepared before the first lane needs it, add - `[prepare] warm = ["origin/main"]` (devstack never fetches; it watches the - ref) and `requires = "0.24.0"`. -- **Lanes on other machines** (`devstack up --on `) run in a Linux - container: `[lanes] image` (a toolchain image) or `[lanes] dockerfile`. Files - git ignores do not go there unless `[lanes] sync` names them (a dev - certificate); `prepare` installs what the copy lacks (`npm ci`). - `[lanes] share` says whom such a lane is shared with by default. The pool - places a lane by what its runs took there (ADR-0049); `[lanes.need]` - (`cpus`, `memory = "6G"`, `disk = "25G"`, `gpus = { count, memory }`) is a - floor only: set it where the first runs would be placed too small, or for - a GPU. A profile's `need` raises it for that profile. -- **Agent skills go where the repository's agents look.** `[agents] skills` - names the folders `devstack skills install` writes to: `.claude/skills` - (Claude Code, the default), `.agents/skills` (Codex, Gemini CLI and most - others); both only when both kinds of agents work here, since an agent - that reads both sees each skill twice. -- **A purpose gets a profile, not a second stack file** (ADR-0041). - `[profiles.]` changes how the stack runs for an acceptance run or a - light review: `workers`, `data = "fresh"`, `env` with the tree's - addresses, `autostart`, per service `kind = "static"` with `build` and - `output`, and the suite as `command`. Each profile is checked as the stack - it makes; add `requires = "0.11.0"` to `[stack]`. A light profile for - daily work leaves heavy containers out with `skip` (ADR-0058): - `skip = ["compose.search", "compose.app.scanner", "indexer"]` (a whole - group, a container, a service; `requires = "0.21.0"`). What it skips is - stopped at the start and still starts on demand (`devstack start - compose.app.scanner`); a service that starts and uses a skipped - container's address (`{compose.…}`, `rewrite_hosts`) must be skipped too. -- **Hot reload is opt-in per session.** `[services..hot_reload]` with - the watcher's `run` (`dotnet watch run --non-interactive`) only makes - `devstack hot-reload on` possible; the service still builds by - default. Built services only. -- **Schema changes wait.** Paths that mean "this build needs a migration" go - into `promote = { hold_if_changed = [...] }`; such a candidate waits for - `devstack promote` instead of switching. -- **Environment from Compose.** `compose = { group, service }` gives the native - process the container's environment with host names rewritten - (`rewrite_hosts`). When the Compose service describes a *deployment* rather - than this dev process, use `inherit = false` with an `ignore` list: then - `devstack check --compose` reports every new variable of the deployment the - stack file does not handle. -- **Ports.** `port` is the fixed port users and other services see. Behind the - proxy the process listens on `{port}` (an internal one), so its listen address - must come from `{port}`, never from the fixed number. -- **Container links** in the dashboard default to `http://localhost:` per - published port; set `urls = { = "https://localhost:9443/ui" }` (or - `""` for none) in the Compose group where that is wrong. -- **Main ports for containers.** `promote --lane` moves the fixed ports of - `[services.*]` only, unless the Compose group names containers in - `main_ports = ["web", "api"]`: devstack then holds their published TCP - ports and points them at the lane. Name what the developer reaches directly - from the host (UI, the API the browser calls), not what those use. -- **Ports a server announces** (a WebRTC media server's ICE candidates, a - broker's advertised listeners) go into the Compose group's - `announced_ports = ["media:7881", "media:7882/udp"]`, each published 1:1 - (`7881:7881`). A lane then moves them inside the container too, and - Compose (and every `exec` step) gets `DEVSTACK_PORT_MEDIA_7881` with this - tree's number: pass it to the server's listen and announce settings with - the files' port as default (`${DEVSTACK_PORT_MEDIA_7881:-7881}`); keep - `ports` literal. Without the key, a lane's server announces the main - tree's port. Add `requires = "0.20.0"` to `[stack]`. -- **A per-lane value in a container** (a login cookie's name, which the - browser shares between the main tree and every lane on `localhost`): every - `docker compose` call (and every `exec` step) gets `DEVSTACK_LANE` - (`main` in the main tree) and `DEVSTACK_LANE_SUFFIX` (empty there, - `_` in a lane). Read them in the Compose file with a default - (`REFRESH_COOKIE: app_refresh${DEVSTACK_LANE_SUFFIX:-}`), never from - `COMPOSE_PROJECT_NAME`. For a native service use `{lane_suffix}` in its - `env`. Both give a lane on a pool node its own name too. -- **A container as a service** (`run = "docker run ..."`, for what needs - Linux tools but should get `watch` and candidates) needs three things: a - process in it that ends on `SIGINT` and `SIGTERM` (`docker run --init`, - or an entrypoint that handles them: devstack's graceful stop reaches the - container through the CLI), `--rm`, and a name with - `{lane_suffix}-{port}` so a candidate and the main instance do not - collide. Add `stop = "docker rm -f "`: devstack runs it - whenever an instance ends, also after a crash, so no container is left - holding the port. Add `requires = "0.21.0"` to `[stack]`. -- **Paths** are relative to the repository root; use `{repo}` where a process - needs an absolute one. Generated directories (`bin`, `obj`, `node_modules`, - `target`, `.git`, `.devstack`) never count as changes. Compose files, env - files and `[lanes] dockerfile` must stay inside the repository (no absolute - path, no `..`). -- **Placeholders only where they have a value**: `{port}` needs `port`, - `{artifact}` needs `build`; `build` and `output` know only `{repo}` and - `${VAR}`; `cwd` and `prepare` take none. `devstack check` names each. -- **Jobs end**: a `kind = "job"` counts as failed after 30 minutes unless it - sets `timeout = "…"`; give a long seed or migration one. -- **Commands with side effects** (deleting data, resetting state) get a - `confirm` text. Steps run in order; one action per step. -- **Secrets** do not belong in the stack file. Use `${VAR}` and an env file that - is not committed (`stack.env_files`), with a committed `.env.example` beside it. - -## When the stack file is not enough - -If devstack lacks something this repository needs (a key, a placeholder, a -behaviour), do not bend the file around it: ask the user for permission to open -an issue in `nuetzliches/devstack` (see the skill `devstack`, section 7, and -keep the project's names out of it). diff --git a/.claude/skills/devstack/SKILL.md b/.claude/skills/devstack/SKILL.md deleted file mode 100644 index 57bd06e0..00000000 --- a/.claude/skills/devstack/SKILL.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -name: devstack -description: "Runs and watches this repository's local stack with devstack (devstack.toml): checks that devstack is installed and current, starts and stops the stack, tells whether a code change is live yet, reads logs, promotes or rolls back builds, runs the stack's commands, and reports devstack problems upstream with the user's consent. Use it whenever the local stack, a service, its logs or its dashboard is involved, e.g. \"start the stack\", \"is my change live\", \"the API does not pick up my change\", \"restart the service\", \"show the logs\", \"run the seed\", \"devstack up/status/down\", \"the dev stack does not start\", \"port is taken\", \"Docker is not running\", and whenever a devstack command or its MCP server fails. Not for editing devstack.toml itself (skill `devstack-config`)." ---- - - - -# devstack: run the local stack (devstack) - -devstack runs the stack described in `devstack.toml`: containers from -Compose, native processes built into immutable artifacts, and commands. A saved -code change is built in the background and replaces the running instance only -once it is healthy, so the stack keeps answering while you work. - -## 1. Is devstack installed and current? (check first) - -```bash -devstack --version # this file needs devstack 0.20.0 or newer -devstack doctor # Docker, Compose, the tools this stack runs, ports, hub, PATH -``` - -Missing (`command not found`) or too old: tell the user how to install, do not -install it yourself. - -```powershell -# Windows -irm https://github.com/nuetzliches/devstack/releases/latest/download/install.ps1 | iex -# or, once winget has the release: winget install nuetzliches.devstack -``` - -```bash -# Linux -curl -fsSL https://github.com/nuetzliches/devstack/releases/latest/download/install.sh | sh -``` - -https://nuetzliches.github.io/devstack/ shows the same commands and whether devstack runs on -the user's machine. - -The installer updates in place; a running daemon keeps the old version until -`devstack down` + `devstack up`. A freshly installed devstack may not be on the -PATH of an already running agent process: then use the full path -(`%LOCALAPPDATA%\Programs\devstack\devstack.exe`, `~/.local/bin/devstack`). - -## 2. Operate - -Run from the repository root (devstack looks for `devstack.toml` there; `-f` otherwise). - -| Command | Effect | -| --- | --- | -| `devstack up` | Docker check, infrastructure, jobs, every autostart service; starts the dashboard hub. First run takes minutes (images, builds), later ones well under a minute | -| `devstack status` | state per service (`SERVICE`: the `[services.*]` entries) and per Compose container (`CONTAINER`, by group); `-> not yet active: …` means the latest change is not running yet | -| `devstack logs --follow` | console output, then every new line (`-n 500` for more history, `--grep X` for matching lines only) | -| `devstack logs --grep ` | matching lines of every service's log ("where did this error come from"); with a service only its log | -| `devstack logs --since 2h` | every instance of that time, not only the current one: what a crashed or replaced instance printed (`--build `: that build's log and its instances; `--list`, `--log `) | -| `devstack logs ` | a Compose container's output by its service name (`docker compose logs`, timestamped; `--grep`, `--since 30m`) | -| `devstack builds ` | the service's builds, newest first: live, failed (with the reason), superseded by a newer change, held; answers "did my change ever go live" and "since when is it broken" | -| `devstack hot-reload on\|off` | for a debugging session: the toolchain's watcher (e.g. `dotnet watch`) from the source tree instead of builds and candidates; needs `hot_reload` in the stack file. Switch it off again afterwards | -| `devstack up` in a `git worktree` | starts that worktree's **lane** (every worktree is one) in the main tree's daemon: its own builds, ports moved by +100 (+200, ...), its own containers (a Compose project per lane, ports moved alike; `shared` services come from the main tree), no background workers (`--workers` turns them on; `--force` skips the memory check). Every command in the worktree then acts on the lane (`devstack lane list` shows all) | -| `git worktree add -b ` | a new worktree is a lane at once, not started (devstack never creates or removes worktrees; use git or your tool); tell the user its dashboard page (`devstack ui --link` in it). A lane runs from a copy of its worktree, so `git worktree remove` works while it runs and stops it. `devstack lane stop ` stops a lane and keeps the worktree | -| a directory in a worktree that `prepare` links (`node_modules`, see `devstack lane list`: `linked`) | it is **the lane's copy**, not the worktree's own: on Windows a junction, which looks like a folder. Do not reinstall, delete or clean it there (`npm ci`, `rm -rf`, `git clean -x`, an IDE's "delete node_modules"): that empties what the lane runs from (for a lane on a node, its copy from the store), and a running dev server then fails. To install your own, ask the user, then stop the lane (`devstack lane stop ` removes the link) or remove only the link (`cmd /c rmdir ` on Windows, without `/s`; `rm ` elsewhere, no trailing slash), then install. devstack prepares a copy emptied this way again (a notice says so), but the lane's dev server fails until then | -| `devstack lane start [--on ]` | start a lane from the main tree (or anywhere in the repository), as `devstack up` in its worktree does; `status` in the main tree lists the lanes in one line. **To run another branch or commit beside the main stack** (an end-to-end run against a given commit, a review): `git worktree add `, `devstack lane start ` (its ports are the main ports plus its offset, `devstack lane list`), test against those, `devstack lane stop `, `git worktree remove `. A commit without a stack file of its own runs with the main tree's. **For an acceptance run** use the stack file's profile if it has one (`status` lists none; `[profiles]` in the file): `devstack lane start --profile

--run` starts the lane as the profile says (a build instead of a dev server, workers, fresh data, the suite's env) and runs its suite command. A worktree another tool or script created is a lane too: starting it gives its own ports, containers and database without building a separate environment | -| `devstack lane reset ` / `devstack lane prune [--older-than 7d] [--dry-run]` | throw a stopped lane's data away (it starts fresh, seeded again); remove what lanes whose worktree is gone left behind, here and on the pool's nodes. A lane on a node keeps its data there between starts. Ask the user before either: data goes | -| `devstack promote --lane ` | the lane's services, dev servers included, answer on the main ports; ask the user first, `--lane main` gives them back. A lane on a node may take them only on a dedicated node (a server) | -| `devstack up --on ` in a worktree | the lane runs on that machine of the pool (`pool`: the coordinator picks one, warm first, `:` in another pool, `local`: here): build, services, its own containers; its ports are forwarded here as if it ran locally, a container's UDP ports relayed too (a node older than 0.20.0 relays no UDP, and `devstack lane list` says so). Without `--on` it goes where this machine starts lanes by default (`devstack pool default-on`; here unless the user set it). Ask the user first before starting elsewhere than that default: the worktree's files go to that machine, untracked env files git does not ignore included | -| `devstack pool placement ` (MCP `placement`) | before choosing `--on`: this machine's free CPU and memory, and each node of the pools with its load, free disk, lanes and the coordinator's rank and reason (`keeps this lane's data`, `the repository ran there`, `free capacity`, or why it cannot take it); and the default. Read only | -| `devstack pool default-on [pool\|\|local]` | where lanes start without `--on`; setting it is the user's consent to send worktrees there without being asked, so only on the user's word | -| `devstack lane move --to ` | move a started lane: a cold start there that takes over once ready; its data comes from the seed jobs again | -| `devstack lane share --with ` | let others in the pool open the lane's services and view its state, logs and events, read only (they do not control it). Ask the user first: they read what its services print. Without `--with`: nobody again | -| `devstack pool` / `devstack pool shared` / `devstack open [service]` | the pools and their machines; lanes others share with you; open one of their services here (connects the lane) | -| `devstack pool connect ` / `devstack pool disconnect ` | forward all of a shared lane's services here, on its owner's ports if free; close them again and free the ports | -| `devstack logs --daemon` | devstack's own log: every decision with its reason (`--grep `, `--hub` for the dashboard hub) | -| `devstack restart ` | rebuild now; the running instance stays until the new one is healthy. `--rebuild` builds again although an artifact for the same inputs exists (an input devstack does not see changed: the SDK, a file outside the repository) | -| `devstack restart ` | every service of a group from the stack file, built at the same time, and its containers (`start`/`stop` take a group too, its containers with it; `--rebuild` builds its services again even for inputs built before) | -| `devstack restart .` | one Compose container (`compose.app.web` or `web` work too; `start`/`stop` as well); in a lane its own container, on a node through the node | -| `devstack promote ` | take over a candidate that is held (schema change, see below) | -| `devstack rollback ` | back to the build before the last replacement, without building | -| `devstack start ` / `stop ` | one service | -| `devstack run ` | a command of the stack file (list below) | -| `devstack top` | CPU, memory, disk per service, container, group and lane | -| `devstack ui` | dashboard in the browser, on this stack (in a worktree on its lane; `--lane ` on another), and pairs the browser once; `--browser chrome\|edge\|firefox\|brave\|`, else `DEVSTACK_BROWSER`, else `BROWSER` picks the browser. `--link` prints the lasting links instead (see "Tell the user where to look"), `--print` the one-time pairing link | -| `devstack hub notify` | the desktop notifications the hub shows (a build failed, a candidate held, a service crashed, a lane's start on a node failed) and whether they show; `on\|off …\|all`, `test`. The user's own choice: change it only when asked | -| `devstack hub tray` | whether the tray icon runs (the hub starts it); `on\|off`. The user's own choice: change it only when asked | -| `devstack update` | install the newest devstack (`--check` only asks); stacks switch at their next restart | -| `devstack down` | stop the services and the daemon and remove the containers (volumes, and with them the data, stay); `down --keep-infra` leaves the containers running. In the main tree, lanes that run keep the daemon, what serves them and the `shared` containers they use (only the main tree's services and its other containers stop); `down --all` stops the lanes too: ask first, they may be someone else's | - -### Is my change live? - -Changes arrive by themselves: saving a file under a service's `watch` paths -starts a candidate build. **Before testing a change, check that `devstack status` -shows no `not yet active` line for the service.** The states: - -| Candidate | Meaning | What to do | -| --- | --- | --- | -| `changed`, `building`, `starting`, `switching` | on its way | wait; `devstack status` again | -| `failed` | build or health check failed; the old build keeps running | read the reason in `devstack status` (compiler output), fix the code | -| `held` | built and healthy, waits for `promote` (it touched a path like a migration) | ask the user, then `devstack promote ` | - -A `devserver` (hot reload) has no candidates: it picks up changes itself. - -A folder that was moved or renamed (`mv`, `git mv`, an IDE's "move folder") -counts as one change, on the folder's own path. A `watch` pattern like -`src/**/*.cs` does not match it, so no candidate starts and `devstack status` -shows nothing pending although the running build lacks the folder's files. -After moving a folder with sources, run `devstack restart `. - -## 3. This stack - -| Service | Kind | URL | Health | A saved change | -| --- | --- | --- | --- | --- | -| `dashboard` | devserver | http://localhost:5199 | `/` | hot reload; restart for `restart_on` files | - -This stack defines no commands. - -Commands with a confirmation text (and anything else that deletes data) run only -after the user said yes; never answer a confirmation on the user's behalf. - -## 4. After starting: verify (required before saying "it runs") - -```bash -devstack status # every service healthy / running / completed, no "not yet active" -curl -sk -o /dev/null -w '%{http_code}\n' http://localhost:5199/ # dashboard: 200 -``` - -Check, do not assume: if something "does not run", `devstack status` and the -port tell within a second, and they are the evidence to quote. - -### Tell the user where to look - -Whenever you started the stack or a lane, or created a worktree, give the user -its dashboard page: one link to its services, logs, builds and events. -`devstack status`, `devstack up` and `devstack lane start` end with it -(`dashboard: http://127.0.0.1:/#/s/?lane=`, an empty -`lane=` is the main working tree); for a worktree not started yet, -`devstack ui --link` in it (or `--lane ` from the main tree) prints it. -Quote it as printed, never build it yourself. The page opens in a browser that -was paired before; `devstack ui --link` also prints a -`devstack://open?stack=…&lane=…` link that pairs the browser first (where the -chat or terminal makes it clickable), and `devstack ui` opens the page paired. - -## 5. Agents: MCP - -`devstack mcp` is an MCP server (stdio) with `status`, `journal`, `up` (`on` for a lane on a -node), `down`, `start_service`, `stop_service`, `restart_service`, -`promote_service`, `rollback_service`, `hot_reload`, `logs`, `builds`, -`diagnostics`, `doctor`, `run_command`, `usage`, `lanes`, `lane_start`, -`lane_stop`, `lane_move`, `lane_share`, `promote_lane`, `placement`, -`hub_status`, `hub_start`. `status`, `up` and `lane_start` end with the -`dashboard:` page, `lanes` names each lane's. `lane_start` and `lane_stop` work from the main tree too: an -agent there runs another worktree's lane without moving to it. `up` also -takes `profile`, `run` and `yes` (as `--profile`, `--run`, `--yes`) and -`timeout_s` (how long it waits for the services and containers; the stack keeps starting); -`lane_start` takes `profile`, `run` and `timeout_s` too; `logs` takes `file` (one kept log, from its -list); `diagnostics` takes `source: "hub"` for the hub's log. Each tool -describes its parameters. -Tools named `__` are not devstack's: they are the user's MCP -upstreams, which the hub logs in to (the dashboard's *MCP upstreams*), some -of them named by the user's pool and accepted there. One that answers it is -not logged in needs the user, in the dashboard; tell them, do not look for -another way in. -Register it once (project `.mcp.json` or user configuration; the dashboard -shows *no MCP* in the stack's head while neither has it): - -```json -{ "mcpServers": { "devstack": { "command": "devstack", "args": ["mcp"] } } } -``` - -`run_command` for a command with a confirmation text runs only with -`confirm: true`, and that comes from the user, never from the agent. - -## 6. When something goes wrong - -| Symptom | Cause and fix | -| --- | --- | -| a state looks wrong (a lane on the main ports, a service stopped, containers gone) | look before reporting or undoing it: `devstack status` says who gave a lane the main ports and who stopped a service last, `devstack journal` (MCP `journal`) every change with its client (`dashboard`, `cli`, `mcp`, `tray`, `auto`). A change a client made is the user's decision, not a fault: ask before you undo it, and do not report it upstream | -| anything does not start, before guessing | `devstack doctor` (MCP `doctor`): what this machine lacks for this stack, one line each, with the fix | -| something happened and nothing says why (a restart, a switch, a stop) | `devstack logs --daemon --grep ` (MCP `diagnostics`): service and candidate states with reasons, every request that changed something, daemon start and stop; it works with the daemon stopped | -| `devstack up`: Docker is not running | `up` (CLI and MCP) starts Docker Desktop and waits; with Docker Engine as a Linux service it names `sudo systemctl start docker` for the user | -| "the daemon of this stack (pid …) does not answer" or "… refused: missing or wrong token" | it hangs, or the token changed since it started: `devstack logs --daemon -n 50` says what it did last; `devstack down --all` in the main tree ends it by its pid, lanes included (ask the user first), then `devstack up` | -| a port is taken | another process (often a second copy of the stack, an IDE run, a leftover process) holds it; find it (`Get-NetTCPConnection -LocalPort

` / `ss -ltnp`) and ask before ending it | -| `failed` candidate | the old build keeps running; `devstack status` shows the reason, the build log is in `.devstack/logs//build-.log` | -| `held` candidate | waits for `devstack promote ` after the user agreed | -| `devstack status`: "the stack file changed since the daemon started" | the daemon reads the file once: `devstack down` + `devstack up` (ask first if others use the stack) | -| `devstack status`: another `!` line (a lane's worktree missing, a worktree without a lane, a lane's copy behind, `prepare` not linked, the file watcher) | a condition that holds until it is fixed; the line says what follows from it. Tell the user; `devstack logs --daemon --grep ` has the details | -| a service exits right after start | `devstack logs -n 200`; every start has its own log in `.devstack/logs//run-*.log` | -| dashboard: "hub not reachable" | `devstack ui` (or the "Start hub" button once `devstack hub install` ran; macOS has none yet: `devstack hub start`) | -| this skill says it is outdated | `devstack skills install` refreshes it from the installed devstack and this stack file | -| dashboard: "runs devstack X, Y is installed" | the stack still runs the old daemon: "Restart stack" there, or `devstack down` + `devstack up` | -| a job `failed` after a long wait | jobs end after 30 minutes unless the stack file sets `timeout`; read its log, then ask the user before raising it (skill `devstack-config`) | -| `devstack down` names services that did not stop | they still run: `devstack status`, then `devstack stop `; ask before ending a process yourself | -| `devstack up --on`: the node refuses the lane | the message names what the lane's Compose files ask that a node does not allow (privileged, host mounts, devices, build `tags`, a service key the node does not know, ...) or that the pool has not granted that node; the lane can still run on this machine with `devstack up --on local` (a plain `devstack up` goes to the machine's default, which may be the pool again) | -| `devstack up`: "no node of the pool can take the lane now" | the pool is this machine's default (`devstack pool default-on`) and is full: `devstack pool placement ` says what is free where; try again later, or run it here with `devstack up --on local`. The user chose the pool as the default: ask before running it here | -| `devstack up --on` (or the MCP `up` with `on`) was interrupted or timed out while the lane started on the node | the start goes on there: `devstack lane list` shows its step; the same `devstack up --on ` again follows it to the end. A first start can take minutes (images pulled and built). It ends when the lane's daemon answers; its containers come up after, and its services start once those are healthy. A container that does not get healthy shows in `devstack status` with its group's error; `devstack logs ` has its output | - -## 7. Problems in devstack itself - -devstack is young. **If you find a bug or a rough edge in devstack, or something -that would make the work between this repository, devstack and the agent harness -smoother (a missing MCP tool, an unclear message, a status that was wrong or did -not say enough), ask the user for permission to open an issue in -`nuetzliches/devstack`.** Do not open it without a yes. - -What the issue needs: devstack version (`devstack --version`), OS, what you did, -what happened and what you expected, the relevant lines of `devstack status`, -`devstack logs --daemon` and the service log, and a minimal stack file excerpt -that shows it. - -**Keep the project out of it.** The issue goes to another repository (and may -become public): no names of this project, its customers, hosts, internal paths, -ticket numbers or credentials. Describe the shape of the setup generically ("a -.NET API behind the proxy with a migrator job") and replace names in excerpts. - -```bash -gh issue create -R nuetzliches/devstack --title "" --body-file -``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cfd7ab7..ad7956f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,34 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **A pool's project skills stay in their repository** (ADR-0079): a skill + with `metadata.repos: [owner/name]` in its frontmatter goes into the + agents' skill folders of the working trees whose `origin` is that + repository (`.claude/skills`, `.agents/skills`, ...), not into the user + folders, so sessions in other repositories neither see it nor pay for + its description. Each such folder holds a `.gitignore` that ignores it: + git never sees it. The Skills page shows a skill's repositories and the + working trees it is in. +- **A skill set of several folders, each for its own members** + (ADR-0079): `devstack pool skills add team --github org/skills --path + skills --to '*' --path projects/shop/skills --to shop --repos - + --repos org/shop`, or as rows in the pool area. A member reads and + downloads only the skills of its folders. + +### Changed + +- **devstack's generated skills are local to the working tree** + (ADR-0079): each of their folders ignores itself, and the hub writes + them into the skill folders of the agents switched on on its Skills + page, in every stack and worktree, whenever devstack or the stack file + changes. Commit them no more: `devstack skills install` lists the copies + git still tracks with the `git rm -r --cached` that takes them out, and + the upgrade prompt does it (a migration step that goes again in a later + release, #389). `[agents] skills` still names where + `devstack skills install` writes. + ### Fixed - **An MCP upstream's tools show right after its login**: for up to a minute diff --git a/README.md b/README.md index ee2b106b..450ccd70 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,9 @@ per machine, a customer's beside the team's. Setup and everything else: folders, `.agents/skills` for Codex and most other agents): **`devstack`** (operating this stack, "is my change live", troubleshooting) and **`devstack-config`** (editing the stack file). They are filled in from -the stack file; `devstack status` says when they are out of date. A command with a confirmation text in the stack file runs only +the stack file; `devstack status` says when they are out of date. They are +local to the working tree, not committed: each folder ignores itself, and +the hub keeps them current for the agents switched on on its Skills page. A command with a confirmation text in the stack file runs only when the agent passes `confirm: true`, which it may only do after you agreed. ## Commands diff --git a/crates/devstack-hub/src/branches.rs b/crates/devstack-hub/src/branches.rs index ddbb2e6b..72c7d5ad 100644 --- a/crates/devstack-hub/src/branches.rs +++ b/crates/devstack-hub/src/branches.rs @@ -146,6 +146,21 @@ fn git_with( } /// The repository's git directory shared by its worktrees. +/// The URL of the remote `origin` of the working tree `tree`, if it has one. +pub(crate) fn origin(tree: &Path) -> Option { + git(tree, &["remote", "get-url", "origin"], LOCAL) + .ok() + .map(|u| u.trim().to_string()) + .filter(|u| !u.is_empty()) +} + +/// Whether git tracks a file at or below `rel` in the working tree `tree` +/// (ADR-0079: what devstack writes there must not be one). +pub(crate) fn tracked(tree: &Path, rel: &Path) -> bool { + git(tree, &["ls-files", "--", &rel.to_string_lossy()], LOCAL) + .is_ok_and(|o| !o.trim().is_empty()) +} + pub(crate) fn common_dir(repo: &Path) -> Result { let d = git(repo, &["rev-parse", "--git-common-dir"], LOCAL)?; Ok(repo.join(d.trim())) diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index cc6d493a..0d4570ef 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -452,8 +452,10 @@ pub fn serve() -> Result<(), String> { // The pools, followed over their coordinators' streams (ADR-0073): // their guest lanes and MCP upstreams (ADR-0069 option B). poolfeed::start(state.upstreams.clone(), state.skills.clone()); - // Every stack's worktrees, its daemon running or not (ADR-0078). + // Every stack's worktrees, its daemon running or not (ADR-0078), + // and the skills local to them (ADR-0079). worktrees::start(); + poolskills::follow(state.skills.clone()); tray::start_quietly(); let app = router(state); if let Some(v6) = v6 { diff --git a/crates/devstack-hub/src/poolskills.rs b/crates/devstack-hub/src/poolskills.rs index 932584e9..ed6aa1cc 100644 --- a/crates/devstack-hub/src/poolskills.rs +++ b/crates/devstack-hub/src/poolskills.rs @@ -1,5 +1,8 @@ //! The skill sets this machine's pools hand out, installed into the coding -//! agents' user skill folders (ADR-0074). +//! agents' user skill folders (ADR-0074); a skill bound to repositories +//! (`metadata.repos`, ADR-0079) into the agents' skill folders of the +//! working trees of those repositories instead, each folder it writes +//! there ignored by a `.gitignore` of its own. //! //! - A set is used only once its user accepted it, from the source it names //! then; a set whose source changed is offered again. Its updates come at @@ -46,6 +49,24 @@ pub struct Decision { pub off: BTreeSet, } +/// A working tree the hub follows (ADR-0078), and the URL of its `origin`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tree { + pub root: PathBuf, + pub origin: Option, +} + +/// A folder a skill goes to: an agent's user folder, or (a skill bound to +/// repositories) an agent's folder in a working tree. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Place { + dir: PathBuf, + /// The working tree it is in. + tree: Option, + /// The agents switched on that read it. + agents: Vec, +} + /// A skill the hub installed. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Installed { @@ -95,6 +116,12 @@ pub struct SkillView { pub updated: Option, /// The agents whose folder holds it as the set has it. pub agents: Vec, + /// The repositories it is bound to (ADR-0079); none: every one. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub repos: Vec, + /// The working trees it is in as the set has it (a bound skill). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub trees: Vec, } #[derive(Debug, Clone, Serialize)] @@ -121,6 +148,10 @@ pub struct AgentView { pub id: String, pub name: String, pub dir: String, + /// Its folder in a working tree, for the skills bound to repositories + /// (ADR-0079). + #[serde(skip_serializing_if = "Option::is_none")] + pub project: Option, pub enabled: bool, } @@ -152,8 +183,19 @@ type Folder = Box Option + S type Found = Box bool + Send + Sync>; /// How a skill's archive is fetched: pool, set, skill. type Download = Box Result, String> + Send + Sync>; -/// What each skill name should be: pool, set, SHA-256. -type Wanted = BTreeMap; +/// The working trees the hub follows. +type Trees = Box Vec + Send + Sync>; +/// Whether git tracks a file at or below a path (relative) of a tree. +type Tracked = Box bool + Send + Sync>; + +/// What a skill name should be. +struct Want { + pool: String, + set: String, + sha: String, + repos: Vec, +} +type Wanted = BTreeMap; pub struct PoolSkills { dir: PathBuf, @@ -167,6 +209,10 @@ pub struct PoolSkills { found: Found, /// How a skill's archive is fetched: pool, set, skill. download: Download, + /// The working trees the hub follows, and the ones the last sync saw. + trees: Trees, + seen: Mutex>, + tracked: Tracked, } fn now_ms() -> u128 { @@ -209,9 +255,10 @@ pub fn tree(dir: &Path) -> Option { } impl PoolSkills { - /// The hub's: the table's folders, archives from the pools. + /// The hub's: the table's folders, archives from the pools, the + /// working trees of the stacks registered here. pub fn open(dir: PathBuf) -> Self { - Self::with( + let mut s = Self::with( dir, Box::new(|a| a.skills_dir()), Box::new(|a| a.installed()), @@ -221,7 +268,10 @@ impl PoolSkills { .skill_archive(set, skill) .map_err(|e| e.to_string()) }), - ) + ); + s.trees = Box::new(registered_trees); + s.tracked = Box::new(crate::branches::tracked); + s } fn with(dir: PathBuf, folder: Folder, found: Found, download: Download) -> Self { @@ -233,6 +283,9 @@ impl PoolSkills { folder, found, download, + trees: Box::new(Vec::new), + seen: Mutex::new(Vec::new()), + tracked: Box::new(|_, _| false), }; s.publish(); s @@ -301,6 +354,7 @@ impl PoolSkills { id: a.id.clone(), name: a.name.clone(), dir: (self.folder)(a)?.to_string_lossy().into_owned(), + project: a.project.clone(), enabled: s.agents.get(&a.id) == Some(&true), }) }) @@ -320,9 +374,72 @@ impl PoolSkills { self.save(&s)?; } self.sync(); + self.local(); Ok(()) } + /// The generated devstack skills (`devstack skills install`) in every + /// working tree of the stacks registered here (ADR-0079): into the + /// folders there of the agents switched on, and refreshed where an + /// earlier one is; each folder ignores itself. A skill git tracks is + /// left to the upgrade prompt. + pub fn local(&self) { + let s = self.settings(); + let mut rels: Vec<&str> = Vec::new(); + for a in devstack_skills::agents::all() { + if s.agents.get(&a.id) == Some(&true) + && let Some(p) = a.project.as_deref() + && !rels.contains(&p) + { + rels.push(p); + } + } + for e in devstack_daemon::registry::list() { + let rel = e + .file + .strip_prefix(&e.repo) + .map(Path::to_path_buf) + .unwrap_or_else(|_| PathBuf::from("devstack.toml")); + let mut roots = vec![e.repo.clone()]; + roots.extend( + devstack_daemon::lanes::worktree_branches(&e.repo) + .unwrap_or_default() + .into_iter() + .map(|(p, _)| p) + .filter(|p| !devstack_daemon::lanes::same_tree(p, &e.repo)), + ); + for root in roots { + // A worktree without a stack file of its own runs with the + // main tree's (ADR-0055); its skills say so too. + let file = root.join(&rel); + let Ok(stack) = devstack_config::load(if file.is_file() { &file } else { &e.file }) + else { + continue; + }; + let base = file.parent().unwrap_or(&root).to_path_buf(); + let dirs: Vec = rels + .iter() + .map(|r| { + let mut d = base.clone(); + d.extend(r.split('/').filter(|p| !p.is_empty())); + d + }) + .collect(); + let skip = |folder: &Path| { + folder + .strip_prefix(&root) + .is_ok_and(|rel| (self.tracked)(&root, rel)) + }; + if let Err(err) = devstack_skills::install_into(&stack, &file, &dirs, &skip) { + devstack_daemon::diag::warn( + "local_skills", + serde_json::json!({ "tree": root, "error": format!("{err:#}") }), + ); + } + } + } + } + fn manifest(&self, pool: &str, set: &str) -> Result { self.lists() .remove(pool) @@ -494,7 +611,15 @@ impl PoolSkills { if want.contains_key(&k.name) { twice.insert(k.name.clone()); } else { - want.insert(k.name.clone(), (pool.clone(), m.name.clone(), sha)); + want.insert( + k.name.clone(), + Want { + pool: pool.clone(), + set: m.name.clone(), + sha, + repos: k.repos.clone(), + }, + ); } } } @@ -543,24 +668,23 @@ impl PoolSkills { }) .collect(); let mut errors = Vec::new(); - // The folders written to, once each. - let mut dirs: Vec = Vec::new(); - for a in devstack_skills::agents::all() { - if s.agents.get(&a.id) == Some(&true) - && let Some(d) = (self.folder)(a) - && !dirs.contains(&d) - { - dirs.push(d); - } - } + let trees = (self.trees)(); + *self.seen.lock().unwrap() = trees.clone(); + // The folders each skill goes to. + let places: BTreeMap<&String, Vec> = want + .iter() + .map(|(n, w)| (n, self.places(&s, &w.repos, &trees))) + .collect(); // What goes: in a folder no longer written to, or no longer wanted // as it is there. let mut keep = Vec::new(); for i in std::mem::take(&mut s.installed) { - let wanted_here = dirs.contains(&i.dir) - && want + let wanted_here = want + .get(&i.name) + .is_some_and(|w| w.pool == i.pool && w.set == i.set) + && places .get(&i.name) - .is_some_and(|(p, set, _)| *p == i.pool && *set == i.set); + .is_some_and(|ps| ps.iter().any(|p| p.dir == i.dir)); if wanted_here { keep.push(i); continue; @@ -582,8 +706,10 @@ impl PoolSkills { } } s.installed = keep; - for dir in &dirs { - for (name, (pool, set, sha)) in &want { + for (name, w) in &want { + let (pool, set, sha) = (&w.pool, &w.set, &w.sha); + for place in &places[name] { + let dir = &place.dir; let path = dir.join(name); let mine = s .installed @@ -616,9 +742,21 @@ impl PoolSkills { } None => {} } + // A file git tracks there is the repository's (ADR-0071). + if let Some(root) = &place.tree + && let Ok(rel) = path.strip_prefix(root) + && (self.tracked)(root, rel) + { + conflicts.push(Conflict { + dir: dir.to_string_lossy().into_owned(), + name: name.clone(), + reason: "git tracks a file of this skill in the working tree: devstack writes none of the repository's files".into(), + }); + continue; + } let result = self .archive(pool, set, name, sha) - .and_then(|bytes| install(dir, name, &bytes)); + .and_then(|bytes| install(dir, name, &bytes, place.tree.is_some())); match result { Ok(t) => { s.installed.retain(|i| !(&i.dir == dir && &i.name == name)); @@ -643,6 +781,47 @@ impl PoolSkills { self.publish(); } + /// The folders a skill bound to `repos` goes to: the user folders of the + /// agents switched on, or, bound, their folders in the working trees of + /// those repositories. Each once, with the agents that read it. + fn places(&self, s: &Settings, repos: &[String], trees: &[Tree]) -> Vec { + let mut out: Vec = Vec::new(); + let mut add = |dir: PathBuf, tree: Option, agent: &str| match out + .iter_mut() + .find(|p| p.dir == dir) + { + Some(p) => p.agents.push(agent.to_string()), + None => out.push(Place { + dir, + tree, + agents: vec![agent.to_string()], + }), + }; + for a in devstack_skills::agents::all() { + if s.agents.get(&a.id) != Some(&true) { + continue; + } + if repos.is_empty() { + if let Some(d) = (self.folder)(a) { + add(d, None, &a.name); + } + continue; + } + let Some(rel) = &a.project else { continue }; + for t in trees { + if t.origin + .as_deref() + .is_some_and(|o| devstack_node::skills::repo_matches(repos, o)) + { + let mut d = t.root.clone(); + d.extend(rel.split('/').filter(|p| !p.is_empty())); + add(d, Some(t.root.clone()), &a.name); + } + } + } + out + } + /// Archives no set names any more go from the store. fn prune_store(&self, lists: &BTreeMap>) { let named: BTreeSet = lists @@ -670,11 +849,7 @@ impl PoolSkills { let s = self.settings(); let lists = self.lists(); let agents = self.agents(&s); - let dirs: Vec = agents - .iter() - .filter(|a| a.enabled) - .map(|a| PathBuf::from(&a.dir)) - .collect(); + let trees = self.seen.lock().unwrap().clone(); let mut sets = Vec::new(); for (pool, ms) in &lists { for m in ms { @@ -700,6 +875,7 @@ impl PoolSkills { .skills .iter() .map(|k| { + let places = self.places(&s, &k.repos, &trees); let enabled = !d.is_some_and(|d| d.off.contains(&k.name)); let mine = |i: &&Installed| { &i.pool == pool && i.set == m.name && i.name == k.name @@ -716,8 +892,8 @@ impl PoolSkills { sha256: k.sha256.clone(), installed: accepted && enabled - && !dirs.is_empty() - && dirs.iter().all(here), + && !places.is_empty() + && places.iter().all(|p| here(&p.dir)), pending: accepted && enabled && !auto @@ -734,9 +910,25 @@ impl PoolSkills { .max(), agents: agents .iter() - .filter(|a| a.enabled && here(&PathBuf::from(&a.dir))) + .filter(|a| { + places + .iter() + .any(|p| p.agents.contains(&a.name) && here(&p.dir)) + }) .map(|a| a.name.clone()) .collect(), + repos: k.repos.clone(), + trees: { + let mut t: Vec = places + .iter() + .filter(|p| here(&p.dir)) + .filter_map(|p| p.tree.as_ref()) + .map(|t| t.to_string_lossy().into_owned()) + .collect(); + t.sort(); + t.dedup(); + t + }, } }) .collect(), @@ -782,13 +974,22 @@ fn write(path: &Path, bytes: &[u8]) -> Result<(), String> { } /// Unpack a skill into `dir/name`: into a folder beside it first, then -/// swapped in. The hash of what was written. -fn install(dir: &Path, name: &str, bytes: &[u8]) -> Result { +/// swapped in; in a working tree (`ignored`) with a `.gitignore` that +/// ignores the folder. The hash of what was written. +fn install(dir: &Path, name: &str, bytes: &[u8], ignored: bool) -> Result { std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let n = rand::random::(); let fresh = dir.join(format!(".{name}.devstack-new-{n:08x}")); let old = dir.join(format!(".{name}.devstack-old-{n:08x}")); - if let Err(e) = devstack_node::skills::unpack(bytes, &fresh) { + let unpacked = devstack_node::skills::unpack(bytes, &fresh).and_then(|()| { + if ignored { + std::fs::write(fresh.join(".gitignore"), devstack_skills::IGNORE_ALL) + .map_err(|e| e.to_string()) + } else { + Ok(()) + } + }); + if let Err(e) = unpacked { let _ = std::fs::remove_dir_all(&fresh); return Err(e); } @@ -808,6 +1009,73 @@ fn install(dir: &Path, name: &str, bytes: &[u8]) -> Result { tree(&target).ok_or_else(|| format!("{}: not readable after writing", target.display())) } +/// Keep the skills of the working trees in step (ADR-0079): when a stack is +/// registered or forgotten, a worktree comes or goes or checks out another +/// branch, a stack file changes, or devstack is another version, the bound +/// skills of the pools and the generated ones are written again. Once a +/// minute at the latest. +pub fn follow(skills: std::sync::Arc) { + let _ = std::thread::Builder::new() + .name("tree-skills".into()) + .spawn(move || { + let worktrees = crate::worktrees::subscribe(); + let mut last: Option<(u64, std::time::Instant)> = None; + loop { + let print = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + worktrees.borrow().hash(&mut h); + for e in devstack_daemon::registry::list() { + e.file.hash(&mut h); + std::fs::metadata(&e.file) + .and_then(|m| m.modified()) + .ok() + .hash(&mut h); + } + h.finish() + }; + let due = last.is_none_or(|(p, at)| { + p != print || at.elapsed() >= std::time::Duration::from_secs(60) + }); + if due { + skills.sync(); + skills.local(); + last = Some((print, std::time::Instant::now())); + } + std::thread::sleep(std::time::Duration::from_secs(3)); + } + }); +} + +/// The working trees of the stacks registered here (their main working +/// trees and worktrees), with their `origin`, asked of git once per +/// repository. +fn registered_trees() -> Vec { + let mut out: Vec = Vec::new(); + for e in devstack_daemon::registry::list() { + let origin = crate::branches::origin(&e.repo); + let mut roots = vec![e.repo.clone()]; + roots.extend( + devstack_daemon::lanes::worktree_branches(&e.repo) + .unwrap_or_default() + .into_iter() + .map(|(p, _)| p), + ); + for root in roots { + if !out + .iter() + .any(|t| devstack_daemon::lanes::same_tree(&t.root, &root)) + { + out.push(Tree { + root, + origin: origin.clone(), + }); + } + } + } + out +} + // ------------------------------------------------------------------ routes use axum::Json; @@ -952,12 +1220,103 @@ mod tests { size: b.len() as u64, group: name.starts_with("biz").then(|| "Business".to_string()), tags: Vec::new(), + repos: if name.starts_with("shop") { + vec!["acme/shop".into()] + } else { + Vec::new() + }, + folder: None, }; self.archives.lock().unwrap().insert(name.into(), b); e } } + #[test] + fn a_bound_skill_goes_into_the_working_trees_of_its_repository_only() { + let (st, home, wt) = ( + tempfile::tempdir().unwrap(), + tempfile::tempdir().unwrap(), + tempfile::tempdir().unwrap(), + ); + let (mut hub, pool) = hub(st.path(), home.path()); + let (shop, lane, other) = ( + wt.path().join("shop"), + wt.path().join("shop-lane"), + wt.path().join("blog"), + ); + let tree = |root: &Path, origin: &str| Tree { + root: root.to_path_buf(), + origin: Some(origin.into()), + }; + let trees = Arc::new(Mutex::new(vec![ + tree(&shop, "git@github.com:acme/shop.git"), + tree(&lane, "https://github.com/Acme/Shop"), + tree(&other, "git@github.com:acme/blog.git"), + ])); + let t = trees.clone(); + hub.trees = Box::new(move || t.lock().unwrap().clone()); + let a = pool.put("work-issue", "v1"); + let b = pool.put("shop-page", "v1"); + hub.set_pool("default", Some(set(vec![a, b.clone()]))); + hub.set_agent("claude-code", true).unwrap(); + hub.set_agent("codex", true).unwrap(); + hub.accept("default", "core", true).unwrap(); + + // Unbound: the user folders. Bound: the agents' folders of the + // working trees of acme/shop, each ignoring itself. + assert!(home.path().join(".claude/skills/work-issue").exists()); + assert!(!home.path().join(".claude/skills/shop-page").exists()); + for root in [&shop, &lane] { + for d in [".claude/skills", ".agents/skills"] { + let k = root.join(d).join("shop-page"); + assert!(k.join("SKILL.md").exists(), "{}", k.display()); + assert_eq!( + std::fs::read_to_string(k.join(".gitignore")).unwrap(), + devstack_skills::IGNORE_ALL + ); + } + assert!(!root.join(".claude/skills/work-issue").exists()); + } + assert!(!other.join(".claude").exists()); + let v = hub.view(); + let k = v.sets[0] + .skills + .iter() + .find(|k| k.name == "shop-page") + .unwrap(); + assert!(k.installed, "{k:?}"); + assert_eq!(k.repos, ["acme/shop"]); + assert_eq!(k.trees.len(), 2); + assert_eq!(k.agents, ["Claude Code", "Codex"]); + + // A worktree removed: its folders are no longer the hub's. + trees.lock().unwrap().retain(|t| t.root != lane); + std::fs::remove_dir_all(&lane).unwrap(); + hub.sync(); + assert_eq!(hub.view().sets[0].skills[1].trees.len(), 1); + + // A file git tracks there is the repository's: not written over. + hub.tracked = Box::new(|_, rel| rel.starts_with(".agents")); + std::fs::remove_dir_all(shop.join(".agents/skills/shop-page")).unwrap(); + hub.sync(); + assert!(!shop.join(".agents/skills/shop-page").exists()); + assert!( + hub.view() + .conflicts + .iter() + .any(|c| c.name == "shop-page" && c.reason.contains("git tracks")) + ); + hub.tracked = Box::new(|_, _| false); + + // A skill bound later leaves the user folders for the working trees. + let mut bound = pool.put("work-issue", "v1"); + bound.repos = vec!["acme/blog".into()]; + hub.set_pool("default", Some(set(vec![bound, b]))); + assert!(!home.path().join(".claude/skills/work-issue").exists()); + assert!(other.join(".claude/skills/work-issue/SKILL.md").exists()); + } + /// A hub whose agents `claude-code` and `codex` are found, with their /// folders in `home`. fn hub(state: &Path, home: &Path) -> (PoolSkills, Pool) { diff --git a/crates/devstack-hub/src/prompts.rs b/crates/devstack-hub/src/prompts.rs index 0c145089..30073977 100644 --- a/crates/devstack-hub/src/prompts.rs +++ b/crates/devstack-hub/src/prompts.rs @@ -68,6 +68,10 @@ pub fn text(p: &Prompt) -> String { // Where the MCP server goes: the project's file of each agent, an // existing file merged into. let mcp = "devstack's MCP server (`devstack mcp`, stdio) gives coding agents its tools (status, logs, restart, lanes). Register it in the project's configuration of the coding agents this repository is worked on with, next to the servers already there: `.mcp.json` (Claude Code) `{ \"mcpServers\": { \"devstack\": { \"command\": \"devstack\", \"args\": [\"mcp\"] } } }`; `.vscode/mcp.json` (VS Code) the same under `servers`, with `\"type\": \"stdio\"`; `.codex/config.toml` (Codex) `[mcp_servers.devstack]` with `command = \"devstack\"`, `args = [\"mcp\"]`. Keep the files' other entries and their formatting; an agent loads a new server when it starts again."; + // Generated skills are local to the working tree since 0.32.0 + // (ADR-0079): copies an earlier devstack had committed leave git. A + // migration aid, removed again once repositories have moved (#389). + let untrack = "The generated skills are local to each working tree, not the repository's: each of their folders holds a `.gitignore` that ignores it, and the devstack hub keeps them current. Where git still tracks one (`git ls-files` lists a skill folder whose SKILL.md has the line `(devstack skills install)`, such as `.claude/skills/devstack`), take it out of git with `git rm -r --cached `: the files stay. A skill the project wrote itself stays tracked."; match *p { Prompt::Setup { repo, drafted } => format!( "Set up devstack for the repository at {repo}. @@ -142,7 +146,7 @@ pub fn text(p: &Prompt) -> String { 4. Run `devstack check` (and `devstack check --compose`) and `devstack doctor`, and fix every error and warning. 5. Tell me which new features would help this stack, and add only those I agree to. Raise `[stack] requires` only when the file uses something an older devstack does not know: it shuts out everyone still on one. 6. Set `reviewed = \"{current}\"` in `[stack]`: the stack file is up to date with devstack {current} then, and the dashboard stops offering this.{requires} -7. Run `devstack skills install` to refresh the generated skills. Check the project's own skills, CLAUDE.md and AGENTS.md for anything that contradicts devstack {current}. Where no agent configuration of the project registers devstack's MCP server, ask me whether to; suggest yes. {mcp} +7. Run `devstack skills install` to refresh the generated skills. {untrack} Check the project's own skills, CLAUDE.md and AGENTS.md for anything that contradicts devstack {current}. Where no agent configuration of the project registers devstack's MCP server, ask me whether to; suggest yes. {mcp} 8. Restart the stack so it runs devstack {current}, and check that every service becomes healthy. Before you stop it, look at `devstack status` and `devstack lane list`: when lanes run, a lane holds the main ports, or other sessions may use this stack, ask me first. Restart with `devstack down --keep-infra`, then `devstack up`: the containers keep running (a plain `down` removes them since 0.25.0). {careful}", repo = display(repo), file = display(file), @@ -199,8 +203,9 @@ pub fn text(p: &Prompt) -> String { 1. `devstack --version` must say {v}; if it says another, run `devstack update` first and tell me. 2. Run `devstack skills install` in the repository. It rewrites the generated skills only (their marker line says so); a skill the project wrote itself stays. -3. Read what changed in them (`git diff`). Check the project's own skills, CLAUDE.md and AGENTS.md for anything that now contradicts them, and tell me what you would change there. -4. {careful}", +3. {untrack} +4. Check the project's own skills, CLAUDE.md and AGENTS.md for anything that now contradicts the generated ones, and tell me what you would change there. +5. {careful}", repo = display(repo), ), Prompt::StartFailed { diff --git a/crates/devstack-node/src/coordinator.rs b/crates/devstack-node/src/coordinator.rs index 3cb9ec6f..5aebbdaf 100644 --- a/crates/devstack-node/src/coordinator.rs +++ b/crates/devstack-node/src/coordinator.rs @@ -4242,10 +4242,8 @@ async fn skill_archive( ) }; let skill = file.strip_suffix(".tar.gz").ok_or_else(not_found)?; - let given = crate::skills::load(&s.dir) - .into_iter() - .any(|x| x.name == set && x.given_to(&m.id, &m.tags)); - if !given { + // The set, and the folder the skill is in (ADR-0079), given to it. + if !crate::skills::skill_given_to(&s.dir, &set, skill, &m.id, &m.tags) { return Err(not_found()); } let bytes = crate::skills::archive(&s.dir, &set, skill).ok_or_else(not_found)?; @@ -4332,12 +4330,26 @@ async fn admin_skill_put( Json(set): Json, ) -> ApiResult> { let (me, by) = admin(&s, &peer)?; - let detail = format!( - "{} {} to {}", - set.name, - set.source.label(), - set.to.join(",") - ); + let detail = if set.folders.is_empty() { + format!( + "{} {} to {}", + set.name, + set.source.label(), + set.to.join(",") + ) + } else { + let folders: Vec = set + .folders + .iter() + .map(|f| format!("{} to {}", f.path, f.to.join(","))) + .collect(); + format!( + "{} {} ({})", + set.name, + set.source.label(), + folders.join("; ") + ) + }; let name = set.name.clone(); { let _one = s.upstreams.lock().unwrap(); diff --git a/crates/devstack-node/src/skills.rs b/crates/devstack-node/src/skills.rs index 3b61c05b..18c98d33 100644 --- a/crates/devstack-node/src/skills.rs +++ b/crates/devstack-node/src/skills.rs @@ -52,6 +52,109 @@ pub struct SkillSet { /// Whom it is given to: `*`, member ids, tags. #[serde(default)] pub to: Vec, + /// The repositories its skills without `metadata.repos` of their own + /// are bound to (ADR-0079); none: no binding. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub repos: Vec, + /// Several folders of the source, each given to its own members + /// (ADR-0079); none: the source's path, given to `to`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub folders: Vec, +} + +/// A folder of a set's source with its own members (ADR-0079). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SkillFolder { + /// Below the source's path; `""`: the source's path itself. + pub path: String, + /// Whom its skills are given to: `*`, member ids, tags. + #[serde(default)] + pub to: Vec, + /// The repositories its skills without `metadata.repos` are bound to. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub repos: Vec, +} + +/// At most this many folders in a set. +pub const MAX_FOLDERS: usize = 16; +/// At most this many repositories a skill or folder is bound to. +pub const MAX_REPOS: usize = 16; + +/// Whether `r` names a repository as `metadata.repos` does: `owner/name`, +/// or more segments (`project/_git/name`), without a host. +pub fn valid_repo(r: &str) -> bool { + let parts: Vec<&str> = r.split('/').collect(); + parts.len() >= 2 + && r.len() <= 200 + && parts.iter().all(|p| { + !p.is_empty() + && *p != "." + && *p != ".." + && p.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) + }) +} + +/// The path of a remote's URL, by segment: `git@github.com:acme/shop.git`, +/// `https://github.com/acme/shop`, `ssh://git@host:22/acme/shop.git` all +/// give `["acme", "shop"]`. +fn url_path(url: &str) -> Vec { + let u = url.trim().trim_end_matches('/'); + let u = u.strip_suffix(".git").unwrap_or(u); + let rest = if let Some((_, r)) = u.split_once("://") { + // Past the host (and a port). + r.split_once('/').map_or("", |(_, p)| p) + } else if let Some((host, p)) = u.split_once(':') + && !host.contains('/') + && host.len() > 1 + { + // scp-like `user@host:path`; `C:` (a drive) is a path. + p + } else { + u + }; + rest.split(['/', '\\']) + .filter(|s| !s.is_empty()) + .map(str::to_ascii_lowercase) + .collect() +} + +/// Whether a working tree whose `origin` is `url` is one of `repos`: an +/// entry matches the last segments of the URL's path, case aside, the host +/// left out (ADR-0079). +pub fn repo_matches(repos: &[String], url: &str) -> bool { + let path = url_path(url); + repos.iter().any(|r| { + let want: Vec = r + .split('/') + .filter(|s| !s.is_empty()) + .map(str::to_ascii_lowercase) + .collect(); + want.len() >= 2 && path.len() >= want.len() && path[path.len() - want.len()..] == want[..] + }) +} + +fn check_repos(repos: &[String]) -> Result<(), String> { + if repos.len() > MAX_REPOS { + return Err(format!("{MAX_REPOS} repositories at most")); + } + match repos.iter().find(|r| !valid_repo(r)) { + Some(r) => Err(format!("`{r}`: a repository is owner/name, without a host")), + None => Ok(()), + } +} + +/// One folder of a set as fetched: its path below the source's, whom it is +/// given to, its repositories. +pub struct Part<'a> { + pub path: &'a str, + pub to: &'a [String], + pub repos: &'a [String], +} + +fn given(to: &[String], id: &str, tags: &[String]) -> bool { + to.iter() + .any(|t| t == "*" || t == id || tags.iter().any(|x| x == t)) } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -154,17 +257,75 @@ impl SkillSet { } } } - if self.to.len() > 256 || self.to.iter().any(|t| t.is_empty() || t.len() > 64) { + let to_ok = + |to: &[String]| to.len() <= 256 && to.iter().all(|t| !t.is_empty() && t.len() <= 64); + if !to_ok(&self.to) { return Err("`to` names 1 to 64 characters each, 256 at most".into()); } + check_repos(&self.repos)?; + if self.folders.len() > MAX_FOLDERS { + return Err(format!("a set has {MAX_FOLDERS} folders at most")); + } + if !self.folders.is_empty() && !(self.to.is_empty() && self.repos.is_empty()) { + return Err("a set with folders names `to` and `repos` per folder".into()); + } + let mut seen = std::collections::BTreeSet::new(); + for f in &self.folders { + let p = f.path.trim_matches('/'); + if !relative(p) { + return Err(format!( + "`{}`: a folder of the source, without `..`", + f.path + )); + } + if !seen.insert(p) { + return Err(format!("`{p}`: a folder named twice")); + } + if !to_ok(&f.to) { + return Err(format!( + "`{p}`: `to` names 1 to 64 characters each, 256 at most" + )); + } + check_repos(&f.repos)?; + } Ok(()) } - /// Whether the member `id` with `tags` gets it. + /// Its folders: the ones it names, else the source's path given to `to`. + pub fn parts(&self) -> Vec> { + if self.folders.is_empty() { + vec![Part { + path: "", + to: &self.to, + repos: &self.repos, + }] + } else { + self.folders + .iter() + .map(|f| Part { + path: f.path.trim_matches('/'), + to: &f.to, + repos: &f.repos, + }) + .collect() + } + } + + /// Whether the member `id` with `tags` gets it, or a folder of it. pub fn given_to(&self, id: &str, tags: &[String]) -> bool { - self.to - .iter() - .any(|t| t == "*" || t == id || tags.iter().any(|x| x == t)) + self.parts().iter().any(|p| given(p.to, id, tags)) + } + + /// Whether the member gets the skills of the folder `folder` (`None`: + /// a set of one folder). + pub fn folder_given_to(&self, folder: Option<&str>, id: &str, tags: &[String]) -> bool { + match folder { + None => self.folders.is_empty() && given(&self.to, id, tags), + Some(f) => self + .folders + .iter() + .any(|x| x.path.trim_matches('/') == f && given(&x.to, id, tags)), + } } } @@ -183,6 +344,13 @@ pub struct SkillEntry { /// `metadata.tags` of its frontmatter. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tags: Vec, + /// The repositories it is bound to (ADR-0079): `metadata.repos` of its + /// frontmatter, else its folder's; none: every repository. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub repos: Vec, + /// The folder of the set it is from, for a set of several folders. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, } /// A set as its members read it: what the last fetch that worked found, @@ -300,15 +468,33 @@ pub fn manifest(dir: &Path, s: &SkillSet) -> SetManifest { }) } -/// The sets given to the member `id` with `tags`, as last fetched. +/// The sets given to the member `id` with `tags`, as last fetched: of a set +/// of several folders, the skills of the folders given to it. pub fn for_member(dir: &Path, id: &str, tags: &[String]) -> Vec { load(dir) .iter() .filter(|s| s.given_to(id, tags)) - .map(|s| manifest(dir, s)) + .map(|s| { + let mut m = manifest(dir, s); + m.skills + .retain(|k| s.folder_given_to(k.folder.as_deref(), id, tags)); + m + }) .collect() } +/// Whether the member gets the skill `skill` of the set `set` as last +/// fetched: the set and the skill's folder are given to it. +pub fn skill_given_to(dir: &Path, set: &str, skill: &str, id: &str, tags: &[String]) -> bool { + load(dir).iter().any(|s| { + s.name == set + && manifest(dir, s) + .skills + .iter() + .any(|k| k.name == skill && s.folder_given_to(k.folder.as_deref(), id, tags)) + }) +} + /// Every set with its state. pub fn admin_view(dir: &Path) -> AdminView { AdminView { @@ -354,15 +540,38 @@ pub fn refresh(dir: &Path, s: &SkillSet) -> SetManifest { .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); let old = manifest(dir, s); - let fetched = match &s.source { + let below = |base: &str, p: &str| { + [base.trim_matches('/'), p] + .iter() + .filter(|x| !x.is_empty()) + .copied() + .collect::>() + .join("/") + }; + let fetched: Result<(Vec, Option), String> = match &s.source { Source::Github { repo, reference, path, - } => fetch_github(repo, reference, path), - Source::Folder { path } => { - read_folder(&dir.join(SOURCES).join(path.trim_matches('/'))).map(|f| (f, None)) - } + } => fetch_github(repo, reference).and_then(|bytes| { + let mut commit = None; + let mut all = Vec::new(); + for p in s.parts() { + let (found, c) = from_github_archive(&bytes, &below(path, p.path))?; + commit = commit.or(c); + all.push(fetched_part(s, &p, found)); + } + Ok((all, commit)) + }), + Source::Folder { path } => s + .parts() + .iter() + .map(|p| { + read_folder(&dir.join(SOURCES).join(below(path, p.path))) + .map(|found| fetched_part(s, p, found)) + }) + .collect::, _>>() + .map(|all| (all, None)), }; let target = cache(dir, &s.name); let m = match fetched @@ -393,11 +602,27 @@ pub fn refresh(dir: &Path, s: &SkillSet) -> SetManifest { m } +/// The skills one folder of a set holds: the folder (`None` for a set of +/// one), its repositories, its skill folders. +struct Fetched { + folder: Option, + repos: Vec, + found: Found, +} + +fn fetched_part(s: &SkillSet, p: &Part<'_>, found: Found) -> Fetched { + Fetched { + folder: (!s.folders.is_empty()).then(|| p.path.to_string()), + repos: p.repos.to_vec(), + found, + } +} + fn pack( target: &Path, set: &str, source: &str, - found: Found, + parts: Vec, commit: Option, now: u64, ) -> Result { @@ -408,31 +633,64 @@ fn pack( commit, ..Default::default() }; + // A skill name in two folders: neither is handed out. + let mut count: BTreeMap<&str, usize> = BTreeMap::new(); + for p in &parts { + for name in p.found.keys() { + *count.entry(name).or_default() += 1; + } + } + let twice: Vec = count + .into_iter() + .filter(|(_, n)| *n > 1) + .map(|(k, _)| k.to_string()) + .collect(); let mut archives = Vec::new(); - for (folder, files) in found { - match skill(&folder, &files) { - Ok(front) => { - let bytes = tar_gz(&files).map_err(|e| format!("{folder}: {e}"))?; - if bytes.len() as u64 > MAX_ARCHIVE { - m.skipped.push(format!( - "{folder}: its archive is over {} MiB", - MAX_ARCHIVE >> 20 - )); - continue; + for p in parts { + let at = |folder: &str| match &p.folder { + Some(f) if !f.is_empty() => format!("{f}/{folder}"), + _ => folder.to_string(), + }; + for (folder, files) in p.found { + if twice.contains(&folder) { + m.skipped.push(format!( + "{}: a skill of this name is in another folder of the set too", + at(&folder) + )); + continue; + } + match skill(&folder, &files) { + Ok(front) => { + let bytes = tar_gz(&files).map_err(|e| format!("{}: {e}", at(&folder)))?; + if bytes.len() as u64 > MAX_ARCHIVE { + m.skipped.push(format!( + "{}: its archive is over {} MiB", + at(&folder), + MAX_ARCHIVE >> 20 + )); + continue; + } + m.skills.push(SkillEntry { + name: folder.clone(), + description: front.description, + sha256: hex(&Sha256::digest(&bytes)), + size: bytes.len() as u64, + group: front.group, + tags: front.tags, + repos: if front.repos.is_empty() { + p.repos.clone() + } else { + front.repos + }, + folder: p.folder.clone(), + }); + archives.push((folder, bytes)); } - m.skills.push(SkillEntry { - name: folder.clone(), - description: front.description, - sha256: hex(&Sha256::digest(&bytes)), - size: bytes.len() as u64, - group: front.group, - tags: front.tags, - }); - archives.push((folder, bytes)); + Err(e) => m.skipped.push(format!("{}: {e}", at(&folder))), } - Err(e) => m.skipped.push(format!("{folder}: {e}")), } } + m.skills.sort_by(|a, b| a.name.cmp(&b.name)); if m.skills.is_empty() && !m.skipped.is_empty() { return Err(format!( "no skill there to hand out: {}", @@ -502,6 +760,9 @@ pub struct Front { pub description: String, pub group: Option, pub tags: Vec, + /// `metadata.repos`: the repositories it is bound to (ADR-0079), the + /// ones not of the form `owner/name` left out. + pub repos: Vec, } /// The frontmatter of a `SKILL.md`. @@ -520,7 +781,7 @@ pub fn frontmatter(md: &str) -> Result { return Err("SKILL.md starts without frontmatter (`---`)".into()); } let (mut name, mut description) = (None, None); - let (mut group, mut tags) = (None, Vec::new()); + let (mut group, mut tags, mut repos) = (None, Vec::new(), Vec::new()); let mut block = Block::None; let list = |v: &str| -> Vec { v.trim_start_matches('[') @@ -547,8 +808,10 @@ pub fn frontmatter(md: &str) -> Result { Block::Metadata(last) if indented => { let t = l.trim(); if let Some(item) = t.strip_prefix("- ") { - if last == "tags" { - tags.push(unquote(item)); + match last.as_str() { + "tags" => tags.push(unquote(item)), + "repos" => repos.push(unquote(item)), + _ => {} } } else if let Some((k, v)) = t.split_once(':') { let (k, v) = (k.trim(), v.trim()); @@ -556,6 +819,7 @@ pub fn frontmatter(md: &str) -> Result { match k { "group" if !v.is_empty() => group = Some(unquote(v)), "tags" if !v.is_empty() => tags = list(v), + "repos" if !v.is_empty() => repos = list(v), _ => {} } } @@ -584,11 +848,14 @@ pub fn frontmatter(md: &str) -> Result { let group = group.filter(|g| !g.is_empty() && g.chars().count() <= 48); tags.retain(|t| t.chars().count() <= 32); tags.truncate(16); + repos.retain(|r| valid_repo(r)); + repos.truncate(MAX_REPOS); Ok(Front { name: name.ok_or("SKILL.md names no `name`")?, description: description.ok_or("SKILL.md has no `description`")?, group, tags, + repos, }) } @@ -765,11 +1032,8 @@ fn github_api() -> String { std::env::var("DEVSTACK_SKILLS_GITHUB_API").unwrap_or_else(|_| "https://api.github.com".into()) } -fn fetch_github( - repo: &str, - reference: &str, - path: &str, -) -> Result<(Found, Option), String> { +/// The repository's archive at `reference`. +fn fetch_github(repo: &str, reference: &str) -> Result, String> { let agent = ureq::Agent::config_builder() .timeout_global(Some(std::time::Duration::from_secs(120))) .http_status_as_error(false) @@ -799,13 +1063,11 @@ fn fetch_github( s => format!("GitHub answered {s}"), }); } - let bytes = res - .body_mut() + res.body_mut() .with_config() .limit(MAX_SOURCE) .read_to_vec() - .map_err(|e| format!("GitHub: {e}"))?; - from_github_archive(&bytes, path) + .map_err(|e| format!("GitHub: {e}")) } /// The secret a refresh is signed with, if the coordinator takes one. @@ -854,6 +1116,8 @@ mod tests { name: "core".into(), source: Source::Folder { path: path.into() }, to: vec!["*".into()], + repos: Vec::new(), + folders: Vec::new(), } } @@ -897,6 +1161,117 @@ mod tests { assert_eq!(f.description, "d"); } + #[test] + fn metadata_binds_a_skill_to_repositories() { + let f = frontmatter( + "---\nname: a\ndescription: d\nmetadata:\n repos: [acme/shop, \"https://x/y\", org/proj/_git/app]\n---\n", + ) + .unwrap(); + assert_eq!(f.repos, ["acme/shop", "org/proj/_git/app"]); + let f = frontmatter( + "---\nname: a\ndescription: d\nmetadata:\n repos:\n - Acme/Shop\n---\n", + ) + .unwrap(); + assert_eq!(f.repos, ["Acme/Shop"]); + } + + #[test] + fn a_repository_matches_its_origin_in_every_form() { + let r = vec!["Acme/Shop".to_string()]; + for url in [ + "git@github.com:acme/shop.git", + "https://github.com/acme/shop", + "https://github.com/acme/shop.git/", + "ssh://git@git.example:2222/acme/shop.git", + "https://gitlab.example/group/acme/shop", + ] { + assert!(repo_matches(&r, url), "{url}"); + } + for url in [ + "git@github.com:acme/shopping.git", + "https://github.com/other/shop", + "https://github.com/shop", + "", + ] { + assert!(!repo_matches(&r, url), "{url}"); + } + assert!(repo_matches( + &["proj/_git/app".to_string()], + "https://dev.azure.com/org/proj/_git/app" + )); + assert!(!repo_matches(&["shop".to_string()], "git@h:acme/shop.git")); + } + + #[test] + fn a_set_of_folders_gives_each_its_members() { + let mut s = set("core"); + s.folders = vec![ + SkillFolder { + path: "".into(), + to: vec!["*".into()], + repos: Vec::new(), + }, + SkillFolder { + path: "projects/shop/".into(), + to: vec!["shop".into()], + repos: vec!["acme/shop".into()], + }, + ]; + s.to = Vec::new(); + assert!(s.check().is_ok()); + assert!(s.folder_given_to(Some(""), "x", &[])); + assert!(!s.folder_given_to(Some("projects/shop"), "x", &[])); + assert!(s.folder_given_to(Some("projects/shop"), "x", &["shop".into()])); + assert!(!s.folder_given_to(None, "x", &[]), "a skill of no folder"); + s.to = vec!["*".into()]; + assert!(s.check().is_err(), "`to` goes per folder"); + s.to = Vec::new(); + s.folders[1].path = "../x".into(); + assert!(s.check().is_err()); + s.folders[1].path = "".into(); + assert!(s.check().is_err(), "a folder twice"); + } + + #[test] + fn a_skill_in_two_folders_is_handed_out_from_neither() { + let dir = tempfile::tempdir().unwrap(); + let src = dir.path().join(SOURCES).join("core"); + write(&src, "a/SKILL.md", "---\nname: a\ndescription: d\n---\n"); + write(&src, "b/SKILL.md", "---\nname: b\ndescription: d\n---\n"); + write( + &src, + "p/shop/a/SKILL.md", + "---\nname: a\ndescription: d\n---\n", + ); + write( + &src, + "p/shop/page/SKILL.md", + "---\nname: page\ndescription: d\nmetadata:\n repos: [acme/web]\n---\n", + ); + let mut s = set("core"); + s.to = Vec::new(); + s.folders = vec![ + SkillFolder { + path: "".into(), + to: vec!["*".into()], + repos: Vec::new(), + }, + SkillFolder { + path: "p/shop".into(), + to: vec!["shop".into()], + repos: vec!["acme/shop".into()], + }, + ]; + let m = refresh(dir.path(), &s); + let names: Vec<&str> = m.skills.iter().map(|k| k.name.as_str()).collect(); + assert_eq!(names, ["b", "page"], "{:?}", m.skipped); + // Its own `metadata.repos` before its folder's. + assert_eq!(m.skills[1].repos, ["acme/web"]); + assert_eq!(m.skills[1].folder.as_deref(), Some("p/shop")); + assert_eq!(m.skills[0].folder.as_deref(), Some("")); + assert_eq!(m.skipped.len(), 3, "{:?}", m.skipped); + } + #[test] fn a_folder_source_is_packed_and_a_wrong_skill_left_out() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/devstack-node/tests/skills.rs b/crates/devstack-node/tests/skills.rs index 8584eb32..0cfe5d42 100644 --- a/crates/devstack-node/tests/skills.rs +++ b/crates/devstack-node/tests/skills.rs @@ -5,7 +5,7 @@ use devstack_node::coordinator; use devstack_node::events::{self, Ended, Heard}; use devstack_node::member::{Local, MemberError}; -use devstack_node::skills::{SkillSet, Source}; +use devstack_node::skills::{SkillFolder, SkillSet, Source}; use devstack_node::store::{Role, SHELL, Store}; use std::path::Path; use std::time::{Duration, Instant}; @@ -79,6 +79,8 @@ fn a_set_goes_to_whom_it_is_given_and_its_change_is_told() { path: "core".into(), }, to: vec!["team".into()], + repos: Vec::new(), + folders: Vec::new(), }; assert!(matches!( dev.admin_skill_put(&set), @@ -144,6 +146,80 @@ fn a_set_goes_to_whom_it_is_given_and_its_change_is_told() { assert!(dev.skills().unwrap().is_empty()); } +#[test] +fn each_folder_of_a_set_goes_to_its_own_members() { + let c = tempfile::tempdir().unwrap(); + let (url, fp) = coordinator(c.path()); + // `core/work-issue` for everyone, `core/projects/shop/shop-page` for + // the tag `shop` only, bound to its repository by the folder. + skill(c.path(), "work-issue", "Work on an issue"); + let d = c.path().join("skill-sources/core/projects/shop/shop-page"); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write( + d.join("SKILL.md"), + "---\nname: shop-page\ndescription: A page of the shop\n---\n", + ) + .unwrap(); + let ad = tempfile::tempdir().unwrap(); + let admin = member(c.path(), &url, &fp, ad.path(), "lead-pc", Role::Admin); + let md = tempfile::tempdir().unwrap(); + let dev = member(c.path(), &url, &fp, md.path(), "dev-pc", Role::Member); + let od = tempfile::tempdir().unwrap(); + let other = member(c.path(), &url, &fp, od.path(), "guest-pc", Role::Member); + let dev_id = dev.membership().unwrap().unwrap().id; + admin.admin_tags(&dev_id, &["shop".into()]).unwrap(); + + let set = SkillSet { + name: "core".into(), + source: Source::Folder { + path: "core".into(), + }, + to: Vec::new(), + repos: Vec::new(), + folders: vec![ + SkillFolder { + path: String::new(), + to: vec!["*".into()], + repos: Vec::new(), + }, + SkillFolder { + path: "projects/shop".into(), + to: vec!["shop".into()], + repos: vec!["acme/shop".into()], + }, + ], + }; + admin.admin_skill_put(&set).unwrap(); + let names = |l: &Local| -> Vec { + l.skills() + .unwrap() + .iter() + .flat_map(|m| m.skills.iter().map(|k| k.name.clone())) + .collect() + }; + until("the set is fetched", || { + (names(&dev).len() == 2).then_some(()) + }); + let mine = dev.skills().unwrap(); + let shop = mine[0] + .skills + .iter() + .find(|k| k.name == "shop-page") + .unwrap(); + assert_eq!(shop.repos, ["acme/shop"]); + assert_eq!(shop.folder.as_deref(), Some("projects/shop")); + assert_eq!(names(&other), ["work-issue"]); + assert!(other.skill_archive("core", "work-issue").is_ok()); + assert!( + matches!( + other.skill_archive("core", "shop-page"), + Err(MemberError::Status(404, _)) + ), + "a folder not given to it is not downloaded either" + ); + assert!(dev.skill_archive("core", "shop-page").is_ok()); +} + #[test] fn a_refresh_without_a_signature_is_refused() { let c = tempfile::tempdir().unwrap(); diff --git a/crates/devstack-skills/agents.toml b/crates/devstack-skills/agents.toml index 7f0a9174..89f7ca1e 100644 --- a/crates/devstack-skills/agents.toml +++ b/crates/devstack-skills/agents.toml @@ -1,5 +1,6 @@ # The coding agents devstack knows (ADR-0074): each one's user skill folder, -# and the paths that tell it installed. Taken from src/agents.ts of +# its skill folder in a working tree (`project`, ADR-0079), and the paths +# that tell it installed. Taken from src/agents.ts of # https://github.com/vercel-labs/skills (MIT, Copyright (c) Vercel, Inc.) # by scripts/sync-agents.py; `[agent.open]` is devstack's own (how # "Open with" starts the agent) and kept when the table is taken again. @@ -9,54 +10,63 @@ id = "aider-desk" name = "AiderDesk" skills = "~/.aider-desk/skills" +project = ".aider-desk/skills" detect = ["~/.aider-desk"] [[agent]] id = "amp" name = "Amp" skills = "${XDG_CONFIG_HOME:-~/.config}/agents/skills" +project = ".agents/skills" detect = ["${XDG_CONFIG_HOME:-~/.config}/amp"] [[agent]] id = "antigravity" name = "Antigravity" skills = "~/.gemini/antigravity/skills" +project = ".agents/skills" detect = ["~/.gemini/antigravity"] [[agent]] id = "antigravity-cli" name = "Antigravity CLI" skills = "~/.gemini/antigravity-cli/skills" +project = ".agents/skills" detect = ["~/.gemini/antigravity-cli"] [[agent]] id = "astrbot" name = "AstrBot" skills = "~/.astrbot/data/skills" +project = "data/skills" detect = ["~/.astrbot"] [[agent]] id = "autohand-code" name = "Autohand Code CLI" skills = "${AUTOHAND_HOME:-~/.autohand}/skills" +project = ".autohand/skills" detect = ["${AUTOHAND_HOME:-~/.autohand}"] [[agent]] id = "augment" name = "Augment" skills = "~/.augment/skills" +project = ".augment/skills" detect = ["~/.augment"] [[agent]] id = "bob" name = "IBM Bob" skills = "~/.bob/skills" +project = ".bob/skills" detect = ["~/.bob"] [[agent]] id = "claude-code" name = "Claude Code" skills = "${CLAUDE_CONFIG_DIR:-~/.claude}/skills" +project = ".claude/skills" detect = ["${CLAUDE_CONFIG_DIR:-~/.claude}"] [agent.open] links = [{ scheme = "claude-cli", label = "Claude Code" }, { scheme = "claude", label = "Claude Desktop" }] @@ -65,358 +75,418 @@ links = [{ scheme = "claude-cli", label = "Claude Code" }, { scheme = "claude", id = "cline" name = "Cline" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.cline"] [[agent]] id = "codearts-agent" name = "CodeArts Agent" skills = "~/.codeartsdoer/skills" +project = ".codeartsdoer/skills" detect = ["~/.codeartsdoer"] [[agent]] id = "codebuddy" name = "CodeBuddy" skills = "~/.codebuddy/skills" +project = ".codebuddy/skills" detect = ["~/.codebuddy"] [[agent]] id = "codemaker" name = "Codemaker" skills = "~/.codemaker/skills" +project = ".codemaker/skills" detect = ["~/.codemaker"] [[agent]] id = "codestudio" name = "Code Studio" skills = "~/.codestudio/skills" +project = ".codestudio/skills" detect = ["~/.codestudio"] [[agent]] id = "codex" name = "Codex" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["${CODEX_HOME:-~/.codex}", "/etc/codex"] [[agent]] id = "command-code" name = "Command Code" skills = "~/.commandcode/skills" +project = ".commandcode/skills" detect = ["~/.commandcode"] [[agent]] id = "continue" name = "Continue" skills = "~/.continue/skills" +project = ".continue/skills" detect = ["~/.continue"] [[agent]] id = "cortex" name = "Cortex Code" skills = "~/.snowflake/cortex/skills" +project = ".cortex/skills" detect = ["~/.snowflake/cortex"] [[agent]] id = "crush" name = "Crush" skills = "~/.config/crush/skills" +project = ".crush/skills" detect = ["~/.config/crush"] [[agent]] id = "cursor" name = "Cursor" skills = "~/.cursor/skills" +project = ".agents/skills" detect = ["~/.cursor"] [[agent]] id = "deepagents" name = "Deep Agents" skills = "~/.deepagents/agent/skills" +project = ".agents/skills" detect = ["~/.deepagents"] [[agent]] id = "devin" name = "Devin for Terminal" skills = "${XDG_CONFIG_HOME:-~/.config}/devin/skills" +project = ".devin/skills" detect = ["${XDG_CONFIG_HOME:-~/.config}/devin"] [[agent]] id = "dexto" name = "Dexto" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.dexto"] [[agent]] id = "droid" name = "Droid" skills = "~/.factory/skills" +project = ".agents/skills" detect = ["~/.factory"] [[agent]] id = "firebender" name = "Firebender" skills = "~/.firebender/skills" +project = ".agents/skills" detect = ["~/.firebender"] [[agent]] id = "forgecode" name = "ForgeCode" skills = "~/.forge/skills" +project = ".forge/skills" detect = ["~/.forge"] [[agent]] id = "fx" name = "fx" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.fx"] [[agent]] id = "gemini-cli" name = "Gemini CLI" skills = "~/.gemini/skills" +project = ".agents/skills" detect = ["~/.gemini"] [[agent]] id = "github-copilot" name = "GitHub Copilot" skills = "~/.copilot/skills" +project = ".agents/skills" detect = ["~/.copilot"] [[agent]] id = "goose" name = "Goose" skills = "${XDG_CONFIG_HOME:-~/.config}/goose/skills" +project = ".goose/skills" detect = ["${XDG_CONFIG_HOME:-~/.config}/goose"] [[agent]] id = "grok" name = "Grok Build" skills = "${GROK_HOME:-~/.grok}/skills" +project = ".grok/skills" detect = ["${GROK_HOME:-~/.grok}"] [[agent]] id = "hermes-agent" name = "Hermes Agent" skills = "${HERMES_HOME:-~/.hermes}/skills" +project = ".hermes/skills" detect = ["${HERMES_HOME:-~/.hermes}"] [[agent]] id = "inference-sh" name = "inference.sh" skills = "~/.inferencesh/skills" +project = ".inferencesh/skills" detect = ["~/.inferencesh"] [[agent]] id = "jazz" name = "Jazz" skills = "~/.jazz/skills" +project = ".jazz/skills" detect = ["~/.jazz"] [[agent]] id = "junie" name = "Junie" skills = "~/.junie/skills" +project = ".junie/skills" detect = ["~/.junie"] [[agent]] id = "iflow-cli" name = "iFlow CLI" skills = "~/.iflow/skills" +project = ".iflow/skills" detect = ["~/.iflow"] [[agent]] id = "kilo" name = "Kilo Code" skills = "~/.kilo/skills" +project = ".agents/skills" detect = ["~/.kilo", "~/.kilocode"] [[agent]] id = "kimi-code-cli" name = "Kimi Code CLI" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.kimi-code", "~/.kimi"] [[agent]] id = "kiro-cli" name = "Kiro CLI" skills = "~/.kiro/skills" +project = ".kiro/skills" detect = ["~/.kiro"] [[agent]] id = "kode" name = "Kode" skills = "~/.kode/skills" +project = ".kode/skills" detect = ["~/.kode"] [[agent]] id = "lingma" name = "Lingma" skills = "~/.lingma/skills" +project = ".lingma/skills" detect = ["~/.lingma"] [[agent]] id = "loaf" name = "Loaf" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.loaf"] [[agent]] id = "mcpjam" name = "MCPJam" skills = "~/.mcpjam/skills" +project = ".mcpjam/skills" detect = ["~/.mcpjam"] [[agent]] id = "mistral-vibe" name = "Mistral Vibe" skills = "${VIBE_HOME:-~/.vibe}/skills" +project = ".vibe/skills" detect = ["${VIBE_HOME:-~/.vibe}"] [[agent]] id = "moxby" name = "Moxby" skills = "~/.moxby/skills" +project = ".moxby/skills" detect = ["~/.moxby"] [[agent]] id = "mux" name = "Mux" skills = "~/.mux/skills" +project = ".mux/skills" detect = ["~/.mux"] [[agent]] id = "opencode" name = "OpenCode" skills = "${XDG_CONFIG_HOME:-~/.config}/opencode/skills" +project = ".agents/skills" detect = ["${XDG_CONFIG_HOME:-~/.config}/opencode"] [[agent]] id = "openhands" name = "OpenHands" skills = "~/.openhands/skills" +project = ".openhands/skills" detect = ["~/.openhands"] [[agent]] id = "ona" name = "Ona" skills = "~/.ona/skills" +project = ".ona/skills" detect = ["~/.ona"] [[agent]] id = "pi" name = "Pi" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.pi/agent"] [[agent]] id = "qoder" name = "Qoder" skills = "~/.qoder/skills" +project = ".qoder/skills" detect = ["~/.qoder"] [[agent]] id = "qoder-cn" name = "Qoder CN" skills = "~/.qoder-cn/skills" +project = ".qoder/skills" detect = ["~/.qoder-cn"] [[agent]] id = "qwen-code" name = "Qwen Code" skills = "~/.qwen/skills" +project = ".qwen/skills" detect = ["~/.qwen"] [[agent]] id = "reasonix" name = "Reasonix" skills = "~/.reasonix/skills" +project = ".reasonix/skills" detect = ["~/.reasonix"] [[agent]] id = "rovodev" name = "Rovo Dev" skills = "~/.rovodev/skills" +project = ".rovodev/skills" detect = ["~/.rovodev"] [[agent]] id = "roo" name = "Roo Code" skills = "~/.roo/skills" +project = ".roo/skills" detect = ["~/.roo"] [[agent]] id = "sarvam-code" name = "Sarvam Code" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["${SARVAM_HOME:-~/.sarvam}"] [[agent]] id = "tabnine-cli" name = "Tabnine CLI" skills = "~/.tabnine/agent/skills" +project = ".tabnine/agent/skills" detect = ["~/.tabnine"] [[agent]] id = "terramind" name = "Terramind" skills = "~/.terramind/skills" +project = ".terramind/skills" detect = ["~/.terramind"] [[agent]] id = "tinycloud" name = "Tinycloud" skills = "~/.tinycloud/skills" +project = ".tinycloud/skills" detect = ["~/.tinycloud"] [[agent]] id = "trae" name = "Trae" skills = "~/.trae/skills" +project = ".trae/skills" detect = ["~/.trae"] [[agent]] id = "trae-cn" name = "Trae CN" skills = "~/.trae-cn/skills" +project = ".trae/skills" detect = ["~/.trae-cn"] [[agent]] id = "warp" name = "Warp" skills = "~/.agents/skills" +project = ".agents/skills" detect = ["~/.warp"] [[agent]] id = "windsurf" name = "Windsurf" skills = "~/.codeium/windsurf/skills" +project = ".windsurf/skills" detect = ["~/.codeium/windsurf"] [[agent]] id = "zencoder" name = "Zencoder" skills = "~/.zencoder/skills" +project = ".zencoder/skills" detect = ["~/.zencoder"] [[agent]] id = "zenflow" name = "Zenflow" skills = "~/.zencoder/skills" +project = ".zencoder/skills" detect = ["~/.zencoder"] [[agent]] id = "neovate" name = "Neovate" skills = "~/.neovate/skills" +project = ".neovate/skills" detect = ["~/.neovate"] [[agent]] id = "pochi" name = "Pochi" skills = "~/.pochi/skills" +project = ".pochi/skills" detect = ["~/.pochi"] [[agent]] id = "adal" name = "AdaL" skills = "~/.adal/skills" +project = ".adal/skills" detect = ["~/.adal"] diff --git a/crates/devstack-skills/src/agents.rs b/crates/devstack-skills/src/agents.rs index f5245e22..2eb80eff 100644 --- a/crates/devstack-skills/src/agents.rs +++ b/crates/devstack-skills/src/agents.rs @@ -1,5 +1,6 @@ //! The coding agents devstack knows (ADR-0074): each one's user skill -//! folder and how it is told installed, as data (`agents.toml`, taken from +//! folder, its skill folder in a working tree (ADR-0079), and how it is +//! told installed, as data (`agents.toml`, taken from //! vercel-labs/skills by `scripts/sync-agents.py`). The hub installs a //! pool's skill sets into these folders; "Open with" takes its agents from //! here too, with what `[agent.open]` adds. @@ -19,6 +20,10 @@ pub struct Agent { pub name: String, /// Its user skill folder, as the table writes it. pub skills: String, + /// Its skill folder in a working tree (`.claude/skills`), where the + /// skills bound to a repository go (ADR-0079); `None`: it has none. + #[serde(default)] + pub project: Option, /// Paths of which one exists when it is installed. pub detect: Vec, #[serde(default)] @@ -138,6 +143,14 @@ mod tests { ] { assert!(get(id).is_some(), "{id}"); } + assert_eq!( + get("claude-code").unwrap().project.as_deref(), + Some(".claude/skills") + ); + assert_eq!( + get("codex").unwrap().project.as_deref(), + Some(".agents/skills") + ); let links = &get("claude-code").unwrap().open.as_ref().unwrap().links; assert!(links.iter().any(|l| l.scheme == "claude-cli")); } diff --git a/crates/devstack-skills/src/lib.rs b/crates/devstack-skills/src/lib.rs index 24838a7b..0be2c6b6 100644 --- a/crates/devstack-skills/src/lib.rs +++ b/crates/devstack-skills/src/lib.rs @@ -10,6 +10,11 @@ //! this stack file (a new version alone does not count). What is //! specific to a project beyond that belongs in a skill of the project's own, //! which devstack never touches. +//! +//! A generated skill is local to the working tree (ADR-0079): its folder +//! holds a `.gitignore` that ignores the folder, so git leaves it out, and +//! the hub keeps it in step with this devstack ([`install_into`]); one git +//! still tracks (an earlier devstack's) is left to the upgrade prompt. pub mod agents; @@ -23,6 +28,10 @@ const VERSION: &str = devstack_config::VERSION; const REPO_URL: &str = "https://github.com/nuetzliches/devstack"; /// The words that tell a generated skill from one a project wrote itself. const MARKER_TAG: &str = "(devstack skills install)"; +/// The `.gitignore` of a skill folder devstack writes into a working tree +/// (ADR-0079): it ignores the folder, itself included. +pub const IGNORE_ALL: &str = + "# Written by devstack: this skill is local to the working tree, not the repository's.\n*\n"; const TEMPLATES: &[(&str, &str)] = &[ ( @@ -369,6 +378,49 @@ pub fn install( Ok(done) } +/// What the hub writes (ADR-0079): the skills into `dirs` (the agents' skill +/// folders in the working tree of `stack_file`), and a generated copy found +/// in another agent's folder refreshed. A path `skip` says no to (one git +/// tracks) is left alone; a skill the project wrote itself too. +pub fn install_into( + stack: &Stack, + stack_file: &Path, + dirs: &[PathBuf], + skip: &dyn Fn(&Path) -> bool, +) -> Result> { + let rendered = render_all(stack, stack_file); + let mut targets: Vec<(PathBuf, bool)> = dirs.iter().map(|d| (d.clone(), true)).collect(); + for d in search_dirs(stack, stack_file)? { + if !targets.iter().any(|(t, _)| *t == d) { + targets.push((d, false)); + } + } + let mut done = Vec::new(); + for (dir, asked) in targets { + for (name, content) in &rendered { + let folder = dir.join(name); + if !asked && !generated(&folder) { + continue; + } + // Asked (git, for `skip`) only when something is to be written. + let path = folder.join("SKILL.md"); + let same = std::fs::read_to_string(&path) + .is_ok_and(|e| normalize(&e) == normalize(content)) + && std::fs::read_to_string(folder.join(".gitignore")) + .is_ok_and(|e| normalize(&e) == IGNORE_ALL); + if same { + done.push(Outcome::Unchanged(path)); + continue; + } + if skip(&folder) { + continue; + } + done.push(write_one(&path, content, false)?); + } + } + Ok(done) +} + /// A generated skill in `skill_dir` (its own folder, `…/skills/devstack`). fn generated(skill_dir: &Path) -> bool { std::fs::read_to_string(skill_dir.join("SKILL.md")).is_ok_and(|e| e.contains(MARKER_TAG)) @@ -376,17 +428,32 @@ fn generated(skill_dir: &Path) -> bool { fn write_one(path: &Path, content: &str, force: bool) -> Result { let path = path.to_path_buf(); + let folder = path.parent().expect("has a parent"); match std::fs::read_to_string(&path).ok() { - Some(e) if normalize(&e) == normalize(content) => return Ok(Outcome::Unchanged(path)), + Some(e) if normalize(&e) == normalize(content) => { + ignore_folder(folder)?; + return Ok(Outcome::Unchanged(path)); + } Some(e) if !e.contains(MARKER_TAG) && !force => return Ok(Outcome::Kept(path)), _ => {} } - std::fs::create_dir_all(path.parent().expect("has a parent")) - .with_context(|| format!("create {}", path.display()))?; + std::fs::create_dir_all(folder).with_context(|| format!("create {}", folder.display()))?; + // The ignore first: git, and a watcher that reads the ignore rules, + // never take the skill for the repository's. + ignore_folder(folder)?; std::fs::write(&path, content).with_context(|| format!("write {}", path.display()))?; Ok(Outcome::Written(path)) } +/// The `.gitignore` that keeps a generated skill's folder out of git. +fn ignore_folder(folder: &Path) -> Result<()> { + let p = folder.join(".gitignore"); + if std::fs::read_to_string(&p).is_ok_and(|e| normalize(&e) == IGNORE_ALL) { + return Ok(()); + } + std::fs::write(&p, IGNORE_ALL).with_context(|| format!("write {}", p.display())) +} + fn normalize(s: &str) -> String { s.replace("\r\n", "\n") } @@ -730,4 +797,34 @@ ours" "two folders named, one copy elsewhere" ); } + + #[test] + fn a_generated_skill_ignores_itself_and_the_hub_leaves_a_tracked_one() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("devstack.toml"); + std::fs::write(&file, STACK).unwrap(); + let stack = devstack_config::load(&file).unwrap(); + install(&stack, &file, None, false).unwrap(); + let claude = dir.path().join(".claude/skills/devstack"); + assert_eq!( + std::fs::read_to_string(claude.join(".gitignore")).unwrap(), + IGNORE_ALL + ); + + // The hub: into the folders it is given, a copy elsewhere refreshed, + // one `skip` says no to (git tracks it) left as it is. + let agents = dir.path().join(".agents/skills"); + age(&claude.join("SKILL.md"), true); + let old = std::fs::read_to_string(claude.join("SKILL.md")).unwrap(); + let tracked = |f: &Path| f.ends_with(".claude/skills/devstack"); + install_into(&stack, &file, std::slice::from_ref(&agents), &tracked).unwrap(); + assert!(agents.join("devstack/SKILL.md").is_file()); + assert!(agents.join("devstack/.gitignore").is_file()); + assert_eq!( + std::fs::read_to_string(claude.join("SKILL.md")).unwrap(), + old + ); + install_into(&stack, &file, &[], &|_| false).unwrap(); + assert!(outdated(&file).is_empty(), "{:?}", outdated(&file)); + } } diff --git a/crates/devstack/src/dispatch/skills.rs b/crates/devstack/src/dispatch/skills.rs index 245baa9d..70f287aa 100644 --- a/crates/devstack/src/dispatch/skills.rs +++ b/crates/devstack/src/dispatch/skills.rs @@ -8,16 +8,39 @@ pub(crate) fn run(file: &Path, action: SkillsAction) -> Result<()> { match action { SkillsAction::Install { dir, force } => { let stack = load(file); + let mut tracked = Vec::new(); for o in skills::install(&stack, file, dir.as_deref(), force)? { + let fresh = matches!(o, skills::Outcome::Written(_)); match o { - skills::Outcome::Written(p) => println!("written {}", p.display()), - skills::Outcome::Unchanged(p) => println!("up to date {}", p.display()), + skills::Outcome::Written(p) | skills::Outcome::Unchanged(p) => { + println!( + "{} {}", + if fresh { "written " } else { "up to date" }, + p.display() + ); + if let Some(folder) = p.parent() + && git_tracks(folder) + { + tracked.push(folder.to_path_buf()); + } + } skills::Outcome::Kept(p) => println!( "kept {} (written by the project, not by devstack; --force replaces it)", p.display() ), } } + // Local to the working tree since ADR-0079: a copy an earlier + // devstack had committed is the user's to take out of git (a + // migration aid, #389). + if !tracked.is_empty() { + println!( + "git still tracks these generated skills; they are local to the working tree now (each ignores itself). Take them out of git, the files stay:" + ); + for f in tracked { + println!(" git rm -r --cached \"{}\"", f.display()); + } + } Ok(()) } SkillsAction::Check => { @@ -33,3 +56,14 @@ pub(crate) fn run(file: &Path, action: SkillsAction) -> Result<()> { } } } + +/// Whether git tracks a file in `folder`. +fn git_tracks(folder: &Path) -> bool { + let mut cmd = std::process::Command::new("git"); + cmd.args(["ls-files", "--", "."]) + .current_dir(folder) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + cmd.output() + .is_ok_and(|o| o.status.success() && !o.stdout.is_empty()) +} diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index eab7d00e..d27aa821 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -419,15 +419,23 @@ enum PoolSkillsAction { /// The branch, tag or commit of `--github`. #[arg(long = "ref", default_value = "main")] reference: String, - /// The folder of the skills in the repository; the top by default. - #[arg(long, default_value = "")] - path: String, + /// The folder of the skills in the source; the top by default. + /// Several (ADR-0079): each its own folder of the set, below the + /// top, with the `--to` (and `--repos`) of the same place. + #[arg(long)] + path: Vec, /// A folder below `skill-sources/` in the coordinator's directory. #[arg(long)] folder: Option, /// Whom it is given to, comma-separated: `*`, member ids, tags. - #[arg(long, value_delimiter = ',', default_value = "*")] + /// With several `--path`, one per path, in their order. + #[arg(long)] to: Vec, + /// The repositories its skills without `metadata.repos` are bound + /// to, comma-separated `owner/name` (ADR-0079). With several + /// `--path`, none or one per path (`-`: none). + #[arg(long)] + repos: Vec, }, /// Stop handing a set out (admins): members' hubs remove its skills. Remove { name: String }, @@ -1089,7 +1097,12 @@ mod tests { assert!(matches!( parse(&["pool", "skills", "add", "core", "--github", "org/skills", "--path", "skills", "--to", "team,*"]).cmd, Cmd::Pool { action: Some(PoolAction::Skills { action: Some(PoolSkillsAction::Add { name, github: Some(repo), reference, path, to, .. }) }), .. } - if name == "core" && repo == "org/skills" && reference == "main" && path == "skills" && to == ["team", "*"] + if name == "core" && repo == "org/skills" && reference == "main" && path == ["skills"] && to == ["team,*"] + )); + assert!(matches!( + parse(&["pool", "skills", "add", "team", "--github", "org/skills", "--path", "skills", "--to", "*", "--path", "projects/shop/skills", "--to", "tag:shop", "--repos", "-", "--repos", "acme/shop"]).cmd, + Cmd::Pool { action: Some(PoolAction::Skills { action: Some(PoolSkillsAction::Add { path, to, repos, .. }) }), .. } + if path == ["skills", "projects/shop/skills"] && to == ["*", "tag:shop"] && repos == ["-", "acme/shop"] )); assert!(matches!( parse(&["pool", "upstreams"]).cmd, diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index 222109ed..76e051e0 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -1306,23 +1306,84 @@ pub fn skills(pool: &str, action: Option) -> Result<()> path, folder, to, + repos, } => { + let list = |s: &str| -> Vec { + s.split(',') + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty() && t != "-") + .collect() + }; + // One path: the source's; several: the set's folders below its top. + let several = path.len() > 1; + let top = if several { + String::new() + } else { + path.first().cloned().unwrap_or_default() + }; let source = match (github, folder) { (Some(repo), None) => Source::Github { repo, reference, - path, + path: top, + }, + (None, Some(f)) if top.is_empty() => Source::Folder { path: f }, + (None, Some(f)) => Source::Folder { + path: format!("{}/{}", f.trim_end_matches('/'), top.trim_matches('/')), }, - (None, Some(path)) => Source::Folder { path }, _ => bail!("name a source: `--github owner/name` or `--folder `"), }; - let set = SkillSet { - name, - source, - to: to.into_iter().filter(|t| !t.trim().is_empty()).collect(), + let set = if several { + if to.len() != path.len() { + bail!("with several `--path`, give one `--to` per path, in their order"); + } + if !repos.is_empty() && repos.len() != path.len() { + bail!("with several `--path`, give no `--repos` or one per path (`-`: none)"); + } + SkillSet { + name, + source, + to: Vec::new(), + repos: Vec::new(), + folders: path + .iter() + .enumerate() + .map(|(i, p)| devstack_node::skills::SkillFolder { + path: p.trim_matches('/').to_string(), + to: list(&to[i]), + repos: repos.get(i).map(|r| list(r)).unwrap_or_default(), + }) + .collect(), + } + } else { + if to.len() > 1 || repos.len() > 1 { + bail!("one `--to` and one `--repos` for a set of one path (comma-separated)"); + } + SkillSet { + name, + source, + to: to.first().map_or_else(|| vec!["*".into()], |t| list(t)), + repos: repos.first().map(|r| list(r)).unwrap_or_default(), + folders: Vec::new(), + } }; set.check().map_err(|e| anyhow!(e))?; - local.admin_skill_put(&set)?; + let back = local.admin_skill_put(&set)?; + // A coordinator before ADR-0079 drops the folders and the + // binding: the set is taken out again rather than handed out + // wider than asked. + let kept = back + .sets + .iter() + .find(|s| s.set.name == set.name) + .is_some_and(|s| s.set.folders == set.folders && s.set.repos == set.repos); + if !kept { + let _ = local.admin_skill_remove(&set.name); + bail!( + "the coordinator is older and left the folders or `--repos` out, so `{}` was removed again: update the coordinator first", + set.name + ); + } println!( "pool `{pool}` hands out `{}` ({}); the coordinator fetches it now, and each member's hub offers it in the dashboard", set.name, @@ -1351,12 +1412,25 @@ pub fn skills(pool: &str, action: Option) -> Result<()> } for s in &v.sets { let m = &s.manifest; - println!( - "{:<16} {} to {}", - s.set.name, - s.set.source.label(), - s.set.to.join(",") - ); + if s.set.folders.is_empty() { + println!( + "{:<16} {} to {}{}", + s.set.name, + s.set.source.label(), + s.set.to.join(","), + bound(&s.set.repos) + ); + } else { + println!("{:<16} {}", s.set.name, s.set.source.label()); + for f in &s.set.folders { + println!( + " folder {:<24} to {}{}", + if f.path.is_empty() { "(top)" } else { &f.path }, + f.to.join(","), + bound(&f.repos) + ); + } + } print_manifest(m); } if !v.github_token { @@ -1385,12 +1459,21 @@ pub fn skills(pool: &str, action: Option) -> Result<()> Ok(()) } +/// ` (only in acme/shop)` for a binding (ADR-0079), else nothing. +fn bound(repos: &[String]) -> String { + if repos.is_empty() { + String::new() + } else { + format!(" (only in {})", repos.join(", ")) + } +} + fn print_manifest(m: &devstack_node::skills::SetManifest) { if let Some(e) = &m.error { println!(" last fetch failed: {e}"); } for k in &m.skills { - println!(" {:<24} {}", k.name, k.description); + println!(" {:<24} {}{}", k.name, k.description, bound(&k.repos)); } for k in &m.skipped { println!(" left out: {k}"); diff --git a/docs/adr/0071-the-dashboard-writes-no-file-of-a-repository.md b/docs/adr/0071-the-dashboard-writes-no-file-of-a-repository.md index b98222ac..116e2a0d 100644 --- a/docs/adr/0071-the-dashboard-writes-no-file-of-a-repository.md +++ b/docs/adr/0071-the-dashboard-writes-no-file-of-a-repository.md @@ -1,6 +1,6 @@ # ADR-0071: The dashboard writes no file of a repository; a change to one is a prompt for a coding agent -- **Status:** Accepted (2026-10-27) +- **Status:** Accepted (2026-10-27), amended by [ADR-0079](0079-skills-local-to-a-working-tree.md) (2026-10-30) - **Date:** 2026-10-27 - **Deciders:** project owner - **Related:** [ADR-0046](0046-the-hub-opens-a-worktree-in-the-users-programs.md) (prompts for an agent; the `skills` prompt added here), [ADR-0047](0047-the-dashboard-makes-a-lane-from-a-branch.md) (worktrees, unchanged), [ADR-0055](0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md) (point 4 replaced here), [ADR-0021](0021-a-hub-serves-the-dashboard.md) @@ -52,6 +52,14 @@ And a button a click away is proposed again whenever a prompt seems slower. install`, a copy by hand: the user or their agent runs them in the repository, which is the point of this decision. +**Amendment 2026-10-30 ([ADR-0079](0079-skills-local-to-a-working-tree.md)).** +The hub writes agent skills devstack owns into a working tree: devstack's +generated skills and a pool's skills bound to the repository, each in a +folder that ignores itself with a `.gitignore` of `*`. Git never sees +them, so nothing unread gets committed, which is what point 1 guards +against; a file git tracks stays off limits, and taking an earlier +devstack's committed skills out of git is still a prompt. + ## Alternatives considered - **Keep the buttons, and say what they write.** Fast, but the files still diff --git a/docs/adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md b/docs/adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md index d01f3bbb..859dc240 100644 --- a/docs/adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md +++ b/docs/adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md @@ -1,6 +1,6 @@ # ADR-0074: A pool hands out skill sets; each member's hub installs them into the coding agents' user skill folders -- **Status:** Accepted (2026-10-29) +- **Status:** Accepted (2026-10-29), extended by [ADR-0079](0079-skills-local-to-a-working-tree.md) - **Date:** 2026-10-29 - **Deciders:** project owner - **Related:** [ADR-0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) (the pool's MCP upstreams, the model for acceptance and precedence), [ADR-0071](0071-the-dashboard-writes-no-file-of-a-repository.md) (nothing goes into a repository), [ADR-0073](0073-a-pool-tells-its-members-what-changed-over-one-stream.md) (how a change reaches the members), [ADR-0046](0046-the-hub-opens-a-worktree-in-the-users-programs.md) ("Open with"), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) @@ -108,7 +108,9 @@ What was built: - Every skill a member accepts reaches every agent switched on, in every repository: a project's skills are visible in sessions for other projects. The allocation keeps them to the project's members; a skill's - description says which repository it is for. + description says which repository it is for. Since ADR-0079 a skill + bound to repositories (`metadata.repos`) goes into their working trees + only, and a set's folders can go to different members. - A member removed from the pool loses its sets: its stream ends and its hub removes their skills (but ones it changed). - An agent picks up a skill's new content at its next use; a new or diff --git a/docs/adr/0079-skills-local-to-a-working-tree.md b/docs/adr/0079-skills-local-to-a-working-tree.md new file mode 100644 index 00000000..4f31245f --- /dev/null +++ b/docs/adr/0079-skills-local-to-a-working-tree.md @@ -0,0 +1,169 @@ +# ADR-0079: Skills local to a working tree: a pool's project skills bound to their repository, devstack's own untracked + +- **Status:** Accepted (2026-10-30) +- **Date:** 2026-10-30 +- **Deciders:** project owner +- **Related:** [ADR-0074](0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md) (skill sets, the agent table; its "per-repository installation" alternative taken up here), [ADR-0077](0077-a-sets-skills-are-grouped-and-switched-one-by-one.md) (`metadata` of a skill), [ADR-0071](0071-the-dashboard-writes-no-file-of-a-repository.md) (amended here), [ADR-0078](0078-the-hub-follows-every-stacks-worktrees.md) (the working trees the hub follows), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) + +## Context + +ADR-0074 installs a pool's skill sets into the agents' user skill folders. +That is right for generic skills; a set that also carries a project's +skills puts them into every session on the machine, in every repository. +Project skills tend to have generic triggers ("new page", "add a button") +and very specific content (one codebase's libraries and paths): an agent in +another repository picks one and scaffolds against libraries that are not +there, and the descriptions cost context in every session. The stopgap was +a description that says "only in `/`" and a first step that +checks `origin`. + +A team that keeps generic and project skills in one source had to register +a set per folder to give the project folder only to the people on that +project. + +devstack's own generated skills (`devstack skills install`) were committed +to each repository, although what they say is decided by the devstack +installed on each machine: every update changed them, and two teammates on +two versions wrote them back and forth. + +Trying the options showed: + +- A skill offered through `devstack mcp` (its description in the server's + `instructions`, its text from a tool) is triggered by prose instead of + the agent's skill mechanism, costs a round trip in harnesses that defer + MCP tools, and has its scripts outside the workspace (permission prompts, + sandboxes). +- Claude Code (2.1.312) and OpenCode find a skill in `.claude/skills` and + `.agents/skills` of a working tree whose folder ignores itself with a + `.gitignore` of `*`; Claude Code runs it. Codex and the Copilot CLI were + not tried. +- devstack's file watcher reads nested `.gitignore` files, so a folder + that ignores itself does not start a build. + +## Decision + +The owner approved the review card in the conversation on **2026-10-30**, +all seven points: + +| Category | Point | Beats | Reversing costs | +|---|---|---|---| +| concept | Each working tree has a local, untracked layer of skills: devstack's generated skills and the pool's skills bound to its repository. The hub writes them into the skill folders in the working tree of the agents switched on (each agent's folder from the agent table; the user's switches per machine decide), for every stack and worktree it follows (ADR-0078). | MCP `instructions` with a `skill` tool; user folders with a rewritten description; `.devstack/skills` with a pointer from `AGENTS.md`. | The layer goes; devstack's skills are committed again, bound ones go into the user folders. | +| trust | Every folder devstack writes there ignores itself (`.gitignore` with `*`); the hub's lock records what it wrote. A foreign or hand-changed skill of the same name stays and is shown as a conflict; a file git tracks is never written. ADR-0071 is amended: ignored copies devstack owns are allowed, tracked files stay off limits. If wrong: the hub overwrites a repository's own skill or one the user changed. | An entry in the repository's `.gitignore` (tracked, a list of names); `.git/info/exclude` (the hub writes git's configuration). | The exception in ADR-0071 goes; the hub removes what its lock names. | +| concept | devstack's generated skills are no longer tracked: their version follows the local devstack, and the hub writes them again when devstack or the stack file changes. `devstack skills install` writes them the same way, ignore included. The upgrade prompt has the agent take tracked copies out of git once. Agents in the cloud and CI, which see tracked files only, have no devstack skills then. | Tracked copies that change with every update and flip between teammates on different versions. | They are tracked again, through the prompt. | +| contract | `metadata.repos: [acme/shop]` in a skill's frontmatter binds it, matched against the last segments of the path of the working tree's `origin`, case and host aside. A bound skill goes only into the agents' folders of the matching working trees, never into the user folders; a skill without `repos` behaves as before. An older hub ignores the field. | A binding by a flag of the set only. | A field in the pool protocol; without it the skills are everywhere again. | +| contract | A set can name several folders, each with its own `to` (and `repos` for its skills without their own); a set of one `path` and `to` stays as it is. | A set per folder (source, acceptance and updates several times). | The pool protocol and `skills.json`; a set of folders would have to be split into sets again. | +| trust | The coordinator checks which folder goes to whom for a skill's archive too, not only in the list. If wrong: a member downloads the knowledge of a project it does not work on. | Filtering the list only. | None; it is only stricter. | +| contract | `GET /hub/skills` carries per skill `repos` and the working trees it is in; the Skills page shows both. | The binding in a skill's detail only. | Hub API, additive. | + +What was built: + +1. **Frontmatter.** `metadata.repos`, a list as `tags` is (brackets, + commas, or one `- item` per line): `owner/name`, or more segments + (`project/_git/name`), at most 16; an entry with a host or other + characters is left out. +2. **Matching.** The URL of `origin` (`git@host:acme/shop.git`, + `https://host/acme/shop`, `ssh://git@host:22/acme/shop.git`) is cut to + its path; an entry matches when it equals the last segments of it, case + aside. A working tree without `origin` matches nothing. Worktrees share + their repository's `origin`. +3. **Sets of folders.** `folders: [{path, to, repos}]` in the coordinator's + `skills.json`, each `path` below the source's; with folders, the set's + own `to` and `repos` are empty. A fetch reads each folder (a GitHub + source's archive once) and records per skill `folder` and `repos` (its + own, else its folder's). A skill name in two folders of a set is left + out of both. `GET /v1/skills` gives a member only the skills of its + folders, `GET /v1/skills/{set}/{skill}.tar.gz` answers `404` for the + others. `devstack pool skills add` takes `--path` with `--to` (and + `--repos`, `-` for none) once per folder; against a coordinator that + drops the folders or the binding, it takes the set out again and says + so. The pool area edits folders as rows. +4. **The hub, a pool's bound skills.** The working trees are the main + trees and worktrees of the stacks registered here, `origin` asked of + git once per repository. A bound skill goes into the folder of each + agent switched on that has one in a working tree (the agent table's + `project`, from `skillsDir` of vercel-labs/skills: `.claude/skills` for + Claude Code, `.agents/skills` for Codex, Cursor, Copilot, OpenCode and + most others), in every matching working tree, once per folder; its + folder gets the `.gitignore`. Before writing, the hub asks git whether + it tracks a file there; then it writes nothing and shows a conflict. A + worktree that goes takes its entries out of the lock. A skill that gains + `repos` leaves the user folders. +5. **The hub, devstack's own skills.** For the same working trees, the hub + renders the generated skills from the stack file the tree runs with + (its own, else the main tree's) and writes them into the folders of the + agents switched on, next to the stack file, refreshing a generated copy + found in another agent's folder. A copy git tracks is left alone; the + banner offers the prompt that untracks it. Nothing is written for a tree + whose stack file does not load. +6. **When.** A thread of the hub looks every three seconds at the + worktrees' version (ADR-0078) and the registered stack files' times, + and writes both kinds again when one changed, once a minute at the + latest; switching an agent writes at once. +7. **The CLI.** `devstack skills install` writes the `.gitignore` into + every generated skill's folder and lists the folders git still tracks, + with the `git rm -r --cached` that takes them out (the files stay). +8. **The prompts.** The upgrade and skills prompts have the agent take + tracked generated skills out of git, whatever version the repository + comes from: a repository may skip releases, and the step does nothing + without such copies. It is a migration aid and goes again once the + repositories have moved, with the hint of `devstack skills install` + ([#389](https://github.com/nuetzliches/devstack/issues/389)). +9. **The dashboard.** The Skills page shows each agent's folder in a + working tree beside its user folder, a bound skill's repositories as a + pill and in its detail with the working trees it is in, and the state + *no working tree here* for one whose repositories are no stack on this + machine. + +`[agents] skills` in the stack file still names the folders `devstack +skills install` writes; the hub goes by the user's agents instead. The key +stays as it is: no stack file changes meaning. + +## Alternatives considered + +- **Bound skills through `devstack mcp`** (descriptions in the server's + `instructions`, the text from a `skill` tool, the files in the hub's + state). Knows the repository and needs no file in the working tree, but + is triggered by prose instead of the agent's skill mechanism, needs a + harness that loads `instructions`, costs a round trip where MCP tools are + deferred, and puts scripts outside the workspace. +- **User folders with a rewritten description** ("only in `acme/shop`") + and an `origin` check. Works in every agent, but the descriptions still + load everywhere: the context cost and the false triggers stay. +- **`.devstack/skills` with a pointer from `AGENTS.md`.** One folder of + devstack's own, but no agent reads skills from there, and the pointer is + a tracked file that changes with the skills. +- **A plugin per project** (Claude Code, a local marketplace enabled per + project). One agent only, and an entry in the project's settings file. +- **An entry in the repository's `.gitignore`.** One place, but a tracked + file to change, and a list of names that changes with the pool's sets. +- **`.git/info/exclude`.** Untracked and shared by the worktrees, but the + hub would write git's own configuration. + +## Consequences + +- A project's skills reach its members (the folder's `to`) and, on their + machines, the working trees of its repository only: twice scoped. +- A repository that is no stack registered here gets no bound skills and + no devstack skills from the hub; `devstack skills install` still writes + the latter. +- An agent that reads both `.claude/skills` and `.agents/skills` sees a + bound skill twice when both are switched on, as with devstack's skills + before. +- `git clean -fdx` removes the local layer; the hub writes it again. +- A coordinator before this release ignores `folders` and `repos`; a hub + before it installs bound skills into the user folders, as ADR-0074 did. +- Not tried: whether Codex and the Copilot CLI find skills in a folder git + ignores. + +## Enforced by + +`crates/devstack-node/src/skills.rs` (`SkillFolder`, `repo_matches`, +`folder_given_to`, `skill_given_to`, `pack`), `crates/devstack-node/src/coordinator.rs` +(`skill_archive`), `crates/devstack-hub/src/poolskills.rs` (`places`, `local`, +`follow`, `registered_trees`, `install`), `crates/devstack-hub/src/branches.rs` +(`origin`, `tracked`), `crates/devstack-skills/src/lib.rs` (`IGNORE_ALL`, +`install_into`), `crates/devstack-skills/agents.toml` (`project`), +`scripts/sync-agents.py`, `crates/devstack/src/poolcmd.rs`, +`crates/devstack/src/dispatch/skills.rs`, `crates/devstack-hub/src/prompts.rs`, +`ui/src/views/SkillsView.vue`, `ui/src/components/PoolSkills.vue`, +`ui/src/lib/skills.ts`, `crates/devstack-node/tests/skills.rs`. diff --git a/docs/adr/README.md b/docs/adr/README.md index e58c7933..c232dbfa 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -153,11 +153,12 @@ stay. | [0068](0068-a-stop-takes-the-containers-too.md) | A stop takes the stack's containers too, unless asked to keep them | Accepted | | [0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) | `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub | Accepted ([card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)): a proxy in the hub, per user; amended 2026-10-27 (keychain via `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, a member accepts each); addendum 2026-10-30 (an OAuth app's client secret, for GitHub) | | [0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) | A review card comes before the code; an ADR records what was built | Accepted (supersedes ADR-0001); point 1 amended 2026-10-28 (the card in the conversation and the pull request, no issue) | -| [0071](0071-the-dashboard-writes-no-file-of-a-repository.md) | The dashboard writes no file of a repository; a change to one is a prompt for a coding agent | Accepted | +| [0071](0071-the-dashboard-writes-no-file-of-a-repository.md) | The dashboard writes no file of a repository; a change to one is a prompt for a coding agent | Accepted, amended by ADR-0079 (skills devstack owns, ignored by git, are written into a working tree) | | [0072](0072-a-restart-is-warm-a-rebuild-or-cold.md) | A restart is warm, a rebuild or cold; a group acts on its containers too | Accepted ([card](https://github.com/nuetzliches/devstack/pull/351)) | | [0073](0073-a-pool-tells-its-members-what-changed-over-one-stream.md) | A pool tells its members what changed, over one stream; nobody polls the coordinator | Accepted (card in the pull request) | -| [0074](0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md) | A pool hands out skill sets; each member's hub installs them into the coding agents' user skill folders | Accepted (card in the pull request) | +| [0074](0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md) | A pool hands out skill sets; each member's hub installs them into the coding agents' user skill folders | Accepted (card in the pull request); extended by ADR-0079 (skills bound to a repository go into its working trees; a set's folders) | | [0075](0075-a-lanes-steady-use-is-measured-and-shown-never-admitted-by.md) | A lane's steady use is measured and shown, never admitted by | Accepted (card in the pull request) | | [0076](0076-a-pool-machine-has-one-page-the-pool-area-has-tabs.md) | A machine of the pool has one page; the pool area has tabs, and the pool and the tab are in the URL | Accepted (card in the pull request) | | [0077](0077-a-sets-skills-are-grouped-and-switched-one-by-one.md) | A set's skills are grouped by their frontmatter and switched one by one | Accepted (card in the pull request; point 5 taken back) | | [0078](0078-the-hub-follows-every-stacks-worktrees.md) | The hub follows every stack's worktrees; a stopped stack's lane can be started from the dashboard | Accepted (card in the pull request) | +| [0079](0079-skills-local-to-a-working-tree.md) | Skills local to a working tree: a pool's project skills bound to their repository, devstack's own untracked | Accepted (card in the pull request) | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index ffb754ce..678429b6 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -66,7 +66,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/stacks/{id}/worktrees/remove {"path"}` | cookie + Origin | `git worktree remove` (never `--force`) of a linked worktree of the stack (`400` for the main working tree or anything else): `{}`; `409 {"error"}` with git's refusal, a worktree with changes. The branch stays | | `POST /hub/stacks/{id}/fetch` | cookie + Origin | `git fetch --all --prune`, without a prompt (`GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`) and within 120 s: `{}`; `409 {"error"}` with what git said | | `GET /hub/stacks/{id}/skills` | cookie | the agent skills `devstack skills install` wrote into the repository (the folders `[agents] skills` names, and generated copies in the other agents' folders), held against what this devstack would write for the stack file: `{found, outdated, from, current, ahead}`. `found`, `outdated`: skills by their folder, `.claude/skills/devstack` (one the project wrote itself is not listed); `from`: the oldest devstack their marker lines name (`null` when none); `current`: this devstack; `ahead`: `from` is newer than `current` (a teammate's newer devstack wrote them; installing would go back). All empty when the stack file does not load. Read while the stack is stopped too | -| *(none)* | | No route writes a file of a repository ([ADR-0071](adr/0071-the-dashboard-writes-no-file-of-a-repository.md)): the skills, a first stack file and a worktree's stack file are prompts for a coding agent (`GET /hub/prompt`, kinds `skills`, `setup`, `lane-file`). `POST /hub/stacks/init`, `POST /hub/stacks/{id}/skills` and `POST /hub/stacks/{id}/worktrees/stack-file` are gone since 0.27.0 (`405`/`404`) | +| *(none)* | | No route writes a file of a repository ([ADR-0071](adr/0071-the-dashboard-writes-no-file-of-a-repository.md); the hub's skill folders that ignore themselves are no file of it, [ADR-0079](adr/0079-skills-local-to-a-working-tree.md)): the skills, a first stack file and a worktree's stack file are prompts for a coding agent (`GET /hub/prompt`, kinds `skills`, `setup`, `lane-file`). `POST /hub/stacks/init`, `POST /hub/stacks/{id}/skills` and `POST /hub/stacks/{id}/worktrees/stack-file` are gone since 0.27.0 (`405`/`404`) | | `GET /hub/stacks/{id}/upgrade` | cookie | how far the stack file is behind this devstack, apart from the agent skills (a refresh of those leaves it): `{reviewed, from, current, behind}`. `reviewed`: `[stack] reviewed`, the devstack the file was last brought up to date with (`null` when not set); `from`: the devstack to read the changes after, `reviewed`, or for a file without it the agent skills' `from` when older than `current` (`null` when unknown); `behind`: `reviewed` is older than `current`, or not set. `behind` is `false` when the stack file does not load. Read while the stack is stopped too | | `GET /hub/stacks/{id}/mcp` | cookie | whether a coding agent finds devstack's MCP server for the repository: `{registered, files}`, `files` the agent configuration files with a server that runs `devstack mcp` (command `devstack`, a path to it or `devstack.exe`, first argument `mcp`). The project's first: `.mcp.json`, `.vscode/mcp.json` (`servers`), `.cursor/mcp.json`, `.codex/config.toml` (`[mcp_servers.*]`); then the user's: `~/.claude.json` (its `mcpServers`, and those of its entry for the repository under `projects`), `~/.cursor/mcp.json`, `~/.codex/config.toml`. A file that does not parse (JSON with comments) counts when it names devstack. Read only; the dashboard offers the prompt `mcp` where `registered` is `false` | | `POST /hub/open {"stack", "path", "with"}` | cookie + Origin | open `path` with the program `with`: `204`. `path` must be the stack's repository or one of its worktrees (`git worktree list`), `with` an id `GET /hub/openers` lists now; `400` otherwise, `404` for an unknown stack, `502 {"error"}` when the program could not be started | @@ -89,12 +89,12 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/pool/upstreams` | cookie | the MCP upstreams the pool names for its members: `[{name, url, prefix?, allow?, auth: {kind: "none"} \| {kind: "token"} \| {kind: "oauth", client_id?, client_secret?, scopes?}}]`, never a user's credential: an OAuth app's client secret is answered as `client_secret: true` (one is set; members' hubs get the value from the coordinator) ([pool.md](pool.md#mcp-upstreams-for-the-members)) | | `POST /hub/pool/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | admins only: add one, or change the one of that name; the list after it. `auth.client_secret` (with a `client_id`): a string sets it, `""` takes it away, left out keeps the one set. `400` with why (a URL over `https://` only, a prefix another entry has, at most 64, a client secret without a client id); the coordinator audits it | | `DELETE /hub/pool/upstreams/{name}` | cookie + Origin | admins only: take one off the list: `204`, `404` when the pool names none such; audited | -| `GET /hub/pool/skills` | cookie | admins only ([ADR-0074](adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md)): `{sets: [{name, source: {kind: "github", repo, ref, path} \| {kind: "folder", path}, to: [string], manifest: {source, fetched?, commit?, error?, skills: [{name, description, sha256, size, group?, tags?}], skipped?}}], github_token, refresh_signed}`; `404` from a coordinator before skill sets | -| `POST /hub/pool/skills {name, source, to}` | cookie + Origin | admins only: add a set, or change the one of that name, and have it fetched; `400` with why; audited | +| `GET /hub/pool/skills` | cookie | admins only ([ADR-0074](adr/0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md)): `{sets: [{name, source: {kind: "github", repo, ref, path} \| {kind: "folder", path}, to: [string], repos?: [string], folders?: [{path, to, repos?}], manifest: {source, fetched?, commit?, error?, skills: [{name, description, sha256, size, group?, tags?, repos?, folder?}], skipped?}}], github_token, refresh_signed}`; `404` from a coordinator before skill sets. `repos` binds the skills without `metadata.repos` of their own to repositories; `folders` (then `to` and `repos` are empty) are folders below the source's path, each given to its own members ([ADR-0079](adr/0079-skills-local-to-a-working-tree.md)) | +| `POST /hub/pool/skills {name, source, to, repos?, folders?}` | cookie + Origin | admins only: add a set, or change the one of that name, and have it fetched; `400` with why; audited | | `DELETE /hub/pool/skills/{name}` | cookie + Origin | admins only: stop handing it out: `204`; audited | | `POST /hub/pool/skills/refresh[?set=]` | cookie + Origin | admins only: have the coordinator fetch the sets (or one) again: `202` | -| `GET /hub/skills` | cookie | the pools' skill sets on this machine (ADR-0074), the agents looked for again (one installed since shows, switched off) and the state told on `/hub/events` too: `{agents: [{id, name, dir, enabled}], sets: [{pool, set, source, state: "offered"\|"accepted"\|"declined"\|"changed", auto, fetched?, commit?, error?, skills: [{name, description, sha256, installed, pending, enabled, group?, tags?, updated?, agents}]}], conflicts: [{dir, name, reason}], errors?, synced?}`; also on `/hub/events` as `{"type":"skills","skills":...}`, first and on every change. Per skill ([ADR-0077](adr/0077-a-sets-skills-are-grouped-and-switched-one-by-one.md)): `enabled` (switched on; older hubs leave it out), `group` and `tags` (from `metadata` in its frontmatter), `updated` (when this hub wrote it, Unix ms), `agents` (the names of the agents whose folder holds it) | -| `PUT /hub/skills/agents/{id} {enabled}` | cookie + Origin | install into that agent's user skill folder, or no longer (what devstack installed there goes); the state after it, `409` with why | +| `GET /hub/skills` | cookie | the pools' skill sets on this machine (ADR-0074), the agents looked for again (one installed since shows, switched off) and the state told on `/hub/events` too: `{agents: [{id, name, dir, project?, enabled}], sets: [{pool, set, source, state: "offered"\|"accepted"\|"declined"\|"changed", auto, fetched?, commit?, error?, skills: [{name, description, sha256, installed, pending, enabled, group?, tags?, updated?, agents, repos?, trees?}]}], conflicts: [{dir, name, reason}], errors?, synced?}`; also on `/hub/events` as `{"type":"skills","skills":...}`, first and on every change. Per skill ([ADR-0077](adr/0077-a-sets-skills-are-grouped-and-switched-one-by-one.md)): `enabled` (switched on; older hubs leave it out), `group` and `tags` (from `metadata` in its frontmatter), `updated` (when this hub wrote it, Unix ms), `agents` (the names of the agents whose folder holds it). [ADR-0079](adr/0079-skills-local-to-a-working-tree.md): an agent's `project` is its skill folder in a working tree; a skill's `repos` binds it to repositories (it goes into the agents' folders of their working trees, not the user folders), `trees` are the working trees it is in, and `installed` means in every folder it goes to | +| `PUT /hub/skills/agents/{id} {enabled}` | cookie + Origin | install into that agent's user skill folder (and, for bound skills and devstack's generated ones, its folder in the working trees), or no longer (what devstack installed there goes); the state after it, `409` with why | | `PUT /hub/skills/sets/{pool}/{set}/skills/{name} {enabled}`, `PUT /hub/skills/sets/{pool}/{set}/groups/{group} {enabled}` | cookie + Origin | switch a skill of an accepted set, or every skill of a group (`-`: the skills without one), on or off (ADR-0077); off, it goes from the agents' folders unless changed there; the state after it, `409` with why | | `POST /hub/skills/sets/{pool}/{set}/accept {auto}`, `.../decline`, `.../update`; `PUT /hub/skills/sets/{pool}/{set} {auto}` | cookie + Origin | accept a set from its source (updates at once with `auto`, else they wait), decline or remove it, take its waiting updates, change `auto`; the state after it | | `POST /hub/skills/sync` | cookie + Origin | bring the agents' folders to the accepted sets again (a skill removed by hand comes back); the state after it | diff --git a/docs/pool.md b/docs/pool.md index 131f4f38..441d601d 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -661,8 +661,9 @@ A pool can hand its members agent skills folders with a `SKILL.md`, from a GitHub repository or a folder on the coordinator, which each member's hub installs into the user skill folders of the coding agents on the machine (`~/.claude/skills`, `~/.agents/skills`, -`~/.config/opencode/skills`, ...). Nothing goes into a repository. An admin -names the sets: +`~/.config/opencode/skills`, ...). A skill bound to repositories goes into +their working trees instead (see below); no file of a repository changes. +An admin names the sets: ```bash devstack pool skills add core --github example-org/skills --path skills --to '*' @@ -696,8 +697,7 @@ status` and `sync` do the same from a terminal. Each skill of an accepted set can be switched off, and a group of them at once ([ADR-0077](adr/0077-a-sets-skills-are-grouped-and-switched-one-by-one.md)); all are on when a set is accepted, a skill the set gains later too. Who -gets a set is still the set's `--to`: split a repository into sets by -`--path` where some skills are not for everyone. Within a set, a skill +gets a skill is the set's `--to`, or its folder's. Within a set, a skill names its group and tags in its frontmatter, for the page's grouping and filters: @@ -711,6 +711,42 @@ metadata: --- ``` +### A project's skills + +A project's skills ("add a page", "add a grid") have generic triggers and +content only one codebase fits. Two things keep them where they belong +([ADR-0079](adr/0079-skills-local-to-a-working-tree.md)): + +- **Folders with their own members.** One set can name several folders of + its source, each with its own `--to` (one `--to`, and `--repos` or none, + per `--path`, in their order); a member reads and downloads only the + skills of its folders: + + ```bash + devstack pool skills add team --github example-org/team-skills \ + --path skills --to '*' \ + --path projects/shop/skills --to shop-team --repos - --repos example-org/shop + ``` + +- **A binding to repositories.** A skill with `metadata.repos` (or of a + folder with `--repos`) goes into no user folder: the member's hub writes + it into the skill folders of the agents switched on in each working tree + whose `origin` is one of those repositories (`.claude/skills` for Claude + Code, `.agents/skills` for most others), its worktrees too. Each such + folder holds a `.gitignore` that ignores it, so git never sees it; a file + git tracks there is never written. An entry matches the last segments of + the `origin` URL, case and host aside: + + ```yaml + metadata: + repos: [example-org/shop] + ``` + +The Skills page shows a bound skill's repositories and the working trees it +is in; *no working tree here* when none of them is a stack on this +machine. devstack's own generated skills live in the same place, ignored +the same way. + ## Several pools A machine can belong to several pools, a customer's beside the team's, each diff --git a/docs/releasing.md b/docs/releasing.md index 526e5e5c..510c3156 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -58,7 +58,8 @@ On a branch `chore/X.Y.Z` from `main`: raised, the binary built here is already `X.Y.Z`, so it writes what the release will: `cargo run -q -p devstack -- skills install` refreshes - `.claude/skills/devstack*`, and `devstack.toml` gets + `.claude/skills/devstack*` (local, ignored by git since ADR-0079; + nothing to commit), and `devstack.toml` gets `reviewed = "X.Y.Z"` in `[stack]`. Raise `requires` only when the file uses something new. `cargo run -q -p devstack -- check` is clean. Otherwise `main` lags one release behind, and the dashboard diff --git a/docs/stack-file.md b/docs/stack-file.md index d50f3418..dae6fb9c 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -952,7 +952,11 @@ skills = [".claude/skills", ".agents/skills"] # default: [".claude/skills"] ``` `skills` names the folders `devstack skills install` writes the generated -agent skills to, relative to the stack file. Claude Code reads +agent skills to, relative to the stack file. The skills are local to the +working tree ([ADR-0079](adr/0079-skills-local-to-a-working-tree.md)): +each folder holds a `.gitignore` that ignores it, so they are not +committed; the hub writes them, for the agents switched on on its Skills +page, into those agents' folders, whatever this key names. Claude Code reads `.claude/skills` only, Codex `.agents/skills` only; Copilot, Cursor, Gemini CLI, OpenCode, Amp and Windsurf read `.agents/skills`, most of them `.claude/skills` too, and then find each skill twice: name both only when diff --git a/scripts/sync-agents.py b/scripts/sync-agents.py index 56ddcb9f..b23b0cc7 100644 --- a/scripts/sync-agents.py +++ b/scripts/sync-agents.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 """Write crates/devstack-skills/agents.toml from vercel-labs/skills' agent table. -devstack keeps the coding agents' user skill folders, and how each agent is -told installed, as data taken from `src/agents.ts` of +devstack keeps the coding agents' user skill folders, their skill folders in +a working tree, and how each agent is told installed, as data taken from `src/agents.ts` of https://github.com/vercel-labs/skills (MIT, Copyright (c) Vercel, Inc.): the skill folders a pool's sets go to, and the agents "Open with" knows (ADR-0074). Run it to take a newer table: @@ -65,6 +65,7 @@ def agents(src: str): aid, body = m.group(1), m.group(2) name = re.search(r"displayName: '([^']*)'", body) skills = re.search(r"globalSkillsDir: ([^\n]*?),?\n", body) + project = re.search(r"\bskillsDir: '([^'/][^']*)'", body) detect = re.search(r"detectInstalled: async \(\) => \{(.*?)\n \}", body, re.S) if not (name and skills and detect): continue @@ -72,7 +73,7 @@ def agents(src: str): found = [path(e, b) for e in re.findall(r"existsSync\(((?:[^()]|\([^()]*\))*)\)", detect.group(1))] if not skills_path or not found or None in found: continue - yield aid, name.group(1), skills_path, found + yield aid, name.group(1), skills_path, project.group(1) if project else None, found def kept(old: str) -> dict: @@ -92,7 +93,8 @@ def main(): opens = kept(old) lines = [ "# The coding agents devstack knows (ADR-0074): each one's user skill folder,", - "# and the paths that tell it installed. Taken from src/agents.ts of", + "# its skill folder in a working tree (`project`, ADR-0079), and the paths", + "# that tell it installed. Taken from src/agents.ts of", "# https://github.com/vercel-labs/skills (MIT, Copyright (c) Vercel, Inc.)", "# by scripts/sync-agents.py; `[agent.open]` is devstack's own (how", "# \"Open with\" starts the agent) and kept when the table is taken again.", @@ -100,13 +102,17 @@ def main(): "", ] n = 0 - for aid, name, skills, detect in agents(src): + for aid, name, skills, project, detect in agents(src): n += 1 lines += [ "[[agent]]", f'id = "{aid}"', f'name = "{name}"', f'skills = "{skills}"', + ] + if project: + lines.append(f'project = "{project}"') + lines += [ "detect = [" + ", ".join(f'"{d}"' for d in detect) + "]", ] if aid in opens: diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index e21ee2d9..7191b3d6 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -93,9 +93,9 @@ class MockHub { /** The pool's skill sets on this machine (ADR-0074): one accepted, one offered. */ poolSkillState: PoolSkillsState = { agents: [ - { id: 'claude-code', name: 'Claude Code', dir: '~/.claude/skills', enabled: true }, - { id: 'codex', name: 'Codex', dir: '~/.agents/skills', enabled: false }, - { id: 'opencode', name: 'OpenCode', dir: '~/.config/opencode/skills', enabled: false }, + { id: 'claude-code', name: 'Claude Code', dir: '~/.claude/skills', project: '.claude/skills', enabled: true }, + { id: 'codex', name: 'Codex', dir: '~/.agents/skills', project: '.agents/skills', enabled: false }, + { id: 'opencode', name: 'OpenCode', dir: '~/.config/opencode/skills', project: '.agents/skills', enabled: false }, ], sets: [ { @@ -112,6 +112,9 @@ class MockHub { { name: 'timetrack', description: 'Book time entries from the commits of a day', sha256: 'cc33', installed: true, pending: false, enabled: true, group: 'Time', updated: Date.now() - 600_000, agents: ['Claude Code'] }, { name: 'idea-validate', description: 'Validate a business idea in six phases, as an HTML report', sha256: 'dd44', installed: false, pending: false, enabled: false, group: 'Business', tags: ['html'] }, { name: 'idea-overview', description: 'A one-page overview of a business idea', sha256: 'ee55', installed: false, pending: false, enabled: false, group: 'Business', tags: ['html'] }, + // Bound to a repository (ADR-0079): in the working trees of shop only; crm's is no stack here. + { name: 'shop-page', description: 'Scaffold a page of the shop with its router and store', sha256: 'ab12', installed: true, pending: false, enabled: true, group: 'Shop', updated: Date.now() - 1_800_000, agents: ['Claude Code'], repos: ['example-org/shop'], trees: ['~/src/shop', '~/src/shop-feat-cart'] }, + { name: 'crm-report', description: 'Add a report to the CRM', sha256: 'cd34', installed: false, pending: false, enabled: true, group: 'CRM', repos: ['example-org/crm-legacy'] }, ], }, { @@ -132,8 +135,10 @@ class MockHub { for (const k of s.skills) { const want = s.state === 'accepted' && k.enabled !== false ? on : []; if (want.join() !== (k.agents ?? []).join() && want.length) k.updated = Date.now(); - k.agents = want; - k.installed = want.length > 0 && !k.pending; + // A bound skill whose repositories are no stack here goes nowhere. + const nowhere = !!k.repos?.length && !k.trees?.length; + k.agents = nowhere ? [] : want; + k.installed = !nowhere && want.length > 0 && !k.pending; } } poolSkills: PoolSkillsAdmin = { @@ -144,6 +149,24 @@ class MockHub { to: ['*'], manifest: { source: 'github:example-org/skills@main/skills', fetched: Math.floor(Date.now() / 1000) - 600, commit: 'a1b2c3d', skills: [{ name: 'work-issue', description: '' }, { name: 'push-tag', description: '' }] }, }, + { + name: 'team', + source: { kind: 'github', repo: 'example-org/team-skills', ref: 'main', path: '' }, + to: [], + folders: [ + { path: 'skills', to: ['*'] }, + { path: 'projects/shop/skills', to: ['shop'], repos: ['example-org/shop'] }, + ], + manifest: { + source: 'github:example-org/team-skills@main', + fetched: Math.floor(Date.now() / 1000) - 900, + commit: 'e4f5a6b', + skills: [ + { name: 'review-pr', description: '', folder: 'skills' }, + { name: 'shop-page', description: '', folder: 'projects/shop/skills', repos: ['example-org/shop'] }, + ], + }, + }, ], github_token: true, refresh_signed: true, diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 241e4240..4dfb7e59 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -69,8 +69,8 @@ export type PoolFeed = { /** The pools' skill sets on this machine (ADR-0074), as `GET /hub/skills` and `skills` events give them. */ export type PoolSkillsState = { - /** The coding agents found here (and those switched on), with their user skill folder. */ - agents: { id: string; name: string; dir: string; enabled: boolean }[]; + /** The coding agents found here (and those switched on), with their user skill folder and their folder in a working tree (ADR-0079). */ + agents: { id: string; name: string; dir: string; project?: string; enabled: boolean }[]; sets: SkillSetState[]; conflicts: { dir: string; name: string; reason: string }[]; errors?: string[]; @@ -110,6 +110,10 @@ export type SkillState = { updated?: number; /** The agents whose folder holds it. */ agents?: string[]; + /** The repositories it is bound to (`metadata.repos`, ADR-0079): it goes into their working trees only. */ + repos?: string[]; + /** The working trees it is in, a bound skill. */ + trees?: string[]; }; /** A pool's skill set as an admin names it (`/hub/pool/skills`). */ @@ -117,12 +121,16 @@ export type PoolSkillSet = { name: string; source: { kind: 'github'; repo: string; ref: string; path: string } | { kind: 'folder'; path: string }; to: string[]; + /** The repositories its skills without `metadata.repos` are bound to (ADR-0079). */ + repos?: string[]; + /** Folders of the source, each given to its own members (ADR-0079); then `to` and `repos` are empty. */ + folders?: { path: string; to: string[]; repos?: string[] }[]; }; /** `GET /hub/pool/skills` (admins): the sets with what the coordinator last fetched. */ export type PoolSkillsAdmin = { sets: (PoolSkillSet & { - manifest: { source: string; fetched?: number; commit?: string; error?: string; skills: { name: string; description: string }[]; skipped?: string[] }; + manifest: { source: string; fetched?: number; commit?: string; error?: string; skills: { name: string; description: string; repos?: string[]; folder?: string }[]; skipped?: string[] }; })[]; github_token: boolean; refresh_signed: boolean; diff --git a/ui/src/components/PoolSkills.vue b/ui/src/components/PoolSkills.vue index ca7910e6..c293d7db 100644 --- a/ui/src/components/PoolSkills.vue +++ b/ui/src/components/PoolSkills.vue @@ -37,8 +37,23 @@ watch(() => [pool.current, pool.isAdmin], load); // The coordinator tells when a fetch changed the sets (ADR-0073). watch(() => pool.feeds[pool.current]?.versions.skills, load); -type Form = { name: string; kind: 'github' | 'folder'; repo: string; ref: string; path: string; to: string }; -const empty = (): Form => ({ name: '', kind: 'github', repo: '', ref: 'main', path: 'skills', to: '*' }); +// A set of one folder names `to` and `repos`; one of several folders +// (ADR-0079) names them per folder, each below `path`. +type FolderForm = { path: string; to: string; repos: string }; +type Form = { name: string; kind: 'github' | 'folder'; repo: string; ref: string; path: string; to: string; repos: string; folders: FolderForm[] }; +const empty = (): Form => ({ name: '', kind: 'github', repo: '', ref: 'main', path: 'skills', to: '*', repos: '', folders: [] }); +const list = (s: string) => + s + .split(',') + .map((t) => t.trim()) + .filter(Boolean); +const folderForms = (s: PoolSkillSet): FolderForm[] => (s.folders ?? []).map((f) => ({ path: f.path, to: f.to.join(', '), repos: (f.repos ?? []).join(', ') })); +function addFolder() { + const f = form.value; + // The first folder takes what the set named so far. + if (!f.folders.length) f.folders.push({ path: '', to: f.to, repos: f.repos }); + f.folders.push({ path: '', to: '', repos: '' }); +} const form = ref

(empty()); const formOpen = ref(false); const busy = ref(false); @@ -51,8 +66,8 @@ function startAdd() { function startEdit(s: PoolSkillSet) { form.value = s.source.kind === 'github' - ? { name: s.name, kind: 'github', repo: s.source.repo, ref: s.source.ref, path: s.source.path, to: s.to.join(', ') } - : { name: s.name, kind: 'folder', repo: '', ref: 'main', path: s.source.path, to: s.to.join(', ') }; + ? { name: s.name, kind: 'github', repo: s.source.repo, ref: s.source.ref, path: s.source.path, to: s.to.join(', '), repos: (s.repos ?? []).join(', '), folders: folderForms(s) } + : { name: s.name, kind: 'folder', repo: '', ref: 'main', path: s.source.path, to: s.to.join(', '), repos: (s.repos ?? []).join(', '), folders: folderForms(s) }; formOpen.value = true; } @@ -61,10 +76,9 @@ async function save() { const body: PoolSkillSet = { name: f.name.trim(), source: f.kind === 'github' ? { kind: 'github', repo: f.repo.trim(), ref: f.ref.trim() || 'main', path: f.path.trim() } : { kind: 'folder', path: f.path.trim() }, - to: f.to - .split(',') - .map((t) => t.trim()) - .filter(Boolean), + to: f.folders.length ? [] : list(f.to), + repos: f.folders.length ? [] : list(f.repos), + folders: f.folders.map((x) => ({ path: x.path.trim().replace(/^\/+|\/+$/g, ''), to: list(x.to), repos: list(x.repos) })), }; busy.value = true; const r = await act({ label: `Hand out ${body.name}`, path: at(paths.poolSkills), body, success: `The pool hands out ${body.name}; the coordinator fetches it now` }); @@ -95,6 +109,7 @@ async function refresh(name?: string) { }); } +const bound = (repos?: string[]) => (repos?.length ? ` · only in ${repos.join(', ')}` : ''); const sourceText = (s: PoolSkillSet) => (s.source.kind === 'github' ? `${s.source.repo}@${s.source.ref}${s.source.path ? `/${s.source.path}` : ''}` : `folder ${s.source.path}`); @@ -133,8 +148,26 @@ const sourceText = (s: PoolSkillSet) => (s.source.kind === 'github' ? `${s.sourc - + +
+ Folders below it, each with its own members +
+ + + + +
+
+
@@ -145,7 +178,13 @@ const sourceText = (s: PoolSkillSet) => (s.source.kind === 'github' ? `${s.sourc
  • {{ s.name }} - {{ sourceText(s) }} · to {{ s.to.join(', ') || 'nobody' }} + {{ sourceText(s) }} · to {{ s.to.join(', ') || 'nobody' }}{{ bound(s.repos) }} + {{ s.manifest.skills.length }} skill(s) @@ -174,6 +213,18 @@ const sourceText = (s: PoolSkillSet) => (s.source.kind === 'github' ? `${s.sourc gap: 12px 16px; margin: 16px 0 4px; } +.folders { + border: 1px solid var(--border); + border-radius: 6px; + padding: 6px 8px; + display: grid; + gap: 6px; +} +.folder { + display: grid; + grid-template-columns: 1fr 1fr 1fr auto; + gap: 6px; +} .form label { display: flex; flex-direction: column; diff --git a/ui/src/lib/skills.test.ts b/ui/src/lib/skills.test.ts index be573e20..808fe601 100644 --- a/ui/src/lib/skills.test.ts +++ b/ui/src/lib/skills.test.ts @@ -46,6 +46,18 @@ describe('the skills list', () => { expect(names({ status: 'off' })).toEqual(['biz']); }); + it('tells a skill bound to repositories that are no stack here', () => { + const bound = (trees: string[], installed: boolean): PoolSkillsState => ({ + ...state, + conflicts: [], + sets: [{ ...state.sets[0], skills: [{ name: 'shop-page', description: 'd', sha256: 'f', installed, pending: false, enabled: true, repos: ['acme/shop'], trees }] }], + }); + expect(rows(bound([], false))[0].status).toBe('elsewhere'); + expect(rows(bound(['/src/shop'], true))[0].status).toBe('installed'); + expect(rows(bound(['/src/shop'], false))[0].status).toBe('not-installed'); + expect(filtered(rows(bound([], false)), { ...NO_FILTER, text: 'acme/' }).length).toBe(1); + }); + it('lists the groups, the skills without one last', () => { expect(groups(rows(state))).toEqual(['Dev', 'Business', '']); }); diff --git a/ui/src/lib/skills.ts b/ui/src/lib/skills.ts index d53c88c0..e20b3149 100644 --- a/ui/src/lib/skills.ts +++ b/ui/src/lib/skills.ts @@ -1,16 +1,17 @@ -// The pools' skills on this machine (ADR-0074, ADR-0077) as the Skills page +// The pools' skills on this machine (ADR-0074, ADR-0077, ADR-0079) as the Skills page // lists them: one row per skill, with the set it comes from, filtered by // text, set, group and state. Pure, so the page and its tests share it. import type { PoolSkillsState, SkillSetState, SkillState } from '@/api/types'; /** What a row shows of a skill's state, in the order the filter offers them. */ -export type SkillStatus = 'installed' | 'pending' | 'off' | 'conflict' | 'not-installed' | 'not-accepted'; +export type SkillStatus = 'installed' | 'pending' | 'off' | 'conflict' | 'elsewhere' | 'not-installed' | 'not-accepted'; export const STATUS_LABEL: Record = { installed: 'installed', pending: 'update waits', off: 'off', conflict: 'conflict', + elsewhere: 'no working tree here', 'not-installed': 'not installed', 'not-accepted': 'set not accepted', }; @@ -28,6 +29,8 @@ export function statusOf(set: SkillSetState, k: SkillState, conflicts: Set x.toLowerCase().includes(t))), + (!t || r.skill.name.toLowerCase().includes(t) || r.skill.description.toLowerCase().includes(t) || [...(r.skill.tags ?? []), ...(r.skill.repos ?? [])].some((x) => x.toLowerCase().includes(t))), ); } diff --git a/ui/src/views/SkillsView.vue b/ui/src/views/SkillsView.vue index 58d117d3..ccf41268 100644 --- a/ui/src/views/SkillsView.vue +++ b/ui/src/views/SkillsView.vue @@ -1,6 +1,8 @@