@bezel-labs/bezel-kit 0.9.0 → 0.11.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/dist/node.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/node.ts
@@ -27,6 +37,12 @@ __export(node_exports, {
27
37
  DEFAULT_NAME_EXTENSION: () => DEFAULT_NAME_EXTENSION,
28
38
  DEFAULT_OUTPUT_DIR: () => DEFAULT_OUTPUT_DIR,
29
39
  FALLBACK_OUTPUT_DIR: () => FALLBACK_OUTPUT_DIR,
40
+ LOCKFILE_NAME: () => LOCKFILE_NAME,
41
+ LOCKFILE_VERSION: () => LOCKFILE_VERSION,
42
+ SYNC_STAGING_PATH: () => SYNC_STAGING_PATH,
43
+ buildLockfile: () => buildLockfile,
44
+ changedPaths: () => changedPaths,
45
+ diffTokens: () => diffTokens,
30
46
  emitCss: () => emitCss,
31
47
  formatContextsModule: () => formatContextsModule,
32
48
  formatFontsModule: () => formatFontsModule,
@@ -34,14 +50,23 @@ __export(node_exports, {
34
50
  getContexts: () => getContexts,
35
51
  getFonts: () => getFonts,
36
52
  initConfig: () => initConfig,
53
+ isOperationApplied: () => isOperationApplied,
54
+ isPatchApplied: () => isPatchApplied,
55
+ jsonEqual: () => jsonEqual,
56
+ parseLockfile: () => parseLockfile,
37
57
  readPackageScripts: () => readPackageScripts,
58
+ removeLockfileForOtherProject: () => removeLockfileForOtherProject,
38
59
  resolveCssOptions: () => resolveCssOptions,
39
60
  resolveOptions: () => resolveOptions,
40
- tokensToCss: () => tokensToCss
61
+ serializeLockfile: () => serializeLockfile,
62
+ serializeTokensFile: () => serializeTokensFile,
63
+ syncFromStaging: () => syncFromStaging,
64
+ tokensToCss: () => tokensToCss,
65
+ unappliedOperations: () => unappliedOperations
41
66
  });
42
67
  module.exports = __toCommonJS(node_exports);
43
- var import_promises2 = require("fs/promises");
44
- var import_node_path3 = require("path");
68
+ var import_promises3 = require("fs/promises");
69
+ var import_node_path4 = require("path");
45
70
 
46
71
  // src/config.ts
47
72
  var import_node_path = require("path");
@@ -471,17 +496,123 @@ function mergeGitignore(existing, entries) {
471
496
  return mergeManagedBlock(existing, entries, { start: START, end: END });
472
497
  }
473
498
 
499
+ // src/lockfile.ts
500
+ var LOCKFILE_NAME = "design-tokens-lock.json";
501
+ var LOCKFILE_VERSION = 1;
502
+ var SYNC_STAGING_PATH = ".bezel/sync.json";
503
+ function buildLockfile(input) {
504
+ return {
505
+ lockfileVersion: LOCKFILE_VERSION,
506
+ projectId: input.projectId,
507
+ version: input.version,
508
+ revision: input.revision,
509
+ tokens: input.tokens
510
+ };
511
+ }
512
+ function serializeLockfile(lockfile) {
513
+ return `${JSON.stringify(lockfile, null, 2)}
514
+ `;
515
+ }
516
+ function serializeTokensFile(tokens) {
517
+ return `${JSON.stringify(tokens, null, 2)}
518
+ `;
519
+ }
520
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
521
+ function parseLockfile(text, name = LOCKFILE_NAME) {
522
+ let parsed;
523
+ try {
524
+ parsed = JSON.parse(text);
525
+ } catch {
526
+ const merged = /^(<<<<<<<|=======|>>>>>>>)/m.test(text);
527
+ return {
528
+ ok: false,
529
+ reason: "invalid-json",
530
+ message: merged ? `${name} has git merge conflict markers. Do not resolve them by hand; sync from Bezel to rewrite it.` : `${name} is not valid JSON. Sync from Bezel to rewrite it.`
531
+ };
532
+ }
533
+ if (!isRecord(parsed) || parsed["lockfileVersion"] !== LOCKFILE_VERSION || typeof parsed["projectId"] !== "string" || typeof parsed["version"] !== "string" || typeof parsed["revision"] !== "number" || !isRecord(parsed["tokens"])) {
534
+ return {
535
+ ok: false,
536
+ reason: "invalid-shape",
537
+ message: `${name} is not a version ${LOCKFILE_VERSION} Bezel lockfile. Sync from Bezel to rewrite it.`
538
+ };
539
+ }
540
+ return { ok: true, lockfile: parsed };
541
+ }
542
+
543
+ // src/patch-applied.ts
544
+ var MISSING = /* @__PURE__ */ Symbol("missing");
545
+ var decodeSegment = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
546
+ function valueAt(document, pointer) {
547
+ if (pointer === "") return document;
548
+ let node = document;
549
+ for (const raw of pointer.split("/").slice(1)) {
550
+ const segment = decodeSegment(raw);
551
+ if (Array.isArray(node)) {
552
+ const index = Number(segment);
553
+ if (!Number.isInteger(index) || index < 0 || index >= node.length) return MISSING;
554
+ node = node[index];
555
+ } else if (typeof node === "object" && node !== null && Object.prototype.hasOwnProperty.call(node, segment)) {
556
+ node = node[segment];
557
+ } else {
558
+ return MISSING;
559
+ }
560
+ }
561
+ return node;
562
+ }
563
+ function jsonEqual(a, b) {
564
+ if (a === b) return true;
565
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
566
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
567
+ if (Array.isArray(a) && Array.isArray(b)) {
568
+ return a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]));
569
+ }
570
+ const aKeys = Object.keys(a);
571
+ const bKeys = Object.keys(b);
572
+ if (aKeys.length !== bKeys.length) return false;
573
+ return aKeys.every(
574
+ (key) => Object.prototype.hasOwnProperty.call(b, key) && jsonEqual(a[key], b[key])
575
+ );
576
+ }
577
+ function isOperationApplied(document, operation) {
578
+ switch (operation.op) {
579
+ case "test":
580
+ return true;
581
+ case "add":
582
+ case "replace": {
583
+ const current = valueAt(document, operation.path);
584
+ return current !== MISSING && jsonEqual(current, operation.value);
585
+ }
586
+ case "remove":
587
+ return valueAt(document, operation.path) === MISSING;
588
+ case "copy": {
589
+ const target = valueAt(document, operation.path);
590
+ return target !== MISSING && jsonEqual(target, valueAt(document, operation.from ?? ""));
591
+ }
592
+ case "move":
593
+ return valueAt(document, operation.path) !== MISSING && (operation.from === void 0 || valueAt(document, operation.from) === MISSING);
594
+ default:
595
+ return false;
596
+ }
597
+ }
598
+ function unappliedOperations(document, operations) {
599
+ return operations.filter((operation) => operation.op !== "test" && !isOperationApplied(document, operation));
600
+ }
601
+ function isPatchApplied(document, operations) {
602
+ return unappliedOperations(document, operations).length === 0;
603
+ }
604
+
474
605
  // src/agent-skill.ts
