@reddoorla/maintenance 0.81.0 → 0.83.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 (131) hide show
  1. package/dist/airtable-5ZPU3MT4.js +9 -0
  2. package/dist/{announce-KZDU65IF.js → announce-4H64L2Z6.js} +4 -4
  3. package/dist/{blux-EATHOHKK.js → blux-ZGDSHI3U.js} +5 -5
  4. package/dist/{bump-deps-XB2LJTVN.js → bump-deps-2OL6PGTM.js} +5 -5
  5. package/dist/{chunk-SK44IFZN.js → chunk-2WN4SNBQ.js} +2 -2
  6. package/dist/{chunk-HVOOCK6L.js → chunk-4DHQCN5H.js} +2 -1
  7. package/dist/{chunk-R5KAXGSP.js → chunk-5P2HVNLZ.js} +3 -3
  8. package/dist/{chunk-TEOENEJH.js → chunk-6V7565O2.js} +8 -8
  9. package/dist/{chunk-GXVX4HUH.js → chunk-CLWNAMUX.js} +38 -3
  10. package/dist/chunk-CLWNAMUX.js.map +1 -0
  11. package/dist/{chunk-KKIKJWM2.js → chunk-FSRJAF2Q.js} +64 -5
  12. package/dist/chunk-FSRJAF2Q.js.map +1 -0
  13. package/dist/{chunk-B5ZUQZFL.js → chunk-ICXV25N7.js} +2 -2
  14. package/dist/{chunk-6M2IXJ3E.js → chunk-JVWJJ36K.js} +5 -4
  15. package/dist/chunk-JVWJJ36K.js.map +1 -0
  16. package/dist/{chunk-AKRUYPLU.js → chunk-KV7DIRRO.js} +3 -3
  17. package/dist/{chunk-4BHNP6Y2.js → chunk-MQUOUVQP.js} +2 -2
  18. package/dist/{chunk-3PU2QWOJ.js → chunk-OQFOMKBP.js} +2 -2
  19. package/dist/{chunk-42A4H6SF.js → chunk-PBCGXXG6.js} +2 -2
  20. package/dist/{chunk-JMAFXEQE.js → chunk-QRDB4NLB.js} +11 -8
  21. package/dist/chunk-QRDB4NLB.js.map +1 -0
  22. package/dist/{chunk-K5JZ5KLO.js → chunk-R4AB6GCT.js} +3 -3
  23. package/dist/chunk-R53VL3RI.js +32 -0
  24. package/dist/chunk-R53VL3RI.js.map +1 -0
  25. package/dist/{chunk-FX7RAMGC.js → chunk-R6FPFMOS.js} +3 -3
  26. package/dist/{chunk-MGJ72BA4.js → chunk-RJB3QUSP.js} +2 -2
  27. package/dist/{chunk-ATJ6ZA2V.js → chunk-SDUJIANJ.js} +2 -2
  28. package/dist/{chunk-7ADQL5Y3.js → chunk-THEFTZ7F.js} +2 -2
  29. package/dist/{chunk-NT4WIP7I.js → chunk-UYCAF77E.js} +2 -2
  30. package/dist/chunk-VNB5XBQ4.js +699 -0
  31. package/dist/chunk-VNB5XBQ4.js.map +1 -0
  32. package/dist/{chunk-YAMRVXOD.js → chunk-VRWUL4TR.js} +2 -2
  33. package/dist/{chunk-JR67FZVC.js → chunk-XDCRVYFL.js} +3 -3
  34. package/dist/chunk-XDCRVYFL.js.map +1 -0
  35. package/dist/{chunk-4NAOR44V.js → chunk-ZMIPG6TR.js} +2 -2
  36. package/dist/cli/bin.js +51 -23
  37. package/dist/cli/bin.js.map +1 -1
  38. package/dist/cli/commands/audit.d.ts +1 -1
  39. package/dist/cli/commands/audit.js +10 -10
  40. package/dist/{convert-to-pnpm-FZHSLUQB.js → convert-to-pnpm-KCXOYOHW.js} +5 -5
  41. package/dist/{digest-44QNZZKM.js → digest-WGEPAWMP.js} +12 -7
  42. package/dist/digest-WGEPAWMP.js.map +1 -0
  43. package/dist/{ensure-site-3SOAWTZF.js → ensure-site-HYAIVZY2.js} +2 -2
  44. package/dist/{forms-notify-target-CL3HRVKN.js → forms-notify-target-HSL4ZMT5.js} +2 -2
  45. package/dist/{github-signals-2BFMZLPV.js → github-signals-I7XACMCE.js} +6 -6
  46. package/dist/{header-image-H4N54DHN.js → header-image-ADYPTGVY.js} +2 -2
  47. package/dist/{health-endpoint-LFVE26QS.js → health-endpoint-JNCUILHO.js} +6 -6
  48. package/dist/index.d.ts +74 -3
  49. package/dist/index.js +32 -31
  50. package/dist/index.js.map +1 -1
  51. package/dist/{init-RYKQFSZI.js → init-FLGLJCMJ.js} +13 -13
  52. package/dist/{launch-EGKYS3BD.js → launch-AVKH2JVF.js} +10 -10
  53. package/dist/{lighthouse-airtable-ZXNMDEPE.js → lighthouse-airtable-CHANWVO6.js} +3 -3
  54. package/dist/{onboard-RDGHVCNG.js → onboard-HF4FTJDE.js} +5 -5
  55. package/dist/{orchestrate-NY6L4Q7Q.js → orchestrate-5FMNYJEA.js} +3 -3
  56. package/dist/{preflight-SRDQS7Y6.js → preflight-HTWIX3MN.js} +4 -4
  57. package/dist/prismic-ci-BH225Q4L.js +363 -0
  58. package/dist/prismic-ci-BH225Q4L.js.map +1 -0
  59. package/dist/prismic-models-HXCAM4ZL.js +1020 -0
  60. package/dist/prismic-models-HXCAM4ZL.js.map +1 -0
  61. package/dist/{protection-audit-2UR45SOC.js → protection-audit-64PLLBLI.js} +3 -3
  62. package/dist/recipes/sync-configs.d.ts +1 -1
  63. package/dist/{renovate-dispatch-7D7FMMJP.js → renovate-dispatch-HBZG2UEU.js} +8 -5
  64. package/dist/renovate-dispatch-HBZG2UEU.js.map +1 -0
  65. package/dist/{report-MLCIIML5.js → report-LV7NY5W3.js} +20 -13
  66. package/dist/report-LV7NY5W3.js.map +1 -0
  67. package/dist/{self-updating-WJEHPASK.js → self-updating-4Q65OVXY.js} +6 -6
  68. package/dist/{selftest-ZJDB4JQB.js → selftest-K5XZKVTE.js} +7 -7
  69. package/dist/{smoke-suite-SUEJFBYP.js → smoke-suite-J3LL3JZJ.js} +6 -6
  70. package/dist/{submissions-RAYGOASP.js → submissions-GMBUP4LV.js} +2 -2
  71. package/dist/{svelte-codemods-IWO7X3F3.js → svelte-codemods-JTMX4BSX.js} +4 -4
  72. package/dist/{sync-configs-7XGHFC6P.js → sync-configs-5DXSL64Q.js} +4 -4
  73. package/dist/{types-DnEL3NRn.d.ts → types-OIQZ5hWN.d.ts} +1 -1
  74. package/dist/{upgrade-AM4S7JF3.js → upgrade-HCR25P25.js} +5 -5
  75. package/dist/{websites-U6642XSE.js → websites-VITQ3WXN.js} +8 -2
  76. package/dist/{write-audits-to-airtable-22T6D733.js → write-audits-to-airtable-3SOXLKJK.js} +4 -4
  77. package/package.json +3 -3
  78. package/dist/airtable-6L3JD7FY.js +0 -9
  79. package/dist/chunk-6M2IXJ3E.js.map +0 -1
  80. package/dist/chunk-GXVX4HUH.js.map +0 -1
  81. package/dist/chunk-JMAFXEQE.js.map +0 -1
  82. package/dist/chunk-JR67FZVC.js.map +0 -1
  83. package/dist/chunk-KKIKJWM2.js.map +0 -1
  84. package/dist/chunk-KRDLHAKK.js +0 -17
  85. package/dist/chunk-KRDLHAKK.js.map +0 -1
  86. package/dist/digest-44QNZZKM.js.map +0 -1
  87. package/dist/renovate-dispatch-7D7FMMJP.js.map +0 -1
  88. package/dist/report-MLCIIML5.js.map +0 -1
  89. /package/dist/{airtable-6L3JD7FY.js.map → airtable-5ZPU3MT4.js.map} +0 -0
  90. /package/dist/{announce-KZDU65IF.js.map → announce-4H64L2Z6.js.map} +0 -0
  91. /package/dist/{blux-EATHOHKK.js.map → blux-ZGDSHI3U.js.map} +0 -0
  92. /package/dist/{bump-deps-XB2LJTVN.js.map → bump-deps-2OL6PGTM.js.map} +0 -0
  93. /package/dist/{chunk-SK44IFZN.js.map → chunk-2WN4SNBQ.js.map} +0 -0
  94. /package/dist/{chunk-HVOOCK6L.js.map → chunk-4DHQCN5H.js.map} +0 -0
  95. /package/dist/{chunk-R5KAXGSP.js.map → chunk-5P2HVNLZ.js.map} +0 -0
  96. /package/dist/{chunk-TEOENEJH.js.map → chunk-6V7565O2.js.map} +0 -0
  97. /package/dist/{chunk-B5ZUQZFL.js.map → chunk-ICXV25N7.js.map} +0 -0
  98. /package/dist/{chunk-AKRUYPLU.js.map → chunk-KV7DIRRO.js.map} +0 -0
  99. /package/dist/{chunk-4BHNP6Y2.js.map → chunk-MQUOUVQP.js.map} +0 -0
  100. /package/dist/{chunk-3PU2QWOJ.js.map → chunk-OQFOMKBP.js.map} +0 -0
  101. /package/dist/{chunk-42A4H6SF.js.map → chunk-PBCGXXG6.js.map} +0 -0
  102. /package/dist/{chunk-K5JZ5KLO.js.map → chunk-R4AB6GCT.js.map} +0 -0
  103. /package/dist/{chunk-FX7RAMGC.js.map → chunk-R6FPFMOS.js.map} +0 -0
  104. /package/dist/{chunk-MGJ72BA4.js.map → chunk-RJB3QUSP.js.map} +0 -0
  105. /package/dist/{chunk-ATJ6ZA2V.js.map → chunk-SDUJIANJ.js.map} +0 -0
  106. /package/dist/{chunk-7ADQL5Y3.js.map → chunk-THEFTZ7F.js.map} +0 -0
  107. /package/dist/{chunk-NT4WIP7I.js.map → chunk-UYCAF77E.js.map} +0 -0
  108. /package/dist/{chunk-YAMRVXOD.js.map → chunk-VRWUL4TR.js.map} +0 -0
  109. /package/dist/{chunk-4NAOR44V.js.map → chunk-ZMIPG6TR.js.map} +0 -0
  110. /package/dist/{convert-to-pnpm-FZHSLUQB.js.map → convert-to-pnpm-KCXOYOHW.js.map} +0 -0
  111. /package/dist/{ensure-site-3SOAWTZF.js.map → ensure-site-HYAIVZY2.js.map} +0 -0
  112. /package/dist/{forms-notify-target-CL3HRVKN.js.map → forms-notify-target-HSL4ZMT5.js.map} +0 -0
  113. /package/dist/{github-signals-2BFMZLPV.js.map → github-signals-I7XACMCE.js.map} +0 -0
  114. /package/dist/{header-image-H4N54DHN.js.map → header-image-ADYPTGVY.js.map} +0 -0
  115. /package/dist/{health-endpoint-LFVE26QS.js.map → health-endpoint-JNCUILHO.js.map} +0 -0
  116. /package/dist/{init-RYKQFSZI.js.map → init-FLGLJCMJ.js.map} +0 -0
  117. /package/dist/{launch-EGKYS3BD.js.map → launch-AVKH2JVF.js.map} +0 -0
  118. /package/dist/{lighthouse-airtable-ZXNMDEPE.js.map → lighthouse-airtable-CHANWVO6.js.map} +0 -0
  119. /package/dist/{onboard-RDGHVCNG.js.map → onboard-HF4FTJDE.js.map} +0 -0
  120. /package/dist/{orchestrate-NY6L4Q7Q.js.map → orchestrate-5FMNYJEA.js.map} +0 -0
  121. /package/dist/{preflight-SRDQS7Y6.js.map → preflight-HTWIX3MN.js.map} +0 -0
  122. /package/dist/{protection-audit-2UR45SOC.js.map → protection-audit-64PLLBLI.js.map} +0 -0
  123. /package/dist/{self-updating-WJEHPASK.js.map → self-updating-4Q65OVXY.js.map} +0 -0
  124. /package/dist/{selftest-ZJDB4JQB.js.map → selftest-K5XZKVTE.js.map} +0 -0
  125. /package/dist/{smoke-suite-SUEJFBYP.js.map → smoke-suite-J3LL3JZJ.js.map} +0 -0
  126. /package/dist/{submissions-RAYGOASP.js.map → submissions-GMBUP4LV.js.map} +0 -0
  127. /package/dist/{svelte-codemods-IWO7X3F3.js.map → svelte-codemods-JTMX4BSX.js.map} +0 -0
  128. /package/dist/{sync-configs-7XGHFC6P.js.map → sync-configs-5DXSL64Q.js.map} +0 -0
  129. /package/dist/{upgrade-AM4S7JF3.js.map → upgrade-HCR25P25.js.map} +0 -0
  130. /package/dist/{websites-U6642XSE.js.map → websites-VITQ3WXN.js.map} +0 -0
  131. /package/dist/{write-audits-to-airtable-22T6D733.js.map → write-audits-to-airtable-3SOXLKJK.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/alerts/digest-collectors.ts","../src/alerts/digest-state.ts"],"sourcesContent":["// src/alerts/digest-collectors.ts\nimport type { AttentionItem } from \"./attention.js\";\nimport {\n allActionableVulnsTransitive,\n siteSlug,\n ACTIVE_STATUSES,\n isPreLaunch,\n type WebsiteRow,\n} from \"../reports/airtable/websites.js\";\nimport type { ReportRow } from \"../reports/airtable/reports.js\";\nimport { approveBlockers } from \"../reports/preflight.js\";\n\n/** Build the same `/s/<slug>` dashboard link the M3 ready-section uses, trailing-slash-safe.\n * An empty Name slugs to \"\" and `/s/` is a dead link — fall back to the fleet homepage,\n * exactly like the ready-section does. */\nfunction dashboardUrl(baseUrl: string, siteName: string): string {\n const root = baseUrl.replace(/\\/$/, \"\");\n const slug = siteSlug(siteName);\n return slug ? `${root}/s/${slug}` : root;\n}\n\n/**\n * A GitHub-signals sweep older than this (or never run) is no longer trustworthy:\n * a repo whose nightly probe THREW stops being re-swept, so its persisted\n * `Default Branch CI` / `Renovate Failing CIs` freeze at their last value forever\n * — a phantom 🔴 that can never clear. 3 days ≈ 3× the daily sweep interval, so a\n * single missed/flaky run doesn't drop a real signal. The CI/Renovate collectors\n * (only) skip a site whose `githubSignalsAt` is staler than this. Vuln/Lighthouse/\n * delivery signals come from other sweeps and are unaffected.\n */\nconst GITHUB_SIGNALS_STALE_DAYS = 3;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/** True when a site's GitHub-signals sweep is too old (or never ran) to trust the\n * persisted CI/Renovate fields. A null `githubSignalsAt` (never swept) is stale —\n * there's no sweep to vouch for the values. A future timestamp (now - swept < 0)\n * is fresh. `now` is injected so the gate is testable. */\nfunction gitHubSignalsStale(swept: string | null, now: Date): boolean {\n if (swept === null) return true;\n const ageMs = now.getTime() - Date.parse(swept);\n if (!Number.isFinite(ageMs)) return true; // unparseable timestamp → don't trust it\n return ageMs > GITHUB_SIGNALS_STALE_DAYS * MS_PER_DAY;\n}\n\n/** Renovate auto-fix dispatches for one vuln episode before it's \"exhausted\" (manual fix needed). */\nconst AUTO_FIX_EXHAUSTED_CYCLES = 3;\n\n/**\n * One attention item per site carrying current critical+high vulns (medium/low omitted\n * per the locked threshold). PURE: takes already-fetched Websites rows. `metric` is the\n * critical+high count (so a rising count diffs as WORSE); `severity` is `critical` when\n * any critical exists, else `warning`. Null counts (never audited) read as 0 → skipped.\n * Once `securityAutoFixAttempts` reaches AUTO_FIX_EXHAUSTED_CYCLES the item is flagged\n * `autoFixExhausted` (forced-critical, escalated title) — Renovate tried and couldn't fix it.\n * EXCEPT when the persisted advisories prove every critical/high vuln is TRANSITIVE: then\n * nightly dispatches were green no-ops (no direct dep to bump — the fix rides the weekly\n * lockfile window), \"auto-fix failed\" would be a lie, and a stale pre-fix counter must not\n * escalate (Sonder said \"auto-fix failed (5×)\" on exactly this, 2026-08-10). Those sites get\n * an honest transitive-only title, keep count-based severity, and stay out of the digest\n * email (amber cockpit Watch still shows them). Unknown relationship data never mutes.\n *\n * Emission is UNCONDITIONAL — every surface applies its own policy on top:\n * - digest email: includes a vuln only when `autoFixExhausted` (the operator hears\n * about a vuln only after Renovate tried and failed; before that the fleet is\n * still self-patching) — runDigest filters\n * - cockpit: non-exhausted vuln → amber Watch; exhausted → hard break (assignTier),\n * and only an exhausted vuln pierces the pre-launch mute (piercesPreLaunchMute)\n */\nexport function collectVulnAlerts(sites: WebsiteRow[], baseUrl: string): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n const critical = s.securityVulnsCritical ?? 0;\n const high = s.securityVulnsHigh ?? 0;\n const metric = critical + high;\n if (metric <= 0) continue;\n const attempts = s.securityAutoFixAttempts ?? 0;\n const transitiveOnly = allActionableVulnsTransitive(s.securityAdvisories);\n const exhausted = !transitiveOnly && attempts >= AUTO_FIX_EXHAUSTED_CYCLES;\n const noun = metric === 1 ? \"vuln\" : \"vulns\";\n items.push({\n key: `vuln:${s.id}`,\n kind: \"vuln\",\n siteName: s.name,\n title: exhausted\n ? `${metric} critical/high ${noun} — auto-fix failed (${attempts}×)`\n : transitiveOnly\n ? `${metric} critical/high ${noun} — transitive-only, fix rides the weekly lockfile window`\n : `${metric} critical/high ${noun}`,\n url: dashboardUrl(baseUrl, s.name),\n severity: exhausted || critical > 0 ? \"critical\" : \"warning\",\n metric,\n ...(exhausted ? { autoFixExhausted: true } : {}),\n });\n }\n return items;\n}\n\n/** Absolute floor below which a Lighthouse category is \"Needs attention\" (Tucker's call). */\nconst LIGHTHOUSE_FLOOR = 75;\n\n/** The four Lighthouse categories, each mapped to its WebsiteRow score field, URL slug,\n * and the human label rendered in the digest title. Order is the operator's reading order. */\nconst LIGHTHOUSE_CATEGORIES: ReadonlyArray<{\n field: \"pScore\" | \"rScore\" | \"bpScore\" | \"seoScore\";\n slug: string;\n label: string;\n}> = [\n { field: \"pScore\", slug: \"performance\", label: \"Performance\" },\n { field: \"rScore\", slug: \"accessibility\", label: \"Accessibility\" },\n { field: \"bpScore\", slug: \"best-practices\", label: \"Best Practices\" },\n { field: \"seoScore\", slug: \"seo\", label: \"SEO\" },\n];\n\n/**\n * One attention item per Lighthouse category below the absolute floor (75) for each site.\n * PURE: takes already-fetched Websites rows. Categories are Performance/Accessibility/\n * Best-Practices/SEO. A null score (never audited) or a score >= 75 is skipped. The\n * `metric` is the DEFICIT (`100 - score`): a lower score → higher metric, so a category\n * that drops further diffs as WORSE and one that first crosses below 75 diffs as NEW —\n * which is how `diffAttention`'s \"WORSE on increase\" rule reads an inverted score. `key`\n * is `lighthouse:<siteId>:<categorySlug>`, so the four categories stay distinct per site.\n */\nexport function collectLighthouseAlerts(sites: WebsiteRow[], baseUrl: string): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n for (const cat of LIGHTHOUSE_CATEGORIES) {\n const score = s[cat.field];\n if (score === null || score >= LIGHTHOUSE_FLOOR) continue;\n items.push({\n key: `lighthouse:${s.id}:${cat.slug}`,\n kind: \"lighthouse\",\n siteName: s.name,\n title: `Lighthouse ${cat.label} ${score} (below ${LIGHTHOUSE_FLOOR})`,\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: 100 - score,\n });\n }\n }\n return items;\n}\n\n/**\n * One attention item per report whose `deliveryStatus` is a failure (`bounced` or\n * `complained` — `delivered`/`pending` are ignored). PURE: takes already-fetched\n * Reports rows + a record-id→site map. A complaint ranks above a bounce (locked\n * threshold), so `severity` is `critical` for complained / `warning` for bounced.\n * `metric` is 1 (a binary event). Orphans (siteId not in the map) are skipped, as\n * the M3 ready-section does, so the digest never renders a broken link. The diff\n * key is the report RECORD id, so two failures on one site stay distinct.\n */\n/**\n * One attention item per unsent draft whose send is ALREADY known to fail\n * (approveBlockers: recipients / header image / report scores). An APPROVED one\n * is critical — the next 09:23 UTC run will go red on it; a pending one is a\n * warning — approving it just schedules that failure. Keyed `preflight:<reportId>`.\n * PURE; same predicate the approve gate and the dashboard chip use.\n */\nexport function collectPreflightBlocked(\n reports: ReportRow[],\n sitesById: Map<string, WebsiteRow>,\n baseUrl: string,\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const r of reports) {\n if (!r.draftReady || r.sentAt !== null) continue;\n // The approved state rides the KEY so a pending→approved escalation with\n // unchanged blockers re-news as a fresh critical instead of diffing\n // \"standing\" against its old warning self.\n const state = r.approvedToSend ? \"approved\" : \"pending\";\n const site = sitesById.get(r.siteId);\n if (!site) {\n // A dangling/empty Site link is itself a send blocker (sendApprovedReports\n // fails with \"Site row not found\") — surface it; the empty-slug\n // dashboardUrl fallback yields the fleet root, not a broken /s/ link.\n items.push({\n key: `preflight:${r.id}:${state}`,\n kind: \"preflight\",\n siteName: \"(unlinked site)\",\n title: r.approvedToSend\n ? `Approved ${r.reportType} will fail at send — site-not-found`\n : `${r.reportType} draft can't be approved — site-not-found`,\n url: dashboardUrl(baseUrl, \"\"),\n severity: r.approvedToSend ? \"critical\" : \"warning\",\n metric: 1,\n });\n continue;\n }\n const fails = approveBlockers(site, r).filter((f) => f.level === \"fail\");\n if (fails.length === 0) continue;\n const first = fails[0]!;\n const more = fails.length > 1 ? ` (+${fails.length - 1} more)` : \"\";\n items.push({\n key: `preflight:${r.id}:${state}`,\n kind: \"preflight\",\n siteName: site.name,\n title: r.approvedToSend\n ? `Approved ${r.reportType} will fail at send — ${first.check}${more}`\n : `${r.reportType} draft can't be approved — ${first.check}${more}`,\n url: dashboardUrl(baseUrl, site.name),\n severity: r.approvedToSend ? \"critical\" : \"warning\",\n metric: fails.length,\n });\n }\n return items;\n}\n\nexport function collectDeliveryFailures(\n reports: ReportRow[],\n sitesById: Map<string, WebsiteRow>,\n baseUrl: string,\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const r of reports) {\n if (r.deliveryStatus !== \"bounced\" && r.deliveryStatus !== \"complained\") continue;\n const site = sitesById.get(r.siteId);\n if (!site) continue; // orphan → skip rather than render a broken link\n const complained = r.deliveryStatus === \"complained\";\n items.push({\n key: `delivery:${r.id}`,\n kind: \"delivery\",\n siteName: site.name,\n title: complained ? \"Spam complaint on a sent report\" : \"A sent report bounced\",\n url: dashboardUrl(baseUrl, site.name),\n severity: complained ? \"critical\" : \"warning\",\n metric: 1,\n });\n }\n return items;\n}\n\n/**\n * One attention item per site carrying failing Renovate PRs, read from the\n * slice-2a-persisted `renovateFailingCis` field (the nightly github-signals sweep\n * populates it). PURE. Keyed `renovate:<siteId>` so the digest and the cockpit\n * share one diff key. `metric` is the count (a rising count diffs WORSE); severity\n * `warning`. Null/0 → skipped. A site whose `githubSignalsAt` is >3 days stale (or\n * null) is ALSO skipped — a repo that stopped being swept must not show a phantom\n * count forever (`now` injected, defaults to wall-clock).\n */\nexport function collectRenovateAlerts(\n sites: WebsiteRow[],\n baseUrl: string,\n now: Date = new Date(),\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n if (gitHubSignalsStale(s.githubSignalsAt, now)) continue;\n const n = s.renovateFailingCis ?? 0;\n if (n <= 0) continue;\n items.push({\n key: `renovate:${s.id}`,\n kind: \"renovate\",\n siteName: s.name,\n title: `${n} Renovate ${n === 1 ? \"PR\" : \"PRs\"} failing CI`,\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: n,\n });\n }\n return items;\n}\n\n/**\n * One attention item per site whose persisted default-branch CI rollup is\n * `failing` (slice 2a). PURE. `metric` 1 (binary); severity `warning`. Any other\n * state (passing/pending/none) or null is skipped. A site whose `githubSignalsAt`\n * is >3 days stale (or null) is ALSO skipped — a repo that stopped being swept must\n * not show a phantom 🔴 forever (`now` injected, defaults to wall-clock).\n */\nexport function collectCiAlerts(\n sites: WebsiteRow[],\n baseUrl: string,\n now: Date = new Date(),\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n if (gitHubSignalsStale(s.githubSignalsAt, now)) continue;\n if (s.defaultBranchCi !== \"failing\") continue;\n items.push({\n key: `ci:${s.id}`,\n kind: \"ci\",\n siteName: s.name,\n title: \"Default-branch CI failing\",\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: 1,\n });\n }\n return items;\n}\n\n/**\n * A soft-fail older than this is no longer a trustworthy CURRENT signal. Drafting\n * self-clears `analyticsSoftFailAt` on the next clean enrichment, so a non-null\n * value normally means \"errored on the most recent draft and hasn't recovered\" —\n * but a site that stopped being drafted (freq→None, deprecated) would otherwise\n * show a phantom forever. 45 days covers a monthly cadence + margin; older drops.\n */\nconst ANALYTICS_SOFT_FAIL_STALE_DAYS = 45;\n\n/**\n * One attention item per site whose last draft's GA/Search enrichment ERRORED, read\n * from the `analyticsSoftFailAt` timestamp (drafting sets it on a soft-fail, clears\n * it on a clean enrichment). PURE. Keyed `analytics:<siteId>` so the digest and the\n * cockpit share one diff key; `metric` 1 (binary), severity `warning`. A null\n * timestamp (clean, or the operator-added `Analytics soft-fail at` column absent) is\n * skipped, as is one staler than {@link ANALYTICS_SOFT_FAIL_STALE_DAYS}. On a\n * FLEET-WIDE subject outage many sites surface this at once — that breadth IS the\n * signal here; the report cron additionally emails a single concise fleet-wide alert\n * (see `assessAnalyticsAlert`). `now` injected, defaults to wall-clock.\n */\n/** A function-health sweep older than this can't confirm the CURRENT widget state.\n * The sweep is nightly, so 3 days (mirrors GITHUB_SIGNALS_STALE_DAYS) tolerates a\n * weekend of runner flakes without letting a months-old verdict drive an alarm. */\nconst TURNSTILE_WIDGET_STALE_DAYS = 3;\n\n/**\n * One CRITICAL attention item per site with `Require Turnstile` ON whose deployed\n * `/health` reports the Turnstile widget NOT configured (`turnstileWidget === \"fail\"`,\n * fresh per {@link TURNSTILE_WIDGET_STALE_DAYS}). That combination silently buckets\n * 100% of the site's real leads (token-less submissions escalate to spam_auto with\n * notify skipped) and the form-e2e probe cannot see it — testMode bypasses the gate —\n * so the operator's inbox just goes quiet. PURE. Keyed `turnstile:<siteId>`. Because\n * this is an AttentionItem it rides assignTier's items short-circuit, which sits ABOVE\n * the accepted-watch mute loop — an accept key can never silence it. A null verdict or\n * a stale sweep is NOT alarmed here; assignTier raises those as an acceptable\n * \"can't verify\" watch instead. `now` injected, defaults to wall-clock.\n */\nexport function collectTurnstileGuardrailAlerts(\n sites: WebsiteRow[],\n baseUrl: string,\n now: Date = new Date(),\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n if (!s.requireTurnstile || s.turnstileWidget !== \"fail\") continue;\n const at = s.functionHealthCheckedAt;\n if (at !== null) {\n const ageMs = now.getTime() - Date.parse(at);\n // Parseable and beyond the window → stale, downgraded to assignTier's watch.\n // Unparseable (NaN) keeps the item — never silently drop a real failure.\n if (Number.isFinite(ageMs) && ageMs > TURNSTILE_WIDGET_STALE_DAYS * MS_PER_DAY) continue;\n }\n items.push({\n key: `turnstile:${s.id}`,\n kind: \"turnstile\",\n siteName: s.name,\n title:\n \"Require Turnstile is ON but /health reports no widget — real leads are being auto-bucketed\",\n url: dashboardUrl(baseUrl, s.name),\n severity: \"critical\",\n metric: 1,\n });\n }\n return items;\n}\n\n/** Bounced lead notifications inside the window before a site alarms. One bounce can\n * be a transient greylist/full-mailbox blip; a repeat says the point-of-contact\n * address itself is bad (the Espada mode: apm@ bounced 4 of 8 with nothing alarming). */\nexport const NOTIFY_BOUNCE_THRESHOLD = 2;\n\n/** Window (days) the bounce count covers. Two weeks: long enough that a low-volume\n * site's second bounce still lands in the same window as its first, short enough\n * that a long-fixed address doesn't alarm forever (bounced rows never self-clear —\n * the alarm ages out as bounced submissions leave the window). */\nexport const NOTIFY_BOUNCE_WINDOW_DAYS = 14;\n\n/**\n * One CRITICAL attention item per site with >= {@link NOTIFY_BOUNCE_THRESHOLD} bounced\n * lead notifications in the last {@link NOTIFY_BOUNCE_WINDOW_DAYS} days — leads are\n * being captured but silently never reach the client, which is worse than no form at\n * all (notifyStatus \"sent\" only means Resend accepted the email; the resend-webhook\n * flips it to \"bounced\" when Resend later reports the failure, 2026-07-16). PURE:\n * takes the pre-fetched per-site counts (`countNotifyBouncedBySite`, keyed by the\n * Websites record id). Keyed `notify-bounce:<siteId>` so the digest and the cockpit\n * share one diff key; `metric` is the bounce count (a rising count diffs WORSE).\n * A site absent from the map (or below threshold) is skipped, as is a count for a\n * site id not in `sites` (orphan → never render a broken link).\n */\nexport function collectNotifyBounceAlerts(\n sites: WebsiteRow[],\n bouncedBySite: ReadonlyMap<string, number>,\n baseUrl: string,\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n const n = bouncedBySite.get(s.id) ?? 0;\n if (n < NOTIFY_BOUNCE_THRESHOLD) continue;\n items.push({\n key: `notify-bounce:${s.id}`,\n kind: \"notify-bounce\",\n siteName: s.name,\n title: `${n} lead notifications bounced (${NOTIFY_BOUNCE_WINDOW_DAYS}d) — check the point-of-contact address`,\n url: dashboardUrl(baseUrl, s.name),\n severity: \"critical\",\n metric: n,\n });\n }\n return items;\n}\n\nexport function collectAnalyticsFailures(\n sites: WebsiteRow[],\n baseUrl: string,\n now: Date = new Date(),\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n const at = s.analyticsSoftFailAt;\n if (at === null) continue;\n const ageMs = now.getTime() - Date.parse(at);\n // Unparseable timestamp (NaN) → keep the item (don't silently drop a real failure\n // on a parse glitch); only a parseable, beyond-window age is skipped as stale.\n if (Number.isFinite(ageMs) && ageMs > ANALYTICS_SOFT_FAIL_STALE_DAYS * MS_PER_DAY) continue;\n items.push({\n key: `analytics:${s.id}`,\n kind: \"analytics\",\n siteName: s.name,\n title: \"GA/Search enrichment failing (analytics blank)\",\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: 1,\n });\n }\n return items;\n}\n\n/** How current a `fail` / `unknown` must be to still CLAIM the fleet's present\n * state. The sweep is nightly, so 3 days (mirrors GITHUB_SIGNALS_STALE_DAYS)\n * tolerates a weekend of runner flakes without letting a months-old finding drive\n * a \"models diverge right now\" alarm. Past it the finding does not vanish — it\n * converts to the staleness item below, which claims nothing about the models. */\nconst PRISMIC_DRIFT_STALE_DAYS = 3;\n\n/** How long a `pass` may go unrefreshed before it is treated as unverified.\n *\n * Deliberately LONGER than the currency window, and the asymmetry is the point.\n * An old `fail` stops being reported as CURRENT drift at 3 days because it may\n * already be fixed. An old `pass` is a green claim nobody has re-established, and\n * escalating that at 3 days would light up the WHOLE fleet after a long weekend of\n * runner flakes — the noise that gets a real alarm muted. A week is the interval\n * over which a silently-dead nightly actually matters. */\nconst PRISMIC_STALE_PASS_DAYS = 7;\n\n/**\n * True when the nightly `prismic-models --fleet airtable` sweep is EXPECTED to\n * cover this site. Mirrors the Airtable inventory's own filter (src/inventory/\n * airtable.ts): live `maintenance` sites (active, not pre-launch) that carry a\n * `url` AND a Name that yields a slug. Deliberately duplicated rather than\n * imported — the inventory builds `Site` objects and needs a workdir; this is a\n * pure predicate over a row — but the two must stay in step: widen the inventory\n * and widen this. That is no longer left to memory: every shape of row is put\n * through BOTH implementations by tests/alerts/prismic-sweep-scope.test.ts, which\n * goes red the moment they diverge.\n *\n * THE SLUG CLAUSE IS NOT COSMETIC, and it was the first drift this pair produced.\n * The inventory drops an empty-slug row (`siteSlug(name) === \"\"`) with a warning,\n * because such a row can neither form a checkout path nor be matched back to its\n * Websites row on write-back — and `writeSweepToAirtable` joins by that same slug,\n * so even a verdict computed for it could never land. Without this clause a live\n * site named in a script with no `[a-z0-9]` (or with an empty Name) was covered\n * here and swept nowhere: the permanent, un-ackable morning email this predicate\n * exists to prevent, produced by the predicate itself.\n *\n * Only the STALENESS escalation consults it. A `fail`/`unknown` is a verdict some\n * run actually established and is reported wherever it came from; the staleness\n * item is an alarm invented FROM AN ABSENCE, and an absence is only wrong where a\n * sweep was owed. A deprecated site that left the inventory would otherwise carry\n * a frozen `pass` into the digest every morning forever — un-ackable (attention\n * items sit above the accepted-watch mute) and unfixable except by hand-clearing\n * an Airtable cell.\n */\nfunction prismicSweepCovers(s: WebsiteRow): boolean {\n return (\n s.status !== null &&\n ACTIVE_STATUSES.has(s.status) &&\n !isPreLaunch(s.status) &&\n s.url.length > 0 &&\n siteSlug(s.name).length > 0\n );\n}\n\n/**\n * One item per site whose nightly Prismic model verdict needs a human, from the\n * `prismic-models --fleet --write-airtable` sweep. PURE (`now` injected).\n *\n * The verdict is THREE-valued plus blank, and each state gets its own key so the\n * digest's snapshot diff (keyed on `key`) can never let one condition stand in for\n * another — a site sliding from drift to \"couldn't check\" re-news as NEW rather\n * than diffing \"standing\" against the drift it replaced (both carry `metric` 1):\n *\n * - `fail`, fresh → `prismic-drift:<siteId>` — repo and Prismic diverge.\n * - `unknown`, fresh → `prismic-unknown:<siteId>` — the check RAN AND COULD NOT\n * ANSWER (unreadable checkout, dead write token, unreachable Prismic). Its own\n * wording, because reporting a dead token as \"models diverge\" sends the\n * operator to fix a model when the job is to fix a secret.\n * - any verdict nobody has re-established → `prismic-stale:<siteId>` — a `pass`\n * older than {@link PRISMIC_STALE_PASS_DAYS} (or undateable), or a `fail` /\n * `unknown` older than {@link PRISMIC_DRIFT_STALE_DAYS}. A stale verdict is\n * never silence: dropping it would make \"nobody could evaluate this\" read\n * exactly like \"this is fine\", which is the failure this whole column exists\n * to close. Gated by {@link prismicSweepCovers}.\n * - blank (never swept, or not a Prismic site) → nothing, at any age. There is\n * no claim to un-verify.\n *\n * A `pass` inside its window is the ONLY silent verdict. At most one item per site\n * — the Airtable cell holds one state at a time.\n *\n * `warning`, not `critical`: on the cockpit ANY item already tiers the site 🔴, so\n * severity buys only (a) piercing the pre-launch mute and (b) sorting first in the\n * needs-you feed. `critical` is reserved for the guardrails that are actively\n * losing leads or breaking a live page (Turnstile, notify-bounce, delivery); a\n * model that drifted — or a check that could not run — is neither, and piercing\n * the pre-launch mute would alarm on exactly the sites the sweep excludes by\n * design.\n */\nexport function collectPrismicDriftAlerts(\n sites: WebsiteRow[],\n baseUrl: string,\n now: Date = new Date(),\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n const verdict = s.prismicModels;\n if (verdict === null) continue;\n\n const at = s.prismicModelsCheckedAt;\n // +Infinity when there is no timestamp, NaN when it won't parse — both mean\n // \"the age of this answer is unknowable\", which the two verdict families read\n // in OPPOSITE directions on purpose (see `unverified`).\n const ageMs = at === null ? Number.POSITIVE_INFINITY : now.getTime() - Date.parse(at);\n const ageKnown = Number.isFinite(ageMs);\n const windowDays = verdict === \"pass\" ? PRISMIC_STALE_PASS_DAYS : PRISMIC_DRIFT_STALE_DAYS;\n // An undateable `pass` is unverified — a green claim nobody can date is not a\n // green claim. An undateable `fail`/`unknown` is NOT downgraded: never silently\n // drop a real finding over a parse glitch.\n const unverified = ageKnown ? ageMs > windowDays * MS_PER_DAY : verdict === \"pass\";\n\n if (unverified) {\n if (!prismicSweepCovers(s)) continue;\n items.push({\n key: `prismic-stale:${s.id}`,\n kind: \"prismic-drift\",\n siteName: s.name,\n title: `Prismic model check has not run recently — the last verdict (\"${verdict}\") is unverified`,\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: 1,\n });\n continue;\n }\n\n if (verdict === \"pass\") continue;\n\n const first = s.prismicModelsDrift\n ?.split(\"\\n\")\n .find((l) => l.trim() !== \"\")\n ?.trim();\n if (verdict === \"unknown\") {\n items.push({\n key: `prismic-unknown:${s.id}`,\n kind: \"prismic-drift\",\n siteName: s.name,\n title: first\n ? `Prismic model check could not run — ${first}`\n : \"Prismic model check could not run\",\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: 1,\n });\n continue;\n }\n\n items.push({\n key: `prismic-drift:${s.id}`,\n kind: \"prismic-drift\",\n siteName: s.name,\n title: first\n ? `Prismic models diverge from the repo — ${first}`\n : \"Prismic models diverge from the repo\",\n url: dashboardUrl(baseUrl, s.name),\n severity: \"warning\",\n metric: 1,\n });\n }\n return items;\n}\n","// src/alerts/digest-state.ts\nimport type { FieldSet } from \"airtable\";\nimport type { AirtableBase } from \"../reports/airtable/client.js\";\nimport type { AttentionItem } from \"./attention.js\";\n\n/**\n * The persisted prior-run snapshot: stable item `key` → its last metric + the\n * date it was FIRST flagged. Lives as JSON in the single \"Digest State\" Airtable\n * row (the IO that loads/stores it — readDigestState/writeDigestState — is added\n * in component 2). `next` from diffAttention is what gets written back.\n * `exhausted` is carried only for vuln keys whose Renovate auto-fix has been\n * exhausted (absent = not exhausted; older snapshots without the field read the\n * same way).\n */\nexport type DigestSnapshot = Record<\n string,\n { metric: number; firstFlaggedAt: string; exhausted?: boolean }\n>;\n\n/**\n * PURE diff — the testable core of the hybrid \"snapshot now, mark what's new\".\n * For each current item vs the prior snapshot:\n * - key absent from prior → NEW (firstFlaggedAt = today)\n * - present and metric > prior.metric → WORSE (keep the original firstFlaggedAt)\n * - present and autoFixExhausted flipped on → WORSE (the count didn't move, but\n * \"Renovate gave up\" is an escalation — without this the digest's first mention\n * of a vuln, which is gated on exhaustion, would arrive unbadged)\n * - otherwise (equal or dropped) → STANDING (keep the original firstFlaggedAt)\n * `next` contains EXACTLY the current items' keys: resolved keys drop out, so a\n * fixed-then-recurring problem re-news correctly. Neither input is mutated.\n */\nexport function diffAttention(\n items: AttentionItem[],\n prior: DigestSnapshot,\n today: string,\n): { tagged: AttentionItem[]; next: DigestSnapshot } {\n const tagged: AttentionItem[] = [];\n const next: DigestSnapshot = {};\n for (const it of items) {\n const was = prior[it.key];\n const exhaustedFlip = it.autoFixExhausted === true && was?.exhausted !== true;\n let status: AttentionItem[\"status\"];\n let firstFlaggedAt: string;\n if (!was) {\n status = \"new\";\n firstFlaggedAt = today;\n } else if (it.metric > was.metric || exhaustedFlip) {\n status = \"worse\";\n firstFlaggedAt = was.firstFlaggedAt;\n } else {\n status = \"standing\";\n firstFlaggedAt = was.firstFlaggedAt;\n }\n tagged.push({ ...it, status });\n next[it.key] = {\n metric: it.metric,\n firstFlaggedAt,\n ...(it.autoFixExhausted === true ? { exhausted: true } : {}),\n };\n }\n return { tagged, next };\n}\n\n/** The single-row Airtable table that persists the prior digest snapshot. */\nexport const DIGEST_STATE_TABLE = \"Digest State\";\n\n/**\n * Read the persisted prior snapshot from the \"Digest State\" singleton.\n *\n * Reads the FIRST row of an unfiltered select (the table holds exactly one row;\n * the test fake does not evaluate filterByFormula, so we never rely on one). A\n * read miss (no row) OR a parse error (malformed Snapshot JSON) collapses to `{}`\n * — every key then reads as NEW once, which is safe degradation (never crashes\n * the digest).\n */\nexport async function readDigestState(base: AirtableBase): Promise<DigestSnapshot> {\n const rows: { id: string; fields: Record<string, unknown> }[] = [];\n await base(DIGEST_STATE_TABLE)\n .select({ maxRecords: 1, pageSize: 1 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push({ id: rec.id, fields: rec.fields });\n fetchNextPage();\n });\n const first = rows[0];\n if (!first) return {};\n const raw = first.fields[\"Snapshot\"];\n if (typeof raw !== \"string\") return {};\n try {\n return JSON.parse(raw) as DigestSnapshot;\n } catch {\n return {};\n }\n}\n\n/**\n * Persist the next snapshot to the \"Digest State\" singleton: get-or-create the\n * one row. If a row exists, UPDATE it (keyed by its record id); otherwise CREATE\n * one. `Snapshot` = JSON.stringify(snap); `Updated At` = the injected ISO\n * timestamp (or now). A caller that catches+logs a write failure keeps the\n * already-sent digest unaffected (next run re-news at worst).\n */\nexport async function writeDigestState(\n base: AirtableBase,\n snap: DigestSnapshot,\n updatedAt: string = new Date().toISOString(),\n): Promise<void> {\n const rows: { id: string }[] = [];\n await base(DIGEST_STATE_TABLE)\n .select({ maxRecords: 1, pageSize: 1 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push({ id: rec.id });\n fetchNextPage();\n });\n const fields: FieldSet = {\n Snapshot: JSON.stringify(snap),\n \"Updated At\": updatedAt,\n };\n const existing = rows[0];\n if (existing) {\n await base(DIGEST_STATE_TABLE).update([{ id: existing.id, fields }]);\n } else {\n await base(DIGEST_STATE_TABLE).create([{ fields }]);\n }\n}\n"],"mappings":";;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E,kBAAc;AAAA,EAChB,CAAC;AACH,QAAM,QAAQ,KAAK,CAAC;AACpB,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,QAAM,MAAM,MAAM,OAAO,UAAU;AACnC,MAAI,OAAO,QAAQ,SAAU,QAAO,CAAC;AACrC,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AASA,eAAsB,iBACpB,MACA,MACA,aAAoB,oBAAI,KAAK,GAAE,YAAY,GAC5B;AACf,QAAM,OAAyB,CAAC;AAChC,QAAM,KAAK,kBAAkB,EAC1B,OAAO,EAAE,YAAY,GAAG,UAAU,EAAE,CAAC,EACrC,SAAS,CAAC,SAAS,kBAAkB;AACpC,eAAW,OAAO,QAAS,MAAK,KAAK,EAAE,IAAI,IAAI,GAAG,CAAC;AACnD,kBAAc;AAAA,EAChB,CAAC;AACH,QAAM,SAAmB;AAAA,IACvB,UAAU,KAAK,UAAU,IAAI;AAAA,IAC7B,cAAc;AAAA,EAChB;AACA,QAAM,WAAW,KAAK,CAAC;AACvB,MAAI,UAAU;AACZ,UAAM,KAAK,kBAAkB,EAAE,OAAO,CAAC,EAAE,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC;AAAA,EACrE,OAAO;AACL,UAAM,KAAK,kBAAkB,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;AAAA,EACpD;AACF;","names":[]}
@@ -11,7 +11,7 @@ import {
11
11
  } from "./chunk-OTGB6YQO.js";
12
12
  import {
13
13
  defaultSpawn
14
- } from "./chunk-HVOOCK6L.js";
14
+ } from "./chunk-4DHQCN5H.js";
15
15
 
