@imgly/codesign-mcp 0.2.0 → 0.2.1-next.20260820151648.ge42664a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/docs/handbook/SKILL.md +1 -1
- package/assets/docs/judge/SKILL.md +1 -0
- package/dist/assets/inline.generated.js +2 -2
- package/dist/assets/inline.generated.js.map +1 -1
- package/dist/cli/trial-license.generated.d.ts +1 -1
- package/dist/cli/trial-license.generated.js +1 -1
- package/dist/cli/trial-license.generated.js.map +1 -1
- package/dist/instructions.js +1 -1
- package/dist/instructions.js.map +1 -1
- package/dist/revisions/scorecards.d.ts +38 -0
- package/dist/revisions/scorecards.d.ts.map +1 -0
- package/dist/revisions/scorecards.js +59 -0
- package/dist/revisions/scorecards.js.map +1 -0
- package/dist/revisions/store.d.ts +14 -1
- package/dist/revisions/store.d.ts.map +1 -1
- package/dist/revisions/store.js +26 -0
- package/dist/revisions/store.js.map +1 -1
- package/dist/revisions/types.d.ts +10 -0
- package/dist/revisions/types.d.ts.map +1 -1
- package/dist/revisions/types.js.map +1 -1
- package/dist/tools/export.d.ts.map +1 -1
- package/dist/tools/export.js +9 -1
- package/dist/tools/export.js.map +1 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/preview.d.ts.map +1 -1
- package/dist/tools/preview.js +16 -0
- package/dist/tools/preview.js.map +1 -1
- package/dist/tools/scorecard.d.ts +7 -0
- package/dist/tools/scorecard.d.ts.map +1 -0
- package/dist/tools/scorecard.js +75 -0
- package/dist/tools/scorecard.js.map +1 -0
- package/package.json +1 -1
|
@@ -588,12 +588,12 @@ export const INLINE_ASSETS = {
|
|
|
588
588
|
"docs/guide/use-templates/programmatic.md": "> This is one page of the CE.SDK Node.js documentation. For a complete overview, see the [Node.js Documentation Index](https://img.ly/docs/cesdk/node.md). For all docs in one file, see [llms-full.txt](./llms-full.txt.md).\n\n**Navigation:** [Guides](./guides.md) > [Create and Use Templates](./create-templates.md) > [Programmatic](./use-templates/programmatic.md)\n\n---\n\nAutomate template workflows with CE.SDK's engine APIs for batch processing, personalization, and headless design generation.\n\n> **Reading time:** 15 minutes\n>\n> **Resources:**\n>\n> - [Download examples](https://github.com/imgly/cesdk-web-examples/archive/refs/tags/release-$UBQ_VERSION$.zip)\n>\n> - [View source on GitHub](https://github.com/imgly/cesdk-web-examples/tree/release-$UBQ_VERSION$/guides-use-templates-programmatic-server-js)\n>\n> - [Open in StackBlitz](https://stackblitz.com/github/imgly/cesdk-web-examples/tree/v$UBQ_VERSION$/guides-use-templates-programmatic-server-js)\n\nTemplates are scenes with predefined structures that support dynamic content through variables. This guide shows you how to work with templates programmatically using CE.SDK's engine APIs—without requiring user interface interactions.\n\n```typescript file=@cesdk_web_examples/guides-use-templates-programmatic-server-js/server-js.ts reference-only\nimport CreativeEngine from '@cesdk/node';\nimport { writeFileSync } from 'fs';\nimport { config as loadEnv } from 'dotenv';\n\n// Load environment variables\nloadEnv();\n\n/**\n * Use Templates Programmatically (Server/Node.js)\n *\n * This example demonstrates headless template workflows:\n * 1. Creating templates from scratch with text variables\n * 2. Setting up text variables for dynamic content\n * 3. Batch processing: populating templates with data\n * 4. Exporting multiple personalized outputs\n */\n\nasync function run() {\n let engine;\n\n try {\n const config = {\n baseURL: process.env.IMGLY_LOCAL_ASSETS_URL,\n // license: process.env.CESDK_LICENSE,\n logger: (message: string, logLevel?: string) => {\n if (logLevel === 'ERROR' || logLevel === 'WARN') {\n console.log(`[${logLevel}]`, message);\n }\n }\n };\n\n engine = await CreativeEngine.init(config);\n console.log('✓ Engine initialized');\n\n // Create a greeting card template from scratch\n const scene = engine.scene.create();\n const page = engine.block.create('page');\n engine.block.appendChild(scene, page);\n\n // Set page dimensions\n engine.block.setWidth(page, 800);\n engine.block.setHeight(page, 600);\n\n // Set page background\n const pageFill = engine.block.getFill(page);\n engine.block.setColor(pageFill, 'fill/color/value', {\n r: 0.95,\n g: 0.95,\n b: 0.95,\n a: 1.0\n });\n\n // Set up text variables FIRST so they're available when text is created\n engine.variable.setString('recipientName', 'Template');\n engine.variable.setString('customMessage', 'This is a template example');\n\n // Add title text block with variable placeholder\n const titleBlock = engine.block.create('text');\n engine.block.setName(titleBlock, 'title');\n engine.block.appendChild(page, titleBlock);\n engine.block.setPositionX(titleBlock, 50);\n engine.block.setPositionY(titleBlock, 50);\n engine.block.setWidth(titleBlock, 700);\n engine.block.setHeight(titleBlock, 80);\n\n // Set text with variable syntax\n engine.block.replaceText(titleBlock, 'Hello, {{recipientName}}!');\n engine.block.setTextColor(titleBlock, {\n r: 0.2,\n g: 0.2,\n b: 0.2,\n a: 1.0\n });\n\n // Configure font size and weight\n engine.block.setFloat(titleBlock, 'text/fontSize', 48);\n engine.block.setBool(titleBlock, 'text/bold', true);\n\n // Add message text block with variable\n const messageBlock = engine.block.create('text');\n engine.block.setName(messageBlock, 'message');\n engine.block.appendChild(page, messageBlock);\n engine.block.setPositionX(messageBlock, 50);\n engine.block.setPositionY(messageBlock, 140);\n engine.block.setWidth(messageBlock, 700);\n engine.block.setHeight(messageBlock, 120);\n\n engine.block.replaceText(messageBlock, '{{customMessage}}');\n engine.block.setTextColor(messageBlock, {\n r: 0.3,\n g: 0.3,\n b: 0.3,\n a: 1.0\n });\n\n engine.block.setFloat(messageBlock, 'text/fontSize', 28);\n\n console.log('✓ Template structure created');\n\n // Variables have already been set earlier in the template creation\n // List all variables\n const allVariables = engine.variable.findAll();\n console.log('✓ Variables initialized:', allVariables);\n\n // Save the template for reuse\n const templateString = await engine.scene.saveToString();\n writeFileSync('template.imgly', templateString);\n console.log('✓ Template saved to template.imgly');\n\n // Demonstrate batch processing: populate template with multiple data records\n const recipients = [\n {\n name: 'Alice',\n message: 'Congratulations on your promotion!'\n },\n {\n name: 'Bob',\n message: 'Happy Birthday! Have a wonderful day!'\n },\n {\n name: 'Charlie',\n message: 'Thank you for your amazing work!'\n }\n ];\n\n console.log('\\n✓ Starting batch processing...');\n\n for (let i = 0; i < recipients.length; i++) {\n const recipient = recipients[i];\n\n // Populate template with recipient data\n engine.variable.setString('recipientName', recipient.name);\n engine.variable.setString('customMessage', recipient.message);\n\n // Export the personalized card\n const blob = await engine.block.export(page, {\n mimeType: 'image/png',\n targetWidth: 800,\n targetHeight: 600\n });\n\n const filename = `greeting-card-${recipient.name.toLowerCase()}.png`;\n const buffer = Buffer.from(await blob.arrayBuffer());\n writeFileSync(filename, buffer);\n console.log(` ✓ Exported ${filename}`);\n }\n\n console.log('\\n✓ Batch processing complete!');\n console.log(`✓ Generated ${recipients.length} personalized cards`);\n\n console.log('\\n✓ All operations completed successfully!');\n } catch (error) {\n console.error('Error:', error);\n process.exit(1);\n } finally {\n // Always dispose the engine\n engine?.dispose();\n console.log('\\n✓ Engine disposed');\n }\n}\n\n// Run the example\nrun();\n```\n\nThis guide covers creating templates from scratch, configuring text variables, populating templates with data, implementing batch processing workflows, and exporting personalized designs.\n\n## Initialize CE.SDK\n\nWe start by initializing CE.SDK and creating a design scene. This provides the foundation for programmatic template operations.\n\n```typescript highlight=highlight-setup\n const config = {\n baseURL: process.env.IMGLY_LOCAL_ASSETS_URL,\n // license: process.env.CESDK_LICENSE,\n logger: (message: string, logLevel?: string) => {\n if (logLevel === 'ERROR' || logLevel === 'WARN') {\n console.log(`[${logLevel}]`, message);\n }\n }\n };\n\n engine = await CreativeEngine.init(config);\n console.log('✓ Engine initialized');\n```\n\nWe create a page with specific dimensions and set a light gray background. This serves as the canvas for our template structure.\n\n## Creating Templates from Scratch\n\nWe build templates programmatically by creating and arranging blocks with `engine.block.create()` and `engine.block.appendChild()`.\n\n```typescript highlight=highlight-create-template\n // Create a greeting card template from scratch\n const scene = engine.scene.create();\n const page = engine.block.create('page');\n engine.block.appendChild(scene, page);\n\n // Set page dimensions\n engine.block.setWidth(page, 800);\n engine.block.setHeight(page, 600);\n\n // Set page background\n const pageFill = engine.block.getFill(page);\n engine.block.setColor(pageFill, 'fill/color/value', {\n r: 0.95,\n g: 0.95,\n b: 0.95,\n a: 1.0\n });\n\n // Set up text variables FIRST so they're available when text is created\n engine.variable.setString('recipientName', 'Template');\n engine.variable.setString('customMessage', 'This is a template example');\n\n // Add title text block with variable placeholder\n const titleBlock = engine.block.create('text');\n engine.block.setName(titleBlock, 'title');\n engine.block.appendChild(page, titleBlock);\n engine.block.setPositionX(titleBlock, 50);\n engine.block.setPositionY(titleBlock, 50);\n engine.block.setWidth(titleBlock, 700);\n engine.block.setHeight(titleBlock, 80);\n\n // Set text with variable syntax\n engine.block.replaceText(titleBlock, 'Hello, {{recipientName}}!');\n engine.block.setTextColor(titleBlock, {\n r: 0.2,\n g: 0.2,\n b: 0.2,\n a: 1.0\n });\n\n // Configure font size and weight\n engine.block.setFloat(titleBlock, 'text/fontSize', 48);\n engine.block.setBool(titleBlock, 'text/bold', true);\n\n // Add message text block with variable\n const messageBlock = engine.block.create('text');\n engine.block.setName(messageBlock, 'message');\n engine.block.appendChild(page, messageBlock);\n engine.block.setPositionX(messageBlock, 50);\n engine.block.setPositionY(messageBlock, 140);\n engine.block.setWidth(messageBlock, 700);\n engine.block.setHeight(messageBlock, 120);\n\n engine.block.replaceText(messageBlock, '{{customMessage}}');\n engine.block.setTextColor(messageBlock, {\n r: 0.3,\n g: 0.3,\n b: 0.3,\n a: 1.0\n });\n\n engine.block.setFloat(messageBlock, 'text/fontSize', 28);\n\n console.log('✓ Template structure created');\n```\n\nWe create a greeting card template with two text blocks. The title block contains `{{recipientName}}` and the message block contains `{{customMessage}}`—these double-brace syntax markers define where variables will be replaced. We position each block precisely and configure text properties like font size and color.\n\n## Text Variables for Dynamic Content\n\nVariables enable text replacement throughout templates. We set variable values with `engine.variable.setString()`, which automatically updates any text containing `{{variableName}}` syntax.\n\n```typescript highlight=highlight-manage-variables\n// Variables have already been set earlier in the template creation\n// List all variables\nconst allVariables = engine.variable.findAll();\nconsole.log('✓ Variables initialized:', allVariables);\n```\n\nWe initialize variables for `recipientName` and `customMessage`. The `engine.variable.getString()` method retrieves current values, and `engine.variable.findAll()` lists all variables in the scene. Variables persist with the scene and automatically update text content whenever changed.\n\n## Saving Templates for Reuse\n\nTemplates can be serialized for storage and reuse. We use `engine.scene.saveToString()` to create portable template files.\n\n```typescript highlight=highlight-save-template\n// Save the template for reuse\nconst templateString = await engine.scene.saveToString();\nwriteFileSync('template.imgly', templateString);\nconsole.log('✓ Template saved to template.imgly');\n```\n\nThe `saveToString()` method returns a base64-encoded string containing the complete scene. This string can be stored in databases or file systems for later use in batch processing workflows.\n\n## Batch Processing with Templates\n\nWe demonstrate batch processing by populating the template with multiple data records and exporting personalized outputs.\n\n```typescript highlight=highlight-batch-processing\n // Demonstrate batch processing: populate template with multiple data records\n const recipients = [\n {\n name: 'Alice',\n message: 'Congratulations on your promotion!'\n },\n {\n name: 'Bob',\n message: 'Happy Birthday! Have a wonderful day!'\n },\n {\n name: 'Charlie',\n message: 'Thank you for your amazing work!'\n }\n ];\n\n console.log('\\n✓ Starting batch processing...');\n\n for (let i = 0; i < recipients.length; i++) {\n const recipient = recipients[i];\n\n // Populate template with recipient data\n engine.variable.setString('recipientName', recipient.name);\n engine.variable.setString('customMessage', recipient.message);\n\n // Export the personalized card\n const blob = await engine.block.export(page, {\n mimeType: 'image/png',\n targetWidth: 800,\n targetHeight: 600\n });\n\n const filename = `greeting-card-${recipient.name.toLowerCase()}.png`;\n const buffer = Buffer.from(await blob.arrayBuffer());\n writeFileSync(filename, buffer);\n console.log(` ✓ Exported ${filename}`);\n }\n\n console.log('\\n✓ Batch processing complete!');\n console.log(`✓ Generated ${recipients.length} personalized cards`);\n```\n\nThe batch processing pattern loads a template once, then iterates through data records. For each record, we update variables with specific values, then export the result. This efficient approach generates multiple personalized designs from a single template. Each export operation renders the current state to a PNG file saved to disk.\n\n## Data-Driven Workflows\n\nBatch processing combines template creation, data population, and export operations. A common pattern loads a template once, then iterates through data records:\n\n```typescript\nconst templateString = await engine.scene.saveToString();\n\nfor (const record of dataRecords) {\n await engine.scene.load(templateString);\n engine.variable.setString('name', record.name);\n engine.variable.setString('title', record.title);\n\n const page = engine.block.findByType('page')[0];\n const buffer = await engine.block.export(page, 'image/png');\n writeFileSync(`output-${record.id}.png`, Buffer.from(buffer));\n}\n```\n\nThis pattern works for generating personalized certificates, greeting cards, social media graphics, or any scenario requiring multiple customized outputs from a single template.\n\n## Loading Existing Templates\n\nTemplates can be loaded from various sources. Use `engine.scene.load()` to fetch remote templates:\n\n```typescript\nawait engine.scene.load(\n 'https://cdn.img.ly/assets/demo/v1/ly.img.template/templates/cesdk_postcard_1.scene'\n);\n```\n\nFor templates with embedded assets, `engine.scene.load()` loads the complete package including all resources.\n\nThe `engine.scene.applyTemplateFromString()` and `engine.scene.applyTemplateFromURL()` methods merge template content into existing scenes without replacing everything—useful for adding template sections to ongoing designs.\n\n## Populating Template Content\n\nWe populate templates by updating variables with new data. When variables are updated, all text blocks containing those variable references automatically display the new values. This approach enables efficient template population without manually finding and updating individual blocks.\n\n## Managing Variables\n\nVariables integrate with text blocks automatically. When you set a variable value, CE.SDK updates all text containing that variable immediately:\n\n```typescript\nengine.variable.setString('userName', 'Alice');\n// All text with {{userName}} now displays 'Alice'\n\nengine.variable.setString('userName', 'Bob');\n// Same text now displays 'Bob'\n```\n\nRemove variables with `engine.variable.remove()` when they're no longer needed. This doesn't affect existing text—the variable syntax remains as literal text.\n\n## API Reference\n\n| Method | Description |\n| --- | --- |\n| `engine.block.create()` | Create a new design block |\n| `engine.block.appendChild()` | Add a block to the scene hierarchy |\n| `engine.block.setPositionX()` | Set block horizontal position |\n| `engine.block.setPositionY()` | Set block vertical position |\n| `engine.block.setWidth()` | Set block width |\n| `engine.block.setHeight()` | Set block height |\n| `engine.block.replaceText()` | Set text content (supports variable tokens) |\n| `engine.variable.setString()` | Create or update a text variable |\n| `engine.variable.getString()` | Read the current value of a variable |\n| `engine.variable.findAll()` | Get array of all variable keys in the scene |\n| `engine.variable.remove()` | Delete a variable from the scene |\n| `engine.scene.saveToString()` | Serialize scene to portable string |\n| `engine.scene.load()` | Load a scene from a remote URL or a serialized string |\n| `engine.block.export()` | Export block to image blob |\n\n## Troubleshooting\n\n**Template loading failures:** Verify scene strings are properly encoded and URLs are accessible. Use `try-catch` blocks around loading operations to handle network or parsing errors.\n\n**Variables not replacing text:** Variable names in text (within `{{}}`) must exactly match keys passed to `engine.variable.setString()`. Variables are case-sensitive.\n\n**Export issues:** Validate that all required assets are accessible before exporting. Missing images or fonts can cause export failures. Check block hierarchy structure—orphaned blocks (not connected to the page tree) won't appear in exports.\n\n\n\n---\n\n## More Resources\n\n- **[Node.js Documentation Index](https://img.ly/docs/cesdk/node.md)** - Browse all Node.js documentation\n- **[Complete Documentation](./llms-full.txt.md)** - Full documentation in one file (for LLMs)\n- **[Web Documentation](./node.md)** - Interactive documentation with examples\n- **[Support](mailto:support@img.ly)** - Contact IMG.LY support",
|
|
589
589
|
"docs/guide/use-templates/replace-content.md": "> This is one page of the CE.SDK Node.js documentation. For a complete overview, see the [Node.js Documentation Index](https://img.ly/docs/cesdk/node.md). For all docs in one file, see [llms-full.txt](./llms-full.txt.md).\n\n**Navigation:** [Guides](./guides.md) > [Create and Use Templates](./create-templates.md) > [Replace Content](./use-templates/replace-content.md)\n\n---\n\nDynamically replace content within templates using CE.SDK's placeholder and variable systems in server-side Node.js applications. Find placeholder blocks by name, update text using variables, and swap images programmatically.\n\n> **Reading time:** 10 minutes\n>\n> **Resources:**\n>\n> - [Download examples](https://github.com/imgly/cesdk-web-examples/archive/refs/tags/release-$UBQ_VERSION$.zip)\n>\n> - [View source on GitHub](https://github.com/imgly/cesdk-web-examples/tree/release-$UBQ_VERSION$/guides-use-templates-replace-content-server-js)\n>\n> - [Open in StackBlitz](https://stackblitz.com/github/imgly/cesdk-web-examples/tree/v$UBQ_VERSION$/guides-use-templates-replace-content-server-js)\n\nTemplate content replacement enables dynamic designs by swapping placeholder content programmatically. Templates contain blocks marked as placeholders that can be located by name or discovered in bulk for batch processing. Text replacement uses the variable system with `{{variableName}}` syntax, while images are updated by modifying fill properties.\n\n```typescript file=@cesdk_web_examples/guides-use-templates-replace-content-server-js/server-js.ts reference-only\nimport CreativeEngine from '@cesdk/node';\nimport { writeFileSync, mkdirSync, existsSync } from 'fs';\nimport { config } from 'dotenv';\n\n// Load environment variables\nconfig();\n\n/**\n * CE.SDK Server Guide: Replace Content\n *\n * Demonstrates how to dynamically replace content in templates:\n * - Finding placeholder blocks by name\n * - Using text variables for dynamic content\n * - Replacing image sources\n * - Building data-driven template workflows\n */\nasync function main() {\n // Initialize the headless Creative Engine\n const engine = await CreativeEngine.init({\n baseURL: process.env.IMGLY_LOCAL_ASSETS_URL\n // license: process.env.CESDK_LICENSE\n });\n\n try {\n // Create a scene with a page\n engine.scene.create('VerticalStack', {\n page: { size: { width: 800, height: 600 } }\n });\n\n const page = engine.block.findByType('page')[0];\n\n // Create a text block with a name for later retrieval\n const headerText = engine.block.create('text');\n engine.block.setName(headerText, 'header-text');\n engine.block.replaceText(headerText, 'Welcome, {{userName}}!');\n engine.block.setTextFontSize(headerText, 96);\n engine.block.setWidthMode(headerText, 'Auto');\n engine.block.setHeightMode(headerText, 'Auto');\n engine.block.appendChild(page, headerText);\n engine.block.setPositionX(headerText, 50);\n engine.block.setPositionY(headerText, 30);\n\n // Find the block by its name\n const [foundHeader] = engine.block.findByName('header-text');\n console.log('Found header block:', foundHeader);\n\n // Enable placeholder behavior on blocks\n engine.block.setPlaceholderEnabled(headerText, true);\n\n // Create an image placeholder\n const imageBlock = await engine.block.addImage(\n 'https://img.ly/static/ubq_samples/sample_1.jpg',\n { size: { width: 300, height: 200 } }\n );\n engine.block.appendChild(page, imageBlock);\n engine.block.setPositionX(imageBlock, 50);\n engine.block.setPositionY(imageBlock, 120);\n engine.block.setName(imageBlock, 'product-image');\n engine.block.setPlaceholderEnabled(imageBlock, true);\n\n // Find all placeholder blocks in the scene\n const placeholders = engine.block.findAllPlaceholders();\n console.log('Found placeholders:', placeholders.length);\n\n // Check if a block supports placeholder behavior\n const supportsPlaceholder =\n engine.block.supportsPlaceholderBehavior(imageBlock);\n console.log('Supports placeholder behavior:', supportsPlaceholder);\n\n // Check if placeholder is enabled\n const isPlaceholderEnabled = engine.block.isPlaceholderEnabled(imageBlock);\n console.log('Placeholder enabled:', isPlaceholderEnabled);\n\n // Set text variables to replace {{variableName}} placeholders\n engine.variable.setString('userName', 'Alex');\n\n // The text block now displays \"Welcome, Alex!\"\n console.log('Variable set, text updated automatically');\n\n // List all variables in the scene\n const allVariables = engine.variable.findAll();\n console.log('All variables:', allVariables);\n\n // Get a variable value\n const userName = engine.variable.getString('userName');\n console.log('Current userName:', userName);\n\n // Update the variable\n engine.variable.setString('userName', 'Jordan');\n\n // Replace image content by updating the fill's image URI\n const [productImage] = engine.block.findByName('product-image');\n const fill = engine.block.getFill(productImage);\n engine.block.setString(\n fill,\n 'fill/image/imageFileURI',\n 'https://img.ly/static/ubq_samples/sample_2.jpg'\n );\n console.log('Image replaced');\n\n // Create another text block for direct replacement\n const subtitleText = engine.block.create('text');\n engine.block.setName(subtitleText, 'subtitle');\n engine.block.replaceText(subtitleText, 'Original subtitle text');\n engine.block.setTextFontSize(subtitleText, 48);\n engine.block.setWidthMode(subtitleText, 'Auto');\n engine.block.setHeightMode(subtitleText, 'Auto');\n engine.block.appendChild(page, subtitleText);\n engine.block.setPositionX(subtitleText, 50);\n engine.block.setPositionY(subtitleText, 350);\n\n // Replace text directly without using variables\n const [subtitle] = engine.block.findByName('subtitle');\n engine.block.replaceText(subtitle, 'Updated subtitle content');\n console.log('Text replaced directly');\n\n // Demonstrate data-driven template workflow pattern\n const dataRecords = [\n { name: 'Alice', title: 'Designer' },\n { name: 'Bob', title: 'Developer' }\n ];\n\n // Process each record (in practice, you'd export between iterations)\n for (const record of dataRecords) {\n engine.variable.setString('userName', record.name);\n console.log(`Processed record for: ${record.name}`);\n // In a real workflow, you would export here:\n // const blob = await engine.block.export(page, { mimeType: 'image/png' });\n }\n\n // Export the final result\n const outputDir = './output';\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n\n const blob = await engine.block.export(page, { mimeType: 'image/png' });\n const buffer = Buffer.from(await blob.arrayBuffer());\n writeFileSync(`${outputDir}/replaced-content.png`, buffer);\n\n console.log('Exported result to output/replaced-content.png');\n } finally {\n // Always dispose of the engine to free resources\n engine.dispose();\n }\n}\n\nmain().catch(console.error);\n```\n\nThis guide covers how to find placeholder blocks, replace text using variables, swap image content, and build data-driven template workflows in server-side applications.\n\n## Initialize the Engine\n\nWe start by initializing the headless Creative Engine with a scene and page for our template processing workflow.\n\n```typescript highlight=highlight-setup\n // Initialize the headless Creative Engine\n const engine = await CreativeEngine.init({\n baseURL: process.env.IMGLY_LOCAL_ASSETS_URL\n // license: process.env.CESDK_LICENSE\n });\n\n try {\n // Create a scene with a page\n engine.scene.create('VerticalStack', {\n page: { size: { width: 800, height: 600 } }\n });\n\n const page = engine.block.findByType('page')[0];\n```\n\n## Finding Placeholder Blocks\n\nLocate replaceable content using block discovery APIs. Use `engine.block.findByName()` to find specific blocks when you know the placeholder name.\n\n```typescript highlight=highlight-find-by-name\n // Create a text block with a name for later retrieval\n const headerText = engine.block.create('text');\n engine.block.setName(headerText, 'header-text');\n engine.block.replaceText(headerText, 'Welcome, {{userName}}!');\n engine.block.setTextFontSize(headerText, 96);\n engine.block.setWidthMode(headerText, 'Auto');\n engine.block.setHeightMode(headerText, 'Auto');\n engine.block.appendChild(page, headerText);\n engine.block.setPositionX(headerText, 50);\n engine.block.setPositionY(headerText, 30);\n\n // Find the block by its name\n const [foundHeader] = engine.block.findByName('header-text');\n console.log('Found header block:', foundHeader);\n```\n\n### Discover All Placeholders\n\nUse `engine.block.findAllPlaceholders()` to discover all placeholder blocks in a template for iterating through them programmatically.\n\n```typescript highlight=highlight-find-all-placeholders\n // Enable placeholder behavior on blocks\n engine.block.setPlaceholderEnabled(headerText, true);\n\n // Create an image placeholder\n const imageBlock = await engine.block.addImage(\n 'https://img.ly/static/ubq_samples/sample_1.jpg',\n { size: { width: 300, height: 200 } }\n );\n engine.block.appendChild(page, imageBlock);\n engine.block.setPositionX(imageBlock, 50);\n engine.block.setPositionY(imageBlock, 120);\n engine.block.setName(imageBlock, 'product-image');\n engine.block.setPlaceholderEnabled(imageBlock, true);\n\n // Find all placeholder blocks in the scene\n const placeholders = engine.block.findAllPlaceholders();\n console.log('Found placeholders:', placeholders.length);\n```\n\n### Query Placeholder State\n\nVerify blocks support replacement with `engine.block.isPlaceholderEnabled()` and `engine.block.supportsPlaceholderBehavior()` before attempting content updates.\n\n```typescript highlight=highlight-query-placeholder-state\n // Check if a block supports placeholder behavior\n const supportsPlaceholder =\n engine.block.supportsPlaceholderBehavior(imageBlock);\n console.log('Supports placeholder behavior:', supportsPlaceholder);\n\n // Check if placeholder is enabled\n const isPlaceholderEnabled = engine.block.isPlaceholderEnabled(imageBlock);\n console.log('Placeholder enabled:', isPlaceholderEnabled);\n```\n\n## Text Variable Replacement\n\nReplace text content dynamically using CE.SDK's variable system. Text blocks containing `{{variableName}}` syntax automatically update when you set variable values with `engine.variable.setString()`.\n\n```typescript highlight=highlight-text-variables\n // Set text variables to replace {{variableName}} placeholders\n engine.variable.setString('userName', 'Alex');\n\n // The text block now displays \"Welcome, Alex!\"\n console.log('Variable set, text updated automatically');\n```\n\n### Managing Variables\n\nList all variables with `engine.variable.findAll()`, retrieve current values using `engine.variable.getString()`, and update variables as needed.\n\n```typescript highlight=highlight-manage-variables\n // List all variables in the scene\n const allVariables = engine.variable.findAll();\n console.log('All variables:', allVariables);\n\n // Get a variable value\n const userName = engine.variable.getString('userName');\n console.log('Current userName:', userName);\n\n // Update the variable\n engine.variable.setString('userName', 'Jordan');\n```\n\n## Replacing Image Content\n\nUpdate image placeholders by modifying the fill's image URI. First get the fill block using `engine.block.getFill()`, then set the new image source with `engine.block.setString()` on the `'fill/image/imageFileURI'` property.\n\n```typescript highlight=highlight-replace-image\n// Replace image content by updating the fill's image URI\nconst [productImage] = engine.block.findByName('product-image');\nconst fill = engine.block.getFill(productImage);\nengine.block.setString(\n fill,\n 'fill/image/imageFileURI',\n 'https://img.ly/static/ubq_samples/sample_2.jpg'\n);\nconsole.log('Image replaced');\n```\n\n## Direct Text Replacement\n\nReplace text content directly without variables using `engine.block.replaceText()`. This method replaces all text in a block when you need precise control without the variable system.\n\n```typescript highlight=highlight-direct-text-replacement\n // Create another text block for direct replacement\n const subtitleText = engine.block.create('text');\n engine.block.setName(subtitleText, 'subtitle');\n engine.block.replaceText(subtitleText, 'Original subtitle text');\n engine.block.setTextFontSize(subtitleText, 48);\n engine.block.setWidthMode(subtitleText, 'Auto');\n engine.block.setHeightMode(subtitleText, 'Auto');\n engine.block.appendChild(page, subtitleText);\n engine.block.setPositionX(subtitleText, 50);\n engine.block.setPositionY(subtitleText, 350);\n\n // Replace text directly without using variables\n const [subtitle] = engine.block.findByName('subtitle');\n engine.block.replaceText(subtitle, 'Updated subtitle content');\n console.log('Text replaced directly');\n```\n\n## Data-Driven Template Workflows\n\nBuild automated template population by iterating through data records. Load the template once, then loop through your data, updating variables and placeholders for each record before exporting.\n\n```typescript highlight=highlight-data-driven\n // Demonstrate data-driven template workflow pattern\n const dataRecords = [\n { name: 'Alice', title: 'Designer' },\n { name: 'Bob', title: 'Developer' }\n ];\n\n // Process each record (in practice, you'd export between iterations)\n for (const record of dataRecords) {\n engine.variable.setString('userName', record.name);\n console.log(`Processed record for: ${record.name}`);\n // In a real workflow, you would export here:\n // const blob = await engine.block.export(page, { mimeType: 'image/png' });\n }\n```\n\n## Export and Cleanup\n\nAfter processing the template, we export the result to a file and dispose of the engine to free resources.\n\n```typescript highlight=highlight-export\n // Export the final result\n const outputDir = './output';\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n\n const blob = await engine.block.export(page, { mimeType: 'image/png' });\n const buffer = Buffer.from(await blob.arrayBuffer());\n writeFileSync(`${outputDir}/replaced-content.png`, buffer);\n\n console.log('Exported result to output/replaced-content.png');\n```\n\nAlways dispose of the engine in a finally block to ensure resources are freed even if an error occurs.\n\n```typescript highlight=highlight-cleanup\n// Always dispose of the engine to free resources\nengine.dispose();\n```\n\n## Troubleshooting\n\n### Block Not Found by Name\n\nVerify the exact name string matches what's set in the template. Names are case-sensitive. Use `engine.block.getName()` to inspect existing block names.\n\n### Variable Not Replacing Text\n\nEnsure the variable syntax `{{variableName}}` in the text block matches the key used in `engine.variable.setString()` exactly, including casing.\n\n### Image Not Updating\n\nConfirm the block has an image fill by checking `engine.block.getFill()` returns a valid fill block. Verify the URI is accessible and properly formatted.\n\n### Placeholder State Queries Return False\n\nNot all blocks support placeholder behavior. Use `engine.block.supportsPlaceholderBehavior()` to check compatibility before querying enabled state.\n\n## API Reference\n\n| Method | Description |\n|--------|-------------|\n| `block.findByName(name)` | Find blocks by name identifier |\n| `block.getName(block)` | Get the name of a block |\n| `block.findAllPlaceholders()` | Discover all placeholder blocks in scene |\n| `block.isPlaceholderEnabled(block)` | Check if placeholder functionality is enabled |\n| `block.supportsPlaceholderBehavior(block)` | Verify block supports placeholder behavior |\n| `block.getFill(block)` | Get fill block from a graphic block |\n| `block.setString(block, property, value)` | Set string properties like image URIs |\n| `block.replaceText(block, text)` | Replace text content directly |\n| `variable.setString(name, value)` | Set text variable value for dynamic replacement |\n| `variable.getString(name)` | Get current variable value |\n| `variable.findAll()` | List all variable names in scene |\n\n\n\n---\n\n## More Resources\n\n- **[Node.js Documentation Index](https://img.ly/docs/cesdk/node.md)** - Browse all Node.js documentation\n- **[Complete Documentation](./llms-full.txt.md)** - Full documentation in one file (for LLMs)\n- **[Web Documentation](./node.md)** - Interactive documentation with examples\n- **[Support](mailto:support@img.ly)** - Contact IMG.LY support",
|
|
590
590
|
"docs/guide/what-is-cesdk.md": "> This is one page of the CE.SDK Node.js documentation. For a complete overview, see the [Node.js Documentation Index](https://img.ly/docs/cesdk/node.md). For all docs in one file, see [llms-full.txt](./llms-full.txt.md).\n\n**Navigation:** [Get Started](./get-started/overview.md) > [What is CE.SDK?](./what-is-cesdk.md)\n\n---\n\n### What is CE.SDK?\n\n**CreativeEditor SDK (CE.SDK)** on Node.js is a powerful design engine that brings fully automated image and design editing directly into your Node app. Whether you're enabling AI-powered design workflows, template-based creation, or dynamic content generation, CE.SDK offers the flexibility, performance, and developer control you need — all with minimal integration overhead.\n\n[Get Started](./get-started/overview.md)\n\nTrusted by leading organizations worldwide, CE.SDK powers the creative editors used in best-in-class applications, including those from Shopify, Semrush, HP, Shutterfly, Ticketmaster, and Swiss Post.\n\n## Key Capabilities of the Node.js Creative Editor SDK\n\n<CapabilityGrid\n features={[\n {\n title: 'Transform',\n description:\n 'Perform operations like cropping, rotating, and resizing design elements.',\n imageId: 'transform',\n },\n {\n title: 'Templating',\n description:\n 'Create and apply design templates with placeholders and text variables for dynamic content.',\n imageId: 'templating',\n },\n {\n title: 'Placeholders & Lockable Design',\n description:\n 'Constrain templates to guide your users’ design and ensure brand consistency.',\n imageId: 'placeholders',\n },\n {\n title: 'Asset Management',\n description:\n 'Import and manage images, shapes, and other assets to build your designs.',\n imageId: 'asset-libraries',\n },\n {\n title: 'Design Collage',\n description:\n 'Arrange multiple elements on a single canvas to create complex layouts.',\n imageId: 'video-collage',\n },\n {\n title: 'Text Editing',\n description:\n 'Add and style text blocks with various fonts, colors, and effects.',\n imageId: 'text-editing',\n },\n {\n title: 'Background Removal',\n description:\n 'This plugin makes it easy to remove the background from images running entirely in the browser.',\n imageId: 'green-screen',\n },\n {\n title: 'Extendible',\n description:\n 'Hook into the engine API and editor events to implement custom features.',\n imageId: 'extendible',\n },\n {\n title: 'Headless & Automation',\n description:\n 'Programmatically edit designs within your React application using the engine API.',\n imageId: 'headless',\n },\n]}\n/>\n\n## File Format Support\n\nCE.SDK supports a wide range of file types to ensure maximum flexibility for developers:\n\n### Importing Media\n\n### Exporting Media\n\n### Importing Templates\n\nFor detailed information, see the [full file format support list](./file-format-support.md).\n\n## Integrations\n\nCE.SDK supports out-of-the-box integrations with:\n\n- **Getty Images**\n- **Unsplash**\n- **Pexels**\n- **Soundstripe**\n\nWant to connect your own asset sources? Register a custom provider using our API.\n\n\n\n---\n\n## More Resources\n\n- **[Node.js Documentation Index](https://img.ly/docs/cesdk/node.md)** - Browse all Node.js documentation\n- **[Complete Documentation](./llms-full.txt.md)** - Full documentation in one file (for LLMs)\n- **[Web Documentation](./node.md)** - Interactive documentation with examples\n- **[Support](mailto:support@img.ly)** - Contact IMG.LY support",
|
|
591
|
-
"docs/handbook/SKILL.md": "---\nname: handbook\ndescription: |\n The CoDesign design loop, tool contract, workspace cheatsheet, typeface\n schema, common operations cheatsheet, and the full design-quality rubric.\n **Read this skill before any edit call** — it contains the 5-step Loop\n (decide parent → read API → exec → preview → judge), the tool roster and\n cross-tool rules, the workspace revision model (list / history / rename),\n rewind-recovery procedure, the typeface object shape required by setFont,\n and §6: the design-rules index — the full enforceable rubric (typography,\n hierarchy, composition, craft) ships as this skill's design-rules.md, the\n runtime-quirk reference as its quirks.md, and the input-resolution contract\n every skill follows as its intake.md, all read on demand.\n\n Triggered for any task using this server's `edit` or `preview` tools.\n---\n\n## 1. Loop\n\nYou MUST follow these steps in order for ANY canvas change:\n\n1. **Decide where you're editing from — based on what the user asked for, not what's in the workspace.** Either:\n - **New design requested** (the default in a fresh conversation) → pass `parent: null` and supply a `title` (the design name). The workspace persists across all past conversations — designs in it are not yours to continue unless the user points at them. For a new design, run the `create` skill's intake first to assemble the brief — and when two or more of the five design-defining parameters (topic, audience, visual direction, brand, format) are neither stated nor safely inferable, that intake **asks** before this edit rather than defaulting them.\n - **Continuing this conversation's design** → use the `revision` id from your last `edit` response as `parent`.\n - **User explicitly asked to resume earlier work** (\"keep working on yesterday's flyer\") → call `list` to see designs newest-first, then `history({ revision })` on the design they meant; pass the leaf as `parent`. Never do this unprompted.\n\n2. **Read the API docs** for every engine method you plan to use. Use `skill({ name: 'api' })` for signatures, `skill({ name: 'guide' })` for prose explanations and recipes. NEVER guess parameters.\n3. **Run `edit({ parent, code, note? })`** — execute the JS body. The response's first text part is JSON `{ revision, parent }` — save `revision`; it's your `parent` for the next edit.\n4. **Visually verify.** Call `preview({ blockIds: [<pageId>], revision })` — `revision` is REQUIRED; omit `blockIds` for every page. Never tell the user something \"looks good\" without seeing it yourself.\n\n5. **Judge & remediate before reporting done.** When the design is a candidate for \"done\", run the build → judge → remediate loop from the `judge` skill: score all 8 design axes against your actual `preview` renders, dry-run the applicable §6 Pass checklists (§6.1.11, §6.5.2 — in this skill's design-rules.md), and remediate any applicable axis below 8 via further `edit`s — then re-preview and re-judge. Never report an unjudged design as done.\n\nSteps 1, 2, 4, and 5 are NOT optional. Step 3's `note` is encouraged: a one-liner describing what you accomplished, so you can re-ground later.\n\n**Resolve your inputs before step 3, whichever skill you are in.** Derive what the request already answers, ask **once** for what is genuinely missing, echo what you resolved, and never invent a value that belongs to the user — a brand colour, a licensed font, a locale's wording. Ask through your environment's own question UI when it has one; a design's visual direction and brand are never silently defaulted on a first build. The contract is this skill's `intake.md` (`skill({ name: 'handbook', path: 'intake.md' })`); `create`, `brand`, `resize` and `localize` each carry the parameter table it applies to. `judge` is the one exception and asks nothing — it is the gate on every build.\n\n### Speak the user's language\n\n**Reply in whatever language the user writes to you in.** From their first message, and in everything they read: prose, questions, option labels and their subtext, the resolved-input echo, what you say about a preview, error explanations, the close. Switch if they switch. This is not a translation step at the end — it is the language you work in.\n\n**Two languages, not one.** The language you _speak_ and the language the design _contains_ are different axes, and conflating them is the failure mode here:\n\n- **Conversation language** — always mirrors the user. No exceptions.\n- **Design copy** — follows the brief. When the user has stated or implied a language for the content, that wins outright: someone writing to you in German may well want an English poster, and an English speaker may ask for an Arabic edition. Only when nothing implies otherwise does design copy **default** to the conversation's language — and when it does, say so in the echo (\"Textsprache: Deutsch\"), so a wrong guess costs one word to correct.\n- Changing an existing design's content language is never a side effect of the conversation — that is the `localize` skill, on request.\n\n**Never translate these**, in any language, because they are values rather than copy: skill and tool names (`judge`, `asset_generate`); `/onboard` job ids and other typed argument values (`job=generate`, `start=demo`); format ids and sizes (`ig-story`, `A4`, `1080×1350`); colour values; URLs, handles and channel names (`#showcase`); and revision ids. Translate a chip's **label**, never its **value** — a translated value breaks the call it feeds.\n\n**These documents stay English.** Every skill, handbook section and reference file is agent-facing instruction, not user-facing copy. Read them in English; speak to the user in theirs. The copy grammar in `create/choice-copy.md` — system-POV headers, verb-led titles, no pronouns in titles, lists parallel within themselves — applies in whatever language you are writing.\n\n### Re-grounding after a rewind / restart\n\nIf your conversation was rewound (double-ESC in Claude Code), or your process restarted mid-conversation, your in-memory \"current revision\" is wrong. The engine's state is the truth, but the server can't tell you've been rewound. Recovery:\n\n1. Call `list` — see the workspace's designs and their `latestLeaf` revisions.\n2. Call `history({ revision: latestLeaf })` — read the notes to find where the user wanted to be.\n3. Pass that revision id as `parent` on your next `edit`. The server reloads the engine to that scene before running your code — your edits land on top of the right state.\n\nRe-grounding recovers the design this conversation was already working on. It is not for starting a new conversation — a fresh session with a new request starts at `parent: null`.\n\nEditing on top of an OLDER revision (not the latest leaf) is fine: it creates a **non-destructive fork**. The previous leaves stay in storage; you can switch back any time by passing one of their ids as `parent`.\n\n## 2. Tools\n\nEach tool's full contract lives on the tool itself — its description in tools/list is authoritative and always in front of you. This section is only the roster plus the rules that span tools.\n\n- `edit({ parent, code, title?, note? })` — THE mutating tool: runs async JS (`engine` in scope) and commits a revision. The response's first text part is JSON `{ revision, parent }` — save `revision`; it is your `parent` for the next edit.\n- `preview({ blockIds, revision })` — render blocks to inline PNGs; omit `blockIds` for every page (max 10, full-size each).\n- `export({ format, revision, blockId?, outPath? })` — write a pdf/image/design artifact (`format`: `\"pdf\"`, `\"png\"`, `\"jpeg\"`, `\"webp\"`, `\"svg\"`, or `\"imgly\"`); omit `blockId` to export the whole document (`pdf` → one multi-page PDF, an image format → one composite image of all pages); returns `{ uri, httpUrl, bytes, format, revision }` (+ `path` when you pass `outPath`). `uri` is the durable handle; `httpUrl` is a fetch link tied to this process — never persist it. `outPath` (absolute path) ALSO writes the file to local disk — use it whenever your environment cannot fetch localhost URLs (sandboxed harnesses, e.g. Claude Cowork). `\"svg\"` is a vector SVG: text is outlined into paths (not editable text) and raster images are embedded at source resolution — the file can be much larger than its source images. `\"imgly\"` is the portable, self-contained design file (scene + all asset bytes, whole design only, no `blockId`) — the inverse of `import`, for taking an editable copy OUT; every `edit` already auto-persists, so it is never needed for durability.\n<!-- feature:video -->\n- `export` also accepts `format: \"mp4\"` — renders the block's authored timeline (see the video recipe in §4); needs the native engine (the default while video is enabled).\n<!-- /feature:video -->\n- `import({ source, title? })` — ingest a design FILE as a NEW root (was `load`): native `.imgly` (also legacy `.scene` / `.zip`), foreign Photoshop `.psd` / InDesign `.idml` / PowerPoint `.pptx` / PDF (translated in; `warnings` are your touch-up list — preview, then repair with `edit`), or a plain image/SVG (one page sized to it). Continue with `edit({ parent: revision })`.\n- `asset_add({ source: { path } })` — bring a local file (image or font) into the workspace for use in a design (was `import`); embed the returned `workspace://` uri in `edit` code — never `httpUrl`, and never the original local path or a `file://` URI (renders server-side but breaks the browser editor and portability).\n- `asset_search({ sourceId?, query?, page?, perPage? })` — discover and search the engine's asset sources; apply results inside `edit` (the exact patterns are in the tool's description). The `ly.img.workspace.images` source also lists images the human uploaded in the browser editor — searchable by their original filename, newest first.\n- `list()` / `history({ revision })` / `changes({ revision })` / `inspect({ revision })` / `rename({ revision, title })` — the workspace tools; usage in §3.\n- `view({ revision, pin? })` — human-facing viewer URL. Print it once; the viewer keeps it live.\n\nCross-tool rules:\n\n- **Revision ids are durable, block ids are not.** Everything flows through revisions: `edit` produces one, `preview`/`export`/`view` consume one, `history`/`inspect` walk them. Block ids are session-scoped — re-discover blocks in the current engine; never persist or replay literal block ids (see `inspect`'s description).\n- **The single mutating tool is `edit`.** `asset_add`, `asset_search`, and `view` never change the scene; placement and application always happen inside `edit` code. (`import` is the exception: it creates a new root to `edit` from.)\n\n## 3. Workspace cheatsheet\n\nThe workspace is your durable memory: every revision you commit via `edit` is there, addressable by id, walkable via `history`. It survives a process restart and a Claude rewind.\n\n```\nlist() → [{ rootRevision, title, latestLeaf, updatedAt, headOrigin?, headNote? }, …]\nhistory({ revision: leaf }) → [{ revision, parent, note?, origin?, createdAt }, …] (root first)\nchanges({ revision }) → { head, state, design, since?, wouldOrphanEditorWork, guidance } (what landed AFTER it)\ninspect({ revision }) → { revision, parent, note?, origin?, createdAt, title?, code? }\nedit({ parent: leaf, code }) → linear edit, no engine reload\nedit({ parent: olderRev, code }) → fork; engine reloads to olderRev first\nedit({ parent: null, title }) → new design\nrename({ revision: any, title }) → updates the root title\n```\n\nA revision id is a 12-hex-char string. You never construct it; the server hands it back from `edit`. Treat it as opaque.\n\n### Human edits from the browser editor\n\nThe `view` URL is a full editor. When the human clicks **Save**,\ntheir edits land as a normal child revision with `origin: \"editor\"`, no code,\nand a note that starts `Edited in the browser editor. Engine-computed diff vs\nparent:` followed by block-level changes.\n\n- **Finding their revision**: `changes({ revision })`, passing the revision you\n hold — normally the one your last `edit` returned. It tells you whether that\n revision is still the design head, lists what was written since it (oldest\n first, each with its `note` and `origin`), and names the revision to build\n on. Do NOT use `history` for this: it walks _ancestors_, so called with your\n own last revision it will never show their newer save — and previewing your\n own last revision renders the pre-edit scene, which looks exactly like\n \"nothing changed\". In a fresh conversation you hold no revision to pass;\n there `list` is the signal — it reports `headOrigin: \"editor\"` and the\n `headNote` for a design whose newest revision came from the editor.\n- **Call `changes` before your first `edit`** of a design the user may have had\n open in the browser. `edit` REFUSES a parent whose path to the head contains\n one of their editor saves — building from it would orphan their work on a\n sibling branch — and the refusal names the revision to pass instead. Pass\n `fork: true` only when the user explicitly asked you to discard their own\n browser changes and branch from the older revision.\n- **That note is authoritative.** It is computed by the engine, not\n free-typed. Do NOT re-derive it with preview loops or read-only `edit`\n dumps — that burns your edit budget and mints junk revisions.\n- **Continue from the human revision**: `edit(parent=<their revision>)`. Their\n changes are already in that scene.\n- A `Note: this design has newer revision(s)…` line on an `edit`/`preview`/\n `inspect`/`export` result means someone committed after the revision you\n passed. When that someone is you (your own earlier branch), the note is\n advisory and the fork is legal; the human's saves come back as the refusal\n above instead. Unless you are deliberately rewinding, rerun with the newer\n revision.\n\n## 4. Engine recipes\n\n### Build ONE complete page per `edit`\n\nThe unit of work is the **page**: every `edit` call emits one complete page — all its blocks, all setFont, all sizes, the `forceLoadResources` await, then positioning. Do **not** split a single page's build across 2–3 calls. Each tool call costs 20–200s of LLM streaming wall time; one ~10000-char call is faster than three ~3000-char calls because there's no thinking-between-calls overhead.\n\nFor a **single-page design** that means the entire scene in one `edit` — scene, page, all blocks:\n\n```js\n// 1. Structure\nconst scene = engine.scene.create('VerticalStack');\nconst stack = engine.block.findByType('stack')[0];\nconst page = engine.block.create('page');\nengine.block.appendChild(stack, page);\nengine.block.setWidth(page, 720);\nengine.block.setHeight(page, 1008);\n\n// 2. Look up fonts (ly.img.gfonts — design-rules.md §6.7), create all blocks\n// + setFont + setTextFontWeight + setString (fire-and-forget loads)\nconst FAMILY = 'Playfair Display';\nconst { assets: pf } = await engine.asset.findAssets('ly.img.gfonts', {\n query: FAMILY,\n page: 0,\n perPage: 20 // fuzzy ranking can put the exact match behind longer names\n});\nconst tfPlayfair = pf\n .map((a) => a?.payload?.typeface)\n .find((t) => t?.name === FAMILY);\nif (!tfPlayfair)\n throw new Error(\n `font lookup missed: no exact match for \"${FAMILY}\" among ` +\n pf.map((a) => a?.payload?.typeface?.name).join(', ')\n );\nconst titleText = engine.block.create('text');\nengine.block.setFont(titleText, tfPlayfair.fonts[0].uri, tfPlayfair);\n// REQUIRED on every text block: fonts[0] is the family's LIGHTEST weight\n// (Thin/100 on Inter, Roboto, …), so setFont alone renders hairline text.\nengine.block.setTextFontWeight(titleText, 'bold');\nengine.block.setString(titleText, 'text/text', 'Alex & Jordan');\nengine.block.setTextFontSize(titleText, 48, { unit: 'Pixel' });\nengine.block.setWidthMode(titleText, 'Auto');\nengine.block.setHeightMode(titleText, 'Auto');\nengine.block.appendChild(page, titleText);\n// ... repeat for every text + graphic block ...\n\n// 3. Deterministic font-load await\nawait engine.block.forceLoadResources([page]);\n\n// 4. Now position with measured frame dims\nconst w = engine.block.getFrameWidth(titleText);\nengine.block.setPositionX(titleText, (720 - w) / 2);\nengine.block.setPositionY(titleText, 250);\n// ... position everything ...\n\nreturn { type: 'text', text: `page=${page} ready` };\n```\n\nAfter this one call, your next tool call is `preview({ blockIds: [page], revision })`. **Exactly 2 calls per page — build, then capture. For a single-page design that's the whole job. Then STOP.**\n\n### Multi-page designs: page by page, page 1 first\n\nNever emit a multi-page design (carousel, slide deck, brochure) in one giant `edit`. Build it **page by page**, one `edit` + one `preview` per page:\n\n1. **Page 1 is the design-language gate.** The first `edit` builds the scene and page 1 only — it establishes fonts, palette, margins, grid. Preview it before touching page 2: a wrong aesthetic choice caught here costs one page, not N.\n2. **Pages 2..N each get their own `edit` + `preview`.** Each call builds one complete page reusing the design language page 1 proved out. Preview each page right after building it — the bugs on later pages are content-dependent (a headline that overflows, an image that crops badly), so batching pages doesn't avoid them, it just delays discovery. Feed findings forward: if body text at 28px overflowed on page 3, use 26px from page 4 on.\n3. **Batching is allowed only for near-identical clones** — templated pages differing by a short label or image swap. Even then, a thrown error mid-call loses every page in the batch; when in doubt, one page per call. Multi-block `preview` follows the same rule: batch renders are for review and final capture, never the build.\n\nThe objective-bug bar below applies per page: fix an overflow on page 3 with a targeted `edit` to page 3, then re-capture page 3 only.\n\n**Editing an existing multi-page design:** a mechanical change applied uniformly (swap a font everywhere, recolor a brand accent) is one `edit` looping over `engine.scene.getPages()` — that's one logical change, not a batch. Substantial per-page rework (rewriting layouts, restructuring content) goes page by page like a build, with a `preview` per reworked page.\n\nAfter the capture, fire a 2nd `edit` ONLY if the rendered PNG shows a specific, OBJECTIVE bug (text overflowing the page bounds, blocks visibly overlapping, missing characters, blank glyphs). Aesthetic refinement does NOT warrant another exec — sub-pixel nudges, \"could be a touch tighter\", compositional balance, vertical centering, whitespace distribution (\"top-heavy\", \"feels off-center\") are all DISALLOWED, even when the imbalance is large or intentional. If in doubt, STOP — a needless 3rd or 4th call (~30s wall + thinking tokens + latency) far outweighs any aesthetic gain. A read-only `edit` (one that returns data and mutates nothing — `getTextFontSizes`, `getFrameWidth`, etc.) still counts as a call against the limit, plus it forces a follow-up capture. Only fire a read-only exec if you'd otherwise be guessing at a number you can't read off the captured PNG.\n\n**Scope of these stop-rules: the build phase, before a `judge` pass.** They cap self-initiated polish between build and capture — they do not override Loop step 5. Once the `judge` skill has scored the design, remediating a failed axis (including composition or whitespace) is required work, not aesthetic refinement: apply the scorecard's fixes via `edit`, then re-preview and re-judge. The boundary is the scorecard — without one, only objective bugs warrant another `edit`; with one, its fixes do.\n\n### Font sizes are PIXELS, not points\n\nCE.SDK's font size APIs default to **points**. CE.SDK's scene unit defaults to **Inch** out of the box — but this demo wraps `engine.scene.create(...)` to call `setDesignUnit('Pixel')` immediately, so every scene the agent creates is in pixels by default. You don't need to set the unit yourself, but if you ever destroy + bare-call into the engine outside `scene.create`, re-set it. A unit-less font size is still read as points and converted at the scene's 300 dpi, so it lands **~4.2× too large**: `setTextFontSize(block, 32)` measures back as **133 px**, not 32.\n\n**ALWAYS pass `{ unit: 'Pixel' }`** when reading or writing font sizes:\n\n```js\nengine.block.setTextFontSize(block, 32, { unit: 'Pixel' }); // 32 px ✓\nengine.block.getTextFontSizes(block, { unit: 'Pixel' }); // returns px ✓\n```\n\n**NEVER:**\n\n```js\nengine.block.setFloat(block, 'text/fontSize', 32); // unit-less → 133 px ✗\nengine.block.setTextFontSize(block, 32); // defaults to points → 133 px ✗\n```\n\nLine-height is NOT a raw multiplier either: CE.SDK's `text/lineHeight` scales the font's content area, not the em — every visual line-height target must be divided by the font's content area (measured via `engine.editor.getFontMetrics`) before being set, and a reshape (`setString`) afterwards wipes per-character style ranges, so the order is line-height → reshape → re-apply every color/style range. Full rule and code: §6.1.3 in this skill's design-rules.md.\n\n### Text sizing — Auto + read frame dims\n\nFor text blocks, the canonical CE.SDK pattern is **Auto width/height + `getFrameWidth` / `getFrameHeight`** for measured dims. The engine shapes the text and exposes the actual frame extent through these reads, which you then use for centering, stacking, and overflow checks. Manual `setWidth`/`setHeight` on text is fragile: too small and the engine silently drops the render (no glyphs drawn, no error); too large and your alignment math is off.\n\n```js\nconst text = engine.block.create('text');\nengine.block.replaceText(text, 'Alex & Jordan');\nengine.block.setFont(text, uri, typeface); // 3-arg form (mandatory)\nengine.block.setTextFontSize(text, 64, { unit: 'Pixel' });\nengine.block.setWidthMode(text, 'Auto');\nengine.block.setHeightMode(text, 'Auto');\nengine.block.appendChild(page, text);\n\n// IMPORTANT: getWidth/getHeight return 0 in Auto mode. Read frame dims instead.\nconst w = engine.block.getFrameWidth(text); // measured shaped width\nconst h = engine.block.getFrameHeight(text); // measured shaped height\nengine.block.setPositionX(text, (pageW - w) / 2);\nengine.block.setPositionY(text, y);\n```\n\nUse absolute `setWidth`/`setHeight` only when you specifically want to constrain a wrap box (e.g. multi-line body copy with a fixed column width). Even then, set `setWidthMode(id, 'Absolute')` and pick height ≥ `fontSize × 1.6` for body sans, `≥ 1.8` for display serifs (Playfair, Cormorant) and scripts (Great Vibes, Caveat) — ascenders/descenders need the headroom or the engine drops the render.\n\n### Font-load barrier: `forceLoadResources`\n\n```js\nawait engine.block.forceLoadResources([page]); // recurses into children\n// now getFrameWidth returns real values for every text block on the page\n```\n\n`forceLoadResources(blocks)` returns `Promise<void>` that resolves once all fonts/images/fills bound to those blocks (and descendants) have finished loading. Pass `[page]` to await everything on the page. **No `setTimeout`, no polling.**\n\nThis barrier is for **your own measuring** inside `edit` code — positioning by measured frame width needs the fonts loaded first. Capturing is covered server-side: `preview`, `export`, and the commit at the end of every `edit` all force-load the scene's resources before rendering or serializing, so you never need a separate wait-for-fonts edit.\n\n`getFrameWidth(id) > 0` after the await is your \"font loaded + shaped successfully\" signal. **Never** use `getWidth(id) === 0` as a font-load probe — it returns 0 by design in Auto mode regardless of font state.\n\n<!-- feature:video -->\n\n### Video: any design can become a video\n\nScenes are not \"static\" or \"video\" at creation time — add time-based content\nto the scene you already have, then `export({ format: \"mp4\" })` renders the\nauthored timeline. Do NOT rebuild a scene with `scene.createVideo()` just to\nanimate it (`createVideo` and `scene.setMode('Video')` exist as conveniences;\nyou rarely need either).\n\n```js\n// Page duration = length of the exported video.\nengine.block.setDuration(page, 10); // seconds\n\n// Tracks hold timed children; blocks get offsets + durations.\nconst track = engine.block.create('track');\nengine.block.appendChild(page, track);\n// Tracks auto-arrange children back-to-back by default (this is silent —\n// no error, no warning). Turn it off before setting custom offsets below,\n// otherwise setTimeOffset appears to work but gets overwritten later.\nengine.block.setBool(track, 'track/automaticallyManageBlockOffsets', false);\nconst block = engine.block.create('graphic');\nengine.block.appendChild(track, block);\nengine.block.setTimeOffset(block, 1.0); // enters at t=1s\nengine.block.setDuration(block, 5.0); // visible for 5s\n\n// Video fill — use the workspace:// URI from `asset_add`.\nconst fill = engine.block.createFill('video');\nengine.block.setString(\n fill,\n 'fill/video/fileURI',\n 'workspace://assets/<sha>.mp4'\n);\nengine.block.setFill(block, fill);\n// Trim setters need the video's metadata — load it first, or they throw\n// \"The video has not been loaded yet.\"\nawait engine.block.forceLoadAVResource(fill);\nengine.block.setTrimOffset(fill, 2.0); // start 2s into the source\nengine.block.setTrimLength(fill, 5.0); // play 5s of it\n\n// Audio block — plays during the page's timeline.\nconst audio = engine.block.create('audio');\nengine.block.setString(audio, 'audio/fileURI', 'workspace://assets/<sha>.mp3');\nengine.block.appendChild(page, audio);\n```\n\n- Export: `export({ format: \"mp4\", revision, blockId: page })`.\n Duration/resolution come from the page — there are no export knobs.\n- Needs the native engine (the default while video is enabled). On an engine\n error, run `diagnostics` and check `status.config.engineResolved` —\n `wasm`/`wasm-fallback` cannot encode video.\n- `preview` renders a STILL frame of a video scene, not motion — pass `time`\n (seconds) to seek: verify a few salient moments (start, a transition, the\n end). Each video preview returns `{time, duration}` JSON next to the image.\n Export for the real thing.\n- Resource loading during export is handled server-side — you do NOT need a\n `forceLoadResources` barrier before `export` (unlike the font barrier above).\n The one load you DO need is `forceLoadAVResource(fill)` before reading or\n trimming a video fill (see the recipe above).\n- **Multi-clip tracks (sequences, crossfades): disable auto-arrange first.**\n`track/automaticallyManageBlockOffsets` defaults to `true` and silently\noverwrites every child's `setTimeOffset` with an auto-computed back-to-back\nvalue — no error. It looks fine with one clip (offset 0 either way), which\nis why it hides until you need two clips to overlap. Before setting any\nchild offsets: `engine.block.setBool(track, 'track/automaticallyManageBlockOffsets', false)`.\n<!-- /feature:video -->\n\n### Common operations cheatsheet\n\nThe `engine.*` calls used in nearly every `edit`. Verify exact signatures + types in the `cesdk-api` skill before using anything not listed here.\n\n```js\n// Scene + page basics — hierarchy is scene → stack → page (NOT scene → page).\n// engine.scene.create(\"VerticalStack\") makes the scene AND a stack container.\n// Pages attach to the stack, never directly to the scene root.\n// The \"VerticalStack\" argument is REQUIRED — without it, no stack is created\n// and findByType(\"stack\") returns []. (Use \"HorizontalStack\" for side-by-side.)\nconst scene = engine.scene.create('VerticalStack');\nconst stack = engine.block.findByType('stack')[0];\nconst page = engine.block.create('page');\nengine.block.appendChild(stack, page); // ← stack, not scene\n// The stack arrives with the editor's page gap already set (48 screen-space\n// px, matching the CE.SDK editor — the raw engine default of 0 is never what\n// you want). Override only for a deliberate look, e.g. an edge-to-edge collage:\n// engine.block.setFloat(stack, 'stack/spacing', 0);\nconst pages = engine.scene.getPages(); // DesignBlockId[]\nconst current = engine.scene.getCurrentPage(); // DesignBlockId | null\n\n// Block creation\nconst text = engine.block.create('text');\nconst graphic = engine.block.create('graphic');\n\n// Position & size\nengine.block.getPositionX(id);\nengine.block.setPositionX(id, x);\nengine.block.getPositionY(id);\nengine.block.setPositionY(id, y);\nengine.block.getWidth(id);\nengine.block.setWidth(id, w);\nengine.block.getHeight(id);\nengine.block.setHeight(id, h);\n\n// Page dimensions (for proportional calculations)\nconst pageW = engine.block.getWidth(page);\nconst pageH = engine.block.getHeight(page);\n\n// Fills + shapes (graphic blocks)\n// NOT for a text-only chip/pill/badge/button/tag — those are a text block with a\n// native text background, never a rect behind floating text (see the chip recipe\n// below, §6.5.1). Reach for a rect only for real graphics, or a chip whose content\n// is NOT just text (icon + text, an image, multiple elements).\n// \"rect\" | \"line\" | \"ellipse\" | \"polygon\" | \"star\" | \"vector_path\".\n// Anything with a diagonal, a curve or a hole is a vector_path — see the\n// custom-shapes recipe below. Do NOT approximate one out of stacked rects.\nconst shape = engine.block.createShape('rect');\nengine.block.setShape(graphic, shape);\nconst fill = engine.block.createFill('color'); // also: \"image\"\nengine.block.setFill(graphic, fill);\nengine.block.setColor(fill, 'fill/color/value', { r, g, b, a });\n\n// Text content + color + size (PIXELS — see pixel rule above)\nengine.block.setString(text, 'text/text', 'Hello');\nengine.block.setTextColor(text, { r, g, b, a }); // whole text\nengine.block.setTextColor(text, { r, g, b, a }, start, end); // char range\nengine.block.setTextFontSize(text, 32, { unit: 'Pixel' });\nengine.block.getTextFontSizes(text, { unit: 'Pixel' });\n\n// Rich text — STYLE RANGES inside ONE block. Every setter below takes an optional\n// (from, to) character range; omit it to style the whole string. An accent word, a\n// bold lead-in, an inline price, a struck-through old price: all are RANGES on one\n// text block, never a second block placed beside the first. Two blocks look identical\n// in a render and are caught by reading the scene graph — they also re-break on every\n// copy/font/locale change, because nothing binds them to each other. (§6.1.9)\nengine.block.setTextFontWeight(text, 'bold', start, end); // 'thin'…'heavy' (9 steps)\nengine.block.setTextFontStyle(text, 'italic', start, end); // 'normal' | 'italic'\nengine.block.setTypeface(text, tf, start, end); // a second face inline\nengine.block.setTextFontSize(text, 48, { unit: 'Pixel', from: start, to: end });\nengine.block.setTextCase(text, 'Uppercase', start, end); // see the caps rule below\nengine.block.setTextDecoration(text, { lines: ['Underline'] }, start, end);\n// Decoration is configurable, not just on/off:\n// lines: 'Underline' | 'Strikethrough' | 'Overline' (combinable)\n// style: 'Solid' | 'Double' | 'Dotted' | 'Dashed' | 'Wavy'\n// underlineColor / underlineThickness / underlineOffset / skipInk (keep skipInk on\n// so descenders stay legible). Toggle helpers: toggleTextDecorationUnderline(...).\n\n// ALL-CAPS: set the PROPERTY, don't type capitals into the string. setTextCase re-cases\n// on render, so the string stays real words — translatable, searchable, and correct in\n// scripts that have no case at all. Typed capitals are frozen English. (§6.1.6)\nengine.block.setTextCase(text, 'Uppercase'); // 'Normal'|'Uppercase'|'Lowercase'|'Titlecase'\n\n// Read styling back — the ONLY safe way to capture before a reshape. Returns one entry\n// per run with from/to/text/color/fontWeight/fontStyle/fontSize/textCase/typeface/\n// textDecoration/kerning. ⚠ Any write to 'text/text' WIPES every range: capture, write,\n// replay. The wipe collapses the string to RUN 0's formatting — not to a neutral base —\n// so replay EVERY captured run, not just the emphasis spans: if run 0 was a bold lead-in,\n// replaying only the accent leaves the whole paragraph bold, silently, and reading the\n// accent range back still looks correct. setTextFontSize alone does NOT wipe ranges; only\n// the string write does. getTextColors(id)[0] is run 0 only — re-applying it whole-block\n// is what flattens a two-color headline. (handbook quirks; §6.1.9)\nconst runs = engine.block.getTextRuns(text);\n\n// PARAGRAPH-level — these take a paragraphIndex (negative = all paragraphs), NOT a\n// character range. Multi-paragraph copy is ONE block with paragraph spacing, never N\n// blocks stacked by hand and never blank lines used as spacing. (§6.1.8)\n// ⚠ paragraphSpacing is an EM MULTIPLE of the font size, NOT pixels. 0.4–0.8 is the\n// usable band; a pixel-looking value like 12 means twelve em and silently pushes the\n// page metres long with no error (measured: 9 on 17px copy → ~150px gaps).\nengine.block.setFloat(text, 'text/paragraphSpacing', 0.6); // EM between paragraphs\nengine.block.setTextHorizontalAlignment(text, 'Center', 0); // just paragraph 0\nengine.block.setTextLineHeight(text, 1.2, 0); // per-paragraph leading\n// Read alignment back with paragraphIndex -1 for the BLOCK-level value; a per-paragraph\n// read returns undefined when no paragraph override is set, which looks like \"unset\".\nengine.block.getTextHorizontalAlignment(text, -1);\n\n// Text alignment + spacing (typed properties via setEnum / setFloat)\nengine.block.setEnum(text, 'text/horizontalAlignment', 'Center'); // \"Left\" | \"Center\" | \"Right\"\nengine.block.setEnum(text, 'text/verticalAlignment', 'Center'); // \"Top\" | \"Center\" | \"Bottom\"\nengine.block.setFloat(text, 'text/letterSpacing', 0.05); // ratio of em\nengine.block.setFloat(text, 'text/lineHeight', 1.2); // ratio of font size\n\n// Chips (pill / eyebrow / badge / tag / button) — a NATIVE text background on the\n// text block itself. Use this instead of a rectangle behind floating text: the field\n// is bound to the label, so it reflows on any copy/font/locale change instead of\n// drifting off-center. A backing rect is correct ONLY when the chip's content is not\n// just text. This is a build rule, not a preference — a rect+text chip renders\n// identically and is caught by reading the scene graph, not by eye. (§6.5.1)\nengine.block.setBool(text, 'backgroundColor/enabled', true);\nengine.block.setColor(text, 'backgroundColor/color', { r, g, b, a });\nengine.block.setFloat(text, 'backgroundColor/cornerRadius', h / 2); // pill = half the padded height\nengine.block.setFloat(text, 'backgroundColor/paddingLeft', 16); // horizontal ~1.5–2.5× vertical\nengine.block.setFloat(text, 'backgroundColor/paddingRight', 16);\nengine.block.setFloat(text, 'backgroundColor/paddingTop', 8);\nengine.block.setFloat(text, 'backgroundColor/paddingBottom', 8);\n// Align the chip by its padded FIELD edge, not its glyph run (§6.5.1). The padding\n// expands the field OUTWARD from the text frame, and getFrameHeight reports the UNPADDED\n// height — so to land the field edge on the margin, and to get a true capsule:\n// setPositionX(chip, MARGIN + paddingLeft) // not MARGIN\n// cornerRadius = (getFrameHeight(chip) + padTop + padBottom)/2 // not frameHeight/2\n\n// Lists — native bullets/numbers WITH a real hanging indent (wraps align to text,\n// not the marker). Per-paragraph; negative index = all paragraphs. ONE text block\n// holds the WHOLE list, one paragraph per item. All three hand-built fakes are wrong\n// and all three render almost identically, so they are caught in the scene graph:\n// 1. typing \"• \" into the string -> no hanging indent\n// 2. a lone \"•\" text block per item -> marker drifts off its text on any change\n// 3. one text block per list item -> no list at all, N loose ungrouped blocks\n// (§6.1.8)\nengine.block.setTextListStyle(text, 'Unordered'); // \"None\" | \"Unordered\" | \"Ordered\"\nengine.block.setTextListStyle(text, 'Ordered', -1, 0); // all paragraphs, nesting level 0\nengine.block.setTextListLevel(text, 1, 2); // nest paragraph 2 one level in\n// engine.editor.setSettingFloat('listIndentPerLevel', 1.5); // indent width per level, EM\n\n// Text on a path — circular/curved type (\"EST. 2026\" around a seal, a badge arc).\n// Use this instead of faking a curve by placing one text block per letter and rotating\n// each: a per-letter fake has no real baseline, so tracking is uneven, it re-breaks on\n// any copy/font/locale change, and it ships as N loose blocks instead of one. ONE text\n// block on a path is the only correct curved type. (§6.5.4)\n// svgPath is in the block's local coordinate space; null clears it back to normal.\nengine.block.setTextOnPath(text, 'M 0 100 A 100 100 0 1 1 200 100'); // e.g. an arc\nengine.block.setTextOnPathOffset(text, 0.5); // proportional start offset along the path\nengine.block.setTextOnPathFlipped(text, false); // true = underside, reversed direction\n// Three constraints worth knowing before you build the path:\n// - EXACTLY ONE subpath — a single leading \"M\", no second one. Multiple subpaths throw\n// BLOCK.TEXT_ON_PATH_MULTIPLE_SUBPATHS. Split the shape or pass one contour.\n// - The string must be a parseable SVG path, else BLOCK.TEXT_ON_PATH_INVALID_SVG_PATH.\n// - Setting a path RESIZES the block, so set the path BEFORE positioning. But the\n// reported box is NOT the ink box and is smaller than the glyph ring: a 130×130\n// authored path reads back 84×84 on getWidth/getHeight/getFrameWidth/getFrameHeight\n// alike, and previewing the block alone clips its own text on all four sides. Derive\n// margin and collision math from the AUTHORED path geometry, never the re-read box,\n// or curved type sits ~23px per side outside where you placed it. Same reason\n// `localize` (which snaps geometry to a reference) and `resize` (which re-derives it)\n// must carry the path, not the post-path box.\n\n// Font — REQUIRES three args. Passing only (text, uri) throws a cryptic\n// \"Cannot read properties of undefined (reading 'name')\" because cesdk\n// reads typeface.name internally. The typeface object is mandatory.\n// For Google families DON'T build it by hand — look it up from the\n// ly.img.gfonts source (design-rules.md §6.7). Hand-built typefaces are for\n// brand fonts imported to workspace:// URIs:\nconst uri = 'workspace://assets/abc123def456.ttf';\nconst typeface = {\n name: 'Acme Grotesk',\n fonts: [{ uri, subFamily: 'Regular', weight: 'normal', style: 'normal' }]\n};\nengine.block.setFont(text, uri, typeface);\n\n// Await all resource loads (fonts, images, fills) for blocks + descendants.\n// Use this after a batch of setFont calls before reading frame dims or capturing.\nawait engine.block.forceLoadResources([page]);\n```\n\n### Custom shapes — `vector_path`, not a pile of rects\n\n**Any mark with a diagonal, a curve or a hole is one `vector_path` block.** The\nprimitives cannot express those, so approximating a mark out of rects and\nellipses produces stepped edges where a slope should be, and costs one block per\nstep: a windowed facade drawn that way came to 79 blocks and still rendered as a\nstaircase. The same mark as a path is one block with clean geometry.\n\n```js\nconst graphic = engine.block.create('graphic');\nconst shape = engine.block.createShape('vector_path');\nengine.block.setString(shape, 'shape/vector_path/path', d); // SVG path data — built below\n// width/height are the PATH'S COORDINATE FRAME, not the on-canvas size. Author\n// in a fixed box (100x100 is convenient) and scale with the block's size, so one\n// definition works at any scale.\nengine.block.setFloat(shape, 'shape/vector_path/width', 100);\nengine.block.setFloat(shape, 'shape/vector_path/height', 100);\nengine.block.setShape(graphic, shape);\nengine.block.setWidth(graphic, 420); // on-canvas size, independent of the frame\nengine.block.setHeight(graphic, 460);\n```\n\n#### Fill rule: `NonZero` + deliberate winding\n\n`engine.block.setEnum(shape, 'shape/vector_path/fillRule', v)` takes\n**`'EvenOdd'` | `'NonZero'`**. For a mark built from several subpaths this is the\nwhole game:\n\n- **solid parts wound one way** (say clockwise) — they **union** where they overlap\n- **holes wound the opposite way** — they **punch through**\n\n**The default is `EvenOdd`, and it is the wrong one for a composite mark — set\n`NonZero` explicitly.** `EvenOdd` XORs, so any two solid parts that cross — a\ncross-brace over a leg, a spoke over a hub — knock a hole at the intersection,\nand no amount of correcting the winding will fix it. Keep `EvenOdd` only for\nshapes whose subpaths strictly nest and never overlap.\n\n```js\nengine.block.setEnum(shape, 'shape/vector_path/fillRule', 'NonZero');\n```\n\nWinding is a property of point order, so enforce it in code rather than by\nhand-writing paths in the right direction. Screen coordinates are **y-down**, so\nthe usual shoelace sign is inverted:\n\n```js\n// +y is DOWN, so a negative shoelace sum means clockwise.\nconst isClockwise = (pts) =>\n pts.reduce((a, [x1, y1], i) => {\n const [x2, y2] = pts[(i + 1) % pts.length];\n return a + x1 * y2 - x2 * y1;\n }, 0) < 0;\n\nconst orient = (pts, cw) =>\n isClockwise(pts) === cw ? pts : [...pts].reverse();\n\nconst poly = (pts, cw = true) =>\n 'M ' +\n orient(pts, cw)\n .map(([x, y]) => `${x},${y}`)\n .join(' L ') +\n ' Z';\n\nconst d = [poly(body), poly(window, false)].join(' '); // solid + hole\n```\n\nTwo traps worth knowing before you lose an hour to either:\n\n- **A hand-reversed Bézier subpath can silently fail to punch.** Rectangular\n holes work while an arched one built by writing the curve backwards renders\n solid, with no error. Sample curved holes into a polygon and let one\n orientation helper own the winding for every subpath.\n- **Prefer four cubic Béziers to an SVG arc** for circles and rounded caps —\n it sidesteps `A` command largeArc/sweep flag handling entirely. Control points\n sit at `k = 0.5522847498 * r`.\n\n#### Holes are real holes\n\nA `vector_path` hole shows whatever is behind the block — page ground, another\ngraphic, a photograph. That is usually what you want on a flat ground and\nusually **not** what you want over a photograph, where it reads as a hard-edged\ncut-out rather than a printed mark. Over imagery, emit the solid subpaths only\nand drop the holes. Faking a hole with a ground-coloured shape on top is a bug\nwaiting to happen: it only matches a flat, known ground, and it visibly fails\nover a photograph.\n\n### Z-order via child order (no z-index property)\n\nCE.SDK has no z-index. Render order = child order. Later children paint on top of earlier siblings.\n\n```js\nengine.block.appendChild(parent, child); // child becomes LAST = top-most\nengine.block.insertChild(parent, child, index); // index 0 = back-most\nengine.block.getChildren(parent); // current children, back-to-front\n```\n\n**Build pages back-to-front.** Suggested canonical layer stack for a designed page:\n\n1. page background fill — `setFill` on the page block (an attribute, not a child; sits below any children)\n2. full-bleed photo / image (first child, index 0)\n3. scrim / vignette / gradient overlay\n4. structural rules — grid hairlines, dividers, frames\n5. accent shapes — pills, badges, accent bars, icons\n6. body text\n7. headline / display text\n8. foreground decoration (corner brackets, stickers)\n\nAppend in this order. If you create text before its background pill, the pill will cover the text. Deviate from the canonical order when intent demands — it is a default, not a rule.\n\n**Fix without rebuilding** — to demote an existing sibling underneath another, use `insertChild` with a measured index:\n\n```js\n// text block already exists at top of stack; demote a sibling pill behind it\nconst children = engine.block.getChildren(page);\nconst textIdx = children.indexOf(textId); // textId must be a direct child of page (else -1)\nengine.block.insertChild(page, pillId, textIdx); // pillId now sits just behind textId\n```\n\nStack-layout pages (`VerticalStack` / `HorizontalStack`): the stack arranges pages along an axis; the same child-order rule applies WITHIN each page's children.\n\n**Never destroy + recreate to fix ordering.** Use `insertChild`.\n\n### Group blocks & hierarchy — structure every page as a tree\n\nA finished page is a **tree, not a flat list of siblings**. Once blocks are created and positioned, cluster every set that reads as one unit into a group with `engine.block.group(ids)`, and **nest groups into parent groups** where the clusters nest. This is not optional polish: the group hierarchy is how z-order, moving, and later `resize` operate on semantic units instead of loose blocks, it encodes the reading structure the `judge` skill scores (§6.3), and it survives an `.imgly` round-trip.\n\nContract (verify signatures in the `api` skill):\n\n- `engine.block.isGroupable(ids)` — `false` if any id is a scene block or is **already** inside a group. Always guard with it.\n- `engine.block.group(ids)` — returns the new group's id. The blocks must be **siblings** (same parent). Call it **after** positioning: the group's bounding box is derived from its children's placed frames.\n- `group()` inserts the group at the **minimum child index** among its members, so building back-to-front (per the layer stack above) means grouping does **not** disturb z-order.\n- Recover with `engine.block.ungroup(id)`; `enterGroup` / `exitGroup` / `insertChild` still address the children.\n\n```js\nconst group = (ids) =>\n engine.block.isGroupable(ids) ? engine.block.group(ids) : null;\n\n// 1) group each leaf cluster after it is built + positioned\nconst gHeader = group([topRule, kickerL, kickerR]);\nconst gHero = group([title1, title2, tagline]);\nconst gDetail = group([divider1, divider2, ...detailCells]);\n\n// 2) group the groups → a nested super-cluster (group-of-groups)\nconst gMasthead = group([gHeader, gHero]);\n```\n\nGuardrails: group only **direct siblings**; never group across pages; a block already in a group makes `isGroupable` return `false` (ungroup first if you must re-cluster); measure text frames (`forceLoadResources` → `getFrameWidth`) and position **before** grouping. Close the build by returning the group manifest in the edit `note` (e.g. `groups: masthead=… detail=… lineup=…`) so the hierarchy is legible when you re-ground.\n\n## 5. Quirks\n\nCE.SDK errors are short and opaque, and several runtime behaviors don't show up in the .d.ts. The full quirk reference — the error-message → cause table, the runtime-symptom → workaround table, and the text-doesn't-render diagnosis order — lives in this skill's `quirks.md`. On ANY cryptic error or non-rendering block, search it BEFORE bisecting: `skill({ name: 'handbook', path: 'quirks.md', query: '<fragment of the error message>' })`.\n\n### Prefer surgical fixes over wipe-and-rebuild\n\nEach rebuild costs ~10 extra tool calls (re-create scene, re-position every block, re-verify). When something looks wrong, identify the specific block and edit it in place — `setPositionY`, `setTextFontSize`, `replaceText`, etc. Reach for `engine.scene.create(...)` only when the scene graph is genuinely unrecoverable, which is rare.\n\n## 6. Design rules\n\nEnforceable design best practices with numeric thresholds — what you build to, and what the `judge` skill scores against. Each rule group ends with a **Pass condition**; a failed Pass condition pulls its parent axis below 8, and one axis below 8 fails the design (no averaging — see the `judge` skill for the axes and the gate).\n\n- **Web vs print** — where the two media diverge (line height, minimum sizes) the rules are split **Web** / **Print**; \"web\" values apply to screen-destined canvases (social posts, banners). An unqualified rule applies to both.\n- **N/A = 10** — a rule that cannot apply to a given design scores N/A, i.e. 10.\n- **Defaults fill silence** — when the user's brief gives an explicit value for a property, use it; when it is silent, apply this section's defined **default** rather than leaving the property unset or letting the engine default stand. Every numeric rule below that names a _default_ (line-height §6.1.3, type scale §6.1.2, measure §6.1.4, all-caps tracking §6.1.6, margins §6.4) is that fallback. Silence is not permission to skip the property. A brief value that violates a hard threshold is clamped to the threshold — except line-height, which is judged by the rendered gap after conversion, never by the raw number (§6.1.3).\n\n**The full rubric lives in this skill's `design-rules.md`** — read it BEFORE building: `skill({ name: 'handbook', path: 'design-rules.md' })`. Section map:\n\n- **§6.1 Typography** (§6.1.1 families/pairing · §6.1.2 type scale & canvas bands · §6.1.3 line-height/leading incl. the content-area conversion · §6.1.4 measure · §6.1.5 alignment/rag · §6.1.6 tracking & case · §6.1.7 micro-typography · §6.1.8 lists & paragraph structure · §6.1.9 rich text / inline style ranges · §6.1.10 print rules · §6.1.11 the typography pass checklist)\n- **§6.2 Color** — palette ≤ 3 + neutrals, one accent, contrast on the actual background\n- **§6.3 Hierarchy** — one dominant element; rank via size > weight > color > spacing > position\n- **§6.4 Composition & grid** — margins 8–12% of the shortest dimension, the spacing ladder, no dead void\n- **§6.5 Craft & finish** — §6.5.1 chips/pills/badges as native text backgrounds; §6.5.2 the craft pass checklist\n- **§6.6 Localization & RTL** — pointer to the `localize` skill\n- **§6.7 Font discovery & pairing** — the `ly.img.gfonts` lookup pattern, variable-font weights, context→pairing table\n- **§6.8 Copy** — the words, in this skill's `copy-writing-rules.md`\n",
|
|
591
|
+
"docs/handbook/SKILL.md": "---\nname: handbook\ndescription: |\n The CoDesign design loop, tool contract, workspace cheatsheet, typeface\n schema, common operations cheatsheet, and the full design-quality rubric.\n **Read this skill before any edit call** — it contains the 5-step Loop\n (decide parent → read API → exec → preview → judge), the tool roster and\n cross-tool rules, the workspace revision model (list / history / rename),\n rewind-recovery procedure, the typeface object shape required by setFont,\n and §6: the design-rules index — the full enforceable rubric (typography,\n hierarchy, composition, craft) ships as this skill's design-rules.md, the\n runtime-quirk reference as its quirks.md, and the input-resolution contract\n every skill follows as its intake.md, all read on demand.\n\n Triggered for any task using this server's `edit` or `preview` tools.\n---\n\n## 1. Loop\n\nYou MUST follow these steps in order for ANY canvas change:\n\n1. **Decide where you're editing from — based on what the user asked for, not what's in the workspace.** Either:\n - **New design requested** (the default in a fresh conversation) → pass `parent: null` and supply a `title` (the design name). The workspace persists across all past conversations — designs in it are not yours to continue unless the user points at them. For a new design, run the `create` skill's intake first to assemble the brief — and when two or more of the five design-defining parameters (topic, audience, visual direction, brand, format) are neither stated nor safely inferable, that intake **asks** before this edit rather than defaulting them.\n - **Continuing this conversation's design** → use the `revision` id from your last `edit` response as `parent`.\n - **User explicitly asked to resume earlier work** (\"keep working on yesterday's flyer\") → call `list` to see designs newest-first, then `history({ revision })` on the design they meant; pass the leaf as `parent`. Never do this unprompted.\n\n2. **Read the API docs** for every engine method you plan to use. Use `skill({ name: 'api' })` for signatures, `skill({ name: 'guide' })` for prose explanations and recipes. NEVER guess parameters.\n3. **Run `edit({ parent, code, note? })`** — execute the JS body. The response's first text part is JSON `{ revision, parent }` — save `revision`; it's your `parent` for the next edit.\n4. **Visually verify.** Call `preview({ blockIds: [<pageId>], revision })` — `revision` is REQUIRED; omit `blockIds` for every page. Never tell the user something \"looks good\" without seeing it yourself.\n\n5. **Judge & remediate before reporting done.** When the design is a candidate for \"done\", run the `judge` loop: score the 8 axes against your actual `preview` renders, dry-run the §6.1.11 + §6.5.2 checklists (design-rules.md), remediate any applicable axis below 8 via further `edit`s, re-preview, re-judge. On pass, record `scorecard({ revision, verdict: 'pass' })`; later content `edit`s re-arm this step. Never report an unjudged design as done.\n\nSteps 1, 2, 4, and 5 are NOT optional. Step 3's `note` is encouraged: a one-liner describing what you accomplished, so you can re-ground later.\n\n**Resolve your inputs before step 3, whichever skill you are in.** Derive what the request already answers, ask **once** for what is genuinely missing, echo what you resolved, and never invent a value that belongs to the user — a brand colour, a licensed font, a locale's wording. Ask through your environment's own question UI when it has one; a design's visual direction and brand are never silently defaulted on a first build. The contract is this skill's `intake.md` (`skill({ name: 'handbook', path: 'intake.md' })`); `create`, `brand`, `resize` and `localize` each carry the parameter table it applies to. `judge` is the one exception and asks nothing — it is the gate on every build.\n\n### Speak the user's language\n\n**Reply in whatever language the user writes to you in.** From their first message, and in everything they read: prose, questions, option labels and their subtext, the resolved-input echo, what you say about a preview, error explanations, the close. Switch if they switch. This is not a translation step at the end — it is the language you work in.\n\n**Two languages, not one.** The language you _speak_ and the language the design _contains_ are different axes, and conflating them is the failure mode here:\n\n- **Conversation language** — always mirrors the user. No exceptions.\n- **Design copy** — follows the brief. When the user has stated or implied a language for the content, that wins outright: someone writing to you in German may well want an English poster, and an English speaker may ask for an Arabic edition. Only when nothing implies otherwise does design copy **default** to the conversation's language — and when it does, say so in the echo (\"Textsprache: Deutsch\"), so a wrong guess costs one word to correct.\n- Changing an existing design's content language is never a side effect of the conversation — that is the `localize` skill, on request.\n\n**Never translate these**, in any language, because they are values rather than copy: skill and tool names (`judge`, `asset_generate`); `/onboard` job ids and other typed argument values (`job=generate`, `start=demo`); format ids and sizes (`ig-story`, `A4`, `1080×1350`); colour values; URLs, handles and channel names (`#showcase`); and revision ids. Translate a chip's **label**, never its **value** — a translated value breaks the call it feeds.\n\n**These documents stay English.** Every skill, handbook section and reference file is agent-facing instruction, not user-facing copy. Read them in English; speak to the user in theirs. The copy grammar in `create/choice-copy.md` — system-POV headers, verb-led titles, no pronouns in titles, lists parallel within themselves — applies in whatever language you are writing.\n\n### Re-grounding after a rewind / restart\n\nIf your conversation was rewound (double-ESC in Claude Code), or your process restarted mid-conversation, your in-memory \"current revision\" is wrong. The engine's state is the truth, but the server can't tell you've been rewound. Recovery:\n\n1. Call `list` — see the workspace's designs and their `latestLeaf` revisions.\n2. Call `history({ revision: latestLeaf })` — read the notes to find where the user wanted to be.\n3. Pass that revision id as `parent` on your next `edit`. The server reloads the engine to that scene before running your code — your edits land on top of the right state.\n\nRe-grounding recovers the design this conversation was already working on. It is not for starting a new conversation — a fresh session with a new request starts at `parent: null`.\n\nEditing on top of an OLDER revision (not the latest leaf) is fine: it creates a **non-destructive fork**. The previous leaves stay in storage; you can switch back any time by passing one of their ids as `parent`.\n\n## 2. Tools\n\nEach tool's full contract lives on the tool itself — its description in tools/list is authoritative and always in front of you. This section is only the roster plus the rules that span tools.\n\n- `edit({ parent, code, title?, note? })` — THE mutating tool: runs async JS (`engine` in scope) and commits a revision. The response's first text part is JSON `{ revision, parent }` — save `revision`; it is your `parent` for the next edit.\n- `preview({ blockIds, revision })` — render blocks to inline PNGs; omit `blockIds` for every page (max 10, full-size each).\n- `export({ format, revision, blockId?, outPath? })` — write a pdf/image/design artifact (`format`: `\"pdf\"`, `\"png\"`, `\"jpeg\"`, `\"webp\"`, `\"svg\"`, or `\"imgly\"`); omit `blockId` to export the whole document (`pdf` → one multi-page PDF, an image format → one composite image of all pages); returns `{ uri, httpUrl, bytes, format, revision }` (+ `path` when you pass `outPath`). `uri` is the durable handle; `httpUrl` is a fetch link tied to this process — never persist it. `outPath` (absolute path) ALSO writes the file to local disk — use it whenever your environment cannot fetch localhost URLs (sandboxed harnesses, e.g. Claude Cowork). `\"svg\"` is a vector SVG: text is outlined into paths (not editable text) and raster images are embedded at source resolution — the file can be much larger than its source images. `\"imgly\"` is the portable, self-contained design file (scene + all asset bytes, whole design only, no `blockId`) — the inverse of `import`, for taking an editable copy OUT; every `edit` already auto-persists, so it is never needed for durability.\n<!-- feature:video -->\n- `export` also accepts `format: \"mp4\"` — renders the block's authored timeline (see the video recipe in §4); needs the native engine (the default while video is enabled).\n<!-- /feature:video -->\n- `import({ source, title? })` — ingest a design FILE as a NEW root (was `load`): native `.imgly` (also legacy `.scene` / `.zip`), foreign Photoshop `.psd` / InDesign `.idml` / PowerPoint `.pptx` / PDF (translated in; `warnings` are your touch-up list — preview, then repair with `edit`), or a plain image/SVG (one page sized to it). Continue with `edit({ parent: revision })`.\n- `asset_add({ source: { path } })` — bring a local file (image or font) into the workspace for use in a design (was `import`); embed the returned `workspace://` uri in `edit` code — never `httpUrl`, and never the original local path or a `file://` URI (renders server-side but breaks the browser editor and portability).\n- `asset_search({ sourceId?, query?, page?, perPage? })` — discover and search the engine's asset sources; apply results inside `edit` (the exact patterns are in the tool's description). The `ly.img.workspace.images` source also lists images the human uploaded in the browser editor — searchable by their original filename, newest first.\n- `list()` / `history({ revision })` / `changes({ revision })` / `inspect({ revision })` / `rename({ revision, title })` — the workspace tools; usage in §3.\n- `view({ revision, pin? })` — human-facing viewer URL. Print it once; the viewer keeps it live.\n\nCross-tool rules:\n\n- **Revision ids are durable, block ids are not.** Everything flows through revisions: `edit` produces one, `preview`/`export`/`view` consume one, `history`/`inspect` walk them. Block ids are session-scoped — re-discover blocks in the current engine; never persist or replay literal block ids (see `inspect`'s description).\n- **The single mutating tool is `edit`.** `asset_add`, `asset_search`, and `view` never change the scene; placement and application always happen inside `edit` code. (`import` is the exception: it creates a new root to `edit` from.)\n\n## 3. Workspace cheatsheet\n\nThe workspace is your durable memory: every revision you commit via `edit` is there, addressable by id, walkable via `history`. It survives a process restart and a Claude rewind.\n\n```\nlist() → [{ rootRevision, title, latestLeaf, updatedAt, headOrigin?, headNote? }, …]\nhistory({ revision: leaf }) → [{ revision, parent, note?, origin?, createdAt }, …] (root first)\nchanges({ revision }) → { head, state, design, since?, wouldOrphanEditorWork, guidance } (what landed AFTER it)\ninspect({ revision }) → { revision, parent, note?, origin?, createdAt, title?, code? }\nedit({ parent: leaf, code }) → linear edit, no engine reload\nedit({ parent: olderRev, code }) → fork; engine reloads to olderRev first\nedit({ parent: null, title }) → new design\nrename({ revision: any, title }) → updates the root title\n```\n\nA revision id is a 12-hex-char string. You never construct it; the server hands it back from `edit`. Treat it as opaque.\n\n### Human edits from the browser editor\n\nThe `view` URL is a full editor. When the human clicks **Save**,\ntheir edits land as a normal child revision with `origin: \"editor\"`, no code,\nand a note that starts `Edited in the browser editor. Engine-computed diff vs\nparent:` followed by block-level changes.\n\n- **Finding their revision**: `changes({ revision })`, passing the revision you\n hold — normally the one your last `edit` returned. It tells you whether that\n revision is still the design head, lists what was written since it (oldest\n first, each with its `note` and `origin`), and names the revision to build\n on. Do NOT use `history` for this: it walks _ancestors_, so called with your\n own last revision it will never show their newer save — and previewing your\n own last revision renders the pre-edit scene, which looks exactly like\n \"nothing changed\". In a fresh conversation you hold no revision to pass;\n there `list` is the signal — it reports `headOrigin: \"editor\"` and the\n `headNote` for a design whose newest revision came from the editor.\n- **Call `changes` before your first `edit`** of a design the user may have had\n open in the browser. `edit` REFUSES a parent whose path to the head contains\n one of their editor saves — building from it would orphan their work on a\n sibling branch — and the refusal names the revision to pass instead. Pass\n `fork: true` only when the user explicitly asked you to discard their own\n browser changes and branch from the older revision.\n- **That note is authoritative.** It is computed by the engine, not\n free-typed. Do NOT re-derive it with preview loops or read-only `edit`\n dumps — that burns your edit budget and mints junk revisions.\n- **Continue from the human revision**: `edit(parent=<their revision>)`. Their\n changes are already in that scene.\n- A `Note: this design has newer revision(s)…` line on an `edit`/`preview`/\n `inspect`/`export` result means someone committed after the revision you\n passed. When that someone is you (your own earlier branch), the note is\n advisory and the fork is legal; the human's saves come back as the refusal\n above instead. Unless you are deliberately rewinding, rerun with the newer\n revision.\n\n## 4. Engine recipes\n\n### Build ONE complete page per `edit`\n\nThe unit of work is the **page**: every `edit` call emits one complete page — all its blocks, all setFont, all sizes, the `forceLoadResources` await, then positioning. Do **not** split a single page's build across 2–3 calls. Each tool call costs 20–200s of LLM streaming wall time; one ~10000-char call is faster than three ~3000-char calls because there's no thinking-between-calls overhead.\n\nFor a **single-page design** that means the entire scene in one `edit` — scene, page, all blocks:\n\n```js\n// 1. Structure\nconst scene = engine.scene.create('VerticalStack');\nconst stack = engine.block.findByType('stack')[0];\nconst page = engine.block.create('page');\nengine.block.appendChild(stack, page);\nengine.block.setWidth(page, 720);\nengine.block.setHeight(page, 1008);\n\n// 2. Look up fonts (ly.img.gfonts — design-rules.md §6.7), create all blocks\n// + setFont + setTextFontWeight + setString (fire-and-forget loads)\nconst FAMILY = 'Playfair Display';\nconst { assets: pf } = await engine.asset.findAssets('ly.img.gfonts', {\n query: FAMILY,\n page: 0,\n perPage: 20 // fuzzy ranking can put the exact match behind longer names\n});\nconst tfPlayfair = pf\n .map((a) => a?.payload?.typeface)\n .find((t) => t?.name === FAMILY);\nif (!tfPlayfair)\n throw new Error(\n `font lookup missed: no exact match for \"${FAMILY}\" among ` +\n pf.map((a) => a?.payload?.typeface?.name).join(', ')\n );\nconst titleText = engine.block.create('text');\nengine.block.setFont(titleText, tfPlayfair.fonts[0].uri, tfPlayfair);\n// REQUIRED on every text block: fonts[0] is the family's LIGHTEST weight\n// (Thin/100 on Inter, Roboto, …), so setFont alone renders hairline text.\nengine.block.setTextFontWeight(titleText, 'bold');\nengine.block.setString(titleText, 'text/text', 'Alex & Jordan');\nengine.block.setTextFontSize(titleText, 48, { unit: 'Pixel' });\nengine.block.setWidthMode(titleText, 'Auto');\nengine.block.setHeightMode(titleText, 'Auto');\nengine.block.appendChild(page, titleText);\n// ... repeat for every text + graphic block ...\n\n// 3. Deterministic font-load await\nawait engine.block.forceLoadResources([page]);\n\n// 4. Now position with measured frame dims\nconst w = engine.block.getFrameWidth(titleText);\nengine.block.setPositionX(titleText, (720 - w) / 2);\nengine.block.setPositionY(titleText, 250);\n// ... position everything ...\n\nreturn { type: 'text', text: `page=${page} ready` };\n```\n\nAfter this one call, your next tool call is `preview({ blockIds: [page], revision })`. **Exactly 2 calls per page — build, then capture. For a single-page design that's the whole job. Then STOP.**\n\n### Multi-page designs: page by page, page 1 first\n\nNever emit a multi-page design (carousel, slide deck, brochure) in one giant `edit`. Build it **page by page**, one `edit` + one `preview` per page:\n\n1. **Page 1 is the design-language gate.** The first `edit` builds the scene and page 1 only — it establishes fonts, palette, margins, grid. Preview it before touching page 2: a wrong aesthetic choice caught here costs one page, not N.\n2. **Pages 2..N each get their own `edit` + `preview`.** Each call builds one complete page reusing the design language page 1 proved out. Preview each page right after building it — the bugs on later pages are content-dependent (a headline that overflows, an image that crops badly), so batching pages doesn't avoid them, it just delays discovery. Feed findings forward: if body text at 28px overflowed on page 3, use 26px from page 4 on.\n3. **Batching is allowed only for near-identical clones** — templated pages differing by a short label or image swap. Even then, a thrown error mid-call loses every page in the batch; when in doubt, one page per call. Multi-block `preview` follows the same rule: batch renders are for review and final capture, never the build.\n\nThe objective-bug bar below applies per page: fix an overflow on page 3 with a targeted `edit` to page 3, then re-capture page 3 only.\n\n**Editing an existing multi-page design:** a mechanical change applied uniformly (swap a font everywhere, recolor a brand accent) is one `edit` looping over `engine.scene.getPages()` — that's one logical change, not a batch. Substantial per-page rework (rewriting layouts, restructuring content) goes page by page like a build, with a `preview` per reworked page.\n\nAfter the capture, fire a 2nd `edit` ONLY if the rendered PNG shows a specific, OBJECTIVE bug (text overflowing the page bounds, blocks visibly overlapping, missing characters, blank glyphs). Aesthetic refinement does NOT warrant another exec — sub-pixel nudges, \"could be a touch tighter\", compositional balance, vertical centering, whitespace distribution (\"top-heavy\", \"feels off-center\") are all DISALLOWED, even when the imbalance is large or intentional. If in doubt, STOP — a needless 3rd or 4th call (~30s wall + thinking tokens + latency) far outweighs any aesthetic gain. A read-only `edit` (one that returns data and mutates nothing — `getTextFontSizes`, `getFrameWidth`, etc.) still counts as a call against the limit, plus it forces a follow-up capture. Only fire a read-only exec if you'd otherwise be guessing at a number you can't read off the captured PNG.\n\n**Scope of these stop-rules: the build phase, before a `judge` pass.** They cap self-initiated polish between build and capture — they do not override Loop step 5. Once the `judge` skill has scored the design, remediating a failed axis (including composition or whitespace) is required work, not aesthetic refinement: apply the scorecard's fixes via `edit`, then re-preview and re-judge. The boundary is the scorecard — without one, only objective bugs warrant another `edit`; with one, its fixes do.\n\n### Font sizes are PIXELS, not points\n\nCE.SDK's font size APIs default to **points**. CE.SDK's scene unit defaults to **Inch** out of the box — but this demo wraps `engine.scene.create(...)` to call `setDesignUnit('Pixel')` immediately, so every scene the agent creates is in pixels by default. You don't need to set the unit yourself, but if you ever destroy + bare-call into the engine outside `scene.create`, re-set it. A unit-less font size is still read as points and converted at the scene's 300 dpi, so it lands **~4.2× too large**: `setTextFontSize(block, 32)` measures back as **133 px**, not 32.\n\n**ALWAYS pass `{ unit: 'Pixel' }`** when reading or writing font sizes:\n\n```js\nengine.block.setTextFontSize(block, 32, { unit: 'Pixel' }); // 32 px ✓\nengine.block.getTextFontSizes(block, { unit: 'Pixel' }); // returns px ✓\n```\n\n**NEVER:**\n\n```js\nengine.block.setFloat(block, 'text/fontSize', 32); // unit-less → 133 px ✗\nengine.block.setTextFontSize(block, 32); // defaults to points → 133 px ✗\n```\n\nLine-height is NOT a raw multiplier either: CE.SDK's `text/lineHeight` scales the font's content area, not the em — every visual line-height target must be divided by the font's content area (measured via `engine.editor.getFontMetrics`) before being set, and a reshape (`setString`) afterwards wipes per-character style ranges, so the order is line-height → reshape → re-apply every color/style range. Full rule and code: §6.1.3 in this skill's design-rules.md.\n\n### Text sizing — Auto + read frame dims\n\nFor text blocks, the canonical CE.SDK pattern is **Auto width/height + `getFrameWidth` / `getFrameHeight`** for measured dims. The engine shapes the text and exposes the actual frame extent through these reads, which you then use for centering, stacking, and overflow checks. Manual `setWidth`/`setHeight` on text is fragile: too small and the engine silently drops the render (no glyphs drawn, no error); too large and your alignment math is off.\n\n```js\nconst text = engine.block.create('text');\nengine.block.replaceText(text, 'Alex & Jordan');\nengine.block.setFont(text, uri, typeface); // 3-arg form (mandatory)\nengine.block.setTextFontSize(text, 64, { unit: 'Pixel' });\nengine.block.setWidthMode(text, 'Auto');\nengine.block.setHeightMode(text, 'Auto');\nengine.block.appendChild(page, text);\n\n// IMPORTANT: getWidth/getHeight return 0 in Auto mode. Read frame dims instead.\nconst w = engine.block.getFrameWidth(text); // measured shaped width\nconst h = engine.block.getFrameHeight(text); // measured shaped height\nengine.block.setPositionX(text, (pageW - w) / 2);\nengine.block.setPositionY(text, y);\n```\n\nUse absolute `setWidth`/`setHeight` only when you specifically want to constrain a wrap box (e.g. multi-line body copy with a fixed column width). Even then, set `setWidthMode(id, 'Absolute')` and pick height ≥ `fontSize × 1.6` for body sans, `≥ 1.8` for display serifs (Playfair, Cormorant) and scripts (Great Vibes, Caveat) — ascenders/descenders need the headroom or the engine drops the render.\n\n### Font-load barrier: `forceLoadResources`\n\n```js\nawait engine.block.forceLoadResources([page]); // recurses into children\n// now getFrameWidth returns real values for every text block on the page\n```\n\n`forceLoadResources(blocks)` returns `Promise<void>` that resolves once all fonts/images/fills bound to those blocks (and descendants) have finished loading. Pass `[page]` to await everything on the page. **No `setTimeout`, no polling.**\n\nThis barrier is for **your own measuring** inside `edit` code — positioning by measured frame width needs the fonts loaded first. Capturing is covered server-side: `preview`, `export`, and the commit at the end of every `edit` all force-load the scene's resources before rendering or serializing, so you never need a separate wait-for-fonts edit.\n\n`getFrameWidth(id) > 0` after the await is your \"font loaded + shaped successfully\" signal. **Never** use `getWidth(id) === 0` as a font-load probe — it returns 0 by design in Auto mode regardless of font state.\n\n<!-- feature:video -->\n\n### Video: any design can become a video\n\nScenes are not \"static\" or \"video\" at creation time — add time-based content\nto the scene you already have, then `export({ format: \"mp4\" })` renders the\nauthored timeline. Do NOT rebuild a scene with `scene.createVideo()` just to\nanimate it (`createVideo` and `scene.setMode('Video')` exist as conveniences;\nyou rarely need either).\n\n```js\n// Page duration = length of the exported video.\nengine.block.setDuration(page, 10); // seconds\n\n// Tracks hold timed children; blocks get offsets + durations.\nconst track = engine.block.create('track');\nengine.block.appendChild(page, track);\n// Tracks auto-arrange children back-to-back by default (this is silent —\n// no error, no warning). Turn it off before setting custom offsets below,\n// otherwise setTimeOffset appears to work but gets overwritten later.\nengine.block.setBool(track, 'track/automaticallyManageBlockOffsets', false);\nconst block = engine.block.create('graphic');\nengine.block.appendChild(track, block);\nengine.block.setTimeOffset(block, 1.0); // enters at t=1s\nengine.block.setDuration(block, 5.0); // visible for 5s\n\n// Video fill — use the workspace:// URI from `asset_add`.\nconst fill = engine.block.createFill('video');\nengine.block.setString(\n fill,\n 'fill/video/fileURI',\n 'workspace://assets/<sha>.mp4'\n);\nengine.block.setFill(block, fill);\n// Trim setters need the video's metadata — load it first, or they throw\n// \"The video has not been loaded yet.\"\nawait engine.block.forceLoadAVResource(fill);\nengine.block.setTrimOffset(fill, 2.0); // start 2s into the source\nengine.block.setTrimLength(fill, 5.0); // play 5s of it\n\n// Audio block — plays during the page's timeline.\nconst audio = engine.block.create('audio');\nengine.block.setString(audio, 'audio/fileURI', 'workspace://assets/<sha>.mp3');\nengine.block.appendChild(page, audio);\n```\n\n- Export: `export({ format: \"mp4\", revision, blockId: page })`.\n Duration/resolution come from the page — there are no export knobs.\n- Needs the native engine (the default while video is enabled). On an engine\n error, run `diagnostics` and check `status.config.engineResolved` —\n `wasm`/`wasm-fallback` cannot encode video.\n- `preview` renders a STILL frame of a video scene, not motion — pass `time`\n (seconds) to seek: verify a few salient moments (start, a transition, the\n end). Each video preview returns `{time, duration}` JSON next to the image.\n Export for the real thing.\n- Resource loading during export is handled server-side — you do NOT need a\n `forceLoadResources` barrier before `export` (unlike the font barrier above).\n The one load you DO need is `forceLoadAVResource(fill)` before reading or\n trimming a video fill (see the recipe above).\n- **Multi-clip tracks (sequences, crossfades): disable auto-arrange first.**\n`track/automaticallyManageBlockOffsets` defaults to `true` and silently\noverwrites every child's `setTimeOffset` with an auto-computed back-to-back\nvalue — no error. It looks fine with one clip (offset 0 either way), which\nis why it hides until you need two clips to overlap. Before setting any\nchild offsets: `engine.block.setBool(track, 'track/automaticallyManageBlockOffsets', false)`.\n<!-- /feature:video -->\n\n### Common operations cheatsheet\n\nThe `engine.*` calls used in nearly every `edit`. Verify exact signatures + types in the `cesdk-api` skill before using anything not listed here.\n\n```js\n// Scene + page basics — hierarchy is scene → stack → page (NOT scene → page).\n// engine.scene.create(\"VerticalStack\") makes the scene AND a stack container.\n// Pages attach to the stack, never directly to the scene root.\n// The \"VerticalStack\" argument is REQUIRED — without it, no stack is created\n// and findByType(\"stack\") returns []. (Use \"HorizontalStack\" for side-by-side.)\nconst scene = engine.scene.create('VerticalStack');\nconst stack = engine.block.findByType('stack')[0];\nconst page = engine.block.create('page');\nengine.block.appendChild(stack, page); // ← stack, not scene\n// The stack arrives with the editor's page gap already set (48 screen-space\n// px, matching the CE.SDK editor — the raw engine default of 0 is never what\n// you want). Override only for a deliberate look, e.g. an edge-to-edge collage:\n// engine.block.setFloat(stack, 'stack/spacing', 0);\nconst pages = engine.scene.getPages(); // DesignBlockId[]\nconst current = engine.scene.getCurrentPage(); // DesignBlockId | null\n\n// Block creation\nconst text = engine.block.create('text');\nconst graphic = engine.block.create('graphic');\n\n// Position & size\nengine.block.getPositionX(id);\nengine.block.setPositionX(id, x);\nengine.block.getPositionY(id);\nengine.block.setPositionY(id, y);\nengine.block.getWidth(id);\nengine.block.setWidth(id, w);\nengine.block.getHeight(id);\nengine.block.setHeight(id, h);\n\n// Page dimensions (for proportional calculations)\nconst pageW = engine.block.getWidth(page);\nconst pageH = engine.block.getHeight(page);\n\n// Fills + shapes (graphic blocks)\n// NOT for a text-only chip/pill/badge/button/tag — those are a text block with a\n// native text background, never a rect behind floating text (see the chip recipe\n// below, §6.5.1). Reach for a rect only for real graphics, or a chip whose content\n// is NOT just text (icon + text, an image, multiple elements).\n// \"rect\" | \"line\" | \"ellipse\" | \"polygon\" | \"star\" | \"vector_path\".\n// Anything with a diagonal, a curve or a hole is a vector_path — see the\n// custom-shapes recipe below. Do NOT approximate one out of stacked rects.\nconst shape = engine.block.createShape('rect');\nengine.block.setShape(graphic, shape);\nconst fill = engine.block.createFill('color'); // also: \"image\"\nengine.block.setFill(graphic, fill);\nengine.block.setColor(fill, 'fill/color/value', { r, g, b, a });\n\n// Text content + color + size (PIXELS — see pixel rule above)\nengine.block.setString(text, 'text/text', 'Hello');\nengine.block.setTextColor(text, { r, g, b, a }); // whole text\nengine.block.setTextColor(text, { r, g, b, a }, start, end); // char range\nengine.block.setTextFontSize(text, 32, { unit: 'Pixel' });\nengine.block.getTextFontSizes(text, { unit: 'Pixel' });\n\n// Rich text — STYLE RANGES inside ONE block. Every setter below takes an optional\n// (from, to) character range; omit it to style the whole string. An accent word, a\n// bold lead-in, an inline price, a struck-through old price: all are RANGES on one\n// text block, never a second block placed beside the first. Two blocks look identical\n// in a render and are caught by reading the scene graph — they also re-break on every\n// copy/font/locale change, because nothing binds them to each other. (§6.1.9)\nengine.block.setTextFontWeight(text, 'bold', start, end); // 'thin'…'heavy' (9 steps)\nengine.block.setTextFontStyle(text, 'italic', start, end); // 'normal' | 'italic'\nengine.block.setTypeface(text, tf, start, end); // a second face inline\nengine.block.setTextFontSize(text, 48, { unit: 'Pixel', from: start, to: end });\nengine.block.setTextCase(text, 'Uppercase', start, end); // see the caps rule below\nengine.block.setTextDecoration(text, { lines: ['Underline'] }, start, end);\n// Decoration is configurable, not just on/off:\n// lines: 'Underline' | 'Strikethrough' | 'Overline' (combinable)\n// style: 'Solid' | 'Double' | 'Dotted' | 'Dashed' | 'Wavy'\n// underlineColor / underlineThickness / underlineOffset / skipInk (keep skipInk on\n// so descenders stay legible). Toggle helpers: toggleTextDecorationUnderline(...).\n\n// ALL-CAPS: set the PROPERTY, don't type capitals into the string. setTextCase re-cases\n// on render, so the string stays real words — translatable, searchable, and correct in\n// scripts that have no case at all. Typed capitals are frozen English. (§6.1.6)\nengine.block.setTextCase(text, 'Uppercase'); // 'Normal'|'Uppercase'|'Lowercase'|'Titlecase'\n\n// Read styling back — the ONLY safe way to capture before a reshape. Returns one entry\n// per run with from/to/text/color/fontWeight/fontStyle/fontSize/textCase/typeface/\n// textDecoration/kerning. ⚠ Any write to 'text/text' WIPES every range: capture, write,\n// replay. The wipe collapses the string to RUN 0's formatting — not to a neutral base —\n// so replay EVERY captured run, not just the emphasis spans: if run 0 was a bold lead-in,\n// replaying only the accent leaves the whole paragraph bold, silently, and reading the\n// accent range back still looks correct. setTextFontSize alone does NOT wipe ranges; only\n// the string write does. getTextColors(id)[0] is run 0 only — re-applying it whole-block\n// is what flattens a two-color headline. (handbook quirks; §6.1.9)\nconst runs = engine.block.getTextRuns(text);\n\n// PARAGRAPH-level — these take a paragraphIndex (negative = all paragraphs), NOT a\n// character range. Multi-paragraph copy is ONE block with paragraph spacing, never N\n// blocks stacked by hand and never blank lines used as spacing. (§6.1.8)\n// ⚠ paragraphSpacing is an EM MULTIPLE of the font size, NOT pixels. 0.4–0.8 is the\n// usable band; a pixel-looking value like 12 means twelve em and silently pushes the\n// page metres long with no error (measured: 9 on 17px copy → ~150px gaps).\nengine.block.setFloat(text, 'text/paragraphSpacing', 0.6); // EM between paragraphs\nengine.block.setTextHorizontalAlignment(text, 'Center', 0); // just paragraph 0\nengine.block.setTextLineHeight(text, 1.2, 0); // per-paragraph leading\n// Read alignment back with paragraphIndex -1 for the BLOCK-level value; a per-paragraph\n// read returns undefined when no paragraph override is set, which looks like \"unset\".\nengine.block.getTextHorizontalAlignment(text, -1);\n\n// Text alignment + spacing (typed properties via setEnum / setFloat)\nengine.block.setEnum(text, 'text/horizontalAlignment', 'Center'); // \"Left\" | \"Center\" | \"Right\"\nengine.block.setEnum(text, 'text/verticalAlignment', 'Center'); // \"Top\" | \"Center\" | \"Bottom\"\nengine.block.setFloat(text, 'text/letterSpacing', 0.05); // ratio of em\nengine.block.setFloat(text, 'text/lineHeight', 1.2); // ratio of font size\n\n// Chips (pill / eyebrow / badge / tag / button) — a NATIVE text background on the\n// text block itself. Use this instead of a rectangle behind floating text: the field\n// is bound to the label, so it reflows on any copy/font/locale change instead of\n// drifting off-center. A backing rect is correct ONLY when the chip's content is not\n// just text. This is a build rule, not a preference — a rect+text chip renders\n// identically and is caught by reading the scene graph, not by eye. (§6.5.1)\nengine.block.setBool(text, 'backgroundColor/enabled', true);\nengine.block.setColor(text, 'backgroundColor/color', { r, g, b, a });\nengine.block.setFloat(text, 'backgroundColor/cornerRadius', h / 2); // pill = half the padded height\nengine.block.setFloat(text, 'backgroundColor/paddingLeft', 16); // horizontal ~1.5–2.5× vertical\nengine.block.setFloat(text, 'backgroundColor/paddingRight', 16);\nengine.block.setFloat(text, 'backgroundColor/paddingTop', 8);\nengine.block.setFloat(text, 'backgroundColor/paddingBottom', 8);\n// Align the chip by its padded FIELD edge, not its glyph run (§6.5.1). The padding\n// expands the field OUTWARD from the text frame, and getFrameHeight reports the UNPADDED\n// height — so to land the field edge on the margin, and to get a true capsule:\n// setPositionX(chip, MARGIN + paddingLeft) // not MARGIN\n// cornerRadius = (getFrameHeight(chip) + padTop + padBottom)/2 // not frameHeight/2\n\n// Lists — native bullets/numbers WITH a real hanging indent (wraps align to text,\n// not the marker). Per-paragraph; negative index = all paragraphs. ONE text block\n// holds the WHOLE list, one paragraph per item. All three hand-built fakes are wrong\n// and all three render almost identically, so they are caught in the scene graph:\n// 1. typing \"• \" into the string -> no hanging indent\n// 2. a lone \"•\" text block per item -> marker drifts off its text on any change\n// 3. one text block per list item -> no list at all, N loose ungrouped blocks\n// (§6.1.8)\nengine.block.setTextListStyle(text, 'Unordered'); // \"None\" | \"Unordered\" | \"Ordered\"\nengine.block.setTextListStyle(text, 'Ordered', -1, 0); // all paragraphs, nesting level 0\nengine.block.setTextListLevel(text, 1, 2); // nest paragraph 2 one level in\n// engine.editor.setSettingFloat('listIndentPerLevel', 1.5); // indent width per level, EM\n\n// Text on a path — circular/curved type (\"EST. 2026\" around a seal, a badge arc).\n// Use this instead of faking a curve by placing one text block per letter and rotating\n// each: a per-letter fake has no real baseline, so tracking is uneven, it re-breaks on\n// any copy/font/locale change, and it ships as N loose blocks instead of one. ONE text\n// block on a path is the only correct curved type. (§6.5.4)\n// svgPath is in the block's local coordinate space; null clears it back to normal.\nengine.block.setTextOnPath(text, 'M 0 100 A 100 100 0 1 1 200 100'); // e.g. an arc\nengine.block.setTextOnPathOffset(text, 0.5); // proportional start offset along the path\nengine.block.setTextOnPathFlipped(text, false); // true = underside, reversed direction\n// Three constraints worth knowing before you build the path:\n// - EXACTLY ONE subpath — a single leading \"M\", no second one. Multiple subpaths throw\n// BLOCK.TEXT_ON_PATH_MULTIPLE_SUBPATHS. Split the shape or pass one contour.\n// - The string must be a parseable SVG path, else BLOCK.TEXT_ON_PATH_INVALID_SVG_PATH.\n// - Setting a path RESIZES the block, so set the path BEFORE positioning. But the\n// reported box is NOT the ink box and is smaller than the glyph ring: a 130×130\n// authored path reads back 84×84 on getWidth/getHeight/getFrameWidth/getFrameHeight\n// alike, and previewing the block alone clips its own text on all four sides. Derive\n// margin and collision math from the AUTHORED path geometry, never the re-read box,\n// or curved type sits ~23px per side outside where you placed it. Same reason\n// `localize` (which snaps geometry to a reference) and `resize` (which re-derives it)\n// must carry the path, not the post-path box.\n\n// Font — REQUIRES three args. Passing only (text, uri) throws a cryptic\n// \"Cannot read properties of undefined (reading 'name')\" because cesdk\n// reads typeface.name internally. The typeface object is mandatory.\n// For Google families DON'T build it by hand — look it up from the\n// ly.img.gfonts source (design-rules.md §6.7). Hand-built typefaces are for\n// brand fonts imported to workspace:// URIs:\nconst uri = 'workspace://assets/abc123def456.ttf';\nconst typeface = {\n name: 'Acme Grotesk',\n fonts: [{ uri, subFamily: 'Regular', weight: 'normal', style: 'normal' }]\n};\nengine.block.setFont(text, uri, typeface);\n\n// Await all resource loads (fonts, images, fills) for blocks + descendants.\n// Use this after a batch of setFont calls before reading frame dims or capturing.\nawait engine.block.forceLoadResources([page]);\n```\n\n### Custom shapes — `vector_path`, not a pile of rects\n\n**Any mark with a diagonal, a curve or a hole is one `vector_path` block.** The\nprimitives cannot express those, so approximating a mark out of rects and\nellipses produces stepped edges where a slope should be, and costs one block per\nstep: a windowed facade drawn that way came to 79 blocks and still rendered as a\nstaircase. The same mark as a path is one block with clean geometry.\n\n```js\nconst graphic = engine.block.create('graphic');\nconst shape = engine.block.createShape('vector_path');\nengine.block.setString(shape, 'shape/vector_path/path', d); // SVG path data — built below\n// width/height are the PATH'S COORDINATE FRAME, not the on-canvas size. Author\n// in a fixed box (100x100 is convenient) and scale with the block's size, so one\n// definition works at any scale.\nengine.block.setFloat(shape, 'shape/vector_path/width', 100);\nengine.block.setFloat(shape, 'shape/vector_path/height', 100);\nengine.block.setShape(graphic, shape);\nengine.block.setWidth(graphic, 420); // on-canvas size, independent of the frame\nengine.block.setHeight(graphic, 460);\n```\n\n#### Fill rule: `NonZero` + deliberate winding\n\n`engine.block.setEnum(shape, 'shape/vector_path/fillRule', v)` takes\n**`'EvenOdd'` | `'NonZero'`**. For a mark built from several subpaths this is the\nwhole game:\n\n- **solid parts wound one way** (say clockwise) — they **union** where they overlap\n- **holes wound the opposite way** — they **punch through**\n\n**The default is `EvenOdd`, and it is the wrong one for a composite mark — set\n`NonZero` explicitly.** `EvenOdd` XORs, so any two solid parts that cross — a\ncross-brace over a leg, a spoke over a hub — knock a hole at the intersection,\nand no amount of correcting the winding will fix it. Keep `EvenOdd` only for\nshapes whose subpaths strictly nest and never overlap.\n\n```js\nengine.block.setEnum(shape, 'shape/vector_path/fillRule', 'NonZero');\n```\n\nWinding is a property of point order, so enforce it in code rather than by\nhand-writing paths in the right direction. Screen coordinates are **y-down**, so\nthe usual shoelace sign is inverted:\n\n```js\n// +y is DOWN, so a negative shoelace sum means clockwise.\nconst isClockwise = (pts) =>\n pts.reduce((a, [x1, y1], i) => {\n const [x2, y2] = pts[(i + 1) % pts.length];\n return a + x1 * y2 - x2 * y1;\n }, 0) < 0;\n\nconst orient = (pts, cw) =>\n isClockwise(pts) === cw ? pts : [...pts].reverse();\n\nconst poly = (pts, cw = true) =>\n 'M ' +\n orient(pts, cw)\n .map(([x, y]) => `${x},${y}`)\n .join(' L ') +\n ' Z';\n\nconst d = [poly(body), poly(window, false)].join(' '); // solid + hole\n```\n\nTwo traps worth knowing before you lose an hour to either:\n\n- **A hand-reversed Bézier subpath can silently fail to punch.** Rectangular\n holes work while an arched one built by writing the curve backwards renders\n solid, with no error. Sample curved holes into a polygon and let one\n orientation helper own the winding for every subpath.\n- **Prefer four cubic Béziers to an SVG arc** for circles and rounded caps —\n it sidesteps `A` command largeArc/sweep flag handling entirely. Control points\n sit at `k = 0.5522847498 * r`.\n\n#### Holes are real holes\n\nA `vector_path` hole shows whatever is behind the block — page ground, another\ngraphic, a photograph. That is usually what you want on a flat ground and\nusually **not** what you want over a photograph, where it reads as a hard-edged\ncut-out rather than a printed mark. Over imagery, emit the solid subpaths only\nand drop the holes. Faking a hole with a ground-coloured shape on top is a bug\nwaiting to happen: it only matches a flat, known ground, and it visibly fails\nover a photograph.\n\n### Z-order via child order (no z-index property)\n\nCE.SDK has no z-index. Render order = child order. Later children paint on top of earlier siblings.\n\n```js\nengine.block.appendChild(parent, child); // child becomes LAST = top-most\nengine.block.insertChild(parent, child, index); // index 0 = back-most\nengine.block.getChildren(parent); // current children, back-to-front\n```\n\n**Build pages back-to-front.** Suggested canonical layer stack for a designed page:\n\n1. page background fill — `setFill` on the page block (an attribute, not a child; sits below any children)\n2. full-bleed photo / image (first child, index 0)\n3. scrim / vignette / gradient overlay\n4. structural rules — grid hairlines, dividers, frames\n5. accent shapes — pills, badges, accent bars, icons\n6. body text\n7. headline / display text\n8. foreground decoration (corner brackets, stickers)\n\nAppend in this order. If you create text before its background pill, the pill will cover the text. Deviate from the canonical order when intent demands — it is a default, not a rule.\n\n**Fix without rebuilding** — to demote an existing sibling underneath another, use `insertChild` with a measured index:\n\n```js\n// text block already exists at top of stack; demote a sibling pill behind it\nconst children = engine.block.getChildren(page);\nconst textIdx = children.indexOf(textId); // textId must be a direct child of page (else -1)\nengine.block.insertChild(page, pillId, textIdx); // pillId now sits just behind textId\n```\n\nStack-layout pages (`VerticalStack` / `HorizontalStack`): the stack arranges pages along an axis; the same child-order rule applies WITHIN each page's children.\n\n**Never destroy + recreate to fix ordering.** Use `insertChild`.\n\n### Group blocks & hierarchy — structure every page as a tree\n\nA finished page is a **tree, not a flat list of siblings**. Once blocks are created and positioned, cluster every set that reads as one unit into a group with `engine.block.group(ids)`, and **nest groups into parent groups** where the clusters nest. This is not optional polish: the group hierarchy is how z-order, moving, and later `resize` operate on semantic units instead of loose blocks, it encodes the reading structure the `judge` skill scores (§6.3), and it survives an `.imgly` round-trip.\n\nContract (verify signatures in the `api` skill):\n\n- `engine.block.isGroupable(ids)` — `false` if any id is a scene block or is **already** inside a group. Always guard with it.\n- `engine.block.group(ids)` — returns the new group's id. The blocks must be **siblings** (same parent). Call it **after** positioning: the group's bounding box is derived from its children's placed frames.\n- `group()` inserts the group at the **minimum child index** among its members, so building back-to-front (per the layer stack above) means grouping does **not** disturb z-order.\n- Recover with `engine.block.ungroup(id)`; `enterGroup` / `exitGroup` / `insertChild` still address the children.\n\n```js\nconst group = (ids) =>\n engine.block.isGroupable(ids) ? engine.block.group(ids) : null;\n\n// 1) group each leaf cluster after it is built + positioned\nconst gHeader = group([topRule, kickerL, kickerR]);\nconst gHero = group([title1, title2, tagline]);\nconst gDetail = group([divider1, divider2, ...detailCells]);\n\n// 2) group the groups → a nested super-cluster (group-of-groups)\nconst gMasthead = group([gHeader, gHero]);\n```\n\nGuardrails: group only **direct siblings**; never group across pages; a block already in a group makes `isGroupable` return `false` (ungroup first if you must re-cluster); measure text frames (`forceLoadResources` → `getFrameWidth`) and position **before** grouping. Close the build by returning the group manifest in the edit `note` (e.g. `groups: masthead=… detail=… lineup=…`) so the hierarchy is legible when you re-ground.\n\n## 5. Quirks\n\nCE.SDK errors are short and opaque, and several runtime behaviors don't show up in the .d.ts. The full quirk reference — the error-message → cause table, the runtime-symptom → workaround table, and the text-doesn't-render diagnosis order — lives in this skill's `quirks.md`. On ANY cryptic error or non-rendering block, search it BEFORE bisecting: `skill({ name: 'handbook', path: 'quirks.md', query: '<fragment of the error message>' })`.\n\n### Prefer surgical fixes over wipe-and-rebuild\n\nEach rebuild costs ~10 extra tool calls (re-create scene, re-position every block, re-verify). When something looks wrong, identify the specific block and edit it in place — `setPositionY`, `setTextFontSize`, `replaceText`, etc. Reach for `engine.scene.create(...)` only when the scene graph is genuinely unrecoverable, which is rare.\n\n## 6. Design rules\n\nEnforceable design best practices with numeric thresholds — what you build to, and what the `judge` skill scores against. Each rule group ends with a **Pass condition**; a failed Pass condition pulls its parent axis below 8, and one axis below 8 fails the design (no averaging — see the `judge` skill for the axes and the gate).\n\n- **Web vs print** — where the two media diverge (line height, minimum sizes) the rules are split **Web** / **Print**; \"web\" values apply to screen-destined canvases (social posts, banners). An unqualified rule applies to both.\n- **N/A = 10** — a rule that cannot apply to a given design scores N/A, i.e. 10.\n- **Defaults fill silence** — when the user's brief gives an explicit value for a property, use it; when it is silent, apply this section's defined **default** rather than leaving the property unset or letting the engine default stand. Every numeric rule below that names a _default_ (line-height §6.1.3, type scale §6.1.2, measure §6.1.4, all-caps tracking §6.1.6, margins §6.4) is that fallback. Silence is not permission to skip the property. A brief value that violates a hard threshold is clamped to the threshold — except line-height, which is judged by the rendered gap after conversion, never by the raw number (§6.1.3).\n\n**The full rubric lives in this skill's `design-rules.md`** — read it BEFORE building: `skill({ name: 'handbook', path: 'design-rules.md' })`. Section map:\n\n- **§6.1 Typography** (§6.1.1 families/pairing · §6.1.2 type scale & canvas bands · §6.1.3 line-height/leading incl. the content-area conversion · §6.1.4 measure · §6.1.5 alignment/rag · §6.1.6 tracking & case · §6.1.7 micro-typography · §6.1.8 lists & paragraph structure · §6.1.9 rich text / inline style ranges · §6.1.10 print rules · §6.1.11 the typography pass checklist)\n- **§6.2 Color** — palette ≤ 3 + neutrals, one accent, contrast on the actual background\n- **§6.3 Hierarchy** — one dominant element; rank via size > weight > color > spacing > position\n- **§6.4 Composition & grid** — margins 8–12% of the shortest dimension, the spacing ladder, no dead void\n- **§6.5 Craft & finish** — §6.5.1 chips/pills/badges as native text backgrounds; §6.5.2 the craft pass checklist\n- **§6.6 Localization & RTL** — pointer to the `localize` skill\n- **§6.7 Font discovery & pairing** — the `ly.img.gfonts` lookup pattern, variable-font weights, context→pairing table\n- **§6.8 Copy** — the words, in this skill's `copy-writing-rules.md`\n",
|
|
592
592
|
"docs/handbook/copy-writing-rules.md": "# Handbook §6.8 — Copy-writing rules (the words on the page)\n\nExpands the **copy** axis. Every other section governs how the design looks; this one governs what it says. A page can pass all seven other axes and still be obviously machine-written, because nothing else in this rubric reads the words.\n\nThe rules below are adapted from Wikipedia's [\"Signs of AI writing\"](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing) (WikiProject AI Cleanup), narrowed to copy that lives inside a layout. Template copy is not an essay: a slide headline is six words, a menu item is three, a chart caption is one sentence explaining a number. The judgment is not \"does this paragraph flow\" but **\"would a person who actually runs this business write this line on this artifact.\"**\n\n#### The tells worth hunting\n\n- **The nothing tagline.** A line that could sit on any brand in any category. _\"We navigate the intersection of raw human emotion and digital precision to redefine the modern aesthetic\"_ describes no business. Replace it with what the business actually does.\n- **The transformation claim.** _turns X into Y_, _stops being X and becomes Y_, _from a bottleneck into a safety net_. State the change plainly and once. The same shape twice in one design is the confession.\n- **The superlative nobody can check.** _world-class_, _best-in-class_, _premier_, _unparalleled_, _the world's most-loved_. A real company writes the number instead — and when a number is already in the sentence, the superlative is doing nothing.\n- **The upbeat closer.** _the compounding is just getting started_, _exciting times ahead_, _a major step in the right direction_. Cut the sentence; the line before it already made the point.\n- **Manufactured depth.** Present-participle tails that add no fact (_…, reflecting the community's deep connection to the land_), abstract-noun openers that delay the point (_X has always run on a quiet contradiction_), and aphorism formulas (_X is the language of Y_).\n- **Rule-of-three padding.** Three abstract nouns where one concrete one would do: _disciplined growth, operational resilience, and durable long-term value_.\n- **Vocabulary that marks the text as generated.** _elevate, unlock, seamless, empower, effortless, bespoke, timeless, vibrant, tapestry, testament, redefine, leverage, holistic, curated_. Judge each in context — `curated wine pairing` on a restaurant menu is ordinary English; `curated experiences that elevate your journey` is not. The word is never the tell; the emptiness is.\n- **Filler body text.** Copy that fills a frame without saying anything. Delete the block and ask whether the page lost information. If it did not, the block needs a real sentence, not a shorter version of the same nothing.\n\n#### What is not a tell\n\nThe failure mode of a copy pass is damaging good writing. Leave copy alone when it is:\n\n- **Specific.** Numbers, dates, names, addresses, real figures. `ARR reached $48.2M, up 27% year over year` is not slop, whatever its cadence.\n- **Domain idiom.** `synergy targets` in a CV, `transformation programme` in consulting, `house-made` on a menu. Trade language is how those trades write.\n- **The voice the brief asked for.** A luxury stationery card is meant to sound formal; a pull quote is meant to sound quotable; a greeting card is warm and formulaic because that is the product.\n- **Deliberately generic placeholder copy**, where the design ships as a template for someone else's words.\n\n#### Typography is not a tell\n\nTwo rules from general anti-AI-writing guidance are written for web prose and are **wrong here**:\n\n- **Em and en dashes stay.** In a layout the em dash is typography: `Reception 7:00 PM — Dinner at 8:00` is correct setting, and so is a dash in a pull quote or a chart annotation. What can be a tell is **density** — three or more in one short block, or a dash in every second line of a deck. Flag the pattern, never the character.\n- **Curly quotes stay.** `“…”` and `’` are correct typography and §6.1.7 already requires them. Straight quotes are the defect, not the fix — except in a monospace or terminal design where the plain glyph is the point.\n\nLikewise, do not inject personality where the artifact does not want it. Adding opinions, first person or asides is right for a blog post and wrong for a wedding invitation, a lab report cover or a compliance footer, where neutral and plain **is** the correct human voice.\n\n#### Editing copy in an existing design\n\n- **Length is a layout constraint.** The text sits in a frame laid out around it. Keep a rewrite within ~10% of the original character count, preserve explicit line breaks and their positions, and preserve leading/trailing spaces — some strings are fragments of a sentence split across styled blocks. One string in, one string out: never merge or split blocks to make a rewrite fit.\n- **Localized editions move together.** A source-derived edition shares its blocks with the source (§6.6), so rewriting only the source language leaves the German saying what the English used to. Rewrite every language, or leave the string alone.\n- **Check the glyphs before you commit.** A saved archive carries **subsetted** fonts — only the glyphs the copy needed when it was built. A rewrite that introduces a new character has no glyph, and the engine falls back to another face silently rather than failing: the render comes back with mixed stroke weights inside one headline and looks almost right. Latin copy rarely trips this; a CJK subset can be ~150 glyphs, so nearly any rewrite does. Re-render and read the result, and prefer characters the design already uses.\n\n#### Pass\n\nEvery line names something true about this business, product or occasion that a competitor could not paste into their own page; no transformation claim, uncheckable superlative or upbeat closer; no abstract-noun opener or participle tail standing in for a fact; vocabulary chosen for the trade rather than for the register; every rewrite within its frame's length, its line breaks intact, its sibling languages carried, and its glyphs actually present in the packed fonts.\n",
|
|
593
593
|
"docs/handbook/design-rules.md": "# Handbook §6 — Design rules (the full rubric)\n\nThe enforceable design best practices this server's designs are built to and the `judge` skill scores against. Section numbers here are canonical: `§6.x` references across the handbook and the other skills resolve to this file. Sliceable — pass `offset`/`limit` for a section, or `query` to search.\n\n### 6.1 Typography\n\nExpands **Axis 3 — Typography** (\"≤3 font families, correct pairing, sizes in band, sane line-spacing and leading, no tofu\"). Every subsection below must hold for Axis 3 to score ≥ 8.\n\n#### 6.1.1 Font families & pairing\n\n- Use **≤3 font families** per design (≤2 preferred); no more than **4 weights** total. Every extra family/weight dilutes hierarchy and reads as inconsistency.\n- Pair by **contrast**, not similarity — e.g. a serif display against a sans body, or one superfamily used across roles. Never pair two families that are almost alike (two humanist sans, two geometric sans).\n- Give every family a defined fallback: an **embedded/outlined** font (print) — and verify glyph coverage for every character in the copy (web/canvas). System substitution silently changes metrics and breaks leading and measure.\n- **Pass:** ≤3 families, ≤4 weights, pairing is by intentional contrast/superfamily, every family verified to cover the copy (print: embedded/outlined).\n\n#### 6.1.2 Type scale & size bands\n\n- Derive all sizes from **one modular scale** (ratio 1.2–1.618; 1.25 is a safe default). No arbitrary one-off sizes.\n- Keep text in clear **bands** — Display/Headline, Subhead, Body, Caption, Fine print — each separated by **≥1 scale step** so the hierarchy is unambiguous (supports Axis 2).\n- Minimum legible sizes:\n - **Web** — body ≥ **16px**, caption ≥ **12px**, never below **11px**.\n - **Print** — body **9–12pt**, caption ≥ **7pt**, never below **5pt**.\n- **Pass:** every size snaps to one modular scale; body ≥ 16px (web) / ≥ 9pt (print); bands are ≥1 step apart and visually distinct.\n\n**Canvas guidance — sizes as % of page height:**\n\n| Role | % of page height | Example for 1080 px page |\n| ----------- | ---------------- | ------------------------ |\n| Headline | 3 – 5 % | 32 – 54 px |\n| Body | 1.5 – 2 % | 16 – 22 px |\n| Caption | 1.2 – 1.5 % | 13 – 16 px |\n| Min legible | — | 14 px |\n\n#### 6.1.3 Line height / leading — the headline rule\n\nLine spacing is the top driver of the \"inconsistent typography\" complaint. Three principles govern it: **explicitness** (every text block carries a deliberately set line-height — never an inherited default), the **inverse rule** (small text needs more line-height; large display needs less), and **consistency** (identical leading across same-band text within one design).\n\n- **Set line-height explicitly on every text block** — including single-line labels, captions, and all-caps titles, not just multi-line body copy. An unset line-height (the engine/CSS default) is a defect even when the block is one line: it silently tracks the font's default metrics, can't be verified against the bands below, and defeats both the consistency and all-caps rules. A one-line all-caps label still takes the tighter all-caps multiplier (**0.9–1.0**); the value is judged by band + intent, not by whether the text happens to wrap. Same-band single-line blocks (e.g. an attribution and a caption in the same face) share their leading just as body blocks do.\n\n> **Authoring in CoDesign / CE.SDK — convert visual line-height to the engine's content-area scale.** Every line-height figure in this section is a _visual_ target expressed as a CSS-style unitless multiplier. CE.SDK's `text/lineHeight` is **scaled differently** from CSS: it multiplies the font's **content area** — `(ascender − descender + lineGap) / unitsPerEm`, which varies by face (~1.15–1.35 for common text faces, higher for tall display faces) — not the em / point-size. Setting `text/lineHeight` to the raw visual target therefore renders visibly looser, leaving a descender-sized void between lines (worst on multi-line all-caps display like Anton). **Convert every value here by _dividing_ the visual target by the font's content area, measured per font via `engine.editor.getFontMetrics`,** before calling `engine.block.setFloat(id, 'text/lineHeight', …)`:\n>\n> ```js\n> const [block] = engine.block.findAllSelected(); // or a known block id\n> const fontUri = engine.block.getString(block, 'text/fontFileUri');\n> const m = await engine.editor.getFontMetrics(fontUri);\n> const contentArea = (m.ascender - m.descender + m.lineGap) / m.unitsPerEm;\n>\n> const targetLineHeight = 1.2; // the VISUAL line-height the design/prompt wants (a §6.1.3 band value)\n> engine.block.setFloat(\n> block,\n> 'text/lineHeight',\n> targetLineHeight / contentArea\n> );\n> ```\n>\n> `targetLineHeight` is the **visual** leading you want to _see_ (all-caps headline 0.95, body 1.5, …) — the same number as the bands below, and the value you would naively set. It is **not** what lands on the block: the engine receives `targetLineHeight / contentArea`, which is what makes the _render_ hit the target (measured: a Playfair Display headline at content area ~1.33 → `0.95 / 1.33 ≈ 0.71`; Roboto at ~1.17 → `0.95 / 1.17 ≈ 0.81` — **different engine values for the same visual target**, which the old fixed `× 0.66` → 0.63 could not give). `descender` is negative in font metrics, so `ascender − descender` sums the two extents. **Fallback:** when the metrics aren't available (font not yet loaded, etc.), `targetLineHeight × ~0.66` is a rough eyeball only — it freezes `1 / content-area` at a typical ~1.5 em and will mis-correct compact or extra-tall faces; prefer the measured conversion. After changing `lineHeight`, re-set the block's string to itself to force a reshape (CE.SDK caches text layout until the string changes). **⚠ Re-setting the string wipes every per-character style range** — colour, weight, style, size, typeface, case, decoration and kerning applied via `setTextColor(id, …, start, end)` and its siblings all silently revert to the block's base style. So the order is **line-height → reshape → replay every style range**; capture them first with `getTextRuns(id)` (not `getTextColors(id)[0]`, which reads run 0 only and flattens the block when re-applied), and never reshape a multi-colour headline without replaying its ranges afterward, or the accent vanishes with no error. Full rule: §6.1.9. The rubric targets below are **unchanged** — the judge skill scores the _rendered_ visual gap (~0.15–0.25× cap height for all-caps, §6.1.6), never the raw engine number.\n>\n> **⚠ An explicit line-height from the user's brief is a raw visual target — it is NOT a rubric violation until you have applied the content-area conversion and checked the rendered gap.** A value from the user's brief expresses the _same_ visual-multiplier space as the targets in this section, so it needs the content-area conversion (divide by the font's content area, §6.1.3) before it means anything to the engine, and the \"prompt value clamped to the rubric\" carve-out (\"Defaults fill silence\" above) only fires on a **real** violation — which, per this section, is judged by the **rendered visual gap**, not the raw number. Concretely: a prompt asking for an all-caps line-height of **1.15** is not \"too loose for the 0.9–1.0 all-caps band\" — divided by the font's content area (~1.5 for a typical display face) it becomes an engine value of ~0.77 that renders as a correctly tight all-caps line. **Never** compare the prompt's pre-conversion number against a rubric range in raw-number space and clamp on the mismatch; convert it (divide by content area), render it, and only override if the _gap you see_ violates §6.1.6. When the prompt gives an explicit line-height, the default is to **use it** (the prompt author is naming the visual target, not the engine value) — the rubric overrides only a rendered-gap violation, never a raw-number one.\n\n- **Web (unitless multipliers):**\n - Body **1.4–1.6** (default **1.5**); long-form reading up to **1.65**.\n - Headlines **1.1–1.25** (default **1.1**); large display **≤1.1** (default **1.1**).\n - **All-caps display / headlines** take a **tighter** multiplier than mixed-case — **0.9–1.0** for multi-line — because caps fill only the cap-height band (~70% of the em) and use no descender space; a value that looks tight for mixed-case leaves a descender-sized void between all-caps lines. Judge by the **visual gap** (target ~0.15–0.25× cap height), not the number.\n - **WCAG:** body line-height ≥ **1.5**; paragraph spacing ≥ **2×** the font size.\n- **Print (leading as a unitless multiplier of point size):**\n - Body **1.2–1.45** (default **1.2**). Push toward the low end for dense or large-x-height faces, toward the high end for airy or small type.\n - Headlines **1.0–1.2** (default **1.05**); tight display setting may go slightly negative (**0.95–1.0**).\n - **All-caps titles: 0.9–1.0** (tighter than mixed-case display's 1.0–1.2) — same cap-height reason.\n- **Localized / non-Latin copy — the per-script rules live in the `localize` skill.** Per-script leading bands and diacritic rules — the capital-diacritic all-caps loosening, the marked-capital mixed-case nudge, the localized-display default, and the CJK / Arabic-Naskh / Vietnamese bands — live in the `localize` skill's `reference/` family files (`latin-expansion.md`, `arabic.md`, `cjk.md`, `vietnamese.md`, `cyrillic.md`). All values there are **visual multipliers** — apply this section's content-area conversion like every value here (§6.6).\n- **Tune leading to measure** — longer measure needs more leading; short measure needs less. Never set leading in isolation from line length (§6.1.4).\n- **Consistency** — every body block in one design shares the same leading; every same-band heading shares the same leading.\n- **Pass:** **every text block carries an explicit line-height (incl. single-line & all-caps labels)**; body line-height **1.4–1.6** (web) / **1.2–1.45** (print); headline leading tighter than body; **all-caps titles tighter still (0.9–1.0, web & print), no descender-void between lines**; leading uniform across same-band text; **localized / non-Latin leading set per the `localize` skill's family files**; WCAG body ≥ 1.5 (web).\n\n#### 6.1.4 Measure (line length)\n\n- Set body **measure to 45–75 characters** (~66 ideal for a single column; **40–50** per column in multi-column layouts). Too-long lines lose the return sweep; too-short lines fracture rhythm.\n- On wide canvases, constrain body width — don't let body text run the full canvas width.\n- **Pass:** body measure 45–75 chars (40–50 multi-column); no full-canvas-width body lines.\n\n#### 6.1.5 Alignment, rag, justification\n\n- Default body alignment: **left** (LTR) / **right** (RTL). Avoid centered or justified _running_ text.\n- Justify only with **hyphenation on** and rivers controlled (print); **never justify short measure**.\n- Keep a **soft rag** — no ladders (repeated hyphens/word-shapes down the edge), no line more than ~50% shorter than its neighbors.\n- **Set alignment and a growth anchor explicitly — build to survive a text-length change.** A block that _looks_ centred only because its current string happens to be that width is **not** centred: encode the intent. Give every text block an **explicit horizontal alignment** (`text/horizontalAlignment`), and set its width mode so it **grows from the correct edge** when the string changes length — a label centred under a number stays `Center`; a value aligned to a right margin is right-anchored; a column of labels shares one alignment. This is what makes a design **localizable**: when the German string is 30% longer it must grow symmetrically (or from the anchored edge), not drift right off a left-anchored Auto frame. A source that encodes position instead of intent forces the localizer to re-infer alignment from the render and get it wrong (the \"labels drifted right / SEAT not aligned with BLOCK\" defect originates **in the source**, not the localization). Applies equally to chips (§6.5.1: the field grows with the label).\n- **Pass:** body not centered/justified without cause; RTL layouts mirrored (ties to the RTL axis); rag is soft, no ladders; **every text block carries an explicit alignment and grows from the intended edge on a length change (localization-safe), not an incidental centering that breaks when the copy changes.**\n\n#### 6.1.6 Tracking / letter-spacing & case\n\n- **Don't letter-space lowercase body text.** Tighten large display slightly (**−1% to −3%**).\n- **Loosen all-caps and small-caps — always, and to a defined default.** Never leave all-caps at 0 tracking. **Default +10% (0.1em)**; acceptable band **+5% to +25% (0.05–0.25em)**, scaled by size and length — tighter (~+8%) for larger/longer strings, looser (up to +25%) for short airy display labels and wide-set wordmarks. On **web**, never below the WCAG floor of **0.12em** — so a web all-caps label defaults to **0.12em**, not 0.1em. This default applies even to one-line labels and even when the prompt is silent on tracking (per \"Defaults fill silence\" above).\n- Avoid long strings of **all-caps** — reserve caps for short labels; they slow reading in body copy.\n- **Setting all-caps titles** — caps have no ascender/descender extension, so set them **optically**: pull line-height below the mixed-case display range (see §6.1.3), space to **cap height** rather than the em box, and prefer real small-caps to shrunk-and-tracked caps where the family offers them. Keep all-caps to a line or two of display — never a paragraph.\n- Use **real weights and real italics**, never faux-bold or faux-oblique when the family provides the true cut.\n- **Pass:** body untracked; all-caps loosened to the defined default (**+10%; web ≥0.12em**, band +5–25%) and short, **with line-height tightened per §6.1.3 (no inter-line void)**; no faux styling where a real weight/italic exists.\n\n#### 6.1.7 Micro-typography\n\n- Use **smart punctuation**: curly quotes (\" \" ' '), en dash (–) and em dash (—) correctly, real ellipsis (…). No straight quotes, no `--` for a dash.\n- **No double spaces.** Use **non-breaking spaces** to prevent bad breaks (number + unit, \"Fig. 4\", brand names).\n- **No widows or orphans**; no single-word last line; no hyphen on a paragraph's last line.\n- **No missing glyphs / tofu (□)** and **no clipped** ascenders/descenders — the direct expansion of Axis 3's \"no tofu.\" Verify the chosen font actually covers every character in the copy (critical for localized text).\n- **Pass:** smart punctuation throughout; zero tofu and zero clipping; no widows/orphans in headings or short blocks.\n\n#### 6.1.8 Lists & paragraph structure\n\n**Both rules here are construction rules, and construction is invisible in a PNG** — a hand-built list and a native one render almost identically. They are verified by **reading the scene graph**, like grouping (§6.3), chips (§6.5.1) and curved type (§6.5.4).\n\n- **A multi-line list item hangs — wrapped lines align to the text, not under the marker.** When a bulleted / numbered item wraps, the continuation line must indent to the **text start** (a hanging indent), never fall back under the bullet or number. Text wrapping under its own marker is the most common list defect and reads as broken structure.\n- **One text block holds the whole list — one paragraph per item.** Set the marker with the engine's list feature (`setTextListStyle`, `setTextListLevel`). There are three hand-built fakes and all three are wrong: **(1)** a marker typed into the string (`\"• \"`) — no hanging indent; **(2)** a lone marker glyph block beside a left-aligned text frame — the marker is unbound and drifts off its text on any copy, font or locale change; **(3)** one text block per item — there is no list at all, just N loose ungrouped blocks that also fail §6.3. Only the native feature keeps the marker, the gap and the hanging indent bound to the item.\n- **Consistent marker, spacing, and alignment** across every item in a list; nested levels step the indent by one unit (`setTextListLevel`; `listIndentPerLevel` sets the step).\n- **Multi-paragraph copy is ONE text block with paragraph spacing** — `text/paragraphSpacing`, plus per-paragraph alignment and leading (`setTextHorizontalAlignment` / `setTextLineHeight` take a paragraph index; pass `-1` when **reading** alignment back, or a block whose alignment was set block-level reads as `undefined` and looks unset). ⚠ `text/paragraphSpacing` is an **em multiple of the font size, not pixels** — **0.4–0.8** is the usable band, and a pixel-shaped value silently runs the copy off the page with no error (measured: `9` on 17px body produced ~150px gaps and a 2362px content bottom on a 1123px page). Not blank lines: an empty line is a full line box, so it scales with the font size instead of the spacing ladder (§6.4) and can't be tuned independently. And not N stacked blocks: those don't reflow together, drift apart on any length change, and arrive ungrouped.\n- **Pass:** multi-line items use a hanging indent (wrap aligns to the text, not the marker); every list is the native list feature on a single block, one paragraph per item — no typed markers, no lone marker blocks, no block-per-item; marker style, gap, and indent uniform per list; multi-paragraph copy is one block with real paragraph spacing rather than blank lines or stacked blocks.\n\n#### 6.1.9 Rich text — inline style ranges\n\nEmphasis **inside** a line — an accent-coloured word, a bold lead-in, an inline price, a struck-through old price, a superscript-ish unit — is a **style range on one text block**, never a second text block placed beside the first. Like §6.1.8, this is a construction rule: the two builds render near-identically and are told apart in the block tree.\n\n- **A range is the unit of emphasis.** Every character setter takes an optional `(from, to)`: `setTextColor`, `setTextFontWeight`, `setTextFontStyle`, `setTypeface`, `setTextFontSize`, `setTextCase`, `setTextDecoration`, `setTextKerning`. Read them back with `getTextRuns`.\n- **Splitting a headline into blocks to colour one word is the anti-pattern.** Nothing binds the pieces: the gap between them is hand-set, so it re-breaks on any copy, font or locale change; the phrase stops being one string (unsearchable, and the localizer receives fragments instead of a sentence); and it ships as loose siblings that fail grouping (§6.3). The tell in the scene graph is two or more text blocks sharing a baseline and a face, differing only in colour or weight.\n- **All-caps is `setTextCase('Uppercase')`, not capitals typed into the string.** The property re-cases at render time, so the string stays real words — translatable, searchable, and correct in scripts that have no case at all (where typed capitals are simply wrong and unrecoverable). Applies to whole blocks and ranges alike; tracking still follows §6.1.6.\n- **Restraint.** One accent per headline, drawn from the single accent colour (§6.2) — a second colour inside a line reads as a mistake, not emphasis. Don't stack emphasis (bold **and** colour **and** underline on the same span). Never fake a weight or an italic with a range when the family has the real cut (§6.1.6).\n- **Underline is not general emphasis** — reserve it for links and annotations, and keep `skipInk` on so descenders stay legible; prefer weight or colour for emphasis in display type. (Skip-ink only _shows_ at a small `underlineOffset`: push the rule far enough below the baseline and it clears the descenders anyway, so the setting is neither visible nor verifiable in the render. Judge it at the default offset.) Strikethrough is for superseded content (an old price), not decoration.\n- **Ranges do not survive a string write.** Any write to `text/text` — including the same-string reshape that a font/size/line-height change requires — wipes every range. (`setTextFontSize` on its own does **not**; only the string write does.) Capture with `getTextRuns`, write, then replay. `getTextColors(id)[0]` is run 0 only; re-applying it whole-block is itself the flattening bug. Offsets are indices into the string, so they replay verbatim after a **resize** but never after a **translation** (see the `localize` skill).\n- **Replay every run, not just the emphasised ones.** The wipe collapses the whole string to **run 0's** formatting, not to a neutral base. If run 0 was a bold lead-in, replaying only the accent span leaves the rest of the paragraph bold — and the spot-check that would catch it is the one nobody runs, because reading the _accent_ range back shows exactly what was asked for; it is the **unemphasised** text that changed. Either replay all captured runs, or reset the base style across `0..length` before re-applying the emphasis.\n- **Pass:** every inline emphasis is a range on a single text block — verified in the block tree, not the render; no sibling text blocks that differ only in colour/weight on a shared baseline; all-caps carried as `textCase` rather than typed capitals; at most one accent per headline, using the design's single accent colour; no faux weight/italic; underline reserved for links/annotations; and any variant (resized, re-branded, localized) still carries its ranges.\n\n#### 6.1.10 Print-specific rules\n\n- Work in **points/picas** and set text to a **baseline grid** so leading stays consistent across columns and pages.\n- Honor the print minimum sizes (§6.1.2); target **≥300dpi**; **embed or outline** all fonts; keep text out of bleed and inside the safe margin (**~8%**, ties to Composition/Axis 5).\n- **Pass:** baseline-grid aligned; fonts embedded/outlined; sizes ≥ print minimums; text inside the safe area, clear of bleed.\n\n#### 6.1.11 Typography pass checklist\n\nExpands **Axis 3 (Typography) — must score ≥ 8.** Each line is a yes/no the judge skill runs against the rendered output, **except the lines marked _scene graph_ — those are read from the block tree, because the defect they catch is invisible in a render.** Any \"no\" on an applicable line drops Axis 3 below 8.\n\n**Both media**\n\n- [ ] ≤3 font families, ≤4 weights, pairing by contrast/superfamily (§6.1.1)\n- [ ] Every family has a defined fallback / is embedded-outlined (§6.1.1)\n- [ ] All sizes come from one modular scale; bands ≥1 step apart (§6.1.2)\n- [ ] Line-height set explicitly on every text block, incl. single-line & all-caps labels (§6.1.3)\n- [ ] Headline leading tighter than body; leading uniform across same-band text (§6.1.3)\n- [ ] All-caps titles set by cap-height — line-height tightened, no descender-void between lines (§6.1.3, §6.1.6)\n- [ ] Localized / non-Latin text: leading bands + per-language conventions pass the `localize` skill's family files & checklist (§6.1.3 pointer, §6.6)\n- [ ] Body measure 45–75 chars (40–50 multi-column) (§6.1.4)\n- [ ] Body not centered/justified without cause; rag soft, no ladders (§6.1.5)\n- [ ] Every text block has explicit alignment + grows from the intended edge on a length change (localization-safe), not incidental centering (§6.1.5)\n- [ ] Multi-line list items hang (wrap aligns to text, not the marker); marker/gap/indent uniform (§6.1.8)\n- [ ] _(scene graph)_ Every list is the native list feature on ONE block, one paragraph per item — no typed \"• \", no lone marker blocks, no block-per-item (§6.1.8)\n- [ ] _(scene graph)_ Multi-paragraph copy is one block with `text/paragraphSpacing` — not blank lines, not stacked blocks (§6.1.8)\n- [ ] _(scene graph)_ Inline emphasis is a style range on one block — no sibling blocks differing only in colour/weight on a shared baseline (§6.1.9)\n- [ ] _(scene graph)_ All-caps carried as `textCase`, not capitals typed into the string (§6.1.9, §6.1.6)\n- [ ] ≤1 accent per headline, from the single accent colour; no stacked emphasis; underline only for links/annotations (§6.1.9)\n- [ ] Body untracked; all-caps loosened to default (+10%; web ≥0.12em, band +5–25%) and short; no faux bold/italic (§6.1.6)\n- [ ] Smart punctuation; no double spaces; non-breaking spaces where needed (§6.1.7)\n- [ ] No widows/orphans; zero tofu; no clipped ascenders/descenders (§6.1.7)\n\n**Web**\n\n- [ ] Body ≥16px, caption ≥12px, never <11px (§6.1.2)\n- [ ] Body line-height 1.4–1.6; WCAG body ≥1.5, paragraph spacing ≥2× size (§6.1.3)\n- [ ] All-caps display line-height 0.9–1.0 (tighter than mixed-case display) (§6.1.3)\n\n**Print**\n\n- [ ] Body 9–12pt, caption ≥7pt, never <5pt (§6.1.2)\n- [ ] Body leading 1.2–1.45; headlines 1.0–1.2; all-caps titles 0.9–1.0 (§6.1.3)\n- [ ] Baseline-grid aligned; fonts embedded/outlined; ≥300dpi; text inside ~8% safe margin (§6.1.10)\n\n### 6.2 Color\n\nExpands **Axis 4 — Color** (palette respected, exactly one consistent accent, strong contrast everywhere, esp. text on photos/dark backgrounds).\n\n#### Color hierarchy (text on dark backgrounds)\n\n| Role | RGB |\n| --------------------------- | ------------------ |\n| Primary text (headline) | (1.0, 1.0, 1.0) |\n| Accent text (subtitle) | brand color |\n| Secondary text (tagline) | (0.75, 0.75, 0.80) |\n| Tertiary text (description) | (0.5, 0.5, 0.55) |\n\n**Pass:** ≤ 3 colors + neutrals; exactly one consistent accent; all text meets contrast on its actual background (fill, photo, or field — not the page).\n\n### 6.3 Hierarchy\n\nExpands **Axis 2 — Hierarchy**: one element dominates, the reading order is unambiguous, and the eye lands where it should first.\n\n- **One primary element.** Exactly one thing is the hero — the largest, heaviest, highest-contrast element on the page. Everything else is visibly subordinate. Two elements competing at the same visual weight is the most common hierarchy failure: neither wins and the eye stalls.\n- **Rank with the hierarchy chain — `size > weight > color > spacing > position`.** Establish rank primarily by **size**, then **weight**, then **color/contrast**, then the **space around** an element, and only last by position. Don't lean on position alone — a block isn't dominant just because it sits at the top; size/weight/contrast must carry it.\n- **Reading order is deliberate.** The scale steps map to the intended path: hero → supporting → detail. A reader should never hunt for where to start or what comes next. Keep the levels few — ≈3 (primary / secondary / tertiary); more than ~4 competing sizes reads as noise.\n- **Group related, separate unrelated (proximity).** Tight spacing binds a set (eyebrow + headline, label + value); wider spacing sets groups apart (§6.4's ladder). Proximity — not boxes or rules — is the first grouping tool.\n- **Colour serves rank, not decoration.** The single accent (§6.2) marks the one thing it should pull the eye to; spending it on secondary elements flattens the hierarchy.\n- **Express the structure as a block hierarchy.** Proximity is the visual grouping tool; the **block tree** is its structural counterpart. Every logical cluster (eyebrow + headline; label + value; a detail cell; a CTA bar and its text) must be an actual **group block**, and clusters that nest must nest as **groups-of-groups** — no orphan block that belongs to a cluster left as a loose sibling. A page built as one flat list of ungrouped blocks has no expressed hierarchy even when it looks ranked. (Mechanics: handbook §4 \"Group blocks & hierarchy\".)\n- **Pass:** exactly one dominant element; no two elements competing at the same level; reading order unambiguous (hero → supporting → detail); rank carried by size/weight/colour/spacing, not position alone; ≈3 (≤4) distinct levels; related items grouped tighter than unrelated ones; the accent reinforces the primary; **and the reading structure is expressed as grouped block clusters, nested where they nest — a flat page of ungrouped siblings fails.**\n\n### 6.4 Composition & grid\n\nExpands **Axis 5 — Composition**: proper margins, a shared grid, a consistent spacing scale, balanced whitespace, and nothing off-canvas or overlapping. Composition is **relative to the canvas** — every number below scales with the page, so it holds across formats.\n\n- **One margin line / shared grid.** Left-aligned elements share one X; centered elements are **mathematically centered** (`pageX + (pageW − blockW)/2`); right-aligned share one right edge. Pick an alignment per element and hold it — a block that's \"almost\" on the margin reads as a mistake.\n- **Page margins = 8–12% of the _shortest_ page dimension.** Key the outer margin to the shortest side so it stays proportional on any aspect (≈86–130px on a 1080-wide canvas). Content lives inside this frame; nothing crosses it except a deliberate full-bleed background.\n- **One spacing scale.** Base unit ≈0.5–1% of page height; use multiples — 1× / 2× / 3× / 4× / 6× — never arbitrary gaps. More space above a heading than below it; tighter within a group than between groups. The spacing ladder (proportion of page height):\n\n | Relationship | Spacing |\n | --------------------------- | ------- |\n | Accent / decoration → title | 0.5–1× |\n | Title → subtitle | 1–2× |\n | Subtitle → body | 2–3× |\n | Between body paragraphs | 1.5–2× |\n | Between content groups | 4–6× |\n\n- **Content inside a container is spaced relative to the _container_, not the page.** The margins and ladder above are **page**-relative; a card, panel, circle, or badge sitting on the page is a **sub-canvas** with its own inner frame. Give every container an **inner padding keyed to its _own_ shortest dimension** (≈6–10% of the container's short side — a chart inside a 400px card is inset from the card's edge, not the page's), and apply the spacing ladder **relative to the container** a group lives in. Nested content spaced by page-relative numbers, or by eye, crowds the container edge (\"text/chart doesn't respect the card's padding,\" \"elements too close to the edges\"). Content must never touch a container's inner edge.\n- **Lock up a mark and its wordmark as one unit.** A logo mark + wordmark, an avatar + name, an icon + label is a **lockup**: fixed relative spacing and alignment between the two, grouped, positioned as a unit. Its internal gap is set by the pair (roughly the wordmark's cap-height), not the page ladder — too tight reads as collision (\"logo text too close to the mark,\" \"name crossing the avatar\"), too loose as two unrelated elements.\n- **Balanced whitespace — no lopsided dead void.** Whitespace is intentional and distributed; the content should occupy or balance the whole canvas. A large empty band on one side — a top-clustered layout that letterboxes the bottom of a tall canvas — fails composition even when every element is individually fine. Balance the content group within the frame; don't top-anchor and leave a void.\n- **Nothing off-canvas or overlapping.** Every element sits fully within the page (bar intentional edge-bleed decoration); no unintended overlap, no clipping at the edges.\n- **Background back-most.** The full-bleed background / photo is the first child (behind everything); structural rules, then accents, then text paint on top — build back-to-front.\n- **Pass:** margins 8–12% of the shortest dimension; every element on the shared grid / one alignment; one consistent spacing scale following the ladder; **content inside every container inset by the container's own inner padding (never touching its edge), ladder applied container-relative; mark+wordmark / avatar+name lockups grouped at a fixed intra-pair gap**; whitespace balanced with no lopsided dead void; nothing off-canvas, clipped, or overlapping; background back-most.\n\n#### Background\n\n- Card / poster with theme → use a generated or imported background image; place back-most via `engine.block.insertChild(page, bg, 0)` (see §4 \"Z-order via child order\"). If text contrast suffers, add a semi-transparent overlay.\n- Card without theme → solid color or subtle gradient.\n- Document / form / data → solid color or white.\n\n#### Decorative elements\n\n- Low opacity (15 – 30 %) for background decoration.\n- Echo the existing color system — never introduce new colors for decoration alone.\n- Less is more — one accent bar > three.\n- **Place decoration with an internal geometric relationship parametrically, not by transcribed coordinates.** A ring of stars around a circle, evenly-stepped dashes, dots on an arc, elements mirrored about an axis — anything whose _parts relate to each other_ — is generated from the relationship (`cx + r·cos θ`, a fixed angular/linear step, a reflection), **not** placed as N loose blocks at hand-computed x/y. Absolute-coordinate decoration is what \"drifts\": any re-composition, re-snap, or localization has to reproduce N independent numbers and gets some wrong, so the _relationship_ visibly breaks (stars land in a straight line instead of on the arc; dashes space unevenly). Build the relationship once; then a resize scales `r` and a localization leaves it untouched. Group the generated set so it moves and mirrors as a unit (§6.3, §6.6).\n\n### 6.5 Craft & finish\n\nExpands **Axis 6 — Craft** (no overflow/overlap/blank text, legible chart labels with correct proportions, intentional crops, clean decorative elements). Most of this axis is still to be written on the §6.1 pattern; the written topics are accent components (§6.5.1) and curved type (§6.5.4).\n\n**Two of this section's rules are construction rules, and construction is invisible in a PNG.** A rect-behind-text chip and a native text background render pixel-identically; so do one curved text block and a row of hand-rotated letters. Both are therefore verified by **reading the scene graph**, exactly as grouping is (§6.3) — see the instrumented checks in the `judge` skill. A render-only pass will score them 10 while they are wrong.\n\n#### 6.5.1 Accent components — pills, badges, buttons, tags\n\nA **chip** — a pill/eyebrow, badge, tag, or button — is a short label sitting on its own filled, rounded field. How it's _built_ is a craft concern: a well-made chip binds the field to the label so they never drift.\n\n- **Build it as a text block with a native text background — not a rectangle behind floating text** — rationale: a separate backing shape forces you to hand-measure the label width and re-center it inside the box, and the two fall out of sync on any copy/font/localization change (label creeps off-center, box mis-fits, re-fit math must be redone per variant). Binding the field to the text keeps them locked and reflows correctly when the label changes. _(CoDesign/CE.SDK: enable `backgroundColor/enabled`, then `backgroundColor/color` + `backgroundColor/padding{Left,Right,Top,Bottom}` + `backgroundColor/cornerRadius` on the text block itself.)_ A separate container block is legitimate **only** for a chip carrying **non-text** content — an icon + text, an image, multiple elements.\n- **Radius matches the chip's intent** — key the corner radius to the field's padded height `h`: **pill / capsule = `h/2`** (true stadium ends — eyebrows, status, filter chips); **badge / tag / button (soft rectangle) = ~0.1–0.25×h** (≈6–12px on a standard control); **`0` = a square tag**. Pick capsule _or_ clearly-soft-rect — never an ambiguous near-capsule that reads as a mistake.\n- **Padding — horizontal roomier than vertical, symmetric per axis** — left = right, top = bottom (unless deliberately asymmetric); horizontal padding **~1.5–2.5× the vertical**; against the label size, horizontal **~0.8–1.5× the font size**, vertical **~0.4–0.7×**. The label must never touch the field edge. Compensate trailing **letter-spacing** on all-caps labels (§6.1.6) — tracking adds space after the last glyph, so trim right padding a hair to keep the label optically centered.\n- **The label is still a label** — it obeys the type rules like any other text: all-caps tracking (§6.1.6), explicit line-height (§6.1.3), and the type-scale minimums (§6.1.2) — a chip never licenses sub-minimum text. Keep it **short (≤3 words)**; a chip is not a text container.\n- **Align by the field edge, not the text.** A chip aligns to the margin line, the grid, and to neighbouring elements (a headline edge, another chip) by its **background field's outer edge** — the padded box — never by its glyph run. The two differ by the padding, so aligning on the text leaves the visible chip off the line by exactly that padding. **The padding expands the field outward from the text frame**, and `getFrameHeight` / `getFrameWidth` report the **unpadded** extent (measured: 17px frame inside a 35px padded field) — so landing a chip's field edge on the margin means positioning the frame at `margin + paddingLeft`, and a true capsule is `cornerRadius = (frameHeight + paddingTop + paddingBottom) / 2`, not `frameHeight / 2`. **Measure the field's real edge** — the outer edge of the padded box (the glyph extent ± its padding), not the label's glyph run alone; and beware that engine glyph metrics can misreport (especially for RTL/Arabic), silently drifting the chip off-margin.\n- **RTL** — the whole chip mirrors to the opposite margin (§6.6), its field edge on that margin.\n- **Color & contrast** — the field uses the design's single accent or a neutral, **never a new color** (§6.2); check the label's contrast **on the fill**, not against the page (§6.2).\n- **Consistency across the design** — all chips share one system: one radius family (all capsules _or_ all the same soft-rect radius — don't mix), one padding scale, one label treatment. One-off chip geometry reads as a defect.\n- **Pass:** every text-only chip is a text block with a native text background (no separate backing rectangle); radius matches intent (pill = h/2; tag/button ~0.1–0.25×h, no ambiguous near-capsule); padding symmetric per axis, horizontal ~1.5–2.5× vertical, label clear of the field edge with trailing tracking compensated; label follows §6.1.2/§6.1.3/§6.1.6 and stays ≤3 words; the chip is aligned to the margin line / grid / neighbouring elements by its **background field edge** (not its text), measured from the field's real rendered edge, and mirrored to the opposite margin in RTL; single-accent (or neutral) fill with the label contrast-checked on the fill; all chips in the design share one radius/padding/label system.\n\n#### 6.5.2 Craft pass checklist\n\nExpands **Axis 6 (Craft) — must score ≥ 8.** Each line is a yes/no the judge skill runs against the rendered output, **except the two lines marked _scene graph_ — those are read from the block tree, because the defect they catch is invisible in a render.** Any \"no\" on an applicable line drops Axis 6 below 8. _(Craft is otherwise still being written; this checklist currently covers §6.5.1 — accent components, §6.5.3 — text fitted to a container, and §6.5.4 — curved type. Construction is medium-agnostic, so there is no Web/Print split.)_\n\n**Both media**\n\n- [ ] _(scene graph)_ Text-only chips (pills/badges/buttons/tags) built as a text block with a native text background — no separate rectangle behind floating text (§6.5.1)\n- [ ] _(scene graph)_ Curved/circular type is ONE text block on a path — not a run of per-letter text blocks rotated into an arc (§6.5.4)\n- [ ] Radius matches intent: pill/capsule = half the padded height; tag/button = small fixed radius (~0.1–0.25×h); no ambiguous near-capsule (§6.5.1)\n- [ ] Padding symmetric per axis, horizontal ~1.5–2.5× vertical, label never touching the field edge; trailing all-caps tracking compensated (§6.5.1, §6.1.6)\n- [ ] Chip label follows label typography — all-caps tracking (§6.1.6), explicit line-height (§6.1.3), ≥ type-scale minimum (§6.1.2) — and stays ≤3 words (§6.5.1)\n- [ ] Chip aligned to margin / grid / neighbouring elements by its background **field edge**, not its text — measured from the field's real rendered edge (§6.5.1, §6.4); whole chip mirrored to the opposite margin in RTL (§6.5.1, §6.6)\n- [ ] Single-accent (or neutral) fill, no new color; label contrast checked on the fill, not the page (§6.5.1, §6.2)\n- [ ] All chips in the design share one radius family, one padding scale, one label treatment (§6.5.1)\n- [ ] Text inside a shape/container fitted within its band to sit fully inside the padded box — no overshoot, no edge-crowding (§6.5.3)\n- [ ] Short labels/numbers in a badge/circle/pill optically centered by cap height, not the frame (§6.5.3)\n- [ ] Image/photo crops: full coverage (no gap in the frame), uniform scale (no stretch), subject inside the window (§6.5.3, resize crop invariants)\n\n#### 6.5.3 Text fitted to a shape or container\n\nA text block and the shape it visually sits in (a circle, pill, card, panel, badge) are two independent blocks with independent sizes. Nothing binds them unless you bind them — so a size picked by eye, or a copy/locale change, breaks the relationship: the type overshoots the circle, or crowds the frame edge.\n\n- **Fit the type to the container — don't set it by eye.** Shrink the block within its **type-scale band** until its **measured** frame fits inside the container's inner box (§6.4 inner padding), with the minimum inset clear on every side. In CoDesign this is a measure-and-shrink loop (`getFrameWidth`/`getFrameHeight` vs the container's padded box, step the font size down; or auto/fit-to-frame sizing where available) — the same shape as `localize`'s overflow guard, generalized to any text-in-container. Never let the glyph run cross the container edge; a pricing number must sit **fully inside** its circle.\n- **Center optically, not geometrically — by cap height, not the em box.** Centering a text block by its **frame** centers the em box, which includes ascender headroom and descender depth the glyphs don't use. For a short all-caps or numeric label — exactly what goes in a badge or circle — the inked area then sits **above** the true center and reads as \"hanging low.\" Center by the **cap-height band**: offset the block down by roughly half the (ascender-gap − descender) so the ink, not the box, is centered (derive the offset from `getFontMetrics`; §6.1.6 sets all-caps optically for the same reason). Check the render — optical centering is judged by the visible gap above vs below the glyphs.\n- **Pass:** text inside a shape/container is fitted within its band to sit fully inside the container's padded box (no overshoot, no edge-crowding); short labels/numbers in a badge/circle/pill are **optically** centered by cap height (inked area centered, not the frame), verified in the render.\n\n#### 6.5.4 Curved type — text on a path\n\nCircular or arced type — \"EST. 2026\" around a seal, a badge arc, a ribbon, a rosette, type following a curve — is a **native text feature**, not a layout to assemble by hand. Like §6.5.1, this is a construction rule: the two builds can look nearly identical in a render and are told apart by reading the block tree.\n\n- **One text block on a path — never one block per letter.** Set the baseline on the text block itself and let the engine lay the glyphs along it. Hand-placing a text block per character and rotating each into an arc is the anti-pattern: there is no real baseline, so letter spacing is uneven and optically wrong at the arc's ends; the \"text\" is no longer text (uneditable, unsearchable, untranslatable); it re-breaks completely on any copy, font, or locale change; and it ships as N loose blocks that also fail hierarchy's grouping rule (§6.3). _(CoDesign/CE.SDK: `setTextOnPath(id, svgPath)` with `setTextOnPathOffset` for the start position along the curve and `setTextOnPathFlipped` for the underside; `setTextOnPath(id, null)` clears it.)_\n- **The path is a single contour.** Exactly one subpath — one leading `M`, no second one — or the call throws (`BLOCK.TEXT_ON_PATH_MULTIPLE_SUBPATHS`); the string must also be parseable SVG (`BLOCK.TEXT_ON_PATH_INVALID_SVG_PATH`). Text around a full circle is one arc contour, not two half-circles: two halves are two blocks, which is the anti-pattern again with extra steps.\n- **Setting a path resizes the block — but the reported box is not the ink box.** Set the path **before** positioning, and do **not** trust the re-read for layout: a 130 × 130 authored path reads back **84 × 84** on `getWidth` / `getHeight` / `getFrameWidth` / `getFrameHeight` alike, while the glyph ring renders at the authored diameter plus glyph height (previewing the block on its own clips its text on all four sides — direct proof the box under-reports). Derive margin and collision math from the **authored path geometry**; positioning from the re-read box puts curved type roughly 23px per side outside where you intended, which is how a seal crosses a safe margin that the numbers say it clears. Consequences for the sibling skills: `localize` snaps geometry back to a reference, and `resize` re-derives it — both must carry **the path**, not the post-path box, or curved type drifts or flattens on every variant.\n- **Legibility still applies.** Curved type is a display device: keep it short, keep the arc radius large enough that the baseline rotation between adjacent glyphs stays small (tight radii on long strings fan the letters and read as broken), and obey the type-scale minimum (§6.1.2) and all-caps tracking (§6.1.6) as for any label. On the underside of a circle, use the flipped baseline rather than upside-down glyphs.\n- **Pass:** every curved/circular text is a **single** text block with a path baseline (verified in the block tree, not the render); the path is one contour; the block was positioned after the path was set; the string is short with an arc radius that keeps adjacent-glyph rotation small; label typography (§6.1.2, §6.1.6) holds; and any localized or resized edition still carries the path.\n\n### 6.6 Localization & RTL\n\nExpands the localization axis. The base typographic couplings live above: font coverage and no-tofu (§6.1.7), mirrored alignment (§6.1.5), and the content-area line-height conversion (§6.1.3). Everything language-specific — per-script leading bands and diacritic rules (the `localize` skill's `reference/` family files: `latin-expansion.md`, `arabic.md`, `cjk.md`, `vietnamese.md`, `cyrillic.md`), the snap-to-reference workflow, per-language conventions, RTL mirroring, and non-Latin font loading — lives in the `localize` skill.\n\n- **RTL mirroring is selective and operates on groups — keep a do-not-mirror inventory.** Mirroring flips the **reading order** and directional decoration; it is **not** a blanket flip of every block. **Never mirror:** icons, logos, brand/glyph marks, numerals and number strings, charts, photographs, and any pictogram whose handedness carries meaning. **Mirror on the group, not its parts:** a composed icon, a lockup, or a badge moves as one unit — flip the group's position and leave its internal layout intact (or exempt it). Loose sibling parts flipped per-block disassemble the mark (the \"mail icon broke on RTL,\" \"elements moved right / off-center in frames\" defect). Content inside a frame is re-anchored with its frame, never flipped independently. Full inventory + mechanics: `localize` → `reference/arabic.md`.\n\n### 6.7 Font discovery & pairing (CoDesign)\n\n#### Discovering fonts — `ly.img.gfonts`\n\nAll Google Font families (~2,000, self-hosted on the IMG.LY CDN) are registered as the `ly.img.gfonts` asset source. Never hardcode font URLs and never fetch font CSS or manifests yourself — look the typeface up **inside `edit` code** and pass it straight to `setFont`:\n\n```js\nconst FAMILY = 'Playfair Display';\nconst { assets } = await engine.asset.findAssets('ly.img.gfonts', {\n query: FAMILY,\n page: 0,\n perPage: 20\n});\nconst tf = assets\n .map((a) => a?.payload?.typeface)\n .find((t) => t?.name === FAMILY);\nif (!tf)\n throw new Error(\n `font lookup missed: no exact match for \"${FAMILY}\" among ` +\n assets.map((a) => a?.payload?.typeface?.name).join(', ')\n );\nengine.block.setFont(title, tf.fonts[0].uri, tf); // declares the typeface\nengine.block.setTextFontWeight(title, 'normal'); // REQUIRED — see below\n```\n\n- **Select the exact name out of a PAGE of results — never take `assets[0]`.** `query` is fuzzy and ranks by its own score, not by exactness: `query: 'Lora'` returns `Explora`, `Grandiflora One`, `Lora` **in that order**, so `perPage: 1` fetches Explora and the family you asked for is unreachable. Fetching ~20 and picking by `name` is the only reliable lookup. Report the candidates in the throw so the failure teaches.\n- **Always follow `setFont` with `setTextFontWeight`.** `tf.fonts[0]` is the family's **lightest declared weight**, not its regular one — for Inter and Roboto that is Thin (`wght=100`). See \"Weights & italics\" below.\n- One lookup per family per edit; reuse `tf` for every block using that family.\n- `forceLoadResources` rules are unchanged: batch your `setFont` calls, then `await engine.block.forceLoadResources([page])` before measuring or capturing.\n- `asset_search({ sourceId: 'ly.img.gfonts', query })` shows what exists — each hit carries `typeface: { name, weights, styles }`. Use it to check availability or browse; apply via the edit-code lookup above.\n\n#### Weights & italics\n\nMost families are variable fonts: `tf.fonts[]` declares one entry per weight step (several pointing at the same file) and the engine interpolates when you select one:\n\n```js\nengine.block.setFont(title, tf.fonts[0].uri, tf); // declare the full typeface\nengine.block.setTextFontWeight(title, 'bold'); // then select a declared weight\n```\n\n**`tf.fonts[]` is ordered lightest-first, so `setFont` alone renders the family's LIGHTEST weight.** This is the single most common way to ship a broken design, because nothing announces it: no error, no warning, no tofu — just body copy in a hairline weight that reads as a deliberate aesthetic until someone tries to read it.\n\n- Inter and Roboto declare 9 weights each: `fonts[0]` is `thin` (`wght=100`).\n- Playfair Display declares no weight below 400, so its `fonts[0]` is `normal` — which is why a recipe demonstrated on Playfair looks fine and the same recipe silently fails on Inter.\n- **Set the weight explicitly on every text block**, including body copy: `setTextFontWeight(id, 'normal')`. Only treat a weight as available if it is present in `tf.fonts[]` (the `weights` list in `asset_search`).\n\nSelecting a weight on a hand-built single-entry typeface changes nothing — declare every weight you plan to use.\n\n#### Local / brand fonts\n\nA font that exists as a file on the user's machine (brand kit, purchased face) must be **imported first**: `asset_add({ source: { path } })` returns a `workspace://` URI — use that as `setFont`'s uri and in `typeface.fonts[].uri`. Never reference a local path or `file://` URI in a scene: the server renders it fine (previews look green), but the browser editor cannot load `file://` resources and the design breaks on every other machine. This is enforced — an `edit` whose scene references a `file://` URI fails to commit and lists the offending URIs. Google families never need this — they come from `ly.img.gfonts`.\n\n#### Context → pairing\n\n| Context | Style | Pairing |\n| ------------------- | ----------------------------- | ---------------------------------------------- |\n| Wedding invitation | Elegant serif + script accent | Playfair Display + Great Vibes + Source Sans 3 |\n| Restaurant menu | Serif heading + sans body | Cormorant Garamond + Inter |\n| Tech / startup | Clean modern sans | Inter (single family, weight variation) |\n| News / editorial | Traditional, authoritative | EB Garamond + Source Sans 3 |\n| Luxury brand | High-contrast serif | Cormorant Garamond + Montserrat |\n| Children's brand | Rounded, playful | Caveat + Open Sans |\n| E-commerce | Readable, trustworthy | Montserrat + Open Sans |\n| Portfolio / agency | Bold, creative | Playfair Display + Inter |\n| Academic / research | Classic, formal | EB Garamond + Source Sans 3 |\n\nEvery family above resolves via the `ly.img.gfonts` lookup. For contexts not listed: apply the contrast principle (serif heading + sans body, or a single family with weight variation). Never use more than 3 families.\n",
|
|
594
594
|
"docs/handbook/intake.md": "# Intake — derive what you can, ask for the rest, invent nothing\n\nEvery skill that takes input follows this. `create` is the worked example (its\nper-class parameter tables live in `create/classes.md`); `brand`, `resize` and\n`localize` each carry their own table. The one rule underneath all four steps:\n\n> **Derive every parameter you can. Ask only what is missing. Never invent a\n> value that belongs to the user.**\n\n## The four steps\n\n**1. Derive.** Fill your skill's parameter table from everything already\navailable — the prompt, earlier conversation, attached files or images, the\ncurrent design itself, and **whatever a calling skill handed you**. A parameter\ncounts as answered if it is stated outright or safely inferable. Track each\nvalue's source: `stated`, `inferred`, or `default`.\n\n**2. Ask — once.** Put every still-unresolved **R** and **A** parameter to the\nuser in a **single round**, phrased as the table's canned question with its chips.\n**Ask through your own environment's question UI whenever it has one** — a\nstructured question tool, an elicitation API, a form, any chip-style picker. You\nknow your host better than this server does, and its native surface is the best\nexperience your user can get: options become chips, \"Other\" stays free. Only when\nyour environment offers nothing at all, fall back to one compact markdown list of\njust the missing questions.\n\n**Every question carries options** — three to five concrete choices, plus\n`Decide automatically`, plus Other. A bare open question is not an intake\nquestion. The one exception is the topic/content **R** parameter, which is free\ntext.\n\nNever ask a second round. If an answer is still vague, take the default and say\nso in the echo. **D** parameters are never worth a question on their own.\nShowing work and letting the user pick — 2–3 style frames previewed, then \"which\nof these?\" — is **not** a second round: that rule governs parameter rounds only.\n\nWord every question and chip by `create/choice-copy.md`.\n\n**3. Echo.** State the resolved inputs in one to three lines, tagging what was\ninferred or defaulted — \"acme restyle, paper scheme (defaulted), 1 design\" — so a\nwrong derivation is correctable at a glance. Don't block on confirmation: state it\nand proceed.\n\n**4. Never invent someone else's facts.** Where a parameter's value belongs to\nthe user or a third party — a brand's colours, a font a brand licenses, a locale's\nwording, the contents of a file — a missing value is an **ask**. Never a guess,\nand **never a silent stop** either: \"the kit is incomplete, so I stopped\" leaves\nthe user with nothing. Name what is missing and ask for that one thing.\n\n## When you must ask — the threshold, not a feeling\n\n\"The prompt was vague\" is a self-assessment, and a model with work to do resolves\nit toward working. So the trigger is countable instead. Five parameters are\n**design-defining** — the ones whose value the user sees the moment they look at\nthe result:\n\n> **topic · audience · visual direction · brand / palette · format & placement**\n\n- **Two or more of the five neither stated nor safely inferable → you ask, before\n the first `edit`.** Not \"consider asking\". One or none → derive, echo, build.\n- **Visual direction and brand are never silently defaulted on the first build of\n a new design.** These two are what the user notices first, and their documented\n defaults are exactly what absorbs a skipped intake — a design lands in a style\n nobody chose and nothing in the transcript shows a choice was made. Either the\n request (or a supplied kit, reference image or prior design) implies the\n direction, or you offer it as a question with `Decide automatically` on it.\n- Everything already derived stays derived. **A fully specified request still gets\n zero questions** — the point is never to ask more, only to stop inventing.\n\n## Kind key\n\nEvery parameter table classifies each parameter:\n\n| Kind | Meaning |\n| ----- | ----------------------------------------------------------------------------------- |\n| **R** | Required, no default. Must be stated or asked — the work cannot start without it. |\n| **A** | Ask if underived. Has a default, but is worth one chip row when nothing implies it. |\n| **D** | Defaultable. Never worth a question on its own; state it in the echo. |\n\n`derived` marks a parameter that is never asked because it always comes from\ncontext — \"the latest revision of the current design\" is the usual one.\n\n## Chips may be data-driven\n\n`create`'s chip sets are fixed, so its tables list them literally. Others are\ndiscovered at runtime: the brand kits available come from the workspace, and a\nkit's colour schemes come from its own `tokens.json`. Such a table names the\n**source** of its chips rather than the chips themselves.\n\nNothing may hardcode a brand's schemes, fonts or colours. If the chips have to be\nread from the user's data, read them.\n\n## A handoff is derived input, not a fresh start\n\nWhen another skill routes to you — `onboard` picking a job, `create` handing over\na brief with a brand kit already in play — everything it carried is `stated`\ninput. Re-asking it is the failure mode that makes this whole protocol feel worse\nthan guessing: the user answers the same question twice and concludes the tools\ndon't talk to each other. Read what you were given before you ask anything.\n\n## `judge` does not ask\n\n`judge` is step 5 of the Loop — the mandatory gate on every build. A question\nthere would interrupt every design this server makes, so its axis set and\nthreshold are **D**, overridden by the caller and never asked. This is deliberate:\n\"every skill asks\" does not apply to the gate.\n",
|
|
595
595
|
"docs/handbook/quirks.md": "# Handbook quirks — cryptic errors, runtime symptoms, diagnosis order\n\nThe handbook's quirk reference. CE.SDK errors are short and opaque. Two tables — error-message → cause, and runtime-symptom → workaround. Check both before bisecting; search this file with `query` using a fragment of the error message.\n\n## Cryptic errors\n\n| Error | Cause | Fix |\n| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `Cannot read properties of undefined (reading 'name')` | `setFont` called without the `typeface` object (3rd arg). | Pass `setFont(id, uri, { name, fonts: [{ uri, subFamily, weight, style }] })`. |\n| `The block doesn't have a background color.` | `setBackgroundColor` was called on a `page` (or other block kind that lacks the prop). | Pages don't accept `setBackgroundColor`. Use a full-bleed `graphic` block with a color fill instead. |\n| Text block exists with correct geometry but **glyphs don't draw** | The font resource never loaded: hand-built/hardcoded font URI, or a typeface whose `fonts[]` lacks the selected weight/style. | Look the typeface up from `ly.img.gfonts` inside `edit` (design-rules.md §6.7) instead of hardcoding URIs, then `await forceLoadResources` before capture. |\n| `Couldn't find property \"<name>\" on block.` | Property doesn't exist on this block type, or you guessed the property name. | Read `cesdk-guide/api/BlockAPI.md` for the exact property name and which block types accept it. |\n| `Invalid color reference …` | A color/fill value was passed without first calling `createFill`/`setColor`. | Always `createFill('color')` → `setColor(fill, 'fill/color/value', {r,g,b,a})` → `setFill(block, fill)`. |\n| `Setting the \"text/fontFileUri\" property directly is unsupported.` | Tried to bypass `setFont` via `setString(id, \"text/fontFileUri\", uri)`. | Always go through `setFont(id, uri, typeface)`. There is no shortcut. |\n\nWhen a new error type shows up, isolate it with **one** small `edit` (a single block, the failing call), not a series of trial-and-error rebuilds. The `cesdk-guide/api/BlockAPI.md` reference is the markdown explainer; for the authoritative TypeScript signature, read `cesdk-api/index.d.ts`.\n\n## Runtime quirks\n\nThese are **runtime semantics that don't show up in the .d.ts**. Check this list before re-bisecting.\n\n| Symptom | What's happening | Workaround |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `setFont(id, newUri, …)` doesn't change the rendered font on an existing block. | Engine treats two typeface objects with the same `name` as identical and skips the swap. | Use a unique `name` per swap (e.g. `\"Playfair Display v2\"`), OR delete and recreate that single block with the new font. |\n| Text doesn't reflow after `setFont` / `setTextFontSize`. Old glyph layout sticks. | The text shape is cached and only invalidated when the string content changes. | After the font/size change, force a re-shape: `engine.block.setString(id, \"text/text\", engine.block.getString(id, \"text/text\"))`. ⚠ The re-shape **wipes every per-character style range** (colour, weight, style, size, typeface, case, decoration, kerning) — capture with `getTextRuns(id)` first and replay the ranges after. `getTextColors(id)[0]` is run 0 only; re-applying it whole-block flattens a multi-colour headline. |\n| Text block exists with the right font, string, size, and position — but glyphs don't draw. | Block height is too small for the font's ascender + descender extent. The engine silently drops the render rather than overflowing or clipping. | Set height ≥ `fontSize × 1.6` for sans-serif body, `≥ 1.8` (better 2.0) for display serifs (Playfair, Cormorant) and scripts (Great Vibes, Caveat). Or use Auto + getFrameWidth (SKILL.md §4). |\n| `getWidth(id)` / `getHeight(id)` return `0` on an Auto-sized text block. Tempting to read this as \"font didn't load → text broken\". | `getWidth`/`getHeight` return what you set; in Auto mode that's `0`. They are **not** measurement APIs and **not** a font-load signal. | Use `engine.block.getFrameWidth(id)` / `getFrameHeight(id)` for the measured shaped extent. `getFrameWidth(id) > 0` is the actual \"font loaded + shaped\" probe. |\n| Pages attached via `engine.block.appendChild(scene, page)` don't show up, render at the wrong position, or break multi-page layout. Or `findByType(\"stack\")` returns `[]` and `appendChild(stack, page)` errors with `parent: Expected number, received undefined`. | `engine.scene.create()` (no argument) creates a scene WITHOUT a stack. Pages must attach to a stack, not the scene root. | Always pass the layout type: `engine.scene.create(\"VerticalStack\")` (or `\"HorizontalStack\"`). Then `engine.block.findByType(\"stack\")[0]` returns the auto-created stack, and `engine.block.appendChild(stack, page)` works. The hierarchy is always **scene → stack → page**. |\n| Anthropic returns `400 ... image dimensions exceed max allowed size for many-image requests: 2000 pixels`. | An image from something other than `preview` (e.g. an image your edit `code` returned inline) exceeded 2000 px on a dimension. `preview` itself is capped at 0.25 megapixels and 1568 px per dimension, so it can no longer trigger this. | Check images your own `code` returns inline; keep them under 2000 px per dimension. For seeing your work, prefer `preview` — every image it returns is always within limits, however many blocks you ask for. |\n| Accent shape covers text it should sit behind (pill hides headline; frame hides photo edge). | Child block created and appended AFTER the block it should sit under. `appendChild` places later children on top — there is no z-index property. | Create the background shape first, append it, THEN create+append the foreground text. To fix an existing scene without destroying anything: `engine.block.insertChild(page, bgId, 0)` to push back-most, or insert before a sibling via `getChildren(page).indexOf(siblingId)`. See SKILL.md §4 \"Z-order via child order\". |\n| Resizing a block with an image fill silently crops the subject out — the face/product that was centered drifts to an edge or off-frame after a width/height change. | The fill shows a _window_ onto its source; a `Cover` fill recomputes that window from the block's new **aspect** and re-centers, a `Crop` fill exposes gaps. The block frame is right; the region of interest moved. | Capture the fill's ROI **before** the resize (`getContentFillMode` + `getContentFill{Horizontal,Vertical}Alignment`, and for `Crop` the `getCropScaleRatio`/`getCropTranslationX/Y`/`getCropRotation`) and re-apply **after**, using `adjustCropToFillFrame(id, sr)` to refill gaps. Never call `resetCrop` in a resize path — it forces the mode back to `Cover`. Full routine: `resize` skill, \"Preserve the region of interest\". |\n\n<!-- feature:video -->\n\n| A track child's `setTimeOffset` \"doesn't stick\" — a video/shape renders at the wrong moment, or clips with deliberately overlapping offsets (for a crossfade) instead play back-to-back with a hard cut and no overlap. | `track/automaticallyManageBlockOffsets` defaults to `true`. The track auto-arranges its children back-to-back by cumulative duration and silently overwrites any manual `setTimeOffset` — no error. Coincidentally correct with a single child at offset 0, which is why it hides until you need custom/overlapping timing. | `engine.block.setBool(track, 'track/automaticallyManageBlockOffsets', false)` right after creating the track, before setting any child's `setTimeOffset`. Verify with `engine.block.getTimeOffset(child)` if in doubt. |\n\n<!-- /feature:video -->\n\n## Diagnosis order — text doesn't render\n\nCheap → expensive:\n\n1. **Did you await fonts?** — `await engine.block.forceLoadResources([page])` inside the same edit before measuring. (Capturing is covered: `preview`, `export`, and the commit itself run this barrier server-side.)\n2. **Height vs font size** — `getHeight(id) >= getTextFontSizes(id)[0] * 1.6`?\n3. **Position on page** — block within `[0, pageWidth] × [0, pageHeight]`?\n4. **Font URI valid** — was setFont called with the 3-arg form? Was the typeface looked up from `ly.img.gfonts` (§6.7) rather than hand-built with a guessed URI?\n\nAfter `forceLoadResources`, every text block's `getFrameWidth(id)` returns its measured shaped width. If that's still `0`, the URI didn't deliver a renderable font — look the typeface up from `ly.img.gfonts` instead of hardcoding a URI (design-rules.md §6.7).\n",
|
|
596
|
-
"docs/judge/SKILL.md": "---\nname: judge\ndescription: >-\n Use to quality-gate a design before reporting it done — the mandatory step 5 of the\n handbook Loop; when the user asks for a design review, score, audit, or QA; or when a\n design needs remediation after a failed review. The axes, the gate, the scorecard\n format, and the remediation loop are defined in this skill's body — read it before\n scoring; do not judge from memory of this description.\n---\n\n# judge — the build → judge → remediate loop\n\nYou are the design's QA judge. Judging is scored against what you SEE in `preview` renders of the **latest revision** of the current design — never against the code that produced it, and never from memory. If you are unsure which revision is current, re-ground via `list()` / `history({ revision })` first (handbook §1).\n\n## The 8 axes\n\nScore each axis 0–10 against the render. `baseline` is the execution floor; the other seven map to handbook §6 sections:\n\n| Axis | What it scores | Rubric |\n| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |\n| **baseline** | Nothing broken: no overflow, no blank/placeholder text, no tofu (□), no clipped ascenders/descenders, nothing off-canvas, no unintended overlap | §6.1.7, §6.4 |\n| **hierarchy** | One dominant element; unambiguous reading order; ≈3 (≤4) levels; rank carried by size > weight > color > spacing > position; structure expressed as a grouped block hierarchy (nested where nested) | §6.3 |\n| **typography** | Families/weights, scale bands, leading (incl. the content-area conversion and diacritic/non-Latin rules), measure, rag, tracking, micro-typography, lists & paragraph structure, inline style ranges | §6.1 (checklist §6.1.11) |\n| **color** | Palette ≤ 3 + neutrals; exactly one consistent accent; contrast on the actual background | §6.2 |\n| **composition** | Margins 8–12% of the shortest dimension; shared grid; spacing ladder; balanced whitespace — no dead void; nothing off-canvas | §6.4 |\n| **craft** | Chips/pills/badges built per the chip system; intentional crops; clean decoration; consistent component geometry | §6.5 (checklist §6.5.2) |\n| **copy** | The words say something only this business/occasion could say: no nothing-tagline, transformation claim, uncheckable superlative, upbeat closer or abstract-noun padding; trade idiom and specifics left intact | §6.8 (copy-writing-rules.md) |\n| **localization** | Localized variants only: correct per-language typography, no drift from the source layout, RTL mirrored, script-correct fonts; **source-parity** (appearance/weight/element/decoration match the source render — see below) | §6.6 + the `localize` skill |\n\n**Some axes cannot be judged from a single PNG.** Nine checks below are **instrumented** — they read a measured value, the scene graph, or a second render, not an eyeball — because the naked render either hides the defect or can't reveal the cause. Five of them (chip construction, curved type, list construction, inline emphasis, paragraph structure) catch **construction** defects that render pixel-identically to the correct build: scoring the image alone passes them every time.\n\n- **Leading (typography):** don't eyeball the gap. Read the font's content area (`engine.editor.getFontMetrics` → `(ascender − descender + lineGap)/unitsPerEm`) and check the **rendered** gap against the band (§6.1.3), not the raw `text/lineHeight`. An engine number that \"looks set\" can still render loose on a tall face. This read-back is **required, not optional, on every headline/display block and on every text block of a localized (non-source-language) variant** — the localized-leading defect is the single most common one and it survives a clean-looking PNG. (Elsewhere, run it on any block whose gap you can't confidently pass by eye.)\n- **Grouping (hierarchy):** grouping is **invisible in a PNG**. Read the scene graph — walk `getChildren` from the page — and confirm each logical cluster (eyebrow+headline, label+value, icon+text, chip field+label) is an actual group block, not loose siblings (§6.3). A page that _looks_ ranked but ships flat fails hierarchy, and ungrouped RTL icons break on mirror.\n- **Chip construction (craft):** a rectangle with text floating on top and a text block with a native text background render **pixel-identically**. Scoring the PNG therefore cannot see the defect, and craft passes on a chip that will drift the moment the copy or locale changes. Read the scene graph: for every text-only chip (pill, eyebrow, badge, tag, button), confirm the field is the text block's own `backgroundColor/*` and **not** a sibling shape sitting behind it. A text block centred on a same-size rect sibling is the tell. Fails **craft** (§6.5.1). A separate container is legitimate only when the chip's content is not just text — an icon + text, an image, several elements.\n- **Curved type (craft):** likewise invisible in a render. Confirm every arced/circular text is **one** text block carrying a path baseline (`getTextOnPath` returns non-null), not a run of one-character text blocks rotated into an arc. A cluster of single-glyph text blocks at stepped rotations is the tell; it fails **craft** (§6.5.4) and usually **hierarchy** too, since those loose blocks are ungrouped (§6.3).\n- **List construction (typography):** a native list and a hand-built one render almost identically — the difference only surfaces when an item wraps, and most items don't. Read the scene graph: every bulleted/numbered list must be **one** text block whose paragraphs carry a list style (`getTextListStyle(id, i)` ≠ `'None'`), one paragraph per item. Three tells, all failing **§6.1.8**: a marker typed into the string (`\"• \"`, `\"1. \"` at the start of lines), a **lone marker-glyph text block** sitting beside a text frame (a block whose whole string is `•`/`-`/`·` is never legitimate), and **one text block per item**. The last two also fail **hierarchy** (§6.3) as loose siblings.\n- **Inline emphasis (typography):** an accent word set as a style range and the same word split into its own text block render identically. Read the scene graph: emphasis inside a line must be a **range on one block** — `getTextRuns(id).length > 1` — not a sibling block. The tell is two or more text blocks sharing a baseline `y` and a typeface, differing only in colour or weight, whose strings concatenate into one phrase. Fails **§6.1.9**, and hierarchy too when the fragments are ungrouped. Also check the string itself: capitals typed into the copy where `getTextCases(id)` returns `'Normal'` is the frozen-caps defect (§6.1.9) — invisible until the design is localized.\n- **Paragraph structure (typography):** read `text/paragraphSpacing` on every multi-paragraph block. A string containing a blank line (`\\n\\n`) with `paragraphSpacing == 0` means blank lines are being used as spacing; N stacked single-paragraph blocks that read as one passage mean the block split is doing the paragraph's job. Both fail **§6.1.8**.\n- **Copy (copy):** score the words, not their setting. The scene-graph walk below already hands you every string; read them in the order the render shows them, as one voice, and ask whether a competitor could paste the same lines onto their own page unchanged. Bias hard toward leaving copy alone — the failure mode of this axis is flattening good writing, and specifics (numbers, dates, names) and trade idiom are not tells (§6.8, read via skill({ name: 'handbook', path: 'copy-writing-rules.md' })). **Never dock this axis for em dashes or curly quotes:** both are correct typography here, and §6.1.7 requires the quotes. What fails: a headline or standfirst that names nothing specific to this business, a transformation claim, an uncheckable superlative, an upbeat closer, or body copy that could be deleted without the page losing information. On a source-derived edition this axis is scored on the source's copy layer only — a restyle or a reformat that re-worded anything fails **baseline** under Copy parity below, not this axis.\n- **Source-parity (localization + composition + craft + typography):** a variant is judged against **its source**, not in isolation — see the next section. Applies to every design derived from another: a **localization**, a **resize**, and a **brand restyle**. For a localized variant, also confirm the source's **style ranges survived**: if the source block has multiple runs and the variant has one, the translation flattened the accent (`localize`), which fails **localization** even when the render looks clean.\n\n## The gate\n\n**Every applicable axis ≥ 8. No averaging. N/A = 10.** One axis at 7 fails the design. An axis is N/A only when it genuinely cannot apply (e.g. `localization` on a single-language design) — score it 10 and mark it N/A in the scorecard.\n\nThe caller may override the default: narrow the axes (\"judge typography and composition only\") or move the threshold (\"pass ≥ 9\"). Apply the override for that run; otherwise the full gate is the default.\n\n**This skill never asks.** Its two parameters — the axis set and the threshold — are both\ndefaultable, and it runs as step 5 of the Loop on every build, so a question here would interrupt\nevery design this server makes. Take the override if the caller gave one, otherwise take the full\ngate, and score. This is the stated exception to the intake contract (`skill({ name: 'handbook', path: 'intake.md' })`), which every other skill follows.\n\n**A source-derived variant (localization, resize, or brand restyle) cannot pass on its standalone render.** The source-parity diff below is a **mandatory gate step**, not an \"if in doubt\" — a variant judged only against its own PNG has not been judged. If you did not `preview` the source and diff it, the gate is incomplete and the design is not done.\n\n## Source-derived variants — judge against the source, not just the render\n\nA **localization**, a **resize**, and a **brand restyle** are not standalone designs: each is derived from a source, and each changes exactly **one** layer — the words, the canvas, or the style — while carrying the rest faithfully. Judging one in isolation passes variants that are internally clean but **infidelity to the original** — the single largest class of derived defects (wrong leading after a font swap, a fill/effect/corner-radius/weight that silently changed, decoration that drifted, an element that vanished, a restyle that quietly re-flowed the layout, an icon the RTL flip disassembled). None of these show up scoring the variant's PNG alone; **all** of them show up the moment you put the variant next to the source.\n\n**So for every variant with a source, `preview` the source too and diff the two renders — always, before scoring.** First name **which layer the variant is allowed to change** (words / canvas / style); everything else is held, and every difference outside that layer is a defect until you can name it as a deliberate consequence. Then judge these against the source (they feed the axes noted):\n\n- **Element inventory** (localization + composition) — every content cluster on the source has a counterpart on the variant; nothing silently dropped or added. Missing elements read as \"too simplistic.\"\n- **Copy parity** (baseline; **brand** + resize) — the strings are the source's strings. A restyle and a reformat carry copy verbatim: no re-worded headline, no shortened subline, no dropped line \"to fit\" the new face or canvas. Re-wording is the `localize` layer; if the copy no longer fits, fix the type, not the text.\n- **Appearance parity** (craft + color) — fills, gradients, effect/blur stacks, opacity, corner radius, stroke, shadow, and any overlay match the source; none re-created by eye, none added/removed (a cover that \"became darker,\" a rounded corner gone square). **For a brand restyle this check inverts:** appearance is _supposed_ to change, so parity is on the **role assignment**, not the values — the block that was the background is still the background, the one accent moment is still that block, the divider is still a divider. A restyle that recoloured a rule into a second lead, or promoted a caption to the accent, broke role parity even though every value came from the kit.\n- **Weight parity** (typography) — every block renders at the source block's weight; the font swap did not land on the family's lightest cut (\"too light / unreadable\"). For a brand restyle, the target is the **brand's** weight for that role — but relative weight order across blocks still matches the source's hierarchy.\n- **Geometry / decoration drift** (localization for localize; composition for resize; craft + composition for brand) — for **localize**, every block sits on the source grid (position + size), baseline-relative where the face changed; decoration with an internal geometric relationship (a ring of stars, evenly-stepped dashes) holds that relationship. For **resize**, geometry is _re-derived_ (drift ≠ moved), so instead judge that the **system** and **identity** carried (§6.4/§6.3) and nothing was lost. For **brand**, geometry is held like a localization — a block moved for anything but a stated brand rule (safe-area margin, kicker pill, size threshold) is drift; a re-layout is a `resize`, not a restyle.\n- **Re-wrap fallout** (baseline; **brand** + localization) — a font swap changes the measure, so an auto-height block can re-wrap to a new line count, grow, and collide with or push its neighbour even though nothing was moved. Diff the **line counts** against the source, not just the positions.\n- **RTL selectivity** (localization) — icons/logos/marks/numerals/charts/photos are **not** mirrored; composed marks moved as groups, not disassembled.\n\nA variant that is clean on its own but diverges from the source on any of these fails the axis noted — **do not pass it on the strength of the standalone render.** When a divergence is a deliberate, correct adaptation (a headline re-wrapped for a longer language, a block re-flowed for a new aspect, a margin widened to the brand's safe area), that is not drift; name it and pass.\n\n**A brand restyle carries a second gate.** The kit's `avoid` list and `do-dont/` gallery sit **on top of** the axes: a single hard `avoid` violation fails the restyle even when every axis is ≥ 8. Add an **avoid-list** row to the scorecard and score it against the kit, not the rubric (the `brand` skill).\n\n## The loop\n\n1. **Preview** — `preview` every page that matters of the latest revision, in **one call**: `preview({ revision })` with `blockIds` omitted renders every page, so scoring the whole design costs no more than scoring page 1. Judging an old render is judging the wrong design. A render is invalidated by **content** changes, not by revision ids: if the latest revision is content-identical to one you already rendered this conversation (a no-op edit, a diagnostic/read-only pass, a rename), that render is still current — reuse it instead of re-rendering. **If the design is a localization, a resize, or a brand restyle, also `preview` the source revision** — you need both renders side by side for the source-parity checks above.\n2. **Judge** — score each applicable axis against the render. For `typography` and `craft`, dry-run the §6.1.11 and §6.5.2 checklists line by line (read them via skill({ name: 'handbook', path: 'design-rules.md' })); for `copy`, read §6.8 (skill({ name: 'handbook', path: 'copy-writing-rules.md' })) before scoring the words. Any \"no\" on an applicable checklist line caps that axis below 8. Run the **instrumented checks** where they apply: the leading read-back (getFontMetrics → rendered gap vs band), the scene-graph reads for grouping, chip construction, curved type, list construction, inline emphasis, paragraph structure and copy, and — for source-derived variants — the source-parity diff. A clean-looking PNG is not sufficient for these nine. **All seven scene-graph reads share one walk** of `getChildren` from the page — do them in a single pass, not seven. For each text block that walk reaches, one read of `getTextRuns`, `getTextListStyle` (per paragraph), `text/paragraphSpacing`, `getTextOnPath` and the block's string answers six of the seven; grouping is answered by the walk itself.\n3. **Scorecard** — report the result in this shape (conversational markdown; no files):\n\n | Axis | Score | Violations | Fix |\n | ----------- | ----- | ---------------------------------------------------------------- | ---------------------------------------------------- |\n | typography | 6 | all-caps eyebrow untracked (§6.1.6); body leading unset (§6.1.3) | set letterSpacing 0.12; set converted lineHeight 1.5 |\n | composition | 8 | — | — |\n\n One row per applicable axis, N/A rows marked. Below the table: the verdict (`PASS` / `FAIL — remediating`) and, on failure, the remediation order (worst axis first).\n\n **Then one line for the brief.** Restate the brief this design was built from and name any place the design departs from it — a direction, palette, format or audience that is not what was asked for or agreed. The eight axes score execution only, so a design built beautifully in a direction nobody chose passes all of them; this line is the only thing that catches it. It does not gate (a deliberate, explained departure is fine) and it never becomes a question — `judge` does not ask. If the design was built with a parameter **defaulted rather than asked**, say which: that is the sentence the user needs in order to correct it in one word.\n\n4. **Remediate** — apply the fixes via `edit` on the latest revision. Remediation is surgical: fix the flagged blocks in place (handbook §5 \"Prefer surgical fixes\"); respect the reshape trap (line-height/font changes → reshape → re-apply every color/style range, §6.1.3). Never rebuild the scene to fix a spacing violation.\n5. **Re-preview → re-judge** — repeat from step 1 until the gate passes, but re-capture only what you changed: `preview({ blockIds: [<the pages you fixed>], revision })`. Re-rendering untouched pages puts near-identical copies of the same design at different revisions into the conversation, which makes it harder, not easier, to see what moved. Then report done, with the final scorecard.\n\n## Judging discipline\n\n- **Judge the render, not the intent.** A rule satisfied in code but broken on screen is broken.\n- **Be harsh on your own work.** The common failure is scoring 8 by charity. If you hesitated, it is a 7.\n- **Score honestly on partial remediation.** If a violation cannot be fixed without re-laying-out the design, say so and recommend the `resize` skill (a layout problem) or a rebuild — do not inflate the score.\n- **The brief wins where the rubric is silent**; the rubric wins on hard-threshold conflicts (§6 intro).\n",
|
|
596
|
+
"docs/judge/SKILL.md": "---\nname: judge\ndescription: >-\n Use to quality-gate a design before reporting it done — the mandatory step 5 of the\n handbook Loop; when the user asks for a design review, score, audit, or QA; or when a\n design needs remediation after a failed review. The axes, the gate, the scorecard\n format, and the remediation loop are defined in this skill's body — read it before\n scoring; do not judge from memory of this description.\n---\n\n# judge — the build → judge → remediate loop\n\nYou are the design's QA judge. Judging is scored against what you SEE in `preview` renders of the **latest revision** of the current design — never against the code that produced it, and never from memory. If you are unsure which revision is current, re-ground via `list()` / `history({ revision })` first (handbook §1).\n\n## The 8 axes\n\nScore each axis 0–10 against the render. `baseline` is the execution floor; the other seven map to handbook §6 sections:\n\n| Axis | What it scores | Rubric |\n| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |\n| **baseline** | Nothing broken: no overflow, no blank/placeholder text, no tofu (□), no clipped ascenders/descenders, nothing off-canvas, no unintended overlap | §6.1.7, §6.4 |\n| **hierarchy** | One dominant element; unambiguous reading order; ≈3 (≤4) levels; rank carried by size > weight > color > spacing > position; structure expressed as a grouped block hierarchy (nested where nested) | §6.3 |\n| **typography** | Families/weights, scale bands, leading (incl. the content-area conversion and diacritic/non-Latin rules), measure, rag, tracking, micro-typography, lists & paragraph structure, inline style ranges | §6.1 (checklist §6.1.11) |\n| **color** | Palette ≤ 3 + neutrals; exactly one consistent accent; contrast on the actual background | §6.2 |\n| **composition** | Margins 8–12% of the shortest dimension; shared grid; spacing ladder; balanced whitespace — no dead void; nothing off-canvas | §6.4 |\n| **craft** | Chips/pills/badges built per the chip system; intentional crops; clean decoration; consistent component geometry | §6.5 (checklist §6.5.2) |\n| **copy** | The words say something only this business/occasion could say: no nothing-tagline, transformation claim, uncheckable superlative, upbeat closer or abstract-noun padding; trade idiom and specifics left intact | §6.8 (copy-writing-rules.md) |\n| **localization** | Localized variants only: correct per-language typography, no drift from the source layout, RTL mirrored, script-correct fonts; **source-parity** (appearance/weight/element/decoration match the source render — see below) | §6.6 + the `localize` skill |\n\n**Some axes cannot be judged from a single PNG.** Nine checks below are **instrumented** — they read a measured value, the scene graph, or a second render, not an eyeball — because the naked render either hides the defect or can't reveal the cause. Five of them (chip construction, curved type, list construction, inline emphasis, paragraph structure) catch **construction** defects that render pixel-identically to the correct build: scoring the image alone passes them every time.\n\n- **Leading (typography):** don't eyeball the gap. Read the font's content area (`engine.editor.getFontMetrics` → `(ascender − descender + lineGap)/unitsPerEm`) and check the **rendered** gap against the band (§6.1.3), not the raw `text/lineHeight`. An engine number that \"looks set\" can still render loose on a tall face. This read-back is **required, not optional, on every headline/display block and on every text block of a localized (non-source-language) variant** — the localized-leading defect is the single most common one and it survives a clean-looking PNG. (Elsewhere, run it on any block whose gap you can't confidently pass by eye.)\n- **Grouping (hierarchy):** grouping is **invisible in a PNG**. Read the scene graph — walk `getChildren` from the page — and confirm each logical cluster (eyebrow+headline, label+value, icon+text, chip field+label) is an actual group block, not loose siblings (§6.3). A page that _looks_ ranked but ships flat fails hierarchy, and ungrouped RTL icons break on mirror.\n- **Chip construction (craft):** a rectangle with text floating on top and a text block with a native text background render **pixel-identically**. Scoring the PNG therefore cannot see the defect, and craft passes on a chip that will drift the moment the copy or locale changes. Read the scene graph: for every text-only chip (pill, eyebrow, badge, tag, button), confirm the field is the text block's own `backgroundColor/*` and **not** a sibling shape sitting behind it. A text block centred on a same-size rect sibling is the tell. Fails **craft** (§6.5.1). A separate container is legitimate only when the chip's content is not just text — an icon + text, an image, several elements.\n- **Curved type (craft):** likewise invisible in a render. Confirm every arced/circular text is **one** text block carrying a path baseline (`getTextOnPath` returns non-null), not a run of one-character text blocks rotated into an arc. A cluster of single-glyph text blocks at stepped rotations is the tell; it fails **craft** (§6.5.4) and usually **hierarchy** too, since those loose blocks are ungrouped (§6.3).\n- **List construction (typography):** a native list and a hand-built one render almost identically — the difference only surfaces when an item wraps, and most items don't. Read the scene graph: every bulleted/numbered list must be **one** text block whose paragraphs carry a list style (`getTextListStyle(id, i)` ≠ `'None'`), one paragraph per item. Three tells, all failing **§6.1.8**: a marker typed into the string (`\"• \"`, `\"1. \"` at the start of lines), a **lone marker-glyph text block** sitting beside a text frame (a block whose whole string is `•`/`-`/`·` is never legitimate), and **one text block per item**. The last two also fail **hierarchy** (§6.3) as loose siblings.\n- **Inline emphasis (typography):** an accent word set as a style range and the same word split into its own text block render identically. Read the scene graph: emphasis inside a line must be a **range on one block** — `getTextRuns(id).length > 1` — not a sibling block. The tell is two or more text blocks sharing a baseline `y` and a typeface, differing only in colour or weight, whose strings concatenate into one phrase. Fails **§6.1.9**, and hierarchy too when the fragments are ungrouped. Also check the string itself: capitals typed into the copy where `getTextCases(id)` returns `'Normal'` is the frozen-caps defect (§6.1.9) — invisible until the design is localized.\n- **Paragraph structure (typography):** read `text/paragraphSpacing` on every multi-paragraph block. A string containing a blank line (`\\n\\n`) with `paragraphSpacing == 0` means blank lines are being used as spacing; N stacked single-paragraph blocks that read as one passage mean the block split is doing the paragraph's job. Both fail **§6.1.8**.\n- **Copy (copy):** score the words, not their setting. The scene-graph walk below already hands you every string; read them in the order the render shows them, as one voice, and ask whether a competitor could paste the same lines onto their own page unchanged. Bias hard toward leaving copy alone — the failure mode of this axis is flattening good writing, and specifics (numbers, dates, names) and trade idiom are not tells (§6.8, read via skill({ name: 'handbook', path: 'copy-writing-rules.md' })). **Never dock this axis for em dashes or curly quotes:** both are correct typography here, and §6.1.7 requires the quotes. What fails: a headline or standfirst that names nothing specific to this business, a transformation claim, an uncheckable superlative, an upbeat closer, or body copy that could be deleted without the page losing information. On a source-derived edition this axis is scored on the source's copy layer only — a restyle or a reformat that re-worded anything fails **baseline** under Copy parity below, not this axis.\n- **Source-parity (localization + composition + craft + typography):** a variant is judged against **its source**, not in isolation — see the next section. Applies to every design derived from another: a **localization**, a **resize**, and a **brand restyle**. For a localized variant, also confirm the source's **style ranges survived**: if the source block has multiple runs and the variant has one, the translation flattened the accent (`localize`), which fails **localization** even when the render looks clean.\n\n## The gate\n\n**Every applicable axis ≥ 8. No averaging. N/A = 10.** One axis at 7 fails the design. An axis is N/A only when it genuinely cannot apply (e.g. `localization` on a single-language design) — score it 10 and mark it N/A in the scorecard.\n\nThe caller may override the default: narrow the axes (\"judge typography and composition only\") or move the threshold (\"pass ≥ 9\"). Apply the override for that run; otherwise the full gate is the default.\n\n**This skill never asks.** Its two parameters — the axis set and the threshold — are both\ndefaultable, and it runs as step 5 of the Loop on every build, so a question here would interrupt\nevery design this server makes. Take the override if the caller gave one, otherwise take the full\ngate, and score. This is the stated exception to the intake contract (`skill({ name: 'handbook', path: 'intake.md' })`), which every other skill follows.\n\n**A source-derived variant (localization, resize, or brand restyle) cannot pass on its standalone render.** The source-parity diff below is a **mandatory gate step**, not an \"if in doubt\" — a variant judged only against its own PNG has not been judged. If you did not `preview` the source and diff it, the gate is incomplete and the design is not done.\n\n## Source-derived variants — judge against the source, not just the render\n\nA **localization**, a **resize**, and a **brand restyle** are not standalone designs: each is derived from a source, and each changes exactly **one** layer — the words, the canvas, or the style — while carrying the rest faithfully. Judging one in isolation passes variants that are internally clean but **infidelity to the original** — the single largest class of derived defects (wrong leading after a font swap, a fill/effect/corner-radius/weight that silently changed, decoration that drifted, an element that vanished, a restyle that quietly re-flowed the layout, an icon the RTL flip disassembled). None of these show up scoring the variant's PNG alone; **all** of them show up the moment you put the variant next to the source.\n\n**So for every variant with a source, `preview` the source too and diff the two renders — always, before scoring.** First name **which layer the variant is allowed to change** (words / canvas / style); everything else is held, and every difference outside that layer is a defect until you can name it as a deliberate consequence. Then judge these against the source (they feed the axes noted):\n\n- **Element inventory** (localization + composition) — every content cluster on the source has a counterpart on the variant; nothing silently dropped or added. Missing elements read as \"too simplistic.\"\n- **Copy parity** (baseline; **brand** + resize) — the strings are the source's strings. A restyle and a reformat carry copy verbatim: no re-worded headline, no shortened subline, no dropped line \"to fit\" the new face or canvas. Re-wording is the `localize` layer; if the copy no longer fits, fix the type, not the text.\n- **Appearance parity** (craft + color) — fills, gradients, effect/blur stacks, opacity, corner radius, stroke, shadow, and any overlay match the source; none re-created by eye, none added/removed (a cover that \"became darker,\" a rounded corner gone square). **For a brand restyle this check inverts:** appearance is _supposed_ to change, so parity is on the **role assignment**, not the values — the block that was the background is still the background, the one accent moment is still that block, the divider is still a divider. A restyle that recoloured a rule into a second lead, or promoted a caption to the accent, broke role parity even though every value came from the kit.\n- **Weight parity** (typography) — every block renders at the source block's weight; the font swap did not land on the family's lightest cut (\"too light / unreadable\"). For a brand restyle, the target is the **brand's** weight for that role — but relative weight order across blocks still matches the source's hierarchy.\n- **Geometry / decoration drift** (localization for localize; composition for resize; craft + composition for brand) — for **localize**, every block sits on the source grid (position + size), baseline-relative where the face changed; decoration with an internal geometric relationship (a ring of stars, evenly-stepped dashes) holds that relationship. For **resize**, geometry is _re-derived_ (drift ≠ moved), so instead judge that the **system** and **identity** carried (§6.4/§6.3) and nothing was lost. For **brand**, geometry is held like a localization — a block moved for anything but a stated brand rule (safe-area margin, kicker pill, size threshold) is drift; a re-layout is a `resize`, not a restyle.\n- **Re-wrap fallout** (baseline; **brand** + localization) — a font swap changes the measure, so an auto-height block can re-wrap to a new line count, grow, and collide with or push its neighbour even though nothing was moved. Diff the **line counts** against the source, not just the positions.\n- **RTL selectivity** (localization) — icons/logos/marks/numerals/charts/photos are **not** mirrored; composed marks moved as groups, not disassembled.\n\nA variant that is clean on its own but diverges from the source on any of these fails the axis noted — **do not pass it on the strength of the standalone render.** When a divergence is a deliberate, correct adaptation (a headline re-wrapped for a longer language, a block re-flowed for a new aspect, a margin widened to the brand's safe area), that is not drift; name it and pass.\n\n**A brand restyle carries a second gate.** The kit's `avoid` list and `do-dont/` gallery sit **on top of** the axes: a single hard `avoid` violation fails the restyle even when every axis is ≥ 8. Add an **avoid-list** row to the scorecard and score it against the kit, not the rubric (the `brand` skill).\n\n## The loop\n\n1. **Preview** — `preview` every page that matters of the latest revision, in **one call**: `preview({ revision })` with `blockIds` omitted renders every page, so scoring the whole design costs no more than scoring page 1. Judging an old render is judging the wrong design. A render is invalidated by **content** changes, not by revision ids: if the latest revision is content-identical to one you already rendered this conversation (a no-op edit, a diagnostic/read-only pass, a rename), that render is still current — reuse it instead of re-rendering. **If the design is a localization, a resize, or a brand restyle, also `preview` the source revision** — you need both renders side by side for the source-parity checks above.\n2. **Judge** — score each applicable axis against the render. For `typography` and `craft`, dry-run the §6.1.11 and §6.5.2 checklists line by line (read them via skill({ name: 'handbook', path: 'design-rules.md' })); for `copy`, read §6.8 (skill({ name: 'handbook', path: 'copy-writing-rules.md' })) before scoring the words. Any \"no\" on an applicable checklist line caps that axis below 8. Run the **instrumented checks** where they apply: the leading read-back (getFontMetrics → rendered gap vs band), the scene-graph reads for grouping, chip construction, curved type, list construction, inline emphasis, paragraph structure and copy, and — for source-derived variants — the source-parity diff. A clean-looking PNG is not sufficient for these nine. **All seven scene-graph reads share one walk** of `getChildren` from the page — do them in a single pass, not seven. For each text block that walk reaches, one read of `getTextRuns`, `getTextListStyle` (per paragraph), `text/paragraphSpacing`, `getTextOnPath` and the block's string answers six of the seven; grouping is answered by the walk itself.\n3. **Scorecard** — report the result in this shape (conversational markdown; no files):\n\n | Axis | Score | Violations | Fix |\n | ----------- | ----- | ---------------------------------------------------------------- | ---------------------------------------------------- |\n | typography | 6 | all-caps eyebrow untracked (§6.1.6); body leading unset (§6.1.3) | set letterSpacing 0.12; set converted lineHeight 1.5 |\n | composition | 8 | — | — |\n\n One row per applicable axis, N/A rows marked. Below the table: the verdict (`PASS` / `FAIL — remediating`) and, on failure, the remediation order (worst axis first).\n\n **Then one line for the brief.** Restate the brief this design was built from and name any place the design departs from it — a direction, palette, format or audience that is not what was asked for or agreed. The eight axes score execution only, so a design built beautifully in a direction nobody chose passes all of them; this line is the only thing that catches it. It does not gate (a deliberate, explained departure is fine) and it never becomes a question — `judge` does not ask. If the design was built with a parameter **defaulted rather than asked**, say which: that is the sentence the user needs in order to correct it in one word.\n\n4. **Remediate** — apply the fixes via `edit` on the latest revision. Remediation is surgical: fix the flagged blocks in place (handbook §5 \"Prefer surgical fixes\"); respect the reshape trap (line-height/font changes → reshape → re-apply every color/style range, §6.1.3). Never rebuild the scene to fix a spacing violation.\n5. **Re-preview → re-judge** — repeat from step 1 until the gate passes, but re-capture only what you changed: `preview({ blockIds: [<the pages you fixed>], revision })`. Re-rendering untouched pages puts near-identical copies of the same design at different revisions into the conversation, which makes it harder, not easier, to see what moved. Then report done, with the final scorecard.\n6. **Record the verdict** — `scorecard({ revision: <the revision the passing renders came from>, verdict: 'pass' })`. This closes the loop: `export` checks the latest recorded scorecard and reminds you when a delivered revision carries changes it does not cover. If the loop is being cut short with an axis still below 8 (e.g. the user says ship anyway), record `verdict: 'fail'` — the failure belongs on record, not silently dropped. **The record is a claim about work done**: never record a verdict for renders you did not score, and after any further content `edit` the gate re-arms — judge again, record again.\n\n## Judging discipline\n\n- **Judge the render, not the intent.** A rule satisfied in code but broken on screen is broken.\n- **Be harsh on your own work.** The common failure is scoring 8 by charity. If you hesitated, it is a 7.\n- **Score honestly on partial remediation.** If a violation cannot be fixed without re-laying-out the design, say so and recommend the `resize` skill (a layout problem) or a rebuild — do not inflate the score.\n- **The brief wins where the rubric is silent**; the rubric wins on hard-threshold conflicts (§6 intro).\n",
|
|
597
597
|
"docs/localize/SKILL.md": "---\nname: localize\ndescription: >-\n Use when creating or fixing translated / localized variants of an existing CoDesign / CE.SDK\n design (e.g. de/ja/ru/ar editions); when a localized edition's text blocks or\n decorative elements have drifted, re-centered, or resized away from the source layout; when\n translated copy is tofu, overflowing, mis-tracked, or the wrong font after a language swap; or\n when loading a non-Latin script (Cyrillic / CJK / Arabic RTL / Vietnamese) font into a scene.\n---\n\n# localize\n\nPoint this skill at the current design and the target locales, and it produces or repairs the localized editions. It operates on the **latest revision of the current design** (re-ground via `list()` / `history()` if unsure — handbook §1); each locale lands as its own revision, forked from the source. Single home for localizing CoDesign designs: the **operational workflow**, the **font-loading mechanics**, and the **per-language quality rules**. It builds on two things it does _not_ restate: handbook §6.1 (general typographic thresholds — leading, tracking, all-caps, the content-area line-height conversion (`getFontMetrics`), smart punctuation, reshape-recolor) and handbook §6.7 (general Latin font mechanics — `setFont` single-URI, static-vs-variable, blank-glyph diagnosis). This skill is the non-Latin / localization extension of both.\n\n**Scoring:** localizing is judged with the `judge` skill — every applicable axis ≥ 8, no averaging, N/A = 10. A single tofu glyph, an overflow after expansion, un-mirrored RTL, or a block that drifted off the source grid fails the edition (the `localization` axis).\n\n## Reference files (load on demand)\n\nThis `SKILL.md` holds the always-needed spine: inputs, core principle, workflow, block\nclassification, and the snap-to-reference routine. Two situational bodies of rules live beside it\nand are pulled in only when the task needs them:\n\n- **`reference/font-loading.md`** — getting a non-Latin / non-handbook face to render (jsDelivr\n picks, the variable-bold trap, `setFont` gotchas, the silent-sans failure). Read it whenever the\n target locale needs a Cyrillic / CJK / Arabic / Vietnamese font, or copy came out tofu / wrong\n face.\n- **`reference/language-rules.md`** — the cross-language spine: preserve-vs-localize, translation\n quality, layout integrity after translation, and the localization pass checklist.\n- **`reference/<family>.md`** — per-script-family conventions, numeric leading bands, and\n quotation marks, one file per family: `latin-expansion.md` (de/fr/es…), `arabic.md`, `cjk.md`\n (ja/zh/ko), `vietnamese.md`, `cyrillic.md` (ru…). Read the file(s) for the **target locale(s)**\n you're building — or pull just the rule you need:\n `skill({ name: 'localize', query: 'leading', path: 'reference/arabic.md' })`.\n\n## Inputs — what to localize, and into what\n\nResolved before any work by the intake contract — derive, ask once, echo, invent nothing:\n`skill({ name: 'handbook', path: 'intake.md' })`. **R** = required, no default; **A** = ask if\nunderived; **D** = defaultable.\n\n| Parameter | Kind | Chips / values | Default |\n| -------------- | ------- | --------------------------------------------------------------------------- | ------------------------------------- |\n| target locales | **R** | `German` · `French` · `Spanish` · `Japanese` · `Chinese` · `Arabic` · Other | none |\n| source locale | A | detected from the design's copy · Other | detected, stated in the echo |\n| source design | derived | — | latest revision of the current design |\n\n**1. The source (reference)** — the latest revision of the current design in its source language (usually `en`). That revision's geometry is the grid every target locale snaps to. Never localize _from_ a non-reference locale — always fork each locale from the source revision. If the user means an earlier design, find it via `list()` / `history()` first.\n\n**2. The locales** — the target languages, e.g. `de ja ru ar`. If omitted, **ask** —\n_**Which languages do you need?**_ — with the chips above; there is no defaulting to a language the\nuser didn't name. Then echo the resolved set (\"1 design × 3 locales, source `en` (detected)\") before\nbuilding.\n\n**Never invent copy.** A translation is the user's own content: if a block's meaning is ambiguous,\nor a term is a name/product you cannot safely render in the target script, ask rather than guess —\nsee the keep-byte-identical list in `reference/language-rules.md` §1.\n\n**Per locale, then:** run the Workflow below (fork the source revision, or reuse+snap an existing localized revision). Give each locale's revision a `note` naming the locale. Preview every locale before reporting done.\n\n## Core principle — localize, then snap back to the reference\n\nLocalizing is **surgical**: change the words + the font the new script forces, and **nothing\nelse**. Then **snap every block back to the reference variant's geometry** so the localized\nedition is positionally identical to the source.\n\n- The **reference** is the source-locale variant (usually `en`) **of the same size**. Each size\n has its own reference grid.\n- **Never re-center or re-size a block per variant \"to fit better.\"** That independent re-fitting\n is exactly what makes a localized set drift — the eyebrow creeps up, the quote grows, the rule\n and footer slide down, and the editions stop matching. If there is room for the translated text\n at the reference position/size, keep the reference position/size.\n- Deviate from the reference **only** when the translated text genuinely overflows (expansion\n languages) — then shrink _that block's_ font within its band; do not move its neighbours.\n- **Swap the script font per block, not per scene.** Apply the new face **only to blocks whose\n copy is actually in the target script.** A block that stays in the source script — a personal\n name, brand/wordmark, `@handle`, URL, email, number, date, or product/tech name (the \"keep\n byte-identical\" list in `reference/language-rules.md` §1) — **keeps its original typeface.**\n Re-fonting it to the script face is drift even though its text was correctly preserved: a Latin\n name rendered in the Arabic/CJK serif is the classic tell. So a localized edition differs from\n its reference in **only the translated blocks' text + face**; every untranslated block is\n byte-identical (position mirrored for RTL).\n\n## When to use\n\n- Producing new locale editions (de/ja/ru/ar/…) of a finished design, across one or more sizes.\n- Fixing a localized set whose blocks drifted / re-centered / resized vs the source.\n- Post-translation breakage: tofu, overflow, wrong tracking, Latin-looking sans where a script\n font should be.\n- Loading a non-Latin or non-handbook typeface into a scene.\n\n**Not for:** the original design build (that's the handbook + §6); pure copy edits in the\nsame language. To change\nthe **size/format** — re-compose a design for a new aspect rather than translate it — use the **resize** skill\n(localize snaps geometry; resize re-derives it).\n\n## Reuse an existing localized build vs build fresh\n\n- **The workspace already has the locale** (an earlier pass built it — check `history()`): **reuse its\n build** — the translated copy, script fonts, and RTL are already solved — but still **snap it to\n the reference geometry**. Earlier builds commonly drift; reuse the assets, fix the positions.\n- **No existing build:** fork the reference revision and swap text + font.\n\nEither way the last step is the same: every block lands on the reference grid.\n\n## Workflow\n\n1. **Capture the reference geometry.** Load the source-locale variant of that size and read, per\n block: `x, y, width, widthMode, heightMode, fontSize (Pixel), lineHeight, letterSpacing,\nalignment`, plus page `w/h`, the ghost's anchor (left / centered), and the rule position.\n2. **Load the target** — the localized scene to fix, or fork the reference for a fresh build.\n3. **Classify blocks by role** (see below).\n4. **Apply the reference geometry** to each corresponding block; keep the localized **text** and\n the **script font** (for a non-Latin/non-handbook face see `reference/font-loading.md`). Set\n per-locale: `letterSpacing = 0` for CJK & Arabic; RTL ghost mirrored to the right; alignment as\n the reference (centered-symmetric stays centered — see `reference/arabic.md`).\n5. **Reconcile ghost count.** Keep the reference's number of decorative glyphs. If the localized\n scene has extra ones (e.g. an Arabic closing-quote bookend the English lacks), **destroy the\n extras**; mirror the kept one for RTL.\n6. **Overflow guard.** After setting the reference font size, measure the quote's frame height; if\n it collides with the element below, step the font size down (only that block) until it fits.\n Never move neighbours to make room.\n7. **Reshape, then re-apply rich text.** A font/size/line-height change needs a reshape\n (`setString` with the same text) to take visual effect — and any string write **wipes every\n per-character style range**: color, weight, style, size, typeface, case, decoration and\n kerning. Capture each block with `getTextRuns` first, re-apply after. ⚠ `getTextColors(id)[0]`\n is **not** a capture — it reads the first run only, so re-applying it flattens a two-color\n headline onto one color and the accent is gone with no error. Paragraph state\n (`getTextListStyle` / `getTextListLevel` per paragraph) survives a same-string reshape but not\n a **re-write**, so re-apply it whenever the string itself changed. **Ranges are index-based on\n the source string** — a translated string has different offsets, so never replay `from`/`to`\n verbatim; re-locate the styled substring in the target language (§ \"Carrying rich text across\n a translation\").\n8. **`forceLoadResources` → `preview`.** One preview per locale — tofu / RTL / overflow /\n position match are only visible in the render.\n\nThen apply the per-locale quality rules in `reference/language-rules.md` **and the family\nfile(s) for the target locale(s)** (`reference/latin-expansion.md`, `arabic.md`, `cjk.md`,\n`vietnamese.md`, `cyrillic.md`), and dry-run the localization pass checklist against the render\nbefore reporting done.\n\n## Block-role classification\n\nClassify by measurable properties, not hard-coded ids (ids are session-scoped). For a\nquote-card family the roles are:\n\n- **ghost** (oversized decorative quote) — largest font size **and** trimmed string length ≤ 2.\n A design may have **more than one** (opening + closing bookend); collect all.\n- **footer / handle** — text containing `@`.\n- **quote / headline** — the largest remaining text after removing ghosts + footer.\n- **eyebrow** vs **attribution** — the two small texts; eyebrow sits **above** the quote,\n attribution **below**.\n- **rule / divider** — the graphic (non-text) block.\n\nRoles are design-specific. The general rule: **map each localized block to its reference block by\nrole, or by index across the shared fork lineage** (localized variants forked from the same base\nkeep the same child order), then restore that reference block's geometry.\n\n## The snap-to-reference routine\n\nA single CoDesign `edit` body. Fill the `EN` reference geometry (from step 1) and the locale\nflags, then it classifies, restores geometry, reconciles ghosts, applies per-locale tracking /\nRTL mirroring, guards overflow, and re-applies colors across the reshape.\n\n⚠ This routine is a **worked example, not a template**: every number in `EN` below is from one\nexample quote-card, and the classification heuristics (`fs >= 150`, `s.includes('@')`, …) are\nthat card's — never reuse either literally. Fill `EN` only from your own reference capture (the\nread at the bottom), and rewrite the classification for the actual design's roles.\n\n```js\n// --- config: reference geometry (read from the source-locale variant of THIS size) ---\nconst PW = 1080,\n PH = 1350; // page dims\nconst EN = {\n // lh = VISUAL leading target (from the target locale's script band, NOT the reference's\n // raw engine number) — setLeading() converts it through each block's target face. For a\n // localized display headline in a diacritic language, this is where the conditional +0.2\n // lives (latin-expansion.md): bump ≤1.2 → ~1.35 only if the rendered gap needs it.\n ghost: { x: 70, y: 55, fs: 300, lh: 1 }, // Auto-sized; keep size+lh, reposition\n eyebrow: { x: 110, y: 395, w: 860, fs: 16, lh: 1, ls: 0.25 },\n quote: { x: 110, y: 529, w: 860, fs: 62, lh: 0.85 }, // ls always 0\n rule: { x: 504, y: 930, w: 72 }, // graphic\n attribution: { x: 110, y: 960, w: 860, fs: 16, lh: 1, ls: 0.25 },\n footer: { x: 110, y: 1225, w: 860, fs: 15, lh: 1, ls: 0.12 }\n};\nconst RTL = false; // true for Arabic\nconst trackOK = true; // false for CJK/Arabic → force letterSpacing 0 on eyebrow/attr/footer\nconst ghostAnchor = 'left'; // 'left' (post/square) mirrors to the right for RTL; 'center' (story) stays centered\nconst belowQuoteY = EN.rule.y; // element the quote must stay above\n\nconst page = engine.scene.getPages()[0];\nconst all = [];\n(function walk(id) {\n all.push(id);\n for (const c of engine.block.getChildren(id)) walk(c);\n})(page);\nconst blocks = all.filter((id) => id !== page);\nconst texts = blocks.filter((id) => engine.block.getType(id).includes('text'));\nconst graphic = blocks.find((id) =>\n engine.block.getType(id).includes('graphic')\n);\nawait engine.block.forceLoadResources([page]);\n\nconst meta = (id) => ({\n id,\n s: engine.block.getString(id, 'text/text'),\n fs: engine.block.getTextFontSizes(id, { unit: 'Pixel' })[0],\n y: engine.block.getPositionY(id)\n});\nconst tm = texts.map(meta);\n\n// classify\nconst ghosts = tm.filter((t) => t.fs >= 150 && t.s.trim().length <= 2);\nlet ghost =\n ghosts.find((t) => t.s.includes('“')) ||\n ghosts.slice().sort((a, b) => a.y - b.y)[0];\nfor (const g of ghosts.filter((t) => t !== ghost)) engine.block.destroy(g.id); // drop extra bookend glyphs\nconst footer = tm.find((t) => t.s.includes('@'));\nconst rest = tm.filter((t) => !ghosts.includes(t) && t !== footer);\nconst quote = rest.reduce((a, b) => (b.fs > a.fs ? b : a));\nconst others = rest.filter((t) => t !== quote);\nconst eyebrow = others.reduce((a, b) => (b.y < a.y ? b : a));\nconst attribution = others.find((t) => t !== eyebrow);\n\n// capture rich text (reshape wipes EVERY per-character style range, not just color)\nconst runsOf = (id) => {\n try {\n return engine.block.getTextRuns(id).map((r) => ({\n text: r.text,\n color: r.color,\n fontWeight: r.fontWeight,\n fontStyle: r.fontStyle,\n textCase: r.textCase,\n textDecoration: r.textDecoration\n }));\n } catch (e) {\n return [];\n }\n};\nconst runs = Object.fromEntries(\n [ghost, eyebrow, quote, attribution, footer].map((t) => [t.id, runsOf(t.id)])\n);\n// Re-apply captured styling. Run 0 is the base style and covers the whole block; any\n// further run is an accent whose SOURCE offsets are meaningless once the string is\n// translated, so it is re-located by its target-language substring (SPANS below).\n// Returns false when the accent could not be placed — flag it, never silently flatten.\nconst apply = (id, r, from, to) => {\n if (r.color) engine.block.setTextColor(id, r.color, from, to);\n if (r.fontWeight) engine.block.setTextFontWeight(id, r.fontWeight, from, to);\n if (r.fontStyle) engine.block.setTextFontStyle(id, r.fontStyle, from, to);\n if (r.textCase) engine.block.setTextCase(id, r.textCase, from, to);\n if (r.textDecoration?.lines?.length)\n engine.block.setTextDecoration(id, r.textDecoration, from, to);\n};\nconst restyle = (id, rs, spans = []) => {\n if (!rs.length) return true;\n const s = engine.block.getString(id, 'text/text');\n apply(id, rs[0], 0, s.length); // base style over the whole (translated) string\n let ok = true;\n rs.slice(1).forEach((r, i) => {\n const span = spans[i]; // translator-supplied target-language accent text\n const at = span ? s.indexOf(span) : -1;\n if (at < 0) {\n ok = false; // accent lost in translation — report it, don't fake it\n return;\n }\n apply(id, r, at, at + span.length);\n });\n return ok;\n};\n// Accent spans IN THE TARGET LANGUAGE, one per non-base run, keyed by block.\n// Empty for single-run blocks — which is every block in this quote card.\nconst SPANS = {};\nconst reshape = (id) =>\n engine.block.setString(\n id,\n 'text/text',\n engine.block.getString(id, 'text/text')\n );\n// ⚠ Leading is RE-DERIVED on the TARGET face — never copied raw from the reference.\n// `text/lineHeight` multiplies the font's content area (per-face, ~1.15–1.35), so the\n// same engine number renders a DIFFERENT visual gap once the script font is swapped —\n// the #1 localized-leading defect. So EN.*.lh below is a VISUAL leading target (taken\n// from the target locale's script band in the family file — latin/arabic/cjk — NOT the\n// reference's raw engine value), converted through THIS block's now-current font via\n// getFontMetrics (handbook §6.1.3).\nconst setLeading = async (id, visual) => {\n const uri = engine.block.getString(id, 'text/fontFileUri');\n let ca = 1.5; // fallback ≈ typical content area (the old ×0.66); mis-corrects tall/compact faces\n try {\n const m = await engine.editor.getFontMetrics(uri);\n ca = (m.ascender - m.descender + m.lineGap) / m.unitsPerEm;\n } catch (e) {}\n engine.block.setFloat(id, 'text/lineHeight', visual / ca);\n};\nconst applyText = async (t, g, ls) => {\n engine.block.setWidthMode(t.id, 'Absolute');\n engine.block.setWidth(t.id, g.w);\n engine.block.setHeightMode(t.id, 'Auto');\n engine.block.setTextFontSize(t.id, g.fs, { unit: 'Pixel' });\n await setLeading(t.id, g.lh); // visual target → target-face content area (§6.1.3)\n engine.block.setFloat(t.id, 'text/letterSpacing', ls);\n engine.block.setEnum(t.id, 'text/horizontalAlignment', 'Center');\n reshape(t.id);\n};\n\nengine.block.setTextFontSize(ghost.id, EN.ghost.fs, { unit: 'Pixel' });\nawait setLeading(ghost.id, EN.ghost.lh);\nreshape(ghost.id);\nawait applyText(eyebrow, EN.eyebrow, trackOK ? EN.eyebrow.ls : 0);\nawait applyText(attribution, EN.attribution, trackOK ? EN.attribution.ls : 0);\nawait applyText(footer, EN.footer, trackOK ? EN.footer.ls : 0);\nawait applyText(quote, EN.quote, 0);\nengine.block.setWidth(graphic, EN.rule.w);\nfor (const t of [ghost, eyebrow, quote, attribution, footer])\n restyle(t.id, runs[t.id], SPANS[t.id]);\nawait engine.block.forceLoadResources([page]);\n\n// position (ghost measured for mirroring; others straight from EN)\nconst gw = engine.block.getFrameWidth(ghost.id);\nengine.block.setPositionX(\n ghost.id,\n ghostAnchor === 'center'\n ? (PW - gw) / 2\n : RTL\n ? PW - EN.ghost.x - gw\n : EN.ghost.x\n);\nengine.block.setPositionY(ghost.id, EN.ghost.y);\nfor (const [t, g] of [\n [eyebrow, EN.eyebrow],\n [quote, EN.quote],\n [attribution, EN.attribution],\n [footer, EN.footer]\n]) {\n engine.block.setPositionX(t.id, g.x);\n engine.block.setPositionY(t.id, g.y);\n}\nengine.block.setPositionX(graphic, EN.rule.x);\nengine.block.setPositionY(graphic, EN.rule.y);\n\n// overflow guard — shrink ONLY the quote, never move neighbours\nawait engine.block.forceLoadResources([page]);\nlet qfs = EN.quote.fs;\nconst avail = belowQuoteY - EN.quote.y - 16;\nwhile (engine.block.getFrameHeight(quote.id) > avail && qfs > 44) {\n qfs -= 2;\n engine.block.setTextFontSize(quote.id, qfs, { unit: 'Pixel' });\n reshape(quote.id);\n if (cols[quote.id]) engine.block.setTextColor(quote.id, cols[quote.id]);\n await engine.block.forceLoadResources([page]);\n}\nreturn { type: 'text', text: JSON.stringify({ page, qfs }, null, 1) };\n```\n\nReference-capture read (run on the source variant to fill `EN`):\n\n```js\nconst page = engine.scene.getPages()[0];\nconst out = [];\n(function walk(id) {\n const t = engine.block.getType(id),\n isText = t.includes('text');\n const r = {\n t: t.split('/').pop(),\n x: Math.round(engine.block.getPositionX(id)),\n y: Math.round(engine.block.getPositionY(id)),\n w: Math.round(engine.block.getWidth(id)),\n wm: engine.block.getWidthMode(id)\n };\n if (isText) {\n r.s = engine.block.getString(id, 'text/text').slice(0, 14);\n r.fs = Math.round(engine.block.getTextFontSizes(id, { unit: 'Pixel' })[0]);\n r.lh = +engine.block.getFloat(id, 'text/lineHeight').toFixed(2);\n r.ls = +engine.block.getFloat(id, 'text/letterSpacing').toFixed(2);\n }\n if (id !== page) out.push(r);\n for (const c of engine.block.getChildren(id)) walk(c);\n})(page);\nreturn {\n type: 'text',\n text: JSON.stringify({\n pw: engine.block.getWidth(page),\n ph: engine.block.getHeight(page),\n b: out\n })\n};\n```\n\n## Carrying rich text across a translation\n\nStyled ranges are stored as character offsets into the block's string. Translate the string and\nthose offsets point at different words — sometimes at nothing. So a localized variant must carry\nrich text **semantically**, not numerically.\n\n- **Capture with `getTextRuns`, never `getTextColors(id)[0]`.** The latter reads run 0 only.\n Re-applying it whole-block is what silently flattens a two-color headline.\n- **Run 0 is the base style**; apply it across the whole translated string first.\n- **Every further run is an accent**, and you need its **target-language substring** to place it.\n Ask for it as part of the translation: translate `\"Save 20% today\"` **and** tell me which\n target-language span carries the accent (`\"20 %\"`, `\"٪٢٠\"`, …). Locate that span with\n `indexOf`, then re-apply.\n- **A span that can't be located is a reportable defect**, not something to paper over. Apply the\n base style, leave the accent off, and say so — a flattened headline that nobody mentions is\n exactly the failure this section exists to prevent.\n- **The accent may not survive as a span at all.** Word order moves it, agglutinative targets fuse\n it into a longer word, and some languages have no equivalent fragment. When that happens, prefer\n moving the emphasis to the phrase the target language actually stresses over splitting a word.\n- **Paragraph state is separate from runs.** List style/level and per-paragraph alignment/leading\n live on paragraph indices, not character offsets — re-apply them per paragraph after any string\n re-write, and keep the item count matched (a translation that merges two bullets into one\n silently drops a list item).\n- **`textCase` is not a translation artefact.** All-caps set through `setTextCase` re-cases the\n target string automatically; all-caps typed into the string is frozen English and cannot be\n correctly cased in scripts that have no case at all. Carry the property, not typed capitals.\n\n## Common mistakes / red flags\n\n- **Per-variant re-centering / re-sizing** → drift. If you're re-centering a block because the\n translation is a different length, STOP — snap it to the reference position instead.\n- **Line-height copied raw across the font swap** → wrong gap. `text/lineHeight` is content-area\n scaled and per-face; re-derive it on the target face (`setLeading`, §6.1.3), never carry the\n reference's engine number. The single most common localized-leading defect.\n- **Whole block landed a few px low (ar/ja \"moved down\")** → **baseline drift**. `setPositionY`\n snaps the frame **top** (= ascender line), but the script face's ascender/descender differ from\n the Latin source, so identical `y` renders a different baseline. Snap **baseline-relative** when\n the face changes: after positioning + `forceLoadResources`, nudge `y` by the ascent delta\n `(refAscent − targetAscent) × fontSize` (both `ascender/unitsPerEm` via `getFontMetrics`), or\n align the block by a shared optical anchor rather than the frame top. Confirm against the source\n render (the `judge` source-parity check).\n- **\"Bold\" from a variable TTF** → renders Regular. Use a static Bold file (`reference/font-loading.md`).\n- **Weight not carried onto the swapped face (text \"too light / unreadable\")** → the swap lands on\n the family's lightest cut. Capture the reference block's weight and re-apply it on the target\n face (verify it actually renders — the variable-bold trap, `font-loading.md`); parity is checked\n by the `judge` source-parity render diff.\n- **Appearance not carried (fill/gradient/effect/corner-radius/overlay differs from the source)** →\n fork the source revision so surface styling is inherited; if you rebuilt instead of forked, or a\n reshape/recolor dropped it, re-capture and re-apply. Don't re-create a fill or effect \"by eye\" —\n read its values off the source.\n- **Reshape wiped the accent color / bold / underline** → capture with `getTextRuns` before the\n reshape and re-apply after. If you captured with `getTextColors(id)[0]` you captured run 0 only,\n and re-applying it whole-block is itself the flattening bug.\n- **Accent landed on the wrong word after translation** → run offsets were replayed verbatim. They\n are source-string indices; re-locate the accent by its target-language substring instead.\n- **Bullets became separate blocks / lost their hanging indent in the variant** → list state is\n per-paragraph and does not survive a string re-write. Re-apply `setTextListStyle` (and the level)\n per paragraph after translating.\n- **Letter-spacing on Arabic** → severs joins. `letterSpacing = 0`.\n- **RTL flip disassembled an icon / broke in-frame centering** → mirror operates on **groups, not\n loose blocks**, and **icons/logos/brand marks/numerals/charts/photos must not mirror** at all.\n Group a composed icon and flip the group as a unit (or exempt it); see the do-not-mirror\n inventory in `reference/arabic.md`.\n- **Plausible page, wrong font** → silent sans fallback / tofu. Preview every locale.\n- **Extra or missing decorative glyph** vs the reference → reconcile the count.\n- **Non-native export size** → export the page at its own pixel dimensions.\n\n## Cross-references\n\n- **`reference/font-loading.md`** — non-Latin / non-handbook font mechanics (this skill's font body).\n- **`reference/language-rules.md`** — cross-language quality rules + pass checklist.\n- **`reference/latin-expansion.md` / `arabic.md` / `cjk.md` / `vietnamese.md` / `cyrillic.md`** — per-script-family conventions, leading bands, quotation marks.\n- handbook §6.1 — general typographic thresholds (leading, tracking, all-caps & diacritic leading, the content-area line-height conversion (`getFontMetrics`), smart punctuation, reshape-then-recolor); §6.7 — the Latin font baseline; and the handbook's reshape / `forceLoadResources` / dirty-on-throw runtime quirks.\n- **`judge`** — the acceptance gate (the `localization` axis scores this skill's output).\n- **`resize`** — the sibling skill for changing size/format (re-compose for a new aspect).\n",
|
|
598
598
|
"docs/localize/reference/arabic.md": "# Arabic (RTL)\n\nFamily file for the `localize` skill: conventions, leading bands, and quotation marks for Arabic.\nEvery leading value here is a **visual** multiplier — apply the handbook §6.1.3 content-area\nconversion (divide by the font's content area via `engine.editor.getFontMetrics`) before setting\n`text/lineHeight`.\n\n## Conventions\n\n- **MSA** (Modern Standard Arabic), not dialect; **Western numerals**.\n- **Mirror the layout, not just the text.** Right-align running text; flow directional &\n decorative elements right-to-left (a leading decorative quote glyph → mirror `“`→`”`/`»`). A\n **centered, symmetric** composition is already mirror-invariant — it **stays centered**; only\n text direction and the ghost's side change (the snap routine mirrors a `ghostAnchor:'left'`\n ghost to the right, leaves a `'center'` ghost centered).\n- **Never letter-space Arabic** — joined script; tracking severs the joins. `text/letterSpacing = 0`\n (handbook §6.1.6).\n- Keep names/brands/URLs/numbers as-is (Latin runs stay LTR via bidi) **and in their source\n typeface** — `setFont` the Arabic face **only on Arabic-script blocks**; never re-font a\n Latin-only block (a name, wordmark, chips, dates) to the Arabic serif. Transliteration optional.\n- **Mirror by anchoring to an edge, not by measured width.** `getFrameWidth` can **under-measure\n Auto-width Arabic** (joined-script shaping), so mirroring a block via `x = pageW − x −\ngetFrameWidth(id)` can push it off-page. Give a mirrored Arabic block an **Absolute width,\n right-aligned and anchored to a known right edge** — don't position it by measured width.\n- **Mirror the reading order — not every block. Keep a do-not-mirror inventory.** Mirroring is a\n **selective** transform over a **classified** tree, not a blanket flip of every block's `x`.\n Flip: the column/reading order (what was leftmost becomes rightmost), running-text alignment, and\n **directional** decoration (a leading quote glyph, an arrow that points into the text). Do **not**\n mirror, ever: **icons, logos, brand/wordmarks, glyph-built marks, numerals and number strings,\n charts/graphs, photographs**, and any pictogram whose handedness carries meaning (a check, a\n play triangle). Mirroring these is the \"icons broke / elements moved to the right / off-center in\n their frames\" defect.\n- **Mirror on the GROUP, not its parts.** A composed icon (mail = envelope body + flap + lines),\n a lockup (mark + wordmark), or a badge (field + label + icon) must move **as one unit** — mirror\n the group's position, and leave the group's _internal_ layout intact (or exempt the group\n entirely if it's in the do-not-mirror list). If the parts are loose siblings, a per-block flip\n disassembles them — **group first, then decide mirror-or-exempt for the whole group.** Content\n that sits _inside_ a frame (text/icon centered in a shape) is re-anchored with its frame, never\n flipped independently.\n\n## Leading\n\nTall ascenders + deep descenders demand more vertical room than Latin — set explicitly:\n\n- **Body 1.6–1.8**\n- **Display / headline 1.3–1.5**\n\nNo all-caps concept applies (Arabic has no case).\n\n## Quotation marks\n\n| Locale | Primary quotes | Notes |\n| ------ | -------------- | ------------------------------ |\n| AR | « » | RTL; opening mark on the right |\n\nSecondary: „ “.\n\n## Fonts\n\nUse a script face with full Arabic coverage **matched to the Latin face's character**\n(`language-rules.md` §6), not just any Arabic font:\n\n- **Editorial / high-contrast serif** Latin → **Amiri** (Naskh serif — verified).\n- **Geometric / grotesque sans** Latin → **IBM Plex Sans Arabic / Cairo / Tajawal** (matched sans).\n Do **not** use Amiri here — a Naskh serif on a sans design is a mismatch.\n- **Handwritten / script** accent → **Aref Ruqaa** (Ruqʿah calligraphy) or **Lalezar** (rounded\n playful display), never a flat sans.\n\nLoading mechanics + jsDelivr paths + the variable-bold trap are in `font-loading.md`. A Latin face\nsilently falling back to a system sans is the classic failure — `preview` every Arabic edition.\n\n## Cross-references\n\n- `language-rules.md` — preserve-vs-localize, translation quality, layout integrity, the RTL rows\n of the pass checklist.\n- handbook §6.1.5 — mirrored alignment; §6.1.6 — the no-tracking rule; §6.1.3 — the content-area\n conversion.\n- `judge` — the `localization` axis scores mirroring, bidi, and tofu.\n",
|
|
599
599
|
"docs/localize/reference/cjk.md": "# CJK (Japanese, Chinese, Korean)\n\nFamily file for the `localize` skill: conventions, leading bands, and quotation marks for CJK\nscripts (Japanese guidance is the most developed; the typographic rules hold for CJK generally).\nEvery leading value here is a **visual** multiplier — apply the handbook §6.1.3 content-area\nconversion (divide by the font's content area via `engine.editor.getFontMetrics`) before setting\n`text/lineHeight`.\n\n## Conventions\n\n- **Real kanji**, idiomatic; no romaji dumps.\n- **No all-caps, no italics** — CJK has neither; never fake them. Foreign names may stay Latin\n or, optionally, be written in katakana.\n- **Font swap only on CJK blocks.** Foreign names/brands/URLs/numbers kept in Latin **retain their\n source typeface** — `setFont` the CJK face only on blocks that carry CJK text; don't re-font a\n Latin-only block (a name, wordmark, chips, dates) into the CJK serif.\n- **Full-width punctuation:** 、 。 「 」 『 』 ( ). Do not reuse Latin `, . \" ()`.\n- Respect **kinsoku** — a line shouldn't _start_ with 、 or 。. The engine usually handles this —\n verify in `preview`.\n\n## Leading & tracking\n\nFull-width glyphs fill the em and pack dense — set leading explicitly, looser than Latin:\n\n- **Body 1.6–1.75**\n- **Display / headline 1.25–1.35**\n- **No tracking** — `text/letterSpacing = 0` (handbook §6.1.6); CJK is never letter-spaced.\n\n## Quotation marks\n\n| Locale | Primary quotes | Notes |\n| -------- | -------------- | -------------------------- |\n| JA / CJK | 「 」 『 』 | full-width corner brackets |\n\n## Fonts\n\nA CJK-covering face is mandatory, **matched to the Latin face's character** (`language-rules.md`\n§6) — **Mincho is the CJK serif, Gothic is the CJK sans**:\n\n- **Editorial / high-contrast serif** Latin → **Shippori Mincho / Noto Serif JP** (Mincho).\n- **Geometric / grotesque sans** Latin → **Noto Sans JP / Zen Kaku Gothic New** (Gothic). Setting a\n sans design in Mincho is the common inverted mismatch — check the Latin character both ways.\n- **Handwritten / casual** accent → **Yomogi / RocknRoll One**.\n- No italic/cursive in CJK — carry emphasis with **weight + size**, not a separate style.\n\nLoading mechanics + jsDelivr paths are in `font-loading.md`. Latin faces have zero CJK coverage — a\nwrong font is instant tofu; `preview` every edition.\n\nFor **bold** CJK headings load a **static Bold CJK file**\n(`ofl/shipporimincho/ShipporiMincho-Bold.ttf`) — a single Regular file (or a variable face's\ndefault instance) renders **Regular only** (the bold trap, `font-loading.md`). If no static Bold\nis available, carry the heading's weight with **size/color** instead of a faux-bold.\n\n## Cross-references\n\n- `language-rules.md` — preserve-vs-localize, translation quality, layout integrity, the pass\n checklist.\n- handbook §6.1.3 — the content-area conversion; §6.1.6 — the no-tracking rule.\n- `judge` — the `localization` axis scores kanji quality, punctuation, and tofu.\n",
|