475
606
  var AGENT_SKILL = {
476
607
  name: "bezel",
477
- description: "Use when the repo has bezel.json or design-tokens.json and the task touches design tokens, theme colors, spacing, typography, radii, CSS variables, dark mode, or files under the Bezel output folder (src/bezel by default). Edit design-tokens.json, never the generated variables.css / contexts.ts / fonts.ts, then run the tokens build. Also covers pulling the latest tokens from the Bezel app, pushing local token edits back to Bezel after a preview and confirmation, and using the Bezel MCP tools.",
608
+ description: "Use when the repo has bezel.json or design-tokens.json and the task touches design tokens, theme colors, spacing, typography, radii, CSS variables, dark mode, or files under the Bezel output folder (src/bezel by default). Edit design-tokens.json, never the generated variables.css / contexts.ts / fonts.ts, then run the tokens build. Also covers pulling the latest tokens from the Bezel app, pushing local token edits back to Bezel when the user asks, and using the Bezel MCP tools.",
478
609
  files: {
479
- "SKILL.md": '---\nname: bezel\ndescription: Use when the repo has bezel.json or design-tokens.json and the task touches design tokens, theme colors, spacing, typography, radii, CSS variables, dark mode, or files under the Bezel output folder (src/bezel by default). Edit design-tokens.json, never the generated variables.css / contexts.ts / fonts.ts, then run the tokens build. Also covers pulling the latest tokens from the Bezel app, pushing local token edits back to Bezel after a preview and confirmation, and using the Bezel MCP tools.\n---\n\n# Bezel in this repository\n\nBezel is a design-token platform. Designers maintain the tokens in the Bezel app; this repo holds an exported copy and generates CSS from it with `@bezel-labs/bezel-kit`.\n\n```\nBezel app (cloud, source of truth)\n -> design-tokens.json DTCG file at the repo root, exported from Bezel\n -> bezel build reads bezel.json for options and output paths\n -> variables.css one CSS scope per context (:root, .dark, .light, ...)\n contexts.ts, fonts.ts optional generated TypeScript modules\n```\n\nThe Bezel app stays the source of truth. Local edits to `design-tokens.json` reach Bezel only when they are pushed through the Bezel MCP, after a preview and the user\'s explicit yes (see "Pushing changes back to Bezel"); until then the next sync replaces them.\n\n## Hard rules\n\n1. Never edit a generated file. They start with `/* Generated by bezel \u2014 do not edit by hand. */` and live at the paths named in `bezel.json` (`variablesOutput`, `contextsOutput`, `fontsOutput`; default folder `src/bezel/`). `bezel build` overwrites them without asking and they are gitignored.\n2. To change a token value or add a variable, edit `design-tokens.json`, then rebuild. Never hand-write the CSS variable.\n3. After any change to `design-tokens.json` or `bezel.json`, run the tokens build: `npm run tokens` when that script exists, otherwise `npx bezel build` (use the repo\'s package manager runner). Confirm the outputs were rewritten before finishing.\n4. Only tokens with an `exportName` become CSS variables unless `bezel.json` sets `"includeAll": true`. Adding a token without an `exportName` produces no variable.\n5. Never pass `--force` to `bezel init`; it discards the existing `bezel.json`. `--project` and `--tokens-version` update their own keys without it.\n6. Local edits to `design-tokens.json` are not in Bezel until they are pushed, and a sync from Bezel overwrites them. Never silently sync over local edits: say so and offer to push them first. Pushing means `preview-design-tokens-push`, showing its `confirmationPrompt` word for word, then `push-design-tokens-file` only after the user says yes. Never push without that confirmation, and never push from a "sync" or "pull" request.\n\n## The tokens file\n\n`design-tokens.json` follows the W3C Design Tokens (DTCG) format. Every token is an object with a `$type` and one `$value` per context:\n\n```json\n"semantic": {\n "color": {\n "primary": {\n "$type": "color",\n "$root": { "$value": "{base.color.green.500}" },\n "dark": { "$value": { "colorSpace": "oklch", "components": [0.85, 0.16, 152] } },\n "$extensions": { "com.bezel.app": { "exportName": ["primary", "ring"] } }\n }\n }\n}\n```\n\n- Context keys (`$root`, `dark`, `light`, or whatever `bezel.json` `contexts` lists) sit inside the token. `$root` is the base; other contexts only need the values that differ.\n- `$value` is either a literal (DTCG color, dimension, font family, ...) or a reference like `{base.color.green.500}`. References are resolved to literal values in the generated CSS.\n- `$extensions["com.bezel.app"].exportName` is the list of CSS variable names the token emits. One token can emit several (`foreground`, `card-foreground`). An empty list means no variable.\n- Groups (`base`, `semantic`, `color`, ...) are plain nesting with no `$type`.\n\n## What to do for common requests\n\n| Request | Edit | Then |\n|---|---|---|\n| Change a color, size, radius, or font value | The token\'s `$value` in the right context key (`$root` for every mode, `dark` for dark mode only) | Rebuild |\n| A value should differ in dark mode | Add or edit the `dark` key on that token | Rebuild |\n| New CSS variable | Add a token with `$type`, `$root.$value`, and an `exportName` (or reference an existing token) | Rebuild |\n| Rename a CSS variable | Change the `exportName` entry; update every consumer of the old `--name` | Rebuild |\n| New theme or brand context | Add the context to `bezel.json` `contexts` (name -> selector) and add that key to the tokens that differ | Rebuild |\n| Change where files are generated | Edit `variablesOutput` / `contextsOutput` / `fontsOutput` in `bezel.json`; update the CSS import | Rebuild, delete the old outputs |\n| "Pull the latest tokens" / "sync from Bezel" | See the next section | Rebuild |\n| "Push my changes to Bezel" / save local token edits back | Nothing locally; follow "Pushing changes back to Bezel" | Write the returned `revision` to `bezel.json`; rebuild only if the file was re-synced |\n\nFind the token for an existing variable by searching `design-tokens.json` for its name inside an `exportName` array.\n\n## Pulling the latest tokens from Bezel\n\n`bezel.json` `projectId` and `version` (`"latest"` or a published semver) say which Bezel project and snapshot this repo tracks. `revision` records the project revision the file was last synced from or pushed to.\n\nWith the Bezel MCP connected: call `get-design-tokens-file` with that `projectId` and `version`, write the returned `content` string to `design-tokens.json` verbatim (no reformatting), set `"revision"` in `bezel.json` to the returned `revision`, then rebuild. The `sync-project` prompt walks through this, including linking a project when `projectId` is missing. Never pick a project or version yourself; ask when it is ambiguous.\n\nWithout the MCP: ask the user to download `design-tokens.json` from the project in the Bezel app and replace the file at the repo root, then rebuild.\n\nBefore overwriting a `design-tokens.json` that has local edits, stop and offer to push them first (next section) or confirm they should be discarded.\n\n## Pushing changes back to Bezel\n\nNeeds the Bezel MCP. Pushing saves this repo\'s `design-tokens.json` as the project\'s working tokens (`latest`), so the Bezel app stays the source of truth and everyone who syncs gets the change. Publishing a version still happens in the Bezel app.\n\n1. Read `projectId`, `version`, and `revision` from `bezel.json`. If `version` is a semver, tell the user the push updates the working project, not that pinned release.\n2. Call `preview-design-tokens-push` with the exact file text as `content`, `revision` as `baseRevision`, and `version` as `trackedVersion`. It saves nothing.\n3. `invalid` or `blocked`: report the errors and stop (`blocked` is a plan limit on groups, themes, or descriptions). `no-changes`: say the project already matches. Theme keys the file uses that the project does not have yet are added to the project by the push, within the plan\'s theme limit; the preview lists them as `addedContexts`.\n4. `ready`: show `confirmationPrompt` to the user word for word and wait. Do not push on silence, a question, or a different request.\n5. After an explicit yes, call `push-design-tokens-file` with the same `content` and `expectedRevision` = the preview\'s `currentRevision`. `conflict` means Bezel changed in between: go back to step 2.\n6. Write the returned `revision` to `bezel.json`. If the result says `normalized`, sync once (`get-design-tokens-file`, write verbatim, rebuild) so the local file matches Bezel byte for byte.\n\nThe `push-project` prompt walks through this.\n\n## With the Bezel MCP connected\n\nPrefer small, targeted calls over reading the whole tokens file:\n\n- `get-project-manifest` first: groups, counts, types, contexts, no values.\n- `query-tokens` to find tokens by group, type, name, or `exportName`; `get-token-by-path` for one token with every context value.\n- `get-token-bundle` for a curated set per task (`theming-setup`, `button`, `card`, `form`, ...).\n- `export-tokens` and `get-framework-overrides` to generate CSS, JS/TS objects, or Tailwind / shadcn / Mantine config from tokens.\n- `contrast-check`, `color-convert`, `color-ramp`, `unit-convert` for deterministic math instead of estimating.\n- `design-review` to check a component description against the tokens.\n\nSee `references/mcp-tools.md` for the full list and `references/bezel-json.md` for every config field.\n\n## Setting up a repo that is not on Bezel yet\n\nRun the `setup-project` tool (or the `/mcp__bezel__setup-project` prompt) and follow it; it installs `@bezel-labs/bezel-kit`, writes `bezel.json`, fetches the tokens, builds, and wires the CSS import. Do not improvise the steps.\n',
480
- "references/bezel-json.md": '# bezel.json reference\n\n`bezel.json` lives at the repo root (or the working directory `bezel build` runs in). `bezel build` loads it automatically; `bezel init` writes it. The tokens input is always `design-tokens.json` in that same directory and is not configurable.\n\n| Field | Default | Used by | Meaning |\n|---|---|---|---|\n| `projectId` | none | MCP | UUID of the Bezel project this repo tracks. Set with `npx bezel init --project <uuid>`. |\n| `version` | `"latest"` | MCP | Which tokens snapshot to fetch: `"latest"` or a published semver such as `"1.4.0"`. Set with `--tokens-version`. |\n| `revision` | none | MCP | Project revision the file was last synced from or pushed to. Written by the MCP after a sync or push, never by hand; lets a push preview warn when Bezel changed since. `bezel init --project` drops it when the project changes. |\n| `variablesOutput` | `"src/bezel/variables.css"` | build | Generated CSS file. Import this from the app entry. |\n| `contextsOutput` | none | build | When set, writes a TypeScript module exporting `CONTEXTS` (the context names). |\n| `fontsOutput` | none | build | When set, writes a TypeScript module exporting `FONTS` (web fonts derived from the tokens). |\n| `contexts` | `{ "$root": ":root", "dark": ".dark", "light": ".light" }` | build | Context name -> CSS selector. The first entry is the base context and is emitted in full; the rest are override-only blocks. |\n| `colorFormat` | `"oklch"` | build | `"oklch"` or `"hex"`. |\n| `dimensionUnit` | `"preserve"` | build | `"preserve"` keeps authored units; `"rem"` converts `px` to `rem`. |\n| `nameExtension` | `"com.bezel.app"` | build | The `$extensions` key that holds `exportName`. Only change for files exported before the 0.3.0 rename. |\n| `includeAll` | `false` | build | Also emit a variable for every token without an `exportName`, named by its kebab-cased path (`--base-color-primary-500`). |\n| `write` | `true` | build | `false` returns the CSS without writing files (programmatic use). |\n| `gitignore` | `true` | build | Maintain a `# bezel:start` ... `# bezel:end` block in `.gitignore` listing the generated outputs. |\n| `gitignorePath` | `".gitignore"` | build | Which `.gitignore` to manage. |\n| `cwd` | process cwd | build | Base directory paths resolve against. |\n\n`projectId`, `version`, and `revision` are ignored by `bezel build`; everything else is ignored by the MCP.\n\n## CLI\n\n```\nbezel init [--project <uuid>] [--tokens-version <v>] [--dir <path>] ... create or update bezel.json\nbezel build [--stdout] [--no-gitignore] ... generate the outputs (default command)\nbezel install-mcp [--client <name>] connect an AI coding tool to the Bezel MCP\nbezel install-skills [--client <name>] [--no-agents-md] install this skill into the repo\n```\n\n`bezel init` on an existing `bezel.json` with `--project` or `--tokens-version` updates only those keys. Any other re-run leaves the file alone unless `--force` is passed, which agents must not do.\n',
481
- "references/mcp-tools.md": "# Bezel MCP quick reference\n\nRemote server at `https://mcp.bezel.new/mcp` (Streamable HTTP, OAuth). The server returns data and instructions; the coding agent performs every local file edit and command. Project-scoped tools take the `projectId` from `bezel.json` or from `find-project`.\n\n## Guided workflows\n\n| Tool / prompt | Use |\n|---|---|\n| `setup-project` (tool and prompt) | Resumable setup: install bezel-kit, link a project, write `bezel.json`, fetch tokens, build, wire the CSS import, optional Crystal live preview. |\n| `sync-project` (prompt) | Refresh `design-tokens.json` from the linked project and version, record the revision, then rebuild. Offers to push local edits first instead of overwriting them. |\n| `push-project` (prompt) | Preview, confirm with the user, and push the repo's `design-tokens.json` to the linked project as its working tokens; records the new revision. |\n| `safe-usage-guide` (prompt) | Context-budget rules: manifest first, targeted queries, cite token paths. |\n| `manifest-first-workflow`, `context-resolution` (prompts) | Recommended reading order and how contexts resolve. |\n| `get-agent-guide` (tool) | Returns this skill's text when the repo has no local copy. |\n\n## Discovery\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `find-project` | `query?` | All owned projects (name + id), or one project resolved from a name or UUID. |\n| `get-project-manifest` | `projectId` | Groups, token counts, types, contexts. No values. Call this first. |\n\n## Repo sync\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `get-design-tokens-file` | `projectId`, `version?` | The exact `design-tokens.json` content to write to disk, plus project name, version, and `revision` (store it in `bezel.json`). Unknown version -> list of available versions. |\n| `preview-design-tokens-push` | `projectId`, `content`, `baseRevision?`, `trackedVersion?` | Diff of the file against the project's working tokens, validation and plan-limit problems, the themes the file would add (`addedContexts`), a `stale` flag when Bezel changed since the last sync, and a `confirmationPrompt` to show the user verbatim. Saves nothing. |\n| `push-design-tokens-file` | `projectId`, `content`, `expectedRevision` | Saves the file as the project's working tokens, only when the project is still at `expectedRevision` (else `conflict`). Call only after the user confirms the preview. Returns the new `revision`. |\n\n## Reading tokens\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `query-tokens` | `projectId`, `groupPath?`, `tokenType?`, `search?`, `exportName?`, `contextKey?`, `resolveAliases?` | Filtered tokens. |\n| `get-token-by-path` | `projectId`, `tokenPath`, `contextKey?`, `resolveAliases?` | One token with every context value and alias detail. |\n| `get-token-bundle` | `projectId`, `intent` | Curated set: `theming-setup`, `button`, `card`, `input`, `form`, `auth-page`, `dashboard-shell`. |\n| `get-project-contexts` | `projectId` | Context groups and values (theme modes, platforms, brands). |\n| `resolve-context` | `projectId`, `contextGroup`, `contextValue` | Canonical context value or a structured error. |\n\n## Generating code\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `export-tokens` | `projectId`, `format` (`css-variables`, `js-object`, `ts-object`), filters, `prefix?`, `includeAll?` | Generated code with aliases resolved. |\n| `get-framework-overrides` | `projectId`, `framework` (`tailwind`, `shadcn`, `mantine`), `version?`, filters | Framework config derived from the tokens. |\n\n## Color and unit math (deterministic)\n\n| Tool | Parameters |\n|---|---|\n| `contrast-check` | `foreground`, `background` -> WCAG ratio, grade, recommendations |\n| `color-convert` | `color`, `targetFormat`, `manipulation?`, `mixColor?` |\n| `color-ramp` | `baseColor`, `steps`, `endColor?`, `colorSpace?` |\n| `unit-convert` | `value`, `fromUnit`, `toUnit`, `rootFontSize?`, `parentFontSize?` |\n\n## Review and history\n\n| Tool | Parameters |\n|---|---|\n| `design-review` | `projectId`, `componentDescription`, `tokenPathsUsed?`, `contextKey?` |\n| `get-chat-history` | `projectId` |\n| `search-chat-history` | `projectId`, `query` |\n\n## Resources\n\n- `bezel://projects`: your projects with ids and names.\n- `bezel://agent-guide`: this skill's text.\n"
610
+ "SKILL.md": '---\nname: bezel\ndescription: Use when the repo has bezel.json or design-tokens.json and the task touches design tokens, theme colors, spacing, typography, radii, CSS variables, dark mode, or files under the Bezel output folder (src/bezel by default). Edit design-tokens.json, never the generated variables.css / contexts.ts / fonts.ts, then run the tokens build. Also covers pulling the latest tokens from the Bezel app, pushing local token edits back to Bezel when the user asks, and using the Bezel MCP tools.\n---\n\n# Bezel in this repository\n\nBezel is a design-token platform. Designers maintain the tokens in the Bezel app; this repo holds an exported copy and generates CSS from it with `@bezel-labs/bezel-kit`.\n\n```\nBezel app (cloud, source of truth)\n -> design-tokens.json DTCG file at the repo root, exported from Bezel\n design-tokens-lock.json what was last synced or pushed (tokens + revision); commit it\n -> bezel build reads bezel.json for options and output paths\n -> variables.css one CSS scope per context (:root, .dark, .light, ...)\n contexts.ts, fonts.ts optional generated TypeScript modules\n```\n\nThe Bezel app stays the source of truth. Local edits to `design-tokens.json` reach Bezel only when the user asks to push them through the Bezel MCP (see "Pushing changes back to Bezel").\n\n## Hard rules\n\n1. Never edit a generated file. They start with `/* Generated by bezel \u2014 do not edit by hand. */` and live at the paths named in `bezel.json` (`variablesOutput`, `contextsOutput`, `fontsOutput`; default folder `src/bezel/`). `bezel build` overwrites them without asking and they are gitignored.\n2. To change a token value or add a variable, edit `design-tokens.json`, then rebuild. Never hand-write the CSS variable.\n3. After any change to `design-tokens.json` or `bezel.json`, run the tokens build: `npm run tokens` when that script exists, otherwise `npx bezel build` (use the repo\'s package manager runner). Confirm the outputs were rewritten before finishing.\n4. Only tokens with an `exportName` become CSS variables unless `bezel.json` sets `"includeAll": true`. Adding a token without an `exportName` produces no variable.\n5. Never pass `--force` to `bezel init`; it discards the existing `bezel.json`. `--project` and `--tokens-version` update their own keys without it.\n6. Local edits to `design-tokens.json` are not in Bezel until they are pushed. `npx bezel diff` lists them. Never sync over them silently: offer to push them first. Pushing means `npx bezel diff --json`, then `push-design-tokens` with its operations, then a sync. Push only when the user asks to push, never from a "sync" or "pull" request. When Bezel changed since the last sync, the push returns `needs-confirmation`: show its `confirmationPrompt` word for word and pass `confirmed: true` only after the user says yes.\n7. Never write or edit `design-tokens-lock.json`, and never write a synced `design-tokens.json` from MCP output yourself. Only `bezel sync` writes them, after every sync and every push, so the two files always agree. Commit both files together.\n\n## The tokens file\n\n`design-tokens.json` follows the W3C Design Tokens (DTCG) format. Every token is an object with a `$type` and one `$value` per context:\n\n```json\n"semantic": {\n "color": {\n "primary": {\n "$type": "color",\n "$root": { "$value": "{base.color.green.500}" },\n "dark": { "$value": { "colorSpace": "oklch", "components": [0.85, 0.16, 152] } },\n "$extensions": { "com.bezel.app": { "exportName": ["primary", "ring"] } }\n }\n }\n}\n```\n\n- Context keys (`$root`, `dark`, `light`, or whatever `bezel.json` `contexts` lists) sit inside the token. `$root` is the base; other contexts only need the values that differ.\n- `$value` is either a literal (DTCG color, dimension, font family, ...) or a reference like `{base.color.green.500}`. References are resolved to literal values in the generated CSS.\n- `$extensions["com.bezel.app"].exportName` is the list of CSS variable names the token emits. One token can emit several (`foreground`, `card-foreground`). An empty list means no variable.\n- Groups (`base`, `semantic`, `color`, ...) are plain nesting with no `$type`.\n\n## What to do for common requests\n\n| Request | Edit | Then |\n|---|---|---|\n| Change a color, size, radius, or font value | The token\'s `$value` in the right context key (`$root` for every mode, `dark` for dark mode only) | Rebuild |\n| A value should differ in dark mode | Add or edit the `dark` key on that token | Rebuild |\n| New CSS variable | Add a token with `$type`, `$root.$value`, and an `exportName` (or reference an existing token) | Rebuild |\n| Rename a CSS variable | Change the `exportName` entry; update every consumer of the old `--name` | Rebuild |\n| New theme or brand context | Add the context to `bezel.json` `contexts` (name -> selector) and add that key to the tokens that differ | Rebuild |\n| Change where files are generated | Edit `variablesOutput` / `contextsOutput` / `fontsOutput` in `bezel.json`; update the CSS import | Rebuild, delete the old outputs |\n| "Pull the latest tokens" / "sync from Bezel" | See the next section | `bezel sync` rebuilds |\n| "Push my changes to Bezel" / save local token edits back | Nothing by hand; follow "Pushing changes back to Bezel" | Sync, which updates the lockfile |\n\nFind the token for an existing variable by searching `design-tokens.json` for its name inside an `exportName` array.\n\n## Pulling the latest tokens from Bezel\n\n`bezel.json` `projectId` and `version` (`"latest"` or a published semver) say which Bezel project and snapshot this repo tracks. `design-tokens-lock.json` records the tokens and project revision this repo last synced or pushed, like `package-lock.json` next to `package.json`. Only `bezel sync` writes it.\n\nWith the Bezel MCP connected:\n\n1. Run `npx bezel diff`. If it lists local edits, stop and offer to push them first (next section). A lockfile problem it reports is fixed by this sync.\n2. Call `get-design-tokens-file` with that `projectId` and `version`. Write the returned `lockfileContent` exactly as returned to `.bezel/sync.json`.\n3. Run `npx bezel sync`. It checks the staged file, writes `design-tokens-lock.json` and then `design-tokens.json`, deletes the staged file, and rebuilds.\n - Exit code 2 means `design-tokens.json` has edits Bezel does not have. Show the message and offer to push them. Use `npx bezel sync --discard-local-edits` only when the user says to drop them.\n - `unknown command "sync"` means the installed `@bezel-labs/bezel-kit` is too old. Update it first.\n\nThe `sync-project` prompt walks through this, including linking a project when `projectId` is missing. Never pick a project or version yourself; ask when it is ambiguous.\n\nWithout the MCP: ask the user to download `design-tokens.json` from the project in the Bezel app and replace the file at the repo root, then rebuild. Pushing later needs a lockfile, so sync through the MCP when it becomes available.\n\n## Pushing changes back to Bezel\n\nNeeds the Bezel MCP. A push sends only your edits, as JSON Patch operations, the same way the Bezel app saves. Bezel applies them to the project\'s working tokens (`latest`) and keeps changes others made in the meantime. Publishing a version still happens in the Bezel app.\n\n1. Run `npx bezel diff --json`. `"ok": false` prints what to do (every lockfile problem is fixed by a sync). `"operations": []` means nothing to push.\n2. If `bezel.json` `version` is a semver, tell the user the push updates the working project, not that pinned release.\n3. Call `push-design-tokens` with `projectId`, the printed `operations` and `baseRevision` unchanged, and `version` as `trackedVersion`. If Bezel is still at `baseRevision`, it saves straight away; the user\'s request to push is the go-ahead.\n4. `needs-confirmation`: Bezel changed since the last sync, so nothing was saved. Show `confirmationPrompt` to the user word for word and wait. Only after an explicit yes, call `push-design-tokens` again with the same arguments and `confirmed: true`. Silence, a question, or a different request means no push.\n5. `invalid` or `blocked`: report and stop (`blocked` is a plan limit). `conflict`: the listed tokens changed in Bezel too; follow `nextStep`. `no-changes` with `alreadyApplied`: an earlier push saved these edits but the sync after it did not run; sync now. Themes the edits use that the project lacks are added by the push (`addedContexts`).\n6. A push is not finished until the repo is synced. Sync as in the previous section, steps 2 and 3: `get-design-tokens-file`, write `lockfileContent` to `.bezel/sync.json`, run `npx bezel sync`. Your edits are already in Bezel, so the sync keeps them, pulls in anything others changed, and moves the lockfile to the new revision. Then tell the user to commit `design-tokens.json` and `design-tokens-lock.json` together.\n\n`preview-design-tokens-push` takes the same arguments and shows what a push would change without saving, for when the user asks first. The `push-project` prompt walks through this.\n\n## With the Bezel MCP connected\n\nPrefer small, targeted calls over reading the whole tokens file:\n\n- `get-project-manifest` first: groups, counts, types, contexts, no values.\n- `query-tokens` to find tokens by group, type, name, or `exportName`; `get-token-by-path` for one token with every context value.\n- `get-token-bundle` for a curated set per task (`theming-setup`, `button`, `card`, `form`, ...).\n- `export-tokens` and `get-framework-overrides` to generate CSS, JS/TS objects, or Tailwind / shadcn / Mantine config from tokens.\n- `contrast-check`, `color-convert`, `color-ramp`, `unit-convert` for deterministic math instead of estimating.\n- `design-review` to check a component description against the tokens.\n\nSee `references/mcp-tools.md` for the full list and `references/bezel-json.md` for every config field.\n\n## Setting up a repo that is not on Bezel yet\n\nRun the `setup-project` tool (or the `/mcp__bezel__setup-project` prompt) and follow it; it installs `@bezel-labs/bezel-kit`, writes `bezel.json`, fetches the tokens, builds, and wires the CSS import. Do not improvise the steps.\n',
611
+ "references/bezel-json.md": '# bezel.json reference\n\n`bezel.json` lives at the repo root (or the working directory `bezel build` runs in). `bezel build` loads it automatically; `bezel init` writes it. The tokens input is always `design-tokens.json` in that same directory and is not configurable.\n\n| Field | Default | Used by | Meaning |\n|---|---|---|---|\n| `projectId` | none | MCP | UUID of the Bezel project this repo tracks. Set with `npx bezel init --project <uuid>`. |\n| `version` | `"latest"` | MCP | Which tokens snapshot to fetch: `"latest"` or a published semver such as `"1.4.0"`. Set with `--tokens-version`. |\n| `variablesOutput` | `"src/bezel/variables.css"` | build | Generated CSS file. Import this from the app entry. |\n| `contextsOutput` | none | build | When set, writes a TypeScript module exporting `CONTEXTS` (the context names). |\n| `fontsOutput` | none | build | When set, writes a TypeScript module exporting `FONTS` (web fonts derived from the tokens). |\n| `contexts` | `{ "$root": ":root", "dark": ".dark", "light": ".light" }` | build | Context name -> CSS selector. The first entry is the base context and is emitted in full; the rest are override-only blocks. |\n| `colorFormat` | `"oklch"` | build | `"oklch"` or `"hex"`. |\n| `dimensionUnit` | `"preserve"` | build | `"preserve"` keeps authored units; `"rem"` converts `px` to `rem`. |\n| `nameExtension` | `"com.bezel.app"` | build | The `$extensions` key that holds `exportName`. Only change for files exported before the 0.3.0 rename. |\n| `includeAll` | `false` | build | Also emit a variable for every token without an `exportName`, named by its kebab-cased path (`--base-color-primary-500`). |\n| `write` | `true` | build | `false` returns the CSS without writing files (programmatic use). |\n| `gitignore` | `true` | build | Maintain a `# bezel:start` ... `# bezel:end` block in `.gitignore` listing the generated outputs. |\n| `gitignorePath` | `".gitignore"` | build | Which `.gitignore` to manage. |\n| `cwd` | process cwd | build | Base directory paths resolve against. |\n\n`projectId` and `version` are ignored by `bezel build`; everything else is ignored by the MCP. The synced revision lives in `design-tokens-lock.json`, not here.\n\n## design-tokens-lock.json\n\nCommitted next to `design-tokens.json`, like `package-lock.json` next to `package.json`. It records the tokens and project revision this repo last synced or pushed: `lockfileVersion`, `projectId`, `version`, `revision`, and `tokens`. `bezel diff` compares `design-tokens.json` against it to find local edits. Only `bezel sync` writes it, after every sync and every push; never edit it. `bezel init --project` deletes a lockfile that belongs to a different project.\n\n## CLI\n\n```\nbezel init [--project <uuid>] [--tokens-version <v>] [--dir <path>] ... create or update bezel.json\nbezel build [--stdout] [--no-gitignore] ... generate the outputs (default command)\nbezel install-mcp [--client <name>] connect an AI coding tool to the Bezel MCP\nbezel install-skills [--client <name>] [--no-agents-md] install this skill into the repo\nbezel diff [--json] local edits vs design-tokens-lock.json (--json: JSON Patch operations for a push)\nbezel sync [--discard-local-edits] apply .bezel/sync.json: write the lockfile and design-tokens.json, then build\n```\n\n`bezel sync` exits with code 2 when `design-tokens.json` has edits Bezel does not have; other problems exit with 1.\n\n`bezel init` on an existing `bezel.json` with `--project` or `--tokens-version` updates only those keys. Any other re-run leaves the file alone unless `--force` is passed, which agents must not do.\n',
612
+ "references/mcp-tools.md": "# Bezel MCP quick reference\n\nRemote server at `https://mcp.bezel.new/mcp` (Streamable HTTP, OAuth). The server returns data and instructions; the coding agent performs every local file edit and command. Project-scoped tools take the `projectId` from `bezel.json` or from `find-project`.\n\n## Guided workflows\n\n| Tool / prompt | Use |\n|---|---|\n| `setup-project` (tool and prompt) | Resumable setup: install bezel-kit, link a project, write `bezel.json`, fetch tokens, build, wire the CSS import, optional Crystal live preview. |\n| `sync-project` (prompt) | Refresh `design-tokens.json` and `design-tokens-lock.json` from the linked project and version through `bezel sync`. Offers to push local edits first instead of overwriting them. |\n| `push-project` (prompt) | Diff and push the repo's token edits to the linked project (asking the user first only when Bezel changed), then sync so `design-tokens-lock.json` moves to the new revision. |\n| `safe-usage-guide` (prompt) | Context-budget rules: manifest first, targeted queries, cite token paths. |\n| `manifest-first-workflow`, `context-resolution` (prompts) | Recommended reading order and how contexts resolve. |\n| `get-agent-guide` (tool) | Returns this skill's text when the repo has no local copy. |\n\n## Discovery\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `find-project` | `query?` | All owned projects (name + id), or one project resolved from a name or UUID. |\n| `get-project-manifest` | `projectId` | Groups, token counts, types, contexts. No values. Call this first. |\n\n## Repo sync\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `get-design-tokens-file` | `projectId`, `version?` | `lockfileContent`: the full `design-tokens-lock.json` text (tokens + `revision`). Write it to `.bezel/sync.json` and run `npx bezel sync`. Unknown version -> list of available versions. |\n| `preview-design-tokens-push` | `projectId`, `operations`, `baseRevision?`, `trackedVersion?` | Checks the edits from `npx bezel diff --json` against the working tokens: plan-limit problems, `conflict` (tokens edited here and in Bezel), themes the edits add (`addedContexts`), `behind` when Bezel moved on (those changes are kept), and a `confirmationPrompt`. Saves nothing; optional, for when the user wants to see a push first. |\n| `push-design-tokens` | `projectId`, `operations`, `baseRevision?`, `trackedVersion?`, `confirmed?` | Saves the edits as a new revision when Bezel is still at `baseRevision`. If Bezel changed, saves nothing and returns `needs-confirmation` with a `confirmationPrompt`; call again with `confirmed: true` only after the user says yes. Returns the new `revision`. Sync right after it so the lockfile moves to that revision. |\n\n## Reading tokens\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `query-tokens` | `projectId`, `groupPath?`, `tokenType?`, `search?`, `exportName?`, `contextKey?`, `resolveAliases?` | Filtered tokens. |\n| `get-token-by-path` | `projectId`, `tokenPath`, `contextKey?`, `resolveAliases?` | One token with every context value and alias detail. |\n| `get-token-bundle` | `projectId`, `intent` | Curated set: `theming-setup`, `button`, `card`, `input`, `form`, `auth-page`, `dashboard-shell`. |\n| `get-project-contexts` | `projectId` | Context groups and values (theme modes, platforms, brands). |\n| `resolve-context` | `projectId`, `contextGroup`, `contextValue` | Canonical context value or a structured error. |\n\n## Generating code\n\n| Tool | Parameters | Returns |\n|---|---|---|\n| `export-tokens` | `projectId`, `format` (`css-variables`, `js-object`, `ts-object`), filters, `prefix?`, `includeAll?` | Generated code with aliases resolved. |\n| `get-framework-overrides` | `projectId`, `framework` (`tailwind`, `shadcn`, `mantine`), `version?`, filters | Framework config derived from the tokens. |\n\n## Color and unit math (deterministic)\n\n| Tool | Parameters |\n|---|---|\n| `contrast-check` | `foreground`, `background` -> WCAG ratio, grade, recommendations |\n| `color-convert` | `color`, `targetFormat`, `manipulation?`, `mixColor?` |\n| `color-ramp` | `baseColor`, `steps`, `endColor?`, `colorSpace?` |\n| `unit-convert` | `value`, `fromUnit`, `toUnit`, `rootFontSize?`, `parentFontSize?` |\n\n## Review and history\n\n| Tool | Parameters |\n|---|---|\n| `design-review` | `projectId`, `componentDescription`, `tokenPathsUsed?`, `contextKey?` |\n| `get-chat-history` | `projectId` |\n| `search-chat-history` | `projectId`, `query` |\n\n## Resources\n\n- `bezel://projects`: your projects with ids and names.\n- `bezel://agent-guide`: this skill's text.\n"
482
613
  },
483
- agentsMdBlock: '## Bezel design tokens\n\n- `design-tokens.json` at the repo root is the source for every design token. Edit it to change a color, size, font, or radius, or to add a CSS variable (add an `exportName` under `$extensions["com.bezel.app"]`).\n- Files under the Bezel output folder (`variablesOutput`, `contextsOutput`, `fontsOutput` in `bezel.json`; `src/bezel/` by default) are generated. Never edit them; they are overwritten on every build.\n- After changing `design-tokens.json` or `bezel.json`, run `npm run tokens` (or `npx bezel build`) and check the outputs were rewritten.\n- Dark mode and other contexts are keys inside each token (`$root`, `dark`, `light`). Add a value under the context key instead of writing a CSS override.\n- The Bezel app is the source of truth. Local edits to `design-tokens.json` are not in Bezel until pushed, and the next sync (`get-design-tokens-file` via the Bezel MCP, or a download from the app) replaces them. Before syncing over local edits, or when asked to push, call `preview-design-tokens-push`, show its confirmation prompt word for word, and call `push-design-tokens-file` only after the user says yes.\n- Never run `bezel init --force`; it discards the existing `bezel.json`. Use `--project` or `--tokens-version` to update a single key.\n- Full guidance: the `bezel` skill in `.claude/skills/bezel/SKILL.md` or `.agents/skills/bezel/SKILL.md`.',
484
- summary: 'Use when the repo has bezel.json or design-tokens.json and the task touches design tokens, theme colors, spacing, typography, radii, CSS variables, dark mode, or files under the Bezel output folder (src/bezel by default). Edit design-tokens.json, never the generated variables.css / contexts.ts / fonts.ts, then run the tokens build. Also covers pulling the latest tokens from the Bezel app, pushing local token edits back to Bezel after a preview and confirmation, and using the Bezel MCP tools.\n\n## Hard rules\n\n1. Never edit a generated file. They start with `/* Generated by bezel \u2014 do not edit by hand. */` and live at the paths named in `bezel.json` (`variablesOutput`, `contextsOutput`, `fontsOutput`; default folder `src/bezel/`). `bezel build` overwrites them without asking and they are gitignored.\n2. To change a token value or add a variable, edit `design-tokens.json`, then rebuild. Never hand-write the CSS variable.\n3. After any change to `design-tokens.json` or `bezel.json`, run the tokens build: `npm run tokens` when that script exists, otherwise `npx bezel build` (use the repo\'s package manager runner). Confirm the outputs were rewritten before finishing.\n4. Only tokens with an `exportName` become CSS variables unless `bezel.json` sets `"includeAll": true`. Adding a token without an `exportName` produces no variable.\n5. Never pass `--force` to `bezel init`; it discards the existing `bezel.json`. `--project` and `--tokens-version` update their own keys without it.\n6. Local edits to `design-tokens.json` are not in Bezel until they are pushed, and a sync from Bezel overwrites them. Never silently sync over local edits: say so and offer to push them first. Pushing means `preview-design-tokens-push`, showing its `confirmationPrompt` word for word, then `push-design-tokens-file` only after the user says yes. Never push without that confirmation, and never push from a "sync" or "pull" request.'
614
+ agentsMdBlock: '## Bezel design tokens\n\n- `design-tokens.json` at the repo root is the source for every design token. Edit it to change a color, size, font, or radius, or to add a CSS variable (add an `exportName` under `$extensions["com.bezel.app"]`).\n- Files under the Bezel output folder (`variablesOutput`, `contextsOutput`, `fontsOutput` in `bezel.json`; `src/bezel/` by default) are generated. Never edit them; they are overwritten on every build.\n- After changing `design-tokens.json` or `bezel.json`, run `npm run tokens` (or `npx bezel build`) and check the outputs were rewritten.\n- Dark mode and other contexts are keys inside each token (`$root`, `dark`, `light`). Add a value under the context key instead of writing a CSS override.\n- The Bezel app is the source of truth. `design-tokens-lock.json` records what was last synced or pushed; never edit it, and commit it together with `design-tokens.json`. `npx bezel diff` lists local edits that are not in Bezel yet.\n- Sync through the Bezel MCP: write `get-design-tokens-file`\'s `lockfileContent` to `.bezel/sync.json`, then run `npx bezel sync` (it writes both files and refuses to drop unpushed edits). To push (only when asked), run `npx bezel diff --json`, call `push-design-tokens` with its operations, then sync to update the lockfile. If it returns `needs-confirmation` (Bezel changed meanwhile), show the confirmation prompt word for word and call again with `confirmed: true` only after the user says yes.\n- Never run `bezel init --force`; it discards the existing `bezel.json`. Use `--project` or `--tokens-version` to update a single key.\n- Full guidance: the `bezel` skill in `.claude/skills/bezel/SKILL.md` or `.agents/skills/bezel/SKILL.md`.',
615
+ summary: 'Use when the repo has bezel.json or design-tokens.json and the task touches design tokens, theme colors, spacing, typography, radii, CSS variables, dark mode, or files under the Bezel output folder (src/bezel by default). Edit design-tokens.json, never the generated variables.css / contexts.ts / fonts.ts, then run the tokens build. Also covers pulling the latest tokens from the Bezel app, pushing local token edits back to Bezel when the user asks, and using the Bezel MCP tools.\n\n## Hard rules\n\n1. Never edit a generated file. They start with `/* Generated by bezel \u2014 do not edit by hand. */` and live at the paths named in `bezel.json` (`variablesOutput`, `contextsOutput`, `fontsOutput`; default folder `src/bezel/`). `bezel build` overwrites them without asking and they are gitignored.\n2. To change a token value or add a variable, edit `design-tokens.json`, then rebuild. Never hand-write the CSS variable.\n3. After any change to `design-tokens.json` or `bezel.json`, run the tokens build: `npm run tokens` when that script exists, otherwise `npx bezel build` (use the repo\'s package manager runner). Confirm the outputs were rewritten before finishing.\n4. Only tokens with an `exportName` become CSS variables unless `bezel.json` sets `"includeAll": true`. Adding a token without an `exportName` produces no variable.\n5. Never pass `--force` to `bezel init`; it discards the existing `bezel.json`. `--project` and `--tokens-version` update their own keys without it.\n6. Local edits to `design-tokens.json` are not in Bezel until they are pushed. `npx bezel diff` lists them. Never sync over them silently: offer to push them first. Pushing means `npx bezel diff --json`, then `push-design-tokens` with its operations, then a sync. Push only when the user asks to push, never from a "sync" or "pull" request. When Bezel changed since the last sync, the push returns `needs-confirmation`: show its `confirmationPrompt` word for word and pass `confirmed: true` only after the user says yes.\n7. Never write or edit `design-tokens-lock.json`, and never write a synced `design-tokens.json` from MCP output yourself. Only `bezel sync` writes them, after every sync and every push, so the two files always agree. Commit both files together.'
485
616
  };
