craftar 0.8.6 → 0.10.1

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 0 prototype**. `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) 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` (see *Forge layout*). Everything else in the spec (profiles with IDP/PM-tool integrations, local services, `dotnet new` project templates, `craftar ui`, `craftar mcp`) is not built yet.
5
+ > Status: **phase 0 prototype**. `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) 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` (see *Forge layout*). The read-only catalogue — `recipes`, `ingredients` and `targets` with the capability matrix — works too. Everything else in the spec (profiles with IDP/PM-tool integrations, local services, `dotnet new` project templates, `craftar ui`, `craftar mcp`) is not built yet.
6
6
 
7
7
  ## The idea in one paragraph
8
8
 
@@ -55,14 +55,17 @@ From then on, change a rule in `forge/ingredients/rules/<name>/rule.md`, run `cr
55
55
  | `craftar import --from claude-code --forge <dir> --profile <name> [--workspace .] [--write-config]` | Reads `.claude/{rules,agents,commands,skills,scripts,hooks}`, `.mcp.json` and, when present, `.kiro/steering` (for inclusion modes and hand-written steering). Creates ingredients, recipes (`base`, one `stack-*` per scoped rule, `<profile>-steering`) and a profile, or updates them. An ingredient already in the Forge is reused when the base, **rendered** for this profile (its declared defaults, the profile's `params`, the workspace's `overrides.params`), equals the workspace file; failing that, when a unique, proved assignment of the base's declared `{{keys}}` reproduces it, the values are **inferred** into the profile's `params` (one value per key per run; never a change another ingredient would feel). A base with section markers is rendered with the profile's `sections` and the workspace's `overrides.sections` first; when the workspace file differs from it only inside sections, the unique content that reproduces the file byte for byte is **inferred** into the profile's `sections` (tried after params, never combined with them; the report counts lines and never prints the content). An import that writes a section value, or compares a workspace file against a base holding markers, sets `schema: 2` in `craftar.forge.yaml`. A reused base takes the place its `<name>--<profile>` variant held: the profile moves to the shared recipe when that orders the base there, and an owned recipe gets the base in the variant's slot, so the rule order (and `AGENTS.md`) stays as it was. Anything else becomes a `<name>--<profile>` variant that emits under the original name, with the reason, so the workspace still round-trips while you decide what to unify. A shared recipe is never widened for one client: a profile whose ingredients differ from `base` or a `stack-*` gets its own `<recipe>--<profile>`. An existing profile is merged in place (`params`, `sections`, the recipes import owns, missing `targets`; every other field and comment kept, and an empty `{}` / `[]` it does not change stays on its line), as is a recipe the profile owns; `--write-config` merges an existing `craftar.yaml` (`forge`, `profile`, `targets`). The report adds `rendered` (with `sections <names>` when a section value filled the render), `inferred`, `sectioned`, `param <key>: <old> → <new>`, `section <key> <name>: <old> → <new>`, `forge craftar.forge.yaml edited (schema: 2)` and `profile … created|edited|unchanged` lines. It refuses, with the Forge untouched, a Forge that does not load, a profile or recipe or `craftar.yaml` that does not round-trip through the YAML writer, a misplaced profile, a recipe import writes whose file and `name` disagree, a workspace override that does not parse, a literal `{{key}}` the profile would render, changing a recipe or variant another profile uses, a workspace file holding a section marker at column 0 (sync would not reproduce it: indent it), a Forge base with malformed section markers, and a `craftar.forge.yaml` it needs to bump to `schema: 2` that does not round-trip (set it by hand). Ingredients holding a secret-like value (tokens, private keys, high-entropy MCP `env`/`args` values) are rejected and listed by location — the value is never printed. A UTF-16 file with a byte-order mark is decoded for the scan; UTF-16 without one is not detected. An ingredient that would not load back into the Forge (a name that is not slug-like, a non-string MCP `env` value) refuses the import, naming its source; so does an ingredient already in the Forge whose `ingredient.yaml` has an unknown key or a YAML syntax error, naming that file. Every read and check runs before the first write, so an import that fails leaves the Forge untouched and says so. |
56
56
  | `craftar status` | Classifies every file the Forge would produce: `new`, `update`, `unchanged`, `adopt`, `drift`, `collision`, `orphan`, `orphan-drift`. A `.json` file not yet in `craftar.lock` that parses to the planned value with its keys in the same order (it differs only in whitespace, escapes, number spelling or duplicate keys) is `adopt`, and the first `sync` rewrites it with the planned bytes — by design. For `claude-code`'s `.mcp.json` that is two-space JSON keeping the file's BOM and line endings; Kiro's JSON files become CRLF without a BOM, like every Kiro text file. A different key order is a `collision` — except for integer-like keys, which `JSON.parse` reorders. A locked JSON file reformatted by hand is `drift`, not `adopt`. `--json` for tooling. Exits 1 on malformed section markers and on a section marker in an ingredient the workspace resolves while `craftar.forge.yaml` declares `schema: 1` (or none), naming the Forge file and line, and when a rendered file would still hold a marker line, naming the ingredient, file and rendered line — as do `sync`, `diff`, `explain` and `ls`. Warns about a section value that names no ingredient, or no marker of an ingredient the workspace resolves, and about marker lines in an emitted file not every target renders as text (copied as they are). |
57
57
  | `craftar sync` | Renders sections (no rendered body holds a marker; an emitted file not every target renders as text keeps its markers, with a warning), then writes the plan and `craftar.lock`. `--dry-run` shows without writing. `--check` exits 1 when anything is out of sync (CI). `--overwrite-drift` regenerates hand-edited files (explicit, never default). |
58
- | `craftar diff [path]` | Line diff between disk and what the Forge would generate. |
58
+ | `craftar diff [path] [--exit-code]` | Line diff between disk and what the Forge would generate, for every file `sync --check` refuses: `update`, `drift`, `collision`, `new`, an `orphan` (shown as the removal of the whole file — the next `sync` deletes it) and an `orphan-drift` (a header and one line: `sync` keeps it). `[path]` limits it to the one file whose workspace-relative path, as `status` prints it, equals it. Exits 0 by default, differences or not. `--exit-code` exits 1 when there are differences — exactly when `sync --check` would — and makes a `[path]` that names no file craftar manages an error (exit 1, nothing on stdout); without the flag such a path prints `no differences`. |
59
59
  | `craftar explain <path>` | Which ingredient, recipe chain, target and origin produced a file and, for an ingredient with sections, which layer filled each one: `sections flavors (profile globex), extra (default)` (`default`, `profile <p>` or `workspace`). `AGENTS.md` gets no sections line: it is not one ingredient. |
60
60
  | `craftar ls` | Recipes and ingredients resolved for this workspace. |
61
+ | `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`, `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}`. |
62
+ | `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}`. |
63
+ | `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}`. |
61
64
  | `craftar forge variants [--forge <dir> \| --workspace <dir>] [--json]` | Lists ingredients that have variants, nearest first, with the profile each came from, its distance to the base and its hunks counted by suggested class (`[1 evolution · 2 block]`), then any variant whose base is missing from the Forge. Read-only; exits 0 either way. `--json` prints `{groups, orphans}`; each variant carries `classes: {evolution, value, block}`, which add up to `distance.hunks`. |
62
65
  | `craftar forge diff <type/name> [--against <profile>] [--forge <dir> \| --workspace <dir>] [--json]` | Shows the differences between a base ingredient and each of its variants: a header carrying the same distance `forge variants` reports, then hunk by hunk, each with a suggested class and reason — `evolution` (one side is newer text), `value` (an identifier-like token swapped in shared prose, with a suggested `param.<slug>`) or `block` (lines only one side has) — then the files that exist on only one side. A suggestion never decides anything. It compares the raw Forge text, section marker lines included, so a base with markers shows them as hunks against a variant that has none. Read-only. `--json` prints an array of `{ref, profile, distance, diff}`; each hunk carries `suggestion: {class, reason, tokens?}` next to its `kind`. |
63
66
  | `craftar forge unify <type/name> --profile <p> (--take base\|variant \| --plan <file> \| --save-plan <file>) [--forge <dir> \| --workspace <dir>] [--json]` | Resolves one variant back into its base, hunk by hunk. `--save-plan` writes a reviewable plan with every decision set to `keep`, each hunk annotated with its suggested class (which `--plan` ignores) and, for a `value` hunk, a pre-filled `params` list (`token` → suggested `key`); on a `block` hunk, a pre-filled `section: { name }` from the Markdown heading above (or `section-<n>`); and on a hunk touching a section the base already has, that section's name. It refuses a path that resolves inside the Forge (after `..` segments and symlinks) and a path that already exists, so it never overwrites a Forge file or a plan you already edited; it writes nothing else. A hunk set to `take: param` turns each listed token into `{{key}}` in the base, declares the base's text as the key's default in the base's `ingredient.yaml` and writes the variant's text into the variant profile's `profile.yaml` `params` — only after proving that both the base's and the variant's text render back exactly, and only when the same plan resolves the variant; it refuses (with the Forge untouched) a key another layer, profile or ingredient already uses, a variant another profile also uses, a whitespace-only difference, and a YAML file that would not round-trip unchanged. A hunk set to `take: section` (with `section: { name, lines? }`) wraps the base's lines in section markers as the default and writes the variant's lines into the variant profile's `sections` — consecutive hunks with one name form one section, `lines: "<from>-<to>"` widens it over equal base lines, and hunks inside a section the base already has only write the profile value; it is proved (both sides render back exactly) and needs the same plan to resolve the variant; `take: param` and `take: section` may share a plan, never a hunk. It refuses (Forge untouched) a `take: param` or `take: section` on a file no target emits, a variant that holds markers, a profile that already sets that section (another profile for a new section, or the variant's profile with other content), a span that cuts a hunk or crosses another section, a span that covers a hunk outside the run (including `take: base` on a hunk inside a section the plan fills), a hunk mixing lines inside and outside an existing section, and a span reaching a missing final newline; when it adds a section to a Forge still at `schema: 1` it sets `schema: 2` in `craftar.forge.yaml` in place (refused if the file does not round-trip). `--plan` applies an edited plan, refusing when it is not for this exact ingredient/profile or either side's fingerprint moved since it was saved. `--take base\|variant` resolves every decision to that side. Writes the merged base and, once every difference is resolved, removes the variant and rewrites every recipe reference to it (`ingredients`) to name the base. It never deletes a recipe and never edits an `extends`; it edits a profile only to write the values of a `take: param` or `take: section` extraction into the variant's own profile, and otherwise never: a `<recipe>--<profile>` left identical to `<recipe>` is reported as a warning, to be removed by hand after repointing the lists that name it — unify does not, because a workspace or an `extends` chain may also name `<recipe>` and the recipe order or param precedence would change. Unify cannot reach workspaces, so a removed variant is reported as a warning for any `craftar.yaml` that disables it in `overrides.ingredients.disable`. Every recipe rewrite is checked before the first write, so one that cannot land (a reference behind a YAML alias) is refused with the Forge untouched; a failure after writing began (an I/O error, a locked file) names the paths already touched and the `git checkout` / `git clean` commands that undo them. A merge never adds, removes or changes a section marker other than the sections the plan declares; a plan or `--take variant` that would is refused before the first write — take `base` for the marker lines, or `take: section` to fill the section; the citation checks of `take: param` also read the profiles' section values, which can cite `{{key}}`. `ingredient.yaml` is never merged: when the two sides' metadata differs (beyond `name`, `as` and `origin`), the variant stays unresolved and the differing fields are named — edit it by hand, or `--take base` to discard the variant, metadata included. Requires a clean git checkout in the Forge with at least one commit (`--save-plan` excepted) — the Forge has no lock, so git is the undo. It also refuses when any path it would overwrite or delete (the base, the variant, the recipe files it rewrites, the profile a parameter or section extraction edits, `craftar.forge.yaml` when it is bumped) is ignored, untracked, modified, or flagged skip-worktree or assume-unchanged in the index, since git could not restore it. `--json` prints `{base, profile, resolved, written, removed, unresolved, variantRemoved, recipes: {rewritten, identicalToSibling}, metaDiffers, params, profileEdited, sections, manifestEdited, warnings}` for `--take`/`--plan` (every key always present, `[]` when empty), or `{base, profile, plan, unresolved}` for `--save-plan`. |
64
67
 
65
- All commands take `--workspace <dir>` (default: current directory); the `forge` commands also take `--forge <dir>` as an alternative to it.
68
+ All commands take `--workspace <dir>` (default: current directory); the `forge` commands, `recipes` and `ingredients` also take `--forge <dir>` as an alternative to it, and `targets` needs no Forge.
66
69
 
67
70
  ## Forge layout
68
71
 
@@ -184,6 +187,19 @@ Sections layer the same way, weakest → strongest: the body's default → the p
184
187
 
185
188
  ## Targets
186
189
 
190
+ `craftar targets` prints this matrix from `src/core/capabilities.ts`; a test plans one ingredient of every type for each target and fails when a cell and its emitter disagree. **native** — written in the tool's own place for that type, as the Forge holds it; **converted** — written in another form (frontmatter or a banner added, references rewritten, another container format, or folded into a shared file); **unsupported** — not written: `sync` warns and names an ingredient aimed at that target.
191
+
192
+ | type | `claude-code` | `kiro` | `agents-md` |
193
+ |---|---|---|---|
194
+ | `rule` | native | converted | converted |
195
+ | `agent` | native | converted | unsupported |
196
+ | `command` | native | converted | unsupported |
197
+ | `skill` | native | converted | unsupported |
198
+ | `mcp` | native | native | unsupported |
199
+ | `script` | native | unsupported | unsupported |
200
+ | `steering` | unsupported | native | unsupported |
201
+ | `hook` | native | unsupported | unsupported |
202
+
187
203
  **claude-code** — emits `.claude/rules|agents|commands|skills|scripts|hooks` and `.mcp.json` verbatim from the Forge (frontmatter kept byte-for-byte). Each MCP server is written exactly as the Forge holds it, undeclared keys included, in its own key order. Existing files keep their line endings and BOM; new files are LF without a BOM. Steering is Kiro-only (its `targets` default to `[kiro]`); one aimed at `claude-code` explicitly (`targets: "*"` or a list naming it) is skipped with a warning.
188
204
 
189
205
  **kiro** — reproduces, then extends, the hand-written `sync-steering.ps1` script it replaces:
@@ -236,11 +252,23 @@ Copy a workspace with `.claude/` and `.kiro/` into `fixtures/` (keep `local-stac
236
252
 
