Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(ops): npm run gpu — audit GPU capacity per region, port lanes, request quota
nirholas851868970b3b
diff --git a/docs/ops/gcp-credits-plan.md b/docs/ops/gcp-credits-plan.mdindex ee4e02d73..e5319a3c3 100644--- a/docs/ops/gcp-credits-plan.md+++ b/docs/ops/gcp-credits-plan.md@@ -2,6 +2,27 @@Owner directive (2026-07-16): spend the Google Cloud credits freely on quality, reliability, and UX. Do not onboard new external APIs. This doc is the standing map of where credits buy real product improvement, what has been done, and what any agent should do next without asking. Project: `aerial-vehicle-466722-p5`, region `us-central1`, billing runs on the credit grant.+## Audit and expand capacity with one command: `npm run gpu`++The audit below used to be manual, and it was re-derived by hand twice (2026-07-25, 2026-07-26) before landing the same conclusion each time: **the shortage is usually distribution, not supply.** One region gets pinned to zero headroom while another region's grant sits untouched, and the min-0 services in the pinned region 503 every cold start. [scripts/gpu-capacity.mjs](../../scripts/gpu-capacity.mjs) makes that a command:++```sh+npm run gpu # every GPU region: grant, holders, headroom, ranked actions+npm run gpu -- --json # machine-readable+npm run gpu -- --port model-triposr --to us-east4 # dry-run the cross-region move+npm run gpu -- --port model-triposr --to us-east4 --apply+npm run gpu -- --request 16 --region us-west1 --apply # file/raise that region's L4 grant+```++It ranks by time-to-effect, and deliberately puts **using a grant we already hold above asking Google for more** — a port lands in minutes, a quota raise has been pending since 2026-07-16. `--port` automates the no-rebuild pattern documented under us-east4 below (export, retarget the location label, drop the read-only URLs annotation and the pinned revision name, replace, mirror the invoker IAM). Mutating modes are dry run unless `--apply`. Pure logic is covered by [tests/gpu-capacity.test.js](../../tests/gpu-capacity.test.js).++Two things the tool surfaces that are easy to miss by hand:++- **Zonal redundancy is a separate quota bucket.** `NvidiaL4GpuAllocPerProjectRegion` and `NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion` are different grants. A region can read "full" against one and still have capacity under the other.+- **Every region is its own grant.** Filing a preference in a region we do not use yet costs nothing and is reviewed asynchronously, so file early rather than when a lane is already starving.++Exit code is 1 when there is an action worth taking (idle grant, or a starved service), 0 when there is not, 3 when gcloud auth has lapsed.+## The one constraint that matters: L4 GPU quotaEvery 3D generation engine runs on Cloud Run NVIDIA L4s, and all six GPU services draw from ONE quota: `NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion`, currently **granted 3** for us-central1.diff --git a/docs/ops/gcp-logs.md b/docs/ops/gcp-logs.mdindex c0497f98c..437713435 100644--- a/docs/ops/gcp-logs.md+++ b/docs/ops/gcp-logs.md@@ -1,12 +1,13 @@# Production logs and automated triage on GCP-The `vercel logs` workflow, rebuilt for the Cloud Run fleet. Two tools, both-in `scripts/`, both needing only the already-authenticated gcloud CLI:+The `vercel logs` workflow, rebuilt for the Cloud Run fleet. Three tools, all+in `scripts/`, all needing only the already-authenticated gcloud CLI:| Tool | Job ||---|---|| `npm run logs` ([scripts/gcp-logs.mjs](../../scripts/gcp-logs.mjs)) | Read or live-tail logs from any Cloud Run service, vercel-logs style. || `npm run triage:gcp` ([scripts/gcp-triage.mjs](../../scripts/gcp-triage.mjs)) | Automated monitor: healthz + fleet-wide log sweep + known-signature classification into an action plan. |+| `npm run gpu` ([scripts/gpu-capacity.mjs](../../scripts/gpu-capacity.mjs)) | GPU capacity across every region: grant, holders, headroom, plus cross-region ports and quota requests. Answers the `gpu-quota-starved` finding. |Agents: the monitor-and-fix loop that sits on top of these is the`/gcp-triage` skill ([.agents/skills/gcp-triage/SKILL.md](../../.agents/skills/gcp-triage/SKILL.md)).@@ -89,3 +90,5 @@ findings (so `npm run triage:gcp || <alert>` works in any loop).(LB/DNS/TLS/env/rollback).- [page-audit.md](page-audit.md): the browser-side console sweep(`npm run audit:web`), complementary to server logs.+- [gcp-credits-plan.md](gcp-credits-plan.md): the GPU fleet map, quota state,+ and what `npm run gpu` automates.diff --git a/package.json b/package.jsonindex 17c030bdd..6e0fb1822 100644--- a/package.json+++ b/package.json@@ -154,6 +154,7 @@"audit:web:login": "node scripts/page-audit.mjs --login","logs": "node scripts/gcp-logs.mjs","logs:tail": "node scripts/gcp-logs.mjs --follow",+ "gpu": "node scripts/gpu-capacity.mjs","logs:errors": "node scripts/gcp-logs.mjs --all --errors --since 6h","triage:gcp": "node scripts/gcp-triage.mjs","snapshot": "node scripts/page-snapshot.mjs",diff --git a/scripts/gpu-capacity.mjs b/scripts/gpu-capacity.mjsnew file mode 100644index 000000000..bb3535d34--- /dev/null+++ b/scripts/gpu-capacity.mjs@@ -0,0 +1,472 @@+#!/usr/bin/env node+/**+ * gpu-capacity: where our Cloud Run GPUs are, which ones are idle, and how to+ * get more.+ *+ * Every 3D engine runs on a Cloud Run GPU, and each region has its OWN grant.+ * The recurring failure is not "we are out of GPUs" — it is that one region is+ * pinned to zero headroom while another region's grant sits untouched, so+ * min-0 services there cannot cold-start and 503 every request (the+ * `gpu-quota-starved` signature). This turns the manual audit in+ * docs/ops/gcp-credits-plan.md into one command, and the manual cross-region+ * port pattern into another.+ *+ * npm run gpu # audit every GPU region+ * npm run gpu -- --json # machine-readable+ * npm run gpu -- --port model-triposr --to us-east4 # show the plan+ * npm run gpu -- --port model-triposr --to us-east4 --apply # execute it+ * npm run gpu -- --request 16 --region us-west1 # show the plan+ * npm run gpu -- --request 16 --region us-west1 --apply # file it+ *+ * Mutating modes are DRY RUN unless --apply is passed. Config-only Cloud Run+ * updates and quota requests are pre-approved (CLAUDE.md); nothing here builds+ * or deploys an image.+ *+ * Requires an authenticated gcloud. If `gcloud auth print-access-token` fails,+ * that is the sperax.io Workspace reauth policy — the owner runs+ * `gcloud auth login` once; there is no on-machine fallback.+ */++import { spawnSync } from 'node:child_process';+import { writeFileSync, mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const PROJECT = process.env.GCP_PROJECT || 'aerial-vehicle-466722-p5';++// Cloud Run regions that offer GPUs. Override with --regions a,b,c when Google+// lights up a new one — this list is a convenience, not a contract.+const GPU_REGIONS = ['us-central1', 'us-east4', 'us-west1', 'europe-west1', 'europe-west4', 'asia-southeast1'];++// Quota ids are per accelerator type AND per zonal-redundancy mode. The+// no-zonal-redundancy bucket is the one Cloud Run GPU services draw from by+// default; the redundant bucket is a SEPARATE grant, which is why a region can+// look full and still have capacity under the other mode.+const GPU_QUOTA_LABEL = {+ NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion: 'L4',+ NvidiaL4GpuAllocPerProjectRegion: 'L4 (zonal-redundant)',+ NvidiaRtxPro6000GpuAllocNoZonalRedundancyPerProjectRegion: 'RTX PRO 6000',+ NvidiaRtxPro6000GpuAllocPerProjectRegion: 'RTX PRO 6000 (zonal-redundant)',+};++const C = {+ dim: (s) => `\x1b[2m${s}\x1b[0m`,+ bold: (s) => `\x1b[1m${s}\x1b[0m`,+ red: (s) => `\x1b[31m${s}\x1b[0m`,+ green: (s) => `\x1b[32m${s}\x1b[0m`,+ yellow: (s) => `\x1b[33m${s}\x1b[0m`,+ cyan: (s) => `\x1b[36m${s}\x1b[0m`,+};++function parseArgs(argv) {+ const opts = {+ json: false,+ regions: GPU_REGIONS,+ port: null,+ to: null,+ request: null,+ region: null,+ apply: false,+ project: PROJECT,+ };+ for (let i = 0; i < argv.length; i++) {+ const next = () => argv[++i];+ switch (argv[i]) {+ case '--json': opts.json = true; break;+ case '--regions': opts.regions = next().split(',').map((s) => s.trim()).filter(Boolean); break;+ case '--port': opts.port = next(); break;+ case '--to': opts.to = next(); break;+ case '--request': opts.request = Number(next()); break;+ case '--region': opts.region = next(); break;+ case '--apply': opts.apply = true; break;+ case '--project': opts.project = next(); break;+ case '-h': case '--help': opts.help = true; break;+ default:+ console.error(`unknown flag: ${argv[i]}`);+ process.exit(2);+ }+ }+ return opts;+}++/** Run gcloud, returning { ok, stdout, stderr }. Never throws. */+function gcloud(args, { input } = {}) {+ const r = spawnSync('gcloud', args, { encoding: 'utf8', input, maxBuffer: 64 * 1024 * 1024 });+ const stderr = r.stderr || '';+ if (/Reauthentication failed|gcloud auth login|invalid_rapt/i.test(stderr)) {+ console.error(C.red('\ngcloud auth has expired (sperax.io Workspace reauth policy).'));+ console.error('There is no on-machine fallback. Run this once, then re-run:\n');+ console.error(C.bold(' gcloud auth login\n'));+ process.exit(3);+ }+ return { ok: r.status === 0, stdout: r.stdout || '', stderr };+}++function gcloudJson(args) {+ const r = gcloud([...args, '--format=json']);+ if (!r.ok) return null;+ try {+ return JSON.parse(r.stdout);+ } catch {+ return null;+ }+}++// ── Audit ────────────────────────────────────────────────────────────────────++const annot = (obj, key) => obj?.metadata?.annotations?.[key];+const scale = (svc, which) => {+ const v = annot(svc.spec?.template, `autoscaling.knative.dev/${which}Scale`);+ const n = Number(v);+ return Number.isFinite(n) ? n : which === 'min' ? 0 : 1;+};++/** GPU services in a region, with the GPU count each instance holds. */+function gpuServices(region, project) {+ const list = gcloudJson(['run', 'services', 'list', '--region', region, '--project', project]) || [];+ const out = [];+ for (const svc of list) {+ const container = svc.spec?.template?.spec?.containers?.[0];+ const gpu = Number(container?.resources?.limits?.['nvidia.com/gpu'] || 0);+ if (!gpu) continue;+ out.push({+ name: svc.metadata?.name,+ gpu,+ gpuType: annot(svc.spec?.template, 'run.googleapis.com/accelerator') || 'nvidia-l4',+ min: scale(svc, 'min'),+ max: scale(svc, 'max'),+ // Pinned GPUs are what actually consume the grant around the clock;+ // burst demand is what the region would need under full load.+ pinned: scale(svc, 'min') * gpu,+ ceiling: scale(svc, 'max') * gpu,+ ready: svc.status?.conditions?.find((c) => c.type === 'Ready')?.status === 'True',+ });+ }+ return out.sort((a, b) => b.pinned - a.pinned || a.name.localeCompare(b.name));+}++/**+ * Quota grants per region, from the preferences we have filed. A region with no+ * preference is reported as unknown rather than zero: it may still carry a+ * default grant, and the fix (file a preference) is the same either way.+ */+function quotaGrants(project) {+ const prefs = gcloudJson(['alpha', 'quotas', 'preferences', 'list', '--project', project]) || [];+ const byRegion = new Map();+ for (const p of prefs) {+ if (!GPU_QUOTA_LABEL[p.quotaId]) continue;+ const region = p.dimensions?.region;+ if (!region) continue;+ if (!byRegion.has(region)) byRegion.set(region, []);+ byRegion.get(region).push({+ quotaId: p.quotaId,+ label: GPU_QUOTA_LABEL[p.quotaId],+ granted: Number(p.quotaConfig?.grantedValue ?? 0),+ preferred: Number(p.quotaConfig?.preferredValue ?? 0),+ reconciling: Boolean(p.reconciling),+ name: (p.name || '').split('/').pop(),+ updated: p.updateTime || p.createTime || null,+ });+ }+ return byRegion;+}++const daysSince = (iso) => (iso ? Math.floor((Date.now() - Date.parse(iso)) / 86_400_000) : null);++function audit(opts) {+ const grants = quotaGrants(opts.project);+ const regions = opts.regions.map((region) => {+ const services = gpuServices(region, opts.project);+ const quotas = grants.get(region) || [];+ // L4 is the pool every engine shares; report headroom against it.+ const l4 = quotas.find((q) => q.quotaId === 'NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion');+ const pinned = services.reduce((n, s) => n + s.pinned, 0);+ const ceiling = services.reduce((n, s) => n + s.ceiling, 0);+ return {+ region,+ quotas,+ services,+ pinned,+ ceiling,+ granted: l4 ? l4.granted : null,+ headroom: l4 ? l4.granted - pinned : null,+ starved: services.filter((s) => s.min === 0),+ };+ });+ return { project: opts.project, checkedAt: new Date().toISOString(), regions };+}++/** Where to put work, and how to get more capacity. Ordered by time-to-effect. */+export function recommend(report) {+ const out = [];+ const withHeadroom = report.regions.filter((r) => r.headroom != null && r.headroom > 0);+ const saturated = report.regions.filter((r) => r.headroom != null && r.headroom <= 0 && r.services.length);++ for (const r of withHeadroom) {+ const idle = r.granted - r.pinned;+ out.push({+ priority: 1,+ kind: 'use-existing-grant',+ region: r.region,+ detail: `${idle} of ${r.granted} granted GPU(s) unpinned in ${r.region} — capacity we already own.`,+ command: saturated.length+ ? `npm run gpu -- --port <service-from-${saturated[0].region}> --to ${r.region} --apply`+ : `gcloud run services update <service> --region ${r.region} --min-instances=1`,+ });+ }++ for (const r of saturated) {+ for (const s of r.starved) {+ out.push({+ priority: 2,+ kind: 'starved-service',+ region: r.region,+ service: s.name,+ detail: `${s.name} is min-0 in a region with no headroom: every cold start races for a GPU that is already pinned, so it 503s.`,+ command: withHeadroom.length+ ? `npm run gpu -- --port ${s.name} --to ${withHeadroom[0].region} --apply`+ : `npm run gpu -- --request ${(r.granted || 0) + 8} --region ${r.region} --apply`,+ });+ }+ }++ for (const r of report.regions) {+ const l4 = r.quotas.find((q) => q.quotaId === 'NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion');+ if (!l4) {+ out.push({+ priority: 3,+ kind: 'no-preference-filed',+ region: r.region,+ detail: `No L4 quota preference filed for ${r.region}. Each region is a separate grant; filing one is free and asynchronous.`,+ command: `npm run gpu -- --request 8 --region ${r.region} --apply`,+ });+ } else if (l4.reconciling) {+ const age = daysSince(l4.updated);+ out.push({+ priority: 3,+ kind: 'pending-grant',+ region: r.region,+ detail: `${r.region} L4 raise ${l4.granted} → ${l4.preferred} still reconciling${age != null ? ` after ${age} day(s)` : ''}. Google reviews asynchronously; do not park work on it.`,+ command: `gcloud alpha quotas preferences describe ${l4.name} --project ${report.project}`,+ });+ }+ if (r.ceiling > (r.granted ?? 0) && r.granted != null) {+ out.push({+ priority: 4,+ kind: 'burst-exceeds-grant',+ region: r.region,+ detail: `${r.region} maxScale sums to ${r.ceiling} GPU(s) against a grant of ${r.granted} — under full load the excess fails over instead of scaling.`,+ command: `npm run gpu -- --request ${r.ceiling} --region ${r.region} --apply`,+ });+ }+ }+ return out.sort((a, b) => a.priority - b.priority);+}++function printAudit(report) {+ console.log(`\n${C.bold('Cloud Run GPU capacity')} ${C.dim(`· ${report.project}`)}\n`);+ for (const r of report.regions) {+ if (!r.services.length && !r.quotas.length) {+ console.log(`${C.dim(r.region.padEnd(18))} ${C.dim('no GPU services, no quota preference filed')}`);+ continue;+ }+ const head = r.granted == null+ ? C.dim('grant unknown (no preference filed)')+ : r.headroom > 0+ ? C.green(`${r.pinned}/${r.granted} pinned · ${r.headroom} free`)+ : C.red(`${r.pinned}/${r.granted} pinned · 0 free`);+ console.log(`${C.bold(r.region.padEnd(18))} ${head} ${C.dim(`burst ceiling ${r.ceiling}`)}`);+ for (const q of r.quotas) {+ const state = q.reconciling ? C.yellow(`→ ${q.preferred} pending (${daysSince(q.updated)}d)`) : C.dim('settled');+ console.log(` ${C.dim('quota')} ${q.label.padEnd(26)} granted ${String(q.granted).padStart(4)} ${state}`);+ }+ for (const s of r.services) {+ const warm = s.min > 0 ? C.cyan(`warm ${s.min}`) : C.dim('scale-to-zero');+ const health = s.ready ? '' : C.red(' NOT READY');+ console.log(` ${s.name.padEnd(26)} ${warm.padEnd(22)} ${C.dim(`max ${s.max} · ${s.gpuType}`)}${health}`);+ }+ console.log('');+ }++ const recs = recommend(report);+ if (!recs.length) {+ console.log(C.green('No capacity action available: every region is either saturated with a pending raise or fully used.\n'));+ return;+ }+ console.log(C.bold('What to do, fastest first:\n'));+ for (const rec of recs) {+ console.log(` ${C.bold(rec.kind)} ${C.dim(`· ${rec.region}`)}`);+ console.log(` ${rec.detail}`);+ console.log(` ${C.cyan(rec.command)}\n`);+ }+}++// ── Cross-region port ────────────────────────────────────────────────────────+// The documented no-rebuild pattern (docs/ops/gcp-credits-plan.md §us-east4):+// export the service, retarget its location, replace it in the new region, and+// mirror the invoker IAM. Images pull cross-region from the us-central1+// Artifact Registry and weights mount from GCS either way, so nothing rebuilds.++/** Find which region currently hosts a service. */+function locateService(name, regions, project) {+ for (const region of regions) {+ const svc = gcloudJson(['run', 'services', 'describe', name, '--region', region, '--project', project]);+ if (svc) return { region, svc };+ }+ return null;+}++export function retargetExport(yaml, from, to) {+ return yaml+ .split('\n')+ // Read-only, region-scoped URLs; carrying them into a new region is rejected.+ .filter((line) => !/^\s*run\.googleapis\.com\/urls:/.test(line))+ // The revision name is region-unique; letting Cloud Run mint a fresh one+ // avoids a collision with the source region's revision history.+ .filter((line) => !/^\s*name:\s*\S+-\d{5}-\w{3}\s*$/.test(line))+ .map((line) => line.replace(+ new RegExp(`(cloud\\.googleapis\\.com/location:\\s*)${from}\\s*$`),+ `$1${to}`,+ ))+ .join('\n');+}++function portService(opts) {+ const { port: name, to, apply, project } = opts;+ if (!to) {+ console.error('--port requires --to <region>');+ process.exit(2);+ }+ const found = locateService(name, opts.regions, project);+ if (!found) {+ console.error(`service ${name} not found in any of: ${opts.regions.join(', ')}`);+ process.exit(1);+ }+ if (found.region === to) {+ console.error(`${name} already lives in ${to}`);+ process.exit(1);+ }++ const exported = gcloud(['run', 'services', 'describe', name, '--region', found.region, '--project', project, '--format=export']);+ if (!exported.ok) {+ console.error(`could not export ${name}: ${exported.stderr.trim()}`);+ process.exit(1);+ }+ const retargeted = retargetExport(exported.stdout, found.region, to);+ const dir = mkdtempSync(join(tmpdir(), 'gpu-port-'));+ const file = join(dir, `${name}.yaml`);+ writeFileSync(file, retargeted);++ const policy = gcloudJson(['run', 'services', 'get-iam-policy', name, '--region', found.region, '--project', project]);++ console.log(`\n${C.bold(`Port ${name}: ${found.region} → ${to}`)}\n`);+ console.log(` spec written to ${C.dim(file)}`);+ console.log(` ${C.cyan(`gcloud run services replace ${file} --region ${to} --project ${project}`)}`);+ if (policy?.bindings?.length) {+ console.log(` ${C.cyan(`gcloud run services set-iam-policy ${name} <policy.json> --region ${to} --project ${project}`)}`);+ console.log(` ${C.dim(`mirrors ${policy.bindings.length} binding(s): ${policy.bindings.map((b) => b.role).join(', ')}`)}`);+ }+ console.log(`\n ${C.dim('The image pulls cross-region from the us-central1 Artifact Registry and')}`);+ console.log(` ${C.dim('weights mount from the three-ws-model-weights GCS bucket, so nothing rebuilds.')}`);+ console.log(` ${C.yellow('After this lands, point the caller at the new URL (config-only):')}`);+ console.log(` ${C.dim(`gcloud run services update three-ws-api --region us-central1 --update-env-vars <VAR>=<new-url>`)}\n`);++ if (!apply) {+ console.log(C.yellow('DRY RUN — re-run with --apply to execute.\n'));+ return;+ }++ const replaced = gcloud(['run', 'services', 'replace', file, '--region', to, '--project', project]);+ process.stdout.write(replaced.stdout);+ if (!replaced.ok) {+ console.error(C.red(`replace failed:\n${replaced.stderr}`));+ process.exit(1);+ }+ if (policy?.bindings?.length) {+ const pfile = join(dir, 'policy.json');+ writeFileSync(pfile, JSON.stringify({ bindings: policy.bindings }, null, 2));+ const iam = gcloud(['run', 'services', 'set-iam-policy', name, pfile, '--region', to, '--project', project, '--quiet']);+ if (!iam.ok) console.error(C.yellow(`IAM mirror failed (bind manually):\n${iam.stderr}`));+ }+ const url = gcloudJson(['run', 'services', 'describe', name, '--region', to, '--project', project])?.status?.url;+ console.log(C.green(`\n${name} is live in ${to}${url ? `: ${url}` : ''}\n`));+}++// ── Quota request ────────────────────────────────────────────────────────────++function requestQuota(opts) {+ const { request: value, region, apply, project } = opts;+ if (!region) {+ console.error('--request requires --region <region>');+ process.exit(2);+ }+ if (!Number.isInteger(value) || value < 1) {+ console.error('--request takes a positive integer GPU count');+ process.exit(2);+ }+ const quotaId = 'NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion';+ const existing = (quotaGrants(project).get(region) || []).find((q) => q.quotaId === quotaId);+ const prefName = existing?.name || `l4-no-zonal-${region}-${value}`;+ const args = [+ 'alpha', 'quotas', 'preferences', existing ? 'update' : 'create',+ '--project', project,+ '--service', 'run.googleapis.com',+ '--quota-id', quotaId,+ '--preferred-value', String(value),+ '--dimensions', `region=${region}`,+ ...(existing ? ['--preference-id', prefName, '--allow-missing'] : ['--preference-id', prefName]),+ ];++ console.log(`\n${C.bold(`L4 quota request · ${region}`)}\n`);+ console.log(` current grant: ${existing ? existing.granted : C.dim('none filed')}`);+ console.log(` requesting: ${value}`);+ console.log(` ${C.cyan(`gcloud ${args.join(' ')}`)}\n`);+ if (!apply) {+ console.log(C.yellow('DRY RUN — re-run with --apply to file it.\n'));+ return;+ }+ const r = gcloud(args);+ process.stdout.write(r.stdout);+ if (!r.ok) {+ console.error(C.red(`request failed:\n${r.stderr}`));+ process.exit(1);+ }+ console.log(C.green('\nFiled. Google reviews asynchronously — route around the shortage meanwhile.\n'));+}++// ── Entry ────────────────────────────────────────────────────────────────────+// Guarded so the pure helpers above (retargetExport, recommend) can be unit+// tested without the CLI running on import.++const invokedDirectly = process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1]);+if (!invokedDirectly) { /* imported for tests */ } else {++const opts = parseArgs(process.argv.slice(2));+if (opts.help) {+ console.log(`+ npm run gpu audit every GPU region+ npm run gpu -- --json machine-readable audit+ npm run gpu -- --regions us-central1,us-east4 limit the sweep+ npm run gpu -- --port <service> --to <region> [--apply] move a service to a region with headroom+ npm run gpu -- --request <n> --region <region> [--apply] raise that region's L4 grant+`);+ process.exit(0);+}++if (opts.port) {+ portService(opts);+} else if (opts.request != null) {+ requestQuota(opts);+} else {+ const report = audit(opts);+ if (opts.json) {+ console.log(JSON.stringify({ ...report, recommendations: recommend(report) }, null, 2));+ } else {+ printAudit(report);+ }+ const actionable = recommend(report).filter((r) => r.priority <= 2).length;+ process.exit(actionable ? 1 : 0);+}++}diff --git a/tests/gpu-capacity.test.js b/tests/gpu-capacity.test.jsnew file mode 100644index 000000000..ed54e54d7--- /dev/null+++ b/tests/gpu-capacity.test.js@@ -0,0 +1,157 @@+/**+ * gpu-capacity — unit tests for the two pure decision points.+ *+ * The gcloud calls are integration surface, but the YAML retarget and the+ * recommendation ranking are where a mistake is expensive: a bad retarget+ * either fails the replace or, worse, clones a service on top of its own+ * revision history, and a bad ranking sends an agent to file a quota request+ * when a region already has idle GPUs sitting unused.+ */++import { describe, it, expect } from 'vitest';+import { retargetExport, recommend } from '../scripts/gpu-capacity.mjs';++// A trimmed `gcloud run services describe --format=export` body, same shape as+// the real one for a GPU worker.+const EXPORTED = `apiVersion: serving.knative.dev/v1+kind: Service+metadata:+ annotations:+ run.googleapis.com/ingress: all+ run.googleapis.com/urls: '["https://model-triposr-93741856042.us-central1.run.app"]'+ labels:+ cloud.googleapis.com/location: us-central1+ name: model-triposr+spec:+ template:+ metadata:+ annotations:+ autoscaling.knative.dev/maxScale: '2'+ run.googleapis.com/accelerator: nvidia-l4+ name: model-triposr-00011-rpl+ spec:+ containers:+ - image: us-central1-docker.pkg.dev/p/model-triposr/server:manual02+ name: server-1+ resources:+ limits:+ nvidia.com/gpu: '1'+`;++describe('retargetExport', () => {+ const out = retargetExport(EXPORTED, 'us-central1', 'us-east4');++ it('moves the location label to the destination region', () => {+ expect(out).toContain('cloud.googleapis.com/location: us-east4');+ expect(out).not.toContain('cloud.googleapis.com/location: us-central1');+ });++ it('drops the read-only per-region URLs annotation', () => {+ expect(out).not.toContain('run.googleapis.com/urls');+ });++ it('drops the pinned revision name so the new region mints its own', () => {+ expect(out).not.toContain('model-triposr-00011-rpl');+ });++ it('keeps the service name, image and GPU request intact', () => {+ expect(out).toContain('name: model-triposr');+ expect(out).toContain('image: us-central1-docker.pkg.dev/p/model-triposr/server:manual02');+ expect(out).toContain("nvidia.com/gpu: '1'");+ expect(out).toContain('run.googleapis.com/accelerator: nvidia-l4');+ });++ it('leaves the source-region image registry alone — images pull cross-region', () => {+ expect(out).toContain('us-central1-docker.pkg.dev');+ });++ it('is a no-op on a body that does not mention the source region', () => {+ const untouched = retargetExport('kind: Service\nspec: {}\n', 'us-central1', 'us-east4');+ expect(untouched).toBe('kind: Service\nspec: {}\n');+ });+});++const region = (over) => ({+ region: 'us-central1',+ quotas: [],+ services: [],+ pinned: 0,+ ceiling: 0,+ granted: null,+ headroom: null,+ starved: [],+ ...over,+});++const l4Quota = (over) => ({+ quotaId: 'NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion',+ label: 'L4',+ granted: 3,+ preferred: 3,+ reconciling: false,+ name: 'l4-pref',+ updated: '2026-07-16T00:00:00Z',+ ...over,+});++describe('recommend', () => {+ it('ranks using an already-granted idle GPU above asking for more quota', () => {+ const recs = recommend({+ project: 'p',+ regions: [+ region({ region: 'us-central1', quotas: [l4Quota()], granted: 3, pinned: 3, headroom: 0, ceiling: 8, services: [{ name: 'model-triposr', min: 0 }], starved: [{ name: 'model-triposr', min: 0 }] }),+ region({ region: 'us-east4', quotas: [l4Quota()], granted: 3, pinned: 0, headroom: 3, ceiling: 2, services: [{ name: 'model-text2motion', min: 0 }] }),+ ],+ });+ expect(recs[0].kind).toBe('use-existing-grant');+ expect(recs[0].region).toBe('us-east4');+ // The starved service is told to move to the region with headroom, not to+ // wait behind a quota request.+ const starved = recs.find((r) => r.kind === 'starved-service');+ expect(starved.service).toBe('model-triposr');+ expect(starved.command).toContain('--to us-east4');+ });++ it('falls back to a quota request when no region has headroom', () => {+ const recs = recommend({+ project: 'p',+ regions: [+ region({ granted: 3, pinned: 3, headroom: 0, ceiling: 3, services: [{ name: 'model-triposr', min: 0 }], starved: [{ name: 'model-triposr', min: 0 }], quotas: [l4Quota()] }),+ ],+ });+ const starved = recs.find((r) => r.kind === 'starved-service');+ expect(starved.command).toContain('--request');+ });++ it('flags a region with no preference filed as a free thing to try', () => {+ const recs = recommend({ project: 'p', regions: [region({ region: 'us-west1' })] });+ expect(recs.some((r) => r.kind === 'no-preference-filed' && r.region === 'us-west1')).toBe(true);+ });++ it('reports a pending grant with its age instead of treating it as capacity', () => {+ const recs = recommend({+ project: 'p',+ regions: [region({ granted: 3, pinned: 1, headroom: 2, ceiling: 3, quotas: [l4Quota({ preferred: 16, reconciling: true })] })],+ });+ const pending = recs.find((r) => r.kind === 'pending-grant');+ expect(pending.detail).toContain('3 → 16');+ expect(pending.detail).toMatch(/day\(s\)/);+ });++ it('warns when the burst ceiling exceeds the grant', () => {+ const recs = recommend({+ project: 'p',+ regions: [region({ granted: 3, pinned: 2, headroom: 1, ceiling: 9, quotas: [l4Quota()] })],+ });+ const burst = recs.find((r) => r.kind === 'burst-exceeds-grant');+ expect(burst.command).toContain('--request 9');+ });++ it('says nothing when a fully-used region has a settled grant and no starved service', () => {+ const recs = recommend({+ project: 'p',+ regions: [region({ granted: 3, pinned: 3, headroom: 0, ceiling: 3, quotas: [l4Quota()], services: [{ name: 'model-trellis', min: 3 }] })],+ });+ expect(recs).toEqual([]);+ });+});