486
617
 
487
618
  // src/index.ts
@@ -490,9 +621,206 @@ function tokensToCss(tokens, options = {}) {
490
621
  }
491
622
 
492
623
  // src/init.ts
624
+ var import_node_fs2 = require("fs");
625
+ var import_promises2 = require("fs/promises");
626
+ var import_node_path3 = require("path");
627
+
628
+ // src/tokens-sync.ts
493
629
  var import_node_fs = require("fs");
494
630
  var import_promises = require("fs/promises");
495
631
  var import_node_path2 = require("path");
632
+ var import_fast_json_patch = __toESM(require("fast-json-patch"), 1);
633
+ var { compare } = import_fast_json_patch.default;
634
+ var SYNC_HINT = 'Sync from Bezel (ask your agent to "sync my Bezel tokens").';
635
+ async function readLink(cwd) {
636
+ const path = (0, import_node_path2.resolve)(cwd, DEFAULT_CONFIG_FILE);
637
+ if (!(0, import_node_fs.existsSync)(path)) {
638
+ return { ok: false, reason: "no-config", message: `No ${DEFAULT_CONFIG_FILE} here. Run "bezel init --project <uuid>" first.` };
639
+ }
640
+ let config;
641
+ try {
642
+ config = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
643
+ } catch {
644
+ return { ok: false, reason: "no-config", message: `${DEFAULT_CONFIG_FILE} is not valid JSON.` };
645
+ }
646
+ if (typeof config.projectId !== "string" || config.projectId === "") {
647
+ return {
648
+ ok: false,
649
+ reason: "no-project",
650
+ message: `${DEFAULT_CONFIG_FILE} has no projectId. Link the repo with "bezel init --project <uuid>".`
651
+ };
652
+ }
653
+ const version = typeof config.version === "string" && config.version !== "" ? config.version : "latest";
654
+ return { ok: true, link: { projectId: config.projectId, version } };
655
+ }
656
+ async function readTokensFile(cwd) {
657
+ const path = (0, import_node_path2.resolve)(cwd, DEFAULT_INPUT);
658
+ if (!(0, import_node_fs.existsSync)(path)) {
659
+ return { ok: false, reason: "no-tokens-file", message: `No ${DEFAULT_INPUT} here. ${SYNC_HINT}` };
660
+ }
661
+ try {
662
+ const parsed = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
663
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");
664
+ return { ok: true, tokens: parsed };
665
+ } catch {
666
+ return {
667
+ ok: false,
668
+ reason: "tokens-file-invalid",
669
+ message: `${DEFAULT_INPUT} is not a JSON object. Fix the file (or sync from Bezel to replace it).`
670
+ };
671
+ }
672
+ }
673
+ async function readCurrentLockfile(cwd) {
674
+ const path = (0, import_node_path2.resolve)(cwd, LOCKFILE_NAME);
675
+ if (!(0, import_node_fs.existsSync)(path)) return { ok: true, lockfile: null };
676
+ const parsed = parseLockfile(await (0, import_promises.readFile)(path, "utf8"));
677
+ if (parsed.ok === false) return { ok: false, reason: "lockfile-invalid", message: parsed.message };
678
+ return { ok: true, lockfile: parsed.lockfile };
679
+ }
680
+ function checkLockMatchesLink(lockfile, link, name) {
681
+ if (lockfile.projectId !== link.projectId) {
682
+ return {
683
+ ok: false,
684
+ reason: "project-mismatch",
685
+ message: `${name} is for project ${lockfile.projectId}, but ${DEFAULT_CONFIG_FILE} links ${link.projectId}. ${SYNC_HINT}`
686
+ };
687
+ }
688
+ if (lockfile.version !== link.version) {
689
+ return {
690
+ ok: false,
691
+ reason: "version-mismatch",
692
+ message: `${name} holds version "${lockfile.version}", but ${DEFAULT_CONFIG_FILE} tracks "${link.version}". ${SYNC_HINT}`
693
+ };
694
+ }
695
+ return null;
696
+ }
697
+ function changedPaths(operations) {
698
+ const paths = /* @__PURE__ */ new Set();
699
+ for (const operation of operations) {
700
+ if (operation.op === "test") continue;
701
+ const segments = [];
702
+ for (const raw of operation.path.split("/").slice(1)) {
703
+ const segment = raw.replace(/~1/g, "/").replace(/~0/g, "~");
704
+ if (segment.startsWith("$")) break;
705
+ segments.push(segment);
706
+ }
707
+ paths.add(segments.length > 0 ? segments.join(".") : "(root)");
708
+ }
709
+ return [...paths];
710
+ }
711
+ async function diffTokens({ cwd = process.cwd() } = {}) {
712
+ const link = await readLink(cwd);
713
+ if (link.ok === false) return link;
714
+ const current = await readCurrentLockfile(cwd);
715
+ if (current.ok === false) return current;
716
+ if (current.lockfile === null) {
717
+ return {
718
+ ok: false,
719
+ reason: "no-lockfile",
720
+ message: `No ${LOCKFILE_NAME} yet, so local edits cannot be told apart from Bezel's tokens. ${SYNC_HINT}`
721
+ };
722
+ }
723
+ const mismatch = checkLockMatchesLink(current.lockfile, link.link, LOCKFILE_NAME);
724
+ if (mismatch) return mismatch;
725
+ const local = await readTokensFile(cwd);
726
+ if (local.ok === false) return local;
727
+ const operations = compare(current.lockfile.tokens, local.tokens, true);
728
+ return {
729
+ ok: true,
730
+ projectId: current.lockfile.projectId,
731
+ version: current.lockfile.version,
732
+ baseRevision: current.lockfile.revision,
733
+ operations
734
+ };
735
+ }
736
+ async function syncFromStaging({
737
+ cwd = process.cwd(),
738
+ discardLocalEdits = false
739
+ } = {}) {
740
+ const stagingPath = (0, import_node_path2.resolve)(cwd, SYNC_STAGING_PATH);
741
+ if (!(0, import_node_fs.existsSync)(stagingPath)) {
742
+ return {
743
+ ok: false,
744
+ reason: "no-staging",
745
+ message: `Nothing to sync: ${SYNC_STAGING_PATH} is missing. Write the "lockfileContent" from the Bezel MCP's get-design-tokens-file there first.`
746
+ };
747
+ }
748
+ const incoming = parseLockfile(await (0, import_promises.readFile)(stagingPath, "utf8"), SYNC_STAGING_PATH);
749
+ if (incoming.ok === false) {
750
+ return {
751
+ ok: false,
752
+ reason: "staging-invalid",
753
+ message: `${incoming.message.replace(/ Sync from Bezel to rewrite it\.$/, "")} Write the "lockfileContent" from get-design-tokens-file to ${SYNC_STAGING_PATH} exactly as returned, then run "bezel sync" again.`
754
+ };
755
+ }
756
+ const next = incoming.lockfile;
757
+ const link = await readLink(cwd);
758
+ if (link.ok === false) return link;
759
+ const mismatch = checkLockMatchesLink(next, link.link, SYNC_STAGING_PATH);
760
+ if (mismatch) {
761
+ return {
762
+ ...mismatch,
763
+ message: `${SYNC_STAGING_PATH} is for project ${next.projectId} version "${next.version}", but ${DEFAULT_CONFIG_FILE} links ${link.link.projectId} version "${link.link.version}". Fetch the tokens for the linked project and version, or relink with "bezel init --project <uuid> --tokens-version <v>".`
764
+ };
765
+ }
766
+ const tokensPath = (0, import_node_path2.resolve)(cwd, DEFAULT_INPUT);
767
+ let discardedEdits = 0;
768
+ let tokensChanged = true;
769
+ if ((0, import_node_fs.existsSync)(tokensPath)) {
770
+ const local = await readTokensFile(cwd);
771
+ if (local.ok === true) {
772
+ tokensChanged = !jsonEqual(local.tokens, next.tokens);
773
+ const current = await readCurrentLockfile(cwd);
774
+ const base = current.ok === true && current.lockfile !== null && checkLockMatchesLink(current.lockfile, link.link, LOCKFILE_NAME) === null ? current.lockfile : null;
775
+ if (tokensChanged) {
776
+ if (base === null) {
777
+ if (!discardLocalEdits) {
778
+ return {
779
+ ok: false,
780
+ reason: "unknown-local-edits",
781
+ message: `${DEFAULT_INPUT} differs from Bezel's tokens and there is no usable ${LOCKFILE_NAME} to tell local edits from older Bezel tokens. If the file has no edits worth keeping, run "bezel sync --discard-local-edits" to replace it.`
782
+ };
783
+ }
784
+ } else {
785
+ const localEdits = compare(base.tokens, local.tokens, true);
786
+ const unpushed = unappliedOperations(next.tokens, localEdits);
787
+ if (unpushed.length > 0 && !discardLocalEdits) {
788
+ const paths = changedPaths(unpushed);
789
+ return {
790
+ ok: false,
791
+ reason: "unpushed-edits",
792
+ unpushedPaths: paths,
793
+ message: `${DEFAULT_INPUT} has ${unpushed.length} local ${unpushed.length === 1 ? "edit" : "edits"} Bezel does not have (${paths.slice(0, 10).join(", ")}${paths.length > 10 ? ", ..." : ""}). Push them to Bezel first, or run "bezel sync --discard-local-edits" to drop them.`
794
+ };
795
+ }
796
+ discardedEdits = unpushed.length;
797
+ }
798
+ }
799
+ } else if (!discardLocalEdits) {
800
+ return {
801
+ ...local,
802
+ message: `${local.message.replace(/ \(or sync from Bezel to replace it\)/, "")} Or run "bezel sync --discard-local-edits" to replace it with Bezel's tokens.`
803
+ };
804
+ }
805
+ }
806
+ await (0, import_promises.writeFile)((0, import_node_path2.resolve)(cwd, LOCKFILE_NAME), serializeLockfile(next), "utf8");
807
+ if (tokensChanged) await (0, import_promises.writeFile)(tokensPath, serializeTokensFile(next.tokens), "utf8");
808
+ await (0, import_promises.rm)(stagingPath, { force: true });
809
+ return { ok: true, projectId: next.projectId, version: next.version, revision: next.revision, tokensChanged, discardedEdits };
810
+ }
811
+ async function removeLockfileForOtherProject(cwd, projectId) {
812
+ const path = (0, import_node_path2.resolve)(cwd, LOCKFILE_NAME);
813
+ if (!(0, import_node_fs.existsSync)(path)) return false;
814
+ try {
815
+ const parsed = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
816
+ if (parsed.projectId === projectId) return false;
817
+ } catch {
818
+ }
819
+ await (0, import_promises.rm)(path, { force: true });
820
+ return true;
821
+ }
822
+
823
+ // src/init.ts
496
824
  var isUuid = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