237
253
  ## Roadmap (from the functional spec)
238
254
 
239
- Phase 0 (this): schema, import, sync/status/diff/explain, claude-code + kiro + agents-md targets, lock, drift, orphans.
255
+ Phase 0 (this): schema, import, sync/status/diff/explain, claude-code + kiro + agents-md targets, lock, drift, orphans; the read-only catalogue (`recipes`, `ingredients`, `targets` with the capability matrix).
240
256
  Next: `craftar init` from a profile; profile-driven integrations (PM tool → MCP, IDP → MCP); `service` ingredients with compose fragments (`craftar services up`); `dotnet new` template registration; rulesync bridge for Codex/Kimi/Cursor specifics; remote Forge (git URL + ref); `craftar docs validate`; GitHub Action and Azure Pipelines task around `sync --check`; `craftar ui`; `craftar mcp` + Claude Code / Agent Plugin packaging.
241
257
 
242
258
  ## Upgrading
243
259
 
260
+ ### to 0.10.0
261
+
262
+ - **`craftar diff` shows orphans.** A file the Forge no longer produces is printed as the removal of the whole file (`+++ <path> (forge: no longer produced — sync removes it)`), and a hand-edited one as a header and one line, since `sync` keeps it. Output changes only in a workspace that has an `orphan` or an `orphan-drift` — one whose only pending change was an orphan used to print `no differences`; elsewhere it is byte for byte 0.9.0's.
263
+ - **`craftar diff --exit-code`** exits 1 when there are differences — exactly when `sync --check` would — and refuses a `[path]` that names no file craftar manages. Without the flag `diff` still exits 0.
264
+ - **No byte change**: no emitter, `plan`, `status` or `sync` changed. No workspace sees `update`.
265
+
266
+ ### to 0.9.0
267
+
268
+ - **Three new read-only commands**: `craftar recipes`, `craftar ingredients` and `craftar targets`. They write nothing — no generated file, no lock, no Forge file.
269
+ - **No byte change**: no emitter changed, and `craftar ls` prints what it printed before. No workspace sees `update`.
270
+ - Their `--json` output is a tooling contract, like `status --json`: removing or renaming a key, changing a value's type, or adding a capability state will be announced here.
271
+
244
272
  ### to 0.8.6
