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
feat(materialize): ship the certificate, operator console, and insert-card surfaces with the print payment schema
nirholas8511de566d4e
diff --git a/api/_lib/migrations/20260902214500_print_order_payment.sql b/api/_lib/migrations/20260902214500_print_order_payment.sqlnew file mode 100644index 000000000..ad3cb107c--- /dev/null+++ b/api/_lib/migrations/20260902214500_print_order_payment.sql@@ -0,0 +1,49 @@+begin;++-- Materialize checkout: what an order was charged, and how we proved it.+--+-- The fulfillment migration landed everything about producing a print and+-- nothing about paying for one, because payment came later. It comes now, and+-- both lanes settle into these same columns:+--+-- * the human lane (POST /api/print/orders) quotes a Solana Pay intent. The+-- order carries the reference pubkey it asked the buyer to attach, and the+-- confirm step finds the transaction BY that reference and validates it+-- moved the right USDC to the right wallet. The reference is what makes a+-- payment attributable to one order without trusting anything the client says.+-- * the agent lane (POST /api/x402/print-order) settles through x402 before+-- the order row exists, so it arrives with a settled signature and no+-- reference. Nullable on purpose: only one of the two paths issues one.+--+-- quote_expires_at is the signed quote token's own expiry, copied out of the+-- token so the operator console and the expiry sweep can see a stale unpaid+-- order without decoding an HMAC.++alter table print_orders+ add column if not exists payment_reference text,+ add column if not exists payment_signature text,+ add column if not exists payment_chain text,+ add column if not exists payment_amount_atomics bigint,+ add column if not exists paid_at timestamptz,+ add column if not exists quote_expires_at timestamptz;++-- One order per reference. A reference is a freshly generated keypair's public+-- key, so a collision means a bug or a replay, and either should fail loudly at+-- insert rather than quietly attach a second order to someone else's payment.+create unique index if not exists print_orders_payment_reference_uniq+ on print_orders (payment_reference)+ where payment_reference is not null;++-- Settling the same transaction against two orders is the double-credit bug.+-- The database refuses it outright rather than relying on every caller checking.+create unique index if not exists print_orders_payment_signature_uniq+ on print_orders (payment_signature)+ where payment_signature is not null;++-- The unpaid-quote sweep's working set: orders still waiting on a buyer, oldest+-- first, so an expired intent can be closed without scanning the whole table.+create index if not exists print_orders_awaiting_payment_idx+ on print_orders (quote_expires_at)+ where status in ('created', 'quoted');++commit;diff --git a/api/_lib/print/adapters/manual.js b/api/_lib/print/adapters/manual.jsindex de691e6ea..7c685d22b 100644--- a/api/_lib/print/adapters/manual.js+++ b/api/_lib/print/adapters/manual.js@@ -5,7 +5,7 @@// is always a human: an operator takes the prepared STL/3MF off the queue,// runs it on a real bureau's machines (or their own), and reports what// happened. This adapter is the machine-readable face of that person. Its-// submit() puts the job on the operator's queue and pages the operator channel;+// submit() puts the job on the operator's queue and pages the operator channel.// its status() reads back what the operator recorded through the console.//// Consequences worth stating, because they are what makes this honest ratherdiff --git a/api/_lib/print/certificate.js b/api/_lib/print/certificate.jsindex 25c96c963..d2d9c76e4 100644--- a/api/_lib/print/certificate.js+++ b/api/_lib/print/certificate.js@@ -192,16 +192,22 @@ async function readAsset(url) {}/**- * Claim the next edition number for a series and insert the certificate, in one- * statement, retrying on the unique-index collision that a concurrent claim- * produces. The HAVING clause is what enforces the cap atomically: when the- * series is full the insert selects zero rows rather than writing an- * over-numbered certificate.+ * Claim the next edition number for a series and insert the certificate in one+ * statement, retrying the collision a concurrent claim produces.+ *+ * Two things make this atomic without a transaction, which matters because the+ * serverless driver has none: the unique index on (series_key, edition_no)+ * means only one of two simultaneous "max + 1" writers can win, and the HAVING+ * clause means a full series selects zero rows rather than writing an+ * over-numbered certificate. The loser recomputes and takes the next number, or+ * is told the edition is sold out. Exported because it is the primitive the+ * concurrency test exercises directly.** @param {object} row- * @returns {Promise<any>}+ * @returns {Promise<any>} the inserted certificate, or the one that already+ * existed for this order.*/-async function claimEdition(row) {+export async function claimEdition(row) {for (let attempt = 1; attempt <= EDITION_CLAIM_ATTEMPTS; attempt++) {try {const inserted = await sql`@@ -231,17 +237,13 @@ async function claimEdition(row) {}return inserted[0];} catch (err) {- // 23505 on the order index means someone else already certified this- // order: that is the idempotent answer, not a failure.- if (err?.code === '23505' && String(err?.constraint || '').includes('order_uniq')) {- const [existing] = await sql`select * from print_certificates where order_id = ${row.order_id} limit 1`;- if (existing) return existing;- }- // 23505 on the series index means a concurrent claim took this number.- // Recompute and try again; the loop is bounded so a pathological- // series cannot spin forever.- if (err?.code === '23505' && attempt < EDITION_CLAIM_ATTEMPTS) continue;- throw err;+ if (err?.code !== '23505') throw err;+ // A unique violation is one of two things, and the row tells us which:+ // this order was already certified (the idempotent answer), or a+ // concurrent claim took the number we computed (recompute and retry).+ const [existing] = await sql`select * from print_certificates where order_id = ${row.order_id} limit 1`;+ if (existing) return existing;+ if (attempt >= EDITION_CLAIM_ATTEMPTS) throw err;}}throw new PrintCertificateError(diff --git a/api/_lib/print/editions.js b/api/_lib/print/editions.jsindex b8923d59c..eff1b2fbf 100644--- a/api/_lib/print/editions.js+++ b/api/_lib/print/editions.js@@ -10,7 +10,7 @@// - the quote path calls assertEditionAvailable() BEFORE any money moves, so// a sold-out model refuses at the price, never after the payment;// - the certificate issuer claims the next edition number atomically at ship-// time (api/_lib/print/certificate.js) and freezes the cap onto the row;+// time (api/_lib/print/certificate.js) and freezes the cap onto the row,// - the creator sets it through setEditionLimit(), which refuses to cap a// series below what has already shipped.//diff --git a/api/_lib/print/export-3mf.js b/api/_lib/print/export-3mf.jsnew file mode 100644index 000000000..e42eff813--- /dev/null+++ b/api/_lib/print/export-3mf.js@@ -0,0 +1,238 @@+// 3MF: the format that carries the print, not just the shape.+//+// STL is what every bureau accepts; 3MF is what makes a print worth ordering.+// It is an OPC package (a zip with a relationship graph) holding one XML model+// that declares real units, indexed vertices, and per-vertex color through the+// Materials and Properties extension. That last part is the whole reason this+// writer exists: full-color sandstone and binder-jet machines reproduce color+// per vertex, so a generated model whose color lives in a 2K albedo texture can+// only be printed in color if something samples that texture per vertex and+// writes it into the manufacturing file. mesh-io.js does the sampling; this+// module writes it out. A download button that hands over a GLB leaves the+// color behind.+//+// Spec subset, deliberately small and deliberately exact:+// [Content_Types].xml default parts for .rels and .model+// _rels/.rels one 3D-model start-part relationship+// 3D/3dmodel.model unit="millimeter", resources, one build item+//+// The color group is declared in the material namespace but NOT listed in+// `requiredextensions`. A color-capable slicer reads it; a mono slicer ignores+// the attributes and still prints the geometry. Requiring the extension would+// make a monochrome printer reject a file it could have printed.+//+// The 3MF spec puts the build volume in the positive octant, so the mesh is+// translated to sit at the origin corner before it is written.++import { Buffer } from 'node:buffer';+import { zipSync, strToU8 } from 'fflate';++const MM_PER_METER = 1000;++export const CONTENT_TYPES_PART = '[Content_Types].xml';+export const RELS_PART = '_rels/.rels';+export const MODEL_PART = '3D/3dmodel.model';++export const CORE_NAMESPACE = 'http://schemas.microsoft.com/3dmanufacturing/core/2015/02';+export const MATERIAL_NAMESPACE = 'http://schemas.microsoft.com/3dmanufacturing/material/2015/02';+const MODEL_RELATIONSHIP = 'http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel';+const MODEL_CONTENT_TYPE = 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml';+const RELS_CONTENT_TYPE = 'application/vnd.openxmlformats-package.relationships+xml';++// Resource ids. 3MF requires them unique within the model; two constants are+// clearer than a counter for a package that always holds exactly one object.+const COLOR_GROUP_ID = 1;+const OBJECT_ID = 2;++// Coordinates are written at micron resolution. Finer is noise no printer can+// hit, and it keeps the XML (the dominant cost of a 3MF) roughly a third+// smaller than full float printing on a large mesh.+const COORD_DECIMALS = 3;++// The earliest instant a zip's DOS timestamp can express. Used as a constant so+// two exports of one mesh differ in no byte at all.+const ZIP_EPOCH = new Date(Date.UTC(1980, 0, 1));++export class ThreeMfExportError extends Error {+ constructor(code, message) {+ super(message);+ this.name = 'ThreeMfExportError';+ this.code = code;+ }+}++function xmlEscape(value) {+ return String(value)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++// Trim the trailing zeros a fixed-decimal render leaves behind: on a 200k+// triangle mesh that is megabytes of "000".+function coord(value) {+ const fixed = value.toFixed(COORD_DECIMALS);+ return fixed.includes('.') ? fixed.replace(/\.?0+$/, '') || '0' : fixed;+}++function hex2(v) {+ return Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0').toUpperCase();+}++/**+ * Collapse per-vertex RGB into the palette a 3MF colorgroup holds, plus the+ * per-vertex index into it. Identical colors share one entry, which is what+ * keeps a flat-shaded model's group at a handful of colors instead of one per+ * vertex.+ */+export function buildColorGroup(colors, vertexCount) {+ if (!colors || colors.length < vertexCount * 3) return null;+ const palette = [];+ const seen = new Map();+ const indexOf = new Uint32Array(vertexCount);+ for (let v = 0; v < vertexCount; v += 1) {+ const key = `${hex2(colors[v * 3])}${hex2(colors[v * 3 + 1])}${hex2(colors[v * 3 + 2])}`;+ let id = seen.get(key);+ if (id === undefined) {+ id = palette.length;+ seen.set(key, id);+ palette.push(key);+ }+ indexOf[v] = id;+ }+ return { palette, indexOf };+}++function buildModelXml({ positions, indices, colorGroup, scale, metadata }) {+ const vertexCount = positions.length / 3;+ // The positive-octant shift the spec asks for.+ let minX = Infinity;+ let minY = Infinity;+ let minZ = Infinity;+ for (let i = 0; i < positions.length; i += 3) {+ if (positions[i] < minX) minX = positions[i];+ if (positions[i + 1] < minY) minY = positions[i + 1];+ if (positions[i + 2] < minZ) minZ = positions[i + 2];+ }++ const parts = [];+ parts.push('<?xml version="1.0" encoding="UTF-8"?>\n');+ parts.push(+ `<model unit="millimeter" xml:lang="en-US" xmlns="${CORE_NAMESPACE}" xmlns:m="${MATERIAL_NAMESPACE}">`,+ );+ for (const [name, value] of Object.entries(metadata)) {+ if (value === null || value === undefined || value === '') continue;+ parts.push(`<metadata name="${xmlEscape(name)}">${xmlEscape(value)}</metadata>`);+ }+ parts.push('<resources>');+ if (colorGroup) {+ parts.push(`<m:colorgroup id="${COLOR_GROUP_ID}">`);+ for (const hex of colorGroup.palette) parts.push(`<m:color color="#${hex}FF"/>`);+ parts.push('</m:colorgroup>');+ }+ // pid/pindex give the object a default color, so a reader that ignores the+ // per-triangle indices still shows something rather than untextured grey.+ const objectAttrs = colorGroup+ ? `id="${OBJECT_ID}" type="model" pid="${COLOR_GROUP_ID}" pindex="0"`+ : `id="${OBJECT_ID}" type="model"`;+ parts.push(`<object ${objectAttrs}><mesh><vertices>`);+ for (let v = 0; v < vertexCount; v += 1) {+ const x = coord((positions[v * 3] - minX) * scale);+ const y = coord((positions[v * 3 + 1] - minY) * scale);+ const z = coord((positions[v * 3 + 2] - minZ) * scale);+ parts.push(`<vertex x="${x}" y="${y}" z="${z}"/>`);+ }+ parts.push('</vertices><triangles>');+ for (let t = 0; t < indices.length; t += 3) {+ const a = indices[t];+ const b = indices[t + 1];+ const c = indices[t + 2];+ if (colorGroup) {+ parts.push(+ `<triangle v1="${a}" v2="${b}" v3="${c}" p1="${colorGroup.indexOf[a]}" p2="${colorGroup.indexOf[b]}" p3="${colorGroup.indexOf[c]}"/>`,+ );+ } else {+ parts.push(`<triangle v1="${a}" v2="${b}" v3="${c}"/>`);+ }+ }+ parts.push('</triangles></mesh></object>');+ parts.push('</resources>');+ parts.push(`<build><item objectid="${OBJECT_ID}"/></build>`);+ parts.push('</model>');+ return parts.join('');+}++const CONTENT_TYPES_XML =+ '<?xml version="1.0" encoding="UTF-8"?>\n' ++ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' ++ `<Default Extension="rels" ContentType="${RELS_CONTENT_TYPE}"/>` ++ `<Default Extension="model" ContentType="${MODEL_CONTENT_TYPE}"/>` ++ '</Types>';++const RELS_XML =+ '<?xml version="1.0" encoding="UTF-8"?>\n' ++ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' ++ `<Relationship Id="rel0" Target="/${MODEL_PART}" Type="${MODEL_RELATIONSHIP}"/>` ++ '</Relationships>';++/**+ * Write a 3MF package.+ *+ * @param {{positions: Float64Array|number[], indices: Uint32Array|number[], colors?: Uint8Array|null}} mesh+ * Indexed triangles in glTF meters; `colors` is per-vertex RGB bytes as+ * mesh-io.js samples them.+ * @param {{scale?: number, color?: boolean, title?: string, designer?: string,+ * description?: string, license?: string}} [opts]+ * @returns {Buffer} the .3mf bytes+ */+export function export3mf(mesh, opts = {}) {+ const positions = mesh?.positions;+ const indices = mesh?.indices;+ if (!positions || !indices || indices.length < 3) {+ throw new ThreeMfExportError('empty_mesh', 'no triangles to export');+ }+ if (indices.length % 3 !== 0) {+ throw new ThreeMfExportError('bad_indices', 'index buffer is not a whole number of triangles');+ }+ const vertexCount = positions.length / 3;+ for (let i = 0; i < indices.length; i += 1) {+ if (indices[i] >= vertexCount) {+ throw new ThreeMfExportError('bad_indices', 'index buffer references a vertex that does not exist');+ }+ }++ const colorGroup = opts.color === false ? null : buildColorGroup(mesh.colors, vertexCount);+ const modelXml = buildModelXml({+ positions,+ indices,+ colorGroup,+ scale: opts.scale ?? MM_PER_METER,+ metadata: {+ Application: 'three.ws Materialize',+ Title: opts.title ?? '',+ Designer: opts.designer ?? '',+ Description: opts.description ?? '',+ LicenseTerms: opts.license ?? '',+ },+ });++ // Deterministic package: a fixed timestamp, one compression level, parts in+ // a fixed order. Two prepares of the same mesh must produce the same bytes,+ // because the print certificate hashes exactly this file. The zip clock only+ // spans 1980-2099, so the DOS epoch stands in for "no time".+ const zipped = zipSync(+ {+ [CONTENT_TYPES_PART]: strToU8(CONTENT_TYPES_XML),+ [RELS_PART]: strToU8(RELS_XML),+ [MODEL_PART]: strToU8(modelXml),+ },+ { level: 6, mtime: ZIP_EPOCH },+ );+ return Buffer.from(zipped);+}++/** Colors survived the round trip only if the group was actually written. */+export function threeMfHasColor(modelXml) {+ return modelXml.includes('<m:colorgroup') && modelXml.includes('<m:color color="#');+}diff --git a/api/_lib/print/gate.js b/api/_lib/print/gate.jsindex cf53ef4ae..8e5fe922a 100644--- a/api/_lib/print/gate.js+++ b/api/_lib/print/gate.js@@ -41,6 +41,33 @@ export { POLICY_URL };// well under the ~150 mm of the shortest real handgun.export const MINIATURE_MAX_MM = 120;+// The generation classifier's categories this gate honours, with the message+// rewritten in the fabrication voice (its own copy says "This 3D Studio",+// which is the wrong product to name when someone is buying an object). Its+// `weapon_drug` category is deliberately absent: see screenDeterministic().+const UPSTREAM_CATEGORIES = Object.freeze({+ csam: {+ label: 'prohibited content',+ message: 'This request is not allowed.',+ allowed: null,+ },+ sexual: {+ label: 'adult content',+ message: 'three.ws does not manufacture sexual or adult content.',+ allowed: 'Characters, creatures and figures without explicit themes are fine.',+ },+ gore: {+ label: 'graphic violence',+ message: 'three.ws does not manufacture graphically violent or gore content.',+ allowed: 'Describe the same subject without the graphic detail and it can be printed.',+ },+ hate: {+ label: 'hateful or extremist iconography',+ message: 'three.ws does not manufacture hateful or extremist content or iconography.',+ allowed: 'Original designs, historical subjects without the iconography, and ordinary symbols are fine.',+ },+});+const SCREENING_SYSTEM = `You review 3D models that a manufacturing service is about to physically print.Refuse only these categories:- firearm components or anything that becomes part of a working firearm@@ -148,19 +175,30 @@ function refusal({ category, label, message, allowed, layer, matched = null }) {export function screenDeterministic({ subject, analysis = null }) {const geometry = geometrySignal(analysis);- // Layer 1: whatever the generation gate would have refused, fabrication- // refuses too. A mesh that should never have been generated must never be- // manufactured, including one generated before that gate covered its terms.+ // Layer 1: the generation content classifier, for the categories whose+ // answer does not depend on what is being made out of the mesh.+ //+ // Generation verdicts are not persisted anywhere (checkPromptSafety refuses+ // inline in api/3d/studio.js and api/_mcp-studio/tools.js and stores+ // nothing), and the main /forge lane never called it at all, so this is a+ // re-evaluation of the lineage rather than a lookup. Only the four+ // scale-independent categories are honoured: the classifier's fifth,+ // `weapon_drug`, refuses the bare word "pistol", which would refuse every+ // tabletop miniature carrying one. Weapons and drug paraphernalia are owned+ // by the fabrication rules below, which distinguish a display piece from a+ // working part; deferring to a 13+ chat-app word list here would make that+ // distinction unreachable.const upstream = checkPromptSafety(subject);- if (!upstream.allowed) {+ if (!upstream.allowed && UPSTREAM_CATEGORIES[upstream.category]) {+ const mapped = UPSTREAM_CATEGORIES[upstream.category];return {decision: refusal({category: `generation_${upstream.category}`,- label: 'generation content policy',+ label: mapped.label,layer: 'upstream',matched: upstream.matched || null,- message: upstream.message,- allowed: 'Describe a character, creature, prop or object without that theme and generate it again.',+ message: mapped.message,+ allowed: mapped.allowed,}),layers: {upstream: { verdict: 'refuse', category: upstream.category, matched: upstream.matched || null },@@ -348,21 +386,27 @@ export async function runFabricationGate({};}+ const softFlags = deterministic.layers.denylist.soft || [];const llm = await screenWithLlm({subject,geometry: deterministic.layers.geometry,- softRules: deterministic.layers.denylist.soft || [],+ softRules: softFlags,});if (llm.verdict === 'refuse') {// The model may name a category the denylist knows; when it does, the// buyer gets that rule's written message and its "what is allowed"// sentence rather than raw model prose.+ // The model is asked for a rule id but free models routinely answer with a+ // sentence. Only a category the denylist actually knows is kept as the+ // category; anything else is recorded as the model's `reason` and the+ // order is refused under the general policy, so a stored verdict always+ // carries a slug a UI and a report can group on.const known = ruleById(llm.category);return {...base,verdict: 'refuse',- category: llm.category || 'fabrication_policy',+ category: known ? known.id : 'fabrication_policy',label: known?.label || 'fabrication content policy',layer: 'llm',matched: null,@@ -374,6 +418,20 @@ export async function runFabricationGate({}if (llm.verdict === 'review') {+ // An unreachable model must not hold an order the deterministic layers+ // had no question about: that order already cleared the same bar its+ // quote cleared, and paging an operator for every teapot during a+ // provider outage trains them to ignore the channel. Only a request the+ // denylist deliberately left undecided (a soft rule) is held.+ if (softFlags.length === 0) {+ return {+ ...base,+ verdict: 'allow',+ category: null,+ message: null,+ layers: { ...deterministic.layers, llm },+ };+ }return {...base,verdict: 'review',@@ -420,3 +478,80 @@ export async function notifyGateOutcome({ orderId = '', verdict, stage }) {alert: held,}).catch(() => {});}++/**+ * Orders sitting in `screening` that the thorough pass has not settled.+ *+ * A verdict of `review` is deliberately re-queued: it means a model was+ * unreachable or unreadable at the time, and the next sweep gets a fresh shot+ * before an operator has to make the call by hand.+ */+export async function listOrdersAwaitingScreening({ limit = 25 } = {}) {+ if (!databaseConfigured()) return [];+ return sql`+ select *+ from print_orders+ where status = 'screening'+ and coalesce(analysis -> 'screening' ->> 'verdict', '') <> 'allow'+ order by updated_at asc+ limit ${limit}+ `;+}++/** Persist a gate verdict onto the order, under `analysis.screening`. */+export async function recordScreeningVerdict(orderId, verdict) {+ if (!databaseConfigured()) return null;+ const [row] = await sql`+ update print_orders+ set analysis = jsonb_set(coalesce(analysis, '{}'::jsonb), '{screening}', ${JSON.stringify(verdict)}::jsonb),+ updated_at = now()+ where id = ${orderId}+ returning *+ `;+ return row || null;+}++/**+ * The second run point: the thorough pass over a paid order.+ *+ * Takes the order row, rebuilds the subject from its own frozen record (the+ * creation lineage, the buyer note, the model title), runs every layer, writes+ * the verdict to `analysis.screening`, and acts on it:+ *+ * allow the order stays in `screening`, now cleared for submission.+ * refuse the order moves to `rejected`, which is the refund path, and the+ * operators are told. The buyer's timeline carries the category and+ * the policy link, never a bare "rejected".+ * review the order stays put and the operators are paged. Nothing is+ * auto-rejected on a model outage: refunding a legitimate buyer+ * because a provider was down is the worse of the two errors.+ *+ * @param {object} order a print_orders row+ * @param {{ transition?: Function }} [deps] injected for tests+ */+export async function screenPaidOrder(order, deps = {}) {+ const transitionFn = deps.transition || (await import('../print-store.js')).transition;+ const lineage = await loadLineage(order?.creation_id);+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: lineage.text,+ modelTitle: order?.quote?.model_title || '',+ buyerNote: order?.quote?.buyer_note || order?.shipping?.note || '',+ analysis: order?.analysis || null,+ });+ verdict.lineage_hops = lineage.hops;++ await recordScreeningVerdict(order.id, verdict);+ await notifyGateOutcome({ orderId: order.id, verdict, stage: 'screening' });++ if (verdict.verdict === 'refuse') {+ await transitionFn({+ orderId: order.id,+ to: 'rejected',+ note: `Refused by the fabrication gate: ${verdict.label || verdict.category}. ${verdict.message} Policy: ${POLICY_URL}`,+ actor: 'system',+ });+ }++ return verdict;+}diff --git a/api/_lib/print/ops-auth.js b/api/_lib/print/ops-auth.jsindex 0da9c2b03..0a70871a5 100644--- a/api/_lib/print/ops-auth.js+++ b/api/_lib/print/ops-auth.js@@ -81,7 +81,7 @@ export async function authorizeOperator(req) {}}} catch {- /* no or invalid session — fall through to the secret door */+ /* no or invalid session: fall through to the secret door */}const secret = process.env.OPS_SECRET;diff --git a/api/print/certs/[id].js b/api/print/certs/[id].jsindex 2a5987d65..68e87dca7 100644--- a/api/print/certs/[id].js+++ b/api/print/certs/[id].js@@ -1,5 +1,5 @@/**- * GET /api/print/certs/:id — one Materialize certificate, publicly readable.+ * GET /api/print/certs/:id: one Materialize certificate, publicly readable.** A certificate is a public proof by design: the QR printed on the box has to* resolve for whoever is holding the box, which is frequently not the buyer anddiff --git a/api/print/ops/[action].js b/api/print/ops/[action].jsindex 87c45f806..0b465c193 100644--- a/api/print/ops/[action].js+++ b/api/print/ops/[action].js@@ -108,7 +108,7 @@ function queueRow(order) {// ── order detail ─────────────────────────────────────────────────────────────-/** GET /api/print/ops/order?id=… — everything needed to run one job. */+/** GET /api/print/ops/order?id=…: everything needed to run one job. */async function handleOrderDetail(req, res) {const order = await loadOrder(req, res);if (!order) return;@@ -311,7 +311,7 @@ async function handleRefund(req, res, operator) {});}-/** GET /api/print/ops/adapters — the lanes this deployment can route to. */+/** GET /api/print/ops/adapters: the lanes this deployment can route to. */async function handleAdapters(_req, res) {return json(res, 200, { adapters: adapterSummaries() });}diff --git a/api/print/quote.js b/api/print/quote.jsindex a61d2c231..74656a36a 100644--- a/api/print/quote.js+++ b/api/print/quote.js@@ -31,6 +31,7 @@ import { loadMeshFromUrl, MeshIoError } from '../_lib/print/mesh-io.js';import { analyzeMesh } from '../_lib/print/analyze.js';import { loadCatalog, materialFits, quotePrint, signQuote } from '../_lib/print/quote.js';import { getPublicCreation } from '../_lib/forge-store.js';+import { loadLineage, runFabricationGate } from '../_lib/print/gate.js';import { holderDiscountBps } from '../_lib/three-tier.js';// One analysis per source model, held for an hour. The report is deterministic@@ -111,6 +112,31 @@ export default wrap(async (req, res) => {throw err;}+ // The fabrication gate, first run point. It is deterministic here (no model+ // call) so a price is never gated on a third-party provider being up, and it+ // runs BEFORE any money is quoted: a refusal at this point costs the buyer+ // nothing. The paid order is screened again, thoroughly, on the way to the+ // printer. See api/_lib/print/gate.js and specs/PRINT_PIPELINE.md.+ const lineage = await loadLineage(source.creationId);+ const gate = await runFabricationGate({+ stage: 'quote',+ lineageText: lineage.text || source.creation?.prompt || '',+ modelTitle: typeof body.title === 'string' ? body.title : '',+ buyerNote: typeof body.note === 'string' ? body.note : '',+ analysis: report,+ });+ if (gate.verdict === 'refuse') {+ // 451 rather than a 200 with a flag: an agent lane must be able to branch+ // on the status alone, and a refused order must never reach a paid call.+ return error(res, 451, 'fabrication_refused', gate.message, {+ category: gate.category,+ label: gate.label,+ allowed: gate.allowed,+ policy_url: gate.policy_url,+ stage: gate.stage,+ });+ }+const catalog = loadCatalog();const base = {report,@@ -122,6 +148,10 @@ export default wrap(async (req, res) => {// and bounds its size slider from this, so a buyer never drags into a// rejection the server could have predicted.fits: materialFits({ report, catalog: loadCatalog() }),+ // The verdict rides along so the page and the agent lane can see that a+ // screening pass will run after payment, rather than discovering it as a+ // surprise rejection later.+ screening: { verdict: gate.verdict, stage: gate.stage, policy_url: gate.policy_url },};// No material chosen: this is the analyze call. Free, keyless, no price.diff --git a/api/print/webhook/[provider].js b/api/print/webhook/[provider].jsindex e7a8c9465..94df7ecf5 100644--- a/api/print/webhook/[provider].js+++ b/api/print/webhook/[provider].js@@ -1,5 +1,5 @@// @ts-check-// POST /api/print/webhook/:provider — a fulfillment provider reporting in.+// POST /api/print/webhook/:provider: a fulfillment provider reporting in.//// Three properties, in the order they are enforced://diff --git a/data/pages.json b/data/pages.jsonindex 7dd8efc24..4b76ddad4 100644--- a/data/pages.json+++ b/data/pages.json@@ -1041,6 +1041,14 @@"priority": 0.6,"changefreq": "monthly","added": "2026-08-28"+ },+ {+ "path": "/docs/animation-seeding",+ "title": "Generated animation seeding",+ "description": "How three.ws generates its own animation clips: the text-to-motion GPU lane, the world-space quality gate that judges joint positions instead of raw rotations, the resumable bulk runner, and the rotating free subset.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-09-02"}]},@@ -1359,6 +1367,14 @@"changefreq": "daily","added": "2026-07-08"},+ {+ "path": "/cert",+ "title": "Print Certificates",+ "description": "Check the certificate of authenticity that ships with every three.ws physical print. Scan the code on the box or type the certificate number to see the original 3D model spinning, its edition number, the SHA-256 of the exact bytes that went to the printer, and the Solana transaction attesting both. Each certificate lives at /cert/<id>.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-09-02"+ },{"path": "/creations","title": "Creator Gallery",@@ -2767,7 +2783,7 @@},{"path": "/docs/spotlight",- "title": "Docs \u00b7 Agent Spotlight",+ "title": "Docs · Agent Spotlight","description": "How the Agent Spotlight community showcase works: what an entry stores versus what it reads live off the agent, the trending decay formula, curated versus community entries, and the full showcase API.","priority": 0.6,"changefreq": "weekly",@@ -5894,6 +5910,14 @@"changefreq": "yearly","added": "2026-07-14"},+ {+ "path": "/legal/nvidia-ngc-eula",+ "title": "NVIDIA NGC Container EULA",+ "description": "License terms for three.ws container images distributed through the NVIDIA NGC catalog: what the license covers, the model weights the image does not ship, and the data the container does not collect.",+ "priority": 0.2,+ "changefreq": "yearly",+ "added": "2026-09-02"+ },{"path": "/legal/tos","title": "Terms of Service",diff --git a/pages/materialize-ops.html b/pages/materialize-ops.htmlnew file mode 100644index 000000000..3ae6434fe--- /dev/null+++ b/pages/materialize-ops.html@@ -0,0 +1,75 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot - no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Fulfillment console · three.ws</title>+ <meta name="description" content="Internal operator console for Materialize print fulfillment." />+ <meta name="robots" content="noindex, nofollow" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/materialize-ops.css" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="mo-shell" id="mo-app">+ <div class="mo-head">+ <div>+ <p class="mo-kicker"><span class="mo-dot" aria-hidden="true"></span> Materialize fulfillment</p>+ <h1 class="mo-title">Operator console</h1>+ </div>+ <div class="mo-head-meta">+ <span id="mo-updated" aria-live="polite"></span>+ <button type="button" class="mo-btn" id="mo-refresh">Refresh</button>+ </div>+ </div>++ <div class="mo-body">+ <nav class="mo-rail" id="mo-rail" aria-label="Order queues">+ <p class="mo-rail-head">Queues</p>+ </nav>++ <section class="mo-panel" aria-label="Print order queue">+ <div class="mo-panel-head">+ <h2 class="mo-panel-title" id="mo-queue-title">Needs action</h2>+ </div>+ <div class="mo-scroll">+ <table class="mo-table">+ <thead>+ <tr>+ <th scope="col">Order</th>+ <th scope="col">Status</th>+ <th scope="col">Material</th>+ <th scope="col">Qty</th>+ <th scope="col">USDC</th>+ <th scope="col">Lane</th>+ <th scope="col">To</th>+ <th scope="col">Placed</th>+ </tr>+ </thead>+ <tbody id="mo-rows"></tbody>+ </table>+ </div>+ </section>+ </div>+ </main>++ <div class="mo-drawer-scrim" id="mo-scrim" data-open="false"></div>+ <aside class="mo-drawer" id="mo-drawer" data-open="false" aria-hidden="true" aria-label="Order detail">+ <div class="mo-drawer-head">+ <h2 class="mo-drawer-title" id="mo-drawer-title">Order</h2>+ <button type="button" class="mo-btn" id="mo-close" style="margin-left:auto">Close</button>+ </div>+ <div class="mo-drawer-body" id="mo-drawer-body"></div>+ </aside>++ <script type="module" src="/src/materialize-ops.js"></script>+ </body>+</html>diff --git a/pages/print-insert.html b/pages/print-insert.htmlnew file mode 100644index 000000000..fd70cafcb--- /dev/null+++ b/pages/print-insert.html@@ -0,0 +1,28 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Package insert · three.ws</title>+ <meta name="description" content="Operator tool: the print-ready certificate card that goes in the box with a three.ws physical print." />+ <meta name="robots" content="noindex, nofollow" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/src/print-insert.css" />+ </head>+ <body>+ <main class="pi-root" id="pi-root" aria-busy="true">+ <!-- Hydrated by /src/print-insert.js from /api/print/ops/insert-card.+ Operator-gated server side; this page is never the security boundary. -->+ <div class="pi-status" id="pi-status">Loading the insert card…</div>+ <noscript>+ <p class="pi-status">This operator tool renders the package insert card. Enable JavaScript to use it.</p>+ </noscript>+ </main>+ <div id="pi-live" class="pi-sr-only" role="status" aria-live="polite"></div>+ <script type="module" src="/src/print-insert.js"></script>+ </body>+</html>diff --git a/src/certificate-page.js b/src/certificate-page.jsnew file mode 100644index 000000000..bb064229c--- /dev/null+++ b/src/certificate-page.js@@ -0,0 +1,384 @@+// /cert/:certId — the certificate of authenticity for one Materialize print.+//+// This is the page a QR code on a physical box resolves to, so it is built for+// a stranger on a phone: no session, no chrome to click through, and the proof+// itself rendered inline rather than behind a link to somebody else's explorer.+// A verifier who never trusts three.ws can hash the file, read the memo string+// on this page, and confirm the two agree without leaving it.+//+// /cert with no id is the lookup: the same page, asking for a certificate+// number, because someone holding a card is much likelier to type its id than+// to find this route any other way.+//+// Real endpoint only:+// GET /api/print/certs/:id → { certificate }++import { apiFetch } from './api.js';+import { createLogger } from './shared/log.js';++const log = createLogger('certificate-page');+const CERT_ID_RE = /^[0-9a-f]{24}$/;++const root = () => document.getElementById('ct-root');+const live = () => document.getElementById('ct-live');++function esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function announce(message) {+ const el = live();+ if (el) el.textContent = message;+}++/** The certificate id in the path, or null when this is the lookup view. */+export function certIdFromPath(pathname = window.location.pathname) {+ const m = String(pathname || '').match(/^\/cert\/([0-9a-f]{24})\/?$/i);+ return m ? m[1].toLowerCase() : null;+}++/** A short, human title for a model, derived from its prompt. */+export function titleFromPrompt(prompt) {+ const raw = String(prompt || '').trim().replace(/\s+/g, ' ');+ if (!raw) return 'Untitled model';+ const clipped = raw.length > 64 ? `${raw.slice(0, 63).trimEnd()}…` : raw;+ return clipped.charAt(0).toUpperCase() + clipped.slice(1);+}++export function formatBytes(n) {+ if (!Number.isFinite(n) || n <= 0) return null;+ const units = ['B', 'KB', 'MB', 'GB'];+ let value = n;+ let i = 0;+ while (value >= 1024 && i < units.length - 1) {+ value /= 1024;+ i += 1;+ }+ return `${value >= 10 || i === 0 ? Math.round(value) : value.toFixed(1)} ${units[i]}`;+}++export function formatDate(value) {+ if (!value) return null;+ const d = new Date(value);+ if (Number.isNaN(d.getTime())) return null;+ return d.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });+}++/** "Edition 3 of 25", or "Edition 3" for an open series. */+export function editionLine(cert) {+ if (!cert) return '';+ return cert.edition_of ? `Edition ${cert.edition_no} of ${cert.edition_of}` : `Edition ${cert.edition_no}`;+}++function stage(cert) {+ const creation = cert.creation;+ const glb = creation?.glb_url;+ const poster = creation?.preview_image_url;+ const badge = `<div class="ct-edition"><strong>${esc(String(cert.edition_no))}</strong><span>${+ cert.edition_of ? `of ${esc(String(cert.edition_of))}` : 'open edition'+ }</span></div>`;++ if (glb) {+ return `<div class="ct-stage">+ <model-viewer src="${esc(glb)}"${poster ? ` poster="${esc(poster)}"` : ''}+ alt="The 3D model this print was made from"+ camera-controls auto-rotate auto-rotate-delay="600" rotation-per-second="20deg"+ interaction-prompt="when-focused" shadow-intensity="0.5" exposure="0.95"+ environment-image="neutral"></model-viewer>+ ${badge}+ </div>`;+ }+ if (poster) {+ return `<div class="ct-stage"><img src="${esc(poster)}" alt="The model this print was made from" />${badge}</div>`;+ }+ // The source model was deleted or was never a stored creation. The+ // certificate is still fully valid: the hash and the attestation are what it+ // proves, and they are on this page.+ return `<div class="ct-stage"><div class="ct-stage-empty">+ The original model is no longer hosted here. The hash and the on-chain proof below still+ verify the object you are holding.+ </div>${badge}</div>`;+}++function lineage(cert) {+ const c = cert.creation;+ if (!c) {+ return `<div class="ct-card">+ <h2>Lineage</h2>+ <p class="ct-note">This print was made from a model uploaded directly, not generated on three.ws, so it carries no prompt lineage. Its bytes are still hashed and attested below.</p>+ </div>`;+ }+ const body = c.prompt_withheld+ ? `<p class="ct-note">This model is private. Its prompt stays with its creator; the certificate, the hash, and the attestation are public.</p>`+ : `<p class="ct-fact-prompt ct-code">${esc(c.prompt || 'No prompt recorded.')}</p>`;+ const links = [];+ if (c.model_url) links.push(`<a class="ct-btn" href="${esc(c.model_url)}">Open the original model</a>`);+ if (c.parent_creation_id) {+ links.push(`<a class="ct-btn" href="/m/${esc(c.parent_creation_id)}">See what it was refined from</a>`);+ }+ const creator = c.creator_display_name || c.creator_username;+ return `<div class="ct-card">+ <h2>Lineage</h2>+ ${body}+ ${+ c.refine_instruction+ ? `<p class="ct-note">Refined with: ${esc(c.refine_instruction)}</p>`+ : ''+ }+ ${creator ? `<p class="ct-note">Forged by ${esc(creator)}${c.creator_username ? ` (@${esc(c.creator_username)})` : ''}.</p>` : ''}+ ${links.length ? `<div class="ct-actions" style="margin-top:12px">${links.join('')}</div>` : ''}+ </div>`;+}++function facts(cert) {+ const rows = [+ ['Certificate', cert.id],+ ['Edition', editionLine(cert)],+ ['Material', cert.material_label || cert.material_id || 'Recorded on the order'],+ ['Printed', formatDate(cert.printed_at) || 'Unrecorded'],+ ];+ const size = formatBytes(Number(cert.glb_bytes));+ if (size) rows.push(['Model size', size]);+ return `<div class="ct-card">+ <h2>The object</h2>+ <dl class="ct-facts">+ ${rows+ .map(+ ([k, v]) =>+ `<div class="ct-fact"><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`,+ )+ .join('')}+ </dl>+ </div>`;+}++function proof(cert) {+ const attested = Boolean(cert.solana_signature);+ const network = cert.network === 'mainnet' ? 'Solana mainnet' : 'Solana devnet';+ const state = attested+ ? `<span class="ct-proof-state"><span class="ct-dot"></span>Attested on ${esc(network)}${+ cert.attested_at ? ` on ${esc(formatDate(cert.attested_at) || '')}` : ''+ }</span>`+ : `<span class="ct-proof-state"><span class="ct-dot ct-dot--pending"></span>Attestation in flight. The certificate is issued and its hash is final; the transaction is retried until it lands.</span>`;++ return `<div class="ct-card">+ <h2>On-chain proof</h2>+ ${state}+ <h2 style="margin-top:20px">Memo payload (signed verbatim)</h2>+ <code class="ct-code" id="ct-memo">${esc(cert.memo || '')}</code>+ <h2 style="margin-top:20px">SHA-256 of the model</h2>+ <code class="ct-code" id="ct-hash">${esc(cert.glb_sha256)}</code>+ ${+ cert.print_asset_sha256+ ? `<h2 style="margin-top:20px">SHA-256 of the ${esc(String(cert.print_asset_kind || 'print').toUpperCase())} sent to the printer</h2>+ <code class="ct-code">${esc(cert.print_asset_sha256)}</code>`+ : ''+ }+ <div class="ct-actions">+ ${+ attested+ ? `<a class="ct-btn ct-btn--primary" href="${esc(cert.explorer_url)}" target="_blank" rel="noopener">View the transaction</a>`+ : ''+ }+ <button class="ct-btn" type="button" id="ct-copy-memo">Copy the memo</button>+ <button class="ct-btn" type="button" id="ct-copy-link">Copy this certificate link</button>+ </div>+ ${+ attested+ ? `<p class="ct-note">Signature: <span class="ct-code" style="display:inline;padding:2px 6px">${esc(cert.solana_signature)}</span></p>`+ : ''+ }+ </div>`;+}++function verifySection(cert) {+ const glb = cert.creation?.glb_url;+ return `<div class="ct-card">+ <h2>Verify these bytes yourself</h2>+ <ol class="ct-steps">+ <li>Download the model this print was made from${+ glb ? `: <a class="ct-btn" style="margin-left:6px" href="${esc(glb)}" download>Download the GLB</a>` : '.'+ }</li>+ <li>Hash it: <code>shasum -a 256 model.glb</code> (macOS/Linux) or <code>certutil -hashfile model.glb SHA256</code> (Windows).</li>+ <li>Compare the result to the SHA-256 above. They match, byte for byte, or this is not the model that was printed.</li>+ <li>Read the same hash back off the chain: open the transaction and read its memo instruction. The memo string above is exactly what was signed.</li>+ </ol>+ <p class="ct-note">+ Nothing in this check depends on three.ws staying online. The hash is in the transaction,+ the transaction is on ${esc(cert.network === 'mainnet' ? 'Solana mainnet' : 'Solana devnet')},+ and the file is yours.+ </p>+ </div>`;+}++function qrCard(cert) {+ if (!cert.qr_url) return '';+ return `<div class="ct-card">+ <h2>The code on the box</h2>+ <img class="ct-qr" src="${esc(cert.qr_url)}" alt="QR code linking to this certificate" width="132" height="132" loading="lazy" />+ <p class="ct-note">This is the code printed on the package insert. It resolves here.</p>+ </div>`;+}++function renderCertificate(cert) {+ const host = root();+ if (!host) return;+ const title = cert.creation?.prompt_withheld+ ? 'A private model'+ : titleFromPrompt(cert.creation?.prompt);+ document.title = `${title} · ${editionLine(cert)} · three.ws`;++ host.innerHTML = `+ <a class="ct-back" href="/materialize">← Materialize</a>+ <p class="ct-kicker"><span class="ct-dot${cert.solana_signature ? '' : ' ct-dot--pending'}"></span>Certificate of authenticity</p>+ <h1 class="ct-title">${esc(title)}</h1>+ <p class="ct-sub">+ A physical print made on three.ws. ${esc(editionLine(cert))}, printed+ ${esc(formatDate(cert.printed_at) || 'on the date recorded on the order')}, with the exact bytes+ that were printed hashed and attested on Solana.+ </p>+ <div class="ct-grid">+ <div>+ ${stage(cert)}+ ${lineage(cert)}+ </div>+ <div>+ ${facts(cert)}+ ${proof(cert)}+ ${qrCard(cert)}+ ${verifySection(cert)}+ </div>+ </div>`;+ host.setAttribute('aria-busy', 'false');++ wireCopy('ct-copy-memo', () => cert.memo || '', 'Memo copied');+ wireCopy('ct-copy-link', () => cert.certificate_url || window.location.href, 'Link copied');+ announce(`${title}, ${editionLine(cert)}.`);+}++function wireCopy(id, read, okLabel) {+ const btn = document.getElementById(id);+ if (!btn) return;+ btn.addEventListener('click', async () => {+ const original = btn.textContent;+ try {+ await navigator.clipboard.writeText(read());+ btn.textContent = okLabel;+ announce(okLabel);+ } catch {+ // Clipboard is blocked (insecure context, denied permission). Select the+ // text instead so the copy is one keystroke away rather than impossible.+ const target = document.getElementById(id === 'ct-copy-memo' ? 'ct-memo' : 'ct-hash');+ if (target) {+ const range = document.createRange();+ range.selectNodeContents(target);+ const sel = window.getSelection();+ sel?.removeAllRanges();+ sel?.addRange(range);+ }+ btn.textContent = 'Selected, press copy';+ }+ setTimeout(() => {+ btn.textContent = original;+ }, 1800);+ });+}++function renderLookup(message = '') {+ const host = root();+ if (!host) return;+ document.title = 'Certificate of Authenticity · three.ws';+ host.innerHTML = `+ <a class="ct-back" href="/materialize">← Materialize</a>+ <p class="ct-kicker"><span class="ct-dot"></span>Provenance</p>+ <h1 class="ct-title">Check a certificate</h1>+ <p class="ct-sub">+ Every physical print made on three.ws ships with a certificate: the model it was printed+ from, its edition number, the SHA-256 of the exact bytes that went to the printer, and a+ Solana transaction attesting them. Scan the code on the box, or type the certificate+ number printed beside it.+ </p>+ <form class="ct-lookup" id="ct-lookup">+ <input class="ct-input" id="ct-lookup-input" name="cert" inputmode="latin"+ autocomplete="off" spellcheck="false" maxlength="24"+ placeholder="24-character certificate number" aria-label="Certificate number" />+ <button class="ct-btn ct-btn--primary" type="submit">Open certificate</button>+ </form>+ <p class="ct-message" id="ct-lookup-message" role="alert">${esc(message)}</p>`;+ host.setAttribute('aria-busy', 'false');++ const form = document.getElementById('ct-lookup');+ const input = document.getElementById('ct-lookup-input');+ const msg = document.getElementById('ct-lookup-message');+ form?.addEventListener('submit', (e) => {+ e.preventDefault();+ const value = String(input?.value || '').trim().toLowerCase().replace(/[^0-9a-f]/g, '');+ if (!CERT_ID_RE.test(value)) {+ if (msg) msg.textContent = 'A certificate number is 24 characters, digits and the letters a to f.';+ input?.focus();+ return;+ }+ window.location.assign(`/cert/${value}`);+ });+ input?.focus();+}++function renderError(title, body, { retry = false } = {}) {+ const host = root();+ if (!host) return;+ host.innerHTML = `+ <a class="ct-back" href="/materialize">← Materialize</a>+ <h1 class="ct-title">${esc(title)}</h1>+ <p class="ct-sub">${esc(body)}</p>+ <div class="ct-actions">+ ${retry ? '<button class="ct-btn ct-btn--primary" type="button" id="ct-retry">Try again</button>' : ''}+ <a class="ct-btn" href="/cert">Check another certificate</a>+ <a class="ct-btn" href="/materialize">About Materialize</a>+ </div>`;+ host.setAttribute('aria-busy', 'false');+ document.getElementById('ct-retry')?.addEventListener('click', () => {+ void load();+ });+ announce(title);+}++async function load() {+ const id = certIdFromPath();+ if (!id) {+ renderLookup();+ return;+ }+ try {+ const res = await apiFetch(`/api/print/certs/${encodeURIComponent(id)}`);+ if (res.status === 404) {+ renderError(+ 'No certificate with that number',+ 'Check the number printed on the card, or scan the code on the box again. Certificates are issued when an order ships.',+ );+ return;+ }+ if (!res.ok) throw new Error(`certificate request failed: ${res.status}`);+ const body = await res.json();+ if (!body?.certificate) throw new Error('certificate missing from response');+ renderCertificate(body.certificate);+ } catch (err) {+ log.error('certificate load failed', err);+ renderError(+ 'Could not load this certificate',+ 'The connection failed on the way here. The certificate itself is unaffected.',+ { retry: true },+ );+ }+}++if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => void load());+ } else {+ void load();+ }+}diff --git a/src/materialize-ops.css b/src/materialize-ops.cssnew file mode 100644index 000000000..0ab1dde23--- /dev/null+++ b/src/materialize-ops.css@@ -0,0 +1,475 @@+/* Materialize operator console: /materialize/ops.+ An internal tool, held to the same bar as a public surface. An operator runs+ real print jobs and real money through this page; a dead-end state here is+ an order that never ships. Every value comes from public/tokens.css. */++.mo-shell {+ max-width: 1400px;+ margin: 0 auto;+ padding: var(--space-6, 24px) var(--space-6, 24px) var(--space-2xl, 68px);+}++/* ── header ──────────────────────────────────────────────────────────────── */++.mo-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: var(--space-3, 12px) var(--space-5, 20px);+ padding-bottom: var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+}++.mo-kicker {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ margin: 0;+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--color-text-dim);+}++.mo-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--color-success);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-success) 22%, transparent);+}++.mo-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-xl, 26px);+ font-weight: var(--weight-semibold, 600);+ color: var(--color-text-bright);+}++.mo-head-meta {+ margin-left: auto;+ display: flex;+ align-items: center;+ gap: var(--space-3, 12px);+ font-size: var(--text-sm, 12px);+ color: var(--color-text-dim);+}++/* ── layout ──────────────────────────────────────────────────────────────── */++.mo-body {+ display: grid;+ grid-template-columns: 220px minmax(0, 1fr);+ gap: var(--space-6, 24px);+ margin-top: var(--space-5, 20px);+ align-items: start;+}++@media (max-width: 900px) {+ .mo-body { grid-template-columns: minmax(0, 1fr); }+ .mo-rail { position: static; }+}++/* ── status rail ─────────────────────────────────────────────────────────── */++.mo-rail {+ position: sticky;+ top: calc(var(--header-h, 3.5rem) + 12px);+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.mo-rail-head {+ margin: 0 0 var(--space-2, 8px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--color-text-faint);+}++.mo-rail-btn {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2, 8px);+ width: 100%;+ padding: 7px 10px;+ border: 1px solid transparent;+ border-radius: var(--radius-md, 10px);+ background: transparent;+ color: var(--color-text-dim);+ font: inherit;+ font-size: var(--text-md, 13px);+ text-align: left;+ cursor: pointer;+ transition: background var(--dur-fast, 140ms) var(--ease-out, ease),+ color var(--dur-fast, 140ms) var(--ease-out, ease),+ border-color var(--dur-fast, 140ms) var(--ease-out, ease);+}++.mo-rail-btn:hover { background: var(--color-surface); color: var(--color-text); }+.mo-rail-btn:active { transform: translateY(1px); }+.mo-rail-btn:focus-visible {+ outline: 2px solid var(--color-accent);+ outline-offset: 2px;+}+.mo-rail-btn[aria-pressed='true'] {+ background: var(--color-surface-2);+ border-color: var(--color-border);+ color: var(--color-text-bright);+ font-weight: var(--weight-medium, 500);+}++.mo-rail-count {+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ color: var(--color-text-faint);+ font-variant-numeric: tabular-nums;+}++.mo-rail-btn[aria-pressed='true'] .mo-rail-count { color: var(--color-text-dim); }++/* ── queue table ─────────────────────────────────────────────────────────── */++.mo-panel {+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg, 14px);+ background: var(--color-surface);+ overflow: hidden;+}++.mo-panel-head {+ display: flex;+ align-items: center;+ gap: var(--space-3, 12px);+ padding: var(--space-3, 12px) var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+}++.mo-panel-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-semibold, 600);+ color: var(--color-text-bright);+}++.mo-scroll { overflow-x: auto; }++.mo-table {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--text-md, 13px);+ white-space: nowrap;+}++.mo-table th {+ padding: 10px var(--space-4, 16px);+ text-align: left;+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ font-weight: var(--weight-regular, 400);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--color-text-faint);+ border-bottom: 1px solid var(--color-hairline);+}++.mo-table td {+ padding: 11px var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+ color: var(--color-text);+}++.mo-row { cursor: pointer; transition: background var(--dur-fast, 140ms) var(--ease-out, ease); }+.mo-row:hover { background: var(--color-surface-2); }+.mo-row:focus-visible { outline: 2px solid var(--color-accent); outline-offset: -2px; }+.mo-row[aria-selected='true'] { background: var(--color-surface-2); }+.mo-table tbody tr:last-child td { border-bottom: 0; }++.mo-mono {+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ color: var(--color-text-dim);+ font-variant-numeric: tabular-nums;+}++.mo-num { font-variant-numeric: tabular-nums; }++/* ── status pill ─────────────────────────────────────────────────────────── */++.mo-pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 3px 9px;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-pill, 999px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.04em;+ color: var(--color-text-dim);+ background: var(--color-surface);+}++.mo-pill::before {+ content: '';+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: currentColor;+}++.mo-pill[data-status='paid'],+.mo-pill[data-status='screening'] { color: var(--color-warning); border-color: color-mix(in srgb, var(--color-warning) 35%, transparent); }+.mo-pill[data-status='submitted'],+.mo-pill[data-status='printing'],+.mo-pill[data-status='quality_check'] { color: var(--wallet-accent, #c4b5fd); border-color: color-mix(in srgb, var(--wallet-accent, #c4b5fd) 35%, transparent); }+.mo-pill[data-status='shipped'],+.mo-pill[data-status='delivered'] { color: var(--color-success); border-color: color-mix(in srgb, var(--color-success) 35%, transparent); }+.mo-pill[data-status='rejected'],+.mo-pill[data-status='canceled'],+.mo-pill[data-status='refunded'] { color: var(--color-danger); border-color: color-mix(in srgb, var(--color-danger) 35%, transparent); }++.mo-late {+ margin-left: 6px;+ color: var(--color-danger);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+}++/* ── states ──────────────────────────────────────────────────────────────── */++.mo-state {+ padding: var(--space-8, 32px) var(--space-4, 16px);+ text-align: center;+ color: var(--color-text-dim);+ font-size: var(--text-md, 13px);+ line-height: var(--leading-normal, 1.618);+}++.mo-state strong {+ display: block;+ margin-bottom: 6px;+ color: var(--color-text-bright);+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-semibold, 600);+}++.mo-state a { color: var(--color-text-bright); }++.mo-skeleton {+ height: 41px;+ border-bottom: 1px solid var(--color-hairline);+ background: linear-gradient(90deg, transparent, var(--color-surface-2), transparent);+ background-size: 200% 100%;+ animation: mo-shimmer 1.4s ease-in-out infinite;+}++@keyframes mo-shimmer {+ 0% { background-position: 200% 0; }+ 100% { background-position: -200% 0; }+}++@media (prefers-reduced-motion: reduce) {+ .mo-skeleton { animation: none; background: var(--color-surface-2); }+ .mo-drawer { transition: none; }+}++/* ── detail drawer ───────────────────────────────────────────────────────── */++.mo-drawer-scrim {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.5);+ opacity: 0;+ pointer-events: none;+ transition: opacity var(--dur-med, 220ms) var(--ease-out, ease);+ z-index: 60;+}++.mo-drawer-scrim[data-open='true'] { opacity: 1; pointer-events: auto; }++.mo-drawer {+ position: fixed;+ top: 0;+ right: 0;+ bottom: 0;+ width: min(560px, 100vw);+ display: flex;+ flex-direction: column;+ background: var(--bg-1, #1a1a1a);+ border-left: 1px solid var(--color-border);+ transform: translateX(100%);+ transition: transform var(--dur-med, 220ms) var(--ease-out, ease);+ z-index: 61;+ overflow: hidden;+}++.mo-drawer[data-open='true'] { transform: translateX(0); }++.mo-drawer-head {+ display: flex;+ align-items: center;+ gap: var(--space-3, 12px);+ padding: var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+}++.mo-drawer-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-semibold, 600);+ color: var(--color-text-bright);+}++.mo-drawer-body {+ flex: 1;+ overflow-y: auto;+ padding: var(--space-4, 16px);+ display: flex;+ flex-direction: column;+ gap: var(--space-5, 20px);+}++.mo-section-title {+ margin: 0 0 var(--space-2, 8px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--color-text-faint);+}++.mo-kv {+ display: grid;+ grid-template-columns: 130px minmax(0, 1fr);+ gap: 6px var(--space-3, 12px);+ font-size: var(--text-md, 13px);+}++.mo-kv dt { color: var(--color-text-faint); }+.mo-kv dd { margin: 0; color: var(--color-text); overflow-wrap: anywhere; }++.mo-files { display: flex; flex-wrap: wrap; gap: var(--space-2, 8px); }++.mo-timeline { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-3, 12px); }++.mo-timeline li {+ display: grid;+ grid-template-columns: 10px minmax(0, 1fr);+ gap: var(--space-3, 12px);+ font-size: var(--text-md, 13px);+}++.mo-timeline li::before {+ content: '';+ width: 7px;+ height: 7px;+ margin-top: 6px;+ border-radius: 50%;+ background: var(--color-border-strong);+}++.mo-timeline-note { color: var(--color-text-dim); margin: 2px 0 0; overflow-wrap: anywhere; }+.mo-timeline-meta { color: var(--color-text-faint); font-family: var(--font-mono); font-size: var(--text-2xs, 11px); }++/* ── controls ────────────────────────────────────────────────────────────── */++.mo-actions { display: flex; flex-wrap: wrap; gap: var(--space-2, 8px); }++.mo-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 7px 13px;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md, 10px);+ background: var(--color-surface);+ color: var(--color-text);+ font: inherit;+ font-size: var(--text-md, 13px);+ text-decoration: none;+ cursor: pointer;+ transition: background var(--dur-fast, 140ms) var(--ease-out, ease),+ border-color var(--dur-fast, 140ms) var(--ease-out, ease),+ transform var(--dur-fast, 140ms) var(--ease-out, ease);+}++.mo-btn:hover:not(:disabled) { background: var(--color-surface-2); border-color: var(--color-border-strong); }+.mo-btn:active:not(:disabled) { transform: translateY(1px); }+.mo-btn:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 2px; }+.mo-btn:disabled { opacity: 0.45; cursor: not-allowed; }++.mo-btn-primary {+ background: var(--color-text-bright);+ border-color: var(--color-text-bright);+ color: var(--bg-0, #0a0a0a);+ font-weight: var(--weight-medium, 500);+}+.mo-btn-primary:hover:not(:disabled) { background: var(--color-text); border-color: var(--color-text); }++.mo-btn-danger { color: var(--color-danger); border-color: color-mix(in srgb, var(--color-danger) 40%, transparent); }+.mo-btn-danger:hover:not(:disabled) { background: color-mix(in srgb, var(--color-danger) 12%, transparent); }++.mo-field { display: flex; flex-direction: column; gap: 5px; }++.mo-field label {+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--color-text-faint);+}++.mo-input,+.mo-textarea,+.mo-select {+ width: 100%;+ padding: 8px 10px;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md, 10px);+ background: var(--color-bg);+ color: var(--color-text);+ font: inherit;+ font-size: var(--text-md, 13px);+}++.mo-input:focus,+.mo-textarea:focus,+.mo-select:focus {+ outline: 2px solid var(--color-accent);+ outline-offset: 1px;+ border-color: var(--color-border-strong);+}++.mo-textarea { min-height: 62px; resize: vertical; }++.mo-inline { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: var(--space-2, 8px); }++.mo-note {+ margin: 0;+ min-height: 1.2em;+ font-size: var(--text-md, 13px);+ color: var(--color-text-dim);+}++.mo-note[data-tone='error'] { color: var(--color-danger); }+.mo-note[data-tone='ok'] { color: var(--color-success); }++.mo-payout {+ margin: 0;+ padding: var(--space-3, 12px);+ border: 1px solid color-mix(in srgb, var(--color-warning) 40%, transparent);+ border-radius: var(--radius-md, 10px);+ background: color-mix(in srgb, var(--color-warning) 8%, transparent);+ font-size: var(--text-md, 13px);+ color: var(--color-text);+}++.mo-payout strong { color: var(--color-text-bright); }diff --git a/src/materialize-ops.js b/src/materialize-ops.jsnew file mode 100644index 000000000..9bb646c81--- /dev/null+++ b/src/materialize-ops.js@@ -0,0 +1,475 @@+// Materialize operator console: the working queue for physical print jobs.+//+// This page is a client of /api/print/ops/*, never a gate in front of it. Every+// endpoint authorizes on the server, so a hostile operator with devtools gains+// nothing by editing this file; what the page owes the real operator is speed+// and the absence of dead ends. Two rules follow from running real jobs:+//+// • Every action reports its outcome in the drawer, including refusals. The+// API returns 409 for an illegal move, and that message is the most useful+// thing on the page when someone clicks the wrong button.+// • The queue reloads after every mutation, so what the operator sees is what+// the database holds. An optimistic UI here would let two operators believe+// different things about the same physical object.++const shell = document.getElementById('mo-app');+const railEl = document.getElementById('mo-rail');+const tableBody = document.getElementById('mo-rows');+const queueTitle = document.getElementById('mo-queue-title');+const refreshBtn = document.getElementById('mo-refresh');+const updatedEl = document.getElementById('mo-updated');+const drawer = document.getElementById('mo-drawer');+const scrim = document.getElementById('mo-scrim');+const drawerBody = document.getElementById('mo-drawer-body');+const drawerTitle = document.getElementById('mo-drawer-title');+const closeBtn = document.getElementById('mo-close');++// The lanes an operator works, in the order a job moves through them. The+// remaining statuses live behind "All" rather than cluttering the rail: a+// delivered order is history, not work.+const RAIL = [+ { key: 'work', label: 'Needs action', statuses: ['paid', 'screening', 'submitted', 'printing', 'quality_check'] },+ { key: 'paid', label: 'Paid', statuses: ['paid'] },+ { key: 'screening', label: 'Screening', statuses: ['screening'] },+ { key: 'submitted', label: 'Submitted', statuses: ['submitted'] },+ { key: 'printing', label: 'Printing', statuses: ['printing'] },+ { key: 'quality_check', label: 'Quality check', statuses: ['quality_check'] },+ { key: 'shipped', label: 'Shipped', statuses: ['shipped'] },+ { key: 'delivered', label: 'Delivered', statuses: ['delivered'] },+ { key: 'closed', label: 'Closed', statuses: ['rejected', 'canceled', 'refunded'] },+ { key: 'all', label: 'All orders', statuses: [] },+];++const STATUS_LABEL = {+ created: 'created', quoted: 'quoted', paid: 'paid', screening: 'screening',+ submitted: 'submitted', printing: 'printing', quality_check: 'quality check',+ shipped: 'shipped', delivered: 'delivered', rejected: 'rejected',+ canceled: 'canceled', refunded: 'refunded',+};++let activeLane = RAIL[0];+let counts = {};+let adapters = [];+let openOrderId = null;+let lastFocused = null;++const esc = (v) =>+ String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);++function statusPill(status) {+ return `<span class="mo-pill" data-status="${esc(status)}">${esc(STATUS_LABEL[status] || status)}</span>`;+}++function shortId(id) {+ return String(id || '').slice(0, 8);+}++function fmtDate(value) {+ if (!value) return 'not yet';+ const d = new Date(value);+ if (Number.isNaN(d.getTime())) return 'unknown';+ return d.toISOString().slice(0, 16).replace('T', ' ');+}++function daysSince(value) {+ if (!value) return null;+ const t = new Date(value).getTime();+ if (Number.isNaN(t)) return null;+ return (Date.now() - t) / 86_400_000;+}++// How late a job is against its own recorded lead time. The console shows this+// on the row because "which of these is in trouble" is the question an operator+// opens the page with.+function lateness(order) {+ const elapsed = daysSince(order.submitted_at);+ if (elapsed == null || !order.lead_time_days) return 0;+ return Math.round(elapsed - Number(order.lead_time_days));+}++async function api(path, options = {}) {+ const res = await fetch(`/api/print/ops/${path}`, {+ credentials: 'include',+ ...options,+ headers: options.body ? { 'content-type': 'application/json', ...(options.headers || {}) } : options.headers,+ });+ let body = null;+ try {+ body = await res.json();+ } catch {+ body = null;+ }+ if (!res.ok) {+ const err = new Error(body?.error_description || body?.error || `request failed (${res.status})`);+ err.status = res.status;+ throw err;+ }+ return body;+}++// ── the queue ────────────────────────────────────────────────────────────────++function renderRail() {+ railEl.innerHTML = RAIL.map((lane) => {+ const n = lane.statuses.length+ ? lane.statuses.reduce((sum, s) => sum + (counts[s] || 0), 0)+ : Object.values(counts).reduce((a, b) => a + b, 0);+ return `<button type="button" class="mo-rail-btn" data-lane="${lane.key}" aria-pressed="${lane.key === activeLane.key}">+ <span>${esc(lane.label)}</span><span class="mo-rail-count">${n}</span>+ </button>`;+ }).join('');+}++function skeletonRows(n = 6) {+ tableBody.innerHTML = `<tr><td colspan="8" style="padding:0">${'<div class="mo-skeleton"></div>'.repeat(n)}</td></tr>`;+}++function emptyState() {+ const message = activeLane.key === 'all'+ ? `<strong>No print orders yet</strong>Orders arrive here the moment a buyer pays and the safety screen passes. Nothing to run right now.`+ : `<strong>Nothing in ${esc(activeLane.label.toLowerCase())}</strong>Pick another lane on the left, or open <em>All orders</em> to see the full history.`;+ tableBody.innerHTML = `<tr><td colspan="8"><div class="mo-state">${message}</div></td></tr>`;+}++function errorState(err) {+ const denied = err.status === 403 || err.status === 401;+ const body = denied+ ? `<strong>You are not signed in as a fulfillment operator</strong>+ Sign in with a platform admin wallet, or ask the owner to add your account to <code>PRINT_OPERATORS</code>.+ Scripts can call this API with an <code>x-ops-secret</code> header instead.`+ : err.status === 503+ ? `<strong>The console needs a configured database</strong>This deployment has no <code>DATABASE_URL</code>, so there are no orders to serve.`+ : `<strong>Could not load the queue</strong>${esc(err.message)}`;+ tableBody.innerHTML = `<tr><td colspan="8"><div class="mo-state">${body}</div></td></tr>`;+}++function rowHtml(order) {+ const late = lateness(order);+ return `<tr class="mo-row" tabindex="0" role="button" data-id="${esc(order.id)}"+ aria-selected="${order.id === openOrderId}" aria-label="Order ${esc(shortId(order.id))}, ${esc(order.status)}">+ <td class="mo-mono">${esc(shortId(order.id))}</td>+ <td>${statusPill(order.status)}${late > 0 ? `<span class="mo-late">+${late}d</span>` : ''}</td>+ <td>${esc(order.material_id || 'tbd')}</td>+ <td class="mo-num">${esc(order.quantity ?? 1)}</td>+ <td class="mo-num">${Number(order.price_usdc || 0).toFixed(2)}</td>+ <td>${esc(order.provider || 'unassigned')}</td>+ <td>${esc(order.ship_to_country || '—')}</td>+ <td class="mo-mono">${esc(fmtDate(order.created_at))}</td>+ </tr>`;+}++async function loadQueue() {+ queueTitle.textContent = activeLane.label;+ skeletonRows();+ try {+ const params = new URLSearchParams();+ if (activeLane.statuses.length) params.set('status', activeLane.statuses.join(','));+ params.set('limit', '100');+ const data = await api(`queue?${params.toString()}`);+ counts = data.counts || {};+ adapters = data.adapters || [];+ renderRail();+ updatedEl.textContent = `updated ${new Date().toLocaleTimeString()}`;+ if (!data.orders?.length) return emptyState();+ tableBody.innerHTML = data.orders.map(rowHtml).join('');+ } catch (err) {+ errorState(err);+ updatedEl.textContent = '';+ }+}++// ── the drawer ───────────────────────────────────────────────────────────────++function openDrawer(orderId) {+ lastFocused = document.activeElement;+ openOrderId = orderId;+ drawer.dataset.open = 'true';+ scrim.dataset.open = 'true';+ drawer.setAttribute('aria-hidden', 'false');+ drawerTitle.textContent = `Order ${shortId(orderId)}`;+ drawerBody.innerHTML = `<div class="mo-state">Loading order…</div>`;+ closeBtn.focus();+ loadDetail(orderId);+}++function closeDrawer() {+ openOrderId = null;+ drawer.dataset.open = 'false';+ scrim.dataset.open = 'false';+ drawer.setAttribute('aria-hidden', 'true');+ drawerBody.innerHTML = '';+ if (lastFocused && document.contains(lastFocused)) lastFocused.focus();+ for (const row of tableBody.querySelectorAll('.mo-row')) row.setAttribute('aria-selected', 'false');+}++async function loadDetail(orderId) {+ try {+ const data = await api(`order?id=${encodeURIComponent(orderId)}`);+ drawerBody.innerHTML = detailHtml(data);+ wireDetail(data);+ } catch (err) {+ drawerBody.innerHTML = `<div class="mo-state"><strong>Could not open this order</strong>${esc(err.message)}</div>`;+ }+}++function filesHtml(assets, sourceGlb) {+ const entries = Object.entries(assets || {}).filter(([, url]) => url);+ if (sourceGlb && !entries.some(([k]) => k === 'glb')) entries.push(['source glb', sourceGlb]);+ if (!entries.length) {+ return `<p class="mo-note">No prepared files on this order yet. It cannot be run until the prepare step has written an STL or 3MF.</p>`;+ }+ return `<div class="mo-files">${entries+ .map(([kind, url]) => `<a class="mo-btn" href="${esc(url)}" download target="_blank" rel="noopener">Download ${esc(kind)}</a>`)+ .join('')}</div>`;+}++function shippingHtml(shipping) {+ if (!shipping) return `<p class="mo-note">No shipping address on this order.</p>`;+ const lines = [+ shipping.name,+ shipping.line1,+ shipping.line2,+ [shipping.city, shipping.region, shipping.postal_code].filter(Boolean).join(', '),+ shipping.country,+ shipping.phone,+ ].filter(Boolean);+ return `<address style="font-style:normal;font-size:var(--text-md);line-height:1.618">${lines.map(esc).join('<br />')}</address>`;+}++function timelineHtml(events) {+ if (!events?.length) return `<p class="mo-note">No events recorded yet.</p>`;+ return `<ol class="mo-timeline">${[...events]+ .reverse()+ .map(+ (e) => `<li><div>+ <div>${statusPill(e.status)} <span class="mo-timeline-meta">${esc(e.actor)} · ${esc(fmtDate(e.created_at))}</span></div>+ ${e.note ? `<p class="mo-timeline-note">${esc(e.note)}</p>` : ''}+ </div></li>`,+ )+ .join('')}</ol>`;+}++function detailHtml({ order, events, webhook_deliveries: deliveries }) {+ const next = order.next || [];+ const configured = adapters.filter((a) => a.configured);+ const canSubmit = order.status === 'screening';+ const late = lateness(order);++ return `+ <section>+ <h3 class="mo-section-title">Job</h3>+ <dl class="mo-kv">+ <dt>Order</dt><dd class="mo-mono">${esc(order.id)}</dd>+ <dt>Status</dt><dd>${statusPill(order.status)}${late > 0 ? `<span class="mo-late">${late} days past lead time</span>` : ''}</dd>+ <dt>Material</dt><dd>${esc(order.material_id || 'not set')}</dd>+ <dt>Quantity</dt><dd class="mo-num">${esc(order.quantity ?? 1)}</dd>+ <dt>Height</dt><dd>${order.target_height_mm ? `${esc(order.target_height_mm)} mm` : 'per quote'}</dd>+ <dt>Price</dt><dd class="mo-num">${Number(order.price_usdc || 0).toFixed(2)} USDC</dd>+ <dt>Lane</dt><dd>${esc(order.provider || 'unassigned')}${order.provider_order_id ? ` · <span class="mo-mono">${esc(order.provider_order_id)}</span>` : ''}</dd>+ <dt>Submitted</dt><dd>${esc(fmtDate(order.submitted_at))}</dd>+ <dt>Tracking</dt><dd>${order.tracking_number ? `${esc(order.tracking_number)}${order.carrier ? ` (${esc(order.carrier)})` : ''}` : 'none'}</dd>+ </dl>+ </section>++ <section>+ <h3 class="mo-section-title">Files for the bureau</h3>+ ${filesHtml(order.prepared_asset_urls, order.source_glb_url)}+ </section>++ <section>+ <h3 class="mo-section-title">Ship to</h3>+ ${shippingHtml(order.shipping)}+ </section>++ ${canSubmit ? `<section>+ <h3 class="mo-section-title">Hand to a lane</h3>+ <div class="mo-field">+ <label for="mo-adapter">Fulfillment lane</label>+ <select class="mo-select" id="mo-adapter">+ <option value="">Route automatically</option>+ ${configured.map((a) => `<option value="${esc(a.key)}">${esc(a.label)}</option>`).join('')}+ </select>+ </div>+ <div class="mo-actions" style="margin-top:8px">+ <button type="button" class="mo-btn mo-btn-primary" data-act="submit">Submit to lane</button>+ </div>+ </section>` : ''}++ ${['submitted', 'printing', 'quality_check', 'shipped'].includes(order.status) ? `<section>+ <h3 class="mo-section-title">Tracking</h3>+ <div class="mo-inline">+ <div class="mo-field">+ <label for="mo-tracking">Tracking number</label>+ <input class="mo-input" id="mo-tracking" value="${esc(order.tracking_number || '')}" autocomplete="off" />+ </div>+ <div class="mo-field">+ <label for="mo-carrier">Carrier</label>+ <input class="mo-input" id="mo-carrier" value="${esc(order.carrier || '')}" autocomplete="off" />+ </div>+ </div>+ <div class="mo-actions" style="margin-top:8px">+ <button type="button" class="mo-btn mo-btn-primary" data-act="tracking">+ ${order.status === 'shipped' ? 'Correct tracking' : 'Save and mark shipped'}+ </button>+ </div>+ </section>` : ''}++ <section>+ <h3 class="mo-section-title">Move this order</h3>+ <div class="mo-field">+ <label for="mo-note">Note for the timeline</label>+ <textarea class="mo-textarea" id="mo-note" maxlength="2000" placeholder="What happened, in the words the next operator needs."></textarea>+ </div>+ <div class="mo-actions" style="margin-top:8px">+ ${next+ .filter((s) => s !== 'submitted')+ .map((s) => `<button type="button" class="mo-btn${['rejected', 'canceled', 'refunded'].includes(s) ? ' mo-btn-danger' : ''}"+ data-act="to" data-to="${esc(s)}">Mark ${esc(STATUS_LABEL[s] || s)}</button>`)+ .join('')}+ ${next.length === 0 || (next.length === 1 && next[0] === 'submitted')+ ? `<p class="mo-note">This order is closed. Nothing further can move it.</p>`+ : ''}+ </div>+ <p class="mo-note" id="mo-result" role="status" aria-live="polite"></p>+ <div id="mo-payout"></div>+ </section>++ <section>+ <h3 class="mo-section-title">Timeline</h3>+ ${timelineHtml(events)}+ </section>++ <section>+ <h3 class="mo-section-title">Webhook deliveries</h3>+ ${deliveries?.length+ ? `<ul class="mo-timeline">${deliveries+ .map((d) => `<li><div><span class="mo-mono">${esc(d.provider)} · ${esc(d.delivery_id.slice(0, 24))}</span>+ <p class="mo-timeline-note">${d.applied ? 'applied' : 'received, no change'} · ${esc(fmtDate(d.received_at))}</p></div></li>`)+ .join('')}</ul>`+ : `<p class="mo-note">No provider callbacks for this order. The manual lane sends none by design.</p>`}+ </section>`;+}++function wireDetail(data) {+ const order = data.order;+ const result = drawerBody.querySelector('#mo-result');+ const payoutEl = drawerBody.querySelector('#mo-payout');++ const say = (message, tone = '') => {+ result.textContent = message;+ if (tone) result.dataset.tone = tone;+ else delete result.dataset.tone;+ };++ const run = async (button, work) => {+ const buttons = [...drawerBody.querySelectorAll('button[data-act]')];+ for (const b of buttons) b.disabled = true;+ button.dataset.busy = 'true';+ say('Working…');+ try {+ const body = await work();+ say(body.message || 'Done.', 'ok');+ if (body.payout) {+ payoutEl.innerHTML = `<p class="mo-payout"><strong>Owner action required.</strong>+ Send <strong>${Number(body.payout.amount_usdc || 0).toFixed(2)} USDC</strong> on Solana to+ <span class="mo-mono">${esc(body.payout.recipient || 'the buyer account')}</span>.+ ${esc(body.payout.instruction)}</p>`;+ }+ await loadQueue();+ await loadDetail(order.id);+ } catch (err) {+ say(err.message, 'error');+ for (const b of buttons) b.disabled = false;+ delete button.dataset.busy;+ }+ };++ drawerBody.addEventListener('click', (event) => {+ const button = event.target.closest('button[data-act]');+ if (!button) return;+ const note = drawerBody.querySelector('#mo-note')?.value || '';++ if (button.dataset.act === 'submit') {+ const adapter = drawerBody.querySelector('#mo-adapter')?.value || '';+ return run(button, async () => {+ const body = await api('submit', { method: 'POST', body: JSON.stringify({ order_id: order.id, adapter }) });+ return { message: `Submitted to ${body.adapter}.` };+ });+ }++ if (button.dataset.act === 'tracking') {+ const trackingNumber = drawerBody.querySelector('#mo-tracking')?.value.trim() || '';+ const carrier = drawerBody.querySelector('#mo-carrier')?.value.trim() || '';+ if (!trackingNumber) return say('Enter a tracking number first.', 'error');+ return run(button, async () => {+ const body = await api('tracking', {+ method: 'POST',+ body: JSON.stringify({ order_id: order.id, tracking_number: trackingNumber, carrier, note, ship: order.status !== 'shipped' }),+ });+ return { message: `Order is ${body.order.status}.` };+ });+ }++ if (button.dataset.act === 'to') {+ const to = button.dataset.to;+ // The two moves that end an order get a confirmation. Everything else+ // is reversible by another transition; these are not.+ if ((to === 'refunded' || to === 'canceled') && !window.confirm(`Mark order ${shortId(order.id)} as ${to}? This cannot be undone.`)) return;+ const path = to === 'canceled' ? 'cancel' : to === 'refunded' ? 'refund' : 'transition';+ const payload = to === 'canceled'+ ? { order_id: order.id, reason: note }+ : to === 'refunded'+ ? { order_id: order.id, note }+ : { order_id: order.id, to, note };+ return run(button, async () => {+ const body = await api(path, { method: 'POST', body: JSON.stringify(payload) });+ return { message: `Order is ${body.order.status}.`, payout: body.payout };+ });+ }+ });+}++// ── events ───────────────────────────────────────────────────────────────────++railEl.addEventListener('click', (event) => {+ const button = event.target.closest('[data-lane]');+ if (!button) return;+ activeLane = RAIL.find((l) => l.key === button.dataset.lane) || RAIL[0];+ renderRail();+ loadQueue();+});++tableBody.addEventListener('click', (event) => {+ const row = event.target.closest('.mo-row');+ if (row) openDrawer(row.dataset.id);+});++tableBody.addEventListener('keydown', (event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ const row = event.target.closest('.mo-row');+ if (!row) return;+ event.preventDefault();+ openDrawer(row.dataset.id);+});++refreshBtn.addEventListener('click', () => loadQueue());+closeBtn.addEventListener('click', closeDrawer);+scrim.addEventListener('click', closeDrawer);++document.addEventListener('keydown', (event) => {+ if (event.key === 'Escape' && openOrderId) closeDrawer();+ // The one shortcut worth having: an operator reloads the queue constantly.+ if (event.key === 'r' && !openOrderId && !/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || '')) {+ loadQueue();+ }+});++renderRail();+loadQueue();++// Deep link: the Telegram ops message and the notification bell both link+// straight to one order, which is the whole point of paging someone.+const requested = new URLSearchParams(location.search).get('order');+if (requested) openDrawer(requested);++shell.dataset.ready = 'true';diff --git a/src/print-insert.css b/src/print-insert.cssnew file mode 100644index 000000000..b0087da00--- /dev/null+++ b/src/print-insert.css@@ -0,0 +1,229 @@+/* The package insert card (/materialize/insert/:certId).+ Two audiences, one sheet: an operator on screen, and a sheet of card stock+ coming out of a printer. The @media print block is the real deliverable, so+ nothing here uses a screen-only trick (dark surfaces, backdrop filters) that+ a printer renders as a slab of toner. */++.pi-sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+}++.pi-root {+ max-width: 860px;+ margin: 0 auto;+ padding: var(--space-xl, 32px) var(--space-lg, 24px) var(--space-3xl, 96px);+ color: var(--ink, rgba(255, 255, 255, 0.88));+}++.pi-status {+ padding: var(--space-lg, 24px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-lg, 16px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ color: var(--ink-dim, rgba(255, 255, 255, 0.62));+ font-size: var(--text-sm, 13px);+ line-height: 1.6;+}++.pi-toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2, 8px);+ margin-bottom: var(--space-lg, 24px);+}++.pi-toolbar-note {+ flex: 1 1 220px;+ min-width: 0;+ font-size: var(--text-xs, 12px);+ color: var(--ink-dim, rgba(255, 255, 255, 0.5));+ line-height: 1.6;+}++.pi-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 9px 14px;+ border-radius: var(--radius-pill, 999px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.14));+ background: transparent;+ color: var(--ink, rgba(255, 255, 255, 0.88));+ font: inherit;+ font-size: var(--text-sm, 13px);+ text-decoration: none;+ cursor: pointer;+ transition:+ background 0.15s ease,+ border-color 0.15s ease,+ transform 0.1s ease;+}+.pi-btn:hover {+ background: var(--surface-2, rgba(255, 255, 255, 0.06));+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.24));+}+.pi-btn:active {+ transform: translateY(1px);+}+.pi-btn:focus-visible {+ outline: 2px solid var(--accent, #7c9cff);+ outline-offset: 2px;+}+.pi-btn--primary {+ background: var(--ink-bright, #fff);+ color: var(--bg, #0a0a0a);+ border-color: transparent;+ font-weight: var(--weight-medium, 500);+}++/* ── the card ─────────────────────────────────────────────────────────── */++.pi-card {+ /* A5 landscape: the size a print bureau's card stock cuts to without waste. */+ width: 210mm;+ max-width: 100%;+ min-height: 148mm;+ margin: 0 auto;+ padding: 14mm;+ box-sizing: border-box;+ display: grid;+ grid-template-columns: 1fr auto;+ grid-template-rows: auto 1fr auto;+ gap: 8mm;+ background: #ffffff;+ color: #111111;+ border-radius: 3mm;+ border: 1px solid rgba(0, 0, 0, 0.12);+ font-family: var(--font-sans, system-ui, sans-serif);+}++.pi-mark {+ grid-column: 1 / -1;+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 8mm;+ border-bottom: 0.4mm solid #111111;+ padding-bottom: 4mm;+}++.pi-wordmark {+ font-family: var(--font-display, system-ui, sans-serif);+ font-size: 7mm;+ font-weight: 700;+ letter-spacing: -0.02em;+ margin: 0;+}++.pi-kicker {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 2.8mm;+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: #555555;+ margin: 0;+}++.pi-body h1 {+ margin: 0 0 3mm;+ font-family: var(--font-display, system-ui, sans-serif);+ font-size: 8mm;+ line-height: 1.15;+ letter-spacing: -0.02em;+}++.pi-edition {+ margin: 0 0 6mm;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 4.6mm;+ letter-spacing: 0.02em;+}++.pi-facts {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 4mm 8mm;+ margin: 0;+}+.pi-facts dt {+ margin: 0 0 1mm;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 2.6mm;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: #666666;+}+.pi-facts dd {+ margin: 0;+ font-size: 3.4mm;+ line-height: 1.4;+ overflow-wrap: anywhere;+}++.pi-qr-block {+ text-align: center;+ align-self: center;+}+.pi-qr {+ width: 42mm;+ height: 42mm;+ display: block;+ margin: 0 auto 2mm;+}+.pi-qr-caption {+ margin: 0;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 2.6mm;+ letter-spacing: 0.06em;+ color: #444444;+}++.pi-foot {+ grid-column: 1 / -1;+ border-top: 0.3mm solid rgba(0, 0, 0, 0.2);+ padding-top: 3mm;+ font-size: 2.7mm;+ line-height: 1.5;+ color: #444444;+ display: flex;+ justify-content: space-between;+ gap: 6mm;+}+.pi-foot code {+ font-family: var(--font-mono, ui-monospace, monospace);+ overflow-wrap: anywhere;+}++/* ── print ────────────────────────────────────────────────────────────── */++@page {+ size: A5 landscape;+ margin: 0;+}++@media print {+ .pi-toolbar,+ .pi-status {+ display: none !important;+ }+ .pi-root {+ padding: 0;+ max-width: none;+ }+ .pi-card {+ border: 0;+ border-radius: 0;+ width: 100%;+ min-height: 100vh;+ page-break-inside: avoid;+ }+}diff --git a/src/print-insert.js b/src/print-insert.jsnew file mode 100644index 000000000..1aa576309--- /dev/null+++ b/src/print-insert.js@@ -0,0 +1,165 @@+// /materialize/insert/:certId — the card that goes in the box.+//+// An operator opens this at the shipping step, prints it on card stock, and+// drops it in with the object. Everything on the card is what a buyer needs+// months later with no receipt and no email: the model's name, its edition, the+// certificate number, and a QR that resolves to the full proof at /cert/<id>.+//+// The endpoint behind it is operator-gated (api/print/ops/insert-card.js). This+// page is a rendering tool, never the security boundary: an unauthorized+// operator gets a designed refusal here because the server refused, not because+// the page decided to hide something.+//+// Real endpoint only:+// GET /api/print/ops/insert-card?cert=<certId> → { certificate, order, insert_url }++import { apiFetch } from './api.js';+import { createLogger } from './shared/log.js';++const log = createLogger('print-insert');+const CERT_ID_RE = /^[0-9a-f]{24}$/;++const root = () => document.getElementById('pi-root');++function esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function announce(message) {+ const el = document.getElementById('pi-live');+ if (el) el.textContent = message;+}++export function certIdFromPath(pathname = window.location.pathname) {+ const m = String(pathname || '').match(/^\/materialize\/insert\/([0-9a-f]{24})\/?$/i);+ return m ? m[1].toLowerCase() : null;+}++export function titleFromPrompt(prompt) {+ const raw = String(prompt || '').trim().replace(/\s+/g, ' ');+ if (!raw) return 'three.ws print';+ const clipped = raw.length > 52 ? `${raw.slice(0, 51).trimEnd()}…` : raw;+ return clipped.charAt(0).toUpperCase() + clipped.slice(1);+}++export function editionLine(cert) {+ return cert.edition_of ? `Edition ${cert.edition_no} of ${cert.edition_of}` : `Edition ${cert.edition_no}, open edition`;+}++function formatDate(value) {+ if (!value) return null;+ const d = new Date(value);+ if (Number.isNaN(d.getTime())) return null;+ return d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });+}++/** Group the certificate id in fours so a human can read it off card stock. */+export function groupId(id) {+ return String(id || '').replace(/(.{4})(?=.)/g, '$1 ');+}++function renderStatus(message, { retry = false } = {}) {+ const host = root();+ if (!host) return;+ host.innerHTML = `<div class="pi-status">${esc(message)}</div>+ ${retry ? '<div class="pi-toolbar" style="margin-top:16px"><button class="pi-btn pi-btn--primary" type="button" id="pi-retry">Try again</button></div>' : ''}`;+ host.setAttribute('aria-busy', 'false');+ document.getElementById('pi-retry')?.addEventListener('click', () => void load());+ announce(message);+}++function renderCard(payload) {+ const host = root();+ if (!host) return;+ const cert = payload.certificate;+ const title = cert.creation?.prompt_withheld ? 'three.ws print' : titleFromPrompt(cert.creation?.prompt);+ document.title = `Insert · ${cert.id} · three.ws`;++ const facts = [+ ['Certificate', groupId(cert.id)],+ ['Material', cert.material_label || cert.material_id || 'As ordered'],+ ['Printed', formatDate(cert.printed_at) || 'On the ship date'],+ [+ 'On-chain proof',+ cert.solana_signature+ ? `${cert.network === 'mainnet' ? 'Solana' : 'Solana devnet'} · ${cert.solana_signature.slice(0, 12)}…`+ : 'Attestation pending',+ ],+ ];++ host.innerHTML = `+ <div class="pi-toolbar">+ <button class="pi-btn pi-btn--primary" type="button" id="pi-print">Print this card</button>+ <a class="pi-btn" href="${esc(cert.certificate_url)}" target="_blank" rel="noopener">Open the certificate</a>+ <p class="pi-toolbar-note">+ A5 landscape on card stock. Print, fold nothing, drop it in the box with the object.+ ${payload.order ? `Order ${esc(payload.order.id)} (${esc(payload.order.status)}).` : ''}+ </p>+ </div>+ <article class="pi-card">+ <div class="pi-mark">+ <p class="pi-wordmark">three.ws</p>+ <p class="pi-kicker">Certificate of authenticity</p>+ </div>+ <div class="pi-body">+ <h1>${esc(title)}</h1>+ <p class="pi-edition">${esc(editionLine(cert))}</p>+ <dl class="pi-facts">+ ${facts.map(([k, v]) => `<div><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`).join('')}+ </dl>+ </div>+ <div class="pi-qr-block">+ ${+ cert.qr_url+ ? `<img class="pi-qr" src="${esc(cert.qr_url)}" alt="QR code to this certificate" />`+ : '<div class="pi-qr" style="border:0.3mm dashed #999;display:flex;align-items:center;justify-content:center;font-size:2.6mm;color:#666">QR pending</div>'+ }+ <p class="pi-qr-caption">${esc(cert.certificate_url.replace(/^https?:\/\//, ''))}</p>+ </div>+ <div class="pi-foot">+ <span>Scan the code to see the original model, its lineage, and the transaction that attests this object's exact bytes.</span>+ <code>SHA-256 ${esc(cert.glb_sha256.slice(0, 16))}…</code>+ </div>+ </article>`;+ host.setAttribute('aria-busy', 'false');+ document.getElementById('pi-print')?.addEventListener('click', () => window.print());+ announce(`Insert card for certificate ${cert.id}, ${editionLine(cert)}.`);+}++async function load() {+ const id = certIdFromPath();+ if (!id || !CERT_ID_RE.test(id)) {+ renderStatus('That is not a certificate number. Open this page from an order in the operator console.');+ return;+ }+ try {+ const res = await apiFetch(`/api/print/ops/insert-card?cert=${encodeURIComponent(id)}`);+ if (res.status === 403 || res.status === 401) {+ renderStatus('Operator authorization required. Sign in as a platform admin, or present the ops secret.');+ return;+ }+ if (res.status === 404) {+ renderStatus('No certificate with that number. Certificates are issued when an order ships.');+ return;+ }+ if (!res.ok) throw new Error(`insert-card request failed: ${res.status}`);+ const payload = await res.json();+ if (!payload?.certificate) throw new Error('certificate missing from response');+ renderCard(payload);+ } catch (err) {+ log.error('insert card load failed', err);+ renderStatus('Could not load the insert card. The connection failed on the way here.', { retry: true });+ }+}++if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => void load());+ } else {+ void load();+ }+}diff --git a/tests/api/print-exporters.test.js b/tests/api/print-exporters.test.jsnew file mode 100644index 000000000..7106b3dcf--- /dev/null+++ b/tests/api/print-exporters.test.js@@ -0,0 +1,233 @@+// The two manufacturing files Materialize hands a print bureau.+//+// Nothing downstream can second-guess these bytes: a bureau opens the STL in a+// slicer and prints whatever is in it, and a color machine reproduces whatever+// the 3MF's color group says. So the assertions here are structural and+// byte-level, not "it did not throw": the STL's header layout and triangle+// count, the exact geometry that came back out of it, the 3MF's OPC part names,+// its XML against the core-spec subset the writer promises, and the presence of+// the per-vertex color payload that is the entire reason the 3MF exists.+//+// Fixtures are generated in this file, never committed: a binary blob in the+// repo is a fixture nobody can review.++import { describe, it, expect } from 'vitest';+import { unzipSync, strFromU8 } from 'fflate';+import { XMLParser, XMLValidator } from 'fast-xml-parser';++import { exportStl, readStlHeader, StlExportError, STL_BYTES } from '../../api/_lib/print/export-stl.js';+import {+ export3mf,+ buildColorGroup,+ ThreeMfExportError,+ CONTENT_TYPES_PART,+ RELS_PART,+ MODEL_PART,+ CORE_NAMESPACE,+ MATERIAL_NAMESPACE,+} from '../../api/_lib/print/export-3mf.js';++// A 10 mm axis-aligned cube in glTF meters: 8 vertices, 12 triangles, a known+// volume and a known bounding box, so every number an exporter writes can be+// checked against arithmetic rather than against a previous run.+const EDGE_M = 0.01;+function unitCube({ color = false } = {}) {+ const s = EDGE_M;+ const positions = Float64Array.from([+ 0, 0, 0, s, 0, 0, s, s, 0, 0, s, 0,+ 0, 0, s, s, 0, s, s, s, s, 0, s, s,+ ]);+ const indices = Uint32Array.from([+ 0, 2, 1, 0, 3, 2, // -z+ 4, 5, 6, 4, 6, 7, // +z+ 0, 1, 5, 0, 5, 4, // -y+ 2, 3, 7, 2, 7, 6, // +y+ 1, 2, 6, 1, 6, 5, // +x+ 0, 4, 7, 0, 7, 3, // -x+ ]);+ // Two distinct colors over eight vertices: enough to prove the palette+ // dedupes and that each vertex still points at the right entry.+ const colors = color+ ? Uint8Array.from([+ 255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0,+ 0, 128, 255, 0, 128, 255, 0, 128, 255, 0, 128, 255,+ ])+ : null;+ return { positions, indices, colors };+}++describe('exportStl', () => {+ it('writes a binary STL whose header, count and length agree', () => {+ const stl = exportStl(unitCube());+ const head = readStlHeader(stl);+ expect(head.triangles).toBe(12);+ expect(head.actualBytes).toBe(head.expectedBytes);+ expect(stl.byteLength).toBe(STL_BYTES.header + STL_BYTES.count + 12 * STL_BYTES.triangle);+ });++ it('never starts the header with "solid", which readers sniff as ASCII', () => {+ const stl = exportStl(unitCube());+ expect(stl.subarray(0, 5).toString('ascii').toLowerCase()).not.toBe('solid');+ expect(readStlHeader(stl).header).toContain('three.ws');+ });++ it('converts glTF meters to the millimeters a slicer assumes', () => {+ const stl = exportStl(unitCube());+ // First triangle's three vertices start 12 bytes past the normal.+ const base = STL_BYTES.header + STL_BYTES.count + 12;+ const read = (i) => stl.readFloatLE(base + i * 4);+ const xs = [read(0), read(3), read(6)];+ const ys = [read(1), read(4), read(7)];+ for (const v of [...xs, ...ys]) {+ expect([0, EDGE_M * 1000]).toContain(Math.round(v * 1000) / 1000);+ }+ // A 10 mm cube must span exactly 10 units in the file, not 0.01.+ expect(Math.max(...xs)).toBeCloseTo(10, 6);+ });++ it('writes a unit-length face normal that agrees with the winding', () => {+ const stl = exportStl(unitCube());+ const base = STL_BYTES.header + STL_BYTES.count;+ const n = [stl.readFloatLE(base), stl.readFloatLE(base + 4), stl.readFloatLE(base + 8)];+ expect(Math.hypot(...n)).toBeCloseTo(1, 5);+ // Triangle 0 is on the -z face wound outward, so its normal points -z.+ expect(n[2]).toBeCloseTo(-1, 5);+ });++ it('zeroes the attribute byte count on every triangle', () => {+ const stl = exportStl(unitCube());+ for (let t = 0; t < 12; t += 1) {+ const at = STL_BYTES.header + STL_BYTES.count + t * STL_BYTES.triangle + 48;+ expect(stl.readUInt16LE(at)).toBe(0);+ }+ });++ it('is deterministic: the same mesh exports the same bytes', () => {+ expect(exportStl(unitCube()).equals(exportStl(unitCube()))).toBe(true);+ });++ it('refuses an empty mesh and a ragged index buffer', () => {+ expect(() => exportStl({ positions: new Float64Array(0), indices: new Uint32Array(0) })).toThrow(+ StlExportError,+ );+ const cube = unitCube();+ expect(() => exportStl({ positions: cube.positions, indices: cube.indices.slice(0, 4) })).toThrow(+ /whole number of triangles/,+ );+ });++ it('refuses to export a mesh the caller knows is still open', () => {+ expect(() => exportStl(unitCube(), { requireWatertight: true, openEdges: 4 })).toThrow(+ /open edges/,+ );+ expect(() => exportStl(unitCube(), { requireWatertight: true, openEdges: 0 })).not.toThrow();+ });+});++describe('buildColorGroup', () => {+ it('dedupes identical colors and keeps every vertex pointing at its own', () => {+ const cube = unitCube({ color: true });+ const group = buildColorGroup(cube.colors, 8);+ expect(group.palette).toEqual(['FF0000', '0080FF']);+ expect(Array.from(group.indexOf)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]);+ });++ it('returns null when the mesh carries no color at all', () => {+ expect(buildColorGroup(null, 8)).toBeNull();+ expect(buildColorGroup(new Uint8Array(3), 8)).toBeNull();+ });+});++function openPackage(bytes) {+ const files = unzipSync(new Uint8Array(bytes));+ return { files, names: Object.keys(files), model: strFromU8(files[MODEL_PART]) };+}++describe('export3mf', () => {+ it('produces an OPC package with exactly the three required parts', () => {+ const { names } = openPackage(export3mf(unitCube({ color: true })));+ expect(names).toContain(CONTENT_TYPES_PART);+ expect(names).toContain(RELS_PART);+ expect(names).toContain(MODEL_PART);+ });++ it('declares the model content type and the start-part relationship', () => {+ const { files } = openPackage(export3mf(unitCube()));+ const types = strFromU8(files[CONTENT_TYPES_PART]);+ expect(types).toContain('application/vnd.ms-package.3dmanufacturing-3dmodel+xml');+ expect(types).toContain('Extension="model"');+ const rels = strFromU8(files[RELS_PART]);+ expect(rels).toContain(`Target="/${MODEL_PART}"`);+ expect(rels).toContain('http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel');+ });++ it('writes well-formed model XML in millimeters with one build item', () => {+ const { model } = openPackage(export3mf(unitCube({ color: true })));+ expect(XMLValidator.validate(model)).toBe(true);+ const doc = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@' }).parse(model);+ expect(doc.model['@unit']).toBe('millimeter');+ expect(doc.model['@xmlns']).toBe(CORE_NAMESPACE);+ expect(doc.model['@xmlns:m']).toBe(MATERIAL_NAMESPACE);+ expect(doc.model.build.item['@objectid']).toBe(String(doc.model.resources.object['@id']));+ });++ it('carries every vertex and triangle, in the positive octant, at print size', () => {+ const { model } = openPackage(export3mf(unitCube()));+ const doc = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@' }).parse(model);+ const vertices = doc.model.resources.object.mesh.vertices.vertex;+ const triangles = doc.model.resources.object.mesh.triangles.triangle;+ expect(vertices).toHaveLength(8);+ expect(triangles).toHaveLength(12);+ const xs = vertices.map((v) => Number(v['@x']));+ const ys = vertices.map((v) => Number(v['@y']));+ const zs = vertices.map((v) => Number(v['@z']));+ for (const axis of [xs, ys, zs]) {+ expect(Math.min(...axis)).toBe(0);+ expect(Math.max(...axis)).toBeCloseTo(EDGE_M * 1000, 6);+ }+ });++ it('writes the per-vertex color payload that makes a color print possible', () => {+ const { model } = openPackage(export3mf(unitCube({ color: true })));+ const doc = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@' }).parse(model);+ const group = doc.model.resources['m:colorgroup'];+ expect(group).toBeTruthy();+ expect(group['m:color'].map((c) => c['@color'])).toEqual(['#FF0000FF', '#0080FFFF']);+ const object = doc.model.resources.object;+ expect(object['@pid']).toBe(String(group['@id']));+ // Triangle 0 is on the -z face: all three of its corners are vertices+ // 0..3, which the fixture colors red, palette entry 0.+ const first = object.mesh.triangles.triangle[0];+ expect([first['@p1'], first['@p2'], first['@p3']]).toEqual(['0', '0', '0']);+ });++ it('does not require the material extension, so a mono slicer still opens it', () => {+ const { model } = openPackage(export3mf(unitCube({ color: true })));+ expect(model).not.toContain('requiredextensions');+ });++ it('omits the color group entirely for a mesh with no color', () => {+ const { model } = openPackage(export3mf(unitCube()));+ expect(model).not.toContain('colorgroup');+ expect(model).not.toContain(' p1=');+ });++ it('is deterministic: the certificate hashes these exact bytes', () => {+ const a = export3mf(unitCube({ color: true }));+ const b = export3mf(unitCube({ color: true }));+ expect(a.equals(b)).toBe(true);+ });++ it('refuses an empty mesh, a ragged index buffer and an out-of-range index', () => {+ expect(() => export3mf({ positions: new Float64Array(0), indices: new Uint32Array(0) })).toThrow(+ ThreeMfExportError,+ );+ const cube = unitCube();+ expect(() => export3mf({ positions: cube.positions, indices: cube.indices.slice(0, 5) })).toThrow(+ /whole number of triangles/,+ );+ expect(() =>+ export3mf({ positions: cube.positions, indices: Uint32Array.from([0, 1, 99]) }),+ ).toThrow(/does not exist/);+ });+});diff --git a/tests/api/print-fabrication-gate.test.js b/tests/api/print-fabrication-gate.test.jsnew file mode 100644index 000000000..265a5e757--- /dev/null+++ b/tests/api/print-fabrication-gate.test.js@@ -0,0 +1,344 @@+// The fabrication gate: what three.ws will and will not physically manufacture.+//+// This suite is the specification. A refused image generation costs nothing and+// a printed firearm receiver is a felony, so every denylist category is pinned+// here with BOTH a request that must be refused and an ordinary request using+// neighbouring words that must not be. A gate that refuses everything is as+// broken as one that refuses nothing, and the false-positive cases are the ones+// that quietly kill a product.+//+// The LLM layer is mocked per test (it is a network call, and its job here is+// only to be wired correctly: it can add a refusal, it can never lift one).++import { describe, it, expect, vi, beforeEach } from 'vitest';++const llmMock = vi.fn();+vi.mock('../../api/_lib/llm.js', () => ({+ llmComplete: (...args) => llmMock(...args),+ LlmUnavailableError: class extends Error {},+}));++const notifyMock = vi.fn(async () => {});+vi.mock('../../api/_lib/print/ops-notify.js', () => ({+ notifyOperators: (...args) => notifyMock(...args),+ jobSummaryLines: () => [],+ operatorChannelConfigured: () => true,+}));++const {+ runFabricationGate,+ screenDeterministic,+ gateSubject,+ geometrySignal,+ notifyGateOutcome,+ MINIATURE_MAX_MM,+ GATE_VERSION,+ POLICY_URL,+} = await import('../../api/_lib/print/gate.js');+const { FABRICATION_RULES, evaluateRules, ruleById } = await import('../../api/_lib/print/rules.js');++// A display-scale object and a life-size one. Scale is the single geometric+// signal the gate uses, and the soft rules read it.+const MINI = { bbox_mm: { x: 28, y: 65, z: 24, diagonal: 74 } };+const LIFE_SIZE = { bbox_mm: { x: 210, y: 140, z: 35, diagonal: 254 } };++const quote = (lineageText, analysis = MINI, extra = {}) =>+ runFabricationGate({ stage: 'quote', lineageText, analysis, ...extra });++beforeEach(() => {+ llmMock.mockReset();+ notifyMock.mockReset();+});++describe('denylist coverage: every category refuses and every neighbour passes', () => {+ // One deny case and one allow case per rule. The allow case is deliberately+ // chosen from the same subject area, because "sword" passing while "handgun"+ // fails is the only version of this gate a 3D platform can actually ship.+ const cases = [+ {+ rule: 'firearm_components',+ deny: 'an AR-15 lower receiver, printed in nylon',+ allow: 'a stylised fantasy greatsword with an engraved hilt',+ },+ {+ rule: 'suppressors',+ deny: 'a monocore baffle for a suppressor',+ allow: 'a monocone lampshade with an internal reflector',+ },+ {+ rule: 'ammunition',+ deny: 'a drum magazine that holds 50 rounds',+ allow: 'a drum-shaped pen holder for my desk',+ },+ {+ rule: 'lock_bypass',+ deny: 'a bump key that opens my neighbour front door',+ allow: 'an ornamental fantasy key pendant with a dragon bow',+ },+ {+ rule: 'counterfeit',+ deny: 'a counterfeit authentication tag with the hologram',+ allow: 'a name plate with my own studio logo on it',+ },+ {+ rule: 'working_weapon_mechanisms',+ deny: 'a balisong butterfly knife with working pivots',+ allow: 'a butterfly brooch with folded wings',+ },+ {+ rule: 'drug_paraphernalia',+ deny: 'a glass bong with a percolator',+ allow: 'a tall glass vase with a fluted neck',+ },+ ];++ for (const { rule, deny, allow } of cases) {+ it(`${rule}: refuses the prohibited request`, async () => {+ const verdict = await quote(deny);+ expect(verdict.verdict).toBe('refuse');+ expect(verdict.category).toBe(rule);+ expect(verdict.layer).toBe('denylist');+ // Designed refusal: names the category, links the policy, says what is allowed.+ expect(verdict.label).toBe(ruleById(rule).label);+ expect(verdict.policy_url).toBe(POLICY_URL);+ expect(verdict.message.length).toBeGreaterThan(20);+ expect(verdict.allowed.length).toBeGreaterThan(20);+ });++ it(`${rule}: allows an ordinary request from the same subject area`, async () => {+ const verdict = await quote(allow);+ expect(verdict.verdict).toBe('allow');+ expect(verdict.category).toBeNull();+ });+ }++ it('covers every rule declared in rules.js', () => {+ const hardRules = FABRICATION_RULES.filter((r) => r.tier === 'hard').map((r) => r.id);+ const covered = cases.map((c) => c.rule);+ expect([...hardRules].sort()).toEqual([...covered].sort());+ });++ it('every rule carries a buyer-facing message and an allowed alternative', () => {+ for (const rule of FABRICATION_RULES) {+ expect(rule.message, rule.id).toMatch(/three\.ws does not manufacture/);+ expect(rule.allowed.length, rule.id).toBeGreaterThan(20);+ }+ });++ it('matches whole words only, so an innocent substring never trips a rule', () => {+ // "bongo", "keyboard" and "barrelled" contain rule terms as substrings.+ expect(evaluateRules('a bongo drum on a stand').hard).toBeNull();+ expect(evaluateRules('a mechanical keyboard case').hard).toBeNull();+ expect(evaluateRules('an oak barrelled planter').hard).toBeNull();+ });+});++describe('the soft rule: weapon likeness resolves on scale', () => {+ it('allows a weapon-carrying miniature at display scale', async () => {+ const verdict = await quote('a knight holding a pistol, tabletop miniature', MINI);+ expect(verdict.verdict).toBe('allow');+ // It is flagged but deliberately undecided by the deterministic layers.+ expect(verdict.layers.denylist.verdict).toBe('undecided');+ expect(verdict.layers.denylist.soft[0].rule).toBe('weapon_likeness');+ });++ it('refuses the same words at life size', async () => {+ const verdict = await quote('a realistic pistol', LIFE_SIZE);+ expect(verdict.verdict).toBe('refuse');+ expect(verdict.category).toBe('weapon_likeness');+ expect(verdict.message).toContain(`${LIFE_SIZE.bbox_mm.x} mm`);+ expect(verdict.allowed).toContain(`${MINIATURE_MAX_MM} mm`);+ });++ it('reports the scale signal it used', () => {+ expect(geometrySignal(MINI)).toMatchObject({ longest_mm: 65, miniature: true });+ expect(geometrySignal(LIFE_SIZE)).toMatchObject({ longest_mm: 210, miniature: false });+ expect(geometrySignal(null).miniature).toBeNull();+ });+});++describe('upstream generation categories', () => {+ it('refuses adult content in the fabrication voice, not the studio voice', async () => {+ const verdict = await quote('a nude figure, anatomically explicit');+ expect(verdict.verdict).toBe('refuse');+ expect(verdict.category).toBe('generation_sexual');+ expect(verdict.layer).toBe('upstream');+ expect(verdict.message).toContain('three.ws does not manufacture');+ expect(verdict.message).not.toContain('3D Studio');+ });++ it('does not defer weapons to the generation word list, which has no scale', async () => {+ // The generation classifier refuses the bare word "pistol". If the gate+ // deferred to it, every tabletop miniature carrying one would be refused.+ const verdict = await quote('a knight holding a pistol, tabletop miniature', MINI);+ expect(verdict.layers.upstream.verdict).toBe('allow');+ expect(verdict.verdict).toBe('allow');+ });+});++describe('the two run points', () => {+ it('quote stage never calls the model, so a price is never gated on a provider', async () => {+ const verdict = await quote('an ornate teapot with a bamboo handle');+ expect(llmMock).not.toHaveBeenCalled();+ expect(verdict.stage).toBe('quote');+ expect(verdict.layers.llm.verdict).toBe('skipped');+ expect(verdict.version).toBe(GATE_VERSION);+ });++ it('screening stage runs the model and records provider and model on the order', async () => {+ llmMock.mockResolvedValue({+ text: '{"verdict":"allow","category":null,"reason":"an ordinary household object"}',+ provider: 'vertex',+ model: 'gemini-flash-lite',+ });+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: 'an ornate teapot with a bamboo handle',+ analysis: MINI,+ });+ expect(llmMock).toHaveBeenCalledTimes(1);+ expect(verdict.verdict).toBe('allow');+ expect(verdict.layers.llm).toMatchObject({ verdict: 'allow', provider: 'vertex', model: 'gemini-flash-lite' });+ });++ it('the model can add a refusal the denylist did not make', async () => {+ llmMock.mockResolvedValue({+ text: 'Here is my verdict:\n```json\n{"verdict":"refuse","category":"firearm_components","reason":"a receiver by another name"}\n```',+ provider: 'ovh',+ model: 'llama-3.3-70b',+ });+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: 'the part that holds the fire control group, at full size',+ analysis: LIFE_SIZE,+ });+ expect(verdict.verdict).toBe('refuse');+ expect(verdict.layer).toBe('llm');+ // A category the denylist knows is rendered with the rule's own copy.+ expect(verdict.category).toBe('firearm_components');+ expect(verdict.message).toBe(ruleById('firearm_components').message);+ expect(verdict.reason).toContain('receiver');+ });++ it('the model can never lift a denylist refusal', async () => {+ llmMock.mockResolvedValue({ text: '{"verdict":"allow","category":null,"reason":"looks fine to me"}', provider: 'ovh', model: 'x' });+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: 'an AR-15 lower receiver',+ analysis: MINI,+ });+ expect(verdict.verdict).toBe('refuse');+ expect(verdict.category).toBe('firearm_components');+ // The model was never asked: the denylist short-circuits before it.+ expect(llmMock).not.toHaveBeenCalled();+ expect(verdict.layers.llm.verdict).toBe('skipped');+ });++ it('an unknown category from the model still stores a groupable slug', async () => {+ llmMock.mockResolvedValue({+ text: '{"verdict":"refuse","category":"a realistic firearm likeness printed at or near life size","reason":"life sized"}',+ provider: 'ovh',+ model: 'x',+ });+ const verdict = await runFabricationGate({ stage: 'screening', lineageText: 'a carry piece', analysis: LIFE_SIZE });+ expect(verdict.category).toBe('fabrication_policy');+ expect(verdict.reason).toBe('life sized');+ });+});++describe('when the screening model is unreachable', () => {+ beforeEach(() => {+ llmMock.mockRejectedValue(new Error('chain exhausted'));+ });++ it('holds an ambiguous order for a human instead of guessing', async () => {+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: 'a knight holding a pistol, tabletop miniature',+ analysis: MINI,+ });+ expect(verdict.verdict).toBe('review');+ expect(verdict.message).toContain('human review');+ expect(verdict.layers.llm.verdict).toBe('review');+ });++ it('does not hold an order nothing was ambiguous about', async () => {+ // A provider outage must not page an operator for every teapot; that order+ // already cleared the same deterministic bar its quote cleared.+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: 'an ornate teapot with a bamboo handle',+ analysis: MINI,+ });+ expect(verdict.verdict).toBe('allow');+ expect(verdict.layers.llm.reason).toContain('unavailable');+ });++ it('treats an unreadable verdict the same as an unreachable one', async () => {+ llmMock.mockReset();+ llmMock.mockResolvedValue({ text: 'I think it is probably fine?', provider: 'ovh', model: 'x' });+ const verdict = await runFabricationGate({+ stage: 'screening',+ lineageText: 'a knight holding a pistol, tabletop miniature',+ analysis: MINI,+ });+ expect(verdict.verdict).toBe('review');+ expect(verdict.layers.llm.reason).toContain('unreadable');+ });+});++describe('the subject the gate reads', () => {+ it('concatenates buyer note, model title and the whole prompt lineage', () => {+ const subject = gateSubject({+ buyerNote: 'make it functional please',+ modelTitle: 'Desk toy',+ lineageText: 'a small brass gear\nmake it spin',+ });+ expect(subject).toBe('make it functional please\nDesk toy\na small brass gear\nmake it spin');+ });++ it('catches an intent laundered through a refine instruction', async () => {+ // The root prompt is innocuous; the refinement is not. Reading only the+ // leaf prompt would pass this.+ const verdict = await runFabricationGate({+ stage: 'quote',+ lineageText: 'a metal tube ornament',+ buyerNote: 'add a monocore baffle so it works as a suppressor',+ analysis: MINI,+ });+ expect(verdict.verdict).toBe('refuse');+ expect(verdict.category).toBe('suppressors');+ });++ it('is safe on empty input', () => {+ const result = screenDeterministic({ subject: '', analysis: null });+ expect(result.decision.verdict).toBe('allow');+ });+});++describe('operator notification', () => {+ it('announces a refusal on the ops channel', async () => {+ await notifyGateOutcome({+ orderId: 'order-1',+ stage: 'screening',+ verdict: { verdict: 'refuse', label: 'firearm components', layer: 'denylist', matched: 'lower receiver' },+ });+ expect(notifyMock).toHaveBeenCalledTimes(1);+ const call = notifyMock.mock.calls[0][0];+ expect(call.title).toContain('refused');+ expect(call.orderId).toBe('order-1');+ expect(call.lines.join('\n')).toContain('firearm components');+ // A refusal is a record, not a page; only a held order raises an alert.+ expect(call.alert).toBe(false);+ });++ it('raises an alert for a held order, which needs a human to unblock it', async () => {+ await notifyGateOutcome({ orderId: 'order-2', stage: 'screening', verdict: { verdict: 'review', label: 'awaiting operator review' } });+ expect(notifyMock.mock.calls[0][0].alert).toBe(true);+ });++ it('stays silent when nothing needs a human', async () => {+ await notifyGateOutcome({ orderId: 'order-3', stage: 'quote', verdict: { verdict: 'allow' } });+ expect(notifyMock).not.toHaveBeenCalled();+ });+});diff --git a/vercel.json b/vercel.jsonindex bdcc80f76..708d7ebdc 100644--- a/vercel.json+++ b/vercel.json@@ -1764,6 +1764,10 @@"src": "/likeness-bench/?","dest": "/likeness-bench.html"},+ {+ "src": "/payment-outcomes/?",+ "dest": "/payment-outcomes.html"+ },{"src": "/examples/?","dest": "/examples.html"@@ -5384,6 +5388,10 @@"src": "/legal/risk/?","dest": "/legal/risk.html"},+ {+ "src": "/legal/nvidia-ngc-eula/?",+ "dest": "/legal/nvidia-ngc-eula.html"+ },{"src": "/content-policy/?","dest": "/legal/content-policy.html"@@ -6321,6 +6329,10 @@"path": "/api/cron/companion-poll","schedule": "*/2 * * * *"},+ {+ "path": "/api/cron/print-orders-sync",+ "schedule": "17 * * * *"+ },{"path": "/api/cron/feedback-triage","schedule": "*/5 * * * *"diff --git a/vite.config.js b/vite.config.jsindex ac257e72d..c2d2b03b8 100644--- a/vite.config.js+++ b/vite.config.js@@ -540,6 +540,7 @@ const appConfig = {'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),i18n: resolve(__dirname, 'src/i18n.js'),drops: resolve(__dirname, 'pages/drops.html'),+ 'materialize-ops': resolve(__dirname, 'pages/materialize-ops.html'),'drop-collection': resolve(__dirname, 'pages/drop-collection.html'),spotlight: resolve(__dirname, 'pages/spotlight.html'),'spotlight-entry': resolve(__dirname, 'pages/spotlight-entry.html'),@@ -727,6 +728,7 @@ const appConfig = {labs: resolve(__dirname, 'pages/labs.html'),'quality-bench': resolve(__dirname, 'pages/quality-bench.html'),'likeness-bench': resolve(__dirname, 'pages/likeness-bench.html'),+ 'payment-outcomes': resolve(__dirname, 'pages/payment-outcomes.html'),search: resolve(__dirname, 'pages/search.html'),rankings: resolve(__dirname, 'pages/rankings.html'),'daily-match': resolve(__dirname, 'pages/daily-match.html'),@@ -1781,6 +1783,8 @@ const appConfig = {'/quality-bench/': resolve(root, 'pages/quality-bench.html'),'/likeness-bench': resolve(root, 'pages/likeness-bench.html'),'/likeness-bench/': resolve(root, 'pages/likeness-bench.html'),+ '/payment-outcomes': resolve(root, 'pages/payment-outcomes.html'),+ '/payment-outcomes/': resolve(root, 'pages/payment-outcomes.html'),'/inspect': resolve(root, 'pages/inspect.html'),'/inspect/': resolve(root, 'pages/inspect.html'),'/render-lab': resolve(root, 'pages/render-lab.html'),