@reddoorla/maintenance 0.86.0 → 0.87.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.
- package/dist/airtable-ZBUPQJSC.js +9 -0
- package/dist/{announce-MXTUQ6C7.js → announce-I2Z4JN3I.js} +49 -28
- package/dist/announce-I2Z4JN3I.js.map +1 -0
- package/dist/attachments-NLZIJ5NU.js +9 -0
- package/dist/{bump-deps-EC74CPLS.js → bump-deps-CGVELRLK.js} +2 -2
- package/dist/{chunk-2ZPT7GLV.js → chunk-3JQ2FO3D.js} +3 -3
- package/dist/chunk-3JQ2FO3D.js.map +1 -0
- package/dist/{chunk-KTH5ZODA.js → chunk-7BZUOZPU.js} +2 -2
- package/dist/{chunk-LDWZSLSU.js → chunk-7NYN2P6I.js} +7 -4
- package/dist/{chunk-LDWZSLSU.js.map → chunk-7NYN2P6I.js.map} +1 -1
- package/dist/{chunk-3VQWSE3F.js → chunk-7UAYMAKR.js} +4 -4
- package/dist/{chunk-BYK66EWO.js → chunk-BBUSGEES.js} +52 -46
- package/dist/chunk-BBUSGEES.js.map +1 -0
- package/dist/{chunk-SLUQ7R6I.js → chunk-C6CLRKPV.js} +5 -5
- package/dist/{chunk-P2FE5AI6.js → chunk-CROKUHJB.js} +2 -2
- package/dist/{chunk-W7Z3BGCI.js → chunk-DEWJMMG3.js} +2 -2
- package/dist/{chunk-ACBRLLFT.js → chunk-F3JWOPTG.js} +7 -3
- package/dist/chunk-F3JWOPTG.js.map +1 -0
- package/dist/{chunk-TERE5SDF.js → chunk-HEWSRXYV.js} +4 -4
- package/dist/chunk-HHMMUR4P.js +335 -0
- package/dist/chunk-HHMMUR4P.js.map +1 -0
- package/dist/{chunk-X3B723J4.js → chunk-HSI6Q7MI.js} +38 -9
- package/dist/chunk-HSI6Q7MI.js.map +1 -0
- package/dist/{chunk-Z7AXYKQB.js → chunk-IY6256GK.js} +1 -1
- package/dist/{chunk-CQR4LIM7.js → chunk-MT2JINSS.js} +5 -1
- package/dist/{chunk-CQR4LIM7.js.map → chunk-MT2JINSS.js.map} +1 -1
- package/dist/{chunk-F5KM4LEQ.js → chunk-NCMZMLY7.js} +3 -3
- package/dist/{chunk-2NDRHXMR.js → chunk-NDWYJLRF.js} +17 -140
- package/dist/chunk-NDWYJLRF.js.map +1 -0
- package/dist/{chunk-PPE5KZJK.js → chunk-NXNPDCF3.js} +3 -3
- package/dist/{chunk-ITIOFN7A.js → chunk-P6AORG32.js} +29 -10
- package/dist/chunk-P6AORG32.js.map +1 -0
- package/dist/{chunk-N45M3FDK.js → chunk-SDDPUAWH.js} +4 -4
- package/dist/{chunk-ZKXSX4LO.js → chunk-TD2NNXLZ.js} +9 -9
- package/dist/{chunk-ILUNZHYV.js → chunk-YFAXOD7Z.js} +10 -6
- package/dist/chunk-YFAXOD7Z.js.map +1 -0
- package/dist/{chunk-2EVEFOZY.js → chunk-ZBDZTJUO.js} +2 -2
- package/dist/chunk-ZGBEIWSC.js +146 -0
- package/dist/chunk-ZGBEIWSC.js.map +1 -0
- package/dist/cli/bin.js +32 -27
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.js +15 -11
- package/dist/cli/commands/audit.js.map +1 -1
- package/dist/{convert-to-pnpm-6L6P74WR.js → convert-to-pnpm-QFJOEP5V.js} +2 -2
- package/dist/{db-B35OGV3G.js → db-UXNIZ2RG.js} +6 -6
- package/dist/{digest-BL6UJYKH.js → digest-FW6QMZZJ.js} +17 -16
- package/dist/{digest-BL6UJYKH.js.map → digest-FW6QMZZJ.js.map} +1 -1
- package/dist/{email-VTTTKKL5.js → email-KJXASVH5.js} +3 -3
- package/dist/{ensure-site-DFTB7MN3.js → ensure-site-4DCEBAPM.js} +19 -11
- package/dist/ensure-site-4DCEBAPM.js.map +1 -0
- package/dist/fleet-state-7TJ2GYT2.js +39 -0
- package/dist/{forms-notify-target-75U6OU7L.js → forms-notify-target-2EAWCWBW.js} +7 -4
- package/dist/forms-notify-target-2EAWCWBW.js.map +1 -0
- package/dist/{github-signals-IJUPGCUX.js → github-signals-E2WPYTBK.js} +9 -9
- package/dist/{header-image-AWLLQA4L.js → header-image-6IC53W27.js} +7 -7
- package/dist/{header-images-335L2AKB.js → header-images-SQBCE5OD.js} +21 -1
- package/dist/header-images-SQBCE5OD.js.map +1 -0
- package/dist/{health-endpoint-WJC2UMYS.js → health-endpoint-RFXL2F4A.js} +2 -2
- package/dist/health-mirror-L5JBEJVA.js +41 -0
- package/dist/health-mirror-L5JBEJVA.js.map +1 -0
- package/dist/{import-airtable-HE43FB4H.js → import-airtable-OHVY344G.js} +7 -5
- package/dist/index.d.ts +149 -0
- package/dist/index.js +147 -50
- package/dist/index.js.map +1 -1
- package/dist/{init-NJEOEO7I.js → init-XRAQZYID.js} +9 -9
- package/dist/{launch-XNAX427U.js → launch-IX4Y5JJC.js} +55 -26
- package/dist/launch-IX4Y5JJC.js.map +1 -0
- package/dist/{lighthouse-airtable-LBVIYYP5.js → lighthouse-airtable-3GUWHETW.js} +3 -3
- package/dist/{onboard-GK4PHPNI.js → onboard-O4IAHJMO.js} +2 -2
- package/dist/{orchestrate-77UO4BYJ.js → orchestrate-YLWQ6KK2.js} +10 -9
- package/dist/{parity-MWS24A3H.js → parity-56KA2DGR.js} +4 -4
- package/dist/{pipeline-S6CVHDGB.js → pipeline-3AANZFCR.js} +2 -2
- package/dist/{preflight-6WBNU2GZ.js → preflight-TNORKGCX.js} +11 -10
- package/dist/{preflight-6WBNU2GZ.js.map → preflight-TNORKGCX.js.map} +1 -1
- package/dist/{prismic-ci-3RHOZUUT.js → prismic-ci-G2AK53VL.js} +5 -5
- package/dist/{prismic-models-QBGUT2Q3.js → prismic-models-O6Z3OK3A.js} +13 -8
- package/dist/prismic-models-O6Z3OK3A.js.map +1 -0
- package/dist/prospect/types.d.ts +267 -0
- package/dist/prospect/types.js +1 -0
- package/dist/{prospect-audit-IUNCJ2LV.js → prospect-audit-KSXUNQ5J.js} +4 -4
- package/dist/recipes/sync-configs.js +2 -2
- package/dist/{render-AQAVQDPZ.js → render-IFOGFB5T.js} +3 -3
- package/dist/render-IFOGFB5T.js.map +1 -0
- package/dist/render-from-row-BWSOIYDS.js +17 -0
- package/dist/render-from-row-BWSOIYDS.js.map +1 -0
- package/dist/{renovate-dispatch-QJY75ODR.js → renovate-dispatch-6GQWTRKX.js} +10 -10
- package/dist/{renovate-dispatch-QJY75ODR.js.map → renovate-dispatch-6GQWTRKX.js.map} +1 -1
- package/dist/{report-4EVNDHOZ.js → report-R3E3Y7HR.js} +63 -21
- package/dist/report-R3E3Y7HR.js.map +1 -0
- package/dist/report-mirror-4MNORYQ4.js +49 -0
- package/dist/report-mirror-4MNORYQ4.js.map +1 -0
- package/dist/rerender-3FM6DNRH.js +32 -0
- package/dist/rerender-3FM6DNRH.js.map +1 -0
- package/dist/{self-updating-6DWI2Z56.js → self-updating-UCIWESAX.js} +2 -2
- package/dist/{selftest-RC36MTKP.js → selftest-VGHWPN72.js} +22 -20
- package/dist/{selftest-RC36MTKP.js.map → selftest-VGHWPN72.js.map} +1 -1
- package/dist/site-mirror-NIREX5ME.js +52 -0
- package/dist/site-mirror-NIREX5ME.js.map +1 -0
- package/dist/{smoke-suite-VYY2LXM2.js → smoke-suite-U3UKD3NS.js} +2 -2
- package/dist/{submissions-Q7DRFOCD.js → submissions-IQEJX6FK.js} +2 -2
- package/dist/{svelte-codemods-25J2FO22.js → svelte-codemods-GOKXTBHW.js} +2 -2
- package/dist/{sync-34HNZZ56.js → sync-CTUVXMCK.js} +4 -4
- package/dist/{sync-configs-3SE6PSCO.js → sync-configs-SPTLFJCC.js} +4 -4
- package/dist/{upgrade-WBRQ62FX.js → upgrade-W6ZR3FJH.js} +2 -2
- package/dist/{webflow-IRKOIT7S.js → webflow-624FEBFD.js} +4 -4
- package/dist/{websites-SXWTP72S.js → websites-D6WYFAES.js} +2 -2
- package/dist/websites-D6WYFAES.js.map +1 -0
- package/dist/{write-audits-to-airtable-MBEILLPU.js → write-audits-to-airtable-CMKHGJNQ.js} +4 -4
- package/dist/write-audits-to-airtable-CMKHGJNQ.js.map +1 -0
- package/package.json +5 -1
- package/dist/airtable-G7WBQQMI.js +0 -9
- package/dist/announce-MXTUQ6C7.js.map +0 -1
- package/dist/chunk-2NDRHXMR.js.map +0 -1
- package/dist/chunk-2ZPT7GLV.js.map +0 -1
- package/dist/chunk-ACBRLLFT.js.map +0 -1
- package/dist/chunk-BYK66EWO.js.map +0 -1
- package/dist/chunk-ILUNZHYV.js.map +0 -1
- package/dist/chunk-ITIOFN7A.js.map +0 -1
- package/dist/chunk-X3B723J4.js.map +0 -1
- package/dist/ensure-site-DFTB7MN3.js.map +0 -1
- package/dist/forms-notify-target-75U6OU7L.js.map +0 -1
- package/dist/header-images-335L2AKB.js.map +0 -1
- package/dist/health-mirror-4B2L7T2Y.js +0 -75
- package/dist/health-mirror-4B2L7T2Y.js.map +0 -1
- package/dist/launch-XNAX427U.js.map +0 -1
- package/dist/prismic-models-QBGUT2Q3.js.map +0 -1
- package/dist/report-4EVNDHOZ.js.map +0 -1
- /package/dist/{airtable-G7WBQQMI.js.map → airtable-ZBUPQJSC.js.map} +0 -0
- /package/dist/{import-airtable-HE43FB4H.js.map → attachments-NLZIJ5NU.js.map} +0 -0
- /package/dist/{bump-deps-EC74CPLS.js.map → bump-deps-CGVELRLK.js.map} +0 -0
- /package/dist/{chunk-KTH5ZODA.js.map → chunk-7BZUOZPU.js.map} +0 -0
- /package/dist/{chunk-3VQWSE3F.js.map → chunk-7UAYMAKR.js.map} +0 -0
- /package/dist/{chunk-SLUQ7R6I.js.map → chunk-C6CLRKPV.js.map} +0 -0
- /package/dist/{chunk-P2FE5AI6.js.map → chunk-CROKUHJB.js.map} +0 -0
- /package/dist/{chunk-W7Z3BGCI.js.map → chunk-DEWJMMG3.js.map} +0 -0
- /package/dist/{chunk-TERE5SDF.js.map → chunk-HEWSRXYV.js.map} +0 -0
- /package/dist/{chunk-Z7AXYKQB.js.map → chunk-IY6256GK.js.map} +0 -0
- /package/dist/{chunk-F5KM4LEQ.js.map → chunk-NCMZMLY7.js.map} +0 -0
- /package/dist/{chunk-PPE5KZJK.js.map → chunk-NXNPDCF3.js.map} +0 -0
- /package/dist/{chunk-N45M3FDK.js.map → chunk-SDDPUAWH.js.map} +0 -0
- /package/dist/{chunk-ZKXSX4LO.js.map → chunk-TD2NNXLZ.js.map} +0 -0
- /package/dist/{chunk-2EVEFOZY.js.map → chunk-ZBDZTJUO.js.map} +0 -0
- /package/dist/{convert-to-pnpm-6L6P74WR.js.map → convert-to-pnpm-QFJOEP5V.js.map} +0 -0
- /package/dist/{db-B35OGV3G.js.map → db-UXNIZ2RG.js.map} +0 -0
- /package/dist/{email-VTTTKKL5.js.map → email-KJXASVH5.js.map} +0 -0
- /package/dist/{lighthouse-airtable-LBVIYYP5.js.map → fleet-state-7TJ2GYT2.js.map} +0 -0
- /package/dist/{github-signals-IJUPGCUX.js.map → github-signals-E2WPYTBK.js.map} +0 -0
- /package/dist/{header-image-AWLLQA4L.js.map → header-image-6IC53W27.js.map} +0 -0
- /package/dist/{health-endpoint-WJC2UMYS.js.map → health-endpoint-RFXL2F4A.js.map} +0 -0
- /package/dist/{orchestrate-77UO4BYJ.js.map → import-airtable-OHVY344G.js.map} +0 -0
- /package/dist/{init-NJEOEO7I.js.map → init-XRAQZYID.js.map} +0 -0
- /package/dist/{parity-MWS24A3H.js.map → lighthouse-airtable-3GUWHETW.js.map} +0 -0
- /package/dist/{onboard-GK4PHPNI.js.map → onboard-O4IAHJMO.js.map} +0 -0
- /package/dist/{pipeline-S6CVHDGB.js.map → orchestrate-YLWQ6KK2.js.map} +0 -0
- /package/dist/{render-AQAVQDPZ.js.map → parity-56KA2DGR.js.map} +0 -0
- /package/dist/{websites-SXWTP72S.js.map → pipeline-3AANZFCR.js.map} +0 -0
- /package/dist/{prismic-ci-3RHOZUUT.js.map → prismic-ci-G2AK53VL.js.map} +0 -0
- /package/dist/{write-audits-to-airtable-MBEILLPU.js.map → prospect/types.js.map} +0 -0
- /package/dist/{prospect-audit-IUNCJ2LV.js.map → prospect-audit-KSXUNQ5J.js.map} +0 -0
- /package/dist/{self-updating-6DWI2Z56.js.map → self-updating-UCIWESAX.js.map} +0 -0
- /package/dist/{smoke-suite-VYY2LXM2.js.map → smoke-suite-U3UKD3NS.js.map} +0 -0
- /package/dist/{submissions-Q7DRFOCD.js.map → submissions-IQEJX6FK.js.map} +0 -0
- /package/dist/{svelte-codemods-25J2FO22.js.map → svelte-codemods-GOKXTBHW.js.map} +0 -0
- /package/dist/{sync-34HNZZ56.js.map → sync-CTUVXMCK.js.map} +0 -0
- /package/dist/{sync-configs-3SE6PSCO.js.map → sync-configs-SPTLFJCC.js.map} +0 -0
- /package/dist/{upgrade-WBRQ62FX.js.map → upgrade-W6ZR3FJH.js.map} +0 -0
- /package/dist/{webflow-IRKOIT7S.js.map → webflow-624FEBFD.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/reports/airtable/site-status.ts","../src/reports/airtable/websites.ts"],"sourcesContent":["/**\n * The site-status vocabulary — ONE module owns it (#539 Phase 4).\n *\n * The fleet's lifecycle names were inherited from an Airtable single-select\n * written by hand years ago (\"probably not our problem\"). The operator approved\n * a canonical vocabulary, and the migration is now COMPLETE in both stores:\n * Airtable's \"Status\" single-select carries exactly the six canonical options\n * and nothing else. This module no longer knows the old names at all.\n *\n * The retired mapping, kept as the record of what was merged into what:\n *\n * old (retired 2026-08-25) new (canonical)\n * ───────────────────────── ───────────────\n * in development building\n * launch period launching\n * maintenance maintained\n * hosting hosted-only\n * probably not our problem external\n * legacy ┐\n * deprecated ┴ archived ← approved MERGE, many-to-one\n *\n * `legacy` and `deprecated` were already treated identically by every PREDICATE\n * (ARCHIVED_STATUSES held both), so collapsing them changes no *selection* — no\n * fleet op gains or loses a site. It is NOT true that collapsing them changes\n * nothing at all, and one surface proved it: the cockpit's Archived lane LABELS\n * each row with its Status cell, and canonicalizing there rendered all 12 live\n * archived rows as \"archived\". That lane now labels from `statusRaw`, which is\n * exactly why `WebsiteRow.statusRaw` exists. The rule this leaves behind:\n * canonical values decide BEHAVIOUR; anything DISPLAYING a Status cell, or\n * writing one back, uses the raw cell.\n *\n * The merge had NO clean reverse map while both vocabularies coexisted, which\n * is why `toAirtableStatus` had to pick one archived name deliberately. With the\n * old names retired there is nothing left to pick between, and no code path\n * feeds operator-supplied text through it anyway (see\n * `src/recipes/forms-notify-target.ts`, which writes `--restore` verbatim).\n *\n * THE SHAPE OF THE TRANSITION (three stages):\n *\n * stage 1 (DONE) code speaks the NEW vocabulary internally; reads canonicalize\n * at the two Airtable/Turso seams; writes still emit the OLD\n * Airtable option names. Airtable untouched. No SELECTION\n * change — every predicate picks exactly the sites it picked\n * before (pinned row-by-row in tests/reports/airtable/\n * site-status.test.ts). Displayed labels come from `statusRaw`.\n * stage 2 (DONE) the Airtable \"Status\" single-select gained the 6 new options\n * and all 44 cells were migrated (verified live: maintained=13,\n * archived=12, external=9, building=6, hosted-only=2,\n * launching=2 — zero old values, zero unrecognized), `db sync`\n * ran clean (mismatches=0), and AIRTABLE_USES_NEW_VOCABULARY\n * flipped to true. Writers now emit canonical names verbatim.\n * The alias map STAYS: the 7 old options still exist in the\n * field, so a human can still pick one in the Airtable UI.\n * stage 3 (DONE) the operator deleted the 7 old options from the Airtable\n * \"Status\" field on 2026-08-25, which is what made this safe:\n * the gate was always \"no old value CAN BE ENTERED\", not\n * merely \"none is stored\". Verified against the live base\n * before any code changed — the field carries exactly the six\n * canonical choices, byte-exact, and all 44 cells still hold a\n * canonical value with ZERO blanks (deleting a single-select\n * option CLEARS the cells using it, so \"no cell was blanked\"\n * was checked, not assumed). AIRTABLE_STATUS_ALIASES,\n * AIRTABLE_OLD_NAMES and AIRTABLE_USES_NEW_VOCABULARY are\n * gone; both functions reduce to the identity.\n *\n * WHAT CHANGED IN BEHAVIOUR AT STAGE 3, and it is the only thing that did: an\n * old name is no longer translated. `canonicalizeStatus(\"maintenance\")` used to\n * yield `maintained`; it now yields `\"maintenance\"` verbatim, which\n * `isUnrecognizedStatus` flags and the cockpit surfaces as a watch row. That is\n * intended. The option cannot be selected any more, so a stored old value would\n * mean something went wrong — a restored backup, a scripted write, an API\n * caller with a stale constant — and the fleet should say so rather than absorb\n * it into a status nobody chose.\n *\n * Canonicalization happens on READ, never at rest: `src/db/import-airtable.ts`\n * still stores the raw Airtable cell verbatim in `sites.status`, so the hourly\n * parity check keeps comparing raw-to-raw and the importer stays honest to its\n * source. Both readers — `mapRow` (Airtable) and `rowFromJoined` (Turso) — run\n * the raw value through `canonicalizeStatus`, which is what keeps the #558\n * reader-equivalence instrument green.\n */\n\n/** The canonical site lifecycle vocabulary. */\nexport type Status =\n \"building\" | \"launching\" | \"maintained\" | \"hosted-only\" | \"external\" | \"archived\";\n\n/** Every canonical status, in lifecycle order. The order is load-bearing: the\n * dashboard status editor renders its options from it, and stage 1 must leave\n * that dropdown byte-identical. */\nexport const CANONICAL_STATUSES: readonly Status[] = [\n \"building\",\n \"launching\",\n \"maintained\",\n \"hosted-only\",\n \"external\",\n \"archived\",\n] as const;\n\nconst CANONICAL_SET: ReadonlySet<string> = new Set<string>(CANONICAL_STATUSES);\n\n/**\n * Map a raw Status cell (Airtable field value, or the `sites.status` column) to\n * the canonical vocabulary. Applied at BOTH read seams so the rest of the code\n * only ever sees canonical names.\n *\n * Three deliberate non-obvious behaviours, each protecting an existing invariant:\n *\n * - ABSENT ONLY yields null. A cell that is present but empty (`\"\"`) comes back\n * as `\"\"`, not null, because `due.ts`/`preflight.ts` treat a null status as\n * eligible-by-default — nulling anything non-absent would silently ACTIVATE\n * the row for scheduled client reports.\n * - An unrecognized value is returned VERBATIM (blind-cast to Status, exactly as\n * `mapRow` did before this module existed) so `isUnrecognizedStatus` still\n * flags it and the cockpit still surfaces it as a watch row. Since stage 3\n * that INCLUDES the seven retired names: `maintenance` is now as unrecognized\n * as `maintenence`, which is the point — it can no longer be entered, so its\n * reappearance is an anomaly to surface, not a spelling to absorb.\n * - No trimming or case-folding. `\"maintained \"` stays unrecognized, which is\n * what `isUnrecognizedStatus` has always been documented to catch (\"typo /\n * renamed option / stray whitespace\"). Normalizing here would silence it.\n *\n * With the alias map gone this is the identity on every string, so `status` and\n * `statusRaw` now hold the same value for any present cell. The two fields are\n * kept distinct deliberately — the read/display split is the architecture that\n * made this migration survivable, and collapsing it would have to be undone the\n * next time Airtable's vocabulary and the code's diverge.\n */\nexport function canonicalizeStatus(raw: unknown): Status | null {\n if (typeof raw !== \"string\") return null;\n // Canonical values pass through; so does anything else, unchanged — see above.\n return raw as Status;\n}\n\n/**\n * The string to WRITE into the Airtable \"Status\" cell for a canonical status.\n * Every writer of a CODE-OWNED status routes through here.\n *\n * Since stage 3 this is the identity: Airtable's single-select carries exactly\n * the six canonical options, so the canonical name IS the option name. It is\n * kept as a named seam rather than inlined because it is the one place a future\n * divergence between the code's vocabulary and Airtable's would be expressed,\n * and because every writer already routes through it — inlining would scatter\n * that decision across `ensureSite`, `updateLaunched`, `forms-notify-target`\n * and the dashboard status save.\n *\n * The stage-1/2 hazard it used to carry is GONE: while a many-to-one map\n * existed, `toAirtableStatus(canonicalizeStatus(x))` was not the identity —\n * feeding it \"legacy\" yielded \"deprecated\", silently writing an option the\n * operator never asked for. Both functions are now the identity, so that trap\n * no longer exists. `forms-notify-target --restore` still writes operator text\n * verbatim (`restoreCell`) rather than routing through here, which remains the\n * right shape: operator free text is not a canonical status.\n */\nexport function toAirtableStatus(s: Status): string {\n return s;\n}\n\n/** True when `s` is one of the canonical statuses (not a blind-cast typo). */\nexport function isCanonicalStatus(s: string): s is Status {\n return CANONICAL_SET.has(s);\n}\n","import type { FieldSet } from \"airtable\";\nimport type { AirtableBase } from \"./client.js\";\nimport type { LighthouseScores, LighthouseScoreWriteback } from \"../types.js\";\nimport {\n CANONICAL_STATUSES,\n canonicalizeStatus,\n toAirtableStatus,\n type Status,\n} from \"./site-status.js\";\n\nexport const WEBSITES_TABLE = \"Websites\";\n\nexport type Frequency = \"None\" | \"Monthly\" | \"Quarterly\" | \"Yearly\";\n\n/** The canonical lifecycle vocabulary lives in ./site-status.ts (which also owns\n * the old-Airtable-name aliases and the write-direction mapping). Re-exported\n * here because every consumer already imports `Status` from this module. */\nexport type { Status };\n\n/**\n * Per-site notification routing. When present on a `maintained` site, the form\n * notification is addressed by the value of a submission field (`field`, read from\n * `extraFields`) — e.g. route a contact form's `interest` to a different recipient\n * per option, always CC-ing a shared address. Absent (`null`) → the site keeps the\n * default single-POC behavior. Recipients live HERE (server-side Airtable config),\n * never supplied by the submitting site, so the ingest can't be turned into an open\n * relay.\n */\nexport type NotifyRouting = {\n /** The `extraFields` key whose value selects a route, e.g. \"interest\". */\n field: string;\n /** Field-value → recipient address(es). */\n routes: Record<string, string | string[]>;\n /** Recipient(s) when the value matches no route. */\n default?: string | string[];\n /** Address(es) CC'd on every routed (maintenance) send. */\n cc?: string[];\n};\n\nexport type WebsiteRow = {\n id: string;\n name: string;\n url: string;\n /** Canonical lifecycle status (see ./site-status.ts). Canonicalized at the read\n * boundary, so an old-vocabulary Airtable cell and a new one read identically.\n * A present-but-unrecognized cell survives VERBATIM (blind-cast) rather than\n * becoming null — `isUnrecognizedStatus` flags it, and null would make\n * due.ts/preflight.ts treat the row as eligible-by-default. */\n status: Status | null;\n /** The literal Airtable Status cell behind `status` — same pattern as\n * `maintenanceFreqRaw`. The dashboard status editor round-trips THIS, so its\n * dropdown offers and preselects the values Airtable actually holds while the\n * two vocabularies coexist. Null = blank cell. */\n statusRaw: string | null;\n pointOfContact: string | null;\n maintenanceFreq: Frequency;\n testingFreq: Frequency;\n /** The literal Airtable cell values behind the coerced frequencies. `toFrequency`\n * trims whitespace (\"Monthly \" reads as Monthly), then maps any still-unrecognized\n * value (\"Quaterly\") to \"None\" with a LOUD console.warn so nothing bogus reaches a\n * client email and the drop is never invisible. Preflight validates THESE to surface\n * the same failure as a structured finding. Null = blank cell. */\n maintenanceFreqRaw: string | null;\n testingFreqRaw: string | null;\n /** Last manually-recorded maintenance day (used as fallback when no Reports row exists). */\n maintenanceDay: string | null;\n testingDay: string | null;\n ga4PropertyId: string | null;\n /** Operator-supplied query for the Google search-presence check (e.g. the business name).\n * Null = no query set → the check is skipped for this site. */\n searchQuery: string | null;\n /** Explicit Search Console property for this site (`sc-domain:...` or `https://.../`).\n * Null = auto-resolve from the SA's visible properties by host. */\n searchConsoleProperty: string | null;\n /** ISO timestamp of the last draft run where THIS site's GA/Search enrichment\n * ERRORED (vs a legitimate \"not configured\" skip). Set by drafting on a soft-fail,\n * cleared (null) on a clean enrichment, so the per-site analytics-failure signal\n * self-heals. Null when the operator-added `Analytics soft-fail at` column is absent. */\n analyticsSoftFailAt: string | null;\n /** GitHub repo identity as `owner/repo`. Null = no git wiring → self-update ops skip\n * (or, for local runs, fall back to the checkout's origin remote). */\n gitRepo: string | null;\n reportRecipientsTo: string | null;\n reportRecipientsCc: string | null;\n acceptedWatchConditions: string[];\n /** First attachment in the Header image field (Airtable's signed URL — fetch before expiry). */\n headerImage: { url: string; filename: string; type: string } | null;\n /** Lighthouse \"current state\" snapshot, kept fresh by `audit lighthouse --write-airtable`. */\n pScore: number | null;\n rScore: number | null;\n bpScore: number | null;\n seoScore: number | null;\n /** ISO timestamp set by `audit lighthouse --write-airtable` when scores were last refreshed. */\n lastLighthouseAuditAt: string | null;\n /** Last-known counts from non-lighthouse audits, written by\n * `audit --write-airtable`. `null` = never audited (or this audit\n * type was skipped on the last run). 0 = audited, clean. */\n a11yViolations: number | null;\n /** Declared-range drift vs the Reddoor baseline (what package.json asks for). */\n depsDrifted: number | null;\n depsMajorBehind: number | null;\n /** Real installed-version drift: deps behind the registry's latest, from the\n * committed lockfile (`pnpm outdated`). Null = not determined this run. */\n depsOutdated: number | null;\n /** Of {@link depsOutdated}, how many are a *major* version behind the\n * registry's latest — the \"majors available on npm\" signal, distinct from the\n * baseline-drift {@link depsMajorBehind}. Null = not determined this run. */\n depsMajorOutdated: number | null;\n securityVulnsCritical: number | null;\n securityVulnsHigh: number | null;\n securityVulnsModerate: number | null;\n securityVulnsLow: number | null;\n /** Count of consecutive nightly Renovate auto-fix dispatches for the CURRENT\n * critical/high vuln episode that have NOT yet cleared it. Owned by\n * `renovate-dispatch`: +1 per real dispatch, reset to 0 when vulns clear.\n * Null = field absent / never dispatched → reads as 0. At/above\n * AUTO_FIX_EXHAUSTED_CYCLES the vuln renders as \"auto-fix failed\". */\n securityAutoFixAttempts: number | null;\n /** ISO timestamp the security audit last ran — gates freshness of the Security Updates auto-tick\n * (clean counts only auto-tick when recent). */\n lastSecurityAuditAt: string | null;\n /** The known advisories behind the counts (severity-sorted, capped), so the dashboard can show\n * WHICH packages are vulnerable, not just the totals. null = never audited / unparseable;\n * empty array = audited clean. Written alongside the counts by the security audit. */\n securityAdvisories: SecurityAdvisory[] | null;\n /** Domain/DNS/SSL probe (the `domain` audit). `certDaysRemaining` is days until the TLS cert\n * expires (null = unresolved or no usable cert); `domainCheckedAt` is when it last ran. */\n certDaysRemaining: number | null;\n domainCheckedAt: string | null;\n /** Netlify site id — the IDENTITY the `netlify-deploy` audit needs to query the\n * Netlify API. Read-only input (operator-set in Airtable); null = not on Netlify\n * (or not wired) → that audit skips. Never derived from the URL. */\n netlifyId: string | null;\n /** Latest PRODUCTION deploy health (the `netlify-deploy` audit). `deployStatus` is\n * Netlify's deploy state lower-cased (`ready`/`error`/`building`/…), null = none / not\n * checked; `lastDeployAt` is when it deployed; `deployLogUrl` links to the deploy/log. */\n deployStatus: string | null;\n lastDeployAt: string | null;\n deployLogUrl: string | null;\n /** When the `netlify-deploy` audit last RAN (freshness stamp for `deployStatus`). The audit\n * already writes \"Deploy checked at\"; this read-back is the Plan-2 fix so `deployEvidence`\n * (Plan 4) can gate on check time — NOT on `lastDeployAt`, which is deploy time, not check time. */\n deployCheckedAt: string | null;\n /** Function-health verdict (the `function-health` audit): the deployed `/health` function\n * answered `ok:true` (pass) or `ok:false` (fail). Single-select `pass`/`fail`; null = never ran\n * / unreachable (→ Plan 4 maps to unknown/amber). Kept SEPARATE from `deployStatus` so\n * `isFailedDeployStatus` keeps meaning \"the build failed\". */\n functionHealth: \"pass\" | \"fail\" | null;\n /** CMS reachability (server-side), derived from the same `/health` body's `details.prismic ===\n * \"ok\"`. Single-select `pass`/`fail`; null = never ran. No per-site Prismic token or identity\n * column is ever built — this rides `/health`. */\n cmsReachable: \"pass\" | \"fail\" | null;\n /** From the same `/health` body's `forms.turnstile` boolean: does the deployed site report\n * the Turnstile widget configured (`PUBLIC_TURNSTILE_SITE_KEY` set)? Single-select\n * `pass`/`fail`; null = never ran / older site package whose `/health` has no `forms`\n * block. Freshness gated by `functionHealthCheckedAt`. Powers the cockpit Require-Turnstile\n * guardrail: a site with `requireTurnstile` ON but no widget silently buckets 100% of its\n * real leads (and form-e2e can't see it — testMode bypasses the gate). */\n turnstileWidget: \"pass\" | \"fail\" | null;\n /** When the `function-health` audit last ran — the freshness gate for `functionHealth`,\n * `cmsReachable`, and `turnstileWidget`. Null = never ran. */\n functionHealthCheckedAt: string | null;\n /** Deployed-URL browser probe (the `browser` audit): cross-engine render OK, mobile render OK,\n * internal-links OK + broken count, and when it last ran (one timestamp gates all three). */\n crossbrowserOk: boolean | null;\n mobileOk: boolean | null;\n linksOk: boolean | null;\n brokenLinks: number | null;\n browserCheckedAt: string | null;\n /** Uptime-reachable verdict (browser audit): every sampled route returned 2xx/3xx. Single-select\n * `pass`/`fail`; null = never ran. Point-in-time. Freshness-gated by `browserCheckedAt`. */\n reachableOk: \"pass\" | \"fail\" | null;\n /** Titles & meta verdict (browser audit, chromium): every sampled route has a non-empty `<title>`\n * ≤ 70 chars + a non-empty meta description, and no duplicate titles across the sample.\n * Single-select `pass`/`fail`; null = never ran. Freshness-gated by `browserCheckedAt`. */\n titleMetaOk: \"pass\" | \"fail\" | null;\n /** Per-site copy overrides (M6a). Blank → null → the DEFAULT_COPY value. */\n copyIntro: string | null;\n copyContact: string | null;\n copyFooter: string | null;\n /** Go-live timestamp, stamped when a Launch report sends (M6b). Null = not yet launched. */\n launchedAt: string | null;\n /** Optional per-site webhook (e.g. Zapier Catch Hook). When set, the ingest\n * POSTs newsletter-formType submissions here (best-effort). Blank → null. */\n newsletterWebhook: string | null;\n /** Per-site Mailchimp (newsletter). Both must be set for the direct add;\n * blank → skipped. The API key is `key-dc` format; dc is derived from it. */\n mailchimpApiKey: string | null;\n mailchimpAudienceId: string | null;\n /** Per-site Cloudflare Turnstile gate (Airtable checkbox). When true, a submission\n * whose Turnstile token verifies as \"fail\" (forged) OR \"absent\" (secret configured\n * centrally but NO token forwarded — the direct-POST-bot signature) is escalated to\n * auto-spam regardless of content score. A present-but-expired token stays\n * \"unverifiable\" and neutral (a real browser DID render the widget — fail-open).\n * ROLLOUT PRECONDITION: only enable on a site whose DEPLOYED package forwards\n * `_meta.turnstileToken` from EVERY form (widget rendered + `cf-turnstile-response`\n * posted; check the site's `/health` → forms.turnstile:true). A site that never\n * forwards tokens would silently bucket 100% of its real leads — and the form-e2e\n * probe cannot catch that state (testMode bypasses the gate). */\n requireTurnstile: boolean;\n /** GitHub-signals sweep (slice 2a), written nightly by `github-signals --fleet`. */\n renovateFailingCis: number | null;\n defaultBranchCi: string | null; // \"passing\" | \"failing\" | \"pending\" | \"none\"\n lastCommitAt: string | null;\n githubSignalsAt: string | null;\n /** Per-site smoke-suite verdict (the `smoke` audit runs `pnpm test:smoke`).\n * Single-select pass/fail; null = never ran. `lastSmokeAt` gates freshness. */\n smokeOk: \"pass\" | \"fail\" | null;\n lastSmokeAt: string | null;\n /** Synthetic form end-to-end verdict (the `form-e2e` audit submits the real prod\n * contact form in test-mode). Single-select pass/fail; null = never ran OR (with\n * a fresh `formE2eCheckedAt`) no contact form → n/a. `formE2eCheckedAt` gates\n * freshness AND encodes the n/a-vs-never-ran distinction. */\n formE2eOk: \"pass\" | \"fail\" | null;\n formE2eCheckedAt: string | null;\n /**\n * Nightly Prismic model drift sweep (`prismic-models --fleet --write-airtable`).\n *\n * FOUR-VALUED, unlike every other verdict column in this table, and the extra\n * state is the point:\n *\n * - `pass` — the repo and its Prismic repository were compared and agree.\n * - `fail` — they were compared and DIVERGE (a model to create/update, or\n * one that exists only in Prismic). A finding for a human.\n * - `unknown` — THE CHECK ITSELF FAILED. Unreadable checkout, broken config,\n * missing/expired token, unreadable remote. Nothing at all was\n * established about this site's models.\n * - `null` — no verdict to hold: the sweep has never run for this site, or\n * it ran and found no Prismic config at all (a repo that simply\n * is not a Prismic site). `prismicModelsCheckedAt` separates\n * those two — fresh timestamp, blank verdict = \"checked, and\n * there is nothing here to check\".\n *\n * `unknown` exists because the alternatives are both wrong in the dangerous\n * direction. Writing `pass` for a site nobody could read is a green tick over\n * an outage; writing NOTHING (the obvious \"leave the last known value alone\")\n * leaves yesterday's `pass` standing for a site that has been failing every\n * night since — and nothing ages a stale `pass` out, because the digest's\n * freshness gate only ever examines failures. Both make \"I could not read this\n * site\" indistinguishable from \"this site is fine\", in the record the cockpit\n * and the digest read.\n *\n * OPERATOR PRECONDITION: `Prismic Models` is a single select whose options are\n * `pass`, `fail`, `unknown`. Until the three columns exist the sweep's writes\n * fail with UNKNOWN_FIELD_NAME and are collected as soft failures — the feature\n * ships dark rather than reddening the nightly.\n */\n prismicModels: PrismicModelsVerdict | null;\n /** When the sweep last ran for this site — written on EVERY outcome, including\n * `unknown` and blank, so the age of the row is the age of the answer. */\n prismicModelsCheckedAt: string | null;\n /** What the sweep found, verbatim: the drift report for a `fail`, the reason\n * nothing could be established for an `unknown`, the skip reason for a blank,\n * and null for a `pass` (which clears yesterday's finding). */\n prismicModelsDrift: string | null;\n /**\n * An expiry the operator sets to accept a KNOWN, EXPECTED `fail` — most often\n * \"I am modelling in Prismic on a branch that has not landed, so Prismic is\n * legitimately ahead of `main`\". While this timestamp is in the future the\n * drift item is not raised.\n *\n * It expires on purpose, and nothing renews it automatically. A permanent ack\n * would reproduce this column's own failure mode one step later: once the\n * branch lands, the same acked cell would swallow real drift and \"nobody is\n * looking at this\" would render as \"this is fine\". An expiry means the worst\n * case is a silence that ends by itself.\n *\n * Narrow by construction — it mutes only `fail`, the finding the operator\n * actually reviewed. `unknown` (the check could not run) and a verdict too old\n * to be current are never muted by it; see `collectPrismicDriftAlerts`.\n *\n * OPERATOR PRECONDITION: `Prismic Ack Until` is a dateTime column. Until it\n * exists this reads null and nothing is acked, which is the safe direction.\n */\n prismicAckUntil: string | null;\n notifyRouting: NotifyRouting | null;\n /** The RAW `Notify Routing` cell, verbatim. Same reason `statusRaw` exists: the\n * dashboard editor round-trips this JSON, and re-serializing the PARSED object\n * would drop any key the parser ignores and reformat what the operator typed —\n * a silent rewrite of a cell they only opened to look at. */\n notifyRoutingRaw: string | null;\n /** Read-back of the code-owned next-due dates (date-only, written by the\n * nightly `writeNextDueDates`). These exist so the writer can DIFF the\n * freshly-computed dates against what the row already holds and skip the\n * ~31 no-op writes a night the fleet was paying for (#539 Phase 3). Null =\n * cell blank or the operator-added `Next … at` column absent. */\n nextMaintenanceAt: string | null;\n nextTestingAt: string | null;\n};\n\nexport function siteSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** Blank-trim-to-null: a non-string or whitespace-only value becomes null,\n * otherwise the trimmed string. */\nexport function trimToNull(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Parse the Websites `Notify Routing` JSON into a NotifyRouting, defensively: a\n * non-string, blank, malformed-JSON, or wrong-shape value yields null (the site\n * then keeps default single-POC routing) — never throws. Mirrors the pipeline's\n * \"a bad Airtable string degrades quietly\" rule.\n */\nexport function parseNotifyRouting(raw: unknown): NotifyRouting | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (!trimmed) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const o = parsed as Record<string, unknown>;\n if (typeof o.field !== \"string\" || !o.field.trim()) return null;\n if (!o.routes || typeof o.routes !== \"object\" || Array.isArray(o.routes)) return null;\n const routing: NotifyRouting = {\n field: o.field,\n routes: o.routes as Record<string, string | string[]>,\n };\n if (o.default !== undefined) routing.default = o.default as string | string[];\n if (Array.isArray(o.cc)) routing.cc = o.cc.filter((x): x is string => typeof x === \"string\");\n return routing;\n}\n\n/**\n * Active sites: actively-maintained or pre-launch. Single source of truth for\n * \"is this a live site\" — the operator cockpit shows these, and the fleet\n * audit/report path runs against these. A `null` status (not-yet-active) is\n * deliberately excluded.\n */\nexport const ACTIVE_STATUSES: ReadonlySet<Status> = new Set<Status>([\"maintained\", \"launching\"]);\n\nexport function isDashboardVisible(site: WebsiteRow): boolean {\n return site.status !== null && ACTIVE_STATUSES.has(site.status);\n}\n\n/**\n * Pre-launch lifecycle stages: the site is being built/prepared, NOT yet live. A\n * Launch report (recipes/launch.ts) flips Status → \"maintained\" at go-live\n * (updateLaunched), so \"maintained\" is the true live state. Pre-launch sites must\n * not be audited as production (their deploy/domain/uptime/CMS audits fail because\n * nothing is live yet) nor scheduled recurring Maintenance/Testing reports.\n *\n * NOTE `launching` is deliberately in BOTH this set and ACTIVE_STATUSES — a\n * launching site is cockpit-visible but not production-audited. That dual\n * membership predates the vocabulary rename and was re-approved as-is with it.\n */\nexport const PRE_LAUNCH_STATUSES: ReadonlySet<Status> = new Set<Status>([\"building\", \"launching\"]);\n\nexport function isPreLaunch(status: Status | null): boolean {\n return status !== null && PRE_LAUNCH_STATUSES.has(status);\n}\n\n/** Every Status value the code recognizes — the canonical vocabulary, since both\n * read seams canonicalize. Typed ReadonlySet<string> so a blind-cast typo'd cell\n * can be probed without a cast. */\nexport const KNOWN_STATUSES: ReadonlySet<string> = new Set<Status>(CANONICAL_STATUSES);\n\n/** Terminal, out-of-fleet lifecycle states: kept in Airtable for the record,\n * excluded from every fleet op (sweeps, reports, audits, cockpit tiers) exactly\n * as before, but surfaced on the cockpit as an archived lane so a row can never\n * silently vanish. Airtable's `legacy` AND `deprecated` both canonicalize to the\n * single `archived` — an approved merge; the two were always treated alike. */\nexport const ARCHIVED_STATUSES: ReadonlySet<Status> = new Set<Status>([\"archived\"]);\n\nexport function isArchivedStatus(status: Status | null): boolean {\n return status !== null && ARCHIVED_STATUSES.has(status);\n}\n\n/** True when the Status cell holds a value outside the code's union (typo /\n * renamed option / stray whitespace). mapRow deliberately does NOT null these —\n * due.ts/preflight.ts treat a null status as eligible-by-default, so nulling a\n * typo would ACTIVATE the row. The cockpit surfaces these as watch rows instead. */\nexport function isUnrecognizedStatus(status: Status | null): boolean {\n return status !== null && !KNOWN_STATUSES.has(status);\n}\n\nconst FREQUENCIES: readonly Frequency[] = [\"None\", \"Monthly\", \"Quarterly\", \"Yearly\"];\n\n/** Coerce an Airtable single-select value to a known Frequency at the read boundary.\n * Whitespace is trimmed first, so an operator's trailing-space option (\"Quarterly \")\n * still schedules instead of silently unscheduling the site. Any other non-empty,\n * unrecognized value — a renamed / typo'd option — warns LOUDLY and falls back to\n * \"None\" (its section is simply omitted) rather than flowing a bogus string downstream,\n * which the announcement would otherwise render as \"We do this undefined.\" into a\n * client email. Blank/undefined is a silent \"None\": no schedule is intentional. */\nexport function toFrequency(raw: unknown, context: string): Frequency {\n if (typeof raw !== \"string\") return \"None\";\n const trimmed = raw.trim();\n if ((FREQUENCIES as readonly string[]).includes(trimmed)) return trimmed as Frequency;\n if (trimmed !== \"\") {\n console.warn(\n `⚠ ${context}: unrecognized frequency '${raw}' — treating as None (not scheduling); fix the Airtable value`,\n );\n }\n return \"None\";\n}\n\n/** Coerce an Airtable tri-state single-select verdict cell (`pass`/`fail`/blank) to\n * `\"pass\" | \"fail\" | null`. Any value other than the literal strings \"pass\"/\"fail\" — blank,\n * an unrecognized option, a typo, wrong type — reads as null (\"never ran\"), never guessed. The\n * ONE shared reader for every verdict column of this shape: `Function health`, `CMS Reachable`,\n * `Uptime Reachable`, `Titles & Meta OK` (Plan 2), and reused (not redeclared) by Plan 3's\n * `Smoke OK` / `Form E2E OK` read-backs. */\nexport function toVerdict(raw: unknown): \"pass\" | \"fail\" | null {\n return raw === \"pass\" || raw === \"fail\" ? raw : null;\n}\n\n/** The `Prismic Models` cell — see {@link WebsiteRow.prismicModels} for why it\n * carries a third state that no other verdict column in this table has. */\nexport type PrismicModelsVerdict = \"pass\" | \"fail\" | \"unknown\";\n\n/**\n * Read the `Prismic Models` cell. Deliberately NOT {@link toVerdict}.\n *\n * `toVerdict` maps anything that is not literally `pass`/`fail` to null — which\n * for this column would read `unknown` (\"the check ran and failed\") back as null\n * (\"the check never ran\"), silently, on the way to the cockpit. That is the\n * pipeline's governing failure (\"I could not read X\" wearing the face of \"X does\n * not exist\") reintroduced by a shared helper that predates the third state.\n *\n * Everything else — blank, a typo, an option somebody added by hand, the wrong\n * type — still reads as null. A verdict is never guessed.\n */\nexport function toPrismicModelsVerdict(raw: unknown): PrismicModelsVerdict | null {\n return raw === \"pass\" || raw === \"fail\" || raw === \"unknown\" ? raw : null;\n}\n\n// NOTE: every `f[\"...\"]` key below is a load-bearing magic string that must match\n// the live Airtable \"Websites\" column name EXACTLY — including the legacy\n// misspelling `\"maintenence freq\"`, the mixed-case `\"GA4 property ID\"`, and the\n// lowercase `\"url\"` / `\"point of contact\"`. A column rename in Airtable silently\n// returns undefined here (→ null), which degrades quietly (GA skipped, recipients\n// empty) with no error. If you rename a column, change it here too.\nexport function mapRow(rec: { id: string; fields: Record<string, unknown> }): WebsiteRow {\n const f = rec.fields;\n const name = String(f[\"Name\"] ?? \"\");\n const attachments =\n (f[\"Header image\"] as Array<{ url: string; filename: string; type: string }> | undefined) ?? [];\n // LAST, not first: Airtable's uploadAttachment APPENDS, so the newest file is the\n // tail. Reading [0] served the OLDEST forever whenever a field held more than one —\n // which is how a pre-clean-plate header reached a live announcement (#574/#577).\n // The prune keeps these fields at a single entry, so this is normally the same\n // element; preferring the tail means a field that stacks again still serves the\n // CURRENT header instead of silently reverting to the first one ever uploaded.\n const header = attachments.at(-1) ?? null;\n return {\n id: rec.id,\n name,\n url: String(f[\"url\"] ?? \"\"),\n status: canonicalizeStatus(f[\"Status\"]),\n statusRaw: (f[\"Status\"] as string | undefined) ?? null,\n pointOfContact: (f[\"point of contact\"] as string | undefined) ?? null,\n maintenanceFreq: toFrequency(f[\"maintenence freq\"], `${name} maintenance`),\n testingFreq: toFrequency(f[\"testing freq\"], `${name} testing`),\n maintenanceFreqRaw: (f[\"maintenence freq\"] as string | undefined) ?? null,\n testingFreqRaw: (f[\"testing freq\"] as string | undefined) ?? null,\n maintenanceDay: (f[\"maintenance day\"] as string | undefined) ?? null,\n testingDay: (f[\"testing day\"] as string | undefined) ?? null,\n ga4PropertyId: (f[\"GA4 property ID\"] as string | undefined) ?? null,\n searchQuery: (f[\"Search query\"] as string | undefined) ?? null,\n searchConsoleProperty: (f[\"Search Console property\"] as string | undefined) ?? null,\n analyticsSoftFailAt: (f[\"Analytics soft-fail at\"] as string | undefined) ?? null,\n gitRepo: (f[\"Git repo\"] as string | undefined) ?? null,\n reportRecipientsTo: (f[\"Report recipients (To)\"] as string | undefined) ?? null,\n reportRecipientsCc: (f[\"Report recipients (CC)\"] as string | undefined) ?? null,\n // Tolerate BOTH the current Multiple-Select array shape AND a delimited long-text\n // string (comma/newline separated), so the field can migrate to a plain text column\n // with no code change here. Trim + drop empties either way. The array branch also\n // validates ELEMENT types: a collaborator/attachment-shaped field passes\n // Array.isArray with OBJECT elements, and an unchecked cast would make assignTier's\n // `.trim()` throw — one misconfigured row must not 500 the whole cockpit build.\n acceptedWatchConditions: Array.isArray(f[\"Accepted Watch Conditions\"])\n ? (f[\"Accepted Watch Conditions\"] as unknown[])\n .filter((x): x is string => typeof x === \"string\")\n .map((s) => s.trim())\n .filter(Boolean)\n : typeof f[\"Accepted Watch Conditions\"] === \"string\"\n ? (f[\"Accepted Watch Conditions\"] as string)\n .split(/[\\n,]/)\n .map((s) => s.trim())\n .filter(Boolean)\n : [],\n headerImage: header,\n pScore: (f[\"pScore\"] as number | undefined) ?? null,\n rScore: (f[\"rScore\"] as number | undefined) ?? null,\n bpScore: (f[\"bpScore\"] as number | undefined) ?? null,\n seoScore: (f[\"seoScore\"] as number | undefined) ?? null,\n lastLighthouseAuditAt: (f[\"Last lighthouse audit at\"] as string | undefined) ?? null,\n a11yViolations: (f[\"A11y Violations\"] as number | undefined) ?? null,\n depsDrifted: (f[\"Deps Drifted\"] as number | undefined) ?? null,\n depsMajorBehind: (f[\"Deps Major Behind\"] as number | undefined) ?? null,\n depsOutdated: (f[\"Deps Outdated\"] as number | undefined) ?? null,\n depsMajorOutdated: (f[\"Deps Major Outdated\"] as number | undefined) ?? null,\n securityVulnsCritical: (f[\"Security Vulns Critical\"] as number | undefined) ?? null,\n securityVulnsHigh: (f[\"Security Vulns High\"] as number | undefined) ?? null,\n securityVulnsModerate: (f[\"Security Vulns Moderate\"] as number | undefined) ?? null,\n securityVulnsLow: (f[\"Security Vulns Low\"] as number | undefined) ?? null,\n securityAutoFixAttempts: (f[\"Security Auto-Fix Attempts\"] as number | undefined) ?? null,\n lastSecurityAuditAt: (f[\"Last security audit at\"] as string | undefined) ?? null,\n securityAdvisories: parseSecurityAdvisories(f[\"Security advisories\"]),\n certDaysRemaining: (f[\"Cert days remaining\"] as number | undefined) ?? null,\n domainCheckedAt: (f[\"Domain checked at\"] as string | undefined) ?? null,\n netlifyId: trimToNull(f[\"Netlify ID\"]),\n deployStatus: (f[\"Deploy status\"] as string | undefined) ?? null,\n lastDeployAt: (f[\"Last deploy at\"] as string | undefined) ?? null,\n deployLogUrl: (f[\"Deploy log URL\"] as string | undefined) ?? null,\n deployCheckedAt: (f[\"Deploy checked at\"] as string | undefined) ?? null,\n functionHealth: toVerdict(f[\"Function health\"]),\n cmsReachable: toVerdict(f[\"CMS Reachable\"]),\n turnstileWidget: toVerdict(f[\"Turnstile widget\"]),\n functionHealthCheckedAt: (f[\"Function health checked at\"] as string | undefined) ?? null,\n crossbrowserOk:\n typeof f[\"Crossbrowser OK\"] === \"boolean\" ? (f[\"Crossbrowser OK\"] as boolean) : null,\n mobileOk: typeof f[\"Mobile OK\"] === \"boolean\" ? (f[\"Mobile OK\"] as boolean) : null,\n linksOk: typeof f[\"Links OK\"] === \"boolean\" ? (f[\"Links OK\"] as boolean) : null,\n brokenLinks: typeof f[\"Broken links\"] === \"number\" ? (f[\"Broken links\"] as number) : null,\n browserCheckedAt: (f[\"Browser checked at\"] as string | undefined) ?? null,\n reachableOk: toVerdict(f[\"Uptime Reachable\"]),\n titleMetaOk: toVerdict(f[\"Titles & Meta OK\"]),\n copyIntro: trimToNull(f[\"Copy — Intro\"]),\n copyContact: trimToNull(f[\"Copy — Contact\"]),\n copyFooter: trimToNull(f[\"Copy — Footer\"]),\n launchedAt: (f[\"Launched at\"] as string | undefined) ?? null,\n newsletterWebhook: trimToNull(f[\"Newsletter Webhook\"]),\n notifyRouting: parseNotifyRouting(f[\"Notify Routing\"]),\n notifyRoutingRaw: trimToNull(f[\"Notify Routing\"]),\n mailchimpApiKey: trimToNull(f[\"Mailchimp API Key\"]),\n mailchimpAudienceId: trimToNull(f[\"Mailchimp Audience ID\"]),\n // Boolean guard like crossbrowserOk, but defaults FALSE (not null) when absent: an\n // unset/unknown column must read as \"not required\" so the feature ships dark.\n requireTurnstile:\n typeof f[\"Require Turnstile\"] === \"boolean\" ? (f[\"Require Turnstile\"] as boolean) : false,\n renovateFailingCis: (f[\"Renovate Failing CIs\"] as number | undefined) ?? null,\n defaultBranchCi: (f[\"Default Branch CI\"] as string | undefined) ?? null,\n lastCommitAt: (f[\"Last Commit At\"] as string | undefined) ?? null,\n githubSignalsAt: (f[\"GitHub Signals At\"] as string | undefined) ?? null,\n smokeOk: toVerdict(f[\"Smoke OK\"]),\n lastSmokeAt: (f[\"Last Smoke At\"] as string | undefined) ?? null,\n formE2eOk: toVerdict(f[\"Form E2E OK\"]),\n formE2eCheckedAt: (f[\"Form E2E checked at\"] as string | undefined) ?? null,\n prismicModels: toPrismicModelsVerdict(f[\"Prismic Models\"]),\n prismicModelsCheckedAt: (f[\"Prismic Models Checked At\"] as string | undefined) ?? null,\n prismicModelsDrift: (f[\"Prismic Models Drift\"] as string | undefined) ?? null,\n prismicAckUntil: (f[\"Prismic Ack Until\"] as string | undefined) ?? null,\n nextMaintenanceAt: (f[\"Next maintenance at\"] as string | undefined) ?? null,\n nextTestingAt: (f[\"Next testing at\"] as string | undefined) ?? null,\n };\n}\n\nexport async function listWebsites(base: AirtableBase): Promise<WebsiteRow[]> {\n const out: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ pageSize: 100 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) out.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n return out;\n}\n\nexport async function getWebsiteBySlug(\n base: AirtableBase,\n slug: string,\n): Promise<WebsiteRow | null> {\n // Slugs are siteSlug() output: [a-z0-9] segments joined by single hyphens.\n // Reject anything else — it can't match a real row, and it keeps URL-supplied\n // input out of the filter formula below (formula-injection guard).\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return null;\n\n // Narrow the fetch to the slug-matching row server-side instead of paging the\n // whole table per request (MEDIUM-H). The formula replicates siteSlug() on\n // {Name} — lowercase → non-alnum runs to \"-\" → strip leading/trailing \"-\" —\n // verified against the live base. maxRecords caps it (slug collisions keep the\n // prior first-match-wins behavior).\n const formula = `REGEX_REPLACE(REGEX_REPLACE(LOWER({Name}),\"[^a-z0-9]+\",\"-\"),\"^-|-$\",\"\")=${JSON.stringify(\n slug,\n )}`;\n const rows: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ filterByFormula: formula, maxRecords: 1 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n // Confirm the match in JS too: keeps the function correct if the formula and\n // siteSlug() ever drift, and under test fakes that don't evaluate the formula.\n return rows.find((w) => siteSlug(w.name) === slug) ?? null;\n}\n\n// ── audit-field builders ─────────────────────────────────────────────────────\n// One source of truth for the column-name → value mappings of each audit type.\n// The per-audit `updateXxxCounts` writers delegate to these (for their other\n// callers), and `updateAuditFields` merges whichever are present into ONE write —\n// so the field-name magic strings live in exactly one place.\n\nexport type A11yCounts = { violations: number };\nexport type DepsCounts = {\n drifted: number;\n majorBehind: number;\n outdated: number | null;\n majorOutdated: number | null;\n};\nexport type SecurityCounts = { critical: number; high: number; moderate: number; low: number };\nexport type Severity = \"low\" | \"moderate\" | \"high\" | \"critical\";\n/** One known vulnerability behind the security counts, as persisted/rendered. */\nexport type SecurityAdvisory = {\n module: string;\n severity: Severity;\n title: string;\n cves: string[];\n url: string | null;\n /** GitHub Dependabot dependency scope (\"runtime\" | \"development\"), when known. Lets the\n * dashboard flag build-time-only (\"development\") vulns. Omitted for advisories from the\n * lockfile `pnpm audit` fallback, which carries no per-package graph scope. */\n scope?: \"runtime\" | \"development\";\n /** GitHub Dependabot dependency-graph relationship, when known. \"transitive\" means no\n * direct-dep bump can fix it — Renovate's vuln alerts have no fix vehicle until the weekly\n * lockfile-maintenance window. Omitted when GitHub reports \"unknown\" or for the\n * `pnpm audit` fallback. Drives {@link allActionableVulnsTransitive}. */\n relationship?: \"direct\" | \"transitive\";\n};\nexport type DomainResult = { certDaysRemaining: number | null; checkedAt: string };\nexport type NetlifyDeployResult = {\n /** Netlify deploy state lower-cased (`ready`/`error`/`building`/…), null = none. */\n state: string | null;\n /** When the latest production deploy was published/created (ISO), null = unknown. */\n deployedAt: string | null;\n /** Link to the deploy / its build log, null = unknown. */\n logUrl: string | null;\n /** When the audit last ran. */\n checkedAt: string;\n};\nexport type BrowserAuditFields = {\n desktopOk: boolean;\n mobileOk: boolean;\n linksOk: boolean;\n reachableOk: boolean;\n titleMetaOk: boolean;\n brokenLinks: number;\n checkedAt: string;\n};\nexport type FunctionHealthResult = {\n /** `pass` when `/health` answered `ok:true`, else `fail`. Never null — the audit only produces a\n * result when it ran (a self-skip carries no details, so this extractor isn't reached). */\n functionHealth: \"pass\" | \"fail\";\n /** From the same body's `prismic` sub-status (R2.2): `\"ok\"` → `\"pass\"`, `\"error\"` → `\"fail\"`.\n * Anything else (`\"skipped\"` — a placeholder repo with no live Prismic — or a raw `null`, e.g.\n * the synthetic \"deployed but erroring\" body) → `null`: the CMS probe never actually ran, so it\n * must NOT red CMS reachability for a site that simply hasn't wired Prismic yet. */\n cmsReachable: \"pass\" | \"fail\" | null;\n /** From the same body's `forms.turnstile` boolean: `true` → `\"pass\"`, `false` → `\"fail\"`.\n * A missing/null `forms` block (older site package, or the synthetic \"deployed but\n * erroring\" body) → `null` — the widget state is simply unknown, not a failure. */\n turnstileWidget: \"pass\" | \"fail\" | null;\n /** When the audit ran (freshness stamp for all three verdicts). */\n checkedAt: string;\n};\n\nexport type SmokeResult = { ok: \"pass\" | \"fail\"; checkedAt: string };\n\n/** `ok` null clears the single-select cell (n/a — no contact form); a fresh\n * `checkedAt` still stamps the row so Plan 4 reads null+fresh as n/a. */\nexport type FormE2eResult = { ok: \"pass\" | \"fail\" | null; checkedAt: string };\n\nfunction scoreFields(scores: LighthouseScoreWriteback): FieldSet {\n // A null score CLEARS the cell (→ dashboard \"—\"), distinguishing a metric that\n // errored this run (e.g. NO_LCP → null performance) from a real low score. This\n // intentionally overwrites a prior value: a run that couldn't measure the metric\n // shouldn't keep showing a stale number. Writing null to clear mirrors\n // updateAnalyticsHealth; the `as FieldSet` cast is needed because airtable's\n // FieldSet type omits null.\n const fields: Record<string, number | string | null> = {\n pScore: scores.performance,\n rScore: scores.accessibility,\n bpScore: scores.bestPractices,\n seoScore: scores.seo,\n \"Last lighthouse audit at\": new Date().toISOString(),\n };\n return fields as FieldSet;\n}\n\nfunction a11yFields(counts: A11yCounts): FieldSet {\n return { \"A11y Violations\": counts.violations };\n}\n\nfunction depsFields(counts: DepsCounts): FieldSet {\n const fields: FieldSet = {\n \"Deps Drifted\": counts.drifted,\n \"Deps Major Behind\": counts.majorBehind,\n };\n // Only write the outdated count when it was determined — a null (no/stale\n // lockfile this run) must not clobber a previously-good value.\n if (counts.outdated !== null) {\n fields[\"Deps Outdated\"] = counts.outdated;\n }\n // Same null-guard for the registry-major breakdown (same source signal).\n if (counts.majorOutdated !== null) {\n fields[\"Deps Major Outdated\"] = counts.majorOutdated;\n }\n return fields;\n}\n\n/** Critical first → low last; the persist cap and the dashboard list both lean on this. */\nexport const SEVERITY_RANK: Record<Severity, number> = {\n critical: 0,\n high: 1,\n moderate: 2,\n low: 3,\n};\n/** Cap persisted advisories so the JSON field can't blow up on a badly-neglected site. */\nconst MAX_PERSISTED_ADVISORIES = 25;\n\n/** Coerce one untrusted value into a SecurityAdvisory, or null if it isn't shaped like one.\n * Shared by the read path (`parseSecurityAdvisories`) and the write path so both validate\n * identically. A missing module or unrecognized severity drops the entry entirely. */\nexport function normalizeSecurityAdvisory(raw: unknown): SecurityAdvisory | null {\n if (!raw || typeof raw !== \"object\") return null;\n const e = raw as Record<string, unknown>;\n const module = typeof e[\"module\"] === \"string\" ? (e[\"module\"] as string) : null;\n const severity = e[\"severity\"];\n if (module === null) return null;\n if (\n severity !== \"low\" &&\n severity !== \"moderate\" &&\n severity !== \"high\" &&\n severity !== \"critical\"\n )\n return null;\n const cves = Array.isArray(e[\"cves\"])\n ? (e[\"cves\"] as unknown[]).filter((c): c is string => typeof c === \"string\")\n : [];\n const scope =\n e[\"scope\"] === \"runtime\" || e[\"scope\"] === \"development\"\n ? (e[\"scope\"] as \"runtime\" | \"development\")\n : undefined;\n const relationship =\n e[\"relationship\"] === \"direct\" || e[\"relationship\"] === \"transitive\"\n ? (e[\"relationship\"] as \"direct\" | \"transitive\")\n : undefined;\n return {\n module,\n severity,\n title: typeof e[\"title\"] === \"string\" ? (e[\"title\"] as string) : \"\",\n cves,\n url: typeof e[\"url\"] === \"string\" ? (e[\"url\"] as string) : null,\n ...(scope ? { scope } : {}),\n ...(relationship ? { relationship } : {}),\n };\n}\n\n/**\n * True iff the persisted advisory detail proves EVERY actionable (critical/high) vuln is a\n * TRANSITIVE dependency — i.e. Renovate's vulnerability alerts have no direct-dep bump to\n * open, and the fix rides the weekly lockfile-maintenance window instead. Deliberately\n * conservative: `null` detail (never audited / `pnpm audit` fallback), an advisory missing\n * its `relationship` (unknown / pre-existing JSON), or a counts-vs-detail mismatch (no\n * critical/high advisory in the list) all return false — missing data must never mute the\n * auto-fix-failed escalation. Consumed by the attempts counter (don't count a known no-op\n * dispatch as a failed fix attempt) and the digest (say \"transitive-only\", not\n * \"auto-fix failed\"). The persist cap keeps advisories sorted critical-first, so\n * critical/high entries are never the ones capped away.\n */\nexport function allActionableVulnsTransitive(advisories: SecurityAdvisory[] | null): boolean {\n if (!advisories) return false;\n const actionable = advisories.filter((a) => a.severity === \"critical\" || a.severity === \"high\");\n if (actionable.length === 0) return false;\n return actionable.every((a) => a.relationship === \"transitive\");\n}\n\n/** Parse the `Security advisories` JSON cell. null when absent/blank/unparseable/not-an-array\n * (treated as \"never audited\"); a valid array (possibly empty = audited clean) otherwise. */\nexport function parseSecurityAdvisories(raw: unknown): SecurityAdvisory[] | null {\n if (typeof raw !== \"string\" || raw.trim() === \"\") return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!Array.isArray(parsed)) return null;\n return parsed.map(normalizeSecurityAdvisory).filter((a): a is SecurityAdvisory => a !== null);\n}\n\nfunction securityAdvisoryFields(advisories: SecurityAdvisory[]): FieldSet {\n const capped = [...advisories]\n .sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n .slice(0, MAX_PERSISTED_ADVISORIES);\n // Always write — an empty array (\"[]\") clears a stale list when a once-vulnerable site goes clean.\n return { \"Security advisories\": JSON.stringify(capped) };\n}\n\nfunction securityFields(counts: SecurityCounts): FieldSet {\n return {\n \"Security Vulns Critical\": counts.critical,\n \"Security Vulns High\": counts.high,\n \"Security Vulns Moderate\": counts.moderate,\n \"Security Vulns Low\": counts.low,\n // Stamp freshness alongside the counts so the Security Updates auto-tick can require a recent\n // audit (a clean count from months ago must not silently keep ticking the box).\n \"Last security audit at\": new Date().toISOString(),\n };\n}\n\nfunction domainFields(result: DomainResult): FieldSet {\n const fields: FieldSet = { \"Domain checked at\": result.checkedAt };\n // Write the cert days UNCONDITIONALLY: a null (unresolved / no usable cert) must CLEAR any\n // previously-good value. Leaving a stale number in place — next to a freshly-stamped \"Domain\n // checked at\" — false-passes the Domain/DNS/SSL auto-tick (domainEvidence reads the stale\n // non-null value as a current pass) for a site that's actually down. null clears the cell in\n // Airtable; FieldSet's type doesn't model null, hence the cast through a widened record.\n (fields as Record<string, number | null>)[\"Cert days remaining\"] = result.certDaysRemaining;\n return fields;\n}\n\nfunction netlifyDeployFields(result: NetlifyDeployResult): FieldSet {\n // Write all three deploy fields UNCONDITIONALLY (null clears the cell): a null state /\n // deployedAt / logUrl this run means \"couldn't read it\" and must not leave a STALE value\n // sitting next to a fresh \"Deploy checked at\" — the dashboard would otherwise render a green\n // \"ready\" badge for a site whose latest deploy actually errored. FieldSet's type doesn't model\n // null, hence the cast through a widened record (same approach as domainFields).\n const fields: Record<string, string | null> = {\n \"Deploy status\": result.state,\n \"Last deploy at\": result.deployedAt,\n \"Deploy log URL\": result.logUrl,\n \"Deploy checked at\": result.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction browserFields(r: BrowserAuditFields): FieldSet {\n return {\n \"Crossbrowser OK\": r.desktopOk,\n \"Mobile OK\": r.mobileOk,\n \"Links OK\": r.linksOk,\n \"Broken links\": r.brokenLinks,\n \"Browser checked at\": r.checkedAt,\n // NEW tri-state single-select verdicts (empty = never ran). The browser audit only produces a\n // BrowserAuditFields when it actually ran (hasBrowserResult guards on checkedAt), so each verdict\n // is always a concrete boolean here — serialize true→\"pass\", false→\"fail\". The existing boolean\n // columns above are deliberately NOT retrofitted (out of scope).\n \"Uptime Reachable\": r.reachableOk ? \"pass\" : \"fail\",\n \"Titles & Meta OK\": r.titleMetaOk ? \"pass\" : \"fail\",\n };\n}\n\nfunction functionHealthFields(r: FunctionHealthResult): FieldSet {\n // \"CMS Reachable\" is written UNCONDITIONALLY (null clears the cell): the audit only supplies a\n // result when it ran, but `cmsReachable` itself can legitimately be null this run (R2.2 — the CMS\n // probe never actually happened, e.g. a placeholder repo with no live Prismic). Clearing rather\n // than leaving a stale pass/fail sitting next to a freshly-stamped checked-at is what keeps a\n // placeholder site from showing a stale CMS verdict. FieldSet's type doesn't model null, hence the\n // cast through a widened record (same approach as domainFields/netlifyDeployFields).\n // \"Function health\" is never null — the audit only writes when it ran, so it's always a concrete\n // pass/fail. Written SEPARATELY from \"Deploy status\" so the Netlify build state keeps its own\n // meaning.\n const fields: Record<string, string | null> = {\n \"Function health\": r.functionHealth,\n \"CMS Reachable\": r.cmsReachable,\n // Same null-clears semantics as \"CMS Reachable\": a body without a forms block means the\n // widget state is unknown THIS run — clearing beats a stale verdict next to a fresh stamp.\n \"Turnstile widget\": r.turnstileWidget,\n \"Function health checked at\": r.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction smokeFields(r: SmokeResult): FieldSet {\n // The verdict is stored as the literal single-select option (\"pass\"/\"fail\"), so\n // no boolean→string coercion is needed. A skip never reaches here (it produces no\n // SmokeResult), so this column is only ever written with a concrete verdict.\n return { \"Smoke OK\": r.ok, \"Last Smoke At\": r.checkedAt };\n}\n\nfunction formE2eFields(r: FormE2eResult): FieldSet {\n // `ok` is already the single-select value (\"pass\"/\"fail\") or null. Writing null\n // CLEARS the cell (→ n/a, distinguished from \"never ran\" by the fresh checked-at\n // stamped alongside). FieldSet's type omits null, hence the widened-record cast\n // (same approach as domainFields / netlifyDeployFields).\n const fields: Record<string, string | null> = {\n \"Form E2E OK\": r.ok,\n \"Form E2E checked at\": r.checkedAt,\n };\n return fields as FieldSet;\n}\n\n/**\n * Write the four Lighthouse scores + a refreshed-at timestamp onto a Websites row.\n * Called by `audit lighthouse --write-airtable` after a successful audit run, so\n * the operator never has to paste numbers manually before drafting a report.\n */\nexport async function updateScores(\n base: AirtableBase,\n recordId: string,\n scores: LighthouseScores,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: scoreFields(scores) }]);\n}\n\n/**\n * Record (or clear) the per-site GA/Search enrichment health on the `Analytics\n * soft-fail at` column. `at` is an ISO timestamp when the site's last draft had a\n * GA/Search soft-failure, or `null` to clear it after a clean enrichment. The\n * caller (drafting) swallows errors: this column is operator-added, so until it\n * exists Airtable throws UNKNOWN_FIELD_NAME — which must not break a draft.\n */\nexport async function updateAnalyticsHealth(\n base: AirtableBase,\n recordId: string,\n at: string | null,\n): Promise<void> {\n const fields: Record<string, string | null> = { \"Analytics soft-fail at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n}\n\n/** Persist a11y violation count. */\nexport async function updateA11yCounts(\n base: AirtableBase,\n recordId: string,\n counts: A11yCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: a11yFields(counts) }]);\n}\n\n/** Persist deps drift counts (declared-range drift + real outdated installs). */\nexport async function updateDepsCounts(\n base: AirtableBase,\n recordId: string,\n counts: DepsCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: depsFields(counts) }]);\n}\n\n/** Persist security vulnerability counts by severity. */\nexport async function updateSecurityCounts(\n base: AirtableBase,\n recordId: string,\n counts: SecurityCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: securityFields(counts) }]);\n}\n\n/** Persist a site's auto-fix attempt counter. Its own one-field writer so the\n * nightly Renovate dispatch can update it without touching the audit's counts. */\nexport async function updateAutoFixAttempts(\n base: AirtableBase,\n recordId: string,\n attempts: number,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([\n { id: recordId, fields: { \"Security Auto-Fix Attempts\": attempts } },\n ]);\n}\n\n/**\n * Persist the code-computed next-due dates (date-only `YYYY-MM-DD`, or `null` to\n * clear) for the maintenance + testing schedules. Owned by the nightly `--due` sweep\n * so the \"next\" dates shown in Airtable come from the SAME logic as the scheduler\n * (`nextDueDate`) — no Airtable-side formula or automation. Best-effort at the call\n * site: the `Next … at` columns are operator-added, so until they exist Airtable\n * throws UNKNOWN_FIELD_NAME, which must not break the nightly draft run.\n */\nexport async function updateNextDueDates(\n base: AirtableBase,\n recordId: string,\n dates: { maintenanceAt: string | null; testingAt: string | null },\n): Promise<FieldSet> {\n const fields: Record<string, string | null> = {\n \"Next maintenance at\": dates.maintenanceAt,\n \"Next testing at\": dates.testingAt,\n };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n // Same contract as updateAuditFields/updateGitHubSignals: the Phase 3 Turso\n // mirror consumes the returned FieldSet, so the two writes cannot diverge.\n return fields as FieldSet;\n}\n\n/** Generic single-field writer for the dashboard site-details editor. The caller\n * (setSiteDetail) restricts `column` to the EDITABLE_SITE_FIELDS allowlist, so this\n * never writes an arbitrary column from request input. */\nexport async function updateSiteField(\n base: AirtableBase,\n recordId: string,\n column: string,\n value: string,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: { [column]: value } }]);\n}\n\n/**\n * Persist all of a single audit run's results to one Websites row in ONE atomic\n * `update()` — instead of up to four sequential updates on the same id (which left\n * a row half-written on a mid-sequence failure and quadrupled the request volume).\n * Pass only the audit slices that produced real values; each present slice is merged\n * via the SAME field mappings the per-audit writers use. Omit a slice (or pass\n * undefined) to leave those columns untouched. Returns the merged FieldSet so the\n * caller can enumerate what was written.\n */\nexport async function updateAuditFields(\n base: AirtableBase,\n recordId: string,\n audits: {\n scores?: LighthouseScoreWriteback;\n a11y?: A11yCounts;\n deps?: DepsCounts;\n security?: SecurityCounts;\n securityAdvisories?: SecurityAdvisory[];\n domain?: DomainResult;\n browser?: BrowserAuditFields;\n netlifyDeploy?: NetlifyDeployResult;\n functionHealth?: FunctionHealthResult;\n smoke?: SmokeResult;\n formE2e?: FormE2eResult;\n },\n): Promise<FieldSet> {\n const fields: FieldSet = {};\n if (audits.scores) Object.assign(fields, scoreFields(audits.scores));\n if (audits.a11y) Object.assign(fields, a11yFields(audits.a11y));\n if (audits.deps) Object.assign(fields, depsFields(audits.deps));\n if (audits.security) Object.assign(fields, securityFields(audits.security));\n // Separate slice (not folded into `security`) so the advisory list and the counts can be\n // written independently, but in practice the security audit supplies both together.\n if (audits.securityAdvisories)\n Object.assign(fields, securityAdvisoryFields(audits.securityAdvisories));\n if (audits.domain) Object.assign(fields, domainFields(audits.domain));\n if (audits.browser) Object.assign(fields, browserFields(audits.browser));\n if (audits.netlifyDeploy) Object.assign(fields, netlifyDeployFields(audits.netlifyDeploy));\n if (audits.functionHealth) Object.assign(fields, functionHealthFields(audits.functionHealth));\n if (audits.smoke) Object.assign(fields, smokeFields(audits.smoke));\n if (audits.formE2e) Object.assign(fields, formE2eFields(audits.formE2e));\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n return fields;\n}\n\n/** Persist the GitHub-signals sweep onto a Websites row (slice 2a). A null\n * `lastCommitAt` is OMITTED so a not-determined-this-run value never clobbers a\n * previously-good timestamp (mirrors updateDepsCounts' outdated handling).\n * Returns the FieldSet it wrote — the Phase 3 Turso mirror consumes the same\n * payload, so the two writes cannot diverge (updateAuditFields' contract). */\nexport async function updateGitHubSignals(\n base: AirtableBase,\n recordId: string,\n signals: {\n renovateFailingCis: number;\n ciState: string;\n lastCommitAt: string | null;\n sweptAt: string;\n },\n): Promise<FieldSet> {\n const fields: FieldSet = {\n \"Renovate Failing CIs\": signals.renovateFailingCis,\n \"Default Branch CI\": signals.ciState,\n \"GitHub Signals At\": signals.sweptAt,\n };\n if (signals.lastCommitAt !== null) {\n fields[\"Last Commit At\"] = signals.lastCommitAt;\n }\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n return fields;\n}\n\n/** One site's Prismic model verdict, as the sweep hands it to the record.\n *\n * `verdict: null` is a REQUEST TO BLANK the cell, not \"leave it alone\" — see\n * {@link updatePrismicModels}. There is no way to express \"leave it alone\" here\n * on purpose. */\nexport type PrismicModelsWriteback = {\n verdict: PrismicModelsVerdict | null;\n checkedAt: string;\n /** The finding, the failure reason, or the skip reason — whichever this\n * verdict has. `null` clears the column. */\n detail: string | null;\n};\n\n/** Airtable's long-text cells hold ~100k characters and the sweep's report runs\n * long on a badly drifted site (an empty Prismic repository sorts every local\n * model into `toCreate`, with a line per field). Half the cell is the budget;\n * the rest is headroom for whatever renders it. */\nconst MAX_PRISMIC_DETAIL_CHARS = 50_000;\n\n/**\n * Shorten a detail that will not fit, and SAY SO — with the original length, so\n * nobody mistakes the remainder for the whole. Same reasoning as the PR comment's\n * truncation notice: a report that was shortened without saying it was shortened\n * is a report that looks complete and is not.\n *\n * The cut is by code unit, so it can land between the halves of an astral\n * character; a lone surrogate is not valid text and can make Airtable reject the\n * write, losing the entire finding to a cosmetic detail.\n */\nfunction truncatePrismicDetail(detail: string): string {\n if (detail.length <= MAX_PRISMIC_DETAIL_CHARS) return detail;\n const notice =\n `\\n…[truncated: this report is ${detail.length} characters and only the first` +\n ` ${MAX_PRISMIC_DETAIL_CHARS} are kept here. Run \\`reddoor-maint prismic-models\\` in the` +\n ` site — dry is the default — for the whole thing.]`;\n let head = detail.slice(0, MAX_PRISMIC_DETAIL_CHARS - notice.length);\n const last = head.charCodeAt(head.length - 1);\n if (last >= 0xd800 && last <= 0xdbff) head = head.slice(0, -1);\n return head + notice;\n}\n\n/**\n * Persist one site's Prismic model verdict.\n *\n * ALL THREE COLUMNS, ALWAYS, in one update — including when the verdict is\n * `unknown` or blank. That is the whole design: the alternative (\"only write a\n * verdict when we have one\") leaves the PREVIOUS verdict standing for a site\n * whose check has since started failing, and a stale `pass` is never aged out by\n * anything — the digest's freshness gate only examines failures. So the record\n * always says what the last run actually established, and `checkedAt` always\n * says when. See {@link WebsiteRow.prismicModels} for the four states.\n *\n * Best-effort AT THE CALL SITE: `Prismic Models*` are operator-added columns, so\n * until they exist Airtable throws UNKNOWN_FIELD_NAME. The nightly sweep must\n * survive that and collect it — same contract as `updateNextDueDates`.\n *\n * Takes a non-null `AirtableBase`, like every other writer here: whether to write\n * at all is the caller's decision, and this repo keeps \"do no writes\" separate\n * from \"do no IO\" one layer up.\n */\nexport async function updatePrismicModels(\n base: AirtableBase,\n recordId: string,\n models: PrismicModelsWriteback,\n): Promise<void> {\n const fields: Record<string, string | null> = {\n \"Prismic Models\": models.verdict,\n \"Prismic Models Checked At\": models.checkedAt,\n \"Prismic Models Drift\": models.detail === null ? null : truncatePrismicDetail(models.detail),\n };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n}\n\n/** Mark a site launched: flip Status → maintained + stamp Launched at (M6b).\n * The first code that writes Status. Called after a Launch report sends.\n * Routed through `toAirtableStatus`, so it still writes Airtable's \"maintenance\"\n * option until the stage-2 switch flips. */\nexport async function updateLaunched(\n base: AirtableBase,\n recordId: string,\n at: string,\n): Promise<void> {\n const fields: FieldSet = { Status: toAirtableStatus(\"maintained\"), \"Launched at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n}\n"],"mappings":";AAyFO,IAAM,qBAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,gBAAqC,IAAI,IAAY,kBAAkB;AA6BtE,SAAS,mBAAmB,KAA6B;AAC9D,MAAI,OAAO,QAAQ,SAAU,QAAO;AAEpC,SAAO;AACT;AAsBO,SAAS,iBAAiB,GAAmB;AAClD,SAAO;AACT;;;ACjJO,IAAM,iBAAiB;AAwRvB,SAAS,SAAS,MAAsB;AAC7C,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AACzB;AAIO,SAAS,WAAW,KAA6B;AACtD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;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\n * The site-status vocabulary — ONE module owns it (#539 Phase 4).\n *\n * The fleet's lifecycle names were inherited from an Airtable single-select\n * written by hand years ago (\"probably not our problem\"). The operator approved\n * a canonical vocabulary, and the migration is now COMPLETE in both stores:\n * Airtable's \"Status\" single-select carries exactly the six canonical options\n * and nothing else. This module no longer knows the old names at all.\n *\n * The retired mapping, kept as the record of what was merged into what:\n *\n * old (retired 2026-08-25) new (canonical)\n * ───────────────────────── ───────────────\n * in development building\n * launch period launching\n * maintenance maintained\n * hosting hosted-only\n * probably not our problem external\n * legacy ┐\n * deprecated ┴ archived ← approved MERGE, many-to-one\n *\n * `legacy` and `deprecated` were already treated identically by every PREDICATE\n * (ARCHIVED_STATUSES held both), so collapsing them changes no *selection* — no\n * fleet op gains or loses a site. It is NOT true that collapsing them changes\n * nothing at all, and one surface proved it: the cockpit's Archived lane LABELS\n * each row with its Status cell, and canonicalizing there rendered all 12 live\n * archived rows as \"archived\". That lane now labels from `statusRaw`, which is\n * exactly why `WebsiteRow.statusRaw` exists. The rule this leaves behind:\n * canonical values decide BEHAVIOUR; anything DISPLAYING a Status cell, or\n * writing one back, uses the raw cell.\n *\n * The merge had NO clean reverse map while both vocabularies coexisted, which\n * is why `toAirtableStatus` had to pick one archived name deliberately. With the\n * old names retired there is nothing left to pick between, and no code path\n * feeds operator-supplied text through it anyway (see\n * `src/recipes/forms-notify-target.ts`, which writes `--restore` verbatim).\n *\n * THE SHAPE OF THE TRANSITION (three stages):\n *\n * stage 1 (DONE) code speaks the NEW vocabulary internally; reads canonicalize\n * at the two Airtable/Turso seams; writes still emit the OLD\n * Airtable option names. Airtable untouched. No SELECTION\n * change — every predicate picks exactly the sites it picked\n * before (pinned row-by-row in tests/reports/airtable/\n * site-status.test.ts). Displayed labels come from `statusRaw`.\n * stage 2 (DONE) the Airtable \"Status\" single-select gained the 6 new options\n * and all 44 cells were migrated (verified live: maintained=13,\n * archived=12, external=9, building=6, hosted-only=2,\n * launching=2 — zero old values, zero unrecognized), `db sync`\n * ran clean (mismatches=0), and AIRTABLE_USES_NEW_VOCABULARY\n * flipped to true. Writers now emit canonical names verbatim.\n * The alias map STAYS: the 7 old options still exist in the\n * field, so a human can still pick one in the Airtable UI.\n * stage 3 (DONE) the operator deleted the 7 old options from the Airtable\n * \"Status\" field on 2026-08-25, which is what made this safe:\n * the gate was always \"no old value CAN BE ENTERED\", not\n * merely \"none is stored\". Verified against the live base\n * before any code changed — the field carries exactly the six\n * canonical choices, byte-exact, and all 44 cells still hold a\n * canonical value with ZERO blanks (deleting a single-select\n * option CLEARS the cells using it, so \"no cell was blanked\"\n * was checked, not assumed). AIRTABLE_STATUS_ALIASES,\n * AIRTABLE_OLD_NAMES and AIRTABLE_USES_NEW_VOCABULARY are\n * gone; both functions reduce to the identity.\n *\n * WHAT CHANGED IN BEHAVIOUR AT STAGE 3, and it is the only thing that did: an\n * old name is no longer translated. `canonicalizeStatus(\"maintenance\")` used to\n * yield `maintained`; it now yields `\"maintenance\"` verbatim, which\n * `isUnrecognizedStatus` flags and the cockpit surfaces as a watch row. That is\n * intended. The option cannot be selected any more, so a stored old value would\n * mean something went wrong — a restored backup, a scripted write, an API\n * caller with a stale constant — and the fleet should say so rather than absorb\n * it into a status nobody chose.\n *\n * Canonicalization happens on READ, never at rest: `src/db/import-airtable.ts`\n * still stores the raw Airtable cell verbatim in `sites.status`, so the hourly\n * parity check keeps comparing raw-to-raw and the importer stays honest to its\n * source. Both readers — `mapRow` (Airtable) and `rowFromJoined` (Turso) — run\n * the raw value through `canonicalizeStatus`, which is what keeps the #558\n * reader-equivalence instrument green.\n */\n\n/** The canonical site lifecycle vocabulary. */\nexport type Status =\n \"building\" | \"launching\" | \"maintained\" | \"hosted-only\" | \"external\" | \"archived\";\n\n/** Every canonical status, in lifecycle order. The order is load-bearing: the\n * dashboard status editor renders its options from it, and stage 1 must leave\n * that dropdown byte-identical. */\nexport const CANONICAL_STATUSES: readonly Status[] = [\n \"building\",\n \"launching\",\n \"maintained\",\n \"hosted-only\",\n \"external\",\n \"archived\",\n] as const;\n\nconst CANONICAL_SET: ReadonlySet<string> = new Set<string>(CANONICAL_STATUSES);\n\n/**\n * Map a raw Status cell (Airtable field value, or the `sites.status` column) to\n * the canonical vocabulary. Applied at BOTH read seams so the rest of the code\n * only ever sees canonical names.\n *\n * Three deliberate non-obvious behaviours, each protecting an existing invariant:\n *\n * - ABSENT ONLY yields null. A cell that is present but empty (`\"\"`) comes back\n * as `\"\"`, not null, because `due.ts`/`preflight.ts` treat a null status as\n * eligible-by-default — nulling anything non-absent would silently ACTIVATE\n * the row for scheduled client reports.\n * - An unrecognized value is returned VERBATIM (blind-cast to Status, exactly as\n * `mapRow` did before this module existed) so `isUnrecognizedStatus` still\n * flags it and the cockpit still surfaces it as a watch row. Since stage 3\n * that INCLUDES the seven retired names: `maintenance` is now as unrecognized\n * as `maintenence`, which is the point — it can no longer be entered, so its\n * reappearance is an anomaly to surface, not a spelling to absorb.\n * - No trimming or case-folding. `\"maintained \"` stays unrecognized, which is\n * what `isUnrecognizedStatus` has always been documented to catch (\"typo /\n * renamed option / stray whitespace\"). Normalizing here would silence it.\n *\n * With the alias map gone this is the identity on every string, so `status` and\n * `statusRaw` now hold the same value for any present cell. The two fields are\n * kept distinct deliberately — the read/display split is the architecture that\n * made this migration survivable, and collapsing it would have to be undone the\n * next time Airtable's vocabulary and the code's diverge.\n */\nexport function canonicalizeStatus(raw: unknown): Status | null {\n if (typeof raw !== \"string\") return null;\n // Canonical values pass through; so does anything else, unchanged — see above.\n return raw as Status;\n}\n\n/**\n * The string to WRITE into the Airtable \"Status\" cell for a canonical status.\n * Every writer of a CODE-OWNED status routes through here.\n *\n * Since stage 3 this is the identity: Airtable's single-select carries exactly\n * the six canonical options, so the canonical name IS the option name. It is\n * kept as a named seam rather than inlined because it is the one place a future\n * divergence between the code's vocabulary and Airtable's would be expressed,\n * and because every writer already routes through it — inlining would scatter\n * that decision across `ensureSite`, `updateLaunched`, `forms-notify-target`\n * and the dashboard status save.\n *\n * The stage-1/2 hazard it used to carry is GONE: while a many-to-one map\n * existed, `toAirtableStatus(canonicalizeStatus(x))` was not the identity —\n * feeding it \"legacy\" yielded \"deprecated\", silently writing an option the\n * operator never asked for. Both functions are now the identity, so that trap\n * no longer exists. `forms-notify-target --restore` still writes operator text\n * verbatim (`restoreCell`) rather than routing through here, which remains the\n * right shape: operator free text is not a canonical status.\n */\nexport function toAirtableStatus(s: Status): string {\n return s;\n}\n\n/** True when `s` is one of the canonical statuses (not a blind-cast typo). */\nexport function isCanonicalStatus(s: string): s is Status {\n return CANONICAL_SET.has(s);\n}\n","import type { FieldSet } from \"airtable\";\nimport type { AirtableBase } from \"./client.js\";\nimport type { LighthouseScores, LighthouseScoreWriteback } from \"../types.js\";\nimport {\n CANONICAL_STATUSES,\n canonicalizeStatus,\n toAirtableStatus,\n type Status,\n} from \"./site-status.js\";\n\nexport const WEBSITES_TABLE = \"Websites\";\n\nexport type Frequency = \"None\" | \"Monthly\" | \"Quarterly\" | \"Yearly\";\n\n/** The canonical lifecycle vocabulary lives in ./site-status.ts (which also owns\n * the old-Airtable-name aliases and the write-direction mapping). Re-exported\n * here because every consumer already imports `Status` from this module. */\nexport type { Status };\n\n/**\n * Per-site notification routing. When present on a `maintained` site, the form\n * notification is addressed by the value of a submission field (`field`, read from\n * `extraFields`) — e.g. route a contact form's `interest` to a different recipient\n * per option, always CC-ing a shared address. Absent (`null`) → the site keeps the\n * default single-POC behavior. Recipients live HERE (server-side Airtable config),\n * never supplied by the submitting site, so the ingest can't be turned into an open\n * relay.\n */\nexport type NotifyRouting = {\n /** The `extraFields` key whose value selects a route, e.g. \"interest\". */\n field: string;\n /** Field-value → recipient address(es). */\n routes: Record<string, string | string[]>;\n /** Recipient(s) when the value matches no route. */\n default?: string | string[];\n /** Address(es) CC'd on every routed (maintenance) send. */\n cc?: string[];\n};\n\nexport type WebsiteRow = {\n id: string;\n name: string;\n url: string;\n /** Canonical lifecycle status (see ./site-status.ts). Canonicalized at the read\n * boundary, so an old-vocabulary Airtable cell and a new one read identically.\n * A present-but-unrecognized cell survives VERBATIM (blind-cast) rather than\n * becoming null — `isUnrecognizedStatus` flags it, and null would make\n * due.ts/preflight.ts treat the row as eligible-by-default. */\n status: Status | null;\n /** The literal Airtable Status cell behind `status` — same pattern as\n * `maintenanceFreqRaw`. The dashboard status editor round-trips THIS, so its\n * dropdown offers and preselects the values Airtable actually holds while the\n * two vocabularies coexist. Null = blank cell. */\n statusRaw: string | null;\n pointOfContact: string | null;\n maintenanceFreq: Frequency;\n testingFreq: Frequency;\n /** The literal Airtable cell values behind the coerced frequencies. `toFrequency`\n * trims whitespace (\"Monthly \" reads as Monthly), then maps any still-unrecognized\n * value (\"Quaterly\") to \"None\" with a LOUD console.warn so nothing bogus reaches a\n * client email and the drop is never invisible. Preflight validates THESE to surface\n * the same failure as a structured finding. Null = blank cell. */\n maintenanceFreqRaw: string | null;\n testingFreqRaw: string | null;\n /** Last manually-recorded maintenance day (used as fallback when no Reports row exists). */\n maintenanceDay: string | null;\n testingDay: string | null;\n ga4PropertyId: string | null;\n /** Operator-supplied query for the Google search-presence check (e.g. the business name).\n * Null = no query set → the check is skipped for this site. */\n searchQuery: string | null;\n /** Explicit Search Console property for this site (`sc-domain:...` or `https://.../`).\n * Null = auto-resolve from the SA's visible properties by host. */\n searchConsoleProperty: string | null;\n /** ISO timestamp of the last draft run where THIS site's GA/Search enrichment\n * ERRORED (vs a legitimate \"not configured\" skip). Set by drafting on a soft-fail,\n * cleared (null) on a clean enrichment, so the per-site analytics-failure signal\n * self-heals. Null when the operator-added `Analytics soft-fail at` column is absent. */\n analyticsSoftFailAt: string | null;\n /** GitHub repo identity as `owner/repo`. Null = no git wiring → self-update ops skip\n * (or, for local runs, fall back to the checkout's origin remote). */\n gitRepo: string | null;\n reportRecipientsTo: string | null;\n reportRecipientsCc: string | null;\n acceptedWatchConditions: string[];\n /** First attachment in the Header image field (Airtable's signed URL — fetch before expiry). */\n headerImage: { url: string; filename: string; type: string } | null;\n /** Lighthouse \"current state\" snapshot, kept fresh by `audit lighthouse --write-airtable`. */\n pScore: number | null;\n rScore: number | null;\n bpScore: number | null;\n seoScore: number | null;\n /** ISO timestamp set by `audit lighthouse --write-airtable` when scores were last refreshed. */\n lastLighthouseAuditAt: string | null;\n /** Last-known counts from non-lighthouse audits, written by\n * `audit --write-airtable`. `null` = never audited (or this audit\n * type was skipped on the last run). 0 = audited, clean. */\n a11yViolations: number | null;\n /** Declared-range drift vs the Reddoor baseline (what package.json asks for). */\n depsDrifted: number | null;\n depsMajorBehind: number | null;\n /** Real installed-version drift: deps behind the registry's latest, from the\n * committed lockfile (`pnpm outdated`). Null = not determined this run. */\n depsOutdated: number | null;\n /** Of {@link depsOutdated}, how many are a *major* version behind the\n * registry's latest — the \"majors available on npm\" signal, distinct from the\n * baseline-drift {@link depsMajorBehind}. Null = not determined this run. */\n depsMajorOutdated: number | null;\n securityVulnsCritical: number | null;\n securityVulnsHigh: number | null;\n securityVulnsModerate: number | null;\n securityVulnsLow: number | null;\n /** Count of consecutive nightly Renovate auto-fix dispatches for the CURRENT\n * critical/high vuln episode that have NOT yet cleared it. Owned by\n * `renovate-dispatch`: +1 per real dispatch, reset to 0 when vulns clear.\n * Null = field absent / never dispatched → reads as 0. At/above\n * AUTO_FIX_EXHAUSTED_CYCLES the vuln renders as \"auto-fix failed\". */\n securityAutoFixAttempts: number | null;\n /** ISO timestamp the security audit last ran — gates freshness of the Security Updates auto-tick\n * (clean counts only auto-tick when recent). */\n lastSecurityAuditAt: string | null;\n /** The known advisories behind the counts (severity-sorted, capped), so the dashboard can show\n * WHICH packages are vulnerable, not just the totals. null = never audited / unparseable;\n * empty array = audited clean. Written alongside the counts by the security audit. */\n securityAdvisories: SecurityAdvisory[] | null;\n /** Domain/DNS/SSL probe (the `domain` audit). `certDaysRemaining` is days until the TLS cert\n * expires (null = unresolved or no usable cert); `domainCheckedAt` is when it last ran. */\n certDaysRemaining: number | null;\n domainCheckedAt: string | null;\n /** Netlify site id — the IDENTITY the `netlify-deploy` audit needs to query the\n * Netlify API. Read-only input (operator-set in Airtable); null = not on Netlify\n * (or not wired) → that audit skips. Never derived from the URL. */\n netlifyId: string | null;\n /** Latest PRODUCTION deploy health (the `netlify-deploy` audit). `deployStatus` is\n * Netlify's deploy state lower-cased (`ready`/`error`/`building`/…), null = none / not\n * checked; `lastDeployAt` is when it deployed; `deployLogUrl` links to the deploy/log. */\n deployStatus: string | null;\n lastDeployAt: string | null;\n deployLogUrl: string | null;\n /** When the `netlify-deploy` audit last RAN (freshness stamp for `deployStatus`). The audit\n * already writes \"Deploy checked at\"; this read-back is the Plan-2 fix so `deployEvidence`\n * (Plan 4) can gate on check time — NOT on `lastDeployAt`, which is deploy time, not check time. */\n deployCheckedAt: string | null;\n /** Function-health verdict (the `function-health` audit): the deployed `/health` function\n * answered `ok:true` (pass) or `ok:false` (fail). Single-select `pass`/`fail`; null = never ran\n * / unreachable (→ Plan 4 maps to unknown/amber). Kept SEPARATE from `deployStatus` so\n * `isFailedDeployStatus` keeps meaning \"the build failed\". */\n functionHealth: \"pass\" | \"fail\" | null;\n /** CMS reachability (server-side), derived from the same `/health` body's `details.prismic ===\n * \"ok\"`. Single-select `pass`/`fail`; null = never ran. No per-site Prismic token or identity\n * column is ever built — this rides `/health`. */\n cmsReachable: \"pass\" | \"fail\" | null;\n /** From the same `/health` body's `forms.turnstile` boolean: does the deployed site report\n * the Turnstile widget configured (`PUBLIC_TURNSTILE_SITE_KEY` set)? Single-select\n * `pass`/`fail`; null = never ran / older site package whose `/health` has no `forms`\n * block. Freshness gated by `functionHealthCheckedAt`. Powers the cockpit Require-Turnstile\n * guardrail: a site with `requireTurnstile` ON but no widget silently buckets 100% of its\n * real leads (and form-e2e can't see it — testMode bypasses the gate). */\n turnstileWidget: \"pass\" | \"fail\" | null;\n /** When the `function-health` audit last ran — the freshness gate for `functionHealth`,\n * `cmsReachable`, and `turnstileWidget`. Null = never ran. */\n functionHealthCheckedAt: string | null;\n /** Deployed-URL browser probe (the `browser` audit): cross-engine render OK, mobile render OK,\n * internal-links OK + broken count, and when it last ran (one timestamp gates all three). */\n crossbrowserOk: boolean | null;\n mobileOk: boolean | null;\n linksOk: boolean | null;\n brokenLinks: number | null;\n browserCheckedAt: string | null;\n /** Uptime-reachable verdict (browser audit): every sampled route returned 2xx/3xx. Single-select\n * `pass`/`fail`; null = never ran. Point-in-time. Freshness-gated by `browserCheckedAt`. */\n reachableOk: \"pass\" | \"fail\" | null;\n /** Titles & meta verdict (browser audit, chromium): every sampled route has a non-empty `<title>`\n * ≤ 70 chars + a non-empty meta description, and no duplicate titles across the sample.\n * Single-select `pass`/`fail`; null = never ran. Freshness-gated by `browserCheckedAt`. */\n titleMetaOk: \"pass\" | \"fail\" | null;\n /** Per-site copy overrides (M6a). Blank → null → the DEFAULT_COPY value. */\n copyIntro: string | null;\n copyContact: string | null;\n copyFooter: string | null;\n /** Go-live timestamp, stamped when a Launch report sends (M6b). Null = not yet launched. */\n launchedAt: string | null;\n /** Optional per-site webhook (e.g. Zapier Catch Hook). When set, the ingest\n * POSTs newsletter-formType submissions here (best-effort). Blank → null. */\n newsletterWebhook: string | null;\n /** Per-site Mailchimp (newsletter). Both must be set for the direct add;\n * blank → skipped. The API key is `key-dc` format; dc is derived from it. */\n mailchimpApiKey: string | null;\n mailchimpAudienceId: string | null;\n /** Per-site Cloudflare Turnstile gate (Airtable checkbox). When true, a submission\n * whose Turnstile token verifies as \"fail\" (forged) OR \"absent\" (secret configured\n * centrally but NO token forwarded — the direct-POST-bot signature) is escalated to\n * auto-spam regardless of content score. A present-but-expired token stays\n * \"unverifiable\" and neutral (a real browser DID render the widget — fail-open).\n * ROLLOUT PRECONDITION: only enable on a site whose DEPLOYED package forwards\n * `_meta.turnstileToken` from EVERY form (widget rendered + `cf-turnstile-response`\n * posted; check the site's `/health` → forms.turnstile:true). A site that never\n * forwards tokens would silently bucket 100% of its real leads — and the form-e2e\n * probe cannot catch that state (testMode bypasses the gate). */\n requireTurnstile: boolean;\n /** GitHub-signals sweep (slice 2a), written nightly by `github-signals --fleet`. */\n renovateFailingCis: number | null;\n defaultBranchCi: string | null; // \"passing\" | \"failing\" | \"pending\" | \"none\"\n lastCommitAt: string | null;\n githubSignalsAt: string | null;\n /** Per-site smoke-suite verdict (the `smoke` audit runs `pnpm test:smoke`).\n * Single-select pass/fail; null = never ran. `lastSmokeAt` gates freshness. */\n smokeOk: \"pass\" | \"fail\" | null;\n lastSmokeAt: string | null;\n /** Synthetic form end-to-end verdict (the `form-e2e` audit submits the real prod\n * contact form in test-mode). Single-select pass/fail; null = never ran OR (with\n * a fresh `formE2eCheckedAt`) no contact form → n/a. `formE2eCheckedAt` gates\n * freshness AND encodes the n/a-vs-never-ran distinction. */\n formE2eOk: \"pass\" | \"fail\" | null;\n formE2eCheckedAt: string | null;\n /**\n * Nightly Prismic model drift sweep (`prismic-models --fleet --write-airtable`).\n *\n * FOUR-VALUED, unlike every other verdict column in this table, and the extra\n * state is the point:\n *\n * - `pass` — the repo and its Prismic repository were compared and agree.\n * - `fail` — they were compared and DIVERGE (a model to create/update, or\n * one that exists only in Prismic). A finding for a human.\n * - `unknown` — THE CHECK ITSELF FAILED. Unreadable checkout, broken config,\n * missing/expired token, unreadable remote. Nothing at all was\n * established about this site's models.\n * - `null` — no verdict to hold: the sweep has never run for this site, or\n * it ran and found no Prismic config at all (a repo that simply\n * is not a Prismic site). `prismicModelsCheckedAt` separates\n * those two — fresh timestamp, blank verdict = \"checked, and\n * there is nothing here to check\".\n *\n * `unknown` exists because the alternatives are both wrong in the dangerous\n * direction. Writing `pass` for a site nobody could read is a green tick over\n * an outage; writing NOTHING (the obvious \"leave the last known value alone\")\n * leaves yesterday's `pass` standing for a site that has been failing every\n * night since — and nothing ages a stale `pass` out, because the digest's\n * freshness gate only ever examines failures. Both make \"I could not read this\n * site\" indistinguishable from \"this site is fine\", in the record the cockpit\n * and the digest read.\n *\n * OPERATOR PRECONDITION: `Prismic Models` is a single select whose options are\n * `pass`, `fail`, `unknown`. Until the three columns exist the sweep's writes\n * fail with UNKNOWN_FIELD_NAME and are collected as soft failures — the feature\n * ships dark rather than reddening the nightly.\n */\n prismicModels: PrismicModelsVerdict | null;\n /** When the sweep last ran for this site — written on EVERY outcome, including\n * `unknown` and blank, so the age of the row is the age of the answer. */\n prismicModelsCheckedAt: string | null;\n /** What the sweep found, verbatim: the drift report for a `fail`, the reason\n * nothing could be established for an `unknown`, the skip reason for a blank,\n * and null for a `pass` (which clears yesterday's finding). */\n prismicModelsDrift: string | null;\n /**\n * An expiry the operator sets to accept a KNOWN, EXPECTED `fail` — most often\n * \"I am modelling in Prismic on a branch that has not landed, so Prismic is\n * legitimately ahead of `main`\". While this timestamp is in the future the\n * drift item is not raised.\n *\n * It expires on purpose, and nothing renews it automatically. A permanent ack\n * would reproduce this column's own failure mode one step later: once the\n * branch lands, the same acked cell would swallow real drift and \"nobody is\n * looking at this\" would render as \"this is fine\". An expiry means the worst\n * case is a silence that ends by itself.\n *\n * Narrow by construction — it mutes only `fail`, the finding the operator\n * actually reviewed. `unknown` (the check could not run) and a verdict too old\n * to be current are never muted by it; see `collectPrismicDriftAlerts`.\n *\n * OPERATOR PRECONDITION: `Prismic Ack Until` is a dateTime column. Until it\n * exists this reads null and nothing is acked, which is the safe direction.\n */\n prismicAckUntil: string | null;\n notifyRouting: NotifyRouting | null;\n /** The RAW `Notify Routing` cell, verbatim. Same reason `statusRaw` exists: the\n * dashboard editor round-trips this JSON, and re-serializing the PARSED object\n * would drop any key the parser ignores and reformat what the operator typed —\n * a silent rewrite of a cell they only opened to look at. */\n notifyRoutingRaw: string | null;\n /** Read-back of the code-owned next-due dates (date-only, written by the\n * nightly `writeNextDueDates`). These exist so the writer can DIFF the\n * freshly-computed dates against what the row already holds and skip the\n * ~31 no-op writes a night the fleet was paying for (#539 Phase 3). Null =\n * cell blank or the operator-added `Next … at` column absent. */\n nextMaintenanceAt: string | null;\n nextTestingAt: string | null;\n};\n\nexport function siteSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** Blank-trim-to-null: a non-string or whitespace-only value becomes null,\n * otherwise the trimmed string. */\nexport function trimToNull(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Parse the Websites `Notify Routing` JSON into a NotifyRouting, defensively: a\n * non-string, blank, malformed-JSON, or wrong-shape value yields null (the site\n * then keeps default single-POC routing) — never throws. Mirrors the pipeline's\n * \"a bad Airtable string degrades quietly\" rule.\n */\nexport function parseNotifyRouting(raw: unknown): NotifyRouting | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (!trimmed) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const o = parsed as Record<string, unknown>;\n if (typeof o.field !== \"string\" || !o.field.trim()) return null;\n if (!o.routes || typeof o.routes !== \"object\" || Array.isArray(o.routes)) return null;\n const routing: NotifyRouting = {\n field: o.field,\n routes: o.routes as Record<string, string | string[]>,\n };\n if (o.default !== undefined) routing.default = o.default as string | string[];\n if (Array.isArray(o.cc)) routing.cc = o.cc.filter((x): x is string => typeof x === \"string\");\n return routing;\n}\n\n/**\n * Active sites: actively-maintained or pre-launch. Single source of truth for\n * \"is this a live site\" — the operator cockpit shows these, and the fleet\n * audit/report path runs against these. A `null` status (not-yet-active) is\n * deliberately excluded.\n */\nexport const ACTIVE_STATUSES: ReadonlySet<Status> = new Set<Status>([\"maintained\", \"launching\"]);\n\nexport function isDashboardVisible(site: WebsiteRow): boolean {\n return site.status !== null && ACTIVE_STATUSES.has(site.status);\n}\n\n/**\n * Pre-launch lifecycle stages: the site is being built/prepared, NOT yet live. A\n * Launch report (recipes/launch.ts) flips Status → \"maintained\" at go-live\n * (updateLaunched), so \"maintained\" is the true live state. Pre-launch sites must\n * not be audited as production (their deploy/domain/uptime/CMS audits fail because\n * nothing is live yet) nor scheduled recurring Maintenance/Testing reports.\n *\n * NOTE `launching` is deliberately in BOTH this set and ACTIVE_STATUSES — a\n * launching site is cockpit-visible but not production-audited. That dual\n * membership predates the vocabulary rename and was re-approved as-is with it.\n */\nexport const PRE_LAUNCH_STATUSES: ReadonlySet<Status> = new Set<Status>([\"building\", \"launching\"]);\n\nexport function isPreLaunch(status: Status | null): boolean {\n return status !== null && PRE_LAUNCH_STATUSES.has(status);\n}\n\n/** Every Status value the code recognizes — the canonical vocabulary, since both\n * read seams canonicalize. Typed ReadonlySet<string> so a blind-cast typo'd cell\n * can be probed without a cast. */\nexport const KNOWN_STATUSES: ReadonlySet<string> = new Set<Status>(CANONICAL_STATUSES);\n\n/** Terminal, out-of-fleet lifecycle states: kept in Airtable for the record,\n * excluded from every fleet op (sweeps, reports, audits, cockpit tiers) exactly\n * as before, but surfaced on the cockpit as an archived lane so a row can never\n * silently vanish. Airtable's `legacy` AND `deprecated` both canonicalize to the\n * single `archived` — an approved merge; the two were always treated alike. */\nexport const ARCHIVED_STATUSES: ReadonlySet<Status> = new Set<Status>([\"archived\"]);\n\nexport function isArchivedStatus(status: Status | null): boolean {\n return status !== null && ARCHIVED_STATUSES.has(status);\n}\n\n/** True when the Status cell holds a value outside the code's union (typo /\n * renamed option / stray whitespace). mapRow deliberately does NOT null these —\n * due.ts/preflight.ts treat a null status as eligible-by-default, so nulling a\n * typo would ACTIVATE the row. The cockpit surfaces these as watch rows instead. */\nexport function isUnrecognizedStatus(status: Status | null): boolean {\n return status !== null && !KNOWN_STATUSES.has(status);\n}\n\nconst FREQUENCIES: readonly Frequency[] = [\"None\", \"Monthly\", \"Quarterly\", \"Yearly\"];\n\n/** Coerce an Airtable single-select value to a known Frequency at the read boundary.\n * Whitespace is trimmed first, so an operator's trailing-space option (\"Quarterly \")\n * still schedules instead of silently unscheduling the site. Any other non-empty,\n * unrecognized value — a renamed / typo'd option — warns LOUDLY and falls back to\n * \"None\" (its section is simply omitted) rather than flowing a bogus string downstream,\n * which the announcement would otherwise render as \"We do this undefined.\" into a\n * client email. Blank/undefined is a silent \"None\": no schedule is intentional. */\nexport function toFrequency(raw: unknown, context: string): Frequency {\n if (typeof raw !== \"string\") return \"None\";\n const trimmed = raw.trim();\n if ((FREQUENCIES as readonly string[]).includes(trimmed)) return trimmed as Frequency;\n if (trimmed !== \"\") {\n console.warn(\n `⚠ ${context}: unrecognized frequency '${raw}' — treating as None (not scheduling); fix the Airtable value`,\n );\n }\n return \"None\";\n}\n\n/** Coerce an Airtable tri-state single-select verdict cell (`pass`/`fail`/blank) to\n * `\"pass\" | \"fail\" | null`. Any value other than the literal strings \"pass\"/\"fail\" — blank,\n * an unrecognized option, a typo, wrong type — reads as null (\"never ran\"), never guessed. The\n * ONE shared reader for every verdict column of this shape: `Function health`, `CMS Reachable`,\n * `Uptime Reachable`, `Titles & Meta OK` (Plan 2), and reused (not redeclared) by Plan 3's\n * `Smoke OK` / `Form E2E OK` read-backs. */\nexport function toVerdict(raw: unknown): \"pass\" | \"fail\" | null {\n return raw === \"pass\" || raw === \"fail\" ? raw : null;\n}\n\n/** The `Prismic Models` cell — see {@link WebsiteRow.prismicModels} for why it\n * carries a third state that no other verdict column in this table has. */\nexport type PrismicModelsVerdict = \"pass\" | \"fail\" | \"unknown\";\n\n/**\n * Read the `Prismic Models` cell. Deliberately NOT {@link toVerdict}.\n *\n * `toVerdict` maps anything that is not literally `pass`/`fail` to null — which\n * for this column would read `unknown` (\"the check ran and failed\") back as null\n * (\"the check never ran\"), silently, on the way to the cockpit. That is the\n * pipeline's governing failure (\"I could not read X\" wearing the face of \"X does\n * not exist\") reintroduced by a shared helper that predates the third state.\n *\n * Everything else — blank, a typo, an option somebody added by hand, the wrong\n * type — still reads as null. A verdict is never guessed.\n */\nexport function toPrismicModelsVerdict(raw: unknown): PrismicModelsVerdict | null {\n return raw === \"pass\" || raw === \"fail\" || raw === \"unknown\" ? raw : null;\n}\n\n// NOTE: every `f[\"...\"]` key below is a load-bearing magic string that must match\n// the live Airtable \"Websites\" column name EXACTLY — including the legacy\n// misspelling `\"maintenence freq\"`, the mixed-case `\"GA4 property ID\"`, and the\n// lowercase `\"url\"` / `\"point of contact\"`. A column rename in Airtable silently\n// returns undefined here (→ null), which degrades quietly (GA skipped, recipients\n// empty) with no error. If you rename a column, change it here too.\nexport function mapRow(rec: { id: string; fields: Record<string, unknown> }): WebsiteRow {\n const f = rec.fields;\n const name = String(f[\"Name\"] ?? \"\");\n const attachments =\n (f[\"Header image\"] as Array<{ url: string; filename: string; type: string }> | undefined) ?? [];\n // LAST, not first: Airtable's uploadAttachment APPENDS, so the newest file is the\n // tail. Reading [0] served the OLDEST forever whenever a field held more than one —\n // which is how a pre-clean-plate header reached a live announcement (#574/#577).\n // The prune keeps these fields at a single entry, so this is normally the same\n // element; preferring the tail means a field that stacks again still serves the\n // CURRENT header instead of silently reverting to the first one ever uploaded.\n const header = attachments.at(-1) ?? null;\n return {\n id: rec.id,\n name,\n url: String(f[\"url\"] ?? \"\"),\n status: canonicalizeStatus(f[\"Status\"]),\n statusRaw: (f[\"Status\"] as string | undefined) ?? null,\n pointOfContact: (f[\"point of contact\"] as string | undefined) ?? null,\n maintenanceFreq: toFrequency(f[\"maintenence freq\"], `${name} maintenance`),\n testingFreq: toFrequency(f[\"testing freq\"], `${name} testing`),\n maintenanceFreqRaw: (f[\"maintenence freq\"] as string | undefined) ?? null,\n testingFreqRaw: (f[\"testing freq\"] as string | undefined) ?? null,\n maintenanceDay: (f[\"maintenance day\"] as string | undefined) ?? null,\n testingDay: (f[\"testing day\"] as string | undefined) ?? null,\n ga4PropertyId: (f[\"GA4 property ID\"] as string | undefined) ?? null,\n searchQuery: (f[\"Search query\"] as string | undefined) ?? null,\n searchConsoleProperty: (f[\"Search Console property\"] as string | undefined) ?? null,\n analyticsSoftFailAt: (f[\"Analytics soft-fail at\"] as string | undefined) ?? null,\n gitRepo: (f[\"Git repo\"] as string | undefined) ?? null,\n reportRecipientsTo: (f[\"Report recipients (To)\"] as string | undefined) ?? null,\n reportRecipientsCc: (f[\"Report recipients (CC)\"] as string | undefined) ?? null,\n // Tolerate BOTH the current Multiple-Select array shape AND a delimited long-text\n // string (comma/newline separated), so the field can migrate to a plain text column\n // with no code change here. Trim + drop empties either way. The array branch also\n // validates ELEMENT types: a collaborator/attachment-shaped field passes\n // Array.isArray with OBJECT elements, and an unchecked cast would make assignTier's\n // `.trim()` throw — one misconfigured row must not 500 the whole cockpit build.\n acceptedWatchConditions: Array.isArray(f[\"Accepted Watch Conditions\"])\n ? (f[\"Accepted Watch Conditions\"] as unknown[])\n .filter((x): x is string => typeof x === \"string\")\n .map((s) => s.trim())\n .filter(Boolean)\n : typeof f[\"Accepted Watch Conditions\"] === \"string\"\n ? (f[\"Accepted Watch Conditions\"] as string)\n .split(/[\\n,]/)\n .map((s) => s.trim())\n .filter(Boolean)\n : [],\n headerImage: header,\n pScore: (f[\"pScore\"] as number | undefined) ?? null,\n rScore: (f[\"rScore\"] as number | undefined) ?? null,\n bpScore: (f[\"bpScore\"] as number | undefined) ?? null,\n seoScore: (f[\"seoScore\"] as number | undefined) ?? null,\n lastLighthouseAuditAt: (f[\"Last lighthouse audit at\"] as string | undefined) ?? null,\n a11yViolations: (f[\"A11y Violations\"] as number | undefined) ?? null,\n depsDrifted: (f[\"Deps Drifted\"] as number | undefined) ?? null,\n depsMajorBehind: (f[\"Deps Major Behind\"] as number | undefined) ?? null,\n depsOutdated: (f[\"Deps Outdated\"] as number | undefined) ?? null,\n depsMajorOutdated: (f[\"Deps Major Outdated\"] as number | undefined) ?? null,\n securityVulnsCritical: (f[\"Security Vulns Critical\"] as number | undefined) ?? null,\n securityVulnsHigh: (f[\"Security Vulns High\"] as number | undefined) ?? null,\n securityVulnsModerate: (f[\"Security Vulns Moderate\"] as number | undefined) ?? null,\n securityVulnsLow: (f[\"Security Vulns Low\"] as number | undefined) ?? null,\n securityAutoFixAttempts: (f[\"Security Auto-Fix Attempts\"] as number | undefined) ?? null,\n lastSecurityAuditAt: (f[\"Last security audit at\"] as string | undefined) ?? null,\n securityAdvisories: parseSecurityAdvisories(f[\"Security advisories\"]),\n certDaysRemaining: (f[\"Cert days remaining\"] as number | undefined) ?? null,\n domainCheckedAt: (f[\"Domain checked at\"] as string | undefined) ?? null,\n netlifyId: trimToNull(f[\"Netlify ID\"]),\n deployStatus: (f[\"Deploy status\"] as string | undefined) ?? null,\n lastDeployAt: (f[\"Last deploy at\"] as string | undefined) ?? null,\n deployLogUrl: (f[\"Deploy log URL\"] as string | undefined) ?? null,\n deployCheckedAt: (f[\"Deploy checked at\"] as string | undefined) ?? null,\n functionHealth: toVerdict(f[\"Function health\"]),\n cmsReachable: toVerdict(f[\"CMS Reachable\"]),\n turnstileWidget: toVerdict(f[\"Turnstile widget\"]),\n functionHealthCheckedAt: (f[\"Function health checked at\"] as string | undefined) ?? null,\n crossbrowserOk:\n typeof f[\"Crossbrowser OK\"] === \"boolean\" ? (f[\"Crossbrowser OK\"] as boolean) : null,\n mobileOk: typeof f[\"Mobile OK\"] === \"boolean\" ? (f[\"Mobile OK\"] as boolean) : null,\n linksOk: typeof f[\"Links OK\"] === \"boolean\" ? (f[\"Links OK\"] as boolean) : null,\n brokenLinks: typeof f[\"Broken links\"] === \"number\" ? (f[\"Broken links\"] as number) : null,\n browserCheckedAt: (f[\"Browser checked at\"] as string | undefined) ?? null,\n reachableOk: toVerdict(f[\"Uptime Reachable\"]),\n titleMetaOk: toVerdict(f[\"Titles & Meta OK\"]),\n copyIntro: trimToNull(f[\"Copy — Intro\"]),\n copyContact: trimToNull(f[\"Copy — Contact\"]),\n copyFooter: trimToNull(f[\"Copy — Footer\"]),\n launchedAt: (f[\"Launched at\"] as string | undefined) ?? null,\n newsletterWebhook: trimToNull(f[\"Newsletter Webhook\"]),\n notifyRouting: parseNotifyRouting(f[\"Notify Routing\"]),\n notifyRoutingRaw: trimToNull(f[\"Notify Routing\"]),\n mailchimpApiKey: trimToNull(f[\"Mailchimp API Key\"]),\n mailchimpAudienceId: trimToNull(f[\"Mailchimp Audience ID\"]),\n // Boolean guard like crossbrowserOk, but defaults FALSE (not null) when absent: an\n // unset/unknown column must read as \"not required\" so the feature ships dark.\n requireTurnstile:\n typeof f[\"Require Turnstile\"] === \"boolean\" ? (f[\"Require Turnstile\"] as boolean) : false,\n renovateFailingCis: (f[\"Renovate Failing CIs\"] as number | undefined) ?? null,\n defaultBranchCi: (f[\"Default Branch CI\"] as string | undefined) ?? null,\n lastCommitAt: (f[\"Last Commit At\"] as string | undefined) ?? null,\n githubSignalsAt: (f[\"GitHub Signals At\"] as string | undefined) ?? null,\n smokeOk: toVerdict(f[\"Smoke OK\"]),\n lastSmokeAt: (f[\"Last Smoke At\"] as string | undefined) ?? null,\n formE2eOk: toVerdict(f[\"Form E2E OK\"]),\n formE2eCheckedAt: (f[\"Form E2E checked at\"] as string | undefined) ?? null,\n prismicModels: toPrismicModelsVerdict(f[\"Prismic Models\"]),\n prismicModelsCheckedAt: (f[\"Prismic Models Checked At\"] as string | undefined) ?? null,\n prismicModelsDrift: (f[\"Prismic Models Drift\"] as string | undefined) ?? null,\n prismicAckUntil: (f[\"Prismic Ack Until\"] as string | undefined) ?? null,\n nextMaintenanceAt: (f[\"Next maintenance at\"] as string | undefined) ?? null,\n nextTestingAt: (f[\"Next testing at\"] as string | undefined) ?? null,\n };\n}\n\nexport async function listWebsites(base: AirtableBase): Promise<WebsiteRow[]> {\n const out: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ pageSize: 100 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) out.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n return out;\n}\n\nexport async function getWebsiteBySlug(\n base: AirtableBase,\n slug: string,\n): Promise<WebsiteRow | null> {\n // Slugs are siteSlug() output: [a-z0-9] segments joined by single hyphens.\n // Reject anything else — it can't match a real row, and it keeps URL-supplied\n // input out of the filter formula below (formula-injection guard).\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return null;\n\n // Narrow the fetch to the slug-matching row server-side instead of paging the\n // whole table per request (MEDIUM-H). The formula replicates siteSlug() on\n // {Name} — lowercase → non-alnum runs to \"-\" → strip leading/trailing \"-\" —\n // verified against the live base. maxRecords caps it (slug collisions keep the\n // prior first-match-wins behavior).\n const formula = `REGEX_REPLACE(REGEX_REPLACE(LOWER({Name}),\"[^a-z0-9]+\",\"-\"),\"^-|-$\",\"\")=${JSON.stringify(\n slug,\n )}`;\n const rows: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ filterByFormula: formula, maxRecords: 1 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n // Confirm the match in JS too: keeps the function correct if the formula and\n // siteSlug() ever drift, and under test fakes that don't evaluate the formula.\n return rows.find((w) => siteSlug(w.name) === slug) ?? null;\n}\n\n// ── audit-field builders ─────────────────────────────────────────────────────\n// One source of truth for the column-name → value mappings of each audit type.\n// The per-audit `updateXxxCounts` writers delegate to these (for their other\n// callers), and `updateAuditFields` merges whichever are present into ONE write —\n// so the field-name magic strings live in exactly one place.\n\nexport type A11yCounts = { violations: number };\nexport type DepsCounts = {\n drifted: number;\n majorBehind: number;\n outdated: number | null;\n majorOutdated: number | null;\n};\nexport type SecurityCounts = { critical: number; high: number; moderate: number; low: number };\nexport type Severity = \"low\" | \"moderate\" | \"high\" | \"critical\";\n/** One known vulnerability behind the security counts, as persisted/rendered. */\nexport type SecurityAdvisory = {\n module: string;\n severity: Severity;\n title: string;\n cves: string[];\n url: string | null;\n /** GitHub Dependabot dependency scope (\"runtime\" | \"development\"), when known. Lets the\n * dashboard flag build-time-only (\"development\") vulns. Omitted for advisories from the\n * lockfile `pnpm audit` fallback, which carries no per-package graph scope. */\n scope?: \"runtime\" | \"development\";\n /** GitHub Dependabot dependency-graph relationship, when known. \"transitive\" means no\n * direct-dep bump can fix it — Renovate's vuln alerts have no fix vehicle until the weekly\n * lockfile-maintenance window. Omitted when GitHub reports \"unknown\" or for the\n * `pnpm audit` fallback. Drives {@link allActionableVulnsTransitive}. */\n relationship?: \"direct\" | \"transitive\";\n};\nexport type DomainResult = { certDaysRemaining: number | null; checkedAt: string };\nexport type NetlifyDeployResult = {\n /** Netlify deploy state lower-cased (`ready`/`error`/`building`/…), null = none. */\n state: string | null;\n /** When the latest production deploy was published/created (ISO), null = unknown. */\n deployedAt: string | null;\n /** Link to the deploy / its build log, null = unknown. */\n logUrl: string | null;\n /** When the audit last ran. */\n checkedAt: string;\n};\nexport type BrowserAuditFields = {\n desktopOk: boolean;\n mobileOk: boolean;\n linksOk: boolean;\n reachableOk: boolean;\n titleMetaOk: boolean;\n brokenLinks: number;\n checkedAt: string;\n};\nexport type FunctionHealthResult = {\n /** `pass` when `/health` answered `ok:true`, else `fail`. Never null — the audit only produces a\n * result when it ran (a self-skip carries no details, so this extractor isn't reached). */\n functionHealth: \"pass\" | \"fail\";\n /** From the same body's `prismic` sub-status (R2.2): `\"ok\"` → `\"pass\"`, `\"error\"` → `\"fail\"`.\n * Anything else (`\"skipped\"` — a placeholder repo with no live Prismic — or a raw `null`, e.g.\n * the synthetic \"deployed but erroring\" body) → `null`: the CMS probe never actually ran, so it\n * must NOT red CMS reachability for a site that simply hasn't wired Prismic yet. */\n cmsReachable: \"pass\" | \"fail\" | null;\n /** From the same body's `forms.turnstile` boolean: `true` → `\"pass\"`, `false` → `\"fail\"`.\n * A missing/null `forms` block (older site package, or the synthetic \"deployed but\n * erroring\" body) → `null` — the widget state is simply unknown, not a failure. */\n turnstileWidget: \"pass\" | \"fail\" | null;\n /** When the audit ran (freshness stamp for all three verdicts). */\n checkedAt: string;\n};\n\nexport type SmokeResult = { ok: \"pass\" | \"fail\"; checkedAt: string };\n\n/** `ok` null clears the single-select cell (n/a — no contact form); a fresh\n * `checkedAt` still stamps the row so Plan 4 reads null+fresh as n/a. */\nexport type FormE2eResult = { ok: \"pass\" | \"fail\" | null; checkedAt: string };\n\nfunction scoreFields(scores: LighthouseScoreWriteback): FieldSet {\n // A null score CLEARS the cell (→ dashboard \"—\"), distinguishing a metric that\n // errored this run (e.g. NO_LCP → null performance) from a real low score. This\n // intentionally overwrites a prior value: a run that couldn't measure the metric\n // shouldn't keep showing a stale number. Writing null to clear mirrors\n // updateAnalyticsHealth; the `as FieldSet` cast is needed because airtable's\n // FieldSet type omits null.\n const fields: Record<string, number | string | null> = {\n pScore: scores.performance,\n rScore: scores.accessibility,\n bpScore: scores.bestPractices,\n seoScore: scores.seo,\n \"Last lighthouse audit at\": new Date().toISOString(),\n };\n return fields as FieldSet;\n}\n\nfunction a11yFields(counts: A11yCounts): FieldSet {\n return { \"A11y Violations\": counts.violations };\n}\n\nfunction depsFields(counts: DepsCounts): FieldSet {\n const fields: FieldSet = {\n \"Deps Drifted\": counts.drifted,\n \"Deps Major Behind\": counts.majorBehind,\n };\n // Only write the outdated count when it was determined — a null (no/stale\n // lockfile this run) must not clobber a previously-good value.\n if (counts.outdated !== null) {\n fields[\"Deps Outdated\"] = counts.outdated;\n }\n // Same null-guard for the registry-major breakdown (same source signal).\n if (counts.majorOutdated !== null) {\n fields[\"Deps Major Outdated\"] = counts.majorOutdated;\n }\n return fields;\n}\n\n/** Critical first → low last; the persist cap and the dashboard list both lean on this. */\nexport const SEVERITY_RANK: Record<Severity, number> = {\n critical: 0,\n high: 1,\n moderate: 2,\n low: 3,\n};\n/** Cap persisted advisories so the JSON field can't blow up on a badly-neglected site. */\nconst MAX_PERSISTED_ADVISORIES = 25;\n\n/** Coerce one untrusted value into a SecurityAdvisory, or null if it isn't shaped like one.\n * Shared by the read path (`parseSecurityAdvisories`) and the write path so both validate\n * identically. A missing module or unrecognized severity drops the entry entirely. */\nexport function normalizeSecurityAdvisory(raw: unknown): SecurityAdvisory | null {\n if (!raw || typeof raw !== \"object\") return null;\n const e = raw as Record<string, unknown>;\n const module = typeof e[\"module\"] === \"string\" ? (e[\"module\"] as string) : null;\n const severity = e[\"severity\"];\n if (module === null) return null;\n if (\n severity !== \"low\" &&\n severity !== \"moderate\" &&\n severity !== \"high\" &&\n severity !== \"critical\"\n )\n return null;\n const cves = Array.isArray(e[\"cves\"])\n ? (e[\"cves\"] as unknown[]).filter((c): c is string => typeof c === \"string\")\n : [];\n const scope =\n e[\"scope\"] === \"runtime\" || e[\"scope\"] === \"development\"\n ? (e[\"scope\"] as \"runtime\" | \"development\")\n : undefined;\n const relationship =\n e[\"relationship\"] === \"direct\" || e[\"relationship\"] === \"transitive\"\n ? (e[\"relationship\"] as \"direct\" | \"transitive\")\n : undefined;\n return {\n module,\n severity,\n title: typeof e[\"title\"] === \"string\" ? (e[\"title\"] as string) : \"\",\n cves,\n url: typeof e[\"url\"] === \"string\" ? (e[\"url\"] as string) : null,\n ...(scope ? { scope } : {}),\n ...(relationship ? { relationship } : {}),\n };\n}\n\n/**\n * True iff the persisted advisory detail proves EVERY actionable (critical/high) vuln is a\n * TRANSITIVE dependency — i.e. Renovate's vulnerability alerts have no direct-dep bump to\n * open, and the fix rides the weekly lockfile-maintenance window instead. Deliberately\n * conservative: `null` detail (never audited / `pnpm audit` fallback), an advisory missing\n * its `relationship` (unknown / pre-existing JSON), or a counts-vs-detail mismatch (no\n * critical/high advisory in the list) all return false — missing data must never mute the\n * auto-fix-failed escalation. Consumed by the attempts counter (don't count a known no-op\n * dispatch as a failed fix attempt) and the digest (say \"transitive-only\", not\n * \"auto-fix failed\"). The persist cap keeps advisories sorted critical-first, so\n * critical/high entries are never the ones capped away.\n */\nexport function allActionableVulnsTransitive(advisories: SecurityAdvisory[] | null): boolean {\n if (!advisories) return false;\n const actionable = advisories.filter((a) => a.severity === \"critical\" || a.severity === \"high\");\n if (actionable.length === 0) return false;\n return actionable.every((a) => a.relationship === \"transitive\");\n}\n\n/** Parse the `Security advisories` JSON cell. null when absent/blank/unparseable/not-an-array\n * (treated as \"never audited\"); a valid array (possibly empty = audited clean) otherwise. */\nexport function parseSecurityAdvisories(raw: unknown): SecurityAdvisory[] | null {\n if (typeof raw !== \"string\" || raw.trim() === \"\") return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!Array.isArray(parsed)) return null;\n return parsed.map(normalizeSecurityAdvisory).filter((a): a is SecurityAdvisory => a !== null);\n}\n\nfunction securityAdvisoryFields(advisories: SecurityAdvisory[]): FieldSet {\n const capped = [...advisories]\n .sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n .slice(0, MAX_PERSISTED_ADVISORIES);\n // Always write — an empty array (\"[]\") clears a stale list when a once-vulnerable site goes clean.\n return { \"Security advisories\": JSON.stringify(capped) };\n}\n\nfunction securityFields(counts: SecurityCounts): FieldSet {\n return {\n \"Security Vulns Critical\": counts.critical,\n \"Security Vulns High\": counts.high,\n \"Security Vulns Moderate\": counts.moderate,\n \"Security Vulns Low\": counts.low,\n // Stamp freshness alongside the counts so the Security Updates auto-tick can require a recent\n // audit (a clean count from months ago must not silently keep ticking the box).\n \"Last security audit at\": new Date().toISOString(),\n };\n}\n\nfunction domainFields(result: DomainResult): FieldSet {\n const fields: FieldSet = { \"Domain checked at\": result.checkedAt };\n // Write the cert days UNCONDITIONALLY: a null (unresolved / no usable cert) must CLEAR any\n // previously-good value. Leaving a stale number in place — next to a freshly-stamped \"Domain\n // checked at\" — false-passes the Domain/DNS/SSL auto-tick (domainEvidence reads the stale\n // non-null value as a current pass) for a site that's actually down. null clears the cell in\n // Airtable; FieldSet's type doesn't model null, hence the cast through a widened record.\n (fields as Record<string, number | null>)[\"Cert days remaining\"] = result.certDaysRemaining;\n return fields;\n}\n\nfunction netlifyDeployFields(result: NetlifyDeployResult): FieldSet {\n // Write all three deploy fields UNCONDITIONALLY (null clears the cell): a null state /\n // deployedAt / logUrl this run means \"couldn't read it\" and must not leave a STALE value\n // sitting next to a fresh \"Deploy checked at\" — the dashboard would otherwise render a green\n // \"ready\" badge for a site whose latest deploy actually errored. FieldSet's type doesn't model\n // null, hence the cast through a widened record (same approach as domainFields).\n const fields: Record<string, string | null> = {\n \"Deploy status\": result.state,\n \"Last deploy at\": result.deployedAt,\n \"Deploy log URL\": result.logUrl,\n \"Deploy checked at\": result.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction browserFields(r: BrowserAuditFields): FieldSet {\n return {\n \"Crossbrowser OK\": r.desktopOk,\n \"Mobile OK\": r.mobileOk,\n \"Links OK\": r.linksOk,\n \"Broken links\": r.brokenLinks,\n \"Browser checked at\": r.checkedAt,\n // NEW tri-state single-select verdicts (empty = never ran). The browser audit only produces a\n // BrowserAuditFields when it actually ran (hasBrowserResult guards on checkedAt), so each verdict\n // is always a concrete boolean here — serialize true→\"pass\", false→\"fail\". The existing boolean\n // columns above are deliberately NOT retrofitted (out of scope).\n \"Uptime Reachable\": r.reachableOk ? \"pass\" : \"fail\",\n \"Titles & Meta OK\": r.titleMetaOk ? \"pass\" : \"fail\",\n };\n}\n\nfunction functionHealthFields(r: FunctionHealthResult): FieldSet {\n // \"CMS Reachable\" is written UNCONDITIONALLY (null clears the cell): the audit only supplies a\n // result when it ran, but `cmsReachable` itself can legitimately be null this run (R2.2 — the CMS\n // probe never actually happened, e.g. a placeholder repo with no live Prismic). Clearing rather\n // than leaving a stale pass/fail sitting next to a freshly-stamped checked-at is what keeps a\n // placeholder site from showing a stale CMS verdict. FieldSet's type doesn't model null, hence the\n // cast through a widened record (same approach as domainFields/netlifyDeployFields).\n // \"Function health\" is never null — the audit only writes when it ran, so it's always a concrete\n // pass/fail. Written SEPARATELY from \"Deploy status\" so the Netlify build state keeps its own\n // meaning.\n const fields: Record<string, string | null> = {\n \"Function health\": r.functionHealth,\n \"CMS Reachable\": r.cmsReachable,\n // Same null-clears semantics as \"CMS Reachable\": a body without a forms block means the\n // widget state is unknown THIS run — clearing beats a stale verdict next to a fresh stamp.\n \"Turnstile widget\": r.turnstileWidget,\n \"Function health checked at\": r.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction smokeFields(r: SmokeResult): FieldSet {\n // The verdict is stored as the literal single-select option (\"pass\"/\"fail\"), so\n // no boolean→string coercion is needed. A skip never reaches here (it produces no\n // SmokeResult), so this column is only ever written with a concrete verdict.\n return { \"Smoke OK\": r.ok, \"Last Smoke At\": r.checkedAt };\n}\n\nfunction formE2eFields(r: FormE2eResult): FieldSet {\n // `ok` is already the single-select value (\"pass\"/\"fail\") or null. Writing null\n // CLEARS the cell (→ n/a, distinguished from \"never ran\" by the fresh checked-at\n // stamped alongside). FieldSet's type omits null, hence the widened-record cast\n // (same approach as domainFields / netlifyDeployFields).\n const fields: Record<string, string | null> = {\n \"Form E2E OK\": r.ok,\n \"Form E2E checked at\": r.checkedAt,\n };\n return fields as FieldSet;\n}\n\n/**\n * Write the four Lighthouse scores + a refreshed-at timestamp onto a Websites row.\n * Called by `audit lighthouse --write-airtable` after a successful audit run, so\n * the operator never has to paste numbers manually before drafting a report.\n */\nexport async function updateScores(\n base: AirtableBase,\n recordId: string,\n scores: LighthouseScores,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: scoreFields(scores) }]);\n}\n\n/**\n * Record (or clear) the per-site GA/Search enrichment health on the `Analytics\n * soft-fail at` column. `at` is an ISO timestamp when the site's last draft had a\n * GA/Search soft-failure, or `null` to clear it after a clean enrichment. The\n * caller (drafting) swallows errors: this column is operator-added, so until it\n * exists Airtable throws UNKNOWN_FIELD_NAME — which must not break a draft.\n */\nexport async function updateAnalyticsHealth(\n base: AirtableBase,\n recordId: string,\n at: string | null,\n): Promise<FieldSet> {\n const fields: Record<string, string | null> = { \"Analytics soft-fail at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n // Same contract as updateNextDueDates/updateAuditFields: the #539 Turso mirror\n // consumes the returned FieldSet, so the two writes cannot diverge.\n return fields as FieldSet;\n}\n\n/** Persist a11y violation count. */\nexport async function updateA11yCounts(\n base: AirtableBase,\n recordId: string,\n counts: A11yCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: a11yFields(counts) }]);\n}\n\n/** Persist deps drift counts (declared-range drift + real outdated installs). */\nexport async function updateDepsCounts(\n base: AirtableBase,\n recordId: string,\n counts: DepsCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: depsFields(counts) }]);\n}\n\n/** Persist security vulnerability counts by severity. */\nexport async function updateSecurityCounts(\n base: AirtableBase,\n recordId: string,\n counts: SecurityCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: securityFields(counts) }]);\n}\n\n/** Persist a site's auto-fix attempt counter. Its own one-field writer so the\n * nightly Renovate dispatch can update it without touching the audit's counts. */\nexport async function updateAutoFixAttempts(\n base: AirtableBase,\n recordId: string,\n attempts: number,\n): Promise<FieldSet> {\n const fields: FieldSet = { \"Security Auto-Fix Attempts\": attempts };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n // Returned for the #539 Turso mirror — see updateNextDueDates.\n return fields;\n}\n\n/**\n * Persist the code-computed next-due dates (date-only `YYYY-MM-DD`, or `null` to\n * clear) for the maintenance + testing schedules. Owned by the nightly `--due` sweep\n * so the \"next\" dates shown in Airtable come from the SAME logic as the scheduler\n * (`nextDueDate`) — no Airtable-side formula or automation. Best-effort at the call\n * site: the `Next … at` columns are operator-added, so until they exist Airtable\n * throws UNKNOWN_FIELD_NAME, which must not break the nightly draft run.\n */\nexport async function updateNextDueDates(\n base: AirtableBase,\n recordId: string,\n dates: { maintenanceAt: string | null; testingAt: string | null },\n): Promise<FieldSet> {\n const fields: Record<string, string | null> = {\n \"Next maintenance at\": dates.maintenanceAt,\n \"Next testing at\": dates.testingAt,\n };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n // Same contract as updateAuditFields/updateGitHubSignals: the Phase 3 Turso\n // mirror consumes the returned FieldSet, so the two writes cannot diverge.\n return fields as FieldSet;\n}\n\n/** The cell shapes the site editor can write. Airtable rejects a string written\n * to a checkbox or a multi-select, so `Require Turnstile` (boolean) and\n * `Accepted Watch Conditions` (string[]) travel as themselves rather than being\n * stringified at the boundary and coerced back later. */\nexport type AirtableCellValue = string | boolean | string[];\n\n/** Generic single-field writer for the dashboard site-details editor. The caller\n * (setSiteDetail) restricts `column` to the EDITABLE_SITE_FIELDS allowlist, so this\n * never writes an arbitrary column from request input. */\nexport async function updateSiteField(\n base: AirtableBase,\n recordId: string,\n column: string,\n value: AirtableCellValue,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: { [column]: value } }]);\n}\n\n/**\n * Persist all of a single audit run's results to one Websites row in ONE atomic\n * `update()` — instead of up to four sequential updates on the same id (which left\n * a row half-written on a mid-sequence failure and quadrupled the request volume).\n * Pass only the audit slices that produced real values; each present slice is merged\n * via the SAME field mappings the per-audit writers use. Omit a slice (or pass\n * undefined) to leave those columns untouched. Returns the merged FieldSet so the\n * caller can enumerate what was written.\n */\nexport async function updateAuditFields(\n base: AirtableBase,\n recordId: string,\n audits: {\n scores?: LighthouseScoreWriteback;\n a11y?: A11yCounts;\n deps?: DepsCounts;\n security?: SecurityCounts;\n securityAdvisories?: SecurityAdvisory[];\n domain?: DomainResult;\n browser?: BrowserAuditFields;\n netlifyDeploy?: NetlifyDeployResult;\n functionHealth?: FunctionHealthResult;\n smoke?: SmokeResult;\n formE2e?: FormE2eResult;\n },\n): Promise<FieldSet> {\n const fields: FieldSet = {};\n if (audits.scores) Object.assign(fields, scoreFields(audits.scores));\n if (audits.a11y) Object.assign(fields, a11yFields(audits.a11y));\n if (audits.deps) Object.assign(fields, depsFields(audits.deps));\n if (audits.security) Object.assign(fields, securityFields(audits.security));\n // Separate slice (not folded into `security`) so the advisory list and the counts can be\n // written independently, but in practice the security audit supplies both together.\n if (audits.securityAdvisories)\n Object.assign(fields, securityAdvisoryFields(audits.securityAdvisories));\n if (audits.domain) Object.assign(fields, domainFields(audits.domain));\n if (audits.browser) Object.assign(fields, browserFields(audits.browser));\n if (audits.netlifyDeploy) Object.assign(fields, netlifyDeployFields(audits.netlifyDeploy));\n if (audits.functionHealth) Object.assign(fields, functionHealthFields(audits.functionHealth));\n if (audits.smoke) Object.assign(fields, smokeFields(audits.smoke));\n if (audits.formE2e) Object.assign(fields, formE2eFields(audits.formE2e));\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n return fields;\n}\n\n/** Persist the GitHub-signals sweep onto a Websites row (slice 2a). A null\n * `lastCommitAt` is OMITTED so a not-determined-this-run value never clobbers a\n * previously-good timestamp (mirrors updateDepsCounts' outdated handling).\n * Returns the FieldSet it wrote — the Phase 3 Turso mirror consumes the same\n * payload, so the two writes cannot diverge (updateAuditFields' contract). */\nexport async function updateGitHubSignals(\n base: AirtableBase,\n recordId: string,\n signals: {\n renovateFailingCis: number;\n ciState: string;\n lastCommitAt: string | null;\n sweptAt: string;\n },\n): Promise<FieldSet> {\n const fields: FieldSet = {\n \"Renovate Failing CIs\": signals.renovateFailingCis,\n \"Default Branch CI\": signals.ciState,\n \"GitHub Signals At\": signals.sweptAt,\n };\n if (signals.lastCommitAt !== null) {\n fields[\"Last Commit At\"] = signals.lastCommitAt;\n }\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n return fields;\n}\n\n/** One site's Prismic model verdict, as the sweep hands it to the record.\n *\n * `verdict: null` is a REQUEST TO BLANK the cell, not \"leave it alone\" — see\n * {@link updatePrismicModels}. There is no way to express \"leave it alone\" here\n * on purpose. */\nexport type PrismicModelsWriteback = {\n verdict: PrismicModelsVerdict | null;\n checkedAt: string;\n /** The finding, the failure reason, or the skip reason — whichever this\n * verdict has. `null` clears the column. */\n detail: string | null;\n};\n\n/** Airtable's long-text cells hold ~100k characters and the sweep's report runs\n * long on a badly drifted site (an empty Prismic repository sorts every local\n * model into `toCreate`, with a line per field). Half the cell is the budget;\n * the rest is headroom for whatever renders it. */\nconst MAX_PRISMIC_DETAIL_CHARS = 50_000;\n\n/**\n * Shorten a detail that will not fit, and SAY SO — with the original length, so\n * nobody mistakes the remainder for the whole. Same reasoning as the PR comment's\n * truncation notice: a report that was shortened without saying it was shortened\n * is a report that looks complete and is not.\n *\n * The cut is by code unit, so it can land between the halves of an astral\n * character; a lone surrogate is not valid text and can make Airtable reject the\n * write, losing the entire finding to a cosmetic detail.\n */\nfunction truncatePrismicDetail(detail: string): string {\n if (detail.length <= MAX_PRISMIC_DETAIL_CHARS) return detail;\n const notice =\n `\\n…[truncated: this report is ${detail.length} characters and only the first` +\n ` ${MAX_PRISMIC_DETAIL_CHARS} are kept here. Run \\`reddoor-maint prismic-models\\` in the` +\n ` site — dry is the default — for the whole thing.]`;\n let head = detail.slice(0, MAX_PRISMIC_DETAIL_CHARS - notice.length);\n const last = head.charCodeAt(head.length - 1);\n if (last >= 0xd800 && last <= 0xdbff) head = head.slice(0, -1);\n return head + notice;\n}\n\n/**\n * Persist one site's Prismic model verdict.\n *\n * ALL THREE COLUMNS, ALWAYS, in one update — including when the verdict is\n * `unknown` or blank. That is the whole design: the alternative (\"only write a\n * verdict when we have one\") leaves the PREVIOUS verdict standing for a site\n * whose check has since started failing, and a stale `pass` is never aged out by\n * anything — the digest's freshness gate only examines failures. So the record\n * always says what the last run actually established, and `checkedAt` always\n * says when. See {@link WebsiteRow.prismicModels} for the four states.\n *\n * Best-effort AT THE CALL SITE: `Prismic Models*` are operator-added columns, so\n * until they exist Airtable throws UNKNOWN_FIELD_NAME. The nightly sweep must\n * survive that and collect it — same contract as `updateNextDueDates`.\n *\n * Takes a non-null `AirtableBase`, like every other writer here: whether to write\n * at all is the caller's decision, and this repo keeps \"do no writes\" separate\n * from \"do no IO\" one layer up.\n */\nexport async function updatePrismicModels(\n base: AirtableBase,\n recordId: string,\n models: PrismicModelsWriteback,\n): Promise<FieldSet> {\n const fields: Record<string, string | null> = {\n \"Prismic Models\": models.verdict,\n \"Prismic Models Checked At\": models.checkedAt,\n \"Prismic Models Drift\": models.detail === null ? null : truncatePrismicDetail(models.detail),\n };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n // Returned for the #539 Turso mirror — see updateNextDueDates.\n return fields as FieldSet;\n}\n\n/** Mark a site launched: flip Status → maintained + stamp Launched at (M6b).\n * The first code that writes Status. Called after a Launch report sends.\n * Routed through `toAirtableStatus`, so it still writes Airtable's \"maintenance\"\n * option until the stage-2 switch flips. */\nexport async function updateLaunched(\n base: AirtableBase,\n recordId: string,\n at: string,\n): Promise<FieldSet> {\n const fields: FieldSet = { Status: toAirtableStatus(\"maintained\"), \"Launched at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n // Returned for the #539 Turso mirror. BOTH columns travel together on purpose:\n // mirroring them as two UPDATEs would open a window where Turso says a site is\n // maintained but never launched.\n return fields;\n}\n"],"mappings":";AAyFO,IAAM,qBAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,gBAAqC,IAAI,IAAY,kBAAkB;AA6BtE,SAAS,mBAAmB,KAA6B;AAC9D,MAAI,OAAO,QAAQ,SAAU,QAAO;AAEpC,SAAO;AACT;AAsBO,SAAS,iBAAiB,GAAmB;AAClD,SAAO;AACT;;;ACjJO,IAAM,iBAAiB;AAwRvB,SAAS,SAAS,MAAsB;AAC7C,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AACzB;AAIO,SAAS,WAAW,KAA6B;AACtD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAQO,SAAS,mBAAmB,KAAoC;AACrE,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACJ,MAAI;AACF,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+
withRecipe
|
|
7
|
+
} from "./chunk-3G25KIWW.js";
|
|
8
8
|
import {
|
|
9
9
|
listTrackedFiles,
|
|
10
10
|
removeFromIndex
|
|
@@ -207,4 +207,4 @@ export {
|
|
|
207
207
|
isConfigName,
|
|
208
208
|
syncConfigs
|
|
209
209
|
};
|
|
210
|
-
//# sourceMappingURL=chunk-
|
|
210
|
+
//# sourceMappingURL=chunk-7UAYMAKR.js.map
|
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
import {
|
|
2
2
|
queueDraft
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import {
|
|
5
|
-
generateHeaderImage
|
|
6
|
-
} from "./chunk-5UINJNAJ.js";
|
|
7
|
-
import {
|
|
8
|
-
renderReportHtml,
|
|
9
|
-
resolveCopy
|
|
10
|
-
} from "./chunk-CQR4LIM7.js";
|
|
11
|
-
import {
|
|
12
|
-
uploadAttachment
|
|
13
|
-
} from "./chunk-Z7AXYKQB.js";
|
|
3
|
+
} from "./chunk-YFAXOD7Z.js";
|
|
14
4
|
import {
|
|
15
5
|
createDraft,
|
|
16
6
|
listReportsForSite
|
|
17
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-F3JWOPTG.js";
|
|
18
8
|
import {
|
|
19
9
|
checklistFor,
|
|
20
10
|
gatingFields
|
|
21
11
|
} from "./chunk-VAD43MOR.js";
|
|
22
12
|
import {
|
|
23
|
-
|
|
24
|
-
} from "./chunk-
|
|
13
|
+
uploadAttachment
|
|
14
|
+
} from "./chunk-IY6256GK.js";
|
|
15
|
+
import {
|
|
16
|
+
renderReportHtml,
|
|
17
|
+
resolveCopy
|
|
18
|
+
} from "./chunk-MT2JINSS.js";
|
|
19
|
+
import {
|
|
20
|
+
generateHeaderImage
|
|
21
|
+
} from "./chunk-5UINJNAJ.js";
|
|
25
22
|
import {
|
|
26
23
|
siteSlug,
|
|
27
24
|
updateAnalyticsHealth
|
|
28
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-7NYN2P6I.js";
|
|
26
|
+
import {
|
|
27
|
+
isNetlifyAppUrl
|
|
28
|
+
} from "./chunk-EVBCK2KC.js";
|
|
29
29
|
import {
|
|
30
30
|
defaultCredentialsPath
|
|
31
31
|
} from "./chunk-6VAL7XJT.js";
|
|
@@ -583,22 +583,23 @@ async function draftReportForSite(base, siteRow, reportType, options = {}) {
|
|
|
583
583
|
if (base === null) throw new Error("base required when previewOnly=false");
|
|
584
584
|
if (readGaConfig() !== null && Boolean(siteRow.ga4PropertyId || siteRow.searchQuery)) {
|
|
585
585
|
try {
|
|
586
|
-
await updateAnalyticsHealth(
|
|
586
|
+
const fields = await updateAnalyticsHealth(
|
|
587
587
|
base,
|
|
588
588
|
siteRow.id,
|
|
589
589
|
softFailures.length > 0 ? today.toISOString() : null
|
|
590
590
|
);
|
|
591
|
+
await options.siteMirror?.health(siteRow.id, fields);
|
|
591
592
|
} catch (e) {
|
|
592
593
|
console.warn(`\u26A0 analytics-health write skipped for ${siteRow.name}: ${e.message}`);
|
|
593
594
|
}
|
|
594
595
|
}
|
|
595
596
|
if (options.completeRowId) {
|
|
596
|
-
await uploadDraftHtml(options.completeRowId, slug, periodEnd, html);
|
|
597
|
-
const outcome2 = await queueDraft(
|
|
598
|
-
|
|
599
|
-
siteId: siteRow.id,
|
|
600
|
-
|
|
601
|
-
|
|
597
|
+
await uploadDraftHtml(options.completeRowId, slug, periodEnd, html, options.reportMirror);
|
|
598
|
+
const outcome2 = await queueDraft(
|
|
599
|
+
base,
|
|
600
|
+
{ id: options.completeRowId, siteId: siteRow.id, reportType },
|
|
601
|
+
options.reportMirror
|
|
602
|
+
);
|
|
602
603
|
return {
|
|
603
604
|
reportRow: options.existingRow ?? null,
|
|
604
605
|
htmlPath: null,
|
|
@@ -614,28 +615,32 @@ async function draftReportForSite(base, siteRow, reportType, options = {}) {
|
|
|
614
615
|
const checklistTicks = [...evidence.entries()].filter(([, e]) => e.result === "pass").map(([field]) => field);
|
|
615
616
|
const autoEvidence = Object.fromEntries(evidence);
|
|
616
617
|
const reportId = `${siteRow.name} \u2014 ${reportType} \u2014 ${periodEnd.toISOString().slice(0, 10)}`;
|
|
617
|
-
const created = await createDraft(
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
618
|
+
const created = await createDraft(
|
|
619
|
+
base,
|
|
620
|
+
{
|
|
621
|
+
reportId,
|
|
622
|
+
siteId: siteRow.id,
|
|
623
|
+
reportType,
|
|
624
|
+
period: options.period ?? periodEnd.toISOString().slice(0, 7),
|
|
625
|
+
periodStart,
|
|
626
|
+
periodEnd,
|
|
627
|
+
completedOn,
|
|
628
|
+
lighthouse: scores,
|
|
629
|
+
lastTestedDate,
|
|
630
|
+
...gaUsers ? { gaUsersCurrent: gaUsers.current, gaUsersPrevious: gaUsers.previous } : {},
|
|
631
|
+
...search ? { searchFoundPage1: search.foundOnPage1 } : {},
|
|
632
|
+
...search?.foundOnPage1 && search.position !== null ? { searchPosition: search.position } : {},
|
|
633
|
+
checklistTicks,
|
|
634
|
+
autoEvidence
|
|
635
|
+
},
|
|
636
|
+
options.reportMirror?.created
|
|
637
|
+
);
|
|
638
|
+
await uploadDraftHtml(created.id, slug, periodEnd, html, options.reportMirror);
|
|
639
|
+
const outcome = await queueDraft(
|
|
640
|
+
base,
|
|
641
|
+
{ id: created.id, siteId: siteRow.id, reportType },
|
|
642
|
+
options.reportMirror
|
|
643
|
+
);
|
|
639
644
|
return {
|
|
640
645
|
reportRow: created,
|
|
641
646
|
htmlPath: null,
|
|
@@ -647,9 +652,10 @@ async function draftReportForSite(base, siteRow, reportType, options = {}) {
|
|
|
647
652
|
supersededIds: outcome.supersededIds
|
|
648
653
|
};
|
|
649
654
|
}
|
|
650
|
-
async function uploadDraftHtml(rowId, slug, periodEnd, html) {
|
|
655
|
+
async function uploadDraftHtml(rowId, slug, periodEnd, html, mirror) {
|
|
651
656
|
const htmlFilename = `${slug}-${periodEnd.toISOString().slice(0, 10)}.html`;
|
|
652
657
|
await uploadAttachment(rowId, "Rendered HTML", html, htmlFilename, "text/html");
|
|
658
|
+
await mirror?.body(rowId, html);
|
|
653
659
|
}
|
|
654
660
|
var NO_ENRICHMENT = { value: null, softFailed: false };
|
|
655
661
|
async function fetchGaUsers(siteRow, periodStart, periodEnd) {
|
|
@@ -735,4 +741,4 @@ export {
|
|
|
735
741
|
fetchGaUsers,
|
|
736
742
|
fetchSearch
|
|
737
743
|
};
|
|
738
|
-
//# sourceMappingURL=chunk-
|
|
744
|
+
//# sourceMappingURL=chunk-BBUSGEES.js.map
|