497
825
  var isTokensVersion = (value) => value === "latest" || /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(value);
498
826
  var joinPath = (dir, file) => dir === "" ? file : `${dir.replace(/\/+$/, "")}/${file}`;
@@ -506,11 +834,11 @@ async function initConfig(options = {}) {
506
834
  );
507
835
  }
508
836
  const cwd = options.cwd ?? process.cwd();
509
- const toAbs = (p) => (0, import_node_path2.isAbsolute)(p) ? p : (0, import_node_path2.resolve)(cwd, p);
837
+ const toAbs = (p) => (0, import_node_path3.isAbsolute)(p) ? p : (0, import_node_path3.resolve)(cwd, p);
510
838
  const configPath = toAbs(DEFAULT_CONFIG_FILE);
511
- const hasTokensFile = (0, import_node_fs.existsSync)(toAbs(DEFAULT_INPUT));
512
- const isTypeScript = (0, import_node_fs.existsSync)(toAbs("tsconfig.json"));
513
- const hasSrc = (0, import_node_fs.existsSync)(toAbs("src"));
839
+ const hasTokensFile = (0, import_node_fs2.existsSync)(toAbs(DEFAULT_INPUT));
840
+ const isTypeScript = (0, import_node_fs2.existsSync)(toAbs("tsconfig.json"));
841
+ const hasSrc = (0, import_node_fs2.existsSync)(toAbs("src"));
514
842
  const outputDir = options.outputDir ?? (hasSrc ? DEFAULT_OUTPUT_DIR : FALLBACK_OUTPUT_DIR);
