AI-native design editor. Open-source Figma alternative.
docs: route contributors through per-domain guides and ship npm license text (#785)
Danila Poyarkovb0231927c509
diff --git a/AGENTS.md b/AGENTS.mdindex 6844e0127..886b5af0d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,220 +1,68 @@# OpenPencil-Vue 3 + CanvasKit (Skia WASM) + Yoga WASM design editor. Tauri v2 desktop, also runs in browser.--**Roadmap:** `packages/docs/development/roadmap.md` tracks product direction, Figma compatibility gaps, and raw metadata coverage. This file keeps agent-facing architecture, conventions, and commands; detailed public docs live under `packages/docs/**`.--## Monorepo--Bun workspace packages:--- `scene-graph` — framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, and the shared primitives formats need: color conversion and color management, and text/layout direction.-- `pen` — Pencil.dev `.pen` model, parser, and SceneGraph adapter.-- `kiwi` — SceneGraph-independent Kiwi schema/runtime, codecs, containers, and parse helpers.-- `fig` — `.fig` archives, SceneGraph conversion, metadata policy, and component/instance interpretation.-- `core` — renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and document I/O; depends on scene-graph and the format packages (pen, kiwi, fig, dom-css), and keeps browser DOM out.-- `dom-css` — DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph, and takes engine services such as web-font resolution as injected options.-- `vue` — headless Vue 3 SDK primitives and composables; the root app is one consumer.-- `cli` — headless `.fig` inspection, export, and linting with `citty` and `agentfmt`.-- `mcp` — stdio and Hono HTTP MCP server reusing Core tools.-- `harness` — optional Node companion for HarnessAgent sessions and its bounded JSONL host protocol; Tauri launches the separately installed command.-- `docs` — published VitePress site. Use `bun run docs:dev`, `bun run docs:build` for fast checks, and `bun run docs:build:production` for deployment output.--The root Tauri/Vite app lives in `src/`; app services and state belong under `src/app/**`, views under `src/views/**`, and app UI under `src/components/**`.--### Settings UI ownership--Compose Settings sections with `SettingsSection` and its `title`, `description`, `actions`, and default content slots. It owns heading association and internal spacing; `SettingsGroup` owns bordered row grouping. Do not repeat section/header/spacing markup in each feature.--Settings components own layout, translated copy, confirmation visibility, and emits. Reactive settings workflows live under the owning app domain's `settings/` folder (for example `src/app/ai/models/settings/profile-editor/{use,selection,connection}.ts`), not a global composables bucket. Use `use.ts` for orchestration and focused sibling modules for substantial sub-workflows. Keep persistence and external operations in domain services, and pure option projections as ordinary functions. Return operation outcomes rather than importing dialogs, routers, or toast UI into workflow composables. Keep newly entered secrets short-lived, never expose saved secrets, and guard async results against changed targets. Small presentation-only computed bindings can remain in components. New explicit settings forms use headless VeeValidate v5 with native Valibot schemas and existing controlled UI components; keep form state in the owning settings domain. Saved secrets and replacement-secret drafts stay outside form snapshots and devtools, and persistence/concurrency remain in domain workflows rather than form callbacks.--### Public package exports--Across package/app boundaries, import the owning package's public exports—never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus targeted subpaths listed in `packages/core/package.json`.--CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere prefer `import type` and pass CanvasKit in.--### Editor architecture--`packages/core/src/editor/` is the framework-agnostic editor core. `createEditor()` in `create.ts` assembles an `EditorContext` plus domain action modules for viewport, selection, pages, shapes, structure, components, clipboard, undo/history, text, variables, layout, color space, graph reads, tool registry, and related helpers. Check the folder before adding editor behavior; keep new actions in the nearest domain module/folder instead of growing unrelated files.--`Editor` type = `ReturnType<typeof createEditor>`. Core modules should share state through `EditorContext` rather than importing app code or Vue.--#### Retained property panels--`DesignPanel` retains at most one selection-property subtree through `RetainedPanel`. The app installs `createRetainedScopePlugin()` from the Vue SDK; opted-in descendants receive `provideRetainedActivity()`. Vue component scopes are detached, so pausing only a parent or using bare `KeepAlive` does not suspend descendant work. Cancel drafts synchronously before DOM detachment can fire blur, close transient state and gate portals with `useRetainedPopup()`, and invalidate pending async results on deactivation/disposal. The plugin lets cleanup flush before pausing each component scope and resumes it on activation; it requires Vue's Options API. Unmounting the owning editor releases the retained subtree.--#### Editor event bus--The editor exposes a typed nanoevents emitter. Event names/payloads live in `EditorEvents` in `packages/core/src/editor/types.ts`; graph events are bridged from SceneGraph by `graph-events.ts`. Subscribe with `editor.onEditorEvent(event, handler)`, or in Vue use `useEditorEvent(event, handler)` from `packages/vue/src/editor/events/use.ts`.--Important invariant: all selection mutations in core go through `ctx.setSelectedIds()` and all tool changes go through `ctx.setActiveTool()` so events fire consistently. App-layer code should use editor actions such as `clearSelection()`, `select()`, or `setTool()` — never direct `state.selectedIds =` or `state.activeTool =` assignments.--The app editor session (`src/app/editor/session/create.ts`) is a Vue wrapper around core: it creates reactive state, calls `createEditor()`, and assembles app-specific document I/O, autosave, export, vector edit, pen resume, flashes, profiler, and mobile clipboard. Tabs live in `src/app/tabs/`; active editor access lives in `src/app/editor/active-store/`.--Headless SDK fields compose variable/token binding through `BindingProvider` and the `BindableValue` primitives in `packages/vue/src/controls/binding-provider/` and `packages/vue/src/primitives/BindableValue/`. Keep numeric interaction in `NumberField`; providers own binding lookup, mutation, and undo batching.--Property-panel anatomy in `packages/vue/src/primitives/PropertySection/`, `SegmentedControl/`, and `PropertyList/` is controlled and editor-agnostic. Connect PropertyList events to OpenPencil selection and undo through `useEditorPropertyList()` or an app adapter; never call `useEditor()` from these primitives.--### Settings and credentials--Credential persistence lives under `src/app/settings/credentials/`. Settings components receive `CredentialManager` and may inspect status, replace, or clear credentials; runtime adapters receive `CredentialResolver`. Components must not read saved secrets or keep them in long-lived reactive refs. Non-secret provider preferences remain in normal settings storage.--Tauri stores secrets in the native system credential store through `desktop/src/credentials.rs`; browsers default to WebCrypto-encrypted IndexedDB storage and may explicitly opt out to session-only memory. Native failures must never silently fall back to browser or plaintext storage. New integration credentials use stable `CredentialRef` values and join the unified Settings surface rather than adding feature-local key forms.--Storage-provider schemas and runtime adapters live under `src/app/integrations/storage/`; non-secret preferences and credential references stay separate, and adapters resolve secrets at operation time. Local-first document caching and outbox synchronization live under `src/app/storage/`. A remote storage binding augments document source state and must not replace local file identity.--Bitmap-to-vector conversion lives in `packages/core/src/vector/vectorize/`; app provider clients, preferences, and lazy credential resolution live under `src/app/editor/vectorize/`. Keep provider credentials in the centralized credential manager, bound request and response sizes, and validate provider-owned download URLs before importing returned SVG.--App dialogs compose the Reka-backed components under `src/components/ui/dialog/` and the typed theme in `src/theme/dialog.ts`. Do not repeat portal, overlay, content, header, or footer infrastructure in feature dialogs.+Vue 3 + CanvasKit (Skia WASM) + Yoga WASM design editor. Tauri v2 desktop, also runs in browser. Bun workspace monorepo.++This file holds the repository map and the rules that apply everywhere. Rules for one folder live in that folder's `AGENTS.md`. **Before changing files under a mapped path, read this file and that path's guide.** Paths in every guide are repository-relative. Process for humans (setup, PRs, commits) is in `CONTRIBUTING.md`; product direction and Figma gaps are in `packages/docs/development/roadmap.md`.++## Map++| Path | Owns | Guide |+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |+| `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, text/layout direction | `packages/scene-graph/AGENTS.md` |+| `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |+| `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` |+| `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` |+| `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, kiwi, fig, dom-css); no browser DOM | `packages/core/AGENTS.md` |+| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and takes engine services such as web-font resolution as injected options | — |+| `packages/vue` | Headless Vue 3 SDK primitives, composables, commands, i18n, menu model | `packages/vue/AGENTS.md` |+| `packages/cli` | Headless `.fig` inspection, export, linting, `eval` | `packages/cli/AGENTS.md` |+| `packages/mcp` | stdio and Hono HTTP MCP server reusing Core tools | `packages/mcp/AGENTS.md` |+| `packages/harness` | Optional Node companion for HarnessAgent sessions | `packages/harness/AGENTS.md` |+| `packages/docs` | Published VitePress site | `packages/docs/AGENTS.md` |+| `src` | Tauri/Vite app: services and state in `src/app/**`, views in `src/views/**`, UI in `src/components/**` | `src/AGENTS.md` |+| `desktop` | Tauri v2 shell, capabilities, native credentials, menus | `desktop/AGENTS.md` |+| `tests` | Central app, integration, E2E, native, and Figma acceptance tests | `tests/AGENTS.md` |+| `tools`, `.github` | Private repo tooling, CI classification, releases, brand generation | `tools/AGENTS.md` |+| `skills/open-pencil` | Installable agent skill | `packages/core/AGENTS.md` (Tools) |+| `assets/brand` | Canonical brand artwork | `assets/brand/README.md` |## Commands-- `bun run dev:portless` — preferred browser server at `https://open-pencil.localhost`; worktrees use `https://<branch>.open-pencil.localhost`.-- `bun run dev` — fixed `http://localhost:1420` server for Playwright, Tauri, and Dev Containers.+- `bun run dev:portless` — preferred browser server at `https://open-pencil.localhost`; worktrees get `https://<branch>.open-pencil.localhost` and a sibling `mcp.open-pencil` URL with isolated runtime discovery.+- `bun run dev` — fixed `http://localhost:1420`; use only for Playwright, Tauri, and Dev Containers.+- `bun run tauri dev` — desktop app with hot reload.+- A fresh worktree needs `bun install` and `bun run build:packages` before docs, Storybook, or any workflow that resolves workspace subpath exports; without the package builds those resolve to missing `packages/*/dist` targets.- `bun run check` — complete build, lint, type, architecture, docs, package, dependency, security, tooling, and duplication gate.- `bun run format` — format and sort imports.-- `bun run test:unit` / `bun run test` — engine/unit and app Playwright suites.-- `bun run test:storybook` — the Storybook Playwright project in `playwright.config.ts`. Test scripts select their server; direct Playwright commands start both servers unless `OPENPENCIL_TEST_SERVER=app|storybook|all` is set.-- `bun run tauri dev` — desktop app with hot reload.+- `bun run test:unit` / `bun run test` / `bun run test:storybook` — engine/unit, app Playwright, and Storybook Playwright suites. See `tests/AGENTS.md` for server selection and worktree ports.- `bun open-pencil --help` — current CLI command list.-## Git worktrees and development servers--Prefer `dev:portless`, especially in worktrees. It assigns branch-specific app and `mcp.open-pencil` sibling URLs with isolated runtime discovery. Use fixed-port `dev` only for Playwright, Tauri, and Dev Container flows.--A fresh worktree needs `bun install` and `bun run build:packages` before docs, Storybook, or any workflow that resolves workspace subpath exports; without the package builds those resolve to missing `packages/*/dist` targets.--Browser tests use the canonical `playwright.config.ts`; do not create task-specific config copies or server runners. Managed runs must start the intended checkout, with server reuse explicitly opted into only for local development, never baseline comparisons or CI. Isolate the app URL and MCP endpoint, CORS origin, socket, and discovery path together. Playwright owns Vite; the existing Vite automation plugin owns MCP startup and cleanup; browser fixtures own interactions, not server processes. See `packages/docs/development/testing.md` for configuration and commands.--## Releases & CI--For releases, update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; move `Unreleased` into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; then tag and push `vX.Y.Z`.--`.github/workflows/build.yml` is the source of truth: `v*` tags (or dispatches for an immutable stable tag) build shared frontend/package outputs once, build signed desktop artifacts in parallel, verify and attest one complete same-run artifact set, publish npm packages, and replace the draft release assets using the exact changelog section. Native release policy and recovery rules live in `tools/release-packages/README.md`; workflow and application source commits are recorded separately. Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports continue to use `dist`. Release preparation must preserve resolution maps. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks—do not publish package directories manually. `test:packages` first runs the packaging guards in `tools/package-quality/src/smoke/guards.ts`: fixture manifests packed with the real `npm pack` that must trip the tarball inspector and the Node/Bun consumer checks before those checks vouch for real packages. Keep package-manager invocations out of `bun test` suites; their cold start is not bounded, and raising a test timeout is never the fix. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it. Release titles are exactly the tag (`vX.Y.Z`), without a product-name prefix. Homebrew's official `openpencil` cask is managed upstream: BrewTestBot proposes version updates, then Homebrew reviews and merges them. Check the upstream cask/PR after publication; do not push to the archived custom tap or create duplicate bump automation. Install the desktop app with `brew install --cask openpencil`; install the CLI separately through npm or Bun.--App/docs production workflows run on `v*` tags or `workflow_dispatch`, not ordinary `master` pushes. `ci.yml` and `heavy-tests.yml` define validation gates.--PR CI always classifies changed paths through `tools/ci/`. Docs-only changes run documentation integrity/reference checks and the docs build, not engine, browser, Storybook, or native suites. Runtime prompt Markdown, executable examples, configuration, and unknown paths require code validation. The aggregate `CI result` gate requires successful classification and every applicable job; failures, cancellations, and unexpected skips cannot pass. Do not restore workflow-level path filtering on required CI.--## Documentation--- `CHANGELOG.md` — curated user-facing changes by version; `Unreleased` stays first.-- `README.md` — concise features, setup, CLI, and project overview.-- `AGENTS.md` — contributor/agent architecture and conventions.-- `packages/docs/` — public VitePress docs. Keep routes under `/getting-started`, `/overview/**`, `/user-guide/**`, `/programmable/**`, `/reference/**`, and `/development/**`; do not recreate `/guide/**`. Preserve moves in `public/_redirects`, and link untranslated locale navigation to canonical English pages rather than adding placeholders.--For user-facing work, add one present-tense outcome under the single appropriate `Unreleased` category: `Breaking changes`, `Added`, `Changed`, `Fixed`, `Performance`, or `Security`. Treat it as release notes, not a commit log: omit tests, benchmarks, CI, internal refactors/tooling, and bugs both introduced and fixed since the last release. After merges, compare the whole section with changes since the latest release, preserve important outcomes, consolidate related work, and remove duplicate bullets/headings. End sentences with periods and retain relevant issue/PR references. Update `README.md` when appropriate and this file when architecture or conventions change. Keep internal plans in ignored `scratch/`, not published docs.--Before finalizing `Unreleased`:--- Compare released behavior at the latest published tag with the final implementation, not just commit subjects. Verify questionable fixes existed at that tag; fold fixes to newly added features into their final feature description.-- Check public exports, model/config/data contracts, and peer requirements for removals, renames, and upgrade instructions under `Breaking changes`.-- Remove superseded intermediate behavior and duplicate outcomes across categories. State platform requirements and concrete supported behavior instead of unqualified compatibility or performance claims.-- Run `bun run check:changelog`. Keep historical sections unchanged during routine cleanup; release publication uses the matching tagged section, not regenerated prose.+Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun run test`.-## Commit messages+## Package boundaries-`commitlint.config.ts` enforces message structure through the **Commit messages** CI job on all PRs, including docs-only changes. Run `bun run check:commits --last` or pass `--from`/`--to` for a branch range. Preserve the release exception and product casing when changing rules; CI gate policy lives in `tools/ci/src/policy.ts`.--Use Conventional Commits (`feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, `chore`) for regular work. Keep subjects short, imperative, and narrowly scoped; explain rationale in the body. Preserve product casing such as DOM/CSS, HTML, JSX, Tailwind, Kiwi, `.fig`, MCP, CLI, AI, ACP, and i18n. Release commits use `Release vX.Y.Z`.--Keep AI assistance in the PR's AI assistance section, not commit authorship or `Co-authored-by` trailers. Do not append tool-generated promotional signatures or session links. Preserve human co-author credits and required third-party notices. Follow the vendor-neutral attribution policy in `CONTRIBUTING.md`; the existing commitlint gate checks known AI co-author identities without rewriting base history.--PR titles use Conventional Commits because GitHub uses them as merge subjects. The separate **PR title** workflow validates titles, including title edits, without rerunning the full CI suite. Preserve the conventional subject when merging via CLI/API; if setting it explicitly with `gh pr merge --subject`, use the validated PR title. Give branch-update merges explicit subjects such as `chore: merge master into <branch>`. Commitlint's default merge exceptions are not a naming convention. Do not rewrite published history solely to normalize messages.--## CLI--- Format all output with the `agentfmt` helpers re-exported from `packages/cli/src/format.ts`; do not hand-roll terminal formatting.-- Data/inspection commands should support `--json`.--## Tools (AI / MCP / CLI)--- Core operations are `ToolDef`s under `packages/core/src/tools/**`; `schema.ts` defines their contract and registries expose them. Each definition owns its native Valibot `input`, execution/mutation metadata, and optional per-interface exposure exclusions (`mcp`, `ai`, `webmcp`). Exposure defaults to inclusion; adapters use `isToolExposed()`, then apply execution support and user permissions independently. Infer arguments from the schema; derive effects and default capabilities from execution metadata instead of maintaining parameter DSLs or tool-name lists. Add work to the nearest existing domain and the appropriate registry.-- `ai-adapter.ts` converts ToolDefs for Vercel AI; `src/app/ai/tools/index.ts` binds them to the active editor's `FigmaAPI`.-- CLI commands own CLI UX independently; `eval` exposes operations through `FigmaAPI`.-- MCP-only filesystem/server tools live in `packages/mcp/src/tool/registration.ts`; listener/session lifecycle lives under `server/`, stdio under `stdio/`, and transport discovery under `transport/`. File access must resolve symlinks inside the effective MCP root; CLI defaults are cwd on macOS/Linux and home on Windows.-- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. Core owns synchronous property/variable transactions in `editor/history/atomic-tool.ts`; Scene Graph owns checkpoint recovery, including hierarchy and indexes. AI, MCP, and WebMCP share this execution path; async and structural tools cannot declare atomic property execution. App completion under `src/app/automation/execution/` loads fonts after commit. Keep browser lifecycle out of Core and the MCP server package.-- Keep MCP transport tests under `tests/engine/mcp/{server,stdio,transport}` and shared fixtures under `tests/helpers/mcp`; isolate tests from user runtime discovery.-- Shared scene-authoring guidance and tested examples live under `packages/core/src/design-jsx/reference/`; `reference.ts` combines them with renderer metadata. Core codegen prompts under `packages/core/src/tools/prompts/` and the app chat/ACP prompt compose that public reference rather than copying it. Run `bun run generate:authoring-reference` after changes; committed skill/docs copies are checked by `check:authoring-reference` (also part of `check:docs`). Do not edit generated reference files directly.-- The installable agent skill is maintained in `skills/open-pencil/`. Changes to agent-facing APIs, CLI/MCP behavior, or design authoring must update affected skill examples, prompts, and public documentation in the same change. Keep examples valid in their actual execution environment; do not advertise library exports as scripting globals unless exposed there. Prefer runtime discovery and canonical references over duplicated API/tool inventories.--## ACP and collaboration--- Harness agents live in the optional `@open-pencil/harness` Node companion. Keep it backend-neutral, persist only opaque non-secret resume state, expose the bounded JSONL protocol, and never bundle a JavaScript runtime into Tauri. Pi's in-memory `just-bash` cannot recover across process restarts.-- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/constants.ts`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily.-- ACP process changes require checking `desktop/capabilities/**`.-- Collaboration lives under `src/app/collab/**` and uses Trystero, Yjs, and awareness; preserve crypto-safe room IDs and peer cleanup.+- Across package/app boundaries import the owning package's public exports, never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus the subpaths listed in `packages/core/package.json`.+- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.+- Package aliases are `#core/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.+- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.## Code conventions-- Use Valibot for first-party runtime validation. MCP v2 registration uses Standard Schema with Valibot JSON Schema conversion; AI and WebMCP adapters share the Core tool input contract. Keep Zod only where upstream dependencies require it; do not maintain parallel first-party schemas in both libraries.--- Put code and tests in the established owning domain; inspect nearby structure before adding files.-- `bun run check:arch` enforces boundaries: use public workspace exports, keep Core framework-neutral, keep app services out of views/shared UI, and keep property-panel internals scoped to that panel.-- Follow the canonical [testing architecture](packages/docs/development/testing.md): package-local tests mirror source domains; central app tests mirror `src/app/**`; central integration requires a genuinely cross-owner contract. E2E follows user workflows; native and Figma acceptance remain explicit exceptions. Existing `tests/engine/**` domains migrate together with runner discovery—`tools/unit-tests/src/shards.ts` lists each owner's canonical home and its current `tests/engine` directories, so a move is a `git mv` plus imports; do not create competing homes or undiscovered suites. Owner-local helpers/fixtures stay local; only genuinely shared support is central. Specs use domain drivers/probes, not scattered Window/store traversal or unrestricted evaluator wrappers. Test contracts, not source text; never commit temporary/profile specs.--### File and folder naming--- App services/state/integrations live in `src/app/**`, views in `src/views/**`, and UI in `src/components/**`; `src/components/ui/**` is generic design-system code and must not import app stores/services.-- Component domains use lowercase/kebab-case folders; Vue files stay PascalCase and component composables camelCase. Do not add new PascalCase app folders or root-level base controls; migrate old ones when touched.-- Non-component folders/files use lowercase or kebab-case except standard entrypoints. Group multi-file domains in subfolders instead of repeated sibling prefixes (`selection/container.ts`, not `selection-container.ts`).--### Brand assets--Canonical brand artwork lives in `assets/brand/`: the main mark and an optical micro master. `tools/brand/` derives web/docs/native icons locally with RealFaviconGenerator and Tauri; generated assets are ignored, not committed. Vite/VitePress configs prepare their own targets, and Tauri dev/build hooks prepare native icons. Direct Cargo checks must run `bun run generate:icons --target desktop` first. Keep the app manifest in `vite/pwa.ts`, use `BrandMark` for in-app branding, and never symlink web assets to desktop icons. See `assets/brand/README.md` for commands and output ownership.--### Repo tools and scripts--Private tooling belongs under `tools/<domain>/{src,tests}`, with kebab-case domains and focused tests. `scripts/` may contain only tiny compatibility entrypoints; put real workflow, release, architecture, package, or visual tooling in `tools/`.--- Use `@/` for app cross-directory imports. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead. Package aliases are `#vue/*`, `#cli/*`, `#dom-css/*`, `#mcp/*`, and `#core/*`; prefer clear relative imports nearby.+- Put code and tests in the established owning domain; inspect nearby structure before adding files. Group multi-file domains in subfolders instead of repeated sibling prefixes (`selection/container.ts`, not `selection-container.ts`).+- Non-component folders and files use lowercase or kebab-case except standard entrypoints (`README.md`, `AGENTS.md`, `index.ts`). Component domains use kebab-case folders; Vue files stay PascalCase and component composables camelCase. Do not add new PascalCase app folders or root-level base controls; migrate old ones when touched.- No `any`, non-null assertions, or `Math.random()`; use precise types, guards, and `crypto.getRandomValues()`.-- Use the existing `dedent` package for multiline prompt composition and embedded examples instead of escaped newline strings. Keep substantial prompt prose in the owning Markdown source; compose it rather than duplicating it. Apply this convention across app, packages, and tools.-- Tooling must resolve the workspace with `resolveWorkspaceRoot` from `@open-pencil/package-artifacts`, not parent-directory traversal. Use domain aliases for cross-directory tooling imports, including tests; keep nearby sibling imports relative.-- Reuse named types and primitives from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke` shapes.-- Window API augmentations belong in the owning compilation boundary: app declarations in `src/global.d.ts`, package DOM gaps in the owning package's `global.d.ts`, and native-test declarations in `tests/helpers/tauri/native-global.d.ts`. Never put `declare global` in specs or implementation modules. Include canonical declarations through tsconfig instead of duplicating them.-- Keep app API contracts named and owned by their implementation domain; declaration files import those types. Derive vendor API types from top-level type imports rather than hand-copying signatures. Optional runtime globals remain optional and require a runtime guard.-- Native tests centralize invocation in a guarded test helper using vendor-derived types; do not import packages inside serialized WebView callbacks or repeat direct Tauri-global access in specs. Never expand production Window declarations just to accommodate test fixtures.-- Prefer test-runner-owned fixtures and request/route counters over browser globals. For in-page performance instrumentation, return a scoped `JSHandle` from `evaluateHandle()`; restore patched methods/listeners and dispose the handle in `finally`. Handles do not survive navigation. Assert transient DOM state with locators before the interaction ends when possible. Do not create a catch-all test Window interface or add ad-hoc counter properties to window.-- In Bun tests, prefer injected dependencies or scoped spies with explicit cleanup. `mock.restore()` restores spies but does not undo `mock.module()` overrides; do not assume module mocks are isolated by cleanup hooks. Read the installed runner's current lifecycle/mocking docs before introducing global or module-level instrumentation.-- Use `culori` for color conversion and existing dependencies before custom implementations.+- Valibot for first-party runtime validation. Keep Zod only where an upstream dependency requires it; never maintain parallel first-party schemas in both.+- Use existing dependencies before writing utilities: `culori` for color conversion, `es-toolkit` for focused helpers (without replacing clear native code), VueUse for browser, event, focus, clipboard, storage, and timer behavior (one-shot rAF or service-owned timers are fine when clearer), `dedent` for multiline prompt composition and embedded examples. Keep substantial prompt prose in the owning Markdown source and compose it.- Use `js-base64` directly for Base64: `fromUint8Array`/`toUint8Array` for bytes, `encode`/`decode` for text, and `isValid` before decoding input from outside (clipboard, imported files, tool arguments). Do not wrap it or use `atob`, `btoa`, or `Buffer` Base64 conversions; `open-pencil/no-hand-rolled-base64` enforces this.-- Prefer VueUse for common browser, event, focus, clipboard, storage, and timer behavior, but keep one-shot rAF or explicit service-owned timers when clearer.-- Components must not hold module-level mutable state. Share repeated logic/constants rather than copying it.-- Keep Kiwi runtime changes minimal; prefer wrappers for project policy.-- Guard browser globals explicitly in Core. Name repeated/cross-feature constants; app-wide values belong in `src/constants.ts`.-- The supported browser baseline lives in `src/app/shell/support/baseline.ts` and feeds the Vite `build.target`, the startup gate, and the documented system requirements; change all three together, including `desktop/tauri.conf.json` `minimumSystemVersion`. Vite lowers syntax but never polyfills APIs, so two data-driven checks enforce the baseline: the app and browser-shipped packages pin TypeScript `lib` to ES2023 (the last edition those engines implement fully), so newer built-ins fail type-checking, and `compat/compat` (`eslint-plugin-compat` under oxlint, fed the same browsers from `settings.browsers`) rejects Web APIs they lack. Do not raise the lib to `ESNext` in those tsconfigs; use `createDeferred()` from `src/app/runtime/deferred.ts` instead of `Promise.withResolvers()`. Node-only packages (`cli`, `mcp`, `harness`) are exempt from both. `tests/app/shell/support/baseline.test.ts` keeps the tsconfigs and oxlint browsers in step with the baseline. `src/main.ts` must stay a tiny gate that only dynamically imports `src/boot.ts`, so an unsupported engine can still render `src/app/shell/support/` guidance.--## Issue and PR writing--Use concise, concrete technical prose for issues, PR descriptions, and public comments. Lead with the problem and outcome; add a short example when needed to make the behavior clear. Avoid filler, promotional claims, decorative emojis, unnecessary tables, and file-by-file change inventories. Preserve the PR template's headings: Summary explains why and the outcome; What changed adds one to three non-repeated details; Validation reports actual commands/results and relevant omissions; AI assistance discloses known model names. Link lengthy logs or design notes rather than expanding the description into a work diary. Follow `CONTRIBUTING.md`; brevity must not omit reproduction steps, material risks, or validation limitations.--## Code review--- Review codebase fit, not just the diff. Before judging or implementing a change, inspect the owning folder, nearby analogous implementations, shared helpers/types, public exports, callers, and tests. Check new files against the established file tree, package boundaries, naming, and local conventions. Prefer an existing abstraction when it fits; do not invent a parallel pattern or demand unrelated cleanup.-- Verify findings against the current PR head and pinned dependency APIs. Give the concrete failing scenario and consequence; distinguish demonstrated bugs from defensive hardening and preferences. If runtime validation or dependency source is unavailable, state that limitation rather than treating an assumption as a fact.-- On re-review, check later commits and the discussion before repeating a finding. Mark addressed, obsolete, or intentionally declined suggestions accurately. Green checks and resolved threads are not substitutes for reviewing the current code.-- Request evidence appropriate to the change: engine tests for state contracts, Storybook for isolated component states, browser integration tests for workflows, canvas snapshots for rendering, and native tests for platform delivery. Do not claim one proves another.-- Preserve intentional behavior unless a concrete regression is demonstrated. For example, preferences and native credentials cannot transact together; documented partial-save outcomes and retryable drafts are not inherently bugs.-- Keep review comments concise and actionable. Cite the relevant location and repository rule or existing analogue for codebase-fit findings. Independently assess automated suggestions; do not bulk-apply or bulk-resolve them merely to make a bot green.--## Code quality--Before submitting a PR, run the complete gate and relevant tests:--```sh-bun run check-bun run format-bun run test:unit-bun run test-```--Self-review for duplication, named shared types, precise unions, and files approaching ~600 lines. Use `structuredClone` or typed copy helpers for nested mutable data. Check existing dependencies before implementing utilities; `es-toolkit` is available for focused helpers without replacing clear native code. Read current Reka UI, VueUse, and Tailwind/tailwind-variants docs before inventing UI primitives or composables, and update local wrappers deliberately when upstream APIs changed.+- Browser-shipped code targets the supported browser baseline in `src/app/shell/support/baseline.ts`: TypeScript `lib` stays ES2023 and `compat/compat` rejects missing Web APIs; Node-only packages (`cli`, `mcp`, `harness`) are exempt. Details in `src/AGENTS.md` (Browser baseline).+- Components must not hold module-level mutable state. Name repeated or cross-feature constants; app-wide values belong in `src/constants.ts`.+- Window API augmentations belong to the owning compilation boundary: `src/global.d.ts` for the app, the package's `global.d.ts` for package DOM gaps, `tests/helpers/tauri/native-global.d.ts` for native tests. Never put `declare global` in specs or implementation modules; include canonical declarations through tsconfig. Keep app API contracts named and owned by their implementation domain; derive vendor API types from top-level type imports. Optional runtime globals stay optional and need a runtime guard.+- Use `structuredClone` or typed copy helpers for nested mutable data. Self-review for duplication, named shared types, precise unions, and files approaching ~600 lines.+- Detect desktop with `IS_TAURI`, never ad-hoc `__TAURI_INTERNALS__` checks.### Dependency documentation-Before using an unfamiliar dependency API or writing a replacement utility, inspect existing project wrappers and read the relevant official documentation. Start with the indexes below, then fetch specific pages rather than entire `llms-full.txt` dumps. Match documentation to versions in the package manifests and lockfiles; verify signatures against installed types/source when versions differ. Do not guess APIs or invent primitives already supplied by dependencies.+Before using an unfamiliar dependency API or writing a replacement, inspect existing project wrappers and read the official documentation. Start with these indexes, then fetch specific pages rather than entire `llms-full.txt` dumps. Match versions in the manifests and lockfile; verify signatures against installed types when versions differ. Do not guess APIs or invent primitives already supplied by dependencies. Read current Reka UI, VueUse, and Tailwind/tailwind-variants docs before inventing UI primitives or composables, and update local wrappers deliberately when upstream APIs changed.| Dependency | Official documentation entrypoint || ---------------------------- | ---------------------------------------------------------------------------------------------- |@@ -229,118 +77,44 @@ Before using an unfamiliar dependency API or writing a replacement utility, insp| es-toolkit | https://es-toolkit.dev/llms.txt || CanvasKit | https://skia.org/docs/user/modules/canvaskit/ and installed `canvaskit-wasm/types/index.d.ts`. |-VueUse currently serves HTML homepage content at its `llms.txt` URL; Tailwind CSS and Skia have no verified index there. Use their official documentation above instead. If an index disappears or returns HTML, fall back to official API documentation, not guessed methods or unofficial generated indexes.--### Native WebView tests--Native desktop interaction checks live under `tests/e2e/native/**` and run through WebdriverIO against an explicit test-only Tauri binary. Use `bun run test:native` to build and run them, or `bun run build:native-test` when only the binary is needed. The embedded WebDriver plugin is compiled only with the `native-test` Cargo feature and must never be enabled in normal development or production binaries.--Native-test builds use a separate application identifier, an ephemeral WebView data store, and process-memory credentials. Never run UI smoke tests against production Keychain entries or clear user recovery data to unblock tests. Tests requiring persistence across application restarts need a dedicated test-owned persistent profile rather than the default ephemeral profile.--Keep responsibilities distinct: engine tests cover state contracts, Playwright browser E2E covers application integration, and native tests answer only whether the real platform WebView and Tauri shell deliver an interaction correctly. Platform-limited checks must skip rather than claim coverage. Synthetic composition tests do not prove real IME behavior, and native clipboard behavior remains a separate acceptance gap unless the test receives trusted OS clipboard events.--## Rendering+VueUse serves HTML at its `llms.txt` URL; Tailwind CSS and Skia have no verified index. If an index disappears or returns HTML, fall back to official API documentation, not guessed methods or unofficial generated indexes.-- Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM-- Bounded rendering caches share `packages/core/src/cache/resource.ts` for recency, count/weight accounting, and removal disposal. Domain adapters own keys, font/page/dependency invalidation, and sizing units; use non-touching `peek()` for FIFO/planning reads. Rejected insertions leave ownership with the caller. Keep weak memos, async request registries, pools, and dependency-owned picture/path maps on their distinct lifetime policies.-- `renderVersion` vs `sceneVersion`: `renderVersion` = canvas repaint (pan/zoom/hover); `sceneVersion` = scene graph mutations. UI that only cares about graph data should avoid watching repaint-only state; use editor events for incremental surfaces such as the layer tree.-- Live property controls use selected-node projections from `editor/selection-state/nodes.ts`: shallow reactive copies receive `node:previewUpdated` patches at property granularity. Never add preview invalidation to all `useSceneComputed` consumers; catalogs and unrelated controls must not refresh for geometry previews. Projection subscriptions belong to the consuming scope/session and must be disposed.-- Numeric geometry edits own a `beginNodePreview()` handle with `update`, `commit`, and `cancel`. It captures all affected fields/layout children, publishes the complete delta once, and restores exact originals on cancellation. Selection/page/graph changes and disposal cancel the old edit; trailing input must not target the new selection. Controls must close previews even when a gesture returns to its starting value.-- Renderer interaction policy uses explicit `beginInteractiveEdit()` leases and `isInteractiveEditing()`, not undo batching. Release leases on every terminal path. Keep live queries callable across app facades that spread editor actions.-- Drawing and input share preview-aware geometry through `@open-pencil/core/geometry`, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement instead of independently interpreting ancestor rotations or reflections. LINE pivots remain at the origin; other nodes rotate around their centers.-- Label drawing and hit testing share `canvas/labels/{layout,transform,style}.ts`, including paragraph measurements and unreflected label axes. Rotation previews change through `setRotationPreview()` and `rotation:preview-changed`; cancellation must close the owning gesture without deselecting or committing it.-- Paragraph construction is typed against `canvas/text/paragraph-inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.-- `requestRender()` bumps `renderVersion` and `sceneVersion`; `requestRepaint()` bumps only `renderVersion`-- `renderNow()` is only for surface recreation and font loading (need immediate draw)-- Resize observer uses rAF throttle, not debounce — debounce causes canvas skew-- Overscan images accelerate navigation; settled scenes rasterize existing retained pictures at the live viewport size/origin. Pixel-grid alignment alone does not guarantee Skia AA parity. Keep settlement pending until the viewport pass completes; do not add a second viewport image cache.-- Viewport culling skips off-screen nodes; unclipped parents are NOT culled (children may extend beyond bounds)-- Selection border width must be constant regardless of zoom — divide by scale-- Section/frame title text never scales — render at fixed font size, ellipsize to fit-- Rulers are rendered on the canvas (not DOM), with selection range badges that don't overlap tick numbers-- Remote cursors: Figma-style colored arrows with white border + name pill, rendered in screen space-- Pixel-affecting renderer features need committed visual coverage, not just mock/geometry assertions. Add or update a Playwright canvas snapshot for changes to fills, gradients, images, blend modes, masks, boolean geometry, corners, strokes, shadows, blur, text rendering, or demo showcase scenes. Use targeted snapshot updates such as `bun run test tests/e2e/canvas/fill-modes-visual.spec.ts --update-snapshots` and then rerun the same test without `--update-snapshots`.+## Tests-## Scene graph+Follow `packages/docs/development/testing.md` and `tests/AGENTS.md`. Package-local tests mirror source domains; central app tests mirror `src/app/**`; central integration requires a genuinely cross-owner contract. Test contracts, not source text; never commit temporary or profile specs. Pixel-affecting renderer changes need committed canvas snapshots; simple CSS-only UI changes need visual verification, not new automated tests.-- Nodes live in a flat `Map<string, SceneNode>`; runtime hierarchy uses `parentId` and `childIds`.-- Frames do not clip by default.-- Sort children geometrically before creating auto-layout. Dragging outside a frame reparents; groups preserve child world positions.-- Layer trees must react to reparenting rather than retaining stale child references.+## Documentation and changelog-## Components & instances+- `CHANGELOG.md` — curated user-facing changes by version; `Unreleased` stays first. `README.md` — concise features, setup, CLI, and overview. `AGENTS.md` files — contributor/agent rules. `packages/docs/` — public site (`packages/docs/AGENTS.md`). Keep internal plans in ignored `scratch/`.+- For user-facing work add one present-tense outcome under the single appropriate `Unreleased` category: `Breaking changes`, `Added`, `Changed`, `Fixed`, `Performance`, or `Security`. Treat it as release notes: omit tests, benchmarks, CI, internal refactors/tooling, and bugs both introduced and fixed since the last release. End sentences with periods and retain issue/PR references. Update `README.md` when appropriate and the owning `AGENTS.md` when architecture or conventions change.+- After merges, compare the whole section with changes since the latest release, preserve important outcomes, consolidate related work, and remove duplicate bullets and headings.+- Before finalizing `Unreleased`: compare released behavior at the latest tag with the final implementation, not commit subjects; verify questionable fixes existed at that tag and fold fixes to newly added features into the feature bullet; check public exports, model/config/data contracts, and peer requirements for `Breaking changes`; remove superseded intermediate behavior; state platform requirements and concrete supported behavior instead of unqualified claims; run `bun run check:changelog`. Keep historical sections unchanged.-- Component types use `#9747ff`.-- Instance children map to component children through `componentId`; runtime overrides use structured `InstanceOverrideState` (`self` and `descendants` maps).-- Component edits must propagate through editor/component sync—never hand-copy properties in app UI. Use Scene Graph copy helpers for nested values.+## Commits, PRs, and issues-## Layout+`CONTRIBUTING.md` is canonical for commit messages, PR titles and bodies, and attribution. Digest:-- Recompute layout after demo creation and for each materialized/imported page; scope computation to the affected page/subtree where possible.-- `@open-pencil/yoga-layout` supplies both flexbox and CSS Grid.-- The first Hug/Fill dimension mutation switches only that axis to Fixed; focus is non-destructive, and mode/value changes share one undo transaction.+- Conventional Commits (`feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, `chore`); short imperative subjects, rationale in the body; release commits are exactly `Release vX.Y.Z`. Preserve product casing: DOM/CSS, HTML, JSX, Tailwind, Kiwi, `.fig`, MCP, CLI, AI, ACP, i18n. Validate with `bun run check:commits --last` or `--from`/`--to`.+- PR titles are Conventional Commits because GitHub uses them as merge subjects; branch-update merges get explicit subjects such as `chore: merge master into <branch>`. Do not rewrite published history solely to normalize messages.+- Disclose AI assistance in the PR's AI assistance section, never as commit authorship, `Co-authored-by` trailers, promotional signatures, or session links. Preserve human co-author credits and third-party notices.+- Issues, PR descriptions, and public comments use concise concrete technical prose: lead with the problem and outcome, add a short example when needed, avoid filler, promotional claims, decorative emojis, unnecessary tables, and file-by-file inventories. Link long logs or design notes.-## UI--### Component structure--- Generic UI is grouped by component family under `src/components/ui/{button,input,select,toggle,dialog,panel,binding,feedback,overlay,menu,paint}/`; do not create a folder named after a single component. Theme families mirror these under `src/theme/`; feature themes remain separate. Use explicit imports without old-path forwarding shims.-- Colocate `ComponentName.stories.ts` with `ComponentName.vue`. Multipart composition stories may use a descriptive family name. Preserve explicit Storybook titles and exported story names during file moves; keep default playgrounds static and give interaction flows named stories. Prefer inline story fixtures for small app-local states. Use colocated `examples/<Variant>.vue` SFCs for substantial templates or fixtures that need SFC template/slot typing, including app-only fixtures; shared SDK examples use the same convention (see below). Story templates compile at runtime, so they must be plain JavaScript — no type assertions or other TypeScript syntax — and `icon-lucide-*` tags do not resolve there; import icons from `~icons/...` and register them.-- `src/components/ui/**` is store-free app design-system code; feature controls stay in their domain.-- SDK property primitives remain controlled/editor-agnostic. Compose property rows from `PanelGrid`, `PanelFieldGroup`, `PanelItemRow`, and `PropertyItemRow`; use `BindableValue`, `FillRoot`, and `FillSwatch` rather than rebuilding binding/picker infrastructure.-- Do not add automated tests or snapshot baselines for simple CSS-only UI changes, including spacing, sizing, colors, and responsive breakpoints. Verify these visually instead. Keep automated coverage focused on behavior and contracts; the separate canvas-renderer visual coverage requirement still applies.-- Prefer accessible role/name, label, then text in tests. Use scoped `data-slot` anatomy or semantic attributes (`data-property`, `data-command`, `data-node-id`) when needed; reserve `data-test-id` for integration boundaries and never add test-hook props.-- Use Reka UI primitives and typed Tailwind Variants themes under `src/theme/**`; merge per-instance `ui` slot overrides, expose `class` for single-root components, and do not add one-off class props. Use `UI` casing in type names.-- Bind visual state through semantic `data-*` attributes; Steiger rejects template-time `use*UI()`, visual-state utility branches, and raw SVG app icons.-- Storybook is the internal state workshop; VitePress is canonical public SDK documentation. Derive API tables from source/JSDoc and keep examples valid against public exports. An example shared by Storybook and a docs page lives in `packages/vue/src/primitives/<Primitive>/examples/<Variant>.vue` (PascalCase variant name, e.g. `States.vue`); the story renders it and the docs page imports it with `#vue/primitives/...`. Do not render Storybook stories inside VitePress pages: `@storybook/vue3` assigns `window.STORYBOOK_ENV` on import so it cannot be server-rendered, the docs bundle ships runtime-only Vue so runtime templates silently fail, and a client-only embed drops examples from the prerendered HTML while adding the Storybook preview runtime and `storybook/test` to the published docs.-- Prefer models/events/props over imperative slot actions except for explicitly renderless action primitives. Use VueUse for DOM refs/focus.-- App wrappers around SDK primitives use shared UI helpers rather than scattered raw classes.-- Commands use `packages/vue/src/editor/commands/registry.ts` for shortcuts, bindings, and menu IDs. Store portable tokens (`MOD+D`) and format them at render time; labels/translations never contain shortcuts.-- i18n uses narrow product-domain catalogs under `packages/vue/src/i18n/messages/` with matching locale files. Inspect existing domains instead of adding generic UI/component namespaces; prefer narrow `use*Messages()` composables over aggregate `useI18n()`.-- `check:i18n` enforces structure, placeholder parity, and reviewed translation baselines. Remove stale baseline identities when fixing existing debt.-- Canvas menu structure lives in `packages/vue/src/editor/menu-model/canvas.ts`; `CanvasMenu.vue` renders it.-- Browser/native menus share `src/app/shell/menu/schema.ts`; handle IDs in `use.ts` or editor commands, and regenerate `desktop/generated/menu.json` with `generate:tauri-menu`.-- Use Tailwind 4 and `tw-animate-css`; no static inline styling or component `<style>` blocks. Dynamic `:style` bindings are allowed for runtime geometry/CSS variables.-- Use `Tip`, not native `title`; Lucide/Iconify components, not raw SVG/Unicode icons; and `e.code`, not `e.key`, for modified shortcuts.-- Binding-aware fields detach/mutate only on the first value change; opening/focusing is non-destructive.-- Preserve nearby interaction gotchas when refactoring: splitter handles, NumberField pointer ownership, section dragging, panel containment, and number-spinner styling.--### Feedback and form submission--- Use `AppAlert` (`src/components/ui/feedback/AppAlert.vue`) for persistent contextual errors, warnings, recovery guidance, and informative results. Its typed theme lives in `src/theme/feedback/alert.ts`; use translated `heading`/`description` and the `actions` slot for recovery controls. Do not hand-roll feature-level alert markup or colored error paragraphs.-- Use the existing toast service for transient confirmations such as copying or completing an action after its view closes. Do not show both a toast and an alert for the same event. Partial saves and actionable failures must not disappear in a toast.-- Field validation stays inline in the shared field component, with `aria-invalid`, associated error text before hints, and first-invalid-field focus. VeeValidate owns validation and form submission state; domain workflows retain their own pending/lifecycle guards for external operations. A credential-store failure does not make the entered key invalid.-- Settings save feedback uses `SettingsSaveFeedback`, which maps domain outcomes to `AppAlert`. Keep persistence outcomes (`saved`, `failed`, `partial`) in the domain: a form library cannot make preferences and a native credential store transactional. Preserve retryable drafts, reuse already-persisted identities on retries, and show the partial-save warning. Never render raw credential backend errors or secrets.-- Use `SettingsLink` for external Settings links, including provider key pages and setup guides. It owns link styling, the external-link icon, and native opening behavior. Keep arrow glyphs out of translated labels.-- Ordinary labels such as Running/Stopped remain status text or badges, not alerts. Destructive confirmation belongs in the shared confirmation dialog. Alerts announce changes without taking keyboard focus.-- Isolated feedback-component visual states belong in colocated Storybook stories, not Playwright application screenshots. Settings E2E tests cover integration behavior: when feedback appears, validation/focus, retained drafts, and successful retries.--### Animations--Motion policy lives in `src/app/shell/motion/`: resolve persisted System/Off preference and OS reduction once. The root `data-motion` attribute and the app's Tailwind `motion-safe`/`motion-reduce` variants represent this effective policy, including portalled content. Store-free presets/treatments live in `src/theme/motion/`; compose them into owning themes. Use the policy-aware Motion adapters for shared or feature-specific transitions rather than repeating preference conditionals in components. Keep what moves, geometry, and genuinely feature-specific spring values local.--- Use Tailwind transitions and `tw-animate-css` for simple visual state changes and enter/exit animations. Use the existing `motion-v` dependency for gesture-driven motion, coordinated layout changes, and springs; do not add another animation library.-- Use Reka state attributes and measured CSS variables for collapsibles. The utilities are `animate-collapsible-down` and `animate-collapsible-up`; keep padding and borders inside the animated height wrapper so they do not snap during collapse.-- Respect `prefers-reduced-motion` in both CSS and Motion. Disable or simplify nonessential motion while preserving state changes and interaction feedback.-- Keep reusable animation styling in the owning theme and share repeated duration/easing values rather than scattering timing constants across components.-- Verify opening and closing, interrupted transitions, reduced motion, and scroll behavior. Expanding historical chat content must not force the transcript to the bottom.--## File format+## Code review-- Figma clipboard envelope encoding, decoding, bounds, and SceneGraph import conversion belong to `@open-pencil/fig/clipboard`. Core prepares runtime fonts/text and owns editor placement/history; browser/Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs to Fig.-- Kiwi schema/runtime/codec/container helpers live in `@open-pencil/kiwi`; complete archive parsing and SceneGraph conversion live in `@open-pencil/fig`; Core owns format-neutral orchestration, runtime fonts/workers, and thumbnails.-- Vector networks use the reverse-engineered `vectorNetworkBlob`; codecs live under `packages/core/src/vector/` and types in Scene Graph.-- File System Access APIs are browser APIs, not Tauri-only. Keep Safari download fallback and defer `revokeObjectURL`.-- Detect desktop with `IS_TAURI`, never ad-hoc `__TAURI_INTERNALS__` checks.-- Browser FIG export uses fflate/`@open-pencil/fig`; Tauri uses `build_fig_file`.-- Changes to `.fig` behavior require round-trip validation in Figma. Fixtures under `tests/fixtures/*.fig` use Git LFS; use normal `git push` when they change.+- Review codebase fit, not just the diff. Inspect the owning folder, nearby analogous implementations, shared helpers and types, public exports, callers, and tests. Prefer an existing abstraction when it fits; do not invent a parallel pattern or demand unrelated cleanup.+- Verify findings against the current PR head and pinned dependency APIs. Give the concrete failing scenario and consequence; distinguish demonstrated bugs from hardening and preferences. State when runtime validation or dependency source was unavailable.+- On re-review, check later commits and the discussion before repeating a finding. Green checks and resolved threads are not substitutes for reviewing the current code.+- Request evidence appropriate to the change: engine tests for state contracts, Storybook for isolated component states, browser integration tests for workflows, canvas snapshots for rendering, native tests for platform delivery. One does not prove another.+- Preserve intentional behavior unless a concrete regression is demonstrated; for example, preferences and native credentials cannot transact together, so documented partial-save outcomes and retryable drafts are not bugs.+- Keep comments concise and actionable; cite the location and the repository rule or existing analogue. Independently assess automated suggestions; never bulk-apply or bulk-resolve them to make a bot green.-## Tauri+## Maintaining these guides-- Tauri v2 desktop app lives under `desktop/`; check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.json` before adding desktop capabilities.-- File system and shell permissions must be configured explicitly; vague "Internal error" save failures often mean missing permissions.-- Dev tools: add or use a menu item to toggle, don't rely on keyboard shortcuts.+- One rule per bullet, at most three sentences, ending with its anchor: the enforcing check, the analogous file, or the test. A rule that can become a lint, `check:arch` boundary, or type-level test should become one, and the prose is then removed.+- A rule lives in exactly one guide: here if it applies across the repository, otherwise in the nearest `AGENTS.md` of the owning folder. Explanations belong in `packages/docs/development/`, not in guides.+- Every nested `AGENTS.md` is listed in the Map above; `bun run check:docs` fails on an unlisted or missing guide. Nested guides are classified as documentation by CI.+- When a section here passes about ten lines, move it to a domain guide and leave the map row.## Reference-[`figma-use`](https://github.com/dannote/figma-use) is historical context only; verify current paths, types, and behavior before adapting anything.+[`figma-use`](https://github.com/dannote/figma-use) is a historical code reference and a live-Figma oracle (`packages/core/AGENTS.md`, Figma API); verify current paths, types, and behavior before adapting anything from it.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 95f7aa9a8..1ca97ab89 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@- Render the Medium, Semibold, Bold, and other styles of variable fonts at their named weights instead of drawing Regular or a synthetic bold.- Load the Bold, Medium, and other styles of macOS system fonts packaged as font collections, such as Menlo, Helvetica Neue, and Avenir Next, instead of reporting them as substituted or drawing a different style (#746).- Load the Medium, Semibold, Bold, and other styles of installed variable fonts such as SF Pro on macOS instead of reporting them as substituted (#752).+- Ship the MIT license text in every published npm package, and add READMEs for `@open-pencil/core`, `@open-pencil/cli`, and `@open-pencil/mcp` on npm.### Security@@ -646,7 +647,6 @@- Fix component property override resolution through clone chains.- Fix text/property overrides clobbered by second transitive sync.-- Fix text rendering with wrong fonts on file open — all font weights (including default family) are now loaded before the first render.- Fix `weightToStyle` mapping: weight 400 now correctly maps to "Regular" instead of "Medium".- Fix detached ArrayBuffer crash when switching pages after saving — export worker now copies image buffers before transferring.@@ -770,7 +770,6 @@- Add `geometry.ts` with shared rotation math (`degToRad`, `radToDeg`, `rotatePoint`, `rotatedCorners`, `rotatedBBox`).- Extract `isArrayMixed()` helper for multi-selection property panels.-- Add `motion-v` for declarative animations — used in mobile drawer (spring-animated height with pan gestures) and toolbar (layout-animated category switching with directional slide transitions).- Mobile drawer: replace `useSwipe` + manual rAF animation with `motion.div` `:animate` + `@pan`/`@panEnd`; always-on tab state (no more null `activeRibbonTab`); content stays rendered when closed.- Mobile toolbar: replace manual `scrollWidth` measuring + inline CSS transitions with `motion.div layout` + `AnimatePresence` directional slide variants.@@ -921,18 +920,15 @@- Fix font picker dropdown truncating long font names.- Show explanation in font picker when Local Font Access API unavailable (Safari/Firefox).-- Auto-populate GitHub Release notes from CHANGELOG.md via `ffurrer2/extract-release-notes@v2`.- Skip already-published npm versions on CI re-runs instead of failing.- Exclude non-app directories from Vite file watcher.-- Extract shared color constants (`BLACK`, `TRANSPARENT`, `DEFAULT_SHADOW_COLOR`) — replaces 8 inline literals across core.- Extract shared `NodeContextMenuContent` component to avoid menu duplication.- Fix `@open-pencil/core` dep in MCP package: `workspace:*` for local dev (pnpm resolves at publish time).- Replace store thunks with a late-binding proxy.-- Clipboard roundtrip tests: encode to Figma Kiwi binary → decode → verify.- 9 visual regression snapshot tests for effects rendering.- Zoom/pan E2E tests and pipeline benchmark.@@ -964,7 +960,6 @@- Import additional properties from Figma clipboard: `layoutAlignSelf`, `clipsContent`, `fontWeight`, `italic`, `letterSpacing`, `lineHeight`.- Convert `letterSpacing` PERCENT units to pixels based on font size.-- 7 new clipboard import unit tests (14 total).### Fixed@@ -1104,13 +1099,11 @@ First public alpha. The editor is functional but not production-ready.- ScrubInput drag-to-change number controls.- Resizable side panels via reka-ui Splitter.-- .fig file import via Kiwi binary codec (194 definitions, ~390 fields).- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation.- Figma clipboard: copy/paste between OpenPencil and Figma.- Round-trip fidelity for supported node types.-- Built-in AI chat in properties panel (⌘J).- Direct browser → OpenRouter communication, no backend.- Model selector: Claude, Gemini, GPT, DeepSeek, Qwen, Kimi, Llama.@@ -1118,12 +1111,10 @@ First public alpha. The editor is functional but not production-ready.- Streaming markdown responses (vue-stream-markdown).- Tool call timeline with collapsible details.-- JSX export of selected nodes with Tailwind-like shorthand props.- Syntax highlighting via Prism.js.- Copy to clipboard.-- `info` — document stats, node types, fonts.- `tree` — visual node tree.- `find` — search by name/type.@@ -1138,25 +1129,21 @@ First public alpha. The editor is functional but not production-ready.- `analyze clusters` — repeated patterns.- All commands support `--json`.-- Scene graph with flat Map storage and parentIndex tree.- FigmaAPI with ~65% Figma plugin API compatibility.- JSX renderer (TreeNode builder functions with shorthand props).- Kiwi binary codec (encode/decode).- Vector network blob encoder/decoder.-- Tauri v2 (~5 MB).- Native menu bar, save/open dialogs.- System font enumeration via font-kit.- Zstd compression in Rust.- macOS and Windows builds via GitHub Actions.-- Runs at [app.openpencil.dev](https://app.openpencil.dev).- No installation required.- File System Access API for save/open (Chrome/Edge), download fallback elsewhere.-- [openpencil.dev](https://openpencil.dev) — VitePress site with user guide, reference, and development docs.- Deployed via Cloudflare Pages.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 54cbff1a7..4271c6694 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,25 +1,53 @@# Contributing-Questions and ideas go to [GitHub Discussions](https://github.com/open-pencil/open-pencil/discussions) or [Discord](https://discord.gg/4wXc9fuZfm); open an issue for a reproducible bug.+Questions and ideas go to [GitHub Discussions](https://github.com/open-pencil/open-pencil/discussions) or [Discord](https://discord.gg/4wXc9fuZfm); open an issue for a reproducible bug. Report security problems through a [private advisory](https://github.com/open-pencil/open-pencil/security/advisories/new), not a public issue or PR.++## Where the rules live++- `CONTRIBUTING.md` (this file): setup, pull requests, validation, commits.+- [`AGENTS.md`](./AGENTS.md): repository map, cross-cutting conventions, and a `Guide` column pointing to the `AGENTS.md` inside each package or app domain. Read the root file and every guide on the path to the folder you change; coding agents pick them up the same way.+- [`packages/docs/development/`](packages/docs/development/): public explanations such as [architecture](https://openpencil.dev/development/architecture), [testing](packages/docs/development/testing.md), and the [roadmap](packages/docs/development/roadmap.md).## Setup-```bash+```shgit clone https://github.com/open-pencil/open-pencil.gitcd open-pencilbun install+bun run dev:portless # Web editor at https://open-pencil.localhost+bun run dev # Fixed http://localhost:1420 for Playwright, Tauri, and Dev Containers+bun run tauri dev # Desktop app (requires Rust)```-## Development+The first Portless run creates and trusts a local HTTPS certificate. Linked Git worktrees receive branch-prefixed URLs such as `https://fix-ui.open-pencil.localhost` and matching `https://fix-ui.mcp.open-pencil.localhost` MCP bridges with isolated ports and socket files, so concurrent servers do not compete for port 1420. Run `bunx portless doctor` if routing or certificate trust fails.-```bash-bun run dev # Vite dev server on localhost:1420-bun run tauri dev # Tauri desktop app with hot reload+The repository also works in any [Dev Container](https://containers.dev/)-compatible tool: the container pins Bun, installs dependencies, and forwards port 1420; start with `bun run dev`. It covers the web editor, packages, CLI, and automated checks. Native Tauri development needs [Rust](https://rustup.rs/) and the [Tauri v2 prerequisites](https://v2.tauri.app/start/prerequisites/) on the host.-# For macOS release builds with ad-hoc signing (no Apple Developer account, local testing only):+For macOS release builds with ad-hoc signing (no Apple Developer account, local testing only):++```shAPPLE_SIGNING_IDENTITY=- bun run tauri build -c '{"bundle": { "createUpdaterArtifacts": false }}'```+## Making a change++- Before adding a helper, type, component, state mechanism, parser, or test utility, inspect the owning folder, nearby implementations, existing dependencies, and tests. Reuse or extend the established mechanism; extract genuinely shared logic instead of introducing a parallel implementation.+- Keep package boundaries and public exports intact. Keep pull requests focused: no temporary scaffolding, unrelated refactors, or changelog claims not represented by the diff.+- Update `CHANGELOG.md` for user-facing changes following the rules in `AGENTS.md` (Documentation and changelog).+- Tests follow the [testing architecture](packages/docs/development/testing.md) and `tests/AGENTS.md`. Extend an existing `tests/engine/**` suite until its domain migrates; do not create a duplicate home.+- `.fig` fixtures in `tests/fixtures/` are Git LFS. Use `git push --no-verify` to skip the slow LFS pre-push hook unless you changed `.fig` files.++## Quality checks++Run all of these before submitting a PR:++```sh+bun run check # lint, type checks, architecture, docs, package, duplication, and tooling checks+bun run format # oxfmt with import sorting+bun run test:unit # bun:test engine/unit suite (test:unit:quick for the fast parallel loop)+bun run test # Playwright browser E2E and visual regression+```+## Pull requestsPull requests must be reviewable without guessing the author's intent.@@ -32,8 +60,7 @@ Pull requests must be reviewable without guessing the author's intent.### PR body-- Follow the PR template when one is provided.-- Keep the existing template headings. Use one short Summary paragraph for the problem, why it matters, and the outcome. Use What changed for one to three meaningful implementation details, not a repeated summary or a file-by-file inventory.+- Follow the PR template and keep its headings. Use one short Summary paragraph for the problem, why it matters, and the outcome. Use What changed for one to three meaningful implementation details, not a repeated summary or a file-by-file inventory.- Write concrete, direct prose. Avoid promotional claims, filler, decorative emojis, and unnecessary tables. Add a small example when the behavior is otherwise hard to explain; keep lengthy logs or design notes in linked material.- Document commands actually run and their results, such as `bun run check`, targeted tests, or docs-only review. State relevant checks not run and why, and note whether a changelog entry is needed. Do not present planned validation as completed.- Complete the AI assistance section. If an LLM materially helped create or modify the PR, list the model names you know. Write `None` otherwise. This is review context, not authorship attribution; prompts and transcripts are not required.@@ -45,68 +72,8 @@ Do not submit placeholder PRs. Remove template comments before opening a PR. DoCodeRabbit may flag PR description or readability issues for maintainers to review. Missing template sections or validation details are normal review feedback; they are not, by themselves, a personal judgment on the contributor. Maintainers may close PRs manually when they are clearly automated, not written in English, unrelated to the project, or impossible to review without substantial guesswork. If you are unsure how to fix something, please open a detailed issue instead of submitting a placeholder PR.-## Quality checks--Run all of these before submitting a PR:--```bash-bun run check # lint, type checks, architecture, package, duplication, and tooling checks-bun run format # oxfmt with import sorting-bun run test:unit # bun:test engine/unit suite-bun run test # Playwright browser E2E and visual regression-```--## Project structure--OpenPencil is a Bun monorepo. Stable ownership boundaries are:--- `packages/scene-graph`, `pen`, `kiwi`, and `fig` — framework-neutral document models and format layers.-- `packages/core` — renderer, layout, editor core, Figma API, tools, and app-facing document I/O.-- `packages/dom-css` and `vue` — DOM/CSS projection and the headless Vue SDK.-- `packages/cli`, `mcp`, and `harness` — automation and agent-facing entry points.-- `src/app` — app services, state, and integrations; `src/components` and `src/views` — app UI and views.-- `packages/docs` — the published VitePress site.--See [`AGENTS.md`](./AGENTS.md) for canonical package ownership and architecture rules, and [Architecture](https://openpencil.dev/development/architecture) for the public overview.--## Codebase fit--Before adding a helper, type, component, state mechanism, parser, or test utility, inspect the owning domain, nearby implementations, existing dependencies, and tests. Reuse or extend the established mechanism; extract genuinely shared logic instead of introducing a parallel implementation.--Keep package boundaries and public exports intact. Keep pull requests focused: exclude temporary or development scaffolding, unrelated refactors, and changelog claims that are not represented by the diff.--## Tests--Follow the [testing architecture](packages/docs/development/testing.md) for ownership, helpers, fixtures, browser adapters and migration rules. Package-local tests mirror their source domains; central integration is reserved for genuinely cross-owner contracts. E2E follows user workflows rather than implementation files.--Existing `tests/engine/**` coverage moves domain-by-domain with runner discovery, not opportunistically during feature work. Extend the existing home until that migration; do not create a duplicate suite. Test behavior and stable contracts, not source text. During iteration, run focused checks for the changed contract rather than the complete suite after every edit.--### Test selectors--Playwright tests should locate behavior the way users and assistive technology do: prefer roles and accessible names, labels, and visible text. Scope repeated controls to a named region. Multi-part components expose local `data-slot` anatomy, while stable app concepts may expose semantic attributes such as `data-property`, `data-command`, or `data-node-id`.--Reserve `data-test-id` for integration boundaries that have no meaningful user-facing or domain identity. Do not add test-ID props to reusable components or generate compound IDs from component nesting.--## Conventions--See [`AGENTS.md`](./AGENTS.md) for the full architecture reference, code conventions, and quality checklist. Key points:--- Bun runtime, not Node.-- Tailwind 4 for styles; no inline CSS or component `<style>` blocks.-- No `any` or non-null assertions; use guards and precise types.-- Use public package exports across package boundaries.-- Use `crypto.getRandomValues()`, never `Math.random()`.-- Use existing dependencies and Reka UI components before hand-rolling.-- Keep UI labels translatable and shortcuts in the shared command registry.--## Test fixtures--`.fig` fixtures in `tests/fixtures/` are Git LFS. Use `git push --no-verify` to skip the slow LFS pre-push hook unless you changed `.fig` files.-## Commits-Follow the commit-message conventions in [`AGENTS.md`](./AGENTS.md). Update `CHANGELOG.md` for user-facing changes.-### AttributionAI-assisted contributions are welcome. Credit human collaborators in commit authorship and `Co-authored-by` trailers; don't add AI assistants as co-authors or append tool-generated promotional signatures. Record AI assistance in the PR's existing AI assistance section instead. Preserve human attribution and required third-party notices.@@ -119,11 +86,11 @@ The Commit messages check flags known AI co-author identities in newly introduceThe **Commit messages** CI job checks every commit introduced by a PR, including docs-only PRs. It does not lint existing base-branch history or GitHub's synthetic merge commit. The aggregate CI result requires this job to pass.-Use `type(optional-scope): short description`, for example `fix(MCP): preserve connection settings`. Allowed types are `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, and `chore`. Keep headers within 100 characters and omit a trailing period. Product names retain their casing; bodies and footers may contain long lines.+Use `type(optional-scope): short description`, for example `fix(MCP): preserve connection settings`. Allowed types are `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, and `chore`. Keep subjects short, imperative, and narrowly scoped; explain rationale in the body. Keep headers within 100 characters and omit a trailing period. Product names retain their casing (DOM/CSS, HTML, JSX, Tailwind, Kiwi, `.fig`, MCP, CLI, AI, ACP, i18n); bodies and footers may contain long lines. Release commits use exactly `Release vX.Y.Z`.PR titles follow the same convention because GitHub uses them as merge subjects. The separate **PR title** workflow checks new and updated PRs, including title edits, without rerunning the full CI suite. Title validation disables commitlint's default merge/revert exceptions. Release titles and commits retain the exact `Release vX.Y.Z` convention.-Commit-range validation retains commitlint's default merge/revert exceptions, but they are not a naming convention. Preserve the validated PR title when merging via CLI/API, and use explicit conventional subjects for branch updates, for example `chore: merge master into my-branch`. Do not rewrite published history solely to normalize messages. These checks validate structure and known AI co-author identities, not whether a description is meaningful or the type is appropriate.+Commit-range validation retains commitlint's default merge/revert exceptions, but they are not a naming convention. Preserve the validated PR title when merging via CLI/API (`gh pr merge --subject` must use it), and use explicit conventional subjects for branch updates, for example `chore: merge master into my-branch`. Do not rewrite published history solely to normalize messages. These checks validate structure and known AI co-author identities, not whether a description is meaningful or the type is appropriate.```shbun run check:commits --lastdiff --git a/README.md b/README.mdindex eb459dbc4..c7344474f 100644--- a/README.md+++ b/README.md@@ -262,52 +262,13 @@ See the [roadmap](https://openpencil.dev/development/roadmap) for product direct## Contributing-### Setup-```shbun installbun run dev:portless # Web editor at https://open-pencil.localhost-bun run dev # Direct Vite server at http://localhost:1420bun run tauri dev # Desktop app (requires Rust)```-The first Portless run creates and trusts a local HTTPS certificate. Linked Git worktrees automatically receive branch-prefixed URLs such as `https://fix-ui.open-pencil.localhost`, so concurrent development servers do not compete for port 1420. Their development MCP bridges are exposed through matching sibling URLs such as `https://fix-ui.mcp.open-pencil.localhost`, with isolated TCP ports and runtime socket files. Run `bunx portless doctor` if local routing or certificate trust fails.--Alternatively, open the repository in any [Dev Container](https://containers.dev/)-compatible tool. The container pins Bun, installs the workspace dependencies, and forwards the direct web editor on port 1420. Start it with `bun run dev` after the container is ready.--The Dev Container supports the web editor, packages, CLI, and automated checks. Native Tauri development still requires the host setup described below because desktop windows and platform WebView dependencies are not provided in the container.--### Quality gates--| Command | Description |-| ------------------------- | ----------------------------------------------------------- |-| `bun run check` | Full gate: lint, typecheck, package, docs, and arch checks |-| `bun run test:unit:quick` | Unit tests in parallel, heavy fixtures skipped (about 15 s) |-| `bun run test:unit` | Every unit test, heavy fixtures included |-| `bun run test` | E2E visual regression |-| `bun run format` | Code formatting |--### Project structure--```-packages/- scene-graph/ @open-pencil/scene-graph — nodes, primitives, hit testing, copy/snap/undo- pen/ @open-pencil/pen — Pencil document format helpers- kiwi/ @open-pencil/kiwi — Kiwi runtime and low-level .fig container parsing- fig/ @open-pencil/fig — .fig archives, SceneGraph conversion, instances, metadata- core/ @open-pencil/core — editor engine, renderer, layout, tools, RPC, document I/O- dom-css/ @open-pencil/dom-css — HTML/CSS/Tailwind to editable design documents- vue/ @open-pencil/vue — headless Vue SDK- cli/ @open-pencil/cli — headless CLI- mcp/ @open-pencil/mcp — MCP server (stdio + HTTP)- harness/ @open-pencil/harness — companion CLI for coding-agent Harness sessions- docs/ Documentation site (openpencil.dev)-src/ Vue app (editor shell, AI, collaboration, document I/O)-desktop/ Tauri v2 desktop app (Rust + config)-skills/ Agent skill (npx skills add open-pencil/open-pencil)-tools/ Repository tooling: CI, release, lint, and test infrastructure-tests/ E2E, visual, and engine tests-```+[CONTRIBUTING.md](CONTRIBUTING.md) covers setup, quality gates, pull requests, and commits. [AGENTS.md](AGENTS.md) maps the repository and links the guide inside each package. Desktop builds need [Rust](https://rustup.rs/) and the [Tauri v2 prerequisites](https://v2.tauri.app/start/prerequisites/); run `bun run tauri build`.### Tech stack@@ -321,14 +282,6 @@ tests/ E2E, visual, and engine tests| Desktop | Tauri v2 || AI/MCP | Vercel AI SDK (multi-provider BYOK), MCP SDK, Hono |-### Desktop builds--Requires [Rust](https://rustup.rs/) and platform-specific prerequisites ([Tauri v2 guide](https://v2.tauri.app/start/prerequisites/)).--```sh-bun run tauri build-```-## AcknowledgmentsThanks to [@sld0Ant](https://github.com/sld0Ant) (Anton Soldatov) for creating and maintaining the [documentation site](https://openpencil.dev).diff --git a/bun.lock b/bun.lockindex 7b858db49..a265bba25 100644--- a/bun.lock+++ b/bun.lock@@ -463,6 +463,9 @@"js-base64": "^3.9.3","valibot": "^1.4.2",},+ "devDependencies": {+ "nanotar": "^0.3.0",+ },},"tools/tauri-menu": {"name": "@open-pencil/tauri-menu-tools",diff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdnew file mode 100644index 000000000..725aaf35e--- /dev/null+++ b/desktop/AGENTS.md@@ -0,0 +1,12 @@+# Desktop (Tauri v2)++Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.json` before adding desktop capabilities. Release versions are also set in `desktop/tauri.conf.json` and `desktop/Cargo.toml` (`tools/AGENTS.md`, Releases).++- File system and shell permissions must be configured explicitly; a vague "Internal error" save failure usually means a missing permission.+- Dev tools: add or use a menu item to toggle them; do not rely on keyboard shortcuts.+- `desktop/src/credentials.rs` stores secrets in the native system credential store; failures must surface, never fall back to browser or plaintext storage (`src/AGENTS.md`, Settings).+- ACP and harness process changes require checking `desktop/capabilities/**`.+- `desktop/generated/menu.json` is produced by `bun run generate:tauri-menu` from `src/app/shell/menu/schema.ts`; do not edit or import it directly.+- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.+- `build_fig_file` performs `.fig` export on desktop; the browser path uses fflate (`packages/fig/AGENTS.md`).+- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.mdnew file mode 100644index 000000000..3186e1430--- /dev/null+++ b/packages/cli/AGENTS.md@@ -0,0 +1,8 @@+# CLI++Headless `.fig` inspection, export, linting, and scripting with `citty`. `bun open-pencil --help` lists current commands.++- Format all output with the `agentfmt` helpers re-exported from `packages/cli/src/format.ts`; do not hand-roll terminal formatting.+- Data and inspection commands support `--json`.+- Commands own their CLI UX independently of tools; `eval` exposes operations through `FigmaAPI` (`packages/core/AGENTS.md`, Figma API). Keep the public docs under `packages/docs/programmable/cli/` and the skill examples current when commands change.+- The MCP `--root` default is the current directory on macOS and Linux and the home directory on Windows; see `packages/mcp/AGENTS.md`.diff --git a/packages/cli/README.md b/packages/cli/README.mdnew file mode 100644index 000000000..35b99ea4f--- /dev/null+++ b/packages/cli/README.md@@ -0,0 +1,17 @@+# @open-pencil/cli++Headless command line for [OpenPencil](https://openpencil.dev) and `.fig` files: inspect documents and layers, query with XPath, export to PNG, JPG, WEBP, SVG, PDF, PPTX, JSX, HTML, or `.fig`, import HTML/CSS/Tailwind, lint design files, analyze and extract design tokens, and script documents with a Figma Plugin API-compatible `figma` global through `eval`.++```sh+npm install -g @open-pencil/cli # or: bun add -g @open-pencil/cli+openpencil --help+openpencil eval design.fig -c "return figma.currentPage.children.length"+```++Inspection commands support `--json` for automation. The MCP server ships separately as `@open-pencil/mcp`.++- CLI reference: https://openpencil.dev/programmable/cli/inspecting+- Scripting with the Plugin API: https://openpencil.dev/programmable/cli/scripting+- Source and issues: https://github.com/open-pencil/open-pencil++MIT License.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdnew file mode 100644index 000000000..8f4911a96--- /dev/null+++ b/packages/core/AGENTS.md@@ -0,0 +1,84 @@+# Core++Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and document I/O. Depends on scene-graph, pen, kiwi, and fig. Framework-neutral: no Vue, no app imports, no browser DOM; guard browser globals explicitly.++- Public surface is the compatibility barrel plus the subpaths listed in `packages/core/package.json` `exports`; add a subpath there rather than deep-importing.+- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere `import type` and pass CanvasKit in.+- Drawing and input share preview-aware geometry through `@open-pencil/core/geometry`, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement.++## Layout++- `@open-pencil/yoga-layout` supplies both flexbox and CSS Grid.+- Recompute layout after demo creation and for each materialized or imported page; scope computation to the affected page or subtree where possible.+- The first Hug/Fill dimension mutation switches only that axis to Fixed; focus is non-destructive, and mode/value changes share one undo transaction.++## Components and instances++- Component types use `#9747ff`.+- Component edits propagate through editor component sync in `packages/core/src/editor/components/`; never hand-copy properties in app UI. Use Scene Graph copy helpers for nested values.++## Vector conversion++- Bitmap-to-vector conversion lives in `packages/core/src/vector/vectorize/`; app provider clients, preferences, and credential resolution live under `src/app/editor/vectorize/` in the app. Bound request and response sizes and validate provider-owned download URLs before importing returned SVG.++## Tools (AI, MCP, CLI, WebMCP)++- Operations are `ToolDef`s under `packages/core/src/tools/**`; `schema.ts` defines the contract and registries expose them. Each definition owns its native Valibot `input`, execution/mutation metadata, and optional per-interface exposure exclusions (`mcp`, `ai`, `webmcp`). Exposure defaults to inclusion; adapters use `isToolExposed()`, then apply execution support and user permissions independently.+- Infer arguments from the schema; derive effects and default capabilities from execution metadata. Do not maintain parameter DSLs or tool-name lists. Add work to the nearest existing domain and the appropriate registry.+- `packages/core/src/tools/ai-adapter.ts` converts ToolDefs for Vercel AI; the app binds them to the active editor's `FigmaAPI` in `src/app/ai/tools/index.ts`. MCP v2 registration uses Standard Schema with Valibot JSON Schema conversion; AI and WebMCP adapters share the same input contract.+- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions; Scene Graph owns checkpoint recovery. AI, MCP, and WebMCP share this execution path. Async and structural tools cannot declare atomic property execution.+- Shared scene-authoring guidance and tested examples live under `packages/core/src/design-jsx/reference/`; `reference.ts` combines them with renderer metadata. Prompts under `packages/core/src/tools/prompts/` and the app chat/ACP prompt compose that reference rather than copying it. Run `bun run generate:authoring-reference` after changes; `check:authoring-reference` (part of `check:docs`) verifies the committed skill/docs copies. Do not edit generated reference files.+- The installable agent skill is maintained in `skills/open-pencil/`. Changes to agent-facing APIs, CLI/MCP behavior, or design authoring must update affected skill examples, prompts, and public documentation in the same change. Keep examples valid in their actual execution environment; do not advertise library exports as scripting globals unless exposed there. Prefer runtime discovery and canonical references over duplicated API/tool inventories.+- MCP-only tools and transports: `packages/mcp/AGENTS.md`. WebMCP registration and app completion: `src/AGENTS.md`.++## Editor++`createEditor()` in `packages/core/src/editor/create.ts` assembles an `EditorContext` plus domain action modules for viewport, selection, pages, shapes, structure, components, clipboard, undo/history, text, variables, layout, color space, graph reads, and the tool registry. `Editor` is `ReturnType<typeof createEditor>`. Check the folder before adding behavior; keep new actions in the nearest domain module or folder instead of growing unrelated files. Modules share state through `EditorContext`, never through app code or Vue.++- All selection mutations go through `ctx.setSelectedIds()` and all tool changes through `ctx.setActiveTool()` so events fire consistently. App code uses editor actions such as `clearSelection()`, `select()`, or `setTool()`, never direct `state.selectedIds =` or `state.activeTool =` assignments.+- The editor exposes a typed nanoevents emitter. Event names and payloads live in `EditorEvents` in `packages/core/src/editor/types.ts`; graph events are bridged from SceneGraph by `packages/core/src/editor/graph-events.ts`. Subscribe with `editor.onEditorEvent(event, handler)`; in Vue use `useEditorEvent()` from `packages/vue/src/editor/events/use.ts`. UI that only cares about graph data should use editor events for incremental surfaces such as the layer tree instead of watching repaint-only state.+- Commands under `packages/core/src/editor/structure/` (group, boolean, container wrap, flatten) and `packages/core/src/editor/components/` are the canonical implementations of user actions. The Figma API, tools, and app call them or share their helpers; do not reimplement sizing, placement, or propagation elsewhere.+- Live property controls use selected-node projections from `packages/core/src/editor/selection-state/nodes.ts`: shallow reactive copies that receive `node:previewUpdated` patches at property granularity. Never add preview invalidation to all `useSceneComputed` consumers; catalogs and unrelated controls must not refresh for geometry previews. Projection subscriptions belong to the consuming scope or session and must be disposed.+- Numeric geometry edits own a `beginNodePreview()` handle with `update`, `commit`, and `cancel`. It captures all affected fields and layout children, publishes the complete delta once, and restores exact originals on cancellation. Selection, page, and graph changes and disposal cancel the old edit; trailing input must not target the new selection. Controls must close previews even when a gesture returns to its starting value.+- Rotation previews change through `setRotationPreview()` and `rotation:preview-changed`; cancellation must close the owning gesture without deselecting or committing it.+- Renderer interaction policy uses explicit `beginInteractiveEdit()` leases and `isInteractiveEditing()`, not undo batching. Release leases on every terminal path. Keep live queries callable across app facades that spread editor actions.+- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions for AI, MCP, and WebMCP tools; see Tools above.++## Renderer++Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.++### Invalidation++- `renderVersion` is a canvas repaint (pan, zoom, hover); `sceneVersion` is a scene-graph mutation. `requestRender()` bumps both; `requestRepaint()` bumps only `renderVersion`. UI that only cares about graph data must not watch repaint-only state.+- `renderNow()` is only for surface recreation and font loading, where an immediate draw is required.+- The resize observer uses a rAF throttle, not a debounce; debounce causes canvas skew.+- Viewport culling skips off-screen nodes; unclipped parents are not culled because children may extend beyond bounds.+- Overscan images accelerate navigation; settled scenes rasterize existing retained pictures at the live viewport size and origin. Pixel-grid alignment alone does not guarantee Skia anti-aliasing parity. Keep settlement pending until the viewport pass completes; do not add a second viewport image cache.++### Caches++- Bounded rendering caches share `packages/core/src/cache/resource.ts` for recency, count/weight accounting, and removal disposal. Domain adapters own keys, font/page/dependency invalidation, and sizing units; use non-touching `peek()` for FIFO or planning reads. Rejected insertions leave ownership with the caller.+- Keep weak memos, async request registries, pools, and dependency-owned picture/path maps on their distinct lifetime policies.+- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph-inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.++### Geometry and overlays++- Use `@open-pencil/core/geometry` for world/screen transforms, inverses, bounds, and handle placement instead of interpreting ancestor rotations or reflections independently.+- Label drawing and hit testing share `packages/core/src/canvas/labels/{layout,transform,style}.ts`, including paragraph measurements and unreflected label axes.+- Selection border width is constant regardless of zoom: divide by scale. Section and frame title text never scales: render at a fixed font size and ellipsize to fit.+- Rulers are rendered on the canvas with selection range badges that do not overlap tick numbers. Remote cursors are Figma-style colored arrows with a white border and name pill, rendered in screen space.++### Visual coverage++Pixel-affecting features need committed visual coverage, not only mock or geometry assertions. Add or update a Playwright canvas snapshot for changes to fills, gradients, images, blend modes, masks, boolean geometry, corners, strokes, shadows, blur, text rendering, or demo showcase scenes. Use targeted updates such as `bun run test tests/e2e/canvas/fill-modes-visual.spec.ts --update-snapshots`, then rerun the same test without `--update-snapshots`.++## Figma API++`FigmaAPI` mimics Figma's Plugin API over the SceneGraph. `openpencil eval`, the AI and MCP tools, and the app bind to it. Tests live under `tests/engine/figma/api/` and mirror the API surface.++- **Shape follows Figma.** Match `@figma/plugin-typings` at the version pinned in the root `package.json`. `packages/core/src/figma-api/compatibility.ts` type-checks the supported surface against `PluginAPI`; add every new member to `SupportedPluginAPI` there. Model unsupported members explicitly rather than approximating them.+- **Behavior follows Figma.** Read the Plugin API documentation for the member, and for anything observable (geometry, ordering, defaults, errors) run the same script in live Figma and record the observed result in the test. `figma-use` and `tests/figma/` are the live oracle; `tests/fixtures/figma-oracles/` holds recorded values.+- **User actions are shared code.** When an editor command does the same thing (group, ungroup, boolean, flatten, instance creation, component sync), call the implementation under `packages/core/src/editor/` or its shared helper. Do not reimplement geometry, placement, or propagation here; new geometry helpers belong in Scene Graph.+- Node proxies live in `packages/core/src/figma-api/proxy.ts` and `packages/core/src/figma-api/accessors/`; `packages/core/src/figma-api/render-bounds.ts` implements Figma's `absoluteRenderBounds` semantics and is the only geometry that is Figma-specific.+- `packages/core/src/figma-api/index.ts` stays under the 600-line limit by moving whole domains into sibling modules such as `components.ts` and `text.ts`, not by extracting generic helpers into this folder.diff --git a/packages/core/README.md b/packages/core/README.mdnew file mode 100644index 000000000..c7992c008--- /dev/null+++ b/packages/core/README.md@@ -0,0 +1,12 @@+# @open-pencil/core++Editor engine for [OpenPencil](https://openpencil.dev): the CanvasKit (Skia WASM) renderer, Yoga layout, the framework-agnostic editor with undo and selection, the Figma Plugin API compatibility layer, the AI/MCP tool definitions, clipboard and vector conversion, and format-neutral document I/O.++It depends on `@open-pencil/scene-graph`, `@open-pencil/pen`, `@open-pencil/kiwi`, and `@open-pencil/fig`, and keeps browser DOM out so it runs in the app, the CLI, the MCP server, and headless scripts alike.++Import the root barrel or the targeted subpaths listed in `package.json` `exports`, for example `@open-pencil/core/io`, `@open-pencil/core/geometry`, and `@open-pencil/core/canvaskit`.++- Programmable overview and SDK docs: https://openpencil.dev/programmable/+- Source and issues: https://github.com/open-pencil/open-pencil++MIT License.diff --git a/packages/docs/AGENTS.md b/packages/docs/AGENTS.mdnew file mode 100644index 000000000..83791d96c--- /dev/null+++ b/packages/docs/AGENTS.md@@ -0,0 +1,10 @@+# Docs site++Published VitePress site. `bun run docs:dev`, `bun run docs:build` for fast checks, and `bun run docs:build:production` for deployment output. `bun run check:docs` runs the integrity checks in `tools/docs/` plus `check:authoring-reference`.++- Keep routes under `/getting-started`, `/overview/**`, `/user-guide/**`, `/programmable/**`, `/reference/**`, and `/development/**`; do not recreate `/guide/**`. Preserve moves in `packages/docs/public/_redirects`.+- Link untranslated locale navigation to canonical English pages rather than adding placeholders.+- `packages/docs/development/roadmap.md` tracks product direction, Figma compatibility gaps, raw metadata coverage, and the code map. `packages/docs/development/testing.md` is the canonical testing architecture. Explanations that would bloat an `AGENTS.md` belong under `packages/docs/development/`.+- SDK pages embed the demos colocated with `packages/vue` primitives, derive API tables from source and JSDoc with `vue-component-meta`, and process examples with Twoslash so imports and types stay aligned with the public package API. The docs Tailwind entry scans those demos.+- Generated authoring-reference copies under this site are checked, not edited; run `bun run generate:authoring-reference` (`packages/core/AGENTS.md`, Tools).+- CI runs documentation integrity and the docs build for docs-only changes, not engine, browser, Storybook, or native suites (`tools/AGENTS.md`).diff --git a/packages/docs/development/contributing.md b/packages/docs/development/contributing.mdindex ddae5ae03..93fc75429 100644--- a/packages/docs/development/contributing.md+++ b/packages/docs/development/contributing.md@@ -1,57 +1,18 @@# Contributing-The root [`CONTRIBUTING.md`](https://github.com/open-pencil/open-pencil/blob/master/CONTRIBUTING.md) is the source of truth for setup, pull-request requirements, validation, and commit expectations. Developers and coding agents should also read [`AGENTS.md`](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md) for current package ownership and architecture rules.+The root [`CONTRIBUTING.md`](https://github.com/open-pencil/open-pencil/blob/master/CONTRIBUTING.md) is the source of truth for setup, pull-request requirements, validation, and commit expectations. The root [`AGENTS.md`](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md) holds the repository map and cross-cutting conventions, and links the `AGENTS.md` guide inside each package or app domain. Read the root file and every guide on the path to the folder you change; coding agents pick them up the same way.-## Project structure+See [Architecture](/development/architecture) for the system overview and [Testing](/development/testing) for test ownership, fixtures, and commands. Use the root `AGENTS.md` map when exact package ownership or paths matter; do not infer ownership from an older copied tree.-OpenPencil is a Bun monorepo: framework-neutral document and format packages feed the core editor, DOM/CSS and Vue SDK layers, automation entry points, and the Tauri/Vite app.--See [Architecture](/development/architecture) for a public overview. Use root `AGENTS.md` when exact package ownership or paths matter; do not infer ownership from an older copied tree.--## Development setup+## Quick start```shbun install-bun run dev # Editor at localhost:1420+bun run dev:portless # Editor at https://open-pencil.localhostbun run docs:dev # Docs at localhost:5173```-## Pull requests--Follow the root PR template. Explain what changed, why it changed, and how it was validated. Remove template comments and unfinished placeholders, keep the title in English and the body primarily in English, and complete the AI assistance section.--CodeRabbit may flag description or readability issues for maintainers to review. Missing template sections or validation details are normal review feedback, not by themselves a judgment on the contributor.--## Validation--Run the checks relevant to the change. The normal complete gate is:--```sh-bun run check-bun run format-bun run test:unit-bun run test-```--Rendering and other pixel-affecting changes require targeted visual coverage. Package publishing changes require the package verification commands documented in `AGENTS.md`.--## Test placement--Place tests in the established layer and mirror the source domain where practical:--- `tests/e2e/**/*.spec.ts` — browser UI and visual behavior.-- `tests/figma/**/*.spec.ts` — Figma automation.-- `tests/engine/**/*.test.ts` — engine and unit behavior.-- `tests/helpers/**` — shared test utilities.-- Package-local `tests/**` — standalone package coverage where already established.--Test behavior and stable contracts, not source text or implementation details. Before adding a test file or helper, inspect nearby tests and follow their existing structure.--### Test selectors--Playwright tests should locate behavior the way users and assistive technology do: prefer roles and accessible names, labels, and visible text. Scope repeated controls to a named region. Multi-part UI components expose local `data-slot` anatomy, while stable app concepts may expose semantic attributes such as `data-property`, `data-command`, or `data-node-id`.--Reserve `data-test-id` for integration boundaries that have no meaningful user-facing or domain identity. Do not add test-ID props to reusable components or generate compound IDs from component nesting.+The complete gate before a pull request is `bun run check`, `bun run format`, `bun run test:unit`, and `bun run test`. Rendering and other pixel-affecting changes require targeted visual coverage.## SDK documentationdiff --git a/packages/fig/AGENTS.md b/packages/fig/AGENTS.mdnew file mode 100644index 000000000..9456af057--- /dev/null+++ b/packages/fig/AGENTS.md@@ -0,0 +1,10 @@+# Fig and Kiwi++`@open-pencil/kiwi` owns Kiwi schema, runtime, codecs, containers, and parse helpers without SceneGraph knowledge. `@open-pencil/fig` owns complete `.fig` archive parsing, SceneGraph conversion, metadata policy, component/instance interpretation, and the Figma clipboard format. Core owns format-neutral orchestration, runtime fonts and workers, and thumbnails.++- Keep Kiwi runtime changes minimal; put project policy in wrappers, not in the runtime.+- Figma clipboard envelope encoding, decoding, bounds, and SceneGraph import conversion belong to `@open-pencil/fig/clipboard`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.+- Browser `.fig` export uses fflate and `@open-pencil/fig`; Tauri uses `build_fig_file` in `desktop/`.+- Vector networks use the reverse-engineered `vectorNetworkBlob`; codecs live under `packages/core/src/vector/` and types in Scene Graph.+- Changes to `.fig` behavior require round-trip validation in Figma. `packages/docs/development/roadmap.md` tracks raw metadata coverage and the code map for import/export mapping and schema files.+- Fixtures under `tests/fixtures/*.fig` use Git LFS; use a normal `git push` when they change, and `git push --no-verify` to skip the LFS hook otherwise.diff --git a/packages/harness/AGENTS.md b/packages/harness/AGENTS.mdnew file mode 100644index 000000000..c7871195f--- /dev/null+++ b/packages/harness/AGENTS.md@@ -0,0 +1,8 @@+# Harness++Optional Node companion for HarnessAgent sessions. Tauri launches the separately installed command; never bundle a JavaScript runtime into Tauri.++- Keep the package backend-neutral.+- Persist only opaque, non-secret resume state. Pi's in-memory `just-bash` cannot recover across process restarts.+- Expose the bounded JSONL host protocol; changes to it must keep the desktop launcher and `desktop/capabilities/**` in sync (`desktop/AGENTS.md`).+- `bun run test:tools` runs this package's tests together with the repo tooling suites.diff --git a/packages/mcp/AGENTS.md b/packages/mcp/AGENTS.mdnew file mode 100644index 000000000..680f0d373--- /dev/null+++ b/packages/mcp/AGENTS.md@@ -0,0 +1,9 @@+# MCP server++stdio and Hono HTTP MCP server that reuses Core tools (`packages/core/AGENTS.md`, Tools).++- MCP-only filesystem and server tools live in `packages/mcp/src/tool/registration.ts`; listener and session lifecycle under `packages/mcp/src/server/`, stdio under `packages/mcp/src/stdio/`, transport discovery under `packages/mcp/src/transport/`.+- Registration uses Standard Schema with Valibot JSON Schema conversion from the Core tool input contract; per-tool exposure comes from `isToolExposed()`.+- File access must resolve symlinks inside the effective MCP root. CLI defaults are the current directory on macOS and Linux and the home directory on Windows.+- Keep browser lifecycle out of this package and out of Core.+- Transport tests live under `tests/engine/mcp/{server,stdio,transport}` with shared fixtures under `tests/helpers/mcp`; isolate tests from user runtime discovery. Playwright starts the development MCP companion through the Vite automation plugin; see `tests/AGENTS.md`.diff --git a/packages/mcp/README.md b/packages/mcp/README.mdnew file mode 100644index 000000000..ae77889f3--- /dev/null+++ b/packages/mcp/README.md@@ -0,0 +1,16 @@+# @open-pencil/mcp++Model Context Protocol server for [OpenPencil](https://openpencil.dev). It lets MCP clients such as Claude Code, Cursor, and Windsurf inspect and edit designs through the running app, reusing the same tool definitions as the built-in AI chat.++```sh+npm install -g @open-pencil/mcp+openpencil-mcp # stdio transport for MCP clients+openpencil-mcp-http # Streamable HTTP transport for browser extensions and scripts+```++On macOS and Linux, local clients prefer a private Unix domain socket; Windows and unavailable sockets fall back to localhost TCP. File access is limited to the effective MCP root.++- Setup and client configuration: https://openpencil.dev/programmable/mcp-server+- Source and issues: https://github.com/open-pencil/open-pencil++MIT License.diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.mdnew file mode 100644index 000000000..afdd8d186--- /dev/null+++ b/packages/scene-graph/AGENTS.md@@ -0,0 +1,14 @@+# Scene Graph++Framework-neutral document model. Owns node types, primitives, geometry, matrices, copy/snap/undo helpers, variables, instances, hit testing, and checkpoint recovery.++- Nodes live in a flat `Map<string, SceneNode>`; runtime hierarchy uses `parentId` and `childIds`. Frames do not clip by default.+- Geometry is built on the matrices in `packages/scene-graph/src/matrix.ts` and `packages/scene-graph/src/coordinate.ts` (`getWorldMatrix`, `getAxisAlignedWorldBounds`, `getNodeLocalMatrix`). Add new transform, bounds, or inverse helpers here beside them; do not interpret ancestor rotations or reflections independently elsewhere. LINE pivots remain at the origin; other nodes rotate around their centers.+- Bounds accumulation goes through the helpers in `packages/scene-graph/src/geometry.ts` (`computeBounds`, `computeAbsoluteBounds`, `computeVisualBounds`); do not add another min/max loop.+- Reparenting preserves child world positions; groups preserve them too. Sort children geometrically before creating auto-layout. Consumers such as layer trees must react to reparenting rather than retaining stale child references.+- Use the copy helpers in `packages/scene-graph/src/copy.ts` for nested values (fills, strokes, effects); never hand-copy node properties.+- Instance children map to component children through `componentId`; runtime overrides use the structured `InstanceOverrideState` (`self` and `descendants` maps) in `packages/scene-graph/src/instance-overrides.ts`.+- Shared primitives that format packages need live here: color conversion and management under `@open-pencil/scene-graph/color` and text/layout direction under `@open-pencil/scene-graph/text-direction`.+- Vector network types live here; the reverse-engineered `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.+- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes; Core's atomic tool execution relies on it.+- Export named types and primitives (`Color`, `Vector`, `Rect`, `SceneNode`, `Effect`, `Fill`, `Stroke`) from the public entry; downstream packages reuse them instead of respelling shapes.diff --git a/packages/vue/AGENTS.md b/packages/vue/AGENTS.mdnew file mode 100644index 000000000..e3dd8b78d--- /dev/null+++ b/packages/vue/AGENTS.md@@ -0,0 +1,27 @@+# Vue SDK++Headless Vue 3 primitives and composables; the root app is one consumer. Primitives are controlled and editor-agnostic. Stories follow `src/AGENTS.md` (Storybook).++## Property primitives++- Fields compose variable/token binding through `BindingProvider` (`packages/vue/src/controls/binding-provider/`) and `BindableValue` (`packages/vue/src/primitives/BindableValue/`). Keep numeric interaction in `NumberField`; providers own binding lookup, mutation, and undo batching.+- `PropertySection`, `SegmentedControl`, and `PropertyList` under `packages/vue/src/primitives/` are controlled and editor-agnostic. Connect PropertyList events to selection and undo through `useEditorPropertyList()` or an app adapter; never call `useEditor()` from a primitive.+- Compose property rows from `PanelGrid`, `PanelFieldGroup`, `PanelItemRow`, and `PropertyItemRow`; use `BindableValue`, `FillRoot`, and `FillSwatch` rather than rebuilding binding or picker infrastructure.+- Binding-aware fields detach or mutate only on the first value change; opening and focusing are non-destructive.+- Prefer models, events, and props over imperative slot actions except for explicitly renderless action primitives. Use VueUse for DOM refs and focus.+- Preserve interaction gotchas when refactoring: splitter handles, NumberField pointer ownership, section dragging, panel containment, and number-spinner styling.++## Retained panels++The app's `DesignPanel` retains at most one selection-property subtree through `RetainedPanel`. The app installs `createRetainedScopePlugin()`; opted-in descendants receive `provideRetainedActivity()`. Vue component scopes are detached, so pausing only a parent or bare `KeepAlive` does not suspend descendant work. Cancel drafts synchronously before DOM detachment can fire blur, close transient state and gate portals with `useRetainedPopup()`, and invalidate pending async results on deactivation or disposal. The plugin lets cleanup flush before pausing each component scope and resumes it on activation; it requires Vue's Options API. Unmounting the owning editor releases the retained subtree.++## Commands, menus, i18n++- Commands use `packages/vue/src/editor/commands/registry.ts` for shortcuts, bindings, and menu IDs. Store portable tokens (`MOD+D`) and format them at render time; labels and translations never contain shortcuts.+- Canvas menu structure lives in `packages/vue/src/editor/menu-model/canvas.ts`; the app's `CanvasMenu.vue` renders it.+- `useEditorEvent(event, handler)` in `packages/vue/src/editor/events/use.ts` wraps the editor event bus.+- i18n uses narrow product-domain catalogs under `packages/vue/src/i18n/messages/` with matching locale files. Inspect existing domains instead of adding generic UI/component namespaces; prefer narrow `use*Messages()` composables over aggregate `useI18n()`. `bun run check:i18n` enforces structure, placeholder parity, and reviewed translation baselines; remove stale baseline identities when fixing existing debt.++## Documentation++VitePress is the canonical public SDK documentation; Storybook is the internal state workshop. API tables are extracted from source and JSDoc with `vue-component-meta`, so keep descriptions next to public props, events, and slots, and keep examples valid against public exports (`packages/docs/AGENTS.md`). An example shared by Storybook and a docs page lives in `packages/vue/src/primitives/<Primitive>/examples/<Variant>.vue` (PascalCase variant, e.g. `States.vue`); the story renders it and the docs page imports it with `#vue/primitives/...`. Do not render Storybook stories inside VitePress pages: `@storybook/vue3` assigns `window.STORYBOOK_ENV` on import so it cannot be server-rendered, the docs bundle ships runtime-only Vue so runtime templates silently fail, and a client-only embed drops examples from the prerendered HTML while adding the Storybook preview runtime and `storybook/test` to the published docs.diff --git a/src/AGENTS.md b/src/AGENTS.mdnew file mode 100644index 000000000..3eac46655--- /dev/null+++ b/src/AGENTS.md@@ -0,0 +1,74 @@+# App++Root Tauri/Vite app. Services and state live under `src/app/**`, views under `src/views/**`, UI under `src/components/**` (UI section below). Use `@/` for cross-directory imports. Detect desktop with `IS_TAURI`.++## Editor session++- `src/app/editor/session/create.ts` wraps Core: it creates reactive state, calls `createEditor()`, and assembles document I/O, autosave, export, vector edit, pen resume, flashes, profiler, and mobile clipboard. Tabs live in `src/app/tabs/`; active editor access in `src/app/editor/active-store/`.+- Use editor actions (`clearSelection()`, `select()`, `setTool()`), never direct state assignments (`packages/core/AGENTS.md`, Editor).+- File System Access APIs are browser APIs, not Tauri-only. Keep the Safari download fallback and defer `revokeObjectURL`.+- Vectorize provider clients, preferences, and lazy credential resolution live under `src/app/editor/vectorize/`; conversion itself is in Core.++## Settings, credentials, storage++- Reactive settings workflows live under the owning domain's `settings/` folder (for example `src/app/ai/models/settings/profile-editor/{use,selection,connection}.ts`), not a global composables bucket. `use.ts` orchestrates; focused siblings hold substantial sub-workflows. Persistence and external operations stay in domain services; pure option projections are ordinary functions. Return operation outcomes rather than importing dialogs, routers, or toasts into workflows. Guard async results against changed targets.+- Persistence outcomes (`saved`, `failed`, `partial`) stay in the domain: preferences and a native credential store cannot transact together. Preserve retryable drafts, reuse already-persisted identities on retries, and surface the partial-save warning. Never render raw credential backend errors or secrets.+- New explicit settings forms use headless VeeValidate v5 with native Valibot schemas and existing controlled UI components; form state lives in the owning settings domain. VeeValidate owns validation and submission state; domain workflows keep their own pending/lifecycle guards. Saved secrets and replacement-secret drafts stay outside form snapshots and devtools. A credential-store failure does not make the entered key invalid.+- Credential persistence lives under `src/app/settings/credentials/`. Settings components receive `CredentialManager` and may inspect status, replace, or clear; runtime adapters receive `CredentialResolver` and resolve secrets at operation time. Components must not read saved secrets or keep them in long-lived reactive refs; keep newly entered secrets short-lived. Non-secret provider preferences stay in normal settings storage.+- Tauri stores secrets in the system credential store through `desktop/src/credentials.rs`; browsers default to WebCrypto-encrypted IndexedDB and may explicitly opt out to session-only memory. Native failures must never silently fall back to browser or plaintext storage. New integration credentials use stable `CredentialRef` values and join the unified Settings surface rather than feature-local key forms.+- Storage-provider schemas and runtime adapters live under `src/app/integrations/storage/`; non-secret preferences and credential references stay separate. Local-first document caching and outbox synchronization live under `src/app/storage/`. A remote storage binding augments document source state and must not replace local file identity.++## AI, ACP, automation, collaboration++- `src/app/ai/tools/index.ts` binds Core ToolDefs to the active editor's `FigmaAPI`. The chat and ACP prompt compose the Core authoring reference rather than copying it (`packages/core/AGENTS.md`, Tools).+- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/constants.ts`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. ACP process changes require checking `desktop/capabilities/**`.+- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. App completion under `src/app/automation/execution/` loads fonts after commit.+- Collaboration lives under `src/app/collab/**` on Trystero, Yjs, and awareness; preserve crypto-safe room IDs and peer cleanup.++## Browser baseline++The supported browser baseline lives in `src/app/shell/support/baseline.ts` and feeds the Vite `build.target`, the startup gate, and the documented system requirements; change all three together, including `desktop/tauri.conf.json` `minimumSystemVersion`. Vite lowers syntax but never polyfills APIs, so two data-driven checks enforce the baseline: the app and browser-shipped packages pin TypeScript `lib` to ES2023 (the last edition those engines implement fully), so newer built-ins fail type-checking, and `compat/compat` (`eslint-plugin-compat` under oxlint, fed the same browsers from `settings.browsers`) rejects Web APIs they lack. Do not raise the lib to `ESNext` in those tsconfigs; use `createDeferred()` from `src/app/runtime/deferred.ts` instead of `Promise.withResolvers()`. Node-only packages (`cli`, `mcp`, `harness`) are exempt from both. `tests/app/shell/support/baseline.test.ts` keeps the tsconfigs and oxlint browsers in step with the baseline. `src/main.ts` must stay a tiny gate that only dynamically imports `src/boot.ts`, so an unsupported engine can still render `src/app/shell/support/` guidance.++## Shell++- Browser and native menus share `src/app/shell/menu/schema.ts`; handle IDs in `use.ts` or editor commands, and regenerate `desktop/generated/menu.json` with `bun run generate:tauri-menu`.+- Motion policy lives in `src/app/shell/motion/`: resolve the persisted System/Off preference and OS reduction once. The root `data-motion` attribute and the Tailwind `motion-safe`/`motion-reduce` variants represent the effective policy, including portalled content. Use the policy-aware Motion adapters rather than repeating preference conditionals in components.+- Keep the app manifest in `vite/pwa.ts`; use `BrandMark` for in-app branding; never symlink web assets to desktop icons (`tools/AGENTS.md`, Brand assets).++## UI++`src/components/ui/**` is generic, store-free design-system code grouped by family: `{button,input,select,toggle,dialog,panel,binding,feedback,overlay,menu,paint}/`. Do not create a folder named after a single component. Feature controls stay in their domain. Theme families mirror these under `src/theme/`; feature themes stay separate. Use explicit imports without old-path forwarding shims.++### Building blocks++- Use Reka UI primitives and typed Tailwind Variants themes under `src/theme/**`; merge per-instance `ui` slot overrides, expose `class` for single-root components, and do not add one-off class props. Use `UI` casing in type names. App wrappers around SDK primitives use shared UI helpers rather than scattered raw classes.+- Tailwind 4 and `tw-animate-css`; no static inline styling or component `<style>` blocks. Dynamic `:style` bindings are allowed for runtime geometry and CSS variables.+- Bind visual state through semantic `data-*` attributes. Steiger rejects template-time `use*UI()`, visual-state utility branches, and raw SVG app icons.+- `Tip`, not native `title`; Lucide/Iconify components, not raw SVG or Unicode icons; `e.code`, not `e.key`, for modified shortcuts.+- App dialogs compose the Reka-backed components under `src/components/ui/dialog/` and the typed theme in `src/theme/dialog.ts`. Do not repeat portal, overlay, content, header, or footer infrastructure in feature dialogs.+- SDK property primitives, binding fields, commands, and i18n: `packages/vue/AGENTS.md`.++### Settings++- Compose Settings sections with `SettingsSection` and its `title`, `description`, `actions`, and default content slots. It owns heading association and internal spacing; `SettingsGroup` owns bordered row grouping. Do not repeat section, header, or spacing markup per feature.+- Settings components own layout, translated copy, confirmation visibility, and emits; small presentation-only computed bindings may stay in components. Workflows, persistence, and credentials: `src/AGENTS.md`.+- `SettingsSaveFeedback` maps domain outcomes (`saved`, `failed`, `partial`) to `AppAlert`. `SettingsLink` owns external-link styling, the icon, and native opening for provider key pages and setup guides; keep arrow glyphs out of translated labels.++### Feedback and forms++- `AppAlert` (`src/components/ui/feedback/AppAlert.vue`, theme `src/theme/feedback/alert.ts`) for persistent contextual errors, warnings, recovery guidance, and informative results, with translated `heading`/`description` and an `actions` slot. Do not hand-roll alert markup or colored error paragraphs. Alerts announce changes without taking keyboard focus.+- The toast service is for transient confirmations such as copying or completing an action after its view closes. Never show a toast and an alert for the same event; partial saves and actionable failures must not disappear in a toast.+- Field validation stays inline in the shared field component with `aria-invalid`, error text before hints, and first-invalid-field focus.+- Ordinary labels such as Running/Stopped remain status text or badges. Destructive confirmation belongs in the shared confirmation dialog.++### Animations++- Tailwind transitions and `tw-animate-css` for simple state changes and enter/exit; the existing `motion-v` dependency for gesture-driven motion, coordinated layout changes, and springs. Do not add another animation library.+- Store-free presets live in `src/theme/motion/` and compose into owning themes; keep what moves, geometry, and feature-specific spring values local. Share repeated duration and easing values. Policy resolution: Shell above.+- Collapsibles use Reka state attributes and measured CSS variables with `animate-collapsible-down` / `animate-collapsible-up`; keep padding and borders inside the animated height wrapper.+- Respect `prefers-reduced-motion` in CSS and Motion; simplify nonessential motion while preserving state changes and feedback. Verify opening, closing, interrupted transitions, reduced motion, and scroll behavior. Expanding historical chat content must not force the transcript to the bottom.++### Storybook++- Colocate `ComponentName.stories.ts` with `ComponentName.vue`; multipart compositions may use a descriptive family name. Preserve explicit titles and exported story names during moves. Default playgrounds stay static; interaction flows get named stories. Prefer inline story fixtures for small app-local states; use colocated `examples/<Variant>.vue` SFCs for substantial templates or fixtures that need SFC template/slot typing, including app-only fixtures (shared SDK examples follow `packages/vue/AGENTS.md`, Documentation). Story templates compile at runtime, so they must be plain JavaScript with no TypeScript syntax, and `icon-lucide-*` tags do not resolve there; import icons from `~icons/...` and register them.+- Isolated visual states of feedback components belong in stories, not Playwright application screenshots. Do not add automated tests or snapshot baselines for CSS-only changes (spacing, sizing, colors, breakpoints); verify those visually. Settings E2E covers integration behavior: feedback appearance, validation and focus, retained drafts, successful retries.diff --git a/tests/AGENTS.md b/tests/AGENTS.mdnew file mode 100644index 000000000..c8adcd763--- /dev/null+++ b/tests/AGENTS.md@@ -0,0 +1,32 @@+# Tests++`packages/docs/development/testing.md` is the canonical testing architecture: ownership table, fixture/driver/probe roles, browser and native boundaries, execution commands, server ownership, and worktree ports. This file holds the rules that bite during implementation.++## Placement++- Package-local tests mirror source domains under `packages/<owner>/tests/`; central app tests mirror `src/app/**` under `tests/app/`; `tests/integration/` requires a genuinely cross-owner contract; E2E under `tests/e2e/` follows user workflows; native and Figma acceptance are explicit exceptions.+- Existing `tests/engine/**` domains migrate together with runner discovery: `tools/unit-tests/src/shards.ts` lists each owner's canonical home and its current `tests/engine` directories, so a move is a `git mv` plus imports. Do not create competing homes or undiscovered suites.+- Owner-local helpers and fixtures stay local; only genuinely shared support goes under central `tests/helpers/<domain>/` and `tests/fixtures/`. MCP transport tests: `tests/engine/mcp/{server,stdio,transport}` with `tests/helpers/mcp`.+- Never commit temporary, diagnostic, or profile specs; keep them in ignored `scratch/`.++## Writing specs++- Test contracts and observable behavior, not source text. Specs use domain drivers and probes, not scattered Window/store traversal or unrestricted evaluator wrappers.+- Locate behavior by accessible role and name, then label, then visible text. Scope repeated controls to a named region. Use scoped `data-slot` anatomy or semantic attributes (`data-property`, `data-command`, `data-node-id`) when needed; reserve `data-test-id` for integration boundaries and never add test-hook props or compound IDs.+- Prefer test-runner-owned fixtures and request/route counters over browser globals. For in-page performance instrumentation, return a scoped `JSHandle` from `evaluateHandle()`, restore patched methods and listeners, and dispose the handle in `finally`; handles do not survive navigation. Assert transient DOM state with locators before the interaction ends.+- Do not create a catch-all test Window interface or ad-hoc counter properties on `window`. Native-test declarations live in `tests/helpers/tauri/native-global.d.ts`; never expand production Window declarations for fixtures.+- In Bun tests prefer injected dependencies or scoped spies with explicit cleanup. `mock.restore()` restores spies but does not undo `mock.module()` overrides; do not assume module mocks are isolated by cleanup hooks. Read the installed runner's lifecycle and mocking docs before adding global or module-level instrumentation.+- Make flaky tests deterministic; raising a timeout is never the fix. Keep package-manager invocations out of `bun test` suites; their cold start is not bounded.++## Browser runs++- Use the canonical `playwright.config.ts`; do not create task-specific config copies or server runners. Playwright owns Vite; the Vite automation plugin owns MCP startup and cleanup; browser fixtures own interactions, not server processes.+- Test scripts select their server; direct Playwright commands start both servers unless `OPENPENCIL_TEST_SERVER=app|storybook|all` is set. Managed runs start the intended checkout; server reuse is opt-in for local development only, never for baseline comparisons or CI. Isolate the app URL, MCP endpoint, CORS origin, socket, and discovery path together.+- Pixel-affecting renderer changes need committed canvas snapshots (`packages/core/AGENTS.md`, Renderer). Update only the justified affected snapshot and rerun without update mode.++## Native WebView++- Native checks live under `tests/e2e/native/**` and run through WebdriverIO against an explicit test-only Tauri binary: `bun run test:native` builds and runs, `bun run build:native-test` only builds. The binary uses a separate application identifier, an ephemeral WebView data store, and process-memory credentials.+- Never run UI smoke tests against production Keychain entries or clear user recovery data to unblock tests. Persistence across restarts needs a dedicated test-owned persistent profile.+- Native tests answer only whether the real WebView and Tauri shell deliver an interaction; engine tests cover state contracts and Playwright covers app integration. Platform-limited checks skip rather than claim coverage. Synthetic composition does not prove IME behavior; native clipboard remains a separate acceptance gap without trusted OS clipboard events.+- Centralize native invocation in a guarded helper using vendor-derived types; do not import packages inside serialized WebView callbacks or repeat direct Tauri-global access in specs.diff --git a/tools/AGENTS.md b/tools/AGENTS.mdnew file mode 100644index 000000000..a046aa45f--- /dev/null+++ b/tools/AGENTS.md@@ -0,0 +1,25 @@+# Repo tooling, CI, and releases++Private tooling lives under `tools/<domain>/{src,tests}` with kebab-case domains and focused tests; `bun run test:tools` runs every tool package with a `test` script. `scripts/` may contain only tiny compatibility entrypoints.++- Resolve the workspace with `resolveWorkspaceRoot` from `@open-pencil/package-artifacts`, not parent-directory traversal. Use domain aliases for cross-directory tooling imports, including tests; keep sibling imports relative.+- `tools/architecture` (Steiger rules) backs `check:arch`; `tools/docs` backs `check:docs`, including the guide-map check; `tools/i18n`, `tools/release-packages`, `tools/unit-tests`, `tools/ci`, and `tools/brand` own their namesake commands.++## CI++- `.github/workflows/ci.yml` and `heavy-tests.yml` define validation gates. PR CI always classifies changed paths through `tools/ci/src/policy.ts`: root docs, package READMEs, every `AGENTS.md`, `packages/docs` Markdown and assets, and skill Markdown are docs-only; runtime prompt Markdown, executable examples, configuration, and unknown paths require code validation.+- Docs-only changes run documentation integrity and the docs build; everything else runs the full suites. The aggregate `CI result` gate requires successful classification and every applicable job; failures, cancellations, and unexpected skips cannot pass. Do not restore workflow-level path filtering on required CI.+- `commitlint.config.ts` enforces commit structure in the **Commit messages** job; the separate **PR title** workflow validates titles. Preserve the `Release vX.Y.Z` exception and product casing when changing rules; the known AI co-author check does not rewrite base history. Gate policy lives in `tools/ci/src/policy.ts`.+- App and docs production workflows run on `v*` tags or `workflow_dispatch`, not ordinary `master` pushes.++## Releases++- Update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; move `Unreleased` into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; tag and push `vX.Y.Z`.+- `.github/workflows/build.yml` is the source of truth: `v*` tags (or dispatches for an immutable stable tag) build shared frontend/package outputs once, build signed desktop artifacts in parallel, verify and attest one complete same-run artifact set, publish npm packages, and replace the draft release assets using the exact changelog section. Policy, provenance, and recovery: `tools/release-packages/README.md`.+- Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports use `dist`. Release preparation must preserve resolution maps. Prepared publish directories receive the root `LICENSE` when a package has none of its own, and every package needs a `README.md` because npm renders it. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks; never publish package directories manually. `test:packages` first runs the packaging guards in `tools/package-quality/src/smoke/guards.ts`: fixture manifests packed with the real `npm pack` that must trip the tarball inspector and the Node/Bun consumer checks before those checks vouch for real packages.+- Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title, body, and artifacts, then publish. Release titles are exactly the tag (`vX.Y.Z`) without a product-name prefix.+- Homebrew's `openpencil` cask is managed upstream: BrewTestBot proposes bumps and Homebrew merges them. Check the upstream cask PR after publication; do not push to the archived custom tap or add bump automation. Users install the app with `brew install --cask openpencil` and the CLI through npm or Bun.++## Brand assets++Canonical artwork lives in `assets/brand/` (main mark and optical micro master; see its README). `tools/brand/` derives web, docs, and native icons with RealFaviconGenerator and Tauri; generated assets are ignored, not committed. Vite and VitePress configs prepare their own targets, and Tauri dev/build hooks prepare native icons.diff --git a/tools/ci/src/policy.ts b/tools/ci/src/policy.tsindex 4810c94cc..998811c63 100644--- a/tools/ci/src/policy.ts+++ b/tools/ci/src/policy.ts@@ -3,11 +3,12 @@ const DOC_ASSET = /\.(?:md|png|jpe?g|gif|webp|svg|ico|pdf|woff2?|ttf)$/iexport type ChangeScope = 'docs' | 'code'-/** Unknown paths, executable docs, and runtime prompt Markdown require the code checks. */+/** Root docs, package READMEs, and every AGENTS.md guide are docs-only; unknown paths, executable docs, and runtime prompt Markdown require the code checks. */export function classifyPaths(paths: readonly string[]): ChangeScope {if (paths.length === 0) return 'code'return paths.every((path) => {if (ROOT_DOCS.has(path) || /^packages\/[^/]+\/README\.md$/.test(path)) return true+ if (/(?:^|\/)AGENTS\.md$/.test(path)) return trueif (path.startsWith('packages/docs/')) return DOC_ASSET.test(path)if (path.startsWith('openspec/')) return path.endsWith('.md')if (path.startsWith('skills/')) return path.endsWith('.md') || path.endsWith('/LICENSE.txt')diff --git a/tools/ci/tests/policy.test.ts b/tools/ci/tests/policy.test.tsindex 2053d9df1..923a6a1f9 100644--- a/tools/ci/tests/policy.test.ts+++ b/tools/ci/tests/policy.test.ts@@ -16,6 +16,10 @@ const documentation = ['CHANGELOG.md','packages/vue/README.md','packages/core/README.md',+ 'packages/core/AGENTS.md',+ 'src/AGENTS.md',+ 'tests/AGENTS.md',+ 'tools/AGENTS.md','packages/docs/programmable/sdk/api/components/bindable-value.md','packages/docs/public/logo.svg','skills/open-pencil/SKILL.md',@@ -28,6 +32,8 @@ const code = ['packages/core/src/README.md','packages/core/README.md.ts','packages/core/instructions.md',+ 'src/app/agents.md',+ 'packages/core/src/AGENTS.md.ts','packages/docs/.vitepress/config.ts','packages/docs/demo.vue','skills/open-pencil/scripts/create.ts',diff --git a/tools/docs/src/check.ts b/tools/docs/src/check.tsindex af7a3dff2..1ea606c82 100644--- a/tools/docs/src/check.ts+++ b/tools/docs/src/check.ts@@ -28,6 +28,7 @@ import {userGuideSidebar} from '#docs-config/sidebars'+import { checkGuideMap } from './guides'import { checkDocsIntegrity } from './integrity'interface SidebarItem {@@ -85,12 +86,17 @@ console.log(`Localized page presence: ${Math.min(...translationCounts)}–${Math.max(...translationCounts)} of ${result.canonicalPageCount} canonical routes per locale; content quality is audited separately.`)-if (result.errors.length > 0) {+const guides = checkGuideMap({ repoRoot })+const errors = [...result.errors, ...guides.errors]++if (errors.length > 0) {console.error('\nDocumentation integrity check failed:')- for (const error of result.errors) console.error(`- ${error}`)+ for (const error of errors) console.error(`- ${error}`)process.exit(1)}+console.log(`Guide map check passed for ${guides.guides.length} AGENTS.md guides.`)+console.log(`Documentation integrity check passed for ${result.markdownFiles.length} Markdown files.`)diff --git a/tools/docs/src/guides.ts b/tools/docs/src/guides.tsnew file mode 100644index 000000000..edf4a5213--- /dev/null+++ b/tools/docs/src/guides.ts@@ -0,0 +1,65 @@+import { existsSync, readdirSync, readFileSync } from 'node:fs'+import { join, relative, sep } from 'node:path'++export interface GuideMapOptions {+ repoRoot: string+ /** Directory names that are never scanned for guides; hidden directories are always skipped. */+ ignoredDirectories?: readonly string[]+}++export interface GuideMapResult {+ errors: string[]+ /** Nested guides found on disk, repo-relative with `/` separators, sorted. */+ guides: string[]+ /** Guide paths referenced from the root `AGENTS.md`, sorted. */+ listed: string[]+}++export const ROOT_GUIDE = 'AGENTS.md'+const DEFAULT_IGNORED_DIRECTORIES = ['dist', 'node_modules', 'scratch', 'target']+const GUIDE_REFERENCE = /`((?:[\w.-]+\/)+AGENTS\.md)`/g++function walkGuides(directory: string, repoRoot: string, ignored: ReadonlySet<string>): string[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ if (entry.name.startsWith('.') || ignored.has(entry.name)) return []+ const path = join(directory, entry.name)+ if (entry.isDirectory()) return walkGuides(path, repoRoot, ignored)+ if (!entry.isFile() || entry.name !== ROOT_GUIDE) return []+ const rel = relative(repoRoot, path).split(sep).join('/')+ return rel === ROOT_GUIDE ? [] : [rel]+ })+}++/** Guide paths written as inline code in Markdown, for example `packages/core/AGENTS.md`. */+export function listedGuides(markdown: string): string[] {+ const found = new Set<string>()+ for (const match of markdown.matchAll(GUIDE_REFERENCE)) found.add(match[1])+ return [...found].sort()+}++/**+ * Every nested `AGENTS.md` must be reachable from the root guide's map, and every guide the root+ * mentions must exist, so agents that only read the root file are routed to current guides.+ */+export function checkGuideMap(options: GuideMapOptions): GuideMapResult {+ const ignored = new Set(options.ignoredDirectories ?? DEFAULT_IGNORED_DIRECTORIES)+ const rootPath = join(options.repoRoot, ROOT_GUIDE)+ const errors: string[] = []+ if (!existsSync(rootPath)) {+ return { errors: [`Missing root ${ROOT_GUIDE}`], guides: [], listed: [] }+ }++ const guides = walkGuides(options.repoRoot, options.repoRoot, ignored).sort()+ const listed = listedGuides(readFileSync(rootPath, 'utf8'))+ const listedSet = new Set(listed)+ const guideSet = new Set(guides)++ for (const guide of guides) {+ if (!listedSet.has(guide)) errors.push(`${guide} is not listed in the root ${ROOT_GUIDE} map`)+ }+ for (const guide of listed) {+ if (!guideSet.has(guide)) errors.push(`Root ${ROOT_GUIDE} references missing guide ${guide}`)+ }++ return { errors, guides, listed }+}diff --git a/tools/docs/tests/guides.test.ts b/tools/docs/tests/guides.test.tsnew file mode 100644index 000000000..4d3bfe3d5--- /dev/null+++ b/tools/docs/tests/guides.test.ts@@ -0,0 +1,65 @@+import { describe, expect, test } from 'bun:test'+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { checkGuideMap, listedGuides } from '../src/guides'++async function repo(rootGuide: string, guides: string[] = []) {+ const repoRoot = await mkdtemp(join(tmpdir(), 'open-pencil-guides-'))+ await writeFile(join(repoRoot, 'AGENTS.md'), rootGuide, 'utf8')+ for (const guide of guides) {+ await mkdir(join(repoRoot, guide, '..'), { recursive: true })+ await writeFile(join(repoRoot, guide), '# Guide\n', 'utf8')+ }+ return repoRoot+}++describe('listedGuides', () => {+ test('collects unique nested guide paths written as inline code', () => {+ const markdown = [+ '| `packages/core` | Core | `packages/core/AGENTS.md`, `packages/vue/AGENTS.md` |',+ 'See `packages/core/AGENTS.md` again and `AGENTS.md` at the root.',+ 'Not a guide: `packages/core/README.md` or packages/vue/AGENTS.md without code spans.'+ ].join('\n')++ expect(listedGuides(markdown)).toEqual(['packages/core/AGENTS.md', 'packages/vue/AGENTS.md'])+ })+})++describe('checkGuideMap', () => {+ test('passes when every nested guide is listed and every listed guide exists', async () => {+ const repoRoot = await repo(+ '| `src` | App | `src/AGENTS.md` |\n| `tests` | Tests | `tests/AGENTS.md` |\n',+ [+ 'src/AGENTS.md',+ 'tests/AGENTS.md',+ 'node_modules/dep/AGENTS.md',+ '.claude/worktrees/other/packages/core/AGENTS.md'+ ]+ )++ const result = checkGuideMap({ repoRoot })++ expect(result.errors).toEqual([])+ expect(result.guides).toEqual(['src/AGENTS.md', 'tests/AGENTS.md'])+ expect(result.listed).toEqual(['src/AGENTS.md', 'tests/AGENTS.md'])+ })++ test('reports unlisted guides on disk and listed guides that do not exist', async () => {+ const repoRoot = await repo('Guides: `packages/vue/AGENTS.md`.\n', ['packages/core/AGENTS.md'])++ const result = checkGuideMap({ repoRoot })++ expect(result.errors).toEqual([+ 'packages/core/AGENTS.md is not listed in the root AGENTS.md map',+ 'Root AGENTS.md references missing guide packages/vue/AGENTS.md'+ ])+ })++ test('fails without a root guide', async () => {+ const repoRoot = await mkdtemp(join(tmpdir(), 'open-pencil-guides-empty-'))++ expect(checkGuideMap({ repoRoot }).errors).toEqual(['Missing root AGENTS.md'])+ })+})diff --git a/tools/release-packages/package.json b/tools/release-packages/package.jsonindex 1705d85d3..5bb5ef667 100644--- a/tools/release-packages/package.json+++ b/tools/release-packages/package.json@@ -20,5 +20,8 @@"es-toolkit": "^1.51.0","js-base64": "^3.9.3","valibot": "^1.4.2"+ },+ "devDependencies": {+ "nanotar": "^0.3.0"}}diff --git a/tools/release-packages/src/publish-dirs.ts b/tools/release-packages/src/publish-dirs.tsindex 8fe0b7865..a403e577c 100644--- a/tools/release-packages/src/publish-dirs.ts+++ b/tools/release-packages/src/publish-dirs.ts@@ -1,3 +1,4 @@+import { existsSync } from 'node:fs'import { cp, mkdir, rm, writeFile } from 'node:fs/promises'import { basename, dirname, join } from 'node:path'@@ -16,11 +17,16 @@ export interface PackagePublishConfig {directory: string}+/** Lists the files `npm pack` would ship from a package directory, relative to it. */+export type PackageFileLister = (sourceDir: string) => Promise<string[]>+export interface PreparePublishDirectoriesOptions {coreVersion: stringpackages: PackagePublishConfig[]root: stringoutRoot?: string+ /** Defaults to a real `npm pack --dry-run`; tests inject a listing to stay out of npm. */+ listPackageFiles?: PackageFileListerlog?: (message: string) => void}@@ -31,6 +37,7 @@ const PACKAGE_FIELDS = ['optionalDependencies'] as const satisfies ReadonlyArray<keyof PackageManifest>const PUBLISH_CONFIG_FIELDS = new Set(['access', 'provenance', 'registry'])+const LICENSE_FILE = 'LICENSE'export function publishPackageJSON(source: PackageManifest, coreVersion: string): PackageManifest {if (source.publishConfig) {@@ -82,10 +89,21 @@ export async function discoverPublishPackages(root: string): Promise<PackagePublreturn (await discoverPublicPackages(root)).map(packagePublishConfig)}+export async function npmPackFileList(sourceDir: string): Promise<string[]> {+ const listing = await runCommand({+ command: 'npm',+ args: ['pack', '--dry-run', '--json', '--ignore-scripts'],+ cwd: sourceDir,+ timeoutMs: 60_000+ })+ return parseNpmPack(listing.stdout).files+}+export async function preparePublishDirectories(options: PreparePublishDirectoriesOptions): Promise<void> {const outRoot = options.outRoot ?? join(options.root, '.publish')+ const listPackageFiles = options.listPackageFiles ?? npmPackFileListawait rm(outRoot, { recursive: true, force: true })await mkdir(outRoot, { recursive: true })@@ -94,19 +112,22 @@ export async function preparePublishDirectories(const destinationDir = join(outRoot, basename(pkg.directory))await mkdir(destinationDir, { recursive: true })- const listing = await runCommand({- command: 'npm',- args: ['pack', '--dry-run', '--json', '--ignore-scripts'],- cwd: sourceDir,- timeoutMs: 60_000- })- const files = parseNpmPack(listing.stdout).files+ // npm always packs a root LICENSE, so a package without its own gets the repository's text.+ const hasOwnLicense = existsSync(join(sourceDir, LICENSE_FILE))+ const rootLicense = join(options.root, LICENSE_FILE)+ if (!hasOwnLicense && !existsSync(rootLicense)) {+ throw new Error(`${pkg.directory}: no LICENSE in the package or the repository root`)+ }++ const files = await listPackageFiles(sourceDir)for (const relativePath of files) {const destination = join(destinationDir, relativePath)await mkdir(dirname(destination), { recursive: true })await cp(join(sourceDir, relativePath), destination, { dereference: false })}+ if (!hasOwnLicense) await cp(rootLicense, join(destinationDir, LICENSE_FILE))+const packageJSON = await readPackageManifest(join(sourceDir, 'package.json'))const publishJSON = publishPackageJSON(packageJSON, options.coreVersion)await writeFile(diff --git a/tools/release-packages/src/workflow.ts b/tools/release-packages/src/workflow.tsindex 1a9cd60ea..b3042c1df 100644--- a/tools/release-packages/src/workflow.ts+++ b/tools/release-packages/src/workflow.ts@@ -17,7 +17,11 @@ import { inspectTarball, validatePackedTarballs } from '@open-pencil/package-artimport { verifyArtifactConsumers } from '@open-pencil/package-quality-tools/consumer'import { NPM_RELEASE_POLICY } from './policy'-import { discoverPublishPackages, preparePublishDirectories } from './publish-dirs'+import {+ discoverPublishPackages,+ preparePublishDirectories,+ type PackageFileLister+} from './publish-dirs'export interface PublicationPlanEntry {package: WorkspacePackage@@ -26,6 +30,18 @@ export interface PublicationPlanEntry {export type PackagePublicationLookup = (pkg: WorkspacePackage) => Promise<boolean>+export interface PrepareReleaseOptions {+ listPackageFiles?: PackageFileLister+}++/** Packs a prepared package directory into `destination` and returns the tarball filename. */+export type PackDirectory = (directory: string, destination: string) => Promise<string>++export interface PackReleaseOptions {+ /** Defaults to a real `npm pack`; tests inject an in-process packer to stay out of npm. */+ packDirectory?: PackDirectory+}+export interface ReleasePaths {artifacts: stringprepared: string@@ -42,7 +58,10 @@ export function releasePaths(root: string): ReleasePaths {export { buildPublicPackages as buildReleasePackages }-export async function prepareReleasePackages(root: string): Promise<void> {+export async function prepareReleasePackages(+ root: string,+ options: PrepareReleaseOptions = {}+): Promise<void> {const packages = await discoverPublicPackages(root)const { version } = await readPackageManifest(join(root, 'package.json'))if (packages.length === 0) throw new Error('No public packages discovered')@@ -53,10 +72,21 @@ export async function prepareReleasePackages(root: string): Promise<void> {coreVersion: version,packages: await discoverPublishPackages(root),root,+ listPackageFiles: options.listPackageFiles,log: console.log})}+async function npmPackDirectory(directory: string, destination: string): Promise<string> {+ const result = await runCommand({+ command: 'npm',+ args: ['pack', '--json', '--pack-destination', destination],+ cwd: directory,+ timeoutMs: 60_000+ })+ return parseNpmPack(result.stdout).filename+}+async function packageIsPublished(pkg: WorkspacePackage, root: string): Promise<boolean> {const specifier = `${pkg.manifest.name}@${pkg.manifest.version}`try {@@ -88,9 +118,11 @@ export async function createPublicationPlan(export async function packReleasePackages(root: string,- isPublished?: PackagePublicationLookup+ isPublished?: PackagePublicationLookup,+ options: PackReleaseOptions = {}): Promise<PublicationPlanEntry[]> {const paths = releasePaths(root)+ const packDirectory = options.packDirectory ?? npmPackDirectoryconst plan = await createPublicationPlan(root, isPublished)await rm(paths.artifacts, { recursive: true, force: true })await mkdir(paths.artifacts, { recursive: true })@@ -98,13 +130,8 @@ export async function packReleasePackages(for (const entry of plan) {const { manifest } = entry.packageconst preparedDirectory = join(paths.prepared, basename(entry.package.directory))- const result = await runCommand({- command: 'npm',- args: ['pack', '--json', '--pack-destination', paths.artifacts],- cwd: preparedDirectory,- timeoutMs: 60_000- })- console.log(`Packed ${manifest.name}: ${parseNpmPack(result.stdout).filename}`)+ const filename = await packDirectory(preparedDirectory, paths.artifacts)+ console.log(`Packed ${manifest.name}: ${filename}`)}await validatePackedTarballs(paths.artifacts)diff --git a/tools/release-packages/tests/publish-dirs.test.ts b/tools/release-packages/tests/publish-dirs.test.tsindex a40fee778..02221410c 100644--- a/tools/release-packages/tests/publish-dirs.test.ts+++ b/tools/release-packages/tests/publish-dirs.test.ts@@ -9,12 +9,12 @@ import {publishPackageJSON} from '#release/publish-dirs'-async function fixtureRoot() {+async function fixtureRoot({ rootLicense = true } = {}) {const root = join(tmpdir(), `open-pencil-release-packages-${crypto.randomUUID()}`)await mkdir(join(root, 'packages/example/dist'), { recursive: true })await writeFile(join(root, 'packages/example/dist/index.js'), 'export {}\n')await writeFile(join(root, 'packages/example/README.md'), '# Example\n')- await writeFile(join(root, 'packages/example/LICENSE'), 'fixture license\n')+ if (rootLicense) await writeFile(join(root, 'LICENSE'), 'root license\n')await writeFile(join(root, 'package.json'), JSON.stringify({ workspaces: ['packages/example'] }))await writeFile(join(root, 'packages/example/package.json'),@@ -114,7 +114,7 @@ describe('preparePublishDirectories', () => {})expect(await readFile(join(outRoot, 'example/dist/index.js'), 'utf8')).toBe('export {}\n')- expect(await readFile(join(outRoot, 'example/LICENSE'), 'utf8')).toBe('fixture license\n')+ expect(await readFile(join(outRoot, 'example/LICENSE'), 'utf8')).toBe('root license\n')expect(await readFile(join(outRoot, 'example/README.md'), 'utf8')).toBe('# Example\n')expect(JSON.parse(await readFile(join(outRoot, 'example/package.json'), 'utf8'))).toEqual({name: '@open-pencil/example',@@ -126,4 +126,17 @@ describe('preparePublishDirectories', () => {types: './dist/index.d.ts'})}, 30_000)++ test('refuses to prepare a package without any license text before packing', async () => {+ const root = await fixtureRoot({ rootLicense: false })++ await expect(+ preparePublishDirectories({+ coreVersion: '0.13.2',+ outRoot: join(root, '.publish'),+ packages: await discoverPublishPackages(root),+ root+ })+ ).rejects.toThrow('no LICENSE in the package or the repository root')+ })})diff --git a/tools/release-packages/tests/workflow.test.ts b/tools/release-packages/tests/workflow.test.tsindex 150461252..f1070d34a 100644--- a/tools/release-packages/tests/workflow.test.ts+++ b/tools/release-packages/tests/workflow.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from 'bun:test'-import { mkdir, readdir, writeFile } from 'node:fs/promises'+import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { join, relative, sep } from 'node:path'import {buildReleasePackages,@@ -11,6 +11,40 @@ import {releasePaths,validatePublicationArtifacts} from '#release/workflow'+import { createTarGzip } from 'nanotar'++import { readTarball } from '@open-pencil/package-artifacts/tarball'++const FIXTURE_FILES = ['dist/index.js', 'dist/index.d.ts']++async function listFiles(directory: string, base = directory): Promise<string[]> {+ const entries = await readdir(directory, { withFileTypes: true })+ const nested = await Promise.all(+ entries.map(async (entry) => {+ const path = join(directory, entry.name)+ if (entry.isDirectory()) return listFiles(path, base)+ return [relative(base, path).split(sep).join('/')]+ })+ )+ return nested.flat().sort()+}++/** Packs a prepared directory the way npm lays out a tarball, without starting npm. */+async function packInProcess(directory: string, destination: string): Promise<string> {+ const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8')) as {+ name: string+ version: string+ }+ const files = await Promise.all(+ (await listFiles(directory)).map(async (name) => ({+ name: `package/${name}`,+ data: new Uint8Array(await readFile(join(directory, name)))+ }))+ )+ const filename = `${manifest.name.replace(/^@/, '').replace('/', '-')}-${manifest.version}.tgz`+ await writeFile(join(destination, filename), await createTarGzip(files))+ return filename+}async function createWorkspace() {const root = join(tmpdir(), `open-pencil-release-workflow-${crypto.randomUUID()}`)@@ -91,6 +125,7 @@ describe('release workflow', () => {JSON.stringify({ name: 'fixture', version: '1.0.0', workspaces: ['packages/example'] }))await writeFile(join(root, 'packages/example/dist/index.js'), 'export const ready = true\n')+ await writeFile(join(root, 'LICENSE'), 'fixture license\n')await writeFile(join(root, 'packages/example/dist/index.d.ts'),'export declare const ready: true\n'@@ -112,14 +147,22 @@ describe('release workflow', () => {}))- await prepareReleasePackages(root)- const plan = await packReleasePackages(root, async () => false)+ await prepareReleasePackages(root, { listPackageFiles: async () => FIXTURE_FILES })+ const plan = await packReleasePackages(root, async () => false, {+ packDirectory: packInProcess+ })expect(plan.map(({ package: pkg, status }) => [pkg.manifest.name, status])).toEqual([['@fixture/release-package', 'unpublished']])- expect(- (await readdir(releasePaths(root).artifacts)).filter((name) => name.endsWith('.tgz'))- ).toHaveLength(1)+ const artifacts = releasePaths(root).artifacts+ const tarballs = (await readdir(artifacts)).filter((name) => name.endsWith('.tgz'))+ expect(tarballs).toEqual(['fixture-release-package-1.0.0.tgz'])+ expect([...(await readTarball(join(artifacts, tarballs[0]))).entries].sort()).toEqual([+ 'package/LICENSE',+ 'package/dist/index.d.ts',+ 'package/dist/index.js',+ 'package/package.json'+ ])})test('builds discovered packages in dependency order', async () => {