Skip to Content
StudioThe Studio of TwoUse CasesDesign to Code

Design to Code

ScenarioCorporate UX & Universal Design System
StatusIn progress (Phase 3)
Timeline2025 - June 2026

Deep Dive: Treating AI Context as a Budget

A deep dive into the design-to-code pipeline, context engineering, and the pursuit of a universal design system.
Generated with NotebookLM based on Luis's technical documentation
0:000:00

This is a living record. It documents an ongoing use case - not a completed experiment, but an active exploration that will continue to evolve as each phase is implemented, validated, and extended.

The scenario: A UX designer working within a large corporate environment, with access to Figma and AI tooling but without dedicated development resources - dev team is fully booked in deliveries. The ambition is not to generate a component library - it is to build an automated pipeline that powers a universal design system spanning web, mobile, and embedded surfaces. Figma is the available tool, not the chosen one. The constraints are the environment.

The problem being solved: The gap between design intent and running component has always required translation through other people. The Studio of Two closes that gap - but only if the AI’s context window receives high-signal, low-noise input. Raw Figma extraction fails that requirement. This use case is the ongoing record of building a pipeline that meets it.

The expected outcome: A deterministic, self-healing pipeline that translates Figma designs into multi-platform runtime specs, optimised for design intent preservation and token economy. The resulting component library is a byproduct of the pipeline’s operation, not the primary goal - making the design-to-code process faster, more reliable, and higher quality, while enabling rapid prototyping and earlier tests with close-to-production components.

Read the personal journey: Horizon - The Thing I Was Always Building.


Current State

Phase 1 - Complete. The extraction-to-component pipeline is defined and operational, running on macOS as the primary execution environment. Quality contracts are established at each gate (covering manifest, specification schema, fallback logic, and token implementation conformance). The native MCP refactor is complete - wrapper scripts replaced by first-class pipe nodes. The correction feedback loop is live.

Phase 2 - Complete. Branch-aware conditional routing (validator nodes with branches) is fully rolled out. Pre-handshake banner tolerance is fully supported for non-conformant MCP servers.

Phase 3 - In progress. Expanding the pipeline beyond Figma toward the universal design system - web, mobile, and embedded surfaces under one token vocabulary - is the active sprint target.


Phase 1: Establishing the Pipeline

Objective: Define a reliable extraction-to-component pipeline with explicit quality gates. Status: Complete


The Landscape: Why Build This?

Several tools already address design-to-code generation. Figma has native Dev Mode and code export built in. Claude Code, Lovable, Google Stitch, and others can take a design and produce a working component with impressive speed. The Figma MCP server itself provides direct API access from within an AI agent context.

These tools are genuinely valuable. They are optimised for a specific outcome: speed to a working component. You provide the design, and the tool generates something that renders.

This pipeline is optimised for a different outcome: design intent preservation at scale - building a universal design system where the same design decision generates reliable, parity-accurate components across multiple platforms and runtimes, with a compounding knowledge base that improves with every correction.

The distinction matters in practice:

  • Most generation tools are black boxes - you cannot inspect what context reaches the model, cannot apply correction rules, cannot build an auditable artifact trail.
  • Most are optimised for one-shot generation, not for a pipeline that runs hundreds of times across a growing component library.
  • Most assume full access to the design system’s variable definitions - which, as the next section describes, is not always the case in a constrained corporate environment.
  • Most run without regard for token economy, resulting in high operational costs at scale. This pipeline focuses on token compression to support an automated, self-sufficient workflow. It is flexible enough to avoid lock-in to any specific vendor or framework, yet robust and reliable enough to execute, validate, and self-heal. This delivers a direct return on investment (ROI) by producing dense, high-quality context that slashes context window costs, eliminates developer manual review for recurring updates, and allows a single design specification to target multiple runtimes.

A real migration evaluation was conducted using an open-source alternative design tool, Penpot , to verify if it could replace the high-cost and messy layer structures of Figma. The evaluation yielded promising insights, validating a clean target spec format where design tokens are resolved synchronously. However, the current poor performance of Penpot’s rendering engine and page traversal timeouts on complex files was the dealbreaker, making it inviable for a large design system to migrate at this time. The lesson was not to immediately change tools but to target that clean spec format from the canonical source.

This evaluation also exposed a critical requirement: the pipeline must not rely on third-party design tools or plugins. Although various proprietary plugins can help extract design data, they introduce severe vendor lock-in and brittle dependencies. Relying on them creates a chain of potential issues when those external tools change direction, introduce bugs, fail to support other design vendors, or fall out of maintenance. Furthermore, avoiding third-party plugins directly increases security and privacy by keeping all design data within your own local, audited extraction environment.