245
273
 
246
274
  - **A rule reference inside the text of a Markdown link is now resolved like any other**, in `AGENTS.md` and in the kiro files. Before, the text of a link that `AGENTS.md` or kiro rewrote was copied as the Forge held it, or blanket-rewritten to `.kiro/steering/`.
package/dist/cli.js CHANGED
@@ -4,21 +4,23 @@ import path from "node:path";
4
4
  import { promises as fs } from "node:fs";
5
5
  import YAML from "yaml";
6
6
  import { importClaudeCode } from "./importers/claude-code.js";
7
- import { loadWorkspace, plan, readLock, status, apply, resolveForge } from "./core/sync.js";
8
- import { sectionKey } from "./core/resolve.js";
7
+ import { loadWorkspace, plan, readLock, status, apply, resolveForge, resolveForgeSource, WORKSPACE_FILE } from "./core/sync.js";
8
+ import { resolve, sectionKey } from "./core/resolve.js";
9
+ import { catalogueContext, listRecipes, listIngredients, checkType } from "./core/catalogue.js";
10
+ import { listTargets } from "./core/capabilities.js";
9
11
  import { canonicalValue } from "./core/sections.js";
10
12
  import { renderDiff, NO_EOF_NEWLINE_MARKER } from "./core/diff.js";
