@reddoorla/maintenance 0.96.0 → 0.97.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 (237) hide show
  1. package/README.md +5 -6
  2. package/dist/{announce-45HVP4J4.js → announce-5ZD2SBGD.js} +39 -31
  3. package/dist/announce-5ZD2SBGD.js.map +1 -0
  4. package/dist/attachments-JFGFQRXQ.js +10 -0
  5. package/dist/{blux-RUFMNOUJ.js → blux-NXQLMS4W.js} +5 -5
  6. package/dist/{bump-deps-EL3TKMIL.js → bump-deps-775VLDYB.js} +6 -6
  7. package/dist/{chunk-IMYL67JV.js → chunk-3RLDX3Q2.js} +5 -5
  8. package/dist/{chunk-CA6ADGOC.js → chunk-6PGXKN6F.js} +2 -2
  9. package/dist/{chunk-Y5BVR4HW.js → chunk-6THEZQLA.js} +3 -3
  10. package/dist/chunk-ASLDCWBF.js +41 -0
  11. package/dist/chunk-ASLDCWBF.js.map +1 -0
  12. package/dist/{chunk-DVJNYPFR.js → chunk-AYDQQBNG.js} +2 -2
  13. package/dist/{chunk-GEUC5VGM.js → chunk-BINFZQ2T.js} +49 -4
  14. package/dist/chunk-BINFZQ2T.js.map +1 -0
  15. package/dist/{chunk-72FJZ6LO.js → chunk-DRNZVORX.js} +26 -22
  16. package/dist/chunk-DRNZVORX.js.map +1 -0
  17. package/dist/{chunk-SHGIDTYF.js → chunk-DYTYPKFN.js} +2 -2
  18. package/dist/{chunk-NVLREB5R.js → chunk-EN6CTBUN.js} +7 -7
  19. package/dist/{chunk-ZH5LOQET.js → chunk-FHFXJ3EM.js} +7 -5
  20. package/dist/chunk-FHFXJ3EM.js.map +1 -0
  21. package/dist/{chunk-H445EH33.js → chunk-FP6HOW6J.js} +10 -7
  22. package/dist/chunk-FP6HOW6J.js.map +1 -0
  23. package/dist/{chunk-RRE74VWI.js → chunk-HSMN35LU.js} +2 -2
  24. package/dist/chunk-ICSRWW5Q.js +148 -0
  25. package/dist/chunk-ICSRWW5Q.js.map +1 -0
  26. package/dist/{chunk-XG2A6GIG.js → chunk-IDBPII6G.js} +4 -4
  27. package/dist/{chunk-XG2A6GIG.js.map → chunk-IDBPII6G.js.map} +1 -1
  28. package/dist/{chunk-T76MA2FH.js → chunk-IOTOOTII.js} +12 -1
  29. package/dist/{chunk-T76MA2FH.js.map → chunk-IOTOOTII.js.map} +1 -1
  30. package/dist/{chunk-ECDJDHKT.js → chunk-JHJNNJLG.js} +2 -2
  31. package/dist/{chunk-XY7YV2YQ.js → chunk-L3S3QZXL.js} +2 -2
  32. package/dist/{chunk-XED2DNAI.js → chunk-LAG6IP7Y.js} +7 -7
  33. package/dist/{chunk-P4A6D6HO.js → chunk-LDHRIQUW.js} +32 -18
  34. package/dist/chunk-LDHRIQUW.js.map +1 -0
  35. package/dist/{chunk-UIITN37J.js → chunk-LF2TJN4X.js} +2 -2
  36. package/dist/chunk-LF2TJN4X.js.map +1 -0
  37. package/dist/{chunk-SQ4FSNYL.js → chunk-LUF52EIY.js} +2 -2
  38. package/dist/{chunk-MZZDMBDT.js → chunk-LZMAG73U.js} +19 -19
  39. package/dist/chunk-LZMAG73U.js.map +1 -0
  40. package/dist/{chunk-6INOBNRO.js → chunk-MMSMZC7S.js} +2 -2
  41. package/dist/{chunk-CGQZFQAY.js → chunk-MVKNU4QD.js} +2 -3
  42. package/dist/chunk-MVKNU4QD.js.map +1 -0
  43. package/dist/{chunk-62YWOFVN.js → chunk-PARKXDXI.js} +3 -3
  44. package/dist/{chunk-62YWOFVN.js.map → chunk-PARKXDXI.js.map} +1 -1
  45. package/dist/{chunk-44SDGPGQ.js → chunk-PZZ6HM5T.js} +3 -3
  46. package/dist/chunk-RQJFGK3A.js +51 -0
  47. package/dist/chunk-RQJFGK3A.js.map +1 -0
  48. package/dist/{chunk-KN52PM63.js → chunk-TC4GANMX.js} +47 -149
  49. package/dist/chunk-TC4GANMX.js.map +1 -0
  50. package/dist/{chunk-F3JWOPTG.js → chunk-TEMQPSCM.js} +45 -105
  51. package/dist/chunk-TEMQPSCM.js.map +1 -0
  52. package/dist/{chunk-4UTJ4G6P.js → chunk-TJLKWQOX.js} +2 -2
  53. package/dist/{chunk-VEIIUCYL.js → chunk-TV76A6GN.js} +2 -2
  54. package/dist/{chunk-D3CTOCUR.js → chunk-TVZ6QCOE.js} +3 -3
  55. package/dist/{chunk-3EA43S3R.js → chunk-U2ZI6G7H.js} +12 -12
  56. package/dist/chunk-UPE6D4AT.js +69 -0
  57. package/dist/chunk-UPE6D4AT.js.map +1 -0
  58. package/dist/{chunk-OTEVKRAH.js → chunk-VMGHQUTV.js} +7 -16
  59. package/dist/chunk-VMGHQUTV.js.map +1 -0
  60. package/dist/chunk-VQMAAQ5M.js +53 -0
  61. package/dist/chunk-VQMAAQ5M.js.map +1 -0
  62. package/dist/{chunk-EASYCD6F.js → chunk-WMF5S2MB.js} +1 -1
  63. package/dist/{chunk-EASYCD6F.js.map → chunk-WMF5S2MB.js.map} +1 -1
  64. package/dist/{chunk-37B4LVB3.js → chunk-X56LAKPR.js} +3 -3
  65. package/dist/chunk-X56LAKPR.js.map +1 -0
  66. package/dist/{chunk-IY6256GK.js → chunk-YJBSB4LP.js} +6 -1
  67. package/dist/chunk-YJBSB4LP.js.map +1 -0
  68. package/dist/{chunk-EQQ4H6L3.js → chunk-YXWBM26P.js} +2 -2
  69. package/dist/cli/bin.js +92 -50
  70. package/dist/cli/bin.js.map +1 -1
  71. package/dist/cli/commands/audit.d.ts +33 -3
  72. package/dist/cli/commands/audit.js +25 -22
  73. package/dist/cli/commands/audit.js.map +1 -1
  74. package/dist/client-DGTO65WB.js +11 -0
  75. package/dist/{convert-to-pnpm-4DON7IFS.js → convert-to-pnpm-KLWA53N5.js} +6 -6
  76. package/dist/{db-5K4CDEGJ.js → db-II5WAK4D.js} +13 -13
  77. package/dist/{digest-5AJGWS33.js → digest-CWKK2DMR.js} +28 -27
  78. package/dist/digest-CWKK2DMR.js.map +1 -0
  79. package/dist/{digest-collectors-MC5NWEUA.js → digest-collectors-CYTN2EUX.js} +15 -12
  80. package/dist/ensure-site-2QZHFVQ3.js +70 -0
  81. package/dist/ensure-site-2QZHFVQ3.js.map +1 -0
  82. package/dist/ensure-site-JEKV2ODE.js +105 -0
  83. package/dist/ensure-site-JEKV2ODE.js.map +1 -0
  84. package/dist/{ensure-site-XESZHZEB.js → ensure-site-OO4UPWNQ.js} +19 -42
  85. package/dist/ensure-site-OO4UPWNQ.js.map +1 -0
  86. package/dist/fleet-events-CkOZpMVC.d.ts +435 -0
  87. package/dist/{fleet-state-GJWGKTLD.js → fleet-state-RJROYXKO.js} +17 -7
  88. package/dist/{forms-notify-target-4NPLX2UG.js → forms-notify-target-X6UEOI2M.js} +17 -13
  89. package/dist/forms-notify-target-X6UEOI2M.js.map +1 -0
  90. package/dist/{github-signals-DMU74SAX.js → github-signals-QIRTHHET.js} +20 -15
  91. package/dist/github-signals-QIRTHHET.js.map +1 -0
  92. package/dist/{header-image-BRTOLHJF.js → header-image-H7ZJAV26.js} +13 -17
  93. package/dist/header-image-H7ZJAV26.js.map +1 -0
  94. package/dist/{health-endpoint-UCLMSSCN.js → health-endpoint-BJ6BKRHF.js} +7 -7
  95. package/dist/{health-mirror-ONRT4DQ5.js → health-mirror-KU3G7V2Y.js} +10 -10
  96. package/dist/{import-airtable-IIK2QUUF.js → import-airtable-UBF5GYAL.js} +3 -3
  97. package/dist/index.d.ts +102 -494
  98. package/dist/index.js +60 -49
  99. package/dist/index.js.map +1 -1
  100. package/dist/{init-3LMZTCVD.js → init-GOWDA5QS.js} +15 -15
  101. package/dist/{launch-XTDMC6LD.js → launch-7N3X2MXB.js} +36 -34
  102. package/dist/launch-7N3X2MXB.js.map +1 -0
  103. package/dist/lighthouse-airtable-M45OPVRV.js +14 -0
  104. package/dist/{chunk-IHHAYXKY.js → match-harness-GBCDSVPS.js} +70 -4
  105. package/dist/match-harness-GBCDSVPS.js.map +1 -0
  106. package/dist/migrate-XZ7U5DFC.js +7 -0
  107. package/dist/notify-K3WVH3DM.js +1 -1
  108. package/dist/{onboard-CZYBWVWH.js → onboard-JQQIMQW7.js} +6 -6
  109. package/dist/{orchestrate-TGDFGY52.js → orchestrate-L2A5BZFY.js} +13 -10
  110. package/dist/parity-2JGVUCZD.js +14 -0
  111. package/dist/{preflight-POZZI3GN.js → preflight-O7Q6FWHU.js} +35 -11
  112. package/dist/preflight-O7Q6FWHU.js.map +1 -0
  113. package/dist/{prismic-ci-AHY5ULJR.js → prismic-ci-NAPWOXXD.js} +11 -11
  114. package/dist/prismic-ci-NAPWOXXD.js.map +1 -0
  115. package/dist/{prismic-models-URYGODNY.js → prismic-models-LL6ORTQ2.js} +19 -16
  116. package/dist/prismic-models-LL6ORTQ2.js.map +1 -0
  117. package/dist/{prospect-audit-AJEE3Z4L.js → prospect-audit-FMPGQIRQ.js} +2 -2
  118. package/dist/{protection-audit-3J3UEOVT.js → protection-audit-YXJKFU6O.js} +3 -3
  119. package/dist/{protection-audit-3J3UEOVT.js.map → protection-audit-YXJKFU6O.js.map} +1 -1
  120. package/dist/recipes/sync-configs.js +3 -3
  121. package/dist/{render-from-row-65DC6ZP3.js → render-from-row-75JTED2Z.js} +6 -4
  122. package/dist/{renovate-dispatch-ONJMBUHJ.js → renovate-dispatch-2IHAZDVA.js} +13 -8
  123. package/dist/{renovate-dispatch-ONJMBUHJ.js.map → renovate-dispatch-2IHAZDVA.js.map} +1 -1
  124. package/dist/{report-RC5LGPU3.js → report-IAHXN5CW.js} +102 -58
  125. package/dist/report-IAHXN5CW.js.map +1 -0
  126. package/dist/{report-mirror-KKZZ6RMZ.js → report-mirror-4QM57LMS.js} +28 -10
  127. package/dist/report-mirror-4QM57LMS.js.map +1 -0
  128. package/dist/roster-GDNSIRAK.js +19 -0
  129. package/dist/roster-GDNSIRAK.js.map +1 -0
  130. package/dist/{self-updating-RKKIYNV4.js → self-updating-ZUWPGYUP.js} +7 -7
  131. package/dist/{selftest-AFLR7YV7.js → selftest-G4W3LIBQ.js} +21 -17
  132. package/dist/{selftest-AFLR7YV7.js.map → selftest-G4W3LIBQ.js.map} +1 -1
  133. package/dist/site-create-ZU3ACBTO.js +45 -0
  134. package/dist/site-create-ZU3ACBTO.js.map +1 -0
  135. package/dist/{site-mirror-H2FYMN55.js → site-mirror-WR7ACXOV.js} +10 -10
  136. package/dist/site-mirror-WR7ACXOV.js.map +1 -0
  137. package/dist/{smoke-suite-BWHR3XX5.js → smoke-suite-WAUPI6EJ.js} +7 -7
  138. package/dist/{submissions-II5J35QM.js → submissions-2SHCFOKD.js} +11 -6
  139. package/dist/submissions-2SHCFOKD.js.map +1 -0
  140. package/dist/{svelte-codemods-QWGIRNN6.js → svelte-codemods-VOLOKKFI.js} +6 -6
  141. package/dist/{sync-NKPDCMYW.js → sync-F4USL4K5.js} +6 -6
  142. package/dist/{sync-configs-HGLQV55H.js → sync-configs-OXSWKVZ2.js} +6 -6
  143. package/dist/turso-KQKBBQCK.js +24 -0
  144. package/dist/turso-KQKBBQCK.js.map +1 -0
  145. package/dist/{upgrade-WZ44IARG.js → upgrade-EVAL3JTO.js} +6 -6
  146. package/dist/util/git.d.ts +1 -1
  147. package/dist/util/git.js +1 -1
  148. package/dist/{websites-6DHIHJ2D.js → websites-Y6FN2XFD.js} +26 -21
  149. package/dist/{write-audits-to-airtable-BIK6LNVC.js → write-audits-to-airtable-TI3JMWSY.js} +6 -4
  150. package/package.json +1 -1
  151. package/dist/airtable-SJV4ZSMS.js +0 -9
  152. package/dist/announce-45HVP4J4.js.map +0 -1
  153. package/dist/attachments-NLZIJ5NU.js +0 -9
  154. package/dist/chunk-37B4LVB3.js.map +0 -1
  155. package/dist/chunk-72FJZ6LO.js.map +0 -1
  156. package/dist/chunk-74QRWE6G.js +0 -53
  157. package/dist/chunk-74QRWE6G.js.map +0 -1
  158. package/dist/chunk-CGQZFQAY.js.map +0 -1
  159. package/dist/chunk-F3JWOPTG.js.map +0 -1
  160. package/dist/chunk-GEUC5VGM.js.map +0 -1
  161. package/dist/chunk-H445EH33.js.map +0 -1
  162. package/dist/chunk-IHHAYXKY.js.map +0 -1
  163. package/dist/chunk-IY6256GK.js.map +0 -1
  164. package/dist/chunk-KN52PM63.js.map +0 -1
  165. package/dist/chunk-MZZDMBDT.js.map +0 -1
  166. package/dist/chunk-OTEVKRAH.js.map +0 -1
  167. package/dist/chunk-P4A6D6HO.js.map +0 -1
  168. package/dist/chunk-UIITN37J.js.map +0 -1
  169. package/dist/chunk-YFAXOD7Z.js +0 -42
  170. package/dist/chunk-YFAXOD7Z.js.map +0 -1
  171. package/dist/chunk-ZH5LOQET.js.map +0 -1
  172. package/dist/client-L7NAUG6J.js +0 -11
  173. package/dist/digest-5AJGWS33.js.map +0 -1
  174. package/dist/ensure-site-XESZHZEB.js.map +0 -1
  175. package/dist/fleet-events-cF2Om88w.d.ts +0 -24
  176. package/dist/forms-notify-target-4NPLX2UG.js.map +0 -1
  177. package/dist/github-signals-DMU74SAX.js.map +0 -1
  178. package/dist/header-image-BRTOLHJF.js.map +0 -1
  179. package/dist/launch-XTDMC6LD.js.map +0 -1
  180. package/dist/lighthouse-airtable-3NOFB42B.js +0 -12
  181. package/dist/match-harness-OW45CB5H.js +0 -77
  182. package/dist/match-harness-OW45CB5H.js.map +0 -1
  183. package/dist/migrate-NE3DUMTM.js +0 -7
  184. package/dist/parity-AEKYSLN6.js +0 -14
  185. package/dist/preflight-POZZI3GN.js.map +0 -1
  186. package/dist/prismic-ci-AHY5ULJR.js.map +0 -1
  187. package/dist/prismic-models-URYGODNY.js.map +0 -1
  188. package/dist/report-RC5LGPU3.js.map +0 -1
  189. package/dist/report-mirror-KKZZ6RMZ.js.map +0 -1
  190. package/dist/site-mirror-H2FYMN55.js.map +0 -1
  191. package/dist/submissions-II5J35QM.js.map +0 -1
  192. package/dist/write-audits-to-airtable-BIK6LNVC.js.map +0 -1
  193. /package/dist/{airtable-SJV4ZSMS.js.map → attachments-JFGFQRXQ.js.map} +0 -0
  194. /package/dist/{blux-RUFMNOUJ.js.map → blux-NXQLMS4W.js.map} +0 -0
  195. /package/dist/{bump-deps-EL3TKMIL.js.map → bump-deps-775VLDYB.js.map} +0 -0
  196. /package/dist/{chunk-IMYL67JV.js.map → chunk-3RLDX3Q2.js.map} +0 -0
  197. /package/dist/{chunk-CA6ADGOC.js.map → chunk-6PGXKN6F.js.map} +0 -0
  198. /package/dist/{chunk-Y5BVR4HW.js.map → chunk-6THEZQLA.js.map} +0 -0
  199. /package/dist/{chunk-DVJNYPFR.js.map → chunk-AYDQQBNG.js.map} +0 -0
  200. /package/dist/{chunk-SHGIDTYF.js.map → chunk-DYTYPKFN.js.map} +0 -0
  201. /package/dist/{chunk-NVLREB5R.js.map → chunk-EN6CTBUN.js.map} +0 -0
  202. /package/dist/{chunk-RRE74VWI.js.map → chunk-HSMN35LU.js.map} +0 -0
  203. /package/dist/{chunk-ECDJDHKT.js.map → chunk-JHJNNJLG.js.map} +0 -0
  204. /package/dist/{chunk-XY7YV2YQ.js.map → chunk-L3S3QZXL.js.map} +0 -0
  205. /package/dist/{chunk-XED2DNAI.js.map → chunk-LAG6IP7Y.js.map} +0 -0
  206. /package/dist/{chunk-SQ4FSNYL.js.map → chunk-LUF52EIY.js.map} +0 -0
  207. /package/dist/{chunk-6INOBNRO.js.map → chunk-MMSMZC7S.js.map} +0 -0
  208. /package/dist/{chunk-44SDGPGQ.js.map → chunk-PZZ6HM5T.js.map} +0 -0
  209. /package/dist/{chunk-4UTJ4G6P.js.map → chunk-TJLKWQOX.js.map} +0 -0
  210. /package/dist/{chunk-VEIIUCYL.js.map → chunk-TV76A6GN.js.map} +0 -0
  211. /package/dist/{chunk-D3CTOCUR.js.map → chunk-TVZ6QCOE.js.map} +0 -0
  212. /package/dist/{chunk-3EA43S3R.js.map → chunk-U2ZI6G7H.js.map} +0 -0
  213. /package/dist/{chunk-EQQ4H6L3.js.map → chunk-YXWBM26P.js.map} +0 -0
  214. /package/dist/{attachments-NLZIJ5NU.js.map → client-DGTO65WB.js.map} +0 -0
  215. /package/dist/{convert-to-pnpm-4DON7IFS.js.map → convert-to-pnpm-KLWA53N5.js.map} +0 -0
  216. /package/dist/{db-5K4CDEGJ.js.map → db-II5WAK4D.js.map} +0 -0
  217. /package/dist/{client-L7NAUG6J.js.map → digest-collectors-CYTN2EUX.js.map} +0 -0
  218. /package/dist/{digest-collectors-MC5NWEUA.js.map → fleet-state-RJROYXKO.js.map} +0 -0
  219. /package/dist/{health-endpoint-UCLMSSCN.js.map → health-endpoint-BJ6BKRHF.js.map} +0 -0
  220. /package/dist/{health-mirror-ONRT4DQ5.js.map → health-mirror-KU3G7V2Y.js.map} +0 -0
  221. /package/dist/{fleet-state-GJWGKTLD.js.map → import-airtable-UBF5GYAL.js.map} +0 -0
  222. /package/dist/{init-3LMZTCVD.js.map → init-GOWDA5QS.js.map} +0 -0
  223. /package/dist/{import-airtable-IIK2QUUF.js.map → lighthouse-airtable-M45OPVRV.js.map} +0 -0
  224. /package/dist/{lighthouse-airtable-3NOFB42B.js.map → migrate-XZ7U5DFC.js.map} +0 -0
  225. /package/dist/{onboard-CZYBWVWH.js.map → onboard-JQQIMQW7.js.map} +0 -0
  226. /package/dist/{migrate-NE3DUMTM.js.map → orchestrate-L2A5BZFY.js.map} +0 -0
  227. /package/dist/{orchestrate-TGDFGY52.js.map → parity-2JGVUCZD.js.map} +0 -0
  228. /package/dist/{prospect-audit-AJEE3Z4L.js.map → prospect-audit-FMPGQIRQ.js.map} +0 -0
  229. /package/dist/{parity-AEKYSLN6.js.map → render-from-row-75JTED2Z.js.map} +0 -0
  230. /package/dist/{self-updating-RKKIYNV4.js.map → self-updating-ZUWPGYUP.js.map} +0 -0
  231. /package/dist/{smoke-suite-BWHR3XX5.js.map → smoke-suite-WAUPI6EJ.js.map} +0 -0
  232. /package/dist/{svelte-codemods-QWGIRNN6.js.map → svelte-codemods-VOLOKKFI.js.map} +0 -0
  233. /package/dist/{sync-NKPDCMYW.js.map → sync-F4USL4K5.js.map} +0 -0
  234. /package/dist/{sync-configs-HGLQV55H.js.map → sync-configs-OXSWKVZ2.js.map} +0 -0
  235. /package/dist/{upgrade-WZ44IARG.js.map → upgrade-EVAL3JTO.js.map} +0 -0
  236. /package/dist/{render-from-row-65DC6ZP3.js.map → websites-Y6FN2XFD.js.map} +0 -0
  237. /package/dist/{websites-6DHIHJ2D.js.map → write-audits-to-airtable-TI3JMWSY.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/reports/header-image/geometry.ts","../src/reports/header-image/assets/index.ts","../src/reports/header-image/index.ts","../src/reports/header-image/capture.ts","../src/reports/header-image/compose.ts"],"sourcesContent":["// Measured off the real plate, not guessed.\n//\n// SCREEN is the hole INSIDE the laptop bezel. It is derived from the bezel —\n// a perfectly flat black frame (luminance 0.0) — because that is\n// content-independent. Deriving it from content instead (diffing two headers for\n// pixels that vary) yields a rect that spans the laptop's outer panel, covering\n// the bezel on three sides, so the plate's baked-in screenshot shows as a strip\n// under every site's content.\n//\n// ⚠️ THIS RECT IS A PROPERTY OF THE PLATE ASSET, AND THE ASSET HAS MOVED ONCE.\n// The values below were correct for `plate.png` (#476) and went stale when #570\n// re-exported the Figma frame as `plate-clean.png` to drop the baked headline:\n// the laptop moved 7px right and 26px up and grew slightly. Nothing re-measured\n// SCREEN, so for three weeks every generated header left rows 1887..1912 and\n// columns 1651..1655 of the plate UNPAINTED — and what showed through there was\n// the Alamo Anatomy homepage baked into the export: a green nav bar with a\n// \"Contact Us\" pill, across the top of all 13 maintained sites' headers, in\n// client-facing maintenance reports. Found 2026-09-17 on 29 Navy's.\n//\n// Evidence that the old values were right for the old asset, and are wrong for\n// this one — the hole measured by walking outward from the screen interior to\n// the first flat-black run:\n//\n// plate.png (#476) x=302 y=1913 w=1349 ← dx=0 dy=0 dw=0 vs SCREEN\n// plate-clean.png x=309 y=1887 w=1347 ← dx=-7 dy=26 dw=2\n//\n// The old cross-check in this comment said \"the photo-to-flat-black transition\n// at the bottom lands at y=2756, exactly SCREEN.y + SCREEN.h - 1\". That is true\n// of plate.png — y=2755 is photo, y=2756 is rgb(2,2,2), y=2757 is black — and\n// false of plate-clean.png, where y=2756 sits 29 rows inside the bottom bezel's\n// black run (2728..2775). A cross-check that still passes against the wrong file\n// is not a cross-check, which is why the guard is now a test against the bundled\n// asset (tests/reports/header-image/plate-geometry.test.ts) rather than a number\n// in a comment. Re-export the plate and that test fails; it cannot go stale\n// silently the way this paragraph did.\n//\n// Re-measure only if the Figma template changes — and if you do, find the bezel.\n\n/** The plate's pixel dimensions — Figma frame 600x800 exported at 4x. */\nexport const CANVAS = { width: 2400, height: 3200 } as const;\n\n/** The MacBook Pro screen the site screenshot is pasted into — the area inside\n * the bezel, so the bezel stays visible around the content exactly as it does\n * in the hand-made headers. Aspect 1.6017 (16:10 to within 0.11%).\n *\n * Measured on plate-clean.png: content spans x 310..1655, y 1888..2727, with a\n * single anti-aliased blend pixel on the outside of the left, top and bottom\n * edges (x=309 rgb(5,10,8); y=1887 rgb(14,29,24); y=2727 rgb(27,50,74)). The\n * rect INCLUDES those blend pixels deliberately: each one is part baked\n * screenshot, so leaving it uncovered leaves a faint tinted line of the other\n * site, while covering it repaints one pixel of bezel edge and is invisible. */\nexport const SCREEN = { x: 309, y: 1887, w: 1347, h: 841 } as const;\n\n/** Where a report-type headline overlay lands on the clean plate.\n *\n * Measured, not guessed: red ink present in the baked maintenance plate but\n * absent from plate-clean spans x=277 y=998 w=1326 h=658 — and\n * headline-maintenance.png is that ink box cropped to its own edges\n * (1328x660, ±1px of anti-aliasing at the threshold), so compositing the\n * asset at this origin reproduces the baked plate's headline exactly. */\nexport const HEADLINE = { x: 277, y: 998 } as const;\n\n/** The band a headline occupies, sized to the WIDEST registered overlay\n * (Testing, 1715x664). Used to detect a header that already carries a baked-in\n * headline, so it can't be stamped a second time. Deliberately clear of the\n * logo above (ends y≈506) and the laptop screen below (starts y=1887), so the\n * only ink that can land here is a headline. */\nexport const HEADLINE_BAND = { x: HEADLINE.x, y: HEADLINE.y, w: 1715, h: 664 } as const;\n\n/** The headline ink colour (brand red), and how far a pixel may drift from it\n * and still count — JPEG re-encoding moves it by a level or two. */\nexport const HEADLINE_INK = { r: 209, g: 34, b: 62 } as const;\n\n/** The per-site domain line, bottom left.\n *\n * Solved against the hand-made reference rather than guessed: rendering\n * \"gallerysonder.com\" with these values reproduces Sonder's original ink box\n * (x=283 y=2963 w=645 h=74) EXACTLY — dx=0 dy=0 dw=0 dh=0. A sweep over sizes\n * 62-88 at weights 300/400 has a single exact solution at size 80 / weight 400.\n *\n * `baseline` is the text baseline in canvas pixels; the ink box sits above it\n * by the cap height and below by the descender. */\nexport const DOMAIN = {\n x: 280,\n baseline: 3020,\n size: 80,\n weight: 400,\n color: \"#747474\",\n} as const;\n\n/** Flat paper tone, used as the compositing background so a transparent or\n * short source can never punch a hole in the plate. */\nexport const PAPER = \"#fcfcfc\" as const;\n","import { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst PLATE = \"plate-clean.png\";\n\n/** Per-report-type headline overlays, stamped over the CLEAN plate at send time\n * (see orchestrate.ts). Types with no entry go out on the clean plate.\n *\n * Source: Figma \"Web-Maintenance-Email\" (mQ3hy2d9JnOG9ljCzbZS8j) —\n * Maintenance is node 158:15, Testing is 153:721 (\"maintenance & testing\",\n * which is what a Testing report actually covers). Export each at 4x; Figma\n * crops a text export to its ink box, which is why these are 1328x660 /\n * 1715x664 rather than the 1840x720 text box.\n *\n * ⚠️ A Figma MCP `download_assets` export arrives FLATTENED — never\n * transparent — and it flattens onto WHATEVER SITS BEHIND THE NODE, which is\n * not one fixed colour: Maintenance/Testing live inside a white Header frame\n * and come back on white, while Announcement/Launch sit on the bare canvas and\n * come back on Figma's canvas grey (30,30,30). Stamping either unprocessed\n * paints a solid slab over the paper texture — that, not a bad design file, is\n * what made the 2026-08-20 Testing asset unusable.\n *\n * Recover the alpha instead of re-exporting by hand: for ink C over backdrop B,\n * a = (px - B) / (C - B). DETECT B (the export's most common colour) rather\n * than assuming white, and pick the channel with the largest |C - B| — green\n * separates the brand red from white by 221 levels but from canvas grey by only\n * 4, which would quantise the alpha to noise. Verified against the known-good\n * Maintenance asset at mean abs alpha diff 0.022, 0.0037% of pixels off by\n * more than 8.\n *\n * Editing this copy needs Figma desktop, not the Plugin API: `characters`\n * requires loadFontAsync and the MCP font environment carries no Helvetica at\n * all, so the licensed Helvetica Neue LT Std can never load there. */\nconst HEADLINE_FILES = {\n Maintenance: \"headline-maintenance.png\",\n Testing: \"headline-testing.png\",\n Announcement: \"headline-announcement.png\",\n Launch: \"headline-launch.png\",\n} as const;\n\nexport type HeadlineKind = keyof typeof HEADLINE_FILES;\n\n/** The headline kind for a report type, or null for types that ship clean. */\nexport function headlineKindFor(reportType: string): HeadlineKind | null {\n return Object.hasOwn(HEADLINE_FILES, reportType) ? (reportType as HeadlineKind) : null;\n}\n\n// Walk up from this module's URL looking for the assets dir in either the dev\n// layout (src/reports/header-image/assets/) or the published layout\n// (dist/reports/header-image/assets/). REQUIRED because tsup inlines this module\n// into dist/cli/bin.js — so import.meta.url-based sibling resolution looks in\n// dist/cli/ and fails with ENOENT. This exact bug shipped in 0.10.0-0.10.1 for\n// the maintenance-email assets; tests passed in dev because vitest evaluates the\n// source file, where import.meta.url is already correct. Only `pnpm test:dist`\n// catches a regression here.\nlet cachedAssetsDir: string | null = null;\nfunction resolveAssetsDir(): string {\n if (cachedAssetsDir) return cachedAssetsDir;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n for (const layout of [\"src\", \"dist\"]) {\n const candidate = join(dir, layout, \"reports\", \"header-image\", \"assets\", PLATE);\n if (existsSync(candidate)) {\n cachedAssetsDir = dirname(candidate);\n return cachedAssetsDir;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) {\n throw new Error(\n `loadPlate: could not locate the header-image assets dir by walking up from ${fileURLToPath(import.meta.url)}. Checked both src/ and dist/ layouts.`,\n );\n }\n dir = parent;\n }\n}\n\n/** Read the bundled 2400x3200 CLEAN plate (no headline — the report type's\n * headline is stamped at send time, so one stored image serves every type). */\nexport async function loadPlate(): Promise<Uint8Array> {\n return new Uint8Array(await readFile(join(resolveAssetsDir(), PLATE)));\n}\n\n/** Read a headline overlay (transparent PNG, ink-box cropped). */\nexport async function loadHeadline(kind: HeadlineKind): Promise<Uint8Array> {\n return new Uint8Array(await readFile(join(resolveAssetsDir(), HEADLINE_FILES[kind])));\n}\n","import sharp from \"sharp\";\nimport { captureHomepage, type Shooter } from \"./capture.js\";\nimport { composeHeaderImage, stampHeadline, headlineInkCount } from \"./compose.js\";\nimport { loadPlate, loadHeadline, headlineKindFor } from \"./assets/index.js\";\nimport { CANVAS } from \"./geometry.js\";\n\n/** Headline-red pixels tolerated in the band before a stored header is treated\n * as already carrying a headline. A clean-plate header measures 0 and a baked\n * one ~62,000, so this sits far from both — it exists only to absorb stray\n * JPEG artefacts, not to tune a boundary. */\nconst HEADLINE_INK_TOLERANCE = 500;\n\nexport type GenerateInput = {\n /** The site's production URL. */\n url: string;\n /** Airtable site slug; drives the attachment filename. */\n slug?: string;\n /** Injected browser IO (tests). */\n shooter?: Shooter;\n /** Per-site settle override for animation-heavy homepages. */\n settleMs?: number;\n /** Extra CSS selector(s) hidden before the shutter, for consent or\n * interstitial UI the capture's class/id heuristic misses (#654). */\n consentSelector?: string;\n};\n\nexport type GeneratedHeaderImage = {\n bytes: Uint8Array;\n /** The domain as printed on the plate. */\n domain: string;\n filename: string;\n contentType: \"image/jpeg\";\n};\n\n/** Strip scheme, leading www and any path — the plate prints a bare domain. */\nexport function domainFromUrl(url: string): string {\n return new URL(url).hostname.replace(/^www\\./, \"\");\n}\n\n/**\n * A capture is \"blank\" when it is almost entirely near-white — a consent gate,\n * a failed render (blank canvas), or a shot fired before first paint. The\n * operator reviews the rendered email before sending, so this is a backstop\n * rather than the only gate; its job is to stop an obviously broken shot from\n * replacing a good stored header.\n *\n * Uniformity alone is NOT the signal: a homepage with a large solid-colour\n * hero (any brand colour) is legitimately uniform but not blank. Only\n * near-white uniformity is flagged, since every real failure mode here\n * (consent overlay, unrendered canvas, pre-paint flash) lands on a white\n * background.\n */\nasync function assertNotBlank(shot: Uint8Array): Promise<void> {\n const { data, info } = await sharp(Buffer.from(shot))\n .resize(64, 40, { fit: \"fill\" })\n .removeAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const total = info.width * info.height;\n const at = (i: number): number => data[i] ?? 0;\n\n let sumR = 0;\n let sumG = 0;\n let sumB = 0;\n for (let i = 0; i < data.length; i += info.channels) {\n sumR += at(i);\n sumG += at(i + 1);\n sumB += at(i + 2);\n }\n const meanR = sumR / total;\n const meanG = sumG / total;\n const meanB = sumB / total;\n\n let near = 0;\n for (let i = 0; i < data.length; i += info.channels) {\n if (\n Math.abs(at(i) - meanR) < 8 &&\n Math.abs(at(i + 1) - meanG) < 8 &&\n Math.abs(at(i + 2) - meanB) < 8\n ) {\n near++;\n }\n }\n\n const uniform = near / total > 0.95;\n const nearWhite = meanR > 240 && meanG > 240 && meanB > 240;\n if (uniform && nearWhite) {\n throw new Error(\n \"header-image: capture looks blank (near-white, >95% one colour) — keeping the existing header\",\n );\n }\n}\n\n/**\n * Stamp the report type's headline onto a stored (clean) header at send time.\n * Types with no headline registered pass through untouched, as does any header\n * that must not be stamped:\n *\n * - wrong dimensions (a legacy hand-made header), where fixed coordinates\n * would misplace the text;\n * - a header that ALREADY CARRIES A HEADLINE, i.e. one built on the old baked\n * plate. Stamping those prints the new headline directly over the baked one\n * and the two overprint into unreadable pulp — which shipped in a real\n * announcement on 2026-08-24. An earlier version of this comment claimed\n * such headers were safe because they'd \"keep their baked headline\"; that\n * was wrong. They are canvas-sized, so nothing stopped them being stamped.\n *\n * The band is empty on a clean-plate header and holds ~62k red px on a baked\n * one, so the check is unambiguous rather than a tuned threshold. A skipped\n * header still goes out looking correct (its baked headline is a real headline)\n * and self-heals on the site's next draft, which regenerates it clean;\n * `header-image --all --force` does the whole fleet at once.\n */\nexport async function applyReportTypeHeadline(\n header: Uint8Array,\n reportType: string,\n): Promise<Uint8Array> {\n const kind = headlineKindFor(reportType);\n if (!kind) return header;\n // Best-effort by design: the headline is cosmetic, so anything unexpected —\n // undecodable bytes included — warns and sends the header as stored rather\n // than failing the send. Mandatory processing (and its hard failures) lives\n // in prepareHeaderImage downstream.\n try {\n const meta = await sharp(Buffer.from(header)).metadata();\n if (meta.width !== CANVAS.width || meta.height !== CANVAS.height) {\n console.warn(\n `⚑ header headline skipped: stored header is ${meta.width}x${meta.height}, not ${CANVAS.width}x${CANVAS.height} — sending it as stored`,\n );\n return header;\n }\n const existing = await headlineInkCount(header);\n if (existing > HEADLINE_INK_TOLERANCE) {\n console.warn(\n `⚑ header headline skipped: the stored header already carries a headline (${existing} ink px in the band) — it predates the clean-plate switch, so stamping would overprint. Sending it as stored; run \\`header-image ${\"<site>\"} --write-back\\` to regenerate it clean.`,\n );\n return header;\n }\n return await stampHeadline(header, await loadHeadline(kind));\n } catch (err) {\n console.warn(\n `⚑ header headline skipped (${err instanceof Error ? err.message : String(err)}) — sending the header as stored`,\n );\n return header;\n }\n}\n\n/** Capture a site's homepage and composite its header image. */\nexport async function generateHeaderImage(input: GenerateInput): Promise<GeneratedHeaderImage> {\n const screenshot = await captureHomepage(input.url, {\n ...(input.shooter !== undefined ? { shooter: input.shooter } : {}),\n ...(input.settleMs !== undefined ? { settleMs: input.settleMs } : {}),\n ...(input.consentSelector !== undefined ? { consentSelector: input.consentSelector } : {}),\n });\n await assertNotBlank(screenshot);\n\n const domain = domainFromUrl(input.url);\n const bytes = await composeHeaderImage({\n plate: await loadPlate(),\n screenshot,\n domain,\n });\n const base = input.slug ?? domain.split(\".\")[0];\n return { bytes, domain, filename: `${base}Header.jpg`, contentType: \"image/jpeg\" };\n}\n","/** Viewport matching the plate's MacBook screen aspect (16:10), so the crop in\n * compose.ts is a no-op for a well-behaved homepage. */\nconst VIEWPORT = { width: 1600, height: 1000 } as const;\n/** 2x so the 1349px-wide screen rect is fed real pixels, not upscaled ones. */\nconst DEVICE_SCALE_FACTOR = 2;\n/** Entrance animations and webfonts settle before the shutter. Measured against\n * live fleet sites; overridable per site because consent gates and long\n * animations vary. */\nconst DEFAULT_SETTLE_MS = 2500;\n/** Budget for the `load` milestone — the navigation we actually gate on.\n *\n * Do NOT put `waitUntil: \"networkidle\"` back on the `goto`. Measured across all\n * 14 live fleet sites (30s timeout): `load` succeeded on 14/14 in 346–1205ms,\n * while `networkidle` NEVER fired on 4 of them (ERP Industrials, Vineyard,\n * Revogen, 1836dig) — chat widgets, analytics polling and websockets hold the\n * connection open forever, so `goto` threw and those sites could never get a\n * header image at all. */\nconst NAV_TIMEOUT_MS = 60_000;\n/** Best-effort extra wait for network idle, applied *after* `load` and with its\n * rejection swallowed. The 10 sites that do settle still get the benefit; the 4\n * that never will just proceed. 3s is sized from the measurement above: the\n * slowest site that does reach idle took 4078ms from `goto` start, and by the\n * time this runs the `load` milestone (~0.3–1.2s) has already passed, so 3s\n * covers the real remaining settle time without stalling the never-idle sites. */\nconst IDLE_BUDGET_MS = 3_000;\n\n/** Attribute heuristic for a cookie / consent banner: any element whose class or\n * id mentions \"cookie\" or \"consent\", case-insensitively. Sonder's header shipped\n * its consent panel and the panel's scrim over the hero (#654) — the banner\n * never leaves on its own, so settle time was irrelevant and hiding it is the\n * whole fix. Kept narrow on purpose: a broader net (e.g. \"modal\", \"overlay\")\n * would start hiding hero art on sites that use those words for content. */\nexport const CONSENT_SELECTOR =\n '[class*=\"cookie\" i],[id*=\"cookie\" i],[class*=\"consent\" i],[id*=\"consent\" i]';\n\n/** Accessible names of the buttons a consent banner offers. Clicking one lets the\n * site run its own dismissal, which is the only thing that reliably removes a\n * scrim living OUTSIDE the banner element (a `body::before`, a sibling overlay). */\nexport const CONSENT_BUTTON_NAME =\n /^(accept( all)?( cookies)?|allow( all)?|reject( all)?|decline|got it|ok(ay)?|i (agree|understand)|agree)$/i;\n\n/** Budget for the best-effort consent click. A site with no banner has no button,\n * so the click times out on every capture there — it must be short, and it is\n * swallowed. Sized so the 14 consent-free fleet sites pay ≤1.5s each. */\nconst CONSENT_CLICK_TIMEOUT_MS = 1_500;\n\n/**\n * The CSS rule that hides consent UI before the shutter. `consentSelector` is a\n * per-site addition for banners the heuristic misses (a newsletter interstitial,\n * a GDPR shield with a bespoke class); it is joined onto the heuristic, never a\n * replacement for it. Pure, so it can be tested without a browser.\n */\nexport function consentHideRule(consentSelector?: string): string {\n const extra = consentSelector?.trim();\n const selector = extra ? `${CONSENT_SELECTOR},${extra}` : CONSENT_SELECTOR;\n return `${selector}{display:none!important;visibility:hidden!important;pointer-events:none!important}`;\n}\n\nexport type ShootOptions = {\n url: string;\n width: number;\n height: number;\n deviceScaleFactor: number;\n settleMs: number;\n /** Extra CSS selector(s) hidden before the shutter, for a site whose consent\n * or interstitial UI the class/id heuristic misses. */\n consentSelector?: string;\n};\n\n/** Injected browser IO. The real impl drives Playwright; tests pass a fake. */\nexport type Shooter = {\n shoot: (opts: ShootOptions) => Promise<Uint8Array>;\n};\n\nexport type CaptureOptions = {\n shooter?: Shooter;\n settleMs?: number;\n consentSelector?: string;\n};\n\n/**\n * Screenshot a site's homepage for the header image.\n *\n * Viewport-only, never `fullPage`: the plate shows a laptop screen, not a\n * scroll. Failures propagate — a caller must be able to keep the site's existing\n * header rather than overwrite it with a broken shot.\n */\nexport async function captureHomepage(\n url: string,\n options: CaptureOptions = {},\n): Promise<Uint8Array> {\n const shooter = options.shooter ?? (await defaultShooter());\n return shooter.shoot({\n url,\n width: VIEWPORT.width,\n height: VIEWPORT.height,\n deviceScaleFactor: DEVICE_SCALE_FACTOR,\n settleMs: options.settleMs ?? DEFAULT_SETTLE_MS,\n ...(options.consentSelector !== undefined ? { consentSelector: options.consentSelector } : {}),\n });\n}\n\n/** Real Playwright shooter. Lazily imported so unit tests never load it and the\n * static import graph stays central-dep-free for `test:dist`. */\nexport async function defaultShooter(): Promise<Shooter> {\n const { chromium } = await import(\"@playwright/test\");\n return {\n async shoot(opts) {\n const browser = await chromium.launch();\n try {\n const page = await browser.newPage({\n viewport: { width: opts.width, height: opts.height },\n deviceScaleFactor: opts.deviceScaleFactor,\n });\n await page.goto(opts.url, { waitUntil: \"load\", timeout: NAV_TIMEOUT_MS });\n // Best-effort only — a site that never idles must still be captured.\n await page.waitForLoadState(\"networkidle\", { timeout: IDLE_BUDGET_MS }).catch(() => {});\n await page.evaluate(\"document.fonts && document.fonts.ready\");\n // Dismiss consent UI, strictly best-effort — a header capture must never\n // fail because a site has no banner. The click goes FIRST: once the rule\n // below hides the button it is no longer actionable, and the site's own\n // dismissal is what unwinds a scrim that lives outside the banner. Then\n // the style tag catches a banner with no matching button, or one that\n // fades out slower than the settle. Both run before the settle wait so\n // the settle absorbs whatever animation the dismissal starts.\n await page\n .getByRole(\"button\", { name: CONSENT_BUTTON_NAME })\n .first()\n .click({ timeout: CONSENT_CLICK_TIMEOUT_MS })\n .catch(() => {});\n await page.addStyleTag({ content: consentHideRule(opts.consentSelector) });\n await page.waitForTimeout(opts.settleMs);\n const buf = await page.screenshot({ type: \"png\" });\n return new Uint8Array(buf);\n } finally {\n await browser.close();\n }\n },\n };\n}\n","import sharp from \"sharp\";\nimport type { OverlayOptions } from \"sharp\";\nimport {\n CANVAS,\n SCREEN,\n DOMAIN,\n PAPER,\n HEADLINE,\n HEADLINE_BAND,\n HEADLINE_INK,\n} from \"./geometry.js\";\n\nexport type ComposeInput = {\n /** The bundled 2400x3200 plate. */\n plate: Uint8Array;\n /** A homepage screenshot, any size. Cropped to fill the screen rect. */\n screenshot: Uint8Array;\n /** The site's public domain, drawn bottom-left (e.g. \"gallerysonder.com\"). */\n domain: string;\n};\n\n/** JPEG quality. The hand-made headers are ~2.4MB; 88 lands near 0.7MB with no\n * visible difference at the 600px the email actually renders. */\nconst JPEG_QUALITY = 88;\n\n/** Escape the five XML metacharacters. The domain is interpolated into an SVG,\n * and a bare `&` yields invalid XML that sharp rejects outright. */\nfunction escapeXml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&apos;\");\n}\n\n/**\n * The domain line as a transparent SVG overlay the size of the full canvas, so\n * it can be composited at 0,0 and positioned by its own coordinates.\n *\n * ⚠️ FONT AVAILABILITY IS ENVIRONMENT-DEPENDENT. sharp renders SVG through\n * librsvg + fontconfig, so the family below resolves against INSTALLED fonts.\n * On macOS it resolves to real Helvetica Neue, which reproduces the hand-made\n * reference exactly (verified: ink box dx=0 dy=0 dw=0 dh=0). A stock\n * ubuntu-latest runner has none of Helvetica Neue / Helvetica / Arial, so it\n * falls through to `sans-serif` — typically DejaVu Sans, which is wider and\n * would render a visibly different domain line.\n *\n * This matters because report drafting (which regenerates the header) runs on\n * ubuntu-latest in `.github/workflows/daily-reports.yml`. That workflow now\n * installs `fonts-urw-base35`, which provides Nimbus Sans — metrically\n * equivalent to Helvetica and third in the stack below — so a CI-generated\n * header's domain line matches a locally-generated one. Any OTHER environment\n * that runs this code still needs a Helvetica-metric font installed.\n */\nfunction domainSvg(domain: string): Buffer {\n return Buffer.from(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${CANVAS.width}\" height=\"${CANVAS.height}\">\n <text x=\"${DOMAIN.x}\" y=\"${DOMAIN.baseline}\"\n font-family=\"Helvetica Neue, Helvetica, Nimbus Sans, Arial, sans-serif\"\n font-size=\"${DOMAIN.size}\" font-weight=\"${DOMAIN.weight}\"\n fill=\"${DOMAIN.color}\">${escapeXml(domain)}</text>\n </svg>`,\n \"utf-8\",\n );\n}\n\n/**\n * Composite one site's header image: paste its homepage screenshot into the\n * plate's laptop screen and draw its domain underneath.\n *\n * PURE — no browser, no network, no filesystem. Fidelity lives here, so it must\n * be verifiable in a unit test.\n *\n * The screenshot is cropped to FILL the 16:10 screen from the top: a taller\n * homepage loses its fold rather than being squashed, which would be obvious\n * and wrong. `flatten` guards against a transparent source punching a hole in\n * the plate.\n */\nexport async function composeHeaderImage(input: ComposeInput): Promise<Uint8Array> {\n const screen = await sharp(Buffer.from(input.screenshot))\n .resize(SCREEN.w, SCREEN.h, { fit: \"cover\", position: \"top\" })\n .flatten({ background: PAPER })\n .toBuffer();\n\n const layers: OverlayOptions[] = [{ input: screen, left: SCREEN.x, top: SCREEN.y }];\n if (input.domain.trim().length > 0) {\n layers.push({ input: domainSvg(input.domain), left: 0, top: 0 });\n }\n\n const out = await sharp(Buffer.from(input.plate))\n .composite(layers)\n .jpeg({ quality: JPEG_QUALITY })\n .toBuffer();\n return new Uint8Array(out);\n}\n\n/**\n * Count headline-red pixels already present in the headline band.\n *\n * A header composed on the clean plate has EXACTLY ZERO (measured), because the\n * band sits between the logo and the laptop and nothing else paints there. A\n * header built on the old baked plate has ~62,000 — its headline is part of the\n * image. That gap is what lets {@link stampHeadline}'s caller refuse to print a\n * second headline over the first. PURE.\n */\nexport async function headlineInkCount(header: Uint8Array): Promise<number> {\n const { data, info } = await sharp(Buffer.from(header))\n .extract({\n left: HEADLINE_BAND.x,\n top: HEADLINE_BAND.y,\n width: HEADLINE_BAND.w,\n height: HEADLINE_BAND.h,\n })\n .removeAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n let n = 0;\n for (let i = 0; i < data.length; i += info.channels) {\n const r = data[i] ?? 0;\n const g = data[i + 1] ?? 0;\n const b = data[i + 2] ?? 0;\n // Generous band around the brand red rather than an exact match: the stored\n // header is a JPEG, so its ink has been through lossy re-encoding.\n if (r > HEADLINE_INK.r - 60 && g < HEADLINE_INK.g + 60 && b < HEADLINE_INK.b + 60) n++;\n }\n return n;\n}\n\n/**\n * Stamp a report-type headline overlay onto a finished (clean-plate) header at\n * the measured HEADLINE origin. PURE and strict: the header must be exactly\n * CANVAS-sized — a legacy hand-made header at other dimensions would misplace\n * the text, so the caller (applyReportTypeHeadline) size-guards and skips\n * instead of calling in. One extra JPEG generation at quality 88 is invisible\n * at the email's 600px display size.\n */\nexport async function stampHeadline(header: Uint8Array, headline: Uint8Array): Promise<Uint8Array> {\n const meta = await sharp(Buffer.from(header)).metadata();\n if (meta.width !== CANVAS.width || meta.height !== CANVAS.height) {\n throw new Error(\n `stampHeadline: header is ${meta.width}x${meta.height}, expected ${CANVAS.width}x${CANVAS.height}`,\n );\n }\n const out = await sharp(Buffer.from(header))\n .composite([{ input: Buffer.from(headline), left: HEADLINE.x, top: HEADLINE.y }])\n .jpeg({ quality: JPEG_QUALITY })\n .toBuffer();\n return new Uint8Array(out);\n}\n"],"mappings":";AAuCO,IAAM,SAAS,EAAE,OAAO,MAAM,QAAQ,KAAK;AAY3C,IAAM,SAAS,EAAE,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI;AASlD,IAAM,WAAW,EAAE,GAAG,KAAK,GAAG,IAAI;AAOlC,IAAM,gBAAgB,EAAE,GAAG,SAAS,GAAG,GAAG,SAAS,GAAG,GAAG,MAAM,GAAG,IAAI;AAItE,IAAM,eAAe,EAAE,GAAG,KAAK,GAAG,IAAI,GAAG,GAAG;AAW5C,IAAM,SAAS;AAAA,EACpB,GAAG;AAAA,EACH,UAAU;AAAA,EACV,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACT;AAIO,IAAM,QAAQ;;;AC5FrB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAE9B,IAAM,QAAQ;AA8Bd,IAAM,iBAAiB;AAAA,EACrB,aAAa;AAAA,EACb,SAAS;AAAA,EACT,cAAc;AAAA,EACd,QAAQ;AACV;AAKO,SAAS,gBAAgB,YAAyC;AACvE,SAAO,OAAO,OAAO,gBAAgB,UAAU,IAAK,aAA8B;AACpF;AAUA,IAAI,kBAAiC;AACrC,SAAS,mBAA2B;AAClC,MAAI,gBAAiB,QAAO;AAC5B,MAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;AAChD,aAAS;AAC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,aAAa,IAAI,CAAC;AAAA,EAC7D,SAAS,KAAK;AACZ,YAAQ;AAAA,MACN,mCAA8B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAChF;AACA,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,oBAAoB,OAAqD;AAC7F,QAAM,aAAa,MAAM,gBAAgB,MAAM,KAAK;AAAA,IAClD,GAAI,MAAM,YAAY,SAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,IAChE,GAAI,MAAM,aAAa,SAAY,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;AAAA,IACnE,GAAI,MAAM,oBAAoB,SAAY,EAAE,iBAAiB,MAAM,gBAAgB,IAAI,CAAC;AAAA,EAC1F,CAAC;AACD,QAAM,eAAe,UAAU;AAE/B,QAAM,SAAS,cAAc,MAAM,GAAG;AACtC,QAAM,QAAQ,MAAM,mBAAmB;AAAA,IACrC,OAAO,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACD,QAAM,OAAO,MAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,CAAC;AAC9C,SAAO,EAAE,OAAO,QAAQ,UAAU,GAAG,IAAI,cAAc,aAAa,aAAa;AACnF;","names":["sharp","sharp"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runMigrations
3
- } from "./chunk-T76MA2FH.js";
3
+ } from "./chunk-IOTOOTII.js";
4
4
  import {
5
5
  defaultCredentialsPath
6
6
  } from "./chunk-6VAL7XJT.js";