515
843
  const wantsContexts = options.contextsOutput !== void 0 || (options.contexts ?? isTypeScript);
516
844
  const wantsFonts = options.fontsOutput !== void 0 || (options.fonts ?? isTypeScript);
@@ -527,29 +855,24 @@ async function initConfig(options = {}) {
527
855
  if (options.colorFormat) config.colorFormat = options.colorFormat;
528
856
  if (options.dimensionUnit) config.dimensionUnit = options.dimensionUnit;
529
857
  if (options.includeAll) config.includeAll = true;
530
- if ((0, import_node_fs.existsSync)(configPath) && !options.force) {
858
+ if ((0, import_node_fs2.existsSync)(configPath) && !options.force) {
531
859
  const wantsLinkUpdate = options.projectId !== void 0 || options.version !== void 0;
532
860
  if (!wantsLinkUpdate) {
533
861
  return { configPath, config, written: false, updated: false, hasTokensFile, isTypeScript };
534
862
  }
535
- const existing = JSON.parse(await (0, import_promises.readFile)(configPath, "utf8"));
536
- const {
537
- projectId: previousProjectId,
538
- version: previousVersion,
539
- revision: previousRevision,
540
- ...rest
541
- } = existing;
863
+ const existing = JSON.parse(await (0, import_promises2.readFile)(configPath, "utf8"));
864
+ delete existing.revision;
865
+ const { projectId: previousProjectId, version: previousVersion, ...rest } = existing;
542
866
  const merged = {};
543
867
  const projectId = options.projectId ?? previousProjectId;
544
868
  if (projectId !== void 0) merged.projectId = projectId;
545
869
  merged.version = options.version ?? previousVersion ?? "latest";
546
- if (previousRevision !== void 0 && projectId === previousProjectId) {
547
- merged.revision = previousRevision;
548
- }
549
870
  Object.assign(merged, rest);
550
- await (0, import_promises.writeFile)(configPath, `${JSON.stringify(merged, null, 2)}
871
+ await (0, import_promises2.writeFile)(configPath, `${JSON.stringify(merged, null, 2)}
551
872
  `, "utf8");
873
+ const removedLockfile2 = projectId !== void 0 ? await removeLockfileForOtherProject(cwd, projectId) : false;
552
874
  return {
875
+ removedLockfile: removedLockfile2,
553
876
  configPath,
554
877
  config: merged,
555
878
  written: true,
@@ -560,13 +883,14 @@ async function initConfig(options = {}) {
560
883
  isTypeScript
561
884
  };
562
885
  }
563
- await (0, import_promises.writeFile)(configPath, `${JSON.stringify(config, null, 2)}
886
+ await (0, import_promises2.writeFile)(configPath, `${JSON.stringify(config, null, 2)}
564
887
  `, "utf8");
565
- return { configPath, config, written: true, updated: false, hasTokensFile, isTypeScript };
888
+ const removedLockfile = config.projectId !== void 0 ? await removeLockfileForOtherProject(cwd, config.projectId) : false;
889
+ return { configPath, config, written: true, updated: false, removedLockfile, hasTokensFile, isTypeScript };
566
890
  }
567
891
  async function readPackageScripts(cwd) {
568
892
  try {
569
- const raw = await (0, import_promises.readFile)((0, import_node_path2.resolve)(cwd, "package.json"), "utf8");
893
+ const raw = await (0, import_promises2.readFile)((0, import_node_path3.resolve)(cwd, "package.json"), "utf8");
570
894
  const parsed = JSON.parse(raw);
571
895
  return parsed.scripts ?? {};
572
896
  } catch {
@@ -579,7 +903,7 @@ async function generateVariablesCss(options = {}) {
579
903
  const resolved = resolveOptions(options);
580
904
  let raw;
581
905
  try {
582
- raw = await (0, import_promises2.readFile)(resolved.inputPath, "utf8");
906
+ raw = await (0, import_promises3.readFile)(resolved.inputPath, "utf8");
583
907
  } catch (err) {
584
908
  throw new Error(
585
909
  `bezel: could not read tokens file at "${resolved.inputPath}". A "design-tokens.json" file must exist at the project root.
@@ -595,17 +919,17 @@ ${err.message}`);
595
919
  }
596
920
  const css = emitCss(tokens, resolved);
597
921
  if (resolved.write) {
598
- await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(resolved.variablesOutputPath), { recursive: true });
599
- await (0, import_promises2.writeFile)(resolved.variablesOutputPath, css, "utf8");
922
+ await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(resolved.variablesOutputPath), { recursive: true });
923
+ await (0, import_promises3.writeFile)(resolved.variablesOutputPath, css, "utf8");
600
924
  if (resolved.contextsOutput) {
601
925
  const contextsModule = formatContextsModule(getContexts(tokens));
602
- await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(resolved.contextsOutput), { recursive: true });
603
- await (0, import_promises2.writeFile)(resolved.contextsOutput, contextsModule, "utf8");
926
+ await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(resolved.contextsOutput), { recursive: true });
927
+ await (0, import_promises3.writeFile)(resolved.contextsOutput, contextsModule, "utf8");
604
928
  }
605
929
  if (resolved.fontsOutput) {
606
930
  const fontsModule = formatFontsModule(getFonts(tokens));
607
- await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(resolved.fontsOutput), { recursive: true });
608
- await (0, import_promises2.writeFile)(resolved.fontsOutput, fontsModule, "utf8");
931
+ await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(resolved.fontsOutput), { recursive: true });
932
+ await (0, import_promises3.writeFile)(resolved.fontsOutput, fontsModule, "utf8");
609
933
  }
610
934
  if (resolved.gitignore) {
611
935
  await updateGitignore(resolved);
@@ -614,15 +938,17 @@ ${err.message}`);
614
938
  return css;
615
939
  }
616
940
  async function updateGitignore(resolved) {
617
- const dir = (0, import_node_path3.dirname)(resolved.gitignorePath);
941
+ const dir = (0, import_node_path4.dirname)(resolved.gitignorePath);
618
942
  const outputs = [
619
943
  resolved.variablesOutputPath,
620
944
  resolved.contextsOutput,
621
- resolved.fontsOutput
945
+ resolved.fontsOutput,
946
+ // The MCP's sync payload is a temporary hand-off file; the lockfile itself is committed.
947
+ (0, import_node_path4.resolve)((0, import_node_path4.dirname)(resolved.inputPath), SYNC_STAGING_PATH)
622
948
  ].filter((p) => p !== null);
623
949
  const entries = [];
624
950
  for (const output of outputs) {
625
- const rel = (0, import_node_path3.relative)(dir, output);
951
+ const rel = (0, import_node_path4.relative)(dir, output);
626
952
  if (rel === "" || rel.startsWith("..")) {
627
953
  process.stderr.write(
628
954
  `bezel: skipping .gitignore entry for "${output}" \u2014 outside ${resolved.gitignorePath}
@@ -630,18 +956,18 @@ async function updateGitignore(resolved) {
630
956
  );
631
957
  continue;
632
958
  }
633
- entries.push(`/${rel.split(import_node_path3.sep).join("/")}`);
959
+ entries.push(`/${rel.split(import_node_path4.sep).join("/")}`);
634
960
  }
