craftar 0.28.2 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Craft, sync and convert AI-coding workspace harnesses — rules, agents, commands, skills, MCP servers — across every client workspace you maintain and every AI coder each team uses.
4
4
 
5
- > Status: **phase 1 in progress** — phase 0, the foundations, is done. `import`, `sync`, `status`, `diff`, `explain`, `ls` work end-to-end for the `claude-code` and `kiro` targets and are validated byte-for-byte against a real workspace (see *Oracle*). The Forge commands `forge variants`, `forge diff` (with a suggested class per hunk) and `forge unify` (`--take base|variant`, `take: param` to turn a value into a `{{key}}` parameter, and `take: section` to turn a client block into a section) and `forge promote` (a profile's variant becomes the base) also work, covered by the unit and golden suites rather than the oracle, and `import` is render-aware: importing into an existing Forge reuses a base whose render equals the workspace file, and edits an existing profile and the recipes it owns in place. Ingredient bodies can hold client-specific **sections** (`<!-- craftar:section <name> -->` … `<!-- /craftar:section -->`), overridden by a profile's `sections` and a workspace's `overrides.sections`; import infers each client's content and `forge unify` can extract a section from a variant, and a Forge that uses them declares `schema: 2` or above (see *Forge layout*). The read-only catalogue — `recipes`, `ingredients` and `targets` with the capability matrix — works too, and a workspace can name its Forge by git URL with an optional `ref`, read from a per-machine cache, with a lock that records the ref, commit, recipes and targets it was generated from (see *Remote Forge*). `add recipe` / `remove recipe` change a workspace's recipe choice in `craftar.yaml`, refusing an edit that would not resolve. A writing `sync` records each workspace in a per-machine registry, and `craftar workspaces` lists them all with their status (see *Workspace registry*). `craftar forge impact` lists the workspaces registered on this machine that read a Forge (by path, by a git remote of the clone, or through another clone of the same remote) with what their next sync would do against it, and `forge unify` plans them before and after its writes, names the ones its warnings concern, and with `--prune-recipes` deletes a recipe left identical to its sibling once every one of them plans the same. `craftar doctor` reports, one line per finding, what is off on this machine and in this workspace. `craftar cache prune` removes the cache entries and trees nothing uses. An MCP ingredient can declare `authEnv`, the environment variables its server needs (names only, never a value), and `craftar doctor` checks them; with `claude-code`, `sync` writes an example file listing them. A recipe can bring **local services**: a `service` ingredient is a Docker Compose fragment that `sync` writes under `.craftar/`, and `craftar services up | down | status` run Compose on what the lock records (see *Local services*). A profile's `integrations` block can select recipes and give params in a Forge that declares `schema: 3` or above (see *Integrations*), since `0.27.0`. `craftar templates list | install` shows and runs the profile's `templates` block — `install` runs `dotnet new install` per entry into the user's template store; nothing installs implicitly. An MCP `server` takes the params its ingredient declares, in a Forge that declares `schema: 4` (see *Server params*), since `0.28.0`. Everything else in the spec (`craftar ui`, `craftar mcp`) is not built yet.
5
+ > Status: **phase 1 in progress** — phase 0, the foundations, is done. `import`, `sync`, `status`, `diff`, `explain`, `ls` work end-to-end for the `claude-code` and `kiro` targets and are validated byte-for-byte against a real workspace (see *Oracle*). The Forge commands `forge variants`, `forge diff` (with a suggested class per hunk) and `forge unify` (`--take base|variant`, `take: param` to turn a value into a `{{key}}` parameter, and `take: section` to turn a client block into a section) and `forge promote` (a profile's variant becomes the base) also work, covered by the unit and golden suites rather than the oracle, and `import` is render-aware: importing into an existing Forge reuses a base whose render equals the workspace file, and edits an existing profile and the recipes it owns in place. Ingredient bodies can hold client-specific **sections** (`<!-- craftar:section <name> -->` … `<!-- /craftar:section -->`), overridden by a profile's `sections` and a workspace's `overrides.sections`; import infers each client's content and `forge unify` can extract a section from a variant, and a Forge that uses them declares `schema: 2` or above (see *Forge layout*). The read-only catalogue — `recipes`, `ingredients` and `targets` with the capability matrix — works too, and a workspace can name its Forge by git URL with an optional `ref`, read from a per-machine cache, with a lock that records the ref, commit, recipes and targets it was generated from (see *Remote Forge*). `add recipe` / `remove recipe` change a workspace's recipe choice in `craftar.yaml`, refusing an edit that would not resolve. A writing `sync` records each workspace in a per-machine registry, and `craftar workspaces` lists them all with their status (see *Workspace registry*). `craftar forge impact` lists the workspaces registered on this machine that read a Forge (by path, by a git remote of the clone, or through another clone of the same remote) with what their next sync would do against it, and `forge unify` plans them before and after its writes, names the ones its warnings concern, and with `--prune-recipes` deletes a recipe left identical to its sibling once every one of them plans the same. `craftar doctor` reports, one line per finding, what is off on this machine and in this workspace. `craftar cache prune` removes the cache entries and trees nothing uses. An MCP ingredient can declare `authEnv`, the environment variables its server needs (names only, never a value), and `craftar doctor` checks them; with `claude-code`, `sync` writes an example file listing them. A recipe can bring **local services**: a `service` ingredient is a Docker Compose fragment that `sync` writes under `.craftar/`, and `craftar services up | down | status` run Compose on what the lock records (see *Local services*). A profile's `integrations` block can select recipes and give params in a Forge that declares `schema: 3` or above (see *Integrations*), since `0.27.0`. `craftar templates list | install` shows and runs the profile's `templates` block — `install` runs `dotnet new install` per entry into the user's template store; nothing installs implicitly. An MCP `server` takes the params its ingredient declares, in a Forge that declares `schema: 4` (see *Server params*), since `0.28.0`. `craftar mcp` serves a workspace to an AI coder over the Model Context Protocol — seven reading tools with the data of `status`, `diff`, `explain`, `recipes`, `ingredients`, `targets` and `doctor`; it reads only. `craftar ui` serves a local, read-only dashboard of every registered workspace — the table of `craftar workspaces`, and for one workspace its file states, a file's diff and explanation, and its Forge's recipes and ingredients — on `127.0.0.1` only. Everything else in the spec (cloning a profile's repositories at init) is not built yet.
6
6
 
7
7
  ## The idea in one paragraph
8
8
 
@@ -82,8 +82,10 @@ From then on, change a rule in `forge/ingredients/rules/<name>/rule.md`, run `cr
82
82
  | `craftar doctor [--workspace <dir>] [--fetch] [--strict] [--json]` | Checks this machine — Node ≥ 22, `git`, `$CRAFTAR_HOME`, the registry (entries whose workspace is gone), the Forge cache (its size, entries nothing names, a fetch that never completed) — and, when run inside one (the current directory, or `--workspace`), this workspace: the configuration and its Forge (cached, fetched or pinned), whether the workspace sits inside its Forge, the plan's warnings, declared parameters with no value, the `${NAME}` variables a written MCP server expects and this environment lacks — `mcp-env` reads `authEnv` next to `${NAME}` (names only, never values), `templates` when the profile declares a `templates` block (an empty `templates:` line declares none), `dotnet` when that block is accepted and declares a `dotnet-new` entry (the .NET SDK answering `dotnet --version` at the workspace root); neither goes above `warn` — the lock, `status`, and registration; in a workspace with a service: `docker` — Docker and its Compose plugin, 2.20.0 or later — and `services-env` — the variables a fragment needs. One line per finding — `ok`, `warn` or `error` — each problem with the command that fixes it; each cause is reported once. A declared parameter with no value is an `error` when a file the plan writes cites it (`sync` refuses that workspace) and a `warn` when nothing cites it. It only reports: nothing is written to a workspace, a lock or the registry, and the Forge cache is used as every reader uses it (`.used` stamps, a rebuilt tree; under `--fetch`, a fetch and the cleanup of trees unused for 14 days). Read without the network; `--fetch` fetches a remote Forge first. Exits 1 on an `error`, or on a `warn` under `--strict`; an explicit `--workspace` without `craftar.yaml` exits 1, while the current directory without one runs the machine checks only. `--json` is a contract: `{version, workspace, fetch, strict, checks: [{id, scope, level, message, fix}], summary}`. In a schema 4 Forge `mcp-env` reads the server as rendered, so a `${NAME}` a param brings into `env` is checked. |
83
83
  | `craftar templates list [--json] [--workspace <dir>] [--offline]` | What the profile's `templates` block declares: one line per package — kind, package, version or `latest`, source or `default feeds` — and one per entry this craftar cannot install. Runs no program and does not know what is installed. `--json` is a contract: `{profile, templates: [{entry, kind, package, version, source, installable}], warnings}`. Exits 1 when the block is refused, naming the position and the rule, never a value. |
84
84
  | `craftar templates install [--dry-run] [--force] [--interactive] [--workspace <dir>] [--offline]` | Runs `dotnet new install <pkg>[::<version>]... [--add-source <source>]` once per `dotnet-new` entry, in the profile's order, at the workspace root. `--dry-run` prints the exact lines, needs no `dotnet` and exits 0 over an accepted block, even with a skipped entry. A real run exits 1 when the .NET SDK is not available. Both exit 1 when the block is refused or a package ID exists as a file or folder at the workspace root. `--force` and `--interactive` are passed to `dotnet` as typed, never otherwise; `--interactive` also gives `dotnet` the terminal's input. An entry that fails does not stop the others; a real run exits 1 when any failed or was skipped. When an entry declares a `source` and the workspace root has no `NuGet.Config`, a warning line is printed before the runs. Writes nothing in the workspace, the lock or the registry; nothing else (`sync`, `init`, `doctor`) runs it. See *Project templates*. |
85
+ | `craftar mcp [--workspace <dir>] [--fetch]` | An MCP server (Model Context Protocol, revision `2025-06-18`) over stdin and stdout, started by an AI coder as a subprocess — not typed in a terminal, where it refuses to start. It serves **one workspace**, the one it was started in, through seven tools that only read: `status`, `diff` (the pending files; with a `path`, that file's diff), `explain`, `recipes`, `ingredients`, `targets` and `doctor` (the checks about this workspace, plus Node and `git`; like the command, it asks `docker compose` for its version when the workspace has a service and `dotnet` for its version when the profile declares a template it can install) — each answers with the data its command prints, as one JSON object. Nothing is written to the workspace, the lock, `craftar.yaml`, the registry or the Forge; there is no `sync` tool. The Forge cache is used as every reader uses it (`.used` stamps, a rebuilt tree; under `--fetch`, a fetch and the cleanup of trees unused for 14 days). Without `--fetch` no tool touches the network: a remote Forge is read from the cached copy, and the answer says so — for `doctor` in its `forge` check, for the others but `targets` in `warnings` unless `ref` is a full commit SHA, which cannot go stale (`targets` reads only which targets the configuration resolves, never fetches and carries no such line). The `forge`, `ref` and `profile` of `craftar.yaml` / `craftar.local.yaml` are fixed when the server starts: after one of them changes, every tool but `targets` answers with an error until it is put back or the server is restarted (`targets` answers the matrix unmarked, with a warning). A hand-edited `.mcp.json`, `.kiro/settings/mcp.json` or `.claude/settings.craftar.example.json` is never returned — a note stands in for its diff. A line that is not JSON, or longer than 1 MiB, is not answered — the server reads on. Exits 0 when stdin closes; exits 1, with one line on stderr, in a terminal, without a `craftar.yaml`, or when the configuration does not read. See *Craftar inside the AI coder*. |
85
86
  | `craftar cache prune [--dry-run] [--workspace <dir>] [--json]` | Removes the Forge cache entries nothing uses — no registered workspace (`missing` ones included until `craftar workspaces prune`) and not the current workspace — entries whose first fetch never completed (even when named), and trees unused for 14 days. Whole entries are kept with a warning when the registry is off or unreadable, or the current `craftar.yaml` does not read. Deletes by default; `--dry-run` shows. Never touches a workspace, a lock or the registry; no network. One removing prune at a time per `$CRAFTAR_HOME` (`forges/prune.lock`). An explicit `--workspace` without `craftar.yaml` exits 1. `--json` is a contract: `{home, dryRun, removed: [{path, kind, reason, bytes}], kept: [{path, reason, namedBy}], freedBytes, warnings}`. |
86
87
  | `craftar workspaces forget <dir>` / `craftar workspaces prune` | `forget` removes one entry (the directory is not touched; an unregistered path exits 1); `prune` removes every `missing` entry and never an `error` one. Nothing else removes an entry. |
88
+ | `craftar ui [--port <n>]` | A local dashboard, in a browser: the table of `craftar workspaces` and, for a registered workspace, what `status`, `diff` and `explain` say about it and what `recipes` and `ingredients` say about its Forge. It prints one address and serves until interrupted (`Ctrl-C` exits 0). **Read-only**: nothing is written to a workspace, a lock, the registry or a Forge — the Forge cache is used as every reader uses it (`.used` stamps, a rebuilt tree; `git` runs as for `craftar workspaces`) — and the page never runs `sync` — it prints the command to copy. **Loopback only**: it listens on `127.0.0.1` (no `--host`; `localhost` is refused), answers `GET` only, and every answer that carries data needs a token generated for that run — it travels in the address's fragment, which the browser does not send, so open the address exactly as printed (pasted, not clicked from a web page; a reload keeps working, a new tab needs the address again); it stays in the terminal's scrollback (and in a file, if the output is redirected) and may stay in the browser's history, and is worth nothing once the command stops. **No network**: a remote Forge is read from the cached copy, never fetched, and the page says so. `--port` (default `4747`; `0` takes a free one); a taken port is refused, never replaced. A Forge URL the registry recorded with credentials is shown as `(a URL with credentials — not shown)`, with no cache key — as `craftar workspaces --json` gives it since `0.28.1` (see *Upgrading › to 0.28.1*). Takes no `--workspace`; exits 1 when the registry is off (`CRAFTAR_NO_REGISTRY`) or cannot be read. The page's routes are not a contract. |
87
89
  | `craftar recipes [--forge <dir> [--profile <name>] \| --workspace <dir>] [--json]` | Every recipe of the Forge, sorted by name: slot, the parents it extends, the ingredients it lists itself and the profiles that reach it. In a workspace (or with `--forge <dir> --profile <name>`) each recipe says whether it is in use and why — `profile` (listed in `recipes` or selected by the profile's `integrations` block), `workspace` (`recipes.add`), `extends <child>` — and a recipe `recipes.remove` names reads `removed by this workspace`. A context that does not resolve (two recipes on one slot, an unknown recipe, a cycle) still lists everything, marks nothing and warns. Read-only: it resolves, never plans. `--json` is a contract: `{forge, context, recipes, warnings}`. |
88
90
  | `craftar ingredients [--recipe <name>] [--type <type>] [--forge <dir> [--profile <name>] \| --workspace <dir>] [--json]` | Every ingredient of the Forge, grouped by type: output name, targets, the recipes that list it, and whether the context uses it or the workspace disables it; a reference a recipe makes to an ingredient the Forge does not hold is listed under `missing`, never dropped. `--recipe <name>` lists what choosing that recipe brings, with the parents it extends, parents first; two of them on one slot is a warning. `--type` keeps one type. Read-only. `--json` is a contract: `{forge, context, recipe, ingredients, missing, warnings}`. |
89
91
  | `craftar targets [--workspace <dir>] [--json]` | The capability matrix (see *Targets*): what each target does with each ingredient type, the paths it writes and what changes. Needs no Forge; inside a workspace it marks the targets in use, and when that workspace does not load or resolve it prints the matrix unmarked with a warning. An explicit `--workspace <dir>` without a `craftar.yaml` exits 1; the current directory without one just prints the matrix unmarked. `--json` is a contract: `{ingredientTypes, targets, warnings}`. |
@@ -98,7 +100,7 @@ From then on, change a rule in `forge/ingredients/rules/<name>/rule.md`, run `cr
98
100
  | `craftar services down [--volumes] [--workspace <dir>]` | Stops them (`docker compose -p <project> [-f .craftar/compose.yaml [--env-file .env]] down`). Never refused on the files or the lock: when a recorded file is missing or edited, the stack is not craftar's, the lock cannot be read, or Compose is older than 2.20.0, the project is stopped by its name alone. An unreadable lock is a warning, not a refusal. `--volumes` also removes the volumes the stack declares. Exits with Compose's code; 1 when Docker or its Compose plugin is missing. |
99
101
  | `craftar services status [--json] [--workspace <dir>]` | One line per container of a declared service (a service with none reads `not created`) — its ingredient, state (`not created`, or Compose's own: `running`, `exited`…), health and published ports — then every pending file with its fix — a recorded file that is `missing` or `edited`, or a stack or fragment that is `unrecorded` (the lock does not record it). Exits 0 also when nothing runs; 1 when Docker cannot be asked (`--json` still prints, every service `not created`) or the lock cannot be read. A container of the project that no recorded fragment declares is listed too (`(not declared)`; `ingredient: null` in `--json`, where `health`, `composeFile` and `docker.compose` can be `null` as well; `docker.compose` is the bare version, `2.24.5` for `2.24.5-desktop.1`). `--json`: `{workspace, project, composeFile, docker: {available, compose}, services: [{name, ingredient, state, health, ports}], pending: [{path, reason}], warnings}`. `pending[].reason` is `missing`, `edited` or `unrecorded`. |
100
102
 
101
- All commands but `workspaces` take `--workspace <dir>` (default: current directory); the `forge` commands, `recipes` and `ingredients` also take `--forge <dir>` as an alternative to it — a directory: a URL there is refused — and `targets` needs no Forge. With a remote Forge (see *Remote Forge*), `status`, `sync`, `diff`, `explain`, `ls`, `recipes`, `ingredients`, `add recipe`, `remove recipe`, `forge variants` and `forge diff` fetch first and take `--offline` to use the cached copy; `targets` never fetches; `forge unify` and `forge promote` refuse a workspace whose Forge is remote — clone it and pass `--forge <dir>`; `import --write-config` keeps a remote `forge:` and sets only `profile` and `targets`.
103
+ All commands but `workspaces` and `ui` take `--workspace <dir>` (default: current directory); the `forge` commands, `recipes` and `ingredients` also take `--forge <dir>` as an alternative to it — a directory: a URL there is refused — and `targets` needs no Forge. With a remote Forge (see *Remote Forge*), `status`, `sync`, `diff`, `explain`, `ls`, `recipes`, `ingredients`, `add recipe`, `remove recipe`, `forge variants` and `forge diff` fetch first and take `--offline` to use the cached copy; `targets` never fetches; `forge unify` and `forge promote` refuse a workspace whose Forge is remote — clone it and pass `--forge <dir>`; `import --write-config` keeps a remote `forge:` and sets only `profile` and `targets`.
102
104
 
103
105
  ## Forge layout
104
106
 
@@ -372,7 +374,7 @@ They are generated files like any other: `status`, `diff`, `sync --check` and `-
372
374
 
373
375
  **The plan fails** when a fragment is not a YAML mapping, declares no service, declares a top-level `name` (the project name is craftar's) or `include` (every file of the stack is in the lock) — also when they arrive through a YAML merge key (`<<`): a fragment is checked as Compose reads it; when a service's `extends` names a `file` (it may extend a service of the same fragment), or when two fragments declare the same key under `services`, `volumes`, `networks`, `configs` or `secrets` — Compose would keep one silently. A file not listed in `binary` must be UTF-8 text. **It warns** when two fragments publish the same literal host port, and when a rendered file holds a secret-like value (the kind and the line, never the value): keep values out of the Forge and use `${NAME}`.
374
376
 
375
- **Running it.** `craftar services up` runs `docker compose up -d` on the stack, `services down` stops it and `services status` shows it (see *Commands*). They need Docker with its Compose plugin, found on `PATH` by the lookup that finds `dotnet` and `git` (see *Project templates*); `up` needs Compose **2.20.0 or later** (the first with `include`), while `down` and `status` work on an older one. `sync` needs no Docker. `up` reads the lock, not the Forge: it comes up on what the last `sync` wrote, and refuses a file that is missing or edited rather than run something the lock does not record. Nothing runs Docker implicitly — not `sync`, not `init`, and `doctor` only asks for the version. craftar adds no policy over what a fragment declares: a service runs with your Docker rights, as the hooks and scripts of a Forge run with yours.
377
+ **Running it.** `craftar services up` runs `docker compose up -d` on the stack, `services down` stops it and `services status` shows it (see *Commands*). They need Docker with its Compose plugin, found on `PATH` by the lookup that finds `dotnet` and `git` (see *Project templates*); `up` needs Compose **2.20.0 or later** (the first with `include`), while `down` and `status` work on an older one. `sync` needs no Docker. `up` reads the lock, not the Forge: it comes up on what the last `sync` wrote, and refuses a file that is missing or edited rather than run something the lock does not record. Nothing runs Docker implicitly — not `sync`, not `init`, and `doctor` — the command, or the `doctor` tool of `craftar mcp` — only asks for the version. craftar adds no policy over what a fragment declares: a service runs with your Docker rights, as the hooks and scripts of a Forge run with yours.
376
378
 
377
379
  - **The project** is `craftar-<slug>-<hash>`: the workspace directory's name, lowercased, every character outside `a-z 0-9 _ -` replaced by `-`, cut at 40, then the first 8 hex digits of the SHA-256 of the workspace's real path. It is computed, never written, so the files under `.craftar/` are the same on every machine and two checkouts are two projects. `services status` prints it. Moving a workspace changes it: stop the old one with `docker compose -p <old name> down`. A name that leaves nothing but dashes gives `craftar--<hash>`.
378
380
  - **`${CRAFTAR_WORKSPACE}`** is set by `craftar services` to the workspace's real path, so a fragment can mount a repository of the workspace.
@@ -426,7 +428,7 @@ Copy a workspace with `.claude/` and `.kiro/` into `fixtures/` (keep `local-stac
426
428
 
427
429
  A writing `sync` records the workspace in `$CRAFTAR_HOME/registry.json` (`~/.craftar` by default): its real path, profile, the Forge it used and where that Forge lives, the resolved recipes and targets, and when `sync` last ran there. It is an index, not the memory — `craftar.lock` stays that, and nothing in a workspace changes because of it. `craftar workspaces` prints it as a table with every status computed on the spot — `up to date`, `outdated`, `drift`, `no lock`, `missing` or `error` — read without the network (a remote Forge from the cache; `--fetch` fetches first); `forget` and `prune` remove entries, and a workspace that is gone stays listed as `missing` until you prune it.
428
430
 
429
- - **`CRAFTAR_NO_REGISTRY`** — read the name as "no registry", the way `NO_COLOR` means "no colour". Set to any non-empty value, it turns the registry off: `sync` neither reads nor writes it, and `craftar workspaces` exits 1. An empty value counts as unset. Set it on CI runners and throwaway checkouts, whose directories would only pile up as `missing`.
431
+ - **`CRAFTAR_NO_REGISTRY`** — read the name as "no registry", the way `NO_COLOR` means "no colour". Set to any non-empty value, it turns the registry off: `sync` neither reads nor writes it, and `craftar workspaces` and `craftar ui` exit 1. An empty value counts as unset. Set it on CI runners and throwaway checkouts, whose directories would only pile up as `missing`.
430
432
  - **A registry that cannot be written** (an unwritable `$CRAFTAR_HOME`, a busy lock after 60 s, a file this craftar cannot read) leaves `sync`'s files, lock and exit code as they would be, and adds one warning. Craftar never overwrites a registry it cannot read: repair or remove it yourself.
431
433
  - The registry is per machine: paths are native and absolute, and SSH and HTTPS spellings of one remote are two Forges in it, as they are two cache entries.
432
434
  - **`craftar init` reads it for the Forge it offers** when it asks: the Forge of the most recent `sync` on this machine, skipping a directory that is gone. The questions never write it — the first `sync` registers the new workspace as any `sync` does. With `CRAFTAR_NO_REGISTRY` set, or a registry it cannot read, no Forge is offered and the question is asked without a default.
@@ -451,23 +453,65 @@ templates:
451
453
  A `kind` is a lowercase name (`dotnet-new`); a package is a NuGet ID, optionally with a version (`<id>::<version>`). A `source` is an `https://` URL with a host, in printable ASCII, and no user or password. There is no workspace layer: `craftar.yaml` and `craftar.local.yaml` cannot add or remove a template.
452
454
 
453
455
  - **The store is the user's** — one per machine user, shared by every workspace; the last install of a package ID wins. Remove one with `dotnet new uninstall <package>`.
454
- - **Feeds are additive** — a declared `source` is added to the feeds `dotnet` already uses, so an ID nobody reserved on a public feed can be served from there. Pin it with the team's own `NuGet.Config` at the workspace root (craftar looks there only, and generates none). `install` and `doctor` warn when an entry declares a `source` and the root has no `NuGet.Config`.
456
+ - **Feeds are additive** — a declared `source` is added to the feeds `dotnet` already uses, so an ID nobody reserved on a public feed can be served from there. Pin it with the team's own `NuGet.Config` at the workspace root (craftar looks there only, and generates none). `install` and `doctor` — the command, or the `doctor` tool of `craftar mcp` — warn when an entry declares a `source` and the root has no `NuGet.Config`.
455
457
  - **Private feeds** — authentication is NuGet's (`NuGet.Config`, a credential provider, `--interactive`); craftar holds no token, and a `source` carrying a user or a password is refused and never printed. A `source` is printed as written by `list`, `--dry-run` and `install`: craftar refuses a user or a password in it, not a token in its path or query — keep those out of the profile.
456
- - **`dotnet` comes from `PATH`** — craftar looks for it itself, in the absolute entries of `PATH` only (on Windows, a `dotnet.exe` or `dotnet.com` in an entry with a drive or a UNC host), and never in the workspace root unless `PATH` names it: a `dotnet` committed in a repository is not run by `install` or by `doctor`'s probe, which both run there. An empty or relative entry, an unset `PATH` and a `.cmd` / `.bat` shim are not used, and neither is a `node_modules/.bin` of the directory craftar is started in or of a directory above it — the entries `npx` and `npm` put first. The same lookup finds `git` and `docker`.
458
+ - **`dotnet` comes from `PATH`** — craftar looks for it itself, in the absolute entries of `PATH` only (on Windows, a `dotnet.exe` or `dotnet.com` in an entry with a drive or a UNC host), and never in the workspace root unless `PATH` names it: a `dotnet` committed in a repository is not run by `install` or by `doctor`'s probe (the command's, or that of the `doctor` tool of `craftar mcp`), all of which run there. An empty or relative entry, an unset `PATH` and a `.cmd` / `.bat` shim are not used, and neither is a `node_modules/.bin` of the directory craftar is started in or of a directory above it — the entries `npx` and `npm` put first. The same lookup finds `git` and `docker`.
457
459
  - **Unknown kind** — an entry of a kind this craftar cannot install (`npm-create`, `nx`) is listed, skipped and warned; `install` then exits 1 (`--dry-run` still exits 0).
458
460
 
461
+ ## Craftar inside the AI coder
462
+
463
+ An AI coder working in a generated workspace does not know the files are generated. `craftar mcp` tells it: registered as an MCP server, it lets the agent ask what is pending, why a file exists and what the Forge offers — and say "run `craftar sync`" instead of editing a generated file.
464
+
465
+ Register it by hand, in the AI coder's own MCP configuration — a file `sync` does not write (the user's own, not a generated `.mcp.json` or `.kiro/settings/mcp.json`):
466
+
467
+ ```json
468
+ { "mcpServers": { "craftar": { "command": "craftar", "args": ["mcp"] } } }
469
+ ```
470
+
471
+ or for a whole team, as an ordinary `mcp` ingredient in the Forge, which `sync` writes to `.mcp.json` and `.kiro/settings/mcp.json` like any other server:
472
+
473
+ ```yaml
474
+ # ingredients/mcp/craftar/ingredient.yaml
475
+ type: mcp
476
+ name: craftar
477
+ server:
478
+ command: craftar
479
+ args: [mcp]
480
+ ```
481
+
482
+ The server answers for the directory it is started in; a client that starts its servers elsewhere needs `args: [mcp, --workspace, <dir>]`. The server also sees only the environment the client starts it with: `git`, `dotnet` and `docker` are looked for in the absolute entries of that `PATH` (a `node_modules/.bin` of the directory the server is started in, or of one above it, aside — see *to 0.28.2*), and the variables `doctor` checks are read there — so a client that starts its servers with a reduced `PATH` gets `git not found` from `doctor` (its `dotnet` and `docker` checks warn too, when the workspace uses them and its Forge loads), no commit for a Forge that is a directory and, when the Forge is a git URL, an error from `status`, `diff`, `explain`, `recipes` and `ingredients` — `targets` then answers the matrix unmarked, with a warning, and `doctor` reports `git` as an `error` and, of the workspace's checks, runs only `lock`.
483
+
484
+ **What the results hold.** A tool result goes wherever the AI coder sends its context, and the tools return the commands' data with three things left out: `doctor`'s checks about the rest of the machine (`$CRAFTAR_HOME`, the registry, the Forge cache), the on-disk content of a hand-edited MCP configuration file, and — from `diff` without a path — the bodies (it lists counts). Nothing else is filtered. So a result can hold: the content of a generated file with its hand edits, or of a file craftar never wrote that sits where it would write one (`diff` with a path, on a `drift` or a `collision`) — a hand-edited service file under `.craftar/` included; values a profile or `overrides.params` put into a generated file; the Forge's path or URL as `craftar.yaml` names it; the absolute path of the workspace and of a path Forge, the Docker Compose and .NET SDK versions found on this machine and the names of the variables a service fragment expects — names, never values (`doctor`); and **the names of every profile of the Forge and the workspace an ingredient was imported from** — the profiles beside each recipe in `recipes`, the origin in `explain`. In a Forge shared across clients those names can be client names — register the server only where that is acceptable.
485
+
459
486
  ## Roadmap (from the functional spec)
460
487
 
461
488
  Phase 0 — foundations (done): schema, import, sync/status/diff/explain, claude-code + kiro + agents-md targets, lock, drift, orphans; `forge variants`, `forge diff` and `forge unify` (`take: param`, `take: section`); sections.
462
489
 
463
- Phase 1 — client profile (in progress). Shipped: the read-only catalogue (`recipes`, `ingredients`, `targets` with the capability matrix); remote Forge (git URL + `ref`, a per-machine cache, the schema 2 lock) and `craftar cache prune`; the workspace registry and `craftar workspaces`; `craftar add recipe` / `remove recipe`; `craftar init` with flags; `craftar doctor`; `craftar forge impact`, `forge unify --prune-recipes` and `forge promote`; an interactive `craftar init` (choose the Forge and the profile); `authEnv` on MCP ingredients (the environment variables a server needs, by name, and the generated `.claude/settings.craftar.example.json`); `craftar drift show` / `drift discard` / `drift promote` (list the files edited by hand, discard an edit, or carry one into the Forge as a profile value or a variant); a sync refused when a declared parameter has no value; `craftar import --report` (a Markdown report of an import, as paths and line counts) and `import --prefer-kiro` (a rule's source taken from its Kiro steering file); a profile's `integrations` block (PM tool and IDP as recipes selected by the profile); `{{param}}` inside an MCP server. Next: cloning a profile's repositories at init.
490
+ Phase 1 — client profile (in progress). Shipped: the read-only catalogue (`recipes`, `ingredients`, `targets` with the capability matrix); remote Forge (git URL + `ref`, a per-machine cache, the schema 2 lock) and `craftar cache prune`; the workspace registry and `craftar workspaces`; `craftar add recipe` / `remove recipe`; `craftar init` with flags; `craftar doctor`; `craftar forge impact`, `forge unify --prune-recipes` and `forge promote`; an interactive `craftar init` (choose the Forge and the profile); `authEnv` on MCP ingredients (the environment variables a server needs, by name, and the generated `.claude/settings.craftar.example.json`); `craftar drift show` / `drift discard` / `drift promote` (list the files edited by hand, discard an edit, or carry one into the Forge as a profile value or a variant); a sync refused when a declared parameter has no value; `craftar import --report` (a Markdown report of an import, as paths and line counts) and `import --prefer-kiro` (a rule's source taken from its Kiro steering file); a profile's `integrations` block (PM tool and IDP as recipes selected by the profile); `{{param}}` inside an MCP server; `craftar mcp` (a read-only MCP server: seven reading tools for an AI coder, over stdin and stdout); `craftar ui` (a local, read-only dashboard of the registered workspaces, on `127.0.0.1` only). Next: cloning a profile's repositories at init.
464
491
 
465
492
  Phase 2 — environment (in progress). Shipped: local services (`service` ingredients, `.craftar/`, `craftar services up | down | status`); `craftar templates list | install` (`dotnet new` project templates declared in a profile).
466
493
 
467
- Later: rulesync bridge for Codex/Kimi/Cursor specifics; `craftar docs validate`; GitHub Action and Azure Pipelines task around `sync --check`; `craftar ui`; `craftar mcp` + Claude Code / Agent Plugin packaging.
494
+ Later: rulesync bridge for Codex/Kimi/Cursor specifics; `craftar docs validate`; GitHub Action and Azure Pipelines task around `sync --check`; writing tools for `craftar mcp` (`sync`, `add recipe`) and its Claude Code / Agent Plugin packaging.
468
495
 
469
496
  ## Upgrading
470
497
 
498
+ ### to 0.30.0
499
+
500
+ - **New command: `craftar ui [--port <n>]`**, a local, read-only dashboard in a browser (see *Commands*). It writes nothing to a workspace, its lock, the registry or a Forge — the Forge cache is used as every reader uses it — reaches no network (a remote Forge is read from the cached copy), and never runs `sync`: it prints the command to copy. It takes no `--workspace`, and exits 1 when `CRAFTAR_NO_REGISTRY` is set or the registry cannot be read.
501
+ - **Nothing that exists changes**: no emitted byte, no lock, no Forge schema, no `--json` key and no exit code; `workspaces`, `doctor`, `status --json`, `diff`, `drift show` and `explain` print what they printed before — `workspaces` and `doctor` pinned by tests, the others untouched. The page's routes are not a tooling contract: only `--port`, the refusals before the server starts and the exit codes are.
502
+ - **The first craftar command that listens on a socket.** It binds `127.0.0.1` only (no `--host`; `localhost` and every other name are refused) and answers `GET` only. The default port is `4747`: a second `craftar ui` on the same machine, or another tool on that port, needs `--port` (`0` takes a free one) — a taken port is refused, never replaced.
503
+ - **Whoever holds the printed address can read what the reading commands print**: every registered workspace's absolute path, its Forge's source, its profile and file states, and the on-disk side of a file that is not in sync — `.mcp.json` and `.kiro/settings/mcp.json` included, as `craftar diff` shows them and unlike `craftar mcp`. The address stays in the terminal's scrollback, in redirected output and possibly in the browser's history, and is worth nothing once the command stops; open it only in a browser of the same user on the same machine.
504
+ - **A Forge URL the registry recorded with credentials** is shown as `(a URL with credentials — not shown)` with no cache key, as `craftar workspaces --json` gives it since `0.28.1`; the page checks every row of its table itself, and a recorded `ref` that holds a URL with credentials gets the same label there.
505
+
506
+ ### to 0.29.0
507
+
508
+ - **New command: `craftar mcp`**, a read-only MCP server over stdin and stdout, started by an AI coder (see *Commands* and *Craftar inside the AI coder*). It writes nothing to a workspace, its lock or `craftar.yaml`, the registry or the Forge — the Forge cache is used as every reader uses it — and there is no `sync` tool.
509
+ - **Nothing that exists changes**: no emitted byte, no lock, no Forge schema; `status`, `diff`, `explain`, `recipes`, `ingredients`, `targets` and `drift show` print what they printed before, with the same `--json` keys and exit codes — their builders moved into the core, and their output is pinned by tests.
510
+ - **New tooling contracts**: the seven tool names and their arguments; the `diff` tool's result (`{files: [{path, state, added, removed, diff, note}], warnings, unsetParams}`); the `explain` tool's (`{path, target, ingredient, origin, via, sections, params, profile, recipes, hash, warnings}`); and the `doctor` tool's, which is `doctor --json` narrowed to the workspace's checks plus `node` and `git`, its summary recounted. The `status`, `recipes`, `ingredients` and `targets` tools answer with the shapes of those commands' `--json`, which now bind the tools too.
511
+ - **Upgrade every machine before adding the server to a shared Forge.** A Forge can register `craftar mcp` as an ordinary `mcp` ingredient, and `sync` on any version that reads the Forge writes it to `.mcp.json` / `.kiro/settings/mcp.json` for the targets a workspace uses (its workspaces see `new` or `update` on those files); an AI coder on a machine with a craftar before `0.29.0` then starts `craftar mcp`, an unknown command, and the server fails to start.
512
+ - **The server runs in its client's environment**: the programs it runs (`git`, and for the `doctor` tool `docker` and `dotnet`) are looked for in the `PATH` the client gives it, by the lookup of *to 0.28.2*, and the `forge`, `ref` and `profile` it was started with stay fixed: after one of them changes, every tool but `targets` answers with an error until it is restarted.
513
+ - **A result can carry what the reading commands print** — the names of the Forge's profiles and of the workspace an ingredient was imported from, absolute paths, and the parameter values a generated file holds (at Forge `schema: 4`, also those rendered into an MCP server; a value that looks like a credential still refuses the plan, and the tool then answers with the plan's line, never the value). Register the server only where that is acceptable.
514
+
471
515
  ### to 0.28.2
472
516
 
473
517
  - **A program is no longer looked for in a `node_modules/.bin` of the current directory or of a directory above it.** `npx craftar` — and an `npm` script — puts those entries first on `PATH`, as absolute ones, so a `git`, a `dotnet` or a `docker` committed there was the program craftar ran. They are now skipped, in the lookup and in the `PATH` the program gets, so what it starts in turn (`ssh`, a credential helper) is not found there either. The current directory is the one craftar is started in, whatever `--workspace` names. The entries are compared as written — `.`, `..` and repeated separators resolved, no link followed, without case on Windows. A `node_modules/.bin` anywhere else on `PATH` (npx's own cache, a global prefix) is looked in as before.
package/dist/cli.js CHANGED
@@ -9,21 +9,22 @@ import { planPromote, applyPromote, UnheldError } from "./importers/drift-promot
9
9
  import { providedRefs } from "./importers/provided.js";
10
10
  import { holdsBaseCitations, rendersServers } from "./core/mcp-server.js";
11
11
  import { classifyForge } from "./core/remote.js";
12
- import { forget, listWorkspaces, prune, register, registryFile } from "./core/registry.js";
12
+ import { forget, listWorkspaces, prune, readRegistry, register, registryFile } from "./core/registry.js";
13
13
  import { forgeWorkspaces, planAll, nextSync, impactOf, concerned, refineRegistryState, countStates, countStatesObject, NEXT_SYNC_STATES } from "./core/impact.js";
14
14
  import { runDoctor } from "./core/doctor.js";
15
+ import { launchRefusal, pinOf } from "./core/mcp-protocol.js";
16
+ import { serve } from "./mcp.js";
15
17
  import { pruneCache } from "./core/cache.js";
16
18
  import { resolveHome } from "./core/home-lock.js";
17
- import { loadWorkspace, plan, readLock, status, apply, unsetDeclared, unsetRefusal, unsetRefused, resolveForge, resolveForgeSource, WORKSPACE_FILE, LOCAL_FILE } from "./core/sync.js";
18
- import { resolve, sectionKey } from "./core/resolve.js";
19
- import { catalogueContext, listRecipes, listIngredients, checkType } from "./core/catalogue.js";
20
- import { listTargets } from "./core/capabilities.js";
19
+ import { loadWorkspace, readWorkspaceConfig, plan, readLock, status, apply, unsetDeclared, unsetRefusal, unsetRefused, resolveForge, resolveForgeSource, WORKSPACE_FILE, LOCAL_FILE } from "./core/sync.js";
20
+ import { sectionKey } from "./core/resolve.js";
21
+ import { catalogueContext, listRecipes, listIngredients, checkType, withLoadWarnings } from "./core/catalogue.js";
21
22
  import { canonicalValue } from "./core/sections.js";
22
23
  import { renderDiff, NO_EOF_NEWLINE_MARKER } from "./core/diff.js";
23
24
  import { preferredLine, renderImportReport } from "./core/import-report.js";
24
25
  import { driftList, unmanaged } from "./core/drift.js";
26
+ import { EXAMPLE_CONTENT_HIDDEN, diffReport, explainFile, explainSkip, notProduced, readText, statusPath, statusReport, targetsReport } from "./core/report.js";
25
27
  import { diffIngredients, listVariants, profileOf } from "./core/variants.js";
26
- import { hashNormalized, toLf, stripBom } from "./core/text.js";
27
28
  import { exists, gitDirty, gitIgnored, gitIsRepo, gitUnheld, loadForge } from "./core/forge.js";
28
29
  import { applyBasePromotion, planBasePromotion, proveBasePromotion } from "./core/promote.js";
29
30
  import { fingerprintDir } from "./core/fingerprint.js";
@@ -37,10 +38,11 @@ import { localKeys, readLocalFile } from "./core/workspace-yaml.js";
37
38
  import { HUNK_CLASSES, INGREDIENT_TYPES, UnifyPlanSchema } from "./schema/index.js";
38
39
  import { EXAMPLE_SETTINGS } from "./emitters/shared.js";
39
40
  import { YamlSyntaxError, parseYamlText } from "./core/yaml-read.js";
40
- import { recordedServices, pendingLine, upRefusal, composeArgv, downArgv, readPs, dockerVersion, dockerFault, dockerRunner, projectName, statusReport } from "./core/services.js";
41
+ import { recordedServices, pendingLine, upRefusal, composeArgv, downArgv, readPs, dockerVersion, dockerFault, dockerRunner, projectName, statusReport as servicesStatusReport } from "./core/services.js";
41
42
  import { errorText } from "./core/schema-fault.js";
42
43
  import { declaredTemplates, DOTNET_MISSING, DOTNET_MISSING_FIX, dotnetVersion, feedMessage, installReport, installTemplates, profileLabel, templateRows, unpinnedSources } from "./core/templates.js";
43
44
  import { capture, spawnInherited } from "./core/proc.js";
45
+ import { startUi } from "./ui/server.js";
44
46
  process.stdout.on("error", (e) => { if (e.code === "EPIPE")
45
47
  process.exit(0); });
46
48
  /**
@@ -50,7 +52,7 @@ process.stdout.on("error", (e) => { if (e.code === "EPIPE")
50
52
  */
51
53
  const DIFF_EXIT_CODE_FETCH_MODE = "sync";
52
54
  const program = new Command();
53
- program.name("craftar").description("Craft, sync and convert AI-coding workspace harnesses.").version("0.28.2");
55
+ program.name("craftar").description("Craft, sync and convert AI-coding workspace harnesses.").version("0.30.0");
54
56
  const SAVE_PLAN_GATE = { what: "plan", who: "unify", outside: "save plans outside the Forge", never: "unify never overwrites" };
55
57
  const REPORT_GATE = { what: "report", who: "import", outside: "write the report outside the Forge", never: "import never overwrites" };
56
58
  program
@@ -148,9 +150,10 @@ program
148
150
  const p = await plan(ws);
149
151
  const lock = await readLock(ws.root);
150
152
  const st = await status(ws, p, lock);
151
- const unset = unsetDeclared(p);
153
+ const report = statusReport(ws, p, lock, st);
154
+ const unset = report.unsetParams;
152
155
  if (o.json) {
153
- console.log(JSON.stringify({ forge: forgeJson(ws, lock), statuses: st.map(({ planned, ...s }) => s), warnings: p.warnings, unsetParams: unset }, null, 2));
156
+ console.log(JSON.stringify(report, null, 2));
154
157
  // exitCode, not process.exit: a piped object is not cut (spec 29 §4.1)
155
158
  if (unset.length)
156
159
  process.exitCode = 1;
@@ -406,11 +409,9 @@ program
406
409
  for (const s of st) {
407
410
  if (only && s.path !== only)
408
411
  continue;
409
- // Spec 19 §3.2: show the six states sync --check refuses (skip unchanged and adopt)
410
- if (["unchanged", "adopt"].includes(s.state))
411
- continue;
412
- shown++;
413
- await printFileDiff(ws.root, s);
412
+ // Spec 19 §3.2: the six states sync --check refuses are shown; which those are is diffReport's to say
413
+ if (await printFileDiff(ws.root, s))
414
+ shown++;
414
415
  }
415
416
  if (!shown)
416
417
  console.log(pc.green("no differences"));
@@ -424,36 +425,31 @@ program
424
425
  const DIFF_PAINT = { paint: { same: pc.dim, del: pc.red, add: pc.green } };
425
426
  /** What `craftar diff` prints for one file `sync --check` refuses; `drift show <path>` prints the same for a drifted one. */
426
427
  async function printFileDiff(root, s) {
428
+ // What to show is decided in the core (`diffReport`); the headers and the paint are this command's.
429
+ const [row] = await diffReport({ root }, [s], { withholdMcp: false });
430
+ // Nothing to show for `unchanged` and `adopt`: says so, for the caller's count
431
+ if (!row)
432
+ return false;
427
433
  if (s.state === "orphan-drift") {
428
434
  // Header and one line, no body: sync keeps this file
429
435
  console.log(pc.bold(`--- ${s.path} (disk, orphan-drift)`));
430
- console.log(` ${explainSkip(s)}`);
431
- return;
432
436
  }
433
- const disk = await readText(path.join(root, s.path));
434
- if (s.state === "orphan") {
437
+ else if (s.state === "orphan") {
435
438
  // A removal: the file exists on disk but the Forge no longer produces it
436
439
  console.log(pc.bold(`--- ${s.path} (disk, orphan)`));
437
440
  console.log(pc.bold(`+++ ${s.path} (forge: no longer produced — sync removes it)`));
438
- console.log(renderDiff(disk ?? "", "", DIFF_PAINT));
439
441
  }
440
442
  else {
441
- const next = s.planned ? toLf(stripBom(s.planned.content.toString("utf8"))) : "";
442
443
  console.log(pc.bold(`--- ${s.path} (disk, ${s.state})`));
443
444
  console.log(pc.bold(`+++ ${s.path} (forge)`));
444
- // Spec 27 §4.2, Ruling 4: do not print on-disk content of the example file for drift/collision
445
- if (s.path === EXAMPLE_SETTINGS && (s.state === "drift" || s.state === "collision")) {
446
- console.log(EXAMPLE_CONTENT_HIDDEN);
447
- }
448
- else {
449
- console.log(renderDiff(disk ?? "", next, DIFF_PAINT));
450
- }
451
445
  }
446
+ // Spec 27 §4.2, Ruling 4: a note stands in for the on-disk content of the example file in drift / collision
447
+ if (row.note !== null)
448
+ console.log(` ${row.note}`);
449
+ else
450
+ console.log(renderDiff(row.disk ?? "", row.forge ?? "", DIFF_PAINT));
451
+ return true;
452
452
  }
453
- /** Spec 27 Ruling 4: the on-disk content of the example file is never printed. */
454
- const EXAMPLE_CONTENT_HIDDEN = " content not shown: an example file may hold a value typed by hand";
455
- /** A path as the user may type it, to the spelling `status` prints: forward slashes, no leading `./`. */
456
- const statusPath = (p) => p.replace(/\\/g, "/").replace(/^\.\//, "");
457
453
  /* ---------------------------------------------------------------- drift */
458
454
  const drift = program.command("drift").description("Hand-edited generated files: show them, discard the edit, or promote it to the Forge");
459
455
  drift
@@ -521,7 +517,7 @@ drift
521
517
  console.log(pc.bold(`+++ ${named.path} (forge: no longer produced — \`craftar drift discard\` removes it)`));
522
518
  // Spec 27 Ruling 4: the on-disk content of the example file is never printed.
523
519
  if (named.path === EXAMPLE_SETTINGS) {
524
- console.log(EXAMPLE_CONTENT_HIDDEN);
520
+ console.log(` ${EXAMPLE_CONTENT_HIDDEN}`);
525
521
  }
526
522
  else {
527
523
  console.log(renderDiff((await readText(path.join(ws.root, named.path))) ?? "", "", DIFF_PAINT));
@@ -819,29 +815,26 @@ program
819
815
  const ws = await loadWorkspace(o.workspace, load(o, "read"));
820
816
  warnStderr(ws.warnings);
821
817
  const p = await plan(ws);
822
- const f = p.files.find((x) => x.path === file.replace(/\\/g, "/"));
818
+ const f = explainFile(ws, p, file.replace(/\\/g, "/"));
823
819
  if (!f)
824
- fail(`${file} is not produced by the Forge for profile ${ws.config.profile}`);
825
- const ing = p.resolution.ingredients.find((i) => i.ref === f.ingredient);
820
+ fail(notProduced(file, ws.config.profile));
826
821
  console.log(pc.bold(f.path));
827
822
  console.log(` target ${f.target}`);
828
- console.log(` ingredient ${f.ingredient}${ing?.meta.origin ? pc.dim(` (imported from ${ing.meta.origin.workspace}:${ing.meta.origin.path})`) : ""}`);
829
- if (ing)
830
- console.log(` via recipes ${ing.via.join(" → ")}`);
823
+ console.log(` ingredient ${f.ingredient}${f.origin ? pc.dim(` (imported from ${f.origin.workspace}:${f.origin.path})`) : ""}`);
824
+ if (f.via)
825
+ console.log(` via recipes ${f.via.join(" → ")}`);
831
826
  // Spec 11 §4.2 (Ruling 15): which layer filled each section. AGENTS.md (rule/*) is not one ingredient.
832
- const sections = p.sections.get(f.ingredient);
833
- if (sections?.length) {
827
+ if (f.sections.length) {
834
828
  const layer = (l) => (l === "profile" ? `profile ${p.resolution.profile.name}` : l);
835
- console.log(` sections ${sections.map((x) => `${x.name} (${layer(x.layer)})`).join(", ")}`);
829
+ console.log(` sections ${f.sections.map((x) => `${x.name} (${layer(x.layer)})`).join(", ")}`);
836
830
  }
837
831
  // Spec 29 §4.1: which layer filled each parameter the file's ingredient cites — or `unset`.
838
- const params = p.params.get(f.ingredient);
839
- if (params?.length) {
832
+ if (f.params.length) {
840
833
  const layer = (l) => (typeof l === "string" ? l : "recipe" in l ? `recipe ${l.recipe}` : `profile ${l.profile}`);
841
- console.log(` params ${params.map((x) => `${x.key} (${layer(x.layer)})`).join(", ")}`);
834
+ console.log(` params ${f.params.map((x) => `${x.key} (${layer(x.layer)})`).join(", ")}`);
842
835
  }
843
- console.log(` profile ${ws.config.profile} (recipes: ${p.resolution.recipes.join(", ")})`);
844
- console.log(` hash ${hashNormalized(f.content)}`);
836
+ console.log(` profile ${f.profile} (recipes: ${f.recipes.join(", ")})`);
837
+ console.log(` hash ${f.hash}`);
845
838
  });
846
839
  /* ---------------------------------------------------------------- forge ls */
847
840
  program
@@ -899,6 +892,54 @@ workspaces
899
892
  for (const p of gone)
900
893
  console.log(`pruned ${p}`);
901
894
  });
895
+ /* ---------------------------------------------------------------- ui */
896
+ program
897
+ .command("ui")
898
+ .description("A local dashboard: the table of `craftar workspaces` and, for one workspace, its file states, a file's diff and explanation, and its Forge's recipes and ingredients — in a browser, on 127.0.0.1 only, behind an address that works for this run. Reads only — writes no workspace, lock, registry or Forge — and reaches no network; Ctrl-C stops it")
899
+ .option("--port <n>", "the port to listen on, 0 to 65535; 0 takes a free one", "4747")
900
+ .action(async (o) => {
901
+ // Every refusal comes before the bind (spec 36 §4.2).
902
+ const port = parsePort(o.port);
903
+ if (port === null)
904
+ fail("--port takes a whole number from 0 to 65535");
905
+ registryGate();
906
+ let reg;
907
+ try {
908
+ reg = await readRegistry(craftarHome());
909
+ }
910
+ catch (e) {
911
+ fail(errorText(e));
912
+ }
913
+ const version = program.version() ?? "unknown";
914
+ let ui;
915
+ try {
916
+ // The one line a failing request leaves in the terminal; nothing is printed per request otherwise.
917
+ ui = await startUi({ home: craftarHome(), version, port, onError: (line) => console.error(line) });
918
+ }
919
+ catch (e) {
920
+ // The code only, never the message.
921
+ const code = e.code;
922
+ if (code === "EADDRINUSE")
923
+ fail(`port ${port} is in use on 127.0.0.1 — pass --port <other>, or --port 0 for a free one`);
924
+ fail(`cannot listen on 127.0.0.1:${port}: ${code ?? "unknown"}`);
925
+ }
926
+ console.log(pc.bold(`craftar ui — craftar ${version} · read-only · ${reg.workspaces.length} registered`));
927
+ console.log(` open ${ui.url}`);
928
+ console.log(" the address works for this run only, on this machine — Ctrl-C stops it");
929
+ // The first signal closes the listener and lets the process end; a second one, while closing, ends it at once.
930
+ let closing = false;
931
+ const stop = () => {
932
+ if (closing)
933
+ process.exit(0);
934
+ closing = true;
935
+ void ui.close().then(() => {
936
+ console.log("stopped");
937
+ process.exitCode = 0;
938
+ });
939
+ };
940
+ process.on("SIGINT", stop);
941
+ process.on("SIGTERM", stop);
942
+ });
902
943
  /* ---------------------------------------------------------------- doctor */
903
944
  program
904
945
  .command("doctor")
@@ -1029,6 +1070,37 @@ templates
1029
1070
  if (report.exitCode)
1030
1071
  process.exitCode = 1;
1031
1072
  });
1073
+ /* ---------------------------------------------------------------- mcp */
1074
+ program
1075
+ .command("mcp")
1076
+ .description("Serve this workspace to an AI coder over the Model Context Protocol, on stdin and stdout: seven reading tools — status, diff, explain, recipes, ingredients, targets, doctor — with the data those commands print. Started by the AI coder, not typed. Reads only; reads without the network unless --fetch")
1077
+ .option("--workspace <dir>", "the workspace to serve", ".")
1078
+ .option("--fetch", "let a tool call fetch a remote Forge instead of reading the cached copy", false)
1079
+ .action(async (o) => {
1080
+ // The bound workspace, resolved once: no tool takes a directory (spec 35 §4.1).
1081
+ const root = path.resolve(o.workspace);
1082
+ const refusal = launchRefusal(process.stdin.isTTY === true, await exists(path.join(root, WORKSPACE_FILE)), root);
1083
+ if (refusal !== null)
1084
+ fail(refusal);
1085
+ // The configuration must read at launch — its forge, ref and profile are the pin. The Forge need not load: each call says so.
1086
+ let merged;
1087
+ try {
1088
+ merged = await readWorkspaceConfig(root);
1089
+ }
1090
+ catch (e) {
1091
+ fail(errorText(e));
1092
+ }
1093
+ // From here stdout carries protocol lines only, and stderr nothing (spec 35 §4.1, §7). Stdin ending ends the process, exit 0.
1094
+ await serve(process.stdin, process.stdout, {
1095
+ root,
1096
+ fetch: o.fetch,
1097
+ home: craftarHome(),
1098
+ version: program.version() ?? "unknown",
1099
+ registryOff: registryOff(),
1100
+ env: process.env,
1101
+ pin: pinOf(merged),
1102
+ });
1103
+ });
1032
1104
  /* ---------------------------------------------------------------- recipes */
1033
1105
  program
1034
1106
  .command("recipes")
@@ -1059,7 +1131,7 @@ program
1059
1131
  const r = listRecipes(forg, context);
1060
1132
  // Loading the workspace may warn (spec 13 §4.2); those come first, as in `plan()`.
1061
1133
  if (workspace)
1062
- r.warnings.unshift(...workspace.warnings);
1134
+ withLoadWarnings(r, workspace.warnings);
1063
1135
  if (o.json) {
1064
1136
  return console.log(JSON.stringify(r, null, 2));
1065
1137
  }
@@ -1184,7 +1256,7 @@ program
1184
1256
  fail(e instanceof Error ? e.message : String(e));
1185
1257
  }
1186
1258
  if (workspace)
1187
- result.warnings.unshift(...workspace.warnings);
1259
+ withLoadWarnings(result, workspace.warnings);
1188
1260
  if (o.json) {
1189
1261
  return console.log(JSON.stringify(result, null, 2));
1190
1262
  }
@@ -1344,36 +1416,32 @@ program
1344
1416
  .option("--workspace <dir>", "workspace whose targets to mark (default: . when it holds a craftar.yaml)")
1345
1417
  .option("--json", "machine-readable output", false)
1346
1418
  .action(async (o) => {
1347
- let inUse = null;
1348
- const warnings = [];
1349
1419
  const root = o.workspace ?? ".";
1420
+ let input = null;
1350
1421
  if (!(await exists(path.join(root, WORKSPACE_FILE)))) {
1351
- // craftar.yaml does not exist
1422
+ // Explicit --workspace without craftar.yaml: exit 1 with the load's own message. No --workspace: unmarked, no warning.
1352
1423
  if (o.workspace !== undefined) {
1353
- // Explicit --workspace: exit 1 with loadWorkspace's message
1354
1424
  try {
1355
- await loadWorkspace(root, load({}, "no-fetch"));
1425
+ await readWorkspaceConfig(root);
1356
1426
  }
1357
1427
  catch (e) {
1358
1428
  fail(e instanceof Error ? e.message : String(e));
1359
1429
  }
1360
1430
  }
1361
- // No --workspace: just show unmarked, no warning
1362
1431
  }
1363
1432
  else {
1364
- // craftar.yaml exists, try to load
1433
+ // craftar.yaml exists: a configuration that does not read is a warning, as a Forge that does not load is
1365
1434
  try {
1366
- const ws = await loadWorkspace(root, load({}, "no-fetch"));
1367
- inUse = resolve(ws.forge, ws.config).targets;
1435
+ input = { merged: await readWorkspaceConfig(root) };
1368
1436
  }
1369
1437
  catch (e) {
1370
- // Load or resolve failed — warning, not error
1371
- warnings.push(`targets in use not shown: ${e instanceof Error ? e.message : String(e)}`);
1438
+ input = { reason: e instanceof Error ? e.message : String(e) };
1372
1439
  }
1373
1440
  }
1374
- const result = listTargets(inUse);
1441
+ const result = await targetsReport(root, { home: load({}, "no-fetch").home }, input);
1442
+ const warnings = result.warnings;
1375
1443
  if (o.json) {
1376
- return console.log(JSON.stringify({ ...result, warnings }, null, 2));
1444
+ return console.log(JSON.stringify(result, null, 2));
1377
1445
  }
1378
1446
  // Text mode
1379
1447
  const targetLine = result.targets
@@ -2328,7 +2396,7 @@ services
2328
2396
  else
2329
2397
  psFault = `docker compose ps failed — ${r.stderr.trim().split("\n")[0] || `exit ${r.code}`}`;
2330
2398
  }
2331
- const report = statusReport(real, recorded, docker, ps, psFault);
2399
+ const report = servicesStatusReport(real, recorded, docker, ps, psFault);
2332
2400
  if (o.json)
2333
2401
  console.log(JSON.stringify(report, null, 2));
2334
2402
  else {
@@ -2473,6 +2541,13 @@ function printPrune(result) {
2473
2541
  function registryOff() {
2474
2542
  return Boolean(process.env.CRAFTAR_NO_REGISTRY);
2475
2543
  }
2544
+ /** `--port` as typed: digits only, 0 to 65535 — `0x10`, `1e3`, `+80` and `80.0` are not ports. */
2545
+ function parsePort(text) {
2546
+ if (!/^\d{1,5}$/.test(text))
2547
+ return null;
2548
+ const n = Number(text);
2549
+ return n <= 65535 ? n : null;
2550
+ }
2476
2551
  function registryGate() {
2477
2552
  if (registryOff())
2478
2553
  fail("the workspace registry is off (CRAFTAR_NO_REGISTRY is set)");
@@ -2554,19 +2629,6 @@ function forgeLine(ws, lock) {
2554
2629
  const moved = lock?.forge.commit && commit && lock.forge.commit !== commit ? ` · lock ${lock.forge.commit.slice(0, 8)}` : "";
2555
2630
  return ` forge ${o.source} @ ${at} ${commit?.slice(0, 8) ?? "no git"}${moved}`;
2556
2631
  }
2557
- /** `status --json`'s `forge` key, for every Forge (spec 13 §4.1). */
2558
- function forgeJson(ws, lock) {
2559
- const o = ws.origin;
2560
- return {
2561
- kind: o.kind,
2562
- source: o.source,
2563
- ref: o.ref,
2564
- defaultBranch: o.defaultBranch,
2565
- commit: ws.forge.commit,
2566
- lockCommit: lock?.forge.commit ?? null,
2567
- fetched: o.fetched,
2568
- };
2569
- }
2570
2632
  /** One line on stderr with the `error: ` prefix, without exiting — `fail()` is this, then exit 1. */
2571
2633
  function errorLine(msg) {
2572
2634
  console.error(pc.red("error: ") + msg);
@@ -2612,26 +2674,6 @@ function color(state) {
2612
2674
  return pc.dim;
2613
2675
  }
2614
2676
  }
2615
- function explainSkip(s) {
2616
- switch (s.state) {
2617
- case "drift":
2618
- return "hand-edited since last sync — `craftar drift show <path>`, then `craftar drift discard` or `craftar drift promote`";
2619
- case "collision":
2620
- return "exists but was never generated by craftar and differs from the Forge — rename it or import it";
2621
- case "orphan-drift":
2622
- return "no longer produced by the Forge but hand-edited — kept; `craftar drift discard <path>` removes it, or delete it yourself";
2623
- default:
2624
- return "";
2625
- }
2626
- }
2627
- async function readText(p) {
2628
- try {
2629
- return toLf(stripBom(await fs.readFile(p, "utf8")));
2630
- }
2631
- catch {
2632
- return null;
2633
- }
2634
- }
2635
2677
  /**
2636
2678
  * The real path of `abs`, resolved through its nearest existing ancestor: `fs.realpath` needs the
2637
2679
  * path to exist, and a plan target usually does not yet — so the part that exists is resolved