16
16
  // src/recipes/svelte-5/index.ts
17
17
  import { join as join5 } from "path";
@@ -243,4 +243,4 @@ async function upgradeSvelte4to5(site, opts = {}) {
243
243
  export {
244
244
  upgradeSvelte4to5
245
245
  };
246
- //# sourceMappingURL=chunk-B5ZUQZFL.js.map
246
+ //# sourceMappingURL=chunk-ICXV25N7.js.map
@@ -21,7 +21,7 @@ import {
21
21
  import {
22
22
  siteSlug,
23
23
  updateAnalyticsHealth
24
- } from "./chunk-GXVX4HUH.js";
24
+ } from "./chunk-CLWNAMUX.js";
25
25
  import {
26
26
  defaultCredentialsPath
27
27
  } from "./chunk-6VAL7XJT.js";
@@ -523,8 +523,9 @@ async function draftReportForSite(base, siteRow, reportType, options = {}) {
523
523
  const periodEnd = today;
524
524
  const completedOn = today;
525
525
  const lastTestedDate = reportType === "Maintenance" && siteRow.lastLighthouseAuditAt ? new Date(siteRow.lastLighthouseAuditAt) : null;
526
- const gaResult = base !== null ? await fetchGaUsers(siteRow, periodStart, periodEnd) : NO_ENRICHMENT;
527
- const searchResult = base !== null ? await fetchSearch(siteRow, periodStart, periodEnd) : (
526
+ const shouldEnrich = options.enrich ?? base !== null;
527
+ const gaResult = shouldEnrich ? await fetchGaUsers(siteRow, periodStart, periodEnd) : NO_ENRICHMENT;
528
+ const searchResult = shouldEnrich ? await fetchSearch(siteRow, periodStart, periodEnd) : (
528
529
  // No-IO render path: nothing was attempted, so this is not an environment gap
529
530
  // (`notConfigured` would wrongly tell the operator to go wire a secret).
530
531
  {
@@ -727,4 +728,4 @@ export {
727
728
  fetchGaUsers,
728
729
  fetchSearch
729
730
  };
730
- //# sourceMappingURL=chunk-6M2IXJ3E.js.map
731
+ //# sourceMappingURL=chunk-JVWJJ36K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/reports/ga/config.ts","../src/reports/draft.ts","../src/reports/auto-tick.ts","../src/reports/ga/client.ts","../src/reports/ga/failover.ts","../src/reports/search/client.ts"],"sourcesContent":["import { dirname, join } from \"node:path\";\nimport { defaultCredentialsPath } from \"../../util/credentials.js\";\n\nexport type GaConfig = {\n /** Workspace users the service account impersonates (domain-wide delegation), in\n * failover order — the first subject that authenticates wins. */\n subjects: string[];\n /** Absolute path to the service-account JSON key file. */\n keyPath: string;\n};\n\n/**\n * Read GA configuration from the environment (credentials.env is already loaded into\n * process.env by the CLI entrypoint). Returns null when `GA_SUBJECT` is unset/blank — the\n * signal that GA enrichment is simply not configured, so drafting skips it silently.\n *\n * `GA_SUBJECT` is a comma-separated list of impersonation subjects tried in order\n * (e.g. `reports@reddoorla.com,person@reddoorla.com`), so losing one Workspace account\n * degrades to a logged failover instead of blanking the whole fleet's analytics; a single\n * address remains the degenerate one-element case. Entries are trimmed, empties dropped.\n *\n * `GA_SA_KEY_PATH` is optional; it defaults to `ga-service-account.json` alongside the\n * credentials file (e.g. ~/.config/reddoor-maint/), keeping the key out of the repo.\n */\nexport function readGaConfig(): GaConfig | null {\n const subjects = (process.env.GA_SUBJECT ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n if (subjects.length === 0) return null;\n const keyPath =\n process.env.GA_SA_KEY_PATH?.trim() ||\n join(dirname(defaultCredentialsPath()), \"ga-service-account.json\");\n return { subjects, keyPath };\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { ReportType, LighthouseScores } from \"./types.js\";\nimport { renderReportHtml } from \"./render.js\";\nimport { siteSlug, updateAnalyticsHealth } from \"./airtable/websites.js\";\nimport { resolveCopy } from \"./copy.js\";\nimport type { WebsiteRow } from \"./airtable/websites.js\";\nimport type { ReportRow } from \"./airtable/reports.js\";\nimport { createDraft, listReportsForSite } from \"./airtable/reports.js\";\nimport { queueDraft } from \"./queue.js\";\nimport { autoTickChecklist } from \"./auto-tick.js\";\nimport { uploadAttachment } from \"./airtable/attachments.js\";\nimport type { AirtableBase } from \"./airtable/client.js\";\nimport { readGaConfig } from \"./ga/config.js\";\nimport { fetchPeriodUsers } from \"./ga/client.js\";\nimport { fetchSearchPresence } from \"./search/client.js\";\nimport type { SearchPresence } from \"./search/client.js\";\nimport { generateHeaderImage } from \"./header-image/index.js\";\nimport type { GeneratedHeaderImage } from \"./header-image/index.js\";\n\nexport type RefreshHeaderDeps = {\n generate?: (input: { url: string; slug?: string }) => Promise<GeneratedHeaderImage>;\n upload?: (\n recordId: string,\n field: string,\n bytes: Uint8Array,\n filename: string,\n contentType: string,\n ) => Promise<void>;\n};\n\n/**\n * Regenerate a site's Header image from its live homepage so the report ships a\n * current screenshot rather than one frozen whenever the image was last made by\n * hand. Sonder alone runs 16 reports a year, so a static header goes visibly\n * stale.\n *\n * BEST-EFFORT BY DESIGN — returns false and never throws. A capture or upload\n * failure must not fail the draft: the stored image is still perfectly usable,\n * and the operator reviews the rendered preview before approving the send.\n */\nexport async function refreshHeaderImage(\n site: WebsiteRow,\n deps: RefreshHeaderDeps = {},\n): Promise<boolean> {\n if (!site.url) return false;\n const generate = deps.generate ?? generateHeaderImage;\n const upload = deps.upload ?? uploadAttachment;\n try {\n const gen = await generate({ url: site.url, slug: siteSlug(site.name) });\n await upload(site.id, \"Header image\", gen.bytes, gen.filename, gen.contentType);\n return true;\n } catch (err) {\n console.warn(\n `⚠ header-image refresh skipped for ${site.name}: ${\n err instanceof Error ? err.message : String(err)\n } — keeping the stored image`,\n );\n return false;\n }\n}\n\nexport type DraftOptions = {\n /** Where to write the local preview HTML when `previewOnly`. Defaults to `reports/<slug>/draft.html`. */\n previewPath?: string;\n /** If true: render locally only, never touch Airtable. */\n previewOnly?: boolean;\n /** Whether to run the GA / Search Console enrichment fetches. Defaults to\n * `base !== null`, i.e. the real drafting path enriches and a preview does not.\n *\n * This exists because `base === null` was carrying two unrelated meanings —\n * \"never write to Airtable\" AND \"perform no IO at all\" — and only the first is\n * what `previewOnly` actually asks for. Enrichment reads Google; it writes\n * nothing, so there is no reason a preview cannot do it on request. Conflating\n * the two made the preview path structurally incapable of ever producing an\n * ANALYTICS section, which in turn made a CI job built to prove the GA secrets\n * fail 100% of the time and report it as a credential outage (2026-08-12). Set\n * this true to render a preview that exercises the credentials for real. */\n enrich?: boolean;\n /** UTC \"YYYY-MM\" recurrence key; falls back to periodEnd's month when omitted. */\n period?: string;\n /** Airtable record id of an EXISTING (not-ready) row to COMPLETE in place rather\n * than creating a new one. When set, we skip createDraft and only re-render →\n * upload the HTML attachment → flip Draft ready on this row. Used by the --due\n * re-draft path to finish a draft whose createDraft succeeded but whose\n * setDraftReady never ran (a crash mid-sequence wedged the period). */\n completeRowId?: string;\n /** The mapped ReportRow being completed, returned as `reportRow` from the\n * complete path so callers keep the same shape they get on the create path. */\n existingRow?: ReportRow;\n /** Injected deps for the draft-time header refresh, or `false` to skip it\n * entirely. Tests set `false` (or a stub) so a unit suite never launches a\n * browser or resolves DNS. Production leaves it unset and gets the real thing. */\n refreshHeader?: RefreshHeaderDeps | false;\n};\n\n/** An enrichment fetch that *errored* (not one that was legitimately skipped\n * because it isn't configured / the site lacks the inputs). Surfaced so a\n * fleet-wide GA/Search outage is visible in a `--due` batch summary instead of\n * hiding behind one easily-missed console.warn per site. */\nexport type SoftFailure = \"ga\" | \"search\";\n\nexport type DraftResult = {\n /** null when previewOnly. */\n reportRow: ReportRow | null;\n /** Path to the local preview file (only set when previewOnly). */\n htmlPath: string | null;\n /** Always present — the rendered HTML string. */\n html: string;\n /** Enrichment fetches that errored for this site (empty on success or skip). */\n softFailures: SoftFailure[];\n /** True when search enrichment fell back to the site name (no explicit `Search query`)\n * AND that default matched nothing in Search Console — the signal that this site needs\n * a hand-tuned brand query. Distinct from a soft-failure/outage: the fetch succeeded, it\n * just found no data for the name. Requires a property to have RESOLVED — a site with no\n * Search Console property at all raises `searchPropertyMissing` instead (a query change\n * can't fix that, and prescribing one would silence the real problem). */\n searchDefaultMissed: boolean;\n /** True when NO Search Console property matched the site for any subject — a\n * missing/unverified property or lost service-account access. Fires for BOTH explicit\n * and name-default queries (unlike `searchDefaultMissed`), because no query can succeed\n * without a property. Distinct from a soft-failure: the API worked, the property list\n * just contained nothing for this site. */\n searchPropertyMissing: boolean;\n /** Whether the draft was placed in the approve queue. False when a higher-or-equal-tier\n * report is already queued for the site (single-queue rule); null on the previewOnly path. */\n queued: boolean | null;\n /** Ids of lower-tier queued reports this draft superseded (un-queued). */\n supersededIds: string[];\n};\n\nfunction scoresFromWebsite(siteRow: WebsiteRow): LighthouseScores {\n const { pScore, rScore, bpScore, seoScore } = siteRow;\n if (pScore === null || rScore === null || bpScore === null || seoScore === null) {\n throw new Error(\n `Site '${siteRow.name}' is missing one or more Lighthouse scores on the Websites row (pScore, rScore, bpScore, seoScore). ` +\n `Run 'reddoor-maint audit lighthouse' from the site's checkout and paste the four numbers into Airtable, then retry.`,\n );\n }\n return { performance: pScore, accessibility: rScore, bestPractices: bpScore, seo: seoScore };\n}\n\nfunction daysAgo(today: Date, n: number): Date {\n // UTC accessors to stay TZ-consistent with `due.ts` (and avoid landing\n // Airtable's `Period start` on a different calendar day than the operator\n // expects on late-night runs near a month boundary). See morning brief\n // 2026-05-29 (M1) for context.\n const out = new Date(today);\n out.setUTCDate(out.getUTCDate() - n);\n return out;\n}\n\n/**\n * Render and create an Airtable draft for one site.\n *\n * No idempotency guard here — the recurrence guard lives in draftDueReports\n * (cli/commands/report.ts), keyed on reportPeriodKey(dueDate). The manual\n * single-site path intentionally always drafts (an operator asking for a draft\n * gets one). findReportByPeriod (airtable/reports.ts) is the real-Airtable\n * point lookup available to dashboard/digest callers that need the same\n * idempotency guarantee outside the CLI batch loop.\n */\nexport async function draftReportForSite(\n base: AirtableBase | null,\n siteRow: WebsiteRow,\n reportType: ReportType,\n options: DraftOptions = {},\n): Promise<DraftResult> {\n const scores = scoresFromWebsite(siteRow);\n\n const today = new Date();\n const slug = siteSlug(siteRow.name);\n\n const periodStart =\n base !== null ? await derivePeriodStart(base, siteRow, reportType, today) : daysAgo(today, 30);\n\n const periodEnd = today;\n const completedOn = today;\n // \"Last Tested\" on the Maintenance email is the REAL timestamp of the most recent automated\n // Lighthouse audit — stamped live on the Websites row (`Last lighthouse audit at`) by\n // `audit lighthouse --write-airtable` every time the scores refresh. It is deliberately NOT\n // the `testing day` field: that's the recurrence anchor consumed by due.ts and is hand-set, so\n // it goes stale. Reading the audit timestamp keeps the date current with no manual upkeep.\n const lastTestedDate =\n reportType === \"Maintenance\" && siteRow.lastLighthouseAuditAt\n ? new Date(siteRow.lastLighthouseAuditAt)\n : null;\n\n // GA enrichment. Soft-fail: any GA problem leaves the numbers null so\n // the draft still proceeds (operator fills them manually) — GA is an enhancement, not a\n // gate. Rendered with the fetched numbers so the review HTML matches the Airtable fields.\n // An *error* (vs a legitimate not-configured skip) is recorded in softFailures so the\n // caller can surface a fleet-wide outage in the batch summary.\n // Enrichment is gated on `enrich`, NOT on `base`: reading Google and writing to\n // Airtable are independent, and only the write is what previewOnly forbids.\n const shouldEnrich = options.enrich ?? base !== null;\n const gaResult = shouldEnrich\n ? await fetchGaUsers(siteRow, periodStart, periodEnd)\n : NO_ENRICHMENT;\n const searchResult = shouldEnrich\n ? await fetchSearch(siteRow, periodStart, periodEnd)\n : // No-IO render path: nothing was attempted, so this is not an environment gap\n // (`notConfigured` would wrongly tell the operator to go wire a secret).\n {\n ...NO_ENRICHMENT,\n defaultQueryMissed: false,\n propertyMissing: false,\n notConfigured: false,\n };\n const gaUsers = gaResult.value;\n const search = searchResult.value;\n const softFailures: SoftFailure[] = [\n ...(gaResult.softFailed ? ([\"ga\"] as const) : []),\n ...(searchResult.softFailed ? ([\"search\"] as const) : []),\n ];\n\n // Header-image refresh (real path only). Regenerated BEFORE the render so the\n // preview the operator approves carries the same screenshot the client will\n // receive — the send reads this attachment off the Websites row. Gated on\n // `base !== null` exactly like the GA/Search enrichment above: the no-IO render\n // path (base === null, used for pure rendering and tests) must not launch a\n // browser or write to production Airtable. `refreshHeader: false` is the second\n // gate, for suites that DO pass a fake base and would otherwise pay a real\n // chromium launch per case. Production leaves it unset and gets the real\n // refresh. Best-effort — see refreshHeaderImage.\n if (base !== null && options.refreshHeader !== false) {\n await refreshHeaderImage(siteRow, options.refreshHeader ?? {});\n }\n\n const cidName = `${slug}-header`;\n const { html } = await renderReportHtml({\n siteName: siteRow.name,\n siteUrl: siteRow.url,\n reportType,\n completedOn,\n lighthouse: scores,\n gaUsersCurrent: gaUsers?.current,\n gaUsersPrevious: gaUsers?.previous,\n searchPosition: search?.foundOnPage1 ? (search.position ?? undefined) : undefined,\n lastTestedDate,\n commentary: null,\n copy: resolveCopy(siteRow),\n headerImageCid: cidName,\n });\n\n if (options.previewOnly) {\n const path = options.previewPath ?? `reports/${slug}/draft.html`;\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, html, \"utf-8\");\n return {\n reportRow: null,\n htmlPath: path,\n html,\n softFailures,\n searchDefaultMissed: searchResult.defaultQueryMissed,\n searchPropertyMissing: searchResult.propertyMissing,\n queued: null,\n supersededIds: [],\n };\n }\n\n if (base === null) throw new Error(\"base required when previewOnly=false\");\n\n // Record this site's GA/Search enrichment health for the per-site analytics-failure\n // signal (cockpit/digest). Only when analytics is configured for THIS site — set the\n // timestamp on a soft-fail, clear it (null) on a clean enrichment so the signal\n // self-heals. Best-effort: the `Analytics soft-fail at` column is operator-added, so\n // until it exists the write throws UNKNOWN_FIELD_NAME — which must NOT break drafting.\n if (readGaConfig() !== null && Boolean(siteRow.ga4PropertyId || siteRow.searchQuery)) {\n try {\n await updateAnalyticsHealth(\n base,\n siteRow.id,\n softFailures.length > 0 ? today.toISOString() : null,\n );\n } catch (e) {\n console.warn(`⚠ analytics-health write skipped for ${siteRow.name}: ${(e as Error).message}`);\n }\n }\n\n // \"Finish an existing row\" path (the --due re-draft wedge fix). When the caller\n // hands us a row that was created but never made Draft-ready — a crash between\n // createDraft and setDraftReady leaves exactly this — we DON'T createDraft again\n // (that would duplicate the period). We re-attach the rendered HTML and queue the\n // EXISTING row, completing the half-made draft in place. The row's other fields\n // (scores, period, dates) were already written at create time; the only pieces a\n // crash drops are the attachment + the ready flag.\n if (options.completeRowId) {\n await uploadDraftHtml(options.completeRowId, slug, periodEnd, html);\n const outcome = await queueDraft(base, {\n id: options.completeRowId,\n siteId: siteRow.id,\n reportType,\n });\n return {\n reportRow: options.existingRow ?? null,\n htmlPath: null,\n html,\n softFailures,\n searchDefaultMissed: searchResult.defaultQueryMissed,\n searchPropertyMissing: searchResult.propertyMissing,\n queued: outcome.queued,\n supersededIds: outcome.supersededIds,\n };\n }\n\n // Auto-tick the checklist boxes the system can prove (Phase 1: Google Indexed via the\n // inline search signal). Fail-safe lives in autoTickChecklist: only `pass` entries are ticked;\n // the evidence snapshot drives the dashboard's green/amber badges. The operator's approve gate\n // and per-box override are unchanged.\n const evidence = autoTickChecklist(siteRow, reportType, completedOn, { search: searchResult });\n const checklistTicks = [...evidence.entries()]\n .filter(([, e]) => e.result === \"pass\")\n .map(([field]) => field);\n const autoEvidence = Object.fromEntries(evidence);\n\n const reportId = `${siteRow.name} — ${reportType} — ${periodEnd.toISOString().slice(0, 10)}`;\n const created = await createDraft(base, {\n reportId,\n siteId: siteRow.id,\n reportType,\n period: options.period ?? periodEnd.toISOString().slice(0, 7),\n periodStart,\n periodEnd,\n completedOn,\n lighthouse: scores,\n lastTestedDate,\n ...(gaUsers ? { gaUsersCurrent: gaUsers.current, gaUsersPrevious: gaUsers.previous } : {}),\n ...(search ? { searchFoundPage1: search.foundOnPage1 } : {}),\n ...(search?.foundOnPage1 && search.position !== null\n ? { searchPosition: search.position }\n : {}),\n checklistTicks,\n autoEvidence,\n });\n\n await uploadDraftHtml(created.id, slug, periodEnd, html);\n const outcome = await queueDraft(base, {\n id: created.id,\n siteId: siteRow.id,\n reportType,\n });\n\n return {\n reportRow: created,\n htmlPath: null,\n html,\n softFailures,\n searchDefaultMissed: searchResult.defaultQueryMissed,\n searchPropertyMissing: searchResult.propertyMissing,\n queued: outcome.queued,\n supersededIds: outcome.supersededIds,\n };\n}\n\n/** Attach the rendered HTML to a Reports row. Queueing (Draft ready + the single-queue\n * reconciliation) is handled separately by queueDraft so both the create path and the\n * \"complete a half-made row\" path share the identical, re-runnable upload step. */\nasync function uploadDraftHtml(\n rowId: string,\n slug: string,\n periodEnd: Date,\n html: string,\n): Promise<void> {\n const htmlFilename = `${slug}-${periodEnd.toISOString().slice(0, 10)}.html`;\n await uploadAttachment(rowId, \"Rendered HTML\", html, htmlFilename, \"text/html\");\n}\n\n/** Result of an enrichment fetch: the value (null if unavailable) plus whether\n * it errored (`softFailed`) as opposed to being legitimately not-configured. */\ntype Enrichment<T> = { value: T | null; softFailed: boolean };\n/** A not-configured / skipped enrichment — null value, not a soft-failure. */\nconst NO_ENRICHMENT: Enrichment<never> = { value: null, softFailed: false };\n\n/**\n * Fetch GA \"Users\" for the period, soft-failing to null. Returns a null value (no enrichment)\n * when GA isn't configured (`GA_SUBJECT` unset) or the site has no GA4 property ID — those are\n * legitimate skips, `softFailed: false`. When the GA API errors it logs a one-line warning and\n * returns `softFailed: true`. Never throws, so a GA problem can never block a draft; the\n * operator can always enter the numbers by hand.\n */\nexport async function fetchGaUsers(\n siteRow: WebsiteRow,\n periodStart: Date,\n periodEnd: Date,\n): Promise<Enrichment<{ current: number; previous: number }>> {\n const cfg = readGaConfig();\n if (!cfg || !siteRow.ga4PropertyId) return NO_ENRICHMENT;\n try {\n const value = await fetchPeriodUsers(\n { propertyId: siteRow.ga4PropertyId, subjects: cfg.subjects, keyPath: cfg.keyPath },\n periodStart,\n periodEnd,\n );\n return { value, softFailed: false };\n } catch (e) {\n console.warn(`⚠ GA skipped for ${siteRow.name}: ${(e as Error).message}`);\n return { value: null, softFailed: true };\n }\n}\n\n/** A search enrichment, plus the two distinct miss flags (see `fetchSearch` /\n * `DraftResult.searchDefaultMissed` / `DraftResult.searchPropertyMissing`) and the\n * environment-gap flag `notConfigured`. */\ntype SearchEnrichment = Enrichment<SearchPresence> & {\n defaultQueryMissed: boolean;\n propertyMissing: boolean;\n /** True when the site IS analytics-enrolled but this environment has no GA/SC\n * credentials (`GA_SUBJECT` unset) — so the check could not run at all. Distinct\n * from the un-enrolled skip (nothing to measure) and from a soft-fail (the API\n * errored). See {@link fetchSearch}. */\n notConfigured: boolean;\n};\n\n/**\n * Fetch the site's Google search presence for the period, soft-failing to null. Runs whenever\n * GA/SA is configured (`readGaConfig()` non-null — search shares the SA credentials) AND the\n * site is analytics-enrolled (has a `ga4PropertyId` OR an explicit `searchQuery`); otherwise a\n * legitimate skip (null value, `softFailed: false`). The brand query defaults to the site NAME\n * when no explicit `searchQuery` is set (whitespace-only counts as unset) — so brand presence is\n * tracked automatically, and the operator only hand-tunes the handful of sites the name misses.\n *\n * `propertyMissing` is true when NO Search Console property matched the site for any subject\n * (missing/unverified property or lost SA access) — flagged for BOTH explicit and name-default\n * queries, because no query can fix a missing property. Pre-split, this case was folded into\n * `defaultQueryMissed`, whose \"set an explicit Search query\" remedy would permanently SILENCE\n * it (an explicit query that finds nothing is by design never flagged).\n *\n * `defaultQueryMissed` is true ONLY when a property resolved, the site-name default was used,\n * AND Search Console returned no data for it (`position === null`) — the signal to set an\n * explicit `Search query`. It is false for an explicit query (even one that finds nothing —\n * that's a valid measurement), a default that does find a position, the not-enrolled skip,\n * and the errored soft-fail path.\n *\n * `notConfigured` splits the old single skip in two. An un-enrolled site is a true skip —\n * there is nothing to measure, and the checklist row stays manual. But an ENROLLED site in an\n * environment with no credentials is an environment gap: the check was supposed to run and\n * couldn't. Collapsing the two made a credential-less run (exactly what the daily-reports\n * workflow was) indistinguishable from \"this site opted out\", so the Google Indexed row\n * silently vanished from every drafted report instead of saying why.\n *\n * When the Search Console API errors it logs a one-line warning and returns `softFailed: true`.\n * Never throws, so a search problem can never block a draft.\n */\nexport async function fetchSearch(\n siteRow: WebsiteRow,\n periodStart: Date,\n periodEnd: Date,\n): Promise<SearchEnrichment> {\n const cfg = readGaConfig();\n const enrolled = Boolean(siteRow.ga4PropertyId || siteRow.searchQuery);\n if (!cfg || !enrolled) {\n const notConfigured = enrolled && !cfg;\n if (notConfigured) {\n console.warn(\n `⚑ Search: no GA/Search Console credentials in this environment (GA_SUBJECT unset) — the Google Indexed check could not run for ${siteRow.name}.`,\n );\n }\n return { ...NO_ENRICHMENT, defaultQueryMissed: false, propertyMissing: false, notConfigured };\n }\n const explicit = siteRow.searchQuery?.trim();\n const query = explicit || siteRow.name;\n const usedDefault = !explicit;\n try {\n const value = await fetchSearchPresence(\n {\n keyPath: cfg.keyPath,\n subjects: cfg.subjects,\n property: siteRow.searchConsoleProperty ?? undefined,\n host: siteRow.url,\n query,\n },\n periodStart,\n periodEnd,\n );\n const propertyMissing = !value.propertyFound;\n if (propertyMissing) {\n console.warn(\n `⚑ Search: no Search Console property matched ${siteRow.url} for ${siteRow.name} — verify the domain property exists and the service account has access. (A \"Search query\" change cannot fix this.)`,\n );\n }\n const defaultQueryMissed = value.propertyFound && usedDefault && value.position === null;\n if (defaultQueryMissed) {\n console.warn(\n `⚑ Search: site-name default \"${query}\" found no Search Console data for ${siteRow.name} — set an explicit \"Search query\" in Airtable to track brand presence.`,\n );\n }\n return { value, softFailed: false, defaultQueryMissed, propertyMissing, notConfigured: false };\n } catch (e) {\n console.warn(`⚠ Search presence skipped for ${siteRow.name}: ${(e as Error).message}`);\n return {\n value: null,\n softFailed: true,\n defaultQueryMissed: false,\n propertyMissing: false,\n notConfigured: false,\n };\n }\n}\n\nasync function derivePeriodStart(\n base: AirtableBase,\n siteRow: WebsiteRow,\n reportType: ReportType,\n today: Date,\n): Promise<Date> {\n const prior = await listReportsForSite(base, siteRow.id);\n const sameType = prior\n .filter((r) => r.reportType === reportType && r.periodEnd)\n .map((r) => r.periodEnd!)\n .sort();\n const latest = sameType[sameType.length - 1];\n if (!latest) return daysAgo(today, 30);\n // Half-open periods. The prior report's GA/Search windows are inclusive of its\n // periodEnd, so starting this report on the *same* day double-counts that\n // boundary day across two consecutive reports (and inflates the headline Users\n // count). Start the next day instead. UTC to stay TZ-consistent with daysAgo.\n const start = new Date(latest);\n start.setUTCDate(start.getUTCDate() + 1);\n return start;\n}\n","import type { ReportType } from \"./types.js\";\nimport type { WebsiteRow } from \"./airtable/websites.js\";\nimport type { SearchPresence } from \"./search/client.js\";\nimport { checklistFor, gatingFields } from \"./checklist.js\";\nimport { isNetlifyAppUrl } from \"../util/url.js\";\n\n/** A persisted audit signal is only trusted within this window — a stale \"pass\" degrades to\n * \"unknown\" (no tick). Matches the github-signals staleness convention (~3 days). */\nconst STALE_DAYS = 3;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/** True when `checkedAt` is a valid timestamp within STALE_DAYS of `now`. */\nfunction isFresh(checkedAt: string | null, now: Date): boolean {\n if (!checkedAt) return false;\n const t = new Date(checkedAt).getTime();\n if (Number.isNaN(t)) return false;\n return now.getTime() - t <= STALE_DAYS * MS_PER_DAY;\n}\n\n/** Cert-expiry buffer: a cert must have MORE than this many days left to pass (renew window).\n * Exactly 14 days does NOT pass — matches the spec's strict \">14 days\" and the domain audit's\n * own `> 14` pass status, so the two thresholds can't drift. */\nconst CERT_MIN_DAYS = 14;\n\n/** A single auto-check outcome. `pass` + fresh ⇒ the caller ticks the box. */\nexport type EvidenceResult = \"pass\" | \"fail\" | \"unknown\" | \"n/a\";\nexport type EvidenceRecord = { result: EvidenceResult; checkedAt: string | null; note: string };\n\n/**\n * Inline signals fetched during the draft. Phase 1 carries Search Console only; Phase 2/3 read\n * the remaining signals (security, domain, browser) off the Websites row passed as `site`.\n */\nexport type AutoTickSignals = {\n search: {\n value: SearchPresence | null;\n softFailed: boolean;\n /** The site is analytics-enrolled but this environment has no GA/Search Console\n * credentials, so the check could not run. Kept distinct from the un-enrolled skip\n * (`value: null`, this false) so the evidence can name the environment gap instead\n * of disappearing. */\n notConfigured: boolean;\n };\n};\n\n/**\n * Decide, per checklist item for this report type, an evidence record. PURE. The fail-safe\n * invariant lives here: a box is only tickable when `result === \"pass\"`. Google Indexed is an\n * inline signal (fetched at draft), so its evidence is inherently fresh (`checkedAt = now`).\n *\n * The semantic inversion: every GATING item for this report type gets a status even with no\n * signal — a never-measured gating item resolves to `unknown` (which blocks the send gate), not\n * an omission the caller could read as \"manual/OK\". Only non-gating (advisory) items keep the old\n * omit-when-absent behavior, so an unconfigured advisory check stays silently manual.\n */\nexport function autoTickChecklist(\n site: WebsiteRow,\n reportType: ReportType,\n now: Date,\n signals: AutoTickSignals,\n): Map<string, EvidenceRecord> {\n const out = new Map<string, EvidenceRecord>();\n const gating = new Set(gatingFields(reportType));\n\n for (const item of checklistFor(reportType)) {\n let ev: EvidenceRecord | null;\n switch (item.field) {\n case \"Maint: Google Indexed\":\n ev = googleEvidence(now, signals.search);\n break;\n case \"Maint: Deploy & Function Health\":\n ev = deployEvidence(site, now);\n break;\n case \"Maint: CMS Checked\":\n ev = cmsEvidence(site, now);\n break;\n case \"Maint: Domain, DNS & SSL\":\n ev = domainEvidence(site, now);\n break;\n case \"Maint: Security Updates\":\n ev = securityEvidence(site, now);\n break;\n case \"Maint: Uptime Checked\":\n ev = uptimeEvidence(site, now);\n break;\n case \"Test: Desktop Browsers\":\n ev = browserEvidence(\n site.crossbrowserOk,\n site,\n now,\n \"Desktop renders cleanly\",\n \"render errors\",\n );\n break;\n case \"Test: Mobile Browsers\":\n ev = browserEvidence(site.mobileOk, site, now, \"Mobile renders cleanly\", \"overflow/errors\");\n break;\n case \"Test: Page Titles & Meta\":\n ev = titlesEvidence(site, now);\n break;\n case \"Test: Links & Navigation\": {\n const broken = site.brokenLinks;\n const failNote = broken && broken > 0 ? `${broken} broken link(s)` : \"broken links / nav\";\n ev = browserEvidence(site.linksOk, site, now, \"All internal links resolve\", failNote);\n break;\n }\n case \"Test: Form Functionality\":\n ev = formsEvidence(site, now);\n break;\n case \"Test: Interactions & Animations\":\n ev = interactionsEvidence(site, now);\n break;\n case \"Test: Verified After Updates\":\n ev = updatesEvidence(site, now);\n break;\n default:\n ev = null;\n }\n // The semantic inversion: a GATING item with no fresh signal must still carry a status —\n // `unknown` (blocks) — so an unwired/absent signal can never leave the gate silently\n // passable. Advisory items (e.g. Google Indexed on a Maintenance report) keep the old\n // omit-when-absent behavior.\n if (ev === null && gating.has(item.field)) {\n ev = { result: \"unknown\", checkedAt: null, note: \"Not yet measured\" };\n }\n if (ev !== null) out.set(item.field, ev);\n }\n\n return out;\n}\n\n/** One browser-audit verdict (Desktop/Mobile/Links) → evidence, gated on `Browser checked at`\n * freshness. null verdict (never run) → omit (manual); stale → unknown; true → pass; false →\n * fail (with the failure note). The verdict itself was computed by the audit (summarizeBrowser). */\nfunction browserEvidence(\n ok: boolean | null,\n site: WebsiteRow,\n now: Date,\n passNote: string,\n failNote: string,\n): EvidenceRecord | null {\n if (ok === null || !site.browserCheckedAt) return null;\n const at = site.browserCheckedAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Browser check is stale (>3d)\" };\n }\n return ok\n ? { result: \"pass\", checkedAt: at, note: passNote }\n : { result: \"fail\", checkedAt: at, note: failNote };\n}\n\n/**\n * Security Updates evidence from the persisted `security` audit. Omits (→ manual) when the audit\n * never ran (counts null / no timestamp); stale → unknown; 0 critical AND 0 high → pass; any\n * critical/high → fail (with the count). Honest scope: \"no known critical/high advisories in the\n * declared dependencies as of the last audit\" — moderate/low are advisory, not gating, and this\n * does not prove the fix is deployed.\n */\nfunction securityEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n const crit = site.securityVulnsCritical;\n const high = site.securityVulnsHigh;\n if (crit === null || high === null || !site.lastSecurityAuditAt) return null;\n const at = site.lastSecurityAuditAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Security audit is stale (>3d)\" };\n }\n if (crit === 0 && high === 0) {\n return { result: \"pass\", checkedAt: at, note: \"No known critical/high vulnerabilities\" };\n }\n return { result: \"fail\", checkedAt: at, note: `${crit} critical / ${high} high vuln(s)` };\n}\n\n/**\n * Search Console → Google Indexed evidence. A soft-fail (the API errored) and an unwired\n * environment (`notConfigured`) are both `unknown`, but they carry DIFFERENT notes — an\n * operator staring at an amber pill has to be able to tell \"Google was unreachable this run\"\n * from \"this deployment has no Search Console credentials\", because only the second one is\n * fixed by wiring a secret. An un-enrolled site (`value: null`, not configured, not failed)\n * emits nothing so the box stays manual.\n *\n * Page-1 is `pass` (with the position in the note); off page 1 is `fail`.\n */\nfunction googleEvidence(now: Date, search: AutoTickSignals[\"search\"]): EvidenceRecord | null {\n const at = now.toISOString();\n if (search.softFailed) {\n return { result: \"unknown\", checkedAt: at, note: \"Search Console unavailable this run\" };\n }\n if (search.notConfigured) {\n return {\n result: \"unknown\",\n checkedAt: at,\n note: \"Search Console not configured in the environment that drafted this report\",\n };\n }\n if (search.value === null) return null;\n if (search.value.foundOnPage1) {\n const pos = search.value.position;\n return {\n result: \"pass\",\n checkedAt: at,\n note: `Page 1 on Google${pos !== null ? ` (#${pos})` : \"\"}`,\n };\n }\n const pos = search.value.position;\n return {\n result: \"fail\",\n checkedAt: at,\n note: `Not on page 1${pos !== null ? ` (avg #${pos})` : \"\"}`,\n };\n}\n\n/**\n * Domain/DNS/SSL evidence from the persisted `domain` audit. Omits (→ manual) when there's no\n * custom domain to verify (`*.netlify.app`) or the audit never ran. A `pass` requires a fresh\n * check that resolved with a cert comfortably before expiry; stale → unknown; resolved-but-no-cert\n * or near/past expiry → fail. The honest scope is resolve + valid cert — NOT registrar expiry,\n * www↔apex redirect, or MX.\n */\nfunction domainEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n // No custom domain to verify — the no-domain watch signal covers `*.netlify.app` elsewhere.\n if (!site.url || isNetlifyAppUrl(site.url)) return null;\n if (!site.domainCheckedAt) return null; // never probed → leave manual\n const at = site.domainCheckedAt;\n if (!isFresh(site.domainCheckedAt, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Domain check is stale (>3d)\" };\n }\n const days = site.certDaysRemaining;\n if (days === null) {\n return { result: \"fail\", checkedAt: at, note: \"Did not resolve, or no valid TLS cert\" };\n }\n if (days <= CERT_MIN_DAYS) {\n return { result: \"fail\", checkedAt: at, note: `TLS cert expires in ${days}d` };\n }\n return { result: \"pass\", checkedAt: at, note: `Custom domain, valid cert (${days}d left)` };\n}\n\n/**\n * Deploy & Function Health: the Netlify build is `ready` AND the deployed function responds\n * healthy. Two freshness stamps must both be fresh (deploy check + function-health check). Never\n * measured → null (omit → the gating dispatch coerces to unknown); either stale → unknown; both\n * fresh + ready + fn pass → pass; otherwise fail.\n */\nfunction deployEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (!site.deployCheckedAt && !site.functionHealthCheckedAt) return null;\n if (!isFresh(site.deployCheckedAt, now) || !isFresh(site.functionHealthCheckedAt, now)) {\n return {\n result: \"unknown\",\n checkedAt: site.functionHealthCheckedAt ?? site.deployCheckedAt,\n note: \"Deploy/function-health check is stale (>3d)\",\n };\n }\n const ready = site.deployStatus === \"ready\";\n const fnOk = site.functionHealth === \"pass\";\n if (ready && fnOk) {\n return {\n result: \"pass\",\n checkedAt: site.functionHealthCheckedAt,\n note: \"Netlify build ready + functions respond\",\n };\n }\n const why =\n !ready && !fnOk\n ? \"build not ready + functions unhealthy\"\n : !ready\n ? \"build not ready\"\n : \"functions unhealthy\";\n return {\n result: \"fail\",\n checkedAt: site.functionHealthCheckedAt,\n note: `Deploy/function-health failing — ${why}`,\n };\n}\n\n/**\n * CMS Checked: the server-side `/health` Prismic probe reported reachable. Freshness rides the\n * function-health check stamp (one `/health` fetch feeds both Deploy and CMS). Never measured →\n * null; stale → unknown; pass/fail mirror the stored verdict; a fresh stamp with no verdict →\n * unknown.\n */\nfunction cmsEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (!site.functionHealthCheckedAt) return null;\n const at = site.functionHealthCheckedAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"CMS check is stale (>3d)\" };\n }\n if (site.cmsReachable === \"pass\") {\n return { result: \"pass\", checkedAt: at, note: \"Prismic reachable (server-side)\" };\n }\n if (site.cmsReachable === \"fail\") {\n return { result: \"fail\", checkedAt: at, note: \"Prismic unreachable (server-side)\" };\n }\n return { result: \"unknown\", checkedAt: at, note: \"CMS reachability not reported\" };\n}\n\n/**\n * Uptime Checked: every sampled route returned 2xx/3xx on the browser audit (point-in-time).\n * Freshness rides the shared `browserCheckedAt`. Never ran → null; stale → unknown.\n */\nfunction uptimeEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (site.reachableOk === null || !site.browserCheckedAt) return null;\n const at = site.browserCheckedAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Uptime check is stale (>3d)\" };\n }\n return site.reachableOk === \"pass\"\n ? { result: \"pass\", checkedAt: at, note: \"All sampled routes reachable (point-in-time)\" }\n : { result: \"fail\", checkedAt: at, note: \"One or more sampled routes did not respond 2xx/3xx\" };\n}\n\n/**\n * Page Titles & Meta: every sampled route had a non-empty title + meta description with no\n * duplicate titles (browser audit, chromium). Freshness rides `browserCheckedAt`.\n */\nfunction titlesEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (site.titleMetaOk === null || !site.browserCheckedAt) return null;\n const at = site.browserCheckedAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Titles/meta check is stale (>3d)\" };\n }\n return site.titleMetaOk === \"pass\"\n ? { result: \"pass\", checkedAt: at, note: \"Titles + meta present\" }\n : {\n result: \"fail\",\n checkedAt: at,\n note: \"Missing/duplicate title or missing meta description\",\n };\n}\n\n/**\n * Form Functionality: a synthetic prod submission succeeded (form-e2e audit). `n/a` when the audit\n * ran (checked-at stamp set) but the site has no contact form (verdict cleared to null). Never ran\n * (no stamp) → null; stale → unknown.\n */\nfunction formsEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (!site.formE2eCheckedAt) return null;\n const at = site.formE2eCheckedAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Form E2E check is stale (>3d)\" };\n }\n if (site.formE2eOk === \"pass\") {\n return { result: \"pass\", checkedAt: at, note: \"Synthetic submission succeeded\" };\n }\n if (site.formE2eOk === \"fail\") {\n return { result: \"fail\", checkedAt: at, note: \"Synthetic submission failed\" };\n }\n return { result: \"n/a\", checkedAt: at, note: \"No contact form on this site\" };\n}\n\n/**\n * Interactions & Animations: the per-site smoke suite is green. Freshness rides `lastSmokeAt`.\n * Never ran → null; stale → unknown.\n */\nfunction interactionsEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (site.smokeOk === null || !site.lastSmokeAt) return null;\n const at = site.lastSmokeAt;\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"Smoke suite is stale (>3d)\" };\n }\n return site.smokeOk === \"pass\"\n ? { result: \"pass\", checkedAt: at, note: \"Smoke suite green\" }\n : { result: \"fail\", checkedAt: at, note: \"Smoke suite red\" };\n}\n\n/**\n * Tested After Updates: default-branch CI is green on the latest commit (github-signals). A repo\n * with no CI (`defaultBranchCi === \"none\"`) is `n/a`. Never swept (null / no stamp) → null; stale\n * → unknown; passing → pass; failing → fail; pending → unknown.\n */\nfunction updatesEvidence(site: WebsiteRow, now: Date): EvidenceRecord | null {\n if (site.defaultBranchCi === null || !site.githubSignalsAt) return null;\n const at = site.githubSignalsAt;\n if (site.defaultBranchCi === \"none\") {\n return { result: \"n/a\", checkedAt: at, note: \"Repository has no CI\" };\n }\n if (!isFresh(at, now)) {\n return { result: \"unknown\", checkedAt: at, note: \"CI signal is stale (>3d)\" };\n }\n if (site.defaultBranchCi === \"passing\") {\n return { result: \"pass\", checkedAt: at, note: \"Default-branch CI green on latest commit\" };\n }\n if (site.defaultBranchCi === \"failing\") {\n return { result: \"fail\", checkedAt: at, note: \"Default-branch CI is failing\" };\n }\n return { result: \"unknown\", checkedAt: at, note: \"Default-branch CI is pending\" };\n}\n","import { readFileSync } from \"node:fs\";\nimport { JWT } from \"google-auth-library\";\nimport { BetaAnalyticsDataClient } from \"@google-analytics/data\";\nimport { withSubjectFailover } from \"./failover.js\";\n\nconst ANALYTICS_READONLY = \"https://www.googleapis.com/auth/analytics.readonly\";\nconst MS_PER_DAY = 86_400_000;\n\nexport type GaQuery = {\n /** GA4 numeric property ID (e.g. \"471880366\"). */\n propertyId: string;\n /** Workspace users to impersonate via domain-wide delegation, tried in order\n * (auth-failure failover — see `withSubjectFailover`). */\n subjects: string[];\n /** Path to the service-account JSON key. */\n keyPath: string;\n};\n\n/** UTC YYYY-MM-DD — matches the rest of the reports pipeline's date handling. */\nfunction ymd(d: Date): string {\n return d.toISOString().slice(0, 10);\n}\n\n/**\n * Fetch GA4 `activeUsers` (\"Users\") for a report period and the equal-length window\n * immediately before it, via a domain-wide-delegation service account impersonating each\n * of `subjects` in order until one authenticates. Throws on any non-auth API error, or\n * once every subject has failed auth — the caller (draftReportForSite) soft-fails.\n *\n * Previous window: same length as the current period, ending the day before `periodStart`.\n */\nexport async function fetchPeriodUsers(\n query: GaQuery,\n periodStart: Date,\n periodEnd: Date,\n): Promise<{ current: number; previous: number }> {\n const key = JSON.parse(readFileSync(query.keyPath, \"utf8\")) as {\n client_email: string;\n private_key: string;\n };\n\n const lengthDays = Math.round((periodEnd.getTime() - periodStart.getTime()) / MS_PER_DAY);\n const prevEnd = new Date(periodStart.getTime() - MS_PER_DAY);\n const prevStart = new Date(prevEnd.getTime() - lengthDays * MS_PER_DAY);\n const property = `properties/${query.propertyId}`;\n\n return withSubjectFailover(query.subjects, \"GA\", async (subject) => {\n const authClient = new JWT({\n email: key.client_email,\n key: key.private_key,\n scopes: [ANALYTICS_READONLY],\n subject,\n });\n const client = new BetaAnalyticsDataClient({ authClient });\n\n const run = async (start: Date, end: Date): Promise<number> => {\n const [resp] = await client.runReport({\n property,\n dateRanges: [{ startDate: ymd(start), endDate: ymd(end) }],\n metrics: [{ name: \"activeUsers\" }],\n });\n const raw = resp.rows?.[0]?.metricValues?.[0]?.value ?? \"0\";\n const n = Number.parseInt(raw, 10);\n return Number.isFinite(n) ? n : 0;\n };\n\n const current = await run(periodStart, periodEnd);\n const previous = await run(prevStart, prevEnd);\n return { current, previous };\n });\n}\n","/**\n * Impersonation-subject failover, shared by the GA Data client and the Search Console\n * client (both impersonate the same `GA_SUBJECT` list via domain-wide delegation).\n *\n * The point: one personal Workspace account backing every site's analytics is a fleet-wide\n * SPOF — if it's offboarded/suspended or loses property access, all analytics soft-fail to\n * blank at once. With `GA_SUBJECT` as an ordered list, an auth failure on one subject falls\n * through to the next, and a *partial* outage (primary dying, backup carrying) is surfaced\n * as a greppable `subject failover` warning before it becomes a total one.\n */\n\nconst AUTH_HTTP_STATUS = new Set([401, 403]);\n/** gRPC PERMISSION_DENIED (7) / UNAUTHENTICATED (16) — how the GA Data API surfaces auth. */\nconst AUTH_GRPC_CODES = new Set([7, 16]);\n/** Message shapes across the three auth surfaces: gRPC code names (GA Data), OAuth token\n * exchange (`invalid_grant` = suspended/deleted subject, `unauthorized_client` = DWD scope\n * missing), and plain HTTP 401/403 texts (Search Console via gaxios). */\nconst AUTH_MESSAGE =\n /permission[_ ]denied|unauthenticated|unauthorized|invalid_grant|access[_ ]denied|forbidden|insufficient permission|status code 40[13]/i;\n\ntype ErrorShape = {\n code?: number | string;\n status?: number | string;\n response?: { status?: number; data?: { error?: { errors?: Array<{ reason?: string }> } } };\n /** Explicit opt-in marker for errors that aren't auth-shaped per se but mean \"this\n * subject can't do the job, try the next one\" (see the search client's empty\n * sites.list case — that API hides inaccessible properties instead of 403ing). */\n failoverToNextSubject?: boolean;\n};\n\n/** Google surfaces per-user throughput caps as HTTP 403 with one of these `reason`s — a\n * transient rate-limit, NOT a lost grant. Distinguished so the failover warning doesn't\n * send operators to the offboarding runbook over a quota blip. */\nconst QUOTA_REASONS = new Set([\n \"userratelimitexceeded\",\n \"ratelimitexceeded\",\n \"quotaexceeded\",\n \"dailylimitexceeded\",\n]);\nconst QUOTA_MESSAGE = /quota exceeded|rate limit exceeded|user rate limit/i;\n\n/** True when an error looks like THIS subject's auth/authorization failed — the only\n * condition worth retrying under a different subject. Network/5xx/bad-input errors\n * would fail identically for every subject, so they propagate immediately. */\nexport function isAuthShapedError(e: unknown): boolean {\n const err = e as ErrorShape | null | undefined;\n if (err?.failoverToNextSubject === true) return true;\n if ([err?.status, err?.response?.status].some((s) => AUTH_HTTP_STATUS.has(Number(s))))\n return true;\n if (AUTH_HTTP_STATUS.has(Number(err?.code)) || AUTH_GRPC_CODES.has(Number(err?.code)))\n return true;\n const msg = e instanceof Error ? e.message : String(e);\n return AUTH_MESSAGE.test(msg);\n}\n\n/** A soft \"this subject can't see the resource, try the next one\" marker (the search\n * client's empty sites.list case) — NOT a genuine failure. It must never dominate a real\n * auth error when deciding what to throw after all subjects are exhausted. */\nfunction isFailoverSentinel(e: unknown): boolean {\n return (e as ErrorShape | null | undefined)?.failoverToNextSubject === true;\n}\n\n/** True when a 403 is a transient per-user quota/rate-limit, not an access loss. A\n * structured `reason` is authoritative (so a real `forbidden` 403 whose message happens to\n * mention a limit is NOT quota); otherwise fall back to the message. Still auth-shaped for\n * failover purposes — this only softens the warning wording, never the control flow. */\nexport function isQuotaShapedError(e: unknown): boolean {\n const err = e as ErrorShape | null | undefined;\n if (err?.failoverToNextSubject === true) return false;\n const reasons = err?.response?.data?.error?.errors;\n if (Array.isArray(reasons) && reasons.length > 0) {\n return reasons.some((r) => r?.reason != null && QUOTA_REASONS.has(r.reason.toLowerCase()));\n }\n const msg = e instanceof Error ? e.message : String(e);\n return QUOTA_MESSAGE.test(msg);\n}\n\n/**\n * Run `attempt` with each subject in order until one succeeds. Auth-shaped failures fall\n * through to the next subject; anything else throws immediately. When all subjects fail,\n * the LAST error is thrown — callers keep their existing catch-and-soft-fail behavior.\n * When an earlier subject failed but a later one succeeded, emit ONE console.warn so a\n * dying primary is visible in the cron log before it becomes a total outage.\n */\nexport async function withSubjectFailover<T>(\n subjects: readonly string[],\n label: string,\n attempt: (subject: string) => Promise<T>,\n): Promise<T> {\n if (subjects.length === 0) throw new Error(`${label}: no impersonation subjects configured`);\n const failed: string[] = [];\n // Track a genuine auth failure separately from a soft sentinel. If ANY subject failed for\n // real, that error must be what we throw — never a later subject's \"no resource here\"\n // sentinel. Otherwise [real-auth-failure, empty-result] would surface as a clean sentinel\n // and the caller would record it as verified data instead of soft-failing (the exact\n // masking the analytics-health alarm exists to catch).\n let lastRealError: unknown;\n let lastSentinel: unknown;\n // Stays true only while every failure so far is a transient quota/rate-limit — a lost\n // grant or a sentinel flips it, escalating the warning from \"transient\" to the runbook.\n let allQuota = true;\n for (const subject of subjects) {\n try {\n const result = await attempt(subject);\n if (failed.length > 0) {\n console.warn(\n allQuota\n ? `⚠ ${label} subject failover: ${failed.join(\"; \")} — succeeded via ${subject} ` +\n `(transient quota/rate-limit, not an access loss).`\n : `⚠ ${label} subject failover: ${failed.join(\"; \")} — succeeded via ${subject}. ` +\n `Restore the failing subject's access or drop it from GA_SUBJECT ` +\n `(docs/runbooks/ga-search-role-account-cutover.md).`,\n );\n }\n return result;\n } catch (e) {\n if (!isAuthShapedError(e)) throw e;\n failed.push(`${subject} (${e instanceof Error ? e.message : String(e)})`);\n if (isFailoverSentinel(e)) {\n lastSentinel = e;\n allQuota = false;\n } else {\n lastRealError = e;\n if (!isQuotaShapedError(e)) allQuota = false;\n }\n }\n }\n // A real auth failure dominates a sentinel regardless of subject order; only when EVERY\n // subject merely returned the soft sentinel do we throw it (the search client turns that\n // into a legitimate not-found).\n throw lastRealError ?? lastSentinel;\n}\n","import { readFileSync } from \"node:fs\";\nimport { JWT } from \"google-auth-library\";\nimport { withSubjectFailover } from \"../ga/failover.js\";\n\nconst WEBMASTERS_READONLY = \"https://www.googleapis.com/auth/webmasters.readonly\";\nconst SC_BASE = \"https://searchconsole.googleapis.com/webmasters/v3\";\n/** Average-position threshold for \"on page 1\" (10 organic results per page). */\nconst PAGE_1_MAX_POSITION = 10;\n/** Rows to pull for the brand `contains` match. searchAnalytics has no orderBy and returns\n * rows clicks-desc, so the exact-query row survives into the response only if it isn't paged\n * out beyond this cap. Sized with wide headroom — a brand has a handful of phrasing variants,\n * far below 100 — so the exact query (and every variant) is in practice always present. */\nexport const BRAND_QUERY_ROW_LIMIT = 100;\n\nexport type SearchPresenceQuery = {\n /** Path to the service-account JSON key (same one GA uses). */\n keyPath: string;\n /** Workspace users to impersonate via domain-wide delegation, tried in order\n * (auth-failure failover — see `withSubjectFailover`). */\n subjects: string[];\n /** Explicit Search Console property (`sc-domain:...` or `https://.../`). Overrides auto-resolution. */\n property?: string | undefined;\n /** Site host, used to auto-resolve the property from `sites.list` when `property` is absent. */\n host: string;\n /** Operator-supplied brand hint (e.g. the business name). Matched as a case-insensitive\n * SUBSTRING (`contains`) of the actual user query — NOT a hard exact string — so it tolerates\n * phrasing (\"red door creative\" vs \"…creative la\"). An exact-query match is preferred when\n * present; otherwise the most-searched matching query wins. */\n query: string;\n};\n\nexport type SearchPresence = {\n /** True when the average position for the query is on page 1 (<= 10). */\n foundOnPage1: boolean;\n /** Rounded average position, or null when not found / no data. */\n position: number | null;\n /** True when a Search Console property was actually resolved for the site (even if the\n * query then found no data). False ONLY when every subject resolved ZERO matching\n * properties — a missing/unverified property or lost SA access. Callers must\n * distinguish these: \"property exists, query missed\" is fixable with a better query;\n * \"no property at all\" is not, and prescribing a query change would silence the real\n * problem forever (an explicit query that returns nothing is by design never flagged). */\n propertyFound: boolean;\n};\n\ntype SiteEntry = { siteUrl: string };\n\n/** Reduce any property string or URL to a bare host: no `sc-domain:`, scheme, `www.`, path, lowercased. */\nexport function bareHost(s: string): string {\n return s\n .trim()\n .replace(/^sc-domain:/i, \"\")\n .replace(/^https?:\\/\\//i, \"\")\n .split(\"/\")[0]!\n .replace(/^www\\./i, \"\")\n .toLowerCase();\n}\n\n/**\n * All Search Console properties matching `host`, ordered for query fallback: Domain\n * (`sc-domain:`) forms first (broadest coverage), then URL-prefix forms. A site can be verified\n * as both; a freshly-created Domain property has no backfilled history, so its data can be empty\n * even while a long-lived URL-prefix property has data — hence we return every match and let the\n * caller try them in order until one returns data. Empty list = nothing matches.\n */\nexport function resolvePropertyCandidates(entries: SiteEntry[], host: string): string[] {\n const target = bareHost(host);\n const matches = entries.filter((e) => bareHost(e.siteUrl) === target).map((e) => e.siteUrl);\n const domains = matches.filter((s) => s.toLowerCase().startsWith(\"sc-domain:\"));\n const prefixes = matches.filter((s) => !s.toLowerCase().startsWith(\"sc-domain:\"));\n return [...domains, ...prefixes];\n}\n\n/** UTC YYYY-MM-DD — matches the rest of the reports pipeline. */\nfunction ymd(d: Date): string {\n return d.toISOString().slice(0, 10);\n}\n\n/**\n * From the queries matching the brand substring, pick the one the brand is actually FOUND\n * by most — the highest-impression row — and return its average position; tie-break on the\n * better (lower) position. Returns undefined when no row carries a numeric position. This is\n * what makes the reported \"brand search\" position robust to phrasing: with a `contains`\n * filter several variants can match, and we report the position of the variant real users\n * search most, not whichever the operator happened to type. Rows missing `impressions` count\n * as 0 (keeps a single-row, impression-less response — e.g. a test fixture — working). PURE.\n */\nexport function pickBrandQuery(\n rows: Array<{ position?: number; impressions?: number }>,\n): number | undefined {\n let best: { position: number; impressions: number } | undefined;\n for (const r of rows) {\n if (typeof r.position !== \"number\") continue;\n const impressions = r.impressions ?? 0;\n if (\n best === undefined ||\n impressions > best.impressions ||\n (impressions === best.impressions && r.position < best.position)\n ) {\n best = { position: r.position, impressions };\n }\n }\n return best?.position;\n}\n\n/**\n * The brand's reported position from the `contains`-matched rows, preferring an EXACT match.\n * When a returned row's query equals the operator's configured string (case-insensitive), its\n * position is used verbatim — a precisely-configured brand query is honored, with no chance a\n * longer higher-impression variant (\"…reviews\", \"…near me\") hijacks the number. Otherwise we\n * fall back to the most-searched matching query (`pickBrandQuery`). Operates only on the rows\n * actually returned: a string `contains` itself, so the exact query is among the `contains`\n * results whenever it has data AND isn't paged out beyond `BRAND_QUERY_ROW_LIMIT` (sized so a\n * brand's handful of phrasing variants always fit; if it ever were paged out, the most-searched\n * fallback still returns a valid brand position). Returns undefined when no row carries a\n * numeric position. PURE.\n */\nexport function selectBrandPosition(\n rows: Array<{ keys?: string[]; position?: number; impressions?: number }>,\n exactQuery: string,\n): number | undefined {\n const want = exactQuery.toLowerCase();\n const exact = rows.find(\n (r) => typeof r.position === \"number\" && (r.keys?.[0] ?? \"\").toLowerCase() === want,\n );\n if (exact) return exact.position;\n return pickBrandQuery(rows);\n}\n\n/** Per-subject \"this subject resolved NO matching Search Console property\". sites.list only\n * returns properties the impersonated user can access — a subject that lost access sees an\n * empty list with no auth error at all — so this opts into subject failover explicitly.\n * When EVERY subject resolves empty, `fetchSearchPresence` restores the pre-failover\n * behavior: a plain not-found result, not a throw. */\nclass NoPropertyForSubjectError extends Error {\n readonly failoverToNextSubject = true;\n constructor(subject: string, host: string) {\n super(`no Search Console property matching ${host} is visible to ${subject}`);\n }\n}\n\n/**\n * Query Google Search Console for the brand's average position on the site over the report\n * period, via a domain-wide-delegation service account impersonating each of `subjects` in\n * order until one authenticates. `query` is a case-insensitive SUBSTRING (`contains`) hint;\n * among the matching user queries we report the position of the exact-match query when\n * present, else the most-searched one (see `selectBrandPosition`) — so it doesn't depend on\n * the operator typing the exact search string, yet honors one verbatim when they do. Uses\n * `property` verbatim when given (operator's choice is final — no fallback); otherwise\n * auto-discovers all matching properties via `sites.list` and tries them in order (Domain\n * first) until one returns data. Throws on any non-auth API error, or once every subject\n * has failed auth — the caller (draftReportForSite) soft-fails.\n */\nexport async function fetchSearchPresence(\n q: SearchPresenceQuery,\n periodStart: Date,\n periodEnd: Date,\n): Promise<SearchPresence> {\n const key = JSON.parse(readFileSync(q.keyPath, \"utf8\")) as {\n client_email: string;\n private_key: string;\n };\n\n try {\n return await withSubjectFailover(q.subjects, \"Search Console\", async (subject) => {\n const jwt = new JWT({\n email: key.client_email,\n key: key.private_key,\n scopes: [WEBMASTERS_READONLY],\n subject,\n });\n\n const explicit = q.property?.trim();\n let candidates: string[];\n if (explicit) {\n candidates = [explicit];\n } else {\n const list = await jwt.request<{ siteEntry?: SiteEntry[] }>({\n url: `${SC_BASE}/sites`,\n method: \"GET\",\n });\n candidates = resolvePropertyCandidates(list.data.siteEntry ?? [], q.host);\n if (candidates.length === 0) throw new NoPropertyForSubjectError(subject, q.host);\n }\n\n for (const property of candidates) {\n const res = await jwt.request<{\n rows?: Array<{ keys?: string[]; position?: number; impressions?: number }>;\n }>({\n url: `${SC_BASE}/sites/${encodeURIComponent(property)}/searchAnalytics/query`,\n method: \"POST\",\n data: {\n startDate: ymd(periodStart),\n endDate: ymd(periodEnd),\n dimensions: [\"query\"],\n dimensionFilterGroups: [\n {\n filters: [\n { dimension: \"query\", operator: \"contains\", expression: q.query.toLowerCase() },\n ],\n },\n ],\n rowLimit: BRAND_QUERY_ROW_LIMIT,\n },\n });\n const pos = selectBrandPosition(res.data.rows ?? [], q.query.toLowerCase());\n if (typeof pos === \"number\") {\n // Search Console can average below 1; floor to 1 so the template never\n // renders a nonsensical \"#0\" (positions are 1-indexed).\n return {\n foundOnPage1: pos <= PAGE_1_MAX_POSITION,\n position: Math.max(1, Math.round(pos)),\n propertyFound: true,\n };\n }\n }\n // A property WAS resolved (or operator-pinned); the query just found no rows.\n return { foundOnPage1: false, position: null, propertyFound: true };\n });\n } catch (e) {\n // Every subject resolved zero matching properties — same legitimate \"no property\"\n // outcome as before failover existed, NOT an analytics soft-failure. Marked\n // propertyFound:false so the draft layer can flag the ACTUAL problem (missing\n // property / lost SA access) instead of blaming the query.\n if (e instanceof NoPropertyForSubjectError)\n return { foundOnPage1: false, position: null, propertyFound: false };\n throw e;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,YAAY;AAwBvB,SAAS,eAAgC;AAC9C,QAAM,YAAY,QAAQ,IAAI,cAAc,IACzC,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,OAAO;AACjB,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,QAAM,UACJ,QAAQ,IAAI,gBAAgB,KAAK,KACjC,KAAK,QAAQ,uBAAuB,CAAC,GAAG,yBAAyB;AACnE,SAAO,EAAE,UAAU,QAAQ;AAC7B;;;AClCA,SAAS,OAAO,iBAAiB;AACjC,SAAS,WAAAA,gBAAe;;;ACOxB,IAAM,aAAa;AACnB,IAAM,aAAa,KAAK,KAAK,KAAK;AAGlC,SAAS,QAAQ,WAA0B,KAAoB;AA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M,mBAAmB,MAAM,QAAQ,EAAE;AACvD,QAAM,WAAW,MACd,OAAO,CAAC,MAAM,EAAE,eAAe,cAAc,EAAE,SAAS,EACxD,IAAI,CAAC,MAAM,EAAE,SAAU,EACvB,KAAK;AACR,QAAM,SAAS,SAAS,SAAS,SAAS,CAAC;AAC3C,MAAI,CAAC,OAAQ,QAAO,QAAQ,OAAO,EAAE;AAKrC,QAAM,QAAQ,IAAI,KAAK,MAAM;AAC7B,QAAM,WAAW,MAAM,WAAW,IAAI,CAAC;AACvC,SAAO;AACT;","names":["dirname","pos","MS_PER_DAY","readFileSync","JWT","ymd","readFileSync","JWT","dirname","outcome"]}
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  fetchGaUsers,
3
3
  fetchSearch
4
- } from "./chunk-6M2IXJ3E.js";
4
+ } from "./chunk-JVWJJ36K.js";
5
5
  import {
6
6
  announcementSiteExtras,
7
7
  resolveCopy
8
8
  } from "./chunk-6QRLRT3P.js";
9
9
  import {
10
10
  siteSlug
11
- } from "./chunk-GXVX4HUH.js";
11
+ } from "./chunk-CLWNAMUX.js";
12
12
 
13
13
  // src/reports/report-data.ts
14
14
  var PREVIEW_WINDOW_DAYS = 30;
@@ -60,4 +60,4 @@ export {
60
60
  scoresFromRow,
61
61
  buildReportDataForSite
62
62
  };
63
- //# sourceMappingURL=chunk-AKRUYPLU.js.map
63
+ //# sourceMappingURL=chunk-KV7DIRRO.js.map
@@ -30,7 +30,7 @@ async function resolveSites(input) {
30
30
  }
31
31
  if (input.fleet === "airtable") {
32
32
  const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
33
- const { fromAirtableBase } = await import("./airtable-6L3JD7FY.js");
33
+ const { fromAirtableBase } = await import("./airtable-5ZPU3MT4.js");
34
34
  const base = openBase(readAirtableConfig());
35
35
  const provider = fromAirtableBase(base, input.workdir ? { workdir: input.workdir } : {});
36
36
  return provider();
@@ -61,4 +61,4 @@ async function resolveSites(input) {
61
61
  export {
62
62
  resolveSites
63
63
  };
64
- //# sourceMappingURL=chunk-4BHNP6Y2.js.map
64
+ //# sourceMappingURL=chunk-MQUOUVQP.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  siteSlug
3
- } from "./chunk-GXVX4HUH.js";
3
+ } from "./chunk-CLWNAMUX.js";
4
4
 
5
5
  // src/audits/lighthouse-airtable.ts
6
6
  import { readFile } from "fs/promises";
@@ -48,4 +48,4 @@ export {
48
48
  lighthouseScoresFromResult,
49
49
  resolveSlugFromCwd
50
50
  };
51
- //# sourceMappingURL=chunk-3PU2QWOJ.js.map
51
+ //# sourceMappingURL=chunk-OQFOMKBP.js.map
@@ -25,7 +25,7 @@ import {
25
25
  listWebsites,
26
26
  siteSlug,
27
27
  updateLaunched
28
- } from "./chunk-GXVX4HUH.js";
28
+ } from "./chunk-CLWNAMUX.js";
29
29
  import {
30
30
  openBase,
31
31
  readAirtableConfig
@@ -333,4 +333,4 @@ export {
333
333
  parseAddresses,
334
334
  isProbablyEmail
335
335
  };
336
- //# sourceMappingURL=chunk-42A4H6SF.js.map
336
+ //# sourceMappingURL=chunk-PBCGXXG6.js.map
@@ -1,15 +1,15 @@
1
+ import {
2
+ baselineVersions
3
+ } from "./chunk-LKGVSM2O.js";
1
4
  import {
2
5
  readGitHubConfig
3
6
  } from "./chunk-GASBX52O.js";
4
7
  import {
5
8
  assertUrlSegment
6
- } from "./chunk-YAMRVXOD.js";
7
- import {
8
- baselineVersions
9
- } from "./chunk-LKGVSM2O.js";
9
+ } from "./chunk-VRWUL4TR.js";
10
10
  import {
11
11
  defaultSpawn
12
- } from "./chunk-HVOOCK6L.js";
12
+ } from "./chunk-4DHQCN5H.js";
13
13
  import {
14
14
  INGEST_TIMEOUT_MS
15
15
  } from "./chunk-A3WDWNN5.js";
