@canvakit/core 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CANVAKIT.md ADDED
@@ -0,0 +1,645 @@
1
+ # CANVAKIT.md — template + data-source specification (v1, alpha)
2
+
3
+ Canvakit is an **open standard for templates bound to data sources**. A canvakit
4
+ template is a single file with YAML frontmatter that declares named data sources
5
+ and a body written in a pluggable template engine (Mustache by default). A
6
+ canvakit runtime resolves the sources in parallel, merges the results into a
7
+ rendering context, and emits the body — typically HTML, but the spec doesn't
8
+ require a specific output format.
9
+
10
+ Canvakit's companion standard is
11
+ [DESIGN.md](https://github.com/google-labs-code/design.md) (aka designkit).
12
+ DESIGN.md covers **style** — tokens and atomic components. CANVAKIT covers
13
+ **structure + binding** — composable templates that agents fill in, update, and
14
+ bind to tool outputs. The two are orthogonal and often used together: canvakit
15
+ templates consume designkit tokens through the optional `@canvakit/designkit`
16
+ bridge.
17
+
18
+ The reference implementation is `@canvakit/core` (Node/TypeScript). Canvakit
19
+ templates are portable: any runtime that can resolve tool names, read files, and
20
+ call a template engine can render them.
21
+
22
+ ## Why canvakit
23
+
24
+ An agent that needs to _update_ a rendered UI with new data has two usual
25
+ options: re-emit the whole HTML (expensive in tokens, fragile), or hand-wire a
26
+ component library that knows how to refresh itself (heavy, framework-specific,
27
+ non-portable). Canvakit gives a third option: **render a template once, bind it
28
+ to live data sources, re-render when the data changes**. The template body is
29
+ the same between updates; only the resolved data differs. Agents don't re-author
30
+ HTML on every turn.
31
+
32
+ A canvakit template declares its _tool dependencies_. A runtime with those tools
33
+ available (Mastra, MCP client, Vercel AI SDK, a CI job with fixtures) can render
34
+ the template. The template is portable because the binding layer — `kind: tool`
35
+ references — is a normalized concept that every agent runtime speaks.
36
+
37
+ ## Document structure
38
+
39
+ A canvakit template has three parts:
40
+
41
+ 1. **YAML frontmatter** (required) — machine-readable declarations: identity,
42
+ data sources, variables.
43
+ 2. **Body** (required) — the content, interpreted by the chosen template engine.
44
+ In v1 the default engine is
45
+ [Mustache](https://mustache.github.io/mustache.5.html).
46
+ 3. **Output** — whatever the engine produces. HTML is the soft default (what v1
47
+ tooling assumes); non-HTML outputs are spec-legal.
48
+
49
+ ## Canonical filename
50
+
51
+ Canvakit templates use a double extension: `<name>.canvakit.<engine-ext>`.
52
+
53
+ - `q2-dashboard.canvakit.html` — Mustache-templated HTML
54
+ - `brief.canvakit.md` — Mustache-templated markdown
55
+ - `report.canvakit.mdx` — MDX-templated (Phase 3)
56
+
57
+ `find . -name '*.canvakit.*'` is the canonical glob. Editors autodetect the
58
+ template file type by the infix. The body engine is self-describing via the
59
+ final extension. The frontmatter `template: true` field is a redundant safety
60
+ check — tooling that loads files by glob can still catch "renamed but not a
61
+ template" mistakes.
62
+
63
+ The gallery + CLI resolve templates by the identity tuple
64
+ `(author, name, version)` from the frontmatter. The filename on disk is a
65
+ convention for humans and editors, not load-bearing for the registry.
66
+
67
+ ## YAML frontmatter
68
+
69
+ The frontmatter block must begin and end with lines containing exactly `---`.
70
+ Everything between is parsed as YAML.
71
+
72
+ ### Schema
73
+
74
+ ```yaml
75
+ # ── Identity (registry + tooling) ─────────────────────────────
76
+ template: true # required marker
77
+ name: <string> # required; slug-safe
78
+ version: <semver> # required
79
+ description: <string> # optional; one-liner for gallery
80
+ author: <string> # optional; registry populates from publish identity
81
+ # ── Rendering ─────────────────────────────────────────────────
82
+ renderer: mustache # optional; default "mustache"
83
+ type: email/verify-email # optional; template type for host-level resolution — see §Template resolution & overrides (v1.x)
84
+ design: dk:heritage # optional; designkit hint — see below
85
+ # ── Output medium (geometry + export defaults; see below) ─────
86
+ medium: web # web | document | presentation | image (default web)
87
+ page: # optional; print/image geometry + document chrome
88
+ size: A4 # A4|Letter | 16:9|4:3|1:1 | "<W>x<H>" | raw @page size
89
+ orientation: portrait # portrait | landscape
90
+ margin: 18mm # CSS page margin
91
+ cover: false # true ⇒ full-bleed first page
92
+ header: <string> # running header (document renderer)
93
+ footer: <string> # running footer (document renderer)
94
+ pageNumbers: true # "current / total" page numbers (document renderer)
95
+ # ── Refresh cadence (declarative; honored opportunistically) ──
96
+ refreshEvery: manual # manual | <duration> | on-tool-change
97
+ # ── Data ──────────────────────────────────────────────────────
98
+ variables: # authored defaults; overridable by caller
99
+ <string>: <any>
100
+ sources: # the binding layer
101
+ <name>:
102
+ kind: tool | static | file | query
103
+ # kind-specific fields — see §Data source kinds
104
+ ```
105
+
106
+ ### `design` and `forceDesign`
107
+
108
+ Two frontmatter fields select a design. Both accept the same scheme- prefixed
109
+ refs; they differ only in priority:
110
+
111
+ - **`design:`** — _fallback hint_. Used only when no workspace design is active.
112
+ Operator-set selection wins.
113
+ - **`forceDesign:`** — _override_. Bypasses workspace selection. The template
114
+ author is declaring "this canvas must render against this specific design."
115
+
116
+ Accepted ref shapes (extensible via `DesignSourceRegistry`):
117
+
118
+ - `dk:<preset-id>` — preset shipped with `@designkit-sh/core` (e.g.
119
+ `dk:heritage`, `dk:modern-minimal`).
120
+ - `ws:<path>` — workspace fs file (e.g. `ws:DESIGN.md`, `ws:_design/foo.md`).
121
+ - `kit:<slug>` — sugar for `ws:_design/<slug>.md`.
122
+ - `./brand.md` / `brand.md` / any path ending in `.md` — back-compat: bare paths
123
+ fall through to a workspace fs read.
124
+
125
+ Runtime callers may also force a design at the render call (e.g.
126
+ `renderCanvas({ designOverride: "dk:neon-grid" })`) — runtimes that support this
127
+ option pass it down to the bridge as the highest-priority ref.
128
+
129
+ When the `@canvakit/designkit` bridge is wired, design resolution priority is
130
+ (highest first):
131
+
132
+ 1. Runtime `designOverride` (caller force at render time)
133
+ 2. `forceDesign:` frontmatter (template author force)
134
+ 3. Workspace pointer — `_design/active.txt` → `_design/<slug>.md`
135
+ 4. Workspace root `DESIGN.md` (Stitch drop-in)
136
+ 5. `design:` frontmatter hint (fallback)
137
+
138
+ The operator's workspace choice overrides the _fallback hint_ — an active
139
+ `DESIGN.md` represents operator intent, not accident. _Forces_ (1, 2)
140
+ intentionally bypass workspace selection: caller / author intent declares
141
+ "regardless of what's active globally, this canvas must use <X>." Templates that
142
+ want graceful degradation should still reference tokens from CSS via
143
+ `var(--color-foo, <fallback>)`.
144
+
145
+ ### `DesignSourceRegistry` (resolver extensibility)
146
+
147
+ Schemes are pluggable. Apps and packages register custom schemes via
148
+ `DesignSourceRegistry.register({ scheme, resolve })` — once registered, the
149
+ scheme works in `design:`, `forceDesign:`, and any runtime `designOverride`.
150
+ Built-ins ship with `dk:`, `ws:`, `kit:`. Common extensions: `db:<slug>`
151
+ (DB-backed kits), `npm:@brand/kit` (npm packages), `https://` (URL-fetched
152
+ kits).
153
+
154
+ A resolver returns a `DesignArtifact`:
155
+
156
+ ```typescript
157
+ interface DesignArtifact {
158
+ tokens: DesignFrontmatter // CSS vars (mandatory)
159
+ tailwindExtend?: Record<string, ...> // optional Tailwind theme overrides
160
+ fonts?: Array<{ family, weights?, href? }> // optional explicit font imports
161
+ }
162
+ ```
163
+
164
+ `tokens` always emits as `:root { --color-* }`. `tailwindExtend` (when present)
165
+ merges into the Tailwind bridge's default config so a design can ship its own
166
+ utility classes. `fonts` (when present) takes precedence over the auto-detection
167
+ from typography tokens.
168
+
169
+ ### `medium` and `page` (output medium)
170
+
171
+ A canvas's **medium** is its intended output form — a _design constraint_, not a
172
+ post-hoc file format. It shapes both how the canvas is authored (geometry, type
173
+ scale, whether it scrolls or paginates) and the export defaults. It is
174
+ orthogonal to `design` (a designkit = palette / tokens / theme); `medium` is
175
+ geometry / output. They compose (`document` + a `corporate` design).
176
+
177
+ | `medium` | geometry | default export |
178
+ | --------------- | ------------------------------ | ------------------- |
179
+ | `web` (default) | responsive, scrollable | `html` / `html-zip` |
180
+ | `document` | A4/Letter portrait, paginated | `pdf` (numbered) |
181
+ | `presentation` | 16:9 landscape slides | `pdf` (slides) |
182
+ | `image` | a single fixed-dimension frame | `png` |
183
+
184
+ `page` tunes the geometry and document chrome (all optional; defaults per
185
+ medium). `size` accepts named paper (`A4`, `Letter`), a slide aspect (`16:9`,
186
+ `4:3`, `1:1`), `"<W>x<H>"` pixels (`1080x1080`, `1200x630`), or a raw CSS
187
+ `@page size` value. `cover: true` makes the first page full-bleed.
188
+
189
+ **Document chrome** (`header` / `footer` / `pageNumbers`) and a **Table of
190
+ Contents with real page numbers** are produced by the _document renderer_, not
191
+ plain CSS — headless Chrome has no `@page` margin boxes and no `target-counter`.
192
+ The renderer (`@canvakit/export`'s CDP path + `renderDocumentPdf`) delivers them
193
+ via `Page.printToPDF` header/footer templates plus a two-pass page-number
194
+ extraction (render content → locate headings → render the TOC with the found
195
+ numbers → merge cover + TOC + content → re-stamp clickable TOC links). Geometry
196
+ and a full-bleed cover work on the base single-pass renderer; the running
197
+ header/footer/page-numbers/TOC need the document renderer.
198
+
199
+ The exporter reads `medium` / `page` automatically (`exportCanvas` fills them
200
+ from frontmatter; an explicit `format` / `pageSpec` at the call site wins).
201
+
202
+ ### `refreshEvery`
203
+
204
+ Declarative cadence hint. A runtime MAY honor it by scheduling re-renders;
205
+ runtimes that can't (browser playground, one-shot CLI) treat it as `manual`.
206
+ Accepted values:
207
+
208
+ - `manual` (default) — never auto-refresh
209
+ - duration string (`60s`, `5m`, `1h`) — timer-driven refresh
210
+ - `on-tool-change` — re-render when any `kind: tool` source's input invalidates
211
+ (for agent runtimes with tool tracking)
212
+
213
+ ### Identity tuple
214
+
215
+ `(author, name, version)` is the canonical registry key. Templates published to
216
+ a canvakit gallery MUST carry all three. Local / in-workspace templates MAY omit
217
+ `author` — the identity is local to the workspace.
218
+
219
+ ## Template resolution & overrides (v1.x)
220
+
221
+ Hosts that render canvakit templates inside a product (a mailer, a document
222
+ service, a hub) can layer **overrides** on top of the default template set. This
223
+ is a host-side resolution mechanism, generic over the template type; the `type:`
224
+ frontmatter field is what makes a template addressable by it.
225
+
226
+ ### The `type` field
227
+
228
+ `type: <string>` (optional, v1.x) identifies the template's type for host-level
229
+ resolution, namespaced by convention `<medium>/<name>` (e.g.
230
+ `email/verify-email`, `report/q2-summary`). It is orthogonal to the identity
231
+ tuple `(author, name, version)`: the tuple identifies a specific published
232
+ template, `type` identifies a _slot_ that several candidates can fill. The field
233
+ is optional and retro-compatible — existing templates are unaffected, and
234
+ tooling that ignores `type` keeps working.
235
+
236
+ ### Resolution order (highest priority first)
237
+
238
+ 1. **Active design kit override** — the design kit active in the host context
239
+ may ship its own template of the same `type`.
240
+ 2. **Namespace override** — per product / tenant namespace:
241
+ `templates/<ns>/<type>` (e.g. `templates/simone/email/verify-email`).
242
+ 3. **Default template** — shipped by the host package/app.
243
+
244
+ First match that passes validation wins (see below); a missing candidate falls
245
+ through silently.
246
+
247
+ ### Partial (graceful) overrides
248
+
249
+ An override does not have to redefine the whole template:
250
+
251
+ - **Tokens-only override** — the override layer provides only design tokens
252
+ (colors, typography, spacing); the default body renders with the override's
253
+ tokens. This is the cheapest, safest customization path.
254
+ - **Body override** — the layer supplies its own body for the same `type`. An
255
+ overridden body MUST declare the **same required variables** as the default
256
+ body it replaces. The runtime validates this before rendering; if validation
257
+ fails (e.g. the override references a variable the default never required, so
258
+ callers won't be supplying it), the runtime falls back to the next lower
259
+ resolution level and emits a warning. It never crashes the render.
260
+
261
+ Token precedence follows the ordinary layering: default tokens < namespace
262
+ tokens < active-kit tokens. Frontmatter-declared `variables` defaults still
263
+ apply on top as authored defaults, exactly as in §Context shape.
264
+
265
+ ### Versioning note
266
+
267
+ This mechanism (the optional `type:` field + host-side override resolution) is a
268
+ **minor addition to v1 (v1.x)**: purely additive, no breaking change. Templates
269
+ without `type:` are never picked up by the override resolver at any layer.
270
+
271
+ ## Data source kinds
272
+
273
+ Canvakit ships **two primitives** and **two filesystem shorthands**.
274
+
275
+ ### `tool` — primitive
276
+
277
+ ```yaml
278
+ weather: { kind: tool, ref: <tool-id>, params: { ... } }
279
+ ```
280
+
281
+ Invokes a tool by name with JSON params. The portable binding — any runtime that
282
+ can resolve tool names can satisfy it. `ref` resolves in three styles, and
283
+ implementations SHOULD support all three:
284
+
285
+ | Style | Example | Runtime behavior |
286
+ | ------------- | -------------------------------- | ---------------------------------------------------------- |
287
+ | Flat id | `searchFlights` | Look up in the host's local tool registry |
288
+ | Namespaced | `stripe.mrr`, `notion.pages.get` | Longest-prefix match against registered wildcard resolvers |
289
+ | MCP-qualified | `mcp://myserver/toolName` | Proxy through MCP |
290
+
291
+ Resolution precedence: **exact flat > longest wildcard > MCP**. Params are
292
+ passed through verbatim to the resolver; the returned value passes through
293
+ verbatim into the context.
294
+
295
+ ### `static` — primitive
296
+
297
+ ```yaml
298
+ header: { kind: static, value: "Welcome back" }
299
+ ```
300
+
301
+ Literal pass-through. Never fetched, never parsed. Useful for caller-supplied
302
+ defaults and per-template constants.
303
+
304
+ ### `file` — shorthand for `tool` + `readFile`
305
+
306
+ ```yaml
307
+ roadmap: { kind: file, path: /plans/q2.md }
308
+ ```
309
+
310
+ Read a single file from the render filesystem, parse by extension (see §Format
311
+ contract). A runtime without filesystem sugar MAY emit `kind: file` as
312
+ `{ kind: tool, ref: "readFile", params: { path } }` and implement the shape
313
+ conversion in its `readFile` tool — the observed value in the context is
314
+ identical.
315
+
316
+ The resolved value lands at the source name. For a markdown file, frontmatter
317
+ keys are flattened onto the resolved object alongside `$body`:
318
+
319
+ ```mustache
320
+ <h1>{{roadmap.title}}</h1> {{! frontmatter `title:` }}
321
+ <p>{{roadmap.owner}}</p> {{! frontmatter `owner:` }}
322
+ <article>{{{roadmap.$body}}}</article>
323
+ ```
324
+
325
+ For a CSV: `{{#roadmap.rows}}{{name}}{{/roadmap.rows}}`. For JSON / YAML: the
326
+ parsed shape is exposed as-is under `roadmap`.
327
+
328
+ ### `query` — shorthand for `tool` + `query`
329
+
330
+ ```yaml
331
+ tasks:
332
+ kind: query
333
+ include: /tasks/**/*.md
334
+ where: { status: todo }
335
+ sort: -updatedAt
336
+ limit: 20
337
+ fields: [title, priority, assignee]
338
+ ```
339
+
340
+ Fetch many files matching one or more globs; parse each by format; filter / sort
341
+ / project.
342
+
343
+ - `include` — glob pattern or array of patterns. A bare directory path (no glob
344
+ char) is interpreted as `<path>/**/*.md` for back-compat with canvakit's
345
+ pre-v1 `queryFiles` kind.
346
+ - `where` — field predicates on the parsed shape. Operators: equality, `_in`
347
+ (array membership), `_contains` (substring), `_before` / `_after` (date or
348
+ number compare).
349
+ - `sort` — `field` (asc) or `-field` (desc) on a parsed field.
350
+ - `limit` — max entries (default 50).
351
+ - `fields` — project into a subset of parsed keys.
352
+
353
+ Output: `[{ path, data }]` where `data` is the parsed content per the format
354
+ contract. **The entry is the iteration unit, not the parsed shape itself** —
355
+ templates address fields through `data.<key>`, not at the top level. `path` is
356
+ the source-relative file path (useful for links / debug).
357
+
358
+ ```mustache
359
+ {{#tasks}}
360
+ <li>
361
+ <a href="/{{path}}">{{data.title}}</a>
362
+ — {{data.assignee}} ({{data.priority}})
363
+ </li>
364
+ {{/tasks}}
365
+ ```
366
+
367
+ For a markdown query, `data` is `{ ...frontmatter, $body }` — frontmatter keys
368
+ are flattened on `data`, **not** nested under `data.frontmatter`. Use
369
+ `{{data.title}}`, never `{{data.frontmatter.title}}`. For CSV the per-entry
370
+ `data` is `{ columns, rows }`; for JSON / YAML it's the parsed shape as-is.
371
+
372
+ Equivalent `tool` form:
373
+ `{ kind: tool, ref: "query", params: { include, where, sort, limit, fields } }`.
374
+
375
+ ### Per-source status
376
+
377
+ Every resolution reports a status — runtimes MUST surface this so authors can
378
+ debug "empty render" cases without log-diving.
379
+
380
+ ```typescript
381
+ type SourceStatus =
382
+ | { status: "ok"; sampleKeys?: string[]; count?: number }
383
+ | { status: "missing"; reason: string }
384
+ | { status: "error"; reason: string }
385
+ ```
386
+
387
+ A failed source degrades its own key (returns `null` / `[]`); the render
388
+ completes with the remaining sources intact.
389
+
390
+ ### Deprecated kinds
391
+
392
+ - **`kind: integration`** (pre-v1) — remapped to `kind: tool` with the same
393
+ `ref`. Accepted in v1 with a parse-time warning; **removed in v2** (target:
394
+ 2026-Q4).
395
+ - **`kind: queryFiles`** (pre-v1) — remapped to `kind: query`. Bare directory
396
+ paths become `<path>/**/*.md` for continuity. Same deprecation cadence.
397
+ **Iteration shape changed**: pre-v1 entries were `{ path, frontmatter }`; v1
398
+ entries are `{ path, data }` with frontmatter flattened on `data`. Templates
399
+ carrying `{{frontmatter.x}}` references must be updated to `{{data.x}}` — the
400
+ kind rewrite alone does not touch the body.
401
+
402
+ ## Imports (composable canvases)
403
+
404
+ A template MAY declare an `imports` map in its frontmatter. Each entry is a
405
+ nested canvas that renders in isolation; the rendered body is exposed under
406
+ `{{{imports.<name>}}}` in the parent's context.
407
+
408
+ ```yaml
409
+ imports:
410
+ header:
411
+ template: parts/header.canvakit.html # no variables — pure partial
412
+ mrr:
413
+ template: widgets/mrr-card.canvakit.html # reusable widget, own sources
414
+ variables: { period: "Q2 2026" }
415
+ ```
416
+
417
+ Semantics:
418
+
419
+ - Each import is a **full nested render** — its own frontmatter parse, its own
420
+ `sources` resolution, its own engine pass, its own `_data` payload.
421
+ - Imports **inherit** the parent's filesystem, tool registry, and render
422
+ extensions (so `@canvakit/designkit` themes children automatically).
423
+ - Imports **do not inherit** the parent's `variables` or resolved sources —
424
+ scope is deliberately isolated. Pass values down explicitly via each entry's
425
+ `variables:` block.
426
+ - Per-source statuses from an imported canvas roll up into the parent's
427
+ `statuses` map under `<importName>.<sourceName>`.
428
+ - **Cycle protection**: a template path already in the active import chain is
429
+ rejected with a warning and renders as the empty string.
430
+ - **Depth cap**: at least 8 levels of nested imports. Runtimes MAY cap at a
431
+ lower value.
432
+ - Reference the rendered body with triple-brace: `{{{imports.mrr}}}`.
433
+ Double-brace would HTML-escape the rendered HTML.
434
+
435
+ ### Use cases
436
+
437
+ - **Shared layout fragments** (header, footer, nav) — imports with no variables
438
+ and no sources act as partials.
439
+ - **Reusable widgets** (a stripe-mrr-card, a flights-card) — self-contained
440
+ canvases composed into dashboards. Each re-renders against fresh tool data
441
+ when its ref is re-invoked; the parent doesn't need to know.
442
+ - **Base layouts** — a parent template with slots; child templates fill the
443
+ body.
444
+
445
+ ### Token economics
446
+
447
+ A composed dashboard ships with thin frontmatter + a body that references
448
+ `{{{imports.*}}}`. The agent authoring the dashboard doesn't re-emit every
449
+ widget's HTML; the import reference is a few tokens. Re-running a widget's
450
+ underlying tool re-renders just that widget's output, not the whole page.
451
+
452
+ ## Format contract
453
+
454
+ Both `file` and `query` parse a file's content by its extension into a uniform
455
+ shape. Canvakit runtimes MUST implement these mappings so templates see the same
456
+ data regardless of source format:
457
+
458
+ | Extension | Parsed shape |
459
+ | ------------------------- | ------------------------------------------------------- |
460
+ | `.json` | Parsed JSON (any shape) |
461
+ | `.yaml` / `.yml` | Parsed YAML (any shape) |
462
+ | `.csv` / `.tsv` | `{ columns: string[], rows: Record<string, string>[] }` |
463
+ | `.md` / `.markdown` | `{ ...frontmatter, $body: string }` |
464
+ | `.html` / `.htm` / `.txt` | `{ $text: string }` (escape-safe raw text) |
465
+ | (anything else) | `{ $text: string }` |
466
+
467
+ A template rolling up tasks from markdown frontmatter and pricing from a CSV
468
+ uses the same `kind: query` with two `include` patterns — the parsed shapes
469
+ differ per entry but the iteration pattern is identical.
470
+
471
+ ## Context shape
472
+
473
+ The render pipeline merges resolved sources into a context object and passes it
474
+ to the engine. Precedence (lowest to highest):
475
+
476
+ 1. Template-declared `variables` defaults
477
+ 2. Caller-provided `variables` overrides
478
+ 3. Resolved `sources` (wins — the dynamic data is the point)
479
+
480
+ Plus these well-known roots:
481
+
482
+ - **`$meta`** — `{ renderedAt, templatePath, renderedFrom, instanceSlug }`
483
+ - **`$design`** — flattened designkit tokens when the optional designkit bridge
484
+ is wired (e.g. `{{$design.colors.primary}}`). `null` when no design is active.
485
+ Authoring convention: reference tokens from CSS via
486
+ `var(--color-foo, <fallback>)` rather than emitting a competing
487
+ `:root { ... defaults ... }` block in the template body — the bridge's
488
+ injected `:root` can't override a later-in-body `:root` declaration (CSS
489
+ cascade), and inline `var()` fallbacks render cleanly whether the bridge is
490
+ wired or not.
491
+ - **`_data`** — entire context serialized as `<script>`-safe JSON. See
492
+ §Client-side rehydration.
493
+ - **`renderedAt`** — alias for `$meta.renderedAt` exposed at the top level for
494
+ older templates.
495
+
496
+ A caller-provided `variables` key that shadows a `sources` name is silently
497
+ replaced by the source (the dynamic value wins). Runtimes SHOULD emit a warning
498
+ so the collision is visible.
499
+
500
+ ## Client-side rehydration
501
+
502
+ Canvakit produces server-rendered content AND an embedded JSON copy of the same
503
+ context, so the browser can rehydrate typed values without re-fetching or
504
+ re-computing, without prescribing a frontend framework:
505
+
506
+ ```html
507
+ <script id="canvas-data" type="application/json">
508
+ {{{_data}}}
509
+ </script>
510
+
511
+ <script type="module">
512
+ const ctx = JSON.parse(document.getElementById("canvas-data").textContent)
513
+ // ctx.flights.flights is typed exactly as the tool returned it —
514
+ // draw sparklines, animate counters, filter a table client-side
515
+ // without duplicating logic in SQL or a second fetch.
516
+ </script>
517
+ ```
518
+
519
+ The triple-brace `{{{_data}}}` skips the engine's default HTML escaping (because
520
+ `_data` is already safe JSON — `<` in string values is pre-escaped to `<` to
521
+ neutralize stray `</script>` sequences). React islands, Solid signals, Vue refs,
522
+ and any other opinionated hydration contract build on this primitive.
523
+
524
+ ## Tool registry
525
+
526
+ A canvakit runtime hosts a tool registry that resolves `kind: tool` refs. The
527
+ reference implementation exposes one function:
528
+
529
+ ```typescript
530
+ registerTool(match, resolver)
531
+ ```
532
+
533
+ where `match` is one of:
534
+
535
+ - `"searchFlights"` — exact flat id
536
+ - `"stripe.*"` — namespaced wildcard (longest-prefix match)
537
+ - `"mcp://myserver/*"` — MCP prefix
538
+
539
+ Resolution precedence is exact flat > longest wildcard > MCP. Registering the
540
+ same `match` twice replaces the previous resolver (supports hot reload in dev).
541
+
542
+ ### Portability
543
+
544
+ A canvakit template with only `kind: tool` + `kind: static` entries is portable
545
+ to any runtime that implements the tool registry. The frontmatter becomes a
546
+ declaration of tool dependencies:
547
+
548
+ ```yaml
549
+ sources:
550
+ flights: { kind: tool, ref: searchFlights, params: { ... } }
551
+ mrr: { kind: tool, ref: stripe.mrr, params: { ... } }
552
+ ```
553
+
554
+ Render under Mastra → its tool registry resolves `searchFlights`; a registered
555
+ `stripe.*` handler resolves `stripe.mrr`.
556
+
557
+ Render under a Vercel AI app → the tools array supplies both.
558
+
559
+ Render under an MCP-speaking runtime → both proxied through MCP.
560
+
561
+ Render in CI with fixtures → each ref resolves to a mock.
562
+
563
+ Same template, different runtime, correct render.
564
+
565
+ The `file` / `query` shorthands exist because simple filesystem-driven templates
566
+ are the 80% case. A bare-bones renderer (filesystem + Mustache, no tool runtime)
567
+ handles them natively; a tool-runtime-only renderer maps them through the
568
+ `readFile` / `query` well-known tools.
569
+
570
+ ## Streaming — v1 limitation
571
+
572
+ Tools that stream incremental results (long-running search, multi-step agent
573
+ runs) are resolved fully before render in v1. Templates expecting progressive
574
+ rendering SHOULD use `refreshEvery` or `on-tool-change` to re-render after each
575
+ update. True streaming bodies (render-as-the-tool-streams) are out of scope for
576
+ v1.
577
+
578
+ ## Output
579
+
580
+ Whatever the engine produces. HTML is the **soft default** — the v1 Mustache
581
+ engine, the v1 playground, the v1 gallery preview, and all example templates in
582
+ this spec assume HTML. Non-HTML templates (`foo.canvakit.svg`,
583
+ `foo.canvakit.xml`, `foo.canvakit.csv`) are spec-legal but outside v1 tooling's
584
+ polished path; runtimes MAY refuse them or render without preview.
585
+
586
+ ### Export artifacts (`@canvakit/export`)
587
+
588
+ Generation (above) stays format-agnostic — it emits an HTML string. The
589
+ **export** layer turns that into a downloadable artifact, the `format` chosen by
590
+ the `medium` (or explicitly):
591
+
592
+ - `html` — the rendered document, as-is.
593
+ - `html-zip` — a self-contained bundle (referenced images/CSS inlined) for
594
+ offline use.
595
+ - `text` — an **LLM-readable markdown projection** (an `llms.txt` for the
596
+ canvas): headings, lists, links, tables, emphasis kept; visual chrome
597
+ stripped. The agent-facing counterpart to pdf/png.
598
+ - `png` — a full-page image (headless Chrome).
599
+ - `pdf` — a paginated document (headless Chrome). For a `document` medium, the
600
+ CDP renderer adds running header/footer + page numbers, and
601
+ `renderDocumentPdf` assembles a cover + a clickable Table of Contents with
602
+ real page numbers (see `medium` / `page` above).
603
+
604
+ ## Engine contract
605
+
606
+ A canvakit engine is a single function: `(body, context) => Promise<string>`. No
607
+ class hierarchy, no lifecycle. An MDX engine (Phase 3) and a Handlebars engine
608
+ both fit this shape. A canvakit core implementation MUST NOT import React, DOM,
609
+ or any front-end framework; engines that need React import it themselves in a
610
+ separate package.
611
+
612
+ ## Unknown content handling
613
+
614
+ Per the consumer-behavior convention inherited from DESIGN.md:
615
+
616
+ | Scenario | Behavior |
617
+ | ------------------------------------------- | ------------------------------------------------- |
618
+ | Unknown frontmatter key | Preserve (round-trip); do not error. |
619
+ | Missing `template: true` marker | Warn; render anyway. |
620
+ | Unknown `sources` kind | Drop with warning; other sources still render. |
621
+ | Malformed source fields | Drop with warning; status reports the issue. |
622
+ | Missing / unreadable file for `file` source | Source status becomes `missing`; value is `null`. |
623
+ | Unregistered tool ref | Source status becomes `missing`; value is `null`. |
624
+ | Unknown `refreshEvery` value | Warn; fall back to `manual`. |
625
+
626
+ Runtimes SHOULD NOT crash a render over author / data mistakes — surface
627
+ per-source statuses and carry on.
628
+
629
+ ## Versioning
630
+
631
+ This spec is `v1, alpha` in 2026-04. Breaking changes land in `v2` (target:
632
+ 2026-Q4):
633
+
634
+ - `kind: integration` — removed
635
+ - `kind: queryFiles` — removed
636
+ - Stricter `refreshEvery` parsing
637
+
638
+ Additions (new kinds, new format mappings, new context roots) are non-breaking
639
+ and land as minor updates to v1.
640
+
641
+ ---
642
+
643
+ The reference implementation — `@canvakit/core` + `@canvakit/designkit` — lives
644
+ in the [openagentik/canvakit](https://github.com/openagentik/canvakit) repository. The
645
+ public gallery + playground + CLI live at [canvakit.sh](https://canvakit.sh).