@@ -48,4 +48,4 @@ export {
48
48
  readDbConfig,
49
49
  openDb
50
50
  };
51
- //# sourceMappingURL=chunk-6INOBNRO.js.map
51
+ //# sourceMappingURL=chunk-MMSMZC7S.js.map
@@ -28,11 +28,10 @@ function resolveToken(exec) {
28
28
  function readGitHubConfig(opts = {}) {
29
29
  const token = resolveToken(opts.execFileSync);
30
30
  if (!token) return null;
31
- const renovateToken = process.env.RENOVATE_TOKEN?.trim() || token;
32
- return { token, renovateToken };
31
+ return { token };
33
32
  }
34
33
 
35
34
  export {
36
35
  readGitHubConfig
37
36
  };
38
- //# sourceMappingURL=chunk-CGQZFQAY.js.map
37
+ //# sourceMappingURL=chunk-MVKNU4QD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/github/config.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\n\nexport type GitHubConfig = {\n /** Broad PAT used by the tool's own `gh` calls (PRs, branch protection, secrets). */\n token: string;\n};\n\n/** The shape of `node:child_process`'s `execFileSync` that `ghAuthToken` needs —\n * injectable so a test never shells out (and never depends on the runner's\n * own keyring). */\nexport type ExecFileSyncFn = (\n cmd: string,\n args: readonly string[],\n opts: {\n env: NodeJS.ProcessEnv;\n encoding: \"utf8\";\n stdio: [\"ignore\", \"pipe\", \"ignore\"];\n timeout: number;\n },\n) => string;\n\nconst defaultExecFileSync: ExecFileSyncFn = (cmd, args, opts) => execFileSync(cmd, [...args], opts);\n\n/**\n * The token `gh` itself is logged in with (`gh auth token`), or null when `gh`\n * is missing, not logged in, or prints nothing. #665.\n *\n * Two traps, both from the issue:\n *\n * - `gh auth token` ECHOES `$GITHUB_TOKEN` / `$GH_TOKEN` back when either is\n * set, so the child runs with both stripped. Without that a dead file token\n * makes the good keyring token look dead as well — which is exactly how the\n * original failure was misdiagnosed once.\n * - The token is NOT validated by pinging an endpoint. A fine-grained token can\n * be refused by `/user` and still be fully working for the calls it is scoped\n * to; \"validating\" it there would declare working tokens dead.\n *\n * stderr is discarded (gh prints its \"not logged in\" hint there) and the call\n * is bounded so a wedged keychain prompt cannot hang a recipe.\n */\nexport function ghAuthToken(exec: ExecFileSyncFn = defaultExecFileSync): string | null {\n const { GITHUB_TOKEN: _github, GH_TOKEN: _gh, ...env } = process.env;\n void _github;\n void _gh;\n try {\n const out = exec(\"gh\", [\"auth\", \"token\"], {\n env,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5_000,\n });\n return out.trim() || null;\n } catch {\n return null;\n }\n}\n\n/**\n * The broad token, from the environment or the keyring, or null for \"nobody has\n * one\". `GITHUB_TOKEN` has THREE states here, not two, and the third is the one\n * #665's fix collapsed by accident:\n *\n * - **Absent** — the recommended shape. Ask `gh auth token`.\n * - **Set to a value** — that value wins; `gh` is never asked.\n * - **Set to the EMPTY STRING** — `GITHUB_TOKEN=` in a shell, an env block, or\n * a test's `vi.stubEnv(\"GITHUB_TOKEN\", \"\")`. That is a DELIBERATE \"no token\",\n * and it must resolve to null rather than quietly reaching past the operator\n * to the keyring. Under the previous `?.trim() || ghAuthToken()` it did not:\n * `\"\"` is falsy, so an explicitly-disabled token fell through and a machine\n * that had run `gh auth login` silently resolved one anyway. The token gate\n * then read as configured on a developer's laptop and unconfigured in CI —\n * the same code taking different paths on ambient login state, which is how\n * `tests/cli/prismic-ci-command.test.ts` came to pass only where `gh` was\n * logged out.\n *\n * Whitespace-only is NOT the empty string and keeps falling through to the\n * keyring: `GITHUB_TOKEN=\" \"` is a mis-pasted `credentials.env` line, never\n * an instruction, and #665 exists precisely so a bad file value cannot override\n * a working keyring credential.\n */\nfunction resolveToken(exec?: ExecFileSyncFn): string | null {\n const set = process.env.GITHUB_TOKEN;\n if (set === undefined) return ghAuthToken(exec);\n const trimmed = set.trim();\n if (trimmed) return trimmed;\n if (set === \"\") return null; // explicitly disabled — do not consult the keyring\n return ghAuthToken(exec); // blank-but-not-empty: an accident, not a decision\n}\n\n/**\n * Read GitHub config from the environment (credentials.env is loaded into process.env by the CLI).\n *\n * `GITHUB_TOKEN` wins when set; when it is ABSENT the token comes from\n * `gh auth token` — the keyring `gh auth login` populated — so `GITHUB_TOKEN`\n * may be left OUT of `credentials.env` entirely, and should be: `gh.ts` hands\n * this token to `gh` as `GH_TOKEN`, so a set-but-dead file value actively\n * overrides a working keyring credential, and a file COPY of the keyring token\n * goes stale on the next `gh auth login/refresh/logout` (#665). Returns null\n * only when neither source has a token — the signal that git/GitHub features\n * aren't configured.\n */\nexport function readGitHubConfig(\n opts: { execFileSync?: ExecFileSyncFn } = {},\n): GitHubConfig | null {\n const token = resolveToken(opts.execFileSync);\n if (!token) return null;\n return { token };\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAqB7B,IAAM,sBAAsC,CAAC,KAAK,MAAM,SAAS,aAAa,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI;AAmB3F,SAAS,YAAY,OAAuB,qBAAoC;AACrF,QAAM,EAAE,cAAc,SAAS,UAAU,KAAK,GAAG,IAAI,IAAI,QAAQ;AACjE,OAAK;AACL,OAAK;AACL,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,CAAC,QAAQ,OAAO,GAAG;AAAA,MACxC;AAAA,MACA,UAAU;AAAA,MACV,OAAO,CAAC,UAAU,QAAQ,QAAQ;AAAA,MAClC,SAAS;AAAA,IACX,CAAC;AACD,WAAO,IAAI,KAAK,KAAK;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAyBA,SAAS,aAAa,MAAsC;AAC1D,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,QAAQ,OAAW,QAAO,YAAY,IAAI;AAC9C,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,QAAS,QAAO;AACpB,MAAI,QAAQ,GAAI,QAAO;AACvB,SAAO,YAAY,IAAI;AACzB;AAcO,SAAS,iBACd,OAA0C,CAAC,GACtB;AACrB,QAAM,QAAQ,aAAa,KAAK,YAAY;AAC5C,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,EAAE,MAAM;AACjB;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  approveBlockers
3
- } from "./chunk-OTEVKRAH.js";
3
+ } from "./chunk-VMGHQUTV.js";
4
4
  import {
5
5
  ACTIVE_STATUSES,
6
6
  allActionableVulnsTransitive,
7
7
  isPreLaunch,
8
8
  siteSlug
9
- } from "./chunk-KN52PM63.js";
9
+ } from "./chunk-ICSRWW5Q.js";
10
10
 