635
961
  if (entries.length === 0) return;
636
962
  let existing = "";
637
963
  try {
638
- existing = await (0, import_promises2.readFile)(resolved.gitignorePath, "utf8");
964
+ existing = await (0, import_promises3.readFile)(resolved.gitignorePath, "utf8");
639
965
  } catch {
640
966
  }
641
967
  const next = mergeGitignore(existing, entries);
642
968
  if (next !== existing) {
643
- await (0, import_promises2.mkdir)(dir, { recursive: true });
644
- await (0, import_promises2.writeFile)(resolved.gitignorePath, next, "utf8");
969
+ await (0, import_promises3.mkdir)(dir, { recursive: true });
970
+ await (0, import_promises3.writeFile)(resolved.gitignorePath, next, "utf8");
645
971
  }
646
972
  }
647
973
  // Annotate the CommonJS export names for ESM import in node:
@@ -653,6 +979,12 @@ async function updateGitignore(resolved) {
653
979
  DEFAULT_NAME_EXTENSION,
654
980
  DEFAULT_OUTPUT_DIR,
655
981
  FALLBACK_OUTPUT_DIR,
982
+ LOCKFILE_NAME,
983
+ LOCKFILE_VERSION,
984
+ SYNC_STAGING_PATH,
985
+ buildLockfile,
986
+ changedPaths,
987
+ diffTokens,
656
988
  emitCss,
657
989
  formatContextsModule,
658
990
  formatFontsModule,
@@ -660,9 +992,18 @@ async function updateGitignore(resolved) {
660
992
  getContexts,
661
993
  getFonts,
662
994
  initConfig,
995
+ isOperationApplied,
996
+ isPatchApplied,
997
+ jsonEqual,
998
+ parseLockfile,
663
999
  readPackageScripts,
1000
+ removeLockfileForOtherProject,
664
1001
  resolveCssOptions,
665
1002
  resolveOptions,
666
- tokensToCss
1003
+ serializeLockfile,
1004
+ serializeTokensFile,
1005
+ syncFromStaging,
1006
+ tokensToCss,
1007
+ unappliedOperations
667
1008
  });
668
1009
  //# sourceMappingURL=node.cjs.map