This use case is not a replacement for those tools. It is what the Studio of Two approach looks like for a designer who needs the pipeline to be transparent, controllable, and cumulative. Under this philosophy, the partnership rises to a collaboration focused on orchestrating a systemic environment and workflow, where the resulting components and codebase tools are simply the byproducts of a well-engineered system.


The Problem: Figma Extraction Is Context-Expensive

Design-to-code extraction is powerful. It is also one of the most context-expensive operations in an AI-assisted workflow.

Raw Figma API outputs are large. They are structured for design tools, not for reasoning engines. A single extraction call can return tens of kilobytes of nested JSON - layer trees, variant definitions, component metadata, code connect references - most of which the implementation step will never use.

In practice this creates three compounding problems:

  • Context bloat: the payload arriving at the reasoning stage contains far more structure than is needed.
  • Token waste: expensive context windows are consumed by fields that never influence a decision.
  • Fragile handoffs: each stage forwards too much to the next, and the accumulated noise degrades reasoning quality progressively.

For parity-focused design-to-code work - where the goal is a component that faithfully reflects the design system’s token vocabulary and behavioral intent, not just one that renders - this problem appears quickly once workflows become multi-step.

Additional friction points that compounded the problem:

  • Spec drift: extraction output and implementation diverge without explicit contracts to hold them together.
  • Verification ambiguity: easy to validate that a component looks right, but hard to validate that it behaves right across states.
  • Retry cost: full reruns are expensive when only one gate fails. No concept of resuming from a known good point.
  • Tier-locked variable resolution: The API tool that provides direct access to the design tool’s variable definitions and their token bindings was restricted to a higher subscription tier. Without it, variable-to-token mapping could not be automated. This forced a manual reference mapping approach: a curated file documenting the relationship between variable names and the design system’s canonical token paths, maintained by hand and applied through the correction contract. The constraint shaped the architecture more than any deliberate design decision.
  • Layered corporate tool restrictions: Variable resolution was not the only blocked path. A second extraction tool - restricted at the organisation level rather than by subscription tier - would have provided richer component context for the same operation. Both restrictions arrived from different sources and were invisible until the extraction pipeline was being built. In a corporate environment, the available toolset is not the canonical toolset. The pipeline had to be designed around what was actually accessible.
  • Source design quality debt: The design file is a corporate asset maintained across a team over time. Some layers carry generic names rather than semantic ones. Some property types are used for purposes outside their intended semantic scope. Some components have incomplete state coverage. These are not errors - they are the natural result of a file that evolved faster than its maintenance discipline. The pipeline must compensate for upstream quality issues that the extraction author does not fully control.

Each is a form of the same underlying problem: the cognitive supply chain between the design file and the running component had no quality gates, no compression, and no evidence trail.


What Failed Before

Before the current approach, multiple extraction and generation strategies were attempted. Each failure is documented - not as a cautionary tale but as direct evidence for why each contract in the current system exists.

  1. Direct variable ID mapping. Raw variable identifiers from the extraction output were mapped directly to resolved style values. This worked until any variable changed in the design file - at which point every mapping that referenced that variable broke simultaneously. Maintenance cost grew with the size of the design system.

  2. No intermediate spec layer. Components were generated directly from raw extraction output, skipping any platform-agnostic intermediate format. Implementation inherited the extraction’s noise: wrong token references, missing nested components, inconsistent state handling. Every run required manual cleanup.

  3. Hardcoded resolved values in generated code. Components built with literal resolved values - colours, dimensions - could not adapt to a second brand, platform, or theme. What passed visual review was not maintainable at scale.

  4. Competing transformation pipelines. Multiple parallel paths for token transformation ran independently, produced different output shapes, and diverged over time. Debugging required knowing which pipeline had run last, not whether the logic was correct.

  5. One-shot generation tools. Automated generation tools produced output that looked correct at first glance but was not maintainable. Manual correction followed every run. The same problems recurred component by component with no compounding improvement.

Each failure mode maps directly to a contract in the current system. The spec layer prevents (2). The validation gates prevent (1) and (3). A consolidated token pipeline prevents (4). The correction feedback loop transforms (5) from a recurring cost into a compounding asset.

None of these failures were unique to this project. They are the predictable result of starting where most workflows start - with a sequential script and the assumption that a better prompt or a faster model will eventually close the gap. They don’t. The gap is structural. The next section shows what that looks like in practice.


The Naive Baseline: Sequential Scripts

The baseline is sequential and task-focused: treating scripts as isolated steps in a workflow. Most workflows start here, viewing the process much like how AI agents handle skills and workflows - as a static set of instructions and available tools.

