Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(glb-diff): give the diff package its README and cover the ANSI renderer
nirholasdedcbca4f028
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 1c0a79ff2..46863a4f6 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -53,6 +53,7 @@ bottom.| Agent Symphony (economy as generative music) | [pages/symphony.html](pages/symphony.html) `→ /symphony`, engine [src/symphony.js](src/symphony.js), grammar [src/symphony-score.js](src/symphony-score.js) | Live | The live activity bus (`GET /api/feed` + `/api/feed-stream` SSE) rendered as WebAudio generative music: one synthesized note per real platform event, voice by event type (payments pluck, coin buys land as bass, new agents chime, guard refusals play dissonance, jackpots glissando), pitch register by amount (whales sit lower), stable per-actor motif + stereo position via FNV-1a hash, all quantized to one pentatonic scale so arbitrary event streams harmonize. Canvas visualization, live ledger with real click-throughs, and a MediaRecorder tap that exports a shareable audio clip of the master bus. A burst gate collapses event floods (a sniper sweep emitting dozens of identical guard events) into one accented note per actor per 1.5s. Solo mode narrows the stream to one participant client-side (`?agent=<id>` exact, `?actor=<label>` case-insensitive), reachable from the per-row "solo" control and from the "Listen →" link on every agent profile's Wallet Story card. No audio assets, no synthetic events. Tests: [tests/symphony-score.test.js](tests/symphony-score.test.js) || Platform activity feed | [pages/feed.html](pages/feed.html) `→ /feed` + [pages/community.html](pages/community.html) `→ /community`, backend [api/users/me/feed.js](api/users/me/feed.js) | Live | Reverse-chronological creation events (avatars, agents, coins, models, worlds) plus follow activity, merged at read time from `forge_creations`, `dioramas`, and `user_follows` (no separate event log to drift out of sync). `?scope=following` (default; session-gated, anonymous gets 401) vs `?scope=all` (public; powers `/community` and first-visit feeds); `limit` 1..50, `before` ISO cursor. Items deep-link to creator portfolios. Distinct from the Money Pulse ticker `GET /api/feed` ([docs/money-feed.md](docs/money-feed.md)). Docs: [docs/social-layer.md](docs/social-layer.md) || Follow graph | [api/users/[username]/follow.js](api/users/%5Busername%5D/follow.js) + [api/users/[username]/follows.js](api/users/%5Busername%5D/follows.js), table `user_follows`, buttons on [pages/profile.html](pages/profile.html) | Live | `GET` returns `{following, followed_by, followers_count, following_count}`; `POST`/`DELETE` are idempotent (session + CSRF, self-follow 400) and return the same envelope so one round-trip updates the button and the counts. A genuinely new edge (`ON CONFLICT DO NOTHING`) publishes a `follow` user event to the notification bell exactly once. Feeds the activity feed's following scope, search ranking, and the `followers` leaderboard metric. Tests: [tests/api/users-follow.test.js](tests/api/users-follow.test.js). Docs: [docs/social-layer.md](docs/social-layer.md) |+| Herald: messages delivered in person | SDK [herald-sdk/](herald-sdk) `→ /herald.js` (published as `@three-ws/herald`), rail [api/herald/announce.js](api/herald/announce.js) + [api/herald/stream.js](api/herald/stream.js) + [api/_lib/herald.js](api/_lib/herald.js), playground [pages/herald.html](pages/herald.html) `→ /herald` + [src/herald-page.js](src/herald-page.js), CLI [herald-sdk/bin/herald.mjs](herald-sdk/bin/herald.mjs), MCP [packages/herald-mcp/](packages/herald-mcp) | Live | A 3D character walks onto the page and says what happened, instead of a badge nobody notices. The library is the interrupt budget: importance scoring with pluggable scorers, a floor, quiet hours, a rate limit, dedupe with a TTL, freshness, batch collapse, focus awareness, and a stable reason for every message it refuses (`duplicate`, `rate-limited`, `quiet-hours`, `below-importance-floor`). Delivery is the walk companion ([walk-sdk](walk-sdk) `control.announce`) with an accessible `aria-live` card fallback for anything that cannot render 3D, and opt-in gesture-gated voice. **The rail is the part nobody expects:** `POST /api/herald/announce` with an API key carrying the `herald:announce` scope reaches the browser tab the caller has open over SSE, so `herald watch -- npm test` makes your avatar tell you the build finished, and an AI agent can do the same through the MCP server. An announcement is always delivered to the caller's own sessions (no recipient field, so no key can interrupt anyone else); the queue is Redis-backed, drained not broadcast, and expires in five minutes. Docs: [docs/herald.md](docs/herald.md), [docs/api-reference.md](docs/api-reference.md). Tests: [tests/herald-rules.test.js](tests/herald-rules.test.js), [tests/herald-runtime.test.js](tests/herald-runtime.test.js), [tests/herald-rail.test.js](tests/herald-rail.test.js), [tests/herald-announce-endpoint.test.js](tests/herald-announce-endpoint.test.js) || Notification bell & preferences | Event vocabulary [api/_lib/feed.js](api/_lib/feed.js) (`USER_EVENT_TYPES` → `publishUserEvent()` → `user_notifications`), endpoints [api/notifications/](api/notifications), preference matrix [api/_lib/notify-prefs.js](api/_lib/notify-prefs.js), bell client [src/notifications.js](src/notifications.js), avatar announcements [src/notification-herald.js](src/notification-herald.js), settings panel [src/dashboard-next/pages/settings.js](src/dashboard-next/pages/settings.js) | Live | In-app inbox covering remixes ([api/x402/remix-asset.js](api/x402/remix-asset.js)), DMs ([api/friends/messages.js](api/friends/messages.js)), coin bonding-curve graduations (pump cron in [api/cron/[name].js](api/cron/%5Bname%5D.js)), follows, sales, purchases, IRL, market, and account events. Preferences are a category × channel matrix (`in_app` always on; push/email/telegram/avatar are per-category opt-outs) edited from `/dashboard/settings`. **The `avatar` channel delivers in person:** for a fresh, unread notification in an opted-in category the corner companion walks on screen, gestures, and says the line with a link straight to it, summoning itself for that one message and retreating if it was off ([walk-sdk](walk-sdk) `control.announce`). Rules (15-minute freshness, once per browser, two per batch, visible tab only, device-level mute) live in [src/notification-herald.js](src/notification-herald.js). Docs: [docs/notifications.md](docs/notifications.md), [docs/social-layer.md](docs/social-layer.md). Tests: [tests/notification-herald.test.js](tests/notification-herald.test.js), [tests/notify-prefs.test.js](tests/notify-prefs.test.js) || Personal companion (`/companion`) | Page [pages/companion.html](pages/companion.html) `→ /companion` + [src/companion/](src/companion) (page, source cards, voice), API [api/companion/](api/companion) (settings, sources, contacts, events, `ingest`, `stream`, `poll`), engine [api/_lib/companion/](api/_lib/companion) (store, encrypted BYOK configs, triage, lanes for Telegram / iCal / IMAP), cron [api/cron/companion-poll.js](api/cron/companion-poll.js), migration [api/_lib/migrations/20260828140000_companion_harness.sql](api/_lib/migrations/20260828140000_companion_harness.sql) | Live | Turns a person's own inbox, chats, calendar and phone into deliveries a 3D character makes **in person**. BYOK per source (a Telegram bot the user made, a private iCal URL, IMAP with an app password) plus a universal bridge token anything can POST to. Every message is scored 0-100 by the shared deterministic rules ([@three-ws/companion/triage](packages/companion-sdk/src/triage-rules.js), the same module the CLI runs locally) and optionally refined by the user's own Anthropic key; above their threshold and outside quiet hours it is delivered through `companion_delivery` notifications, so the bell, Web Push, and the avatar channel all carry it. A contact's message is spoken by **that contact's avatar and voice** (`control.announce({ avatar })` in [walk-sdk](walk-sdk)). Live SSE at `/api/companion/stream` feeds the desktop app and any third-party body. Docs: [docs/companion.md](docs/companion.md). Tests: [tests/companion-triage.test.js](tests/companion-triage.test.js), [tests/companion-calendar.test.js](tests/companion-calendar.test.js), [packages/companion-sdk/tests/](packages/companion-sdk/tests) || Visitor feedback loop | Recorder [@three-ws/witness](packages/witness), capture + panel [src/feedback-companion.js](src/feedback-companion.js) (mounted by [src/walk-companion.js](src/walk-companion.js)), intake [api/feedback/report.js](api/feedback/report.js), queue API [api/feedback/index.js](api/feedback/index.js), scoring [api/_lib/feedback/triage.js](api/_lib/feedback/triage.js), store [api/_lib/feedback/store.js](api/_lib/feedback/store.js), cron [api/cron/feedback-triage.js](api/cron/feedback-triage.js), review page [pages/feedback.html](pages/feedback.html) `→ /feedback` + [src/feedback-page.js](src/feedback-page.js) | Live | The return channel on the corner companion: the visitor tells the avatar what broke and the report carries the route, build SHA, viewport, and the last console errors and failed requests the browser captured, so a vague sentence lands as an actionable row. The companion offers proactively at the one moment worth asking (right after the page actually threw), once per route per session, never in a background tab. **Feedback is data, never an instruction:** the model that reads untrusted visitor text writes six scalars to that report's own row and has no path to the repo, a deploy, or any other write; the admin-only `/feedback` queue groups reports into one row per problem and a person decides. **A report arrives as a runnable failing test:** the recorded session compiles into a Playwright spec asserting the failure is GONE (red until fixed, green after), reachable from the queue's Copy test button, `GET /api/feedback/repro`, `npm run feedback:repro`, and the `get_feedback_repro` MCP tool. Docs: [docs/feedback.md](docs/feedback.md), [docs/witness.md](docs/witness.md). Tests: [tests/feedback-triage.test.js](tests/feedback-triage.test.js) |@@ -315,6 +316,7 @@ packages/copy-mcp/ → @three-ws/copy-mcp (MCP server — mapackages/signals-mcp/ → @three-ws/signals-mcp (MCP server — discover signal feeds by proven edge; rank publishers)packages/alerts-mcp/ → @three-ws/alerts-mcp (MCP server — pump.fun alert rules: in-app, webhook, Telegram)packages/notifications-mcp/ → @three-ws/notifications-mcp (MCP server — inbox, read state, delivery prefs, Web Push)+packages/herald-mcp/ → @three-ws/herald-mcp (MCP server: an agent tells its human in person, on their own avatar)packages/billing-mcp/ → @three-ws/billing-mcp (MCP server — plan quotas, usage, invoices, receipts)packages/agentcore-payments-mcp/ → @three-ws/agentcore-payments-mcp (MCP server: platform-managed agent payment sessions)packages/activity-mcp/ → @three-ws/activity-mcp (MCP server — trending agents/coins, $THREE holder board, activity ticker)@@ -331,6 +333,7 @@ packages/spatial-mcp/ → @three-ws/spatial-mcp (Spatial MCP validpackages/agent-sniper/ → @three-ws/agent-sniper (engine + CLI + MCP server + x402 paid API — autonomous, self-custodial pump.fun sniper)packages/companion-sdk/ → @three-ws/companion (personal companion: client + SSE stream, shared triage rules, page stage, CLI, MCP server)walk-sdk/ → @three-ws/walk (page walking companion + playground + avatar picker)+herald-sdk/ → @three-ws/herald (deliver a message in person: rules engine, avatar/card presenters, sources, CLI)tour-sdk/ → @three-ws/tour (guided site tour: 3D guide walks a live site, spotlights sections)assistant-sdk/ → @three-ws/assistant (embeddable 3D avatar assistant widget: loader + one-tag CDN build)concierge-sdk/ → @three-ws/concierge (embeddable AI support chat with a lipsyncing 3D avatar)diff --git a/data/changelog.json b/data/changelog.jsonindex 439b70a21..c7b120274 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-28",+ "title": "Herald: your terminal can now make a 3D character walk onto your screen and talk to you",+ "summary": "We took the part of three.ws where an avatar delivers a notification in person and turned it into something anyone can use, on any website. @three-ws/herald is an open library: one line of code and a 3D character walks into the corner of your page, looks at the person using it, and tells them, with a link to the thing it is about. It is not a toast library. It is an interrupt budget: an importance floor, quiet hours, a rate limit, dedupe, freshness, batch collapse, and a stable reason for every message it refuses to deliver, so you can always answer why you did not hear about something. No GPU, an iframe, or reduced motion falls back to an accessible card that screen readers announce the same moment everyone else hears it. There is also a rail: with an API key, anything that can make an HTTPS request reaches the browser tab you already have open. Run npx @three-ws/herald watch -- npm test and your avatar tells you when the build finishes, keeping the exit code. Wire the MCP server into Claude or Cursor and an agent that worked for twenty minutes can walk on and tell you it is done. An announcement always goes to your own sessions, so no key can interrupt anyone but its owner. Try the whole thing, rules engine included, at three.ws/herald.",+ "tags": [+ "feature",+ "sdk"+ ],+ "link": "/herald"+ },{"date": "2026-08-28","title": "Every release note now shows you the code that shipped it",diff --git a/packages/agent-glance/src/index.js b/packages/agent-glance/src/index.jsindex a9889f513..55717e40a 100644--- a/packages/agent-glance/src/index.js+++ b/packages/agent-glance/src/index.js@@ -151,35 +151,62 @@ export function renderGlanceAnsi(card, opts = {}) {// Wide enough that the agent URL fits whole: a card whose last line is a// half-truncated uuid cannot be copied, which is most of why it is there.const width = Math.max(40, Math.min(100, opts.width || 68));+ const inner = width - 4;const c = (code, text) => (color ? `\u001b[${code}m${text}\u001b[0m` : String(text));const dot = { active: '32', idle: '33', new: '90' }[card.status] || '90';- const pad = (text) => {- const clipped = clip(text, width - 4);- return `${clipped}${' '.repeat(Math.max(0, width - 4 - visibleLength(clipped)))}`;+ const line = (text) => {+ const clipped = clipVisible(text, inner);+ return `${c('90', '│')} ${clipped}${' '.repeat(Math.max(0, inner - visibleLength(clipped)))} ${c('90', '│')}`;};- const line = (text) => `${c('90', '│')} ${pad(text)} ${c('90', '│')}`;const stats = (card.stats || []).map((s) => `${s.label} ${c('1', s.value)}`).join(' ');return [c('90', `╭${'─'.repeat(width - 2)}╮`),- line(`${c('1', clip(card.name, 24))} ${c(dot, '●')} ${c('90', card.status)}`),- line(c('90', clip(card.description || card.headline, width - 6))),+ line(`${c('1', card.name)} ${c(dot, '●')} ${c('90', card.status)}`),+ line(c('90', card.description || card.headline)),line(''),line(`${c('1', String(card.metric.value))} ${c('90', card.metric.label.toLowerCase())}`),- line(c('90', stats)),+ line(stats),line(''),line(c('90', card.url)),c('90', `╰${'─'.repeat(width - 2)}╯`),].join('\n');}-function clip(text, max) {+const ANSI_RE = /^\u001b\[[0-9;]*m/;++/**+ * Clip to a visible column count without cutting an escape sequence in half:+ * colour codes take no columns, so counting them (the naive slice) truncates+ * a coloured line early and leaves the terminal in the last colour it saw.+ */+function clipVisible(text, max) {const value = String(text ?? '');- return value.length <= max ? value : `${value.slice(0, Math.max(1, max - 1))}…`;+ let out = '';+ let visible = 0;+ let i = 0;+ let colored = false;+ while (i < value.length) {+ const escape = ANSI_RE.exec(value.slice(i));+ if (escape) {+ out += escape[0];+ i += escape[0].length;+ colored = true;+ continue;+ }+ if (visible >= max) {+ // One column is spent on the ellipsis, so step back if we are exactly full.+ const trimmed = out.replace(/.$/, '');+ return `${visible > max - 1 ? trimmed : out}…${colored ? '\u001b[0m' : ''}`;+ }+ out += value[i];+ visible += 1;+ i += 1;+ }+ return out;}// Length as the terminal sees it: ANSI escapes take no columns.function visibleLength(text) {- // eslint-disable-next-line no-control-regexreturn String(text).replace(/\u001b\[[0-9;]*m/g, '').length;}diff --git a/packages/glb-diff/README.md b/packages/glb-diff/README.mdnew file mode 100644index 000000000..0c8ce3928--- /dev/null+++ b/packages/glb-diff/README.md@@ -0,0 +1,266 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/glb-diff</h1>++<p align="center"><strong>git diff for 3D. Tell what actually changed between two glTF/GLB models, and whether it breaks anything.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/glb-diff"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/glb-diff?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/glb-diff?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/glb-diff?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#the-cli">CLI</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-decides">How it decides</a> ·+ <a href="https://three.ws/diff">Try it in the browser</a>+</p>++---++## Why++A checksum tells you two `.glb` files differ. It cannot tell a lossless+recompression from a rig that quietly lost three finger joints, and only one of+those takes your avatar off the screen.++That failure is specific and expensive: animation clips address joints **by+name**. Drop a joint, rename a bone, re-export through a tool that renumbers+`Mesh.001`, and the model still loads, still renders, and never moves. Nothing+throws. There is no error to grep for. You find out when someone tells you the+character is standing in a T-pose.++`glb-diff` is the check that catches it before the deploy. It reads both models,+matches their objects the way `git` matches renamed files, and reports every+difference with a severity you can gate a build on.++```+glb-diff avatar.v3.glb -> avatar.v4.glb+ BREAKING 12 change(s): +0 -3 ~6 renamed 3 moved 0+ Something a consumer references by name is gone. Clips, attachments, or materials bound to it will fail.++ !! Skeleton "Character" lost 2 joint(s): mixamorig:LeftEye, mixamorig:RightEye. Clips that target them will not play.+ ! 1 mesh(es) have different vertex data: "Body".+ ! Triangle count is down 21,006 (-42.8%).+ 3 object(s) kept their content and changed name.+```++## Install++```bash+npm install @three-ws/glb-diff+```++Node 18+. Works in the browser too (the [/diff](https://three.ws/diff) page runs+this exact package client side, and nothing is uploaded).++`meshoptimizer` is an optional peer dependency. Install it if your models ship+with `EXT_meshopt_compression`, which most web-optimized assets do:++```bash+npm install meshoptimizer+```++## Quick start++```js+import { readFile } from 'node:fs/promises';+import { diffModels, formatText } from '@three-ws/glb-diff';++const before = await readFile('avatar.v1.glb');+const after = await readFile('avatar.v2.glb');++const changes = await diffModels(before, after, { nameA: 'v1', nameB: 'v2' });++console.log(formatText(changes));+if (changes.severity === 'breaking') process.exit(1);+```++## The CLI++```bash+npx @three-ws/glb-diff before.glb after.glb+```++Either side may be a file path or an `http(s)` URL, so comparing a local build+against the copy already live on your CDN takes one command:++```bash+npx @three-ws/glb-diff dist/avatar.glb https://cdn.example.com/avatar.glb+```++| Flag | What it does |+| --- | --- |+| `--json` | Print the full change set as JSON |+| `--markdown` | Print a Markdown report, sized for a pull-request comment |+| `--fail-on <level>` | Exit 1 when severity reaches `cosmetic`/`minor`/`major`/`breaking` |+| `--verbose` | Include unchanged rows in the totals table |+| `--no-color` | Disable ANSI colour |++Exit codes are the contract a pipeline depends on, so they are deliberate:++| Code | Meaning |+| --- | --- |+| `0` | The diff ran and stayed below `--fail-on` |+| `1` | The diff ran and the severity reached `--fail-on` |+| `2` | The tool could not run: bad arguments, unreadable input, unparseable model |++A tool that returns `1` for both "your model regressed" and "I could not open the+file" is useless in a pipeline, which is why `2` exists.++### In a build++```bash+# Fail the build if an optimization pass broke the rig.+npx @three-ws/glb-diff src/avatar.glb dist/avatar.glb --fail-on breaking++# Post the report on the pull request.+npx @three-ws/glb-diff base.glb head.glb --markdown > diff.md+```++## API++### `diffModels(bytesA, bytesB, opts?)`++Read two models and diff them. Returns a `ChangeSet`.++```js+const changes = await diffModels(beforeBytes, afterBytes, { nameA: 'before.glb', nameB: 'after.glb' });+```++### `describeModel(bytes, meta?)` and `diffDescriptions(a, b)`++The two halves of `diffModels`, exposed separately because the interesting uses+are not always end to end. A **description** is a small, JSON-safe summary of a+model: hashes, counts, names, and structure, with no geometry buffers in it.++```js+const baseline = await describeModel(await readFile('base.glb'), { name: 'base.glb' });+await writeFile('base.description.json', JSON.stringify(baseline));++// Later, in another job, with the model itself long gone:+const candidate = await describeModel(await readFile('build.glb'), { name: 'build.glb' });+const changes = diffDescriptions(baseline, candidate);+```++That is how you keep a per-release baseline in CI without storing every+historical `.glb`, and how a browser can describe one file once and compare it+against many candidates without re-parsing.++### `formatText(changeset, opts?)` and `formatMarkdown(changeset)`++Render a change set. `formatText` takes `{ color, verbose }`; pass+`color: false` for a log file.++### `atLeast(severity, threshold)`++The severity comparison the CLI gates on, exported so your own gate matches:++```js+import { atLeast } from '@three-ws/glb-diff';+if (atLeast(changes.severity, 'major')) throw new Error('model regressed');+```++### The change set++```jsonc+{+ "version": 1,+ "identical": false,+ "severity": "breaking",+ "a": { "name": "before.glb", "sizeBytes": 780912, "generator": "glTF-Transform v4.4.0" },+ "b": { "name": "after.glb", "sizeBytes": 829780, "generator": "glTF-Transform v4.4.0" },+ "summary": { "changed": 98, "added": 6, "removed": 13, "modified": 70, "renamed": 4, "moved": 1 },+ "totals": {+ "triangles": { "a": 49112, "b": 28106, "delta": -21006, "pct": -42.8 }+ // ... vertices, joints, nodes, meshes, materials, textures, animations, skins, textureBytes, sizeBytes+ },+ "sections": {+ "skins": { "added": [], "removed": [], "renamed": [], "modified": [], "unchanged": 0, "changed": 3, "severity": "breaking" },+ "animations": { "...": "same shape" },+ "meshes": { "...": "same shape" },+ "nodes": { "...": "same shape, plus a `moved` list for reparented nodes" },+ "materials": { "...": "same shape" },+ "textures": { "...": "same shape" }+ },+ "extensions": { "used": { "added": [], "removed": [] }, "required": { "added": [], "removed": [] } },+ "asset": [],+ "highlights": [+ { "severity": "breaking", "text": "Skeleton \"Character\" lost 2 joint(s): mixamorig:LeftEye, mixamorig:RightEye. Clips that target them will not play." }+ ]+}+```++`highlights` is the layer you print when you only have room for three lines. The+sections are the layer you open when one of them is worth investigating.++## How it decides++### Matching: renames, not churn++Objects are paired in three passes, the same strategy `git` uses for file+renames:++1. **by key** the names agree, so the objects correspond+2. **by fingerprint** the names disagree but the content hashes identically, so+ it is a rename+3. **by similarity** neither agrees, but one candidate scores close enough that+ "the same object, edited and renamed" is more honest than an add plus a remove++Anything still unpaired really is an addition or a removal. Nodes get a fourth+distinction: a node that kept its name and changed parent is reported as+**moved**, because that changes where anything attached to it ends up.++Objects with no name in the file are labelled `(unnamed mesh 3)` and keyed to+their slot, so they only ever pair with the same slot on the other side rather+than accidentally matching an unrelated object that happened to come third.++### Tolerance: strict on edits, quiet on noise++Vertex data is hashed at a quantum of `1e-4` units. A re-export through Blender,+a `gltfpack` round trip, or a Draco decode perturbs positions in the `1e-6`+range and does **not** register. A genuine edit moves vertices by orders of+magnitude more and does.++Positions are not the only thing hashed. Normals, tangents, UVs, colors, and+**skin joints and weights** all participate, because a re-skin that leaves every+vertex exactly where it was still changes how the model deforms, and a+positions-only hash would call that unchanged.++### Severity++| Level | Meaning |+| --- | --- |+| `none` | Structurally identical |+| `cosmetic` | Only metadata changed. Nothing a renderer or a clip can observe |+| `minor` | Appearance changed. Still loads, animates, keeps its shape |+| `major` | Geometry or hierarchy changed. Re-check anything positioned against it |+| `breaking` | Something a consumer references by name is gone. Clips, attachments, or materials bound to it will fail |++The ladder is defined by what a downstream consumer notices, not by how large+the byte delta is. A 40 MB texture swap is `minor`. Deleting one joint is+`breaking`.++## Determinism++The same two files always produce the same change set, byte for byte, on any+machine. That is what makes the output worth committing, posting on a pull+request, and diffing against yesterday's.++## Also available as++- **A page.** [three.ws/diff](https://three.ws/diff) runs this package in your+ browser, overlays both models in 3D, and lets you wipe between them.+- **A free API.** `GET https://three.ws/api/3d/diff?a=<url>&b=<url>` returns the+ same change set. Keyless, no account. Add `&format=markdown` for a report.+- **An MCP tool.** `diff_models` on the three.ws MCP server, so an agent can ask+ whether the model it just optimized is still safe to ship.++## License++Apache-2.0. Built by [three.ws](https://three.ws).diff --git a/packages/render/tests/ansi.test.js b/packages/render/tests/ansi.test.jsnew file mode 100644index 000000000..3a33760f6--- /dev/null+++ b/packages/render/tests/ansi.test.js@@ -0,0 +1,126 @@+// Terminal encoding.+//+// The half-block encoder is the fallback everything else degrades to, so it has+// to be exactly right: two vertical pixels per cell, colours emitted only on+// change, and transparent pixels left as real gaps rather than black squares.++import { describe, it, expect } from 'vitest';+import { toHalfBlocks, to256, toKitty, toITerm, detectTerminal, CURSOR } from '../src/ansi.js';++const ESC = '\x1b';++/** A frame of solid colour, optionally transparent. */+function solid(width, height, [r, g, b, a = 255]) {+ const data = new Uint8ClampedArray(width * height * 4);+ for (let i = 0; i < width * height; i++) {+ data[i * 4] = r;+ data[i * 4 + 1] = g;+ data[i * 4 + 2] = b;+ data[i * 4 + 3] = a;+ }+ return { width, height, data };+}++describe('toHalfBlocks', () => {+ it('emits one line per two pixel rows', () => {+ expect(toHalfBlocks(solid(4, 8, [200, 100, 50])).split('\n')).toHaveLength(4);+ // An odd height still renders its last row.+ expect(toHalfBlocks(solid(4, 7, [200, 100, 50])).split('\n')).toHaveLength(4);+ });++ it('writes truecolor foreground and background for a solid frame', () => {+ const out = toHalfBlocks(solid(2, 2, [10, 20, 30]));+ expect(out).toContain(`${ESC}[48;2;10;20;30m`);+ expect(out).toContain(`${ESC}[38;2;10;20;30m`);+ expect(out).toContain('▀');+ });++ it('repeats a colour code only when the colour changes', () => {+ const out = toHalfBlocks(solid(20, 2, [10, 20, 30]));+ expect(out.split(`${ESC}[38;2;10;20;30m`).length - 1).toBe(1);+ });++ it('leaves fully transparent pixels as spaces', () => {+ const out = toHalfBlocks(solid(3, 2, [255, 0, 0, 0]));+ expect(out).not.toContain('▀');+ expect(out.replace(/\x1b\[[0-9;]*m/g, '')).toBe(' ');+ });++ it('composites semi-transparent pixels over a backdrop', () => {+ const half = solid(1, 2, [255, 255, 255, 128]);+ const out = toHalfBlocks(half, { backdrop: [0, 0, 0] });+ // 255 at alpha 128/255 over black lands near the midpoint.+ expect(out).toMatch(/38;2;12[0-9];/);+ });++ it('falls back to the 256-colour cube', () => {+ const out = toHalfBlocks(solid(2, 2, [10, 20, 30]), { truecolor: false });+ expect(out).toContain(`${ESC}[38;5;`);+ expect(out).not.toContain(';2;10;20;30m');+ });+});++describe('to256', () => {+ it('maps greys onto the grey ramp, not the colour cube', () => {+ expect(to256(0, 0, 0)).toBe(16);+ expect(to256(255, 255, 255)).toBe(231);+ const mid = to256(128, 128, 128);+ expect(mid).toBeGreaterThanOrEqual(232);+ expect(mid).toBeLessThanOrEqual(255);+ });++ it('maps saturated colours into the 6x6x6 cube', () => {+ const red = to256(255, 0, 0);+ expect(red).toBe(16 + 36 * 5);+ expect(to256(0, 255, 0)).toBe(16 + 6 * 5);+ expect(to256(0, 0, 255)).toBe(16 + 5);+ });+});++describe('inline image protocols', () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]);++ it('wraps a PNG in the kitty graphics protocol', () => {+ const out = toKitty(png, { columns: 40 });+ expect(out.startsWith(`${ESC}_Ga=T,f=100,c=40,m=0;`)).toBe(true);+ expect(out.endsWith(`${ESC}\\`)).toBe(true);+ });++ it('chunks a large payload with continuation markers', () => {+ const big = Buffer.alloc(8000, 1);+ const out = toKitty(big);+ expect(out.split(`${ESC}_G`).length - 1).toBeGreaterThan(1);+ expect(out).toContain('m=1;');+ });++ it('wraps a PNG in the iTerm2 inline escape', () => {+ expect(toITerm(png)).toContain(']1337;File=inline=1');+ });+});++describe('detectTerminal', () => {+ it('reads truecolor support from COLORTERM', () => {+ expect(detectTerminal({ COLORTERM: 'truecolor' }, null).truecolor).toBe(true);+ expect(detectTerminal({ TERM: 'xterm-256color' }, null).truecolor).toBe(false);+ });++ it('recognizes terminals that draw real images', () => {+ expect(detectTerminal({ KITTY_WINDOW_ID: '1' }, null).kitty).toBe(true);+ expect(detectTerminal({ TERM_PROGRAM: 'ghostty' }, null).kitty).toBe(true);+ expect(detectTerminal({ TERM_PROGRAM: 'iTerm.app' }, null).iterm).toBe(true);+ });++ it('falls back to a sane size with no tty', () => {+ const term = detectTerminal({}, null);+ expect(term.columns).toBe(80);+ expect(term.tty).toBe(false);+ });+});++describe('CURSOR', () => {+ it('moves up by a positive count only', () => {+ expect(CURSOR.up(3)).toBe(`${ESC}[3A`);+ expect(CURSOR.up(0)).toBe('');+ expect(CURSOR.up(-1)).toBe('');+ });+});