Files
WRNexusJS/docs/plans/2026-10-19-design-system-phase-5-implementation.md

68 lines
9.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Phase 5 — Guided generation and decision locks
Date: 2026-10-19. Delivered on the Phase 4 Studio, existing engine and 104 contracts. No existing component, theme, compiler or application API is replaced.
## Guided workflow
The Studio adds a Guided design editor with three progressive steps: product/audience; tone, geometry, density and surface choices; then fixed brand color, references and constraints. Geometry choices have visual examples. Reference URLs are recorded as text and never fetched.
Generate three directions stages three complete validated design systems on identical composed preview content. Every candidate has a rationale, changed paths and an isolated real-component preview. Review shows before/after values. Accepting a candidate creates a normal recoverable Studio revision. Applying to an application remains the existing separate Review & apply flow.
Users can mix named color, geometry, typography, spacing and elevation decisions from the alternatives. A combination passes schema, recipe and lock validation again before becoming a reviewed proposal. Mixing is scoped to the preset foundation vocabulary and core rotation decisions, not arbitrary markup or external assets.
Edit with words stages one proposal. Local examples include rounded controls, compact/spacious spacing, flat/soft/hard shadows, serif/sans-serif/monospace typography, and primary color in #RRGGBB form. Multiple supported clauses can be joined with “and”, commas or semicolons. An unsupported clause rejects the whole edit; it never silently applies the recognized portion. Local geometry/density commands affect shared base foundations; existing mode/density overrides can still take precedence. Exact component-only edits remain available in the recipe editor or through a configured LLM patch.
## Local rules and optional LLM provider
The default is explicitly labeled **local rules**. It uses deterministic preset-based visual choices and brand values. Product, audience and free-form reference/constraint prose are retained as context; local rules do not claim to interpret that prose. Locked decisions override conflicting brief choices. When locks prevent three distinct candidates, generation reports the conflict instead of fabricating alternatives.
The actual `@wrnexus/ai` implementation was audited: it exports provider adapters with `generate`, signals, model selection and result metadata. The Studio uses that provider interface through a server-only adapter; it does not assume README defaults or structured-output claims guarantee a valid document.
To opt into the existing Anthropic adapter, set `ANTHROPIC_API_KEY` on the server and start:
```sh
bun run design:studio --ai-model <explicit-provider-model-id>
```
`--app-root` can be combined with this flag. The launcher requires an explicit model and server key; it does not pick a changing/default model. Other existing `AIProvider` adapters can be injected with `createStudioHandler({ generationProvider, generationModel })` from the Studio server entry. There is no automatic fallback between providers or from a failed LLM response to local rules.
The Studio displays the configured provider/model and transmission scope. Only pressing Generate/Propose sends the source system, brief, locks and compact contract capabilities to that provider. Credentials stay in server configuration and are not included in drafts, previews, generation reports or browser configuration. No provider requests were made during implementation verification; transport was tested with deterministic fixtures.
## Validation, repair and budgets
Provider output is a data-only JSON proposal envelope containing at most 48 set/remove JSON-pointer operations per alternative. It cannot submit executable components, arbitrary CSS, tools or unsupported schema fields. Contract context contains reusable property profiles, named parts, accepted axes and states. Each complete candidate is reconstructed, validated for all engine modes/densities and checked against locks before it is exposed as an alternative.
The configured provider gets a 4096-token output budget per attempt by default; the generation API supports 256–8192. A batch has at most two attempts: an initial request and one diagnostic repair. Transport errors are not repaired/retried and their raw messages are not exposed. Total output budget is therefore at most twice the per-attempt limit, not a dollar/cost estimate. Input context is capped at 180,000 characters plus the fixed instruction template; provider response text is capped at 100,000 characters. HTTP JSON bodies remain capped at 2 MB.
Generation has a 20-second deadline covering both attempts; the API permits bounded test/host overrides of 10–60,000 ms. Abort signals reach the provider, and an abort race releases the caller even if a provider ignores its signal. Cancellation cannot guarantee that an external service stops its own computation/billing; late results are never applied. At most two generation requests run concurrently per Studio handler.
Provenance records the source revision, exact brief, locks, instruction, provider/model, prompt-template version, attempt count, output budget and timestamp. Generation reports contain complete candidate specifications so they can be inspected independently of the live service. Canonical application exports remain the unchanged engine schema and require no Studio or AI runtime.
## Locks and recovery
Decision locks are JSON pointers to canonical decisions. Foundation group buttons cover the preset color, geometry, typography, spacing and elevation decisions; individual pointers can protect a token, mode/density override, recipe or part property, including an absent optional decision. Pointers handle literal dotted token names and reject unsafe/prototype paths.
Locks protect raw values and effective referenced token values across available modes/densities. A token alias, mode override or underlying recipe token cannot silently bypass a lock. Local alternatives preserve the dependencies needed by a locked decision; provider patches must satisfy locks without silently rewriting their output. Checks are bounded to 128 distinct pointers and 128 mode/density configurations. These are authoring constraints, not access control over a caller that intentionally changes its own lock preferences.
Manual canonical edits, structured editors, imports, proposal acceptance and undo/redo all retain lock checks. An invalid or lock-violating source stays in raw history while the last valid preview is preserved. Explicitly unlocking can recover that raw edit into a valid draft. Lock preferences are independent of undo history, and are saved alongside the Studio state; older Phase 4 drafts restore with no locks. Canonical JSON intentionally excludes Studio lock/provenance metadata; the generation report carries it separately.
A SHA-256 revision of the canonical source and sorted locks binds every batch to its base. Changes to source or locks, or to the active guided brief in the UI, invalidate acceptance and mixing until the user regenerates; old proposals remain inspectable/exportable. Accepting a proposal never writes application files. Provider failures, invalid repairs, cancellation and stale responses preserve the canonical draft and prior valid proposals.
The brief, last completed batch and instruction autosave separately from canonical history, with corruption/quota reporting. Up to three complete alternatives are retained. Generation never commits partial streamed output. Reload restores the brief, candidates, source and locks; stale candidates still require regeneration. Multiple browser tabs remain independent local workspaces without collaborative merge.
## Verification
- **374 passing tests, zero failures**, 34 files, 7,049 assertions across Studio, engine, CLI, styles, UI, SSR and theme runtime.
- Studio TypeScript source/test/launcher check, targeted lint and formatting pass.
- New tests cover distinct complete directions; brand/shape/density/surface choices; direct, alias, mode and recipe dependency locks; raw-edit/reload/unlock recovery; supported/unsupported word edits; valid combinations; stale source and lock revisions; bounded repair and output patches; malicious paths/values; deadlines/cancellation; provider-error redaction and generation HTTP metadata/origin enforcement.
- Native browser generated three alternatives with distinct fonts/radii on identical content while retaining a locked primary color in every candidate. The original draft stayed unchanged until acceptance.
- Native browser accepted a direction, proposed/accepted a word edit, restored brief/20 color locks/alternatives after reload, rejected a locked shape edit while retaining the previous proposal, and rejected stale acceptance after changing the source. Fresh regeneration recovered the workflow.
- Native browser combined rounded geometry from one alternative and typography from another, reviewed the exact differences, accepted it as a normal draft revision, and applied a validated bundle only to `output/design-system-phase-5/application-demo`.
- Provider integration was exercised with fixtures, including a provider that ignores abort, invalid JSON followed by a valid repair, and repeated lock/property violations. A paid/live provider call was not run. Broader prose quality therefore depends on the configured provider and is not certified by local-rule tests.
Evidence and screenshots are under `output/design-system-phase-5`. Phase 4's preview isolation and current provider/native component limitations continue to apply. Existing APIs and visual baselines outside Studio remain untouched by this phase; unrelated workspace-wide drift is not accepted by a wholesale refresh.
## Next scope
Phase 6 remains MCP operations, reusable agent generation context and conformance/evaluation. This phase provides the Studio generation pipeline and server provider seam, not public agent mutation tools. Collaborative storage, publication, migrations and organization workflows remain later phases.