Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ disable/replace a core row **in its own layer** — a later layer wins per row.
| `dsh-video` | `video` | video player tab; the bytes stay on the host and stream through a Range route |
| `dsh-media` | `media` | the pack's ffmpeg owner: `media_probe` / `media_run` / `media_frames`, the Range file route, remux jobs |
| `dsh-supercollider` | `supercollider` | SuperCollider the agent can play: ten `sc_*` tools over one warm `sclang` session (~31 ms a call, state kept) and a hand-written OSC client to `scsynth`, the installed `.schelp` reference indexed for `sc_help`, the `.scd` file workflow, five skills whose every example is compiled by a check, and one small console tab |
| `dsh-diagrams` | `diagrams` | Mermaid + TikZ + the vendored **Diagram Design** kit (204 examples, 44 documented types) and the seven `diagram_*` tools, validated on the host |
| `dsh-diagrams` | `diagrams` | Mermaid + TikZ + the vendored **Diagram Design** kit (204 examples, 44 documented types) + a **figure compiler** (`kind:"figure"`: a JSON spec measured, laid out, routed and emitted as one vector figure at a paper's column width), the seven `diagram_*` tools, validated on the host, and a reference corpus of two published paper figures rebuilt in that grammar |
| `dsh-shaders` | `shaders` | GLSL that **compiles for real**: seven `shader_*` tools over a disposable headless browser (ANGLE/SwiftShader, argv-only, `MAP * ~NOTFOUND`), a rung ladder that is always stated (`v1-static` → `v2-compiled` → `v3-drawn` → `v4-measured`), diagnostics mapped onto the author's own line numbers, five dialects kept apart (es100, es300, shadertoy, shader-skills, and desktop GLSL, which is **refused** rather than faked), emit for web / `.frag` / ISF / FFGL-scaffold / Shadertoy, a Shaders tab with a live WebGL preview and `@param` sliders, five skills whose every example a check compiles, and three vendored corpora (106 Radiant pages with 79 extracted fragments, shader-skills' 20 modules + 11 templates + 11 pieces, and a 48-link curated index) that each re-derive offline |
| `dsh-frontend-craft` | `frontend-craft` | front-end design craft: Impeccable's Apache-2.0 corpus (24 commands, 41 references) vendored at a pinned commit, its 61-rule detector built to a 4.5 MB WebAssembly module shipped in the package, `fe_context` / `fe_detect` / `fe_direction` / `fe_render` / `fe_artifact`, and a **Frontend** tab of findings, artifacts, directions and rendered previews. No network, no install, no engine download |
| `dsh-rust-dev` | `rust-dev` | Rust as a surface: `rust_status` (toolchain / components / targets / workspace — the four facts that fail independently), `cargo_check` (diagnostics parsed from `--message-format=json`, codes and `file:line:col`, duplicates collapsed), `cargo_test`, `cargo_build` (artefact path and size), `rust_deps` (duplicate versions, feature chains), `rust_backtrace` (demangled frames classed into your code / a dependency / the runtime), and four skills including egui/eframe/wgpu. `--offline` by default, nothing installed, a build is never presented as read-only. Host-only |
Expand Down
67 changes: 62 additions & 5 deletions packages/dsh-diagrams/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ reads, addressed without naming one (`dsh-resource://diagram/library/<id>`).
(re-validate; no revision bump, report kept), `diagram_publish` (copy into the LIBRARY), `diagram_delete` and
`diagram_kit` (the vendored design kit: `catalog`, `reference`, `example`, `insert`) — each taking an optional
`scope` (`conversation` | `library`), a bare id resolving **library-first**.
- **Three kinds.** `mermaid` and `tikz` are languages; **`html`** is a complete self-contained HTML+SVG
document — the shape of the design kit's own examples.
- **Four kinds.** `mermaid` and `tikz` are languages; **`html`** is a complete self-contained HTML+SVG
document — the shape of the design kit's own examples; **`figure`** is a JSON spec the host
*compiles* — measured, laid out, routed and emitted as one vector figure (see below).
- **Every write is validated before storage**, so a broken diagram returns the parser's or compiler's
line-accurate error. Mermaid is parsed in a **child process** (a DOM stub and the same vendored engine the
browser uses); TikZ is compiled by the machine's engine (`pdflatex`, else `xelatex`, else `lualatex`); `html`
Expand All @@ -33,10 +34,60 @@ reads, addressed without naming one (`dsh-resource://diagram/library/<id>`).
write. `diagrams` (the index, `sidebar://diagrams`, `priority: 'builtin'`) lists the library, this
conversation and the **design kit**, with the one guide entry at `order: 40` (after Files 10, Editor 20,
History 30), and a `tool.call.toolview` card per tool draws it inline.
- **Export** saves what each kind can actually produce - `mmd`/`md`/`svg`/`png` for Mermaid (no PDF), `tex`/`pdf`/`svg`/`png` for TikZ, `html`/`svg` for the kit (no PNG) - to the **Desktop of the machine running the harness**,
- **Export** saves what each kind can actually produce - `mmd`/`md`/`svg`/`png` for Mermaid (no PDF), `tex`/`pdf`/`svg`/`png` for TikZ, `html`/`svg` for the kit (no PNG), `json`/`svg`/`png` for a figure (the spec, the compiled vector, and the vector rasterised 3× by the panel) - to the **Desktop of the machine running the harness**,
create-exclusively; the client names a format, never a path (a browser download is the fallback). An `html`
diagram exports as `.html` (the composed document a person can open) and `.svg` (the picture inside it).