11
11
  // src/alerts/digest-collectors.ts
12
12
  function dashboardUrl(baseUrl, siteName) {
@@ -337,4 +337,4 @@ export {
337
337
  prismicAckIsLive,
338
338
  collectPrismicDriftAlerts
339
339
  };
340
- //# sourceMappingURL=chunk-62YWOFVN.js.map
340
+ //# sourceMappingURL=chunk-PARKXDXI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/digest-collectors.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\";\nimport type { NotifyBounceCounts } from \"../db/submissions.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 form-e2e run older than this can't confirm the CURRENT widget state. The run\n * is nightly, so 3 days (mirrors GITHUB_SIGNALS_STALE_DAYS) tolerates a weekend of\n * 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 Turnstile\n * widget is known BROKEN (`turnstileWidget === \"fail\"`, fresh per\n * {@link TURNSTILE_WIDGET_STALE_DAYS}). That combination silently buckets 100% of the\n * site's real leads (token-less submissions escalate to spam_auto with notify skipped),\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 // The stamp of the audit that OWNS the verdict, not function-health's.\n // `form-e2e` took ownership of `turnstileWidget` (#689) because only it opens\n // a browser on the real widget; function-health merely re-stamped its own\n // clock at 08:00 whether or not anything had looked at Turnstile, so gating on\n // it would age a verdict against a timer that never stops — freezing a stale\n // \"fail\" into a red that pages every morning and can never be muted. Verdict\n // and stamp are now written in the SAME FieldSet (`formE2eFields`), so they\n // always move together; `turnstile-freshness.test.ts` pins that coupling.\n const at = s.formE2eCheckedAt;\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 // Sensor-neutral, and it has to be: the verdict now has TWO fail arms and the\n // row carries no discriminator. Naming /health sent the operator to Netlify to\n // check a `PUBLIC_TURNSTILE_SITE_KEY` that is correctly set — because on the\n // only site that can raise this alarm (Require Turnstile presupposes the key)\n // the reachable arm is the OTHER one: a browser seeing 110200, i.e. the\n // hostname missing from the Cloudflare widget's allowlist. Both causes are\n // named so the runbook fix is the obvious next step.\n title:\n \"Require Turnstile is ON but no working widget was found (no sitekey, or the \" +\n \"hostname is not on the Cloudflare widget's allowlist) — 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, NotifyBounceCounts>,\n baseUrl: string,\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n const counts = bouncedBySite.get(s.id);\n const n = counts?.total ?? 0;\n if (n < NOTIFY_BOUNCE_THRESHOLD) continue;\n // #783. ONE permanent bounce is enough to keep accusing the address: Resend\n // said the mailbox itself is bad, and that outranks any number of transient\n // refusals alongside it. With none, the address is not the suspect — the\n // receiving server refused our CONTENT, which is what happened to Espada,\n // and \"check the point-of-contact address\" sent the operator to inspect the\n // one thing that was working.\n //\n // An UNCLASSIFIED count (every row written before migration 0018, and every\n // complaint) takes the filter wording too. That is the safe direction: the\n // old title asserted a dead address on no evidence at all.\n const addressIsSuspect = (counts?.permanent ?? 0) > 0;\n items.push({\n key: `notify-bounce:${s.id}`,\n kind: \"notify-bounce\",\n siteName: s.name,\n title: addressIsSuspect\n ? `${n} lead notifications bounced (${NOTIFY_BOUNCE_WINDOW_DAYS}d) — check the point-of-contact address`\n : `${n} lead notifications bounced (${NOTIFY_BOUNCE_WINDOW_DAYS}d) — the client's mail filter is rejecting them; acknowledge them on the site page if the address is fine`,\n url: dashboardUrl(baseUrl, s.name),\n // Critical either way: severity is about the LEAD, which reached nobody in\n // both cases. Only the instruction changes.\n severity: \"critical\",\n metric: n,\n });\n }\n return items;\n}\n\n/**\n * One CRITICAL attention item per slug holding unreplayed dead-letter rows —\n * leads that were captured but never placed (#645).\n *\n * CRITICAL at a single row, unlike notify-bounce's threshold of 2. A bounce may\n * be a greylist blip; a dead letter is by construction a lead that reached\n * nobody, and post-flip the commonest way to get one is a site whose Turso row\n * is missing — the fleet's only silent, permanent lead-loser.\n *\n * Keyed `deadletter:<slug>` because the queue is keyed by slug and the worst case\n * is precisely a slug that resolves to no site. Such a slug is NOT dropped: it\n * gets the `(unknown site: …)` pseudo-name (the `(unlinked site)` precedent above)\n * and no `url`, since `/s/<slug>` would 404. `metric` is the row count, so a\n * growing queue diffs WORSE. PURE: takes pre-fetched counts\n * (`countUnreplayedDeadLettersBySlug`); slug-ordered for a stable digest.\n */\nexport function collectDeadLetterAlerts(\n sites: WebsiteRow[],\n unreplayedBySlug: ReadonlyMap<string, number>,\n baseUrl: string,\n): AttentionItem[] {\n const bySlug = new Map<string, WebsiteRow>();\n for (const s of sites) {\n const slug = siteSlug(s.name);\n if (slug) bySlug.set(slug, s);\n }\n const items: AttentionItem[] = [];\n for (const slug of [...unreplayedBySlug.keys()].sort()) {\n const n = unreplayedBySlug.get(slug) ?? 0;\n if (n < 1) continue;\n const site = bySlug.get(slug);\n const noun = n === 1 ? \"lead\" : \"leads\";\n items.push({\n key: `deadletter:${slug}`,\n kind: \"deadletter\",\n siteName: site ? site.name : `(unknown site: ${slug})`,\n title: site\n ? `${n} ${noun} dead-lettered and not yet replayed — run \\`db replay-deadletters\\``\n : `${n} ${noun} dead-lettered for '${slug}', which resolves to NO fleet site — leads are being dropped; run \\`ensure-site ${slug}\\` then \\`db replay-deadletters\\``,\n // No link for an unresolvable slug: /s/<slug> would 404, and the\n // collectors' own rule is never to render a broken link.\n ...(site ? { url: dashboardUrl(baseUrl, site.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 */\n/**\n * Is an operator's acceptance of a known divergence still in force?\n *\n * Every uncertain answer is `false` — an absent, blank or unparseable cell leaves\n * the alarm ringing. The asymmetry is the point: a mistyped date costing one noisy\n * item is recoverable, and a mistyped date silently muting a live finding is the\n * exact failure this column was built to close. The boundary belongs to the alarm\n * too: an ack \"until 09:00\" has nothing left to say at 09:00.\n */\nexport function prismicAckIsLive(ackUntil: string | null, now: Date): boolean {\n if (ackUntil === null || ackUntil.trim() === \"\") return false;\n const until = Date.parse(ackUntil);\n if (!Number.isFinite(until)) return false;\n return until > now.getTime();\n}\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 // The operator has reviewed THIS divergence and accepted it until a date they\n // set — see `WebsiteRow.prismicAckUntil`. Reached only on `fail`: the `unknown`\n // and staleness branches above have already returned, so an ack can never mute\n // \"the check could not run\" or \"nobody has re-established this\".\n if (prismicAckIsLive(s.prismicAckUntil, now)) continue;\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"],"mappings":";;;;;;;;;;;AAgBA,SAAS,aAAa,SAAiB,UAA0B;AAC/D,QAAM,OAAO,QAAQ,QAAQ,OAAO,EAAE;AACtC,QAAM,OAAO,SAAS,QAAQ;AAC9B,SAAO,OAAO,GAAG,IAAI,MAAM,IAAI,KAAK;AACtC;AAWA,IAAM,4BAA4B;AAClC,IAAM,aAAa,KAAK,KAAK,KAAK;AAMlC,SAAS,mBAAmB,OAAsB,KAAoB;AACpE,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,QAAQ,IAAI,QAAQ,IAAI,KA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sources":["../src/alerts/digest-collectors.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\";\nimport type { NotifyBounceCounts } from \"../db/submissions.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 form-e2e run older than this can't confirm the CURRENT widget state. The run\n * is nightly, so 3 days (mirrors GITHUB_SIGNALS_STALE_DAYS) tolerates a weekend of\n * 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 Turnstile\n * widget is known BROKEN (`turnstileWidget === \"fail\"`, fresh per\n * {@link TURNSTILE_WIDGET_STALE_DAYS}). That combination silently buckets 100% of the\n * site's real leads (token-less submissions escalate to spam_auto with notify skipped),\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 // The stamp of the audit that OWNS the verdict, not function-health's.\n // `form-e2e` took ownership of `turnstileWidget` (#689) because only it opens\n // a browser on the real widget; function-health merely re-stamped its own\n // clock at 08:00 whether or not anything had looked at Turnstile, so gating on\n // it would age a verdict against a timer that never stops — freezing a stale\n // \"fail\" into a red that pages every morning and can never be muted. Verdict\n // and stamp are now written in the SAME FieldSet (`formE2eFields`), so they\n // always move together; `turnstile-freshness.test.ts` pins that coupling.\n const at = s.formE2eCheckedAt;\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 // Sensor-neutral, and it has to be: the verdict now has TWO fail arms and the\n // row carries no discriminator. Naming /health sent the operator to Netlify to\n // check a `PUBLIC_TURNSTILE_SITE_KEY` that is correctly set — because on the\n // only site that can raise this alarm (Require Turnstile presupposes the key)\n // the reachable arm is the OTHER one: a browser seeing 110200, i.e. the\n // hostname missing from the Cloudflare widget's allowlist. Both causes are\n // named so the runbook fix is the obvious next step.\n title:\n \"Require Turnstile is ON but no working widget was found (no sitekey, or the \" +\n \"hostname is not on the Cloudflare widget's allowlist) — 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, NotifyBounceCounts>,\n baseUrl: string,\n): AttentionItem[] {\n const items: AttentionItem[] = [];\n for (const s of sites) {\n const counts = bouncedBySite.get(s.id);\n const n = counts?.total ?? 0;\n if (n < NOTIFY_BOUNCE_THRESHOLD) continue;\n // #783. ONE permanent bounce is enough to keep accusing the address: Resend\n // said the mailbox itself is bad, and that outranks any number of transient\n // refusals alongside it. With none, the address is not the suspect — the\n // receiving server refused our CONTENT, which is what happened to Espada,\n // and \"check the point-of-contact address\" sent the operator to inspect the\n // one thing that was working.\n //\n // An UNCLASSIFIED count (every row written before migration 0018, and every\n // complaint) takes the filter wording too. That is the safe direction: the\n // old title asserted a dead address on no evidence at all.\n const addressIsSuspect = (counts?.permanent ?? 0) > 0;\n items.push({\n key: `notify-bounce:${s.id}`,\n kind: \"notify-bounce\",\n siteName: s.name,\n title: addressIsSuspect\n ? `${n} lead notifications bounced (${NOTIFY_BOUNCE_WINDOW_DAYS}d) — check the point-of-contact address`\n : `${n} lead notifications bounced (${NOTIFY_BOUNCE_WINDOW_DAYS}d) — the client's mail filter is rejecting them; acknowledge them on the site page if the address is fine`,\n url: dashboardUrl(baseUrl, s.name),\n // Critical either way: severity is about the LEAD, which reached nobody in\n // both cases. Only the instruction changes.\n severity: \"critical\",\n metric: n,\n });\n }\n return items;\n}\n\n/**\n * One CRITICAL attention item per slug holding unreplayed dead-letter rows —\n * leads that were captured but never placed (#645).\n *\n * CRITICAL at a single row, unlike notify-bounce's threshold of 2. A bounce may\n * be a greylist blip; a dead letter is by construction a lead that reached\n * nobody, and post-flip the commonest way to get one is a site whose Turso row\n * is missing — the fleet's only silent, permanent lead-loser.\n *\n * Keyed `deadletter:<slug>` because the queue is keyed by slug and the worst case\n * is precisely a slug that resolves to no site. Such a slug is NOT dropped: it\n * gets the `(unknown site: …)` pseudo-name (the `(unlinked site)` precedent above)\n * and no `url`, since `/s/<slug>` would 404. `metric` is the row count, so a\n * growing queue diffs WORSE. PURE: takes pre-fetched counts\n * (`countUnreplayedDeadLettersBySlug`); slug-ordered for a stable digest.\n */\nexport function collectDeadLetterAlerts(\n sites: WebsiteRow[],\n unreplayedBySlug: ReadonlyMap<string, number>,\n baseUrl: string,\n): AttentionItem[] {\n const bySlug = new Map<string, WebsiteRow>();\n for (const s of sites) {\n const slug = siteSlug(s.name);\n if (slug) bySlug.set(slug, s);\n }\n const items: AttentionItem[] = [];\n for (const slug of [...unreplayedBySlug.keys()].sort()) {\n const n = unreplayedBySlug.get(slug) ?? 0;\n if (n < 1) continue;\n const site = bySlug.get(slug);\n const noun = n === 1 ? \"lead\" : \"leads\";\n items.push({\n key: `deadletter:${slug}`,\n kind: \"deadletter\",\n siteName: site ? site.name : `(unknown site: ${slug})`,\n title: site\n ? `${n} ${noun} dead-lettered and not yet replayed — run \\`db replay-deadletters\\``\n : `${n} ${noun} dead-lettered for '${slug}', which resolves to NO fleet site — leads are being dropped; run \\`ensure-site ${slug}\\` then \\`db replay-deadletters\\``,\n // No link for an unresolvable slug: /s/<slug> would 404, and the\n // collectors' own rule is never to render a broken link.\n ...(site ? { url: dashboardUrl(baseUrl, site.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 turso` sweep is EXPECTED to\n * cover this site. Mirrors the fleet inventory's own filter (src/inventory/\n * select.ts): live `maintained` 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-back` 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 */\n/**\n * Is an operator's acceptance of a known divergence still in force?\n *\n * Every uncertain answer is `false` — an absent, blank or unparseable cell leaves\n * the alarm ringing. The asymmetry is the point: a mistyped date costing one noisy\n * item is recoverable, and a mistyped date silently muting a live finding is the\n * exact failure this column was built to close. The boundary belongs to the alarm\n * too: an ack \"until 09:00\" has nothing left to say at 09:00.\n */\nexport function prismicAckIsLive(ackUntil: string | null, now: Date): boolean {\n if (ackUntil === null || ackUntil.trim() === \"\") return false;\n const until = Date.parse(ackUntil);\n if (!Number.isFinite(until)) return false;\n return until > now.getTime();\n}\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 // The operator has reviewed THIS divergence and accepted it until a date they\n // set — see `WebsiteRow.prismicAckUntil`. Reached only on `fail`: the `unknown`\n // and staleness branches above have already returned, so an ack can never mute\n // \"the check could not run\" or \"nobody has re-established this\".\n if (prismicAckIsLive(s.prismicAckUntil, now)) continue;\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"],"mappings":";;;;;;;;;;;AAgBA,SAAS,aAAa,SAAiB,UAA0B;AAC/D,QAAM,OAAO,QAAQ,QAAQ,OAAO,EAAE;AACtC,QAAM,OAAO,SAAS,QAAQ;AAC9B,SAAO,OAAO,GAAG,IAAI,MAAM,IAAI,KAAK;AACtC;AAWA,IAAM,4BAA4B;AAClC,IAAM,aAAa,KAAK,KAAK,KAAK;AAMlC,SAAS,mBAAmB,OAAsB,KAAoB;AACpE,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,QAAQ,IAAI,QAAQ,IAAI,KAAK,MAAM,KAAK;AAC9C,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,SAAO,QAAQ,4BAA4B;AAC7C;AAGA,IAAM,4BAA4B;AAuB3B,SAAS,kBAAkB,OAAqB,SAAkC;AACvF,QAAM,QAAyB,CAAC;AAChC,aAAW,KAAK,OAAO;AACrB,UAAM,WAAW,EAA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,mBAAmB,CAAC,EAAG;AAC5B,YAAM,KAAK;AAAA,QACT,KAAK,iBAAiB,EAAE,EAAE;AAAA,QAC1B,MAAM;AAAA,QACN,UAAU,EAAE;AAAA,QACZ,OAAO,sEAAiE,OAAO;AAAA,QAC/E,KAAK,aAAa,SAAS,EAAE,IAAI;AAAA,QACjC,UAAU;AAAA,QACV,QAAQ;AAAA,MACV,CAAC;AACD;AAAA,IACF;AAEA,QAAI,YAAY,OAAQ;AAExB,UAAM,QAAQ,EAAE,oBACZ,MAAM,IAAI,EACX,KAAK,CAAC,MAAM,EAAE,KAAK,MAAM,EAAE,GAC1B,KAAK;AACT,QAAI,YAAY,WAAW;AACzB,YAAM,KAAK;AAAA,QACT,KAAK,mBAAmB,EAAE,EAAE;AAAA,QAC5B,MAAM;AAAA,QACN,UAAU,EAAE;AAAA,QACZ,OAAO,QACH,4CAAuC,KAAK,KAC5C;AAAA,QACJ,KAAK,aAAa,SAAS,EAAE,IAAI;AAAA,QACjC,UAAU;AAAA,QACV,QAAQ;AAAA,MACV,CAAC;AACD;AAAA,IACF;AAMA,QAAI,iBAAiB,EAAE,iBAAiB,GAAG,EAAG;AAE9C,UAAM,KAAK;AAAA,MACT,KAAK,iBAAiB,EAAE,EAAE;AAAA,MAC1B,MAAM;AAAA,MACN,UAAU,EAAE;AAAA,MACZ,OAAO,QACH,+CAA0C,KAAK,KAC/C;AAAA,MACJ,KAAK,aAAa,SAAS,EAAE,IAAI;AAAA,MACjC,UAAU;AAAA,MACV,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":[]}
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  fetchGaUsers,
3
3
  fetchSearch
4
- } from "./chunk-72FJZ6LO.js";
4
+ } from "./chunk-DRNZVORX.js";
5
5
  import {
6
6
  announcementSiteExtras,
7
7
  resolveCopy
8
8
  } from "./chunk-KJGKZLCT.js";