In this early phase, the concept of a “pipe” or context budget was entirely absent. The focus was simply on execution. The hidden cost of this approach is opacity. The scripts run, and they produce output that looks reasonable at first glance. But when component tests fail - a token path unresolved, a fallback value wrong, an icon slot wired to a deprecated name - there is no trace of where in the chain signal was lost. Everything reruns from the beginning.

Where sequential scripts systematically break down:

  • Cross-runtime composition is awkward - Node, Python, and MCP tooling each have their own invocation patterns.
  • Context compression is not considered at all - the AI is forced to reason through the raw noise of the design file.
  • Reuse is low because orchestration logic is embedded in scripts rather than declared.
  • Workflow intent is invisible to anyone who didn’t write the code - including future self.
  • Ad-hoc patching is common - the agent ends up creating custom helper scripts along the way to patch compilation and token errors rather than addressing the structural pipeline faults.

Agentic sequential baseline. The natural evolution is an agent that orchestrates the same linear flow, representing the typical implementation of agent workflows and skills. This improves flexibility but the structural problems remain. The execution path is highly volatile, depending on the model’s brand, size, and infused context. Orchestration logic moves into prompts and transient runtime state - neither auditable nor reproducible. When the agent drifts on a model upgrade, there is no way to inspect why. When it fails a validation gate, there is no way to resume from that gate. Start over.

It was only late in the process, when the limits of this noisy agentic flow became critical, that context sifting and piping were introduced to save tokens and improve the signal-to-noise ratio. Later into the implementation, the pipeline model was adopted to manage deterministic, stateful flows.

Running a LLM over noisy, uncompressed extraction output is like asking a surgeon to operate in poor light. The capability is there. The environment is working against it.


The Pipe Insight: Context Is a Budget

Context-Pipe  was not built for design-to-code workflows. It was built earlier to solve a different problem: context bloat in local AI inference, where small models operating on limited context windows needed high-signal input to reason accurately. The core idea was a Unix-inspired chain - each node reads from stdin, transforms, writes to stdout - applied to the problem of refining raw data before it reached the model.

What became apparent during that development was that the same pipeline model had a second property: determinism. A declared chain of named nodes, each with a fixed contract, produces the same output for the same input every time. That is not a context management feature - it is an automation primitive. The pipeline does not just compress. It orchestrates reliably.

That observation prompted a deliberate test: apply the same infrastructure to the Figma-to-code workflow, where the extraction-to-component chain had all the same symptoms - noise accumulation, opaque failures, no resume points - and where deterministic, auditable orchestration was exactly what was missing. The result is documented here.

The shift that changed how the workflow operated: treating context not as a space to fill but as a budget to spend deliberately.

Once framed that way, the redesign became obvious. Every stage should receive only what it needs to do its job. No stage should forward accumulated noise to the next. Compression should happen at the boundary between stages - not as an afterthought at the end.

The pipeline shape:

  1. preflight - validate the source, establish canonical artifact paths
  2. extract - call Figma MCP tools, produce structured extraction manifest
  3. spec-seed - assemble component spec input, apply any recorded correction rules
  4. run - validate spec against hard gates, promote to canonical path
  5. query summary - extract only the fields the next reasoning step needs
  6. sift - compress for handoff

Each node reads from stdin and writes to stdout. Each is independently testable. Compression at step 6 applies to the summarised output of step 5, not to the raw extraction of step 2. The AI that performs implementation work receives a high-signal payload, not a transcript of everything the pipeline touched.

This provides:

  • Composable nodes through stdin/stdout contracts - language-agnostic, runtime-agnostic.
  • Cross-runtime interoperability - scripts, sift tools, and MCP servers in the same chain.
  • Per-node telemetry - input size, output size, reduction percentage, latency at every boundary.
  • Portable declarations in pipes.json - readable by humans and executable by machines.

Most importantly: compression becomes part of the workflow design, not a cleanup step applied after the fact.

The extraction phase - preflight through sift - is fully deterministic. No reasoning required. Every step is a transformation with a fixed contract: validate, extract, assemble, gate, summarise, compress. This work can be delegated entirely to the pipeline, and within the pipeline, individual nodes can be handed off to lighter models, subagents, or specialised workers. The pipeline does not care what executes each node. It cares only that the contract is honoured.

In the Context Design framework, this extraction phase is Context Priming in automated form. Context Priming is the discipline of building and maintaining the structured knowledge base the agent operates within - design system tokens, component semantics, correction rules, validated specs. Manually, this is a curation task. Through the pipeline, it becomes a reproducible, auditable process that runs on demand and compounds over time. The agent is not discovering the design system during implementation. It arrives primed with a validated, compressed version of it - built and maintained by the extraction phase before reasoning begins.

