hostinger-api-mcp 4.15.0 → 4.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +23 -2
  3. package/gemini-extension.json +1 -1
  4. package/package.json +1 -1
  5. package/server.json +2 -2
  6. package/skills/headless/VERSION +3 -3
  7. package/skills/headless/connect/bootstrap.mjs +3 -3
  8. package/skills/headless/run-log.mjs +17 -4
  9. package/src/core/runtime.js +1 -1
  10. package/src/core/runtime.ts +1 -1
  11. package/src/core/skills.js +6 -6
  12. package/src/core/skills.ts +6 -6
  13. package/src/core/tools/all.js +101 -0
  14. package/src/core/tools/all.ts +101 -0
  15. package/src/core/tools/ecommerce.js +101 -0
  16. package/src/core/tools/ecommerce.ts +101 -0
  17. package/src/servers/agency-hosting.js +1 -1
  18. package/src/servers/agency-hosting.ts +1 -1
  19. package/src/servers/agent-readiness.js +1 -1
  20. package/src/servers/agent-readiness.ts +1 -1
  21. package/src/servers/all.js +1 -1
  22. package/src/servers/all.ts +1 -1
  23. package/src/servers/billing.js +1 -1
  24. package/src/servers/billing.ts +1 -1
  25. package/src/servers/dns.js +1 -1
  26. package/src/servers/dns.ts +1 -1
  27. package/src/servers/domains.js +1 -1
  28. package/src/servers/domains.ts +1 -1
  29. package/src/servers/ecommerce.js +1 -1
  30. package/src/servers/ecommerce.ts +1 -1
  31. package/src/servers/gpu.js +1 -1
  32. package/src/servers/gpu.ts +1 -1
  33. package/src/servers/horizons.js +1 -1
  34. package/src/servers/horizons.ts +1 -1
  35. package/src/servers/hosting.js +1 -1
  36. package/src/servers/hosting.ts +1 -1
  37. package/src/servers/mail.js +1 -1
  38. package/src/servers/mail.ts +1 -1
  39. package/src/servers/reach.js +1 -1
  40. package/src/servers/reach.ts +1 -1
  41. package/src/servers/vps.js +1 -1
  42. package/src/servers/vps.ts +1 -1
  43. package/src/servers/wordpress.js +1 -1
  44. package/src/servers/wordpress.ts +1 -1
  45. package/types.d.ts +47 -0
@@ -117,10 +117,10 @@ const skills: Skill[] = [
117
117
  },
118
118
  {
119
119
  "uri": "skill://hostinger-headless/connect/bootstrap.mjs",
120
- "digest": "sha256:61646f8c7aabf99bb23549c8877a1acd7579c010c9d311ac3808681675c6efff",
121
- "size": 6177,
120
+ "digest": "sha256:fc983c62d8eddfc92f5cb4cf3cc8f28a0f58d5f33a1108c5c425d874b076a7dc",
121
+ "size": 6172,
122
122
  "mimeType": "text/plain",
123
- "text": "#!/usr/bin/env node\n// Hostinger Headless — bootstrap.\n// Verifies the Hostinger MCP server is reachable and drives the OAuth sign-in,\n// emitting one JSON event per line on stdout so a coding agent can relay\n// progress to the user. Its only writes are the launcher (~/.hostinger/mcp/launch.mjs, which\n// coding tools register) and what the MCP itself stores (OAuth credentials); no network calls of its own.\nimport { spawn, spawnSync } from 'node:child_process';\nimport { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\n\n// ── tiny event protocol (one JSON object per line) ───────────────────────────\nconst emit = (event, extra = {}) =>\n process.stdout.write(JSON.stringify({ event, ...extra }) + '\\n');\nconst fail = (event, extra = {}) => {\n emit(event, { ok: false, ...extra });\n process.exit(1);\n};\n\n// ── the MCP server, always through the launcher ──────────────────────────────\n// launch.mjs runs the latest published package via npx from the home folder (see its header for why\n// npx must never run in the project). Coding tools register the home copy, which every run refreshes,\n// so a registration keeps working when the skill folder moves to a new version.\nconst isWin = process.platform === 'win32';\nconst LAUNCHER = path.join(os.homedir(), '.hostinger', 'mcp', 'launch.mjs');\ntry {\n mkdirSync(path.dirname(LAUNCHER), { recursive: true });\n copyFileSync(new URL('./launch.mjs', import.meta.url), LAUNCHER);\n copyFileSync(new URL('./launch.sh', import.meta.url), LAUNCHER.replace(/\\.mjs$/, '.sh'));\n} catch (e) {\n fail('launcher_failed', { detail: String(e) });\n}\nconst MCP = [process.execPath, LAUNCHER];\n// A registration never names a bare `node`: Windows looks it up in the working directory (the project)\n// first, and a version manager's shim (asdf, mise) runs the Node the project's .tool-versions names.\n// macOS/Linux register /bin/sh with launch.sh, which finds node only after moving to home, so Node\n// upgrades keep working. Windows names this Node by absolute path (this script runs from home).\nemit('launcher', isWin\n ? { command: process.execPath, args: [LAUNCHER] }\n : { command: '/bin/sh', args: [LAUNCHER.replace(/\\.mjs$/, '.sh')] });\n\nfunction capture(cmd, args) {\n const r = spawnSync(cmd, args, { encoding: 'utf8', cwd: os.homedir() });\n return { status: r.status ?? 1, out: `${r.stdout || ''}${r.stderr || ''}`, error: r.error };\n}\n\n// ── 1. MCP server reachable ──────────────────────────────────────────────────\nfunction checkMcp() {\n const r = capture(MCP[0], [...MCP.slice(1), '--version']);\n if (r.status !== 0) fail('mcp_unreachable', { detail: r.out.trim().slice(0, 400) });\n // npx interleaves \"npm notice …\" lines, so pick the first semver-looking token.\n const version = (r.out.match(/\\d+\\.\\d+\\.\\d+[^\\s]*/) || [])[0] || r.out.trim().split('\\n').pop();\n emit('mcp_ok', { version });\n}\n\n// ── 2. Existing auth? ────────────────────────────────────────────────────────\n// An env token always wins (the MCP bypasses OAuth entirely when it is set).\n// Otherwise stored OAuth credentials mean a previous sign-in can be reused —\n// the MCP refreshes expired tokens automatically on the first tool call.\nfunction existingAuth() {\n if (process.env.HOSTINGER_API_TOKEN || process.env.API_TOKEN) {\n return 'api_token';\n }\n const base = isWin ? (process.env.APPDATA || os.homedir()) : path.join(os.homedir(), '.config');\n const credsPath = path.join(base, 'hostinger-mcp', 'credentials.json');\n if (existsSync(credsPath)) {\n try {\n const creds = JSON.parse(readFileSync(credsPath, 'utf8'));\n if (creds.refresh_token || (creds.access_token && creds.expires_at > Date.now())) {\n return 'oauth_cached';\n }\n } catch {\n /* unreadable credentials — fall through to a fresh login */\n }\n }\n return null;\n}\n\n// ── 3. Login (human-in-the-loop browser flow) ────────────────────────────────\n// `hostinger-api-mcp --login` opens the Hostinger sign-in page and listens on\n// an ephemeral localhost port for the OAuth callback, so the browser must run\n// on this same machine. It prints the sign-in URL to stderr with a stable\n// prefix — forward it so the agent can show it if the browser didn't open.\nfunction login() {\n return new Promise((resolve) => {\n const child = spawn(MCP[0], [...MCP.slice(1), '--login'], { cwd: os.homedir() });\n let diag = '';\n let urlSent = false;\n const collect = (chunk) => {\n diag = (diag + chunk).slice(-2000);\n if (!urlSent) {\n const m = diag.match(/Opening browser for sign-in:\\s*\\n\\s*(https?:\\/\\/\\S+)/);\n if (m) {\n urlSent = true;\n emit('awaiting_user', {\n verificationUri: m[1],\n note: 'A browser window should have opened. If not, open this URL manually on this machine and sign in.',\n });\n }\n }\n };\n child.stderr?.on('data', collect);\n child.stdout?.on('data', collect);\n child.on('close', (code) => {\n if (code === 0 && /Sign-in successful/i.test(diag)) {\n emit('logged_in', { method: 'oauth' });\n resolve();\n return;\n }\n const detail = diag.trim().slice(-1500) || `--login exited (code ${code}) with no output.`;\n fail('login_failed', { code, detail });\n });\n child.on('error', (e) => fail('login_failed', { detail: String(e) }));\n });\n}\n\n// ── main ─────────────────────────────────────────────────────────────────────\ncheckMcp();\nconst method = existingAuth();\nif (method) {\n emit('logged_in', { method });\n} else {\n await login();\n}\nemit('success');\n"
123
+ "text": "#!/usr/bin/env node\n// Hostinger Headless — bootstrap.\n// Verifies the Hostinger MCP server is reachable and drives the OAuth sign-in,\n// emitting one JSON event per line on stdout so a coding agent can relay\n// progress to the user. Its only writes are the launcher (~/.hostinger/mcp/launch.mjs, which\n// coding tools register) and what the MCP itself stores (OAuth credentials); no network calls of its own.\nimport { spawn, spawnSync } from 'node:child_process';\nimport { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\n\n// ── tiny event protocol (one JSON object per line) ───────────────────────────\nconst emit = (event, extra = {}) =>\n process.stdout.write(JSON.stringify({ event, ...extra }) + '\\n');\nconst fail = (event, extra = {}) => {\n emit(event, { ok: false, ...extra });\n process.exit(1);\n};\n\n// ── the MCP server, always through the launcher ──────────────────────────────\n// launch.mjs runs the latest published package via npx from the home folder (see its header for why\n// npx must never run in the project). Coding tools register the home copy, which every run refreshes,\n// so a registration keeps working when the skill folder moves to a new version.\nconst isWin = process.platform === 'win32';\nconst LAUNCHER = path.join(os.homedir(), '.hostinger', 'mcp', 'launch.mjs');\ntry {\n mkdirSync(path.dirname(LAUNCHER), { recursive: true });\n copyFileSync(new URL('./launch.mjs', import.meta.url), LAUNCHER);\n copyFileSync(new URL('./launch.sh', import.meta.url), LAUNCHER.replace(/\\.mjs$/, '.sh'));\n} catch (e) {\n fail('launcher_failed', { detail: String(e) });\n}\nconst MCP = [process.execPath, LAUNCHER];\n// A registration never names a bare `node`: Windows looks it up in the working directory (the project)\n// first, and a version manager's shim (asdf, mise) runs the Node the project's .tool-versions names.\n// macOS/Linux register /bin/sh with launch.sh, which finds node only after moving to home, so Node\n// upgrades keep working. Windows names this Node by absolute path (this script runs from home).\nemit('launcher', isWin\n ? { command: process.execPath, args: [LAUNCHER] }\n : { command: '/bin/sh', args: [LAUNCHER.replace(/\\.mjs$/, '.sh')] });\n\nfunction capture(args) {\n const r = spawnSync(MCP[0], [...MCP.slice(1), ...args], { encoding: 'utf8', cwd: os.homedir() });\n return { status: r.status ?? 1, out: `${r.stdout || ''}${r.stderr || ''}`, error: r.error };\n}\n\n// ── 1. MCP server reachable ──────────────────────────────────────────────────\nfunction checkMcp() {\n const r = capture(['--version']);\n if (r.status !== 0) fail('mcp_unreachable', { detail: r.out.trim().slice(0, 400) });\n // npx interleaves \"npm notice …\" lines, so pick the first semver-looking token.\n const version = (r.out.match(/\\d+\\.\\d+\\.\\d+[^\\s]*/) || [])[0] || r.out.trim().split('\\n').pop();\n emit('mcp_ok', { version });\n}\n\n// ── 2. Existing auth? ────────────────────────────────────────────────────────\n// An env token always wins (the MCP bypasses OAuth entirely when it is set).\n// Otherwise stored OAuth credentials mean a previous sign-in can be reused —\n// the MCP refreshes expired tokens automatically on the first tool call.\nfunction existingAuth() {\n if (process.env.HOSTINGER_API_TOKEN || process.env.API_TOKEN) {\n return 'api_token';\n }\n const base = isWin ? (process.env.APPDATA || os.homedir()) : path.join(os.homedir(), '.config');\n const credsPath = path.join(base, 'hostinger-mcp', 'credentials.json');\n if (existsSync(credsPath)) {\n try {\n const creds = JSON.parse(readFileSync(credsPath, 'utf8'));\n if (creds.refresh_token || (creds.access_token && creds.expires_at > Date.now())) {\n return 'oauth_cached';\n }\n } catch {\n /* unreadable credentials — fall through to a fresh login */\n }\n }\n return null;\n}\n\n// ── 3. Login (human-in-the-loop browser flow) ────────────────────────────────\n// `hostinger-api-mcp --login` opens the Hostinger sign-in page and listens on\n// an ephemeral localhost port for the OAuth callback, so the browser must run\n// on this same machine. It prints the sign-in URL to stderr with a stable\n// prefix — forward it so the agent can show it if the browser didn't open.\nfunction login() {\n return new Promise((resolve) => {\n const child = spawn(MCP[0], [...MCP.slice(1), '--login'], { cwd: os.homedir() });\n let diag = '';\n let urlSent = false;\n const collect = (chunk) => {\n diag = (diag + chunk).slice(-2000);\n if (!urlSent) {\n const m = diag.match(/Opening browser for sign-in:\\s*\\n\\s*(https?:\\/\\/\\S+)/);\n if (m) {\n urlSent = true;\n emit('awaiting_user', {\n verificationUri: m[1],\n note: 'A browser window should have opened. If not, open this URL manually on this machine and sign in.',\n });\n }\n }\n };\n child.stderr?.on('data', collect);\n child.stdout?.on('data', collect);\n child.on('close', (code) => {\n if (code === 0 && /Sign-in successful/i.test(diag)) {\n emit('logged_in', { method: 'oauth' });\n resolve();\n return;\n }\n const detail = diag.trim().slice(-1500) || `--login exited (code ${code}) with no output.`;\n fail('login_failed', { code, detail });\n });\n child.on('error', (e) => fail('login_failed', { detail: String(e) }));\n });\n}\n\n// ── main ─────────────────────────────────────────────────────────────────────\ncheckMcp();\nconst method = existingAuth();\nif (method) {\n emit('logged_in', { method });\n} else {\n await login();\n}\nemit('success');\n"
124
124
  },
