Open-source design agent: on-brand stills, decks, diagrams, charts and motion graphics from a chat thread, built on Deep Agents.
JavaScript agentagentsai-agentdeepagentsdesignhyperframeslanggraphmanaged-agentsmotion-graphicspaperslackvideo
Fix web-font brands and onboarding gaps a fresh coding-agent setup found
Amal Irgashev451be2a75dc8
diff --git a/.agents/skills/brand-onboarding/SKILL.md b/.agents/skills/brand-onboarding/SKILL.mdindex 49617b3..6686d3d 100644--- a/.agents/skills/brand-onboarding/SKILL.md+++ b/.agents/skills/brand-onboarding/SKILL.md@@ -10,22 +10,34 @@ language. Schema: `src/design_agent/brand/schema.py`; a complete example:`examples/brands/example-studio/`. Never invent a rule, colour, font or logo the sources do not show:leave it out and list it as a question for the person.-1. Copy the example pack's layout into `workspace/brand/` (Git-ignored) and replace its content.+1. `uv run design-agent brand init` copies the example pack into `workspace/brand/` (Git-ignored);+ replace every file's content, logos included.2. **Sources, best first:** the brand's own guide (PDF), its design files (Paper: read tokens,palette and type nodes with `get_tokens`, `get_computed_styles`, `get_jsx`; never write to thebrand file), the live website's CSS, then existing marketing files.-3. `tokens.json`: palette with roles (ground, text, accent), font stacks for display, text and mono,- radii, stroke, spacing, and the copy rules the guide states. Check every text/ground pair you list- for WCAG contrast; mark accents that fail on light grounds as non-text.+3. `tokens.json`: palette, font stacks for display, text and mono, radii, stroke, spacing, and the+ copy rules the guide states. Check every text/ground pair you list for WCAG contrast; mark+ accents that fail on light grounds as non-text. Say which colour plays which role in+ `design.roles.light` and `design.roles.dark` (`ground`, `ink`, `accent`, `muted`, `quiet`,+ `rule`, `series`, each a token): charts and diagrams use them, and otherwise guess from the+ palette. Porting an existing tokens file: names must be `--brand-*`, hexes carry `#`, `version`+ is `"1"`, unknown keys are refused, and every font stack ends in a generic family.4. `logos/`: SVG where the brand provides it; every variant the guide allows (mark, lockup,reversed). Do not redraw or trace a logo; ask for files.-5. `fonts.toml`: for each family, an open font in `fonts/` or a licensed file the person supplies in+5. `fonts.toml`: for each face, an open font in `fonts/` or a licensed file the person supplies in`private-fonts/` (Git-ignored; it reaches the sandbox as deployment files or a mount). Never- commit licensed fonts. If a licensed face is unavailable, name the closest open fallback and say- so in `graphic-language.md`.+ commit licensed fonts. `family` is the name inside the file (the sandbox resolves fonts by it),+ `weight` a CSS weight (`"400"`, or `"100 900"` for a variable face), `sha256` from+ `shasum -a 256 <file>`. `uv run design-agent fonts verify` checks all three. Web formats+ (`.woff2`, `.woff`) are fine: `tokens.css` declares them with `@font-face`. If a licensed face+ is unavailable, name the closest open fallback and say so in `graphic-language.md`.6. `voice.md` and `graphic-language.md`: short, concrete, sourced ("headlines in sentence case",- "one accent per frame"), no generic advice.-7. `uv run design-agent brand validate`, then `uv run design-agent brand css` regenerates- `tokens.css`. Render a test card with `uv run design-agent demo` against the new brand- (`DESIGN_AGENT_BRAND_PATH=workspace/brand`) and look at it with the person.-8. Hand the person the open questions; the pack is done when they have reviewed it.+ "one accent per frame"), no generic advice. Anything else the guide has (type tables, icons,+ pattern art, construction specs) can live in the pack too; link it from `graphic-language.md`,+ which is what the agent reads first.+7. `uv run design-agent brand validate`, `uv run design-agent fonts verify`, then+ `uv run design-agent brand css` regenerates `tokens.css`. For a first look, ask for one card+ (`uv run design-agent ask "A 1200x630 card announcing …"`) and review it with the person; `demo`+ always renders the sample brand.+8. Hand the person the open questions, including rules the guide contradicts itself on; the pack is+ done when they have reviewed it.diff --git a/.agents/skills/design-agent-onboarding/SKILL.md b/.agents/skills/design-agent-onboarding/SKILL.mdindex b055892..2909b49 100644--- a/.agents/skills/design-agent-onboarding/SKILL.md+++ b/.agents/skills/design-agent-onboarding/SKILL.md@@ -8,12 +8,15 @@ description: Install and configure Design Agent, add a brand, connect Paper, choWork through these with the person, in order. Never print a key or token; report missing settingsby name. Do not deploy, connect accounts or publish anything until the person asks.-1. **Install and prove the computer.** `uv sync`, then `uv run design-agent sandbox build` (Docker)- and `uv run design-agent demo`: a scripted run renders a launch card in three sizes and a 4-second- teaser with no keys. If it fails, `uv run design-agent doctor` says what is missing.+1. **Install and prove the computer.** `uv sync`, then `uv run design-agent sandbox build` (Docker;+ a cold build downloads about 2 GB and takes several minutes) and `uv run design-agent demo`: a+ scripted run renders the sample brand's launch card in three sizes and a 4-second teaser with no+ keys. If it fails, `uv run design-agent doctor` says what is missing.2. **Model.** `uv run design-agent config set DESIGN_AGENT_MODEL=provider:model` and the provider's- key (`ANTHROPIC_API_KEY=…`, typed by the person, or set in `.env` by hand). Defaults and other- roles: `docs/models.md`. Re-run `doctor`.+ key (`ANTHROPIC_API_KEY=…`, or `LANGSMITH_GATEWAY_API_KEY` for a `langsmith:` model; typed by the+ person, or set in `.env` by hand). Defaults and other roles: `docs/models.md`. Re-run `doctor`,+ then `uv run design-agent test model`: `doctor` only checks that a key is set, the test makes+ one cheap call with it.3. **Media keys (optional).** `OPENAI_API_KEY` (image generation), `ELEVENLABS_API_KEY` (voice,music, sound effects), `GROQ_API_KEY` (fast transcription). Each tool says plainly when its keyis missing.@@ -22,7 +25,8 @@ by name. Do not deploy, connect accounts or publish anything until the person as5. **Paper (optional).** `PAPER_MODE=local` when Paper Desktop runs on this machine; `bridged` for adeployed agent (see `docs/partners/paper.md`). `off` is fine: boards render in the sandbox.6. **Try it.** `uv run design-agent ask "Make a LinkedIn card announcing …"`. Finals land in- `workspace/out/<thread>/`; `--thread <id>` continues a conversation.+ `workspace/out/<thread>/`, the last line estimates what the run cost, and `--thread <id>`+ continues a conversation.7. **Choose where it runs.** Explain `docs/deploy-mda.md` (managed: runtime, sandbox, Slack,schedules; one command) and `docs/self-hosting.md` (Docker Compose with Postgres, your Slack app,your machine). For MDA: `uv run design-agent sandbox publish` once, thendiff --git a/AGENTS.md b/AGENTS.mdindex b7f85bc..95c3e5d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -6,22 +6,26 @@ decks, diagrams, charts and motion graphics from a chat thread, on its own compuas the video engine and Paper as the shared canvas. Keep company-specific brands, credentials, fonts,reference films and operational history out of the public repository.-This repository starts spec-first. Until the implementation exists, `SPEC.md` and-`IMPLEMENTATION_PROMPT.md` are the source of truth; afterwards, code and tests are.+**Setting up or using Design Agent?** Follow+[.agents/skills/design-agent-onboarding/SKILL.md](.agents/skills/design-agent-onboarding/SKILL.md)+(and [brand-onboarding](.agents/skills/brand-onboarding/SKILL.md) for a brand). The rest of this+file is for changing the agent.-## Read first+Code and tests are the source of truth; `SPEC.md` records the product intent behind them.-1. [SPEC.md](SPEC.md): product behavior, architecture, extraction plan, slices and acceptance criteria.-2. [docs/prep/extraction-map.md](docs/prep/extraction-map.md): every source component from the- internal agent, classified as keep, generalize, rewrite or exclude.-3. [docs/prep/source-inventory.md](docs/prep/source-inventory.md): pinned source revisions and- package versions this build is based on.-4. [docs/prep/partner-integrations.md](docs/prep/partner-integrations.md): HyperFrames and Paper- contracts and open partner questions.-5. [docs/sources/official-links.md](docs/sources/official-links.md): primary documentation for- every external contract.+## Read first (to change the agent)-## Folder boundaries (target)+1. [docs/architecture/](docs/architecture/README.md): how the assembly, harness, surfaces and+ sandbox fit together.+2. [SPEC.md](SPEC.md): product behavior, slices and acceptance criteria.+3. [docs/sources/official-links.md](docs/sources/official-links.md): primary documentation for+ every external contract; [docs/upstream.md](docs/upstream.md): seams we work around.+4. Pre-release only (removed before the repository goes public):+ [docs/prep/extraction-map.md](docs/prep/extraction-map.md),+ [docs/prep/source-inventory.md](docs/prep/source-inventory.md) and+ [docs/prep/partner-integrations.md](docs/prep/partner-integrations.md).++## Folder boundaries- `.agents/skills/`: workflows for coding agents (onboarding, brand setup, vendor sync, release).`.claude/skills` links here. Never synced to the runtime sandbox.@@ -83,7 +87,7 @@ session handoffs or audit transcripts to the repository. Preserve unrelated locaDo not commit, push, deploy, create remote repositories, connect accounts, publish packages, orcontact partners unless the user asks.-## Verification (target)+## Verification```bashuv sync --all-extras --devdiff --git a/OPERATIONS.md b/OPERATIONS.mdindex 2f1938b..cead750 100644--- a/OPERATIONS.md+++ b/OPERATIONS.md@@ -46,7 +46,7 @@ truth. Set `DESIGN_AGENT_JOB_BUDGET_USD` to make the agent ask before going past| Symptom | Likely cause and fix || --- | --- || `demo` says it needs a sandbox | Docker is not running or the image is missing: `uv run design-agent sandbox build` |-| A render fails with a missing font | the brand's family is not in `fonts/` or `private-fonts/`, or `fonts.toml` names it wrong: `brand validate` |+| A render fails with a missing font | the file is not in `fonts/` or `private-fonts/`, or `fonts.toml` names a family the file does not carry: `fonts verify` || "The connection to the model stalled" | a call passed `DESIGN_AGENT_MODEL_TIMEOUT_SECONDS`; reply `continue` || "The model stayed unavailable" | the provider failed through every retry; check the provider's status, reply `continue` || Background news arrives a minute or two late on MDA | expected: MDA schedules land on the next minute |diff --git a/README.md b/README.mdindex 9f57c88..175fdcf 100644--- a/README.md+++ b/README.md@@ -45,11 +45,12 @@ uv run design-agent demoThe demo needs no keys: a scripted run renders a launch card in three sizes and a 4-second teaserfor the sample brand, through the real agent, sandbox and gates, into `workspace/out/demo/`.-Then add a model and ask for something:+Then add a model (put `ANTHROPIC_API_KEY=…` in `.env` yourself, so the key stays out of your shell+history) and ask for something:```bash-uv run design-agent config set DESIGN_AGENT_MODEL=anthropic:claude-opus-5-5 ANTHROPIC_API_KEY=…-uv run design-agent doctor+uv run design-agent config set DESIGN_AGENT_MODEL=anthropic:claude-opus-5-5+uv run design-agent test modeluv run design-agent ask "A LinkedIn card announcing our design review service, 1200x627."```diff --git a/skills/data-viz/scripts/lib/brand-theme.mjs b/skills/data-viz/scripts/lib/brand-theme.mjsindex df5f383..3a3ece6 100644--- a/skills/data-viz/scripts/lib/brand-theme.mjs+++ b/skills/data-viz/scripts/lib/brand-theme.mjs@@ -11,8 +11,9 @@// series chromatic palette colours in brand order, minus the accent and anything that would read// as it, minus anything too close to the ground to see// ramp one hue family from light to dark, for sequential encodings-// A spec can pin any role to a token (`"colors": {"ground": "--brand-color-paper"}`); the token must-// resolve to a palette colour.+// The pack can assign roles per mode (`design.roles.light|dark` in tokens.json), and a spec can pin any+// role to a token (`"colors": {"ground": "--brand-color-paper"}`); a spec's pin wins over the pack's,+// and both win over the measurement. Every token must resolve to a palette colour.import { readFileSync } from "node:fs";@@ -107,13 +108,19 @@ export function brandTheme(tokensFile, { mode = "light", roles = {} } = {}) {const palette = new Set([...core, ...extended]);const tokens = design.tokens || {};- const pinned = {};- for (const [role, token] of Object.entries(roles)) {- if (!(token in tokens)) throw new BrandError(`colors.${role}: unknown token ${token}`);+ const resolve = (where, token) => {+ if (!(token in tokens)) throw new BrandError(`${where}: unknown token ${token}`);const hex = normalizeHex(tokens[token]);- if (!hex || !palette.has(hex)) throw new BrandError(`colors.${role}: ${token} is not a palette colour`);- pinned[role] = hex;+ if (!hex || !palette.has(hex)) throw new BrandError(`${where}: ${token} is not a palette colour`);+ return hex;+ };+ const packRoles = design.roles?.[mode] || {};+ const pinned = {};+ for (const role of ["ground", "ink", "accent", "muted", "quiet", "rule"]) {+ if (packRoles[role]) pinned[role] = resolve(`roles.${mode}.${role}`, packRoles[role]);}+ const packSeries = (packRoles.series || []).map((token, i) => resolve(`roles.${mode}.series[${i}]`, token));+ for (const [role, token] of Object.entries(roles)) pinned[role] = resolve(`colors.${role}`, token);const byLum = [...core].sort((a, b) => luminance(a) - luminance(b));const ground = pinned.ground ?? (mode === "light" ? byLum[byLum.length - 1] : byLum[0]);@@ -141,10 +148,13 @@ export function brandTheme(tokensFile, { mode = "light", roles = {} } = {}) {hueGap(c, accent) > 0.35 &&contrast(c, ground) >= 1.4,);- // Distinct hues first (in brand order), then the remaining tints in brand order.- const series = [];- for (const c of candidates) if (series.every((s) => hueGap(c, s) > 0.5)) series.push(c);- for (const c of candidates) if (!series.includes(c)) series.push(c);+ // The pack's series as written; otherwise distinct hues first (in brand order), then the+ // remaining tints in brand order.+ const series = [...packSeries];+ if (!series.length) {+ for (const c of candidates) if (series.every((s) => hueGap(c, s) > 0.5)) series.push(c);+ for (const c of candidates) if (!series.includes(c)) series.push(c);+ }if (pinned.series) series.unshift(pinned.series);const anchor = series[0] ?? accent;diff --git a/src/design_agent/brand/schema.py b/src/design_agent/brand/schema.pyindex 360555b..30cd717 100644--- a/src/design_agent/brand/schema.py+++ b/src/design_agent/brand/schema.py@@ -12,7 +12,7 @@ import jsonimport reimport tomllibfrom collections.abc import Mapping-from pathlib import Path+from pathlib import Path, PurePosixPathfrom typing import Annotated, Literalfrom pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator@@ -91,6 +91,32 @@ class DiagramConstruction(_Strict):max_arrowhead_markers: int = Field(default=1, ge=0, alias="maxArrowheadMarkers")+class ColorRoles(_Strict):+ """The colours a brand assigns to each role in one mode, as tokens. Renderers prefer these over+ what they would measure from the palette; a role left out is still measured."""++ note: str = Field(default="", alias="_note")+ ground: CssToken | None = None+ ink: CssToken | None = None+ accent: CssToken | None = None+ muted: CssToken | None = None+ """Secondary text."""+ quiet: CssToken | None = None+ """De-emphasised marks: the bars that are not the point."""+ rule: CssToken | None = None+ """Grid lines and dividers."""+ series: tuple[CssToken, ...] = ()+ """Categorical colours, in the order a chart uses them."""++ def named(self) -> list[tuple[str, CssToken]]:+ single = [+ (role, token)+ for role in ("ground", "ink", "accent", "muted", "quiet", "rule")+ if (token := getattr(self, role)) is not None+ ]+ return single + [(f"series[{i}]", token) for i, token in enumerate(self.series)]++class DesignTokens(_Strict):allowed_colors: tuple[HexColor, ...] = Field(min_length=2, alias="allowedColors")extended_palette: NotedColors = Field(default_factory=NotedColors, alias="extendedPalette")@@ -114,6 +140,8 @@ class DesignTokens(_Strict):)tokens: Mapping[CssToken, str] = Field(min_length=1)"""CSS custom properties written to tokens.css. Colors must come from the palette."""+ roles: Mapping[Literal["light", "dark"], ColorRoles] = Field(default_factory=dict)+ """Optional colour roles per mode (charts and diagrams); see `ColorRoles`."""rules: tuple[str, ...] = ()@model_validator(mode="after")@@ -131,6 +159,13 @@ class DesignTokens(_Strict):for token in self.diagram_construction.stroke_tokens:if token not in self.tokens:raise ValueError(f"diagram stroke token {token} is not defined in tokens")+ for mode, roles in self.roles.items():+ for role, token in roles.named():+ value = self.tokens.get(token, "").strip()+ if not HEX.match(value) or normalize_hex(value) not in palette:+ raise ValueError(+ f"roles.{mode}.{role}: {token} must be a token holding a palette colour"+ )return selfdef palette(self) -> frozenset[str]:@@ -320,14 +355,30 @@ def load_brand_pack(return BrandPack(root=root, brand=brand, tokens=tokens, fonts=fonts)+#: Formats Chrome reads only through @font-face, never as installed system fonts.+WEB_FONT_FORMATS = {".woff2": "woff2", ".woff": "woff"}++def render_tokens_css(pack: BrandPack) -> str:- """tokens.css: every token plus the three font-stack variables, sorted, under `:root`."""+ """tokens.css: an @font-face rule for each web-format brand font (staged in /workspace/fonts/),+ then every token plus the three font-stack variables, sorted, under `:root`."""design = pack.tokens.designvalues = dict(design.tokens)for role in ("display", "text", "mono"):values.setdefault(f"--brand-font-{role}", design.font_stacks.css(role))body = "\n".join(f" {name}: {values[name]};" for name in sorted(values))+ faces = [+ "@font-face {\n"+ f" font-family: {json.dumps(font.family)};\n"+ f" font-weight: {font.weight};\n"+ f" font-style: {font.style};\n"+ f' src: url("/workspace/fonts/{PurePosixPath(font.file).name}") format("{kind}");\n'+ "}\n"+ for font in pack.fonts.fonts+ if (kind := WEB_FONT_FORMATS.get(PurePosixPath(font.file).suffix.lower()))+ ]return (f"/* Generated from {pack.brand.files.tokens} by `design-agent brand css`. Do not edit. */\n"- f":root {{\n{body}\n}}\n"+ + "".join(faces)+ + f":root {{\n{body}\n}}\n")diff --git a/src/design_agent/cli.py b/src/design_agent/cli.pyindex d1ff13a..817b0a7 100644--- a/src/design_agent/cli.py+++ b/src/design_agent/cli.py@@ -572,10 +572,18 @@ def brand_init(force: bool) -> None:if (target / "brand.toml").exists() and not force:click.echo("workspace/brand/ already holds a pack; --force replaces it.", err=True)sys.exit(1)- shutil.copytree(root / "examples" / "brands" / "example-studio", target, dirs_exist_ok=True)+ # The folder's README is tracked, and the sample's LICENSE covers only the sample's files.+ shutil.copytree(+ root / "examples" / "brands" / "example-studio",+ target,+ dirs_exist_ok=True,+ ignore=lambda folder, _names: (+ {"README.md", "LICENSE"} if Path(folder).name == "example-studio" else set()+ ),+ )click.echo(- "Copied the sample brand to workspace/brand/. Replace its content with yours; the "- "brand-onboarding skill walks through it, and `brand validate` checks it."+ "Copied the sample brand to workspace/brand/. Replace its content with yours (its logos "+ "too); the brand-onboarding skill walks through it, and `brand validate` checks it.")@@ -586,7 +594,10 @@ def fonts() -> None:@fonts.command("verify")def fonts_verify() -> None:- """Every brand font file is present with its recorded checksum, and every open font is licensed."""+ """Every brand font file is present with its recorded checksum and the family fonts.toml names,+ and every open font is licensed."""+ from PIL import ImageFont+from design_agent.brand.schema import BrandPackError, load_brand_packroot = _root()@@ -594,6 +605,17 @@ def fonts_verify() -> None:try:pack = load_brand_pack(Settings().resolved_brand_path(root), project_root=root)for font in pack.fonts.fonts:+ # The sandbox resolves fonts by this name (fontconfig's family[0]), so a family that+ # differs from the file's own passes the checksum and fails at render time.+ try:+ inside = ImageFont.truetype(str(pack.font_path(font, root)), 12).getname()[0]+ except OSError:+ inside = None+ if inside is not None and inside != font.family:+ problems.append(+ f'{font.file}: fonts.toml says family "{font.family}", the file says "{inside}"'+ )+ continueclick.echo(f"ok {font.family:20} {font.file}")except BrandPackError as error:problems.append(str(error))diff --git a/src/design_agent/demo.py b/src/design_agent/demo.pyindex b76d38a..36d65f4 100644--- a/src/design_agent/demo.py+++ b/src/design_agent/demo.py@@ -18,7 +18,7 @@ from pathlib import Pathfrom PIL import Image-from design_agent.config import Settings+from design_agent.config import SAMPLE_BRAND, Settingsfrom design_agent.runtime.local import build_local_runtime, final_textfrom design_agent.runtime.sandbox import SandboxSelectionError, select_bindingfrom design_agent.testing.demo_script import (@@ -65,7 +65,9 @@ def _verify_outputs(folder: Path) -> tuple[list[Path], list[str]]:async def run_demo(project_root: Path, settings: Settings | None = None) -> DemoResult:- settings = settings or Settings()+ # The scripted model writes the sample brand's tokens, fonts and logo, so the demo proves the+ # computer on that brand whatever pack is installed; `ask` is the first look at your own.+ settings = (settings or Settings()).model_copy(update={"brand_path": SAMPLE_BRAND})started = time.monotonic()binding = select_binding(settings, project_root)thread_id = f"demo-{uuid.uuid4().hex[:8]}"diff --git a/src/design_agent/envfile.py b/src/design_agent/envfile.pyindex e567d32..40fc475 100644--- a/src/design_agent/envfile.py+++ b/src/design_agent/envfile.py@@ -15,7 +15,7 @@ from collections.abc import Mappingfrom dataclasses import dataclassfrom pathlib import Path-_LINE = re.compile(r"^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*)$")+_LINE = re.compile(r"^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=(.*)$")_SECRET = re.compile(r"(KEY|TOKEN|SECRET|PASSWORD)$|^DATABASE_URL$|_TOKENS$")#: Keys `generate` may fill with a random value, and how.GENERATED = {@@ -58,6 +58,9 @@ def known_keys(root: Path) -> dict[str, EnvKey]:def _unquote(raw: str) -> str:+ # As python-dotenv reads it: a `#` after whitespace starts a comment, even with no value before.+ if raw[:1].isspace() and raw.lstrip().startswith("#"):+ return ""raw = raw.strip()if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":return raw[1:-1].replace('\\"', '"').replace("\\\\", "\\")diff --git a/src/design_agent/runtime/sandbox/docker.py b/src/design_agent/runtime/sandbox/docker.pyindex 265fccb..1209243 100644--- a/src/design_agent/runtime/sandbox/docker.py+++ b/src/design_agent/runtime/sandbox/docker.py@@ -143,14 +143,19 @@ class DockerSandboxRunner:raise SandboxUnavailableError(f"docker {args[0]} failed: {detail[:300]}")return result- def _cpu_limit(self) -> str:- """`--cpus`: the configured vCPUs, capped at the Docker host's, which refuses more."""- info = self._run(["info", "--format", "{{.NCPU}}"], timeout=30, check=False)+ def _host_limits(self) -> tuple[str, str]:+ """`--cpus` and `--memory`: the configured limits, capped at the Docker host's. The daemon+ refuses more CPUs than it has, and a memory limit above the VM's only hides the OOM."""+ info = self._run(["info", "--format", "{{.NCPU}} {{.MemTotal}}"], timeout=30, check=False)try:- host = int(info.stdout.strip())+ cpus, memory = (int(part) for part in info.stdout.split())except ValueError:- host = 0- return str(min(self.limits.vcpus, host) if host > 0 else self.limits.vcpus)+ cpus, memory = 0, 0+ wanted = self.limits.mem_gib * 1024**3+ return (+ str(min(self.limits.vcpus, cpus) if cpus > 0 else self.limits.vcpus),+ str(min(wanted, memory) if memory > 0 else wanted),+ )def available(self) -> tuple[bool, str]:"""Whether Docker answers and the image exists, with a reason when not."""@@ -193,6 +198,7 @@ class DockerSandboxRunner:if state.returncode == 0:self._run(["start", container.name], timeout=60)else:+ cpus, memory = self._host_limits()self._run(["run",@@ -217,9 +223,9 @@ class DockerSandboxRunner:"--pids-limit",str(self.limits.pids),"--cpus",- self._cpu_limit(),+ cpus,"--memory",- f"{self.limits.mem_gib}g",+ memory,"--shm-size",f"{self.limits.shm_gib}g","--mount",diff --git a/tests/fixtures/media/data-viz.test.mjs b/tests/fixtures/media/data-viz.test.mjsindex 48c28ab..ba6940f 100644--- a/tests/fixtures/media/data-viz.test.mjs+++ b/tests/fixtures/media/data-viz.test.mjs@@ -94,6 +94,20 @@ test("brand roles come from the brand pack's palette, with readable text", () =>assert.throws(() => brandTheme(tokens, { roles: { ground: "--brand-color-nope" } }), /unknown token/);});+test("the pack's roles win over the measurement, and a spec's pin over both", () => {+ const graphite = tokens.design.tokens["--brand-color-graphite"];+ const paper = tokens.design.tokens["--brand-color-paper"];+ const withRoles = structuredClone(tokens);+ withRoles.design.roles = { light: { accent: "--brand-color-graphite", series: ["--brand-color-paper"] } };+ const assigned = brandTheme(withRoles);+ assert.equal(assigned.accent, graphite.toLowerCase());+ assert.deepEqual(assigned.series, [paper.toLowerCase()]);+ assert.equal(brandTheme(withRoles, { mode: "dark" }).accent, theme.accent, "a mode without roles is measured");+ assert.equal(brandTheme(withRoles, { roles: { accent: "--brand-color-paper" } }).accent, paper.toLowerCase());+ withRoles.design.roles.light.muted = "--brand-color-nope";+ assert.throws(() => brandTheme(withRoles), /roles\.light\.muted: unknown token/);+});+test("numbers are formatted from the field's unit and precision", () => {assert.equal(formatValue(1200, { unit: "$", precision: 0 }), "$1,200");assert.equal(formatValue(72.04, { unit: "%", precision: 1 }), "72%");diff --git a/tests/render/test_gates_render.py b/tests/render/test_gates_render.pyindex eca6edd..4f6fffa 100644--- a/tests/render/test_gates_render.py+++ b/tests/render/test_gates_render.py@@ -165,6 +165,23 @@ def test_html2png_fails_when_a_required_font_is_missing(sandbox: Sandbox, out: Passert list(out.iterdir()) == []+def test_html2png_counts_a_web_font_under_its_css_family(sandbox: Sandbox, out: Path) -> None:+ """woff2 faces load only through @font-face, and CDP names them by the name inside the file+ (here "Inter"), not the CSS family the page asked for."""+ (out / "f").mkdir()+ shutil.copy(ROOT / "fonts" / "Inter-Variable.ttf", out / "f" / "probe.ttf")+ (out / "page.html").write_text(+ '<style>@font-face{font-family:"Probe Face";src:url("f/probe.woff2") format("woff2")}'+ 'body{font-family:"Probe Face"}</style><body>Probe</body>'+ )+ proc = sandbox(+ "woff2_compress out/f/probe.ttf >/dev/null && "+ 'node tools/html2png.mjs out/page.html --out out --name p --size 400x200 --require-font "Probe Face"'+ )+ assert proc.returncode == 0, proc.stdout + proc.stderr+ assert last_json(proc)["fonts"] == {"Probe Face": True}++def test_html2png_writes_jpeg_and_webp(sandbox: Sandbox, out: Path) -> None:proc = sandbox("node tools/html2png.mjs fixtures/brand/clean.html --out out --name j --size 1080x1080 --format jpeg && "diff --git a/tests/unit/test_brand_schema.py b/tests/unit/test_brand_schema.pyindex da08366..c07422e 100644--- a/tests/unit/test_brand_schema.py+++ b/tests/unit/test_brand_schema.py@@ -71,6 +71,15 @@ def test_tokens_must_use_palette_colors(pack_copy: Path) -> None:load_brand_pack(pack_copy, project_root=ROOT)+def test_colour_roles_name_tokens_that_hold_palette_colours(pack_copy: Path) -> None:+ roles = {"light": {"accent": "--brand-color-signal", "series": ["--brand-color-graphite"]}}+ _mutate(pack_copy, lambda d: d["design"].update(roles=roles))+ assert load_brand_pack(pack_copy, project_root=ROOT).tokens.design.roles["light"].accent+ _mutate(pack_copy, lambda d: d["design"]["roles"]["light"].update(muted="--brand-font-display"))+ with pytest.raises(BrandPackError, match=r"roles\.light\.muted"):+ load_brand_pack(pack_copy, project_root=ROOT)++def test_font_checksum_mismatch_fails(pack_copy: Path) -> None:fonts = ((pack_copy / "fonts.toml")diff --git a/tests/unit/test_cli_commands.py b/tests/unit/test_cli_commands.pyindex fe5f3d7..ebc22ca 100644--- a/tests/unit/test_cli_commands.py+++ b/tests/unit/test_cli_commands.py@@ -24,8 +24,12 @@ def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:def test_brand_init_copies_the_sample_once(project: Path) -> None:+ (project / "workspace/brand").mkdir(parents=True)+ (project / "workspace/brand/README.md").write_text("tracked")first = CliRunner().invoke(cli.main, ["brand", "init"])assert first.exit_code == 0 and (project / "workspace/brand/brand.toml").is_file()+ assert (project / "workspace/brand/README.md").read_text() == "tracked"+ assert not (project / "workspace/brand/LICENSE").exists()assert CliRunner().invoke(cli.main, ["brand", "init"]).exit_code == 1@@ -36,6 +40,17 @@ def test_fonts_verify_checks_checksums_and_licenses(project: Path) -> None:assert result.exit_code == 1 and "Unlisted-Regular.ttf is not listed" in result.output+def test_fonts_verify_catches_a_family_the_file_does_not_carry(project: Path) -> None:+ pack = project / "examples/brands/example-studio"+ for name in ("fonts.toml", "tokens.json"):+ text = (pack / name).read_text()+ assert '"Fraunces"' in text+ (pack / name).write_text(text.replace('"Fraunces"', '"Fraunces Display"'))+ result = CliRunner().invoke(cli.main, ["fonts", "verify"])+ assert result.exit_code == 1+ assert 'says family "Fraunces Display", the file says "Fraunces"' in result.output++def test_sandbox_use_points_local_runs_at_a_snapshot(project: Path) -> None:assert (CliRunner().invoke(cli.main, ["sandbox", "use", "design-agent-computer-abc"]).exit_code == 0diff --git a/tests/unit/test_docker_runner.py b/tests/unit/test_docker_runner.pyindex 26cb81a..1ccbf55 100644--- a/tests/unit/test_docker_runner.py+++ b/tests/unit/test_docker_runner.py@@ -16,11 +16,11 @@ from design_agent.runtime.sandbox.docker import (class RecordingRunner(DockerSandboxRunner):- def __init__(self, host_cpus: int = 16, **kwargs: Any) -> None:+ def __init__(self, host_cpus: int = 16, host_mem_gib: int = 64, **kwargs: Any) -> None:super().__init__(image="design-agent-sandbox:test", **kwargs)self.calls: list[list[str]] = []self.running: set[str] = set()- self.host_cpus = host_cpus+ self.host = f"{host_cpus} {host_mem_gib * 1024**3}\n"def _run(self,@@ -40,7 +40,7 @@ class RecordingRunner(DockerSandboxRunner):b"",)if args[0] == "info":- return subprocess.CompletedProcess(args, 0, f"{self.host_cpus}\n".encode(), b"")+ return subprocess.CompletedProcess(args, 0, self.host.encode(), b"")if args[0] == "run":self.running.add(args[args.index("--name") + 1])if args[0] == "exec" and args[-2:-1] == ["cat"]:@@ -62,12 +62,17 @@ def test_container_runs_isolated() -> None:)[email protected](("host_cpus", "expected"), [(16, "8"), (4, "4")])-def test_the_cpu_limit_never_exceeds_the_docker_host(host_cpus: int, expected: str) -> None:- runner = RecordingRunner(host_cpus=host_cpus)+ ("host_cpus", "host_mem_gib", "cpus", "mem_gib"), [(16, 64, "8", 16), (4, 8, "4", 8)]+)+def test_limits_never_exceed_the_docker_host(+ host_cpus: int, host_mem_gib: int, cpus: str, mem_gib: int+) -> None:+ runner = RecordingRunner(host_cpus=host_cpus, host_mem_gib=host_mem_gib)runner.container_for("t")run = next(c for c in runner.calls if c[0] == "run")- assert run[run.index("--cpus") + 1] == expected+ assert run[run.index("--cpus") + 1] == cpus+ assert run[run.index("--memory") + 1] == str(mem_gib * 1024**3)def test_a_failed_docker_call_reports_the_daemon_reason(monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/test_envfile.py b/tests/unit/test_envfile.pyindex 3d0e6ef..6ebfdda 100644--- a/tests/unit/test_envfile.py+++ b/tests/unit/test_envfile.py@@ -58,3 +58,8 @@ def test_generate_fills_secrets_once(project: Path) -> None:first = read_env(project)["PAPER_BRIDGE_TOKEN"]assert len(first) >= 32 and generate(project, ["PAPER_BRIDGE_TOKEN"]) == []assert read_env(project)["PAPER_BRIDGE_TOKEN"] == first+++def test_a_comment_after_an_empty_value_is_not_the_value(tmp_path: Path) -> None:+ (tmp_path / ".env").write_text("A= # what A is for\nB=#hex\nC=v # note\n")+ assert read_env(tmp_path) == {"A": "", "B": "#hex", "C": "v"}diff --git a/workspace/tools/toolchain.mjs b/workspace/tools/toolchain.mjsindex 22f3bd8..660bc64 100644--- a/workspace/tools/toolchain.mjs+++ b/workspace/tools/toolchain.mjs@@ -228,7 +228,19 @@ export async function unresolvedFonts(page, families) {const { fonts } = await cdp.send("CSS.getPlatformFontsForNode", { nodeId });await page.evaluate((attr) => document.querySelectorAll(`[${attr}]`).forEach((el) => el.remove()), PROBE_ATTR);const used = fonts.map((font) => font.familyName);- if (!checked || !used.some((name) => name.toLowerCase() === family.toLowerCase())) {+ // A system font reports its family; a web font (an @font-face rule, as woff2 faces must be)+ // reports the name inside its file ("Brand Sans 250"), so it counts when a face registered+ // under the requested family loaded and a web font painted the probe.+ const webFace = await page.evaluate(+ (name) =>+ [...document.fonts].some(+ (face) => face.status === "loaded" && face.family.replace(/^["']|["']$/g, "").toLowerCase() === name.toLowerCase(),+ ),+ family,+ );+ const painted =+ used.some((name) => name.toLowerCase() === family.toLowerCase()) || (webFace && fonts.some((font) => font.isCustomFont));+ if (!checked || !painted) {missing.push({ family, renderedWith: used.join(", ") || "nothing" });}}