## The figure compiler (`kind: "figure"`)

A paper figure is not a drawing, it is a **layout problem**: 40–200 labelled boxes, measured type,
leaders anchored to one byte of a bar, and a print size the journal fixes. The `figure` kind takes a
JSON spec and compiles it on the host, with no browser and no clock, so the same spec always produces
the same bytes:

```
spec → resolve → measure (Core-14 metrics) → place (rows/columns/panels) → route (leaders, arrows, braces)
→ emit SVG → check geometry (f0–f2) → [the panel rasterises a PNG in the browser]
```

| | |
|---|---|
| rungs | `f0-spec` (JSON, ids, links) → `f1-layout` (inside the page) → `f2-paper` (no overlap, no clipping, legible, greyscale-safe) → `f3-drawn` (the panel reported a picture) |
| primitives | `rows`, `columns`, `panel`, `text`, `list`, `code`, `strip`, `node`, `matrix`, `badge`, `legend`, `rule`, `spacer`, `stack` |
| inline markup | `**bold**`, `` `mono` ``, `{tone:text}` |
| connectors | `leader`, `arrow` (orthogonal, rounded), `brace`; an end is `"id.side"`, or `"strip.meta.bottom"` for one segment |
| sizes | **points**, because a paper is specified in points: a 7 pt label is `"size": 7` |
| presets | `ieee-single` 252 pt, `ieee-double` 516, `acm-single` 240, `acm-double` 504, `neurips` 397, `cvpr` 495, `slide` 720, `web` 540 |
| themes | `paper` (print), `editorial` (the kit's page), `dark` (screen only) |
| tones | roles, never hex: `ink`, `muted`, `meta`, `tensor`, `link`, `accent`, `warn`, `teal`, `yellow` — each with a luminance, which is what the greyscale check reads |
| export | `json` (the spec), `svg` (the compiled vector), `png` (rasterised 3× by the panel) |

**Diagnostics are the product.** A spec that would print badly comes back as geometry, not as a
silent picture:

```
overlap "pane-metadata" and "pane-tensors" overlap by 4×9pt around (120, 208).
print "card-kv-count" is set at 5.2pt, below the 5.5pt a printed figure can carry.
fit "code-tensors" has a line wider than its pane; at 250pt the pane needs 268pt.
grey tones "accent" and "link" have almost the same luminance; they merge in black and white.
```

### The reference corpus

`reference/figures/` is the benchmark, and it is what "paper level" means here. Each entry carries the
published original (`reference/targets/`), a written `anatomy.md`, the same figure rebuilt as
`spec.json`, the committed vector in `out/`, and a `rubric.json` of acceptance checks. Two entries ship:

| figure | width | what it proves |
|---|---|---|
| `gguf-file-layout` | 516 pt | a byte layout: a weighted strip, a brace, segment-anchored leaders, a boxed pointer tail, two monospaced panes |
| `neo-motivation` | 516 pt | a motivation plate: three-column reading order, ✗/✓ comparison cards, two property lists, a node pipeline with an arrow, a labelled matrix |

`checks/check-figure-corpus.mjs` rebuilds both, requires byte-identical output twice, fails on drift
against the committed SVG, and traces every rubric row to a block id and a label in the picture.
`reference/THIRD-PARTY.md` records each target's provenance, licence and sha256, and deleting a
target degrades the check to its structural tier instead of breaking it.

## The Diagram Design kit

Forty-four documented visual types and 204 worked examples, vendored whole from
Expand Down Expand Up @@ -84,7 +135,7 @@ table. The kit is *data*, not an engine — it gives the model a third kind to w
paths with **GET/HEAD/POST only** —
`/api/dsh-diagrams/{health,state,diagram,document,example,artifact,export,render-report,vendor/mermaid.js}` —
which is why the engine is one self-contained file on one route (ETag, ~3.4 MB) and why every write, delete
included, is a POST. Three skills are registered at runtime from the package folder **and** copied by both
included, is a POST. Four skills are registered at runtime from the package folder **and** copied by both
installers into `$DSH_HOME/skills` with a `.vncode-<package>` marker, so a person's own skill is never
overwritten.

Expand All @@ -95,6 +146,10 @@ overwritten.
page — inside a **4 MiB source budget per conversation** (charged once on replace, checked on write AND patch,
`BUDGET` on refusal) and a **16 MiB file cap**.
`$DSH_HOME/dsh-diagrams/library.json` is the same shape for the whole harness.
- **A figure is compiled once per spec**: its artifact key is the spec plus `FIGURE_RENDERER_VERSION`,
so editing one field recompiles and an engine change invalidates every cached figure instead of
serving a picture the current code would not produce. A spec is a document like a TikZ source and
lives under the same 256 KiB ceiling.
- **Cache**: `artifacts/<sha256[0:24]>/{doc.tex,doc.pdf,doc.svg,doc.png,meta.json}`, keyed by engine + renderer
+ normalized source, LRU-pruned at **200 MiB**, **8 MiB** per artifact; a cache hit re-reads the verdict it
was cached with. An `html` diagram produces no artifact: there is nothing to compile and the frame is the
Expand Down Expand Up @@ -122,9 +177,10 @@ overwritten.

```sh
node scripts/checks/check-client-bundles.mjs # tab types, seats, cards, the frame, verdicts
node scripts/checks/check-node-routes.mjs # routes, tools, store, kit, compile, export, drift, budgets
node scripts/checks/check-node-routes.mjs # routes, tools, store, kit, compile, figure, export, drift, budgets
node scripts/checks/check-skill-examples.mjs # every fenced skill example, parsed or compiled
node packages/dsh-diagrams/checks/check-diagrams-kit.mjs # the kit, the corpus, the port
node packages/dsh-diagrams/checks/check-figure-corpus.mjs # both reference figures: build, determinism, drift, rubric
```

`check-diagrams-kit.mjs` travels with this package. It runs the vendored tree's own `--check`, walks all **209**
Expand All @@ -138,3 +194,4 @@ node packages/dsh-diagrams/vendor/build.mjs --check # fail on drift (offline)
node packages/dsh-diagrams/vendor/design/build.mjs --check # re-hash the kit (offline)
```


139 changes: 139 additions & 0 deletions packages/dsh-diagrams/checks/check-figure-corpus.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// check-figure-corpus.mjs — the reference corpus is a benchmark, so it has to run.
//
// Why this exists: `reference/figures/` is what "paper level" MEANS for this
// package. A figure compiler that nobody measures against a published figure is a
// drawing tool with an opinion. This check rebuilds every spec and asserts:
//
// - the spec compiles with no geometry diagnostic (f2-paper);
// - the same spec builds byte-identical SVG twice (determinism, which is what
// lets the artifact cache key on the source);
// - the committed `out/figure.svg` is what the current compiler produces (DRIFT
// otherwise: the corpus is a regression target, not a screenshot);
// - every rubric row is traceable: its block ids exist, its labels appear in the
// built picture, its caption exists, and its type floor holds;
// - a committed target still hashes to what its rubric records.
//
// Run: node packages/dsh-diagrams/checks/check-figure-corpus.mjs
import { createHash } from 'node:crypto'
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { buildFigure } from '../lib/figure/index.js'
import { MIN_PRINT_TEXT } from '../lib/figure/constants.js'

const here = path.dirname(fileURLToPath(import.meta.url))
const packageRoot = path.resolve(here, '..')
const referenceRoot = path.join(packageRoot, 'reference')
const figuresRoot = path.join(referenceRoot, 'figures')

let failures = 0
function check(label, actual, expected = true) {
const ok = actual === expected
if (!ok) failures += 1
const shown = typeof actual === 'string' || typeof actual === 'number' ? ' "' + String(actual).slice(0, 160) + '"' : ''
console.log((ok ? 'ok ' : 'FAIL ') + label + shown)
}

/** Every block id in a spec, including a strip's segment and tail addresses. */
function collectIds(blocks, into = new Set()) {
for (const entry of blocks ?? []) {
const block = entry && entry.block ? entry.block : entry
if (!block || typeof block !== 'object') continue
if (typeof block.id === 'string' && block.id.length > 0) {
into.add(block.id)
if (Array.isArray(block.segments)) {
for (const segment of block.segments) if (segment && segment.id) into.add(block.id + '.' + String(segment.id))
if (block.tail) into.add(block.id + '.tail')
}
}
if (Array.isArray(block.children)) collectIds(block.children, into)
}
return into
}

/** The text a reader can see in the built SVG (tags stripped, entities decoded). */
function visibleText(svg) {
return String(svg)
.replace(/<[^>]+>/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&amp;/g, '&')
}

if (!existsSync(figuresRoot)) {
console.log('skip: no reference figures (the package still ships the grammar)')
process.exit(0)
}

const folders = readdirSync(figuresRoot).filter((name) => statSync(path.join(figuresRoot, name)).isDirectory()).sort()
check('the corpus has figures', folders.length > 0)

for (const slug of folders) {
const folder = path.join(figuresRoot, slug)
const specPath = path.join(folder, 'spec.json')
const outPath = path.join(folder, 'out', 'figure.svg')
console.log('\n# ' + slug)

check(slug + ': anatomy.md is written', existsSync(path.join(folder, 'anatomy.md')))
check(slug + ': SOURCE.md records provenance', existsSync(path.join(folder, 'SOURCE.md')))
if (!existsSync(specPath)) {
check(slug + ': spec.json exists', false)
continue
}
const source = readFileSync(specPath, 'utf8')
const first = buildFigure(source)
const second = buildFigure(source)
check(slug + ': compiles to f2-paper', first.rung, 'f2-paper')
check(slug + ': no geometry diagnostic', first.diagnostics.length, 0)
check(slug + ': builds byte-identical twice', first.svg === second.svg)
check(slug + ': draws something', String(first.svg ?? '').includes('<svg'))

if (!existsSync(outPath)) {
check(slug + ': out/figure.svg is committed', false)
continue
}
const committed = readFileSync(outPath, 'utf8')
check(slug + ': out/figure.svg matches the compiler (no drift)', committed === first.svg)
const metricsPath = path.join(folder, 'out', 'metrics.json')
if (existsSync(metricsPath)) {
const metrics = JSON.parse(readFileSync(metricsPath, 'utf8'))
check(slug + ': metrics width', metrics.width, first.width)
check(slug + ': metrics height', metrics.height, first.height)
}

const rubricPath = path.join(folder, 'rubric.json')
if (!existsSync(rubricPath)) {
check(slug + ': rubric.json exists', false)
continue
}
const rubric = JSON.parse(readFileSync(rubricPath, 'utf8'))
const spec = JSON.parse(source)
const ids = collectIds(spec.blocks)
const text = visibleText(first.svg)
const seen = new Set()
for (const row of rubric.checks) {
const where = slug + ': rubric ' + row.id
if (seen.has(row.id)) check(where + ' id is unique', false)
seen.add(row.id)
for (const id of row.blocks ?? []) check(where + ' names "' + id + '"', ids.has(id))
for (const label of row.labels ?? []) check(where + ' draws "' + label.slice(0, 32) + '"', text.includes(label))
}
const figure = spec.figure ?? {}
check(slug + ': the spec carries a caption', typeof figure.caption === 'string' && figure.caption.length > 20)
check(slug + ': the spec carries a description', typeof figure.description === 'string' && figure.description.length > 20)
check(slug + ': no type below the print floor', (first.stats?.smallestText ?? 0) >= MIN_PRINT_TEXT)

const targetName = typeof rubric.target === 'string' ? path.basename(rubric.target) : null
const targetPath = targetName ? path.join(referenceRoot, 'targets', targetName) : null
if (targetPath && existsSync(targetPath)) {
const digest = createHash('sha256').update(readFileSync(targetPath)).digest('hex')
check(slug + ': the committed target still hashes to the rubric', digest, rubric.targetSha256)
} else {
console.log('ok ' + slug + ': no target committed (structural tier only)')
}
}

console.log('\n' + (failures === 0 ? 'figure corpus ok: ' + folders.length + ' figure(s)' : failures + ' figure-corpus check(s) FAILED'))
process.exit(failures === 0 ? 0 : 1)
Loading