@reddoorla/maintenance 0.88.2 → 0.89.0

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 (116) hide show
  1. package/dist/{announce-GKD5YJNB.js → announce-OJFAS5JT.js} +6 -6
  2. package/dist/{blux-DN4MI532.js → blux-EATHOHKK.js} +5 -5
  3. package/dist/{chunk-7UAYMAKR.js → chunk-3VQWSE3F.js} +4 -4
  4. package/dist/{chunk-A2UNJIKH.js → chunk-5PWB3JHJ.js} +6 -4
  5. package/dist/chunk-5PWB3JHJ.js.map +1 -0
  6. package/dist/{chunk-K6SLF6GI.js → chunk-62NYED6E.js} +6 -6
  7. package/dist/{chunk-B23FFWU4.js → chunk-AEXJDCJN.js} +96 -19
  8. package/dist/{chunk-B23FFWU4.js.map → chunk-AEXJDCJN.js.map} +1 -1
  9. package/dist/{chunk-7FFUBF4I.js → chunk-AX22DH6S.js} +2 -2
  10. package/dist/{chunk-7TMWBXX7.js → chunk-DXKF552B.js} +269 -7
  11. package/dist/chunk-DXKF552B.js.map +1 -0
  12. package/dist/{chunk-6I6L3CMX.js → chunk-KGUKL3CV.js} +2 -2
  13. package/dist/{chunk-ULHPALI5.js → chunk-NDCOOI3V.js} +2 -2
  14. package/dist/{chunk-GQDDWYU2.js → chunk-QBAAZY7W.js} +1 -1
  15. package/dist/{chunk-GQDDWYU2.js.map → chunk-QBAAZY7W.js.map} +1 -1
  16. package/dist/{chunk-KMCZA7CH.js → chunk-QLIUDTY6.js} +2 -2
  17. package/dist/{chunk-XP5WM2LV.js → chunk-SKI23ZZH.js} +4 -4
  18. package/dist/chunk-SVAAONYB.js +21 -0
  19. package/dist/chunk-SVAAONYB.js.map +1 -0
  20. package/dist/{chunk-DGZWFI2G.js → chunk-VBEKL445.js} +17 -8
  21. package/dist/chunk-VBEKL445.js.map +1 -0
  22. package/dist/{chunk-ANJNTAMM.js → chunk-ZOCJBJQV.js} +4 -2
  23. package/dist/{chunk-J3WEZGIN.js → chunk-ZRI5VRPG.js} +4 -4
  24. package/dist/cli/bin.js +27 -18
  25. package/dist/cli/bin.js.map +1 -1
  26. package/dist/cli/commands/audit.js +5 -5
  27. package/dist/{db-V6UIS433.js → db-DAJX7NNW.js} +51 -10
  28. package/dist/db-DAJX7NNW.js.map +1 -0
  29. package/dist/{digest-2JEAEJK6.js → digest-T6TAZNLF.js} +73 -16
  30. package/dist/digest-T6TAZNLF.js.map +1 -0
  31. package/dist/digest-collectors-NI2M3UTC.js +50 -0
  32. package/dist/digest-state-3KHZF7GD.js +50 -0
  33. package/dist/digest-state-3KHZF7GD.js.map +1 -0
  34. package/dist/{dump-EPL7AZFR.js → dump-QK7LNOGC.js} +14 -1
  35. package/dist/{dump-EPL7AZFR.js.map → dump-QK7LNOGC.js.map} +1 -1
  36. package/dist/{email-SL7464YI.js → email-LJQT5J7F.js} +6 -7
  37. package/dist/{email-SL7464YI.js.map → email-LJQT5J7F.js.map} +1 -1
  38. package/dist/{ensure-site-FU6527OU.js → ensure-site-NSNY2QHN.js} +2 -2
  39. package/dist/{fleet-state-R5LU7IC3.js → fleet-state-3LQUQHYD.js} +2 -2
  40. package/dist/{forms-notify-target-SGDGXXK5.js → forms-notify-target-LYSKME5L.js} +2 -2
  41. package/dist/freeze-A6MUCZU4.js +9 -0
  42. package/dist/{github-signals-GWGCKEE2.js → github-signals-4YML6NY5.js} +4 -4
  43. package/dist/{health-mirror-GCDN7BJL.js → health-mirror-7LKC7Q5Z.js} +5 -5
  44. package/dist/index.d.ts +19 -4
  45. package/dist/index.js +29 -28
  46. package/dist/index.js.map +1 -1
  47. package/dist/{init-FGTYNGUI.js → init-NHKADHB6.js} +7 -7
  48. package/dist/{launch-5H7LPEGP.js → launch-VQJ4Z35C.js} +6 -6
  49. package/dist/{orchestrate-JNKCWU5K.js → orchestrate-6HROYTM6.js} +4 -4
  50. package/dist/{parity-NBYZUBFU.js → parity-623WNFZG.js} +3 -3
  51. package/dist/{pipeline-WYTXSLHX.js → pipeline-MQJD4CKN.js} +6 -2
  52. package/dist/{preflight-IMTYDDD4.js → preflight-LIN5NCYU.js} +5 -5
  53. package/dist/{prismic-ci-MY2U6NN7.js → prismic-ci-PZ5LCPWT.js} +4 -4
  54. package/dist/{prismic-models-NJN5JORF.js → prismic-models-6OYYZUR5.js} +3 -3
  55. package/dist/prospect/types.d.ts +27 -0
  56. package/dist/{prospect-audit-JMBRVXSG.js → prospect-audit-DBBXL7EG.js} +8 -6
  57. package/dist/prospect-audit-DBBXL7EG.js.map +1 -0
  58. package/dist/recipes/sync-configs.js +2 -2
  59. package/dist/{render-VX72AESY.js → render-P3SBUFVB.js} +3 -3
  60. package/dist/{render-from-row-DOYJDO2L.js → render-from-row-P5CWM3MQ.js} +3 -3
  61. package/dist/render-from-row-P5CWM3MQ.js.map +1 -0
  62. package/dist/{report-TALY5P3L.js → report-2N4PXO3L.js} +33 -17
  63. package/dist/report-2N4PXO3L.js.map +1 -0
  64. package/dist/{report-mirror-AAK3MXHY.js → report-mirror-3ENU6OOK.js} +5 -5
  65. package/dist/{selftest-NZTR4SM2.js → selftest-CUX2FIQD.js} +7 -7
  66. package/dist/{site-mirror-Q763PLGG.js → site-mirror-RQTEAID5.js} +5 -5
  67. package/dist/{sync-GBFV45WX.js → sync-ESP5ZQUU.js} +3 -3
  68. package/dist/{sync-configs-34JIA6KZ.js → sync-configs-LVBITPLU.js} +3 -3
  69. package/dist/usage-UHKU76VK.js +147 -0
  70. package/dist/usage-UHKU76VK.js.map +1 -0
  71. package/dist/{write-audits-to-airtable-OBHGR7DQ.js → write-audits-to-airtable-K352LZQY.js} +3 -3
  72. package/dist/write-audits-to-airtable-K352LZQY.js.map +1 -0
  73. package/package.json +1 -1
  74. package/dist/chunk-7TMWBXX7.js.map +0 -1
  75. package/dist/chunk-A2UNJIKH.js.map +0 -1
  76. package/dist/chunk-DGZWFI2G.js.map +0 -1
  77. package/dist/chunk-RUPPWAD6.js +0 -7
  78. package/dist/chunk-RUPPWAD6.js.map +0 -1
  79. package/dist/db-V6UIS433.js.map +0 -1
  80. package/dist/digest-2JEAEJK6.js.map +0 -1
  81. package/dist/digest-state-CRZRNGDI.js +0 -25
  82. package/dist/digest-state-CRZRNGDI.js.map +0 -1
  83. package/dist/prospect-audit-JMBRVXSG.js.map +0 -1
  84. package/dist/report-TALY5P3L.js.map +0 -1
  85. /package/dist/{announce-GKD5YJNB.js.map → announce-OJFAS5JT.js.map} +0 -0
  86. /package/dist/{blux-DN4MI532.js.map → blux-EATHOHKK.js.map} +0 -0
  87. /package/dist/{chunk-7UAYMAKR.js.map → chunk-3VQWSE3F.js.map} +0 -0
  88. /package/dist/{chunk-K6SLF6GI.js.map → chunk-62NYED6E.js.map} +0 -0
  89. /package/dist/{chunk-7FFUBF4I.js.map → chunk-AX22DH6S.js.map} +0 -0
  90. /package/dist/{chunk-6I6L3CMX.js.map → chunk-KGUKL3CV.js.map} +0 -0
  91. /package/dist/{chunk-ULHPALI5.js.map → chunk-NDCOOI3V.js.map} +0 -0
  92. /package/dist/{chunk-KMCZA7CH.js.map → chunk-QLIUDTY6.js.map} +0 -0
  93. /package/dist/{chunk-XP5WM2LV.js.map → chunk-SKI23ZZH.js.map} +0 -0
  94. /package/dist/{chunk-ANJNTAMM.js.map → chunk-ZOCJBJQV.js.map} +0 -0
  95. /package/dist/{chunk-J3WEZGIN.js.map → chunk-ZRI5VRPG.js.map} +0 -0
  96. /package/dist/{fleet-state-R5LU7IC3.js.map → digest-collectors-NI2M3UTC.js.map} +0 -0
  97. /package/dist/{ensure-site-FU6527OU.js.map → ensure-site-NSNY2QHN.js.map} +0 -0
  98. /package/dist/{orchestrate-JNKCWU5K.js.map → fleet-state-3LQUQHYD.js.map} +0 -0
  99. /package/dist/{forms-notify-target-SGDGXXK5.js.map → forms-notify-target-LYSKME5L.js.map} +0 -0
  100. /package/dist/{parity-NBYZUBFU.js.map → freeze-A6MUCZU4.js.map} +0 -0
  101. /package/dist/{github-signals-GWGCKEE2.js.map → github-signals-4YML6NY5.js.map} +0 -0
  102. /package/dist/{health-mirror-GCDN7BJL.js.map → health-mirror-7LKC7Q5Z.js.map} +0 -0
  103. /package/dist/{init-FGTYNGUI.js.map → init-NHKADHB6.js.map} +0 -0
  104. /package/dist/{launch-5H7LPEGP.js.map → launch-VQJ4Z35C.js.map} +0 -0
  105. /package/dist/{pipeline-WYTXSLHX.js.map → orchestrate-6HROYTM6.js.map} +0 -0
  106. /package/dist/{render-VX72AESY.js.map → parity-623WNFZG.js.map} +0 -0
  107. /package/dist/{render-from-row-DOYJDO2L.js.map → pipeline-MQJD4CKN.js.map} +0 -0
  108. /package/dist/{preflight-IMTYDDD4.js.map → preflight-LIN5NCYU.js.map} +0 -0
  109. /package/dist/{prismic-ci-MY2U6NN7.js.map → prismic-ci-PZ5LCPWT.js.map} +0 -0
  110. /package/dist/{prismic-models-NJN5JORF.js.map → prismic-models-6OYYZUR5.js.map} +0 -0
  111. /package/dist/{write-audits-to-airtable-OBHGR7DQ.js.map → render-P3SBUFVB.js.map} +0 -0
  112. /package/dist/{report-mirror-AAK3MXHY.js.map → report-mirror-3ENU6OOK.js.map} +0 -0
  113. /package/dist/{selftest-NZTR4SM2.js.map → selftest-CUX2FIQD.js.map} +0 -0
  114. /package/dist/{site-mirror-Q763PLGG.js.map → site-mirror-RQTEAID5.js.map} +0 -0
  115. /package/dist/{sync-GBFV45WX.js.map → sync-ESP5ZQUU.js.map} +0 -0
  116. /package/dist/{sync-configs-34JIA6KZ.js.map → sync-configs-LVBITPLU.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/bin.ts","../../src/cli/version.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { cac } from \"cac\";\nimport type { AuditName, RecipeName } from \"../types.js\";\nimport { loadCredentialsIntoEnv } from \"../util/credentials.js\";\nimport { resolvePackageVersion } from \"./version.js\";\n\n// Command modules are loaded LAZILY (dynamic `import()` inside each `.action()`),\n// never eagerly at the top. An eager `import { runReportCommand } from\n// \"./commands/report.js\"` would pull EVERY command's transitive dependency chain\n// into the CLI's startup graph — report/announce/launch drag in mjml + resend +\n// @google-analytics/data, `db` drags in the libSQL/kysely stack, etc. Those heavy\n// packages are `devDependencies` (this repo's CLI/functions/audits use them); a\n// consuming fleet site installs @reddoorla/maintenance only for `./forms` +\n// `./configs/*` and runs just `reddoor-maint audit --only a11y` in CI. Lazy\n// loading keeps that path (and `--help`/`--version`) free of the report/db\n// chains, so those packages never land in a consumer's node_modules. The\n// smoke-dist gate asserts bin.js's STATIC import closure stays free of them.\n\n// Load credentials from ~/.config/reddoor-maint/credentials.env before any\n// command runs, so AIRTABLE_PAT/AIRTABLE_BASE_ID/RESEND_API_KEY/etc. are\n// available from any cwd. Shell-exported env vars still win. Silent on\n// missing file — commands that need the credentials will fail with their\n// own clear error.\nloadCredentialsIntoEnv();\n\nconst here = dirname(fileURLToPath(import.meta.url));\nconst version = resolvePackageVersion(here);\n\nconst AUDIT_DESCRIPTIONS: Record<AuditName, string> = {\n deps: \"Diff site package.json against the bundled baseline version map.\",\n lighthouse: \"Run @lhci/cli autorun using the canonical lighthouserc.\",\n a11y: \"Playwright + axe against the canonical a11y routes.\",\n security:\n \"GitHub Dependabot alerts (prod+dev) for repo-backed sites; falls back to pnpm/npm audit (prod-deps) with no repo/token.\",\n lint: \"ESLint + Prettier using the canonical configs.\",\n domain: \"DNS resolve + TLS cert expiry against the deployed URL (checkout-free).\",\n browser:\n \"Playwright across desktop engines + mobile devices + link-check against the deployed URL (checkout-free).\",\n \"netlify-deploy\":\n \"Latest production deploy health via the Netlify API by site id (checkout-free; needs NETLIFY_PAT).\",\n \"function-health\":\n \"GET {deployedUrl}/health and read its ok/prismic/forms status (checkout-free).\",\n smoke: \"Run the site's own `pnpm test:smoke` suite in its checkout (clone-based).\",\n \"form-e2e\":\n \"Submit the real production contact form in test-mode against the deployed URL (checkout-free).\",\n};\n\nconst RECIPE_DESCRIPTIONS: Record<RecipeName, string> = {\n \"sync-configs\": \"Overwrite a site's canonical configs to match @reddoorla/maintenance.\",\n \"bump-deps\": \"Bump dependencies and commit the lockfile change.\",\n \"svelte-4-to-5\": \"Run the 7-commit Svelte 4 → 5 upgrade recipe.\",\n \"svelte-codemods\":\n \"Apply Svelte 5 gotcha codemods to an already-migrated site (state_referenced_locally, etc.).\",\n \"convert-to-pnpm\": \"Convert an npm/yarn site to pnpm (lockfile, packageManager, scripts).\",\n onboard: \"Install @reddoorla/maintenance + audit deps on a site (preferred first step).\",\n \"a11y-fixtures-page\":\n \"Write src/routes/dev/a11y-fixtures/+page.svelte (stub for lhci + axe targets).\",\n \"health-endpoint\":\n \"Write src/routes/health/+server.ts (function-health probe for the report gate).\",\n \"smoke-suite\": \"Add the smoke suite (test:smoke + playwright config + /health smoke routes).\",\n \"self-updating\":\n \"Bootstrap Renovate + repo protection (writes renovate configs via PR, wires ruleset, disables platform auto-merge; ci.yml comes from the starter and is deliberately not managed).\",\n \"prismic-ci\":\n \"Add the Prismic model delivery workflow to a site via PR (dry delta comment on PRs, push to Prismic on merge to main).\",\n init: \"Run the full onboarding chain (convert-to-pnpm → onboard → sync-configs → svelte-codemods → a11y-fixtures-page → health-endpoint → smoke-suite → audit).\",\n};\n\n/** Run a command thunk and surface its result, falling back to a clean error\n * message on throw. Wraps the ~10-line try/catch every `.action()` used to\n * duplicate. `verbose` flips between full stack and message-only.\n *\n * On success it sets `process.exitCode` and RETURNS rather than calling\n * `process.exit()` right after `console.log()`. `process.exit()` does not wait\n * for stdout to flush when stdout is a pipe, so a large `--json` payload piped\n * to another process would get truncated mid-write. Setting `exitCode` and\n * returning lets Node drain stdout and exit naturally with the right code. A\n * non-zero `code` still yields a non-zero process exit.\n *\n * The error path keeps `process.exit()` — error messages are small (one line),\n * always go to stderr, and exiting immediately is the desired fail-fast. */\nexport async function runOrExit(\n fn: () => Promise<{ output: string; code: number }>,\n opts: { verbose?: boolean },\n): Promise<void> {\n try {\n const { output, code } = await fn();\n console.log(output);\n process.exitCode = code;\n return;\n } catch (err) {\n const e = err as { exitCode?: number; message?: string; stack?: string };\n console.error(opts.verbose ? (e.stack ?? e.message) : (e.message ?? String(err)));\n process.exit(e.exitCode ?? 1);\n }\n}\n\nconst cli = cac(\"reddoor-maint\");\n\ncli.option(\"--cwd <path>\", \"Override working directory (default: process.cwd())\");\ncli.option(\"--verbose\", \"Verbose output (full stack on errors)\");\n\ncli.command(\"list-audits\", \"Print the available audits.\").action(() => {\n for (const [name, desc] of Object.entries(AUDIT_DESCRIPTIONS)) {\n console.log(`${name.padEnd(12)} ${desc}`);\n }\n});\n\ncli.command(\"list-recipes\", \"Print the available recipes.\").action(() => {\n for (const [name, desc] of Object.entries(RECIPE_DESCRIPTIONS)) {\n console.log(`${name.padEnd(16)} ${desc}`);\n }\n});\n\ncli\n .command(\"audit [site]\", \"Run audits against a site (default: cwd).\")\n .option(\"--only <names>\", \"Comma-separated audit names (e.g. deps,lighthouse)\")\n .option(\"--json\", \"Machine-readable JSON output\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .option(\n \"--write-airtable [slug]\",\n \"After lighthouse runs, write pScore/rScore/bpScore/seoScore + timestamp to the matching Websites row. Slug defaults to cwd's package.json#name.\",\n )\n .option(\"--fail-on-violations\", \"Exit non-zero if any a11y violations are found (for CI gates)\")\n .option(\n \"--url <url>\",\n \"Audit this deployed URL with lighthouse (no dev server); single-site. Pair with --only lighthouse — other audits still use the local checkout.\",\n )\n .option(\n \"--concurrency <n>\",\n \"Max sites to audit in parallel in --fleet mode (default: all at once). Use 1 for sequential (CI).\",\n )\n .action(\n async (\n site,\n opts: {\n only?: string;\n json?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n writeAirtable?: string | boolean;\n failOnViolations?: boolean;\n url?: string;\n concurrency?: string;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/audit.js\")).runAuditCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"sync-configs [site]\", \"Sync canonical configs into a site.\")\n .option(\"--only <names>\", \"Comma-separated config names (e.g. eslint,prettier)\")\n .option(\"--dry\", \"Print diff without writing\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n only?: string;\n dry?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/sync-configs.js\")).runSyncConfigsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"bump-deps [site]\", \"Bump dependencies.\")\n .option(\"--group <group>\", \"patch | minor | major\", { default: \"minor\" })\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n group?: string;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/bump-deps.js\")).runBumpDepsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"self-updating [site]\",\n \"Bootstrap a repo to keep itself updated (Renovate + protection; platform auto-merge off; ci.yml is the starter's, not managed here).\",\n )\n .option(\"--dry\", \"List what would be enabled without writing or opening PRs\")\n .option(\"--fleet <inventory>\", 'Inventory file (.json or .mjs/.js), or \"airtable\"')\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n dry?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/self-updating.js\")).runSelfUpdatingCommand(site, opts),\n opts,\n ),\n );\n\n// Fleet-wide, this opens ONE PULL REQUEST PER REPOSITORY and never pushes to a\n// client's main. `--dry` exists because that is the only way to see the blast\n// radius before firing it. Both directions of the flag ↔ option link are pinned\n// by tests/cli/prismic-ci-command.test.ts.\ncli\n .command(\n \"prismic-ci [site]\",\n \"Add the Prismic model delivery workflow to a site via PR (one PR per repo; never pushes to main).\",\n )\n .option(\"--dry\", \"List the sites that would be offered the workflow, without opening any PR\")\n .option(\"--fleet <inventory>\", 'Inventory file (.json or .mjs/.js), or \"airtable\"')\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n dry?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/prismic-ci.js\")).runPrismicCiCommand(site, opts),\n opts,\n ),\n );\n\n// EVERY flag below must be one the command actually reads, and every option the\n// command reads must appear below. cac rejects an unknown option outright, so a\n// missing line here is a hard error in whatever workflow types the flag; a line\n// here with no handler is the silent no-op — it parses, it lands in `opts`, and\n// nothing ever looks at it. Both directions are pinned by\n// tests/cli/prismic-models-registration.test.ts, the second one at the type level\n// against `PrismicModelsCommandOptions`.\ncli\n .command(\n \"prismic-models [site]\",\n \"Compare a site's Prismic models against its repo (dry by default).\",\n )\n .option(\n \"--apply\",\n \"Push local models to Prismic. Never deletes — remote-only models are reported.\",\n )\n .option(\"--pull\", \"Write remote-only models into the repo (single-site; review + PR the result).\")\n .option(\"--tokens\", \"Print the per-site write-token doctor: which env var, present?, reads?\")\n .option(\"--fleet <inventory>\", 'Inventory file (.json or .mjs/.js), or \"airtable\". Read-only.')\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .option(\"--write-airtable\", \"Fleet mode: persist each site's verdict to its Websites row\")\n .option(\n \"--comment-file <path>\",\n \"Write the report to this file (the CI workflow posts it as a PR comment)\",\n )\n .action(\n async (\n site,\n opts: {\n apply?: boolean;\n pull?: boolean;\n tokens?: boolean;\n fleet?: string;\n workdir?: string;\n writeAirtable?: boolean;\n commentFile?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/prismic-models.js\")).runPrismicModelsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"upgrade <upgrade> [site]\", \"Run a named upgrade recipe (svelte-4-to-5).\")\n .example(\"reddoor-maint upgrade svelte-4-to-5 ./my-site\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n upgrade: string,\n site: string | undefined,\n opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/upgrade.js\")).runUpgradeCommand(upgrade, site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"convert-to-pnpm [site]\",\n \"Convert an npm/yarn site to pnpm (lockfile, packageManager, scripts).\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/convert-to-pnpm.js\")).runConvertToPnpmCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"svelte-codemods [site]\", \"Apply Svelte 5 gotcha codemods to an already-migrated site.\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/svelte-codemods.js\")).runSvelteCodemodsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"health-endpoint [site]\",\n \"Write src/routes/health/+server.ts (function-health probe for the report gate).\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/health-endpoint.js\")).runHealthEndpointCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"smoke-suite [site]\",\n \"Add the smoke suite (test:smoke + playwright config + /health smoke routes).\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () => (await import(\"./commands/smoke-suite.js\")).runSmokeSuiteCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"onboard [site]\",\n \"Install @reddoorla/maintenance + audit deps on a site (run after convert-to-pnpm).\",\n )\n .option(\"--audits <names>\", \"Comma-separated audit subset: lighthouse,a11y (default: both)\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n audits?: string;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/onboard.js\")).runOnboardCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"init [site]\",\n \"One-shot guided onboarding: convert-to-pnpm → onboard → sync-configs → svelte-codemods → a11y-fixtures-page → health-endpoint → smoke-suite → audit.\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(async () => (await import(\"./commands/init.js\")).runInitCommand(site, opts), opts),\n );\n\ncli\n .command(\n \"launch <site>\",\n \"Bootstrap + first-audit a site, then draft its launch email for approval.\",\n )\n .action(async (site: string, opts: { cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () => (await import(\"./commands/launch.js\")).runLaunchCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"header-image [site]\", \"Generate a site's report header image from its live homepage.\")\n .option(\"--all\", \"Every live site with no Header image yet (backfill)\")\n .option(\"--force\", \"With --all, regenerate sites that already have one\")\n .option(\"--write-airtable\", \"Upload to the Websites row instead of writing a local file\")\n .option(\"--out-dir <path>\", \"Directory for local output (default: reports/)\")\n .option(\"--settle-ms <ms>\", \"Override the post-load settle delay for slow/animated homepages\")\n .action(\n async (\n site: string | undefined,\n opts: {\n all?: boolean;\n force?: boolean;\n writeAirtable?: boolean;\n outDir?: string;\n settleMs?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/header-image.js\")).runHeaderImageCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"announce [site]\",\n \"Draft the monthly-report announcement email for maintenance sites (all, or one) for approval.\",\n )\n .action(async (site: string | undefined, opts: { cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () => (await import(\"./commands/announce.js\")).runAnnounceCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"forms-notify-target [site]\",\n \"Show who a form submission would email, and optionally flip the pre-launch guard (read-back confirmed).\",\n )\n .option(\"--set <on|off>\", \"Flip the guard: on = route to operator, off = restore.\")\n .option(\"--restore <status>\", \"Status to restore with --set off. Required; never inferred.\")\n .action(\n async (\n site: string | undefined,\n opts: { set?: string; restore?: string; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/forms-notify-target.js\")).runFormsNotifyTargetCommand(\n site,\n opts,\n ),\n opts,\n ),\n );\n\ncli\n .command(\n \"selftest <kind> [site]\",\n \"Operator self-tests. kind=email: preview a report email for a site (or --all) to yourself.\",\n )\n .option(\"--type <type>\", \"Report type: announcement (default) | maintenance | testing | launch\")\n .option(\"--to <addr>\", \"Recipient(s), comma-separated. Default: OPERATOR_EMAIL.\")\n .option(\"--all\", \"Send a preview for every maintenance site (to --to/operator).\")\n .option(\"--dry-run\", \"Render only; write reports/<slug>/selftest-<type>.html; do not send.\")\n .action(\n async (\n kind: string,\n site: string | undefined,\n opts: {\n type?: string;\n to?: string;\n all?: boolean;\n dryRun?: boolean;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/selftest.js\")).runSelftestCommand(kind, site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"preflight [site]\",\n \"Read-only pre-send checks: recipients, header image, pending drafts, schedule hygiene.\",\n )\n .option(\"--type <type>\", \"Report type: announcement (default) | maintenance | testing\")\n .option(\n \"--all\",\n \"Fleet mode: announcement→maintenance sites; maintenance/testing→all schedulable sites.\",\n )\n .action(\n async (\n site: string | undefined,\n opts: { type?: string; all?: boolean; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/preflight.js\")).runPreflightCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"ensure-site <slug>\", \"Create/verify the Airtable Websites row for a new site.\")\n .option(\"--name <display name>\", \"Human Name for the row (client-facing copy uses it verbatim).\")\n .option(\"--url <url>\", \"Deployed URL (e.g. the Netlify site URL).\")\n .option(\"--contact <email>\", \"point of contact — the client address reports resolve to.\")\n .option(\"--git-repo <owner/repo>\", \"GitHub identity. Default on create: reddoorla/<slug>.\")\n .action(\n async (\n slug: string,\n opts: {\n name?: string;\n url?: string;\n contact?: string;\n gitRepo?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/ensure-site.js\")).runEnsureSiteCommand(slug, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"prospect-audit <url>\",\n \"AEO/SEO audit an external prospect's site and publish the report.\",\n )\n .option(\n \"--business <name>\",\n \"The prospect's business name (defaults to what the model reads off the site).\",\n )\n .option(\n \"--competitors <list>\",\n \"Comma-separated competitor domains to add comparison probes for.\",\n )\n .option(\"--no-probes\", \"Skip the live AI-visibility probes (tier 3).\")\n .option(\"--out <file>\", \"Also write the rendered report to this file.\")\n .option(\"--json\", \"Print the raw result JSON instead of the report summary.\")\n .option(\n \"--email\",\n \"Email the internal sheet (scores, what wasn't measured, top fixes, the link) to PROSPECT_AUDIT_RECIPIENTS.\",\n )\n .action(\n async (\n url: string,\n opts: {\n business?: string;\n competitors?: string;\n probes?: boolean;\n out?: string;\n json?: boolean;\n email?: boolean;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/prospect-audit.js\")).runProspectAuditCommand(url, opts),\n opts,\n ),\n );\n\ncli\n .command(\"report [site]\", \"Draft or send maintenance/testing reports.\")\n .option(\"--due\", \"Scan all Websites and draft overdue reports.\")\n .option(\"--type <type>\", \"Single-site draft report type: Maintenance (default) or Testing.\")\n .option(\n \"--preview\",\n \"Single-site dry run; writes reports/<slug>/draft.html, never touches Airtable.\",\n )\n .option(\n \"--enrich\",\n \"With --preview: also fetch GA + Search Console, so the render exercises those credentials for real. Still writes nothing.\",\n )\n .option(\n \"--send-ready\",\n \"Send all Reports with Draft ready=true AND Approved to send=true AND Sent at IS NULL.\",\n )\n .option(\n \"--digest\",\n \"Email the operator one daily digest of reports ready for approval (skips when empty).\",\n )\n .option(\n \"--rerender <reportId>\",\n \"Regenerate one UNSENT report's stored HTML from its current row, so the console preview shows edited commentary. Refuses a sent report.\",\n )\n .action(\n async (\n site,\n opts: {\n due?: boolean;\n type?: string;\n preview?: boolean;\n enrich?: boolean;\n sendReady?: boolean;\n digest?: boolean;\n rerender?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/report.js\")).runReportCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"github-signals\",\n \"Sweep the fleet for GitHub signals (Renovate-failing/CI/last-commit) and write Airtable.\",\n )\n .option(\"--fleet\", \"Run across every site in the Airtable inventory.\")\n .option(\"--write-airtable\", \"Write each site's signals back to its Websites row.\")\n .action(\n async (opts: { fleet?: boolean; writeAirtable?: boolean; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/github-signals.js\")).runGitHubSignalsCommand({\n fleet: opts.fleet,\n writeAirtable: opts.writeAirtable,\n }),\n opts,\n ),\n );\n\ncli\n .command(\n \"protection-audit\",\n \"Verify every public org repo carries a sound branch ruleset (empty bypass, PR-required).\",\n )\n .option(\"--org <org>\", \"GitHub org to sweep (enumerated from the API, never a hand list).\")\n .action(async (opts: { org?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/protection-audit.js\")).runProtectionAuditCommand({\n org: opts.org,\n }),\n opts,\n ),\n );\n\ncli\n .command(\n \"db <action>\",\n \"Operate the libSQL store (migrate | replay-deadletters | import-airtable | parity | sync | backfill-header-images | backfill-digest-state | dump | verify-dump | restore).\",\n )\n .option(\"--file <path>\", \"verify-dump: the dump file to load into a scratch engine\")\n .action(async (action: string, opts: { file?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(async () => (await import(\"./commands/db.js\")).runDbCommand(action, opts), opts),\n );\n\ncli\n .command(\n \"submissions <action>\",\n \"Operate on stored form submissions. rescore: re-run the CURRENT spam classifier over the status='new' backlog (dry-run by default; only 'new' rows are ever touched).\",\n )\n .option(\"--dry-run\", \"Print the would-be re-buckets without writing (the default).\")\n .option(\n \"--apply\",\n \"Write the re-buckets: status → spam_auto, spam_score/spam_reason replaced with the new verdict + 'retro-rescore' marker.\",\n )\n .action(\n async (\n action: string,\n opts: { dryRun?: boolean; apply?: boolean; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/submissions.js\")).runSubmissionsCommand(action, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"renovate-dispatch\",\n \"Trigger Renovate on fleet sites the security sweep flagged with critical/high vulns.\",\n )\n .option(\"--fleet\", \"Run across every active, repo-backed site in the Airtable inventory.\")\n .action(async (opts: { fleet?: boolean; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/renovate-dispatch.js\")).runRenovateDispatchCommand({\n fleet: opts.fleet,\n // #539 Phase 5: mirror the auto-fix counter into site_health.\n siteMirror: await (await import(\"../db/site-mirror.js\")).makeSiteMirror(),\n }),\n opts,\n ),\n );\n\ncli\n .command(\n \"blux <action> [dir]\",\n \"Blux conversion pipeline. emit: export dir → migration plan + custom types + theme + review manifest. migrate: emitted plan → live Prismic (needs PRISMIC_REPOSITORY_NAME + PRISMIC_WRITE_TOKEN). validate: content coverage of a rendered site against the export answer key. grid: parse rendered index.html → grid-tree.json (layout tree). convert: parse+classify index.html + assemble IR → migration-plan.json + blux-presentation.json + theme.css (+ map-config.json), offline. catalog: parse each page + classify every band to a blux_section → migration-plan.json only (no sidecar), offline.\",\n )\n .option(\n \"--out <dir>\",\n \"Output directory for emit/grid/convert/catalog (default: <exportDir>/blux-out)\",\n )\n .option(\"--converted-base <url>\", \"Converted-site base URL for the review manifest\")\n .option(\"--blux-base <url>\", \"Original Blux site base URL (default: https://<site.json domain>)\")\n .option(\n \"--probe\",\n \"Reconstruct + HEAD-probe CDN URLs for used assets the HTML scrape missed (network)\",\n )\n .option(\n \"--against <target>\",\n \"validate: rendered HTML of the converted site — a file path or http(s) URL\",\n )\n .option(\n \"--site <slug>\",\n \"freeze/migrate-frozen: site slug naming <slug>.slots.json (default: slugified dir name)\",\n )\n .option(\n \"--extra-slots <path>\",\n \"freeze: JSON declaring slots the template has no token for (video poster, a panel rebuilt from a baked image). Keys must start with 'x.'\",\n )\n .action(\n async (\n action: string,\n dir: string | undefined,\n opts: {\n out?: string;\n convertedBase?: string;\n bluxBase?: string;\n probe?: boolean;\n against?: string;\n site?: string;\n extraSlots?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/blux.js\")).runBluxCommand(action, dir, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"webflow <action> [target]\",\n \"Webflow import pipeline. capture: live-crawl a base url → <out>/ir.json, progress on stderr. docs: convert a saved ir.json → docs.json + assets.json (offline). migrate: push a capture dir's docs.json + assets.json to Prismic via the shared runner (needs PRISMIC_REPOSITORY_NAME + PRISMIC_WRITE_TOKEN).\",\n )\n .option(\n \"--out <dir>\",\n \"Output directory for capture (default: webflow-out) / docs (default: dirname of the ir.json)\",\n )\n .action(\n async (\n action: string,\n target: string | undefined,\n opts: { out?: string; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/webflow.js\")).runWebflowCommand(action, target, opts),\n opts,\n ),\n );\n\ncli.help();\ncli.version(version);\n\n// A typo'd / unrecognized subcommand (e.g. `reddoor-maint auditt`) otherwise\n// falls through cac with no matched command and exits 0 — a cron/CI typo would\n// \"succeed\" silently. cac emits `command:*` at the end of parse() exactly when\n// a positional arg was given but matched no command (a bare `reddoor-maint`,\n// `--help`, and `--version` do NOT trigger it: they have no leading positional\n// or are handled before this fires). Turn that into a clear stderr error +\n// non-zero exit. process.argv[2] is the first positional, i.e. the bad command.\ncli.on(\"command:*\", () => {\n const unknown = cli.args[0] ?? process.argv[2] ?? \"\";\n console.error(\n `error: unknown command '${unknown}'. Run 'reddoor-maint --help' to see available commands.`,\n );\n process.exit(1);\n});\n\ncli.parse();\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * Read the @reddoorla/maintenance package version, given the directory of a\n * file that lives inside the package. Walks UP looking for the first\n * `package.json` whose `name` matches. Defensive against bundling-layout\n * changes — the older \"two levels up\" assumption held for `dist/cli/bin.js`\n * but would silently mis-read (or return \"unknown\") if tsup ever moved bin\n * to a different depth. Same walk-up pattern as the self-version helper.\n *\n * Returns \"unknown\" when no matching package.json is reachable (Yarn PnP\n * setups stash manifests inside .zip caches; the readFileSync there fails\n * before any name check).\n */\nexport function resolvePackageVersion(fromDir: string): string {\n try {\n let dir = fromDir;\n while (true) {\n const candidate = join(dir, \"package.json\");\n if (existsSync(candidate)) {\n const raw = readFileSync(candidate, \"utf-8\");\n const pkg = JSON.parse(raw) as { name?: string; version?: string };\n if (pkg.name === \"@reddoorla/maintenance\") {\n return pkg.version ?? \"unknown\";\n }\n }\n const parent = dirname(dir);\n if (parent === dir) return \"unknown\";\n dir = parent;\n }\n } catch {\n return \"unknown\";\n }\n}\n"],"mappings":";;;;;;AACA,SAAS,WAAAA,gBAAe;AACxB,SAAS,qBAAqB;AAC9B,SAAS,WAAW;;;ACHpB,SAAS,cAAc,kBAAkB;AACzC,SAAS,SAAS,YAAY;AAcvB,SAAS,sBAAsB,SAAyB;AAC7D,MAAI;AACF,QAAI,MAAM;AACV,WAAO,MAAM;AACX,YAAM,YAAY,KAAK,KAAK,cAAc;AAC1C,UAAI,WAAW,SAAS,GAAG;AACzB,cAAM,MAAM,aAAa,WAAW,OAAO;AAC3C,cAAM,MAAM,KAAK,MAAM,GAAG;AAC1B,YAAI,IAAI,SAAS,0BAA0B;AACzC,iBAAO,IAAI,WAAW;AAAA,QACxB;AAAA,MACF;AACA,YAAM,SAAS,QAAQ,GAAG;AAC1B,UAAI,WAAW,IAAK,QAAO;AAC3B,YAAM;AAAA,IACR;AAAA,EACF,QAAQ;AACN,WA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a,MAAM,OAAO,qBAAoB,GAAG,eAAe,QAAQ,KAAK,IAAI;AAAA,IACjF;AAAA,EACF;AACJ;AAEF,IACG;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC,OACE,QACA,QACA,SAEA;AAAA,IACE,aAAa,MAAM,OAAO,wBAAuB,GAAG,kBAAkB,QAAQ,QAAQ,IAAI;AAAA,IAC1F;AAAA,EACF;AACJ;AAEF,IAAI,KAAK;AACT,IAAI,QAAQ,OAAO;AASnB,IAAI,GAAG,aAAa,MAAM;AACxB,QAAM,UAAU,IAAI,KAAK,CAAC,KAAK,QAAQ,KAAK,CAAC,KAAK;AAClD,UAAQ;AAAA,IACN,2BAA2B,OAAO;AAAA,EACpC;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,IAAI,MAAM;","names":["dirname","dirname"]}
