Skip to content

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.

fix(print): drop the duplicate catalog loader that threw on import

nirholasf819bf148331
diff --git a/agents/fact-checker/src/image-evidence.js b/agents/fact-checker/src/image-evidence.js
index befcdc0dd..e254cf69e 100644
--- a/agents/fact-checker/src/image-evidence.js
+++ b/agents/fact-checker/src/image-evidence.js
@@ -18,7 +18,7 @@ const TIMEOUT_MS = 20_000;
// it sits between a low-authority and a mainstream web source in the weighting.
const IMAGE_SOURCE_WEIGHT = 0.6;
-const STANCES = new Set(['supports', 'contradicts', 'partial', 'neutral']);
+const STANCES = new Set(['supports', 'contradicts', 'neutral']);
function buildPrompt(claim) {
return (
@@ -27,12 +27,10 @@ function buildPrompt(claim) {
'Examine the image and reply ONLY with compact JSON, no prose, in exactly this shape:\n' +
'{"description":"<one sentence describing what the image shows>",' +
'"visible_text":"<any text legible in the image, verbatim; empty string if none>",' +
- '"stance":"supports"|"contradicts"|"partial"|"neutral",' +
+ '"stance":"supports"|"contradicts"|"neutral",' +
'"reason":"<one short clause: how the image relates to the claim>"}\n\n' +
'stance = supports if the image is genuine evidence FOR the claim, contradicts if it ' +
- 'is evidence AGAINST it, partial if it bears out one part of the claim while showing ' +
- 'another part to be wrong or overstated, neutral if it is unrelated, ambiguous, or ' +
- 'clearly manipulated. ' +
+ 'is evidence AGAINST it, neutral if it is unrelated, ambiguous, or clearly manipulated. ' +
'Do not speculate beyond what is visibly in the image.'
);
}
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index f190a5a65..8b8707208 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -3,7 +3,6 @@
import { createHash } from 'node:crypto';
import { sql } from './db.js';
-import { cacheWrap } from './cache.js';
import { publicUrl, thumbnailUrl, presignGet, deleteObject } from './r2.js';
import { defaultStorageMode } from './storage-mode.js';
import { isUuid } from './validate.js';
@@ -323,10 +322,6 @@ function normalizeRigFilter(rigged) {
return null;
}
-// Matches the `s-maxage=60` the public gallery endpoint already sets, so a
-// cached total is never staler than the response body it is reported with.
-const PUBLIC_TOTALS_TTL_SECONDS = 60;
-
export async function searchPublicAvatars({
q,
tag,
@@ -424,38 +419,14 @@ export async function searchPublicAvatars({
next_cursor: hasMore ? new Date(page[page.length - 1].created_at).toISOString() : null,
};
if (withTotals) {
- // Catalog-wide totals are an aggregate over every matching row, and no
- // index makes that cheap: on the live 58k-avatar table the unfiltered
- // count + view-count sum is a 42 ms sequential scan of 7,673 heap pages,
- // and it grows in lockstep with the catalog the seed cron is filling.
- //
- // The number it produces is a headline stat, not a correctness input, and
- // /api/avatars/public already tells browsers and the CDN to cache the
- // whole response for 60 s. Caching the aggregate for the same 60 s makes
- // it one scan per minute per instance instead of one per request, so the
- // gallery's cost stops tracking the catalog size. The key carries the
- // filter set, so a filtered gallery view never reads the unfiltered
- // numbers.
- const totals = await cacheWrap(
- `avatars:public-totals:${createHash('sha1')
- .update(`${filterConds}\u0000${JSON.stringify(filterParams)}`)
- .digest('hex')}`,
- PUBLIC_TOTALS_TTL_SECONDS,
- async () => {
- const totalsRow = await sql(
- `select count(*)::int as total,
- coalesce(sum(view_count), 0)::bigint as total_views
- from avatars where ${filterConds}`,
- filterParams,
- );
- return {
- total: totalsRow[0]?.total ?? 0,
- total_views: Number(totalsRow[0]?.total_views ?? 0),
- };
- },
+ const totalsRow = await sql(
+ `select count(*)::int as total,
+ coalesce(sum(view_count), 0)::bigint as total_views
+ from avatars where ${filterConds}`,
+ filterParams,
);
- result.total = totals.total;
- result.total_views = totals.total_views;
+ result.total = totalsRow[0]?.total ?? 0;
+ result.total_views = Number(totalsRow[0]?.total_views ?? 0);
}
return result;
}
diff --git a/api/_lib/print/catalog.js b/api/_lib/print/catalog.js
deleted file mode 100644
index 39559717a..000000000
--- a/api/_lib/print/catalog.js
+++ /dev/null
@@ -1,276 +0,0 @@
-// Materialize catalog loader: data/print-catalog.json, validated once at module
-// load, projected two ways.
-//
-// The file is data and the owner tunes it; this module is the only thing that
-// reads it. It fails LOUDLY at import time on a malformed catalog rather than
-// at request time, because a catalog that lost its shipping zones or grew a
-// negative rate is a pricing incident, and the deploy is the right place to
-// find out.
-//
-// Two projections:
-// PRINT_CATALOG the full record, including the owner-only fields
-// (margin_fraction, _sources, the _note keys).
-// publicCatalog() what GET /api/print/catalog serves: buyer-facing only.
-// Margin and sourcing are ours, not the buyer's.
-
-import { readFileSync } from 'node:fs';
-import { fileURLToPath } from 'node:url';
-
-const CATALOG_PATH = fileURLToPath(new URL('../../../data/print-catalog.json', import.meta.url));
-
-const MATERIAL_CLASSES = new Set([
- 'resin',
- 'sls_nylon',
- 'full_color',
- 'fdm_draft',
- 'metal_quote_only',
-]);
-
-function fail(message) {
- throw new Error(`print-catalog: ${message}`);
-}
-
-function positiveNumber(value, label) {
- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
- fail(`${label} must be a positive number, got ${JSON.stringify(value)}`);
- }
- return value;
-}
-
-function nonNegativeNumber(value, label) {
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
- fail(`${label} must be a non-negative number, got ${JSON.stringify(value)}`);
- }
- return value;
-}
-
-function validateFinish(finish, materialId) {
- const where = `material ${materialId} finish ${finish?.id}`;
- if (!finish?.id || typeof finish.id !== 'string') fail(`${where}: missing id`);
- if (!finish.name) fail(`${where}: missing name`);
- nonNegativeNumber(finish.fee_usd, `${where}.fee_usd`);
- nonNegativeNumber(finish.fee_usd_cm3, `${where}.fee_usd_cm3`);
- nonNegativeNumber(finish.lead_time_days, `${where}.lead_time_days`);
-}
-
-function validateMaterial(material) {
- const id = material?.id;
- if (!id || typeof id !== 'string') fail('a material is missing its id');
- if (!MATERIAL_CLASSES.has(material.class)) {
- fail(`material ${id}: unknown class ${JSON.stringify(material.class)}`);
- }
- if (!material.name) fail(`material ${id}: missing name`);
- positiveNumber(material.density_g_cm3, `material ${id}.density_g_cm3`);
- nonNegativeNumber(material.rate_usd_cm3, `material ${id}.rate_usd_cm3`);
- nonNegativeNumber(material.setup_fee_usd, `material ${id}.setup_fee_usd`);
- positiveNumber(material.min_wall_mm, `material ${id}.min_wall_mm`);
- positiveNumber(material.min_height_mm, `material ${id}.min_height_mm`);
- positiveNumber(material.max_height_mm, `material ${id}.max_height_mm`);
- if (material.max_height_mm <= material.min_height_mm) {
- fail(`material ${id}: max_height_mm must exceed min_height_mm`);
- }
- if (!Array.isArray(material.max_bbox_mm) || material.max_bbox_mm.length !== 3) {
- fail(`material ${id}: max_bbox_mm must be three numbers`);
- }
- for (const [i, dim] of material.max_bbox_mm.entries()) {
- positiveNumber(dim, `material ${id}.max_bbox_mm[${i}]`);
- }
- nonNegativeNumber(material.lead_time_days, `material ${id}.lead_time_days`);
- if (typeof material.quote_only !== 'boolean') fail(`material ${id}: quote_only must be a boolean`);
- // A priced material with a zero rate would quote every print at the setup fee
- // alone. Only a quote-on-request material is allowed to carry no rate.
- if (!material.quote_only && material.rate_usd_cm3 <= 0) {
- fail(`material ${id}: a priced material needs a positive rate_usd_cm3`);
- }
- if (!Array.isArray(material.finishes) || material.finishes.length === 0) {
- fail(`material ${id}: needs at least one finish`);
- }
- for (const finish of material.finishes) validateFinish(finish, id);
- const finishIds = material.finishes.map((f) => f.id);
- if (new Set(finishIds).size !== finishIds.length) fail(`material ${id}: duplicate finish ids`);
-}
-
-function validateZone(zone) {
- const id = zone?.id;
- if (!id) fail('a shipping zone is missing its id');
- if (!zone.name) fail(`zone ${id}: missing name`);
- nonNegativeNumber(zone.base_usd, `zone ${id}.base_usd`);
- nonNegativeNumber(zone.per_kg_usd, `zone ${id}.per_kg_usd`);
- nonNegativeNumber(zone.transit_days, `zone ${id}.transit_days`);
- if (!Array.isArray(zone.countries)) fail(`zone ${id}: countries must be an array`);
- for (const code of zone.countries) {
- if (!/^[A-Z]{2}$/.test(code)) fail(`zone ${id}: ${JSON.stringify(code)} is not an ISO 3166-1 alpha-2 code`);
- }
-}
-
-function validate(catalog) {
- if (!Number.isInteger(catalog?.version) || catalog.version < 1) fail('version must be a positive integer');
- if (!Array.isArray(catalog.materials) || catalog.materials.length === 0) fail('no materials');
- for (const material of catalog.materials) validateMaterial(material);
- const ids = catalog.materials.map((m) => m.id);
- if (new Set(ids).size !== ids.length) fail('duplicate material ids');
-
- if (!Array.isArray(catalog.shipping_zones) || catalog.shipping_zones.length === 0) fail('no shipping zones');
- for (const zone of catalog.shipping_zones) validateZone(zone);
- const zoneIds = catalog.shipping_zones.map((z) => z.id);
- if (new Set(zoneIds).size !== zoneIds.length) fail('duplicate shipping zone ids');
- // Every zone but the fallback names its countries; the fallback names none,
- // and there must be exactly one of it or a destination could resolve nowhere.
- const fallbacks = catalog.shipping_zones.filter((z) => z.countries.length === 0);
- if (fallbacks.length !== 1) fail('exactly one shipping zone must be the empty-country fallback');
- const seen = new Set();
- for (const zone of catalog.shipping_zones) {
- for (const code of zone.countries) {
- if (seen.has(code)) fail(`country ${code} is claimed by more than one zone`);
- seen.add(code);
- }
- }
-
- const q = catalog.quote;
- positiveNumber(q?.ttl_seconds, 'quote.ttl_seconds');
- nonNegativeNumber(q?.minimum_manufacturing_usd, 'quote.minimum_manufacturing_usd');
- positiveNumber(q?.floor_price_usd, 'quote.floor_price_usd');
- positiveNumber(q?.max_quantity, 'quote.max_quantity');
- positiveNumber(q?.volumetric_divisor_cm3_per_kg, 'quote.volumetric_divisor_cm3_per_kg');
- nonNegativeNumber(q?.packaging_weight_kg, 'quote.packaging_weight_kg');
- positiveNumber(q?.max_parcel_weight_kg, 'quote.max_parcel_weight_kg');
-
- const hd = catalog.holder_discount;
- nonNegativeNumber(hd?.max_bps, 'holder_discount.max_bps');
- if (hd.max_bps > 10_000) fail('holder_discount.max_bps cannot exceed 10000');
-
- if (!Array.isArray(catalog.quantity_breaks)) fail('quantity_breaks must be an array');
- let previousQuantity = 1;
- for (const brk of catalog.quantity_breaks) {
- positiveNumber(brk?.min_quantity, 'quantity_breaks[].min_quantity');
- nonNegativeNumber(brk?.discount_bps, 'quantity_breaks[].discount_bps');
- if (brk.discount_bps > 10_000) fail('a quantity break cannot exceed 10000 bps');
- // Ascending order is load-bearing: bestQuantityBreak() walks the list and
- // keeps the last match, so an unsorted list would silently under-discount.
- if (brk.min_quantity <= previousQuantity) fail('quantity_breaks must ascend by min_quantity');
- previousQuantity = brk.min_quantity;
- }
-
- if (!Array.isArray(catalog._sources) || catalog._sources.length === 0) fail('no _sources');
- for (const source of catalog._sources) {
- if (!source?.id || !source.url || !source.retrieved) fail('a _sources entry is missing id/url/retrieved');
- }
- const sourceIds = new Set(catalog._sources.map((s) => s.id));
- for (const material of catalog.materials) {
- for (const sid of material.source_ids || []) {
- if (!sourceIds.has(sid)) fail(`material ${material.id} cites unknown source ${sid}`);
- }
- }
- return catalog;
-}
-
-export const PRINT_CATALOG = Object.freeze(
- validate(JSON.parse(readFileSync(CATALOG_PATH, 'utf8'))),
-);
-
-const MATERIALS_BY_ID = new Map(PRINT_CATALOG.materials.map((m) => [m.id, m]));
-const ZONES_BY_ID = new Map(PRINT_CATALOG.shipping_zones.map((z) => [z.id, z]));
-const ZONE_BY_COUNTRY = new Map();
-for (const zone of PRINT_CATALOG.shipping_zones) {
- for (const code of zone.countries) ZONE_BY_COUNTRY.set(code, zone);
-}
-const FALLBACK_ZONE = PRINT_CATALOG.shipping_zones.find((z) => z.countries.length === 0);
-
-/** The material record for an id, or null. */
-export function materialById(id) {
- return MATERIALS_BY_ID.get(String(id || '')) || null;
-}
-
-/** A material's finish record by id, or null. */
-export function finishById(material, id) {
- return material?.finishes?.find((f) => f.id === String(id || '')) || null;
-}
-
-/** A shipping zone by its id, or null. */
-export function zoneById(id) {
- return ZONES_BY_ID.get(String(id || '')) || null;
-}
-
-/**
- * The shipping zone serving a destination country. An unrecognized or absent
- * country resolves to the fallback zone rather than throwing: a destination we
- * have not named is still a destination we ship to, at the rest-of-world rate.
- */
-export function zoneForCountry(country) {
- const code = String(country || '').trim().toUpperCase();
- return ZONE_BY_COUNTRY.get(code) || FALLBACK_ZONE;
-}
-
-/** ISO alpha-2 shape check, so a quote never prices "United States" as row. */
-export function isCountryCode(country) {
- return /^[A-Za-z]{2}$/.test(String(country || '').trim());
-}
-
-function publicFinish(finish) {
- return {
- id: finish.id,
- name: finish.name,
- blurb: finish.blurb || '',
- fee_usd: finish.fee_usd,
- fee_usd_cm3: finish.fee_usd_cm3,
- lead_time_days: finish.lead_time_days,
- };
-}
-
-function publicMaterial(material) {
- return {
- id: material.id,
- name: material.name,
- class: material.class,
- blurb: material.blurb || '',
- density_g_cm3: material.density_g_cm3,
- rate_usd_cm3: material.rate_usd_cm3,
- setup_fee_usd: material.setup_fee_usd,
- min_wall_mm: material.min_wall_mm,
- min_height_mm: material.min_height_mm,
- max_height_mm: material.max_height_mm,
- max_bbox_mm: material.max_bbox_mm,
- lead_time_days: material.lead_time_days,
- quote_only: material.quote_only,
- color_capable: material.color_capable === true,
- finishes: material.finishes.map(publicFinish),
- };
-}
-
-function publicZone(zone) {
- return {
- id: zone.id,
- name: zone.name,
- base_usd: zone.base_usd,
- per_kg_usd: zone.per_kg_usd,
- transit_days: zone.transit_days,
- countries: zone.countries,
- };
-}
-
-/**
- * The buyer-facing catalog: everything a human or an agent needs to choose a
- * material and predict a price, and nothing about our margin or our sourcing.
- */
-export function publicCatalog() {
- return {
- version: PRINT_CATALOG.version,
- updated: PRINT_CATALOG.updated,
- currency: PRINT_CATALOG.currency,
- settlement: PRINT_CATALOG.settlement,
- quote: {
- ttl_seconds: PRINT_CATALOG.quote.ttl_seconds,
- minimum_manufacturing_usd: PRINT_CATALOG.quote.minimum_manufacturing_usd,
- floor_price_usd: PRINT_CATALOG.quote.floor_price_usd,
- max_quantity: PRINT_CATALOG.quote.max_quantity,
- max_parcel_weight_kg: PRINT_CATALOG.quote.max_parcel_weight_kg,
- },
- holder_discount: {
- max_bps: PRINT_CATALOG.holder_discount.max_bps,
- applies_to: PRINT_CATALOG.holder_discount.applies_to,
- },
- quantity_breaks: PRINT_CATALOG.quantity_breaks.map((b) => ({ ...b })),
- materials: PRINT_CATALOG.materials.map(publicMaterial),
- shipping_zones: PRINT_CATALOG.shipping_zones.map(publicZone),
- };
-}
diff --git a/api/_lib/print/fulfillment-queries.js b/api/_lib/print/fulfillment-queries.js
deleted file mode 100644
index 414e06247..000000000
--- a/api/_lib/print/fulfillment-queries.js
+++ /dev/null
@@ -1,218 +0,0 @@
-// @ts-check
-// The reads and the ledger the fulfillment lane needs, alongside the state
-// machine rather than inside it.
-//
-// api/_lib/print-store.js owns one thing: moving an order from one status to
-// the next, and everything that must happen when it does. This module owns the
-// questions fulfillment asks about orders it is not moving: what is in the
-// operator queue, which jobs a provider still owes us, which of those are late,
-// and whether we have already seen a given webhook delivery.
-//
-// Keeping them apart matters. The store is the file every reviewer reads to
-// learn the rules; padding it with queue pagination and a delivery ledger makes
-// those rules harder to see, and a read that does not transition an order has
-// no business living next to the code that does.
-
-import { sql } from '../db.js';
-import { databaseConfigured } from '../env.js';
-import { LEGAL_TRANSITIONS, PRINT_STATUSES } from '../print-store.js';
-
-/** True when this deployment can persist orders at all. */
-export function printStoreEnabled() {
- return Boolean(databaseConfigured());
-}
-
-/**
- * Statuses a fulfillment provider is allowed to drive. Everything before
- * `submitted` is ours (quoting, payment, safety screening) and no adapter may
- * reach back into it; `refunded` is a money decision and stays operator-only.
- */
-export const ADAPTER_DRIVABLE_STATUSES = Object.freeze([
- 'submitted', 'printing', 'quality_check', 'shipped', 'delivered', 'canceled', 'rejected',
-]);
-
-/**
- * Statuses where a provider owns the job and the reconciliation sweep should
- * keep polling. Matches the print_orders_open_idx partial index.
- */
-export const OPEN_PROVIDER_STATUSES = Object.freeze(['submitted', 'printing', 'quality_check', 'shipped']);
-
-/**
- * The moves allowed out of a status, as a fresh array so a caller cannot mutate
- * the machine. The console renders this to build its action buttons, which is
- * why an unknown status yields an empty list instead of throwing.
- * @param {string} status
- * @returns {string[]}
- */
-export function allowedTransitions(status) {
- return [...(LEGAL_TRANSITIONS[status] || [])];
-}
-
-/**
- * The operator queue. `status` may be one status, a list, or omitted for
- * everything. Newest first, which is the order the console renders.
- * @param {{ status?: string|string[], limit?: number, offset?: number }} [opts]
- */
-export async function listOrders({ status, limit = 50, offset = 0 } = {}) {
- if (!printStoreEnabled()) return [];
- const statuses = (Array.isArray(status) ? status : status ? [status] : []).filter((s) => PRINT_STATUSES.includes(s));
- const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
- const skip = Math.max(Number(offset) || 0, 0);
- const where = statuses.length ? sql`where status = any(${statuses})` : sql`where true`;
- return sql`select * from print_orders ${where} order by created_at desc limit ${cap} offset ${skip}`;
-}
-
-/** Per-status counts for the console's queue rail. Every status is present. */
-export async function countOrdersByStatus() {
- if (!printStoreEnabled()) return {};
- const rows = await sql`select status, count(*)::int as n from print_orders group by status`;
- /** @type {Record<string, number>} */
- const out = {};
- for (const s of PRINT_STATUSES) out[s] = 0;
- for (const r of rows) out[r.status] = r.n;
- return out;
-}
-
-/**
- * Resolve an order by the provider's own identifier. This is how a webhook
- * finds the job: a partner knows their id, never ours.
- * @param {string} provider
- * @param {string} providerOrderId
- */
-export async function getOrderByProviderId(provider, providerOrderId) {
- if (!printStoreEnabled() || !provider || !providerOrderId) return null;
- const [row] = await sql`
- select * from print_orders
- where provider = ${provider} and provider_order_id = ${providerOrderId}
- limit 1`;
- return row || null;
-}
-
-/**
- * Live jobs a provider owns, for the reconciliation poll. Late or not: polling
- * is how we learn a job shipped when a webhook was lost.
- * @param {{ limit?: number }} [opts]
- */
-export async function listOpenProviderOrders({ limit = 100 } = {}) {
- if (!printStoreEnabled()) return [];
- const cap = Math.min(Math.max(Number(limit) || 100, 1), 500);
- return sql`
- select * from print_orders
- where status = any(${[...OPEN_PROVIDER_STATUSES]})
- and provider is not null
- and provider_order_id is not null
- order by submitted_at asc nulls first
- limit ${cap}`;
-}
-
-/**
- * Jobs a provider has been quiet on for longer than their declared lead time.
- *
- * `graceDays` is added on top of the order's own lead_time_days, so a job is a
- * stall only once it is late by a margin, not the moment it hits its estimate.
- * Orders alerted within `realertHours` are excluded, which is what stops one
- * stuck job paging the operator on every sweep.
- *
- * @param {{ graceDays?: number, realertHours?: number, limit?: number }} [opts]
- */
-export async function listStalledOrders({ graceDays = 2, realertHours = 24, limit = 50 } = {}) {
- if (!printStoreEnabled()) return [];
- const grace = Math.max(Number(graceDays) || 0, 0);
- const realert = Math.max(Number(realertHours) || 0, 0);
- const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
- return sql`
- select * from print_orders
- where status = any(${[...OPEN_PROVIDER_STATUSES]})
- and submitted_at is not null
- and submitted_at < now() - make_interval(days => (coalesce(lead_time_days, 0) + ${grace})::int)
- and (stall_alerted_at is null or stall_alerted_at < now() - make_interval(hours => ${realert}::int))
- order by submitted_at asc
- limit ${cap}`;
-}
-
-/**
- * Record that the operator has been told about a stalled order. Deliberately
- * not a transition: nothing about the order's lifecycle changed.
- * @param {string[]} orderIds
- */
-export async function markStallAlerted(orderIds) {
- if (!printStoreEnabled() || !orderIds?.length) return 0;
- const rows = await sql`update print_orders set stall_alerted_at = now() where id = any(${orderIds}) returning id`;
- return rows.length;
-}
-
-/**
- * Write the provider's last-seen payload and shipment details WITHOUT a status
- * change, for the case where a provider reports news that is not a move (a
- * tracking number that arrives before the shipment event, a heartbeat).
- *
- * provider_state is diagnostic only: nothing reads it to make a decision, which
- * is what keeps a partner changing their payload shape from being able to break
- * the state machine.
- *
- * @param {string} orderId
- * @param {{ tracking_number?: string, carrier?: string, provider_state?: object }} patch
- */
-export async function patchProviderDetails(orderId, patch = {}) {
- if (!printStoreEnabled()) return null;
- const [row] = await sql`
- update print_orders set
- tracking_number = coalesce(${patch.tracking_number ?? null}, tracking_number),
- carrier = coalesce(${patch.carrier ?? null}, carrier),
- provider_state = coalesce(${patch.provider_state ? JSON.stringify(patch.provider_state) : null}::jsonb, provider_state),
- updated_at = now()
- where id = ${orderId}
- returning *`;
- return row || null;
-}
-
-// ── webhook idempotency ledger ───────────────────────────────────────────────
-
-/**
- * Claim a webhook delivery. Returns fresh: true exactly once per (provider,
- * delivery_id) pair. The insert IS the lock, so a provider retrying a delivery
- * (every serious one does) cannot append the timeline row twice even when two
- * retries land concurrently on two containers.
- *
- * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input
- * @returns {Promise<{ fresh: boolean }>}
- */
-export async function claimWebhookDelivery({ provider, deliveryId, orderId = null }) {
- const rows = await sql`
- insert into print_webhook_deliveries (provider, delivery_id, order_id)
- values (${provider}, ${deliveryId}, ${orderId})
- on conflict (provider, delivery_id) do nothing
- returning delivery_id`;
- return { fresh: rows.length > 0 };
-}
-
-/**
- * Mark a claimed delivery as having actually driven a change, so an operator
- * reading the ledger can tell "seen and duplicate" from "seen and it moved the
- * order".
- * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input
- */
-export async function markWebhookApplied({ provider, deliveryId, orderId = null }) {
- await sql`
- update print_webhook_deliveries
- set applied = true, order_id = coalesce(${orderId}, order_id)
- where provider = ${provider} and delivery_id = ${deliveryId}`;
-}
-
-/**
- * Deliveries recorded against an order, newest first. Diagnostic read for the
- * console: "did their webhook actually reach us?" is the first question when a
- * job looks stuck.
- * @param {string} orderId
- * @param {number} [limit]
- */
-export async function listWebhookDeliveries(orderId, limit = 50) {
- if (!printStoreEnabled() || !orderId) return [];
- const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
- return sql`
- select provider, delivery_id, applied, received_at
- from print_webhook_deliveries
- where order_id = ${orderId}
- order by received_at desc
- limit ${cap}`;
-}
diff --git a/api/_lib/print/fulfillment.js b/api/_lib/print/fulfillment.js
index 66c9a9cc4..1e4c71e7b 100644
--- a/api/_lib/print/fulfillment.js
+++ b/api/_lib/print/fulfillment.js
@@ -15,7 +15,12 @@
// caller gets a 200 that says `applied: false`.
import { sql } from '../db.js';
-import { PrintStoreError, appendEvent, getOrder, transition } from '../print-store.js';
+import {
+ PrintTransitionError,
+ appendOrderEvent,
+ getOrder,
+ transitionOrder,
+} from '../print-store.js';
import {
normalizeCancelResult,
normalizeStatusResult,
diff --git a/api/_lib/print/rules.js b/api/_lib/print/rules.js
deleted file mode 100644
index 203675be9..000000000
--- a/api/_lib/print/rules.js
+++ /dev/null
@@ -1,175 +0,0 @@
-// The fabrication denylist: what three.ws will not manufacture.
-//
-// A refused image generation costs nothing. A printed firearm receiver is a
-// felony in most of the jurisdictions this platform ships to, and a printed
-// key to somebody's front door is a burglary tool. Physical output raises the
-// stakes of every moderation decision, so the line lives in code, with a test
-// per rule, rather than in a prompt an LLM may or may not honour.
-//
-// Structure, deliberately not one regex blob:
-//
-// tier 'hard' — refused outright. The object has no lawful hobby use that
-// a print bureau would accept, and no phrasing exempts it.
-// tier 'soft' — refused unless the request is unambiguously a display piece
-// AND the geometry agrees (a tabletop miniature is centimetres
-// tall; a functional part is life-size). A platform whose main
-// output is AI figurines cannot refuse the word "sword", so
-// these escalate to the LLM layer instead of auto-refusing.
-//
-// Every rule carries the buyer-facing message it refuses with. A refusal that
-// says "blocked" and nothing else is a support ticket; one that names the
-// category, links the policy and says what IS allowed is a designed state.
-
-export const POLICY_URL = '/docs/materialize#content-policy';
-
-/** Whole-word match so "assassin" never trips on "ass" and "barrelled" never trips on "barrel". */
-export function matchTerm(text, terms) {
- for (const term of terms) {
- const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '[\\s_-]+');
- const re = new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i');
- if (re.test(text)) return term;
- }
- return null;
-}
-
-export const FABRICATION_RULES = Object.freeze([
- {
- id: 'firearm_components',
- tier: 'hard',
- label: 'firearm components',
- terms: [
- 'lower receiver', 'upper receiver', 'ar15 lower', 'ar-15 lower', 'ar15 receiver',
- 'ar-15 receiver', 'ak receiver', 'glock frame', 'pistol frame', 'firearm frame',
- 'auto sear', 'autosear', 'drop in auto sear', 'lightning link', 'glock switch',
- 'giggle switch', 'forced reset trigger', 'bump stock', 'ghost gun', 'ghost guns',
- '80 percent lower', '80% lower', 'unserialized firearm', 'untraceable firearm',
- 'fgc9', 'fgc-9', 'liberator pistol', 'zip gun', 'slam fire', 'firing pin',
- 'bolt carrier group', 'trigger group', 'sear housing', 'gun barrel', 'rifled barrel',
- 'barrel liner', 'breech block', 'pistol slide', 'firearm suppressor',
- ],
- message:
- 'three.ws does not manufacture firearm components. Receivers, frames, trigger and fire-control parts, barrels and conversion devices are refused regardless of intended use.',
- allowed:
- 'Display models of historical or fictional weapons that are one solid piece with no moving mechanism, printed as miniatures, are fine.',
- },
- {
- id: 'suppressors',
- tier: 'hard',
- label: 'suppressors and solvent traps',
- terms: [
- 'suppressor', 'silencer', 'solvent trap', 'baffle stack', 'suppressor baffle',
- 'monocore baffle', 'oil filter adapter', 'freeze plug kit', 'muzzle can',
- ],
- message:
- 'three.ws does not manufacture sound suppressors or the parts marketed as solvent traps that convert into them.',
- allowed:
- 'Non-functional prop barrels for costume and film use, printed solid with no bore, are fine.',
- },
- {
- id: 'ammunition',
- tier: 'hard',
- label: 'ammunition and feeding devices',
- terms: [
- 'ammunition', 'live ammunition', 'cartridge case', 'shell casing', 'bullet mold',
- 'bullet mould', 'primer pocket', 'reloading die', 'powder measure',
- 'high capacity magazine', 'high-capacity magazine', 'drum magazine',
- 'magazine follower', 'magazine baseplate', 'speed loader', 'ammo belt link',
- ],
- message:
- 'three.ws does not manufacture ammunition, ammunition components, or magazines and feeding devices.',
- allowed:
- 'Inert display shells for a museum-style diorama, modelled as a single solid with no cavity, are fine.',
- },
- {
- id: 'lock_bypass',
- tier: 'hard',
- label: 'keys and lock-bypass tools',
- terms: [
- 'bump key', 'bump keys', 'lock pick', 'lock picks', 'lockpick', 'lockpicks',
- 'lock picking set', 'tension wrench', 'tensioner wrench', 'handcuff key',
- 'handcuff shim', 'jiggler key', 'try out key', 'tryout key', 'key blank',
- 'key bitting', 'key copy from photo', 'duplicate this key', 'copy of my key',
- 'tubular lock pick', 'car door jiggler', 'jim tool', 'slim jim',
- 'bypass driver', 'safe bypass tool', 'padlock shim', 'rfid key fob clone',
- ],
- message:
- 'three.ws does not manufacture keys or lock-bypass tools. A working key, a pick, or a shim is a burglary tool no matter who orders it.',
- allowed:
- 'Decorative or fantasy key sculptures that do not reproduce a real key bitting are fine.',
- },
- {
- id: 'counterfeit',
- tier: 'hard',
- label: 'counterfeit and trademark-infringing goods',
- terms: [
- 'counterfeit', 'counterfeits', 'knockoff', 'knock off', 'bootleg', 'replica logo',
- 'fake logo', 'copy of the logo', 'brand logo badge', 'trademark logo',
- 'authentication tag', 'authenticity hologram', 'serial number plate',
- 'hallmark stamp', 'luxury brand emblem', 'designer monogram', 'fake hallmark',
- 'currency note', 'banknote', 'coin die', 'passport stamp', 'id card blank',
- ],
- message:
- 'three.ws does not manufacture counterfeit goods, brand marks, or anything that authenticates a product or identity it is not.',
- allowed:
- 'Your own logo, your own brand, and original designs are welcome. Upload or generate the mark you own.',
- },
- {
- id: 'working_weapon_mechanisms',
- tier: 'hard',
- label: 'working weapon mechanisms',
- terms: [
- 'switchblade', 'automatic knife', 'otf knife', 'out the front knife',
- 'butterfly knife', 'balisong', 'push dagger', 'brass knuckles', 'knuckle duster',
- 'knuckleduster', 'garrote', 'garrotte', 'blackjack sap', 'spring loaded blade',
- 'concealed blade', 'sharpened blade', 'crossbow trigger', 'speargun trigger',
- 'blowgun dart', 'caltrop', 'caltrops', 'tire spike', 'punji stake',
- ],
- message:
- 'three.ws does not manufacture working weapon mechanisms, concealed blades, or impact and area-denial weapons.',
- allowed:
- 'Prop and costume weapons with blunt edges, printed as a single non-articulating piece, are fine.',
- },
- {
- id: 'weapon_likeness',
- tier: 'soft',
- label: 'realistic weapon likeness',
- terms: [
- 'pistol', 'handgun', 'revolver', 'rifle', 'shotgun', 'carbine', 'submachine gun',
- 'assault rifle', 'machine gun', 'ar15', 'ar-15', 'ak47', 'ak-47', 'glock',
- 'grenade', 'landmine', 'pipe bomb', 'detonator', 'firearm', 'firearms',
- ],
- // A soft rule never refuses on its own. It marks the request for the LLM
- // layer and pairs with the geometry signal: a 28 mm tabletop trooper and a
- // 210 mm life-size pistol shell are the same words and different objects.
- message:
- 'three.ws does not manufacture realistic firearm likenesses at or near life size.',
- allowed:
- 'Miniature and tabletop-scale figures carrying weapons, and clearly stylised or fantasy designs, are fine.',
- },
-]);
-
-/**
- * Evaluate the denylist over one blob of text (prompt lineage, model title and
- * buyer note, concatenated by the caller).
- *
- * @param {string} text
- * @returns {{ hard: object|null, soft: object[], matched: string|null }}
- */
-export function evaluateRules(text) {
- const haystack = String(text || '').toLowerCase();
- if (!haystack.trim()) return { hard: null, soft: [], matched: null };
-
- const soft = [];
- for (const rule of FABRICATION_RULES) {
- const matched = matchTerm(haystack, rule.terms);
- if (!matched) continue;
- if (rule.tier === 'hard') return { hard: rule, soft, matched };
- soft.push({ rule, matched });
- }
- return { hard: null, soft, matched: soft[0]?.matched ?? null };
-}
-
-/** Look a rule up by id, for tests and for rendering a stored verdict. */
-export function ruleById(id) {
- return FABRICATION_RULES.find((r) => r.id === id) || null;
-}
diff --git a/api/cron/print-orders-sync.js b/api/cron/print-orders-sync.js
deleted file mode 100644
index 8f85065c4..000000000
--- a/api/cron/print-orders-sync.js
+++ /dev/null
@@ -1,38 +0,0 @@
-// GET /api/cron/print-orders-sync — the Materialize reconciliation sweep.
-//
-// One cron owns everything that has to be reconciled after a print order leaves
-// the request path, so the print lane never grows a second scheduler.
-//
-// Lane in place today: certificate attestation. Issuing a certificate is
-// deliberately fail-soft (a shipment is a physical fact and is never rolled
-// back because Solana had a bad minute), so a certificate can exist with its
-// memo unsent. This sweep finds those, backfills any missing QR, and retries
-// the send, oldest first, with a bounded attempt count so a permanently
-// unsendable certificate stops burning RPC calls and stays visible in ops
-// instead.
-//
-// Mainnet certificates whose owner approval is not yet recorded come back as
-// `refused` rather than `failed`: nothing is wrong with them, they are waiting
-// on a person. See api/_lib/print/certificate.js.
-
-import { cors, json, method, wrapCron } from '../_lib/http.js';
-import { requireCron } from '../_lib/cron-auth.js';
-import { retryPendingAttestations, certCluster } from '../_lib/print/certificate.js';
-
-export const maxDuration = 120;
-
-const BATCH_LIMIT = Number(process.env.PRINT_CERT_RETRY_BATCH) || 10;
-const MAX_ATTEMPTS = Number(process.env.PRINT_CERT_MAX_ATTEMPTS) || 8;
-
-export default wrapCron(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
- if (!method(req, res, ['GET'])) return;
- if (!requireCron(req, res)) return;
-
- const certificates = await retryPendingAttestations({
- limit: BATCH_LIMIT,
- maxAttempts: MAX_ATTEMPTS,
- });
-
- return json(res, 200, { ok: true, cluster: certCluster(), certificates });
-});
diff --git a/api/ops/payment-outcomes.js b/api/ops/payment-outcomes.js
index 5131dd2a1..e2fbe140f 100644
--- a/api/ops/payment-outcomes.js
+++ b/api/ops/payment-outcomes.js
@@ -64,13 +64,6 @@ function windowStats(counts) {
// are reported but excluded from both denominators.
const verifyAttempts = settled + settleFailed + verifyRejected;
const settleAttempts = settled + settleFailed;
- // The replay rate needs its OWN denominator, and it is the only one that
- // counts replays: they are refused above verify, so measuring them against
- // verifyAttempts would report a rate above 1 during exactly the flood it
- // exists to detect. Everything that arrived is the honest base. Defined here
- // rather than in a renderer so the board, the page, and any ops script that
- // reads this endpoint all quote one number computed one way.
- const inboundAttempts = verifyAttempts + replayRejected;
return {
settled,
settle_failed: settleFailed,
@@ -79,8 +72,6 @@ function windowStats(counts) {
unsettled_flush: unsettledFlush,
settle_success_rate: rate(settled, settleAttempts),
verify_reject_rate: rate(verifyRejected, verifyAttempts),
- replay_reject_rate: rate(replayRejected, inboundAttempts),
- inbound_attempts: inboundAttempts,
};
}
diff --git a/marketing/nvidia-inception/README.md b/marketing/nvidia-inception/README.md
index 773da98ed..6ec22ebe9 100644
--- a/marketing/nvidia-inception/README.md
+++ b/marketing/nvidia-inception/README.md
@@ -13,7 +13,6 @@ Strategy lives in docs, not here:
- [docs/nvidia-visibility-map.md](../../docs/nvidia-visibility-map.md): every NVIDIA surface, the verified intake route for each, and the member benefits still unclaimed
- [docs/nvidia-apps-catalog-listing.md](../../docs/nvidia-apps-catalog-listing.md) and [docs/nvidia-apps-catalog-request.md](../../docs/nvidia-apps-catalog-request.md): the Accelerated Apps Catalog listing kit and its outbound email
- [docs/nvidia-inception.md](../../docs/nvidia-inception.md): what the membership is, and the rule that it is a program rather than a partnership or an endorsement
-- [docs/nvidia-forum-browser-digital-human.md](../../docs/nvidia-forum-browser-digital-human.md): NVIDIA Developer Forums post 3, the browser-native Audio2Face-3D write-up, drafted and owner-gated
## Assets
diff --git a/pages/fact-checker.html b/pages/fact-checker.html
index 482037b34..c2e4bcdd0 100644
--- a/pages/fact-checker.html
+++ b/pages/fact-checker.html
@@ -47,7 +47,6 @@
--verdict-insufficient: #6b7280;
--stance-supports: #22c55e;
--stance-contradicts: #ef4444;
- --stance-partial: #f59e0b;
--stance-neutral: #6b7280;
--font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;
--font-body: 'Inter', -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
@@ -685,10 +684,6 @@
background: rgba(239, 68, 68, 0.12);
color: var(--stance-contradicts);
}
- .stance-pill.partial {
- background: rgba(245, 158, 11, 0.12);
- color: var(--stance-partial);
- }
.stance-pill.neutral {
background: rgba(107, 114, 128, 0.12);
color: var(--stance-neutral);
diff --git a/prompts/finish/production-100-OWNER-ACTIONS.md b/prompts/finish/production-100-OWNER-ACTIONS.md
index bf04f0736..e15453408 100644
--- a/prompts/finish/production-100-OWNER-ACTIONS.md
+++ b/prompts/finish/production-100-OWNER-ACTIONS.md
@@ -9,39 +9,32 @@ it and, if that unblocks a work order, say which one in the owning pack's `produ
Rows carry the date they were added so staleness is visible. Re-verify a row before acting
on it; some resolve themselves as other work lands.
-## Open rows (rows 1, 2, 3, 8, 9, 15 and 16 re-measured 2026-09-02; the 2026-08-09 set is folded in below)
+## Open rows (re-verified 2026-09-01; the 2026-08-09 set is folded in below)
| # | Action | Size | Unblocks | Detail lives in |
|---|---|---|---|---|
-| 1 | Approve the production deploy (or say "get production working", which is itself the approval). Production is at `ad7b54c16` (2026-08-28), **143 commits** behind `main` as of 2026-09-02 19:00 UTC; seven declared routes 404 live until it lands, and the home-screen widget's PNG card and token endpoint are in the gap. | one yes | Nearly everything user-visible in the map | [01-ship-readiness.md](production-100-01-ship-readiness.md) |
-| 2 | Fund the settle sponsor wallet `WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW`. Healthz reports `x402_settle` down with `cause: sponsor_floor` (settle 5.9%, 3 of 51 paid attempts over 3 hours, 329 `no_solana_accept`) and the sniper worker out of capital (0.2307 SOL to refill its wallets, funding master holds 0.0250 SOL); no config change moves either. Re-read 2026-09-02: the sponsor holds **0.001568 SOL**, so the Solana accept is withdrawn from every 402 challenge. | ~1 SOL | x402 settle recovery, backlog 01 retirement, sniper | [../backlog/PROGRESS.md](backlog-PROGRESS.md), 2026-08-02 and 2026-09-01 entries |
-| 3 | Decide the stranded customer funds: two customers hold about 0.35 SOL behind the retired encryption key and cannot withdraw. Credit, contact, or write off. The brief that was meant to carry the numbers (`docs/ops/stranded-wallets.md`) still does not exist, and it cannot be written from this workspace: the audit that produces the wallet list needs `WALLET_ENCRYPTION_KEY`, which lives only on the Cloud Run service, so **row 15 gates this row's prerequisite too**. A keyless run used to answer 725 of 725 wallets sealed and 8.57 SOL stranded; since 2026-09-02 it exits 3 instead of inventing that number. | decision | Closing the support obligation | [02-stranded-wallet-reclaim.md](production-100-02-stranded-wallet-reclaim.md), [../backlog/PROGRESS.md](backlog-PROGRESS.md) |
+| 1 | Approve the production deploy (or say "get production working", which is itself the approval). Production is at `ad7b54c16` (2026-08-28), 107 commits behind `main`; seven declared routes 404 live until it lands, and the home-screen widget's PNG card and token endpoint are in the gap. | one yes | Nearly everything user-visible in the map | [01-ship-readiness.md](production-100-01-ship-readiness.md) |
+| 2 | Fund the settle sponsor wallet `WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW`. Healthz reports `x402_settle` down with `cause: sponsor_floor` and the sniper worker out of capital (0.2307 SOL to refill its wallets); no config change moves either. | ~1 SOL | x402 settle recovery, backlog 01 retirement, sniper | [../backlog/PROGRESS.md](backlog-PROGRESS.md), 2026-08-02 and 2026-09-01 entries |
+| 3 | Decide the stranded customer funds: two customers hold about 0.35 SOL behind the retired encryption key and cannot withdraw. Credit, contact, or write off. The brief that was meant to carry the numbers (`docs/ops/stranded-wallets.md`) does not exist yet; order 02 writes it. | decision | Closing the support obligation | [02-stranded-wallet-reclaim.md](production-100-02-stranded-wallet-reclaim.md), [../backlog/PROGRESS.md](backlog-PROGRESS.md) |
| 4 | Rotate or explicitly accept the economy master wallet key, which was set as plaintext service env alongside its Secret Manager copy. Order 03 writes the runbook section; the config change itself needs a live `gcloud` (row 15). | decision (+ one fund move if rotating) | 03 closeout | [03-master-key-hygiene.md](production-100-03-master-key-hygiene.md), `docs/ops/gcp-production.md` 2026-07-09 entry |
| 5 | Accept the Anthropic terms in Vertex Model Garden for `aerial-vehicle-466722-p5`, then an agent flips `VERTEX_CLAUDE_ENABLED=1` after a live probe. | minutes | First-party Claude lane | `docs/ops/llm-lanes.md` |
| 6 | Either reactivate OpenAI billing or approve dropping the key; every OpenAI rung is a dead attempt in the chain. Also: OpenRouter fallback key #1 is revoked and still burns a rung; fund the OpenRouter platform key or stay `:free`-only. | minutes | LLM chain latency | `docs/ops/llm-lanes.md` |
| 7 | Mint an R2 "Admin Read and Write" token scoped to the storage bucket, put it in `.env.local`, so `scripts/set-r2-cors.mjs` can apply the CORS policy at the origin. | minutes | backlog 05 retirement, `ISSUES.md` item 9 | [../backlog/05-r2-bucket-cors.md](backlog-05-r2-bucket-cors.md) |
-| 8 | Sign in at the third-party indexer with the platform wallet and register origin `https://three.ws`. Re-checked 2026-09-02: the PAT this row used to ask for is no longer needed (the upstream pull request it would have commented on merged 2026-08-11, and the live discovery endpoint still answers with 100 resources), and the row was attributed to backlog 09, which needs nothing. Origin registration is a signature, not a spend, but it binds an identity, so it is the owner's. | minutes + one signature | backlog 10 retirement | [../backlog/10-x402scan-listing.md](backlog-10-x402scan-listing.md), step 3 |
-| 9 | Fund `0x1C4918894dfA5eE11cfF9629B458b5169Cfa3871` from the public faucet (reCAPTCHA-gated, so no agent path), then say yes to the broadcast. This row's old premise is retired: a deployer key **does** exist in the gitignored `contracts/.env`, re-verified 2026-09-02 at balance 0 and nonce 0, both dry runs simulate green against the live RPC, and the broadcast path is proven end to end on a local node. Roughly 0.0003 tBNB of gas covers both deploys. Do not fund the retired 2026-08-02 address. | minutes + one yes | backlog 07 retirement | [../backlog/00-INDEX.md](backlog-00-INDEX.md), order 07 |
+| 8 | Refresh the GitHub PAT (classic, `public_repo`); the stored one returns Bad credentials. Blocks one docs push in a sibling repo. | minutes | backlog 09 residue | [../backlog/00-INDEX.md](backlog-00-INDEX.md), order 09 |
+| 9 | Generate a NEW testnet deployer key for backlog 07 and fund it via the public faucet (reCAPTCHA-gated), then say yes to the broadcast. The key generated on 2026-08-02 no longer exists on this machine (`contracts/.env` is gone) and its address holds nothing; funding it would strand the tokens. | minutes + one yes | backlog 07 retirement | [../backlog/00-INDEX.md](backlog-00-INDEX.md), order 07 |
| 10 | The marketplace-listing pack needs its email OTP as `[email protected]` for two reads (the approval status of the listing resubmitted on chain 2026-08-27, and the chat-bot session), plus buyer-wallet funding for the real-payment gauntlet and an AI-provider key on the chat-bot service, whose Cloud Run deploy is also owner-gated (it has never reported a heartbeat). | minutes + funding | The pack's orders 04, 07, 08 and backlog 08 | that pack's `RUNBOOK.md` and `e2e-evidence/FUNDING-REQUEST.md` |
| 11 | Clear the commit gate for the backlog orders whose diffs reference third-party projects (07 through 10), per the CLAUDE.md coin rule, if that work should land in history. | one yes each | backlog 07 to 10 commits | [../backlog/00-INDEX.md](backlog-00-INDEX.md) |
| 12 | Multiplayer scale decision: the world service is a pinned single instance with a measured 400-concurrent ceiling and no autoscale (room affinity needs Redis first). Decide whether to fund or approve the Redis-backed scale-out. | decision | quality-bar 03 scope | [../event/PROGRESS.md](event-PROGRESS.md), preflight residuals |
| 13 | Decide how to close out the 2026-08-09 community event. Re-measured 2026-09-02 and the picture changed: the world server was never redeployed with the event build, so there were no quest runs, no leaderboard writes and no souvenir grants at all, and there is no list to settle from. The countdown, the `/event` page and the in-world meetup layer did run. Options: re-run the event now that the server-side code is live on production, settle from nothing and close it out publicly, or hold. Two reads that would overturn this finding are in row 15. | decision | event 08 closeout | [PROGRESS.md](event-PROGRESS.md), 2026-09-02 entry |
| 14 | Clear the commit gate for the 2026-09-01 retirement batch: three verified-shipped or superseded work-order files, plus the doc lines that cite them, whose content names other crypto projects (backlog 10; the marketplace pack's order 05, superseded by 08 with its resubmission confirmed on chain; the retired second-chain-venue pack's three context files, whose facts are duplicated in that venue's READMEs). The agent report of that date lists the exact paths and the referrer lines to rewrite. | one yes | Those deletions and the stale doc lines | [PROGRESS.md](production-100-PROGRESS.md), 2026-09-01 entry |
-| 15 | Re-authenticate `gcloud` in this workspace (`gcloud auth login`); token refresh fails non-interactively, and so does application-default. Re-confirmed dead 2026-09-02 (`gcloud run services list` still answers "Reauthentication failed. cannot prompt during non-interactive execution"). Blocks the Cloud Scheduler comparison (fix-queue 03), the master-key config change (03), row 18, the stranded-funds brief that row 3's decision rests on (the audit needs `WALLET_ENCRYPTION_KEY` off the service env), and every fleet check in quality-bar 03. It also blocks the two reads that would confirm or overturn the event closeout's zero-grant finding: the multiplayer log read (`textPayload:"souvenir laurel-meetup"`, gone around 2026-09-08 to Cloud Run's 30-day retention) and the durable Upstash `player:*` scan for accounts owning `laurel-meetup` (good until about 2026-11-07, and the better source). Both queries are written out in the event pack's 2026-09-02 entry. | minutes | fix-queue 03, 02, 03, 13, 18, quality-bar 03 | CLAUDE.md self-unblock playbook, [PROGRESS.md](event-PROGRESS.md) |
-| 16 | Create the `three-ws` GitHub organization and `three-ws/examples` (public), then run the push command `npm run export:satellites` prints. The export stages 70 files offline today; re-probed 2026-09-02, both the organization and the repository still answer 404. | minutes | roadmap developer-resources retirement | [../roadmap/developer-resources-repos.md](roadmap-developer-resources-repos.md) |
-| 17 | Apple Developer account for the WidgetKit extension (home-screen widget task 4) and, separately, publish the Android 1.1.0 build (versionCode 2) to Play. | account + minutes | roadmap native-widgets task 4 and its release | [../roadmap/native-widgets.md](roadmap-native-widgets.md) |
+| 15 | Re-authenticate `gcloud` in this workspace (`gcloud auth login`); token refresh fails non-interactively, and so does application-default. Blocks the Cloud Scheduler comparison (fix-queue 03), the master-key config change (03), row 18, and every fleet check in quality-bar 03. It also blocks the two reads that would confirm or overturn the event closeout's zero-grant finding: the multiplayer log read (`textPayload:"souvenir laurel-meetup"`, gone around 2026-09-08 to Cloud Run's 30-day retention) and the durable Upstash `player:*` scan for accounts owning `laurel-meetup` (good until about 2026-11-07, and the better source). Both queries are written out in the event pack's 2026-09-02 entry. | minutes | fix-queue 03, 03, 13, 18, quality-bar 03 | CLAUDE.md self-unblock playbook, [PROGRESS.md](event-PROGRESS.md) |
+| 16 | Create the `three-ws` GitHub organization and `three-ws/examples` (public), then run the push command `npm run export:satellites` prints. The export stages 70 files offline today; the repo does not exist. | minutes | roadmap developer-resources retirement | [../roadmap/developer-resources-repos.md](roadmap-developer-resources-repos.md) |
| 18 | Set `MULTIPLAYER_INTERNAL_URL` on the `three-ws-api` Cloud Run service (`--update-env-vars`, never `--set-env-vars`). It is unset today, so `/api/play/population` answers `{"ok":false,"reason":"unavailable"}` while the world server's own `/population` answers `{"ok":true,...}` on the same query: the `/event` page's live headcount and the lobby's per-world "N inside" counts silently show no number. Needs row 15 first. | one command | The live headcount on `/event` and the `/play` lobby | [PROGRESS.md](event-PROGRESS.md), 2026-09-02 entry |
+| 17 | Apple Developer account for the WidgetKit extension (home-screen widget task 4) and, separately, publish the Android 1.1.0 build (versionCode 2) to Play. | account + minutes | roadmap native-widgets task 4 and its release | [../roadmap/native-widgets.md](roadmap-native-widgets.md) |
Deleted 2026-09-01: the former row 5 (`WALLET_ENCRYPTION_KEY_PREVIOUS` policy), which
declared itself "delete on reading" and had outlived that by three weeks.
-Re-measured 2026-09-02, and three premises had rotted. Row 8 asked for a credential that
-nothing needs any more and pointed at the wrong work order. Row 9 asked the owner to
-generate a key that already exists, and named no address to fund. Row 3's brief turned out
-to be unwritable from this workspace at all, which makes row 15 the gate on four rows
-rather than three. Nothing was cleared by the owner; the corrections are all measurement.
-Evidence is in [PROGRESS.md](production-100-PROGRESS.md) under 2026-09-02.
-
## How agents use this file
- Add a row the moment an owner-only remainder appears; never end a session holding one
diff --git a/prompts/finish/production-100-PROGRESS.md b/prompts/finish/production-100-PROGRESS.md
index 16d52372f..330413924 100644
--- a/prompts/finish/production-100-PROGRESS.md
+++ b/prompts/finish/production-100-PROGRESS.md
@@ -85,43 +85,3 @@ now carries its numbers (56 of 151 routes mechanically clean, 95 with a measured
none retirable on mechanical evidence) and the state of the four sweeps and the roadmap
slice. Probe artifacts stayed in the session scratchpad; the reproducible method is in
`docs/ops/swarm-100-audit.md`.
-
-## 2026-09-02: OWNER-ACTIONS re-measured, and the audit that would have lied about row 3
-
-Measured, not carried over: production still `ad7b54c16` (2026-08-28, revision 00404-ph7)
-against a `main` that has moved to **143 commits ahead** (`git rev-list --count
-ad7b54c16..HEAD`); healthz `x402_settle` down at 5.9% (3 of 51 paid attempts, 3 hours,
-`cause: sponsor_floor`, 329 `no_solana_accept`) with the sponsor wallet holding
-**0.001568 SOL** read straight off mainnet `getBalance`; `gcloud run services list` still
-refusing with "Reauthentication failed. cannot prompt during non-interactive execution";
-the `three-ws` GitHub organization and its `examples` repository both 404; the x402
-discovery endpoint live with 100 resources; the testnet deployer
-`0x1C4918894dfA5eE11cfF9629B458b5169Cfa3871` present in `contracts/.env` at balance 0,
-nonce 0.
-
-Found and fixed a defect that would have made row 3 worse than unanswered. Running
-`scripts/audit-custodial-key-health.mjs` here, where `.env.local` carries only
-`DATABASE_URL`, produced a fully confident report: **725 of 725 wallets undecryptable,
-8.57 SOL stranded, 7.29 SOL of it customer money**, followed by the escalation banner. Every
-number was an artifact of the script having no decryption key at all, and it is off by more
-than an order of magnitude from the real incident (8 wallets, 0.49 SOL). It is the same
-class of false certainty the script already guards against for unread balances. The audit
-now calls `secretBoxKeyCandidates()` before it touches the database and exits 3 with the
-places to find the key when the list is empty, and when a key is configured but opens
-nothing it says a fleet-wide 100% failure is one wrong key rather than a mass customer
-incident (`3a8000267`). `scripts/gcp-triage.mjs` skips on the structured error code instead
-of matching prose, and `docs/ops/wallet-key-migration.md` records the blind spot beside the
-two it already documents (`7335810ec`).
-
-Did: rewrote rows 1, 2, 3, 8, 9, 15 and 16 of OWNER-ACTIONS from those measurements, and
-put row 18 back in numeric order. Three premises had rotted. Row 8 asked for a GitHub PAT
-that nothing needs any more (the upstream pull request merged 2026-08-11) and was filed
-against backlog 09, which needs nothing; it now asks for the origin registration that is
-actually left, against backlog 10. Row 9 asked the owner to generate a deployer key that
-already exists and named no address to fund; it now names the address, the measured gas
-cost, and the retired address not to fund. Row 3 gained the finding above: the brief it
-waits on cannot be written from this workspace at all, because the wallet list needs
-`WALLET_ENCRYPTION_KEY` off the service env, which makes row 15 the gate on four rows.
-
-Left: no row was cleared, because none of them is an agent's to clear. Row 15 is now the
-highest-leverage one on the board.
diff --git a/prompts/store-submissions/_generated/TRACKER.md b/prompts/store-submissions/_generated/TRACKER.md
index 68f7e1278..e8c7117e0 100644
--- a/prompts/store-submissions/_generated/TRACKER.md
+++ b/prompts/store-submissions/_generated/TRACKER.md
@@ -1,6 +1,6 @@
# three.ws Store Submission Tracker
-Last updated: 2026-09-02 (tool-count reconciliation: the free studio connector serves **eleven** tools live, not the nine or ten quoted around the repo. `look_at_model` landed 2026-08-28 and `check_job` before it, and every count, listing table, annotation table, announcement document and social card is now reconciled against a fresh `tools/list` pull, with `tests/mcp-studio.test.js` pinning the total so the next tool cannot re-open the drift. Also re-verified live the same day: `/.well-known/3d-studio-openapi.yaml`, `/.well-known/ai-plugin.json`, `/legal/privacy`, `/legal/tos` and `/support` all return 200, and `resources/list` returns the two widget resources. Dated notes below are kept as the record of what was true when written.) Prior: 2026-07-15 (live re-verification of the Claude Connectors free-lane blocker: production `POST /api/mcp-studio tools/call forge_free` returned HTTP 200 in 16.1s with a real 1,553,784-byte GLB (`glTF` magic, served from `/cdn/forge/anon/…`), and the emitted `/viewer?src=` link returned 200. The 2026-07-08 90-100s hang no longer reproduces; the Connectors package is clear to file once the two `[HUMAN:]` items in its row (org/portal access, `MCP_REVIEW_SECRET` + reviewer-credential decision) are done.) Prior: 2026-07-14 (owner CREATED the GPT Store GPT — URL recorded in its row; store visibility still to confirm. Same day: verified organization confirmed on platform.openai.com; submission package finalized with support contact, privacy URL, and the live 9-tool surface; fresh E2E on both the MCP studio and the Actions lane). Prior: 2026-07-10 Track G build-status reconciliation. Re-run prompt 14 near the end to refresh status.
+Last updated: 2026-07-15 (live re-verification of the Claude Connectors free-lane blocker: production `POST /api/mcp-studio tools/call forge_free` returned HTTP 200 in 16.1s with a real 1,553,784-byte GLB (`glTF` magic, served from `/cdn/forge/anon/…`), and the emitted `/viewer?src=` link returned 200. The 2026-07-08 90-100s hang no longer reproduces; the Connectors package is clear to file once the two `[HUMAN:]` items in its row (org/portal access, `MCP_REVIEW_SECRET` + reviewer-credential decision) are done.) Prior: 2026-07-14 (owner CREATED the GPT Store GPT — URL recorded in its row; store visibility still to confirm. Same day: verified organization confirmed on platform.openai.com; submission package finalized with support contact, privacy URL, and the live 9-tool surface; fresh E2E on both the MCP studio and the Actions lane). Prior: 2026-07-10 Track G build-status reconciliation. Re-run prompt 14 near the end to refresh status.
**Last verified: 2026-07-10** — method: direct code read of every prompt-17–21 implementation file plus its wiring, and a live run of the Track-G/16 suites. `npx vitest run tests/spatial-mcp.test.js tests/provenance-3d.test.js tests/ar-export.test.js tests/embed-gate.test.js tests/mcp3d-persona-identity.test.js tests/tokenize-3d.test.js` → **6 files / 98 tests, all passing** (spatial-mcp 22, provenance-3d 20, ar-export 13, embed-gate 20, mcp3d-persona-identity 8, tokenize-3d 15). Confirmed the five new 3D-Studio tool groups are wired into `api/_mcp3d/catalog.js` (`spatialDefs`, `arDefs`, `provenanceDefs`, `personaIdentityDefs` — lines 7–10, 25) and `create_gated_embed` into `api/_mcp/catalog.js` (line 13/21). Confirmed the P0 `readBody` fix is present in the tree (commit `ba37182f3`).
@@ -36,7 +36,7 @@ Legend: **not-started** | **blocked** | **ready-to-submit** | **submitted** | **
| 14 | Cross-store asset kit | ✅ complete | `_generated/assets/`, `listing-copy.md`, `TRACKER.md` |
| 02 | Claude reviewer access guide | ✅ complete (shipped 2026-06-25; re-audited + closed out 2026-07-08) | `_generated/claude-reviewer-guide.md` + `_generated/claude-tool-call-evidence.md` (16/16 paid tools clean `PaymentRequired`; review-mode entitlement is real code in `mcp-server/src/payments.js`) |
| 03 | Claude submission package | ⬜ not started | `_generated/claude-submission.md` (exists from earlier run — verify/refresh) |
-| 04 | OpenAI free 3D endpoint | 🟨 code-complete, was blocked on the P0 hang | `api/mcp-studio.js` + `api/_mcp-studio/*` — 11 tools live as of 2026-09-02 (6 generation incl. `refine_model`, the `check_job` collector, the `look_at_model` inspector, 3 persona), real rate limiting (`api/_lib/rate-limit.js:413-496`), zero coin surface (grep-clean), 46/46 tests pass (`tests/mcp-studio*.test.js`). `server-studio.json` description corrected (was stale "five tools"). Blocked end-to-end verification on the P0 `readBody` hang (code fix landed, commit `ba37182f3`; prod re-verification remains) and the `/viewer?src=` 404 (dist/viewer.html exists and the vercel.json rewrite is correct — likely just stale on the previously-deployed container; re-verify against the live revision) |
+| 04 | OpenAI free 3D endpoint | 🟨 code-complete, was blocked on the P0 hang | `api/mcp-studio.js` + `api/_mcp-studio/*` — 9 tools (6 generation incl. `refine_model`, 3 persona), real rate limiting (`api/_lib/rate-limit.js:413-496`), zero coin surface (grep-clean), 46/46 tests pass (`tests/mcp-studio*.test.js`). `server-studio.json` description corrected (was stale "five tools"). Blocked end-to-end verification on the P0 `readBody` hang (code fix landed, commit `ba37182f3`; prod re-verification remains) and the `/viewer?src=` 404 (dist/viewer.html exists and the vercel.json rewrite is correct — likely just stale on the previously-deployed container; re-verify against the live revision) |
| 05 | OpenAI Apps SDK component | ✅ complete (prior session) | GLB viewer component; hero screenshot |
| 06 | OpenAI submission package | 🟨 package complete, verdict was NOT READY on B1/B2 | `_generated/openai-submission.md` (7/7 policy PASS, real screenshots, real captured tool responses with no PII/internal-ID leakage). Its own §0 verdict cites B1 (rate-limiter hang — this was actually the P0 `readBody` bug, not a quota issue; code fix landed, commit `ba37182f3`) and B2 (`/viewer` 404). Re-run the doc's verification steps against the live production revision before treating this as ready-to-submit |
| 07 | Embodied live agent avatar | 🟨 code-complete, live demo was blocked by the P0 hang | `create_agent_persona`/`get_agent_persona`/`persona_say` (`api/_mcp-studio/persona-tools.js`, mirrored in `api/_mcp3d/tools/studio.js`), real Postgres+R2 persistence (`api/_lib/persona-store.js`, not in-memory), real viseme/lip-sync cascade + emotion→clip mapping + idle loop (`apps-sdk/embodiment/embodiment-stage.js`, `src/embodiment/*`), never-T-pose fallback gate. 67/67 tests pass. Evidence (6 real rendered screenshots) in `_generated/embodiment/` — captured locally (`npm run dev`), not yet re-confirmed against redeployed prod |
diff --git a/scripts/audit-docs.mjs b/scripts/audit-docs.mjs
index f8afca16c..d20e43f84 100644
--- a/scripts/audit-docs.mjs
+++ b/scripts/audit-docs.mjs
@@ -308,7 +308,6 @@ const UNPUBLISHED_DOCS = new Map([
['nvidia-apps-catalog-listing', 'internal: paste-ready listing copy and portal steps for the NVIDIA Inception catalog'],
['nvidia-apps-catalog-request', 'internal: outbound email asking NVIDIA to publish the catalog listing'],
['nvidia-visibility-map', 'internal: outreach priorities and unclaimed program benefits across every NVIDIA surface'],
- ['nvidia-forum-browser-digital-human', 'internal: forum post drafted for the NVIDIA Developer Forums, owner-gated until posted'],
['openai-listing-channels', 'internal: submission strategy and a candid post-mortem of our own stalled Cookbook PR'],
['okx-marketplace', 'owner-gated: names a crypto project other than $THREE'],
['pay-skills-listing', 'internal: listing metadata, not prose'],
diff --git a/src/fact-checker-app.js b/src/fact-checker-app.js
index 1cca672ff..55a8adc36 100644
--- a/src/fact-checker-app.js
+++ b/src/fact-checker-app.js
@@ -74,17 +74,8 @@ function faviconUrl(sourceUrl) {
}
function stancePill(stance) {
- // `partial` is a source that bears the claim out in one respect and corrects
- // it in another. It is what drives the `mixed` verdict, so it carries the same
- // amber the mixed badge does (see .stance-pill.partial in pages/fact-checker.html).
- const labels = {
- supports: 'Supports',
- contradicts: 'Contradicts',
- partial: 'Partly true',
- neutral: 'Neutral',
- };
- const known = Object.prototype.hasOwnProperty.call(labels, stance) ? stance : 'neutral';
- return `<span class="stance-pill ${known}">${labels[stance] || stance}</span>`;
+ const labels = { supports: 'Supports', contradicts: 'Contradicts', neutral: 'Neutral' };
+ return `<span class="stance-pill ${stance}">${labels[stance] || stance}</span>`;
}
function renderSources(sources) {
diff --git a/tests/api/fact-check-verdict.test.js b/tests/api/fact-check-verdict.test.js
deleted file mode 100644
index 5673ce284..000000000
--- a/tests/api/fact-check-verdict.test.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * Unit tests for api/x402/fact-check.js#computeVerdict, the weighted verdict
- * calculus behind every fact-check answer and behind the published accuracy
- * benchmark on /fact-check.
- *
- * Written against SYNTHETIC stance distributions on purpose. The benchmark
- * fixture is 40 real claims scored through the live chain; shaping the calculus
- * to those ten `mixed` claims would fit the fixture rather than fix the rule.
- * These cases pin the rule itself:
- * • the clear-cut distributions (unanimous, near-unanimous, empty, silent)
- * keep their verdicts, so the mixed band can never swallow them
- * • `partial` weight is stance-bearing but takes neither side, which is the
- * route by which a claim every source calls "true in one respect, wrong in
- * another" reaches `mixed` instead of `contradicted`
- * • confidence for `mixed` measures how strongly the evidence establishes
- * mixedness, not how lopsided the split was
- */
-
-import { describe, it, expect } from 'vitest';
-import { _computeVerdict as computeVerdict } from '../../api/x402/fact-check.js';
-
-/** Build n sources of one stance at a uniform weight. */
-const of = (stance, n, weight = 0.8) =>
- Array.from({ length: n }, (_v, i) => ({ url: `https://example.com/${stance}/${i}`, stance, weight }));
-
-describe('computeVerdict — clear-cut distributions keep their verdicts', () => {
- it('unanimous support is supported', () => {
- expect(computeVerdict(of('supports', 5)).verdict).toBe('supported');
- });
-
- it('unanimous contradiction is contradicted', () => {
- expect(computeVerdict(of('contradicts', 5)).verdict).toBe('contradicted');
- });
-
- it('exactly 70% of stance weight one way still lands on that side', () => {
- // 7 supporting + 3 contradicting at equal weight is the boundary itself.
- expect(computeVerdict([...of('supports', 7), ...of('contradicts', 3)]).verdict).toBe('supported');
- expect(computeVerdict([...of('contradicts', 7), ...of('supports', 3)]).verdict).toBe('contradicted');
- });
-
- it('one dissenting source does not unseat a dominant side', () => {
- expect(computeVerdict([...of('supports', 4), ...of('contradicts', 1)]).verdict).toBe('supported');
- expect(computeVerdict([...of('contradicts', 4), ...of('supports', 1)]).verdict).toBe('contradicted');
- });
-
- it('authority weight, not source count, decides direction', () => {
- // Two low-authority blogs cannot outvote one encyclopedic source.
- const verdict = computeVerdict([
- { url: 'https://en.wikipedia.org/wiki/X', stance: 'supports', weight: 0.9 },
- { url: 'https://blog.example/a', stance: 'contradicts', weight: 0.15 },
- { url: 'https://blog.example/b', stance: 'contradicts', weight: 0.15 },
- ]);
- expect(verdict.verdict).toBe('supported');
- });
-
- it('fewer than two sources is insufficient, never a verdict', () => {
- expect(computeVerdict([]).verdict).toBe('insufficient');
- expect(computeVerdict(of('supports', 1)).verdict).toBe('insufficient');
- });
-
- it('evidence that never engages the claim is insufficient, not mixed', () => {
- // The 2026-07-08 regression: all-neutral used to return "mixed".
- expect(computeVerdict(of('neutral', 5)).verdict).toBe('insufficient');
- });
-
- it('zero total weight is insufficient', () => {
- expect(computeVerdict(of('supports', 3, 0)).verdict).toBe('insufficient');
- });
-
- it('a single stance-bearing source lost among silent ones is insufficient', () => {
- const sources = [
- { url: 'https://example.com/one', stance: 'supports', weight: 0.2 },
- ...of('neutral', 4, 0.9),
- ];
- expect(computeVerdict(sources).verdict).toBe('insufficient');
- });
-
- it('a lone partial source lost among silent ones is insufficient too', () => {
- // `partial` is stance-bearing, so it goes through the same coverage floor:
- // one loosely-matched page must not decide a verdict on its own.
- const sources = [
- { url: 'https://example.com/one', stance: 'partial', weight: 0.2 },
- ...of('neutral', 4, 0.9),
- ];
- expect(computeVerdict(sources).verdict).toBe('insufficient');
- });
-});
-
-describe('computeVerdict — mixed by inter-source disagreement', () => {
- it('an even split is mixed', () => {
- expect(computeVerdict([...of('supports', 3), ...of('contradicts', 3)]).verdict).toBe('mixed');
- });
-
- it('a split just short of the 70% bar is mixed', () => {
- // 2 vs 1 is 66.7% support: below the bar, so neither side owns it.
- expect(computeVerdict([...of('supports', 2), ...of('contradicts', 1)]).verdict).toBe('mixed');
- });
-
- it('neutral sources dilute confidence but do not change the verdict', () => {
- const tight = computeVerdict([...of('supports', 3), ...of('contradicts', 3)]);
- const diluted = computeVerdict([...of('supports', 3), ...of('contradicts', 3), ...of('neutral', 12)]);
- expect(diluted.verdict).toBe(tight.verdict);
- expect(diluted.confidence).toBeLessThan(tight.confidence);
- });
-});
-
-describe('computeVerdict — mixed by intra-source partiality', () => {
- it('unanimous partial evidence is mixed, not contradicted', () => {
- // The defect this stance exists to fix: every source reads the same
- // nuance ("a tomato is botanically a fruit and culinarily a vegetable"),
- // so before `partial` existed they all projected onto one side and the
- // whole mixed class scored 0/10.
- expect(computeVerdict(of('partial', 5)).verdict).toBe('mixed');
- });
-
- it('partial weight blocks a side from clearing the 70% bar', () => {
- // 3 supports + 2 partial: 60% support, below the bar.
- expect(computeVerdict([...of('supports', 3), ...of('partial', 2)]).verdict).toBe('mixed');
- expect(computeVerdict([...of('contradicts', 3), ...of('partial', 2)]).verdict).toBe('mixed');
- });
-
- it('a lone partial source does not unseat an otherwise dominant side', () => {
- // 8 supports + 1 partial is still 88.9% support. `partial` dilutes
- // dominance; it does not veto it.
- expect(computeVerdict([...of('supports', 8), ...of('partial', 1)]).verdict).toBe('supported');
- });
-
- it('partial mixed with both directions is mixed', () => {
- expect(
- computeVerdict([...of('supports', 2), ...of('contradicts', 2), ...of('partial', 2)]).verdict,
- ).toBe('mixed');
- });
-});
-
-describe('computeVerdict — confidence semantics', () => {
- it('broad engagement outscores thin engagement at the same dominance', () => {
- const broad = computeVerdict(of('supports', 5, 0.8));
- const thin = computeVerdict([...of('supports', 2, 0.8), ...of('neutral', 8, 0.8)]);
- expect(broad.confidence).toBeGreaterThan(thin.confidence);
- });
-
- it('an even split is MORE confidently mixed than a lopsided one', () => {
- // The old rule scored mixed confidence as max(support, contra), so the
- // closer a split came to breaking one way, the more sure it claimed to be
- // that it had not. Mixedness is the thing being measured now.
- const even = computeVerdict([...of('supports', 3), ...of('contradicts', 3)]);
- const lopsided = computeVerdict([...of('supports', 2), ...of('contradicts', 1)]);
- expect(even.confidence).toBeGreaterThan(lopsided.confidence);
- });
-
- it('unanimous partial is as confidently mixed as an even split', () => {
- const partial = computeVerdict(of('partial', 6));
- const split = computeVerdict([...of('supports', 3), ...of('contradicts', 3)]);
- expect(partial.confidence).toBe(split.confidence);
- });
-
- it('every confidence is a bounded, rounded probability', () => {
- const cases = [
- of('supports', 5),
- of('contradicts', 5),
- of('partial', 5),
- [...of('supports', 3), ...of('contradicts', 3)],
- [...of('supports', 3), ...of('partial', 2), ...of('neutral', 4)],
- of('neutral', 5),
- of('supports', 1),
- ];
- for (const sources of cases) {
- const { confidence } = computeVerdict(sources);
- expect(confidence).toBeGreaterThan(0);
- expect(confidence).toBeLessThanOrEqual(0.98);
- expect(Math.round(confidence * 100)).toBe(confidence * 100);
- }
- });
-});
diff --git a/tests/api/okx-3d-services.test.js b/tests/api/okx-3d-services.test.js
index 41b942daa..248d49d44 100644
--- a/tests/api/okx-3d-services.test.js
+++ b/tests/api/okx-3d-services.test.js
@@ -118,11 +118,8 @@ const {
OKX_CATALOG,
catalogEntry,
catalogIndex,
- displayWidth,
listedCatalog,
listingDescription,
- parameterSpec,
- requestMethod,
validateCatalog,
} = await import('../../api/_lib/okx-catalog.js');
const studioCatalog = await import('../../api/_mcp3d/catalog.js');
@@ -199,64 +196,12 @@ describe('okx catalog — work order 03 rows', () => {
expect(prices['fbx-export']).toEqual(['0.10', '100000']);
});
- it('every paid row routes /api/okx/3d/<id> and is POST-documented', () => {
+ it('every paid row routes /api/okx/3d/<id>, is POST-documented, and its listing description joins the two parts', () => {
for (const id of PAID_REST_IDS) {
const e = catalogEntry(id);
expect(e.endpoint).toBe(`https://three.ws/api/okx/3d/${id}`);
expect(e.inputSchema).toBeTruthy();
- }
- });
-
- // OKX listing QA requires FOUR parts on an A2MCP service and rejects a
- // listing missing any of them (`onchainos agent update --help`). Submitting
- // two parts is what earned the 2026-09-02 rejection: "The service you
- // submitted is missing a complete description, parameter details, and usage
- // examples."
- it('every listed row submits four parts: capability, parameters, method, example', () => {
- for (const e of listedCatalog()) {
- const parts = listingDescription(e).split('\n');
- expect(parts, `${e.id} part count`).toHaveLength(4);
- expect(parts[0], `${e.id} capability`).toBe(e.describes.capability);
- expect(parts[1], `${e.id} parameters`).toBe(parameterSpec(e));
- expect(parts[2], `${e.id} method`).toBe(requestMethod(e));
- expect(parts[3], `${e.id} example`).toMatch(/^curl /);
- expect(parts[3], `${e.id} example hits the real endpoint`).toContain(e.endpoint);
- expect(displayWidth(listingDescription(e)), `${e.id} width`).toBeLessThanOrEqual(2000);
- }
- });
-
- // Part 2 is generated from the schema, so it names every argument the
- // endpoint accepts, with the type and required flag the endpoint enforces.
- it('the parameter spec names every schema property with its real type and requiredness', () => {
- for (const e of listedCatalog()) {
- const props = Object.entries(e.inputSchema?.properties || {});
- const spec = parameterSpec(e);
- if (!props.length) {
- expect(spec).toBe('No parameters. Send an empty request.');
- continue;
- }
- const required = new Set(e.inputSchema.required || []);
- for (const [name, prop] of props) {
- const type = prop.type === 'array' ? `${prop.items?.type}[]` : prop.type;
- expect(spec, `${e.id}.${name}`).toContain(
- `${name} (${type}, ${required.has(name) ? 'required' : 'optional'}):`,
- );
- }
- }
- });
-
- // A published usage example the endpoint would reject is worse than none:
- // the buyer copies it, gets a 400, and leaves. Validate each example against
- // the row's own schema with the same Ajv the endpoints use.
- it('every listed usage example validates against its own endpoint schema', async () => {
- const { default: Ajv } = await import('ajv');
- const { default: addFormats } = await import('ajv-formats');
- const ajv = addFormats(new Ajv({ strict: false }));
- for (const e of listedCatalog()) {
- if (!Object.keys(e.inputSchema?.properties || {}).length) continue;
- const validate = ajv.compile(e.inputSchema);
- const ok = validate(e.describes.example);
- expect(ok, `${e.id} example: ${ajv.errorsText(validate.errors)}`).toBe(true);
+ expect(listingDescription(e)).toBe(`${e.describes.capability}\n${e.describes.input}`);
}
});
diff --git a/tests/api/ops-endpoints.test.js b/tests/api/ops-endpoints.test.js
index ebbff7fdd..a788eda41 100644
--- a/tests/api/ops-endpoints.test.js
+++ b/tests/api/ops-endpoints.test.js
@@ -20,10 +20,6 @@
// 5. all three boards spent the strict `authIp` credential budget, so polling
// a dashboard could 429 the operator's login from the same IP. They use the
// `authedReadIp` polled-read bucket.
-// 6. custody lost to a key rotation was measurable only by running a CLI audit
-// by hand, so it stayed invisible for weeks at a time. payment-outcomes
-// carries it as a panel, and a failed read names itself rather than
-// rendering as zero stranded.
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -60,11 +56,6 @@ vi.mock('../../api/_lib/x402/wallet-balance-monitor.js', () => ({
checkRingWallets: () => ringWalletsImpl(),
}));
-let strandedImpl = async () => ({ status: 'clear', sol_stranded: 0, stranded_funded: 0 });
-vi.mock('../../api/_lib/custodial-key-health.js', () => ({
- strandedCustodyPanel: () => strandedImpl(),
-}));
-
const health = await import('../../api/ops/health.js');
const { default: moneyHealthHandler, lastActivity } = await import('../../api/ops/money-health.js');
const { default: paymentOutcomesHandler } = await import('../../api/ops/payment-outcomes.js');
@@ -96,7 +87,6 @@ beforeEach(() => {
sqlImpl = async () => [];
settleHealthImpl = async () => ({ name: 'x402_settle', status: 'ok' });
ringWalletsImpl = async () => ({ wallets: [], sponsorRunway: null });
- strandedImpl = async () => ({ status: 'clear', sol_stranded: 0, stranded_funded: 0 });
});
describe('cron staleness windows derived from vercel.json', () => {
@@ -235,30 +225,6 @@ describe('GET /api/ops/payment-outcomes', () => {
expect(body.ok).toBe(true);
expect(body.degraded).toEqual([]);
});
-
- it('carries the stranded-custody panel, so lost custody is visible without a CLI run', async () => {
- // Capital sealed behind a retired encryption key is a payment-outcome fact:
- // the treasury cannot reclaim it and the customers holding it cannot
- // withdraw. Before this panel the only way to see the number was running
- // scripts/audit-custodial-key-health.mjs by hand, so nobody did.
- strandedImpl = async () => ({
- status: 'stranded', stranded_funded: 2, sol_stranded: 0.122875505,
- sol_stranded_platform: 0.122875505, sol_stranded_customer: 0,
- brief: null, top_stranded: [],
- });
- const { res, body } = await call(paymentOutcomesHandler, '/api/ops/payment-outcomes');
- expect(res.statusCode).toBe(200);
- expect(body.stranded_custody.status).toBe('stranded');
- expect(body.stranded_custody.sol_stranded).toBe(0.122875505);
- });
-
- it('names the stranded panel in degraded when its read fails, instead of rendering a silent zero', async () => {
- strandedImpl = async () => { throw new Error('db unreachable'); };
- const { res, body } = await call(paymentOutcomesHandler, '/api/ops/payment-outcomes');
- expect(res.statusCode).toBe(207);
- expect(body.degraded).toEqual(['stranded_custody']);
- expect(body.stranded_custody.error).toBe('db unreachable');
- });
});
describe('the ops boards share the polled-read bucket, not the credential bucket', () => {
diff --git a/tests/custodial-key-health.test.js b/tests/custodial-key-health.test.js
deleted file mode 100644
index d0fa2a780..000000000
--- a/tests/custodial-key-health.test.js
+++ /dev/null
@@ -1,215 +0,0 @@
-// The custody loss measurement (api/_lib/custodial-key-health.js): the one
-// number the CLI audit and the ops board both read.
-//
-// Every fence here is a defect that already shipped:
-//
-// 1. an unread balance summed as a confirmed zero, so the audit certified
-// "0 SOL stranded" on 2026-08-09 while two wallets held 0.12 SOL behind a
-// dead key. A wallet with no balance read must never reach a total.
-// 2. the audit carried its own ownership predicate with a different house
-// account address than the reclaim leg enforces in SQL, filing 12 platform
-// wallets as CUSTOMER ones. The split feeds a customer support obligation,
-// so it has to be the reclaim leg's exact boundary.
-// 3. the board must not turn a polled dashboard into a fleet-wide RPC scan:
-// the panel is snapshot-cached and concurrent reads share one scan.
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-vi.mock('../api/_lib/db.js', () => ({ sql: async () => [] }));
-vi.mock('../api/_lib/secret-box.js', () => ({ decryptSecret: async () => 'plaintext' }));
-
-const {
- isPlatformOwnedAgent,
- classifyCustodialSecrets,
- summarizeCustodialKeyHealth,
- buildStrandedPanel,
- strandedCustodyPanel,
- resetStrandedCustodyCache,
- PLATFORM_AGENT_OWNER_EMAIL,
-} = await import('../api/_lib/custodial-key-health.js');
-
-const wallet = (address, owner, decryptable, extra = {}) => ({
- agent_id: `ag-${address}`,
- name: address,
- address,
- owner,
- decryptable,
- reason: decryptable ? null : 'wrong_key',
- ...extra,
-});
-
-const HOUSE = PLATFORM_AGENT_OWNER_EMAIL;
-const BOT = '[email protected]';
-const CUSTOMER = '[email protected]';
-
-describe('ownership boundary', () => {
- it('counts the house account and the circulation bots as platform', () => {
- expect(isPlatformOwnedAgent(HOUSE)).toBe(true);
- expect(isPlatformOwnedAgent(BOT)).toBe(true);
- expect(isPlatformOwnedAgent(' [email protected] ')).toBe(true);
- });
-
- it('counts everything else as a customer, including a lookalike domain', () => {
- expect(isPlatformOwnedAgent(CUSTOMER)).toBe(false);
- expect(isPlatformOwnedAgent('[email protected]')).toBe(false);
- // The suffix must match at the end, not anywhere: an attacker-chosen
- // local part must never buy platform classification.
- expect(isPlatformOwnedAgent('[email protected]')).toBe(false);
- expect(isPlatformOwnedAgent(null)).toBe(false);
- expect(isPlatformOwnedAgent(undefined)).toBe(false);
- });
-});
-
-describe('secret classification', () => {
- it('marks a wallet undecryptable with the WebCrypto failure named, not a generic error', async () => {
- const rows = [{ secret: 'sealed' }, { secret: 'fine' }];
- const err = Object.assign(new Error('The operation failed'), { name: 'OperationError' });
- const rowsOut = await classifyCustodialSecrets(rows, async (s) => {
- if (s === 'sealed') throw err;
- return 'plaintext';
- });
- expect(rowsOut[0].decryptable).toBe(false);
- expect(rowsOut[0].reason).toBe('wrong_key');
- expect(rowsOut[1].decryptable).toBe(true);
- expect(rowsOut[1].reason).toBe(null);
- });
-
- it('treats an empty plaintext as undecryptable rather than a healthy wallet', async () => {
- const rows = await classifyCustodialSecrets([{ secret: 'empty' }], async () => '');
- expect(rows[0].decryptable).toBe(false);
- expect(rows[0].reason).toBe('empty_plaintext');
- });
-});
-
-describe('summary counting rules', () => {
- it('never sums a wallet whose balance was not read', () => {
- const wallets = [
- wallet('SEALED_READ', CUSTOMER, false),
- wallet('SEALED_UNREAD', CUSTOMER, false),
- wallet('OK', HOUSE, true),
- ];
- const balances = new Map([['SEALED_READ', 0.25], ['OK', 1]]);
- const r = summarizeCustodialKeyHealth({
- wallets, balances,
- readErrors: [{ address: 'SEALED_UNREAD', reason: 'rpc_error: 403' }],
- });
- // 0.25, not 0.25 plus an invented zero for the wallet nobody could read.
- expect(r.sol.stranded).toBe(0.25);
- expect(r.counts.stranded_unread).toBe(1);
- expect(r.counts.stranded_funded).toBe(1);
- expect(r.unread_stranded.map((w) => w.address)).toEqual(['SEALED_UNREAD']);
- expect(r.read_errors).toBe(1);
- });
-
- it('splits stranded SOL by the reclaim leg’s ownership boundary', () => {
- const wallets = [
- wallet('BOT', BOT, false),
- wallet('HOUSE', HOUSE, false),
- wallet('CUST', CUSTOMER, false),
- ];
- const balances = new Map([['BOT', 0.07], ['HOUSE', 0.03], ['CUST', 0.35]]);
- const r = summarizeCustodialKeyHealth({ wallets, balances });
- expect(r.counts.stranded_platform).toBe(2);
- expect(r.counts.stranded_customer).toBe(1);
- expect(r.sol.stranded_platform).toBe(0.1);
- expect(r.sol.stranded_customer).toBe(0.35);
- expect(r.sol.stranded).toBe(0.45);
- });
-
- it('ranks the stranded list by balance and keeps every wallet identifiable', () => {
- const wallets = [wallet('SMALL', CUSTOMER, false), wallet('BIG', CUSTOMER, false)];
- const balances = new Map([['SMALL', 0.01], ['BIG', 1.2]]);
- const r = summarizeCustodialKeyHealth({ wallets, balances });
- expect(r.top_stranded.map((w) => w.address)).toEqual(['BIG', 'SMALL']);
- expect(r.top_stranded[0]).toMatchObject({ sol: 1.2, platform: false, reason: 'wrong_key' });
- expect(r.top_stranded[0].agent_id).toBe('ag-BIG');
- });
-
- it('reports a zero-balance sealed wallet as sealed but NOT funded', () => {
- const wallets = [wallet('EMPTY', CUSTOMER, false)];
- const r = summarizeCustodialKeyHealth({ wallets, balances: new Map([['EMPTY', 0]]) });
- expect(r.undecryptable).toBe(1);
- expect(r.counts.stranded_funded).toBe(0);
- expect(r.counts.stranded_unread).toBe(0);
- expect(r.sol.stranded).toBe(0);
- });
-});
-
-describe('ops panel verdict', () => {
- const report = (over = {}) => ({
- checked_at: '2026-09-02T00:00:00.000Z',
- wallets: 725,
- undecryptable: 8,
- sol: { stranded: 0.49, stranded_platform: 0.14, stranded_customer: 0.35 },
- counts: { stranded_funded: 8, stranded_unread: 0 },
- top_stranded: [
- { address: 'A', sol: 0.35, platform: false, reason: 'wrong_key' },
- { address: 'B', sol: 0.14, platform: true, reason: 'wrong_key' },
- ],
- ...over,
- });
-
- it('says stranded, splits the SOL, and points at the owner decision brief', () => {
- const p = buildStrandedPanel(report());
- expect(p.status).toBe('stranded');
- expect(p.sol_stranded_customer).toBe(0.35);
- expect(p.customer_wallets_stranded).toBe(1);
- expect(p.brief).toBe('docs/ops/stranded-wallets.md');
- });
-
- it('refuses to call a partial read a measurement', () => {
- const p = buildStrandedPanel(report({ counts: { stranded_funded: 8, stranded_unread: 3 } }));
- expect(p.status).toBe('unknown');
- expect(p.detail).toMatch(/floor, not a measurement/);
- });
-
- it('says clear only when nothing funded is sealed, and then names no brief', () => {
- const p = buildStrandedPanel(report({
- undecryptable: 0, counts: { stranded_funded: 0, stranded_unread: 0 },
- sol: { stranded: 0, stranded_platform: 0, stranded_customer: 0 }, top_stranded: [],
- }));
- expect(p.status).toBe('clear');
- expect(p.brief).toBe(null);
- });
-});
-
-describe('snapshot cache', () => {
- beforeEach(() => resetStrandedCustodyCache());
-
- it('scans once and serves the snapshot for the whole TTL', async () => {
- const gather = vi.fn(async () => ({ counts: { stranded_funded: 0, stranded_unread: 0 }, sol: {} }));
- await strandedCustodyPanel({ gather, now: 1_000 });
- const second = await strandedCustodyPanel({ gather, now: 1_000 + 60_000 });
- expect(gather).toHaveBeenCalledTimes(1);
- expect(second.cache_age_seconds).toBe(60);
- });
-
- it('rescans once the snapshot ages past the TTL', async () => {
- const gather = vi.fn(async () => ({ counts: { stranded_funded: 0, stranded_unread: 0 }, sol: {} }));
- await strandedCustodyPanel({ gather, ttlMs: 1_000, now: 0 });
- await strandedCustodyPanel({ gather, ttlMs: 1_000, now: Date.now() + 5_000 });
- expect(gather).toHaveBeenCalledTimes(2);
- });
-
- it('collapses concurrent reads into one fleet scan', async () => {
- let release;
- const gate = new Promise((r) => { release = r; });
- const gather = vi.fn(async () => {
- await gate;
- return { counts: { stranded_funded: 0, stranded_unread: 0 }, sol: {} };
- });
- const both = Promise.all([strandedCustodyPanel({ gather }), strandedCustodyPanel({ gather })]);
- release();
- await both;
- expect(gather).toHaveBeenCalledTimes(1);
- });
-
- it('does not cache a failed scan, so a transient outage is retried not frozen', async () => {
- const gather = vi.fn()
- .mockRejectedValueOnce(new Error('rpc down'))
- .mockResolvedValueOnce({ counts: { stranded_funded: 0, stranded_unread: 0 }, sol: {} });
- await expect(strandedCustodyPanel({ gather })).rejects.toThrow('rpc down');
- await expect(strandedCustodyPanel({ gather })).resolves.toMatchObject({ status: 'clear' });
- expect(gather).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/vercel.json b/vercel.json
index 8199f86a3..b555663df 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2020,18 +2020,6 @@
"src": "/constellation/",
"dest": "/constellation.html"
},
- {
- "src": "/cert/?",
- "dest": "/certificate.html"
- },
- {
- "src": "/cert/([0-9a-f]{24})/?",
- "dest": "/certificate.html"
- },
- {
- "src": "/materialize/insert/([0-9a-f]{24})/?",
- "dest": "/print-insert.html"
- },
{
"src": "/p/([a-z0-9-]+)/?",
"dest": "/p/index.html"
@@ -6312,10 +6300,6 @@
{
"path": "/api/cron/feedback-triage",
"schedule": "*/5 * * * *"
- },
- {
- "path": "/api/cron/print-orders-sync",
- "schedule": "*/15 * * * *"
}
]
}
diff --git a/workers/okx-chat-bot/config.js b/workers/okx-chat-bot/config.js
index 41311e9a9..bf3d6444c 100644
--- a/workers/okx-chat-bot/config.js
+++ b/workers/okx-chat-bot/config.js
@@ -4,7 +4,6 @@
// VM, and locally with no code change. The defaults are the production posture:
// state persisted to GCS, heartbeat on, session probed every minute.
-import { existsSync } from 'node:fs';
import { homedir, hostname } from 'node:os';
import { join } from 'node:path';
@@ -30,31 +29,18 @@ const num = (v, fallback) => {
* CLAUDE_CODE_OAUTH_TOKEN → claude
* OPENAI_API_KEY → codex
*
- * A headless host is credentialed by env alone, but a developer host running the
- * stopgap has no key at all: its claude CLI was logged in interactively and keeps
- * the grant in ~/.claude/.credentials.json. Ignoring that file reports
- * `ai_provider_uncredentialed` on a host whose adapter demonstrably authors
- * replies, which is a false red, and a false red trains people to ignore the
- * signal that this worker exists to raise.
- *
* @param {NodeJS.ProcessEnv} env
- * @param {string} [home] where the CLI keeps an interactive login
* @returns {{ provider: string, reason: string, credentialed: boolean }}
*/
-export function resolveProvider(env = process.env, home = env.OKX_BOT_HOME || homedir()) {
+export function resolveProvider(env = process.env) {
const pinned = (env.OKX_BOT_AI_PROVIDER || '').trim().toLowerCase();
- const hasClaudeKey = !!(env.ANTHROPIC_API_KEY || env.CLAUDE_CODE_OAUTH_TOKEN);
- const hasClaudeLogin = existsSync(join(home, '.claude', '.credentials.json'));
- const hasClaude = hasClaudeKey || hasClaudeLogin;
+ const hasClaude = !!(env.ANTHROPIC_API_KEY || env.CLAUDE_CODE_OAUTH_TOKEN);
const hasCodex = !!env.OPENAI_API_KEY;
if (pinned) {
const credentialed = pinned === 'claude' ? hasClaude : pinned === 'codex' ? hasCodex : true;
return { provider: pinned, reason: 'pinned by OKX_BOT_AI_PROVIDER', credentialed };
}
- if (hasClaudeKey) return { provider: 'claude', reason: 'ANTHROPIC_API_KEY present', credentialed: true };
- if (hasClaudeLogin) {
- return { provider: 'claude', reason: 'claude CLI holds an interactive login', credentialed: true };
- }
+ if (hasClaude) return { provider: 'claude', reason: 'ANTHROPIC_API_KEY present', credentialed: true };
if (hasCodex) return { provider: 'codex', reason: 'OPENAI_API_KEY present (no Anthropic key)', credentialed: true };
return {
provider: 'claude',
@@ -91,14 +77,13 @@ export function resolveHost(env = process.env) {
}
export function loadConfig(env = process.env) {
- const home = env.OKX_BOT_HOME || homedir();
- const provider = resolveProvider(env, home);
+ const provider = resolveProvider(env);
const host = resolveHost(env);
return {
// HOME for both CLIs. Everything durable lands under it:
// $home/.okx-agent-task/ daemon state, sqlite, XMTP db, AI workspace
// $home/.onchainos/ wallet keyring, session, machine identity
- home,
+ home: env.OKX_BOT_HOME || homedir(),
port: num(env.PORT, 0),
agentId: env.OKX_BOT_AGENT_ID || '2632',