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(ops): /api/version deploy traceability + build stamp, harden deploy runbook

nirholasa180e27593a5
diff --git a/CLAUDE.md b/CLAUDE.md
index d8db75293..cc049522c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -33,7 +33,7 @@ Agents stopping mid-task to ask a question is a failure mode the owner explicitl
| Whether tests pass | `npm test`; do NOT pipe through `tail` (masks exit codes); a vitest failure gates the whole Playwright stage. |
| Model weights / assets missing | Stage them from `gs://three-ws-model-weights` or the worker README's source. Staging weights is part of deploying a worker, not a reason to stop. |
| Where a feature lives | `STRUCTURE.md` maps every surface to its directory. |
-| How to deploy | API/frontend: `gcloud builds submit --config server/cloudbuild.yaml` from a CLEAN worktree (`git worktree add --detach /workspaces/.deploy-wt HEAD`, hardlink node_modules with `cp -al` on the same filesystem), `npm run build:vercel` there plus `TARGET=lib LIB_FORMATS=es,umd vite build && node scripts/publish-lib.mjs` (check:dist needs the UMD bundle), then `npm run deploy:gcp:purge-cdn`. GPU workers: their own `workers/<name>/cloudbuild.yaml`. EVERY cloudbuild config must pin `serviceAccount: …/three-ws-build@…` (default compute SA was deleted) and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`. |
+| How to deploy | API/frontend, from a CLEAN worktree (`git worktree add --detach /workspaces/.deploy-wt HEAD`, hardlink node_modules with `cp -al` on the same filesystem): run `npm run build:gcp` then `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`, then `npm run deploy:gcp:purge-cdn` (or the whole build+submit+purge in one: `npm run deploy:gcp:full`). ORDER IS LOAD-BEARING and `build:gcp` encodes it: the frontend `vite build` WIPES `dist/`, so it must run FIRST, then the UMD lib build, then `publish:lib` (which mirrors the lib into `dist/`), then `build:info`, then `check:dist`. Do NOT hand-run `build:vercel` as the frontend build — it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails. `check:dist` needs the UMD bundle (publish:lib) present. GPU workers: their own `workers/<name>/cloudbuild.yaml`. EVERY cloudbuild config must pin `serviceAccount: …/three-ws-build@…` (default compute SA was deleted) and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`. Verify the deploy landed: `curl -s https://three.ws/api/version` returns the live commit SHA + Cloud Run revision. |
The ONLY standing stop-and-ask gates (everything else: proceed, then report):
1. Irreversible on-chain / spend actions (the gate below).
diff --git a/api/version.js b/api/version.js
new file mode 100644
index 000000000..cb5c775ac
--- /dev/null
+++ b/api/version.js
@@ -0,0 +1,104 @@
+// GET /api/version
+// ----------------
+// Deployment traceability. Answers "which commit is live, and on which Cloud Run
+// revision?" without cross-referencing revision timestamps against `git log`.
+//
+// Two sources, both zero-cost at request time:
+// 1. dist/build-info.json — written by scripts/write-build-info.mjs at build
+// time (see build:gcp). Ships in the image via the Dockerfile `COPY . .`.
+// Carries the git commit, branch, commit/build timestamps, and version.
+// 2. Cloud Run runtime env — K_REVISION / K_SERVICE / K_CONFIGURATION are set
+// by the platform on every instance, so the live revision is reported with
+// no deploy-time env injection.
+//
+// The build-info file is read once and cached for process lifetime (it never
+// changes within a running instance). Missing file (e.g. local `vite dev`, or a
+// build that skipped the stamp) degrades to nulls plus package version — the
+// endpoint never fails.
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { createRequire } from 'node:module';
+import { cors, json, method, wrap } from './_lib/http.js';
+
+const STARTED_AT = Date.now();
+const require = createRequire(import.meta.url);
+
+// Read + cache build-info.json once. process.cwd() is /app in the container
+// (WORKDIR), where dist/ sits alongside api/. Resolve from cwd so it works
+// regardless of where this module is imported from.
+let _buildInfo;
+function buildInfo() {
+ if (_buildInfo !== undefined) return _buildInfo;
+ try {
+ _buildInfo = JSON.parse(readFileSync(resolve(process.cwd(), 'dist/build-info.json'), 'utf8'));
+ } catch {
+ // No stamp: fall back to package version so `version` is still meaningful.
+ let version = 'unknown';
+ try {
+ version = require('../package.json').version || 'unknown';
+ } catch {
+ /* package.json unreadable — leave as unknown */
+ }
+ _buildInfo = {
+ version,
+ commit: process.env.VERCEL_GIT_COMMIT_SHA || 'unknown',
+ commitShort: (process.env.VERCEL_GIT_COMMIT_SHA || 'unknown').slice(0, 9),
+ commitTime: null,
+ commitSubject: null,
+ branch: process.env.VERCEL_GIT_COMMIT_REF || 'unknown',
+ dirty: false,
+ builtAt: null,
+ node: process.version,
+ stamped: false,
+ };
+ return _buildInfo;
+ }
+ _buildInfo.stamped = true;
+ return _buildInfo;
+}
+
+// Exported for tests so each case starts with a cold cache.
+export function _resetBuildInfoCache() {
+ _buildInfo = undefined;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const build = buildInfo();
+ const now = Date.now();
+
+ return json(
+ res,
+ 200,
+ {
+ status: 'ok',
+ // What commit is live.
+ version: build.version,
+ commit: build.commit,
+ commitShort: build.commitShort,
+ commitSubject: build.commitSubject,
+ commitTime: build.commitTime,
+ branch: build.branch,
+ dirty: build.dirty,
+ builtAt: build.builtAt,
+ // Whether the running image carries a real build stamp (false = the
+ // deploy skipped write-build-info; commit fields are best-effort).
+ stamped: build.stamped !== false,
+ // Where it is running. K_* are set by Cloud Run; null off-platform.
+ runtime: {
+ service: process.env.K_SERVICE || null,
+ revision: process.env.K_REVISION || null,
+ configuration: process.env.K_CONFIGURATION || null,
+ region: process.env.CLOUD_RUN_REGION || process.env.FUNCTION_REGION || null,
+ node: build.node || process.version,
+ uptimeMs: now - STARTED_AT,
+ },
+ },
+ // Short cache: dashboards and deploy-verification scripts poll this, but a
+ // new revision must show up promptly.
+ { 'cache-control': 'public, max-age=10, s-maxage=10' },
+ );
+});
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 2b89af5a3..950602afc 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -3489,6 +3489,49 @@ Returns public platform configuration. No auth required. CORS open.
---
+## Version API
+
+```
+GET /api/version
+```
+
+Deployment traceability: which commit is live, and on which Cloud Run revision. No auth required. CORS open. Short-cached (10s) so a new deploy shows up promptly. The commit fields are stamped into the image at build time (`dist/build-info.json`, written by `scripts/write-build-info.mjs`); the runtime fields come from the Cloud Run platform env, so no deploy-time injection is needed.
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "version": "1.5.2",
+ "commit": "83368639e0a1b2c3d4e5f6...",
+ "commitShort": "83368639e",
+ "commitSubject": "feat(forge): auto-classify creations into categories",
+ "commitTime": "2026-07-17T20:38:22Z",
+ "branch": "main",
+ "dirty": false,
+ "builtAt": "2026-07-17T21:05:00.000Z",
+ "stamped": true,
+ "runtime": {
+ "service": "three-ws-api",
+ "revision": "three-ws-api-00171-g5p",
+ "configuration": "three-ws-api",
+ "region": null,
+ "node": "v24.0.0",
+ "uptimeMs": 123456
+ }
+}
+```
+
+`stamped` is `false` when the running image carries no build stamp (e.g. a build that skipped `build:info`); the commit fields are then best-effort from env. Use this to verify a deploy landed:
+
+```bash
+curl -s https://three.ws/api/version | jq '{commitShort, revision: .runtime.revision}'
+```
+
+The same stamp is served statically at `/build-info.json`.
+
+---
+
## Pagination
All list endpoints use offset pagination unless noted otherwise.
diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.md
index 2581e04e3..b3360cc8a 100644
--- a/docs/ops/gcp-production.md
+++ b/docs/ops/gcp-production.md
@@ -115,16 +115,26 @@ deploys from a human-authed CLI (command below).
```bash
# Frontend changed? Build first — dist/ ships from the local build.
-# build:gcp = site build + agent-3d CDN lib (build:lib:full + publish:lib) +
-# check:dist. Plain `npm run build` is NOT enough: it skips the lib publish,
-# so /agent-3d/latest/agent-3d.js 404s in prod and the hero avatar dies
-# ("agent-3d element never registered").
+# build:gcp = site build -> agent-3d CDN lib (build:lib:full) -> publish:lib
+# -> build:info -> check:dist, IN THAT ORDER. The order is load-bearing: the
+# site `vite build` WIPES dist/, so it must run before publish:lib mirrors the
+# lib into dist/. Plain `npm run build` is NOT enough (skips the lib publish, so
+# /agent-3d/latest/agent-3d.js 404s and the hero avatar dies). Hand-running
+# `build:vercel` as the frontend build is also WRONG — it builds the SDK/lib
+# sub-artifacts, not the static HTML pages, so dist/ has no /, /create, etc.
npm run build:gcp
# Build image on Cloud Build (32-vCPU + BuildKit layer cache) + push + deploy.
# Gated on check:dist AND db:check so an incomplete dist/ or an out-of-date
# database can no longer ship.
npm run deploy:gcp
+
+# Or do build + submit + CDN purge in one (from a clean worktree):
+# npm run deploy:gcp:full
+
+# Verify the deploy actually landed — /api/version reports the live commit SHA
+# and Cloud Run revision (stamped into dist/build-info.json by build:info):
+curl -s https://three.ws/api/version | jq '{commitShort, branch, builtAt, revision: .runtime.revision}'
```
> **Never bypass `check:dist` by calling `gcloud builds submit` directly.** It is
diff --git a/package.json b/package.json
index 336cfbfef..f4ff446f0 100644
--- a/package.json
+++ b/package.json
@@ -216,8 +216,10 @@
"lint:fix": "eslint . --fix",
"check:dist": "node scripts/check-dist.mjs",
"deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod",
- "build:gcp": "npm run build && npm run build:lib:full && npm run publish:lib && npm run check:dist",
+ "build:info": "node scripts/write-build-info.mjs",
+ "build:gcp": "npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist",
"deploy:gcp": "npm run check:dist && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn",
+ "deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",
"deploy:gcp:purge-cdn": "gcloud compute url-maps invalidate-cdn-cache three-ws-lb --path '/*' --project aerial-vehicle-466722-p5 --async",
"postversion": "git push threews HEAD && git push threews --tags",
"validate:cards": "node scripts/validate-agent-cards.mjs",
diff --git a/pages/status.html b/pages/status.html
index 5a4de671f..4f9063fe4 100644
--- a/pages/status.html
+++ b/pages/status.html
@@ -391,6 +391,9 @@
<a href="/api/status?format=svg" style="color: inherit">status badge</a> ·
<a href="/changelog" style="color: inherit">Changelog</a>
</p>
+ <p class="st-meta" id="st-build" hidden>
+ <!-- filled from /api/version: the exact commit + Cloud Run revision live now -->
+ </p>
<section id="st-services" aria-label="Service status list">
<!-- skeletons swapped out by render() -->
@@ -647,6 +650,28 @@
load();
// Live page: refresh on the probe cadence without requiring a reload.
setInterval(load, 5 * 60 * 1000);
+
+ // Build traceability: show the exact commit + Cloud Run revision that is
+ // serving this page right now. Static (never changes within a revision),
+ // so it loads once and links the short SHA to the commit on GitHub.
+ (async () => {
+ const el = document.getElementById('st-build');
+ try {
+ const res = await fetch('/api/version', { headers: { accept: 'application/json' } });
+ if (!res.ok) return;
+ const v = await res.json();
+ if (!v || v.commitShort === 'unknown') return;
+ const shaLink = v.commit && v.commit !== 'unknown'
+ ? `<a href="https://github.com/nirholas/three.ws/commit/${esc(v.commit)}" rel="noopener" style="color: inherit; font-family: var(--font-mono, monospace)">${esc(v.commitShort)}</a>`
+ : `<span style="font-family: var(--font-mono, monospace)">${esc(v.commitShort)}</span>`;
+ const rev = v.runtime && v.runtime.revision ? ` · revision ${esc(v.runtime.revision)}` : '';
+ const built = v.builtAt ? ` · built ${new Date(v.builtAt).toLocaleString()}` : '';
+ el.innerHTML = `Live build: ${shaLink} <span style="opacity:.7">v${esc(v.version)}</span>${rev}${built}`;
+ el.hidden = false;
+ } catch {
+ /* version endpoint unreachable — leave the build line hidden */
+ }
+ })();
</script>
<script src="/nav.js" defer></script>
diff --git a/scripts/write-build-info.mjs b/scripts/write-build-info.mjs
new file mode 100644
index 000000000..a32b8a7f7
--- /dev/null
+++ b/scripts/write-build-info.mjs
@@ -0,0 +1,78 @@
+#!/usr/bin/env node
+/**
+ * Build-info stamp — the missing traceability link between a running production
+ * revision and the exact commit it was built from.
+ *
+ * Why this exists: the Cloud Run image tags to `:latest` and the container ships
+ * WITHOUT a `.git` dir (`.gcloudignore` excludes it), so at runtime there is no
+ * way to ask "which commit is live?" — you have to cross-reference the revision
+ * creation timestamp against `git log` by hand. This script captures the commit
+ * identity AT BUILD TIME and writes it into `dist/build-info.json`, which ships
+ * in the image (the Dockerfile `COPY . .` includes dist) and is both served as a
+ * static file (`/build-info.json`) and read by the `/api/version` handler.
+ *
+ * Run automatically as the last step of `npm run build:gcp`. Safe to run alone.
+ * Fail-soft: if git is unavailable (e.g. building from a tarball with no .git),
+ * it falls back to CI-provided commit env vars, then to `unknown` — never throws,
+ * never fails the build.
+ */
+import { execSync } from 'node:child_process';
+import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+/** Run a git command from the repo root; return trimmed stdout or '' on any error. */
+function git(args) {
+ try {
+ return execSync(`git ${args}`, { cwd: ROOT, stdio: ['ignore', 'pipe', 'ignore'] })
+ .toString()
+ .trim();
+ } catch {
+ return '';
+ }
+}
+
+function packageVersion() {
+ try {
+ return JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8')).version || 'unknown';
+ } catch {
+ return 'unknown';
+ }
+}
+
+// Prefer live git; fall back to CI-injected commit env vars (Vercel/Cloud Build);
+// finally 'unknown'. Never let a missing .git break the build.
+const fullSha =
+ git('rev-parse HEAD') || process.env.VERCEL_GIT_COMMIT_SHA || process.env.COMMIT_SHA || 'unknown';
+const shortSha = fullSha === 'unknown' ? 'unknown' : fullSha.slice(0, 9);
+const commitTime = git('show -s --format=%cI HEAD') || null; // committer date, ISO 8601
+const branch =
+ git('rev-parse --abbrev-ref HEAD') ||
+ process.env.VERCEL_GIT_COMMIT_REF ||
+ process.env.BRANCH_NAME ||
+ 'unknown';
+const subject = git('show -s --format=%s HEAD') || null;
+const dirty = fullSha !== 'unknown' && git('status --porcelain') !== '';
+
+const info = {
+ version: packageVersion(),
+ commit: fullSha,
+ commitShort: shortSha,
+ commitTime,
+ commitSubject: subject,
+ branch,
+ dirty,
+ builtAt: new Date().toISOString(),
+ node: process.version,
+};
+
+const outDir = resolve(ROOT, 'dist');
+mkdirSync(outDir, { recursive: true });
+const outPath = resolve(outDir, 'build-info.json');
+writeFileSync(outPath, JSON.stringify(info, null, 2) + '\n');
+
+console.log(
+ `[build-info] ${info.commitShort}${info.dirty ? '-dirty' : ''} (${info.branch}) v${info.version} → dist/build-info.json`,
+);
diff --git a/tests/version-endpoint.test.js b/tests/version-endpoint.test.js
new file mode 100644
index 000000000..b857ec8fe
--- /dev/null
+++ b/tests/version-endpoint.test.js
@@ -0,0 +1,118 @@
+/**
+ * /api/version + build-info stamp — unit tests.
+ *
+ * The endpoint is deploy-traceability infrastructure: it must (a) always answer
+ * 200 with a well-formed shape even when the build stamp is absent, (b) reflect
+ * the live Cloud Run revision from the platform K_* env vars, and (c) the
+ * generator must emit a valid, parseable stamp. These guard the "which commit is
+ * live?" answer that the manual deploy runbook now depends on.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { execSync } from 'node:child_process';
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import handler, { _resetBuildInfoCache } from '../api/version.js';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+function fakeReq(method = 'GET') {
+ return { method, headers: {}, url: '/api/version' };
+}
+
+function fakeRes() {
+ const headers = {};
+ return {
+ statusCode: 0,
+ body: undefined,
+ ended: false,
+ setHeader(k, v) {
+ headers[String(k).toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return headers[String(k).toLowerCase()];
+ },
+ end(b) {
+ this.body = b;
+ this.ended = true;
+ },
+ _headers: headers,
+ };
+}
+
+async function call() {
+ const res = fakeRes();
+ await handler(fakeReq('GET'), res);
+ return { res, json: res.body ? JSON.parse(res.body) : undefined };
+}
+
+describe('GET /api/version', () => {
+ let savedRevision, savedService;
+ beforeEach(() => {
+ _resetBuildInfoCache();
+ savedRevision = process.env.K_REVISION;
+ savedService = process.env.K_SERVICE;
+ });
+ afterEach(() => {
+ if (savedRevision === undefined) delete process.env.K_REVISION;
+ else process.env.K_REVISION = savedRevision;
+ if (savedService === undefined) delete process.env.K_SERVICE;
+ else process.env.K_SERVICE = savedService;
+ _resetBuildInfoCache();
+ });
+
+ it('returns 200 JSON with the traceability shape', async () => {
+ const { res, json } = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toMatch(/application\/json/);
+ expect(json.status).toBe('ok');
+ expect(typeof json.version).toBe('string');
+ expect(typeof json.commitShort).toBe('string');
+ expect(typeof json.stamped).toBe('boolean');
+ expect(json.runtime).toBeTruthy();
+ expect(typeof json.runtime.uptimeMs).toBe('number');
+ });
+
+ it('is cacheable but short-lived so a new revision shows up fast', async () => {
+ const { res } = await call();
+ expect(res.getHeader('cache-control')).toMatch(/max-age=10/);
+ });
+
+ it('reflects the live Cloud Run revision from platform env', async () => {
+ process.env.K_SERVICE = 'three-ws-api';
+ process.env.K_REVISION = 'three-ws-api-99999-test';
+ const { json } = await call();
+ expect(json.runtime.service).toBe('three-ws-api');
+ expect(json.runtime.revision).toBe('three-ws-api-99999-test');
+ });
+
+ it('reports null runtime revision off-platform (no K_* set)', async () => {
+ delete process.env.K_REVISION;
+ delete process.env.K_SERVICE;
+ const { json } = await call();
+ expect(json.runtime.revision).toBeNull();
+ expect(json.runtime.service).toBeNull();
+ });
+});
+
+describe('write-build-info.mjs generator', () => {
+ it('emits a valid, parseable build-info.json', () => {
+ execSync('node scripts/write-build-info.mjs', { cwd: ROOT, stdio: 'ignore' });
+ const p = resolve(ROOT, 'dist/build-info.json');
+ expect(existsSync(p)).toBe(true);
+ const info = JSON.parse(readFileSync(p, 'utf8'));
+
+ // version mirrors package.json
+ const pkgVersion = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8')).version;
+ expect(info.version).toBe(pkgVersion);
+
+ // commit is a full 40-char sha (this is a git repo) or the explicit fallback
+ expect(info.commit === 'unknown' || /^[0-9a-f]{40}$/.test(info.commit)).toBe(true);
+ expect(info.commitShort).toBe(info.commit === 'unknown' ? 'unknown' : info.commit.slice(0, 9));
+
+ // builtAt round-trips as ISO 8601
+ expect(new Date(info.builtAt).toISOString()).toBe(info.builtAt);
+ expect(typeof info.dirty).toBe('boolean');
+ });
+});