9
9
  import {
10
10
  siteSlug
11
- } from "./chunk-KN52PM63.js";
11
+ } from "./chunk-ICSRWW5Q.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-44SDGPGQ.js.map
63
+ //# sourceMappingURL=chunk-PZZ6HM5T.js.map
@@ -0,0 +1,51 @@
1
+ // src/fleet/site-id.ts
2
+ var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3
+ var MAX_TIME = 2 ** 48 - 1;
4
+ function encodeUlid(timeMs, random) {
5
+ if (!Number.isInteger(timeMs) || timeMs < 0 || timeMs > MAX_TIME) {
6
+ throw new Error(`encodeUlid: time ${timeMs} is not a 48-bit millisecond timestamp`);
7
+ }
8
+ if (random.length !== 10) {
9
+ throw new Error(`encodeUlid: needs exactly 10 random bytes, got ${random.length}`);
10
+ }
11
+ let time = "";
12
+ let t = timeMs;
13
+ for (let i = 0; i < 10; i++) {
14
+ time = ALPHABET[t % 32] + time;
15
+ t = Math.floor(t / 32);
16
+ }
17
+ let rand = "";
18
+ let buffer = 0;
19
+ let bits = 0;
20
+ for (const byte of random) {
21
+ buffer = buffer << 8 | byte;
22
+ bits += 8;
23
+ while (bits >= 5) {
24
+ bits -= 5;
25
+ rand += ALPHABET[buffer >> bits & 31];
26
+ }
27
+ buffer &= (1 << bits) - 1;
28
+ }
29
+ return time + rand;
30
+ }
31
+ function mintSiteId(now = Date.now()) {
32
+ const random = new Uint8Array(10);
33
+ globalThis.crypto.getRandomValues(random);
34
+ return `site_${encodeUlid(now, random)}`;
35
+ }
36
+ function isAirtableRecordId(id) {
37
+ return id.length > 3 && id.startsWith("rec");
38
+ }
39
+ function skipsAirtableShadow(writer, id) {
40
+ if (isAirtableRecordId(id)) return false;
41
+ console.log(`AIRTABLE_SHADOW skipped=non-rec-id writer=${writer} id=${id}`);
42
+ return true;
43
+ }
44
+
45
+ export {
46
+ encodeUlid,
47
+ mintSiteId,
48
+ isAirtableRecordId,
49
+ skipsAirtableShadow
50
+ };
51
+ //# sourceMappingURL=chunk-RQJFGK3A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fleet/site-id.ts"],"sourcesContent":["/**\n * Site ids after Airtable (#646 step 3, operator decision 2026-09-17).\n *\n * Two shapes coexist PERMANENTLY:\n *\n * - `rec…` every site that existed before the Turso-native creator. The\n * Airtable record id became the Turso primary key at import\n * (design D1), and it is never rewritten: `submissions.site_id`,\n * `reports.site_id`, `fleet_events`, `spam_screenouts`,\n * `digest_state` keys and event ids all hold it by convention.\n * - `site_<ULID>` every site created since, minted here.\n *\n * Neither is the external handle. The stored unique `sites.slug` is — URLs,\n * `/api/forms/:slug` and deployed sites all use it — so the id is free to be\n * whatever sorts and stays unique.\n *\n * ## Why a local ULID and not a dependency\n *\n * Nothing in the dependency tree implements ULID (checked 2026-09-17: the only\n * id-ish package is a transitive `nanoid`, which is not time-sortable and is not\n * ours to import). The encoding is 30 lines of arithmetic over a spec that has\n * not changed since 2016, this package is published to fleet sites, and adding a\n * runtime dependency for it would cost every consumer an install. The random\n * half comes from `globalThis.crypto` (Web Crypto, present in Node 20+ and in\n * Netlify functions), so the module needs no `node:` import either.\n *\n * Not monotonic within a millisecond: two ids minted in the same ms order by\n * their random half. Sites are created by hand, one command at a time; nothing\n * needs a strict order finer than the millisecond.\n */\n\n/** Crockford base32, the ULID alphabet (no I, L, O, U). */\nconst ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst MAX_TIME = 2 ** 48 - 1;\n\n/**\n * Encode a ULID from a millisecond timestamp and 10 random bytes: 10 chars of\n * big-endian time, then 16 chars of the 80 random bits. Pure, so tests can pin it.\n */\nexport function encodeUlid(timeMs: number, random: Uint8Array): string {\n if (!Number.isInteger(timeMs) || timeMs < 0 || timeMs > MAX_TIME) {\n throw new Error(`encodeUlid: time ${timeMs} is not a 48-bit millisecond timestamp`);\n }\n if (random.length !== 10) {\n throw new Error(`encodeUlid: needs exactly 10 random bytes, got ${random.length}`);\n }\n let time = \"\";\n let t = timeMs;\n for (let i = 0; i < 10; i++) {\n time = ALPHABET[t % 32]! + time;\n t = Math.floor(t / 32);\n }\n // 80 bits → 16 five-bit groups. Accumulate MSB-first; the buffer never holds\n // more than 12 bits, so plain numbers stay exact.\n let rand = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of random) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n rand += ALPHABET[(buffer >> bits) & 31]!;\n }\n buffer &= (1 << bits) - 1;\n }\n return time + rand;\n}\n\n/** Mint a new site id: `site_<ULID>`. */\nexport function mintSiteId(now: number = Date.now()): string {\n const random = new Uint8Array(10);\n globalThis.crypto.getRandomValues(random);\n return `site_${encodeUlid(now, random)}`;\n}\n\n/** A `rec…` id — the only shape Airtable can address. Deliberately a PREFIX test,\n * the decision's own wording (\"skip non-`rec` ids\"): real Airtable ids are\n * `rec` + 14 alphanumerics, but the suite's fixtures use readable ones like\n * `rec_site_acme`, and in production the only other shape that exists is\n * `site_<ULID>`, which this rejects either way. */\nexport function isAirtableRecordId(id: string): boolean {\n return id.length > 3 && id.startsWith(\"rec\");\n}\n\n/** A site id minted by {@link mintSiteId}. */\nexport function isMintedSiteId(id: string): boolean {\n return /^site_[0-9A-HJKMNP-TV-Z]{26}$/.test(id);\n}\n\n/**\n * The one decision every Airtable SHADOW writer makes before touching Airtable:\n * is this a record Airtable could possibly hold? A `site_` id never is — the site\n * was created in Turso and Airtable has never heard of it — so the write is\n * skipped ON PURPOSE rather than sent to 404.\n *\n * Returns `true` when the caller must skip, after logging exactly one stable,\n * greppable line:\n *\n * AIRTABLE_SHADOW skipped=non-rec-id writer=<name> id=<id>\n *\n * Logged rather than silent because a skip is a decision someone may need to\n * audit: \"why does Airtable not have this site's scores\" should be one grep away.\n * Lives outside `src/reports/airtable/` so the Turso-native creator can use it\n * without importing the layer Phase 6 deletes.\n */\nexport function skipsAirtableShadow(writer: string, id: string): boolean {\n if (isAirtableRecordId(id)) return false;\n console.log(`AIRTABLE_SHADOW skipped=non-rec-id writer=${writer} id=${id}`);\n return true;\n}\n"],"mappings":";AAgCA,IAAM,WAAW;AACjB,IAAM,WAAW,KAAK,KAAK;AAMpB,SAAS,WAAW,QAAgB,QAA4B;AACrE,MAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,KAAK,SAAS,UAAU;AAChE,UAAM,IAAI,MAAM,oBAAoB,MAAM,wCAAwC;AAAA,EACpF;AACA,MAAI,OAAO,WAAW,IAAI;AACxB,UAAM,IAAI,MAAM,kDAAkD,OAAO,MAAM,EAAE;AAAA,EACnF;AACA,MAAI,OAAO;AACX,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,WAAO,SAAS,IAAI,EAAE,IAAK;AAC3B,QAAI,KAAK,MAAM,IAAI,EAAE;AAAA,EACvB;AAGA,MAAI,OAAO;AACX,MAAI,SAAS;AACb,MAAI,OAAO;AACX,aAAW,QAAQ,QAAQ;AACzB,aAAU,UAAU,IAAK;AACzB,YAAQ;AACR,WAAO,QAAQ,GAAG;AAChB,cAAQ;AACR,cAAQ,SAAU,UAAU,OAAQ,EAAE;AAAA,IACxC;AACA,eAAW,KAAK,QAAQ;AAAA,EAC1B;AACA,SAAO,OAAO;AAChB;AAGO,SAAS,WAAW,MAAc,KAAK,IAAI,GAAW;AAC3D,QAAM,SAAS,IAAI,WAAW,EAAE;AAChC,aAAW,OAAO,gBAAgB,MAAM;AACxC,SAAO,QAAQ,WAAW,KAAK,MAAM,CAAC;AACxC;AAOO,SAAS,mBAAmB,IAAqB;AACtD,SAAO,GAAG,SAAS,KAAK,GAAG,WAAW,KAAK;AAC7C;AAuBO,SAAS,oBAAoB,QAAgB,IAAqB;AACvE,MAAI,mBAAmB,EAAE,EAAG,QAAO;AACnC,UAAQ,IAAI,6CAA6C,MAAM,OAAO,EAAE,EAAE;AAC1E,SAAO;AACT;","names":[]}