11
13
  import { diffIngredients, listVariants, profileOf } from "./core/variants.js";
12
14
  import { hashNormalized, toLf, stripBom } from "./core/text.js";
13
- import { gitDirty, gitIsRepo, gitUnheld } from "./core/forge.js";
15
+ import { exists, gitDirty, gitIsRepo, gitUnheld } from "./core/forge.js";
14
16
  import { fingerprintDir } from "./core/fingerprint.js";
15
17
  import { hunkAt, planFrom, applyPlan, writeUnified, checkRecipeCascade, rewriteRecipes, } from "./core/unify.js";
16
18
  import { checkParamWrites, writeParamFile } from "./core/param-writes.js";
17
- import { HUNK_CLASSES, UnifyPlanSchema } from "./schema/index.js";
19
+ import { HUNK_CLASSES, INGREDIENT_TYPES, UnifyPlanSchema } from "./schema/index.js";
18
20
  process.stdout.on("error", (e) => { if (e.code === "EPIPE")
19
21
  process.exit(0); });
20
22
  const program = new Command();
21
- program.name("craftar").description("Craft, sync and convert AI-coding workspace harnesses.").version("0.8.6");
23
+ program.name("craftar").description("Craft, sync and convert AI-coding workspace harnesses.").version("0.10.1");
22
24
  /* ---------------------------------------------------------------- import */
23
25
  program
24
26
  .command("import")
@@ -118,28 +120,51 @@ program
118
120
  /* ---------------------------------------------------------------- diff */
119
121
  program
120
122
  .command("diff")
121
- .description("Unified diff between the files on disk and what the Forge would generate")
123
+ .description("Unified diff between the files on disk and what the Forge would generate, orphans included (files the Forge no longer produces)")
122
124
  .option("--workspace <dir>", "workspace root", ".")
125
+ .option("--exit-code", "exit 1 when there are differences (exactly when `sync --check` would fail); a [path] that names no file craftar manages becomes an error", false)
123
126
  .argument("[path]", "limit to one file")
