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.

feat(marketplace): trial status, MCP policy, and guard proofs

nirholas2b51b77cee44
diff --git a/api/_lib/marketplace-kinds.js b/api/_lib/marketplace-kinds.js
new file mode 100644
index 000000000..41d48f72b
--- /dev/null
+++ b/api/_lib/marketplace-kinds.js
@@ -0,0 +1,31 @@
+/**
+ * What counts as a marketplace SALE.
+ *
+ * `skill_purchases.kind` records how a row granted access, and only some of those
+ * ways involved money changing hands for that row:
+ *
+ * purchase a one-time skill sale → revenue
+ * time_pass timed access, bought outright → revenue
+ * trial free evaluation access → demand, not revenue
+ * bundle access granted by a bundle already paid for → already counted on
+ * bundle_purchases; counting it again would report one sale as N
+ *
+ * Every aggregate that adds up money or counts distinct buyers/sellers has to
+ * gate on `status = 'confirmed' AND kind = ANY(MARKET_PAID_KINDS)`. Filtering on
+ * status alone silently admits trials and bundle-access rows into published GMV,
+ * which is the exact defect removed from the public /pulse page: one 1000-unit
+ * sale alongside a confirmed bundle row and a confirmed trial published GMV 2600
+ * and 3 buyers instead of 1000 and 1.
+ *
+ * This list lives here rather than in any one handler because /pulse (the public
+ * transparency page) and the bundle pricing simulator both have to mean the same
+ * thing by "sold". A number that disagrees across two surfaces is worse than a
+ * number that is missing.
+ */
+export const MARKET_PAID_KINDS = ['purchase', 'time_pass'];
+
+/**
+ * Kinds that grant access without being a sale of their own. Kept explicit so a
+ * new kind has to be classified deliberately rather than defaulting into revenue.
+ */
+export const MARKET_UNPAID_KINDS = ['trial', 'bundle'];
diff --git a/api/marketplace/start-trial.js b/api/marketplace/start-trial.js
index 104b34bee..483f221e9 100644
--- a/api/marketplace/start-trial.js
+++ b/api/marketplace/start-trial.js
@@ -5,12 +5,17 @@
* Checks the skill has trial_uses > 0 on agent_skill_prices.
* Inserts a skill_purchases row with status='trial', kind='trial', no payment.
* Rate-limit: one trial per (user, agent, skill).
+ *
+ * Auth: browser session cookie (CSRF enforced) OR an API-key bearer token, the
+ * same pair every other marketplace write accepts. Without the bearer branch a
+ * script had to scrape a session cookie and mint a CSRF token just to take a
+ * free trial, while the purchase that follows it took a plain bearer header.
*/
import { z } from 'zod';
import crypto from 'node:crypto';
import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -25,10 +30,14 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id || bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
- const csrfOk = await requireCsrf(req, res, user.id);
+ // requireCsrf short-circuits on an Authorization: Bearer header, so this is
+ // a no-op for key callers and still mandatory for cookie callers.
+ const csrfOk = await requireCsrf(req, res, userId);
if (!csrfOk) return;
const rl = await limits.authIp(clientIp(req));
@@ -58,7 +67,7 @@ export default wrap(async (req, res) => {
const [existing] = await sql`
SELECT id, status, trial_remaining
FROM skill_purchases
- WHERE user_id = ${user.id} AND agent_id = ${agent_id} AND skill = ${skill}
+ WHERE user_id = ${userId} AND agent_id = ${agent_id} AND skill = ${skill}
AND status IN ('confirmed', 'trial')
LIMIT 1
`;
@@ -79,7 +88,7 @@ export default wrap(async (req, res) => {
// Check rate-limit: one trial attempt per (user, agent, skill) — look at any prior trial row
const [priorTrial] = await sql`
SELECT id FROM skill_purchases
- WHERE user_id = ${user.id} AND agent_id = ${agent_id} AND skill = ${skill}
+ WHERE user_id = ${userId} AND agent_id = ${agent_id} AND skill = ${skill}
AND kind = 'trial'
LIMIT 1
`;
@@ -93,7 +102,7 @@ export default wrap(async (req, res) => {
INSERT INTO skill_purchases
(user_id, agent_id, skill, status, kind, reference, amount, currency_mint, chain, trial_remaining)
VALUES
- (${user.id}, ${agent_id}, ${skill}, 'trial', 'trial', ${reference},
+ (${userId}, ${agent_id}, ${skill}, 'trial', 'trial', ${reference},
${price.amount}, ${price.currency_mint}, ${price.chain}, ${price.trial_uses})
RETURNING id, trial_remaining, reference, created_at
`;
diff --git a/api/marketplace/trial-status.js b/api/marketplace/trial-status.js
new file mode 100644
index 000000000..8b8c7de75
--- /dev/null
+++ b/api/marketplace/trial-status.js
@@ -0,0 +1,226 @@
+/**
+ * GET /api/marketplace/trial-status?role=buyer|seller
+ *
+ * The marketplace's conversion surface. A metered free trial is only a funnel
+ * if somebody can see it draining; until this endpoint existed the platform
+ * held thousands of live trials and exposed exactly one bit about any of them
+ * (`has_access: true|false`), so neither side of a trade could act on the one
+ * moment that actually converts: a buyer who liked a skill enough to spend
+ * every free run and wants another.
+ *
+ * Two perspectives, one route:
+ *
+ * role=buyer (default) the caller's own trials, each with the runs left,
+ * the price to keep it, and a state to render against.
+ * role=seller trials running on skills the caller's agents sell,
+ * aggregated per skill, with the revenue sitting in
+ * the queue.
+ *
+ * Privacy: the seller view is deliberately COUNTS ONLY. A seller learns that
+ * nine buyers burned through a trial of `icon-set`; they never learn who. The
+ * buyer view is scoped to the caller's own rows. Neither view can be widened by
+ * a query param, because `role` selects between two fixed queries rather than
+ * parameterising one.
+ *
+ * Auth: session cookie or API-key bearer. Read-only, so no CSRF.
+ */
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+
+/** Trials whose remaining runs are at or below this share of the grant are "running low". */
+const LOW_WATER_SHARE = 1 / 3;
+
+/**
+ * Where a trial sits in its life. `exhausted` is the highest-intent state in
+ * the marketplace: the buyer used everything they were given and came back.
+ */
+export function trialState(remaining, granted) {
+ const left = Number(remaining ?? 0);
+ if (left <= 0) return 'exhausted';
+ const total = Number(granted ?? 0);
+ if (total > 0 && left / total <= LOW_WATER_SHARE) return 'running-low';
+ if (left === 1) return 'running-low';
+ return 'fresh';
+}
+
+/**
+ * Atomic token amounts are strings out of Postgres (they overflow a JS number
+ * at 2^53). Format for display without ever going through Number().
+ */
+export function formatAtomic(atomic, decimals = 6) {
+ const raw = String(atomic ?? '0').replace(/[^0-9]/g, '') || '0';
+ const d = Number.isFinite(Number(decimals)) ? Math.max(0, Math.min(18, Number(decimals))) : 6;
+ if (d === 0) return raw.replace(/^0+(?=\d)/, '');
+ const padded = raw.padStart(d + 1, '0');
+ const whole = padded.slice(0, -d).replace(/^0+(?=\d)/, '');
+ const frac = padded.slice(-d).replace(/0+$/, '');
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+ return frac ? `${grouped}.${frac}` : grouped;
+}
+
+/** Sum atomic strings without precision loss. */
+function sumAtomic(values) {
+ let total = 0n;
+ for (const v of values) {
+ const digits = String(v ?? '0').replace(/[^0-9]/g, '');
+ if (digits) total += BigInt(digits);
+ }
+ return total.toString();
+}
+
+function priceOf(row) {
+ if (row.amount === null || row.amount === undefined) return null;
+ const decimals = row.mint_decimals ?? 6;
+ return {
+ atomic: String(row.amount),
+ decimals,
+ display: formatAtomic(row.amount, decimals),
+ mint: row.currency_mint || null,
+ chain: row.chain || 'solana',
+ };
+}
+
+export async function buyerView(userId) {
+ const rows = await sql`
+ SELECT sp.id, sp.agent_id, sp.skill, sp.trial_remaining, sp.created_at, sp.updated_at,
+ ai.name AS agent_name,
+ ai.profile_image_url AS agent_image,
+ asp.trial_uses, asp.amount, asp.currency_mint, asp.chain, asp.mint_decimals
+ FROM skill_purchases sp
+ JOIN agent_identities ai
+ ON ai.id = sp.agent_id AND ai.deleted_at IS NULL
+ LEFT JOIN agent_skill_prices asp
+ ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill AND asp.is_active = true
+ WHERE sp.user_id = ${userId} AND sp.status = 'trial'
+ ORDER BY COALESCE(sp.trial_remaining, 0) ASC, sp.updated_at DESC
+ LIMIT 200
+ `;
+
+ const trials = rows.map((r) => ({
+ purchaseId: r.id,
+ agentId: r.agent_id,
+ agentName: r.agent_name,
+ agentImage: r.agent_image || null,
+ skill: r.skill,
+ trialRemaining: Number(r.trial_remaining ?? 0),
+ trialUses: r.trial_uses === null || r.trial_uses === undefined ? null : Number(r.trial_uses),
+ state: trialState(r.trial_remaining, r.trial_uses),
+ price: priceOf(r),
+ startedAt: r.created_at,
+ lastUsedAt: r.updated_at,
+ agentUrl: `/agent/${r.agent_id}`,
+ }));
+
+ return {
+ role: 'buyer',
+ trials,
+ summary: {
+ active: trials.length,
+ fresh: trials.filter((t) => t.state === 'fresh').length,
+ runningLow: trials.filter((t) => t.state === 'running-low').length,
+ exhausted: trials.filter((t) => t.state === 'exhausted').length,
+ },
+ };
+}
+
+export async function sellerView(userId) {
+ const rows = await sql`
+ SELECT sp.agent_id, sp.skill,
+ ai.name AS agent_name,
+ ai.profile_image_url AS agent_image,
+ COUNT(*)::int AS active_trials,
+ COUNT(*) FILTER (WHERE COALESCE(sp.trial_remaining, 0) <= 0)::int AS exhausted,
+ COUNT(*) FILTER (WHERE COALESCE(sp.trial_remaining, 0) = 1)::int AS last_run,
+ MAX(sp.updated_at) AS last_activity,
+ asp.trial_uses, asp.amount, asp.currency_mint, asp.chain, asp.mint_decimals
+ FROM skill_purchases sp
+ JOIN agent_identities ai
+ ON ai.id = sp.agent_id AND ai.deleted_at IS NULL
+ LEFT JOIN agent_skill_prices asp
+ ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill AND asp.is_active = true
+ WHERE ai.user_id = ${userId} AND sp.status = 'trial'
+ GROUP BY sp.agent_id, sp.skill, ai.name, ai.profile_image_url,
+ asp.trial_uses, asp.amount, asp.currency_mint, asp.chain, asp.mint_decimals
+ ORDER BY exhausted DESC, last_run DESC, active_trials DESC
+ LIMIT 200
+ `;
+
+ // Sales already made against these same skills, so the queue can be read
+ // against a real conversion rate instead of an absolute count nobody can
+ // calibrate. Scoped to the caller's agents by the same ownership join.
+ const soldRows = await sql`
+ SELECT sp.agent_id, sp.skill, COUNT(*)::int AS sold
+ FROM skill_purchases sp
+ JOIN agent_identities ai
+ ON ai.id = sp.agent_id AND ai.deleted_at IS NULL
+ WHERE ai.user_id = ${userId} AND sp.status = 'confirmed'
+ GROUP BY sp.agent_id, sp.skill
+ `;
+ const sold = new Map(soldRows.map((r) => [`${r.agent_id}::${r.skill}`, r.sold]));
+
+ const queue = rows.map((r) => {
+ const price = priceOf(r);
+ // What the buyers already at zero would pay if every one of them converted.
+ const potential = price ? (BigInt(price.atomic) * BigInt(r.exhausted)).toString() : null;
+ const soldCount = sold.get(`${r.agent_id}::${r.skill}`) || 0;
+ return {
+ agentId: r.agent_id,
+ agentName: r.agent_name,
+ agentImage: r.agent_image || null,
+ skill: r.skill,
+ activeTrials: r.active_trials,
+ exhausted: r.exhausted,
+ lastRun: r.last_run,
+ sold: soldCount,
+ conversionRate: soldCount + r.active_trials > 0 ? soldCount / (soldCount + r.active_trials) : 0,
+ trialUses: r.trial_uses === null || r.trial_uses === undefined ? null : Number(r.trial_uses),
+ lastActivity: r.last_activity,
+ price,
+ potential: price
+ ? { atomic: potential, display: formatAtomic(potential, price.decimals), mint: price.mint }
+ : null,
+ pricingUrl: `/dashboard-next/agent?id=${r.agent_id}`,
+ };
+ });
+
+ const decimals = queue.find((q) => q.price)?.price.decimals ?? 6;
+ const potentialAtomic = sumAtomic(queue.map((q) => q.potential?.atomic || '0'));
+
+ return {
+ role: 'seller',
+ queue,
+ summary: {
+ skillsWithTrials: queue.length,
+ activeTrials: queue.reduce((n, q) => n + q.activeTrials, 0),
+ warmLeads: queue.reduce((n, q) => n + q.exhausted, 0),
+ lastRun: queue.reduce((n, q) => n + q.lastRun, 0),
+ sold: queue.reduce((n, q) => n + q.sold, 0),
+ potential: { atomic: potentialAtomic, decimals, display: formatAtomic(potentialAtomic, decimals) },
+ },
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id || bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const role = new URL(req.url, 'http://x').searchParams.get('role') || 'buyer';
+ if (role !== 'buyer' && role !== 'seller') {
+ return error(res, 400, 'validation_error', "role must be 'buyer' or 'seller'");
+ }
+
+ const data = role === 'seller' ? await sellerView(userId) : await buyerView(userId);
+ res.setHeader('Cache-Control', 'private, no-store');
+ return json(res, 200, { data });
+});
diff --git a/api/mcp-policy.js b/api/mcp-policy.js
new file mode 100644
index 000000000..a8c28b337
--- /dev/null
+++ b/api/mcp-policy.js
@@ -0,0 +1,185 @@
+/**
+ * MCP trust policy — GET /api/mcp-policy
+ * ---------------------------------------
+ * GET /api/mcp-policy?profile=strict|balanced|open&format=json|claude|vscode
+ *
+ * An MCP client decides whether to run a tool without asking you by reading that
+ * tool's `readOnlyHint`. Across the ecosystem that hint is an unverified claim by
+ * the tool's own author. three.ws checks every one of its own against what the
+ * handler actually does (`npm run audit:mcp-safety`, docs/mcp-safety.md), so the
+ * labels here are the rare case where a client can safely automate on them.
+ *
+ * This endpoint turns that verification into configuration: pick how much you
+ * want automated, get back a ready-to-paste allowlist naming exactly the tools
+ * that qualify. Regenerated from public/mcp-catalog.json, which is itself
+ * generated from the tool sources, so a policy fetched today reflects the tools
+ * that exist today rather than a list someone curated once.
+ *
+ * Free, keyless, CORS-open: a policy is only useful if the client can fetch it.
+ */
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+import { cors, wrap } from './_lib/http.js';
+
+// The catalog is baked into the deployed image next to this handler, so it is
+// read once at boot rather than per request.
+const catalog = JSON.parse(
+ readFileSync(join(process.cwd(), 'public/mcp-catalog.json'), 'utf8'),
+);
+
+/**
+ * How much a caller wants automated, as a ladder. Each profile answers one
+ * question per safety class: run it, ask first, or refuse outright.
+ */
+const PROFILES = {
+ strict: {
+ label: 'Strict',
+ summary:
+ 'Automate only what is both verified read-only and free. Every write asks first, and nothing irreversible may run through this client at all.',
+ decide: (tool) => {
+ if (tool.safety === 'irreversible') return 'deny';
+ if (tool.safety === 'read' && tool.price.free) return 'allow';
+ return 'confirm';
+ },
+ },
+ balanced: {
+ label: 'Balanced',
+ summary:
+ 'Automate every verified read, including the paid ones. Anything that changes state asks first. This is the default.',
+ decide: (tool) => (tool.safety === 'read' ? 'allow' : 'confirm'),
+ },
+ open: {
+ label: 'Open',
+ summary:
+ 'Automate reads and reversible writes. Only actions that cannot be undone stop for approval.',
+ decide: (tool) => (tool.safety === 'irreversible' ? 'confirm' : 'allow'),
+ },
+};
+
+const DEFAULT_PROFILE = 'balanced';
+const FORMATS = new Set(['json', 'claude', 'vscode']);
+
+/**
+ * MCP clients namespace a tool as `mcp__<server>__<tool>` in their permission
+ * lists. The server segment is whatever name the user gave the server in their
+ * own config, so the policy states the id three.ws publishes and says so.
+ */
+const permissionId = (tool) => `mcp__${tool.server.id}__${tool.name}`;
+
+function buildPolicy(profileId) {
+ const profile = PROFILES[profileId];
+ const buckets = { allow: [], confirm: [], deny: [] };
+
+ for (const tool of catalog.tools) {
+ buckets[profile.decide(tool)].push({
+ name: tool.name,
+ permission: permissionId(tool),
+ server: tool.server.id,
+ safety: tool.safety,
+ priceUsd: tool.price.usd,
+ });
+ }
+
+ return {
+ $schema: 'https://three.ws/schemas/mcp-trust-policy.json',
+ version: 1,
+ profile: profileId,
+ profileLabel: profile.label,
+ summary: profile.summary,
+ issuer: 'https://three.ws',
+ source: 'https://three.ws/mcp-catalog.json',
+ docs: 'https://three.ws/docs/mcp-safety',
+ verification: {
+ method: 'static analysis of each tool handler',
+ check: 'npm run audit:mcp-safety',
+ claim:
+ 'Every readOnlyHint in this policy was verified against the tool handler that implements it: a tool that writes to the database, signs, sends, or settles cannot be labelled read-only in this repo without failing the build.',
+ },
+ counts: {
+ allow: buckets.allow.length,
+ confirm: buckets.confirm.length,
+ deny: buckets.deny.length,
+ total: catalog.tools.length,
+ },
+ rules: buckets,
+ };
+}
+
+/** Claude Code / Claude Desktop settings.json permission block. */
+function toClaudeSettings(policy) {
+ return {
+ $comment: `three.ws MCP trust policy (${policy.profile}). ${policy.summary} Source: ${policy.docs}`,
+ permissions: {
+ allow: policy.rules.allow.map((t) => t.permission),
+ ask: policy.rules.confirm.map((t) => t.permission),
+ deny: policy.rules.deny.map((t) => t.permission),
+ },
+ };
+}
+
+/** VS Code / Copilot style: a flat map of tool id to boolean auto-approval. */
+function toVsCodeSettings(policy) {
+ const tools = {};
+ for (const tool of policy.rules.allow) tools[tool.permission] = true;
+ for (const tool of [...policy.rules.confirm, ...policy.rules.deny]) {
+ tools[tool.permission] = false;
+ }
+ return {
+ $comment: `three.ws MCP trust policy (${policy.profile}). true = may run unattended. Source: ${policy.docs}`,
+ 'chat.tools.autoApprove': tools,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;
+
+ const url = new URL(req.url, 'http://x');
+ const profileParam = (url.searchParams.get('profile') || DEFAULT_PROFILE).toLowerCase();
+ const formatParam = (url.searchParams.get('format') || 'json').toLowerCase();
+
+ if (!PROFILES[profileParam]) {
+ res.statusCode = 400;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(
+ JSON.stringify({
+ error: `unknown profile "${profileParam}"`,
+ profiles: Object.entries(PROFILES).map(([id, p]) => ({
+ id,
+ label: p.label,
+ summary: p.summary,
+ })),
+ }),
+ );
+ return;
+ }
+
+ if (!FORMATS.has(formatParam)) {
+ res.statusCode = 400;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(
+ JSON.stringify({ error: `unknown format "${formatParam}"`, formats: [...FORMATS] }),
+ );
+ return;
+ }
+
+ const policy = buildPolicy(profileParam);
+ const body =
+ formatParam === 'claude'
+ ? toClaudeSettings(policy)
+ : formatParam === 'vscode'
+ ? toVsCodeSettings(policy)
+ : policy;
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ // The policy only changes when the deployed catalog changes, so it caches
+ // hard at the edge while staying revalidatable.
+ res.setHeader('cache-control', 'public, max-age=300, s-maxage=3600');
+ res.setHeader(
+ 'content-disposition',
+ `inline; filename="three-ws-mcp-policy-${profileParam}.json"`,
+ );
+ res.end(`${JSON.stringify(body, null, 2)}\n`);
+});
diff --git a/data/guards.json b/data/guards.json
index 17a053991..e0ede907f 100644
--- a/data/guards.json
+++ b/data/guards.json
@@ -41,8 +41,21 @@
"title": "Merge-conflict markers",
"protects": "No unresolved conflict marker can be built or deployed.",
"why": "A stash-pop conflict was once committed wholesale and reached production source. A conflict marker is a syntax error rather than a lint violation, so neither eslint nor vitest caught it. It runs first in both chains because it costs seconds and the build costs minutes.",
- "stages": ["gate", "build:gcp"],
- "needs": "none"
+ "stages": [
+ "gate",
+ "build:gcp"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A staged source file carrying an unresolved conflict marker.",
+ "stage": true,
+ "violation": {
+ "write": {
+ "src/guard-proof-conflict.js": "export const side = 'resolved';\n<<<<<<< HEAD\nexport const owner = 'ours';\n=======\nexport const owner = 'theirs';\n>>>>>>> feature\n"
+ }
+ },
+ "expect": "src/guard-proof-conflict.js"
+ }
},
{
"id": "check-claude-md",
@@ -51,8 +64,19 @@
"title": "CLAUDE.md truth check",
"protects": "Every script, path, count, and runbook step named in CLAUDE.md matches the repo.",
"why": "Agents execute CLAUDE.md verbatim, so a stale line does not read as stale, it reads as an instruction. Each claim is re-derived from its source of truth on every run: the cron count from vercel.json, the deploy chain order from the real npm script, the documented git remotes from git itself.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "CLAUDE.md telling an agent to run an npm script that does not exist.",
+ "violation": {
+ "append": {
+ "CLAUDE.md": "\n\nProof fixture: verify the toolchain with `npm run guard-proof-nonexistent`.\n"
+ }
+ },
+ "expect": "guard-proof-nonexistent"
+ }
},
{
"id": "check-rules",
@@ -61,19 +85,39 @@
"title": "Hard rules, diff scoped",
"protects": "The CLAUDE.md hard rules on the lines you actually changed.",
"why": "A repo-wide sweep is impossible because thousands of tracked files predate the rules. Reading added lines only stops the bleeding without rewriting history: your change is held to the bar, the legacy around it is left alone. It also synthesizes hunks for untracked files, which a bare git diff cannot see.",
- "stages": ["pre-push"],
- "needs": "none"
+ "stages": [
+ "pre-push"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A new source file whose added lines break a CLAUDE.md hard rule.",
+ "violation": {
+ "write": {
+ "src/guard-proof-rule.js": "// TODO: wire this up later\nexport function proofFixture() {\n\treturn null;\n}\n"
+ }
+ },
+ "expect": "src/guard-proof-rule.js"
+ }
},
{
"id": "check-cron-drift",
"script": "scripts/check-cron-drift.mjs",
"npm": "check:cron-drift",
- "npmAliases": ["check:cron-syntax"],
+ "npmAliases": [
+ "check:cron-syntax"
+ ],
"title": "Cron schedule drift",
"protects": "Every cron declared in vercel.json is a valid expression, and matches what Cloud Scheduler is actually running.",
"why": "vercel.json is a live config file: the scheduler sync seeds Cloud Scheduler from its crons array. A schedule edited without a re-sync, or a job paused by hand during an incident and never resumed, fails silently because the declared config still looks right. The offline half validates expressions and runs in the gate; the live half compares against the running jobs.",
- "stages": ["gate", "manual"],
- "needs": "gcloud"
+ "stages": [
+ "gate",
+ "manual"
+ ],
+ "needs": "gcloud",
+ "proof": {
+ "kind": "live",
+ "reason": "Compares the crons declared in vercel.json against the jobs actually deployed to Cloud Scheduler, so it needs an authenticated gcloud session and the live project. There is nothing offline to mutate."
+ }
},
{
"id": "audit-page-index",
@@ -82,8 +126,28 @@
"title": "Route documentation",
"protects": "Every human-facing route in vercel.json is documented in data/pages.json.",
"why": "data/pages.json feeds the sitemap, llms.txt, features.json, and the changelog. A page missing from it is invisible to crawlers and to the changelog, so it ships without ever being announced.",
- "stages": ["prebuild", "gate"],
- "needs": "none"
+ "stages": [
+ "prebuild",
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A public page route in vercel.json that no data/pages.json entry documents.",
+ "violation": {
+ "json": [
+ {
+ "file": "vercel.json",
+ "pointer": "routes",
+ "at": 0,
+ "insert": {
+ "src": "/guard-proof-orphan",
+ "dest": "/guard-proof-orphan.html"
+ }
+ }
+ ]
+ },
+ "expect": "guard-proof-orphan"
+ }
},
{
"id": "check-pages",
@@ -92,8 +156,23 @@
"title": "Declared pages resolve",
"protects": "Every page declared in data/pages.json is actually reachable.",
"why": "Anything listed in pages.json is advertised to crawlers the moment it lands. Two pages shipped as hard 404s in three days, each with a built dist file and no route rewrite. The local mode gates the deploy build; the base-url mode sweeps a live deployment after it.",
- "stages": ["build:gcp"],
- "needs": "none"
+ "stages": [
+ "build:gcp"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A page advertised in data/pages.json with no built file behind it.",
+ "setup": {
+ "data/pages.json": "{\n\t\"site\": {\n\t\t\"base\": \"https://three.ws\"\n\t},\n\t\"sections\": [\n\t\t{\n\t\t\t\"id\": \"main\",\n\t\t\t\"title\": \"Main\",\n\t\t\t\"description\": \"Proof fixture section.\",\n\t\t\t\"pages\": [\n\t\t\t\t{\n\t\t\t\t\t\"path\": \"/guards\",\n\t\t\t\t\t\"title\": \"Guards\",\n\t\t\t\t\t\"description\": \"Proof fixture page.\",\n\t\t\t\t\t\"priority\": 0.5,\n\t\t\t\t\t\"changefreq\": \"weekly\",\n\t\t\t\t\t\"added\": \"2026-07-31\"\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t]\n}\n",
+ "dist/guards.html": "<!doctype html><title>guards</title>\n"
+ },
+ "violation": {
+ "delete": [
+ "dist/guards.html"
+ ]
+ },
+ "expect": "unreachable page"
+ }
},
{
"id": "verify-routes",
@@ -102,8 +181,25 @@
"title": "Routing and 404 model",
"protects": "Every catalog page is reachable, unknown paths reach the designed 404, and no page route is shadowed by an earlier rule.",
"why": "The route table is evaluated in order and split at the filesystem marker, so an earlier catch-all can swallow a later literal route. A handler can be routed and still never run, which is invisible until someone reports the endpoint dead.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "Deleting the route that serves a catalogued page, so its pretty URL 404s.",
+ "violation": {
+ "json": [
+ {
+ "file": "vercel.json",
+ "pointer": "routes",
+ "removeWhere": {
+ "src": "/guards/?"
+ }
+ }
+ ]
+ },
+ "expect": "/guards"
+ }
},
{
"id": "audit-empty-handlers",
@@ -112,8 +208,20 @@
"title": "API handlers export a body",
"protects": "No API handler ships as an empty file or without an export.",
"why": "The api tree uses a dispatcher-shim pattern where a real endpoint can be a one-line re-export, which makes an accidentally empty handler look normal in review and return nothing in production.",
- "stages": ["prebuild", "gate"],
- "needs": "none"
+ "stages": [
+ "prebuild",
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "An API file that is routable but exports nothing, so it can never serve a response.",
+ "violation": {
+ "write": {
+ "api/guard-proof-empty.js": "\n"
+ }
+ },
+ "expect": "api/guard-proof-empty.js"
+ }
},
{
"id": "audit-hidden-guard",
@@ -122,8 +230,20 @@
"title": "The [hidden] guard",
"protects": "Every page resolves the CSS that makes the hidden attribute actually hide.",
"why": "The hidden HTML attribute only hides an element while some stylesheet maps it. A page that misses that rule renders its hidden scaffolding to real users. This is the verifier half of an inject-and-audit pair.",
- "stages": ["prebuild", "gate"],
- "needs": "none"
+ "stages": [
+ "prebuild",
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A product page that links no shared stylesheet, so [hidden] never hides anything.",
+ "violation": {
+ "write": {
+ "pages/guard-proof-unguarded.html": "<!doctype html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><title>Proof</title></head>\n<body><div hidden class=\"overlay\">covers everything</div></body>\n</html>\n"
+ }
+ },
+ "expect": "guard-proof-unguarded.html"
+ }
},
{
"id": "audit-docs",
@@ -132,8 +252,19 @@
"title": "Documentation integrity",
"protects": "No dead relative link, no site link that matches no route, no command naming a script that no longer exists, and no packages or workers directory without a README.",
"why": "Docs rot silently: a page gets renamed, a script gets dropped, a directory moves, and the doc that pointed at it keeps looking correct. Renaming or deleting a file is exactly when this earns its keep.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A doc whose relative link points at a file that does not exist.",
+ "violation": {
+ "write": {
+ "docs/guard-proof-dead-link.md": "# Proof fixture\n\nSee [the missing reference](./guard-proof-nowhere.md) for details.\n"
+ }
+ },
+ "expect": "guard-proof-dead-link.md"
+ }
},
{
"id": "sync-tutorial-pages",
@@ -142,8 +273,19 @@
"title": "Tutorial reachability",
"protects": "Every tutorial appears in the library manifest, has its markdown on disk, and is registered in data/pages.json, with no duplicate slugs.",
"why": "Three files have to agree for a tutorial to be both reachable and indexable, and nothing checked that they did: forty-one live tutorials were missing from the page index and invisible to search, and three had markdown with no card in the library. Run it with --write to register what is missing.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A tutorial markdown file that no manifest entry points at, so nothing can reach it.",
+ "violation": {
+ "write": {
+ "docs/tutorials/guard-proof-orphan.md": "# Proof fixture tutorial\n\nThis file exists on disk and in no index.\n"
+ }
+ },
+ "expect": "guard-proof-orphan"
+ }
},
{
"id": "audit-mcp-catalog",
@@ -152,8 +294,19 @@
"title": "MCP tool catalog freshness",
"protects": "public/mcp-catalog.json matches what the MCP servers actually expose.",
"why": "The searchable tool index at /mcp-tools renders from the generated catalog. A stale catalog advertises tools that moved, renamed, or no longer exist, which is worse than advertising nothing.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A new MCP tool landing without regenerating the public catalog.",
+ "violation": {
+ "write": {
+ "api/_mcp/tools/guard-proof-catalog.js": "export const guardProofTool = {\n\tname: 'guard_proof_catalog',\n\tdescription: 'Proof fixture tool used only inside the guard sandbox.',\n\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\tannotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n};\n"
+ }
+ },
+ "expect": "public/mcp-catalog.json is stale"
+ }
},
{
"id": "audit-x402-catalog",
@@ -162,8 +315,19 @@
"title": "x402 endpoint catalog",
"protects": "Every paid endpoint under api/x402 is documented in the public catalog.",
"why": "Each paid endpoint is a sellable product an agent can discover and call. One that exists but is undocumented earns nothing, because no buyer can find it.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A paid x402 endpoint that no buyer can find, because the catalog never mentions it.",
+ "violation": {
+ "write": {
+ "api/x402/guard-proof-endpoint.js": "export default async function handler(req, res) {\n\tres.status(200).json({ ok: true });\n}\n"
+ }
+ },
+ "expect": "guard-proof-endpoint"
+ }
},
{
"id": "audit-mcp-manifests",
@@ -172,8 +336,23 @@
"title": "MCP manifests",
"protects": "Every MCP registry manifest satisfies the official registry's rules, offline.",
"why": "The official registry enforces these rules at publish time, so a manifest that drifts past them blocks the next publish instead of failing here, where it is cheap to fix.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A registry manifest whose description exceeds the 100-character schema limit.",
+ "violation": {
+ "json": [
+ {
+ "file": "server.json",
+ "pointer": "description",
+ "set": "A deliberately overlong registry description used by the guard proof sandbox to exceed the one hundred character schema limit imposed by the registry."
+ }
+ ]
+ },
+ "expect": "[audit:mcp]"
+ }
},
{
"id": "audit-mcp-golden",
@@ -182,8 +361,19 @@
"title": "MCP golden contracts",
"protects": "Tool names, descriptions, annotations, and input schemas of every hosted MCP server, against a committed snapshot.",
"why": "That contract is what external agents integrate against, so a well-meaning description edit silently changes how other people's agents route. It parses the sources statically rather than importing them, because importing would pull in database and RPC clients.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A tool contract appearing on the wire without being declared in the golden fixture.",
+ "violation": {
+ "write": {
+ "api/_mcp/tools/guard-proof-golden.js": "export const guardProofGoldenTool = {\n\tname: 'guard_proof_golden',\n\tdescription: 'Proof fixture tool used only inside the guard sandbox.',\n\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\tannotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n};\n"
+ }
+ },
+ "expect": "[audit:mcp-golden]"
+ }
},
{
"id": "audit-mcp-safety",
@@ -192,8 +382,19 @@
"title": "MCP safety annotations",
"protects": "Every MCP tool's declared safety annotations match what its handler actually does.",
"why": "Annotations are not decoration: clients read readOnlyHint and destructiveHint to decide what may run without asking a human. A tool that writes while claiming to be read-only removes a confirmation the user was relying on.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A tool shipping with no safety annotations at all, so a client cannot judge it.",
+ "violation": {
+ "write": {
+ "api/_mcp/tools/guard-proof-safety.js": "export const guardProofSafetyTool = {\n\tname: 'guard_proof_safety',\n\tdescription: 'Proof fixture tool used only inside the guard sandbox.',\n\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\tasync handler() {\n\t\treturn { ok: true };\n\t},\n};\n"
+ }
+ },
+ "expect": "no annotations"
+ }
},
{
"id": "audit-token-drift",
@@ -202,8 +403,19 @@
"title": "Design-token ratchet",
"protects": "Hardcoded colour hexes cannot creep back past a committed baseline.",
"why": "public/tokens.css is the single source of truth for colour primitives, but a big-bang cleanup of every legacy hex is not possible. Counting violations against a baseline and failing only when the count rises makes the debt strictly decreasing.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A token-covered page hardcoding a hex that is literally a design token.",
+ "violation": {
+ "write": {
+ "pages/guard-proof-token.html": "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"><title>Proof</title>\n<link rel=\"stylesheet\" href=\"/style.css\">\n<style>\n.proof-a { color: #4ade80; }\n.proof-b { color: #f87171; }\n</style>\n</head>\n<body><p class=\"proof-a\">fixture</p></body>\n</html>\n"
+ }
+ },
+ "expect": "design-token drift increased"
+ }
},
{
"id": "check-browser-graph",
@@ -212,8 +424,19 @@
"title": "Browser bundle purity",
"protects": "No Node-only module leaks into the browser bundle.",
"why": "A Node builtin pulled into browser code does not fail the build, it fails at runtime in the user's tab, usually on a page nobody tested after the import was added.",
- "stages": ["build:gcp"],
- "needs": "none"
+ "stages": [
+ "build:gcp"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A Node built-in reaching the browser bundle through a real import chain.",
+ "violation": {
+ "append": {
+ "src/agent-skills.js": "\nimport 'node:zlib';\n"
+ }
+ },
+ "expect": "node:zlib"
+ }
},
{
"id": "check-dist",
@@ -222,8 +445,24 @@
"title": "Build output shape",
"protects": "dist/ contains every artifact the deploy expects, including the UMD library bundle.",
"why": "The frontend build empties dist/, so anything written before it is destroyed. This fails the build when the order was wrong instead of shipping an image missing its pages or its library.",
- "stages": ["build:gcp"],
- "needs": "none"
+ "stages": [
+ "build:gcp"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A build that finished without producing the published embed bundle.",
+ "setup": {
+ "dist/agent-3d/latest/agent-3d.js": "export const proof = 1;\n",
+ "dist/agent-3d/latest/agent-3d.umd.cjs": "module.exports = { proof: 1 };\n",
+ "dist/agent-3d/versions.json": "{\"latest\":\"0.0.0-proof\"}\n"
+ },
+ "violation": {
+ "delete": [
+ "dist/agent-3d/latest/agent-3d.umd.cjs"
+ ]
+ },
+ "expect": "[check-dist] MISSING"
+ }
},
{
"id": "audit-deploy-artifacts",
@@ -232,8 +471,20 @@
"title": "Deploy artifact preflight",
"protects": "The two artifact failure classes that have taken production down.",
"why": "Both are invisible in a diff and obvious in seconds if something looks. Running it before a submit costs nothing next to a failed Cloud Build.",
- "stages": ["manual"],
- "needs": "none"
+ "stages": [
+ "manual"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A symlink committed to the index, which the deploy bundler cannot resolve.",
+ "stage": true,
+ "violation": {
+ "link": {
+ "data/guard-proof-link.md": "../README.md"
+ }
+ },
+ "expect": "guard-proof-link.md"
+ }
},
{
"id": "check-gcloudignore",
@@ -242,8 +493,19 @@
"title": "Cloud Build upload contents",
"protects": "What `gcloud builds submit` would actually upload.",
"why": "An over-broad ignore file silently drops a file the build needs; an under-broad one uploads gigabytes of node_modules and times out. Neither is visible until the build runs.",
- "stages": ["manual"],
- "needs": "gcloud"
+ "stages": [
+ "manual"
+ ],
+ "needs": "gcloud",
+ "proof": {
+ "summary": "A missing .gcloudignore, which silently hands the upload set back to .gitignore.",
+ "violation": {
+ "delete": [
+ ".gcloudignore"
+ ]
+ },
+ "expect": "ignore file not found"
+ }
},
{
"id": "audit-links",
@@ -252,8 +514,19 @@
"title": "Site link integrity",
"protects": "Every navigable target across pages, public, and src resolves to a real route or file.",
"why": "It resolves each link against the real routing model rather than assuming the catch-all rules count as proof, so a dead internal path cannot hide behind a wildcard that would serve a 404 page.",
- "stages": ["manual"],
- "needs": "none"
+ "stages": [
+ "manual"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A page linking to a route that resolves to nothing.",
+ "violation": {
+ "write": {
+ "pages/guard-proof-deadlink.html": "<!doctype html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><title>Proof</title><link rel=\"stylesheet\" href=\"/style.css\"></head>\n<body><a href=\"/guard-proof-nowhere\">go nowhere</a></body>\n</html>\n"
+ }
+ },
+ "expect": "guard-proof-nowhere"
+ }
},
{
"id": "audit-console",
@@ -262,8 +535,14 @@
"title": "Console sweep",
"protects": "A clean browser console on every canonical route, at desktop and mobile widths.",
"why": "A clean console is part of the definition of done, and the only way to prove it is to drive the real pages in a real browser. Environment noise is filtered so the output is signal.",
- "stages": ["manual"],
- "needs": "browser"
+ "stages": [
+ "manual"
+ ],
+ "needs": "browser",
+ "proof": {
+ "kind": "live",
+ "reason": "Drives a real browser over the live page set and reads the console, so it needs Playwright and a running server. A static fixture cannot produce a runtime console error."
+ }
},
{
"id": "audit-image-loading",
@@ -272,8 +551,19 @@
"title": "Image loading attributes",
"protects": "Every JS-rendered image sets its loading and decoding attributes.",
"why": "These images pull remote thumbnails and avatars. Without the attributes the browser blocks rendering on images far below the fold, which shows up as a slow page rather than as an error.",
- "stages": ["manual"],
- "needs": "none"
+ "stages": [
+ "manual"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A JS-rendered image with no loading attribute, which fetches eagerly off-screen.",
+ "violation": {
+ "write": {
+ "src/guard-proof-img.js": "export function proofThumb(url) {\n\treturn `<img src=\"${url}\" alt=\"proof\">`;\n}\n"
+ }
+ },
+ "expect": "guard-proof-img.js"
+ }
},
{
"id": "audit-garments",
@@ -282,8 +572,14 @@
"title": "Wardrobe catalog integrity",
"protects": "Every garment in the live catalog validates, and its GLB hash matches its manifest.",
"why": "It runs the same validation the closet runs at consume time, against the real fetched asset, so a re-uploaded or corrupted GLB is caught before a user wears it.",
- "stages": ["manual"],
- "needs": "network"
+ "stages": [
+ "manual"
+ ],
+ "needs": "network",
+ "proof": {
+ "kind": "live",
+ "reason": "Fetches every published garment asset over the network and inspects the returned GLB, so there is no offline input to mutate."
+ }
},
{
"id": "audit-rig-coverage",
@@ -292,8 +588,14 @@
"title": "Rig coverage",
"protects": "How well the canonicalizer maps the skeletons actually stored in production.",
"why": "The bone-name tables grew by anticipating rig conventions, and anticipation is not evidence. This walks real avatars and ranks the unmapped bone names by frequency, so the next mapping to add is a measurement rather than a guess.",
- "stages": ["manual"],
- "needs": "credentials"
+ "stages": [
+ "manual"
+ ],
+ "needs": "credentials",
+ "proof": {
+ "kind": "live",
+ "reason": "Loads real avatar rigs from production storage and retargets clips onto them, which needs live credentials and the model bucket."
+ }
},
{
"id": "audit-service-wallets",
@@ -302,8 +604,14 @@
"title": "Service wallet configuration",
"protects": "Every platform wallet's on-chain balance, its floor, and whether the advertised x402 fee payer matches the secret we actually co-sign with.",
"why": "An advertised fee-payer that does not match the configured secret silently 502s paid endpoints, and a wallet under its floor pauses its engine. Both look identical from outside and have different fixes.",
- "stages": ["manual"],
- "needs": "credentials"
+ "stages": [
+ "manual"
+ ],
+ "needs": "credentials",
+ "proof": {
+ "kind": "live",
+ "reason": "Reads live balances for the service wallets over RPC using the production keys in .env."
+ }
},
{
"id": "audit-wallet-flows",
@@ -312,8 +620,14 @@
"title": "Fleet wallet flows",
"protects": "Where the platform's SOL is, where it has been going, and whether any of it is leaking.",
"why": "Every time the paid rail goes dry the first theory is a leak. This separates the three real answers by measurement: capital dispersed into agent wallets, a starved fee floor, and an actual unexplained debit.",
- "stages": ["manual"],
- "needs": "credentials"
+ "stages": [
+ "manual"
+ ],
+ "needs": "credentials",
+ "proof": {
+ "kind": "live",
+ "reason": "Reconstructs on-chain transfer history for the fleet wallets from live RPC, so it has no offline input."
+ }
},
{
"id": "check-relayer-balances",
@@ -322,8 +636,14 @@
"title": "Relayer balances",
"protects": "Every configured Solana signer is above its documented minimum.",
"why": "The operator companion to the balance watchdog cron, run on demand from a machine that holds the signer secrets. Unconfigured signers are listed explicitly so the real deployment's holdings are visible at a glance.",
- "stages": ["manual"],
- "needs": "credentials"
+ "stages": [
+ "manual"
+ ],
+ "needs": "credentials",
+ "proof": {
+ "kind": "live",
+ "reason": "Queries the funded relayer accounts over RPC and compares them against the operating floor, which only exists on-chain."
+ }
},
{
"id": "audit-guards",
@@ -332,8 +652,23 @@
"title": "The guard registry itself",
"protects": "Every entry in this file names a real script and a real npm script, every guard on disk is registered, and every stage claim matches the npm chain that would actually run it.",
"why": "This registry is rendered by docs/guards.md and by /guards, so a stale stage column does not read as stale, it reads as coverage a reader then stops looking for. Listing itself is not circular: it verifies its own script, npm binding, and gate membership exactly like every other entry.",
- "stages": ["gate"],
- "needs": "none"
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A registry entry naming a guard script that is not in the repository.",
+ "violation": {
+ "json": [
+ {
+ "file": "data/guards.json",
+ "pointer": "guards.0.script",
+ "set": "scripts/guard-proof-missing.mjs"
+ }
+ ]
+ },
+ "expect": "scripts/guard-proof-missing.mjs"
+ }
},
{
"id": "check-erc7710-addresses",
@@ -342,8 +677,14 @@
"title": "Delegation contract addresses",
"protects": "Every address in the delegation-manager deployment table is a deployed contract on its chain.",
"why": "A wrong or undeployed address fails only at the moment a user signs, which is the worst possible time to discover a typo in a constant.",
- "stages": ["manual"],
- "needs": "network"
+ "stages": [
+ "manual"
+ ],
+ "needs": "network",
+ "proof": {
+ "kind": "live",
+ "reason": "Resolves the delegation-framework contract addresses against live chain RPC, so the values it compares only exist on-chain."
+ }
}
],
"exempt": [
diff --git a/docs/tutorials/sell-a-skill-with-a-trial.md b/docs/tutorials/sell-a-skill-with-a-trial.md
index 14cbb6177..f1762a68d 100644
--- a/docs/tutorials/sell-a-skill-with-a-trial.md
+++ b/docs/tutorials/sell-a-skill-with-a-trial.md
@@ -4,7 +4,7 @@ By the end of this tutorial your agent will have a skill listed for sale in $THR
The interesting part is not the listing. It is the middle. A free trial that never runs out is not a funnel, it is a permanent giveaway, and it will quietly make the skill unsellable to the very people who liked it enough to try it. This tutorial shows you the meter that prevents that.
-**Prerequisites:** an agent you own (make one at [/create](/create)), an API key with the `agents:write` scope from [/settings](/settings), and a second signed-in account to play the buyer. Everything here runs against the live API with `curl`.
+**Prerequisites:** an agent you own (make one at [/create](/create)), an API key with the `agents:write` scope from [/settings](/settings), and a second account with its own key to play the buyer. Everything here runs against the live API with `curl` and two bearer tokens. Nothing needs a browser.
**Time:** about 15 minutes.
@@ -33,8 +33,14 @@ Three free runs, then a real payment. That is the whole shape.
Pricing lives on the agent, not on a global catalog. One `PUT` replaces the agent's full price list, so send every skill you want listed in the same call.
```bash
-export THREE_WS_KEY="sk_live_…" # from /settings, scope agents:write
-export AGENT_ID="00000000-0000-0000-0000-000000000000" # your agent's uuid
+export THREE_WS_KEY="sk_live_…" # /settings → API keys, scope agents:write
+
+# Your agent's uuid. /api/agents/me returns the agent that key owns, so you
+# never have to copy a uuid by hand. (It is also the last path segment of the
+# agent's profile URL if you would rather read it off the page.)
+export AGENT_ID=$(curl -s 'https://three.ws/api/agents/me' \
+ -H "Authorization: Bearer $THREE_WS_KEY" \
+ | node -pe 'JSON.parse(require("fs").readFileSync(0)).agent.id')
curl -X PUT "https://three.ws/api/agents/$AGENT_ID/skills-pricing" \
-H "Authorization: Bearer $THREE_WS_KEY" \
@@ -52,7 +58,7 @@ curl -X PUT "https://three.ws/api/agents/$AGENT_ID/skills-pricing" \
`amount` is in **atomic units** of `currency_mint`, not whole tokens. `trial_uses` accepts 0 to 10; `0` means no trial is offered and `start-trial` will refuse with `422 no_trials`.
-A bearer token is exempt from CSRF, which is why this is one clean `curl`. The same call from a browser session needs an `X-CSRF-Token` header (fetch one from `/api/csrf-token`).
+Every call in this tutorial is authenticated the same way: one `Authorization: Bearer` header. Bearer tokens are exempt from CSRF because the header is proof of intent and browsers never attach it automatically, so there is no cookie to scrape and no token to mint. If you drive these endpoints from a signed-in browser session instead, each write needs an `X-CSRF-Token` header holding a token from `GET /api/csrf-token`.
> **Why `PUT` and not `POST`.** The body is the complete desired state of the agent's pricing. A skill you omit is delisted. That is deliberate: it makes the pricing page idempotent and impossible to leave half-updated.
@@ -67,13 +73,17 @@ curl -s "https://three.ws/api/agents/$AGENT_ID/skills-pricing" \
## 2. The buyer takes a trial
-Now switch to the buyer account. This one is session-authenticated, so it needs the CSRF header.
+Now switch to the buyer account. Make a key on that account the same way, and resolve its agent the same way:
```bash
+export BUYER_KEY="sk_live_…" # the BUYER's key, not yours
+export BUYER_AGENT_ID=$(curl -s 'https://three.ws/api/agents/me' \
+ -H "Authorization: Bearer $BUYER_KEY" \
+ | node -pe 'JSON.parse(require("fs").readFileSync(0)).agent.id')
+
curl -X POST 'https://three.ws/api/marketplace/start-trial' \
-H 'Content-Type: application/json' \
- -H "X-CSRF-Token: $CSRF" \
- --cookie "$BUYER_COOKIE" \
+ -H "Authorization: Bearer $BUYER_KEY" \
-d "{\"agent_id\":\"$AGENT_ID\",\"skill\":\"methods-brief\"}"
```
@@ -122,7 +132,7 @@ After the third call, the access check flips:
```bash
curl -s "https://three.ws/api/marketplace/check-skill-access?agent_id=$AGENT_ID&skill=methods-brief" \
- --cookie "$BUYER_COOKIE"
+ -H "Authorization: Bearer $BUYER_KEY"
```
```json
@@ -136,8 +146,7 @@ An agent buying on its own behalf settles in one request from its custodial wall
```bash
curl -X POST 'https://three.ws/api/marketplace/purchase-as-agent' \
-H 'Content-Type: application/json' \
- -H "X-CSRF-Token: $CSRF" \
- --cookie "$BUYER_COOKIE" \
+ -H "Authorization: Bearer $BUYER_KEY" \
-d "{\"buyer_agent_id\":\"$BUYER_AGENT_ID\",\"seller_agent_id\":\"$AGENT_ID\",\"skill\":\"methods-brief\"}"
```
diff --git a/pages/mcp-tools.html b/pages/mcp-tools.html
index fba06067a..642b3dfb7 100644
--- a/pages/mcp-tools.html
+++ b/pages/mcp-tools.html
@@ -108,6 +108,48 @@
.mc-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.mc-reset { margin-left: auto; }
+ /* ── trust policy ───────────────────────────────────────────────── */
+ .mc-policy {
+ border: 1px solid var(--stroke); border-radius: var(--radius-lg, 14px);
+ background: linear-gradient(180deg, var(--surface-2, rgba(255,255,255,0.05)), transparent 65%);
+ padding: 20px 20px 22px; margin: 0 0 26px;
+ }
+ .mc-policy-head h2 { margin: 0 0 8px; font-size: 1.15rem; letter-spacing: -0.01em; color: var(--ink-bright, var(--ink)); }
+ .mc-policy-head p { margin: 0; max-width: 74ch; font-size: 0.89rem; line-height: 1.6; color: var(--ink-dim); }
+ .mc-policy-head a { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+ .mc-policy-head a:hover { color: var(--ink-bright, var(--ink)); }
+
+ .mc-policy-profiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 10px; margin: 16px 0 18px; }
+ .mc-prof {
+ display: flex; flex-direction: column; gap: 5px; text-align: left; font: inherit; cursor: pointer;
+ padding: 13px 14px; color: var(--ink); background: var(--surface-1, rgba(255,255,255,0.03));
+ border: 1px solid var(--stroke); border-radius: var(--radius-md, 10px);
+ transition: border-color 0.15s ease, background 0.15s ease;
+ }
+ .mc-prof:hover { border-color: var(--stroke-strong); background: var(--surface-2, rgba(255,255,255,0.06)); }
+ .mc-prof:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .mc-prof[aria-checked="true"] { border-color: var(--accent); background: var(--accent-soft, var(--surface-3)); }
+ .mc-prof-name { font-weight: 650; font-size: 0.92rem; color: var(--ink-bright, var(--ink)); }
+ .mc-prof-name em { font-style: normal; font-size: 0.68rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--accent); margin-left: 6px; }
+ .mc-prof-desc { font-size: 0.8rem; line-height: 1.45; color: var(--ink-dim); }
+ .mc-prof-counts { font-size: 0.74rem; font-variant-numeric: tabular-nums; color: var(--ink-faint, var(--ink-dim)); margin-top: 2px; }
+
+ .mc-policy-tabs { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
+ .mc-tab {
+ font: inherit; font-size: 0.8rem; padding: 5px 12px; cursor: pointer; color: var(--ink-dim);
+ background: transparent; border: 1px solid var(--stroke); border-radius: 999px;
+ transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease;
+ }
+ .mc-tab:hover { color: var(--ink); border-color: var(--stroke-strong); }
+ .mc-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .mc-tab[aria-selected="true"] { color: var(--ink-bright, var(--ink)); border-color: currentColor; background: var(--surface-3, rgba(255,255,255,0.08)); }
+ .mc-policy-where { margin: 0 0 10px; font-size: 0.8rem; color: var(--ink-dim); }
+ .mc-policy-where code { font-family: var(--font-mono, ui-monospace, monospace); color: var(--ink); }
+ .mc-policy-out .mc-snippet pre { max-height: 260px; overflow: auto; }
+ .mc-policy-live { margin: 10px 0 0; font-size: 0.78rem; line-height: 1.5; color: var(--ink-faint, var(--ink-dim)); }
+ .mc-policy-live a { color: var(--ink-dim); font-family: var(--font-mono, ui-monospace, monospace); }
+ .mc-policy-live a:hover { color: var(--ink); }
+
.mc-count { font-size: 0.85rem; color: var(--ink-dim); margin: 0 0 14px; font-variant-numeric: tabular-nums; }
/* ── tool grid ──────────────────────────────────────────────────── */
@@ -251,6 +293,57 @@
</div>
</div>
+ <section class="mc-policy" id="mc-policy" aria-labelledby="mc-policy-h">
+ <div class="mc-policy-head">
+ <div>
+ <h2 id="mc-policy-h">Let your assistant run the safe ones by itself</h2>
+ <p>
+ Your AI client decides whether to run a tool without asking you by trusting its
+ read-only label. Everywhere else that label is the tool author's own word for it.
+ Here it is <a href="/docs/mcp-safety">checked against the code on every build</a>,
+ so it is worth automating on. Pick how much you want automated and paste the result
+ into your client.
+ </p>
+ </div>
+ </div>
+
+ <div class="mc-policy-profiles" role="radiogroup" aria-label="How much to automate">
+ <button type="button" class="mc-prof" data-profile="strict" role="radio" aria-checked="false">
+ <span class="mc-prof-name">Strict</span>
+ <span class="mc-prof-desc">Only free, verified reads run by themselves. Nothing irreversible may run at all.</span>
+ <span class="mc-prof-counts" data-counts></span>
+ </button>
+ <button type="button" class="mc-prof" data-profile="balanced" role="radio" aria-checked="true">
+ <span class="mc-prof-name">Balanced <em>recommended</em></span>
+ <span class="mc-prof-desc">Every verified read runs. Anything that changes state asks first.</span>
+ <span class="mc-prof-counts" data-counts></span>
+ </button>
+ <button type="button" class="mc-prof" data-profile="open" role="radio" aria-checked="false">
+ <span class="mc-prof-name">Open</span>
+ <span class="mc-prof-desc">Reads and reversible writes run. Only the un-undoable stops for you.</span>
+ <span class="mc-prof-counts" data-counts></span>
+ </button>
+ </div>
+
+ <div class="mc-policy-out">
+ <div class="mc-policy-tabs" role="tablist" aria-label="Client format">
+ <button type="button" class="mc-tab" data-format="claude" role="tab" aria-selected="true">Claude</button>
+ <button type="button" class="mc-tab" data-format="vscode" role="tab" aria-selected="false">VS Code</button>
+ <button type="button" class="mc-tab" data-format="json" role="tab" aria-selected="false">Portable JSON</button>
+ </div>
+ <p class="mc-policy-where" id="mc-policy-where"></p>
+ <div class="mc-snippet">
+ <pre><code id="mc-policy-code">Loading the policy…</code></pre>
+ <button type="button" class="mc-btn mc-copy" id="mc-policy-copy">Copy</button>
+ </div>
+ <p class="mc-policy-live">
+ Always current: <a id="mc-policy-url" href="/api/mcp-policy">/api/mcp-policy</a> returns
+ this same document, so a client can refetch it instead of pinning a copy that goes stale
+ as tools are added.
+ </p>
+ </div>
+ </section>
+
<p class="mc-count" id="mc-count" role="status" aria-live="polite"></p>
<div class="mc-grid" id="mc-grid"></div>
</main>
@@ -581,6 +674,123 @@
}
});
+ // ── trust policy ──────────────────────────────────────────────────
+ // The decision (which tools may run unattended) belongs to /api/mcp-policy
+ // and is fetched, never re-implemented here: a second copy of those rules
+ // in the page would drift from the endpoint a client actually consumes.
+ // Only the per-client formatting below is presentational, derived from the
+ // buckets the endpoint returns.
+ const WHERE = {
+ claude: 'Paste into <code>.claude/settings.json</code> in your project, or your user settings.',
+ vscode: 'Paste into VS Code <code>settings.json</code>.',
+ json: 'The portable document, for any client that can read an allowlist.',
+ };
+
+ const policyState = { profile: 'balanced', format: 'claude' };
+ const policyCache = new Map();
+ const codeEl = () => document.getElementById('mc-policy-code');
+
+ async function loadPolicy(profile) {
+ if (policyCache.has(profile)) return policyCache.get(profile);
+ const res = await fetch(`/api/mcp-policy?profile=${encodeURIComponent(profile)}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`the policy endpoint returned ${res.status}`);
+ const doc = await res.json();
+ policyCache.set(profile, doc);
+ return doc;
+ }
+
+ /** Shape one policy document for a specific client's settings file. */
+ function formatPolicy(doc, format) {
+ const ids = (bucket) => doc.rules[bucket].map((t) => t.permission);
+ if (format === 'claude') {
+ return { permissions: { allow: ids('allow'), ask: ids('confirm'), deny: ids('deny') } };
+ }
+ if (format === 'vscode') {
+ const tools = {};
+ for (const id of ids('allow')) tools[id] = true;
+ for (const id of [...ids('confirm'), ...ids('deny')]) tools[id] = false;
+ return { 'chat.tools.autoApprove': tools };
+ }
+ return doc;
+ }
+
+ let policyText = '';
+
+ async function renderPolicy() {
+ for (const btn of document.querySelectorAll('.mc-prof')) {
+ btn.setAttribute('aria-checked', String(btn.dataset.profile === policyState.profile));
+ }
+ for (const tab of document.querySelectorAll('.mc-tab')) {
+ tab.setAttribute('aria-selected', String(tab.dataset.format === policyState.format));
+ }
+ document.getElementById('mc-policy-where').innerHTML = WHERE[policyState.format];
+
+ const link = document.getElementById('mc-policy-url');
+ const href = `/api/mcp-policy?profile=${policyState.profile}&format=${policyState.format}`;
+ link.href = href;
+ link.textContent = href;
+
+ let doc;
+ try {
+ doc = await loadPolicy(policyState.profile);
+ } catch (error) {
+ policyText = '';
+ codeEl().textContent =
+ `Could not load the policy: ${error.message}.\nFetch it directly at ${href}`;
+ return;
+ }
+
+ policyText = JSON.stringify(formatPolicy(doc, policyState.format), null, 2);
+ codeEl().textContent = policyText;
+
+ // Each profile advertises its own split, so the trade-off is visible
+ // before you pick. Fetched lazily; the active one is always accurate.
+ for (const btn of document.querySelectorAll('.mc-prof')) {
+ const cached = policyCache.get(btn.dataset.profile);
+ if (!cached) continue;
+ const c = cached.counts;
+ btn.querySelector('[data-counts]').textContent =
+ `${c.allow} run on their own · ${c.confirm} ask` + (c.deny ? ` · ${c.deny} blocked` : '');
+ }
+ }
+
+ /** Warm the other profiles so their counts appear without a click. */
+ async function warmPolicyCounts() {
+ await Promise.all(
+ ['strict', 'balanced', 'open'].map((p) => loadPolicy(p).catch(() => null)),
+ );
+ renderPolicy();
+ }
+
+ for (const btn of document.querySelectorAll('.mc-prof')) {
+ btn.addEventListener('click', () => {
+ policyState.profile = btn.dataset.profile;
+ renderPolicy();
+ });
+ }
+ for (const tab of document.querySelectorAll('.mc-tab')) {
+ tab.addEventListener('click', () => {
+ policyState.format = tab.dataset.format;
+ renderPolicy();
+ });
+ }
+
+ document.getElementById('mc-policy-copy').addEventListener('click', async (event) => {
+ const btn = event.currentTarget;
+ if (!policyText) return;
+ try {
+ await navigator.clipboard.writeText(policyText);
+ btn.textContent = 'Copied';
+ } catch {
+ btn.textContent = 'Select and copy';
+ }
+ setTimeout(() => {
+ btn.textContent = 'Copy';
+ }, 1600);
+ });
+
// ── load ──────────────────────────────────────────────────────────
async function load() {
renderSkeleton();
@@ -606,6 +816,7 @@
readUrl();
syncChips();
render();
+ warmPolicyCounts();
const linked = new URLSearchParams(location.search).get('tool');
if (linked) {
diff --git a/public/mcp-catalog.json b/public/mcp-catalog.json
index e9ccf62b3..44d7ad51d 100644
--- a/public/mcp-catalog.json
+++ b/public/mcp-catalog.json
@@ -2,11 +2,11 @@
"$comment": "Generated by scripts/build-mcp-catalog.mjs from the tool definitions and price maps in this repo. Do not edit by hand: npm run build:mcp-catalog regenerates it and npm run audit:mcp-catalog fails the build when it is stale.",
"docs": "https://three.ws/docs/mcp-safety",
"counts": {
- "tools": 270,
+ "tools": 272,
"servers": 36,
- "free": 242,
+ "free": 244,
"paid": 28,
- "read": 181,
+ "read": 183,
"write": 70,
"irreversible": 19
},
@@ -225,7 +225,7 @@
"endpoint": "/api/mcp",
"transport": "remote",
"auth": "oauth-or-x402",
- "tools": 43
+ "tools": 45
},
{
"id": "threews-3d-studio",
@@ -4190,6 +4190,30 @@
},
"source": "api/_mcp/tools/avatars.js"
},
+ {
+ "name": "list_sign_vocabulary",
+ "title": "List the ASL vocabulary",
+ "description": "List every word three.ws avatars have a real American Sign Language sign for, with a plain description of the handshape, place on the body, and movement each one performs. Words outside this list are fingerspelled letter by letter instead. Use it to know in advance what a phrase will sign versus spell.",
+ "server": {
+ "id": "three.ws",
+ "title": "three.ws",
+ "endpoint": "/api/mcp",
+ "transport": "remote",
+ "auth": "oauth-or-x402"
+ },
+ "safety": "read",
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false
+ },
+ "price": {
+ "usd": 0,
+ "free": true
+ },
+ "source": "api/_mcp/tools/sign.js"
+ },
{
"name": "mint_3d_asset",
"title": "Mint a 3D asset as a Solana NFT",
@@ -4574,6 +4598,30 @@
},
"source": "api/_mcp/tools/avatars.js"
},
+ {
+ "name": "sign_text",
+ "title": "Sign text in ASL",
+ "description": "Compile English text into one continuous American Sign Language performance for a 3D avatar. Words with a real sign are signed; everything else is fingerspelled, in the same clip. Returns the performed timeline (every word, whether it signed or spelled, the seconds it occupies, and where each spelled letter lands) plus a link that plays it on a live avatar. Set include_clip to also get the three.js AnimationClip document, keyed to the canonical humanoid skeleton, to retarget onto any rigged avatar and play.",
+ "server": {
+ "id": "three.ws",
+ "title": "three.ws",
+ "endpoint": "/api/mcp",
+ "transport": "remote",
+ "auth": "oauth-or-x402"
+ },
+ "safety": "read",
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false
+ },
+ "price": {
+ "usd": 0,
+ "free": true
+ },
+ "source": "api/_mcp/tools/sign.js"
+ },
{
"name": "solana_agent_attestations",
"title": "List Solana agent attestations",
diff --git a/scripts/lib/guard-proofs.mjs b/scripts/lib/guard-proofs.mjs
new file mode 100644
index 000000000..2bb602712
--- /dev/null
+++ b/scripts/lib/guard-proofs.mjs
@@ -0,0 +1,383 @@
+// Shared vocabulary for guard proofs: the sandbox, the fixture applier, and the
+// verdict model. scripts/prove-guards.mjs drives it, scripts/audit-guards.mjs
+// validates the declarations against it, and tests/prove-guards.test.js
+// exercises it without touching the real repository.
+//
+// A "proof" answers a question the guard registry could not: does this guard
+// still catch the thing it claims to catch? A registry entry is a claim. A
+// proof is evidence. The difference matters because a guard can rot into a
+// no-op (a renamed directory it no longer scans, a regex that stopped matching,
+// an exclusion list that grew until it excluded everything) and still exit 0
+// forever, which reads exactly like success.
+//
+// Every proof is TWO-SIDED, and that is the whole point:
+//
+// control the sandbox is arranged so the guard MUST pass (exit 0)
+// violation one surgical mutation is applied and the guard MUST fail,
+// with a failure message that names the right reason
+//
+// A one-sided proof is worthless. "The guard exited non-zero" also happens when
+// the sandbox is broken, when a dependency is missing, or when an unrelated
+// pre-existing violation is sitting in the tree. Requiring exit 0 first pins
+// the guard to a known-clean baseline, so the non-zero exit afterwards is
+// attributable to the mutation and nothing else. Requiring the output to
+// contain an expected fragment closes the last hole: a guard that fails for the
+// wrong reason is not a working guard.
+
+import { spawnSync } from 'node:child_process';
+import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+/** Verdicts a proof run can produce, worst first. Order is the report order. */
+export const VERDICTS = {
+ CONTROL_FAILED: 'control-failed',
+ NOT_CAUGHT: 'not-caught',
+ WRONG_REASON: 'wrong-reason',
+ PROVEN: 'proven',
+ DECLARED_LIVE: 'declared-live',
+};
+
+/** Verdicts that mean the guard is not demonstrably working. */
+export const FAILING_VERDICTS = new Set([
+ VERDICTS.CONTROL_FAILED,
+ VERDICTS.NOT_CAUGHT,
+ VERDICTS.WRONG_REASON,
+]);
+
+/**
+ * Normalize a declared proof into the shape the runner executes.
+ * Throws on a malformed declaration so the auditor can report it precisely.
+ */
+export function normalizeProof(guard) {
+ const proof = guard.proof;
+ if (!proof || typeof proof !== 'object') {
+ throw new Error(`guard "${guard.id}" has no proof block`);
+ }
+ if (proof.kind === 'live') {
+ if (!proof.reason || typeof proof.reason !== 'string') {
+ throw new Error(`guard "${guard.id}" declares kind:"live" without a reason`);
+ }
+ return { kind: 'live', reason: proof.reason };
+ }
+ if (!proof.summary || typeof proof.summary !== 'string') {
+ throw new Error(`guard "${guard.id}" proof needs a summary`);
+ }
+ const violation = proof.violation;
+ if (!violation || typeof violation !== 'object') {
+ throw new Error(`guard "${guard.id}" proof needs a violation block`);
+ }
+ const writes = violation.write ?? {};
+ const appends = violation.append ?? {};
+ const deletes = violation.delete ?? [];
+ const links = violation.link ?? {};
+ const jsonOps = violation.json ?? [];
+ if (!Array.isArray(deletes)) {
+ throw new Error(`guard "${guard.id}" violation.delete must be an array`);
+ }
+ if (!Array.isArray(jsonOps)) {
+ throw new Error(`guard "${guard.id}" violation.json must be an array`);
+ }
+ const mutations =
+ Object.keys(writes).length +
+ Object.keys(appends).length +
+ Object.keys(links).length +
+ deletes.length +
+ jsonOps.length;
+ if (!mutations) throw new Error(`guard "${guard.id}" violation mutates nothing`);
+ for (const op of jsonOps) {
+ if (!op || typeof op.file !== 'string' || typeof op.pointer !== 'string') {
+ throw new Error(`guard "${guard.id}" json op needs file + pointer`);
+ }
+ const kinds = ['insert', 'set', 'removeWhere'].filter((k) => k in op);
+ if (kinds.length !== 1) {
+ throw new Error(`guard "${guard.id}" json op needs exactly one of insert/set/removeWhere`);
+ }
+ }
+ if (!proof.expect || typeof proof.expect !== 'string') {
+ throw new Error(`guard "${guard.id}" proof needs an expect fragment`);
+ }
+ return {
+ kind: 'mutation',
+ summary: proof.summary,
+ setup: proof.setup ?? {},
+ stage: proof.stage === true,
+ violation: { write: writes, append: appends, delete: deletes, link: links, json: jsonOps },
+ expect: proof.expect,
+ };
+}
+
+/** Every sandbox path a proof reads or writes, for snapshot and restore. */
+export function touchedPaths(proof) {
+ if (proof.kind === 'live') return [];
+ return [
+ ...Object.keys(proof.setup),
+ ...Object.keys(proof.violation.write),
+ ...Object.keys(proof.violation.append),
+ ...Object.keys(proof.violation.link),
+ ...proof.violation.json.map((op) => op.file),
+ ...proof.violation.delete,
+ ];
+}
+
+/** Capture the current bytes of each path (null when absent). */
+export function snapshot(root, paths) {
+ const saved = new Map();
+ for (const rel of paths) {
+ if (saved.has(rel)) continue;
+ const abs = path.join(root, rel);
+ // lstat, not existsSync: a proof may replace a path with a symlink, and
+ // following it would snapshot the target's bytes and then restore them
+ // over the link's location.
+ let stat = null;
+ try {
+ stat = lstatSync(abs);
+ } catch {
+ stat = null;
+ }
+ saved.set(rel, stat?.isFile() ? readFileSync(abs) : null);
+ }
+ return saved;
+}
+
+/** Put every captured path back exactly as it was. */
+export function restore(root, saved) {
+ for (const [rel, bytes] of saved) {
+ const abs = path.join(root, rel);
+ if (bytes === null) {
+ rmSync(abs, { force: true });
+ } else {
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, bytes);
+ }
+ }
+}
+
+/**
+ * Render a fixture body.
+ *
+ * Two escapes exist because the alternative is a fixture that rots:
+ * {{pkg.version}} the repo's current version. check-dist compares
+ * dist/agent-3d/versions.json against package.json, so a
+ * hardcoded version would make the proof fail on the next
+ * release rather than when the guard breaks.
+ * { fill: n } n bytes of filler. Two guards assert a minimum artifact
+ * size, and a megabyte of literal text does not belong in a
+ * registry a human reads.
+ */
+export function renderFixture(body, context = {}) {
+ if (body && typeof body === 'object' && Number.isInteger(body.fill)) {
+ return Buffer.alloc(body.fill, body.byte ?? 'x');
+ }
+ return String(body).replace(/\{\{pkg\.version\}\}/g, context.pkgVersion ?? '0.0.0');
+}
+
+/** Write a file, creating parent directories. */
+export function writeInto(root, rel, contents, context) {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, renderFixture(contents, context));
+}
+
+/** Apply a set of files verbatim. */
+export function applyFiles(root, files, context) {
+ for (const [rel, contents] of Object.entries(files)) writeInto(root, rel, contents, context);
+}
+
+/**
+ * Resolve a dot-path pointer inside a parsed JSON document.
+ * `routes`, `sections.2.pages` — numeric segments index arrays.
+ */
+export function resolvePointer(doc, pointer) {
+ let node = doc;
+ for (const segment of pointer.split('.').filter(Boolean)) {
+ if (node == null) return undefined;
+ node = node[/^\d+$/.test(segment) ? Number(segment) : segment];
+ }
+ return node;
+}
+
+/** Shallow "every listed key matches" predicate, for removeWhere. */
+function matchesWhere(candidate, where) {
+ if (!candidate || typeof candidate !== 'object') return false;
+ return Object.entries(where).every(([k, v]) => candidate[k] === v);
+}
+
+/**
+ * Edit a JSON file in place.
+ *
+ * Some guards can only be violated by changing a large committed registry
+ * (vercel.json, a golden fixture, a server manifest). Pasting the whole file
+ * into a fixture would make the proof unreadable and would rot the moment the
+ * real file changed, so proofs describe the edit instead of the result.
+ */
+export function applyJsonOp(root, op) {
+ const abs = path.join(root, op.file);
+ const doc = JSON.parse(readFileSync(abs, 'utf8'));
+ if ('set' in op) {
+ const segments = op.pointer.split('.').filter(Boolean);
+ const leaf = segments.pop();
+ const parent = segments.length ? resolvePointer(doc, segments.join('.')) : doc;
+ if (parent == null) throw new Error(`json op: ${op.file} has no ${op.pointer}`);
+ parent[/^\d+$/.test(leaf) ? Number(leaf) : leaf] = op.set;
+ } else {
+ const target = resolvePointer(doc, op.pointer);
+ if (!Array.isArray(target)) throw new Error(`json op: ${op.file}#${op.pointer} is not an array`);
+ if ('insert' in op) {
+ target.splice(Number.isInteger(op.at) ? op.at : 0, 0, op.insert);
+ } else {
+ const index = target.findIndex((entry) => matchesWhere(entry, op.removeWhere));
+ if (index === -1) throw new Error(`json op: nothing in ${op.file}#${op.pointer} matches ${JSON.stringify(op.removeWhere)}`);
+ target.splice(index, 1);
+ }
+ }
+ writeFileSync(abs, `${JSON.stringify(doc, null, '\t')}\n`);
+}
+
+/** Apply the violation: writes, appends, JSON edits, symlinks, then deletes. */
+export function applyViolation(root, violation) {
+ applyFiles(root, violation.write);
+ for (const [rel, tail] of Object.entries(violation.append)) {
+ const abs = path.join(root, rel);
+ const head = existsSync(abs) ? readFileSync(abs, 'utf8') : '';
+ writeInto(root, rel, head + tail);
+ }
+ for (const op of violation.json) applyJsonOp(root, op);
+ for (const [rel, target] of Object.entries(violation.link)) {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ rmSync(abs, { force: true });
+ symlinkSync(target, abs);
+ }
+ for (const rel of violation.delete) rmSync(path.join(root, rel), { force: true, recursive: true });
+}
+
+/**
+ * Run a guard's command inside the sandbox.
+ * The command is the literal package.json script, so a proof exercises exactly
+ * what the gate runs and never a paraphrase of it.
+ */
+export function runGuard(command, cwd, timeoutMs = 180_000) {
+ const started = process.hrtime.bigint();
+ const res = spawnSync('sh', ['-c', command], {
+ cwd,
+ encoding: 'utf8',
+ timeout: timeoutMs,
+ maxBuffer: 32 * 1024 * 1024,
+ env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', GUARD_PROOF_SANDBOX: '1' },
+ });
+ const ms = Number(process.hrtime.bigint() - started) / 1e6;
+ const output = `${res.stdout ?? ''}${res.stderr ?? ''}`;
+ return {
+ code: res.status === null ? 124 : res.status,
+ output,
+ timedOut: res.status === null,
+ ms: Math.round(ms),
+ };
+}
+
+/** Trim guard output to the lines that carry the verdict. */
+export function excerpt(output, limit = 6) {
+ const lines = output
+ .split('\n')
+ .map((l) => l.replace(/\s+$/, ''))
+ .filter((l) => l.trim().length);
+ if (lines.length <= limit) return lines.join('\n');
+ return `${lines.slice(0, limit).join('\n')}\n... ${lines.length - limit} more line(s)`;
+}
+
+/**
+ * Execute one proof against a prepared sandbox and return its verdict.
+ * Pure with respect to the sandbox: whatever it touched is restored on the way
+ * out, so proofs run back to back in a single checkout without contaminating
+ * each other.
+ */
+/**
+ * Stage the sandbox worktree.
+ *
+ * Two guards read the git INDEX rather than the filesystem (`git grep` over
+ * tracked files; `git ls-files -s` for committed symlinks), so an unstaged
+ * fixture is invisible to them and the proof would report NOT CAUGHT for a
+ * guard that works perfectly. Staging is opt-in per proof for that reason.
+ */
+export function stageSandbox(root) {
+ spawnSync('git', ['add', '-A'], { cwd: root, stdio: 'ignore' });
+}
+
+/** Drop everything staging added, back to the sandbox baseline commit. */
+export function unstageSandbox(root) {
+ spawnSync('git', ['reset', '--quiet'], { cwd: root, stdio: 'ignore' });
+}
+
+export function proveGuard(guard, proof, sandbox, { run = runGuard, stage = stageSandbox, unstage = unstageSandbox } = {}) {
+ if (proof.kind === 'live') {
+ return {
+ id: guard.id,
+ verdict: VERDICTS.DECLARED_LIVE,
+ reason: proof.reason,
+ ms: 0,
+ };
+ }
+
+ const saved = snapshot(sandbox, touchedPaths(proof));
+ try {
+ applyFiles(sandbox, proof.setup);
+ const control = run(guard.command, sandbox);
+ if (control.code !== 0) {
+ return {
+ id: guard.id,
+ verdict: VERDICTS.CONTROL_FAILED,
+ summary: proof.summary,
+ controlCode: control.code,
+ output: excerpt(control.output),
+ ms: control.ms,
+ };
+ }
+
+ applyViolation(sandbox, proof.violation);
+ if (proof.stage) stage(sandbox);
+ const violated = run(guard.command, sandbox);
+ if (violated.code === 0) {
+ return {
+ id: guard.id,
+ verdict: VERDICTS.NOT_CAUGHT,
+ summary: proof.summary,
+ controlCode: 0,
+ violationCode: 0,
+ output: excerpt(violated.output),
+ ms: control.ms + violated.ms,
+ };
+ }
+ if (!violated.output.includes(proof.expect)) {
+ return {
+ id: guard.id,
+ verdict: VERDICTS.WRONG_REASON,
+ summary: proof.summary,
+ expect: proof.expect,
+ controlCode: 0,
+ violationCode: violated.code,
+ output: excerpt(violated.output),
+ ms: control.ms + violated.ms,
+ };
+ }
+ return {
+ id: guard.id,
+ verdict: VERDICTS.PROVEN,
+ summary: proof.summary,
+ controlCode: 0,
+ violationCode: violated.code,
+ evidence: firstMatchingLine(violated.output, proof.expect),
+ ms: control.ms + violated.ms,
+ };
+ } finally {
+ if (proof.stage) unstage(sandbox);
+ restore(sandbox, saved);
+ }
+}
+
+/** The single output line that carries the expected fragment. */
+export function firstMatchingLine(output, fragment) {
+ for (const line of output.split('\n')) {
+ if (line.includes(fragment)) return line.trim().slice(0, 240);
+ }
+ return '';
+}
diff --git a/scripts/lib/mcp-schema.mjs b/scripts/lib/mcp-schema.mjs
new file mode 100644
index 000000000..28fe4e5c5
--- /dev/null
+++ b/scripts/lib/mcp-schema.mjs
@@ -0,0 +1,454 @@
+// Static materializer for MCP tool input schemas.
+//
+// Why this exists. scripts/build-mcp-catalog.mjs advertises the catalog as
+// carrying "name, description, input schema, price, safety" in one request, but
+// it shipped every tool without a schema: 272 tools an agent could discover and
+// none it could actually call, because nothing said what arguments to pass.
+// This module recovers the schema from source so the catalog delivers what it
+// claims.
+//
+// Everything is read statically with acorn, for the same reason the rest of the
+// MCP tooling is: importing a hosted catalog pulls in DB and RPC clients that
+// block without live credentials, and a docs build must never depend on
+// production.
+//
+// Two declaration styles exist in this repo and both are handled:
+//
+// 1. `inputSchema: { type: 'object', properties: { … } }` — a JSON Schema
+// literal, which 262 of the 272 tools use. Read by `jsonValue`.
+// 2. `inputSchema: inputJsonSchema` where `const inputJsonSchema =
+// jsonSchemaFromZod(inputZodShape)` — built at import time from a zod
+// shape (the IBM Granite and vanity-grinder tools). Read by `zodShape`,
+// which re-derives what zod-to-json-schema would have produced.
+//
+// The hard rule for both readers: anything not recognized is reported as
+// dynamic and omitted, never guessed. A catalog that is silently wrong about a
+// tool's arguments is worse than one that says it does not know.
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { parse } from 'acorn';
+
+import { ROOT } from './mcp-tool-sources.mjs';
+
+/* ── AST helpers ─────────────────────────────────────────────────────────── */
+
+function walk(node, visit) {
+ if (!node || typeof node.type !== 'string') return;
+ visit(node);
+ for (const key of Object.keys(node)) {
+ if (key === 'type' || key === 'start' || key === 'end') continue;
+ const value = node[key];
+ if (Array.isArray(value)) for (const child of value) walk(child, visit);
+ else if (value && typeof value.type === 'string') walk(value, visit);
+ }
+}
+
+/** `Object.freeze(x)` and `x` alike resolve to x. */
+function unwrapFreeze(node) {
+ if (
+ node?.type === 'CallExpression' &&
+ node.callee?.type === 'MemberExpression' &&
+ node.callee.property?.name === 'freeze' &&
+ node.arguments.length === 1
+ ) {
+ return unwrapFreeze(node.arguments[0]);
+ }
+ return node;
+}
+
+/** Every `const x = …` in the module, by name. */
+function collectConsts(ast) {
+ const out = new Map();
+ walk(ast, (node) => {
+ if (node.type !== 'VariableDeclarator' || node.id?.type !== 'Identifier') return;
+ if (node.init) out.set(node.id.name, unwrapFreeze(node.init));
+ });
+ return out;
+}
+
+const propKey = (prop) => prop.key?.name ?? prop.key?.value;
+
+/* ── JSON Schema literals ────────────────────────────────────────────────── */
+
+/**
+ * Materialize an expression as a plain JSON value.
+ *
+ * Records every expression it cannot resolve on `ctx.dynamic` (as a dotted path
+ * into the schema) and returns `undefined` for it, so the caller drops the key
+ * rather than emitting a placeholder.
+ *
+ * @param {object} node acorn expression node
+ * @param {{consts: Map<string, object>, dynamic: string[], seen: Set<object>}} ctx
+ * @param {string} path dotted path, for the dynamic report
+ * @returns {*} the value, or undefined when it is not statically knowable
+ */
+function jsonValue(node, ctx, path) {
+ if (!node) return undefined;
+
+ switch (node.type) {
+ case 'Literal':
+ // Regex literals carry no JSON value (`value` is a RegExp object).
+ if (node.regex) return node.raw;
+ return node.value;
+
+ case 'TemplateLiteral': {
+ // An interpolated description is still worth showing; `${…}` marks the
+ // hole, matching how the safety and golden readers render one.
+ const cooked = node.quasis.map((q) => q.value.cooked ?? '');
+ return node.expressions.length ? cooked.join('${…}') : cooked.join('');
+ }
+
+ case 'BinaryExpression': {
+ // Long descriptions are routinely written as `'part one ' + 'part two'`.
+ if (node.operator !== '+') break;
+ const left = jsonValue(node.left, ctx, path);
+ const right = jsonValue(node.right, ctx, path);
+ if (left === undefined || right === undefined) return undefined;
+ if (typeof left === 'number' && typeof right === 'number') return left + right;
+ return `${left}${right}`;
+ }
+
+ case 'UnaryExpression': {
+ const inner = jsonValue(node.argument, ctx, path);
+ if (typeof inner !== 'number') break;
+ if (node.operator === '-') return -inner;
+ if (node.operator === '+') return inner;
+ break;
+ }
+
+ case 'ArrayExpression': {
+ const out = [];
+ node.elements.forEach((element, i) => {
+ if (!element) return; // a hole
+ if (element.type === 'SpreadElement') {
+ const spread = jsonValue(element.argument, ctx, `${path}[${i}]`);
+ if (Array.isArray(spread)) out.push(...spread);
+ else ctx.dynamic.push(`${path}[${i}]`);
+ return;
+ }
+ const value = jsonValue(element, ctx, `${path}[${i}]`);
+ if (value === undefined) ctx.dynamic.push(`${path}[${i}]`);
+ else out.push(value);
+ });
+ return out;
+ }
+
+ case 'ObjectExpression': {
+ const out = {};
+ for (const prop of node.properties) {
+ if (prop.type === 'SpreadElement') {
+ const spread = jsonValue(prop.argument, ctx, path);
+ if (spread && typeof spread === 'object' && !Array.isArray(spread)) {
+ Object.assign(out, spread);
+ } else {
+ ctx.dynamic.push(`${path}.…spread`);
+ }
+ continue;
+ }
+ if (prop.type !== 'Property' || prop.computed) {
+ ctx.dynamic.push(`${path}.…computed`);
+ continue;
+ }
+ const key = propKey(prop);
+ if (typeof key !== 'string') {
+ ctx.dynamic.push(`${path}.…computed`);
+ continue;
+ }
+ const child = `${path}.${key}`;
+ // A method or getter in a schema position is code, not data.
+ if (prop.value.type === 'FunctionExpression' || prop.value.type === 'ArrowFunctionExpression') {
+ ctx.dynamic.push(child);
+ continue;
+ }
+ const value = jsonValue(prop.value, ctx, child);
+ if (value === undefined) ctx.dynamic.push(child);
+ else out[key] = value;
+ }
+ return out;
+ }
+
+ case 'Identifier': {
+ const target = ctx.consts.get(node.name);
+ if (!target || ctx.seen.has(target)) return undefined;
+ ctx.seen.add(target);
+ try {
+ return jsonValue(target, ctx, path);
+ } finally {
+ ctx.seen.delete(target);
+ }
+ }
+
+ case 'MemberExpression': {
+ if (node.computed) break;
+ const object = jsonValue(node.object, ctx, path);
+ if (!object || typeof object !== 'object') break;
+ return object[node.property?.name];
+ }
+
+ default:
+ break;
+ }
+ return undefined;
+}
+
+/* ── zod shapes ──────────────────────────────────────────────────────────── */
+
+// The zod vocabulary these tool files actually use. Anything outside it makes
+// the whole schema dynamic rather than a partially-invented one: an argument
+// list that is subtly wrong costs an integrator more than one that is absent.
+const ZOD_BASES = new Set(['string', 'number', 'boolean', 'array', 'object', 'enum', 'literal']);
+const ZOD_MODIFIERS = new Set(['min', 'max', 'int', 'optional', 'describe', 'default', 'nullable']);
+
+/**
+ * Unwind a chained zod expression into its base call plus the modifiers applied
+ * to it, outermost last: `z.string().min(1).optional()` becomes
+ * `{ base: z.string() call, chain: [min, optional] }`.
+ * @returns {{base: object, chain: {name: string, args: object[]}[]}|null}
+ */
+function unwindZodChain(node) {
+ const chain = [];
+ let cursor = node;
+ while (cursor?.type === 'CallExpression' && cursor.callee?.type === 'MemberExpression' && !cursor.callee.computed) {
+ const name = cursor.callee.property?.name;
+ const receiver = cursor.callee.object;
+ // `z.string()` is the base: its receiver is the zod namespace itself.
+ if (receiver?.type === 'Identifier' && receiver.name === 'z') {
+ if (!ZOD_BASES.has(name)) return null;
+ return { base: { name, args: cursor.arguments }, chain: chain.reverse() };
+ }
+ if (!ZOD_MODIFIERS.has(name)) return null;
+ chain.push({ name, args: cursor.arguments });
+ cursor = receiver;
+ }
+ return null;
+}
+
+/**
+ * A single zod field as JSON Schema, mirroring what zod-to-json-schema emits
+ * for the constructs in use.
+ * @returns {{schema: object, required: boolean}|null} null when unreadable
+ */
+function zodField(node, ctx, path) {
+ const unwound = unwindZodChain(node);
+ if (!unwound) return null;
+ const { base, chain } = unwound;
+
+ let schema;
+ switch (base.name) {
+ case 'string':
+ schema = { type: 'string' };
+ break;
+ case 'number':
+ schema = { type: 'number' };
+ break;
+ case 'boolean':
+ schema = { type: 'boolean' };
+ break;
+ case 'array': {
+ const items = base.args[0] ? zodField(base.args[0], ctx, `${path}[]`) : null;
+ if (!items) return null;
+ schema = { type: 'array', items: items.schema };
+ break;
+ }
+ case 'object': {
+ const inner = base.args[0];
+ if (inner?.type !== 'ObjectExpression') return null;
+ const built = zodShapeObject(inner, ctx, path);
+ if (!built) return null;
+ schema = built;
+ break;
+ }
+ case 'enum': {
+ const values = jsonValue(base.args[0], ctx, `${path}.enum`);
+ if (!Array.isArray(values) || !values.every((v) => typeof v === 'string')) return null;
+ schema = { type: 'string', enum: values };
+ break;
+ }
+ case 'literal': {
+ const value = jsonValue(base.args[0], ctx, `${path}.const`);
+ if (value === undefined) return null;
+ schema = { type: typeof value === 'number' ? 'number' : typeof value, const: value };
+ break;
+ }
+ default:
+ return null;
+ }
+
+ // zod-to-json-schema drops a field from `required` for both `.optional()` and
+ // `.default()`; a defaulted field is satisfiable without the caller sending it.
+ let required = true;
+ for (const step of chain) {
+ switch (step.name) {
+ case 'optional':
+ case 'nullable':
+ required = false;
+ break;
+ case 'int':
+ schema.type = 'integer';
+ break;
+ case 'describe': {
+ const text = jsonValue(step.args[0], ctx, `${path}.description`);
+ if (typeof text !== 'string') return null;
+ schema.description = text;
+ break;
+ }
+ case 'default': {
+ const value = jsonValue(step.args[0], ctx, `${path}.default`);
+ if (value === undefined) return null;
+ schema.default = value;
+ required = false;
+ break;
+ }
+ case 'min':
+ case 'max': {
+ const bound = jsonValue(step.args[0], ctx, `${path}.${step.name}`);
+ if (typeof bound !== 'number') return null;
+ const key = {
+ string: step.name === 'min' ? 'minLength' : 'maxLength',
+ array: step.name === 'min' ? 'minItems' : 'maxItems',
+ }[base.name] ?? (step.name === 'min' ? 'minimum' : 'maximum');
+ schema[key] = bound;
+ break;
+ }
+ default:
+ return null;
+ }
+ }
+ return { schema, required };
+}
+
+/**
+ * A `{ field: z.… }` shape object as a JSON Schema object node.
+ * @returns {object|null} null when any field is unreadable
+ */
+function zodShapeObject(node, ctx, path) {
+ const properties = {};
+ const required = [];
+ for (const prop of node.properties) {
+ if (prop.type !== 'Property' || prop.computed) return null;
+ const key = propKey(prop);
+ if (typeof key !== 'string') return null;
+ const field = zodField(prop.value, ctx, `${path}.${key}`);
+ if (!field) return null;
+ properties[key] = field.schema;
+ if (field.required) required.push(key);
+ }
+ // `.strict()` on the outer object and zod's default strip on inner ones both
+ // render as `additionalProperties: false`.
+ const schema = { type: 'object', properties };
+ if (required.length) schema.required = required;
+ schema.additionalProperties = false;
+ return schema;
+}
+
+/* ── entry points ────────────────────────────────────────────────────────── */
+
+/**
+ * Resolve one `inputSchema:` property value to a JSON Schema.
+ *
+ * @param {object} node the expression assigned to `inputSchema`
+ * @param {Map<string, object>} consts the module's const initializers
+ * @returns {{schema: object|null, dynamic: string[], reason: string|null}}
+ */
+export function materializeSchema(node, consts) {
+ const ctx = { consts, dynamic: [], seen: new Set() };
+
+ // `const inputJsonSchema = jsonSchemaFromZod(inputZodShape)` — follow the
+ // identifier to the call, then read the zod shape it was built from.
+ let target = node;
+ if (target?.type === 'Identifier') {
+ const resolved = consts.get(target.name);
+ if (resolved) target = resolved;
+ }
+
+ if (target?.type === 'CallExpression') {
+ const callee = target.callee?.name ?? target.callee?.property?.name;
+ if (callee === 'jsonSchemaFromZod' && target.arguments.length === 1) {
+ let shape = target.arguments[0];
+ if (shape.type === 'Identifier') shape = consts.get(shape.name) ?? shape;
+ if (shape?.type === 'ObjectExpression') {
+ const schema = zodShapeObject(shape, ctx, 'inputSchema');
+ if (schema) return { schema, dynamic: [], reason: null };
+ }
+ return { schema: null, dynamic: [], reason: 'zod shape uses a construct this reader does not model' };
+ }
+ return { schema: null, dynamic: [], reason: 'built by a call at import time' };
+ }
+
+ if (target?.type !== 'ObjectExpression') {
+ return { schema: null, dynamic: [], reason: 'not a statically-declared object' };
+ }
+
+ const schema = jsonValue(target, ctx, 'inputSchema');
+ if (!schema || typeof schema !== 'object') {
+ return { schema: null, dynamic: ctx.dynamic, reason: 'did not resolve to an object' };
+ }
+ return { schema, dynamic: ctx.dynamic, reason: null };
+}
+
+/**
+ * Every statically-declared tool input schema in one tool-definition file,
+ * keyed by wire tool name.
+ *
+ * The tool predicate here is deliberately looser than the safety gate's (a
+ * string `name` plus an `inputSchema` is enough): callers correlate by name, so
+ * a superset costs nothing, while a stricter predicate that drifted from the
+ * gate's would silently drop a tool's arguments.
+ *
+ * @param {string} relPath repo-relative path to a tool-definition file
+ * @returns {Map<string, {schema: object|null, dynamic: string[], reason: string|null}>}
+ */
+export function extractInputSchemas(relPath) {
+ const src = readFileSync(join(ROOT, relPath), 'utf8');
+ let ast;
+ try {
+ ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module' });
+ } catch {
+ return new Map();
+ }
+ const consts = collectConsts(ast);
+ const out = new Map();
+
+ walk(ast, (node) => {
+ if (node.type !== 'ObjectExpression') return;
+ let name = null;
+ let schemaNode = null;
+ for (const prop of node.properties) {
+ if (prop.type !== 'Property' || prop.computed) continue;
+ const key = propKey(prop);
+ if (key === 'name' && prop.value.type === 'Literal' && typeof prop.value.value === 'string') {
+ name = prop.value.value;
+ } else if (key === 'inputSchema') {
+ schemaNode = prop.value;
+ }
+ }
+ if (!name || !schemaNode || out.has(name)) return;
+ out.set(name, materializeSchema(schemaNode, consts));
+ });
+
+ return out;
+}
+
+/**
+ * Argument rows for one schema, in declaration order: what a reference table or
+ * a generated form needs, without either having to re-walk JSON Schema.
+ *
+ * @param {object|null} schema
+ * @returns {{name: string, type: string, required: boolean, description: string|null,
+ * enum: string[]|null, default: *, format: string|null}[]}
+ */
+export function schemaArguments(schema) {
+ const properties = schema?.properties;
+ if (!properties || typeof properties !== 'object') return [];
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
+ return Object.entries(properties).map(([name, spec]) => ({
+ name,
+ type: Array.isArray(spec?.type) ? spec.type.join(' | ') : (spec?.type ?? 'any'),
+ required: required.has(name),
+ description: typeof spec?.description === 'string' ? spec.description : null,
+ enum: Array.isArray(spec?.enum) ? spec.enum.map(String) : null,
+ default: spec?.default,
+ format: typeof spec?.format === 'string' ? spec.format : null,
+ }));
+}