125
125
  {
126
126
  "uri": "skill://hostinger-headless/connect/launch.mjs",
@@ -201,10 +201,10 @@ const skills: Skill[] = [
201
201
  },
202
202
  {
203
203
  "uri": "skill://hostinger-headless/run-log.mjs",
204
- "digest": "sha256:a9ee9600a0e3287f828e2e9a48aacea9ba61b07893e904b1ecf330d1c93188e3",
205
- "size": 52670,
204
+ "digest": "sha256:fac648c79e8748be46e605eb345ecda7b27dd082c5ae543404c58e5fff645a78",
205
+ "size": 53575,
206
206
  "mimeType": "text/plain",
207
- "text": "#!/usr/bin/env node\n// Hostinger Headless run log: records a build as it happens and writes reports/<run>.json + .html.\n//\n// node run-log.mjs <domain> run-start [--kind build|resume|redesign|iterate] [--tool <tool>] [--model <model>] [--skill <version>] [--take-over]\n// node run-log.mjs <domain> run-update [--kind …] [--model …] [--skill …]\n// node run-log.mjs <domain> run-resume [--reason \"<text>\"]\n// node run-log.mjs <domain> stage-start <stage> [--phase <phase>] [--started-ago 6m | --started-at <ISO time>]\n// node run-log.mjs <domain> stage-end <stage> <result> [--phase <phase>] [--note \"<text>\"] [--started-ago 6m | --started-at <ISO time>]\n// node run-log.mjs <domain> next <stage> [--phase <phase>]\n// node run-log.mjs <domain> stage-fix <stage> [--phase <phase>] (--started-ago 6m | --started-at <ISO time>)\n// node run-log.mjs <domain> event <issue|feedback|skill_gap|good> '<json>'\n// node run-log.mjs <domain> pause\n// node run-log.mjs <domain> report [--outcome live|stopped|failed|abandoned] [--tokens '<json>']\n// node run-log.mjs <domain> unsent\n// node run-log.mjs <domain> report-sent [<run>]\n// node run-log.mjs <domain> report-rejected [<run>]\n\nimport { spawnSync } from 'node:child_process';\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { homedir, hostname } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst STAGES = ['refine', 'connect', 'check_state', 'provision', 'content_model', 'design', 'frontend', 'validate', 'deploy', 'done'];\n// Stages that stop for the user to restart their tool, so it loads a newly registered Hostinger MCP server.\nconst RESTART_STAGES = ['connect', 'provision', 'content_model'];\nconst PAUSE_NOTE = 'paused for a tool restart';\n// A domain names a folder under ~/.hostinger, so \"../x\" or \"a/b\" must never reach the file system.\nconst HOSTNAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;\nconst RESULTS = ['ok', 'ok_after_retries', 'ok_with_fixups', 'failed', 'skipped', 'stopped'];\nconst OUTCOMES = ['live', 'stopped', 'failed', 'abandoned'];\nconst EVENT_FIELDS = {\n issue: { required: ['stage', 'symptom'], optional: ['cause', 'workaround', 'severity', 'resolved', 'user_had_to_intervene'] },\n feedback: { required: ['stage', 'category', 'paraphrase'], optional: [] },\n skill_gap: { required: ['skill', 'gap'], optional: ['stage'] },\n good: { required: ['text'], optional: ['stage'] },\n};\nconst EVENT_LISTS = { issue: 'issues', feedback: 'user_feedback', skill_gap: 'skill_gaps', good: 'what_went_well' };\n\nconst here = dirname(fileURLToPath(import.meta.url));\nconst now = () => new Date().toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n// A start logged late is kept but marked estimated, so the report can tell measured times from remembered ones.\nfunction lateStart(flags, run) {\n let at = null;\n if (typeof flags['started-at'] === 'string') {\n if (Number.isNaN(Date.parse(flags['started-at']))) fail(`--started-at \"${flags['started-at']}\" is not a time; use e.g. 2026-10-13T06:26:00Z`);\n at = Date.parse(flags['started-at']);\n } else if (typeof flags['started-ago'] === 'string') {\n const m = flags['started-ago'].match(/^(\\d+(?:\\.\\d+)?)\\s*([smh])$/);\n if (!m) fail(`--started-ago \"${flags['started-ago']}\" should look like 90s, 6m or 1h`);\n at = Date.now() - Number(m[1]) * { s: 1e3, m: 6e4, h: 36e5 }[m[2]];\n }\n if (at === null) return null;\n const clamped = Math.min(Math.max(at, Date.parse(run.started_at)), Date.now());\n return new Date(clamped).toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n}\n\nconst fail = (message) => {\n console.error(`run-log: ${message}`);\n process.exit(1);\n};\n\nfunction parseArgs(argv) {\n const positional = [];\n const flags = {};\n for (let i = 0; i < argv.length; i += 1) {\n if (argv[i].startsWith('--')) {\n const key = argv[i].slice(2);\n const value = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[(i += 1)] : true;\n flags[key] = value;\n } else positional.push(argv[i]);\n }\n return { positional, flags };\n}\n\nconst readJson = (file, fallback) => (existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : fallback);\nconst writeJson = (file, value) => writeFileSync(file, `${JSON.stringify(value, null, 2)}\\n`);\n\n// run-start is a run's first command, before anything else has written to the workspace.\nfunction workspace(domain, { create = false } = {}) {\n if (!domain || domain.startsWith('-')) fail('first argument must be the domain');\n if (!HOSTNAME.test(domain)) fail(`\"${domain}\" is not a domain (use its ASCII form, e.g. xn--caf-dma.com)`);\n const dir = join(homedir(), '.hostinger', domain);\n if (create) mkdirSync(dir, { recursive: true });\n else if (!existsSync(dir)) fail(`no workspace at ${dir}; run-start creates it`);\n return {\n dir,\n domain,\n statePath: join(dir, 'state.json'),\n logPath: join(dir, 'run-log.json'),\n eventsPath: join(dir, 'events.jsonl'),\n reportsDir: join(dir, 'reports'),\n lockPath: join(dir, '.lock'),\n };\n}\n\n// One session at a time builds a domain, and .lock names it. The holder is the agent process (Claude\n// Code, Codex, claude -p): each command runs in a short-lived shell under it, so the nearest ancestor\n// that isn't a shell or a wrapper lives as long as the session and no longer.\n// Linux ps cuts a name to 15 characters, so each wrapper also matches its cut form.\nconst WRAPPERS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'pwsh', 'powershell', 'cmd', 'sandbox-exec', 'bwrap', 'codex-linux-sandbox', 'env', 'timeout', 'caffeinate']\n .flatMap((name) => [name, name.slice(0, 15)]));\n// A lock whose holder can't be checked (another host, no process list, the old timestamp-only lock)\n// counts as live while it was refreshed this recently.\nconst LOCK_FRESH_MS = 30 * 60 * 1000;\n\nconst processName = (name) => basename(name.replace(/\\\\/g, '/')).replace(/^-/, '').replace(/\\.exe$/i, '').toLowerCase();\n\n// pid -> { ppid, started, name }; null when the process list can't be read. The start time tells a\n// reused PID from the process that held the lock.\nfunction processTable() {\n const windows = process.platform === 'win32';\n const r = windows\n ? spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',\n 'Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId)`t$($_.ParentProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\\'o\\') })`t$($_.Name)\" }'], { encoding: 'utf8' })\n : spawnSync('ps', ['-A', '-o', 'pid=,ppid=,lstart=,comm='], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' } });\n if (r.status !== 0 || !r.stdout) return null;\n const table = new Map();\n for (const line of r.stdout.split(/\\r?\\n/)) {\n const m = windows ? line.match(/^(\\d+)\\t(\\d+)\\t([^\\t]*)\\t(.*)$/) : line.trim().match(/^(\\d+)\\s+(\\d+)\\s+(\\w+\\s+\\w+\\s+\\d+\\s+[\\d:]+\\s+\\d+)\\s+(.*)$/);\n if (m) table.set(Number(m[1]), { ppid: Number(m[2]), started: m[3].replace(/\\s+/g, ' ') || null, name: m[4] });\n }\n return table.size ? table : null;\n}\n\nfunction currentHolder(table) {\n let pid = process.ppid;\n while (table?.has(pid) && WRAPPERS.has(processName(table.get(pid).name))) pid = table.get(pid).ppid;\n const proc = table?.get(pid);\n return { host: hostname(), pid, started: proc?.started ?? null, process: proc ? processName(proc.name) : null };\n}\n\n// The old timestamp-only lock, or one another session is still writing, has no holder: only a time.\nfunction readLock(ws) {\n let text;\n let mtime;\n try {\n text = readFileSync(ws.lockPath, 'utf8');\n mtime = statSync(ws.lockPath).mtimeMs;\n } catch {\n return null;\n }\n try {\n const lock = JSON.parse(text);\n if (lock && typeof lock === 'object' && Number.isInteger(lock.pid)) return lock;\n } catch {}\n const stamped = Date.parse(text.trim());\n const refreshed = new Date(Number.isNaN(stamped) ? mtime : stamped).toISOString();\n return { host: null, pid: null, started: null, process: null, tool: null, acquired_at: refreshed, refreshed_at: refreshed };\n}\n\nconst byRecency = (lock) => (Date.now() - Date.parse(lock.refreshed_at) < LOCK_FRESH_MS ? 'live' : 'dead');\n\n// own, live or dead; unverified when there is no process list (a sandbox that blocks ps), where the\n// holder found is the command's own shell and this session can't be told from another on this host.\nfunction lockStatus(lock, me, table) {\n if (lock.host !== me.host) return byRecency(lock);\n if (!table) return 'unverified';\n if (lock.pid === me.pid && lock.started === me.started) return 'own';\n if (lock.started) return table.get(lock.pid)?.started === lock.started ? 'live' : 'dead';\n return byRecency(lock);\n}\n\n// Replacing the lock goes through a rename, so a reader never sees half of it.\nfunction writeLock(ws, lock) {\n const tmp = `${ws.lockPath}.${process.pid}.tmp`;\n writeJson(tmp, lock);\n renameSync(tmp, ws.lockPath);\n}\n\n// Of two sessions creating a missing lock at once, exactly one succeeds.\nfunction createLock(ws, lock) {\n try {\n writeFileSync(ws.lockPath, `${JSON.stringify(lock, null, 2)}\\n`, { flag: 'wx' });\n return true;\n } catch (error) {\n if (error.code === 'EEXIST') return false;\n throw error;\n }\n}\n\n// Reads the run log without migrating it: a refused session writes nothing.\nfunction holderStage(ws) {\n try {\n const log = readJson(ws.logPath, {});\n const open = openStages(log, log.run?.id).at(-1);\n return { tool: log.run?.tool ?? null, stage: open ? stageLabel(open) : null };\n } catch {\n return { tool: null, stage: null };\n }\n}\n\nfunction refuse(ws, lock, { offerTakeOver }) {\n const { tool, stage } = holderStage(ws);\n const who = [\n lock.tool ?? tool ?? lock.process,\n lock.pid === null ? null : lock.host === hostname() ? `pid ${lock.pid}` : `on ${lock.host}`,\n `since ${lock.acquired_at}`,\n stage && `in ${stage}`,\n ].filter(Boolean).join(', ');\n const takeOver = offerTakeOver ? '. Only if the user says to take over, run run-start --take-over: the other session stops at its next step' : '';\n fail(`another session (${who}) is building ${ws.domain}; stop and tell the user${takeOver}`);\n}\n\n// Checks the lock before a command writes anything: another live session's lock refuses it, and this\n// session's own lock is refreshed. `take` also takes a missing lock or one whose holder is gone.\n// `start` (run-start) does too, offers a takeover when refused, and with `takeOver` takes a live lock.\n// wasFree: no lock existed.\nfunction claimLock(ws, { take = false, start = false, takeOver = false, tool = null }) {\n const table = processTable();\n const me = currentHolder(table);\n const record = () => ({ ...me, tool, acquired_at: now(), refreshed_at: now() });\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const lock = readLock(ws);\n if (!lock) {\n if (!take) return { lock: null, wasFree: true };\n const fresh = record();\n if (createLock(ws, fresh)) return { lock: fresh, wasFree: true };\n continue;\n }\n // An unverified lock: run-start judges it by recency, and a later command trusts that run-start\n // settled it rather than refuse its own session.\n const verdict = lockStatus(lock, me, table);\n const status = verdict === 'unverified' ? (start ? byRecency(lock) : 'own') : verdict;\n if (status === 'own') {\n const refreshed = { ...lock, tool: tool ?? lock.tool, refreshed_at: now() };\n writeLock(ws, refreshed);\n return { lock: refreshed, wasFree: false };\n }\n if (status === 'live' && !takeOver) refuse(ws, lock, { offerTakeOver: start });\n if (!take) return { lock: null, wasFree: false };\n // Two sessions taking over the same dead lock at once both rename theirs in; the one that lost\n // is refused at its next command.\n const taken = record();\n writeLock(ws, taken);\n return { lock: taken, wasFree: false };\n }\n fail(`${ws.lockPath} keeps appearing and disappearing; another session is starting on ${ws.domain}. Stop and tell the user`);\n}\n\n// state.json belongs to the agent, which may rewrite it whole or leave it half-written, so the run\n// log keeps its own file and only reads state.json, treating anything unreadable as empty.\nfunction readState(ws) {\n try {\n const state = readJson(ws.statePath, {});\n return state && typeof state === 'object' && !Array.isArray(state) ? state : {};\n } catch {\n return {};\n }\n}\n\nfunction loadLog(ws) {\n if (!existsSync(ws.logPath)) migrate(ws);\n return readJson(ws.logPath, {});\n}\nconst saveLog = (ws, log) => writeJson(ws.logPath, log);\n\n// Builds started before run-log.json existed kept the run log in state.json: move it out once, so\n// those builds keep their timings and the record of reports already sent.\nfunction migrate(ws) {\n const state = readState(ws);\n const fields = ['run', 'history', 'reports_sent', 'reports_rejected'].filter((key) => key in state);\n if (!fields.length) return;\n saveLog(ws, Object.fromEntries(fields.map((key) => [key, state[key]])));\n for (const key of fields) delete state[key];\n writeJson(ws.statePath, state);\n}\n\nconst openStages = (log, runId) => (log.history ?? []).filter((h) => h.run === runId && !h.ended_at);\nconst stageLabel = (h) => `${h.stage}${h.phase ? `/${h.phase}` : ''}`;\n// A run pauses for a tool restart with exactly one stage open, one that can stop for a restart.\nfunction pausableStage(log) {\n const open = openStages(log, log.run?.id);\n return open.length === 1 && RESTART_STAGES.includes(open[0].stage) ? open[0] : null;\n}\n\nfunction currentRun(log) {\n if (!log.run?.id) fail('no run started; call run-start first (the start of every run does this)');\n return log.run;\n}\n\nfunction readEvents(ws) {\n if (!existsSync(ws.eventsPath)) return [];\n return readFileSync(ws.eventsPath, 'utf8')\n .split('\\n')\n .filter(Boolean)\n .map((line) => JSON.parse(line));\n}\n\n// connect.json from older runs may hold mcp as an object or only mcp_version; the report needs strings.\nfunction readConnect(ws) {\n const connect = readJson(join(ws.dir, 'connect.json'), {});\n const mcp = connect.mcp ?? connect.mcp_version ?? null;\n let version = mcp;\n if (mcp !== null && typeof mcp !== 'string') version = mcp.name || mcp.version ? [mcp.name, mcp.version].filter(Boolean).join(' ') : JSON.stringify(mcp);\n return { tool: typeof connect.tool === 'string' ? connect.tool : null, mcp: version, skills: typeof connect.skills === 'string' ? connect.skills : null };\n}\n\nfunction runStart(ws, flags, lockWasFree) {\n const log = loadLog(ws);\n // A run left open in a restart stage goes on in the new session, at connect, instead of being\n // abandoned. The paused stage ends at its last logged activity, so the restart wait isn't counted.\n // A run paused by older skill text has no paused_at; it deleted .lock instead.\n const history = (log.history ?? []).filter((h) => h.run === log.run?.id);\n const paused = pausableStage(log);\n if (log.run?.id && !log.run.reported_at && paused && (log.run.paused_at || lockWasFree)) {\n delete log.run.paused_at;\n for (const key of ['model', 'skill']) if (typeof flags[key] === 'string') log.run[key] = flags[key];\n const events = readEvents(ws).filter((e) => e.run === log.run.id);\n Object.assign(paused, { ended_at: lastActivity(log.run, history, events), result: 'ok', note: paused.note ? `${paused.note}; ${PAUSE_NOTE}` : PAUSE_NOTE });\n log.history.push({ run: log.run.id, stage: 'connect', phase: null, started_at: now(), ended_at: null, result: null, note: 'continued after a tool restart' });\n saveLog(ws, log);\n console.log(`run ${log.run.id} continued after a tool restart in ${stageLabel(paused)}; next: connect`);\n return;\n }\n // A previous run that never reached its report (closed window, crash) is closed out first, so\n // its log still turns into a report.\n if (log.run?.id && !log.run.reported_at) {\n buildReport(ws, { outcome: 'abandoned' });\n console.log(`closed previous run ${log.run.id} as abandoned`);\n }\n const fresh = loadLog(ws);\n const previous = fresh.run ?? {};\n const startedAt = now();\n const connect = readConnect(ws);\n // Run ids are the start time; a second run in the same second gets a suffix.\n const taken = new Set([\n ...(fresh.history ?? []).map((h) => h.run),\n ...(existsSync(ws.reportsDir) ? readdirSync(ws.reportsDir).map((f) => f.replace(/\\.(json|html)$/, '')) : []),\n ]);\n const base = startedAt.replace(/:/g, '-');\n let id = base;\n for (let n = 2; taken.has(id) || id === fresh.run?.id; n += 1) id = `${base}-${n}`;\n const kind = flags.kind ?? 'build';\n if (!['build', 'resume', 'redesign', 'iterate'].includes(kind)) fail(`unknown kind \"${kind}\"; one of build, resume, redesign, iterate`);\n fresh.run = {\n id,\n kind,\n started_at: startedAt,\n tool: flags.tool ?? connect.tool ?? readState(ws).tool ?? previous.tool ?? null,\n model: flags.model ?? previous.model ?? null,\n skill: flags.skill ?? previous.skill ?? null,\n };\n fresh.history ??= [];\n fresh.history.push({ run: id, stage: 'refine', phase: null, started_at: startedAt, ended_at: null, result: null, note: null });\n saveLog(ws, fresh);\n console.log(`run ${fresh.run.id} started; next: refine`);\n}\n\nfunction runUpdate(ws, flags) {\n const log = loadLog(ws);\n const run = currentRun(log);\n for (const key of ['kind', 'tool', 'model', 'skill']) if (typeof flags[key] === 'string') run[key] = flags[key];\n if (!['build', 'resume', 'redesign', 'iterate'].includes(run.kind)) fail(`unknown kind \"${run.kind}\"; one of build, resume, redesign, iterate`);\n saveLog(ws, log);\n console.log(`run ${run.id} updated`);\n}\n\n// A follow-up in the same session (the user asks for a fix right after the final report) belongs\n// to the run it follows: reopen it, so the next `report` rewrites that run's report instead of\n// starting a second one.\nfunction runResume(ws, flags) {\n const log = loadLog(ws);\n const run = currentRun(log);\n if (!run.reported_at) {\n console.log(`run ${run.id} is still open; nothing to resume`);\n return;\n }\n run.follow_ups = [\n ...(run.follow_ups ?? []),\n { resumed_at: now(), after_report_at: run.reported_at, reason: typeof flags.reason === 'string' ? flags.reason : null },\n ];\n delete run.reported_at;\n saveLog(ws, log);\n console.log(`run ${run.id} resumed (follow-up ${run.follow_ups.length})`);\n}\n\n// A tool-restart pause leaves its stage open, and the dispatch releases the lock, so the next\n// session's run-start continues the run at connect instead of closing it as abandoned.\nfunction pause(ws) {\n const log = loadLog(ws);\n const run = currentRun(log);\n const paused = pausableStage(log);\n if (!paused) fail(`a restart pause needs exactly one open stage, one of ${RESTART_STAGES.join(', ')}; open now: ${openStages(log, run.id).map(stageLabel).join(', ') || 'none'}`);\n run.paused_at = now();\n saveLog(ws, log);\n console.log(`run ${run.id} paused in ${stageLabel(paused)}; the next session's run-start continues it at connect`);\n}\n\nfunction stageStart(ws, [stage], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"; one of ${STAGES.join(', ')}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n log.history ??= [];\n const phase = flags.phase ?? null;\n const open = log.history.find((h) => h.run === run.id && h.stage === stage && h.phase === phase && !h.ended_at);\n if (open) {\n console.log(`${stage}${phase ? `/${phase}` : ''} already started at ${open.started_at}`);\n return;\n }\n const late = lateStart(flags, run);\n log.history.push({ run: run.id, stage, phase, started_at: late ?? now(), ended_at: null, result: null, note: null, ...(late ? { start_estimated: true } : {}) });\n saveLog(ws, log);\n console.log(`${stage}${phase ? `/${phase}` : ''} started${late ? ` (estimated start ${late})` : ''}`);\n}\n\nfunction stageEnd(ws, [stage, result], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"`);\n if (!RESULTS.includes(result)) fail(`unknown result \"${result}\"; one of ${RESULTS.join(', ')}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n log.history ??= [];\n const phase = flags.phase ?? null;\n let entry = [...log.history].reverse().find((h) => h.run === run.id && h.stage === stage && h.phase === phase && !h.ended_at);\n if (!entry) {\n // Missed stage-start: use the remembered start if given, else the end of the previous stage; either way estimated.\n const runEntries = log.history.filter((h) => h.run === run.id);\n const lastEnd = runEntries.map((h) => h.ended_at).filter(Boolean).sort().at(-1);\n const late = lateStart(flags, run);\n entry = { run: run.id, stage, phase, started_at: late ?? lastEnd ?? run.started_at, ended_at: null, result: null, note: null, start_estimated: true };\n log.history.push(entry);\n console.log(`${stage}${phase ? `/${phase}` : ''}: stage-start was not logged; start estimated as ${entry.started_at}${late ? '' : ' (end of the previous stage). Pass --started-ago if you know better'}`);\n } else if (flags['started-at'] || flags['started-ago']) {\n entry.started_at = lateStart(flags, run);\n entry.start_estimated = true;\n }\n entry.ended_at = now();\n entry.result = result;\n if (typeof flags.note === 'string') entry.note = flags.note;\n saveLog(ws, log);\n console.log(`${stage}${phase ? `/${phase}` : ''} ended: ${result}`);\n}\n\n// One call at a stage boundary: ends the open stage (or phase) as ok and starts <stage>, unless the open\n// one is <stage> itself, so re-running a chained `next X && …` doesn't close X as ok. With nothing open\n// it only starts; with more than one open it can't tell which ends, so it refuses.\nfunction next(ws, [stage], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"; one of ${STAGES.join(', ')}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n const open = (log.history ?? []).filter((h) => h.run === run.id && !h.ended_at);\n const label = (h) => `${h.stage}${h.phase ? ` --phase ${h.phase}` : ''}`;\n if (open.length > 1) fail(`${open.map(label).join(' and ')} are open; end each with stage-end <stage> <result>, then call next`);\n const phase = flags.phase ?? null;\n const [current] = open;\n if (current && !(current.stage === stage && current.phase === phase)) stageEnd(ws, [current.stage, 'ok'], { phase: current.phase ?? undefined });\n stageStart(ws, [stage], { phase: flags.phase });\n}\n\nfunction stageFix(ws, [stage], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"`);\n const log = loadLog(ws);\n const run = currentRun(log);\n const phase = flags.phase ?? null;\n const entry = [...(log.history ?? [])].reverse().find((h) => h.run === run.id && h.stage === stage && h.phase === phase);\n if (!entry) fail(`${stage}${phase ? `/${phase}` : ''} was never logged in this run; use stage-start with --started-ago instead`);\n const late = lateStart(flags, run);\n if (!late) fail('stage-fix needs --started-ago (e.g. 6m) or --started-at <ISO time>');\n if (entry.ended_at && late > entry.ended_at) fail(`the new start ${late} is after the stage ended (${entry.ended_at})`);\n entry.started_at = late;\n entry.start_estimated = true;\n saveLog(ws, log);\n console.log(`${stage}${phase ? `/${phase}` : ''} start set to ${late} (estimated)`);\n}\n\nfunction event(ws, [type, raw]) {\n const spec = EVENT_FIELDS[type];\n if (!spec) fail(`unknown event type \"${type}\"; one of ${Object.keys(EVENT_FIELDS).join(', ')}`);\n let data;\n try {\n data = JSON.parse(raw ?? '');\n } catch {\n fail(`event ${type} needs a JSON object, e.g. '${JSON.stringify(Object.fromEntries(spec.required.map((k) => [k, '…'])))}'`);\n }\n const missing = spec.required.filter((k) => data[k] === undefined || data[k] === '');\n if (missing.length) fail(`event ${type} is missing ${missing.join(', ')}`);\n const unknown = Object.keys(data).filter((k) => !spec.required.includes(k) && !spec.optional.includes(k));\n if (unknown.length) fail(`event ${type} has unknown fields ${unknown.join(', ')}`);\n if (type === 'issue') {\n data.severity ??= 'medium';\n if (!['high', 'medium', 'low'].includes(data.severity)) fail('issue severity must be high, medium or low');\n data.resolved ??= false;\n data.user_had_to_intervene ??= false;\n }\n // A bad line in events.jsonl would fail every later report and run-start.\n validate({ ...data, logged_at: now() }, eventSchema(type), `event ${type}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n appendFileSync(ws.eventsPath, `${JSON.stringify({ ts: now(), run: run.id, type, ...data })}\\n`);\n console.log(`${type} logged`);\n}\n\nconst minutesBetween = (a, b) => (a && b ? Math.round(((Date.parse(b) - Date.parse(a)) / 60000) * 10) / 10 : null);\n\n// Framework is recorded in state.json by the frontend step.\nfunction frontendStack(fe, dir) {\n const framework = fe.framework ?? fe.stack ?? null;\n if (framework) return fe.rendering ? `${framework} (${fe.rendering})` : framework;\n // Fallback: an older build may have a design.md with a \"## Stack\" heading.\n const design = existsSync(join(dir, 'design.md')) ? readFileSync(join(dir, 'design.md'), 'utf8') : '';\n return design.match(/## Stack\\s*\\n\\s*\\*\\*([^*]+)\\*\\*/)?.[1] ?? null;\n}\n\nfunction buildReport(ws, { outcome, tokens } = {}) {\n const log = loadLog(ws);\n const run = currentRun(log);\n const site = readJson(join(ws.dir, 'site.json'), {});\n const deploy = readJson(join(ws.dir, 'deploy.json'), {});\n const state = readState(ws);\n const connect = readConnect(ws);\n const history = (log.history ?? []).filter((h) => h.run === run.id);\n // Lines logged before events were checked on write may not match the schema.\n const dropped = [];\n const events = readEvents(ws)\n .filter((e) => e.run === run.id)\n .filter((e) => {\n const { ts, run: _run, type, ...rest } = e;\n const problem = schemaError({ ...rest, logged_at: ts }, eventSchema(type), 'event');\n if (problem) dropped.push({ stage: typeof e.stage === 'string' ? e.stage : 'unknown', phase: null, problem: `left out a malformed ${type} event (${problem})` });\n return !problem;\n });\n const resolvedOutcome = outcome ?? (history.some((h) => h.stage === 'deploy' && h.result?.startsWith('ok')) ? 'live' : 'stopped');\n // A run ends at its last logged activity, so re-running `report` later (after fixing warnings, or\n // when the next run-start closes an abandoned run) doesn't stretch it to \"now\". Only a stage still\n // open on a live run keeps the clock running.\n const stillOpen = resolvedOutcome !== 'abandoned' && history.some((h) => !h.ended_at);\n const endedAt = stillOpen ? now() : lastActivity(run, history, events);\n const stages = history.map((h) => ({ ...h, minutes: minutesBetween(h.started_at, h.ended_at ?? endedAt) }));\n const gaps = [...loggingGaps(stages, run, resolvedOutcome), ...dropped];\n const strip = ({ ts, run: _run, type: _type, ...rest }) => ({ ...rest, logged_at: ts });\n const liveStage = stages.find((s) => s.stage === 'deploy' && s.result?.startsWith('ok'));\n if (!OUTCOMES.includes(resolvedOutcome)) fail(`unknown outcome \"${resolvedOutcome}\"; one of ${OUTCOMES.join(', ')}`);\n\n const previous = existsSync(ws.reportsDir)\n ? readdirSync(ws.reportsDir)\n .filter((f) => f.endsWith('.json') && f !== `${run.id}.json`)\n .map((f) => readJson(join(ws.reportsDir, f), {}))\n .sort((a, b) => `${a.timing?.started_at}${a.run?.id}`.localeCompare(`${b.timing?.started_at}${b.run?.id}`))\n .map((r) => ({ run: r.run?.id, kind: r.run?.kind, outcome: r.info?.outcome, minutes: r.timing?.minutes_total, html: `${r.run?.id}.html` }))\n : [];\n\n const report = {\n schema_version: '1',\n generated_at: now(),\n // Intent, not delivery: delivery is tracked in run-log.json.\n consent: { sent: true, note: 'Sent to Hostinger automatically at the end of the run.' },\n run: { id: run.id, kind: run.kind, skill: run.skill, follow_ups: run.follow_ups ?? [] },\n info: {\n domain: ws.domain,\n tool: run.tool ?? connect.tool ?? null,\n model: run.model ?? null,\n os: process.platform,\n node: process.version,\n mcp: connect.mcp,\n skills: connect.skills,\n backend: site.backend ?? null,\n frontend: frontendStack(state.frontend ?? {}, ws.dir),\n outcome: resolvedOutcome,\n stopped_at: resolvedOutcome === 'live' ? null : stoppedAt(stages, state.stage),\n live_url: resolvedOutcome === 'live' ? deploy.urls?.site ?? site.urls?.site ?? null : null,\n admin_url: site.urls?.wp_admin ?? null,\n },\n timing: {\n started_at: run.started_at,\n ended_at: endedAt,\n live_at: liveStage?.ended_at ?? null,\n minutes_total: minutesBetween(run.started_at, endedAt),\n minutes_to_live: liveStage ? minutesBetween(run.started_at, liveStage.ended_at) : null,\n stages: stages.map(({ run: _run, ...s }) => s),\n },\n // Not null: the MCP layer treats a null required field as missing, and the API reads {} as an array.\n tokens: tokens ?? { source: 'not reported' },\n issues: events.filter((e) => e.type === 'issue').map(strip),\n user_feedback: events.filter((e) => e.type === 'feedback').map(strip),\n skill_gaps: events.filter((e) => e.type === 'skill_gap').map(strip),\n what_went_well: events.filter((e) => e.type === 'good').map(strip),\n logging_gaps: gaps,\n previous_runs: previous,\n };\n\n validate(report, reportSchema());\n mkdirSync(ws.reportsDir, { recursive: true });\n writeJson(join(ws.reportsDir, `${run.id}.json`), report);\n writeFileSync(join(ws.reportsDir, `${run.id}.html`), renderHtml(report));\n copyFileSync(join(ws.reportsDir, `${run.id}.html`), join(ws.dir, 'report.html'));\n\n const fresh = loadLog(ws);\n fresh.run.reported_at = now();\n saveLog(ws, fresh);\n for (const g of gaps) console.log(`warning: ${g.stage}${g.phase ? `/${g.phase}` : ''}: ${g.problem}`);\n return join(ws.dir, 'report.html');\n}\n\n// A report counts as sent only while the sent copy's generated_at matches the file.\nfunction reportFile(ws, runId) {\n const id = runId ?? currentRun(loadLog(ws)).id;\n const file = join(ws.reportsDir, `${id}.json`);\n if (!existsSync(file)) fail(`no report for run ${id} at ${file}`);\n return { id, file, generatedAt: readJson(file, {}).generated_at };\n}\n\nfunction unsent(ws) {\n const log = loadLog(ws);\n const files = existsSync(ws.reportsDir) ? readdirSync(ws.reportsDir).filter((f) => f.endsWith('.json')).sort() : [];\n // Older reports promised \"nothing is uploaded\".\n const pending = files\n .map((f) => {\n const report = readJson(join(ws.reportsDir, f), {});\n return { id: f.replace(/\\.json$/, ''), file: join(ws.reportsDir, f), generatedAt: report.generated_at, consent: report.consent };\n })\n .filter(({ consent }) => consent?.sent !== false)\n .filter(({ id, generatedAt }) => log.reports_sent?.[id] !== generatedAt && log.reports_rejected?.[id] !== generatedAt);\n if (!pending.length) console.log('no unsent reports');\n for (const { id, file } of pending) console.log(`${id} ${file}`);\n}\n\nfunction reportSent(ws, [runId]) {\n const { id, generatedAt } = reportFile(ws, runId);\n const log = loadLog(ws);\n log.reports_sent = { ...log.reports_sent, [id]: generatedAt };\n saveLog(ws, log);\n console.log(`report ${id} marked sent`);\n}\n\n// A 422 is schema drift, so resending won't help.\nfunction reportRejected(ws, [runId]) {\n const { id, generatedAt } = reportFile(ws, runId);\n const log = loadLog(ws);\n log.reports_rejected = { ...log.reports_rejected, [id]: generatedAt };\n saveLog(ws, log);\n const run = currentRun(log);\n const symptom = `build report ${id} rejected with 422 by hosting_headless_submit-build-report`;\n appendFileSync(ws.eventsPath, `${JSON.stringify({ ts: now(), run: run.id, type: 'issue', stage: run.reported_at ? 'done' : 'check_state', symptom, severity: 'medium', resolved: false, user_had_to_intervene: false })}\\n`);\n console.log(`report ${id} marked rejected; issue logged in run ${run.id}`);\n}\n\n// Gaps are printed as warnings by `report`, so guesses never pass as measurements.\nconst EXPECTED_FOR_BUILD = STAGES.filter((stage) => stage !== 'done');\nfunction loggingGaps(stages, run, outcome) {\n const gaps = [];\n for (const s of stages) {\n // A skipped stage did no work, so it has no duration to measure.\n const problem = s.result === 'skipped' ? null\n : !s.ended_at ? 'started but never ended'\n : s.start_estimated ? 'start time estimated, not measured'\n : Date.parse(s.ended_at) === Date.parse(s.started_at) && !s.note?.endsWith(PAUSE_NOTE) ? 'logged with no duration; probably started and ended in one go after the work'\n : null;\n if (problem) gaps.push({ stage: s.stage, phase: s.phase, problem });\n }\n if (run.kind === 'build' && outcome === 'live') {\n for (const stage of EXPECTED_FOR_BUILD) {\n if (!stages.some((s) => s.stage === stage)) gaps.push({ stage, phase: null, problem: 'never logged, though the site went live' });\n }\n }\n return gaps;\n}\n\nfunction lastActivity(run, history, events) {\n return [run.started_at, ...history.flatMap((h) => [h.started_at, h.ended_at]), ...events.map((e) => e.ts)]\n .filter(Boolean)\n .sort()\n .at(-1);\n}\n\nfunction stoppedAt(stages, fallbackStage) {\n const stuck = [...stages].reverse().find((s) => !s.ended_at || s.result === 'failed' || s.result === 'stopped');\n return stuck?.stage ?? fallbackStage ?? null;\n}\n\n// Minimal JSON Schema subset, so reports from different tools share one shape without a dependency.\nconst reportSchema = () => readJson(join(here, 'report.schema.json'), null);\nconst eventSchema = (type) => reportSchema()?.properties?.[EVENT_LISTS[type]]?.items ?? null;\n\nfunction schemaError(value, schema, path = 'report') {\n if (!schema) return null;\n const types = [].concat(schema.type ?? []);\n const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : Number.isInteger(value) ? 'integer' : typeof value;\n if (types.length && !types.includes(actual) && !(actual === 'integer' && types.includes('number'))) {\n return `${path} should be ${types.join(' or ')}, got ${actual}`;\n }\n if (schema.enum && !schema.enum.includes(value)) return `${path} should be one of ${schema.enum.join(', ')}`;\n if (actual === 'object') {\n for (const key of schema.required ?? []) if (!(key in value)) return `${path}.${key} is missing`;\n for (const [key, sub] of Object.entries(schema.properties ?? {})) {\n const error = key in value ? schemaError(value[key], sub, `${path}.${key}`) : null;\n if (error) return error;\n }\n }\n if (actual === 'array' && schema.items) {\n for (const [i, item] of value.entries()) {\n const error = schemaError(item, schema.items, `${path}[${i}]`);\n if (error) return error;\n }\n }\n return null;\n}\n\nfunction validate(value, schema, path) {\n const error = schemaError(value, schema, path);\n if (error) fail(error);\n}\n\nconst esc = (v) => String(v ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\nconst label = (s) => String(s ?? '').replace(/_/g, ' ');\nconst time = (iso) => (iso ? iso.slice(11, 19) : '—');\nconst fmt = (n) => (typeof n === 'number' ? n.toLocaleString('en-US') : '—');\n\nfunction gantt(report) {\n const stages = report.timing.stages;\n if (!stages.length) return '<p class=\"muted\">No stages were logged for this run.</p>';\n const t0 = Date.parse(report.timing.started_at);\n const at = (iso) => (Date.parse(iso) - t0) / 60000;\n const total = Math.max(report.timing.minutes_total ?? 1, ...stages.map((s) => at(s.ended_at ?? report.timing.ended_at)), 1);\n const step = [1, 2, 5, 10, 15, 30, 60, 120, 240].find((s) => total / s <= 8) ?? 480;\n const span = Math.ceil(total / step) * step;\n const W = 760;\n const LABEL = 160;\n const ROW = 32;\n const TOP = 32;\n const H = TOP + ROW * stages.length + 32;\n const x = (m) => LABEL + ((W - LABEL - 40) * m) / span;\n const out = [`<svg viewBox=\"0 0 ${W} ${H}\" role=\"img\" aria-labelledby=\"gantt-title\" class=\"gantt\"><title id=\"gantt-title\">Stage timeline, minutes from the start of the run</title>`];\n for (let m = 0; m <= span; m += step) {\n out.push(`<line x1=\"${x(m).toFixed(1)}\" x2=\"${x(m).toFixed(1)}\" y1=\"${TOP - 8}\" y2=\"${H - 28}\" class=\"grid\"/><text x=\"${x(m).toFixed(1)}\" y=\"${H - 10}\" class=\"tick\" text-anchor=\"middle\">${m} min</text>`);\n }\n for (const f of report.run.follow_ups ?? []) {\n const fx = x(at(f.resumed_at)).toFixed(1);\n out.push(`<line x1=\"${fx}\" x2=\"${fx}\" y1=\"${TOP - 12}\" y2=\"${H - 28}\" class=\"follow-up\"/><text x=\"${Number(fx) + 6}\" y=\"${TOP - 12}\" class=\"follow-up-label\">Follow-up</text>`);\n }\n if (report.timing.live_at) {\n const lx = x(at(report.timing.live_at)).toFixed(1);\n out.push(`<line x1=\"${lx}\" x2=\"${lx}\" y1=\"${TOP - 12}\" y2=\"${H - 28}\" class=\"live\"/><text x=\"${lx - 6}\" y=\"${TOP - 12}\" class=\"live-label\" text-anchor=\"end\">Live · ${report.timing.minutes_to_live} min</text>`);\n }\n stages.forEach((s, i) => {\n const y = TOP + i * ROW;\n const a = at(s.started_at);\n const b = at(s.ended_at ?? report.timing.ended_at);\n const width = Math.max(x(b) - x(a), 4);\n const name = `${label(s.stage)}${s.phase ? ` · ${s.phase}` : ''}`;\n const tip = [name, `${s.minutes} min`, s.result ? label(s.result) : 'not finished', s.start_estimated ? 'start estimated' : null, s.note].filter(Boolean).join(' · ');\n const failed = s.result === 'failed' || s.result === 'stopped' || !s.ended_at;\n const fill = failed ? 'url(#hatch)' : s.start_estimated ? 'none' : 'var(--series-1)';\n out.push(`<text x=\"${LABEL - 12}\" y=\"${(y + ROW / 2 + 4).toFixed(1)}\" class=\"row-label\" text-anchor=\"end\">${esc(name)}</text>`);\n out.push(`<g class=\"bar\" tabindex=\"0\" data-tip=\"${esc(tip)}\"><rect x=\"${LABEL}\" y=\"${y}\" width=\"${W - LABEL - 16}\" height=\"${ROW}\" fill=\"transparent\"/><rect x=\"${x(a).toFixed(1)}\" y=\"${y + 8}\" width=\"${width.toFixed(1)}\" height=\"${ROW - 16}\" rx=\"4\" fill=\"${fill}\"${s.start_estimated && !failed ? ' stroke=\"var(--series-1)\" stroke-width=\"2\" stroke-dasharray=\"4 3\"' : ''}/></g>`);\n });\n out.push('<defs><pattern id=\"hatch\" width=\"6\" height=\"6\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\"><rect width=\"6\" height=\"6\" fill=\"var(--series-1)\"/><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"6\" stroke=\"var(--surface-1)\" stroke-width=\"2.5\"/></pattern></defs></svg>');\n return out.join('');\n}\n\nfunction renderHtml(r) {\n const tile = (name, value, sub = '') => `<div class=\"tile\"><div class=\"tile-label\">${esc(name)}</div><div class=\"tile-value\">${esc(value)}</div><div class=\"tile-sub\">${esc(sub)}</div></div>`;\n const stepped = r.issues.filter((i) => i.user_had_to_intervene).length;\n const rejected = r.user_feedback.filter((f) => f.category === 'design_rejected').length;\n const t = r.tokens && ['input', 'output', 'cache_read', 'cache_write', 'est_cost_usd'].some((k) => r.tokens[k] != null) ? r.tokens : null;\n const tiles = [\n r.timing.minutes_to_live != null\n ? tile('Time to live', `${r.timing.minutes_to_live} min`, 'start of run → deploy finished')\n : tile('Outcome', label(r.info.outcome), r.info.stopped_at ? `stopped at ${label(r.info.stopped_at)}` : ''),\n tile('Run length', `${r.timing.minutes_total} min`, `${r.timing.stages.length} stage entries`),\n tile('Issues', String(r.issues.length), `${stepped} needed the user to step in`),\n tile('User feedback', String(r.user_feedback.length), rejected ? `${rejected} design rejections` : 'corrections and requests'),\n t ? tile('Tokens', fmt((t.input ?? 0) + (t.output ?? 0) + (t.cache_read ?? 0) + (t.cache_write ?? 0)), t.est_cost_usd != null ? `≈ $${t.est_cost_usd} API-equivalent` : t.source ?? '') : tile('Tokens', '—', 'not reported by this tool'),\n ].join('');\n const SEV = { high: ['●', 'critical', 'High'], medium: ['▲', 'serious', 'Medium'], low: ['■', 'warning', 'Low'] };\n const order = ['high', 'medium', 'low'];\n const issues = [...r.issues]\n .sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity))\n .map((i) => {\n const [icon, cls, name] = SEV[i.severity];\n return `<tr><td><span class=\"sev sev-${cls}\"><span aria-hidden=\"true\">${icon}</span> ${name}</span></td><td>${esc(label(i.stage))}</td><td>${esc(i.symptom)}${i.user_had_to_intervene ? ' <span class=\"chip\">user had to step in</span>' : ''}</td><td>${esc(i.cause)}</td><td>${esc(i.workaround)}</td><td>${i.resolved ? '✓ Resolved' : 'Open'}</td></tr>`;\n })\n .join('');\n const list = (items, render, empty) => (items.length ? `<ul>${items.map(render).join('')}</ul>` : `<p class=\"muted\">${empty}</p>`);\n const stageRows = r.timing.stages\n .map((s) => `<tr><td>${esc(label(s.stage))}${s.phase ? ` · ${esc(s.phase)}` : ''}</td><td>${time(s.started_at)}</td><td>${time(s.ended_at)}</td><td class=\"num\">${s.minutes ?? '—'}</td><td>${esc(label(s.result ?? 'not finished'))}</td><td>${esc(s.note)}</td></tr>`)\n .join('');\n const details = [\n ['Domain', r.info.domain],\n ['Outcome', [label(r.info.outcome), r.info.live_url].filter(Boolean).join(' · ')],\n ['Run', `${r.run.id} · ${r.run.kind}`],\n ['Tool / model', [r.info.tool, r.info.model].filter(Boolean).join(' · ') || '—'],\n ['Stack', [r.info.backend, r.info.frontend].filter(Boolean).join(' + ') || '—'],\n ['Environment', `${r.info.os} · Node ${r.info.node}${r.info.mcp ? ` · ${r.info.mcp}` : ''}`],\n ['Skill version', r.run.skill ?? '—'],\n ...(r.run.follow_ups?.length\n ? [['Follow-ups', r.run.follow_ups.map((f) => `resumed ${time(f.resumed_at)}${f.reason ? ` — ${f.reason}` : ''}`).join('; ')]]\n : []),\n ]\n .map(([k, v]) => `<div><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`)\n .join('');\n const tokenTable = t\n ? `<section><h2>Tokens</h2><div class=\"table-wrap\"><table><thead><tr><th class=\"num\">Requests</th><th class=\"num\">Input</th><th class=\"num\">Output</th><th class=\"num\">Cache read</th><th class=\"num\">Cache write</th><th class=\"num\">≈ API cost</th></tr></thead><tbody><tr><td class=\"num\">${fmt(t.requests)}</td><td class=\"num\">${fmt(t.input)}</td><td class=\"num\">${fmt(t.output)}</td><td class=\"num\">${fmt(t.cache_read)}</td><td class=\"num\">${fmt(t.cache_write)}</td><td class=\"num\">${t.est_cost_usd != null ? `$${t.est_cost_usd}` : '—'}</td></tr></tbody></table></div><p class=\"muted\">${esc(t.source ?? '')}</p></section>`\n : '';\n const previous = r.previous_runs.length\n ? `<section><h2>Earlier runs on this domain</h2><ul>${r.previous_runs.map((p) => `<li><a href=\"${esc(p.html)}\">${esc(p.run)}</a> — ${esc(p.kind)} · ${esc(label(p.outcome))}${p.minutes != null ? ` · ${p.minutes} min` : ''}</li>`).join('')}</ul></section>`\n : '';\n\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Build report — ${esc(r.info.domain)}</title>\n<style>\n.viz-root { color-scheme: light; --surface-0:#f4f4f2; --surface-1:#fcfcfb; --border:#e2e1dc; --text-primary:#0b0b0b; --text-secondary:#52514e; --text-muted:#6b6a65; --series-1:#2a78d6; --grid:#e8e7e2; --warning:#fab219; --serious:#ec835a; --critical:#d03b3b; }\n@media (prefers-color-scheme: dark) { .viz-root { color-scheme: dark; --surface-0:#111110; --surface-1:#1a1a19; --border:#33332f; --text-primary:#f0efec; --text-secondary:#c3c2b7; --text-muted:#a3a299; --series-1:#3987e5; --grid:#2a2a27; } }\n* { box-sizing: border-box; }\nbody { margin:0; background:var(--surface-0); color:var(--text-primary); font:15px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif; }\nmain { max-width:1080px; margin:0 auto; padding:32px 24px 64px; }\nh1 { font-size:28px; line-height:1.2; margin:0 0 4px; } h2 { font-size:18px; margin:0 0 16px; }\na { color:var(--series-1); }\n.lede { color:var(--text-secondary); margin:0 0 24px; }\nsection { background:var(--surface-1); border:1px solid var(--border); border-radius:12px; padding:24px; margin-bottom:24px; }\n.tiles { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:16px; margin-bottom:24px; }\n.tile { background:var(--surface-1); border:1px solid var(--border); border-radius:12px; padding:16px; }\n.tile-label { color:var(--text-secondary); font-size:13px; } .tile-value { font-size:28px; font-weight:650; line-height:1.3; font-variant-numeric:tabular-nums; } .tile-sub { color:var(--text-muted); font-size:13px; }\ndl { display:grid; grid-template-columns:repeat(auto-fit,minmax(300px,1fr)); gap:12px 24px; margin:0; } dt { color:var(--text-muted); font-size:13px; } dd { margin:0; overflow-wrap:anywhere; }\n.gantt { width:100%; height:auto; display:block; } .grid { stroke:var(--grid); stroke-width:1; } .tick { fill:var(--text-secondary); font-size:12px; } .row-label { fill:var(--text-primary); font-size:13px; text-transform:capitalize; }\n.live { stroke:var(--text-primary); stroke-width:2; stroke-dasharray:4 4; } .follow-up { stroke:var(--text-muted); stroke-width:1; stroke-dasharray:2 4; } .follow-up-label { fill:var(--text-muted); font-size:12px; } .live-label { fill:var(--text-primary); font-size:12px; font-weight:600; }\n.bar { outline:none; } .bar:hover rect:last-child, .bar:focus rect:last-child { stroke:var(--text-primary); stroke-width:2; }\n.legend { display:flex; gap:24px; flex-wrap:wrap; color:var(--text-secondary); font-size:13px; margin-top:8px; } .swatch { display:inline-block; width:24px; height:12px; border-radius:4px; vertical-align:-1px; margin-right:6px; }\n.sw-solid { background:var(--series-1); } .sw-est { border:2px dashed var(--series-1); } .sw-hatch { background:repeating-linear-gradient(45deg,var(--series-1) 0 3px,var(--surface-1) 3px 6px); }\n#tip { position:fixed; pointer-events:none; background:var(--text-primary); color:var(--surface-1); font-size:13px; padding:8px 12px; border-radius:8px; max-width:340px; opacity:0; transition:opacity .1s; z-index:5; }\ntable { width:100%; border-collapse:collapse; font-size:14px; } th,td { text-align:left; padding:8px 12px; border-bottom:1px solid var(--border); vertical-align:top; } th { color:var(--text-secondary); font-weight:600; font-size:13px; }\ntd.num,th.num { text-align:right; font-variant-numeric:tabular-nums; } .table-wrap { overflow-x:auto; }\n.sev { white-space:nowrap; font-weight:600; } .sev-critical span { color:var(--critical); } .sev-serious span { color:var(--serious); } .sev-warning span { color:var(--warning); }\n.chip { display:inline-block; font-size:12px; padding:0 8px; border-radius:999px; border:1px solid var(--border); color:var(--text-secondary); white-space:nowrap; }\n.cols { display:grid; grid-template-columns:repeat(auto-fit,minmax(320px,1fr)); gap:24px; margin-bottom:24px; } .cols section { margin:0; }\nul { margin:0; padding-left:20px; } li { margin-bottom:8px; } .muted { color:var(--text-muted); font-size:13px; }\ncode { font-size:13px; background:var(--surface-0); padding:1px 4px; border-radius:4px; }\ndetails summary { cursor:pointer; color:var(--text-secondary); margin-top:16px; }\n</style></head><body class=\"viz-root\"><main>\n<h1>Build report — ${esc(r.info.domain)}</h1>\n<p class=\"lede\">${esc(label(r.run.kind))} run · ${esc(r.timing.started_at.slice(0, 16).replace('T', ' '))} UTC · ${esc(label(r.info.outcome))}</p>\n<div class=\"tiles\">${tiles}</div>\n<section><h2>Stage timeline</h2>${gantt(r)}\n<div class=\"legend\"><span><span class=\"swatch sw-solid\"></span>Finished</span><span><span class=\"swatch sw-hatch\"></span>Failed, stopped or not finished</span><span><span class=\"swatch sw-est\"></span>Start estimated</span><span>Stages can overlap: prep work runs while provisioning settles.</span></div>\n<details><summary>Show as table</summary><div class=\"table-wrap\"><table><thead><tr><th>Stage</th><th>Start</th><th>End</th><th class=\"num\">Minutes</th><th>Result</th><th>Note</th></tr></thead><tbody>${stageRows}</tbody></table></div></details></section>\n${r.logging_gaps.length ? `<section><h2>Logging gaps (${r.logging_gaps.length})</h2><p class=\"muted\">Where the run log is missing or unsure, so times here are less reliable.</p><ul>${r.logging_gaps.map((g) => `<li><strong>${esc(label(g.stage))}${g.phase ? ` · ${esc(g.phase)}` : ''}</strong> — ${esc(g.problem)}</li>`).join('')}</ul></section>` : ''}\n<section><h2>Issues (${r.issues.length})</h2>${r.issues.length ? `<div class=\"table-wrap\"><table><thead><tr><th>Severity</th><th>Stage</th><th>Symptom</th><th>Cause</th><th>Workaround</th><th>Status</th></tr></thead><tbody>${issues}</tbody></table></div>` : '<p class=\"muted\">No issues logged.</p>'}</section>\n<div class=\"cols\"><section><h2>User feedback</h2>${list(r.user_feedback, (f) => `<li><span class=\"chip\">${esc(label(f.category))}</span> <span class=\"muted\">${esc(label(f.stage))}</span> — “${esc(f.paraphrase)}”</li>`, 'No feedback logged.')}</section>\n<section><h2>Skill gaps</h2>${list(r.skill_gaps, (g) => `<li><code>${esc(g.skill)}</code> — ${esc(g.gap)}</li>`, 'No skill gaps logged.')}</section></div>\n<div class=\"cols\"><section><h2>What went well</h2>${list(r.what_went_well, (g) => `<li>${esc(g.text)}</li>`, 'Nothing logged.')}</section>\n<section><h2>Run details</h2><dl>${details}</dl></section></div>\n${tokenTable}${previous}\n</main><div id=\"tip\" role=\"status\"></div>\n<script>\nconst tip = document.getElementById('tip');\nconst show = (el, x, y) => { tip.textContent = el.dataset.tip; tip.style.left = Math.min(x + 12, innerWidth - 360) + 'px'; tip.style.top = (y + 12) + 'px'; tip.style.opacity = 1; };\ndocument.querySelectorAll('.bar').forEach((el) => {\n el.addEventListener('mousemove', (e) => show(el, e.clientX, e.clientY));\n el.addEventListener('mouseleave', () => (tip.style.opacity = 0));\n el.addEventListener('focus', () => { const r = el.getBoundingClientRect(); show(el, r.left + r.width / 2, r.top); });\n el.addEventListener('blur', () => (tip.style.opacity = 0));\n});\n</script></body></html>\n`;\n}\n\nfunction report(ws, flags) {\n let tokens;\n if (typeof flags.tokens === 'string') {\n try {\n tokens = JSON.parse(flags.tokens);\n } catch {\n fail('--tokens must be JSON, e.g. \\'{\"input\":0,\"output\":0,\"source\":\"…\"}\\'');\n }\n // null and {} can't be sent; treat them as not reported.\n if (tokens === null || (typeof tokens === 'object' && !Array.isArray(tokens) && !Object.keys(tokens).length)) tokens = undefined;\n else validate(tokens, { ...reportSchema()?.properties?.tokens, type: 'object' }, '--tokens');\n }\n console.log(`report written: ${buildReport(ws, { outcome: flags.outcome, tokens })}`);\n const { id, file } = reportFile(ws);\n console.log(`send it: pass ${file} unchanged to hosting_headless_submit-build-report, then run report-sent ${id} (or report-rejected ${id} on a 422)`);\n}\n\n// What each command does with the domain's lock: check it (refuse if another live session holds it,\n// refresh it if this one does), take it, start (take it, or take it over when asked), release it\n// after the command, or leave it alone.\nconst COMMANDS = {\n 'run-start': { lock: 'start', run: (ws, rest, flags, claim) => runStart(ws, flags, claim.wasFree) },\n 'run-update': { lock: 'check', run: (ws, rest, flags) => runUpdate(ws, flags) },\n 'run-resume': { lock: 'take', run: (ws, rest, flags) => runResume(ws, flags) },\n 'stage-start': { lock: 'check', run: stageStart },\n 'stage-end': { lock: 'check', run: stageEnd },\n next: { lock: 'check', run: next },\n 'stage-fix': { lock: 'check', run: stageFix },\n event: { lock: 'check', run: (ws, rest) => event(ws, rest) },\n pause: { lock: 'release', run: (ws) => pause(ws) },\n report: { lock: 'release', run: (ws, rest, flags) => report(ws, flags) },\n unsent: { lock: 'none', run: (ws) => unsent(ws) },\n 'report-sent': { lock: 'check', run: (ws, rest) => reportSent(ws, rest) },\n 'report-rejected': { lock: 'check', run: (ws, rest) => reportRejected(ws, rest) },\n};\n\nconst { positional, flags } = parseArgs(process.argv.slice(2));\nconst [domain, command, ...rest] = positional;\nconst spec = COMMANDS[command];\nconst names = Object.keys(COMMANDS);\nif (!spec) fail(`command must be ${names.slice(0, -1).join(', ')} or ${names.at(-1)}`);\nconst ws = workspace(domain, { create: spec.lock === 'start' });\nconst start = spec.lock === 'start';\nconst claim = spec.lock === 'none' ? null : claimLock(ws, {\n take: start || spec.lock === 'take',\n start,\n takeOver: start && flags['take-over'] === true,\n tool: start && typeof flags.tool === 'string' ? flags.tool : null,\n});\nspec.run(ws, rest, flags, claim);\n// A command that fails exits before this, so a refused pause or report keeps the lock.\nif (spec.lock === 'release' && claim.lock) rmSync(ws.lockPath, { force: true });\n"
207
+ "text": "#!/usr/bin/env node\n// Hostinger Headless run log: records a build as it happens and writes reports/<run>.json + .html.\n//\n// node run-log.mjs <domain> run-start [--kind build|resume|redesign|iterate] [--tool <tool>] [--model <model>] [--skill <version>] [--take-over]\n// node run-log.mjs <domain> run-update [--kind …] [--model …] [--skill …]\n// node run-log.mjs <domain> run-resume [--reason \"<text>\"]\n// node run-log.mjs <domain> stage-start <stage> [--phase <phase>] [--started-ago 6m | --started-at <ISO time>]\n// node run-log.mjs <domain> stage-end <stage> <result> [--phase <phase>] [--note \"<text>\"] [--started-ago 6m | --started-at <ISO time>]\n// node run-log.mjs <domain> next <stage> [--phase <phase>]\n// node run-log.mjs <domain> stage-fix <stage> [--phase <phase>] (--started-ago 6m | --started-at <ISO time>)\n// node run-log.mjs <domain> event <issue|feedback|skill_gap|good> '<json>'\n// node run-log.mjs <domain> pause\n// node run-log.mjs <domain> report [--outcome live|stopped|failed|abandoned] [--tokens '<json>']\n// node run-log.mjs <domain> unsent\n// node run-log.mjs <domain> report-sent [<run>]\n// node run-log.mjs <domain> report-rejected [<run>]\n\nimport { spawnSync } from 'node:child_process';\nimport { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { homedir, hostname } from 'node:os';\nimport { basename, delimiter, dirname, isAbsolute, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst STAGES = ['refine', 'connect', 'check_state', 'provision', 'content_model', 'design', 'frontend', 'validate', 'deploy', 'done'];\n// Stages that stop for the user to restart their tool, so it loads a newly registered Hostinger MCP server.\nconst RESTART_STAGES = ['connect', 'provision', 'content_model'];\nconst PAUSE_NOTE = 'paused for a tool restart';\n// A domain names a folder under ~/.hostinger, so \"../x\" or \"a/b\" must never reach the file system.\nconst HOSTNAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;\nconst RESULTS = ['ok', 'ok_after_retries', 'ok_with_fixups', 'failed', 'skipped', 'stopped'];\nconst OUTCOMES = ['live', 'stopped', 'failed', 'abandoned'];\nconst EVENT_FIELDS = {\n issue: { required: ['stage', 'symptom'], optional: ['cause', 'workaround', 'severity', 'resolved', 'user_had_to_intervene'] },\n feedback: { required: ['stage', 'category', 'paraphrase'], optional: [] },\n skill_gap: { required: ['skill', 'gap'], optional: ['stage'] },\n good: { required: ['text'], optional: ['stage'] },\n};\nconst EVENT_LISTS = { issue: 'issues', feedback: 'user_feedback', skill_gap: 'skill_gaps', good: 'what_went_well' };\n\nconst here = dirname(fileURLToPath(import.meta.url));\nconst now = () => new Date().toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n// A start logged late is kept but marked estimated, so the report can tell measured times from remembered ones.\nfunction lateStart(flags, run) {\n let at = null;\n if (typeof flags['started-at'] === 'string') {\n if (Number.isNaN(Date.parse(flags['started-at']))) fail(`--started-at \"${flags['started-at']}\" is not a time; use e.g. 2026-10-13T06:26:00Z`);\n at = Date.parse(flags['started-at']);\n } else if (typeof flags['started-ago'] === 'string') {\n const m = flags['started-ago'].match(/^(\\d+(?:\\.\\d+)?)\\s*([smh])$/);\n if (!m) fail(`--started-ago \"${flags['started-ago']}\" should look like 90s, 6m or 1h`);\n at = Date.now() - Number(m[1]) * { s: 1e3, m: 6e4, h: 36e5 }[m[2]];\n }\n if (at === null) return null;\n const clamped = Math.min(Math.max(at, Date.parse(run.started_at)), Date.now());\n return new Date(clamped).toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n}\n\nconst fail = (message) => {\n console.error(`run-log: ${message}`);\n process.exit(1);\n};\n\nfunction parseArgs(argv) {\n const positional = [];\n const flags = {};\n for (let i = 0; i < argv.length; i += 1) {\n if (argv[i].startsWith('--')) {\n const key = argv[i].slice(2);\n const value = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[(i += 1)] : true;\n flags[key] = value;\n } else positional.push(argv[i]);\n }\n return { positional, flags };\n}\n\nconst readJson = (file, fallback) => (existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : fallback);\nconst writeJson = (file, value) => writeFileSync(file, `${JSON.stringify(value, null, 2)}\\n`);\n\n// run-start is a run's first command, before anything else has written to the workspace.\nfunction workspace(domain, { create = false } = {}) {\n if (!domain || domain.startsWith('-')) fail('first argument must be the domain');\n if (!HOSTNAME.test(domain)) fail(`\"${domain}\" is not a domain (use its ASCII form, e.g. xn--caf-dma.com)`);\n const dir = join(homedir(), '.hostinger', domain);\n if (create) mkdirSync(dir, { recursive: true });\n else if (!existsSync(dir)) fail(`no workspace at ${dir}; run-start creates it`);\n return {\n dir,\n domain,\n statePath: join(dir, 'state.json'),\n logPath: join(dir, 'run-log.json'),\n eventsPath: join(dir, 'events.jsonl'),\n reportsDir: join(dir, 'reports'),\n lockPath: join(dir, '.lock'),\n };\n}\n\n// One session at a time builds a domain, and .lock names it. The holder is the agent process (Claude\n// Code, Codex, claude -p): each command runs in a short-lived shell under it, so the nearest ancestor\n// that isn't a shell or a wrapper lives as long as the session and no longer.\n// Linux ps cuts a name to 15 characters, so each wrapper also matches its cut form.\nconst WRAPPERS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'pwsh', 'powershell', 'cmd', 'sandbox-exec', 'bwrap', 'codex-linux-sandbox', 'env', 'timeout', 'caffeinate']\n .flatMap((name) => [name, name.slice(0, 15)]));\n// A lock whose holder can't be checked (another host, no process list, the old timestamp-only lock)\n// counts as live while it was refreshed this recently.\nconst LOCK_FRESH_MS = 30 * 60 * 1000;\n\nconst processName = (name) => basename(name.replace(/\\\\/g, '/')).replace(/^-/, '').replace(/\\.exe$/i, '').toLowerCase();\n\n// This script runs in the user's project, maybe a cloned repository. Windows looks a bare program name\n// up in the working directory before PATH, as does a relative PATH entry elsewhere, so the process list\n// is read from home with only absolute, non-node_modules PATH entries (as connect/launch.mjs runs npx),\n// and Windows PowerShell is named by its full path.\nconst helperEnv = { ...process.env, LC_ALL: 'C', TZ: 'UTC' };\nfor (const key of Object.keys(helperEnv).filter((k) => k.toUpperCase() === 'PATH')) {\n helperEnv[key] = helperEnv[key].split(delimiter)\n .filter((p) => isAbsolute(p) && !p.split(/[\\\\/]/).includes('node_modules'))\n .join(delimiter);\n}\nconst systemRoot = isAbsolute(process.env.SystemRoot ?? '') ? process.env.SystemRoot : 'C:\\\\Windows';\nconst POWERSHELL = join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');\n\n// pid -> { ppid, started, name }; null when the process list can't be read. The start time tells a\n// reused PID from the process that held the lock.\nfunction processTable() {\n const windows = process.platform === 'win32';\n const r = windows\n ? spawnSync(POWERSHELL, ['-NoProfile', '-NonInteractive', '-Command',\n 'Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId)`t$($_.ParentProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\\'o\\') })`t$($_.Name)\" }'], { encoding: 'utf8', cwd: homedir(), env: helperEnv })\n : spawnSync('ps', ['-A', '-o', 'pid=,ppid=,lstart=,comm='], { encoding: 'utf8', cwd: homedir(), env: helperEnv });\n if (r.status !== 0 || !r.stdout) return null;\n const table = new Map();\n for (const line of r.stdout.split(/\\r?\\n/)) {\n const m = windows ? line.match(/^(\\d+)\\t(\\d+)\\t([^\\t]*)\\t(.*)$/) : line.trim().match(/^(\\d+)\\s+(\\d+)\\s+(\\w+\\s+\\w+\\s+\\d+\\s+[\\d:]+\\s+\\d+)\\s+(.*)$/);\n if (m) table.set(Number(m[1]), { ppid: Number(m[2]), started: m[3].replace(/\\s+/g, ' ') || null, name: m[4] });\n }\n return table.size ? table : null;\n}\n\nfunction currentHolder(table) {\n let pid = process.ppid;\n while (table?.has(pid) && WRAPPERS.has(processName(table.get(pid).name))) pid = table.get(pid).ppid;\n const proc = table?.get(pid);\n return { host: hostname(), pid, started: proc?.started ?? null, process: proc ? processName(proc.name) : null };\n}\n\n// The old timestamp-only lock, or one another session is still writing, has no holder: only a time.\nfunction readLock(ws) {\n let text;\n let mtime;\n try {\n text = readFileSync(ws.lockPath, 'utf8');\n mtime = statSync(ws.lockPath).mtimeMs;\n } catch {\n return null;\n }\n try {\n const lock = JSON.parse(text);\n if (lock && typeof lock === 'object' && Number.isInteger(lock.pid)) return lock;\n } catch {}\n const stamped = Date.parse(text.trim());\n const refreshed = new Date(Number.isNaN(stamped) ? mtime : stamped).toISOString();\n return { host: null, pid: null, started: null, process: null, tool: null, acquired_at: refreshed, refreshed_at: refreshed };\n}\n\nconst byRecency = (lock) => (Date.now() - Date.parse(lock.refreshed_at) < LOCK_FRESH_MS ? 'live' : 'dead');\n\n// own, live or dead; unverified when there is no process list (a sandbox that blocks ps), where the\n// holder found is the command's own shell and this session can't be told from another on this host.\nfunction lockStatus(lock, me, table) {\n if (lock.host !== me.host) return byRecency(lock);\n if (!table) return 'unverified';\n if (lock.pid === me.pid && lock.started === me.started) return 'own';\n if (lock.started) return table.get(lock.pid)?.started === lock.started ? 'live' : 'dead';\n return byRecency(lock);\n}\n\n// Replacing the lock goes through a rename, so a reader never sees half of it.\nfunction writeLock(ws, lock) {\n const tmp = `${ws.lockPath}.${process.pid}.tmp`;\n writeJson(tmp, lock);\n renameSync(tmp, ws.lockPath);\n}\n\n// Of two sessions creating a missing lock at once, exactly one succeeds.\nfunction createLock(ws, lock) {\n try {\n writeFileSync(ws.lockPath, `${JSON.stringify(lock, null, 2)}\\n`, { flag: 'wx' });\n return true;\n } catch (error) {\n if (error.code === 'EEXIST') return false;\n throw error;\n }\n}\n\n// Reads the run log without migrating it: a refused session writes nothing.\nfunction holderStage(ws) {\n try {\n const log = readJson(ws.logPath, {});\n const open = openStages(log, log.run?.id).at(-1);\n return { tool: log.run?.tool ?? null, stage: open ? stageLabel(open) : null };\n } catch {\n return { tool: null, stage: null };\n }\n}\n\nfunction refuse(ws, lock, { offerTakeOver }) {\n const { tool, stage } = holderStage(ws);\n const who = [\n lock.tool ?? tool ?? lock.process,\n lock.pid === null ? null : lock.host === hostname() ? `pid ${lock.pid}` : `on ${lock.host}`,\n `since ${lock.acquired_at}`,\n stage && `in ${stage}`,\n ].filter(Boolean).join(', ');\n const takeOver = offerTakeOver ? '. Only if the user says to take over, run run-start --take-over: the other session stops at its next step' : '';\n fail(`another session (${who}) is building ${ws.domain}; stop and tell the user${takeOver}`);\n}\n\n// Checks the lock before a command writes anything: another live session's lock refuses it, and this\n// session's own lock is refreshed. `take` also takes a missing lock or one whose holder is gone.\n// `start` (run-start) does too, offers a takeover when refused, and with `takeOver` takes a live lock.\n// wasFree: no lock existed.\nfunction claimLock(ws, { take = false, start = false, takeOver = false, tool = null }) {\n const table = processTable();\n const me = currentHolder(table);\n const record = () => ({ ...me, tool, acquired_at: now(), refreshed_at: now() });\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const lock = readLock(ws);\n if (!lock) {\n if (!take) return { lock: null, wasFree: true };\n const fresh = record();\n if (createLock(ws, fresh)) return { lock: fresh, wasFree: true };\n continue;\n }\n // An unverified lock: run-start judges it by recency, and a later command trusts that run-start\n // settled it rather than refuse its own session.\n const verdict = lockStatus(lock, me, table);\n const status = verdict === 'unverified' ? (start ? byRecency(lock) : 'own') : verdict;\n if (status === 'own') {\n const refreshed = { ...lock, tool: tool ?? lock.tool, refreshed_at: now() };\n writeLock(ws, refreshed);\n return { lock: refreshed, wasFree: false };\n }\n if (status === 'live' && !takeOver) refuse(ws, lock, { offerTakeOver: start });\n if (!take) return { lock: null, wasFree: false };\n // Two sessions taking over the same dead lock at once both rename theirs in; the one that lost\n // is refused at its next command.\n const taken = record();\n writeLock(ws, taken);\n return { lock: taken, wasFree: false };\n }\n fail(`${ws.lockPath} keeps appearing and disappearing; another session is starting on ${ws.domain}. Stop and tell the user`);\n}\n\n// state.json belongs to the agent, which may rewrite it whole or leave it half-written, so the run\n// log keeps its own file and only reads state.json, treating anything unreadable as empty.\nfunction readState(ws) {\n try {\n const state = readJson(ws.statePath, {});\n return state && typeof state === 'object' && !Array.isArray(state) ? state : {};\n } catch {\n return {};\n }\n}\n\nfunction loadLog(ws) {\n if (!existsSync(ws.logPath)) migrate(ws);\n return readJson(ws.logPath, {});\n}\nconst saveLog = (ws, log) => writeJson(ws.logPath, log);\n\n// Builds started before run-log.json existed kept the run log in state.json: move it out once, so\n// those builds keep their timings and the record of reports already sent.\nfunction migrate(ws) {\n const state = readState(ws);\n const fields = ['run', 'history', 'reports_sent', 'reports_rejected'].filter((key) => key in state);\n if (!fields.length) return;\n saveLog(ws, Object.fromEntries(fields.map((key) => [key, state[key]])));\n for (const key of fields) delete state[key];\n writeJson(ws.statePath, state);\n}\n\nconst openStages = (log, runId) => (log.history ?? []).filter((h) => h.run === runId && !h.ended_at);\nconst stageLabel = (h) => `${h.stage}${h.phase ? `/${h.phase}` : ''}`;\n// A run pauses for a tool restart with exactly one stage open, one that can stop for a restart.\nfunction pausableStage(log) {\n const open = openStages(log, log.run?.id);\n return open.length === 1 && RESTART_STAGES.includes(open[0].stage) ? open[0] : null;\n}\n\nfunction currentRun(log) {\n if (!log.run?.id) fail('no run started; call run-start first (the start of every run does this)');\n return log.run;\n}\n\nfunction readEvents(ws) {\n if (!existsSync(ws.eventsPath)) return [];\n return readFileSync(ws.eventsPath, 'utf8')\n .split('\\n')\n .filter(Boolean)\n .map((line) => JSON.parse(line));\n}\n\n// connect.json from older runs may hold mcp as an object or only mcp_version; the report needs strings.\nfunction readConnect(ws) {\n const connect = readJson(join(ws.dir, 'connect.json'), {});\n const mcp = connect.mcp ?? connect.mcp_version ?? null;\n let version = mcp;\n if (mcp !== null && typeof mcp !== 'string') version = mcp.name || mcp.version ? [mcp.name, mcp.version].filter(Boolean).join(' ') : JSON.stringify(mcp);\n return { tool: typeof connect.tool === 'string' ? connect.tool : null, mcp: version, skills: typeof connect.skills === 'string' ? connect.skills : null };\n}\n\nfunction runStart(ws, flags, lockWasFree) {\n const log = loadLog(ws);\n // A run left open in a restart stage goes on in the new session, at connect, instead of being\n // abandoned. The paused stage ends at its last logged activity, so the restart wait isn't counted.\n // A run paused by older skill text has no paused_at; it deleted .lock instead.\n const history = (log.history ?? []).filter((h) => h.run === log.run?.id);\n const paused = pausableStage(log);\n if (log.run?.id && !log.run.reported_at && paused && (log.run.paused_at || lockWasFree)) {\n delete log.run.paused_at;\n for (const key of ['model', 'skill']) if (typeof flags[key] === 'string') log.run[key] = flags[key];\n const events = readEvents(ws).filter((e) => e.run === log.run.id);\n Object.assign(paused, { ended_at: lastActivity(log.run, history, events), result: 'ok', note: paused.note ? `${paused.note}; ${PAUSE_NOTE}` : PAUSE_NOTE });\n log.history.push({ run: log.run.id, stage: 'connect', phase: null, started_at: now(), ended_at: null, result: null, note: 'continued after a tool restart' });\n saveLog(ws, log);\n console.log(`run ${log.run.id} continued after a tool restart in ${stageLabel(paused)}; next: connect`);\n return;\n }\n // A previous run that never reached its report (closed window, crash) is closed out first, so\n // its log still turns into a report.\n if (log.run?.id && !log.run.reported_at) {\n buildReport(ws, { outcome: 'abandoned' });\n console.log(`closed previous run ${log.run.id} as abandoned`);\n }\n const fresh = loadLog(ws);\n const previous = fresh.run ?? {};\n const startedAt = now();\n const connect = readConnect(ws);\n // Run ids are the start time; a second run in the same second gets a suffix.\n const taken = new Set([\n ...(fresh.history ?? []).map((h) => h.run),\n ...(existsSync(ws.reportsDir) ? readdirSync(ws.reportsDir).map((f) => f.replace(/\\.(json|html)$/, '')) : []),\n ]);\n const base = startedAt.replace(/:/g, '-');\n let id = base;\n for (let n = 2; taken.has(id) || id === fresh.run?.id; n += 1) id = `${base}-${n}`;\n const kind = flags.kind ?? 'build';\n if (!['build', 'resume', 'redesign', 'iterate'].includes(kind)) fail(`unknown kind \"${kind}\"; one of build, resume, redesign, iterate`);\n fresh.run = {\n id,\n kind,\n started_at: startedAt,\n tool: flags.tool ?? connect.tool ?? readState(ws).tool ?? previous.tool ?? null,\n model: flags.model ?? previous.model ?? null,\n skill: flags.skill ?? previous.skill ?? null,\n };\n fresh.history ??= [];\n fresh.history.push({ run: id, stage: 'refine', phase: null, started_at: startedAt, ended_at: null, result: null, note: null });\n saveLog(ws, fresh);\n console.log(`run ${fresh.run.id} started; next: refine`);\n}\n\nfunction runUpdate(ws, flags) {\n const log = loadLog(ws);\n const run = currentRun(log);\n for (const key of ['kind', 'tool', 'model', 'skill']) if (typeof flags[key] === 'string') run[key] = flags[key];\n if (!['build', 'resume', 'redesign', 'iterate'].includes(run.kind)) fail(`unknown kind \"${run.kind}\"; one of build, resume, redesign, iterate`);\n saveLog(ws, log);\n console.log(`run ${run.id} updated`);\n}\n\n// A follow-up in the same session (the user asks for a fix right after the final report) belongs\n// to the run it follows: reopen it, so the next `report` rewrites that run's report instead of\n// starting a second one.\nfunction runResume(ws, flags) {\n const log = loadLog(ws);\n const run = currentRun(log);\n if (!run.reported_at) {\n console.log(`run ${run.id} is still open; nothing to resume`);\n return;\n }\n run.follow_ups = [\n ...(run.follow_ups ?? []),\n { resumed_at: now(), after_report_at: run.reported_at, reason: typeof flags.reason === 'string' ? flags.reason : null },\n ];\n delete run.reported_at;\n saveLog(ws, log);\n console.log(`run ${run.id} resumed (follow-up ${run.follow_ups.length})`);\n}\n\n// A tool-restart pause leaves its stage open, and the dispatch releases the lock, so the next\n// session's run-start continues the run at connect instead of closing it as abandoned.\nfunction pause(ws) {\n const log = loadLog(ws);\n const run = currentRun(log);\n const paused = pausableStage(log);\n if (!paused) fail(`a restart pause needs exactly one open stage, one of ${RESTART_STAGES.join(', ')}; open now: ${openStages(log, run.id).map(stageLabel).join(', ') || 'none'}`);\n run.paused_at = now();\n saveLog(ws, log);\n console.log(`run ${run.id} paused in ${stageLabel(paused)}; the next session's run-start continues it at connect`);\n}\n\nfunction stageStart(ws, [stage], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"; one of ${STAGES.join(', ')}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n log.history ??= [];\n const phase = flags.phase ?? null;\n const open = log.history.find((h) => h.run === run.id && h.stage === stage && h.phase === phase && !h.ended_at);\n if (open) {\n console.log(`${stage}${phase ? `/${phase}` : ''} already started at ${open.started_at}`);\n return;\n }\n const late = lateStart(flags, run);\n log.history.push({ run: run.id, stage, phase, started_at: late ?? now(), ended_at: null, result: null, note: null, ...(late ? { start_estimated: true } : {}) });\n saveLog(ws, log);\n console.log(`${stage}${phase ? `/${phase}` : ''} started${late ? ` (estimated start ${late})` : ''}`);\n}\n\nfunction stageEnd(ws, [stage, result], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"`);\n if (!RESULTS.includes(result)) fail(`unknown result \"${result}\"; one of ${RESULTS.join(', ')}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n log.history ??= [];\n const phase = flags.phase ?? null;\n let entry = [...log.history].reverse().find((h) => h.run === run.id && h.stage === stage && h.phase === phase && !h.ended_at);\n if (!entry) {\n // Missed stage-start: use the remembered start if given, else the end of the previous stage; either way estimated.\n const runEntries = log.history.filter((h) => h.run === run.id);\n const lastEnd = runEntries.map((h) => h.ended_at).filter(Boolean).sort().at(-1);\n const late = lateStart(flags, run);\n entry = { run: run.id, stage, phase, started_at: late ?? lastEnd ?? run.started_at, ended_at: null, result: null, note: null, start_estimated: true };\n log.history.push(entry);\n console.log(`${stage}${phase ? `/${phase}` : ''}: stage-start was not logged; start estimated as ${entry.started_at}${late ? '' : ' (end of the previous stage). Pass --started-ago if you know better'}`);\n } else if (flags['started-at'] || flags['started-ago']) {\n entry.started_at = lateStart(flags, run);\n entry.start_estimated = true;\n }\n entry.ended_at = now();\n entry.result = result;\n if (typeof flags.note === 'string') entry.note = flags.note;\n saveLog(ws, log);\n console.log(`${stage}${phase ? `/${phase}` : ''} ended: ${result}`);\n}\n\n// One call at a stage boundary: ends the open stage (or phase) as ok and starts <stage>, unless the open\n// one is <stage> itself, so re-running a chained `next X && …` doesn't close X as ok. With nothing open\n// it only starts; with more than one open it can't tell which ends, so it refuses.\nfunction next(ws, [stage], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"; one of ${STAGES.join(', ')}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n const open = (log.history ?? []).filter((h) => h.run === run.id && !h.ended_at);\n const label = (h) => `${h.stage}${h.phase ? ` --phase ${h.phase}` : ''}`;\n if (open.length > 1) fail(`${open.map(label).join(' and ')} are open; end each with stage-end <stage> <result>, then call next`);\n const phase = flags.phase ?? null;\n const [current] = open;\n if (current && !(current.stage === stage && current.phase === phase)) stageEnd(ws, [current.stage, 'ok'], { phase: current.phase ?? undefined });\n stageStart(ws, [stage], { phase: flags.phase });\n}\n\nfunction stageFix(ws, [stage], flags) {\n if (!STAGES.includes(stage)) fail(`unknown stage \"${stage}\"`);\n const log = loadLog(ws);\n const run = currentRun(log);\n const phase = flags.phase ?? null;\n const entry = [...(log.history ?? [])].reverse().find((h) => h.run === run.id && h.stage === stage && h.phase === phase);\n if (!entry) fail(`${stage}${phase ? `/${phase}` : ''} was never logged in this run; use stage-start with --started-ago instead`);\n const late = lateStart(flags, run);\n if (!late) fail('stage-fix needs --started-ago (e.g. 6m) or --started-at <ISO time>');\n if (entry.ended_at && late > entry.ended_at) fail(`the new start ${late} is after the stage ended (${entry.ended_at})`);\n entry.started_at = late;\n entry.start_estimated = true;\n saveLog(ws, log);\n console.log(`${stage}${phase ? `/${phase}` : ''} start set to ${late} (estimated)`);\n}\n\nfunction event(ws, [type, raw]) {\n const spec = EVENT_FIELDS[type];\n if (!spec) fail(`unknown event type \"${type}\"; one of ${Object.keys(EVENT_FIELDS).join(', ')}`);\n let data;\n try {\n data = JSON.parse(raw ?? '');\n } catch {\n fail(`event ${type} needs a JSON object, e.g. '${JSON.stringify(Object.fromEntries(spec.required.map((k) => [k, '…'])))}'`);\n }\n const missing = spec.required.filter((k) => data[k] === undefined || data[k] === '');\n if (missing.length) fail(`event ${type} is missing ${missing.join(', ')}`);\n const unknown = Object.keys(data).filter((k) => !spec.required.includes(k) && !spec.optional.includes(k));\n if (unknown.length) fail(`event ${type} has unknown fields ${unknown.join(', ')}`);\n if (type === 'issue') {\n data.severity ??= 'medium';\n if (!['high', 'medium', 'low'].includes(data.severity)) fail('issue severity must be high, medium or low');\n data.resolved ??= false;\n data.user_had_to_intervene ??= false;\n }\n // A bad line in events.jsonl would fail every later report and run-start.\n validate({ ...data, logged_at: now() }, eventSchema(type), `event ${type}`);\n const log = loadLog(ws);\n const run = currentRun(log);\n appendFileSync(ws.eventsPath, `${JSON.stringify({ ts: now(), run: run.id, type, ...data })}\\n`);\n console.log(`${type} logged`);\n}\n\nconst minutesBetween = (a, b) => (a && b ? Math.round(((Date.parse(b) - Date.parse(a)) / 60000) * 10) / 10 : null);\n\n// Framework is recorded in state.json by the frontend step.\nfunction frontendStack(fe, dir) {\n const framework = fe.framework ?? fe.stack ?? null;\n if (framework) return fe.rendering ? `${framework} (${fe.rendering})` : framework;\n // Fallback: an older build may have a design.md with a \"## Stack\" heading.\n const design = existsSync(join(dir, 'design.md')) ? readFileSync(join(dir, 'design.md'), 'utf8') : '';\n return design.match(/## Stack\\s*\\n\\s*\\*\\*([^*]+)\\*\\*/)?.[1] ?? null;\n}\n\nfunction buildReport(ws, { outcome, tokens } = {}) {\n const log = loadLog(ws);\n const run = currentRun(log);\n const site = readJson(join(ws.dir, 'site.json'), {});\n const deploy = readJson(join(ws.dir, 'deploy.json'), {});\n const state = readState(ws);\n const connect = readConnect(ws);\n const history = (log.history ?? []).filter((h) => h.run === run.id);\n // Lines logged before events were checked on write may not match the schema.\n const dropped = [];\n const events = readEvents(ws)\n .filter((e) => e.run === run.id)\n .filter((e) => {\n const { ts, run: _run, type, ...rest } = e;\n const problem = schemaError({ ...rest, logged_at: ts }, eventSchema(type), 'event');\n if (problem) dropped.push({ stage: typeof e.stage === 'string' ? e.stage : 'unknown', phase: null, problem: `left out a malformed ${type} event (${problem})` });\n return !problem;\n });\n const resolvedOutcome = outcome ?? (history.some((h) => h.stage === 'deploy' && h.result?.startsWith('ok')) ? 'live' : 'stopped');\n // A run ends at its last logged activity, so re-running `report` later (after fixing warnings, or\n // when the next run-start closes an abandoned run) doesn't stretch it to \"now\". Only a stage still\n // open on a live run keeps the clock running.\n const stillOpen = resolvedOutcome !== 'abandoned' && history.some((h) => !h.ended_at);\n const endedAt = stillOpen ? now() : lastActivity(run, history, events);\n const stages = history.map((h) => ({ ...h, minutes: minutesBetween(h.started_at, h.ended_at ?? endedAt) }));\n const gaps = [...loggingGaps(stages, run, resolvedOutcome), ...dropped];\n const strip = ({ ts, run: _run, type: _type, ...rest }) => ({ ...rest, logged_at: ts });\n const liveStage = stages.find((s) => s.stage === 'deploy' && s.result?.startsWith('ok'));\n if (!OUTCOMES.includes(resolvedOutcome)) fail(`unknown outcome \"${resolvedOutcome}\"; one of ${OUTCOMES.join(', ')}`);\n\n const previous = existsSync(ws.reportsDir)\n ? readdirSync(ws.reportsDir)\n .filter((f) => f.endsWith('.json') && f !== `${run.id}.json`)\n .map((f) => readJson(join(ws.reportsDir, f), {}))\n .sort((a, b) => `${a.timing?.started_at}${a.run?.id}`.localeCompare(`${b.timing?.started_at}${b.run?.id}`))\n .map((r) => ({ run: r.run?.id, kind: r.run?.kind, outcome: r.info?.outcome, minutes: r.timing?.minutes_total, html: `${r.run?.id}.html` }))\n : [];\n\n const report = {\n schema_version: '1',\n generated_at: now(),\n // Intent, not delivery: delivery is tracked in run-log.json.\n consent: { sent: true, note: 'Sent to Hostinger automatically at the end of the run.' },\n run: { id: run.id, kind: run.kind, skill: run.skill, follow_ups: run.follow_ups ?? [] },\n info: {\n domain: ws.domain,\n tool: run.tool ?? connect.tool ?? null,\n model: run.model ?? null,\n os: process.platform,\n node: process.version,\n mcp: connect.mcp,\n skills: connect.skills,\n backend: site.backend ?? null,\n frontend: frontendStack(state.frontend ?? {}, ws.dir),\n outcome: resolvedOutcome,\n stopped_at: resolvedOutcome === 'live' ? null : stoppedAt(stages, state.stage),\n live_url: resolvedOutcome === 'live' ? deploy.urls?.site ?? site.urls?.site ?? null : null,\n admin_url: site.urls?.wp_admin ?? null,\n },\n timing: {\n started_at: run.started_at,\n ended_at: endedAt,\n live_at: liveStage?.ended_at ?? null,\n minutes_total: minutesBetween(run.started_at, endedAt),\n minutes_to_live: liveStage ? minutesBetween(run.started_at, liveStage.ended_at) : null,\n stages: stages.map(({ run: _run, ...s }) => s),\n },\n // Not null: the MCP layer treats a null required field as missing, and the API reads {} as an array.\n tokens: tokens ?? { source: 'not reported' },\n issues: events.filter((e) => e.type === 'issue').map(strip),\n user_feedback: events.filter((e) => e.type === 'feedback').map(strip),\n skill_gaps: events.filter((e) => e.type === 'skill_gap').map(strip),\n what_went_well: events.filter((e) => e.type === 'good').map(strip),\n logging_gaps: gaps,\n previous_runs: previous,\n };\n\n validate(report, reportSchema());\n mkdirSync(ws.reportsDir, { recursive: true });\n writeJson(join(ws.reportsDir, `${run.id}.json`), report);\n writeFileSync(join(ws.reportsDir, `${run.id}.html`), renderHtml(report));\n copyFileSync(join(ws.reportsDir, `${run.id}.html`), join(ws.dir, 'report.html'));\n\n const fresh = loadLog(ws);\n fresh.run.reported_at = now();\n saveLog(ws, fresh);\n for (const g of gaps) console.log(`warning: ${g.stage}${g.phase ? `/${g.phase}` : ''}: ${g.problem}`);\n return join(ws.dir, 'report.html');\n}\n\n// A report counts as sent only while the sent copy's generated_at matches the file.\nfunction reportFile(ws, runId) {\n const id = runId ?? currentRun(loadLog(ws)).id;\n const file = join(ws.reportsDir, `${id}.json`);\n if (!existsSync(file)) fail(`no report for run ${id} at ${file}`);\n return { id, file, generatedAt: readJson(file, {}).generated_at };\n}\n\nfunction unsent(ws) {\n const log = loadLog(ws);\n const files = existsSync(ws.reportsDir) ? readdirSync(ws.reportsDir).filter((f) => f.endsWith('.json')).sort() : [];\n // Older reports promised \"nothing is uploaded\".\n const pending = files\n .map((f) => {\n const report = readJson(join(ws.reportsDir, f), {});\n return { id: f.replace(/\\.json$/, ''), file: join(ws.reportsDir, f), generatedAt: report.generated_at, consent: report.consent };\n })\n .filter(({ consent }) => consent?.sent !== false)\n .filter(({ id, generatedAt }) => log.reports_sent?.[id] !== generatedAt && log.reports_rejected?.[id] !== generatedAt);\n if (!pending.length) console.log('no unsent reports');\n for (const { id, file } of pending) console.log(`${id} ${file}`);\n}\n\nfunction reportSent(ws, [runId]) {\n const { id, generatedAt } = reportFile(ws, runId);\n const log = loadLog(ws);\n log.reports_sent = { ...log.reports_sent, [id]: generatedAt };\n saveLog(ws, log);\n console.log(`report ${id} marked sent`);\n}\n\n// A 422 is schema drift, so resending won't help.\nfunction reportRejected(ws, [runId]) {\n const { id, generatedAt } = reportFile(ws, runId);\n const log = loadLog(ws);\n log.reports_rejected = { ...log.reports_rejected, [id]: generatedAt };\n saveLog(ws, log);\n const run = currentRun(log);\n const symptom = `build report ${id} rejected with 422 by hosting_headless_submit-build-report`;\n appendFileSync(ws.eventsPath, `${JSON.stringify({ ts: now(), run: run.id, type: 'issue', stage: run.reported_at ? 'done' : 'check_state', symptom, severity: 'medium', resolved: false, user_had_to_intervene: false })}\\n`);\n console.log(`report ${id} marked rejected; issue logged in run ${run.id}`);\n}\n\n// Gaps are printed as warnings by `report`, so guesses never pass as measurements.\nconst EXPECTED_FOR_BUILD = STAGES.filter((stage) => stage !== 'done');\nfunction loggingGaps(stages, run, outcome) {\n const gaps = [];\n for (const s of stages) {\n // A skipped stage did no work, so it has no duration to measure.\n const problem = s.result === 'skipped' ? null\n : !s.ended_at ? 'started but never ended'\n : s.start_estimated ? 'start time estimated, not measured'\n : Date.parse(s.ended_at) === Date.parse(s.started_at) && !s.note?.endsWith(PAUSE_NOTE) ? 'logged with no duration; probably started and ended in one go after the work'\n : null;\n if (problem) gaps.push({ stage: s.stage, phase: s.phase, problem });\n }\n if (run.kind === 'build' && outcome === 'live') {\n for (const stage of EXPECTED_FOR_BUILD) {\n if (!stages.some((s) => s.stage === stage)) gaps.push({ stage, phase: null, problem: 'never logged, though the site went live' });\n }\n }\n return gaps;\n}\n\nfunction lastActivity(run, history, events) {\n return [run.started_at, ...history.flatMap((h) => [h.started_at, h.ended_at]), ...events.map((e) => e.ts)]\n .filter(Boolean)\n .sort()\n .at(-1);\n}\n\nfunction stoppedAt(stages, fallbackStage) {\n const stuck = [...stages].reverse().find((s) => !s.ended_at || s.result === 'failed' || s.result === 'stopped');\n return stuck?.stage ?? fallbackStage ?? null;\n}\n\n// Minimal JSON Schema subset, so reports from different tools share one shape without a dependency.\nconst reportSchema = () => readJson(join(here, 'report.schema.json'), null);\nconst eventSchema = (type) => reportSchema()?.properties?.[EVENT_LISTS[type]]?.items ?? null;\n\nfunction schemaError(value, schema, path = 'report') {\n if (!schema) return null;\n const types = [].concat(schema.type ?? []);\n const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : Number.isInteger(value) ? 'integer' : typeof value;\n if (types.length && !types.includes(actual) && !(actual === 'integer' && types.includes('number'))) {\n return `${path} should be ${types.join(' or ')}, got ${actual}`;\n }\n if (schema.enum && !schema.enum.includes(value)) return `${path} should be one of ${schema.enum.join(', ')}`;\n if (actual === 'object') {\n for (const key of schema.required ?? []) if (!(key in value)) return `${path}.${key} is missing`;\n for (const [key, sub] of Object.entries(schema.properties ?? {})) {\n const error = key in value ? schemaError(value[key], sub, `${path}.${key}`) : null;\n if (error) return error;\n }\n }\n if (actual === 'array' && schema.items) {\n for (const [i, item] of value.entries()) {\n const error = schemaError(item, schema.items, `${path}[${i}]`);\n if (error) return error;\n }\n }\n return null;\n}\n\nfunction validate(value, schema, path) {\n const error = schemaError(value, schema, path);\n if (error) fail(error);\n}\n\nconst esc = (v) => String(v ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\nconst label = (s) => String(s ?? '').replace(/_/g, ' ');\nconst time = (iso) => (iso ? iso.slice(11, 19) : '—');\nconst fmt = (n) => (typeof n === 'number' ? n.toLocaleString('en-US') : '—');\n\nfunction gantt(report) {\n const stages = report.timing.stages;\n if (!stages.length) return '<p class=\"muted\">No stages were logged for this run.</p>';\n const t0 = Date.parse(report.timing.started_at);\n const at = (iso) => (Date.parse(iso) - t0) / 60000;\n const total = Math.max(report.timing.minutes_total ?? 1, ...stages.map((s) => at(s.ended_at ?? report.timing.ended_at)), 1);\n const step = [1, 2, 5, 10, 15, 30, 60, 120, 240].find((s) => total / s <= 8) ?? 480;\n const span = Math.ceil(total / step) * step;\n const W = 760;\n const LABEL = 160;\n const ROW = 32;\n const TOP = 32;\n const H = TOP + ROW * stages.length + 32;\n const x = (m) => LABEL + ((W - LABEL - 40) * m) / span;\n const out = [`<svg viewBox=\"0 0 ${W} ${H}\" role=\"img\" aria-labelledby=\"gantt-title\" class=\"gantt\"><title id=\"gantt-title\">Stage timeline, minutes from the start of the run</title>`];\n for (let m = 0; m <= span; m += step) {\n out.push(`<line x1=\"${x(m).toFixed(1)}\" x2=\"${x(m).toFixed(1)}\" y1=\"${TOP - 8}\" y2=\"${H - 28}\" class=\"grid\"/><text x=\"${x(m).toFixed(1)}\" y=\"${H - 10}\" class=\"tick\" text-anchor=\"middle\">${m} min</text>`);\n }\n for (const f of report.run.follow_ups ?? []) {\n const fx = x(at(f.resumed_at)).toFixed(1);\n out.push(`<line x1=\"${fx}\" x2=\"${fx}\" y1=\"${TOP - 12}\" y2=\"${H - 28}\" class=\"follow-up\"/><text x=\"${Number(fx) + 6}\" y=\"${TOP - 12}\" class=\"follow-up-label\">Follow-up</text>`);\n }\n if (report.timing.live_at) {\n const lx = x(at(report.timing.live_at)).toFixed(1);\n out.push(`<line x1=\"${lx}\" x2=\"${lx}\" y1=\"${TOP - 12}\" y2=\"${H - 28}\" class=\"live\"/><text x=\"${lx - 6}\" y=\"${TOP - 12}\" class=\"live-label\" text-anchor=\"end\">Live · ${report.timing.minutes_to_live} min</text>`);\n }\n stages.forEach((s, i) => {\n const y = TOP + i * ROW;\n const a = at(s.started_at);\n const b = at(s.ended_at ?? report.timing.ended_at);\n const width = Math.max(x(b) - x(a), 4);\n const name = `${label(s.stage)}${s.phase ? ` · ${s.phase}` : ''}`;\n const tip = [name, `${s.minutes} min`, s.result ? label(s.result) : 'not finished', s.start_estimated ? 'start estimated' : null, s.note].filter(Boolean).join(' · ');\n const failed = s.result === 'failed' || s.result === 'stopped' || !s.ended_at;\n const fill = failed ? 'url(#hatch)' : s.start_estimated ? 'none' : 'var(--series-1)';\n out.push(`<text x=\"${LABEL - 12}\" y=\"${(y + ROW / 2 + 4).toFixed(1)}\" class=\"row-label\" text-anchor=\"end\">${esc(name)}</text>`);\n out.push(`<g class=\"bar\" tabindex=\"0\" data-tip=\"${esc(tip)}\"><rect x=\"${LABEL}\" y=\"${y}\" width=\"${W - LABEL - 16}\" height=\"${ROW}\" fill=\"transparent\"/><rect x=\"${x(a).toFixed(1)}\" y=\"${y + 8}\" width=\"${width.toFixed(1)}\" height=\"${ROW - 16}\" rx=\"4\" fill=\"${fill}\"${s.start_estimated && !failed ? ' stroke=\"var(--series-1)\" stroke-width=\"2\" stroke-dasharray=\"4 3\"' : ''}/></g>`);\n });\n out.push('<defs><pattern id=\"hatch\" width=\"6\" height=\"6\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\"><rect width=\"6\" height=\"6\" fill=\"var(--series-1)\"/><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"6\" stroke=\"var(--surface-1)\" stroke-width=\"2.5\"/></pattern></defs></svg>');\n return out.join('');\n}\n\nfunction renderHtml(r) {\n const tile = (name, value, sub = '') => `<div class=\"tile\"><div class=\"tile-label\">${esc(name)}</div><div class=\"tile-value\">${esc(value)}</div><div class=\"tile-sub\">${esc(sub)}</div></div>`;\n const stepped = r.issues.filter((i) => i.user_had_to_intervene).length;\n const rejected = r.user_feedback.filter((f) => f.category === 'design_rejected').length;\n const t = r.tokens && ['input', 'output', 'cache_read', 'cache_write', 'est_cost_usd'].some((k) => r.tokens[k] != null) ? r.tokens : null;\n const tiles = [\n r.timing.minutes_to_live != null\n ? tile('Time to live', `${r.timing.minutes_to_live} min`, 'start of run → deploy finished')\n : tile('Outcome', label(r.info.outcome), r.info.stopped_at ? `stopped at ${label(r.info.stopped_at)}` : ''),\n tile('Run length', `${r.timing.minutes_total} min`, `${r.timing.stages.length} stage entries`),\n tile('Issues', String(r.issues.length), `${stepped} needed the user to step in`),\n tile('User feedback', String(r.user_feedback.length), rejected ? `${rejected} design rejections` : 'corrections and requests'),\n t ? tile('Tokens', fmt((t.input ?? 0) + (t.output ?? 0) + (t.cache_read ?? 0) + (t.cache_write ?? 0)), t.est_cost_usd != null ? `≈ $${t.est_cost_usd} API-equivalent` : t.source ?? '') : tile('Tokens', '—', 'not reported by this tool'),\n ].join('');\n const SEV = { high: ['●', 'critical', 'High'], medium: ['▲', 'serious', 'Medium'], low: ['■', 'warning', 'Low'] };\n const order = ['high', 'medium', 'low'];\n const issues = [...r.issues]\n .sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity))\n .map((i) => {\n const [icon, cls, name] = SEV[i.severity];\n return `<tr><td><span class=\"sev sev-${cls}\"><span aria-hidden=\"true\">${icon}</span> ${name}</span></td><td>${esc(label(i.stage))}</td><td>${esc(i.symptom)}${i.user_had_to_intervene ? ' <span class=\"chip\">user had to step in</span>' : ''}</td><td>${esc(i.cause)}</td><td>${esc(i.workaround)}</td><td>${i.resolved ? '✓ Resolved' : 'Open'}</td></tr>`;\n })\n .join('');\n const list = (items, render, empty) => (items.length ? `<ul>${items.map(render).join('')}</ul>` : `<p class=\"muted\">${empty}</p>`);\n const stageRows = r.timing.stages\n .map((s) => `<tr><td>${esc(label(s.stage))}${s.phase ? ` · ${esc(s.phase)}` : ''}</td><td>${time(s.started_at)}</td><td>${time(s.ended_at)}</td><td class=\"num\">${s.minutes ?? '—'}</td><td>${esc(label(s.result ?? 'not finished'))}</td><td>${esc(s.note)}</td></tr>`)\n .join('');\n const details = [\n ['Domain', r.info.domain],\n ['Outcome', [label(r.info.outcome), r.info.live_url].filter(Boolean).join(' · ')],\n ['Run', `${r.run.id} · ${r.run.kind}`],\n ['Tool / model', [r.info.tool, r.info.model].filter(Boolean).join(' · ') || '—'],\n ['Stack', [r.info.backend, r.info.frontend].filter(Boolean).join(' + ') || '—'],\n ['Environment', `${r.info.os} · Node ${r.info.node}${r.info.mcp ? ` · ${r.info.mcp}` : ''}`],\n ['Skill version', r.run.skill ?? '—'],\n ...(r.run.follow_ups?.length\n ? [['Follow-ups', r.run.follow_ups.map((f) => `resumed ${time(f.resumed_at)}${f.reason ? ` — ${f.reason}` : ''}`).join('; ')]]\n : []),\n ]\n .map(([k, v]) => `<div><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`)\n .join('');\n const tokenTable = t\n ? `<section><h2>Tokens</h2><div class=\"table-wrap\"><table><thead><tr><th class=\"num\">Requests</th><th class=\"num\">Input</th><th class=\"num\">Output</th><th class=\"num\">Cache read</th><th class=\"num\">Cache write</th><th class=\"num\">≈ API cost</th></tr></thead><tbody><tr><td class=\"num\">${fmt(t.requests)}</td><td class=\"num\">${fmt(t.input)}</td><td class=\"num\">${fmt(t.output)}</td><td class=\"num\">${fmt(t.cache_read)}</td><td class=\"num\">${fmt(t.cache_write)}</td><td class=\"num\">${t.est_cost_usd != null ? `$${t.est_cost_usd}` : '—'}</td></tr></tbody></table></div><p class=\"muted\">${esc(t.source ?? '')}</p></section>`\n : '';\n const previous = r.previous_runs.length\n ? `<section><h2>Earlier runs on this domain</h2><ul>${r.previous_runs.map((p) => `<li><a href=\"${esc(p.html)}\">${esc(p.run)}</a> — ${esc(p.kind)} · ${esc(label(p.outcome))}${p.minutes != null ? ` · ${p.minutes} min` : ''}</li>`).join('')}</ul></section>`\n : '';\n\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Build report — ${esc(r.info.domain)}</title>\n<style>\n.viz-root { color-scheme: light; --surface-0:#f4f4f2; --surface-1:#fcfcfb; --border:#e2e1dc; --text-primary:#0b0b0b; --text-secondary:#52514e; --text-muted:#6b6a65; --series-1:#2a78d6; --grid:#e8e7e2; --warning:#fab219; --serious:#ec835a; --critical:#d03b3b; }\n@media (prefers-color-scheme: dark) { .viz-root { color-scheme: dark; --surface-0:#111110; --surface-1:#1a1a19; --border:#33332f; --text-primary:#f0efec; --text-secondary:#c3c2b7; --text-muted:#a3a299; --series-1:#3987e5; --grid:#2a2a27; } }\n* { box-sizing: border-box; }\nbody { margin:0; background:var(--surface-0); color:var(--text-primary); font:15px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif; }\nmain { max-width:1080px; margin:0 auto; padding:32px 24px 64px; }\nh1 { font-size:28px; line-height:1.2; margin:0 0 4px; } h2 { font-size:18px; margin:0 0 16px; }\na { color:var(--series-1); }\n.lede { color:var(--text-secondary); margin:0 0 24px; }\nsection { background:var(--surface-1); border:1px solid var(--border); border-radius:12px; padding:24px; margin-bottom:24px; }\n.tiles { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:16px; margin-bottom:24px; }\n.tile { background:var(--surface-1); border:1px solid var(--border); border-radius:12px; padding:16px; }\n.tile-label { color:var(--text-secondary); font-size:13px; } .tile-value { font-size:28px; font-weight:650; line-height:1.3; font-variant-numeric:tabular-nums; } .tile-sub { color:var(--text-muted); font-size:13px; }\ndl { display:grid; grid-template-columns:repeat(auto-fit,minmax(300px,1fr)); gap:12px 24px; margin:0; } dt { color:var(--text-muted); font-size:13px; } dd { margin:0; overflow-wrap:anywhere; }\n.gantt { width:100%; height:auto; display:block; } .grid { stroke:var(--grid); stroke-width:1; } .tick { fill:var(--text-secondary); font-size:12px; } .row-label { fill:var(--text-primary); font-size:13px; text-transform:capitalize; }\n.live { stroke:var(--text-primary); stroke-width:2; stroke-dasharray:4 4; } .follow-up { stroke:var(--text-muted); stroke-width:1; stroke-dasharray:2 4; } .follow-up-label { fill:var(--text-muted); font-size:12px; } .live-label { fill:var(--text-primary); font-size:12px; font-weight:600; }\n.bar { outline:none; } .bar:hover rect:last-child, .bar:focus rect:last-child { stroke:var(--text-primary); stroke-width:2; }\n.legend { display:flex; gap:24px; flex-wrap:wrap; color:var(--text-secondary); font-size:13px; margin-top:8px; } .swatch { display:inline-block; width:24px; height:12px; border-radius:4px; vertical-align:-1px; margin-right:6px; }\n.sw-solid { background:var(--series-1); } .sw-est { border:2px dashed var(--series-1); } .sw-hatch { background:repeating-linear-gradient(45deg,var(--series-1) 0 3px,var(--surface-1) 3px 6px); }\n#tip { position:fixed; pointer-events:none; background:var(--text-primary); color:var(--surface-1); font-size:13px; padding:8px 12px; border-radius:8px; max-width:340px; opacity:0; transition:opacity .1s; z-index:5; }\ntable { width:100%; border-collapse:collapse; font-size:14px; } th,td { text-align:left; padding:8px 12px; border-bottom:1px solid var(--border); vertical-align:top; } th { color:var(--text-secondary); font-weight:600; font-size:13px; }\ntd.num,th.num { text-align:right; font-variant-numeric:tabular-nums; } .table-wrap { overflow-x:auto; }\n.sev { white-space:nowrap; font-weight:600; } .sev-critical span { color:var(--critical); } .sev-serious span { color:var(--serious); } .sev-warning span { color:var(--warning); }\n.chip { display:inline-block; font-size:12px; padding:0 8px; border-radius:999px; border:1px solid var(--border); color:var(--text-secondary); white-space:nowrap; }\n.cols { display:grid; grid-template-columns:repeat(auto-fit,minmax(320px,1fr)); gap:24px; margin-bottom:24px; } .cols section { margin:0; }\nul { margin:0; padding-left:20px; } li { margin-bottom:8px; } .muted { color:var(--text-muted); font-size:13px; }\ncode { font-size:13px; background:var(--surface-0); padding:1px 4px; border-radius:4px; }\ndetails summary { cursor:pointer; color:var(--text-secondary); margin-top:16px; }\n</style></head><body class=\"viz-root\"><main>\n<h1>Build report — ${esc(r.info.domain)}</h1>\n<p class=\"lede\">${esc(label(r.run.kind))} run · ${esc(r.timing.started_at.slice(0, 16).replace('T', ' '))} UTC · ${esc(label(r.info.outcome))}</p>\n<div class=\"tiles\">${tiles}</div>\n<section><h2>Stage timeline</h2>${gantt(r)}\n<div class=\"legend\"><span><span class=\"swatch sw-solid\"></span>Finished</span><span><span class=\"swatch sw-hatch\"></span>Failed, stopped or not finished</span><span><span class=\"swatch sw-est\"></span>Start estimated</span><span>Stages can overlap: prep work runs while provisioning settles.</span></div>\n<details><summary>Show as table</summary><div class=\"table-wrap\"><table><thead><tr><th>Stage</th><th>Start</th><th>End</th><th class=\"num\">Minutes</th><th>Result</th><th>Note</th></tr></thead><tbody>${stageRows}</tbody></table></div></details></section>\n${r.logging_gaps.length ? `<section><h2>Logging gaps (${r.logging_gaps.length})</h2><p class=\"muted\">Where the run log is missing or unsure, so times here are less reliable.</p><ul>${r.logging_gaps.map((g) => `<li><strong>${esc(label(g.stage))}${g.phase ? ` · ${esc(g.phase)}` : ''}</strong> — ${esc(g.problem)}</li>`).join('')}</ul></section>` : ''}\n<section><h2>Issues (${r.issues.length})</h2>${r.issues.length ? `<div class=\"table-wrap\"><table><thead><tr><th>Severity</th><th>Stage</th><th>Symptom</th><th>Cause</th><th>Workaround</th><th>Status</th></tr></thead><tbody>${issues}</tbody></table></div>` : '<p class=\"muted\">No issues logged.</p>'}</section>\n<div class=\"cols\"><section><h2>User feedback</h2>${list(r.user_feedback, (f) => `<li><span class=\"chip\">${esc(label(f.category))}</span> <span class=\"muted\">${esc(label(f.stage))}</span> — “${esc(f.paraphrase)}”</li>`, 'No feedback logged.')}</section>\n<section><h2>Skill gaps</h2>${list(r.skill_gaps, (g) => `<li><code>${esc(g.skill)}</code> — ${esc(g.gap)}</li>`, 'No skill gaps logged.')}</section></div>\n<div class=\"cols\"><section><h2>What went well</h2>${list(r.what_went_well, (g) => `<li>${esc(g.text)}</li>`, 'Nothing logged.')}</section>\n<section><h2>Run details</h2><dl>${details}</dl></section></div>\n${tokenTable}${previous}\n</main><div id=\"tip\" role=\"status\"></div>\n<script>\nconst tip = document.getElementById('tip');\nconst show = (el, x, y) => { tip.textContent = el.dataset.tip; tip.style.left = Math.min(x + 12, innerWidth - 360) + 'px'; tip.style.top = (y + 12) + 'px'; tip.style.opacity = 1; };\ndocument.querySelectorAll('.bar').forEach((el) => {\n el.addEventListener('mousemove', (e) => show(el, e.clientX, e.clientY));\n el.addEventListener('mouseleave', () => (tip.style.opacity = 0));\n el.addEventListener('focus', () => { const r = el.getBoundingClientRect(); show(el, r.left + r.width / 2, r.top); });\n el.addEventListener('blur', () => (tip.style.opacity = 0));\n});\n</script></body></html>\n`;\n}\n\nfunction report(ws, flags) {\n let tokens;\n if (typeof flags.tokens === 'string') {\n try {\n tokens = JSON.parse(flags.tokens);\n } catch {\n fail('--tokens must be JSON, e.g. \\'{\"input\":0,\"output\":0,\"source\":\"…\"}\\'');\n }\n // null and {} can't be sent; treat them as not reported.\n if (tokens === null || (typeof tokens === 'object' && !Array.isArray(tokens) && !Object.keys(tokens).length)) tokens = undefined;\n else validate(tokens, { ...reportSchema()?.properties?.tokens, type: 'object' }, '--tokens');\n }\n console.log(`report written: ${buildReport(ws, { outcome: flags.outcome, tokens })}`);\n const { id, file } = reportFile(ws);\n console.log(`send it: pass ${file} unchanged to hosting_headless_submit-build-report, then run report-sent ${id} (or report-rejected ${id} on a 422)`);\n}\n\n// What each command does with the domain's lock: check it (refuse if another live session holds it,\n// refresh it if this one does), take it, start (take it, or take it over when asked), release it\n// after the command, or leave it alone.\nconst COMMANDS = {\n 'run-start': { lock: 'start', run: (ws, rest, flags, claim) => runStart(ws, flags, claim.wasFree) },\n 'run-update': { lock: 'check', run: (ws, rest, flags) => runUpdate(ws, flags) },\n 'run-resume': { lock: 'take', run: (ws, rest, flags) => runResume(ws, flags) },\n 'stage-start': { lock: 'check', run: stageStart },\n 'stage-end': { lock: 'check', run: stageEnd },\n next: { lock: 'check', run: next },\n 'stage-fix': { lock: 'check', run: stageFix },\n event: { lock: 'check', run: (ws, rest) => event(ws, rest) },\n pause: { lock: 'release', run: (ws) => pause(ws) },\n report: { lock: 'release', run: (ws, rest, flags) => report(ws, flags) },\n unsent: { lock: 'none', run: (ws) => unsent(ws) },\n 'report-sent': { lock: 'check', run: (ws, rest) => reportSent(ws, rest) },\n 'report-rejected': { lock: 'check', run: (ws, rest) => reportRejected(ws, rest) },\n};\n\nconst { positional, flags } = parseArgs(process.argv.slice(2));\nconst [domain, command, ...rest] = positional;\nconst spec = COMMANDS[command];\nconst names = Object.keys(COMMANDS);\nif (!spec) fail(`command must be ${names.slice(0, -1).join(', ')} or ${names.at(-1)}`);\nconst ws = workspace(domain, { create: spec.lock === 'start' });\nconst start = spec.lock === 'start';\nconst claim = spec.lock === 'none' ? null : claimLock(ws, {\n take: start || spec.lock === 'take',\n start,\n takeOver: start && flags['take-over'] === true,\n tool: start && typeof flags.tool === 'string' ? flags.tool : null,\n});\nspec.run(ws, rest, flags, claim);\n// A command that fails exits before this, so a refused pause or report keeps the lock.\nif (spec.lock === 'release' && claim.lock) rmSync(ws.lockPath, { force: true });\n"
208
208
  },
209
209
  {
210
210
  "uri": "skill://hostinger-headless/steps/01-refine/SKILL.md",
@@ -6430,6 +6430,107 @@ export default [
6430
6430
  "manage_inventory"
6431
6431
  ]
6432
6432
  },
6433
+ {
6434
+ "name": "ecommerce_webhooks_get",
6435
+ "title": "Get an ecommerce webhook",
6436
+ "annotations": {
6437
+ "title": "Get an ecommerce webhook",
6438
+ "readOnlyHint": true,
6439
+ "destructiveHint": false
6440
+ },
6441
+ "description": "Get a subscription owned by your store, without signing secrets.",
6442
+ "method": "GET",
6443
+ "path": "/api/ecommerce/v1/stores/{store_id}/webhooks/{endpoint_id}",
6444
+ "inputSchema": {
6445
+ "type": "object",
6446
+ "properties": {
6447
+ "store_id": {
6448
+ "type": "string",
6449
+ "description": "ID of the store owned by your account."
6450
+ },
6451
+ "endpoint_id": {
6452
+ "type": "string",
6453
+ "description": "Webhook endpoint ID belonging to this store."
6454
+ }
6455
+ },
6456
+ "required": [
6457
+ "store_id",
6458
+ "endpoint_id"
6459
+ ]
6460
+ },
6461
+ "security": [
6462
+ {
6463
+ "apiToken": []
6464
+ }
6465
+ ],
6466
+ "group": "ecommerce"
6467
+ },
6468
+ {
6469
+ "name": "ecommerce_webhooks_delete",
6470
+ "title": "Delete an ecommerce webhook",
6471
+ "annotations": {
6472
+ "title": "Delete an ecommerce webhook",
6473
+ "readOnlyHint": false,
6474
+ "destructiveHint": true,
6475
+ "idempotentHint": true
6476
+ },
6477
+ "description": "Delete a subscription owned by your store, retaining delivery audit records.",
6478
+ "method": "DELETE",
6479
+ "path": "/api/ecommerce/v1/stores/{store_id}/webhooks/{endpoint_id}",
6480
+ "inputSchema": {
6481
+ "type": "object",
6482
+ "properties": {
6483
+ "store_id": {
6484
+ "type": "string",
6485
+ "description": "ID of the store owned by your account."
6486
+ },
6487
+ "endpoint_id": {
6488
+ "type": "string",
6489
+ "description": "Webhook endpoint ID belonging to this store."
6490
+ }
6491
+ },
6492
+ "required": [
6493
+ "store_id",
6494
+ "endpoint_id"
6495
+ ]
6496
+ },
6497
+ "security": [
6498
+ {
6499
+ "apiToken": []
6500
+ }
6501
+ ],
6502
+ "group": "ecommerce"
6503
+ },
6504
+ {
6505
+ "name": "ecommerce_webhooks_list",
6506
+ "title": "List ecommerce webhooks",
6507
+ "annotations": {
6508
+ "title": "List ecommerce webhooks",
6509
+ "readOnlyHint": true,
6510
+ "destructiveHint": false
6511
+ },
6512
+ "description": "List your store's subscriptions for external automation systems, without signing secrets.",
6513
+ "method": "GET",
6514
+ "path": "/api/ecommerce/v1/stores/{store_id}/webhooks",
6515
+ "inputSchema": {
6516
+ "type": "object",
6517
+ "properties": {
6518
+ "store_id": {
6519
+ "type": "string",
6520
+ "description": "ID of the store owned by your account."
6521
+ }
6522
+ },
6523
+ "required": [
6524
+ "store_id"
6525
+ ]
6526
+ },
6527
+ "security": [
6528
+ {
6529
+ "apiToken": []
6530
+ }
6531
+ ],
6532
+ "group": "ecommerce"
6533
+ },
6433
6534
  {
6434
6535
  "name": "gpu_instances_get",
6435
6536
  "title": "Get instance details",
@@ -6450,6 +6450,107 @@ const tools: OpenApiTool[] = [
6450
6450
  "manage_inventory"
6451
6451
  ]
6452
6452
  },
6453
+ {
6454
+ "name": "ecommerce_webhooks_get",
6455
+ "title": "Get an ecommerce webhook",
6456
+ "annotations": {
6457
+ "title": "Get an ecommerce webhook",
6458
+ "readOnlyHint": true,
6459
+ "destructiveHint": false
6460
+ },
6461
+ "description": "Get a subscription owned by your store, without signing secrets.",
6462
+ "method": "GET",
6463
+ "path": "/api/ecommerce/v1/stores/{store_id}/webhooks/{endpoint_id}",
6464
+ "inputSchema": {
6465
+ "type": "object",
6466
+ "properties": {
6467
+ "store_id": {
6468
+ "type": "string",
6469
+ "description": "ID of the store owned by your account."
6470
+ },
6471
+ "endpoint_id": {
6472
+ "type": "string",
6473
+ "description": "Webhook endpoint ID belonging to this store."
6474
+ }
6475
+ },
6476
+ "required": [
6477
+ "store_id",
6478
+ "endpoint_id"
6479
+ ]
6480
+ },
6481
+ "security": [
6482
+ {
6483
+ "apiToken": []
6484
+ }
6485
+ ],
6486
+ "group": "ecommerce"
6487
+ },
6488
+ {
6489
+ "name": "ecommerce_webhooks_delete",
6490
+ "title": "Delete an ecommerce webhook",
6491
+ "annotations": {
6492
+ "title": "Delete an ecommerce webhook",
6493
+ "readOnlyHint": false,
6494
+ "destructiveHint": true,
6495
+ "idempotentHint": true
6496
+ },
6497
+ "description": "Delete a subscription owned by your store, retaining delivery audit records.",
6498
+ "method": "DELETE",
6499
+ "path": "/api/ecommerce/v1/stores/{store_id}/webhooks/{endpoint_id}",
6500
+ "inputSchema": {
6501
+ "type": "object",
6502
+ "properties": {
6503
+ "store_id": {
6504
+ "type": "string",
6505
+ "description": "ID of the store owned by your account."
6506
+ },
6507
+ "endpoint_id": {
6508
+ "type": "string",
6509
+ "description": "Webhook endpoint ID belonging to this store."
6510
+ }
6511
+ },
6512
+ "required": [
6513
+ "store_id",
6514
+ "endpoint_id"
6515
+ ]
6516
+ },
6517
+ "security": [
6518
+ {
6519
+ "apiToken": []
6520
+ }
6521
+ ],
6522
+ "group": "ecommerce"
6523
+ },
6524
+ {
6525
+ "name": "ecommerce_webhooks_list",
6526
+ "title": "List ecommerce webhooks",
6527
+ "annotations": {
6528
+ "title": "List ecommerce webhooks",
6529
+ "readOnlyHint": true,
6530
+ "destructiveHint": false
6531
+ },
6532
+ "description": "List your store's subscriptions for external automation systems, without signing secrets.",
6533
+ "method": "GET",
6534
+ "path": "/api/ecommerce/v1/stores/{store_id}/webhooks",
6535
+ "inputSchema": {
6536
+ "type": "object",
6537
+ "properties": {
6538
+ "store_id": {
6539
+ "type": "string",
6540
+ "description": "ID of the store owned by your account."
6541
+ }
6542
+ },
6543
+ "required": [
6544
+ "store_id"
6545
+ ]
6546
+ },
6547
+ "security": [
6548
+ {
6549
+ "apiToken": []
6550
+ }
6551
+ ],
6552
+ "group": "ecommerce"
6553
+ },
6453
6554
  {
6454
6555
  "name": "gpu_instances_get",
6455
6556
  "title": "Get instance details",