Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

docs(spec): define authoring-time palette generation (#5986)

rubyycheung5efaf018211b
diff --git a/docs/specs/AST-008/spec.md b/docs/specs/AST-008/spec.md
new file mode 100644
index 0000000000..8948b43d07
--- /dev/null
+++ b/docs/specs/AST-008/spec.md
@@ -0,0 +1,345 @@
+---
+schema_version: 1
+template_version: 1
+kind: system-spec
+id: spec:AST-008
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+phase: proposed
+owners: [cixzhang, rubyycheung, imdreamrunner]
+affects_architecture:
+ [architecture:theme-authoring-contract, architecture:theme-compilation]
+affects_families: []
+affects_contributing: []
+affects_consumer_docs: [color, theme]
+---
+
+# Authoring-time tonal palette generation system spec
+
+## Intent
+
+Theme authors need a repeatable way to make complete tonal palette candidates.
+Generation is authoring work: it produces colors for people to inspect, adjust,
+and accept. The accepted result is saved as a private, theme-owned palette file.
+A theme may explicitly reference reviewed values from that committed file, but
+ordinary theme builds do not rerun the generator.
+
+Current `main` has an experimental Palette Generator Lab. It compares candidate
+recipes, complete families, modes, anchors, and existing themes, then lets an
+author copy candidate JSON. The latest OKLCH implementation is the visual basis
+for the first production recipe. This record freezes that intent before a
+follow-up extracts it into supported tooling. AST-018 separately proposes the
+shape, ownership, and validation boundary for accepted palette data.
+
+The first supported consumer is the Astryx CLI's theme-authoring workflow. This
+record accepts a pure `generateTonalPalette()` authoring API and the
+`astryx theme palette generate` command. Both use one versioned engine and remain
+outside Core theme normalization and runtime behavior.
+
+## Non-goals
+
+- Add palette data, generation, or mapping to `DefineThemeInput`, `DefinedTheme`,
+ `defineTheme`, `expandColorScale`, runtime mounting, or theme compilation.
+- Require generated palettes or provenance for hand-authored or imported data.
+- Define palette shape, validation, association, inheritance, or artifacts.
+- Make a palette stop a semantic token, live lookup, design approval, or
+ accessibility guarantee.
+
+## Ownership
+
+| Owner | Contract |
+| -------------------------- | -------------------------------------------------------------------------------------------------------------------- |
+| AST-008 | Candidate generation needs, recipe reproducibility, and the candidate-to-acceptance boundary. |
+| Ruby | The visual recipe and recommendation, after the required comparison evidence. |
+| AST-018, if accepted | Accepted palette shape, ownership, validation boundary, and separation from runtime themes. |
+| `theme:<name>` | Accepted exact palette values, saved mappings and deviations, required states, compatibility, and rendered evidence. |
+| Current theme architecture | Productive `defineTheme` normalization and compilation; AST-008 does not change them. |
+| CLI authoring surface | The generation command, pure API, candidate serialization, receipts, and safe writes. |
+
+## Authoring lifecycle
+
+| Stage | Required result |
+| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
+| Create | Generate, hand-author, or import a complete candidate palette. |
+| Review | Inspect complete families, modes, diagnostics, comparisons, and rendered contexts; adjust or reject freely. |
+| Accept | Save the final exact palette data as a reviewed snapshot under the accepted palette contract. |
+| Suggest, optional | Produce a read-only candidate mapping from accepted palette data to one explicit theme role. |
+| Save mapping | After human acceptance, save a literal CSS color or an intentional reference to its exact committed palette value. |
+| Verify | Record contextual evidence for the exact saved values in the owning theme record. |
+
+## Requirements
+
+- **FR1 — Generation is optional.** Generated, hand-authored, and imported
+ palettes are equal after validation. Missing generation provenance means only
+ “not generated by this recipe”; it MUST NOT make valid palette data invalid.
+- **FR2 — Requests describe complete author intent.** A generation request MUST
+ describe the complete family set; normalized seeds; versioned intensity and
+ neutral profiles; exact, bounded, and flexible anchors; an explicit stop
+ layout; light and dark strategy; target gamut and encoding; and every other
+ output-affecting parameter. Astryx tooling SHOULD default family ramps to the
+ 21-stop `0, 5, …, 100` layout, while accepting any non-empty author-defined
+ numeric stop list. Compact and specialized layouts are valid author choices,
+ not exceptions. Stops 0 and 100 resolve to exact black and white in generated
+ families. Authors MAY omit those repeated endpoints with a custom stop list.
+- **FR2a — Custom stop syntax is exact.** Every stop MUST be a finite JSON number
+ from 0 through 100 inclusive. Stops MUST be unique and strictly increasing.
+ Integer and decimal stops are valid; equivalent numeric spellings such as `5`
+ and `5.0` identify the same stop and therefore cannot coexist. Endpoints 0 and
+ 100 are optional. A one-stop palette is valid. Serialization uses the canonical
+ JSON number spelling produced by the implementation and MUST NOT depend on
+ locale.
+- **FR2b — Stop numbers are stable coordinates.** For the same recipe, family,
+ mode, seed, vibrancy, profile, and compatible anchors, a shared stop MUST
+ produce the same exact color in compact, full, and custom layouts. Adding or
+ removing other stops MUST NOT renumber or change it. Generated TypeScript MUST
+ expose only the requested stop keys, so an omitted stop fails type checking.
+- **FR3 — Mode intent is explicit.** Light-only, dark-only, independent light and
+ dark inputs, shared candidates, and named dark transforms are distinct. A
+ light ramp MUST NOT silently become a reviewed dark ramp, and labels MUST NOT
+ be reversed for dark mode.
+- **FR4 — Constraints and preferences stay distinct.** Gamut validity,
+ monotonicity, exact anchors, and bounded-anchor tolerances are hard constraints.
+ Intensity, optical balance, and flexible anchors are optimization preferences.
+ A conflict MUST fail clearly rather than moving an exact anchor, weakening a
+ tolerance, substituting a profile, or changing the stop layout. An anchor MUST
+ NOT turn stop 0 or 100 into a chromatic value; a conflicting endpoint anchor
+ fails with guidance to use an interior stop.
+- **FR5 — Recipes are deterministic and versioned.** A recipe identity MUST pin
+ color space, constants, profiles, schedules, anchors, gamut handling, precision,
+ rounding, serialization, and tie-breaking. The same normalized request MUST
+ produce byte-identical canonical candidate output across supported platforms,
+ with no ambient time, locale, path, network, randomness, traversal, or
+ unrecorded dependency input.
+- **FR6 — Generated candidates carry reproducibility evidence.** The generator
+ MUST emit the complete candidate plus a detached record naming the normalized
+ request, recipe and implementation versions, output format versions,
+ adjustments, deviations, and every canonical output digest. An output change
+ MUST change a matching identity or digest.
+- **FR7 — Generation stops at a candidate.** Output MUST identify itself as a
+ candidate and MUST NOT adopt values, map roles, or claim visual or accessibility
+ approval. Preview is read-only. An explicit output option MAY save the candidate
+ as a separate TypeScript or JSON file, but MUST NOT overwrite an existing file
+ without explicit author intent. Once adopted, the palette is ordinary
+ author-owned data: it may be edited freely and does not remain under generator
+ control. Edited accepted data MUST NOT claim exact regeneration, and ordinary
+ theme builds MUST NOT rerun the generator.
+- **FR8 — The selected recipe preserves complete-family evidence.** The first
+ production recipe MUST preserve the intended results of
+ `apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.ts` at
+ repository commit `d77fd8b43bc3f40dd80e605248fd87c20ccdc03c` rather than
+ reopening the OKLCH-versus-HCT visual decision.
+ Before release, its version-pinned evidence MUST cover complete family sets,
+ rendered light/dark contexts, hue continuity, luminance and adjacent-stop
+ distinction, gamut, family balance, CVD simulations, reproducibility, and
+ performance. Fixtures cover blue-to-purple, yellow-to-brown, disproportionate
+ family strength, and blue/purple, yellow/green, and red/orange distinction.
+ Output remains a candidate until an author accepts it.
+- **FR9 — Mapping suggestions are future read-only assistance.** If proposed, a
+ suggestion MUST take an accepted palette artifact and digest, explicit mode and
+ role, current saved value, and versioned method. It returns an inspectable
+ family, stop, exact color, rationale, and measured differences without editing.
+ A separate explicit apply action shows the target and patch, preserves author
+ edits, saves a literal CSS value or an intentional committed-palette reference,
+ and permits adjustment or rejection.
+- **FR10 — Regeneration never recolors themes implicitly.** Generating a new
+ candidate MUST NOT replace an adopted palette or change saved theme values,
+ normalized tokens, CSS, built runtime modules, or mounted behavior. A committed
+ palette edit MAY intentionally change theme mappings that explicitly reference
+ it; that source diff and its rendered impact MUST be reviewed together.
+- **FR11 — Validation is separate from construction.** Palette inspection uses a
+ `validate*` or `check*` role in theme-package tests, internal test utilities, or
+ an explicitly accepted future CLI checker. Validation-only data and helpers
+ MUST stay outside Core runtime theme input and output.
+- **FR12 — Accessibility is contextual.** Tools MAY report measured properties
+ and contrast for explicit pairs. They MUST NOT label an isolated palette,
+ family, stop, or suggestion accessible. Theme evidence names the exact
+ foreground, background, text size, component state, mode, and non-color cues.
+- **FR13 — Authoring has no runtime cost.** Generator code, color-math
+ dependencies, candidates, reproducibility data, and suggestion logic MUST NOT
+ enter Core component runtime, theme mounting, default theme CSS or JavaScript,
+ or a theme package's default runtime export.
+- **FR14 — The supported surfaces stay narrow.** `generateTonalPalette(request)`
+ is a pure authoring function that returns candidate data without reading or
+ writing files. `astryx theme palette generate <config>` is its non-interactive
+ file adapter. TypeScript is the primary committed output so exact family and
+ stop keys remain checkable; JSON MAY be requested for interoperable tooling.
+ Neither surface changes `defineTheme()` or performs semantic mapping.
+- **FR15 — Visual review uses one standard artifact.** The CLI MAY explicitly
+ write a self-contained HTML preview from the same candidate data. The preview
+ MUST identify itself as `palette-preview-v1`, show every generated family,
+ mode, stop, and hex value, and require no network resources. It MUST NOT make
+ an accessibility claim. It follows the same overwrite protection as palette
+ output and MUST NOT open a browser without a separate explicit action.
+- **FR16 — Authoring guidance preserves intent.** Agent-facing documentation and
+ evaluation fixtures MUST distinguish exact, bounded, and flexible anchors;
+ preserve explicit decimal and custom layouts; omit an accent when none is
+ requested; and ask whether an ambiguous accent is one theme value or a light
+ and dark family rather than guessing.
+
+## Implementation contract
+
+1. The implementation PR pins the current Sandbox OKLCH behavior as
+ `astryx-oklch-v1`, copies its constants and transformations into one owned
+ engine, and adds exact regression vectors. The Sandbox remains a prototype,
+ not the production import path.
+2. The pure authoring API and CLI adapter use one deterministic engine and agree
+ on recipe semantics. The CLI follows `architecture:cli-surface` for its
+ command, response, error, documentation, support, and write contract.
+3. Generated TypeScript exports author-owned palette data without importing the
+ generator. Generated JSON contains the same canonical palette values.
+4. The optional HTML preview is generated by one versioned renderer rather than
+ improvised by each agent or caller.
+5. Every public function, command, package, schema, or artifact receives separate
+ API and AST-017 compatibility acceptance before release.
+6. Focused agent fixtures cover anchor language, optional accents, clarification,
+ and custom stops. Expected decisions remain evaluation-only and MUST NOT be
+ included in prompts sent to agents.
+
+### `astryx-oklch-v1` normative recipe
+
+The first production recipe is defined here rather than by mutable Sandbox code:
+
+- Normalize supported seed and anchor colors to lowercase six-digit sRGB hex.
+- Convert sRGB through the standard D65 OKLab matrices, then express hue and
+ chroma in OKLCH.
+- Convert requested tone to lightness with the CIELAB L* transfer: values above
+ 8 use `((tone + 16) / 116)³`; lower values use `tone / 903.3`; the result is
+ cube-rooted for OKLab lightness.
+- Apply the pinned tone chroma envelope
+ `0.18 + 0.82 × sqrt(sin(π × tone / 100))`.
+- Apply hue-balance factors 0.94 for `[70,115)`, 0.78 for `[115,175)`, 0.82 for
+ `[175,230)`, 0.90 for `[285,340)`, and 1 elsewhere. Orange hues `[40,70)`
+ rotate toward red below tone 50 by at most 8 degrees so low orange stops stay
+ distinct from the red family.
+- Above tone 60, green hues `[115,175)` taper to 72% of their balanced chroma
+ and teal hues `[175,200)` taper to 60% at tone 95 using smoothstep. This keeps
+ their light stops optically balanced without muting cyan or changing the
+ midtone anchors.
+- Vibrancy 50 is neutral. Values 0–25 interpolate to multiplier 0.72; values
+ 25–50 interpolate from 0.72 to 1; values above 50 add 0.0096 per point.
+- Cross-family coordination mixes source chroma 35% with reference chroma 0.18
+ at 65%. Neutral profiles are `neutral-v1` (hue 0, chroma 0), `warm-v1`
+ (hue 75, chroma 0.018), `cool-v1` (hue 250, chroma 0.018), and `custom`
+ (the normalized neutral seed).
+- Stop numbers retain the same literal tone meaning in both modes. Dark ramps
+ multiply chroma by 0.85 without silently shifting the requested tone. Stop 0
+ therefore resolves to exact black in either mode, and stop 100 resolves to
+ exact white. Both endpoints are included by default and MAY be omitted by an
+ explicit custom layout.
+- Out-of-gamut OKLCH candidates preserve lightness and hue while chroma is found
+ by 20 iterations of binary search over `[0, 0.4]`.
+- Exact anchors replace their stop. Bounded anchors move toward the requested
+ color only within their declared OKLab Euclidean `maxDeltaE`; flexible anchors
+ blend 35% toward the requested color. Anchor corrections use smoothstep
+ interpolation and taper to zero 25 tone units beyond the nearest anchor.
+- Convert final colors to sRGB by rounding each clamped channel to the nearest
+ 8-bit integer. Emit lowercase `#rrggbb`. Canonical JSON uses two-space
+ indentation, insertion-ordered families and stops, and one trailing newline.
+- Invalid requests fail before producing a candidate. Family-local anchor
+ conflicts report the family and produce no adoptable output.
+
+The following canonical candidate fixtures use SHA-256 over UTF-8 canonical JSON:
+
+| Fixture | Request summary | Candidate bytes | SHA-256 |
+| ---------------------- | ---------------------------------------------------------------------------------------------- | --------------: | ------------------------------------------------------------------ |
+| `default-three-family` | Neutral `#777777`, blue `#0074e2`, orange `#d57113`; both modes; vibrancy 50; 21 default stops | 3527 | `78ca5bd2afe44d448dc7fd2889196c5a562a9d1f1ff8efcccc67aa1d8a94b76c` |
+| `exact-anchor` | Blue `#0074e2`; light only; stops 20, 50, 80; exact stop-50 anchor `#1682d5` | 242 | `e3dbd30b3eb1e4c2a0350e1321ef44bf16c3ae48ac46ada0dad04368cdd6e4a1` |
+| `single-custom-stop` | Red `#d62830`; dark only; stop 40 | 189 | `d54fe4d202d7bd49f8a286e97eadf9786fe71e21f15e0058975877581b7e025b` |
+| `high-tone-balance` | Green `#358a3a`, teal `#0c7365`, cyan `#0c6f82`; both modes; stops 60, 80, 95 | 825 | `991080568a4e1c1a4b1b23e1d9908fcdd688607aac6be4c55cd216b74ebe7c3d` |
+
+Exact fixture equality is the release gate for recipe compatibility. Monotonicity,
+adjacent-stop distance, hue drift, family distinction, gamut events, and CVD
+simulations are recorded as design evidence for the complete candidate; they do
+not become universal accessibility or contrast guarantees for isolated colors.
+
+## Current-state impact
+
+| State | Required result |
+| ----------------------- | ------------------------------------------------------------------------------------------------- |
+| Generation absent | Existing themes, builds, runtime bytes, and supported package ranges stay unchanged. |
+| Candidate produced | No source, theme, package, or runtime output changes. |
+| Palette accepted | Exact values enter the AST-018-owned shape, if accepted; the theme record owns adoption evidence. |
+| Suggestion produced | Source and output stay unchanged. |
+| Mapping accepted | One reviewed patch saves explicit values; failure leaves no partial edit. |
+| New candidate generated | Adopted palettes and rendered output stay unchanged until an explicit review and save. |
+| Adopted palette edited | Literal mappings stay unchanged; explicit references change intentionally and are reviewed. |
+
+## Verification
+
+Verification MUST cover cross-platform deterministic vectors; hard failures;
+every candidate source and provenance state; complete-family regression/CVD
+evidence; candidate-versus-accepted identity; optional atomic suggest/apply;
+runtime/default-bundle absence; and real-Chromium evidence for accepted mappings.
+
+This specification-only pull request changes no runtime, build, theme, or package
+behavior and carries no Changeset.
+
+## Decision log
+
+### DEC-5 and DEC-9 — Preserve complete-recipe evidence
+
+**Decider:** `cixzhang`, `2026-09-01` through `2026-09-02`
+
+FR8 preserves Ruby's complete-authoring requirements and the comparison evidence
+behind the selected OKLCH direction. A color-space name or isolated ramps alone
+do not define the production recipe.
+
+### DEC-10 — Accepted palettes are committed snapshots
+
+**Decider:** `cixzhang`, `2026-09-03`
+
+FR7, FR9, and FR10 replace former draft DEC-8 and its palette-aware
+`defineTheme` / `expandColorScale` direction. Accepted palettes are committed
+snapshots. Theme mappings use literal CSS values or explicit references to those
+snapshots; generation never runs implicitly. OQ3 is removed with the rejected
+automatic mapping and runtime coupling.
+
+### DEC-11 — Generation has one authoring engine and two adapters
+
+**Decider:** `cixzhang`, `2026-09-03`
+
+The CLI theme-authoring workflow is the first supported consumer. The pure
+`generateTonalPalette()` API enables programmatic authoring without filesystem
+effects; `astryx theme palette generate` adds preview and explicit file output.
+Both use the same `astryx-oklch-v1` engine. Neither enters Core or `defineTheme()`.
+
+### DEC-12 — The generator defaults without restricting palette authors
+
+**Decider:** `rubyycheung`, `2026-09-03`
+
+The first production generator defaults each family to the familiar 21-position
+`0, 5, …, 100` layout and accepts any explicit non-empty numeric stop list.
+Stops 0 and 100 repeat exact black and white in each generated family so authors
+can retain a complete coordinate range or remove the endpoints explicitly. The
+generated candidate becomes author-owned after review and acceptance. Generator
+defaults therefore do not become palette-validity rules.
+
+Generated palettes are reviewable starting points. Authors may adjust
+family-level inputs and regenerate until the palette matches their intended
+expression; only the explicitly approved output becomes the theme-owned palette.
+
+Rejected: requiring every accepted palette to use the generator's 21-stop
+default. Themes may need compact or specialized palettes for iconography,
+illustration, visualization, or brand expression.
+
+### DEC-13 — Intermediate stops are generated explicitly
+
+**Deciders:** `cixzhang`, `rubyycheung`, `2026-09-03`
+
+Compact and full presets share the same 0–100 tonal coordinate system, and
+custom layouts remain valid. An author who needs an intermediate value such as
+12.5 requests that stop during generation and reviews the emitted exact hex.
+The committed TypeScript then exposes `family[12.5]` as an actual typed key.
+
+Rejected: restricting palette authors to two stop counts, renumbering stops when
+the layout changes, or adding a runtime `family.get(12.5)` that creates an
+unreviewed color after authoring.
+
+## Open questions
+
+None. The implementation PR must still pin and verify the exact recipe before it
+becomes a supported public tool; that is implementation evidence, not an open
+visual-direction decision.