1
+ {"version":3,"sources":["../../src/cli/bin.ts","../../src/cli/version.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { cac } from \"cac\";\nimport type { AuditName, RecipeName } from \"../types.js\";\nimport { loadCredentialsIntoEnv } from \"../util/credentials.js\";\nimport { resolvePackageVersion } from \"./version.js\";\n\n// Command modules are loaded LAZILY (dynamic `import()` inside each `.action()`),\n// never eagerly at the top. An eager `import { runReportCommand } from\n// \"./commands/report.js\"` would pull EVERY command's transitive dependency chain\n// into the CLI's startup graph — report/announce/launch drag in mjml + resend +\n// @google-analytics/data, `db` drags in the libSQL/kysely stack, etc. Those heavy\n// packages are `devDependencies` (this repo's CLI/functions/audits use them); a\n// consuming fleet site installs @reddoorla/maintenance only for `./forms` +\n// `./configs/*` and runs just `reddoor-maint audit --only a11y` in CI. Lazy\n// loading keeps that path (and `--help`/`--version`) free of the report/db\n// chains, so those packages never land in a consumer's node_modules. The\n// smoke-dist gate asserts bin.js's STATIC import closure stays free of them.\n\n// Load credentials from ~/.config/reddoor-maint/credentials.env before any\n// command runs, so AIRTABLE_PAT/AIRTABLE_BASE_ID/RESEND_API_KEY/etc. are\n// available from any cwd. Shell-exported env vars still win. Silent on\n// missing file — commands that need the credentials will fail with their\n// own clear error.\nloadCredentialsIntoEnv();\n\nconst here = dirname(fileURLToPath(import.meta.url));\nconst version = resolvePackageVersion(here);\n\nconst AUDIT_DESCRIPTIONS: Record<AuditName, string> = {\n deps: \"Diff site package.json against the bundled baseline version map.\",\n lighthouse: \"Run @lhci/cli autorun using the canonical lighthouserc.\",\n a11y: \"Playwright + axe against the canonical a11y routes.\",\n security:\n \"GitHub Dependabot alerts (prod+dev) for repo-backed sites; falls back to pnpm/npm audit (prod-deps) with no repo/token.\",\n lint: \"ESLint + Prettier using the canonical configs.\",\n domain: \"DNS resolve + TLS cert expiry against the deployed URL (checkout-free).\",\n browser:\n \"Playwright across desktop engines + mobile devices + link-check against the deployed URL (checkout-free).\",\n \"netlify-deploy\":\n \"Latest production deploy health via the Netlify API by site id (checkout-free; needs NETLIFY_PAT).\",\n \"function-health\":\n \"GET {deployedUrl}/health and read its ok/prismic/forms status (checkout-free).\",\n smoke: \"Run the site's own `pnpm test:smoke` suite in its checkout (clone-based).\",\n \"form-e2e\":\n \"Submit the real production contact form in test-mode against the deployed URL (checkout-free).\",\n};\n\nconst RECIPE_DESCRIPTIONS: Record<RecipeName, string> = {\n \"sync-configs\": \"Overwrite a site's canonical configs to match @reddoorla/maintenance.\",\n \"bump-deps\": \"Bump dependencies and commit the lockfile change.\",\n \"svelte-4-to-5\": \"Run the 7-commit Svelte 4 → 5 upgrade recipe.\",\n \"svelte-codemods\":\n \"Apply Svelte 5 gotcha codemods to an already-migrated site (state_referenced_locally, etc.).\",\n \"convert-to-pnpm\": \"Convert an npm/yarn site to pnpm (lockfile, packageManager, scripts).\",\n onboard: \"Install @reddoorla/maintenance + audit deps on a site (preferred first step).\",\n \"a11y-fixtures-page\":\n \"Write src/routes/dev/a11y-fixtures/+page.svelte (stub for lhci + axe targets).\",\n \"health-endpoint\":\n \"Write src/routes/health/+server.ts (function-health probe for the report gate).\",\n \"smoke-suite\": \"Add the smoke suite (test:smoke + playwright config + /health smoke routes).\",\n \"self-updating\":\n \"Bootstrap Renovate + repo protection (writes renovate configs via PR, wires ruleset, disables platform auto-merge; ci.yml comes from the starter and is deliberately not managed).\",\n \"prismic-ci\":\n \"Add the Prismic model delivery workflow to a site via PR (dry delta comment on PRs, push to Prismic on merge to main).\",\n init: \"Run the full onboarding chain (convert-to-pnpm → onboard → sync-configs → svelte-codemods → a11y-fixtures-page → health-endpoint → smoke-suite → audit).\",\n};\n\n/** Run a command thunk and surface its result, falling back to a clean error\n * message on throw. Wraps the ~10-line try/catch every `.action()` used to\n * duplicate. `verbose` flips between full stack and message-only.\n *\n * On success it sets `process.exitCode` and RETURNS rather than calling\n * `process.exit()` right after `console.log()`. `process.exit()` does not wait\n * for stdout to flush when stdout is a pipe, so a large `--json` payload piped\n * to another process would get truncated mid-write. Setting `exitCode` and\n * returning lets Node drain stdout and exit naturally with the right code. A\n * non-zero `code` still yields a non-zero process exit.\n *\n * The error path keeps `process.exit()` — error messages are small (one line),\n * always go to stderr, and exiting immediately is the desired fail-fast. */\nexport async function runOrExit(\n fn: () => Promise<{ output: string; code: number }>,\n opts: { verbose?: boolean },\n): Promise<void> {\n try {\n const { output, code } = await fn();\n console.log(output);\n process.exitCode = code;\n return;\n } catch (err) {\n const e = err as { exitCode?: number; message?: string; stack?: string };\n console.error(opts.verbose ? (e.stack ?? e.message) : (e.message ?? String(err)));\n process.exit(e.exitCode ?? 1);\n }\n}\n\nconst cli = cac(\"reddoor-maint\");\n\ncli.option(\"--cwd <path>\", \"Override working directory (default: process.cwd())\");\ncli.option(\"--verbose\", \"Verbose output (full stack on errors)\");\n\ncli.command(\"list-audits\", \"Print the available audits.\").action(() => {\n for (const [name, desc] of Object.entries(AUDIT_DESCRIPTIONS)) {\n console.log(`${name.padEnd(12)} ${desc}`);\n }\n});\n\ncli.command(\"list-recipes\", \"Print the available recipes.\").action(() => {\n for (const [name, desc] of Object.entries(RECIPE_DESCRIPTIONS)) {\n console.log(`${name.padEnd(16)} ${desc}`);\n }\n});\n\ncli\n .command(\"audit [site]\", \"Run audits against a site (default: cwd).\")\n .option(\"--only <names>\", \"Comma-separated audit names (e.g. deps,lighthouse)\")\n .option(\"--json\", \"Machine-readable JSON output\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .option(\n \"--write-airtable [slug]\",\n \"After lighthouse runs, write pScore/rScore/bpScore/seoScore + timestamp to the matching Websites row. Slug defaults to cwd's package.json#name.\",\n )\n .option(\"--fail-on-violations\", \"Exit non-zero if any a11y violations are found (for CI gates)\")\n .option(\n \"--url <url>\",\n \"Audit this deployed URL with lighthouse (no dev server); single-site. Pair with --only lighthouse — other audits still use the local checkout.\",\n )\n .option(\n \"--concurrency <n>\",\n \"Max sites to audit in parallel in --fleet mode (default: all at once). Use 1 for sequential (CI).\",\n )\n .action(\n async (\n site,\n opts: {\n only?: string;\n json?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n writeAirtable?: string | boolean;\n failOnViolations?: boolean;\n url?: string;\n concurrency?: string;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/audit.js\")).runAuditCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"sync-configs [site]\", \"Sync canonical configs into a site.\")\n .option(\"--only <names>\", \"Comma-separated config names (e.g. eslint,prettier)\")\n .option(\"--dry\", \"Print diff without writing\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n only?: string;\n dry?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/sync-configs.js\")).runSyncConfigsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"bump-deps [site]\", \"Bump dependencies.\")\n .option(\"--group <group>\", \"patch | minor | major\", { default: \"minor\" })\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n group?: string;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/bump-deps.js\")).runBumpDepsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"self-updating [site]\",\n \"Bootstrap a repo to keep itself updated (Renovate + protection; platform auto-merge off; ci.yml is the starter's, not managed here).\",\n )\n .option(\"--dry\", \"List what would be enabled without writing or opening PRs\")\n .option(\"--fleet <inventory>\", 'Inventory file (.json or .mjs/.js), or \"airtable\"')\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n dry?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/self-updating.js\")).runSelfUpdatingCommand(site, opts),\n opts,\n ),\n );\n\n// Fleet-wide, this opens ONE PULL REQUEST PER REPOSITORY and never pushes to a\n// client's main. `--dry` exists because that is the only way to see the blast\n// radius before firing it. Both directions of the flag ↔ option link are pinned\n// by tests/cli/prismic-ci-command.test.ts.\ncli\n .command(\n \"prismic-ci [site]\",\n \"Add the Prismic model delivery workflow to a site via PR (one PR per repo; never pushes to main).\",\n )\n .option(\"--dry\", \"List the sites that would be offered the workflow, without opening any PR\")\n .option(\"--fleet <inventory>\", 'Inventory file (.json or .mjs/.js), or \"airtable\"')\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n dry?: boolean;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/prismic-ci.js\")).runPrismicCiCommand(site, opts),\n opts,\n ),\n );\n\n// EVERY flag below must be one the command actually reads, and every option the\n// command reads must appear below. cac rejects an unknown option outright, so a\n// missing line here is a hard error in whatever workflow types the flag; a line\n// here with no handler is the silent no-op — it parses, it lands in `opts`, and\n// nothing ever looks at it. Both directions are pinned by\n// tests/cli/prismic-models-registration.test.ts, the second one at the type level\n// against `PrismicModelsCommandOptions`.\ncli\n .command(\n \"prismic-models [site]\",\n \"Compare a site's Prismic models against its repo (dry by default).\",\n )\n .option(\n \"--apply\",\n \"Push local models to Prismic. Never deletes — remote-only models are reported.\",\n )\n .option(\"--pull\", \"Write remote-only models into the repo (single-site; review + PR the result).\")\n .option(\"--tokens\", \"Print the per-site write-token doctor: which env var, present?, reads?\")\n .option(\"--fleet <inventory>\", 'Inventory file (.json or .mjs/.js), or \"airtable\". Read-only.')\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .option(\"--write-airtable\", \"Fleet mode: persist each site's verdict to its Websites row\")\n .option(\n \"--comment-file <path>\",\n \"Write the report to this file (the CI workflow posts it as a PR comment)\",\n )\n .action(\n async (\n site,\n opts: {\n apply?: boolean;\n pull?: boolean;\n tokens?: boolean;\n fleet?: string;\n workdir?: string;\n writeAirtable?: boolean;\n commentFile?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/prismic-models.js\")).runPrismicModelsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"upgrade <upgrade> [site]\", \"Run a named upgrade recipe (svelte-4-to-5).\")\n .example(\"reddoor-maint upgrade svelte-4-to-5 ./my-site\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n upgrade: string,\n site: string | undefined,\n opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/upgrade.js\")).runUpgradeCommand(upgrade, site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"convert-to-pnpm [site]\",\n \"Convert an npm/yarn site to pnpm (lockfile, packageManager, scripts).\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/convert-to-pnpm.js\")).runConvertToPnpmCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"svelte-codemods [site]\", \"Apply Svelte 5 gotcha codemods to an already-migrated site.\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/svelte-codemods.js\")).runSvelteCodemodsCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"health-endpoint [site]\",\n \"Write src/routes/health/+server.ts (function-health probe for the report gate).\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/health-endpoint.js\")).runHealthEndpointCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"smoke-suite [site]\",\n \"Add the smoke suite (test:smoke + playwright config + /health smoke routes).\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () => (await import(\"./commands/smoke-suite.js\")).runSmokeSuiteCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"onboard [site]\",\n \"Install @reddoorla/maintenance + audit deps on a site (run after convert-to-pnpm).\",\n )\n .option(\"--audits <names>\", \"Comma-separated audit subset: lighthouse,a11y (default: both)\")\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (\n site,\n opts: {\n audits?: string;\n fleet?: string;\n workdir?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/onboard.js\")).runOnboardCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"init [site]\",\n \"One-shot guided onboarding: convert-to-pnpm → onboard → sync-configs → svelte-codemods → a11y-fixtures-page → health-endpoint → smoke-suite → audit.\",\n )\n .option(\n \"--fleet <inventory>\",\n 'Inventory file (.json or .mjs/.js), or \"airtable\" to read from Websites table',\n )\n .option(\"--workdir <path>\", \"Clone target for fleet mode (default ~/.reddoor-maint/sites)\")\n .action(\n async (site, opts: { fleet?: string; workdir?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(async () => (await import(\"./commands/init.js\")).runInitCommand(site, opts), opts),\n );\n\ncli\n .command(\n \"launch <site>\",\n \"Bootstrap + first-audit a site, then draft its launch email for approval.\",\n )\n .action(async (site: string, opts: { cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () => (await import(\"./commands/launch.js\")).runLaunchCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"header-image [site]\", \"Generate a site's report header image from its live homepage.\")\n .option(\"--all\", \"Every live site with no Header image yet (backfill)\")\n .option(\"--force\", \"With --all, regenerate sites that already have one\")\n .option(\"--write-airtable\", \"Upload to the Websites row instead of writing a local file\")\n .option(\"--out-dir <path>\", \"Directory for local output (default: reports/)\")\n .option(\"--settle-ms <ms>\", \"Override the post-load settle delay for slow/animated homepages\")\n .action(\n async (\n site: string | undefined,\n opts: {\n all?: boolean;\n force?: boolean;\n writeAirtable?: boolean;\n outDir?: string;\n settleMs?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/header-image.js\")).runHeaderImageCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"announce [site]\",\n \"Draft the monthly-report announcement email for maintenance sites (all, or one) for approval.\",\n )\n .action(async (site: string | undefined, opts: { cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () => (await import(\"./commands/announce.js\")).runAnnounceCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"forms-notify-target [site]\",\n \"Show who a form submission would email, and optionally flip the pre-launch guard (read-back confirmed).\",\n )\n .option(\"--set <on|off>\", \"Flip the guard: on = route to operator, off = restore.\")\n .option(\"--restore <status>\", \"Status to restore with --set off. Required; never inferred.\")\n .action(\n async (\n site: string | undefined,\n opts: { set?: string; restore?: string; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/forms-notify-target.js\")).runFormsNotifyTargetCommand(\n site,\n opts,\n ),\n opts,\n ),\n );\n\ncli\n .command(\n \"selftest <kind> [site]\",\n \"Operator self-tests. kind=email: preview a report email for a site (or --all) to yourself.\",\n )\n .option(\"--type <type>\", \"Report type: announcement (default) | maintenance | testing | launch\")\n .option(\"--to <addr>\", \"Recipient(s), comma-separated. Default: OPERATOR_EMAIL.\")\n .option(\"--all\", \"Send a preview for every maintenance site (to --to/operator).\")\n .option(\"--dry-run\", \"Render only; write reports/<slug>/selftest-<type>.html; do not send.\")\n .action(\n async (\n kind: string,\n site: string | undefined,\n opts: {\n type?: string;\n to?: string;\n all?: boolean;\n dryRun?: boolean;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/selftest.js\")).runSelftestCommand(kind, site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"preflight [site]\",\n \"Read-only pre-send checks: recipients, header image, pending drafts, schedule hygiene.\",\n )\n .option(\"--type <type>\", \"Report type: announcement (default) | maintenance | testing\")\n .option(\n \"--all\",\n \"Fleet mode: announcement→maintenance sites; maintenance/testing→all schedulable sites.\",\n )\n .action(\n async (\n site: string | undefined,\n opts: { type?: string; all?: boolean; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/preflight.js\")).runPreflightCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\"ensure-site <slug>\", \"Create/verify the Airtable Websites row for a new site.\")\n .option(\"--name <display name>\", \"Human Name for the row (client-facing copy uses it verbatim).\")\n .option(\"--url <url>\", \"Deployed URL (e.g. the Netlify site URL).\")\n .option(\"--contact <email>\", \"point of contact — the client address reports resolve to.\")\n .option(\"--git-repo <owner/repo>\", \"GitHub identity. Default on create: reddoorla/<slug>.\")\n .action(\n async (\n slug: string,\n opts: {\n name?: string;\n url?: string;\n contact?: string;\n gitRepo?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/ensure-site.js\")).runEnsureSiteCommand(slug, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"prospect-audit <url>\",\n \"AEO/SEO audit an external prospect's site and publish the report.\",\n )\n .option(\n \"--business <name>\",\n \"The prospect's business name (defaults to what the model reads off the site).\",\n )\n .option(\n \"--competitors <list>\",\n \"Comma-separated competitor domains to add comparison probes for.\",\n )\n .option(\"--no-probes\", \"Skip the live AI-visibility probes (tier 3).\")\n .option(\"--out <file>\", \"Also write the rendered report to this file.\")\n .option(\"--json\", \"Print the raw result JSON instead of the report summary.\")\n .option(\n \"--email\",\n \"Email the internal sheet (scores, what wasn't measured, top fixes, the link) to PROSPECT_AUDIT_RECIPIENTS.\",\n )\n .action(\n async (\n url: string,\n opts: {\n business?: string;\n competitors?: string;\n probes?: boolean;\n out?: string;\n json?: boolean;\n email?: boolean;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () =>\n (await import(\"./commands/prospect-audit.js\")).runProspectAuditCommand(url, opts),\n opts,\n ),\n );\n\ncli\n .command(\"report [site]\", \"Draft or send maintenance/testing reports.\")\n .option(\"--due\", \"Scan all Websites and draft overdue reports.\")\n .option(\"--type <type>\", \"Single-site draft report type: Maintenance (default) or Testing.\")\n .option(\n \"--preview\",\n \"Single-site dry run; writes reports/<slug>/draft.html, never touches Airtable.\",\n )\n .option(\n \"--enrich\",\n \"With --preview: also fetch GA + Search Console, so the render exercises those credentials for real. Still writes nothing.\",\n )\n .option(\n \"--send-ready\",\n \"Send all Reports with Draft ready=true AND Approved to send=true AND Sent at IS NULL.\",\n )\n .option(\n \"--digest\",\n \"Email the operator one daily digest of reports ready for approval (skips when empty).\",\n )\n .option(\n \"--rerender <reportId>\",\n \"Regenerate one UNSENT report's stored HTML from its current row, so the console preview shows edited commentary. Refuses a sent report.\",\n )\n .action(\n async (\n site,\n opts: {\n due?: boolean;\n type?: string;\n preview?: boolean;\n enrich?: boolean;\n sendReady?: boolean;\n digest?: boolean;\n rerender?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/report.js\")).runReportCommand(site, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"github-signals\",\n \"Sweep the fleet for GitHub signals (Renovate-failing/CI/last-commit) and write Airtable.\",\n )\n .option(\"--fleet\", \"Run across every site in the Airtable inventory.\")\n .option(\"--write-airtable\", \"Write each site's signals back to its Websites row.\")\n .action(\n async (opts: { fleet?: boolean; writeAirtable?: boolean; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/github-signals.js\")).runGitHubSignalsCommand({\n fleet: opts.fleet,\n writeAirtable: opts.writeAirtable,\n }),\n opts,\n ),\n );\n\ncli\n .command(\n \"protection-audit\",\n \"Verify every public org repo carries a sound branch ruleset (empty bypass, PR-required).\",\n )\n .option(\"--org <org>\", \"GitHub org to sweep (enumerated from the API, never a hand list).\")\n .action(async (opts: { org?: string; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/protection-audit.js\")).runProtectionAuditCommand({\n org: opts.org,\n }),\n opts,\n ),\n );\n\ncli\n .command(\n \"db <action>\",\n \"Operate the libSQL store (migrate | replay-deadletters | import-airtable | parity | sync | backfill-header-images | backfill-digest-state | dump | verify-dump | restore | usage).\",\n )\n .option(\"--file <path>\", \"verify-dump / restore: the dump file to load\")\n .option(\n \"--org <slug>\",\n \"usage: Turso org slug (default: TURSO_ORG, else discovered from the token). The token itself comes from TURSO_FLEET_USAGE — never a flag, since argv is readable from ps.\",\n )\n .option(\n \"--url <url>\",\n \"restore: the TARGET database to load into. Required, never defaulted — a restore \" +\n \"that could fall back to the ambient TURSO_DATABASE_URL is one keystroke from \" +\n \"overwriting production.\",\n )\n .option(\n \"--force\",\n \"import-airtable / sync: run despite the freeze (#643) — a deliberate rollback-window \" +\n \"converge from the frozen Airtable shadow. Without it both refuse while Turso is \" +\n \"authoritative, because an import overwrites authoritative rows.\",\n )\n .action(\n async (\n action: string,\n opts: {\n file?: string;\n url?: string;\n org?: string;\n force?: boolean;\n cwd?: string;\n verbose?: boolean;\n },\n ) => runOrExit(async () => (await import(\"./commands/db.js\")).runDbCommand(action, opts), opts),\n );\n\ncli\n .command(\n \"submissions <action>\",\n \"Operate on stored form submissions. rescore: re-run the CURRENT spam classifier over the status='new' backlog (dry-run by default; only 'new' rows are ever touched).\",\n )\n .option(\"--dry-run\", \"Print the would-be re-buckets without writing (the default).\")\n .option(\n \"--apply\",\n \"Write the re-buckets: status → spam_auto, spam_score/spam_reason replaced with the new verdict + 'retro-rescore' marker.\",\n )\n .action(\n async (\n action: string,\n opts: { dryRun?: boolean; apply?: boolean; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/submissions.js\")).runSubmissionsCommand(action, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"renovate-dispatch\",\n \"Trigger Renovate on fleet sites the security sweep flagged with critical/high vulns.\",\n )\n .option(\"--fleet\", \"Run across every active, repo-backed site in the Airtable inventory.\")\n .action(async (opts: { fleet?: boolean; cwd?: string; verbose?: boolean }) =>\n runOrExit(\n async () =>\n (await import(\"./commands/renovate-dispatch.js\")).runRenovateDispatchCommand({\n fleet: opts.fleet,\n // #539 Phase 5: mirror the auto-fix counter into site_health.\n siteMirror: await (await import(\"../db/site-mirror.js\")).makeSiteMirror(),\n }),\n opts,\n ),\n );\n\ncli\n .command(\n \"blux <action> [dir]\",\n \"Blux conversion pipeline. emit: export dir → migration plan + custom types + theme + review manifest. migrate: emitted plan → live Prismic (needs PRISMIC_REPOSITORY_NAME + PRISMIC_WRITE_TOKEN). validate: content coverage of a rendered site against the export answer key. grid: parse rendered index.html → grid-tree.json (layout tree). convert: parse+classify index.html + assemble IR → migration-plan.json + blux-presentation.json + theme.css (+ map-config.json), offline. catalog: parse each page + classify every band to a blux_section → migration-plan.json only (no sidecar), offline.\",\n )\n .option(\n \"--out <dir>\",\n \"Output directory for emit/grid/convert/catalog (default: <exportDir>/blux-out)\",\n )\n .option(\"--converted-base <url>\", \"Converted-site base URL for the review manifest\")\n .option(\"--blux-base <url>\", \"Original Blux site base URL (default: https://<site.json domain>)\")\n .option(\n \"--probe\",\n \"Reconstruct + HEAD-probe CDN URLs for used assets the HTML scrape missed (network)\",\n )\n .option(\n \"--against <target>\",\n \"validate: rendered HTML of the converted site — a file path or http(s) URL\",\n )\n .option(\n \"--site <slug>\",\n \"freeze/migrate-frozen: site slug naming <slug>.slots.json (default: slugified dir name)\",\n )\n .option(\n \"--extra-slots <path>\",\n \"freeze: JSON declaring slots the template has no token for (video poster, a panel rebuilt from a baked image). Keys must start with 'x.'\",\n )\n .action(\n async (\n action: string,\n dir: string | undefined,\n opts: {\n out?: string;\n convertedBase?: string;\n bluxBase?: string;\n probe?: boolean;\n against?: string;\n site?: string;\n extraSlots?: string;\n cwd?: string;\n verbose?: boolean;\n },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/blux.js\")).runBluxCommand(action, dir, opts),\n opts,\n ),\n );\n\ncli\n .command(\n \"webflow <action> [target]\",\n \"Webflow import pipeline. capture: live-crawl a base url → <out>/ir.json, progress on stderr. docs: convert a saved ir.json → docs.json + assets.json (offline). migrate: push a capture dir's docs.json + assets.json to Prismic via the shared runner (needs PRISMIC_REPOSITORY_NAME + PRISMIC_WRITE_TOKEN).\",\n )\n .option(\n \"--out <dir>\",\n \"Output directory for capture (default: webflow-out) / docs (default: dirname of the ir.json)\",\n )\n .action(\n async (\n action: string,\n target: string | undefined,\n opts: { out?: string; cwd?: string; verbose?: boolean },\n ) =>\n runOrExit(\n async () => (await import(\"./commands/webflow.js\")).runWebflowCommand(action, target, opts),\n opts,\n ),\n );\n\ncli.help();\ncli.version(version);\n\n// A typo'd / unrecognized subcommand (e.g. `reddoor-maint auditt`) otherwise\n// falls through cac with no matched command and exits 0 — a cron/CI typo would\n// \"succeed\" silently. cac emits `command:*` at the end of parse() exactly when\n// a positional arg was given but matched no command (a bare `reddoor-maint`,\n// `--help`, and `--version` do NOT trigger it: they have no leading positional\n// or are handled before this fires). Turn that into a clear stderr error +\n// non-zero exit. process.argv[2] is the first positional, i.e. the bad command.\ncli.on(\"command:*\", () => {\n const unknown = cli.args[0] ?? process.argv[2] ?? \"\";\n console.error(\n `error: unknown command '${unknown}'. Run 'reddoor-maint --help' to see available commands.`,\n );\n process.exit(1);\n});\n\ncli.parse();\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * Read the @reddoorla/maintenance package version, given the directory of a\n * file that lives inside the package. Walks UP looking for the first\n * `package.json` whose `name` matches. Defensive against bundling-layout\n * changes — the older \"two levels up\" assumption held for `dist/cli/bin.js`\n * but would silently mis-read (or return \"unknown\") if tsup ever moved bin\n * to a different depth. Same walk-up pattern as the self-version helper.\n *\n * Returns \"unknown\" when no matching package.json is reachable (Yarn PnP\n * setups stash manifests inside .zip caches; the readFileSync there fails\n * before any name check).\n */\nexport function resolvePackageVersion(fromDir: string): string {\n try {\n let dir = fromDir;\n while (true) {\n const candidate = join(dir, \"package.json\");\n if (existsSync(candidate)) {\n const raw = readFileSync(candidate, \"utf-8\");\n const pkg = JSON.parse(raw) as { name?: string; version?: string };\n if (pkg.name === \"@reddoorla/maintenance\") {\n return pkg.version ?? \"unknown\";\n }\n }\n const parent = dirname(dir);\n if (parent === dir) return \"unknown\";\n dir = parent;\n }\n } catch {\n return \"unknown\";\n }\n}\n"],"mappings":";;;;;;AACA,SAAS,WAAAA,gBAAe;AACxB,SAAS,qBAAqB;AAC9B,SAAS,WAAW;;;ACHpB,SAAS,cAAc,kBAAkB;AACzC,SAAS,SAAS,YAAY;AAcvB,SAAS,sBAAsB,SAAyB;AAC7D,MAAI;AACF,QAAI,MAAM;AACV,WAAO,MAAM;AACX,YAAM,YAAY,KAAK,KAAK,cAAc;AAC1C,UAAI,WAAW,SAAS,GAAG;AACzB,cAAM,MAAM,aAAa,WAAW,OAAO;AAC3C,cAAM,MAAM,KAAK,MAAM,GAAG;AAC1B,YAAI,IAAI,SAAS,0BAA0B;AACzC,iBAAO,IAAI,WAAW;AAAA,QACxB;AAAA,MACF;AACA,YAAM,SAAS,QAAQ,GAAG;AAC1B,UAAI,WAAW,IAAK,QAAO;AAC3B,YAAM;AAAA,IACR;AAAA,EACF,QAAQ;AACN,WAA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;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC,OACE,QACA,KACA,SAYA;AAAA,IACE,aAAa,MAAM,OAAO,qBAAoB,GAAG,eAAe,QAAQ,KAAK,IAAI;AAAA,IACjF;AAAA,EACF;AACJ;AAEF,IACG;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC,OACE,QACA,QACA,SAEA;AAAA,IACE,aAAa,MAAM,OAAO,wBAAuB,GAAG,kBAAkB,QAAQ,QAAQ,IAAI;AAAA,IAC1F;AAAA,EACF;AACJ;AAEF,IAAI,KAAK;AACT,IAAI,QAAQ,OAAO;AASnB,IAAI,GAAG,aAAa,MAAM;AACxB,QAAM,UAAU,IAAI,KAAK,CAAC,KAAK,QAAQ,KAAK,CAAC,KAAK;AAClD,UAAQ;AAAA,IACN,2BAA2B,OAAO;AAAA,EACpC;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,IAAI,MAAM;","names":["dirname","dirname"]}
@@ -12,7 +12,7 @@ import {
12
12
  import {
13
13
  ALL_AUDIT_NAMES,
14
14
  runOneAudit
15
- } from "../../chunk-B23FFWU4.js";
15
+ } from "../../chunk-AEXJDCJN.js";
16
16
  import "../../chunk-LKGVSM2O.js";