The Implementation Phase is different. Assembling a correct, platform-appropriate component from a validated spec requires high reasoning: understanding the target platform’s idioms, applying token semantics correctly, handling state logic, and producing code that is not just syntactically valid but architecturally sound. That is where a capable model is necessary - and where the quality of what the pipeline delivers becomes the primary variable. A high-reasoning model operating on a well-shaped, validated spec produces reliable output. The same model operating on raw extraction noise does not.

The pipe works well in the first phase precisely because the first phase is a problem of structure, not meaning. The second phase is a problem of meaning. Keeping them separate - and routing each to the right kind of executor - is what makes the full workflow tractable.


MCP Evolution: Wrapper Scripts → Native Nodes

The practical progression:

  • Start with custom runner scripts - effective, but bespoke.
  • Introduce declarative pipes for readability and reuse.
  • Move MCP calls into native pipe nodes where the infrastructure supports it.

This evolution is complete. The bridge scripts that previously wrapped Figma MCP calls have been replaced by native type: "mcp" nodes in pipes.json. Figma extraction and context summary both now run as first-class pipe nodes - no custom glue code, no adapter scripts, no wrapper layer between the data and the pipe.

Below is a concrete snippet from pipes.json demonstrating how an MCP extraction tool is declared, filtered, validated, and indexed in a single pipeline:

{ "name": "figma-mcp-extraction-pipe", "description": "Extract design context, validate specification schema, and index results", "nodes": [ { "id": "extract-figma", "type": "mcp", "server": "figma-desktop", "tool": "get_design_context", "args": { "nodeId": "$nodeId", "clientLanguages": ["typescript", "css"], "clientFrameworks": ["svelte"] } }, { "id": "sift-payload", "cmd": "semantic-sift-cli", "args": ["doc", "--rate", "0.4"] }, { "id": "validate-spec", "cmd": "pnpm --filter @org/figma-pipeline validate-spec", "args": ["--spec", "stdin"] }, { "id": "ctx-index", "type": "mcp", "server": "context-mode", "tool": "ctx_index", "args": { "path": "docs/components/specs/$componentName.spec.json" } } ] }

This integration is a game-changer for workflow orchestration. By natively supporting MCP tools alongside standard node types (such as Python scripts, Node.js binaries, and sifting utilities), context-pipe eliminates the runtime barriers that typically partition AI tools from local code. An MCP tool call is treated with the same stdin/stdout filter semantics as a local regex script, entirely eliminating the need for custom wrappers, extra orchestration scripts, or manual adapter layers. Developers can build hybrid pipelines that query an external design system API via MCP, clean the payload with a local sifting tool, and format it using standard CLI utilities, all declared in a single JSON configuration without any glue code.

Two production findings surfaced during this refactor:

Banner tolerance. Some MCP servers emit a startup message to stdout before any JSON-RPC communication begins. Invisible when a wrapper absorbs it. The moment you remove the wrapper and communicate with the server directly over the raw protocol, it breaks the JSON-RPC reader. The pipe infrastructure needs to tolerate non-conformant server output gracefully - silently by default, visible with verbose: true on the server config.

Self-healing branches. Removing wrapper scripts exposed conditional routing requirements that had previously been handled by imperative if/else logic inside the scripts. A create run that detects the output artifact already exists should not fail - it should route to an update sequence automatically. An update run that cannot find the source artifact should route back to create. These are state transitions, not errors. The pipe format currently cannot express this. Adding type: "validator" nodes with branches is Phase 2’s primary target.

On independent axes of change. The refactor clarified how this system scales. A CPP pipeline has three independently swappable layers:

  • Nodes - what each step does. A dumb stdin/stdout tool, unaware of the pipeline around it.
  • pipes.json - the topology. How steps connect, branch, and route. Changed by editing the map - no code changes, no recompile, no redeploy.
  • MCP servers - the capability behind each tool call. Swapped by changing a server key - no imports, no dependency declarations, no build cycle.

These three layers evolve on entirely independent cycles. For MCP nodes specifically: every MCP server speaks the same protocol - JSON-RPC, tools/call, text response. The pipe depends on what speaks the protocol, not on what implements the service.

In a script, you depend on what you import. In a pipe, you depend on what speaks the protocol.


The Workflow Shape

The extraction and validation pipeline has evolved from a linear sequence to a branch-aware Directed Acyclic Graph (DAG) topology. Running on macOS, this branched v2 architecture (*-v2 pipes defined in pipes.json) manages conditional routing and validators dynamically using the orchestrator.

