openpencil/CLAUDE.md
Kayshen Xu 3caaa495bb
V0.5.2 (#82)
* feat(ai): scaffold pen-ai-skills package

* feat(ai): add pen-ai-skills core types

* feat(ai): add Vite plugin for skill file compilation

* feat(ai): add budget module with token estimation and category-priority trimming

* feat(ai): add skill loader with phase filtering and test injection

* feat(ai): add skill resolver with phase filter, intent match, and dynamic injection

* feat(ai): migrate all prompt content to skill files

Extract prompt content from 7 TypeScript source files into 27 Markdown
skill files with proper frontmatter. Each file contains phase, trigger,
priority, budget, and category metadata for the skill resolution engine.

Planning: decomposition, design-type
Generation: jsonl-format, jsonl-format-simplified, schema, layout,
  text-rules, overflow, style-defaults, variables, design-system,
  design-code, design-md
Validation: vision-feedback
Maintenance: local-edit, incremental-add, style-consistency
Domains: landing-page, dashboard, mobile-app, form-ui, cjk-typography
Knowledge: role-definitions, design-principles, icon-catalog,
  copywriting, examples

* feat(ai): add document context memory module

* feat(ai): add generation history memory module

* feat(ai): wire memory loading into skill resolver

Add memory field to ResolveOptions and load documentContext/generationHistory
into AgentContext with per-phase limits (planning:5, maintenance:3, others:0).
Export memory utility functions from package index.

* refactor(ai): use resolveSkills('planning') in orchestrator

Replace ORCHESTRATOR_PROMPT import with resolveSkills() from pen-ai-skills.
The planning phase system prompt is now resolved dynamically from skill
files instead of a static constant.

* refactor(ai): use resolveSkills('generation') in sub-agent

Replace SUB_AGENT_PROMPT + designPrinciples concatenation with
resolveSkills() from pen-ai-skills. The generation phase system prompt
is now resolved dynamically with flag-based skill filtering for
variables and design.md context.

* refactor(ai): use resolveSkills('validation') in design validation

Replace the 70-line inline VALIDATION_SYSTEM_PROMPT constant with a
lazy resolver function that loads the validation prompt from pen-ai-skills
skill files at call time.

* refactor(mcp): use skill registry for design prompt sections

* refactor(ai): remove old prompt files replaced by pen-ai-skills

Delete prompt files whose content has been migrated to the
pen-ai-skills package:
- ai-prompt-sections.ts (section registry, triggers, builders)
- orchestrator-prompts.ts (orchestrator + sub-agent prompts)
- design-system-prompts.ts (design token generation prompt)
- design-code-prompts.ts (HTML/CSS code-gen prompt)
- design-principles/ directory (5 principle files + index)

Consolidate role-definitions/ 8 sub-files into index.ts
(registerRole calls are runtime behavior, must be preserved).

Move buildDesignMdStylePolicy into ai-prompts.ts. Strip migrated
constants (PEN_NODE_SCHEMA, DESIGN_EXAMPLES, ADAPTIVE_STYLE_POLICY,
CHAT_SYSTEM_PROMPT, DESIGN_GENERATOR_PROMPT, etc.) from ai-prompts.ts.

Add pen-ai-skills alias to mcp:compile esbuild script.

* docs: add pen-ai-skills to architecture documentation

* fix(mcp): use h3 v2 createEventStream API for SSE endpoint

event.node.res was removed in h3 v2. Migrate to createEventStream
which handles SSE headers, streaming, and cleanup automatically.

* chore: update package versions and add pen-ai-skills to Dockerfile

- Bump version for multiple packages to 0.5.2, including pen-ai-skills, pen-codegen, pen-core, pen-figma, pen-renderer, pen-sdk, and pen-types.
- Add pen-ai-skills package to Dockerfile for inclusion in the build process.
- Update TypeScript configuration to ensure proper file inclusion.
- Modify GitHub Actions workflow to trigger on version tags.
- Enhance AI-related functionality by integrating resolveAgentModel for dynamic model resolution in chat and generation APIs.

* refactor: clean up unused imports and improve dynamic content handling

- Removed unused imports from various files, including SkillMeta and ResolvedSkill from types.test.ts, and estimateTokens from resolve-skills.ts.
- Updated the dynamic content injection function to use a more concise parameter in the regex replacement callback.

* chore: enhance build and CI workflows with skill generation

- Added a new script to generate the skill registry during post-installation in package.json.
- Updated the GitHub Actions workflows to include steps for compiling the CLI and generating the skill registry, ensuring all necessary components are built and ready for deployment.

---------

Co-authored-by: Fini <fini.yang@gmail.com>
2026-03-24 21:16:28 +08:00

7.5 KiB
Raw Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. Detailed module docs are in packages/CLAUDE.md, apps/web/CLAUDE.md, apps/desktop/CLAUDE.md, and apps/cli/CLAUDE.md — loaded automatically when working in those directories.

Commands

  • Dev server: bun --bun run dev (runs on port 3000)
  • Build: bun --bun run build
  • Preview production build: bun --bun run preview
  • Run all tests: bun --bun run test (Vitest)
  • Run a single test: bun --bun vitest run path/to/test.ts
  • Type check: npx tsc --noEmit
  • Install dependencies: bun install
  • Bump version: bun run bump <version> (syncs all package.json files)
  • Electron dev: bun run electron:dev (starts Vite + Electron together)
  • Electron compile: bun run electron:compile (esbuild electron/ to out/desktop/)
  • Electron build: bun run electron:build (full web build + compile + electron-builder package)
  • CLI compile: bun run cli:compile (esbuild CLI to apps/cli/dist/)
  • CLI dev: bun run cli:dev (run CLI from source via Bun)
  • Publish beta: bun run publish:beta [N] (publish all npm packages with beta tag)

Architecture

OpenPencil is an open-source vector design tool (alternative to Pencil.dev) with a Design-as-Code philosophy. Organized as a Bun monorepo with workspaces:

openpencil/
├── apps/
│   ├── web/           TanStack Start full-stack React app (Vite + Nitro)
│   ├── desktop/       Electron desktop app (macOS, Windows, Linux)
│   └── cli/           CLI tool — control the design tool from the terminal
├── packages/
│   ├── pen-types/     Type definitions for PenDocument model
│   ├── pen-core/      Document tree ops, layout engine, variables, boolean ops, clone utilities
│   ├── pen-codegen/   Multi-platform code generators
│   ├── pen-figma/     Figma .fig file parser and converter
│   ├── pen-renderer/  Standalone CanvasKit/Skia renderer
│   ├── pen-sdk/       Umbrella SDK (re-exports all packages)
│   └── pen-ai-skills/ AI prompt skill engine (phase-driven prompt loading + design memory)
├── scripts/           Build and publish scripts
└── .githooks/         Pre-commit version sync from branch name

Key technologies: React 19, CanvasKit/Skia WASM (canvas engine), Paper.js (boolean path operations), Zustand v5 (state management), TanStack Router (file-based routing), Tailwind CSS v4, shadcn/ui (UI primitives), Vite 7, Nitro (server), Electron 35 (desktop), TypeScript (strict mode).

Data Flow

React Components (Toolbar, LayerPanel, PropertyPanel)
        │ Zustand hooks
        ▼
┌─────────────────┐    ┌───────────────────┐
│  canvas-store   │    │  document-store   │ ← single source of truth
│  (UI state:     │    │  (PenDocument)    │
│   tool/selection │    │  CRUD / tree ops  │
│   /viewport)    │    │                   │
└────────┬────────┘    └────────┬──────────┘
         │                      │
         ▼                      ▼
   CanvasKit/Skia        canvas-sync-lock
   (GPU-accelerated      (prevents circular sync)
    WASM renderer)
  • document-store is the single source of truth. CanvasKit only renders.
  • User edits on canvas → SkiaEngine events → update document-store
  • User edits in panels → update document-store → SkiaEngine syncFromDocument() re-renders
  • canvas-sync-lock.ts prevents circular updates when canvas events write to the store

Multi-Page Architecture

PenDocument
  ├── pages?: PenPage[]   (id, name, children)
  └── children: PenNode[] (default/single-page fallback)

Design Variables Architecture

  • $variable references are preserved in the document store (e.g. $color-1 in fill color)
  • resolveNodeForCanvas() resolves $refs on-the-fly before CanvasKit rendering
  • Code generators output var(--name) for $ref values
  • Multiple theme axes supported (e.g. Theme-1 with Light/Dark, Theme-2 with Compact/Comfortable)

MCP Layered Design Workflow

External LLMs (Claude Code, Codex, Gemini CLI, etc.) can generate designs via MCP:

  • Single-shot: batch_design or insert_node — one call
  • Layered: design_skeletondesign_content × N → design_refine — phased generation with focused context
  • Segmented prompts: get_design_prompt(section=...) loads focused subsets (schema, layout, roles, icons, etc.)

Path Aliases

@/* maps to ./src/* (configured in apps/web/tsconfig.json and apps/web/vite.config.ts).

Styling

Tailwind CSS v4 imported via apps/web/src/styles.css. UI primitives from shadcn/ui. Icons from lucide-react.

CLI (apps/cli/)

The op command-line tool controls the desktop app or web server from the terminal. Arguments that accept JSON or DSL support three input methods: inline string, @filepath (read from file), or - (read from stdin).

  • App control: op start [--desktop|--web], op stop, op status
  • Design: op design <dsl|@file|-> — batch design DSL operations
  • Document: op open, op save, op get, op selection
  • Nodes: op insert, op update, op delete, op move, op copy, op replace
  • Export: op export <react|html|vue|svelte|flutter|swiftui|compose|rn|css>
  • Cross-platform: macOS, Windows (NSIS/portable), Linux (AppImage/deb/snap/flatpak)

CI / CD

  • .github/workflows/ci.yml — Push/PR on main and v* branches: type check, tests, web build
  • .github/workflows/build-electron.yml — Tag push (v*) or manual: builds Electron for all platforms, creates draft GitHub Release
  • .github/workflows/publish-cli.yml — Tag push (v*) or manual: publishes all @zseven-w/* npm packages in topological order
  • .github/workflows/docker.yml — Docker image build and push

Version Sync

  • Pre-commit hook (.githooks/pre-commit): extracts version from branch name (e.g. v0.5.00.5.0) and syncs to all package.json files
  • Manual bump: bun run bump <version> to set a specific version across all workspaces
  • Requires git config core.hooksPath .githooks (one-time setup per clone)

Code Style

  • Single files must not exceed 800 lines. Split into smaller modules when they grow beyond this limit.
  • One component per file, each with a single responsibility.
  • .ts and .tsx files use kebab-case naming, e.g. canvas-store.ts, use-keyboard-shortcuts.ts.
  • UI components must use shadcn/ui design tokens (bg-card, text-foreground, border-border, etc.). No hardcoded Tailwind colors like gray-*, blue-*.
  • Toolbar button active state uses isActive conditional className (bg-primary text-primary-foreground), not Radix Toggle's data-[state=on]: selector (has twMerge conflicts).

Git Commit Convention

Use Conventional Commits format: <type>(<scope>): <subject>

Types: feat, fix, refactor, perf, style, docs, test, chore

Scopes: editor, canvas, panels, history, ai, codegen, store, types, variables, figma, mcp, electron, renderer, sdk, cli

Rules: Subject in English, lowercase start, no period, imperative mood. Body is optional; explain why not what. One commit per change.

License

MIT License. See LICENSE for details.