124
127
  .action(async (only, o) => {
125
128
  const ws = await loadWorkspace(o.workspace);
126
129
  const p = await plan(ws);
127
130
  const st = await status(ws, p, await readLock(ws.root));
131
+ // Spec 19 §3.3: under --exit-code a path nothing matches must not read as "clean" to a script
132
+ if (o.exitCode && only && !st.some((s) => s.path === only))
133
+ fail(`${only} is not a file craftar manages in this workspace — pass the workspace-relative path as \`craftar status\` prints it (forward slashes)`);
128
134
  let shown = 0;
135
+ const render = { paint: { same: pc.dim, del: pc.red, add: pc.green } };
129
136
  for (const s of st) {
130
137
  if (only && s.path !== only)
131
138
  continue;
132
- if (!["update", "drift", "collision", "new"].includes(s.state))
139
+ // Spec 19 §3.2: show the six states sync --check refuses (skip unchanged and adopt)
140
+ if (["unchanged", "adopt"].includes(s.state))
133
141
  continue;
134
142
  shown++;
143
+ if (s.state === "orphan-drift") {
144
+ // Header and one line, no body: sync keeps this file
145
+ console.log(pc.bold(`--- ${s.path} (disk, orphan-drift)`));
146
+ console.log(` ${explainSkip(s)}`);
147
+ continue;
148
+ }
135
149
  const disk = await readText(path.join(ws.root, s.path));
136
- const next = s.planned ? toLf(stripBom(s.planned.content.toString("utf8"))) : "";
137
- console.log(pc.bold(`--- ${s.path} (disk, ${s.state})`));
138
- console.log(pc.bold(`+++ ${s.path} (forge)`));
139
- console.log(renderDiff(disk ?? "", next, { paint: { same: pc.dim, del: pc.red, add: pc.green } }));
150
+ if (s.state === "orphan") {
151
+ // A removal: the file exists on disk but the Forge no longer produces it
152
+ console.log(pc.bold(`--- ${s.path} (disk, orphan)`));
153
+ console.log(pc.bold(`+++ ${s.path} (forge: no longer produced — sync removes it)`));
154
+ console.log(renderDiff(disk ?? "", "", render));
155
+ }
156
+ else {
157
+ const next = s.planned ? toLf(stripBom(s.planned.content.toString("utf8"))) : "";
158
+ console.log(pc.bold(`--- ${s.path} (disk, ${s.state})`));
159
+ console.log(pc.bold(`+++ ${s.path} (forge)`));
160
+ console.log(renderDiff(disk ?? "", next, render));
161
+ }
140
162
  }
141
163
  if (!shown)
142
164
  console.log(pc.green("no differences"));
165
+ // exitCode, not process.exit: exit drops a piped diff still queued for a slow reader (spec 19 §3.1)
166
+ else if (o.exitCode)
167
+ process.exitCode = 1;
143
168
  });
144
169
  /* ---------------------------------------------------------------- explain */
145
170
  program
@@ -187,6 +212,389 @@ program
187
212
  }
188
213
  console.log(`\n${p.files.length} files across targets ${p.resolution.targets.join(", ")}`);
189
214
  });