The core pipeline topology leverages four key branch points and validator sequences:

  1. Branch Point A: Route Selection (Create vs. Refresh)

    • Evaluates index conflict before running heavy extraction tasks. If the nodeId is already registered in the central registry (e.g., docs/components/index.json), the orchestrator automatically routes to the refresh path (archiving the old spec and seeding candidate updates) instead of the create path, avoiding duplicate named components.
    • Includes automatic path reconciliation via check-index-spec-path and reconcile-index-spec-path nodes to verify index registry alignment.
  2. Branch Point B: Extraction Quality Gate

    • Evaluates the output of the Figma extraction step. If the manifest is missing key signals, or if the Figma MCP server returns tool-error payloads (indicated by isError: true or non-empty error fields), the pipeline routes to the quality-fail remediation branch and triggers a hard stop (quality-fail-stop), saving downstream token spend.
  3. Branch Point C: Validation Chain

    • Runs a set of deterministic, sequential validators to verify spec shape:
      • validate-extract-manifest: Assures manifest completeness.
      • validate-spec: Evaluates spec shape and token resolvability against docs/schema/component.spec.schema.json.
      • validate-spec:strict: Assures strict fallback consistency.
    • Merging Rule: The run continues only if all required validators return successful exit codes.
  4. Branch Point D: Context Fan-Out

    • After promoting the canonical spec, the pipeline fans out into parallel, optional context branches:
      • D1 (ctx_index) and D2 (ctx_search): Feed the updated specification back into the local vector index for context retrieval.
      • D3 (semantic-sift): Compresses the validation log and spec metadata for agent handoff.
    • Merging Rule: Optional branch failures (such as local database binary mismatches) are reported but do not block the run.

Minimal reproducible example - a branched pipe definition showing conditional routing:

{ "name": "new-component-workflow-no-vision-v2", "steps": [ { "id": "preflight", "cmd": "figma-preflight", "next": "route-select" }, { "id": "route-select", "type": "validator", "cmd": "check-index-conflict", "branches": { "0": "run-new-component", "2": "run-refresh-component" } }, { "id": "run-new-component", "cmd": "figma-extract", "next": "extract-quality-gate" }, { "id": "extract-quality-gate", "type": "validator", "cmd": "check-extract-quality", "branches": { "0": "spec-seed-v2", "1": "quality-fail-stop" } }, { "id": "quality-fail-stop", "cmd": "emit-remediation-logs" } ] }

Parity-critical extension for complex components:

  • Extract both the component-set node and at least one real composition or example node.
  • Validate not only visual structure but behavioral state - slot visibility, grouped row logic, pagination boundaries.
  • Decouple the visual QA pass as a separate, asynchronous certification step so that core generation flow is never blocked by manual screenshot validation.

The Contracts That Made It Reliable

The largest quality gains did not come from a better model. They came from explicit contracts.

Before contracts: results that were mostly right - every output manually verified because any part could have drifted. After contracts: results that are either provably right or explicitly failed at a named gate. The difference in cognitive experience is significant. Mostly right requires constant vigilance. Provably right or explicitly failed frees attention - the mental bandwidth to focus on the design, not the pipeline.

Extraction contract - required artifacts are fixed. Missing required extraction signals block promotion. The AI cannot proceed to spec authoring on incomplete data.

Validation contract - schema validity, token resolvability, fallback consistency, and unresolved bindings are hard gates. Under this contract, the extraction-to-spec path blocks promotion if any of the following gates fail:

  • Manifest Completeness Check: Ensures all expected extraction assets and signals are present.
  • Specification & Token Integrity Check: Validates spec schema correctness and design token bindings.
  • Strict Fallback Consistency Check: Ensures mathematical styling consistency if variables are missing.
  • Implementation Token Conformance Check: Verifies that downstream code complies strictly with the design system tokens. Implementation starts only after all gates pass. This is the equivalent of a design review sign-off - but deterministic.

Correction contract - manual parity fixes are recorded as deterministic rules and reapplied automatically on every subsequent run. When a token binding is corrected - an icon color that mapped to a hardcoded literal instead of a design token - the correction is recorded once. Every run after that applies it without involvement.

This is the contract with the most compounding value. The first correction costs full attention. The tenth is automatic. The fiftieth means the pipeline understands the design system’s token vocabulary better than a developer who just joined the project. The correction rules are a codified record of domain knowledge - auditable, versioned, and permanently applied. You are not fixing bugs. You are teaching the system the specific priors it needs to reason accurately about this design system, one correction at a time, permanently.

The variable resolution problem is structural to how this class of design tool represents bindings in its extraction output. A component node’s bound properties reference internal variable IDs - not semantic names. Resolving an ID to a semantic token path requires a multi-step join: the ID maps to a variable definition in a separate collection, the definition maps to a value, and that value must be resolved per combination of brand, platform, and theme. For a design system targeting multiple brands and platforms simultaneously, this is a large combinatorial join with no single authoritative path. The tool that automates this join was tier-locked.