17
17
  import "../../chunk-GASBX52O.js";
18
18
  import "../../chunk-XHHMM5HX.js";
@@ -253,7 +253,7 @@ ${formatUnmeasuredSmokeSummary(results)}`;
253
253
  ${wb.summary}`;
254
254
  } else {
255
255
  const { resolveSlugFromCwd } = await import("../../lighthouse-airtable-3GUWHETW.js");
256
- const { writeAuditsToAirtable } = await import("../../write-audits-to-airtable-OBHGR7DQ.js");
256
+ const { writeAuditsToAirtable } = await import("../../write-audits-to-airtable-K352LZQY.js");
257
257
  const slug = typeof opts.writeAirtable === "string" && opts.writeAirtable.length > 0 ? opts.writeAirtable : await resolveSlugFromCwd(cwd);
258
258
  let writeSummary = null;
259
259
  await new Listr(
@@ -267,7 +267,7 @@ ${wb.summary}`;
267
267
  task.output = "writing scores\u2026";
268
268
  writeSummary = await writeAuditsToAirtable({ base, websites, slug, results });
269
269
  if (writeSummary.siteId && writeSummary.fields) {
270
- const { makeSiteMirror } = await import("../../site-mirror-Q763PLGG.js");
270
+ const { makeSiteMirror } = await import("../../site-mirror-RQTEAID5.js");
271
271
  await (await makeSiteMirror()).health(writeSummary.siteId, writeSummary.fields);
272
272
  }
273
273
  task.title = `Wrote to Websites[${writeSummary.siteName}] (${writeSummary.writes.length} audit type${writeSummary.writes.length === 1 ? "" : "s"})`;
@@ -293,7 +293,7 @@ ${notice}`;
293
293
  }
294
294
  async function runFleetWriteBack(args) {
295
295
  const { results, which, deps = {} } = args;
296
- const { writeFleetAuditsToAirtable, formatFleetWriteSummary, fleetWriteFailed } = await import("../../write-audits-to-airtable-OBHGR7DQ.js");
296
+ const { writeFleetAuditsToAirtable, formatFleetWriteSummary, fleetWriteFailed } = await import("../../write-audits-to-airtable-K352LZQY.js");
297
297
  let base;
298
298
  if (deps.openBase) {
299
299
  base = deps.openBase();
@@ -304,7 +304,7 @@ async function runFleetWriteBack(args) {
304
304
  const { listWebsites } = await import("../../websites-D6WYFAES.js");
305
305
  const websites = await listWebsites(base);
306
306
  const makeMirror = deps.makeMirror ?? (async () => {
307
- const { makeHealthMirrorBestEffort } = await import("../../health-mirror-GCDN7BJL.js");
307
+ const { makeHealthMirrorBestEffort } = await import("../../health-mirror-7LKC7Q5Z.js");
308
308
  return makeHealthMirrorBestEffort();
309
309
  });
310
310
  const mirror = await makeMirror();
@@ -1,5 +1,14 @@
1
1
  // src/cli/commands/db.ts
2
- async function runDbCommand(action, opts) {
2
+ function freezeGuardsDbWrite(action, force, authoritative) {
3
+ if (!authoritative) return null;
4
+ if (action !== "import-airtable" && action !== "sync") return null;
5
+ if (force) return null;
6
+ return {
7
+ output: `db ${action} refused: TURSO_IS_AUTHORITATIVE is on (the freeze, 2026-08-31). An import now OVERWRITES authoritative Turso rows with the frozen Airtable archive. Pass --force only for a deliberate rollback-window converge.`,
8
+ code: 1
9
+ };
10
+ }
11
+ async function runDbCommand(action, opts, deps = {}) {
3
12
  if (action === "migrate") {
4
13
  const { readDbConfig } = await import("./client-JYKPVCJX.js");
5
14
  const cfg = opts.url ? { url: opts.url } : readDbConfig();
@@ -75,6 +84,9 @@ async function runDbCommand(action, opts) {
75
84
  return { output: lines.join("\n"), code: result.stillFailing.length > 0 ? 1 : 0 };
76
85
  }
77
86
  if (action === "import-airtable" || action === "parity" || action === "sync") {
87
+ const { TURSO_IS_AUTHORITATIVE } = await import("./freeze-A6MUCZU4.js");
88
+ const refused = freezeGuardsDbWrite(action, opts.force === true, TURSO_IS_AUTHORITATIVE);
89
+ if (refused) return refused;
78
90
  const { readDbConfig, openDb } = await import("./client-JYKPVCJX.js");
79
91
  const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());
80
92
  const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
@@ -116,7 +128,7 @@ async function runDbCommand(action, opts) {
116
128
  return { output: lines.join("\n"), code: 0 };
117
129
  }
118
130
  if (action === "sync") {
119
- const { syncFleetState, formatSyncResult } = await import("./sync-GBFV45WX.js");
131
+ const { syncFleetState, formatSyncResult } = await import("./sync-ESP5ZQUU.js");
120
132
  const result2 = await syncFleetState(db, {
121
133
  ...io,
122
134
  fetchAttachment: async (url) => {
@@ -133,7 +145,7 @@ async function runDbCommand(action, opts) {
133
145
  code: result2.parity.mismatches.length > 0 ? 1 : 0
134
146
  };
135
147
  }
136
- const { checkFleetParity, formatParityResult } = await import("./parity-NBYZUBFU.js");
148
+ const { checkFleetParity, formatParityResult } = await import("./parity-623WNFZG.js");
137
149
  const result = await checkFleetParity(db, io);
138
150
  return { output: formatParityResult(result), code: result.mismatches.length > 0 ? 1 : 0 };
139
151
  }
@@ -162,7 +174,7 @@ async function runDbCommand(action, opts) {
162
174
  if (action === "backfill-digest-state") {
163
175
  const { readDbConfig, openDb } = await import("./client-JYKPVCJX.js");
164
176
  const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());
165
- const { readDigestState: readTurso, writeDigestState: writeTurso } = await import("./digest-state-CRZRNGDI.js");
177
+ const { readDigestState: readTurso, writeDigestState: writeTurso } = await import("./digest-state-3KHZF7GD.js");
166
178
  const existing = await readTurso(db);
167
179
  if (Object.keys(existing).length > 0) {
168
180
  return {
@@ -189,7 +201,7 @@ async function runDbCommand(action, opts) {
189
201
  const cfg = opts.url ? { url: opts.url } : readDbConfig();
190
202
  const { createClient } = await import("@libsql/client");
191
203
  const client = createClient(cfg.url === ":memory:" ? { url: ":memory:" } : cfg);
192
- const { dumpDatabase } = await import("./dump-EPL7AZFR.js");
204
+ const { dumpDatabase } = await import("./dump-QK7LNOGC.js");
193
205
  const sql = await dumpDatabase(
194
206
  {
195
207
  execute: async (q) => {
@@ -210,13 +222,17 @@ async function runDbCommand(action, opts) {
210
222
  code: 1
211
223
  };
212
224
  }
225
+ const { parseDumpManifest, requiresAuthToken } = await import("./dump-QK7LNOGC.js");
226
+ const authToken = deps.restoreAuthToken ?? process.env.TURSO_RESTORE_AUTH_TOKEN ?? "";
227
+ if (requiresAuthToken(opts.url) && !authToken) {
228
+ return { output: "RESTORE refused=auth-token-absent", code: 1 };
229
+ }
213
230
  const { readFile } = await import("fs/promises");
214
231
  const sql = await readFile(file, "utf-8");
215
- const { parseDumpManifest } = await import("./dump-EPL7AZFR.js");
216
232
  const manifest = parseDumpManifest(sql);
217
233
  if (!manifest) return { output: "RESTORE refused=manifest-absent", code: 1 };
218
234
  const { createClient } = await import("@libsql/client");
219
- const target = createClient({ url: opts.url });
235
+ const target = createClient(authToken ? { url: opts.url, authToken } : { url: opts.url });
220
236
  const existing = await target.execute(
221
237
  "SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
222
238
  );
@@ -224,7 +240,7 @@ async function runDbCommand(action, opts) {
224
240
  return { output: "RESTORE refused=target-not-empty", code: 1 };
225
241
  }
226
242
  await target.executeMultiple(sql);
227
- const { tableCounts, headerImageBytes } = await import("./dump-EPL7AZFR.js");
243
+ const { tableCounts, headerImageBytes } = await import("./dump-QK7LNOGC.js");
228
244
  const exec = {
229
245
  execute: async (q) => {
230
246
  const r = await target.execute(q);
@@ -248,6 +264,30 @@ async function runDbCommand(action, opts) {
248
264
  code: bad.length > 0 ? 1 : 0
249
265
  };
250
266
  }
267
+ if (action === "usage") {
268
+ const token = deps.platformToken ?? process.env.TURSO_FLEET_USAGE ?? "";
269
+ if (!token) {
270
+ return {
271
+ output: "FLEET_DB_USAGE verdict=no-token \u2014 set TURSO_FLEET_USAGE (turso auth api-tokens mint \u2026). This is the PLATFORM token, not the database TURSO_AUTH_TOKEN.",
272
+ code: 1
273
+ };
274
+ }
275
+ const { collectUsage, assessUsage } = await import("./usage-UHKU76VK.js");
276
+ const input = await collectUsage({
277
+ token,
278
+ org: opts.org ?? process.env.TURSO_ORG,
279
+ fetchImpl: deps.fetchImpl,
280
+ now: deps.now ?? /* @__PURE__ */ new Date()
281
+ });
282
+ const r = assessUsage(input);
283
+ const window = `${input.cycleStart.toISOString().slice(0, 10)} \u2192 ${input.cycleEnd.toISOString().slice(0, 10)}`;
284
+ return {
285
+ output: [`Turso plan=${input.plan} billing cycle ${window}`, ...r.lines, "", r.marker].join(
286
+ "\n"
287
+ ),
288
+ code: r.code
289
+ };
290
+ }
251
291
  if (action === "verify-dump") {
252
292
  const file = opts.file;
253
293
  if (!file) return { output: "verify-dump: pass the dump path via --file", code: 1 };
@@ -260,7 +300,7 @@ async function runDbCommand(action, opts) {
260
300
  } catch (err) {
261
301
  return { output: `DUMP_VERIFY loaded=false error=${String(err)}`, code: 1 };
262
302
  }
263
- const { tableCounts, headerImageBytes, parseDumpManifest } = await import("./dump-EPL7AZFR.js");
303
+ const { tableCounts, headerImageBytes, parseDumpManifest } = await import("./dump-QK7LNOGC.js");
264
304
  const manifest = parseDumpManifest(sql);
265
305
  if (!manifest) {
266
306
  return {
@@ -307,6 +347,7 @@ async function runDbCommand(action, opts) {
307
347
  };
308
348
  }
309
349
  export {
350
+ freezeGuardsDbWrite,
310
351
  runDbCommand
311
352
  };
312
- //# sourceMappingURL=db-V6UIS433.js.map
353
+ //# sourceMappingURL=db-DAJX7NNW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/db.ts"],"sourcesContent":["export type DbCommandOptions = {\n /** Override the libSQL url (tests use \":memory:\"); otherwise read from env. */\n url?: string;\n /** verify-dump: path to the dump file to load into a scratch engine. */\n file?: string;\n /** usage: org slug override; defaults to TURSO_ORG, else discovered. */\n org?: string;\n /** import-airtable / sync: run despite the freeze — a deliberate\n * rollback-window converge from the frozen Airtable shadow. */\n force?: boolean;\n cwd?: string;\n verbose?: boolean;\n};\n\n/** Injected seams — deliberately NOT part of DbCommandOptions, which is the set\n * of things a shell can type (a registration gate asserts exactly that). The\n * platform token lives here rather than on a flag because a secret passed on\n * argv is readable from `ps`. */\nexport type DbCommandDeps = {\n /** Tests pass \"\" to exercise the unconfigured path, so the implementation\n * must use `?? env` and never `|| env`. */\n platformToken?: string;\n fetchImpl?: (url: string, init?: RequestInit) => Promise<Response>;\n now?: Date;\n /** restore: auth token for the TARGET database; defaults to\n * TURSO_RESTORE_AUTH_TOKEN. Deliberately does NOT fall back to the ambient\n * TURSO_AUTH_TOKEN — that one belongs to production, and inheriting it would\n * undo the whole point of making --url explicit. */\n restoreAuthToken?: string;\n};\n\n/** #643 (the freeze): the scheduled import retired with the flip, but the\n * MANUAL import survives as the rollback-window converge tool — and run out of\n * habit it would overwrite authoritative Turso rows with the frozen Airtable\n * archive, including any post-flip write whose best-effort shadow was\n * swallowed. So the writing actions refuse under the freeze unless the\n * operator says `--force`. `parity` stays unguarded: it only compares, and\n * \"did the shadow drift?\" is exactly the rollback-window question.\n *\n * Pure and exported so the test injects BOTH switch states; `runDbCommand`\n * passes the shipped constant. Returns the refusal, or null to proceed. */\nexport function freezeGuardsDbWrite(\n action: string,\n force: boolean,\n authoritative: boolean,\n): { output: string; code: number } | null {\n if (!authoritative) return null;\n if (action !== \"import-airtable\" && action !== \"sync\") return null;\n if (force) return null;\n return {\n output:\n `db ${action} refused: TURSO_IS_AUTHORITATIVE is on (the freeze, 2026-08-31). ` +\n `An import now OVERWRITES authoritative Turso rows with the frozen Airtable ` +\n `archive. Pass --force only for a deliberate rollback-window converge.`,\n code: 1,\n };\n}\n\n/** `db <action>` — migrate | replay-deadletters | import-airtable | parity | sync | dump | verify-dump. The db layer is imported\n * dynamically so a non-db CLI invocation (and `--help`) never loads\n * @libsql/client. Config is resolved inside each branch so an unknown action\n * returns without needing any Turso env. */\nexport async function runDbCommand(\n action: string,\n opts: DbCommandOptions,\n deps: DbCommandDeps = {},\n): Promise<{ output: string; code: number }> {\n if (action === \"migrate\") {\n const { readDbConfig } = await import(\"../../db/client.js\");\n const cfg = opts.url ? { url: opts.url } : readDbConfig();\n const { runMigrations } = await import(\"../../db/migrate.js\");\n const { createClient } = await import(\"@libsql/client\");\n const client = createClient(cfg.url === \":memory:\" ? { url: \":memory:\" } : cfg);\n const ran = await runMigrations(client);\n return {\n output: ran.length ? `Applied migrations: ${ran.join(\", \")}` : \"Already up to date.\",\n code: 0,\n };\n }\n\n // Re-run every lead that dead-lettered during a site-lookup outage (#539\n // Phase 0) through the normal ingest pipeline. Exit 1 while any row is STILL\n // failing — the store hasn't recovered and the operator should not read the\n // run as \"all leads landed\". Zero rows is a clean 0: nothing owed.\n if (action === \"replay-deadletters\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const { getWebsiteBySlug } = await import(\"../../reports/airtable/websites.js\");\n const base = openBase(readAirtableConfig());\n const {\n createSubmission,\n stampNotified,\n stampFanout,\n findRecentDuplicateSubmissions,\n listRecentSubmissionsForEmail,\n markSubmissionsSpamRetro,\n } = await import(\"../../db/submissions.js\");\n const { makeNotify } = await import(\"../../forms/notify.js\");\n const { classifySpam } = await import(\"../../forms/spam-classifier.js\");\n const { forwardNewsletterToWebhook } = await import(\"../../forms/webhook.js\");\n const { addMailchimpMember, mailchimpTagsFor } = await import(\"../../forms/mailchimp.js\");\n const { defaultResendClient } = await import(\"../../reports/send/resend.js\");\n const { replayDeadLetters } = await import(\"../../forms/replay.js\");\n\n // Same degradation as the ingest handler: an unconfigured Resend key means\n // replayed leads land un-emailed (notify=failed) rather than blocking replay.\n let send = null;\n try {\n send = defaultResendClient().send;\n } catch (err) {\n console.error(`[db] Resend unconfigured; replaying without email: ${String(err)}`);\n }\n\n // Mirrors the production handler's deps minus `deadLetter` (replayDeadLetters\n // forbids and strips it — a throwing lookup must retry, not duplicate) and\n // minus `defer` (a CLI has no post-response phase; the inline tail is fine).\n const result = await replayDeadLetters(db, {\n getWebsiteBySlug: (s) => getWebsiteBySlug(base, s),\n createSubmission: (input) => createSubmission(db, input),\n notify: makeNotify(send),\n stampNotified: (id, status, messageId) => stampNotified(db, id, status, messageId),\n now: () => new Date(),\n classifySpam: (n, outcome) =>\n classifySpam({\n name: n.name,\n email: n.email,\n ...(n.message !== undefined ? { message: n.message } : {}),\n formType: n.formType,\n extraFields: n.extraFields,\n turnstile: outcome,\n }),\n findRecentDuplicates: (message, since) =>\n findRecentDuplicateSubmissions(db, message, since.toISOString()),\n listRecentSubmissionsForEmail: (email, since) =>\n listRecentSubmissionsForEmail(db, email, since.toISOString()),\n retroBucket: (ids, reason) => markSubmissionsSpamRetro(db, ids, reason),\n forwardNewsletter: (url, submission, site) =>\n forwardNewsletterToWebhook(url, submission, site),\n addToMailchimp: (site, submission) =>\n addMailchimpMember({\n apiKey: site.mailchimpApiKey ?? \"\",\n audienceId: site.mailchimpAudienceId ?? \"\",\n email: submission.email,\n name: submission.name,\n tags: mailchimpTagsFor(submission.formType),\n }),\n stampFanout: (id, fanoutStatus) => stampFanout(db, id, fanoutStatus),\n });\n\n const lines = [\n ...result.replayed.map(\n (r) => `replayed ${r.id} → ${r.outcome}${r.submissionId ? ` (${r.submissionId})` : \"\"}`,\n ),\n ...result.stillFailing.map((r) => `still failing ${r.id}: ${r.error}`),\n `DEADLETTER_REPLAY replayed=${result.replayed.length} still_failing=${result.stillFailing.length}`,\n ];\n return { output: lines.join(\"\\n\"), code: result.stillFailing.length > 0 ? 1 : 0 };\n }\n\n // Phase 1.3/1.4 of #539. Both read the same two Airtable tables raw (id +\n // fields, no mapRow coercion — the importer's mapping is the authority) and\n // share that mapping, so parity is definitionally checked against what the\n // importer writes.\n if (action === \"import-airtable\" || action === \"parity\" || action === \"sync\") {\n const { TURSO_IS_AUTHORITATIVE } = await import(\"../../db/freeze.js\");\n const refused = freezeGuardsDbWrite(action, opts.force === true, TURSO_IS_AUTHORITATIVE);\n if (refused) return refused;\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const base = openBase(readAirtableConfig());\n const listRaw = async (table: string) =>\n (await base(table).select().all()).map((r) => ({\n id: r.id,\n fields: r.fields as Record<string, unknown>,\n }));\n const io = {\n listWebsiteRecords: () => listRaw(\"Websites\"),\n listReportRecords: () => listRaw(\"Reports\"),\n now: () => new Date(),\n };\n\n if (action === \"import-airtable\") {\n const { importFleetState, formatReapSummary } = await import(\"../../db/import-airtable.js\");\n const summary = await importFleetState(db, {\n ...io,\n // Attachment bodies ride expiring signed URLs; a failed fetch imports the\n // row with rendered_html null and is NAMED in the summary, never silent.\n fetchAttachment: async (url) => {\n try {\n const res = await fetch(url);\n return res.ok ? await res.text() : null;\n } catch {\n return null;\n }\n },\n });\n const lines = [\n `imported ${summary.sites} site(s) → sites/site_health/site_schedule`,\n `imported ${summary.reports} report(s)`,\n ];\n if (summary.renderedHtmlMisses.length > 0) {\n lines.push(\n `⚠ ${summary.renderedHtmlMisses.length} report(s) imported WITHOUT Rendered HTML ` +\n `(fetch failed / URL expired): ${summary.renderedHtmlMisses.join(\", \")}`,\n );\n }\n // The import deletes rows Airtable no longer has, so this one-shot path\n // reports the reap exactly as `db sync` does — same formatter, no second\n // copy to fall out of step.\n lines.push(...formatReapSummary(summary.reaped));\n return { output: lines.join(\"\\n\"), code: 0 };\n }\n\n // Phase 2 backbone (#539): one hourly pass = import (attachment fetches\n // only where the stored row lacks a body) + parity + one retry to absorb\n // the import-read/parity-read race. Exit 1 on persistent mismatch.\n if (action === \"sync\") {\n const { syncFleetState, formatSyncResult } = await import(\"../../db/sync.js\");\n const result = await syncFleetState(db, {\n ...io,\n fetchAttachment: async (url) => {\n try {\n const res = await fetch(url);\n return res.ok ? await res.text() : null;\n } catch {\n return null;\n }\n },\n });\n return {\n output: formatSyncResult(result),\n code: result.parity.mismatches.length > 0 ? 1 : 0,\n };\n }\n\n const { checkFleetParity, formatParityResult } = await import(\"../../db/parity.js\");\n const result = await checkFleetParity(db, io);\n return { output: formatParityResult(result), code: result.mismatches.length > 0 ? 1 : 0 };\n }\n\n // One-shot completion of design D5 (#539 Phase 2): copy every site's CURRENT\n // Airtable \"Header image\" attachment into sites.header_image*. Idempotent —\n // an already-populated BLOB is never overwritten (a re-run must not clobber\n // a freshly generated image with a stale Airtable copy). Exit 1 when any\n // fetch failed, so a partial backfill is never read as complete.\n if (action === \"backfill-header-images\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const base = openBase(readAirtableConfig());\n const { backfillHeaderImages, formatBackfillResult } =\n await import(\"../../db/header-images.js\");\n const result = await backfillHeaderImages(db, {\n listWebsiteRecords: async () =>\n (await base(\"Websites\").select().all()).map((r) => ({\n id: r.id,\n fields: r.fields as Record<string, unknown>,\n })),\n fetchBytes: async (url) => {\n try {\n const res = await fetch(url);\n return res.ok ? new Uint8Array(await res.arrayBuffer()) : null;\n } catch {\n return null;\n }\n },\n });\n return { output: formatBackfillResult(result), code: result.failed.length > 0 ? 1 : 0 };\n }\n\n // #609: one-shot copy of the single Airtable \"Digest State\" row into Turso,\n // so the first digest run after the read repoint sees yesterday's snapshot\n // instead of an empty one. An empty read is not a crash — it badges EVERY\n // item NEW, which lands in the operator's inbox reading as \"the whole fleet\n // degraded overnight\". REFUSES to overwrite a snapshot Turso already holds:\n // a re-run must never replace a fresher snapshot with a stale Airtable copy.\n if (action === \"backfill-digest-state\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { readDigestState: readTurso, writeDigestState: writeTurso } =\n await import(\"../../db/digest-state.js\");\n const existing = await readTurso(db);\n if (Object.keys(existing).length > 0) {\n return {\n output: `DIGEST_BACKFILL skipped=1 reason=turso-already-populated keys=${Object.keys(existing).length}`,\n code: 0,\n };\n }\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const base = openBase(readAirtableConfig());\n const { readDigestState: readAirtable, DIGEST_STATE_TABLE } =\n await import(\"../../alerts/digest-state.js\");\n // `source` separates \"Airtable has no row\" from \"Airtable has a row holding\n // an empty snapshot\" — the reader collapses BOTH to {}, so copied=0 alone\n // cannot tell a quiet fleet from a failed read. Learned by running this: the\n // first real run printed copied=0 and only a hand probe showed the row was\n // there and genuinely empty.\n const rows = await base(DIGEST_STATE_TABLE).select({ maxRecords: 1, pageSize: 1 }).all();\n const snap = await readAirtable(base);\n const keys = Object.keys(snap).length;\n await writeTurso(db, snap);\n // Read it BACK. A returning write is not evidence the row landed — the same\n // rule forms-notify-target learned on 2026-08-03. `stored` counts the ROW,\n // not its keys, so an empty-but-present snapshot verifies as written.\n const stored = (await db.selectFrom(\"digest_state\").selectAll().execute()).length;\n const after = Object.keys(await readTurso(db)).length;\n return {\n output:\n `DIGEST_BACKFILL source=${rows.length > 0 ? \"row\" : \"absent\"} ` +\n `copied=${keys} verified=${after} rows=${stored}`,\n code: after === keys && stored === 1 ? 0 : 1,\n };\n }\n\n // Phase 1.5 of #539: platform-auth-free SQL dump to stdout-adjacent output.\n // The nightly backup workflow redirects this to a file, encrypts, uploads;\n // the rehearsed restore loads it into stock sqlite3 and compares row counts.\n if (action === \"dump\") {\n const { readDbConfig } = await import(\"../../db/client.js\");\n const cfg = opts.url ? { url: opts.url } : readDbConfig();\n const { createClient } = await import(\"@libsql/client\");\n const client = createClient(cfg.url === \":memory:\" ? { url: \":memory:\" } : cfg);\n const { dumpDatabase } = await import(\"../../db/dump.js\");\n const sql = await dumpDatabase(\n {\n execute: async (q) => {\n const r = await client.execute(q);\n return { columns: r.columns, rows: r.rows as Array<Record<string, unknown>> };\n },\n },\n new Date().toISOString(),\n );\n return { output: sql, code: 0 };\n }\n\n // Load a dump back into a REAL libSQL target (#612 review). The nightly\n // rehearsal loads into `:memory:`, which proves the SQL parses — it does not\n // prove you can get the data back into Turso, and that is the operation an\n // actual recovery needs. Replaying ~17 MB of SQL with megabytes of inline hex\n // over HTTP is materially different from an in-process load, and it had never\n // been done. Refuses to touch a database that already holds rows: a restore\n // is for an EMPTY target, and pointing this at production by mistake should\n // cost nothing.\n if (action === \"restore\") {\n const file = opts.file;\n if (!file) return { output: \"restore: pass the dump path via --file\", code: 1 };\n if (!opts.url) {\n return {\n output:\n \"restore: pass the TARGET database via --url (never defaults, to keep production out of reach)\",\n code: 1,\n };\n }\n // Classify the target BEFORE reading the dump, so a missing token names\n // itself instead of arriving as an opaque 401 (or, worse, as an ENOENT that\n // sends you hunting for the dump file). This command built its client from\n // a url alone until 2026-08-26, which worked against every target the tests\n // and rehearsals used — `:memory:` and a local `turso dev` — and failed\n // against every target an actual recovery has.\n const { parseDumpManifest, requiresAuthToken } = await import(\"../../db/dump.js\");\n const authToken = deps.restoreAuthToken ?? process.env.TURSO_RESTORE_AUTH_TOKEN ?? \"\";\n if (requiresAuthToken(opts.url) && !authToken) {\n return { output: \"RESTORE refused=auth-token-absent\", code: 1 };\n }\n const { readFile } = await import(\"node:fs/promises\");\n const sql = await readFile(file, \"utf-8\");\n const manifest = parseDumpManifest(sql);\n if (!manifest) return { output: \"RESTORE refused=manifest-absent\", code: 1 };\n const { createClient } = await import(\"@libsql/client\");\n const target = createClient(authToken ? { url: opts.url, authToken } : { url: opts.url });\n const existing = await target.execute(\n \"SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\",\n );\n if (Number(existing.rows[0]?.n ?? 0) > 0) {\n return { output: \"RESTORE refused=target-not-empty\", code: 1 };\n }\n await target.executeMultiple(sql);\n const { tableCounts, headerImageBytes } = await import(\"../../db/dump.js\");\n const exec = {\n execute: async (q: string) => {\n const r = await target.execute(q);\n return { columns: r.columns, rows: r.rows as Array<Record<string, unknown>> };\n },\n };\n const counts = await tableCounts(exec);\n const bytes = await headerImageBytes(exec);\n // Same origin-anchored comparison as verify-dump: a restore that \"succeeded\"\n // with fewer rows than the origin held is not a restore.\n const bad: string[] = [];\n for (const [t, want] of Object.entries(manifest.tables)) {\n if ((counts[t] ?? 0) !== want) bad.push(`${t}: origin=${want} restored=${counts[t] ?? 0}`);\n }\n if (bytes !== manifest.blobBytes)\n bad.push(`header_image bytes: origin=${manifest.blobBytes} restored=${bytes}`);\n const rows = Object.values(counts).reduce((a, b) => a + b, 0);\n return {\n output: [\n ...bad.map((b) => `✗ ${b}`),\n `RESTORE loaded=true tables=${Object.keys(counts).length} rows=${rows} blob_bytes=${bytes} mismatches=${bad.length}`,\n ].join(\"\\n\"),\n code: bad.length > 0 ? 1 : 0,\n };\n }\n\n // How much of the plan's quota the fleet has burned this billing cycle\n // (#539 HIGH-10). The starter plan carries `overages: false`, so crossing a\n // quota BLOCKS reads and writes rather than billing for them — and once the\n // Airtable cutover lands, Turso is the only store there is. This is the one\n // alarm that fires before a wall rather than after it.\n //\n // Needs a PLATFORM token, which is a different credential from the\n // database-level TURSO_AUTH_TOKEN the rest of the fleet runs on: the database\n // token cannot read quota state at all.\n if (action === \"usage\") {\n const token = deps.platformToken ?? process.env.TURSO_FLEET_USAGE ?? \"\";\n // An unconfigured alarm must not read as a quiet, healthy one. The tell for\n // \"never ran\" has to be a failure, not a missing line (#585).\n if (!token) {\n return {\n output:\n \"FLEET_DB_USAGE verdict=no-token — set TURSO_FLEET_USAGE (turso auth api-tokens mint …). \" +\n \"This is the PLATFORM token, not the database TURSO_AUTH_TOKEN.\",\n code: 1,\n };\n }\n const { collectUsage, assessUsage } = await import(\"../../db/usage.js\");\n const input = await collectUsage({\n token,\n org: opts.org ?? process.env.TURSO_ORG,\n fetchImpl: deps.fetchImpl,\n now: deps.now ?? new Date(),\n });\n const r = assessUsage(input);\n const window = `${input.cycleStart.toISOString().slice(0, 10)} → ${input.cycleEnd\n .toISOString()\n .slice(0, 10)}`;\n return {\n output: [`Turso plan=${input.plan} billing cycle ${window}`, ...r.lines, \"\", r.marker].join(\n \"\\n\",\n ),\n code: r.code,\n };\n }\n\n // The restore rehearsal (Phase 1.5's hard gate), runnable every night: load\n // the dump into a FRESH in-memory engine and compare what came back against\n // the ORIGIN MANIFEST the dump carries.\n //\n // It used to compare against INSERT counts parsed out of the dump text — i.e.\n // the dump against itself. Both sides derived from one artifact, so a dump\n // that collected 5 of 44 sites shrank both numbers together and verified\n // clean. The manifest is read from the live database before any row is\n // serialised, which is the only measurement that can notice a short dump.\n //\n // A dump that cannot restore is not a backup — and per the repo's instrument\n // rule the check emits its machine line on every run, clean included.\n if (action === \"verify-dump\") {\n const file = opts.file;\n if (!file) return { output: \"verify-dump: pass the dump path via --file\", code: 1 };\n const { readFile } = await import(\"node:fs/promises\");\n const sql = await readFile(file, \"utf-8\");\n const { createClient } = await import(\"@libsql/client\");\n const scratch = createClient({ url: \":memory:\" });\n try {\n await scratch.executeMultiple(sql);\n } catch (err) {\n return { output: `DUMP_VERIFY loaded=false error=${String(err)}`, code: 1 };\n }\n const { tableCounts, headerImageBytes, parseDumpManifest } = await import(\"../../db/dump.js\");\n const manifest = parseDumpManifest(sql);\n if (!manifest) {\n // Refuse rather than fall back to self-comparison. Falling back would\n // re-enable exactly the blind spot the manifest exists to close, and it\n // would do so silently on the one artifact nobody was watching.\n return {\n output: \"DUMP_VERIFY loaded=true manifest=absent — dump predates the origin manifest\",\n code: 1,\n };\n }\n const exec = {\n execute: async (q: string) => {\n const r = await scratch.execute(q);\n return { columns: r.columns, rows: r.rows as Array<Record<string, unknown>> };\n },\n };\n const restored = await tableCounts(exec);\n const restoredBlobBytes = await headerImageBytes(exec);\n const mismatches: string[] = [];\n for (const [table, want] of Object.entries(manifest.tables)) {\n if ((restored[table] ?? 0) !== want) {\n mismatches.push(`${table}: origin=${want} restored=${restored[table] ?? 0}`);\n }\n }\n // A table the origin held and the dump never mentioned would otherwise be\n // invisible: absent from `restored` AND absent from the loop above.\n for (const table of Object.keys(restored)) {\n if (!(table in manifest.tables)) mismatches.push(`${table}: not in origin manifest`);\n }\n // Coverage: every table the APP owns must be present. `tables=N` used to be\n // printed and never asserted, so a table a migration failed to create — or\n // that the dump lost — rode green forever. `digest_state` and\n // `prospect_audits` were both absent from every artifact the night this was\n // found, purely because they postdated the last run.\n const { DATABASE_TABLES } = await import(\"../../db/schema.js\");\n for (const table of DATABASE_TABLES) {\n if (!(table in restored)) mismatches.push(`${table}: MISSING from the backup entirely`);\n }\n if (restoredBlobBytes !== manifest.blobBytes) {\n mismatches.push(\n `header_image bytes: origin=${manifest.blobBytes} restored=${restoredBlobBytes}`,\n );\n }\n const total = Object.values(restored).reduce((a, b) => a + b, 0);\n const lines = [\n ...mismatches.map((m) => `✗ ${m}`),\n `DUMP_VERIFY loaded=true tables=${Object.keys(restored).length} rows=${total} blob_bytes=${restoredBlobBytes} mismatches=${mismatches.length}`,\n ];\n return { output: lines.join(\"\\n\"), code: mismatches.length > 0 ? 1 : 0 };\n }\n\n return {\n output: `unknown db action '${action}'. Use: migrate, replay-deadletters, import-airtable, parity, sync, backfill-header-images, backfill-digest-state, dump, verify-dump, restore.`,\n code: 1,\n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