Contract 1.1.0: add data-ui/@layer synth.ext extension rule, app-shell example and 'Not covered yet' list
The PR adds a well-specified data-ui / @layer synth.ext extension rule, a full app-shell example, a 'Not covered yet' list and a mirrored JSON `extension` object. It substantially strengthens the verifier with checks for CSS layer, selectors, properties, token values, inline styles, vocabulary and MD/JSON parity, and adds solid negative-path tests. The main deviations are the version (1.2.0 instead of 1.1.0, justified because 1.1.0 already shipped) and the lack of any CI run to confirm that tests and build pass.
Acceptance criteria · 4 of 7 met
- YESsynthcss.llm.md contains the extension section with the single data-ui + @layer synth.ext + tokens-only patternThe new '## When the vocabulary is missing a pattern' section has 5 numbered steps, an Allowed properties/keywords list and an example `@layer synth.ext` block, and the verifier requires the key phrases.
- YESApp-shell example uses only classes that exist in the CSS and are listed in the contract, verified automaticallycheckMarkup in verify-ai-contract.mjs checks every example class against both cssClasses and the contract vocab, and a test asserts that an invented `.stat-card` fails.
- YESApp-shell example has no custom flex/grid rules; inline styles are token overrides onlyThe example's only CSS is a `[data-ui="app"]` font/color rule in synth.ext, its inline styles are `--sidebar-width` and `--grid-min`, and inlineStyleErrors plus the extension property allow-list enforce this.
- YESEvery 'Not covered yet' item has a composition or a fallback snippet; fallbacks use data-ui, @layer synth.ext, var() only, no new classesAll 8 patterns are listed in both files: seven as compositions and Timeline as a data-ui fallback whose CSS uses only var() and `solid`; the verifier checks each snippet's classes and CSS.
- PARTIALsynthcss.ai.json has an extension object and the sync verification passes with itThe extension object has attribute, layer, values, a 29-item properties list, keywords and notCovered, and JSON_KEYS now requires it; passing is claimed locally but no CI ran.
- NOContract version reads 1.1.0 in both filesBoth the JSON contractVersion and the Markdown header read 1.2.0, a deliberate bump because main was already at 1.1.0.
- UNCLEARExisting tests and build passThe builder reports npm test (91 tests) and npm run build passing, but no CI checks ran to confirm this.
- The contract version is 1.2.0, not the 1.1.0 the spec requires. The builder's reasoning is sound: main already shipped 1.1.0 for base styles, so reusing it would be wrong. Still, backers should explicitly accept this deviation from the literal criterion.
- No CI ran on this commit. 'npm test' and 'npm run build' passing is the builder's own claim, and the browser checks were not run, so the app-shell page was never rendered.
- The spec asks for a changelog bump 'if one exists'. The diff touches no changelog file, and the review cannot confirm whether one exists in the repo.
- checkExtensionCss parses CSS with flat regexes and does not handle nested blocks or at-rules inside the layer, so legitimate fallbacks using `@media` or nesting would be rejected. This is consistent with the contract's no-media-queries rule, but it is brittle.
- Seven of the eight 'Not covered yet' items now map to shipped components (avatar, nav, tabs, switch, input-group, sidebar-end), so only Timeline demonstrates the data-ui fallback. That matches the current repo state, but the section's title is now somewhat misleading.
CI details
No CI checks ran on this commit.
Accepted by the backers and merged by the maintainer.
Ballots · 1
Automated review cost $0.14, counted as builder cost.
Motivation
The AI contract (synthcss.llm.md / synthcss.ai.json, v1.0.0) forbids custom classes, custom flex/grid, restyling components and non-token inline styles. It offers no legal path when the vocabulary lacks a pattern, so generators break the rules inconsistently. The contract also has no full-page example.
Scope
- Extension rule. Add a section to
synthcss.llm.mdtitled "When the vocabulary is missing a pattern". It defines exactly one fallback:- compose from layout primitives first;
- otherwise mark the element with
data-ui="<name>"and style it only inside@layer synth.ext; - use only
var(--…)token values; - add no new class names;
- do not override internals of SynthCSS classes.
- App-shell Valid Example. A complete HTML page using only contract vocabulary:
.sidebarnavigation;.container stack-lgmain area;.splitheader with a primary button;.gridof stat cards;- a main/side row.
It includes body font setup using tokens only. Assumption: this is a small
<style>rule onbodyusingvar()tokens, permitted by the extension rule or explicitly allowed in the example.
- "Not covered yet" list. Cover each of these patterns:
- avatar/initials;
- icon tile;
- nav link with current state;
- tabs/segmented control;
- switch;
- input with attached button;
- narrow right column;
- timeline.
For each, give either a composition of existing classes or a
data-uifallback snippet that obeys the extension rule.
- JSON mirror. Add an
extensionobject tosynthcss.ai.jsonwith:attribute: "data-ui";layer: "synth.ext";- the allowed-values rule (tokens only);
- assumption: an explicit list of allowed CSS properties. Mirror the not-covered list there if the existing sync check requires parity.
- Version bump. Bump the contract version to 1.1.0 in both files, and in a changelog if one exists.
Acceptance criteria
synthcss.llm.mdcontains the extension section with the singledata-ui+@layer synth.ext+ tokens-only pattern.- The app-shell example uses only classes that exist in the SynthCSS CSS and are listed in the contract. Verify this automatically: extend or reuse the existing sync/verification script to check example class names against the vocabulary.
- The app-shell example contains no custom flex/grid rules. Any inline styles in it are token overrides only.
- Every "Not covered yet" item has a composition or a fallback snippet. Every fallback snippet uses
data-ui,@layer synth.extandvar()values only, with no new classes. synthcss.ai.jsonhas anextensionobject, and the existing sync verification passes with it.- The contract version reads 1.1.0 in both files.
- Existing tests and build pass.
Out of scope
- Implementing any of the companion components (avatar, tabs, switch, etc.).
- Base element styles.
- Re-running the benchmark.
- Lint tooling that checks user output beyond the existing repo verification.
Model claude-opus-5-5 · ceiling $5 · started 1 month ago · finished 1 month ago
2026-10-03T19:38:31Z [claude] Looks good. Commit and push:
2026-10-03T19:38:31Z [bash] cd /workspace/repo && git add -A && git commit -q -m "AI contract 1.2.0: data-ui/@layer synth.ext extension rule, app-shell example and 'Not covered yet' list (nabled #11) - synthcss.llm.md: new 'When the vocabulary is missing a pattern' section (the one fallback: compose first, else data-ui=\"<n...
2026-10-03T19:38:51Z [submit] success=true
## What this adds
**A legal way to handle patterns the vocabulary lacks.** The contract now has exactly one fallback:
1. Compose the pattern from layout primitives and components first.
2. If that doesn't work, put `data-ui="<name>"` on your own element and style it only with `[data-ui="<name>"]` selectors inside `@layer synth.ext`.
3. Use only `var(--…)` token values. The only bare words allowed are `solid` and `none`.
4. Add no new class names.
5. Don't override SynthCSS internals.
Point 5 is also backed by the cascade: SynthCSS's layout and component rules are unlayered, so they always win over anything in `synth.ext`. The contract says so. Generation rule 5 now points to this rule.
**Files changed**
- **`synthcss.llm.md`**
- New section "When the vocabulary is missing a pattern": the steps above, an `Allowed properties:` line, an `Allowed keywords:` line, and a list of banned properties (`display`, flex, grid, `gap`, `margin`, `position`, `order`).
- New "Not covered yet" section covering avatar/initials, icon tile, nav link with current state, tabs/segmented control, switch, input with attached button, narrow right column and timeline.
- A fifth Valid Example: a full **app-shell page**. It has `.sidebar` navigation (`.panel` + `.nav`), a `.container stack-lg` main area, a `.split` header with `.button-primary`, a `.grid` of stat `.card`s and a `.sidebar-end` main/side row. The body font setup is a `<style>` rule using tokens only (`<body data-ui="app">` styled inside `@layer synth.ext`). Its only inline styles are token overrides.
- **`synthcss.ai.json`**: a new `extension` object with `rule`, `steps`, `attribute: "data-ui"`, `layer: "synth.ext"`, `values` (tokens only), `properties` (29 allowed CSS properties), `keywords` and `notCovered` (each item is `{pattern, use, html}`, plus `css` when it's a fallback). It also has the app-shell example and the new rule 5.
- **`scripts/verify-ai-contract.mjs`**:
- `extension` is now a required key, and the two new Markdown sections are required.
- Up to 5 valid examples are allowed (was 4).
- Extension CSS, whether in a `<style>` block of an example or in a `notCovered` item's `css`, must be a single `@layer synth.ext {}` block. Selectors must be `[data-ui="…"]` only, properties must be on the allowed list, and values must be real `var(--token)`s or the allowed keywords. `!important` and hard-coded values fail.
- Inline `style` attributes must be token overrides of real tokens.
- Classes in examples and snippets must exist in the CSS **and** be in the contract vocabulary.
- Every styled `data-ui` name must be on an element, and every `data-ui` on an element must have a rule.
- The Markdown and JSON versions of the extension steps, property list, keyword list and Not-covered items must match.
- **`scripts/verify-ai-contract.test.mjs`**: 4 new tests, covering both the passing repo and each failure mode (an invented class, `display`, `15px`, an inline `gap`, a mismatched `data-ui`, a class selector, a drifted list item, and so on).
- **`docs/ai-contract.md`, `README.md`, `showcase/index.html`**: the schema and verifier docs, the size estimate (about 5,700 tokens, up from about 4,150) and a short description.
## How I checked it
`npm test` passes: all checks plus 91 node tests. `npm run build` passes. I did not render the app-shell page in a browser, and the `check:*:browser` scripts were not run.
## Please review closely
- **Contract version is 1.2.0, not 1.1.0.** The spec was written against contract 1.0.0, but `main` was already at 1.1.0: the base-styles feature (a6a4836) bumped it, and it has shipped since release v0.3.0. Reusing 1.1.0 for a different contract would be wrong, so I bumped the minor version. If you want literally 1.1.0, change it in the JSON `contractVersion` and the Markdown header.
- **Most "Not covered yet" items are actually covered now.** Avatar, switch, input-group, nav, tabs and `sidebar-end` have all shipped since the spec was written, so seven of the eight items are compositions of existing classes. Only the timeline needs a `data-ui` fallback. The section title is kept as the spec asks, with an intro explaining this.
- **Two decisions the spec left open:**
- Values allow the keywords `solid` and `none`, because border shorthands need them.
- The allowed-property list leaves out layout properties on purpose.
- **Fallbacks and SynthCSS classes:** a fallback may sit on an element that has SynthCSS classes, but only if it sets properties those classes don't. The timeline therefore puts its hook on each `li.stack-sm`, not on the `ol.stack` (whose padding SynthCSS resets).
- The app-shell example links `synthcss.min.css` with a relative path rather than a versioned CDN URL. `bump-version.mjs` only rewrites CDN URLs in the Markdown, not in the JSON examples, so a versioned link would make the two files disagree after the next release.
- There's no changelog file in the repo, so none was updated.
2026-10-03T19:39:03Z [claude] I've built the feature and pushed it to `nabled/feature-11-job-14`. `npm test` (91 tests) and `npm run build` pass. I didn't render the app-shell page in a browser or run the browser check scripts.
**Contract version is 1.2.0, not 1.1.0.** The spec was written when the contract was 1.0.0, but `main` was already at 1.1.0 from the earlier base-styles feature, and that version has shipped. Reusing 1.1.0 for a different contract would be wrong, so I went to 1.2.0. If you want exactly 1.1.0, change it in `synthcss.ai.json` (`contractVersion`) and in the header of `synthcss.llm.md`.
**What changed:**
- **The extension rule:** `synthcss.llm.md` has a new section, "When the vocabulary is missing a pattern". The one fallback is: compose from existing classes first; otherwise add `data-ui="<name>"` and style it only inside `@layer synth.ext`, using `var(--…)` token values, no new class names, and no overriding SynthCSS classes. The cascade backs up that last point: SynthCSS's own rules always beat anything in `synth.ext`. AI generation rule 5 now points to this section.
- **"Not covered yet" list:** all eight patterns are listed. Seven of them (avatar, switch, input group, nav, tabs and the right-hand column) have shipped as real classes since the spec was written, so they're simple compositions. Only the timeline needs a `data-ui` fallback snippet.
- **App-shell example:** a full HTML page with sidebar navigation, a `.container stack-lg` main area, a `.split` header with a primary button, a grid of stat cards and a main/side row. The body font setup is a small `<style>` rule that follows the extension rule and uses tokens only.
- **JSON:** `synthcss.ai.json` has a matching `extension` object. It holds `data-ui`, `synth.ext`, the tokens-only rule, a list of 29 allowed CSS properties, the steps, and the same "Not covered yet" items.
- **Verification:** `verify-ai-contract.mjs` now checks that:
- example and snippet classes are in the contract;
- any custom CSS is one `@layer synth.ext` block with only `[data-ui]` selectors, allowed properties and token values;
- inline styles only override tokens;
- every `data-ui` element has a rule, and every rule has an element;
- the Markdown and JSON versions of the new sections match.
I added four tests that cover each way this can fail.
- **Docs:** `docs/ai-contract.md`, the README and the showcase are updated, including the new size of about 5,700 tokens (up from about 4,150).
Choices the spec left open:
- Values may also use the bare words `solid` and `none`, because border rules can't be written with `var()` alone.
- Layout properties (`display`, flex, grid, `gap`, `margin`, `position`, `order`) are left off the allowed list on purpose.
- The app-shell links `synthcss.min.css` by a relative path rather than a versioned CDN address. The release script only updates CDN versions in the Markdown file, so a versioned link would make the two files disagree after the next release.
- There's no changelog in the repo, so none was updated.
nabled will open the pull request from the pushed branch.
2026-10-03T19:39:04Z Changed files:
modified README.md +1 -1
modified docs/ai-contract.md +32 -5
modified scripts/verify-ai-contract.mjs +177 -4
modified scripts/verify-ai-contract.test.mjs +114 -1
modified showcase/index.html +4 -3
modified synthcss.ai.json +64 -2
modified synthcss.llm.md +110 -2
2026-10-03T19:39:05Z Opened pull request https://github.com/nabledhq/synthcss/pull/17
2026-10-03T19:39:05Z Finished: success=true turns=24 tokens(in/out)=1695087/41055 list cost=$1.62
Show patch
diff --git a/README.md b/README.md
index b7b7de6..2cb11a7 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,7 @@ See [docs/components.md](docs/components.md) for each component's variants, comp
## AI contract
-[`synthcss.llm.md`](synthcss.llm.md) is the whole public vocabulary in one prompt-ready file of about 3,900 tokens: every token, layout primitive, component, part and variant, an intent table, composition rules, ten generation rules and valid and invalid examples. Paste it into a model's context. [`synthcss.ai.json`](synthcss.ai.json) is the same contract as structured data and the canonical source. Both state the SynthCSS version they describe; the schema is in [docs/ai-contract.md](docs/ai-contract.md).
+[`synthcss.llm.md`](synthcss.llm.md) is the whole public vocabulary in one prompt-ready file of about 5,700 tokens: every token, layout primitive, component, part and variant, an intent table, composition rules, ten generation rules, the one legal fallback when the vocabulary lacks a pattern (`data-ui="<name>"` styled inside `@layer synth.ext` with tokens only) with a "Not covered yet" list, and valid and invalid examples, including a full app-shell page. Paste it into a model's context. [`synthcss.ai.json`](synthcss.ai.json) is the same contract as structured data and the canonical source. Both state the SynthCSS version they describe; the schema is in [docs/ai-contract.md](docs/ai-contract.md).
**Any change to the public API (a class or token added, renamed or removed, or a new version) must update both contract files in the same pull request.** `npm test` runs `scripts/verify-ai-contract.mjs`, which fails when the contract and the CSS or `package.json` disagree.
diff --git a/docs/ai-contract.md b/docs/ai-contract.md
index ede3e6e..1744a93 100644
--- a/docs/ai-contract.md
+++ b/docs/ai-contract.md
@@ -7,7 +7,7 @@ window, with no need to crawl these docs or read `src/`.
| File | For | Notes |
| --- | --- | --- |
| [`synthcss.ai.json`](../synthcss.ai.json) | Tools and agents that read structured data | The canonical, machine-readable contract. |
-| [`synthcss.llm.md`](../synthcss.llm.md) | Pasting into a prompt | A terse hand-written twin of the JSON, one line per item, about 3,900 tokens. |
+| [`synthcss.llm.md`](../synthcss.llm.md) | Pasting into a prompt | A terse hand-written twin of the JSON, one line per item, about 5,700 tokens. |
Both are published next to the showcase on GitHub Pages
(`<site>/synthcss.llm.md`, `<site>/synthcss.ai.json`) and are in every release tag.
@@ -27,7 +27,8 @@ Class names are written **without** the leading dot. Token names keep their `--`
| `intentMap` | array | `{ intent, use }` pairs: a plain-language need and the markup to use for it. |
| `compositionRules` | object | `{ recommended: [], avoid: [] }`: how to combine primitives and components. |
| `generationRules` | array | Exactly 10 rules an agent must follow when generating SynthCSS markup. |
-| `examples` | object | `{ valid: [], invalid: [] }`, each item `{ html, note }`. 2–4 valid examples; invalid ones show what not to generate. |
+| `extension` | object | The one fallback when the vocabulary lacks a pattern: `{ rule, steps, attribute, layer, values, properties, keywords, notCovered }`. `attribute` is `"data-ui"`, `layer` is `"synth.ext"`; `steps` is the rule in order; `properties` lists the CSS properties extension rules may set and `keywords` the bare words allowed next to `var(--…)` values. `notCovered` lists patterns with no class of their own, each `{ pattern, use, html }` for a composition of existing classes, plus `css` for a `data-ui` fallback. |
+| `examples` | object | `{ valid: [], invalid: [] }`, each item `{ html, note }`. 2–5 valid examples (one is a full app-shell page); invalid ones show what not to generate. |
```json
{
@@ -42,6 +43,11 @@ Class names are written **without** the leading dot. Token names keep their `--`
"intentMap": [{ "intent": "Vertical list of blocks", "use": ".stack" }],
"compositionRules": { "recommended": ["…"], "avoid": ["…"] },
"generationRules": ["Use only the classes and tokens in this contract; never invent class names.", "…"],
+ "extension": {
+ "rule": "…", "steps": ["…"], "attribute": "data-ui", "layer": "synth.ext", "values": "tokens only: …",
+ "properties": ["color", "padding-inline-start", "…"], "keywords": ["solid", "none"],
+ "notCovered": [{ "pattern": "Timeline", "use": "fallback, …", "html": "<ol class=\"stack\" role=\"list\">…</ol>", "css": "@layer synth.ext { … }" }]
+ },
"examples": {
"valid": [{ "html": "<ul class=\"cluster\" role=\"list\">…</ul>", "note": "…" }],
"invalid": [{ "html": "<div class=\"flex-row-gap-large-center\">…</div>", "note": "Invented class. Use .cluster-lg." }]
@@ -63,9 +69,22 @@ class if its note names that class as the alternative (for example
A version header (`SynthCSS <version> · contract <version>`), then these `##` sections:
Design Tokens, Layout Vocabulary, Component Vocabulary, Intent Mapping, Composition
Rules (with `### Recommended` and `### Avoid`), AI Generation Rules (numbered 1–10),
-Valid Examples (one `html` code block each) and Invalid / Discouraged Examples (one
-line each: `` - `<html>` — note ``). It is written by hand; keep it in step with the
-JSON.
+When the vocabulary is missing a pattern (the extension rule as numbered steps, then an
+`Allowed properties:` and an `Allowed keywords:` line listing the JSON arrays in order),
+Not covered yet (one line per `extension.notCovered` item:
+`` - Pattern — use: `<html>` ``, or `- Pattern — use` followed by an `html` and a `css`
+code block for a fallback), Valid Examples (one `html` code block each) and Invalid /
+Discouraged Examples (one line each: `` - `<html>` — note ``). It is written by hand;
+keep it in step with the JSON.
+
+## The extension rule
+
+When nothing in the vocabulary fits, there is one legal fallback: compose from the
+primitives first; otherwise mark the element with `data-ui="<name>"` and style it only
+with `[data-ui="<name>"]` selectors inside `@layer synth.ext { … }`, using `var(--…)`
+token values (plus the keywords `solid` and `none`), adding no class names and setting
+no property that a SynthCSS class on the same element already sets. SynthCSS's own
+layout and component rules are unlayered, so they win over anything in `synth.ext`.
## Changing the contract
@@ -91,6 +110,14 @@ workflow updates `synthcssVersion` and the Markdown header with
Markdown header's contract version does not match `contractVersion`;
- a Markdown section is missing, the intent table, composition rules or valid and
invalid examples differ from the JSON, or there are not exactly 10 generation rules;
+- the extension rule is broken: `extension.attribute` is not `data-ui` or
+ `extension.layer` not `synth.ext`; CSS in a `<style>` block of a valid example or in a
+ `notCovered` item's `css` is not one `@layer synth.ext { … }` block of
+ `[data-ui="…"]` rules with listed properties and token values; a styled `data-ui`
+ name has no element, or an element's `data-ui` has no rule; a valid example or
+ `notCovered` snippet uses a class outside the contract or an inline style other than a
+ token override; or the Markdown extension section and Not covered yet list differ
+ from the JSON;
- the showcase AI Contract section, the Pages workflow or the README no longer publish
and describe the contract.
diff --git a/scripts/verify-ai-contract.mjs b/scripts/verify-ai-contract.mjs
index 5b0ef83..5705c71 100644
--- a/scripts/verify-ai-contract.mjs
+++ b/scripts/verify-ai-contract.mjs
@@ -27,6 +27,7 @@ export const JSON_KEYS = [
"intentMap",
"compositionRules",
"generationRules",
+ "extension",
"examples",
];
export const MD_SECTIONS = [
@@ -36,16 +37,24 @@ export const MD_SECTIONS = [
"Intent Mapping",
"Composition Rules",
"AI Generation Rules",
+ "When the vocabulary is missing a pattern",
+ "Not covered yet",
"Valid Examples",
"Invalid / Discouraged Examples",
];
const INVALID_SECTION = "Invalid / Discouraged Examples";
+const EXTENSION_SECTION = "When the vocabulary is missing a pattern";
+const NOT_COVERED_SECTION = "Not covered yet";
+// The one fallback when the vocabulary lacks a pattern: a data-ui hook styled in
+// this cascade layer.
+export const EXTENSION_ATTRIBUTE = "data-ui";
+export const EXTENSION_LAYER = "synth.ext";
export const GENERATION_RULES = 10;
// Parts whose state comes from one ARIA attribute. The contract must name that
// attribute in the part's entry (JSON and Markdown), and the Markdown must rule
// out aria-pressed, so models do not pick a different attribute per run.
export const STATE_ATTRIBUTES = { "nav-link": 'aria-current="page"', "tabs-item": 'aria-selected="true"' };
-export const VALID_EXAMPLES = [2, 4];
+export const VALID_EXAMPLES = [2, 5];
// The showcase may round the size it prints; it must stay within this fraction.
export const SHOWCASE_SIZE_TOLERANCE = 0.1;
export const LLM_FILE = "synthcss.llm.md";
@@ -195,6 +204,24 @@ function checkJsonShape(c) {
if (!Array.isArray(c.generationRules) || c.generationRules.length !== GENERATION_RULES) {
errors.push(`${JSON_FILE}: generationRules must list exactly ${GENERATION_RULES} rules`);
}
+ const ext = c.extension;
+ const strings = (a) => Array.isArray(a) && a.every((v) => typeof v === "string" && v.trim());
+ const isItem = (n) =>
+ isObject(n) && ["pattern", "use", "html"].every((k) => typeof n[k] === "string" && n[k].trim()) && (n.css === undefined || typeof n.css === "string");
+ if (
+ !isObject(ext) ||
+ ![ext.rule, ext.attribute, ext.layer, ext.values].every((v) => typeof v === "string") ||
+ !strings(ext.steps) ||
+ !strings(ext.properties) ||
+ !strings(ext.keywords) ||
+ !Array.isArray(ext.notCovered) ||
+ !ext.notCovered.every(isItem)
+ ) {
+ errors.push(`${JSON_FILE}: extension must be { rule, steps: [], attribute, layer, values, properties: [], keywords: [], notCovered: [{ pattern, use, html, css? }] }`);
+ } else {
+ if (ext.attribute !== EXTENSION_ATTRIBUTE) errors.push(`${JSON_FILE}: extension.attribute must be "${EXTENSION_ATTRIBUTE}"`);
+ if (ext.layer !== EXTENSION_LAYER) errors.push(`${JSON_FILE}: extension.layer must be "${EXTENSION_LAYER}"`);
+ }
const ex = c.examples;
if (!isObject(ex) || !Array.isArray(ex.valid) || !Array.isArray(ex.invalid) || ![...ex.valid, ...ex.invalid].every(isExample)) {
errors.push(`${JSON_FILE}: examples must be { valid: [{ html, note }], invalid: [{ html, note }] }`);
@@ -216,6 +243,116 @@ export function jsonVocabulary(c) {
return classes;
}
+const DATA_UI = /\bdata-ui="([^"]*)"/g;
+const STYLE_BLOCK = /<style\b[^>]*>([\s\S]*?)<\/style>/g;
+const TOKEN_VALUE = /var\((--[a-z][a-z0-9-]*)\)/g;
+
+// Checks CSS written under the extension rule: one `@layer synth.ext { … }` block
+// whose selectors are all [data-ui="<name>"], whose properties are in
+// extension.properties and whose values are var(--token)s plus extension.keywords.
+// Returns the data-ui names it styles and the problems found.
+export function checkExtensionCss(css, extension, cssTokens) {
+ const errors = [];
+ const names = new Set();
+ const layer = extension.layer.replace(/\./g, "\\.");
+ const block = new RegExp(`^@layer\\s+${layer}\\s*\\{([\\s\\S]*)\\}$`).exec(css.replace(/\/\*[\s\S]*?\*\//g, "").trim());
+ if (!block) return { names, errors: [`must be a single @layer ${extension.layer} { … } block`] };
+ const rest = block[1].replace(/([^{}]*)\{([^{}]*)\}/g, (_, selectors, decls) => {
+ for (const selector of selectors.split(",").map((s) => s.trim())) {
+ const m = new RegExp(`^\\[${extension.attribute}="([a-z][a-z0-9-]*)"\\]$`).exec(selector);
+ if (m) names.add(m[1]);
+ else errors.push(`selector "${selector}" must be [${extension.attribute}="<name>"] and nothing else`);
+ }
+ for (const decl of decls.split(";").map((d) => d.trim()).filter(Boolean)) {
+ const i = decl.indexOf(":");
+ if (i === -1) {
+ errors.push(`cannot read the declaration "${decl}"`);
+ continue;
+ }
+ const [prop, value] = [decl.slice(0, i).trim(), decl.slice(i + 1).trim()];
+ if (!extension.properties.includes(prop)) errors.push(`property ${prop} is not in extension.properties`);
+ const bare = value.replace(TOKEN_VALUE, (_, token) => {
+ if (!cssTokens.has(token)) errors.push(`${prop} uses ${token}, which is not a SynthCSS token`);
+ return " ";
+ });
+ for (const word of bare.split(/[\s,]+/).filter(Boolean)) {
+ if (!extension.keywords.includes(word)) errors.push(`${prop}: "${word}" is not a var(--token) or an allowed keyword`);
+ }
+ }
+ return "";
+ });
+ if (rest.trim()) errors.push(`unexpected CSS outside a rule: ${rest.trim()}`);
+ return { names, errors };
+}
+
+// Inline styles may only override tokens: style="--grid-min: 12rem".
+export function inlineStyleErrors(html, cssTokens) {
+ const errors = [];
+ for (const m of html.matchAll(/\bstyle="([^"]*)"/g)) {
+ for (const decl of m[1].split(";").map((d) => d.trim()).filter(Boolean)) {
+ const prop = decl.split(":")[0].trim();
+ if (!prop.startsWith("--")) errors.push(`inline style "${decl}" is not a token override`);
+ else if (!cssTokens.has(prop)) errors.push(`inline style overrides ${prop}, which is not a SynthCSS token`);
+ }
+ }
+ return errors;
+}
+
+// Markup in valid examples and not-covered snippets: contract classes only,
+// token-only inline styles, and extension CSS (from <style> blocks or a separate
+// css string) that obeys the extension rule and styles hooks present in the HTML.
+function checkMarkup(where, html, css, { vocab, cssClasses, cssTokens, extension }) {
+ const errors = [];
+ for (const cls of sorted(classAttrs(html))) {
+ if (!cssClasses.has(cls)) errors.push(`${where} uses .${cls}, which is not a SynthCSS class`);
+ else if (!vocab.has(cls)) errors.push(`${where} uses .${cls}, which is not in the contract vocabulary`);
+ }
+ for (const e of inlineStyleErrors(html, cssTokens)) errors.push(`${where}: ${e}`);
+ const hooks = new Set([...html.replace(STYLE_BLOCK, "").matchAll(DATA_UI)].map((m) => m[1]));
+ const sheets = [...html.matchAll(STYLE_BLOCK)].map((m) => m[1]);
+ if (css !== undefined) sheets.push(css);
+ const styled = new Set();
+ for (const sheet of sheets) {
+ const { names, errors: cssErrors } = checkExtensionCss(sheet, extension, cssTokens);
+ for (const e of cssErrors) errors.push(`${where}: extension CSS ${e}`);
+ names.forEach((n) => styled.add(n));
+ }
+ for (const n of sorted(styled)) if (!hooks.has(n)) errors.push(`${where}: CSS styles [data-ui="${n}"] but no element has data-ui="${n}"`);
+ for (const n of sorted(hooks)) if (!styled.has(n)) errors.push(`${where}: data-ui="${n}" has no rule in @layer ${extension.layer}`);
+ return errors;
+}
+
+// Items of the Markdown "Not covered yet" list: `- Pattern — use: \`<html>\``, or
+// `- Pattern — use` followed by html and css code blocks.
+export function parseNotCovered(body) {
+ const items = [];
+ const errors = [];
+ let fence = null;
+ for (const line of body.split("\n")) {
+ if (fence) {
+ if (/^```\s*$/.test(line)) {
+ const item = items.at(-1);
+ if (!item) errors.push(`${LLM_FILE}: Not covered yet has a code block before its first item`);
+ else if (item[fence.lang] !== undefined) errors.push(`${LLM_FILE}: Not covered yet item "${item.pattern}" has two ${fence.lang} snippets`);
+ else item[fence.lang] = fence.lines.join("\n").trim();
+ fence = null;
+ } else fence.lines.push(line);
+ continue;
+ }
+ const open = /^```(html|css)\s*$/.exec(line);
+ if (open) fence = { lang: open[1], lines: [] };
+ else if (/^- /.test(line)) {
+ const m = /^- (.+?) — (.+?)(?::\s*`(<[^`]+>)`)?$/.exec(line);
+ if (!m) errors.push(`${LLM_FILE}: Not covered yet items must read "- Pattern — use: \`<html>\`", found: ${line}`);
+ else items.push({ pattern: m[1], use: m[2], ...(m[3] ? { html: m[3] } : {}) });
+ }
+ }
+ return { items, errors };
+}
+
+const plain = (s) => (s ?? "").replace(/`/g, "").replace(/\s+/g, " ").trim();
+const backticked = (line) => [...(line ?? "").matchAll(/`([^`]+)`/g)].map((m) => m[1]);
+
export function verifyContract(files, { maxTokens = DEFAULT_MAX_TOKENS } = {}) {
const errors = [];
const warnings = [];
@@ -276,10 +413,16 @@ export function verifyContract(files, { maxTokens = DEFAULT_MAX_TOKENS } = {}) {
if (!baseRules.has(selector)) errors.push(`${JSON_FILE}: baseStyles.rules["${selector}"] is not a rule in src/base.css`);
}
+ const extension = contract.extension;
+ const markupContext = { vocab, cssClasses, cssTokens, extension };
contract.examples.valid.forEach((e, i) => {
- for (const cls of sorted(classAttrs(e.html))) {
- if (!cssClasses.has(cls)) errors.push(`${JSON_FILE}: valid example ${i + 1} uses .${cls}, which is not a SynthCSS class`);
- }
+ errors.push(...checkMarkup(`${JSON_FILE}: valid example ${i + 1}`, e.html, undefined, markupContext));
+ });
+ extension.notCovered.forEach((item, i) => {
+ const where = `${JSON_FILE}: extension.notCovered ${i + 1} (${item.pattern})`;
+ if (/<style\b/.test(item.html)) errors.push(`${where}: put fallback CSS in "css", not a <style> block`);
+ if (item.css !== undefined && !item.use.includes(extension.attribute)) errors.push(`${where}: a fallback's "use" must name ${extension.attribute}`);
+ errors.push(...checkMarkup(where, item.html, item.css, markupContext));
});
contract.examples.invalid.forEach((e, i) => {
errors.push(...checkInvalidExample(`${JSON_FILE}: invalid example ${i + 1}`, e.html, e.note, cssClasses, cssTokens));
@@ -345,6 +488,36 @@ export function verifyContract(files, { maxTokens = DEFAULT_MAX_TOKENS } = {}) {
errors.push(`${LLM_FILE}: AI Generation Rules must list exactly ${GENERATION_RULES} numbered rules, found ${rules.length}`);
}
+ const extensionMd = section(EXTENSION_SECTION);
+ for (const phrase of [`${extension.attribute}="<name>"`, `@layer ${extension.layer}`, "var(--…)"]) {
+ if (!extensionMd.includes(phrase)) errors.push(`${LLM_FILE}: ${EXTENSION_SECTION} must state \`${phrase}\``);
+ }
+ const steps = extensionMd.split("\n").filter((l) => /^\d+\.\s/.test(l));
+ if (steps.length !== extension.steps.length) {
+ errors.push(`${LLM_FILE}: ${EXTENSION_SECTION} has ${steps.length} numbered steps, ${JSON_FILE} extension.steps has ${extension.steps.length}`);
+ }
+ for (const [label, key] of [["Allowed properties:", "properties"], ["Allowed keywords:", "keywords"]]) {
+ const listed = backticked(extensionMd.split("\n").find((l) => l.startsWith(label)));
+ if (listed.join(",") !== extension[key].join(",")) {
+ errors.push(`${LLM_FILE}: ${EXTENSION_SECTION} must have a "${label}" line listing extension.${key} in order`);
+ }
+ }
+ const notCovered = parseNotCovered(section(NOT_COVERED_SECTION));
+ errors.push(...notCovered.errors);
+ if (notCovered.items.length !== extension.notCovered.length) {
+ errors.push(`${LLM_FILE}: Not covered yet has ${notCovered.items.length} items, ${JSON_FILE} extension.notCovered has ${extension.notCovered.length}`);
+ }
+ notCovered.items.forEach((item, i) => {
+ const twin = extension.notCovered[i];
+ if (!twin) return;
+ const same =
+ plain(item.pattern) === plain(twin.pattern) &&
+ plain(item.use) === plain(twin.use) &&
+ item.html?.trim() === twin.html.trim() &&
+ item.css?.trim() === twin.css?.trim();
+ if (!same) errors.push(`${LLM_FILE}: Not covered yet item ${i + 1} (${item.pattern}) must match ${JSON_FILE} extension.notCovered ${i + 1}`);
+ });
+
const valid = [...section("Valid Examples").matchAll(/```html\n([\s\S]*?)```/g)].map((m) => m[1].trim());
const jsonValid = contract.examples.valid.map((e) => e.html.trim());
if (valid.join("\n\n") !== jsonValid.join("\n\n")) {
diff --git a/scripts/verify-ai-contract.test.mjs b/scripts/verify-ai-contract.test.mjs
index 511b96a..31f2243 100644
--- a/scripts/verify-ai-contract.test.mjs
+++ b/scripts/verify-ai-contract.test.mjs
@@ -1,6 +1,14 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { DEFAULT_MAX_TOKENS, estimateTokens, maxTokensFrom, readRepoFiles, verifyContract } from "./verify-ai-contract.mjs";
+import {
+ DEFAULT_MAX_TOKENS,
+ checkExtensionCss,
+ estimateTokens,
+ maxTokensFrom,
+ parseNotCovered,
+ readRepoFiles,
+ verifyContract,
+} from "./verify-ai-contract.mjs";
const repo = new URL("..", import.meta.url).pathname;
const files = readRepoFiles(repo);
@@ -189,3 +197,108 @@ test("fails when the showcase, Pages workflow or README stop publishing the cont
const readme = files.readme.replace(/same pull request/g, "next release");
assertError(errorsWith({ readme }), "same pull request");
});
+
+const appShellIndex = contract.examples.valid.findIndex((e) => e.html.startsWith("<!doctype html>"));
+const appShell = contract.examples.valid[appShellIndex];
+// Edits the app-shell example in both files so they stay in sync.
+const editAppShell = (find, replace) => {
+ assert.ok(appShell.html.includes(find), `app shell contains ${find}`);
+ return {
+ ...withJson((c) => (c.examples.valid[appShellIndex].html = appShell.html.replace(find, replace))),
+ md: files.md.replace(appShell.html, appShell.html.replace(find, replace)),
+ };
+};
+
+test("states the one extension rule in both files, at contract 1.2.0", () => {
+ const ext = contract.extension;
+ assert.equal(ext.attribute, "data-ui");
+ assert.equal(ext.layer, "synth.ext");
+ assert.match(ext.values, /tokens only/);
+ assert.ok(ext.properties.includes("padding-inline-start"));
+ for (const banned of ["display", "flex", "grid-template-columns", "gap", "margin", "position", "order"]) {
+ assert.ok(!ext.properties.includes(banned), `${banned} is not an extension property`);
+ }
+ assert.equal(contract.contractVersion, "1.2.0");
+ assert.match(files.md, /· contract 1\.2\.0 ·/);
+ assert.match(files.md, /^## When the vocabulary is missing a pattern$/m);
+ for (const phrase of ['`data-ui="<name>"`', "`@layer synth.ext", "`var(--…)`"]) assert.ok(files.md.includes(phrase), phrase);
+ assertError(errorsWith(withJson((c) => delete c.extension)), 'missing top-level key "extension"');
+ assertError(errorsWith(withJson((c) => (c.extension.layer = "ext"))), 'extension.layer must be "synth.ext"');
+ assertError(errorsWith(withJson((c) => (c.extension.attribute = "data-x"))), 'extension.attribute must be "data-ui"');
+ const md = files.md.replace(/^Allowed properties: `color`, /m, "Allowed properties: ");
+ assertError(errorsWith({ md }), 'must have a "Allowed properties:" line');
+ const steps = files.md.replace(/^4\. Add no class names.*\n/m, "");
+ assertError(errorsWith({ md: steps }), "has 4 numbered steps");
+});
+
+test("checks extension CSS: one synth.ext layer, data-ui selectors, listed properties, token values", () => {
+ const tokens = new Set(["--space-4", "--color-border", "--border-width"]);
+ const ok = checkExtensionCss('@layer synth.ext { [data-ui="x"] { padding: var(--space-4); border: var(--border-width) solid var(--color-border); } }', contract.extension, tokens);
+ assert.deepEqual(ok.errors, []);
+ assert.deepEqual([...ok.names], ["x"]);
+ const run = (css) => checkExtensionCss(css, contract.extension, tokens).errors.join("\n");
+ assert.match(run('[data-ui="x"] { padding: var(--space-4); }'), /single @layer synth\.ext/);
+ assert.match(run('@layer synth.ext { .card { padding: var(--space-4); } }'), /selector "\.card"/);
+ assert.match(run('@layer synth.ext { [data-ui="x"] .card { padding: var(--space-4); } }'), /must be \[data-ui="<name>"\]/);
+ assert.match(run('@layer synth.ext { [data-ui="x"] { display: flex; } }'), /property display is not in extension\.properties/);
+ assert.match(run('@layer synth.ext { [data-ui="x"] { padding: 16px; } }'), /"16px" is not a var\(--token\)/);
+ assert.match(run('@layer synth.ext { [data-ui="x"] { padding: var(--space-4) !important; } }'), /"!important"/);
+ assert.match(run('@layer synth.ext { [data-ui="x"] { padding: var(--space-9); } }'), /--space-9, which is not a SynthCSS token/);
+});
+
+test("has a full app-shell valid example built from contract vocabulary only", () => {
+ assert.ok(appShell, "a valid example is a full page starting with <!doctype html>");
+ const html = appShell.html;
+ assert.match(html, /<body data-ui="app">/);
+ assert.match(html, /<div class="sidebar-lg"[^>]*>\s*<nav class="panel" aria-label="Main">/);
+ assert.match(html, /<ul class="nav stack-sm" role="list">/);
+ assert.match(html, /<main class="container stack-lg">/);
+ assert.match(html, /<header class="split">[\s\S]*?class="button button-primary"[\s\S]*?<\/header>/);
+ assert.match(html, /<ul class="grid"[^>]*>\s*<li class="card">/);
+ assert.match(html, /class="sidebar-lg sidebar-end"/);
+ assert.match(html, /@layer synth\.ext \{\s*\[data-ui="app"\] \{ font-family: var\(--font-sans\);/);
+ assert.ok(files.md.includes(html));
+
+ assertError(errorsWith(editAppShell('class="card"', 'class="card stat-card"')), "uses .stat-card, which is not a SynthCSS class");
+ assertError(errorsWith(editAppShell("font-family: var(--font-sans);", "display: flex;")), "property display is not in extension.properties");
+ assertError(errorsWith(editAppShell("font-size: var(--text-base);", "font-size: 15px;")), '"15px" is not a var(--token)');
+ assertError(errorsWith(editAppShell('style="--grid-min: 12rem"', 'style="gap: 1rem"')), 'inline style "gap: 1rem" is not a token override');
+ assertError(errorsWith(editAppShell('<body data-ui="app">', '<body data-ui="shell">')), 'no element has data-ui="app"');
+ assertError(errorsWith(editAppShell('[data-ui="app"]', ".app")), 'selector ".app"');
+});
+
+test("lists every not-covered pattern with a composition or a data-ui fallback", () => {
+ const patterns = contract.extension.notCovered.map((n) => n.pattern);
+ assert.deepEqual(patterns, [
+ "Avatar or initials",
+ "Icon tile",
+ "Nav link with current state",
+ "Tabs or segmented control",
+ "Switch",
+ "Input with attached button",
+ "Narrow right column",
+ "Timeline",
+ ]);
+ for (const item of contract.extension.notCovered) {
+ assert.ok(item.html.includes('class="'), `${item.pattern} has a snippet`);
+ if (item.css) {
+ assert.match(item.html, /data-ui="[a-z-]+"/);
+ assert.match(item.css, /^@layer synth\.ext \{/);
+ } else assert.doesNotMatch(item.html, /data-ui/);
+ }
+ const { items, errors } = parseNotCovered(files.md.split("## Not covered yet")[1].split("\n## ")[0]);
+ assert.deepEqual(errors, []);
+ assert.equal(items.length, patterns.length);
+ assert.ok(items.at(-1).css.includes('[data-ui="timeline-item"]'));
+
+ const badCss = withJson((c) => (c.extension.notCovered.at(-1).css = c.extension.notCovered.at(-1).css.replace("var(--space-4)", "1rem")));
+ assertError(errorsWith(badCss), 'extension.notCovered 8 (Timeline): extension CSS padding-inline-start: "1rem"');
+ const unstyled = withJson((c) => (c.extension.notCovered[0].html = '<span class="avatar" data-ui="initials">AL</span>'));
+ assertError(errorsWith(unstyled), 'data-ui="initials" has no rule in @layer synth.ext');
+ const invented = withJson((c) => (c.extension.notCovered[2].html = '<a class="nav-link nav-link-active" href="/">Home</a>'));
+ assertError(errorsWith(invented), "uses .nav-link-active, which is not a SynthCSS class");
+ const md = files.md.replace("- Switch — ", "- Toggle — ");
+ assertError(errorsWith({ md }), "Not covered yet item 5 (Toggle) must match");
+ const dropped = files.md.replace(/^- Icon tile — .*\n/m, "");
+ assertError(errorsWith({ md: dropped }), "Not covered yet has 7 items");
+});
diff --git a/showcase/index.html b/showcase/index.html
index e25fe3d..4bb9747 100644
--- a/showcase/index.html
+++ b/showcase/index.html
@@ -1077,7 +1077,8 @@ <h2 id="ai-contract-title">AI Contract</h2>
<p class="sc-muted">
One compact file teaches a model the whole public vocabulary of SynthCSS: every
token, layout primitive, component, part and variant, an intent table, composition
- rules, ten generation rules and valid and invalid examples. Paste
+ rules, ten generation rules, one extension rule for patterns the vocabulary lacks
+ and valid and invalid examples. Paste
<code>synthcss.llm.md</code> into a prompt, or read the same contract as structured
data from <code>synthcss.ai.json</code>. Both are versioned with the framework and
checked against the CSS on every change.
@@ -1087,10 +1088,10 @@ <h2 id="ai-contract-title">AI Contract</h2>
<a class="sc-button" href="../synthcss.llm.md">View synthcss.llm.md</a>
<a class="sc-button sc-button-secondary" href="../synthcss.ai.json" download>Download synthcss.ai.json</a>
<a href="https://github.com/nabledhq/synthcss/blob/main/synthcss.llm.md">Read it on GitHub</a>
- <span class="badge badge-info">≈ 4,150 tokens</span>
+ <span class="badge badge-info">≈ 5,700 tokens</span>
</div>
<p class="sc-muted">
- Size estimated as characters ÷ 4 (about 16,600 characters), small enough for one
+ Size estimated as characters ÷ 4 (about 22,700 characters), small enough for one
context window with room to spare.
</p>
<article class="sc-card sidebar-lg">
diff --git a/synthcss.ai.json b/synthcss.ai.json
index 969b1e0..ee9ff45 100644
--- a/synthcss.ai.json
+++ b/synthcss.ai.json
@@ -1,6 +1,6 @@
{
"synthcssVersion": "0.7.0",
- "contractVersion": "1.1.0",
+ "contractVersion": "1.2.0",
"tokens": {
"--color-background": "page background",
"--color-surface": "subtle background for panels, table heads, footers",
@@ -268,13 +268,71 @@
"Build structure from layout primitives and nest them; never write custom flex or grid CSS.",
"Set spacing with the -sm / -lg gap variants, never with margins or utility classes.",
"Never use inline styles except a token override such as style=\"--grid-min: 12rem\".",
- "In any custom CSS, reference tokens with var(); never hard-code colors, px/rem sizes, shadows or durations.",
+ "Write custom CSS only by the extension rule: [data-ui] selectors inside @layer synth.ext, var() token values only; never hard-code colors, px/rem sizes, shadows or durations.",
"Put components on semantic native elements and keep one component per element.",
"Express state with attributes: disabled, checked, aria-disabled=\"true\", aria-busy=\"true\", aria-invalid=\"true\", aria-current=\"page\" (nav), aria-selected=\"true\" (tabs).",
"Pick variants by meaning, not look: button-danger for destructive actions, badge-success for success.",
"Write no media queries or breakpoint classes; primitives adapt to the space they get.",
"Keep it accessible: aria-label on .button-icon, role=\"status\" or role=\"alert\" on .alert, a <label for> on every control."
],
+ "extension": {
+ "rule": "When no class or composition fits: mark your own element with data-ui=\"<name>\" and style it only inside @layer synth.ext, with var(--…) token values only. This is the only legal custom CSS.",
+ "steps": [
+ "Compose the pattern from layout primitives and existing components first (see notCovered).",
+ "Otherwise mark the element with data-ui=\"<name>\" (lowercase, dashed) and style it only with [data-ui=\"<name>\"] selectors inside @layer synth.ext { … }.",
+ "Use only var(--…) token values; the only bare words allowed are the keywords. No px, rem, %, hex, numbers or !important.",
+ "Add no class names; data-ui is the only hook.",
+ "Do not override internals of SynthCSS classes: never select a class, and on an element that has SynthCSS classes set only properties those classes leave alone (unlayered SynthCSS rules beat synth.ext)."
+ ],
+ "attribute": "data-ui",
+ "layer": "synth.ext",
+ "values": "tokens only: every value is var(--…), optionally with the keywords; never a hard-coded length, color, shadow or duration",
+ "properties": ["color", "background", "background-color", "border", "border-color", "border-width", "border-style", "border-radius", "border-block-start", "border-block-end", "border-inline-start", "border-inline-end", "box-shadow", "padding", "padding-block", "padding-inline", "padding-block-start", "padding-block-end", "padding-inline-start", "padding-inline-end", "font-family", "font-size", "font-weight", "line-height", "inline-size", "min-inline-size", "max-inline-size", "block-size", "min-block-size"],
+ "keywords": ["solid", "none"],
+ "notCovered": [
+ {
+ "pattern": "Avatar or initials",
+ "use": ".avatar, plus .avatar-round for people",
+ "html": "<span class=\"avatar avatar-round\" aria-hidden=\"true\">AL</span>"
+ },
+ {
+ "pattern": "Icon tile",
+ "use": ".avatar with a tint variant around an <svg aria-hidden=\"true\">",
+ "html": "<span class=\"avatar avatar-accent\"><svg aria-hidden=\"true\" viewBox=\"0 0 24 24\">…</svg></span>"
+ },
+ {
+ "pattern": "Nav link with current state",
+ "use": ".nav + .nav-link, aria-current=\"page\" on the current one",
+ "html": "<ul class=\"nav stack-sm\" role=\"list\"><li><a class=\"nav-link\" href=\"/\" aria-current=\"page\">Home</a></li><li><a class=\"nav-link\" href=\"/team\">Team</a></li></ul>"
+ },
+ {
+ "pattern": "Tabs or segmented control",
+ "use": ".tabs + .tabs-item, aria-selected on every tab",
+ "html": "<div class=\"tabs\" role=\"tablist\" aria-label=\"Range\"><button type=\"button\" class=\"tabs-item\" role=\"tab\" aria-selected=\"true\">Week</button><button type=\"button\" class=\"tabs-item\" role=\"tab\" aria-selected=\"false\">Month</button></div>"
+ },
+ {
+ "pattern": "Switch",
+ "use": ".switch on a <label> around <input type=\"checkbox\" role=\"switch\">",
+ "html": "<label class=\"switch\"><input type=\"checkbox\" role=\"switch\" checked> Email alerts</label>"
+ },
+ {
+ "pattern": "Input with attached button",
+ "use": ".input-group around one <input> and a .button",
+ "html": "<div class=\"input-group\"><input type=\"search\" aria-label=\"Search\"><button type=\"submit\" class=\"button\">Search</button></div>"
+ },
+ {
+ "pattern": "Narrow right column",
+ "use": ".sidebar + .sidebar-end, width from --sidebar-width",
+ "html": "<div class=\"sidebar sidebar-end\" style=\"--sidebar-width: 18rem\"><main>…</main><aside>…</aside></div>"
+ },
+ {
+ "pattern": "Timeline",
+ "use": "fallback, a .stack of items marked data-ui=\"timeline-item\" for the rail",
+ "html": "<ol class=\"stack\" role=\"list\">\n <li class=\"stack-sm\" data-ui=\"timeline-item\"><time datetime=\"2026-10-01\">Oct 1</time><p>Ana merged #42</p></li>\n <li class=\"stack-sm\" data-ui=\"timeline-item\"><time datetime=\"2026-09-28\">Sep 28</time><p>Ben joined</p></li>\n</ol>",
+ "css": "@layer synth.ext {\n [data-ui=\"timeline-item\"] {\n border-inline-start: var(--border-width) solid var(--color-border);\n padding-inline-start: var(--space-4);\n }\n}"
+ }
+ ]
+ },
"examples": {
"valid": [
{
@@ -292,6 +350,10 @@
{
"html": "<div class=\"sidebar-lg sidebar-end\" style=\"--sidebar-width: 20rem\">\n <main class=\"stack\">\n <h1>Dashboard</h1>\n <div class=\"alert alert-info\" role=\"status\">\n <svg class=\"alert-icon\" aria-hidden=\"true\" viewBox=\"0 0 24 24\">…</svg>\n <p>Billing moves to the 1st of each month.</p>\n </div>\n <div class=\"grid\">\n <div class=\"card\">\n <div class=\"cluster-sm\"><span class=\"avatar avatar-accent\"><svg aria-hidden=\"true\" viewBox=\"0 0 24 24\">…</svg></span><h2>Revenue</h2></div>\n <p>$12,400 this month.</p>\n </div>\n <div class=\"card\">…</div>\n </div>\n </main>\n <aside class=\"panel\">\n <div class=\"panel-header\"><h2>Activity</h2></div>\n <ul class=\"panel-body stack-sm\" role=\"list\">\n <li class=\"cluster-sm\"><span class=\"avatar avatar-round avatar-sm avatar-primary\" aria-hidden=\"true\">AL</span><span>Ana merged #42</span></li>\n <li class=\"cluster-sm\"><img class=\"avatar avatar-round avatar-sm\" src=\"/ben.jpg\" alt=\"\"><span>Ben joined</span></li>\n </ul>\n </aside>\n</div>",
"note": "Dashboard: main content first, narrow column on the right; an alert with an icon, an icon tile in a card, and people as avatars."
+ },
+ {
+ "html": "<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Overview · Acme</title>\n <link rel=\"stylesheet\" href=\"synthcss.min.css\">\n <style>\n @layer synth.ext {\n [data-ui=\"app\"] { font-family: var(--font-sans); font-size: var(--text-base); color: var(--color-text); background: var(--color-surface); }\n }\n </style>\n</head>\n<body data-ui=\"app\">\n <div class=\"sidebar-lg\" style=\"--sidebar-width: 14rem\">\n <nav class=\"panel\" aria-label=\"Main\">\n <strong>Acme</strong>\n <ul class=\"nav stack-sm\" role=\"list\">\n <li><a class=\"nav-link\" href=\"/\" aria-current=\"page\">Overview</a></li>\n <li><a class=\"nav-link\" href=\"/projects\">Projects</a></li>\n <li><a class=\"nav-link\" href=\"/settings\">Settings</a></li>\n </ul>\n </nav>\n <main class=\"container stack-lg\">\n <header class=\"split\">\n <h1>Overview</h1>\n <button type=\"button\" class=\"button button-primary\">New project</button>\n </header>\n <ul class=\"grid\" role=\"list\" style=\"--grid-min: 12rem\">\n <li class=\"card\"><p>Revenue</p><strong>$12,400</strong></li>\n <li class=\"card\"><p>Active projects</p><strong>8</strong></li>\n <li class=\"card\"><p>Open issues</p><strong>23</strong></li>\n </ul>\n <div class=\"sidebar-lg sidebar-end\">\n <section class=\"card\">\n <div class=\"card-header\"><h2>Recent projects</h2></div>\n <div class=\"table-wrap\" tabindex=\"0\">\n <table class=\"table\">\n <thead><tr><th>Name</th><th>Status</th></tr></thead>\n <tbody><tr><td>Atlas</td><td><span class=\"badge badge-success\">Active</span></td></tr></tbody>\n </table>\n </div>\n </section>\n <aside class=\"panel\">\n <div class=\"panel-header\"><h2>Team</h2></div>\n <ul class=\"panel-body stack-sm\" role=\"list\">\n <li class=\"cluster-sm\"><span class=\"avatar avatar-round avatar-sm\" aria-hidden=\"true\">AL</span><span>Ana Lee</span></li>\n </ul>\n </aside>\n </div>\n </main>\n </div>\n</body>\n</html>",
+ "note": "App shell: a full page with .sidebar navigation, a .container stack-lg main area, a .split header with the main action, a .grid of stat cards and a main/side row. Body font setup uses the extension rule with tokens only."
}
],
"invalid": [
diff --git a/synthcss.llm.md b/synthcss.llm.md
index 62f7692..83c4e2d 100644
--- a/synthcss.llm.md
+++ b/synthcss.llm.md
@@ -1,6 +1,6 @@
# SynthCSS AI Contract
-Version: SynthCSS 0.7.0 · contract 1.1.0 · machine-readable twin: synthcss.ai.json
+Version: SynthCSS 0.7.0 · contract 1.2.0 · machine-readable twin: synthcss.ai.json
The complete public vocabulary of SynthCSS. Use only the classes and tokens listed here; anything else does not exist.
Load: `<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/nabledhq/synthcss@0.7.0/dist/synthcss.min.css">`
@@ -208,13 +208,62 @@ One state attribute each: current nav link `aria-current="page"`; selected tab `
2. Build structure from layout primitives and nest them; never write custom flex or grid CSS.
3. Set spacing with the -sm / -lg gap variants, never with margins or utility classes.
4. Never use inline styles except a token override such as `style="--grid-min: 12rem"`.
-5. In any custom CSS, reference tokens with `var()`; never hard-code colors, px/rem sizes, shadows or durations.
+5. Write custom CSS only by the extension rule below: `[data-ui]` selectors inside `@layer synth.ext`, `var()` token values only; never hard-code colors, px/rem sizes, shadows or durations.
6. Put components on semantic native elements and keep one component per element.
7. Express state with attributes: `disabled`, `checked`, `aria-disabled="true"`, `aria-busy="true"`, `aria-invalid="true"`, `aria-current="page"` (nav), `aria-selected="true"` (tabs).
8. Pick variants by meaning, not look: `button-danger` for destructive actions, `badge-success` for success.
9. Write no media queries or breakpoint classes; primitives adapt to the space they get.
10. Keep it accessible: `aria-label` on `.button-icon`, `role="status"` or `role="alert"` on `.alert`, a `<label for>` on every control.
+## When the vocabulary is missing a pattern
+
+There is exactly one fallback. Follow it in order; any other custom CSS breaks the contract.
+
+1. Compose the pattern from layout primitives and existing components first (see Not covered yet).
+2. Otherwise mark the element with `data-ui="<name>"` (lowercase, dashed) and style it only with `[data-ui="<name>"]` selectors inside `@layer synth.ext { … }`.
+3. Use only `var(--…)` token values; the only bare words allowed are the keywords below. No px, rem, %, hex, numbers or `!important`.
+4. Add no class names; `data-ui` is the only hook.
+5. Do not override internals of SynthCSS classes: never select a class, and on an element that has SynthCSS classes set only properties those classes leave alone (unlayered SynthCSS rules beat `synth.ext`).
+
+Allowed properties: `color`, `background`, `background-color`, `border`, `border-color`, `border-width`, `border-style`, `border-radius`, `border-block-start`, `border-block-end`, `border-inline-start`, `border-inline-end`, `box-shadow`, `padding`, `padding-block`, `padding-inline`, `padding-block-start`, `padding-block-end`, `padding-inline-start`, `padding-inline-end`, `font-family`, `font-size`, `font-weight`, `line-height`, `inline-size`, `min-inline-size`, `max-inline-size`, `block-size`, `min-block-size`.
+Allowed keywords: `solid`, `none`.
+Never `display`, flex, grid, `gap`, `margin`, `position` or `order`: layout comes from the primitives.
+
+```css
+@layer synth.ext {
+ [data-ui="<name>"] { padding-inline-start: var(--space-4); }
+}
+```
+
+## Not covered yet
+
+Patterns generators tend to invent classes for. Use the composition; only a fallback uses `data-ui`.
+
+- Avatar or initials — `.avatar`, plus `.avatar-round` for people: `<span class="avatar avatar-round" aria-hidden="true">AL</span>`
+- Icon tile — `.avatar` with a tint variant around an `<svg aria-hidden="true">`: `<span class="avatar avatar-accent"><svg aria-hidden="true" viewBox="0 0 24 24">…</svg></span>`
+- Nav link with current state — `.nav` + `.nav-link`, `aria-current="page"` on the current one: `<ul class="nav stack-sm" role="list"><li><a class="nav-link" href="/" aria-current="page">Home</a></li><li><a class="nav-link" href="/team">Team</a></li></ul>`
+- Tabs or segmented control — `.tabs` + `.tabs-item`, `aria-selected` on every tab: `<div class="tabs" role="tablist" aria-label="Range"><button type="button" class="tabs-item" role="tab" aria-selected="true">Week</button><button type="button" class="tabs-item" role="tab" aria-selected="false">Month</button></div>`
+- Switch — `.switch` on a `<label>` around `<input type="checkbox" role="switch">`: `<label class="switch"><input type="checkbox" role="switch" checked> Email alerts</label>`
+- Input with attached button — `.input-group` around one `<input>` and a `.button`: `<div class="input-group"><input type="search" aria-label="Search"><button type="submit" class="button">Search</button></div>`
+- Narrow right column — `.sidebar` + `.sidebar-end`, width from `--sidebar-width`: `<div class="sidebar sidebar-end" style="--sidebar-width: 18rem"><main>…</main><aside>…</aside></div>`
+- Timeline — fallback, a `.stack` of items marked `data-ui="timeline-item"` for the rail
+
+```html
+<ol class="stack" role="list">
+ <li class="stack-sm" data-ui="timeline-item"><time datetime="2026-10-01">Oct 1</time><p>Ana merged #42</p></li>
+ <li class="stack-sm" data-ui="timeline-item"><time datetime="2026-09-28">Sep 28</time><p>Ben joined</p></li>
+</ol>
+```
+
+```css
+@layer synth.ext {
+ [data-ui="timeline-item"] {
+ border-inline-start: var(--border-width) solid var(--color-border);
+ padding-inline-start: var(--space-4);
+ }
+}
+```
+
## Valid Examples
Page: container + stack, split header with nav, tabs filter beside the main action, grid of cards with a status badge.
@@ -316,6 +365,65 @@ Dashboard: main content first, narrow column on the right; an alert with an icon
</div>
```
+App shell: a full page with .sidebar navigation, a .container stack-lg main area, a .split header with the main action, a .grid of stat cards and a main/side row. Body font setup uses the extension rule with tokens only.
+
+```html
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Overview · Acme</title>
+ <link rel="stylesheet" href="synthcss.min.css">
+ <style>
+ @layer synth.ext {
+ [data-ui="app"] { font-family: var(--font-sans); font-size: var(--text-base); color: var(--color-text); background: var(--color-surface); }
+ }
+ </style>
+</head>
+<body data-ui="app">
+ <div class="sidebar-lg" style="--sidebar-width: 14rem">
+ <nav class="panel" aria-label="Main">
+ <strong>Acme</strong>
+ <ul class="nav stack-sm" role="list">
+ <li><a class="nav-link" href="/" aria-current="page">Overview</a></li>
+ <li><a class="nav-link" href="/projects">Projects</a></li>
+ <li><a class="nav-link" href="/settings">Settings</a></li>
+ </ul>
+ </nav>
+ <main class="container stack-lg">
+ <header class="split">
+ <h1>Overview</h1>
+ <button type="button" class="button button-primary">New project</button>
+ </header>
+ <ul class="grid" role="list" style="--grid-min: 12rem">
+ <li class="card"><p>Revenue</p><strong>$12,400</strong></li>
+ <li class="card"><p>Active projects</p><strong>8</strong></li>
+ <li class="card"><p>Open issues</p><strong>23</strong></li>
+ </ul>
+ <div class="sidebar-lg sidebar-end">
+ <section class="card">
+ <div class="card-header"><h2>Recent projects</h2></div>
+ <div class="table-wrap" tabindex="0">
+ <table class="table">
+ <thead><tr><th>Name</th><th>Status</th></tr></thead>
+ <tbody><tr><td>Atlas</td><td><span class="badge badge-success">Active</span></td></tr></tbody>
+ </table>
+ </div>
+ </section>
+ <aside class="panel">
+ <div class="panel-header"><h2>Team</h2></div>
+ <ul class="panel-body stack-sm" role="list">
+ <li class="cluster-sm"><span class="avatar avatar-round avatar-sm" aria-hidden="true">AL</span><span>Ana Lee</span></li>
+ </ul>
+ </aside>
+ </div>
+ </main>
+ </div>
+</body>
+</html>
+```
+
## Invalid / Discouraged Examples
Never generate these. Each line: wrong markup — why — what to use instead.
No comments yet.