215
+ /* ---------------------------------------------------------------- recipes */
216
+ program
217
+ .command("recipes")
218
+ .description("List every recipe of the Forge — slot, parents, the profiles that use it — marked against this workspace or a profile. Read-only")
219
+ .option("--forge <dir>", "Forge directory (instead of --workspace)")
220
+ .option("--profile <name>", "with --forge: mark what this profile resolves")
221
+ .option("--workspace <dir>", "workspace whose craftar.yaml names the Forge (default: .)")
222
+ .option("--json", "machine-readable output", false)
223
+ .action(async (o) => {
224
+ if (o.profile && !o.forge)
225
+ fail("--profile goes with --forge — inside a workspace the profile comes from craftar.yaml");
226
+ const { forge: forg, workspace } = await resolveForgeSource({ forge: o.forge, workspace: o.workspace });
227
+ const source = workspace
228
+ ? { kind: "workspace", config: workspace.config }
229
+ : o.profile
230
+ ? { kind: "profile", profile: o.profile }
231
+ : null;
232
+ let context = null;
233
+ if (source) {
234
+ try {
235
+ context = catalogueContext(forg, source);
236
+ }
237
+ catch (e) {
238
+ fail(e instanceof Error ? e.message : String(e));
239
+ }
240
+ }
241
+ const r = listRecipes(forg, context);
242
+ if (o.json) {
243
+ return console.log(JSON.stringify(r, null, 2));
244
+ }
245
+ // Text mode
246
+ const ctxDesc = source
247
+ ? source.kind === "workspace"
248
+ ? `workspace profile ${source.config.profile}`
249
+ : `profile ${source.profile}`
250
+ : null;
251
+ console.log(pc.bold(`craftar recipes — forge ${forg.manifest.name} @ ${forg.commit?.slice(0, 8) ?? "no git"}${ctxDesc ? ` · ${ctxDesc}` : ""}`));
252
+ const resolves = context !== null && context.resolution !== null;
253
+ // Compute column widths for alignment
254
+ // Column 1: name[ [slot s]]
255
+ // Column 2: <N ingredient(s)>
256
+ // Column 3: ← parents (empty when none)
257
+ // Column 4: reason (empty when none)
258
+ const col1 = r.recipes.map((rec) => `${rec.name}${rec.slot ? ` [slot ${rec.slot}]` : ""}`);
259
+ const col2 = r.recipes.map((rec) => `${rec.ingredients.length} ingredient${rec.ingredients.length === 1 ? "" : "s"}`);
260
+ const col3 = r.recipes.map((rec) => rec.extends.length ? `← ${rec.extends.join(", ")}` : "");
261
+ const col4 = r.recipes.map((rec) => {
262
+ let reason = "";
263
+ if (rec.inUse) {
264
+ const byParts = [];
265
+ for (const b of rec.inUse.by) {
266
+ if (b === "extends")
267
+ byParts.push(`extends ${rec.inUse.extendedBy.join(", ")}`);
268
+ else
269
+ byParts.push(b);
270
+ }
271
+ reason = `in use (${byParts.join(", ")})`;
272
+ }
273
+ const removed = rec.removedByWorkspace ? (reason ? " · " : "") + "removed by this workspace" : "";
274
+ return reason + removed;
275
+ });
276
+ const w1 = Math.max(...col1.map((s) => s.length));
277
+ const w2 = Math.max(...col2.map((s) => s.length));
278
+ const w3 = Math.max(...col3.map((s) => s.length));
279
+ const w4 = Math.max(...col4.map((s) => s.length));
280
+ for (let i = 0; i < r.recipes.length; i++) {
281
+ const rec = r.recipes[i];
282
+ const desc = rec.description ? `— ${rec.description}` : "";
283
+ let line;
284
+ if (resolves) {
285
+ const mark = rec.inUse ? pc.green("●") : pc.dim("○");
286
+ line = [
287
+ ` ${mark} `,
288
+ col1[i].padEnd(w1),
289
+ " ",
290
+ col2[i].padEnd(w2),
291
+ col3[i] ? " " + col3[i].padEnd(w3) : (w3 > 0 ? " " + "".padEnd(w3) : ""),
292
+ col4[i] ? " " + col4[i].padEnd(w4) : (w4 > 0 ? " " + "".padEnd(w4) : ""),
293
+ desc ? " " + desc : "",
294
+ ].join("").trimEnd();
295
+ }
296
+ else {
297
+ // No context: no mark column, rows start with two spaces then the name
298
+ line = [
299
+ " ",
300
+ col1[i].padEnd(w1),
301
+ " ",
302
+ col2[i].padEnd(w2),
303
+ col3[i] ? " " + col3[i].padEnd(w3) : (w3 > 0 ? " " + "".padEnd(w3) : ""),
304
+ desc ? " " + desc : "",
305
+ ].join("").trimEnd();
306
+ }
307
+ console.log(line);
308
+ }
309
+ // Count line
310
+ const inUseCount = r.recipes.filter((x) => x.inUse).length;
311
+ const profilesPart = r.recipes.length > 0
312
+ ? ` · used by profiles: ${r.recipes.map((x) => `${x.name} (${x.profiles.length ? x.profiles.join(", ") : "—"})`).join(", ")}`
313
+ : "";
314
+ const countLine = resolves
315
+ ? `${r.recipes.length} recipe${r.recipes.length === 1 ? "" : "s"}, ${inUseCount} in use${profilesPart}`
316
+ : `${r.recipes.length} recipe${r.recipes.length === 1 ? "" : "s"}${profilesPart}`;
317
+ console.log(`\n ${countLine}`);
318
+ for (const w of r.warnings)
319
+ console.log(` ${pc.yellow("warn")} ${w}`);
320
+ });
321
+ /* ---------------------------------------------------------------- ingredients */
322
+ program
323
+ .command("ingredients")
324
+ .description("List every ingredient of the Forge — its recipes and targets, references to missing ones — or what one recipe brings with its parents. Read-only")
325
+ .option("--recipe <name>", "only what this recipe brings, with the parents it extends, parents first")
326
+ .option("--type <type>", "only this ingredient type")
327
+ .option("--forge <dir>", "Forge directory (instead of --workspace)")
328
+ .option("--profile <name>", "with --forge: mark what this profile resolves")
329
+ .option("--workspace <dir>", "workspace whose craftar.yaml names the Forge (default: .)")
330
+ .option("--json", "machine-readable output", false)
331
+ .action(async (o) => {
332
+ if (o.profile && !o.forge)
333
+ fail("--profile goes with --forge — inside a workspace the profile comes from craftar.yaml");
334
+ if (o.type) {
335
+ try {
336
+ checkType(o.type);
337
+ }
338
+ catch (e) {
339
+ fail(e instanceof Error ? e.message : String(e));
340
+ }
341
+ }
342
+ const { forge: forg, workspace } = await resolveForgeSource({ forge: o.forge, workspace: o.workspace });
343
+ const source = workspace
344
+ ? { kind: "workspace", config: workspace.config }
345
+ : o.profile
346
+ ? { kind: "profile", profile: o.profile }
347
+ : null;
348
+ let context = null;
349
+ if (source) {
350
+ try {
351
+ context = catalogueContext(forg, source);
352
+ }
353
+ catch (e) {
354
+ fail(e instanceof Error ? e.message : String(e));
355
+ }
356
+ }
357
+ let result;
358
+ try {
359
+ result = listIngredients(forg, context, { recipe: o.recipe, type: o.type });
360
+ }
361
+ catch (e) {
362
+ fail(e instanceof Error ? e.message : String(e));
363
+ }
364
+ if (o.json) {
365
+ return console.log(JSON.stringify(result, null, 2));
366
+ }
367
+ // Text mode
368
+ const ctxDesc = source
369
+ ? source.kind === "workspace"
370
+ ? `workspace profile ${source.config.profile}`
371
+ : `profile ${source.profile}`
372
+ : null;
373
+ const recipeOpt = o.recipe ? ` --recipe ${o.recipe}` : "";
374
+ const typeOpt = o.type ? ` --type ${o.type}` : "";
375
+ console.log(pc.bold(`craftar ingredients${recipeOpt}${typeOpt} — forge ${forg.manifest.name} @ ${forg.commit?.slice(0, 8) ?? "no git"}${ctxDesc ? ` · ${ctxDesc}` : ""}`));
376
+ const resolves = context !== null && context.resolution !== null;
377
+ if (result.recipe) {
378
+ // --recipe mode: grouped by chain entry
379
+ // Compute column widths for alignment across the whole listing
380
+ // Column 1: ref[ → outputName]
381
+ const col1Recipe = [];
382
+ for (const entry of result.recipe.chain) {
383
+ for (const ref of entry.ingredients) {
384
+ const ing = result.ingredients.find((i) => i.ref === ref);
385
+ if (ing) {
386
+ col1Recipe.push(ing.outputName !== ing.name ? `${ref} → ${ing.outputName}` : ref);
387
+ }
388
+ else {
389
+ col1Recipe.push(ref);
390
+ }
391
+ }
392
+ }
393
+ const w1Recipe = Math.max(...col1Recipe.map((s) => s.length), 0);
394
+ for (const entry of result.recipe.chain) {
395
+ const rec = forg.recipes.get(entry.recipe);
396
+ const ext = rec?.extends.length ? ` ← ${rec.extends.join(", ")}` : "";
397
+ const slot = rec?.slot ? ` [slot ${rec.slot}]` : "";
398
+ console.log(`${entry.recipe}${ext}${slot}`);
399
+ for (const ref of entry.ingredients) {
400
+ const ing = result.ingredients.find((i) => i.ref === ref);
401
+ const miss = result.missing.find((m) => m.ref === ref);
402
+ if (ing) {
403
+ const col1 = ing.outputName !== ing.name ? `${ref} → ${ing.outputName}` : ref;
404
+ const disabled = ing.disabled ? "(disabled by this workspace)" : "";
405
+ let line;
406
+ if (resolves) {
407
+ const mark = ing.disabled ? pc.dim("◌") : ing.inUse ? pc.green("●") : pc.dim("○");
408
+ line = ` ${mark} ${col1.padEnd(w1Recipe)}${disabled ? " " + disabled : ""}`.trimEnd();
409
+ }
410
+ else {
411
+ line = ` ${col1.padEnd(w1Recipe)}`.trimEnd();
412
+ }
413
+ console.log(line);
414
+ }
415
+ else if (miss) {
416
+ const line = ` ${pc.red("✗")} ${ref.padEnd(w1Recipe)} not in this Forge`.trimEnd();
417
+ console.log(line);
418
+ }
419
+ }
420
+ }
421
+ // Count line for --recipe
422
+ const countLine = `${result.recipe.chain.length} recipe${result.recipe.chain.length === 1 ? "" : "s"}, ${result.ingredients.length} ingredient${result.ingredients.length === 1 ? "" : "s"}${result.missing.length ? ` · ${result.missing.length} missing reference${result.missing.length === 1 ? "" : "s"}` : ""}`;
423
+ console.log(`\n ${countLine}`);
424
+ }
425
+ else {
426
+ // No --recipe: grouped by type
427
+ // Spec 16 §4.3: rows print the bare `name`, not the `ref`, under their type heading
428
+ // Compute column widths across the whole listing (all types + missing)
429
+ // Column 1: name[ → outputName] (or ref for missing)
430
+ // Column 2: targets <...>
431
+ // Column 3: in <...>
432
+ const allCol1 = [];
433
+ const allCol2 = [];
434
+ const allCol3 = [];
435
+ for (const ing of result.ingredients) {
436
+ const col1 = ing.outputName !== ing.name ? `${ing.name} → ${ing.outputName}` : ing.name;
437
+ allCol1.push(col1);
438
+ allCol2.push(`targets ${ing.targets === "*" ? "*" : ing.targets.join(", ")}`);
439
+ allCol3.push(`in ${ing.recipes.length ? ing.recipes.join(", ") : "no recipe"}`);
440
+ }
441
+ for (const m of result.missing) {
442
+ allCol1.push(m.ref);
443
+ }
444
+ const w1 = Math.max(...allCol1.map((s) => s.length), 0);
445
+ const w2 = Math.max(...allCol2.map((s) => s.length), 0);
446
+ const w3 = Math.max(...allCol3.map((s) => s.length), 0);
447
+ const byType = new Map();
448
+ for (const ing of result.ingredients) {
449
+ if (!byType.has(ing.type))
450
+ byType.set(ing.type, []);
451
+ byType.get(ing.type).push(ing);
452
+ }
453
+ for (const type of INGREDIENT_TYPES) {
454
+ const ings = byType.get(type);
455
+ if (!ings?.length)
456
+ continue;
457
+ console.log(type);
458
+ for (const ing of ings) {
459
+ const col1 = ing.outputName !== ing.name ? `${ing.name} → ${ing.outputName}` : ing.name;
460
+ const col2 = `targets ${ing.targets === "*" ? "*" : ing.targets.join(", ")}`;
461
+ const col3 = `in ${ing.recipes.length ? ing.recipes.join(", ") : "no recipe"}`;
462
+ const desc = ing.description ? `— ${ing.description}` : "";
463
+ const disabled = ing.disabled ? "(disabled by this workspace)" : "";
464
+ let line;
465
+ if (resolves) {
466
+ const mark = ing.disabled ? pc.dim("◌") : ing.inUse ? pc.green("●") : pc.dim("○");
467
+ line = [
468
+ ` ${mark} `,
469
+ col1.padEnd(w1),
470
+ " ",
471
+ col2.padEnd(w2),
472
+ " ",
473
+ col3.padEnd(w3),
474
+ desc ? " " + desc : "",
475
+ disabled ? " " + disabled : "",
476
+ ].join("").trimEnd();
477
+ }
478
+ else {
479
+ // No context: no mark column, rows start with two spaces then the name
480
+ line = [
481
+ " ",
482
+ col1.padEnd(w1),
483
+ " ",
484
+ col2.padEnd(w2),
485
+ " ",
486
+ col3.padEnd(w3),
487
+ desc ? " " + desc : "",
488
+ ].join("").trimEnd();
489
+ }
490
+ console.log(line);
491
+ }
492
+ }
493
+ if (result.missing.length) {
494
+ console.log("missing");
495
+ for (const m of result.missing) {
496
+ const line = ` ${m.ref.padEnd(w1)} cited by ${m.recipes.join(", ")}, not in this Forge`.trimEnd();
497
+ console.log(line);
498
+ }
499
+ }
500
+ // Count line
501
+ const inUseCount = result.ingredients.filter((x) => x.inUse).length;
502
+ const disabledCount = result.ingredients.filter((x) => x.disabled).length;
503
+ const noRecipeCount = result.ingredients.filter((x) => x.recipes.length === 0).length;
504
+ const countParts = [`${result.ingredients.length} ingredient${result.ingredients.length === 1 ? "" : "s"}`];
505
+ if (resolves) {
506
+ countParts.push(`${inUseCount} in use`);
507
+ countParts.push(`${disabledCount} disabled`);
508
+ }
509
+ countParts.push(`${noRecipeCount} in no recipe`);
510
+ const missingPart = result.missing.length ? ` · ${result.missing.length} missing reference${result.missing.length === 1 ? "" : "s"}` : "";
511
+ console.log(`\n ${countParts.join(", ")}${missingPart}`);
512
+ }
513
+ for (const w of result.warnings)
514
+ console.log(` ${pc.yellow("warn")} ${w}`);
515
+ });
516
+ /* ---------------------------------------------------------------- targets */
517
+ program
518
+ .command("targets")
519
+ .description("Print the capability matrix: what each target does with each ingredient type (native, converted, unsupported), marking the targets this workspace uses. Read-only")
520
+ .option("--workspace <dir>", "workspace whose targets to mark (default: . when it holds a craftar.yaml)")
521
+ .option("--json", "machine-readable output", false)
522
+ .action(async (o) => {
523
+ let inUse = null;
524
+ const warnings = [];
525
+ const root = o.workspace ?? ".";
526
+ if (!(await exists(path.join(root, WORKSPACE_FILE)))) {
527
+ // craftar.yaml does not exist
528
+ if (o.workspace !== undefined) {
529
+ // Explicit --workspace: exit 1 with loadWorkspace's message
530
+ try {
531
+ await loadWorkspace(root);
532
+ }
533
+ catch (e) {
534
+ fail(e instanceof Error ? e.message : String(e));
535
+ }
536
+ }
537
+ // No --workspace: just show unmarked, no warning
538
+ }
539
+ else {
540
+ // craftar.yaml exists, try to load
541
+ try {
542
+ const ws = await loadWorkspace(root);
543
+ inUse = resolve(ws.forge, ws.config).targets;
544
+ }
545
+ catch (e) {
546
+ // Load or resolve failed — warning, not error
547
+ warnings.push(`targets in use not shown: ${e instanceof Error ? e.message : String(e)}`);
548
+ }
549
+ }
550
+ const result = listTargets(inUse);
551
+ if (o.json) {
552
+ return console.log(JSON.stringify({ ...result, warnings }, null, 2));
553
+ }
554
+ // Text mode
555
+ const targetLine = result.targets
556
+ .map((t) => (t.inUse === true ? `${t.name} (in use)` : t.name))
557
+ .join(" · ");
558
+ console.log(pc.bold(`craftar targets — ${targetLine}`));
559
+ console.log();
560
+ // Matrix table
561
+ const colWidth = 14;
562
+ const typeColWidth = 10;
563
+ const header = " " + " ".repeat(typeColWidth) + result.targets.map((t) => t.name.padEnd(colWidth)).join("");
564
+ console.log(header.trimEnd());
565
+ for (const type of result.ingredientTypes) {
566
+ const row = " " + type.padEnd(typeColWidth) + result.targets.map((t) => {
567
+ const cap = t.capabilities[type];
568
+ return cap.state.padEnd(colWidth);
569
+ }).join("");
570
+ console.log(row.trimEnd());
571
+ }
572
+ console.log();
573
+ // Legend
574
+ console.log(" native written in the tool's own place for that type, as the Forge holds it");
575
+ console.log(" converted written in another form — see its line below");
576
+ console.log(" unsupported not written; sync warns and names an ingredient aimed at this target");
577
+ console.log();
578
+ // Paths block — type-major (types outer, targets inner); align labels to widest
579
+ console.log("paths");
580
+ const pathLines = [];
581
+ for (const type of INGREDIENT_TYPES) {
582
+ for (const t of result.targets) {
583
+ const cap = t.capabilities[type];
584
+ if (cap.output.length > 0) {
585
+ const pathStr = cap.output.join(", ");
586
+ const note = cap.note ? ` — ${cap.note}` : "";
587
+ pathLines.push({ label: `${t.name} · ${type}`, content: `${pathStr}${note}` });
588
+ }
589
+ }
590
+ }
591
+ const maxLabelLen = Math.max(...pathLines.map((l) => l.label.length));
592
+ for (const line of pathLines) {
593
+ console.log(` ${line.label.padEnd(maxLabelLen)} ${line.content}`);
594
+ }
595
+ for (const w of warnings)
596
+ console.log(` ${pc.yellow("warn")} ${w}`);
597
+ });
190
598
  /* ---------------------------------------------------------------- forge */
191
599
  const forge = program.command("forge").description("Operate on the Forge itself rather than on a workspace");
192
600
  forge