The tier-locked constraint made this contract load-bearing rather than supplementary. Without automated variable resolution, every token binding the extractor got wrong had to be caught and recorded manually. What started as a workaround became a design principle: a hand-crafted layer of domain knowledge that no automated tool would have produced with the same precision or specificity. The constraint forced a more durable solution than the shortcut would have allowed.

Handoff contract - every high-volume boundary includes a compression step. Agent-to-agent handoff uses explicit compression policy, not implicit prompt trimming.

Verification contract - behavior and state checks, not only screenshots, are mandatory. Runs must generate explicit execution traces (logs and status reports) stored as run-log artifacts under a persistent path (e.g. artifacts/new-component/*-pipe-run.json) to serve as verifiable proof of compliance.

Resume contract - resume from a failed gate by default. Full rerun is reserved for missing or corrupted core artifacts. This alone eliminated most of the retry cost.


Architecture-First Parity

A pattern that proved useful across components: map the visual layout from the design canvas into semantic runtime roles rather than raw design-tool names. Under an architecture-first parity model, static design entities are translated into framework-agnostic runtime state definitions:

  • Segment selection (such as a tab bar or button group selector) is mapped to the active content set selection.
  • Filter toggles (such as checkboxes or switches) are mapped to logical data eligibility rules.
  • Pagination links (such as numbered page buttons) are mapped to page count and index clamping rules.
  • Empty states (such as fallback illustrations) are mapped to data-absence rendering behavior.

Define this deterministic state matrix in the spec before writing a line of implementation. This makes parity measurable and implementation-agnostic. It also makes it possible to validate not just that a component renders but that it behaves correctly across all states - which is where most parity failures actually hide.


Token Economics and Phase 1 Results

Token savings are not only a cost metric. Paired with context design, they are a quality metric.

Cost and scale effect - fewer tokens across extraction, summarisation, and handoff stages. Lower per-run cost as premium request budgets tighten.

Reasoning and performance effect - less low-signal noise in context windows. Higher density of relevant signals per token. Better downstream reasoning consistency across multi-agent handoffs.

From the context-pipe balance sheet during the period documented in Phase 1:

MetricValue
Noise reduced157,503 characters
Signal injected868 characters
Net context saved156,635 characters
Events276
Approximate tokens saved~39,000 - 45,000

With retry factor (1.5x - 2.0x for real agentic workflows): 58k - 90k avoided tokens for the same period.

The avoided tokens are not savings on neutral content. They are low-signal payload that would otherwise compete with the reasoning context that drives correct output. Better context means fewer retries. Fewer retries mean better context. The savings compound.

Before and after:

DimensionBeforeAfterWhy it matters
Context sizeLarge payloads pass through unchangedBoundary compression applied intentionallyLower token spend, fewer overflows
Failure isolationFailures opaque and cross-stepNode-level gates with deterministic artifactsFaster triage, safer retries
Rerun costFrequent full rerunsResume from failed gate by defaultLess compute and time waste
AuditabilityLogic hidden in scripts and promptsPipe and artifact trail is inspectableBetter governance and reproducibility
Designer trustVisual checks miss behavioral driftExplicit parity contracts and state matrixHigher confidence in intent preservation
Agent handoff qualityAd-hoc trimming between agentsExplicit A2A compression policyBetter reasoning continuity
Cognitive loadConstant vigilance over “mostly right”Trust gates, investigate failuresAttention back on the design, not the pipeline

Phase 2: Self-Healing Pipeline

Objective: Add conditional routing, validator nodes, and banner tolerance. Status: Completed (Rollout closed; deferred items in backlog)


Validator Nodes and Self-Healing Branches

Branch-aware conditional routing is fully rolled out in pipes.json. By introducing type: "validator" nodes, the orchestrator evaluates process exit codes to dynamically route to named execution branches.

This successfully replaces raw code scripts with declarative topologies:

  • Evaluates registry and index alignment via check-index-spec-path and auto-reconciles files using reconcile-index-spec-path nodes.
  • Captures branch execution traces and merges status logs directly into run artifacts.

In-Run Recovery Case Study: Missing Indexed Spec Path

A common point of failure occurs when a component is registered in the index but its specification file (*.spec.json) is deleted or missing from the filesystem. If reconciliation fails to find a match, a naive run would fail at index-reconcile-fail.

The runners have been updated to catch this failure sequence programmatically. When a missing specification is detected, the runner triggers an internal bootstrap flow (preflight -> extract -> spec-seed -> run --resume) and dynamically routes back to the main pipeline.

Below is a redacted execution log showing the self-healing process in action during a component refresh:

[PIPE] start name=refresh-component-workflow-no-vision-v2 mode=no-vision component=Search [PIPE] execution is streamed node-to-node; final summary only is emitted to stdout [PIPE] node 1 status=pass scope=main id=preflight [PIPE] cmd pnpm --filter @org/figma-pipeline new-component-preflight --url <figma-url> --name Search [PIPE] node 2 status=fail scope=main id=check-index-spec-path [PIPE] cmd pnpm --filter @org/figma-pipeline check-index-spec-path --name Search --node-id 153:3066 [PIPE] branch target=reconcile-index-spec-path [PIPE] self-heal trigger=missing-index-spec-path action=bootstrap-spec-and-retry [PIPE] self-heal status=pass branch target=extract [PIPE] node 3 status=fail scope=main id=reconcile-index-spec-path [PIPE] branch target=extract [PIPE] node 4 status=pass scope=main id=extract [PIPE] cmd pnpm --filter @org/figma-pipeline new-component-extract --preflight <preflight-json> ... [PIPE] node 11 status=pass scope=main id=run-refresh-component [PIPE] context-economics naive=20.4KB final=2.0KB saved=18.4KB (90%) peak-node=3.2KB saved~4592 tokens { "pipe": "refresh-component-workflow-no-vision-v2", "component": "Search", "nodeId": "153:3066", "artifact": "artifacts/new-component/search-refresh-pipe-run.json", "steps": 18, "contextEconomics": { "naiveContextBytes": 20416, "finalPayloadBytes": 2050, "savedBytes": 18366, "savedPct": 90, "peakIntermediateBytes": 3229, "nodesMeasured": 18, "naiveContextTokensApprox": 5104, "finalPayloadTokensApprox": 513, "savedTokensApprox": 4592 }, "status": "pass" }

Net Interaction Savings vs. Context Compression (“Full Savings”)

There is a structural divergence between input context reduction (90% in the log above) and the actual net financial saving on a model interaction. This is driven by LLM API pricing asymmetries (e.g., input cost at $1.75/1M tokens vs. output cost at $14.00/1M tokens):

  • Context Savings (Input): Reducing input bytes by 90% drops input cost from 0.89 credits to 0.09 credits per run (a 90% direct reduction).
  • Output Cost Stability: The generated component code output size remains constant (typically ~500 tokens or 0.72 credits).
  • Net Interaction Savings: When combining both input and output costs, the net cost drops from 1.61 credits to 0.81 credits.

Thus, the “Full Saving” (net billing impact) stands at 49.9% per interaction. However, measuring the value solely through this single-pass, single-model pricing underestimates the systemic gains:

  1. Asymmetric Model Routing (Phase Separation): The extraction phase is a purely structural problem. Because it requires zero creative reasoning, it can be run via local CLI tools or delegated to highly efficient local Small Language Models (SLMs) costing a fraction of a cent. Premium, high-reasoning LLMs (like Codex 5.3) are reserved exclusively for the implementation step.
  2. Mitigating Upstream Extraction Inconsistency: Raw Figma extraction payloads are inherently non-deterministic - layer ordering, transient canvas properties, and dynamic variable IDs can shift slightly between exports. If a reasoning model directly consumes this raw output, the generated code will drift and suffer from subtle inconsistencies on every run. Compiling raw data into a validated, normalized schema (*.spec.json) ensures structural input consistency, protecting components from upstream design-file noise.
  3. Cognitive Protection of the Implementation Model: If raw Figma data (~20K - 40K tokens of nested canvas metadata) is passed directly to the implementation agent, the premium model is forced to navigate noisy design trees. This causes cognitive overload, leading the model to lose track of token bindings, hallucinate layout structures, or fail compilation gates.
  4. Compounding Savings in Developer Loops: A 5K token input reduction on a cheap local SLM is negligible. But keeping 40K tokens of noisy metadata out of the premium implementation model’s context window - and avoiding the premium retry loops when that model gets lost - translates to massive credit savings and vastly superior code quality.
  5. Cost Predictability vs. Endless Agent Loops: Normalizing design parameters into a validated spec makes implementation costs highly predictable (~0.81 credits) because the agent operates within defined constraints. Running agents directly on unprimed raw extraction data is highly volatile - often leading to endless multi-turn loops (getting lost in layouts, drifting on variables, or reverting to hardcoded values as seen in the failed attempts documented below). The pipe converts a volatile research loop into a predictable build gate.

A script embeds its recovery. A pipe declares it.

Graceful handling of MCP servers that emit non-JSON-RPC startup headers is fully supported. The runner automatically filters out pre-handshake stdout banners, allowing standard JSON-RPC parsing to succeed without custom wrappers or adapter scripts.


Phase 3: Universal Design System Readiness

Objective: Close platform semantic gaps, define multi-target token transformations, and implement adapter equivalence test suites. Status: Active sprint (10 workdays starting June 2026)


Universal Targets & Readiness Assessment

Expanding the design-to-code pipeline beyond Web/Svelte targets to other platform targets requires addressing platform-specific constraints. A system audit evaluated readiness for universal scale:

  • Web (Svelte / React): 8/10 (Mature pipeline and established component code generation).
  • Android & iOS Native: 5.5/10 (Conceptually aligned specs; needs target-specific adapters and conformance tests).
  • Embedded Surfaces (LVGL): 4.5/10 (Highest risk due to hardware resource limits, binary compilation constraints, and CPU/memory budgets).

Gaps to Close Before Scale

To safely expand targets, the Universal Readiness sprint is addressing six core engineering gaps:

  1. Spec Expressiveness for Native/Embedded Semantics: Adding layout scaling rules, minimum touch target metrics, focus navigation indexes, and accessibility role mappings.
  2. Token Transformation Compilation: Restricting edits strictly to canonical token source files, utilizing compiler transforms to build CSS properties, Compose XML maps, Swift structures, and C headers automatically.
  3. Adapter Conformance testing: Setting up a unified test harness to assert behavior and event parity across platforms, rather than relying on pixel-by-pixel visual matches.
  4. Layout Mapping Rules: Defining canonical rules to map flexbox layout schemas to native constraints and LVGL.
  5. Asset and Icon Portability: Enforcing canonical registry keys with target-specific rendering fallbacks (e.g. svg - png - placeholder).
  6. Embedded Resource Budget Gates: Implementing automated memory and rendering execution gates in CI for LVGL compilation.

The 10-Day Sprint Schedule

The universal rollout follows a structured 10-day de-risking sprint:

  • Day 1 - 2: Universal Contract: Define v1 specification fields (scaling, touch targets, accessibility).
  • Day 3 - 4: Pilot Component Matrix: Map state matrices and event shapes using a Svelte dashboard application as a semantic reference fixture.
  • Day 5 - 6: Adapter Equivalence Harness: Implement a conformance verification script to validate output parity.
  • Day 7: Token Transform Rules: Validate compiled token outputs and precision rounding rules for native code headers.
  • Day 7.5: Icon Portability Contract: Enforce canonical icon mapping keys with target-specific rendering fallbacks.
  • Day 8: Embedded Performance Gates: Define memory and rendering budget thresholds for LVGL compilation.
  • Day 9: Vehicle Surfaces Feasibility: Document constraints for CarPlay/Android Auto (distraction rules, layout restrictions).
  • Day 10: Tiered Workflow Policy: Cut over to a tiered operation model:
    • Lite Path: Low-risk, visual, or atom-level modifications bypass heavy auditing.
    • Full Path: Stateful, composite, and cross-target components undergo full branched pipeline execution.

Evidence and Replicability

The methodology in this use case is replicable now for:

  • Pipe composition and boundary-first compression.
  • Artifact-first audits with deterministic gates.
  • Correction feedback loops that teach the system domain-specific priors.

What requires abstraction before general sharing:

  • Domain-specific scripts and naming conventions.
  • Design-system token vocabulary and correction rules.

High-value standardisation targets for the community:

  • Pipe run artifact schema: nodes, status, metrics, outputs.
  • Gate taxonomy: extraction, validation, implementation, verification.
  • Handoff metadata: from-agent, to-agent, compression profile, reduction.
  • Minimal parity matrix schema for design-to-code workflows.

Automated Verification in CI

Every pipeline execution persists a detailed trace (*-pipe-run.json) detailing node exit codes, latency, and compression ratios. To enforce compliance programmatically, a verification script (verify-post-run.mjs) runs in CI. It uses the pipe_audit_last tool to audit the runner’s output artifacts, ensuring all mandatory validation gates and path reconciliations have passed before staging code changes.


Systems, Not Patches in Practice

Ultimately, the goal of this pipeline is to codify the Systems, not Patches philosophy. Instead of adjusting prompts or making manual corrections on a component-by-component basis, the pipeline establishes a correction system that compounds permanently. By shifting the workload from reactive debugging to structured, trace-verified contracts, the tool becomes fast enough to keep up with the speed of thought.

Yet, this journey is still in its early stages. As the architecture begins to expand across multiple framework targets and target platforms, the hope is that these systems will hold up, adapt, and continue to evolve naturally.


Open Source Infrastructure

Feel free to check other areas of my page to learn more about me and don't hesitate to connect.