@@ -239,13 +239,15 @@ function mapDependabotAlert(raw) {
239
239
  const adv = raw["security_advisory"] ?? {};
240
240
  const cveId = typeof adv["cve_id"] === "string" ? adv["cve_id"] : null;
241
241
  const rawScope = dependency["scope"];
242
+ const rawRelationship = dependency["relationship"];
242
243
  return {
243
244
  package: packageName,
244
245
  severity: typeof adv["severity"] === "string" ? adv["severity"] : "",
245
246
  summary: typeof adv["summary"] === "string" ? adv["summary"] : "",
246
247
  cves: cveId ? [cveId] : [],
247
248
  url: typeof raw["html_url"] === "string" ? raw["html_url"] : null,
248
- scope: rawScope === "runtime" || rawScope === "development" ? rawScope : null
249
+ scope: rawScope === "runtime" || rawScope === "development" ? rawScope : null,
250
+ relationship: rawRelationship === "direct" || rawRelationship === "transitive" ? rawRelationship : null
249
251
  };
250
252
  }
251
253
  function makeGitHubRest(deps) {
@@ -516,7 +518,8 @@ async function dependabotAudit(deps, repo, label) {
516
518
  title: a.summary || "(no title)",
517
519
  ...a.cves.length > 0 ? { cves: a.cves } : {},
518
520
  ...a.url ? { url: a.url } : {},
519
- ...a.scope ? { scope: a.scope } : {}
521
+ ...a.scope ? { scope: a.scope } : {},
522
+ ...a.relationship ? { relationship: a.relationship } : {}
520
523
  });
521
524
  }
522
525
  const status = classify(counts);
@@ -2260,4 +2263,4 @@ export {
2260
2263
  runAudits,
2261
2264
  runAuditsAcross
2262
2265
  };
2263
- //# sourceMappingURL=chunk-JMAFXEQE.js.map
2266
+ //# sourceMappingURL=chunk-QRDB4NLB.js.map