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(logging): add gcp-logs and gcp-triage scripts for enhanced log management and automated monitoring
nirholas4ad9c9eb75f7
diff --git a/docs/ops/gcp-logs.md b/docs/ops/gcp-logs.mdnew file mode 100644index 000000000..697180f7a--- /dev/null+++ b/docs/ops/gcp-logs.md@@ -0,0 +1,91 @@+# 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:++| 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. |++Agents: the monitor-and-fix loop that sits on top of these is the+`/gcp-triage` skill ([.claude/skills/gcp-triage/SKILL.md](../../.claude/skills/gcp-triage/SKILL.md)).++## Reading logs (`npm run logs`)++```sh+npm run logs # three-ws-api, last hour+npm run logs:tail # live tail (the old `vercel logs --follow`)+npm run logs:errors # ERROR+ across ALL services, last 6h+npm run logs -- -s model-rig --since 2d # any service, wider window+npm run logs -- --grep "forge" --warnings # full-text search WARNING++npm run logs -- --http 500 --since 6h # request logs with status >= 500+npm run logs -- --app --errors # app logs only (hide request logs)+npm run logs -- --services # list the Cloud Run fleet+npm run logs -- --json -n 500 # raw entries for scripts/agents+```++Output is chronological, severity-colored, one line per entry. App logs+render their `textPayload`/`jsonPayload`; request logs render+`status method url latency`. Defaults: service `three-ws-api`, project+`aerial-vehicle-466722-p5`, window `1h`, limit 100 (override with+`--project`, `--region`, `--since`, `-n`).++Two things the raw `gcloud logging read` one-liner in older docs gets wrong,+which this tool handles: structured entries carry `jsonPayload` (a+`textPayload:"term"` filter silently misses them), and request logs carry no+payload at all (severity comes from the HTTP status).++## Automated triage (`npm run triage:gcp`)++```sh+npm run triage:gcp # human report, last hour+npm run triage:gcp -- --since 6h # wider window+npm run triage:gcp -- --json # machine-readable, what agents consume+```++One run merges three signals:++1. **`/api/healthz`** subsystem roll-up (database, cache, Helius, x402 ring,+ world, sniper): the platform self-reports most degradations.+2. **WARNING+ app logs across every service**, fingerprinted (ids, numbers,+ addresses, and URLs collapsed) so repeats group into one finding.+3. **Request logs**: 5xx grouped per route, 429 noted.++Every finding gets a class and a concrete action:++- 🔴 `owner`: money/billing/security; the report carries the exact command,+ only the owner runs it.+- 🟡 `env-action`: config-only Cloud Run change (pre-approved); an agent+ applies it immediately.+- 🟠 `investigate`: unknown signature or 5xx group; an agent root-causes it.+- 🟢 `self-healing`: documented graceful degradation; no action.++Known signatures come from the runbook in+[production-log-triage.md](production-log-triage.md). When a new+expected-degradation signature shows up, add it to `KNOWN_SIGNATURES` in the+script and document it in the runbook; the monitor stops flagging it from+then on.++Exit codes make it schedulable: `0` healthy or noise-only, `1` actionable+findings (so `npm run triage:gcp || <alert>` works in any loop).++## Running it continuously++- **Interactive session:** `/loop 1h /gcp-triage` keeps a Claude agent+ sweeping and fixing while you work.+- **Scheduled Claude agent:** schedule `/gcp-triage` as a recurring routine+ from any Claude Code session (`/schedule`).+- **Independent of any agent**, the platform already self-monitors:+ `/api/cron/uptime-check` snapshots healthz every tick and re-pages+ persistent degradations, and [/status](https://three.ws/status) renders the+ live subsystem state with plain-language fixes.++## Related++- [production-log-triage.md](production-log-triage.md): every known log+ signature, root cause, and exact resolution.+- [gcp-production.md](gcp-production.md): full production runbook+ (LB/DNS/TLS/env/rollback).+- [page-audit.md](page-audit.md): the browser-side console sweep+ (`npm run audit:web`), complementary to server logs.diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.mdindex d85d09492..795218540 100644--- a/docs/ops/gcp-production.md+++ b/docs/ops/gcp-production.md@@ -175,10 +175,14 @@ gcloud run services update-traffic three-ws-api --region us-central1 \--project aerial-vehicle-466722-p5 --to-revisions <good-revision>=100```-**Logs:**+**Logs:** use the reader CLI; it handles `jsonPayload` and request-log+entries that a raw `textPayload` read silently misses. Full guide incl. the+automated triage monitor: [gcp-logs.md](gcp-logs.md).```bash-gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" severity>=ERROR' \- --project aerial-vehicle-466722-p5 --freshness=1h --limit 20 --format="value(textPayload)"+npm run logs # three-ws-api, last hour (vercel logs equivalent)+npm run logs:tail # live tail+npm run logs:errors # ERROR+ across all services, last 6h+npm run triage:gcp # healthz + fleet log sweep -> classified action plan```**Build-context gotcha:** the upload is governed by the **allowlist** indiff --git a/docs/ops/production-log-triage.md b/docs/ops/production-log-triage.mdindex 8d1878884..82f1916f0 100644--- a/docs/ops/production-log-triage.md+++ b/docs/ops/production-log-triage.md@@ -20,6 +20,13 @@ Silencing any of them in code would hide a real production signal, so don't.Severity legend: 🔴 owner decision (money / security / billing) · 🟡 set an envvar or add quota · 🟢 self-healing, no action needed.+> **This table is now machine-checked.** `npm run triage:gcp`+> ([gcp-logs.md](gcp-logs.md)) sweeps WARNING+ logs across the whole Cloud Run+> fleet, matches them against these signatures, and emits a classified action+> plan; agents run the loop via the `/gcp-triage` skill. When you document a+> new signature here, also add it to `KNOWN_SIGNATURES` in+> [scripts/gcp-triage.mjs](../../scripts/gcp-triage.mjs).+> **You no longer need a log export to see most of this.** The platform now> self-reports internal-dependency health: **[/status](https://three.ws/status)**> renders it with a plain-language fix for each degradation, anddiff --git a/package.json b/package.jsonindex 9fdc5610f..9e3e17a97 100644--- a/package.json+++ b/package.json@@ -144,6 +144,10 @@"check:images": "node scripts/audit-image-loading.mjs --strict","audit:web": "node scripts/page-audit.mjs","audit:web:login": "node scripts/page-audit.mjs --login",+ "logs": "node scripts/gcp-logs.mjs",+ "logs:tail": "node scripts/gcp-logs.mjs --follow",+ "logs:errors": "node scripts/gcp-logs.mjs --all --errors --since 6h",+ "triage:gcp": "node scripts/gcp-triage.mjs","snapshot": "node scripts/page-snapshot.mjs","build:news": "node scripts/build-news.mjs","prebuild": "node scripts/copy-three-decoders.mjs && (node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & node scripts/build-discovery-cards.mjs & npm run build:club-assets & npm run build:walk-environments & wait) && node scripts/inject-blog-seo.mjs --write && node scripts/inject-hidden-guard.mjs --write && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/audit-empty-handlers.mjs && node scripts/audit-hidden-guard.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write",diff --git a/scripts/README.md b/scripts/README.mdindex a7434efd4..13e6df27e 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -8,6 +8,32 @@ This directory contains various scripts for the 3D-Agent application.## Operational+### `gcp-logs.mjs`: read/tail Cloud Run production logs (`vercel logs` equivalent)++```sh+npm run logs # three-ws-api, last hour+npm run logs:tail # live tail+npm run logs -- -s model-rig --errors --since 2d+npm run logs -- --all --grep "forge" --warnings+```++Renders app logs (`textPayload`/`jsonPayload`) and request logs chronologically,+severity-colored, for any service in the fleet. Full guide:+[docs/ops/gcp-logs.md](../docs/ops/gcp-logs.md).++### `gcp-triage.mjs`: automated production monitor++```sh+npm run triage:gcp # human report+npm run triage:gcp -- --json # what agents consume (exit 1 = actionable findings)+```++Merges `/api/healthz` with a fleet-wide WARNING+ log sweep, fingerprints+repeated signatures, classifies each against the runbook+([docs/ops/production-log-triage.md](../docs/ops/production-log-triage.md)) into+owner / env-action / investigate / self-healing, and prints the concrete action+per finding. Agents drive the fix loop via the `/gcp-triage` skill.+### `set-r2-cors.mjs` — apply the bucket CORS policyRuns the canonical CORS policy against the R2 bucket holding all mediadiff --git a/scripts/gcp-logs.mjs b/scripts/gcp-logs.mjsnew file mode 100644index 000000000..a344e2b58--- /dev/null+++ b/scripts/gcp-logs.mjs@@ -0,0 +1,229 @@+#!/usr/bin/env node+/**+ * gcp-logs: the `vercel logs` equivalent for our Cloud Run production.+ *+ * Reads Cloud Logging for any Cloud Run service in the project and renders+ * entries the way `vercel logs` did: one line per entry, chronological,+ * severity-colored, with app logs (textPayload/jsonPayload) and request logs+ * (httpRequest) both handled. `--follow` streams live via+ * `gcloud beta run services logs tail`.+ *+ * npm run logs # last hour, three-ws-api+ * npm run logs:tail # live tail (like `vercel logs --follow`)+ * npm run logs:errors # ERROR+ across ALL services, last 6h+ * npm run logs -- -s model-rig --since 2d # another service, wider window+ * npm run logs -- --grep forge --warnings # search payloads+ * npm run logs -- --http 500 # request logs with status >= 500+ * npm run logs -- --services # list Cloud Run services+ *+ * Requires an authenticated gcloud (this workspace already is).+ */++import { spawnSync, spawn } from 'node:child_process';++const DEFAULT_PROJECT = process.env.GCP_PROJECT || 'aerial-vehicle-466722-p5';+const DEFAULT_REGION = process.env.GCP_REGION || 'us-central1';+const DEFAULT_SERVICE = 'three-ws-api';++function parseArgs(argv) {+ const opts = {+ service: DEFAULT_SERVICE,+ all: false,+ follow: false,+ severity: null,+ http: null,+ appOnly: false,+ since: '1h',+ limit: 100,+ grep: null,+ json: false,+ listServices: false,+ project: DEFAULT_PROJECT,+ region: DEFAULT_REGION,+ };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ const next = () => argv[++i];+ switch (a) {+ case '-s': case '--service': opts.service = next(); break;+ case '--all': opts.all = true; break;+ case '-f': case '--follow': opts.follow = true; break;+ case '-e': case '--errors': opts.severity = 'ERROR'; break;+ case '-w': case '--warnings': opts.severity = 'WARNING'; break;+ case '--http': {+ const peek = argv[i + 1];+ opts.http = peek && /^\d{3}$/.test(peek) ? Number(next()) : 400;+ break;+ }+ case '--app': opts.appOnly = true; break;+ case '--since': opts.since = next(); break;+ case '-n': case '--limit': opts.limit = Number(next()); break;+ case '-g': case '--grep': opts.grep = next(); break;+ case '--json': opts.json = true; break;+ case '--services': opts.listServices = true; break;+ case '--project': opts.project = next(); break;+ case '--region': opts.region = next(); break;+ case '-h': case '--help': printHelp(); process.exit(0); break;+ default:+ console.error(`Unknown option: ${a} (see --help)`);+ process.exit(2);+ }+ }+ if (!/^\d+[smhdw]$/.test(opts.since)) {+ console.error(`--since must look like 30m, 2h, 1d (got "${opts.since}")`);+ process.exit(2);+ }+ if (!Number.isFinite(opts.limit) || opts.limit < 1) {+ console.error('--limit must be a positive number');+ process.exit(2);+ }+ return opts;+}++function printHelp() {+ console.log(`gcp-logs: a vercel-logs-style reader for Cloud Run production++Usage: node scripts/gcp-logs.mjs [options]++ -s, --service <name> Cloud Run service (default ${DEFAULT_SERVICE})+ --all every Cloud Run service in the project+ -f, --follow live tail (single service only)+ -e, --errors severity >= ERROR+ -w, --warnings severity >= WARNING+ --http [status] request logs only, status >= given code (default 400)+ --app app logs only (hide request logs)+ --since <window> how far back: 30m, 2h, 1d, 1w (default 1h)+ -n, --limit <n> max entries (default 100)+ -g, --grep <term> search all payload fields for a term+ --json raw JSON entries (for scripts/agents)+ --services list Cloud Run services and exit+ --project <id> GCP project (default ${DEFAULT_PROJECT})+ --region <region> region (default ${DEFAULT_REGION})`);+}++function gcloud(args, { inherit = false } = {}) {+ const res = spawnSync('gcloud', args, {+ encoding: 'utf8',+ stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'],+ maxBuffer: 64 * 1024 * 1024,+ });+ if (res.error) {+ console.error(`Failed to run gcloud: ${res.error.message}`);+ process.exit(1);+ }+ if (res.status !== 0 && !inherit) {+ console.error((res.stderr || '').trim() || `gcloud exited ${res.status}`);+ process.exit(res.status ?? 1);+ }+ return res.stdout ?? '';+}++function buildQuery(opts) {+ const parts = ['resource.type="cloud_run_revision"'];+ if (!opts.all) parts.push(`resource.labels.service_name="${opts.service}"`);+ if (opts.http != null) {+ parts.push('logName:"run.googleapis.com%2Frequests"');+ parts.push(`httpRequest.status>=${opts.http}`);+ } else if (opts.appOnly) {+ parts.push('NOT logName:"run.googleapis.com%2Frequests"');+ }+ if (opts.severity) parts.push(`severity>=${opts.severity}`);+ if (opts.grep) parts.push(JSON.stringify(opts.grep));+ return parts.join(' ');+}++const COLORS = {+ DEFAULT: '\x1b[2m', DEBUG: '\x1b[2m', INFO: '\x1b[36m', NOTICE: '\x1b[36m',+ WARNING: '\x1b[33m', ERROR: '\x1b[31m', CRITICAL: '\x1b[41m\x1b[97m',+ ALERT: '\x1b[41m\x1b[97m', EMERGENCY: '\x1b[41m\x1b[97m',+};+const RESET = '\x1b[0m';+const useColor = process.stdout.isTTY;++function paint(sev, text) {+ if (!useColor) return text;+ return `${COLORS[sev] || ''}${text}${RESET}`;+}++export function renderEntry(entry) {+ const ts = (entry.timestamp || '').replace('T', ' ').replace(/\.\d+Z$/, 'Z');+ const sev = entry.severity || 'DEFAULT';+ const service = entry.resource?.labels?.service_name || '?';+ let msg;+ if (entry.httpRequest) {+ const r = entry.httpRequest;+ const latency = r.latency ? ` ${String(r.latency).replace(/(\.\d{2})\d+s/, '$1s')}` : '';+ msg = `${r.status || '-'} ${r.requestMethod || '-'} ${r.requestUrl || ''}${latency}`;+ if (entry.textPayload) msg += ` :: ${entry.textPayload}`;+ } else if (entry.textPayload != null) {+ msg = entry.textPayload;+ } else if (entry.jsonPayload != null) {+ const p = entry.jsonPayload;+ msg = typeof p.message === 'string' && Object.keys(p).length === 1+ ? p.message+ : JSON.stringify(p);+ } else if (entry.protoPayload != null) {+ msg = `${entry.protoPayload.methodName || 'audit'} ${entry.protoPayload.status?.message || ''}`.trim();+ } else {+ msg = '(empty entry)';+ }+ return `${ts} ${paint(sev, sev.padEnd(7))} [${service}] ${msg}`;+}++export function fetchEntries(opts) {+ const query = buildQuery(opts);+ const out = gcloud([+ 'logging', 'read', query,+ `--project=${opts.project}`,+ `--freshness=${opts.since}`,+ `--limit=${opts.limit}`,+ '--order=desc',+ '--format=json',+ ]);+ const entries = JSON.parse(out || '[]');+ entries.reverse(); // chronological, like vercel logs+ return entries;+}++function main() {+ const opts = parseArgs(process.argv.slice(2));++ if (opts.listServices) {+ gcloud([+ 'run', 'services', 'list',+ `--project=${opts.project}`, `--region=${opts.region}`,+ '--format=table(metadata.name,status.url,status.latestReadyRevisionName)',+ ], { inherit: true });+ return;+ }++ if (opts.follow) {+ if (opts.all) {+ console.error('--follow tails one service at a time; drop --all or pass -s <service>.');+ process.exit(2);+ }+ console.error(`Tailing ${opts.service} (${opts.project}/${opts.region}); Ctrl-C to stop`);+ const child = spawn('gcloud', [+ 'beta', 'run', 'services', 'logs', 'tail', opts.service,+ `--project=${opts.project}`, `--region=${opts.region}`,+ ], { stdio: 'inherit' });+ child.on('exit', (code) => process.exit(code ?? 0));+ return;+ }++ const entries = fetchEntries(opts);+ if (opts.json) {+ process.stdout.write(JSON.stringify(entries, null, 2) + '\n');+ return;+ }+ if (!entries.length) {+ const scope = opts.all ? 'all services' : opts.service;+ console.log(`No matching entries for ${scope} in the last ${opts.since}. Widen with --since or drop filters.`);+ return;+ }+ for (const e of entries) console.log(renderEntry(e));+ console.error(`\n${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} (${opts.all ? 'all services' : opts.service}, last ${opts.since})${entries.length >= opts.limit ? '; hit --limit, raise -n for more' : ''}`);+}++const invokedDirectly = process.argv[1] && import.meta.url.endsWith(process.argv[1].split('/').pop());+if (invokedDirectly) main();diff --git a/scripts/gcp-triage.mjs b/scripts/gcp-triage.mjsnew file mode 100644index 000000000..ae4fe3fe1--- /dev/null+++ b/scripts/gcp-triage.mjs@@ -0,0 +1,354 @@+#!/usr/bin/env node+/**+ * gcp-triage: automated production monitor for the Cloud Run fleet.+ *+ * One command that answers "is production healthy, and if not, what exactly+ * do I do about it": pulls /api/healthz (the platform's own subsystem+ * roll-up), sweeps WARNING+ logs across every Cloud Run service, fingerprints+ * repeated signatures, matches them against the known-signature runbook+ * (docs/ops/production-log-triage.md), and emits a classified action plan.+ *+ * npm run triage:gcp # human report, last hour+ * npm run triage:gcp -- --since 6h # wider window+ * npm run triage:gcp -- --json # machine-readable, for agents+ *+ * Exit codes: 0 = healthy or self-healing noise only; 1 = findings that need+ * action; 2 = usage error. Agents: run with --json, then follow the fix+ * playbook in .claude/skills/gcp-triage/SKILL.md.+ */++import { spawnSync } from 'node:child_process';++const PROJECT = process.env.GCP_PROJECT || 'aerial-vehicle-466722-p5';+const HEALTHZ_URL = process.env.TRIAGE_HEALTHZ_URL || 'https://three.ws/api/healthz';+const RUNBOOK = 'docs/ops/production-log-triage.md';++// Classes, in escalation order. `owner` = only the owner can act (money,+// billing, security credential). `env-action` = fix is a pre-approved+// config-only `gcloud run services update` or quota lever. `investigate` =+// unknown signature, an agent should root-cause it. `self-healing` =+// documented graceful degradation, no action.+const CLASS_ORDER = { owner: 0, 'env-action': 1, investigate: 2, 'self-healing': 3 };++const KNOWN_SIGNATURES = [+ {+ id: 'ring-guard-violated',+ match: /\[ring-invariants\] SPEND PATH DISABLED/i,+ class: 'owner',+ action: `x402 ring guard env is half-configured; loop fails closed. Owner picks: pause (X402_AUTONOMOUS_ENABLED=false) or finish arming. ${RUNBOOK} §ring.`,+ },+ {+ id: 'world-unprotected',+ match: /world is UNPROTECTED|ADMIN_CODE is not set/i,+ class: 'owner',+ action: `world.three.ws serving without ADMIN_CODE: every visitor has build rights. Owner runs deploy/world/apply-hardening.sh. ${RUNBOOK} §world.`,+ },+ {+ id: 'replicate-credit',+ match: /replicate billing\/credit failure|insufficient credit/i,+ class: 'owner',+ action: `Replicate out of credit; forge degrades to free NVIDIA NIM lane meanwhile. Owner adds credit at replicate.com/account/billing. ${RUNBOOK} §replicate.`,+ },+ {+ id: 'db-storage-cap',+ match: /db at storage cap/i,+ class: 'env-action',+ action: `Neon over high-water; write crons preflight-skip until retention reclaims. Levers: DB_RETENTION_HIGH_WATER_MB, PUMP_INTEL_RETENTION_DAYS, or bigger Neon plan. ${RUNBOOK} §storage-cap.`,+ },+ {+ id: 'db-deadline',+ match: /\[x402-audit\] insert failed|db query exceeded \d+ms deadline/i,+ class: 'env-action',+ action: `Neon saturated; best-effort audit write timed out (telemetry only, never a payment). Capacity lever: Neon compute/pooler, or X402_AUDIT_WRITE_TIMEOUT_MS. ${RUNBOOK} §audit-insert.`,+ },+ {+ id: 'run-oom',+ match: /memory limit of \d+\s?MiB exceeded|Consider increasing the memory limit/i,+ class: 'env-action',+ action: 'Container OOM. Raise the service memory: gcloud run services update <service> --region us-central1 --memory <2x-current> (config-only, pre-approved).',+ },+ {+ id: 'run-no-instance',+ match: /no available instance|The request was aborted because there was no available instance/i,+ class: 'env-action',+ action: 'Cloud Run could not schedule an instance (max-instances or quota ceiling). Raise --max-instances or file the quota increase per docs/ops/gcp-credits-plan.md.',+ },+ {+ id: 'indexer-budget',+ match: /time-budget-exceeded/i,+ class: 'self-healing',+ action: `Indexer checkpointed mid-backfill and resumes next tick. Only act if it persists for many hours (slow RPC). ${RUNBOOK} §indexer.`,+ },+ {+ id: 'redis-degraded',+ match: /redis (SET|GET)? ?(failed|degraded)|circuit open(ed)?|memory fallback/i,+ class: 'self-healing',+ action: `Cache circuit breaker riding out an Upstash blip; reads keep serving. Optional: same-region cache store. ${RUNBOOK} §cache.`,+ },+ {+ id: 'helius-backoff',+ match: /helius quota|rate.?limited|refresh deferred \(transient upstream\)/i,+ class: 'self-healing',+ action: `Helius 429; public-RPC fallback serving. Optional: raise Helius plan. ${RUNBOOK} §helius.`,+ },+ {+ id: 'forge-fallback',+ match: /paid .* lane unavailable|degrading .* to free|falling back/i,+ class: 'self-healing',+ action: `Forge lane failover fired; generation keeps succeeding on the next rung. Tied to Replicate credit if you want the paid lane back. ${RUNBOOK} §forge.`,+ },+];++function parseArgs(argv) {+ const opts = { since: '1h', json: false, limit: 1000, project: PROJECT };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ const next = () => argv[++i];+ switch (a) {+ case '--since': opts.since = next(); break;+ case '--json': opts.json = true; break;+ case '-n': case '--limit': opts.limit = Number(next()); break;+ case '--project': opts.project = next(); break;+ case '-h': case '--help':+ console.log('Usage: node scripts/gcp-triage.mjs [--since 1h] [--json] [--limit 1000] [--project <id>]');+ process.exit(0);+ break;+ default:+ console.error(`Unknown option: ${a}`);+ process.exit(2);+ }+ }+ if (!/^\d+[smhdw]$/.test(opts.since)) {+ console.error(`--since must look like 30m, 2h, 1d (got "${opts.since}")`);+ process.exit(2);+ }+ return opts;+}++async function fetchHealthz() {+ try {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), 15000);+ const res = await fetch(HEALTHZ_URL, { signal: controller.signal });+ clearTimeout(timer);+ if (!res.ok) return { reachable: false, error: `HTTP ${res.status}` };+ const body = await res.json();+ return {+ reachable: true,+ status: body.subsystems?.status || body.status,+ degraded: body.subsystems?.degraded || [],+ subsystems: (body.subsystems?.subsystems || []).map((s) => ({+ name: s.name, status: s.status, detail: s.detail,+ })),+ ring: body.x402?.ring || null,+ };+ } catch (err) {+ return { reachable: false, error: err?.message || String(err) };+ }+}++function readLogs(opts) {+ const query = 'resource.type="cloud_run_revision" severity>=WARNING';+ const res = spawnSync('gcloud', [+ 'logging', 'read', query,+ `--project=${opts.project}`,+ `--freshness=${opts.since}`,+ `--limit=${opts.limit}`,+ '--format=json',+ ], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });+ if (res.status !== 0) {+ console.error((res.stderr || '').trim() || 'gcloud logging read failed');+ process.exit(1);+ }+ return JSON.parse(res.stdout || '[]');+}++function entryMessage(entry) {+ if (entry.textPayload != null) return entry.textPayload;+ if (entry.jsonPayload != null) {+ const p = entry.jsonPayload;+ return typeof p.message === 'string' ? p.message : JSON.stringify(p);+ }+ if (entry.protoPayload != null) {+ return `${entry.protoPayload.methodName || 'audit'} ${entry.protoPayload.status?.message || ''}`.trim();+ }+ return '';+}++// Collapse volatile tokens so repeated occurrences of one signature group+// together regardless of ids, sizes, and durations embedded in the line.+export function fingerprint(message) {+ return message+ .replace(/\b0x[0-9a-fA-F]{6,}\b/g, '<hex>')+ .replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}\b/g, '<uuid>')+ .replace(/\b[1-9A-HJ-NP-Za-km-z]{32,44}\b/g, '<addr>')+ .replace(/\bhttps?:\/\/\S+/g, '<url>')+ .replace(/\d+(\.\d+)?/g, '<n>')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, 160);+}++export function classify(message) {+ for (const sig of KNOWN_SIGNATURES) {+ if (sig.match.test(message)) return sig;+ }+ return null;+}++function normalizePath(url) {+ try {+ const path = new URL(url).pathname;+ return path+ .replace(/\/[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}(?=\/|$)/g, '/<uuid>')+ .replace(/\/\d+(?=\/|$)/g, '/<n>')+ .replace(/\/[1-9A-HJ-NP-Za-km-z]{32,44}(?=\/|$)/g, '/<addr>');+ } catch {+ return url || '(unknown)';+ }+}++export function buildFindings(entries) {+ const appGroups = new Map();+ const httpGroups = new Map();++ for (const entry of entries) {+ const service = entry.resource?.labels?.service_name || '?';+ const ts = entry.timestamp || '';+ if (entry.httpRequest) {+ const status = entry.httpRequest.status || 0;+ if (status < 500 && status !== 429) continue; // 4xx is client behavior; 402 is the product+ const key = `${service} ${status} ${entry.httpRequest.requestMethod} ${normalizePath(entry.httpRequest.requestUrl)}`;+ const g = httpGroups.get(key) || {+ kind: 'http', service, status,+ title: `HTTP ${status} ${entry.httpRequest.requestMethod} ${normalizePath(entry.httpRequest.requestUrl)}`,+ count: 0, firstSeen: ts, lastSeen: ts,+ sample: `${entry.httpRequest.requestUrl} (ua: ${entry.httpRequest.userAgent || '-'})`,+ };+ g.count++;+ if (ts < g.firstSeen) g.firstSeen = ts;+ if (ts > g.lastSeen) g.lastSeen = ts;+ httpGroups.set(key, g);+ } else {+ const message = entryMessage(entry);+ if (!message) continue;+ const fp = fingerprint(message);+ const g = appGroups.get(fp) || {+ kind: 'app', title: fp, count: 0, services: new Set(),+ severity: entry.severity || 'WARNING', firstSeen: ts, lastSeen: ts, sample: message.slice(0, 400),+ };+ g.count++;+ g.services.add(service);+ if ((entry.severity || '') === 'ERROR' || (entry.severity || '').startsWith('CRIT')) g.severity = entry.severity;+ if (ts < g.firstSeen) g.firstSeen = ts;+ if (ts > g.lastSeen) g.lastSeen = ts;+ appGroups.set(fp, g);+ }+ }++ const findings = [];+ for (const g of appGroups.values()) {+ const sig = classify(g.sample) || classify(g.title);+ findings.push({+ kind: 'app',+ class: sig ? sig.class : 'investigate',+ signature: sig ? sig.id : null,+ title: g.title,+ severity: g.severity,+ count: g.count,+ services: [...g.services],+ firstSeen: g.firstSeen,+ lastSeen: g.lastSeen,+ sample: g.sample,+ action: sig+ ? sig.action+ : `Unknown signature. Root-cause it: npm run logs -- -s ${[...g.services][0]} --grep "${g.title.split(' ').slice(0, 3).join(' ')}" --since 6h, then fix in code or add it to ${RUNBOOK} + this script's KNOWN_SIGNATURES if it is expected degradation.`,+ });+ }+ for (const g of httpGroups.values()) {+ findings.push({+ kind: 'http',+ class: g.status === 429 ? 'self-healing' : 'investigate',+ signature: null,+ title: g.title,+ severity: g.status >= 500 ? 'ERROR' : 'WARNING',+ count: g.count,+ services: [g.service],+ firstSeen: g.firstSeen,+ lastSeen: g.lastSeen,+ sample: g.sample,+ action: g.status === 429+ ? 'Rate limiter doing its job; only act on a legitimate-traffic spike.'+ : `5xx on a served route. Correlate with app logs: npm run logs -- -s ${g.service} --errors --app --since 6h, and check forge_creations if it is a generation route.`,+ });+ }++ findings.sort((a, b) =>+ (CLASS_ORDER[a.class] - CLASS_ORDER[b.class]) || (b.count - a.count));+ return findings;+}++const CLASS_BADGE = {+ owner: '🔴 owner',+ 'env-action': '🟡 env-action',+ investigate: '🟠 investigate',+ 'self-healing': '🟢 self-healing',+};++function renderReport({ opts, healthz, findings, scanned }) {+ const lines = [];+ lines.push(`# gcp-triage: last ${opts.since}, project ${opts.project}`);+ lines.push('');+ if (!healthz.reachable) {+ lines.push(`## Healthz: UNREACHABLE (${healthz.error}); treat as an outage: check the LB and three-ws-api first`);+ } else {+ lines.push(`## Healthz: ${healthz.status}${healthz.degraded.length ? ` (${healthz.degraded.map((d) => d.name || d).join(', ')})` : ' (all subsystems ok)'}`);+ for (const s of healthz.subsystems.filter((s) => s.status !== 'ok')) {+ lines.push(` - ${s.name}: ${s.status} (${s.detail})`);+ }+ }+ lines.push('');+ const actionable = findings.filter((f) => f.class !== 'self-healing');+ lines.push(`## Log sweep: ${scanned} WARNING+ entries → ${findings.length} distinct signatures (${actionable.length} actionable)`);+ lines.push('');+ if (!findings.length) lines.push('Nothing above WARNING in the window. Production is quiet.');+ for (const f of findings) {+ lines.push(`### ${CLASS_BADGE[f.class]} ×${f.count} [${f.services.join(', ')}] ${f.title}`);+ lines.push(` last seen ${f.lastSeen}`);+ lines.push(` → ${f.action}`);+ lines.push('');+ }+ return lines.join('\n');+}++async function main() {+ const opts = parseArgs(process.argv.slice(2));+ const [healthz, entries] = await Promise.all([+ fetchHealthz(),+ Promise.resolve().then(() => readLogs(opts)),+ ]);+ const findings = buildFindings(entries);+ const actionable = findings.filter((f) => f.class !== 'self-healing');+ const unhealthy = !healthz.reachable+ || (healthz.degraded && healthz.degraded.length > 0)+ || actionable.length > 0;++ if (opts.json) {+ process.stdout.write(JSON.stringify({+ generatedAt: new Date().toISOString(),+ window: opts.since,+ project: opts.project,+ scannedEntries: entries.length,+ healthz,+ findings,+ actionable: actionable.length,+ healthy: !unhealthy,+ }, null, 2) + '\n');+ } else {+ console.log(renderReport({ opts, healthz, findings, scanned: entries.length }));+ }+ process.exit(unhealthy ? 1 : 0);+}++const invokedDirectly = process.argv[1] && import.meta.url.endsWith(process.argv[1].split('/').pop());+if (invokedDirectly) await main();